@squirrelnotes.app/mcp 2.7.1-test.378 → 2.7.1-test.379

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 +525 -49
  2. package/package.json +1 -1
@@ -38131,6 +38131,10 @@ var init_api2 = __esm({
38131
38131
  updateNote(id, dto) {
38132
38132
  return this.request("PATCH", `/public/notes/${id}`, dto);
38133
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
+ }
38134
38138
  deleteNote(id) {
38135
38139
  return this.requestVoid("DELETE", `/public/notes/${id}`);
38136
38140
  }
@@ -41668,7 +41672,12 @@ var init_note_text = __esm({
41668
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.",
41669
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.",
41670
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.",
41671
- "search-incomplete": "The search could not read every note; nothing was matched. Try again."
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 while this was being written, so nothing was written. Read it again and retry."
41672
41681
  };
41673
41682
  refuse2 = (error62, details) => details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
41674
41683
  isRefusal = (x) => "kind" in x && x.kind === "refused";
@@ -41716,6 +41725,443 @@ var init_note_limits = __esm({
41716
41725
  }
41717
41726
  });
41718
41727
 
41728
+ // src/note-chunks.ts
41729
+ function chunkAadText(noteId, chunkId, versionId) {
41730
+ return `sqn-note-chunk-v1:${noteId}:${chunkId}:${versionId}`;
41731
+ }
41732
+ function manifestAadText(noteId, revision) {
41733
+ return `sqn-note-manifest-v1:${noteId}:${revision}`;
41734
+ }
41735
+ function isUuidV4(value) {
41736
+ return typeof value === "string" && UUID_V4.test(value);
41737
+ }
41738
+ function isCount(value, max) {
41739
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
41740
+ }
41741
+ function checkManifest(value, noteId, revision) {
41742
+ const fail2 = () => {
41743
+ throw new NoteBodyUnreadableError();
41744
+ };
41745
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail2();
41746
+ const m = value;
41747
+ if (Object.keys(m).sort().join(",") !== "chunker,chunks,noteId,revision,totalBytes,v") fail2();
41748
+ if (m.v !== 1 || m.chunker !== NOTE_CHUNKER) fail2();
41749
+ if (m.noteId !== noteId || m.revision !== revision) fail2();
41750
+ if (!isCount(m.totalBytes, NOTE_BODY_MAX_BYTES2)) fail2();
41751
+ if (!Array.isArray(m.chunks) || m.chunks.length > NOTE_MANIFEST_MAX_CHUNKS) fail2();
41752
+ const chunks = m.chunks;
41753
+ if (chunks.length === 0 && m.totalBytes !== 0) fail2();
41754
+ const ids = /* @__PURE__ */ new Set();
41755
+ let sum = 0;
41756
+ const out = [];
41757
+ for (const raw of chunks) {
41758
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) fail2();
41759
+ const c = raw;
41760
+ if (Object.keys(c).sort().join(",") !== "id,len,lines,sha256,ver") fail2();
41761
+ if (!isUuidV4(c.id) || !isUuidV4(c.ver)) fail2();
41762
+ if (!isCount(c.len, CHUNK_MAX_BYTES) || c.len === 0) fail2();
41763
+ if (!isCount(c.lines, CHUNK_MAX_BYTES)) fail2();
41764
+ if (typeof c.sha256 !== "string" || !HEX_64.test(c.sha256)) fail2();
41765
+ const id = c.id;
41766
+ if (ids.has(id)) fail2();
41767
+ ids.add(id);
41768
+ sum += c.len;
41769
+ out.push({ id, ver: c.ver, len: c.len, lines: c.lines, sha256: c.sha256 });
41770
+ }
41771
+ if (sum !== m.totalBytes) fail2();
41772
+ return { v: 1, noteId, revision, chunker: NOTE_CHUNKER, totalBytes: sum, chunks: out };
41773
+ }
41774
+ function refsOf(manifest) {
41775
+ return manifest.chunks.map((c) => `${c.id}:${c.ver}`).sort();
41776
+ }
41777
+ function countLines(bytes, start = 0, end = bytes.length) {
41778
+ let n = 0;
41779
+ for (let i = start; i < end; i++) if (bytes[i] === NEWLINE) n += 1;
41780
+ return n;
41781
+ }
41782
+ function paddedLength(len) {
41783
+ return Math.max(1, Math.ceil(len / CHUNK_PAD_BYTES)) * CHUNK_PAD_BYTES;
41784
+ }
41785
+ function padChunk(bytes) {
41786
+ const out = new Uint8Array(paddedLength(bytes.length));
41787
+ out.set(bytes);
41788
+ return out;
41789
+ }
41790
+ function unpadChunk(padded, len) {
41791
+ if (padded.length !== paddedLength(len)) throw new NoteBodyUnreadableError();
41792
+ for (let i = len; i < padded.length; i++) {
41793
+ if (padded[i] !== 0) throw new NoteBodyUnreadableError();
41794
+ }
41795
+ return padded.subarray(0, len);
41796
+ }
41797
+ function gearTableFrom(bytes) {
41798
+ if (bytes.length !== GEAR_TABLE_BYTES) throw new Error("Gear table must be 1024 bytes");
41799
+ const table = new Uint32Array(256);
41800
+ for (let i = 0; i < 256; i++) {
41801
+ table[i] = (bytes[4 * i] << 24 | bytes[4 * i + 1] << 16 | bytes[4 * i + 2] << 8 | bytes[4 * i + 3]) >>> 0;
41802
+ }
41803
+ return table;
41804
+ }
41805
+ function nextCut(bytes, start, to, gear) {
41806
+ if (to - start <= CHUNK_MIN_BYTES) return to;
41807
+ const limit = Math.min(to, start + CHUNK_MAX_BYTES);
41808
+ let hash2 = 0;
41809
+ let armed = false;
41810
+ let lastLineStart = -1;
41811
+ for (let i = start; i < limit; i++) {
41812
+ const b = bytes[i];
41813
+ hash2 = (hash2 << 1) + gear[b] >>> 0;
41814
+ if (b === NEWLINE && i + 1 - start >= CHUNK_MIN_BYTES) {
41815
+ if (armed) return i + 1;
41816
+ lastLineStart = i + 1;
41817
+ }
41818
+ if (!armed && i + 1 - start >= CHUNK_MIN_BYTES && (hash2 & GEAR_ARM_MASK) === 0) armed = true;
41819
+ }
41820
+ if (limit === to) return to;
41821
+ if (lastLineStart > 0) return lastLineStart;
41822
+ let cut = limit;
41823
+ while (cut > start + 1 && (bytes[cut] & 192) === 128) cut -= 1;
41824
+ return cut;
41825
+ }
41826
+ function cdcSplit(bytes, from, to, gear) {
41827
+ const ends = [];
41828
+ let start = from;
41829
+ while (start < to) {
41830
+ const end = nextCut(bytes, start, to, gear);
41831
+ ends.push(end);
41832
+ start = end;
41833
+ }
41834
+ return ends;
41835
+ }
41836
+ function commonPrefix(a, b) {
41837
+ const n = Math.min(a.length, b.length);
41838
+ let i = 0;
41839
+ while (i < n && a[i] === b[i]) i += 1;
41840
+ return i;
41841
+ }
41842
+ function commonSuffix(a, b, max) {
41843
+ let i = 0;
41844
+ while (i < max && a[a.length - 1 - i] === b[b.length - 1 - i]) i += 1;
41845
+ return i;
41846
+ }
41847
+ function sameBytes(a, aStart, b, bStart, len) {
41848
+ for (let i = 0; i < len; i++) if (a[aStart + i] !== b[bStart + i]) return false;
41849
+ return true;
41850
+ }
41851
+ function planChunks(bytes, gear, previous) {
41852
+ if (bytes.length === 0) return [];
41853
+ const old = previous?.manifest.chunks ?? [];
41854
+ if (!previous || old.length === 0) {
41855
+ let start = 0;
41856
+ return cdcSplit(bytes, 0, bytes.length, gear).map((end) => {
41857
+ const chunk = { start, end, keepId: null, reuse: null };
41858
+ start = end;
41859
+ return chunk;
41860
+ });
41861
+ }
41862
+ const oldBytes = previous.bytes;
41863
+ const prefix = commonPrefix(oldBytes, bytes);
41864
+ const suffix = commonSuffix(oldBytes, bytes, Math.min(oldBytes.length, bytes.length) - prefix);
41865
+ const delta = bytes.length - oldBytes.length;
41866
+ const map2 = (b) => {
41867
+ if (b <= prefix) return b;
41868
+ if (b >= oldBytes.length - suffix) return b + delta;
41869
+ return -1;
41870
+ };
41871
+ const oldStarts = [];
41872
+ let offset = 0;
41873
+ for (const c of old) {
41874
+ oldStarts.push(offset);
41875
+ offset += c.len;
41876
+ }
41877
+ const kept = [{ pos: 0, index: 0 }];
41878
+ for (let i = 1; i < old.length; i++) {
41879
+ const pos = map2(oldStarts[i]);
41880
+ if (pos <= kept[kept.length - 1].pos || pos >= bytes.length) continue;
41881
+ if (bytes[pos - 1] !== NEWLINE) continue;
41882
+ kept.push({ pos, index: i });
41883
+ }
41884
+ const spans = [];
41885
+ for (let k = 0; k < kept.length; k++) {
41886
+ const here = kept[k];
41887
+ const next = k + 1 < kept.length ? kept[k + 1].pos : bytes.length;
41888
+ if (spans.length > 0 && next - here.pos < CHUNK_MIN_BYTES && k + 1 < kept.length) continue;
41889
+ spans.push(here);
41890
+ }
41891
+ if (spans.length > 1 && spans[1].pos - spans[0].pos < CHUNK_MIN_BYTES) spans.splice(1, 1);
41892
+ const planned = [];
41893
+ for (let s = 0; s < spans.length; s++) {
41894
+ const span2 = spans[s];
41895
+ const from = span2.pos;
41896
+ const to = s + 1 < spans.length ? spans[s + 1].pos : bytes.length;
41897
+ const ends = to - from > CHUNK_MAX_BYTES ? cdcSplit(bytes, from, to, gear) : [to];
41898
+ let start = from;
41899
+ for (const [n, end] of ends.entries()) {
41900
+ const prev = old[span2.index];
41901
+ const keepId = n === 0 ? prev.id : null;
41902
+ let reuse = null;
41903
+ if (n === 0) {
41904
+ const prevStart = oldStarts[span2.index];
41905
+ if (prev.len === end - start && sameBytes(oldBytes, prevStart, bytes, start, prev.len)) reuse = prev;
41906
+ }
41907
+ planned.push({ start, end, keepId, reuse });
41908
+ start = end;
41909
+ }
41910
+ }
41911
+ return planned;
41912
+ }
41913
+ 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, NOTE_CHUNKER_INFO, GEAR_TABLE_BYTES, GEAR_ARM_MASK, NEWLINE, NoteBodyUnreadableError, UUID_V4, HEX_64;
41914
+ var init_note_chunks = __esm({
41915
+ "src/note-chunks.ts"() {
41916
+ "use strict";
41917
+ NOTE_CHUNKER = "cdc-v1";
41918
+ NOTE_BODY_FORMAT_CHUNKS = "chunks-v1";
41919
+ CHUNK_MIN_BYTES = 16 * 1024;
41920
+ CHUNK_MAX_BYTES = 128 * 1024;
41921
+ CHUNK_PAD_BYTES = 1024;
41922
+ NOTE_CHUNKING_THRESHOLD_BYTES = 256 * 1024;
41923
+ NOTE_BODY_MAX_BYTES2 = 3 * 1024 * 1024;
41924
+ NOTE_MANIFEST_MAX_CHUNKS = 1024;
41925
+ NOTE_CHUNKER_INFO = "sqn-note-chunker-v1";
41926
+ GEAR_TABLE_BYTES = 1024;
41927
+ GEAR_ARM_MASK = 4294705152;
41928
+ NEWLINE = 10;
41929
+ NoteBodyUnreadableError = class extends Error {
41930
+ constructor() {
41931
+ super("This note could not be read in full");
41932
+ this.name = "NoteBodyUnreadableError";
41933
+ }
41934
+ };
41935
+ UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
41936
+ HEX_64 = /^[0-9a-f]{64}$/;
41937
+ }
41938
+ });
41939
+
41940
+ // src/note-body.ts
41941
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, createHash as createHash2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
41942
+ function gcmEncrypt(key, iv, plaintext, aad) {
41943
+ const cipher = createCipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
41944
+ cipher.setAAD(Buffer.from(aad, "utf8"));
41945
+ const body = Buffer.concat([cipher.update(plaintext), cipher.final()]);
41946
+ return Buffer.concat([body, cipher.getAuthTag()]).toString("base64");
41947
+ }
41948
+ function gcmDecrypt(key, ivBase64, ciphertextBase64, aad) {
41949
+ const iv = Buffer.from(ivBase64, "base64");
41950
+ const combined = Buffer.from(ciphertextBase64, "base64");
41951
+ if (iv.length !== IV_BYTES || combined.length < TAG_BYTES) throw new NoteBodyUnreadableError();
41952
+ try {
41953
+ const decipher = createDecipheriv2("aes-256-gcm", key, iv, { authTagLength: TAG_BYTES });
41954
+ decipher.setAAD(Buffer.from(aad, "utf8"));
41955
+ decipher.setAuthTag(combined.subarray(combined.length - TAG_BYTES));
41956
+ return Buffer.concat([decipher.update(combined.subarray(0, combined.length - TAG_BYTES)), decipher.final()]);
41957
+ } catch {
41958
+ throw new NoteBodyUnreadableError();
41959
+ }
41960
+ }
41961
+ function chunkDigest(ivBase64, ciphertextBase64) {
41962
+ return createHash2("sha256").update(Buffer.from(ivBase64, "base64")).update(Buffer.from(ciphertextBase64, "base64")).digest("hex");
41963
+ }
41964
+ function noteChunkerGear(dek) {
41965
+ const ikm = Buffer.from(gcmEncrypt(dek, Buffer.alloc(IV_BYTES), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), ""), "base64");
41966
+ const okm = hkdfSync("sha256", ikm, Buffer.alloc(0), Buffer.from(NOTE_CHUNKER_INFO, "utf8"), GEAR_TABLE_BYTES);
41967
+ return gearTableFrom(new Uint8Array(okm));
41968
+ }
41969
+ function encryptNoteChunk(dek, noteId, chunkId, bytes, fixed = {}) {
41970
+ const versionId = fixed.versionId ?? randomUUID2();
41971
+ const iv = fixed.iv ?? randomBytes2(IV_BYTES);
41972
+ const ciphertext = gcmEncrypt(dek, iv, padChunk(bytes), chunkAadText(noteId, chunkId, versionId));
41973
+ const ivBase64 = iv.toString("base64");
41974
+ return {
41975
+ chunk: { chunkId, versionId, ciphertext, iv: ivBase64 },
41976
+ entry: {
41977
+ id: chunkId,
41978
+ ver: versionId,
41979
+ len: bytes.length,
41980
+ lines: countLines(bytes),
41981
+ sha256: chunkDigest(ivBase64, ciphertext)
41982
+ }
41983
+ };
41984
+ }
41985
+ function decryptNoteChunk(dek, noteId, chunk, expected) {
41986
+ if (chunk.chunkId !== expected.id || chunk.versionId !== expected.ver) throw new NoteBodyUnreadableError();
41987
+ if (chunkDigest(chunk.iv, chunk.ciphertext) !== expected.sha256) throw new NoteBodyUnreadableError();
41988
+ const padded = gcmDecrypt(dek, chunk.iv, chunk.ciphertext, chunkAadText(noteId, chunk.chunkId, chunk.versionId));
41989
+ return unpadChunk(new Uint8Array(padded), expected.len);
41990
+ }
41991
+ function encryptNoteManifest(dek, manifest, fixed = {}) {
41992
+ checkManifest(manifest, manifest.noteId, manifest.revision);
41993
+ const iv = fixed.iv ?? randomBytes2(IV_BYTES);
41994
+ const plaintext = Buffer.from(JSON.stringify(manifest), "utf8");
41995
+ return {
41996
+ ciphertext: gcmEncrypt(dek, iv, plaintext, manifestAadText(manifest.noteId, manifest.revision)),
41997
+ iv: iv.toString("base64")
41998
+ };
41999
+ }
42000
+ function decryptNoteManifest(dek, noteId, revision, ciphertext, iv) {
42001
+ const plaintext = gcmDecrypt(dek, iv, ciphertext, manifestAadText(noteId, revision));
42002
+ let parsed;
42003
+ try {
42004
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(plaintext));
42005
+ } catch {
42006
+ throw new NoteBodyUnreadableError();
42007
+ }
42008
+ return checkManifest(parsed, noteId, revision);
42009
+ }
42010
+ function readChunkedBody(dek, noteId, body) {
42011
+ const manifest = decryptNoteManifest(dek, noteId, body.revision, body.encryptedManifest, body.manifestIv);
42012
+ const served = new Map(body.chunks.map((c) => [`${c.chunkId}:${c.versionId}`, c]));
42013
+ const bytes = new Uint8Array(manifest.totalBytes);
42014
+ const parts = [];
42015
+ let offset = 0;
42016
+ for (const entry2 of manifest.chunks) {
42017
+ const chunk = served.get(`${entry2.id}:${entry2.ver}`);
42018
+ if (!chunk) throw new NoteBodyUnreadableError();
42019
+ const part = decryptNoteChunk(dek, noteId, chunk, entry2);
42020
+ try {
42021
+ parts.push(new TextDecoder("utf-8", { fatal: true }).decode(part));
42022
+ } catch {
42023
+ throw new NoteBodyUnreadableError();
42024
+ }
42025
+ bytes.set(part, offset);
42026
+ offset += entry2.len;
42027
+ }
42028
+ return { text: parts.join(""), revision: body.revision, manifest, bytes };
42029
+ }
42030
+ function buildChunkedCommit(dek, noteId, text, base) {
42031
+ const bytes = new TextEncoder().encode(text);
42032
+ if (bytes.length > NOTE_BODY_MAX_BYTES2) throw new NoteBodyTooLargeError(bytes.length);
42033
+ const plan = planChunks(bytes, noteChunkerGear(dek), base ? { bytes: base.bytes, manifest: base.manifest } : void 0);
42034
+ const entries = [];
42035
+ const fresh = [];
42036
+ for (const p of plan) {
42037
+ if (p.reuse) {
42038
+ entries.push(p.reuse);
42039
+ continue;
42040
+ }
42041
+ const { chunk, entry: entry2 } = encryptNoteChunk(dek, noteId, p.keepId ?? randomUUID2(), bytes.subarray(p.start, p.end));
42042
+ entries.push(entry2);
42043
+ fresh.push(chunk);
42044
+ }
42045
+ const revision = (base?.revision ?? 0) + 1;
42046
+ const manifest = {
42047
+ v: 1,
42048
+ noteId,
42049
+ revision,
42050
+ chunker: NOTE_CHUNKER,
42051
+ totalBytes: bytes.length,
42052
+ chunks: entries
42053
+ };
42054
+ const { ciphertext, iv } = encryptNoteManifest(dek, manifest);
42055
+ fresh.sort((a, b) => a.chunkId === b.chunkId ? cmp(a.versionId, b.versionId) : cmp(a.chunkId, b.chunkId));
42056
+ return {
42057
+ commit: {
42058
+ baseRevision: base?.revision ?? 0,
42059
+ encryptedManifest: ciphertext,
42060
+ manifestIv: iv,
42061
+ refs: refsOf(manifest),
42062
+ chunks: fresh
42063
+ },
42064
+ manifest
42065
+ };
42066
+ }
42067
+ function cmp(a, b) {
42068
+ return a < b ? -1 : a > b ? 1 : 0;
42069
+ }
42070
+ var IV_BYTES, TAG_BYTES, NoteBodyTooLargeError;
42071
+ var init_note_body = __esm({
42072
+ "src/note-body.ts"() {
42073
+ "use strict";
42074
+ init_note_chunks();
42075
+ IV_BYTES = 12;
42076
+ TAG_BYTES = 16;
42077
+ NoteBodyTooLargeError = class extends Error {
42078
+ constructor(bytes) {
42079
+ super("Note body over the limit");
42080
+ this.bytes = bytes;
42081
+ this.name = "NoteBodyTooLargeError";
42082
+ }
42083
+ bytes;
42084
+ };
42085
+ }
42086
+ });
42087
+
42088
+ // src/note-content.ts
42089
+ function inlineContentFields(sealed) {
42090
+ return { encryptedContent: sealed.ciphertext, contentIv: sealed.iv };
42091
+ }
42092
+ function listedBodyOf(n) {
42093
+ return n.encryptedContent !== void 0 ? { encryptedContent: n.encryptedContent, contentIv: n.contentIv } : null;
42094
+ }
42095
+ function bodyOfEntry(b) {
42096
+ return b.bodyFormat === NOTE_BODY_FORMAT_CHUNKS ? { encryptedContent: "", contentIv: null, bodyFormat: NOTE_BODY_FORMAT_CHUNKS, body: b.body } : { encryptedContent: b.encryptedContent, contentIv: b.contentIv };
42097
+ }
42098
+ function bodyOfNote(n) {
42099
+ return {
42100
+ encryptedContent: n.encryptedContent,
42101
+ contentIv: n.contentIv,
42102
+ ...n.bodyFormat ? { bodyFormat: n.bodyFormat } : {},
42103
+ ...n.body ? { body: n.body } : {}
42104
+ };
42105
+ }
42106
+ function readNoteContent(note, key) {
42107
+ if (note.bodyFormat === NOTE_BODY_FORMAT_CHUNKS) {
42108
+ if (!note.body) throw new NoteBodyUnreadableError();
42109
+ const chunked = readChunkedBody(key, note.id, note.body);
42110
+ if (note.encryptedContent) throw new NoteBodyUnreadableError();
42111
+ return { text: chunked.text, chunked };
42112
+ }
42113
+ const text = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42114
+ return { text, chunked: null };
42115
+ }
42116
+ function refused(error62, details) {
42117
+ return details === void 0 ? { kind: "refused", error: error62 } : { kind: "refused", error: error62, details };
42118
+ }
42119
+ function lostRace(err) {
42120
+ return err instanceof SquirrelApiError && err.status === 409 && /NOTE_BODY_(CONFLICT|CHUNKED)/.test(err.responseBody);
42121
+ }
42122
+ async function writeNoteContent(client, key, noteId, text, current, options = {}) {
42123
+ const bytes = utf8Bytes(text);
42124
+ const convert = (options.conversionsOn ?? MCP_CONVERTS_TO_CHUNKS) && bytes > NOTE_CHUNKING_THRESHOLD_BYTES;
42125
+ if (current.chunked || convert) {
42126
+ if (bytes > NOTE_BODY_MAX_BYTES2) return refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES2 });
42127
+ const { commit } = buildChunkedCommit(key, noteId, text, current.chunked ?? void 0);
42128
+ try {
42129
+ const saved = await client.putNoteBody(noteId, commit);
42130
+ return { kind: "written", updatedAt: saved.updatedAt };
42131
+ } catch (err) {
42132
+ if (lostRace(err)) return refused("write-conflict");
42133
+ throw err;
42134
+ }
42135
+ }
42136
+ if (bytes > NOTE_BODY_MAX_BYTES) return refused("too-long", { bytes, limit: NOTE_BODY_MAX_BYTES });
42137
+ const enc = encrypt(text, key);
42138
+ try {
42139
+ const saved = await client.updateNote(noteId, inlineContentFields(enc));
42140
+ return { kind: "written", updatedAt: saved.updatedAt };
42141
+ } catch (err) {
42142
+ if (lostRace(err)) return refused("write-conflict");
42143
+ throw err;
42144
+ }
42145
+ }
42146
+ function newContentTooLong(text, options = {}) {
42147
+ const bytes = utf8Bytes(text);
42148
+ const chunked = (options.conversionsOn ?? MCP_CONVERTS_TO_CHUNKS) && bytes > NOTE_CHUNKING_THRESHOLD_BYTES;
42149
+ const limit = chunked ? NOTE_BODY_MAX_BYTES2 : NOTE_BODY_MAX_BYTES;
42150
+ return bytes > limit ? refused("too-long", { bytes, limit }) : null;
42151
+ }
42152
+ var MCP_CONVERTS_TO_CHUNKS;
42153
+ var init_note_content = __esm({
42154
+ "src/note-content.ts"() {
42155
+ "use strict";
42156
+ init_api_error();
42157
+ init_crypto();
42158
+ init_note_body();
42159
+ init_note_chunks();
42160
+ init_note_limits();
42161
+ MCP_CONVERTS_TO_CHUNKS = false;
42162
+ }
42163
+ });
42164
+
41719
42165
  // src/note-bodies.ts
41720
42166
  function isTransient(err) {
41721
42167
  return err instanceof SquirrelNetworkError || err instanceof SquirrelApiError && (err.status === 429 || err.status >= 500);
@@ -41724,9 +42170,8 @@ async function withBodies(client, listed, options = {}) {
41724
42170
  const delays = options.retryDelaysMs ?? NOTE_BODIES_RETRY_DELAYS_MS;
41725
42171
  const bodies = /* @__PURE__ */ new Map();
41726
42172
  for (const n of listed) {
41727
- if (n.encryptedContent !== void 0) {
41728
- bodies.set(n.id, { encryptedContent: n.encryptedContent, contentIv: n.contentIv });
41729
- }
42173
+ const body = listedBodyOf(n);
42174
+ if (body) bodies.set(n.id, body);
41730
42175
  }
41731
42176
  const missing = /* @__PURE__ */ new Set();
41732
42177
  let owed = listed.map((n) => n.id).filter((id) => !bodies.has(id));
@@ -41754,7 +42199,7 @@ async function withBodies(client, listed, options = {}) {
41754
42199
  throw err;
41755
42200
  }
41756
42201
  for (const b of page.bodies) {
41757
- bodies.set(b.id, { encryptedContent: b.encryptedContent, contentIv: b.contentIv });
42202
+ bodies.set(b.id, bodyOfEntry(b));
41758
42203
  }
41759
42204
  for (const id of page.missing) missing.add(id);
41760
42205
  if (page.bodies.length === 0 && page.missing.length === 0) {
@@ -41771,7 +42216,7 @@ async function oneAtATime(client, ids, bodies, missing, attempt) {
41771
42216
  for (const id of ids) {
41772
42217
  try {
41773
42218
  const n = await attempt(() => client.getNote(id));
41774
- bodies.set(id, { encryptedContent: n.encryptedContent, contentIv: n.contentIv });
42219
+ bodies.set(id, bodyOfNote(n));
41775
42220
  } catch (err) {
41776
42221
  if (err instanceof SquirrelApiError && err.status === 404) missing.add(id);
41777
42222
  else throw err;
@@ -41783,6 +42228,7 @@ var init_note_bodies = __esm({
41783
42228
  "src/note-bodies.ts"() {
41784
42229
  "use strict";
41785
42230
  init_api_error();
42231
+ init_note_content();
41786
42232
  NOTE_BODIES_BATCH = 500;
41787
42233
  NOTE_BODIES_RETRY_DELAYS_MS = [250, 1e3];
41788
42234
  NoteBodiesIncompleteError = class extends Error {
@@ -41807,6 +42253,7 @@ __export(server_exports, {
41807
42253
  inferMimeType: () => inferMimeType
41808
42254
  });
41809
42255
  import { basename as basename2, extname, resolve as resolve2 } from "node:path";
42256
+ import { randomUUID as randomUUID3 } from "node:crypto";
41810
42257
  async function buildContext(creds, onUnauthorized) {
41811
42258
  const client = new SquirrelApiClient(SQUIRREL_API_BASE_URL, creds.apiKey, { onUnauthorized });
41812
42259
  const { salt, keyCheck, wrappedDek, dekIv } = await client.getEncryption();
@@ -41841,7 +42288,7 @@ function decryptNoteTitle(note, key) {
41841
42288
  }
41842
42289
  function decryptNote(note, key) {
41843
42290
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
41844
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42291
+ const content = readNoteContent(note, key).text;
41845
42292
  const tagIds = note.tags?.map((t) => t.id) ?? [];
41846
42293
  return { ...note, title, content, tagIds };
41847
42294
  }
@@ -41873,6 +42320,21 @@ function titleTooLong(title) {
41873
42320
  const bytes = utf8Bytes(title);
41874
42321
  return bytes > NOTE_TITLE_MAX_BYTES ? { kind: "refused", error: "title-too-long", details: { bytes, limit: NOTE_TITLE_MAX_BYTES } } : null;
41875
42322
  }
42323
+ function refuseUnreadableBodies(server) {
42324
+ const register = server.tool.bind(server);
42325
+ server.tool = (...args) => {
42326
+ const handler = args[args.length - 1];
42327
+ args[args.length - 1] = async (...a) => {
42328
+ try {
42329
+ return await handler(...a);
42330
+ } catch (err) {
42331
+ if (err instanceof NoteBodyUnreadableError) return refusalResult({ kind: "refused", error: "unreadable" });
42332
+ throw err;
42333
+ }
42334
+ };
42335
+ return register(...args);
42336
+ };
42337
+ }
41876
42338
  function jsonResult(value) {
41877
42339
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
41878
42340
  }
@@ -41884,6 +42346,7 @@ function createMcpServer(creds, opts = {}) {
41884
42346
  const context = createContextProvider(
41885
42347
  (onUnauthorized) => buildContext(creds, onUnauthorized)
41886
42348
  );
42349
+ refuseUnreadableBodies(server);
41887
42350
  server.prompt(
41888
42351
  "markdown_capabilities",
41889
42352
  "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.",
@@ -41981,15 +42444,18 @@ function createMcpServer(creds, opts = {}) {
41981
42444
  collectionId: external_exports.string().optional().describe("Collection ID to place the note in. Omit to create in scratchpad.")
41982
42445
  },
41983
42446
  async ({ title, content, collectionId }) => {
41984
- const tooLong = titleTooLong(title) ?? (content !== void 0 ? bodyTooLong(content) : null);
42447
+ const tooLong = titleTooLong(title) ?? (content !== void 0 ? newContentTooLong(content) : null);
41985
42448
  if (tooLong) return refusalResult(tooLong);
41986
42449
  const { client, key } = await context.get();
41987
42450
  const encTitle = encrypt(title, key);
41988
- const encContent = content !== void 0 ? encrypt(content, key) : null;
42451
+ const chunked = content !== void 0 && MCP_CONVERTS_TO_CHUNKS && utf8Bytes(content) > NOTE_CHUNKING_THRESHOLD_BYTES;
42452
+ const newId = randomUUID3();
42453
+ const encContent = content !== void 0 && !chunked ? encrypt(content, key) : null;
41989
42454
  const note = await client.createNote({
42455
+ ...chunked ? { id: newId, body: buildChunkedCommit(key, newId, content).commit } : {},
41990
42456
  encryptedTitle: encTitle.ciphertext,
41991
42457
  titleIv: encTitle.iv,
41992
- ...encContent ? { encryptedContent: encContent.ciphertext, contentIv: encContent.iv } : {},
42458
+ ...encContent ? inlineContentFields(encContent) : {},
41993
42459
  collectionId: collectionId ?? null
41994
42460
  });
41995
42461
  return {
@@ -42011,8 +42477,8 @@ function createMcpServer(creds, opts = {}) {
42011
42477
  content: external_exports.string().optional().describe("New content in Markdown (replaces existing content)")
42012
42478
  },
42013
42479
  async ({ id, title, content }) => {
42014
- const tooLong = (title !== void 0 ? titleTooLong(title) : null) ?? (content !== void 0 ? bodyTooLong(content) : null);
42015
- if (tooLong) return refusalResult(tooLong);
42480
+ const titleRefusal = title !== void 0 ? titleTooLong(title) : null;
42481
+ if (titleRefusal) return refusalResult(titleRefusal);
42016
42482
  const { client, key } = await context.get();
42017
42483
  const dto = {};
42018
42484
  if (title !== void 0) {
@@ -42020,15 +42486,29 @@ function createMcpServer(creds, opts = {}) {
42020
42486
  dto.encryptedTitle = enc.ciphertext;
42021
42487
  dto.titleIv = enc.iv;
42022
42488
  }
42023
- if (content !== void 0) {
42489
+ const converts = content !== void 0 && MCP_CONVERTS_TO_CHUNKS && utf8Bytes(content) > NOTE_CHUNKING_THRESHOLD_BYTES;
42490
+ if (content !== void 0 && !bodyTooLong(content) && !converts) {
42024
42491
  const enc = encrypt(content, key);
42025
- dto.encryptedContent = enc.ciphertext;
42026
- dto.contentIv = enc.iv;
42492
+ try {
42493
+ const note = await client.updateNote(id, { ...dto, ...inlineContentFields(enc) });
42494
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42495
+ } catch (err) {
42496
+ if (!(err instanceof SquirrelApiError && err.status === 409 && err.responseBody.includes("NOTE_BODY_CHUNKED"))) throw err;
42497
+ }
42027
42498
  }
42028
- const note = await client.updateNote(id, dto);
42029
- return {
42030
- content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }]
42031
- };
42499
+ if (content === void 0) {
42500
+ const note = await client.updateNote(id, dto);
42501
+ return { content: [{ type: "text", text: JSON.stringify({ id: note.id, updated: true }, null, 2) }] };
42502
+ }
42503
+ const current = readNoteContent(await client.getNote(id), key);
42504
+ if (!current.chunked) {
42505
+ const tooLong = bodyTooLong(content) ?? newContentTooLong(content);
42506
+ if (tooLong) return refusalResult(tooLong);
42507
+ }
42508
+ if (title !== void 0) await client.updateNote(id, dto);
42509
+ const written = await writeNoteContent(client, key, id, content, current);
42510
+ if (written.kind === "refused") return refusalResult(written);
42511
+ return { content: [{ type: "text", text: JSON.stringify({ id, updated: true }, null, 2) }] };
42032
42512
  }
42033
42513
  );
42034
42514
  const staleCheck = (updatedAt, expected) => expected !== void 0 && expected !== updatedAt ? { kind: "refused", error: "stale", details: { updatedAt } } : null;
@@ -42049,16 +42529,12 @@ function createMcpServer(creds, opts = {}) {
42049
42529
  const note = await client.getNote(id);
42050
42530
  const stale = staleCheck(note.updatedAt, expectedUpdatedAt);
42051
42531
  if (stale) return refusalResult(stale);
42052
- const existingContent = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42532
+ const current = readNoteContent(note, key);
42533
+ const existingContent = current.text;
42053
42534
  const newContent = existingContent ? `${existingContent}${separator2}${content}` : content;
42054
- const tooLong = bodyTooLong(newContent);
42055
- if (tooLong) return refusalResult(tooLong);
42056
- const encContent = encrypt(newContent, key);
42057
- const saved = await client.updateNote(id, {
42058
- encryptedContent: encContent.ciphertext,
42059
- contentIv: encContent.iv
42060
- });
42061
- const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: saved.updatedAt };
42535
+ const written = await writeNoteContent(client, key, id, newContent, current);
42536
+ if (written.kind === "refused") return refusalResult(written);
42537
+ const answer = expectedUpdatedAt === void 0 ? { id, appended: true } : { id, appended: true, updatedAt: written.updatedAt };
42062
42538
  return {
42063
42539
  content: [{ type: "text", text: JSON.stringify(answer, null, 2) }]
42064
42540
  };
@@ -42067,15 +42543,12 @@ function createMcpServer(creds, opts = {}) {
42067
42543
  const loadNote = async (id) => {
42068
42544
  const { client, key } = await context.get();
42069
42545
  const note = await client.getNote(id);
42070
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
42071
- return { client, key, note, nt: noteText(content) };
42546
+ const body = readNoteContent(note, key);
42547
+ return { client, key, note, body, nt: noteText(body.text) };
42072
42548
  };
42073
42549
  const writeContent = async (ctx, id, raw) => {
42074
- const tooLong = bodyTooLong(raw);
42075
- if (tooLong) return tooLong;
42076
- const enc = encrypt(raw, ctx.key);
42077
- const saved = await ctx.client.updateNote(id, { encryptedContent: enc.ciphertext, contentIv: enc.iv });
42078
- return saved.updatedAt;
42550
+ const written = await writeNoteContent(ctx.client, ctx.key, id, raw, ctx.body);
42551
+ return written.kind === "written" ? written.updatedAt : written;
42079
42552
  };
42080
42553
  const headingSchema = external_exports.string().describe(`A heading's text exactly as get_note_outline lists it (at most ${HEADING_TEXT_MAX} characters)`);
42081
42554
  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.");
@@ -42716,7 +43189,7 @@ function createMcpServer(creds, opts = {}) {
42716
43189
  const { client, key } = await context.get();
42717
43190
  const note = await client.getNote(noteId);
42718
43191
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42719
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43192
+ const content = readNoteContent(note, key).text;
42720
43193
  const tooLarge = bodyTooLong(content, "too-large-to-share");
42721
43194
  if (tooLarge) return refusalResult(tooLarge);
42722
43195
  const shareSalt = generateSalt();
@@ -42727,8 +43200,7 @@ function createMcpServer(creds, opts = {}) {
42727
43200
  noteId,
42728
43201
  encryptedTitle: encTitle.ciphertext,
42729
43202
  titleIv: encTitle.iv,
42730
- encryptedContent: encContent.ciphertext,
42731
- contentIv: encContent.iv,
43203
+ ...inlineContentFields(encContent),
42732
43204
  salt: shareSalt,
42733
43205
  pbkdf2Iterations: 6e5,
42734
43206
  expiry,
@@ -42781,7 +43253,7 @@ function createMcpServer(creds, opts = {}) {
42781
43253
  const { client, key } = await context.get();
42782
43254
  const note = await client.getNote(noteId);
42783
43255
  const title = decrypt(note.encryptedTitle, note.titleIv, key);
42784
- const content = note.encryptedContent && note.contentIv ? decrypt(note.encryptedContent, note.contentIv, key) : "";
43256
+ const content = readNoteContent(note, key).text;
42785
43257
  const tooLarge = bodyTooLong(content, "too-large-to-share");
42786
43258
  if (tooLarge) return refusalResult(tooLarge);
42787
43259
  const shareSalt = generateSalt();
@@ -42791,8 +43263,7 @@ function createMcpServer(creds, opts = {}) {
42791
43263
  const status = await client.republishShare(shareToken, {
42792
43264
  encryptedTitle: encTitle.ciphertext,
42793
43265
  titleIv: encTitle.iv,
42794
- encryptedContent: encContent.ciphertext,
42795
- contentIv: encContent.iv,
43266
+ ...inlineContentFields(encContent),
42796
43267
  salt: shareSalt,
42797
43268
  pbkdf2Iterations: 6e5
42798
43269
  });
@@ -43030,6 +43501,11 @@ var init_server3 = __esm({
43030
43501
  init_note_text();
43031
43502
  init_note_limits();
43032
43503
  init_note_bodies();
43504
+ init_note_content();
43505
+ init_note_chunks();
43506
+ init_note_body();
43507
+ init_note_content();
43508
+ init_note_chunks();
43033
43509
  SQUIRREL_API_BASE_URL = process.env.SQUIRREL_API_BASE_URL;
43034
43510
  if (!SQUIRREL_API_BASE_URL) {
43035
43511
  throw new Error("SQUIRREL_API_BASE_URL environment variable is required");
@@ -43110,11 +43586,11 @@ __export(vector_cache_exports, {
43110
43586
  vectorFilePathForId: () => vectorFilePathForId,
43111
43587
  writeVectorFile: () => writeVectorFile
43112
43588
  });
43113
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, hkdfSync, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "node:crypto";
43589
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, hkdfSync as hkdfSync2, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
43114
43590
  import { chmod, mkdir as mkdir2, readFile, rename, rm, writeFile } from "node:fs/promises";
43115
43591
  import path from "node:path";
43116
43592
  function vectorFileId(dek) {
43117
- return Buffer.from(hkdfSync("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
43593
+ return Buffer.from(hkdfSync2("sha256", dek, Buffer.alloc(0), FILE_ID_INFO, 8)).toString("hex");
43118
43594
  }
43119
43595
  function vectorFilePath(cacheDir, dek) {
43120
43596
  return vectorFilePathForId(cacheDir, vectorFileId(dek));
@@ -43131,7 +43607,7 @@ function defaultCacheDir(platform, env, home) {
43131
43607
  return env.XDG_CACHE_HOME || path.join(home, ".cache");
43132
43608
  }
43133
43609
  function deriveFileKey(dek, salt) {
43134
- return Buffer.from(hkdfSync("sha256", dek, salt, KEY_INFO, 32));
43610
+ return Buffer.from(hkdfSync2("sha256", dek, salt, KEY_INFO, 32));
43135
43611
  }
43136
43612
  function headerBytes(model, recipe = EMBEDDING_TEXT_RECIPE) {
43137
43613
  return Buffer.from(
@@ -43184,10 +43660,10 @@ function sealVectorFile(entries, model, dek) {
43184
43660
  MAGIC.copy(prefix, 0);
43185
43661
  prefix.writeUInt8(VECTOR_FILE_FORMAT, MAGIC.length);
43186
43662
  prefix.writeUInt16BE(header.length, MAGIC.length + 1);
43187
- const salt = randomBytes2(SALT_LENGTH);
43188
- const iv = randomBytes2(IV_LENGTH2);
43663
+ const salt = randomBytes3(SALT_LENGTH);
43664
+ const iv = randomBytes3(IV_LENGTH2);
43189
43665
  const aad = Buffer.concat([prefix, header, salt, iv]);
43190
- const cipher = createCipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43666
+ const cipher = createCipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43191
43667
  cipher.setAAD(aad);
43192
43668
  const sealed = Buffer.concat([cipher.update(encodeBody(entries, model.dimensions)), cipher.final(), cipher.getAuthTag()]);
43193
43669
  return Buffer.concat([aad, sealed]);
@@ -43205,7 +43681,7 @@ function openVectorFile(file2, model, dek) {
43205
43681
  if (!file2.subarray(fixed, fixed + headerLength).equals(headerBytes(model))) return null;
43206
43682
  const salt = file2.subarray(fixed + headerLength, fixed + headerLength + SALT_LENGTH);
43207
43683
  const iv = file2.subarray(aadEnd - IV_LENGTH2, aadEnd);
43208
- const decipher = createDecipheriv2("aes-256-gcm", deriveFileKey(dek, salt), iv);
43684
+ const decipher = createDecipheriv3("aes-256-gcm", deriveFileKey(dek, salt), iv);
43209
43685
  decipher.setAAD(file2.subarray(0, aadEnd));
43210
43686
  decipher.setAuthTag(file2.subarray(file2.length - TAG_LENGTH));
43211
43687
  const body = Buffer.concat([decipher.update(file2.subarray(aadEnd, file2.length - TAG_LENGTH)), decipher.final()]);
@@ -43227,7 +43703,7 @@ async function writeVectorFile(filePath, entries, model, dek) {
43227
43703
  const dir = path.dirname(filePath);
43228
43704
  await mkdir2(dir, { recursive: true, mode: 448 });
43229
43705
  await chmod(dir, 448);
43230
- const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID2()}.tmp`);
43706
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${randomUUID4()}.tmp`);
43231
43707
  try {
43232
43708
  await writeFile(tmp, sealVectorFile(entries, model, dek), { mode: 384, flag: "wx" });
43233
43709
  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-test.378",
3
+ "version": "2.7.1-test.379",
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": {