@squirrelnotes.app/mcp 2.7.1 → 2.8.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 (2) hide show
  1. package/dist/stdio-handler.js +727 -45
  2. package/package.json +1 -1
@@ -38049,7 +38049,7 @@ function redactBody(body, target) {
38049
38049
  const spellings = [.../* @__PURE__ */ new Set([target.secret, encodeURIComponent(target.secret)])];
38050
38050
  return spellings.reduce((text, spelling) => text.split(spelling).join(TOKEN_LABEL), body);
38051
38051
  }
38052
- var MEMORY_PAGE_LIMIT, TOKEN_LABEL, pathOf, labelOf, CLIENT_HEADER, CLIENT_NAME, SquirrelApiClient;
38052
+ var MEMORY_PAGE_LIMIT, TOKEN_LABEL, pathOf, labelOf, CLIENT_HEADER, CLIENT_NAME, NOTE_BODY_HEADER, NOTE_BODY_CAPABILITY, SquirrelApiClient;
38053
38053
  var init_api2 = __esm({
38054
38054
  "src/api.ts"() {
38055
38055
  "use strict";
@@ -38061,6 +38061,8 @@ var init_api2 = __esm({
38061
38061
  labelOf = (target) => typeof target === "string" ? target : target.label;
38062
38062
  CLIENT_HEADER = "X-Squirrel-Client";
38063
38063
  CLIENT_NAME = "mcp";
38064
+ NOTE_BODY_HEADER = "X-Squirrel-Note-Body";
38065
+ NOTE_BODY_CAPABILITY = "chunks-v1";
38064
38066
  SquirrelApiClient = class {
38065
38067
  baseUrl;
38066
38068
  apiKey;
@@ -38083,7 +38085,8 @@ var init_api2 = __esm({
38083
38085
  headers: {
38084
38086
  Authorization: `Bearer ${this.apiKey}`,
38085
38087
  "Content-Type": "application/json",
38086
- [CLIENT_HEADER]: CLIENT_NAME
38088
+ [CLIENT_HEADER]: CLIENT_NAME,
38089
+ [NOTE_BODY_HEADER]: NOTE_BODY_CAPABILITY
38087
38090
  },
38088
38091
  body: body !== void 0 ? JSON.stringify(body) : void 0
38089
38092
  });
@@ -38109,9 +38112,16 @@ var init_api2 = __esm({
38109
38112
  getEncryption() {
38110
38113
  return this.request("GET", "/public/encryption");
38111
38114
  }
38115
+ /** Titles and metadata, no bodies (the capability header); an old backend still sends them. */
38112
38116
  listNotes() {
38113
38117
  return this.request("GET", "/public/notes");
38114
38118
  }
38119
+ /** One batch of bodies, at most 500 ids (proposal 0110 §4.11.2). */
38120
+ fetchNoteBodies(ids) {
38121
+ return this.request("POST", "/public/notes/bodies", {
38122
+ notes: ids.map((id) => ({ id }))
38123
+ });
38124
+ }
38115
38125
  getNote(id) {
38116
38126
  return this.request("GET", `/public/notes/${id}`);
38117
38127
  }
@@ -38121,6 +38131,10 @@ var init_api2 = __esm({
38121
38131
  updateNote(id, dto) {
38122
38132
  return this.request("PATCH", `/public/notes/${id}`, dto);
38123
38133
  }
38134
+ /** A chunked body's commit (proposal 0110 §4.4): one transaction, with the revision precondition. */
38135
+ putNoteBody(id, dto) {
38136
+ return this.request("PUT", `/public/notes/${id}/body`, dto);
38137
+ }
38124
38138
  deleteNote(id) {
38125
38139
  return this.requestVoid("DELETE", `/public/notes/${id}`);
38126
38140
  }
@@ -41652,7 +41666,25 @@ var init_note_text = __esm({
41652
41666
  "range-inverted": "endLine is before startLine.",
41653
41667
  "empty-content": "content is empty, so there is nothing to insert (insert_in_section also counts blank lines alone as empty).",
41654
41668
  "insert-line-out-of-range": "line is outside the note: insert before a line from minLine to totalLines, or pass maxLine (totalLines + 1) to add at the end.",
41655
- stale: "The note has changed since the updatedAt you passed as expectedUpdatedAt (an edit, or a pin, tag or move), so nothing was written. Read it again and retry with the updatedAt given here."
41669
+ stale: "The note has changed since the updatedAt you passed as expectedUpdatedAt (an edit, or a pin, tag or move), so nothing was written. Read it again and retry with the updatedAt given here.",
41670
+ // Proposal 0110 §4.9, AC5, AC6, AC54 and infosec A2: sizes travel as
41671
+ // `bytes` and `limit`; nothing from the note or an input is quoted.
41672
+ "too-long": "The note's content would be over the size limit (bytes and limit, in bytes of UTF-8 text), so nothing was written. Move part of it to a new note.",
41673
+ "title-too-long": "The title is over the size limit (bytes and limit, in bytes of UTF-8 text), so nothing was written. Use a shorter title.",
41674
+ "too-large-to-share": "This note is too large to share: its content is over the size limit (bytes and limit, in bytes of UTF-8 text). Nothing was shared.",
41675
+ "search-incomplete": "The search could not read every note; nothing was matched. Try again.",
41676
+ // Proposal 0110 R1b, §4.2's reader rule and §4.4's conflict: a long note
41677
+ // stored in parts that does not verify is never shown in part or written
41678
+ // over; a write that lost a race to another writer writes nothing.
41679
+ unreadable: "This note could not be read in full. Nothing has been changed.",
41680
+ "write-conflict": "The note changed on the server since it was read, so nothing was written. Read it again and retry.",
41681
+ // ADR-0523 §7, §8: the account's storage (notes, files and the Trash
41682
+ // until it is emptied) is full. The server's answer carries no size.
41683
+ "storage-full": "The account's storage is full, so nothing was written. Ask the user to free space: delete notes or files, or empty the Trash.",
41684
+ // #668: update_note writes long content first, then the title; the server
41685
+ // refused only the title. `status` is the HTTP status, `reason` the
41686
+ // refusal it maps to when it is one of the above (ADR-0460: no server text).
41687
+ "title-not-saved": "The content was saved, but the title was not: the server refused it (status, and reason when it is a known refusal such as storage-full). Fix the cause, then retry update_note with the title alone."
41656
41688
  };
41657
41689
  refuse2 = (error62, details) => details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
41658
41690
  isRefusal = (x) => "kind" in x && x.kind === "refused";
@@ -41687,6 +41719,589 @@ var init_note_text = __esm({
41687
41719
  }
41688
41720
  });
41689
41721
 
41722
+ // src/note-limits.ts
41723
+ function utf8Bytes(text) {
41724
+ return Buffer.byteLength(text, "utf8");
41725
+ }
41726
+ var NOTE_BODY_MAX_BYTES, NOTE_TITLE_MAX_BYTES;
41727
+ var init_note_limits = __esm({
41728
+ "src/note-limits.ts"() {
41729
+ "use strict";
41730
+ NOTE_BODY_MAX_BYTES = 75e4;
41731
+ NOTE_TITLE_MAX_BYTES = 12e3;
41732
+ }
41733
+ });
41734
+
41735
+ // src/note-chunks.ts
41736
+ function chunkAadText(noteId, chunkId, versionId) {
41737
+ return `sqn-note-chunk-v1:${noteId}:${chunkId}:${versionId}`;
41738
+ }
41739
+ function manifestAadText(noteId, revision) {
41740
+ return `sqn-note-manifest-v1:${noteId}:${revision}`;
41741
+ }
41742
+ function isUuidV4(value) {
41743
+ return typeof value === "string" && UUID_V4.test(value);
41744
+ }
41745
+ function isCount(value, max) {
41746
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
41747
+ }
41748
+ function checkManifest(value, noteId, revision) {
41749
+ const fail2 = () => {
41750
+ throw new NoteBodyUnreadableError();
41751
+ };
41752
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail2();
41753
+ const m = value;
41754
+ if (Object.keys(m).sort().join(",") !== "chunker,chunks,noteId,revision,totalBytes,v") fail2();
41755
+ if (m.v !== 1 || m.chunker !== NOTE_CHUNKER) fail2();
41756
+ if (m.noteId !== noteId || m.revision !== revision) fail2();
41757
+ if (!isCount(m.totalBytes, NOTE_BODY_MAX_BYTES2)) fail2();
41758
+ if (!Array.isArray(m.chunks) || m.chunks.length > NOTE_MANIFEST_MAX_CHUNKS) fail2();
41759
+ const chunks = m.chunks;
41760
+ if (chunks.length === 0 && m.totalBytes !== 0) fail2();
41761
+ const ids = /* @__PURE__ */ new Set();
41762
+ let sum = 0;
41763
+ const out = [];
41764
+ for (const raw of chunks) {
41765
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) fail2();
41766
+ const c = raw;
41767
+ if (Object.keys(c).sort().join(",") !== "id,len,lines,sha256,ver") fail2();
41768
+ if (!isUuidV4(c.id) || !isUuidV4(c.ver)) fail2();
41769
+ if (!isCount(c.len, CHUNK_MAX_BYTES) || c.len === 0) fail2();
41770
+ if (!isCount(c.lines, CHUNK_MAX_BYTES)) fail2();
41771
+ if (typeof c.sha256 !== "string" || !HEX_64.test(c.sha256)) fail2();
41772
+ const id = c.id;
41773
+ if (ids.has(id)) fail2();
41774
+ ids.add(id);
41775
+ sum += c.len;
41776
+ out.push({ id, ver: c.ver, len: c.len, lines: c.lines, sha256: c.sha256 });
41777
+ }
41778
+ if (sum !== m.totalBytes) fail2();
41779
+ return { v: 1, noteId, revision, chunker: NOTE_CHUNKER, totalBytes: sum, chunks: out };
41780
+ }
41781
+ function refsOf(manifest) {
41782
+ return manifest.chunks.map((c) => `${c.id}:${c.ver}`).sort();
41783
+ }
41784
+ function countLines(bytes, start = 0, end = bytes.length) {
41785
+ let n = 0;
41786
+ for (let i = start; i < end; i++) if (bytes[i] === NEWLINE) n += 1;
41787
+ return n;
41788
+ }
41789
+ function paddedLength(len) {
41790
+ return Math.max(1, Math.ceil(len / CHUNK_PAD_BYTES)) * CHUNK_PAD_BYTES;
41791
+ }
41792
+ function padChunk(bytes) {
41793
+ const out = new Uint8Array(paddedLength(bytes.length));
41794
+ out.set(bytes);
41795
+ return out;
41796
+ }
41797
+ function unpadChunk(padded, len) {
41798
+ if (padded.length !== paddedLength(len)) throw new NoteBodyUnreadableError();
41799
+ for (let i = len; i < padded.length; i++) {
41800
+ if (padded[i] !== 0) throw new NoteBodyUnreadableError();
41801
+ }
41802
+ return padded.subarray(0, len);
41803
+ }
41804
+ function gearTableFrom(bytes) {
41805
+ if (bytes.length !== GEAR_TABLE_BYTES) throw new Error("Gear table must be 1024 bytes");
41806
+ const table = new Uint32Array(256);
41807
+ for (let i = 0; i < 256; i++) {
41808
+ table[i] = (bytes[4 * i] << 24 | bytes[4 * i + 1] << 16 | bytes[4 * i + 2] << 8 | bytes[4 * i + 3]) >>> 0;
41809
+ }
41810
+ return table;
41811
+ }
41812
+ function nextCut(bytes, start, to, gear) {
41813
+ if (to - start <= CHUNK_MIN_BYTES) return to;
41814
+ const limit = Math.min(to, start + CHUNK_MAX_BYTES);
41815
+ let hash2 = 0;
41816
+ let armed = false;
41817
+ let lastLineStart = -1;
41818
+ for (let i = start; i < limit; i++) {
41819
+ const b = bytes[i];
41820
+ hash2 = (hash2 << 1) + gear[b] >>> 0;
41821
+ if (b === NEWLINE && i + 1 - start >= CHUNK_MIN_BYTES) {
41822
+ if (armed) return i + 1;
41823
+ lastLineStart = i + 1;
41824
+ }
41825
+ if (!armed && i + 1 - start >= CHUNK_MIN_BYTES && (hash2 & GEAR_ARM_MASK) === 0) armed = true;
41826
+ }
41827
+ if (limit === to) return to;
41828
+ if (lastLineStart > 0) return lastLineStart;
41829
+ let cut = limit;
41830
+ while (cut > start + 1 && (bytes[cut] & 192) === 128) cut -= 1;
41831
+ return cut;
41832
+ }
41833
+ function cdcSplit(bytes, from, to, gear) {
41834
+ const ends = [];
41835
+ let start = from;
41836
+ while (start < to) {
41837
+ const end = nextCut(bytes, start, to, gear);
41838
+ ends.push(end);
41839
+ start = end;
41840
+ }
41841
+ return ends;
41842
+ }
41843
+ function commonPrefix(a, b) {
41844
+ const n = Math.min(a.length, b.length);
41845
+ let i = 0;
41846
+ while (i < n && a[i] === b[i]) i += 1;
41847
+ return i;
41848
+ }
41849
+ function commonSuffix(a, b, max) {
41850
+ let i = 0;
41851
+ while (i < max && a[a.length - 1 - i] === b[b.length - 1 - i]) i += 1;
41852
+ return i;
41853
+ }
41854
+ function sameBytes(a, aStart, b, bStart, len) {
41855
+ for (let i = 0; i < len; i++) if (a[aStart + i] !== b[bStart + i]) return false;
41856
+ return true;
41857
+ }
41858
+ function planChunks(bytes, gear, previous) {
41859
+ if (bytes.length === 0) return [];
41860
+ const old = previous?.manifest.chunks ?? [];
41861
+ if (!previous || old.length === 0) {
41862
+ let start = 0;
41863
+ return cdcSplit(bytes, 0, bytes.length, gear).map((end) => {
41864
+ const chunk = { start, end, keepId: null, reuse: null };
41865
+ start = end;
41866
+ return chunk;
41867
+ });
41868
+ }
41869
+ const oldBytes = previous.bytes;
41870
+ const prefix = commonPrefix(oldBytes, bytes);
41871
+ const suffix = commonSuffix(oldBytes, bytes, Math.min(oldBytes.length, bytes.length) - prefix);
41872
+ const delta = bytes.length - oldBytes.length;
41873
+ const map2 = (b) => {
41874
+ if (b <= prefix) return b;
41875
+ if (b >= oldBytes.length - suffix) return b + delta;
41876
+ return -1;
41877
+ };
41878
+ const oldStarts = [];
41879
+ let offset = 0;
41880
+ for (const c of old) {
41881
+ oldStarts.push(offset);
41882
+ offset += c.len;
41883
+ }
41884
+ const kept = [{ pos: 0, index: 0 }];
41885
+ for (let i = 1; i < old.length; i++) {
41886
+ const pos = map2(oldStarts[i]);
41887
+ if (pos <= kept[kept.length - 1].pos || pos >= bytes.length) continue;
41888
+ if (bytes[pos - 1] !== NEWLINE) continue;
41889
+ kept.push({ pos, index: i });
41890
+ }
41891
+ const spans = [];
41892
+ for (let k = 0; k < kept.length; k++) {
41893
+ const here = kept[k];
41894
+ const next = k + 1 < kept.length ? kept[k + 1].pos : bytes.length;
41895
+ if (spans.length > 0 && next - here.pos < CHUNK_MIN_BYTES && k + 1 < kept.length) continue;
41896
+ spans.push(here);
41897
+ }
41898
+ if (spans.length > 1 && spans[1].pos - spans[0].pos < CHUNK_MIN_BYTES) spans.splice(1, 1);
41899
+ const planned = [];
41900
+ for (let s = 0; s < spans.length; s++) {
41901
+ const span2 = spans[s];
41902
+ const from = span2.pos;
41903
+ const to = s + 1 < spans.length ? spans[s + 1].pos : bytes.length;
41904
+ const ends = to - from > CHUNK_MAX_BYTES ? cdcSplit(bytes, from, to, gear) : [to];
41905
+ let start = from;
41906
+ for (const [n, end] of ends.entries()) {
41907
+ const prev = old[span2.index];
41908
+ const keepId = n === 0 ? prev.id : null;
41909
+ let reuse = null;
41910
+ if (n === 0) {
41911
+ const prevStart = oldStarts[span2.index];
41912
+ if (prev.len === end - start && sameBytes(oldBytes, prevStart, bytes, start, prev.len)) reuse = prev;
41913
+ }
41914
+ planned.push({ start, end, keepId, reuse });
41915
+ start = end;
41916
+ }
41917
+ }
41918
+ return planned;
41919
+ }
41920
+ var NOTE_CHUNKER, NOTE_BODY_FORMAT_CHUNKS, CHUNK_MIN_BYTES, CHUNK_MAX_BYTES, CHUNK_PAD_BYTES, NOTE_CHUNKING_THRESHOLD_BYTES, NOTE_BODY_MAX_BYTES2, NOTE_MANIFEST_MAX_CHUNKS, CHUNK_CIPHERTEXT_OVERHEAD, NOTE_CHUNKER_INFO, GEAR_TABLE_BYTES, GEAR_ARM_MASK, NEWLINE, NoteBodyUnreadableError, UUID_V4, HEX_64;
41921
+ var init_note_chunks = __esm({
41922
+ "src/note-chunks.ts"() {
41923
+ "use strict";
41924
+ NOTE_CHUNKER = "cdc-v1";
41925
+ NOTE_BODY_FORMAT_CHUNKS = "chunks-v1";
41926
+ CHUNK_MIN_BYTES = 16 * 1024;
41927
+ CHUNK_MAX_BYTES = 128 * 1024;
41928
+ CHUNK_PAD_BYTES = 1024;
41929
+ NOTE_CHUNKING_THRESHOLD_BYTES = 256 * 1024;
41930
+ NOTE_BODY_MAX_BYTES2 = 3 * 1024 * 1024;
41931
+ NOTE_MANIFEST_MAX_CHUNKS = Math.floor(NOTE_BODY_MAX_BYTES2 / CHUNK_MIN_BYTES) + Math.floor(NOTE_BODY_MAX_BYTES2 / (CHUNK_MAX_BYTES + 1)) + 1;
41932
+ CHUNK_CIPHERTEXT_OVERHEAD = CHUNK_PAD_BYTES - 1 + 16 + 2;
41933
+ NOTE_CHUNKER_INFO = "sqn-note-chunker-v1";
41934
+ GEAR_TABLE_BYTES = 1024;
41935
+ GEAR_ARM_MASK = 4294705152;
41936
+ NEWLINE = 10;
41937
+ NoteBodyUnreadableError = class extends Error {
41938
+ constructor() {
41939
+ super("This note could not be read in full");
41940
+ this.name = "NoteBodyUnreadableError";
41941
+ }
41942
+ };
41943
+ UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
41944
+ HEX_64 = /^[0-9a-f]{64}$/;
41945
+ }
41946
+ });
41947
+
41948
+ // src/note-body.ts
41949
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, createHash as createHash2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
41950
+ function gcmEncrypt(key, iv, plaintext, aad) {
41951
+ const cipher = createCipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
41952
+ cipher.setAAD(Buffer.from(aad, "utf8"));
41953
+ const body = Buffer.concat([cipher.update(plaintext), cipher.final()]);
41954
+ return Buffer.concat([body, cipher.getAuthTag()]).toString("base64");
41955
+ }
41956
+ function gcmDecrypt(key, ivBase64, ciphertextBase64, aad) {
41957
+ const iv = Buffer.from(ivBase64, "base64");
41958
+ const combined = Buffer.from(ciphertextBase64, "base64");
41959
+ if (iv.length !== IV_BYTES || combined.length < TAG_BYTES) throw new NoteBodyUnreadableError();
41960
+ try {
41961
+ const decipher = createDecipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
41962
+ decipher.setAAD(Buffer.from(aad, "utf8"));
41963
+ decipher.setAuthTag(combined.subarray(combined.length - TAG_BYTES));
41964
+ return Buffer.concat([decipher.update(combined.subarray(0, combined.length - TAG_BYTES)), decipher.final()]);
41965
+ } catch {
41966
+ throw new NoteBodyUnreadableError();
41967
+ }
41968
+ }
41969
+ function chunkDigest(ivBase64, ciphertextBase64) {
41970
+ return createHash2("sha256").update(Buffer.from(ivBase64, "base64")).update(Buffer.from(ciphertextBase64, "base64")).digest("hex");
41971
+ }
41972
+ function noteChunkerGear(dek) {
41973
+ const ikm = Buffer.from(gcmEncrypt(dek, Buffer.alloc(IV_BYTES), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), ""), "base64");
41974
+ const okm = hkdfSync("sha256", ikm, Buffer.alloc(0), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), GEAR_TABLE_BYTES);
41975
+ return gearTableFrom(new Uint8Array(okm));
41976
+ }
41977
+ function encryptNoteChunk(dek, noteId, chunkId, bytes, fixed = {}) {
41978
+ const versionId = fixed.versionId ?? randomUUID2();
41979
+ const iv = fixed.iv ?? randomBytes2(IV_BYTES);
41980
+ const ciphertext = gcmEncrypt(dek, iv, padChunk(bytes), chunkAadText(noteId, chunkId, versionId));
41981
+ const ivBase64 = iv.toString("base64");
41982
+ return {
41983
+ chunk: { chunkId, versionId, ciphertext, iv: ivBase64 },
41984
+ entry: {
41985
+ id: chunkId,
41986
+ ver: versionId,
41987
+ len: bytes.length,
41988
+ lines: countLines(bytes),
41989
+ sha256: chunkDigest(ivBase64, ciphertext)
41990
+ }
41991
+ };
41992
+ }
41993
+ function decryptNoteChunk(dek, noteId, chunk, expected) {
41994
+ if (chunk.chunkId !== expected.id || chunk.versionId !== expected.ver) throw new NoteBodyUnreadableError();
41995
+ if (chunkDigest(chunk.iv, chunk.ciphertext) !== expected.sha256) throw new NoteBodyUnreadableError();
41996
+ const padded = gcmDecrypt(dek, chunk.iv, chunk.ciphertext, chunkAadText(noteId, chunk.chunkId, chunk.versionId));
41997
+ return unpadChunk(new Uint8Array(padded), expected.len);
41998
+ }
41999
+ function encryptNoteManifest(dek, manifest, fixed = {}) {
42000
+ checkManifest(manifest, manifest.noteId, manifest.revision);
42001
+ const iv = fixed.iv ?? randomBytes2(IV_BYTES);
42002
+ const plaintext = Buffer.from(JSON.stringify(manifest), "utf8");
42003
+ return {
42004
+ ciphertext: gcmEncrypt(dek, iv, plaintext, manifestAadText(manifest.noteId, manifest.revision)),
42005
+ iv: iv.toString("base64")
42006
+ };
42007
+ }
42008
+ function decryptNoteManifest(dek, noteId, revision, ciphertext, iv) {
42009
+ const plaintext = gcmDecrypt(dek, iv, ciphertext, manifestAadText(noteId, revision));
42010
+ let parsed;
42011
+ try {
42012
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(plaintext));
42013
+ } catch {
42014
+ throw new NoteBodyUnreadableError();
42015
+ }
42016
+ return checkManifest(parsed, noteId, revision);
42017
+ }
42018
+ function readChunkedBody(dek, noteId, body) {
42019
+ const manifest = decryptNoteManifest(dek, noteId, body.revision, body.encryptedManifest, body.manifestIv);
42020
+ const served = new Map(body.chunks.map((c) => [`${c.chunkId}:${c.versionId}`, c]));
42021
+ const bytes = new Uint8Array(manifest.totalBytes);
42022
+ const parts = [];
42023
+ let offset = 0;
42024
+ for (const entry2 of manifest.chunks) {
42025
+ const chunk = served.get(`${entry2.id}:${entry2.ver}`);
42026
+ if (!chunk) throw new NoteBodyUnreadableError();
42027
+ const part = decryptNoteChunk(dek, noteId, chunk, entry2);
42028
+ try {
42029
+ parts.push(new TextDecoder("utf-8", { fatal: true }).decode(part));
42030
+ } catch {
42031
+ throw new NoteBodyUnreadableError();
42032
+ }
42033
+ bytes.set(part, offset);
42034
+ offset += entry2.len;
42035
+ }
42036
+ return { text: parts.join(""), revision: body.revision, manifest, bytes };
42037
+ }
42038
+ function buildChunkedCommit(dek, noteId, text, base) {
42039
+ const bytes = new TextEncoder().encode(text);
42040
+ if (bytes.length > NOTE_BODY_MAX_BYTES2) throw new NoteBodyTooLargeError(bytes.length);
42041
+ const plan = planChunks(bytes, noteChunkerGear(dek), base ? { bytes: base.bytes, manifest: base.manifest } : void 0);
42042
+ const entries = [];
42043
+ const fresh = [];
42044
+ for (const p of plan) {
42045
+ if (p.reuse) {
42046
+ entries.push(p.reuse);
42047
+ continue;
42048
+ }
42049
+ const { chunk, entry: entry2 } = encryptNoteChunk(dek, noteId, p.keepId ?? randomUUID2(), bytes.subarray(p.start, p.end));
42050
+ entries.push(entry2);
42051
+ fresh.push(chunk);
42052
+ }
42053
+ const revision = (base?.revision ?? 0) + 1;
42054
+ const manifest = {
42055
+ v: 1,
42056
+ noteId,
42057
+ revision,
42058
+ chunker: NOTE_CHUNKER,
42059
+ totalBytes: bytes.length,
42060
+ chunks: entries
42061
+ };
42062
+ const { ciphertext, iv } = encryptNoteManifest(dek, manifest);
42063
+ fresh.sort((a, b) => a.chunkId === b.chunkId ? cmp(a.versionId, b.versionId) : cmp(a.chunkId, b.chunkId));
42064
+ return {
42065
+ commit: {
42066
+ baseRevision: base?.revision ?? 0,
42067
+ encryptedManifest: ciphertext,
42068
+ manifestIv: iv,
42069
+ refs: refsOf(manifest),
42070
+ chunks: fresh
42071
+ },
42072
+ manifest
42073
+ };
42074
+ }
42075
+ function cmp(a, b) {
42076
+ return a < b ? -1 : a > b ? 1 : 0;
42077
+ }
42078
+ var IV_BYTES, TAG_BYTES, NoteBodyTooLargeError;
42079
+ var init_note_body = __esm({
42080
+ "src/note-body.ts"() {
42081
+ "use strict";
42082
+ init_note_chunks();
42083
+ IV_BYTES = 12;
42084
+ TAG_BYTES = 16;
42085
+ NoteBodyTooLargeError = class extends Error {
42086
+ constructor(bytes) {
42087
+ super("Note body over the limit");
42088
+ this.bytes = bytes;
42089
+ this.name = "NoteBodyTooLargeError";
42090
+ }
42091
+ bytes;
42092
+ };
42093
+ }
42094
+ });
42095
+
42096
+ // src/note-content.ts
42097
+ import { randomUUID as randomUUID3 } from "node:crypto";
42098
+ function inlineContentFields(sealed) {
42099
+ return { encryptedContent: sealed.ciphertext, contentIv: sealed.iv };
42100
+ }
42101
+ function listedBodyOf(n) {
42102
+ return n.encryptedContent !== void 0 ? { encryptedContent: n.encryptedContent, contentIv: n.contentIv } : null;
42103
+ }
42104
+ function bodyOfEntry(b) {
42105
+ return b.bodyFormat === NOTE_BODY_FORMAT_CHUNKS ? { encryptedContent: "", contentIv: null, bodyFormat: NOTE_BODY_FORMAT_CHUNKS, body: b.body } : { encryptedContent: b.encryptedContent, contentIv: b.contentIv };
42106
+ }
42107
+ function bodyOfNote(n) {
42108
+ return {
42109
+ encryptedContent: n.encryptedContent,
42110
+ contentIv: n.contentIv,
42111
+ ...n.bodyFormat ? { bodyFormat: n.bodyFormat } : {},
42112
+ ...n.body ? { body: n.body } : {}
42113
+ };
42114
+ }
42115
+ function readNoteContent(note, key) {
42116
+ if (note.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) {
42117
+ if (!note.body) throw new NoteBodyUnreadableError();
42118
+ const chunked = readChunkedBody(key, note.id, note.body);
42119
+ if (note.encryptedContent) throw new NoteBodyUnreadableError();
42120
+ return { text: chunked.text, chunked, inlineIv: null };
42121
+ }
42122
+ const text = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42123
+ return { text, chunked: null, inlineIv: note.contentIv ?? null };
42124
+ }
42125
+ function refused(error62, details) {
42126
+ return details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
42127
+ }
42128
+ function lostRace(err) {
42129
+ return err instanceof SquirrelApiError && err.status === 409 && /NOTE_BODY_(CONFLICT|CHUNKED)/.test(err.responseBody);
42130
+ }
42131
+ function codeOf(err) {
42132
+ try {
42133
+ const body = JSON.parse(err.responseBody);
42134
+ return typeof body === "object" && body !== null ? body.code : void 0;
42135
+ } catch {
42136
+ return void 0;
42137
+ }
42138
+ }
42139
+ function serverRefusal(err, bytes) {
42140
+ if (!(err instanceof SquirrelApiError)) return null;
42141
+ const code = codeOf(err);
42142
+ if (err.status === 413 && code === "NOTE_OVER_PLAN_LIMIT") {
42143
+ return refused("too-long", bytes === void 0 ? { limit: NOTE_BODY_MAX_BYTES2 } : { bytes, limit: NOTE_BODY_MAX_BYTES2 });
42144
+ }
42145
+ if ((err.status === 422 || err.status === 400) && code === "STORAGE_LIMIT_EXCEEDED") return refused("storage-full");
42146
+ return null;
42147
+ }
42148
+ function overThreshold(bytes) {
42149
+ return bytes > NOTE_CHUNKING_THRESHOLD_BYTES;
42150
+ }
42151
+ function overInlineCap(bytes) {
42152
+ return bytes > NOTE_BODY_MAX_BYTES ? refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES }) : null;
42153
+ }
42154
+ async function writeNoteContent(client, key, noteId, text, current) {
42155
+ const tooLong = newContentTooLong(text);
42156
+ if (tooLong) return tooLong;
42157
+ const bytes = utf8Bytes(text);
42158
+ if (current.chunked || overThreshold(bytes)) {
42159
+ const { commit } = buildChunkedCommit(key, noteId, text, current.chunked ?? void 0);
42160
+ try {
42161
+ const saved = await client.putNoteBody(noteId, commit);
42162
+ return { kind: "written", updatedAt: saved.updatedAt };
42163
+ } catch (err) {
42164
+ if (lostRace(err)) return refused("write-conflict");
42165
+ const refusal = serverRefusal(err, bytes);
42166
+ if (refusal) return refusal;
42167
+ throw err;
42168
+ }
42169
+ }
42170
+ const capped = overInlineCap(bytes);
42171
+ if (capped) return capped;
42172
+ const enc = encrypt(text, key);
42173
+ try {
42174
+ const saved = await client.updateNote(noteId, { ...inlineContentFields(enc), baseContentIv: current.inlineIv });
42175
+ return { kind: "written", updatedAt: saved.updatedAt };
42176
+ } catch (err) {
42177
+ if (lostRace(err)) return refused("write-conflict");
42178
+ const refusal = serverRefusal(err, bytes);
42179
+ if (refusal) return refusal;
42180
+ throw err;
42181
+ }
42182
+ }
42183
+ function newContentTooLong(text) {
42184
+ const bytes = utf8Bytes(text);
42185
+ return bytes > NOTE_BODY_MAX_BYTES2 ? refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES2 }) : null;
42186
+ }
42187
+ async function createNoteWithContent(client, key, fields, text) {
42188
+ if (text === void 0) return { kind: "created", note: await client.createNote(fields) };
42189
+ const tooLong = newContentTooLong(text);
42190
+ if (tooLong) return tooLong;
42191
+ const bytes = utf8Bytes(text);
42192
+ if (overThreshold(bytes)) {
42193
+ const id = randomUUID3();
42194
+ let note;
42195
+ try {
42196
+ note = await client.createNote({ ...fields, id, body: buildChunkedCommit(key, id, text).commit });
42197
+ } catch (err) {
42198
+ const refusal = serverRefusal(err, bytes);
42199
+ if (refusal) return refusal;
42200
+ throw err;
42201
+ }
42202
+ if (note.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) return { kind: "created", note };
42203
+ const capped = overInlineCap(bytes);
42204
+ if (capped) return capped;
42205
+ return { kind: "created", note: await client.updateNote(note.id, inlineContentFields(encrypt(text, key))) };
42206
+ }
42207
+ try {
42208
+ return { kind: "created", note: await client.createNote({ ...fields, ...inlineContentFields(encrypt(text, key)) }) };
42209
+ } catch (err) {
42210
+ const refusal = serverRefusal(err, bytes);
42211
+ if (refusal) return refusal;
42212
+ throw err;
42213
+ }
42214
+ }
42215
+ var init_note_content = __esm({
42216
+ "src/note-content.ts"() {
42217
+ "use strict";
42218
+ init_api_error();
42219
+ init_crypto();
42220
+ init_note_body();
42221
+ init_note_chunks();
42222
+ init_note_limits();
42223
+ }
42224
+ });
42225
+
42226
+ // src/note-bodies.ts
42227
+ function isTransient(err) {
42228
+ return err instanceof SquirrelNetworkError || err instanceof SquirrelApiError && (err.status === 429 || err.status >= 500);
42229
+ }
42230
+ async function withBodies(client, listed, options = {}) {
42231
+ const delays = options.retryDelaysMs ?? NOTE_BODIES_RETRY_DELAYS_MS;
42232
+ const bodies = /* @__PURE__ */ new Map();
42233
+ for (const n of listed) {
42234
+ const body = listedBodyOf(n);
42235
+ if (body) bodies.set(n.id, body);
42236
+ }
42237
+ const missing = /* @__PURE__ */ new Set();
42238
+ let owed = listed.map((n) => n.id).filter((id) => !bodies.has(id));
42239
+ const attempt = async (call) => {
42240
+ for (let i = 0; ; i++) {
42241
+ try {
42242
+ return await call();
42243
+ } catch (err) {
42244
+ if (!isTransient(err)) throw err;
42245
+ if (i >= delays.length) throw new NoteBodiesIncompleteError();
42246
+ await sleep(delays[i]);
42247
+ }
42248
+ }
42249
+ };
42250
+ while (owed.length > 0) {
42251
+ const batch = owed.slice(0, NOTE_BODIES_BATCH);
42252
+ let page;
42253
+ try {
42254
+ page = await attempt(() => client.fetchNoteBodies(batch));
42255
+ } catch (err) {
42256
+ if (err instanceof SquirrelApiError && err.status === 404) {
42257
+ await oneAtATime(client, owed, bodies, missing, attempt);
42258
+ break;
42259
+ }
42260
+ throw err;
42261
+ }
42262
+ for (const b of page.bodies) {
42263
+ bodies.set(b.id, bodyOfEntry(b));
42264
+ }
42265
+ for (const id of page.missing) missing.add(id);
42266
+ if (page.bodies.length === 0 && page.missing.length === 0) {
42267
+ throw new NoteBodiesIncompleteError();
42268
+ }
42269
+ owed = owed.filter((id) => !bodies.has(id) && !missing.has(id));
42270
+ }
42271
+ return listed.flatMap((n) => {
42272
+ const body = bodies.get(n.id);
42273
+ return body ? [{ ...n, ...body }] : [];
42274
+ });
42275
+ }
42276
+ async function oneAtATime(client, ids, bodies, missing, attempt) {
42277
+ for (const id of ids) {
42278
+ try {
42279
+ const n = await attempt(() => client.getNote(id));
42280
+ bodies.set(id, bodyOfNote(n));
42281
+ } catch (err) {
42282
+ if (err instanceof SquirrelApiError && err.status === 404) missing.add(id);
42283
+ else throw err;
42284
+ }
42285
+ }
42286
+ }
42287
+ var NOTE_BODIES_BATCH, NOTE_BODIES_RETRY_DELAYS_MS, NoteBodiesIncompleteError, sleep;
42288
+ var init_note_bodies = __esm({
42289
+ "src/note-bodies.ts"() {
42290
+ "use strict";
42291
+ init_api_error();
42292
+ init_note_content();
42293
+ NOTE_BODIES_BATCH = 500;
42294
+ NOTE_BODIES_RETRY_DELAYS_MS = [250, 1e3];
42295
+ NoteBodiesIncompleteError = class extends Error {
42296
+ constructor() {
42297
+ super("not every note body could be read");
42298
+ this.name = "NoteBodiesIncompleteError";
42299
+ }
42300
+ };
42301
+ sleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
42302
+ }
42303
+ });
42304
+
41690
42305
  // src/server.ts
41691
42306
  var server_exports = {};
41692
42307
  __export(server_exports, {
@@ -41733,7 +42348,7 @@ function decryptNoteTitle(note, key) {
41733
42348
  }
41734
42349
  function decryptNote(note, key) {
41735
42350
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
41736
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42351
+ const content = readNoteContent(note, key).text;
41737
42352
  const tagIds = note.tags?.map((t) => t.id) ?? [];
41738
42353
  return { ...note, title, content, tagIds };
41739
42354
  }
@@ -41757,6 +42372,31 @@ function inferMimeType(filePath) {
41757
42372
  function refusalResult(r) {
41758
42373
  return { content: [{ type: "text", text: refusalJson(r) }], isError: true };
41759
42374
  }
42375
+ function bodyTooLong(text, error62 = "too-long") {
42376
+ const bytes = utf8Bytes(text);
42377
+ return bytes > NOTE_BODY_MAX_BYTES ? { kind: "refused", error: error62, details: { bytes, limit: NOTE_BODY_MAX_BYTES } } : null;
42378
+ }
42379
+ function titleTooLong(title) {
42380
+ const bytes = utf8Bytes(title);
42381
+ return bytes > NOTE_TITLE_MAX_BYTES ? { kind: "refused", error: "title-too-long", details: { bytes, limit: NOTE_TITLE_MAX_BYTES } } : null;
42382
+ }
42383
+ function refuseUnreadableBodies(server) {
42384
+ const register = server.tool.bind(server);
42385
+ server.tool = (...args) => {
42386
+ const handler = args[args.length - 1];
42387
+ args[args.length - 1] = async (...a) => {
42388
+ try {
42389
+ return await handler(...a);
42390
+ } catch (err) {
42391
+ if (err instanceof NoteBodyUnreadableError) return refusalResult({ kind: "refused", error: "unreadable" });
42392
+ const refusal = serverRefusal(err);
42393
+ if (refusal) return refusalResult(refusal);
42394
+ throw err;
42395
+ }
42396
+ };
42397
+ return register(...args);
42398
+ };
42399
+ }
41760
42400
  function jsonResult(value) {
41761
42401
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
41762
42402
  }
@@ -41768,6 +42408,7 @@ function createMcpServer(creds, opts = {}) {
41768
42408
  const context = createContextProvider(
41769
42409
  (onUnauthorized) => buildContext(creds, onUnauthorized)
41770
42410
  );
42411
+ refuseUnreadableBodies(server);
41771
42412
  server.prompt(
41772
42413
  "markdown_capabilities",
41773
42414
  "Describes the Markdown and Mermaid diagram features supported by Squirrel Notes. Use this to understand what rich content you can include when creating or updating notes.",
@@ -41865,15 +42506,18 @@ function createMcpServer(creds, opts = {}) {
41865
42506
  collectionId: external_exports.string().optional().describe("Collection ID to place the note in. Omit to create in scratchpad.")
41866
42507
  },
41867
42508
  async ({ title, content, collectionId }) => {
42509
+ const tooLong = titleTooLong(title) ?? (content !== void 0 ? newContentTooLong(content) : null);
42510
+ if (tooLong) return refusalResult(tooLong);
41868
42511
  const { client, key } = await context.get();
41869
42512
  const encTitle = encrypt(title, key);
41870
- const encContent = content !== void 0 ? encrypt(content, key) : null;
41871
- const note = await client.createNote({
41872
- encryptedTitle: encTitle.ciphertext,
41873
- titleIv: encTitle.iv,
41874
- ...encContent ? { encryptedContent: encContent.ciphertext, contentIv: encContent.iv } : {},
41875
- collectionId: collectionId ?? null
41876
- });
42513
+ const created = await createNoteWithContent(
42514
+ client,
42515
+ key,
42516
+ { encryptedTitle: encTitle.ciphertext, titleIv: encTitle.iv, collectionId: collectionId ?? null },
42517
+ content
42518
+ );
42519
+ if (created.kind === "refused") return refusalResult(created);
42520
+ const { note } = created;
41877
42521
  return {
41878
42522
  content: [
41879
42523
  {
@@ -41893,6 +42537,8 @@ function createMcpServer(creds, opts = {}) {
41893
42537
  content: external_exports.string().optional().describe("New content in Markdown (replaces existing content)")
41894
42538
  },
41895
42539
  async ({ id, title, content }) => {
42540
+ const titleRefusal = title !== void 0 ? titleTooLong(title) : null;
42541
+ if (titleRefusal) return refusalResult(titleRefusal);
41896
42542
  const { client, key } = await context.get();
41897
42543
  const dto = {};
41898
42544
  if (title !== void 0) {
@@ -41900,15 +42546,34 @@ function createMcpServer(creds, opts = {}) {
41900
42546
  dto.encryptedTitle = enc.ciphertext;
41901
42547
  dto.titleIv = enc.iv;
41902
42548
  }
41903
- if (content !== void 0) {
42549
+ if (content !== void 0 && utf8Bytes(content) <= NOTE_CHUNKING_THRESHOLD_BYTES) {
41904
42550
  const enc = encrypt(content, key);
41905
- dto.encryptedContent = enc.ciphertext;
41906
- dto.contentIv = enc.iv;
42551
+ try {
42552
+ const note = await client.updateNote(id, { ...dto, ...inlineContentFields(enc) });
42553
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42554
+ } catch (err) {
42555
+ if (!(err instanceof SquirrelApiError && err.status === 409 && err.responseBody.includes("NOTE_BODY_CHUNKED"))) throw err;
42556
+ }
41907
42557
  }
41908
- const note = await client.updateNote(id, dto);
41909
- return {
41910
- content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }]
41911
- };
42558
+ if (content === void 0) {
42559
+ const note = await client.updateNote(id, dto);
42560
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42561
+ }
42562
+ const tooLong = newContentTooLong(content);
42563
+ if (tooLong) return refusalResult(tooLong);
42564
+ const current = readNoteContent(await client.getNote(id), key);
42565
+ const written = await writeNoteContent(client, key, id, content, current);
42566
+ if (written.kind === "refused") return refusalResult(written);
42567
+ if (title !== void 0) {
42568
+ try {
42569
+ await client.updateNote(id, dto);
42570
+ } catch (err) {
42571
+ if (!(err instanceof SquirrelApiError)) throw err;
42572
+ const reason = serverRefusal(err)?.error;
42573
+ return refusalResult({ kind: "refused", error: "title-not-saved", details: { ...reason ? { reason } : {}, status: err.status } });
42574
+ }
42575
+ }
42576
+ return { content: [{ type: "text", text: JSON.stringify({ id, updated: true }, null, 2) }] };
41912
42577
  }
41913
42578
  );
41914
42579
  const staleCheck = (updatedAt, expected) => expected !== void 0 && expected !== updatedAt ? { kind: "refused", error: "stale", details: { updatedAt } } : null;
@@ -41929,14 +42594,12 @@ function createMcpServer(creds, opts = {}) {
41929
42594
  const note = await client.getNote(id);
41930
42595
  const stale = staleCheck(note.updatedAt, expectedUpdatedAt);
41931
42596
  if (stale) return refusalResult(stale);
41932
- const existingContent = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42597
+ const current = readNoteContent(note, key);
42598
+ const existingContent = current.text;
41933
42599
  const newContent = existingContent ? `${existingContent}${separator2}${content}` : content;
41934
- const encContent = encrypt(newContent, key);
41935
- const saved = await client.updateNote(id, {
41936
- encryptedContent: encContent.ciphertext,
41937
- contentIv: encContent.iv
41938
- });
41939
- const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: saved.updatedAt };
42600
+ const written = await writeNoteContent(client, key, id, newContent, current);
42601
+ if (written.kind === "refused") return refusalResult(written);
42602
+ const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: written.updatedAt };
41940
42603
  return {
41941
42604
  content: [{ type: "text", text: JSON.stringify(answer, null, 2) }]
41942
42605
  };
@@ -41945,13 +42608,12 @@ function createMcpServer(creds, opts = {}) {
41945
42608
  const loadNote = async (id) => {
41946
42609
  const { client, key } = await context.get();
41947
42610
  const note = await client.getNote(id);
41948
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
41949
- return { client, key, note, nt: noteText(content) };
42611
+ const body = readNoteContent(note, key);
42612
+ return { client, key, note, body, nt: noteText(body.text) };
41950
42613
  };
41951
42614
  const writeContent = async (ctx, id, raw) => {
41952
- const enc = encrypt(raw, ctx.key);
41953
- const saved = await ctx.client.updateNote(id, { encryptedContent: enc.ciphertext, contentIv: enc.iv });
41954
- return saved.updatedAt;
42615
+ const written = await writeNoteContent(ctx.client, ctx.key, id, raw, ctx.body);
42616
+ return written.kind === "written" ? written.updatedAt : written;
41955
42617
  };
41956
42618
  const headingSchema = external_exports.string().describe(`A heading's text exactly as get_note_outline lists it (at most ${HEADING_TEXT_MAX} characters)`);
41957
42619
  const occurrenceSchema = external_exports.number().int().min(1).optional().describe("Which heading with that text, 1 for the first. Needed only when the text appears more than once.");
@@ -42015,6 +42677,7 @@ function createMcpServer(creds, opts = {}) {
42015
42677
  if (isRefusal(r)) return refusalResult(r);
42016
42678
  if (r.kind === "unchanged") return jsonResult({ id, changed: false, updatedAt: ctx.note.updatedAt });
42017
42679
  const updatedAt = await writeContent(ctx, id, r.raw);
42680
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42018
42681
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
42019
42682
  }
42020
42683
  );
@@ -42037,6 +42700,7 @@ function createMcpServer(creds, opts = {}) {
42037
42700
  const r = replaceSection(ctx.nt, h, content);
42038
42701
  if (r.kind === "unchanged") return jsonResult({ id, changed: false, removedSubheadings: r.removedSubheadings, updatedAt: ctx.note.updatedAt });
42039
42702
  const updatedAt = await writeContent(ctx, id, r.raw);
42703
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42040
42704
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, removedSubheadings: r.removedSubheadings, updatedAt });
42041
42705
  }
42042
42706
  );
@@ -42060,6 +42724,7 @@ function createMcpServer(creds, opts = {}) {
42060
42724
  const r = insertInSection(ctx.nt, h, content, position);
42061
42725
  if (isRefusal(r)) return refusalResult(r);
42062
42726
  const updatedAt = await writeContent(ctx, id, r.raw);
42727
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42063
42728
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
42064
42729
  }
42065
42730
  );
@@ -42080,6 +42745,7 @@ function createMcpServer(creds, opts = {}) {
42080
42745
  if (isRefusal(h)) return refusalResult(h);
42081
42746
  const r = deleteSection(ctx.nt, h);
42082
42747
  const updatedAt = await writeContent(ctx, id, r.raw);
42748
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42083
42749
  return jsonResult({ id, changed: true, removedLines: { startLine: r.startLine, endLine: r.endLine }, removedSubheadings: r.removedSubheadings, updatedAt });
42084
42750
  }
42085
42751
  );
@@ -42099,6 +42765,7 @@ function createMcpServer(creds, opts = {}) {
42099
42765
  const r = insertAtLine(ctx.nt, line, content);
42100
42766
  if (isRefusal(r)) return refusalResult(r);
42101
42767
  const updatedAt = await writeContent(ctx, id, r.raw);
42768
+ if (typeof updatedAt !== "string") return refusalResult(updatedAt);
42102
42769
  return jsonResult({ id, changed: true, startLine: r.startLine, endLine: r.endLine, updatedAt });
42103
42770
  }
42104
42771
  );
@@ -42226,7 +42893,15 @@ function createMcpServer(creds, opts = {}) {
42226
42893
  },
42227
42894
  async ({ query, includeContent = false, limit }) => {
42228
42895
  const { client, key } = await context.get();
42229
- const notes = await client.listNotes();
42896
+ let notes;
42897
+ try {
42898
+ notes = await withBodies(client, await client.listNotes(), {
42899
+ ...opts.noteBodiesRetryDelaysMs ? { retryDelaysMs: opts.noteBodiesRetryDelaysMs } : {}
42900
+ });
42901
+ } catch (err) {
42902
+ if (err instanceof NoteBodiesIncompleteError) return refusalResult({ kind: "refused", error: "search-incomplete" });
42903
+ throw err;
42904
+ }
42230
42905
  const fq = foldForSearch(query);
42231
42906
  const matches = notes.map((n) => decryptNote(n, key)).map((n) => ({ n, titleMatch: foldForSearch(n.title).includes(fq) })).filter(({ n, titleMatch }) => titleMatch || foldForSearch(n.content).includes(fq));
42232
42907
  if (includeContent) {
@@ -42579,7 +43254,9 @@ function createMcpServer(creds, opts = {}) {
42579
43254
  const { client, key } = await context.get();
42580
43255
  const note = await client.getNote(noteId);
42581
43256
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42582
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43257
+ const content = readNoteContent(note, key).text;
43258
+ const tooLarge = bodyTooLong(content, "too-large-to-share");
43259
+ if (tooLarge) return refusalResult(tooLarge);
42583
43260
  const shareSalt = generateSalt();
42584
43261
  const shareKey = await deriveKey(sharePassphrase, shareSalt);
42585
43262
  const encTitle = encrypt(title, shareKey);
@@ -42588,8 +43265,7 @@ function createMcpServer(creds, opts = {}) {
42588
43265
  noteId,
42589
43266
  encryptedTitle: encTitle.ciphertext,
42590
43267
  titleIv: encTitle.iv,
42591
- encryptedContent: encContent.ciphertext,
42592
- contentIv: encContent.iv,
43268
+ ...inlineContentFields(encContent),
42593
43269
  salt: shareSalt,
42594
43270
  pbkdf2Iterations: 6e5,
42595
43271
  expiry,
@@ -42642,7 +43318,9 @@ function createMcpServer(creds, opts = {}) {
42642
43318
  const { client, key } = await context.get();
42643
43319
  const note = await client.getNote(noteId);
42644
43320
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42645
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43321
+ const content = readNoteContent(note, key).text;
43322
+ const tooLarge = bodyTooLong(content, "too-large-to-share");
43323
+ if (tooLarge) return refusalResult(tooLarge);
42646
43324
  const shareSalt = generateSalt();
42647
43325
  const shareKey = await deriveKey(sharePassphrase, shareSalt);
42648
43326
  const encTitle = encrypt(title, shareKey);
@@ -42650,8 +43328,7 @@ function createMcpServer(creds, opts = {}) {
42650
43328
  const status = await client.republishShare(shareToken, {
42651
43329
  encryptedTitle: encTitle.ciphertext,
42652
43330
  titleIv: encTitle.iv,
42653
- encryptedContent: encContent.ciphertext,
42654
- contentIv: encContent.iv,
43331
+ ...inlineContentFields(encContent),
42655
43332
  salt: shareSalt,
42656
43333
  pbkdf2Iterations: 6e5
42657
43334
  });
@@ -42887,6 +43564,11 @@ var init_server3 = __esm({
42887
43564
  init_search_fold();
42888
43565
  init_upload_path();
42889
43566
  init_note_text();
43567
+ init_note_limits();
43568
+ init_note_bodies();
43569
+ init_note_content();
43570
+ init_note_chunks();
43571
+ init_note_chunks();
42890
43572
  SQUIRREL_API_BASE_URL = process.env.SQUIRREL_API_BASE_URL;
42891
43573
  if (!SQUIRREL_API_BASE_URL) {
42892
43574
  throw new Error("SQUIRREL_API_BASE_URL environment variable is required");
@@ -42967,11 +43649,11 @@ __export(vector_cache_exports, {
42967
43649
  vectorFilePathForId: () => vectorFilePathForId,
42968
43650
  writeVectorFile: () => writeVectorFile
42969
43651
  });
42970
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
43652
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, hkdfSync as hkdfSync2, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
42971
43653
  import { chmod, mkdir as mkdir2, readFile, rename, rm, writeFile } from "node:fs/promises";
42972
43654
  import path from "node:path";
42973
43655
  function vectorFileId(dek) {
42974
- return Buffer.from(hkdfSync("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
43656
+ return Buffer.from(hkdfSync2("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
42975
43657
  }
42976
43658
  function vectorFilePath(cacheDir, dek) {
42977
43659
  return vectorFilePathForId(cacheDir, vectorFileId(dek));
@@ -42988,7 +43670,7 @@ function defaultCacheDir(platform, env, home) {
42988
43670
  return env.XDG_CACHE_HOME || path.join(home, ".cache");
42989
43671
  }
42990
43672
  function deriveFileKey(dek, salt) {
42991
- return Buffer.from(hkdfSync("sha256", dek, salt, KEY_INFO, 32));
43673
+ return Buffer.from(hkdfSync2("sha256", dek, salt, KEY_INFO, 32));
42992
43674
  }
42993
43675
  function headerBytes(model, recipe = EMBEDDING_TEXT_RECIPE) {
42994
43676
  return Buffer.from(
@@ -43041,10 +43723,10 @@ function sealVectorFile(entries, model, dek) {
43041
43723
  MAGIC.copy(prefix, 0);
43042
43724
  prefix.writeUInt8(VECTOR_FILE_FORMAT, MAGIC.length);
43043
43725
  prefix.writeUInt16BE(header.length, MAGIC.length + 1);
43044
- const salt = randomBytes2(SALT_LENGTH);
43045
- const iv = randomBytes2(IV_LENGTH2);
43726
+ const salt = randomBytes3(SALT_LENGTH);
43727
+ const iv = randomBytes3(IV_LENGTH2);
43046
43728
  const aad = Buffer.concat([prefix, header, salt, iv]);
43047
- const cipher = createCipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43729
+ const cipher = createCipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43048
43730
  cipher.setAAD(aad);
43049
43731
  const sealed = Buffer.concat([cipher.update(encodeBody(entries, model.dimensions)), cipher.final(), cipher.getAuthTag()]);
43050
43732
  return Buffer.concat([aad, sealed]);
@@ -43062,7 +43744,7 @@ function openVectorFile(file2, model, dek) {
43062
43744
  if (!file2.subarray(fixed, fixed + headerLength).equals(headerBytes(model))) return null;
43063
43745
  const salt = file2.subarray(fixed + headerLength, fixed + headerLength + SALT_LENGTH);
43064
43746
  const iv = file2.subarray(aadEnd - IV_LENGTH2, aadEnd);
43065
- const decipher = createDecipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43747
+ const decipher = createDecipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43066
43748
  decipher.setAAD(file2.subarray(0, aadEnd));
43067
43749
  decipher.setAuthTag(file2.subarray(file2.length - TAG_LENGTH));
43068
43750
  const body = Buffer.concat([decipher.update(file2.subarray(aadEnd, file2.length - TAG_LENGTH)), decipher.final()]);
@@ -43084,7 +43766,7 @@ async function writeVectorFile(filePath, entries, model, dek) {
43084
43766
  const dir = path.dirname(filePath);
43085
43767
  await mkdir2(dir, { recursive: true, mode: 448 });
43086
43768
  await chmod(dir, 448);
43087
- const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID2()}.tmp`);
43769
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID4()}.tmp`);
43088
43770
  try {
43089
43771
  await writeFile(tmp, sealVectorFile(entries, model, dek), { mode: 384, flag: "wx" });
43090
43772
  await chmod(tmp, 384);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@squirrelnotes.app/mcp",
3
- "version": "2.7.1",
3
+ "version": "2.8.0",
4
4
  "description": "MCP stdio CLI for Squirrel Notes — bridges AI agents to the encrypted note-taking API",
5
5
  "type": "module",
6
6
  "repository": {