apple-notes-mcp 2.8.8 → 2.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -2242,10 +2242,10 @@ var require_resolve = __commonJS({
2242
2242
  }
2243
2243
  return count;
2244
2244
  }
2245
- function getFullPath(resolver, id = "", normalize) {
2245
+ function getFullPath(resolver, id2 = "", normalize) {
2246
2246
  if (normalize !== false)
2247
- id = normalizeId(id);
2248
- const p = resolver.parse(id);
2247
+ id2 = normalizeId(id2);
2248
+ const p = resolver.parse(id2);
2249
2249
  return _getFullPath(resolver, p);
2250
2250
  }
2251
2251
  exports.getFullPath = getFullPath;
@@ -2255,13 +2255,13 @@ var require_resolve = __commonJS({
2255
2255
  }
2256
2256
  exports._getFullPath = _getFullPath;
2257
2257
  var TRAILING_SLASH_HASH = /#\/?$/;
2258
- function normalizeId(id) {
2259
- return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
2258
+ function normalizeId(id2) {
2259
+ return id2 ? id2.replace(TRAILING_SLASH_HASH, "") : "";
2260
2260
  }
2261
2261
  exports.normalizeId = normalizeId;
2262
- function resolveUrl(resolver, baseId, id) {
2263
- id = normalizeId(id);
2264
- return resolver.resolve(baseId, id);
2262
+ function resolveUrl(resolver, baseId, id2) {
2263
+ id2 = normalizeId(id2);
2264
+ return resolver.resolve(baseId, id2);
2265
2265
  }
2266
2266
  exports.resolveUrl = resolveUrl;
2267
2267
  var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
@@ -3031,8 +3031,8 @@ var require_compile = __commonJS({
3031
3031
  if (Object.keys(root.schema).length > 0 && refPath === baseId) {
3032
3032
  return getJsonPointer.call(this, p, root);
3033
3033
  }
3034
- const id = (0, resolve_1.normalizeId)(refPath);
3035
- const schOrRef = this.refs[id] || this.schemas[id];
3034
+ const id2 = (0, resolve_1.normalizeId)(refPath);
3035
+ const schOrRef = this.refs[id2] || this.schemas[id2];
3036
3036
  if (typeof schOrRef == "string") {
3037
3037
  const sch = resolveSchema.call(this, root, schOrRef);
3038
3038
  if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
@@ -3043,7 +3043,7 @@ var require_compile = __commonJS({
3043
3043
  return;
3044
3044
  if (!schOrRef.validate)
3045
3045
  compileSchema.call(this, schOrRef);
3046
- if (id === (0, resolve_1.normalizeId)(ref)) {
3046
+ if (id2 === (0, resolve_1.normalizeId)(ref)) {
3047
3047
  const { schema } = schOrRef;
3048
3048
  const { schemaId } = this.opts;
3049
3049
  const schId = schema[schemaId];
@@ -4458,15 +4458,15 @@ var require_core = __commonJS({
4458
4458
  this.addSchema(sch, void 0, _meta, _validateSchema);
4459
4459
  return this;
4460
4460
  }
4461
- let id;
4461
+ let id2;
4462
4462
  if (typeof schema === "object") {
4463
4463
  const { schemaId } = this.opts;
4464
- id = schema[schemaId];
4465
- if (id !== void 0 && typeof id != "string") {
4464
+ id2 = schema[schemaId];
4465
+ if (id2 !== void 0 && typeof id2 != "string") {
4466
4466
  throw new Error(`schema ${schemaId} must be string`);
4467
4467
  }
4468
4468
  }
4469
- key = (0, resolve_1.normalizeId)(key || id);
4469
+ key = (0, resolve_1.normalizeId)(key || id2);
4470
4470
  this._checkUnique(key);
4471
4471
  this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
4472
4472
  return this;
@@ -4545,11 +4545,11 @@ var require_core = __commonJS({
4545
4545
  case "object": {
4546
4546
  const cacheKey = schemaKeyRef;
4547
4547
  this._cache.delete(cacheKey);
4548
- let id = schemaKeyRef[this.opts.schemaId];
4549
- if (id) {
4550
- id = (0, resolve_1.normalizeId)(id);
4551
- delete this.schemas[id];
4552
- delete this.refs[id];
4548
+ let id2 = schemaKeyRef[this.opts.schemaId];
4549
+ if (id2) {
4550
+ id2 = (0, resolve_1.normalizeId)(id2);
4551
+ delete this.schemas[id2];
4552
+ delete this.refs[id2];
4553
4553
  }
4554
4554
  return this;
4555
4555
  }
@@ -4656,10 +4656,10 @@ var require_core = __commonJS({
4656
4656
  }
4657
4657
  }
4658
4658
  _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
4659
- let id;
4659
+ let id2;
4660
4660
  const { schemaId } = this.opts;
4661
4661
  if (typeof schema == "object") {
4662
- id = schema[schemaId];
4662
+ id2 = schema[schemaId];
4663
4663
  } else {
4664
4664
  if (this.opts.jtd)
4665
4665
  throw new Error("schema must be object");
@@ -4669,7 +4669,7 @@ var require_core = __commonJS({
4669
4669
  let sch = this._cache.get(schema);
4670
4670
  if (sch !== void 0)
4671
4671
  return sch;
4672
- baseId = (0, resolve_1.normalizeId)(id || baseId);
4672
+ baseId = (0, resolve_1.normalizeId)(id2 || baseId);
4673
4673
  const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
4674
4674
  sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
4675
4675
  this._cache.set(sch.schema, sch);
@@ -4682,9 +4682,9 @@ var require_core = __commonJS({
4682
4682
  this.validateSchema(schema, true);
4683
4683
  return sch;
4684
4684
  }
4685
- _checkUnique(id) {
4686
- if (this.schemas[id] || this.refs[id]) {
4687
- throw new Error(`schema with key or id "${id}" already exists`);
4685
+ _checkUnique(id2) {
4686
+ if (this.schemas[id2] || this.refs[id2]) {
4687
+ throw new Error(`schema with key or id "${id2}" already exists`);
4688
4688
  }
4689
4689
  }
4690
4690
  _compileSchemaEnv(sch) {
@@ -7952,7 +7952,7 @@ var require_NodeUtils = __commonJS({
7952
7952
  };
7953
7953
  var ESCAPE_REGEXP = /[&<>\u00A0]/g;
7954
7954
  var ESCAPE_ATTR_REGEXP = /[&"<>\u00A0]/g;
7955
- function escape2(s) {
7955
+ function escape3(s) {
7956
7956
  if (!ESCAPE_REGEXP.test(s)) {
7957
7957
  return s;
7958
7958
  }
@@ -8059,7 +8059,7 @@ var require_NodeUtils = __commonJS({
8059
8059
  if (hasRawContent[parenttag] || parenttag === "NOSCRIPT" && parent.ownerDocument._scripting_enabled) {
8060
8060
  s += kid.data;
8061
8061
  } else {
8062
- s += escape2(kid.data);
8062
+ s += escape3(kid.data);
8063
8063
  }
8064
8064
  break;
8065
8065
  case 8:
@@ -9922,13 +9922,13 @@ var require_select = __commonJS({
9922
9922
  return results;
9923
9923
  };
9924
9924
  module.exports = exports = function(sel, context) {
9925
- var id, r;
9925
+ var id2, r;
9926
9926
  if (context.nodeType !== 11 && sel.indexOf(" ") === -1) {
9927
9927
  if (sel[0] === "#" && context.rooted && /^#[A-Z_][-A-Z0-9_]*$/i.test(sel)) {
9928
9928
  if (context.doc._hasMultipleElementsWithId) {
9929
- id = sel.substring(1);
9930
- if (!context.doc._hasMultipleElementsWithId(id)) {
9931
- r = context.doc.getElementById(id);
9929
+ id2 = sel.substring(1);
9930
+ if (!context.doc._hasMultipleElementsWithId(id2)) {
9931
+ r = context.doc.getElementById(id2);
9932
9932
  return r ? [r] : [];
9933
9933
  }
9934
9934
  }
@@ -11110,12 +11110,12 @@ var require_Element = __commonJS({
11110
11110
  if (c.nodeType === Node.ELEMENT_NODE) {
11111
11111
  this[this.childrenByNumber.length] = c;
11112
11112
  this.childrenByNumber.push(c);
11113
- var id = c.getAttribute("id");
11114
- if (id && !this.childrenByName[id])
11115
- this.childrenByName[id] = c;
11113
+ var id2 = c.getAttribute("id");
11114
+ if (id2 && !this.childrenByName[id2])
11115
+ this.childrenByName[id2] = c;
11116
11116
  var name = c.getAttribute("name");
11117
11117
  if (name && this.element.namespaceURI === NAMESPACE.HTML && namedElts.test(this.element.localName) && !this.childrenByName[name])
11118
- this.childrenByName[id] = c;
11118
+ this.childrenByName[id2] = c;
11119
11119
  }
11120
11120
  }
11121
11121
  }
@@ -14845,16 +14845,16 @@ var require_Document = __commonJS({
14845
14845
  this._updateDocTypeElement();
14846
14846
  return child;
14847
14847
  } },
14848
- getElementById: { value: function(id) {
14849
- var n = this.byId[id];
14848
+ getElementById: { value: function(id2) {
14849
+ var n = this.byId[id2];
14850
14850
  if (!n) return null;
14851
14851
  if (n instanceof MultiId) {
14852
14852
  return n.getFirst();
14853
14853
  }
14854
14854
  return n;
14855
14855
  } },
14856
- _hasMultipleElementsWithId: { value: function(id) {
14857
- return this.byId[id] instanceof MultiId;
14856
+ _hasMultipleElementsWithId: { value: function(id2) {
14857
+ return this.byId[id2] instanceof MultiId;
14858
14858
  } },
14859
14859
  // Just copy this method from the Element prototype
14860
14860
  getElementsByName: { value: Element.prototype.getElementsByName },
@@ -15106,29 +15106,29 @@ var require_Document = __commonJS({
15106
15106
  }
15107
15107
  } },
15108
15108
  // Add a mapping from id to n for n.ownerDocument
15109
- addId: { value: function addId(id, n) {
15110
- var val = this.byId[id];
15109
+ addId: { value: function addId(id2, n) {
15110
+ var val = this.byId[id2];
15111
15111
  if (!val) {
15112
- this.byId[id] = n;
15112
+ this.byId[id2] = n;
15113
15113
  } else {
15114
15114
  if (!(val instanceof MultiId)) {
15115
15115
  val = new MultiId(val);
15116
- this.byId[id] = val;
15116
+ this.byId[id2] = val;
15117
15117
  }
15118
15118
  val.add(n);
15119
15119
  }
15120
15120
  } },
15121
15121
  // Delete the mapping from id to n for n.ownerDocument
15122
- delId: { value: function delId(id, n) {
15123
- var val = this.byId[id];
15122
+ delId: { value: function delId(id2, n) {
15123
+ var val = this.byId[id2];
15124
15124
  utils.assert(val);
15125
15125
  if (val instanceof MultiId) {
15126
15126
  val.del(n);
15127
15127
  if (val.length === 1) {
15128
- this.byId[id] = val.downgrade();
15128
+ this.byId[id2] = val.downgrade();
15129
15129
  }
15130
15130
  } else {
15131
- this.byId[id] = void 0;
15131
+ this.byId[id2] = void 0;
15132
15132
  }
15133
15133
  } },
15134
15134
  _resolve: { value: function(href) {
@@ -15238,15 +15238,15 @@ var require_Document = __commonJS({
15238
15238
  n._nid = n.ownerDocument._nextnid++;
15239
15239
  n.ownerDocument._nodes[n._nid] = n;
15240
15240
  if (n.nodeType === Node.ELEMENT_NODE) {
15241
- var id = n.getAttribute("id");
15242
- if (id) n.ownerDocument.addId(id, n);
15241
+ var id2 = n.getAttribute("id");
15242
+ if (id2) n.ownerDocument.addId(id2, n);
15243
15243
  if (n._roothook) n._roothook();
15244
15244
  }
15245
15245
  }
15246
15246
  function uproot(n) {
15247
15247
  if (n.nodeType === Node.ELEMENT_NODE) {
15248
- var id = n.getAttribute("id");
15249
- if (id) n.ownerDocument.delId(id, n);
15248
+ var id2 = n.getAttribute("id");
15249
+ if (id2) n.ownerDocument.delId(id2, n);
15250
15250
  }
15251
15251
  n.ownerDocument._nodes[n._nid] = void 0;
15252
15252
  n._nid = void 0;
@@ -23908,8 +23908,8 @@ var require_turndown_cjs = __commonJS({
23908
23908
  }
23909
23909
  var markdownEscapes = [[/\\/g, "\\\\"], [/\*/g, "\\*"], [/^-/g, "\\-"], [/^\+ /g, "\\+ "], [/^(=+)/g, "\\$1"], [/^(#{1,6}) /g, "\\$1 "], [/`/g, "\\`"], [/^~~~/g, "\\~~~"], [/\[/g, "\\["], [/\]/g, "\\]"], [/^>/g, "\\>"], [/_/g, "\\_"], [/^(\d+)\. /g, "$1\\. "]];
23910
23910
  function escapeMarkdown(string3) {
23911
- return markdownEscapes.reduce(function(accumulator, escape2) {
23912
- return accumulator.replace(escape2[0], escape2[1]);
23911
+ return markdownEscapes.reduce(function(accumulator, escape3) {
23912
+ return accumulator.replace(escape3[0], escape3[1]);
23913
23913
  }, string3);
23914
23914
  }
23915
23915
  var rules = {};
@@ -24037,9 +24037,9 @@ var require_turndown_cjs = __commonJS({
24037
24037
  reference = "[" + content + "]: " + href + title;
24038
24038
  break;
24039
24039
  default:
24040
- var id = this.references.length + 1;
24041
- replacement = "[" + content + "][" + id + "]";
24042
- reference = "[" + id + "]: " + href + title;
24040
+ var id2 = this.references.length + 1;
24041
+ replacement = "[" + content + "][" + id2 + "]";
24042
+ reference = "[" + id2 + "]: " + href + title;
24043
24043
  }
24044
24044
  this.references.push(reference);
24045
24045
  return replacement;
@@ -24465,14 +24465,14 @@ var require_turndown_cjs = __commonJS({
24465
24465
  } else if (node.nodeType === 1) {
24466
24466
  replacement = replacementForNode.call(self, node);
24467
24467
  }
24468
- return join10(output, replacement);
24468
+ return join11(output, replacement);
24469
24469
  }, "");
24470
24470
  }
24471
24471
  function postProcess(output) {
24472
24472
  var self = this;
24473
24473
  this.rules.forEach(function(rule) {
24474
24474
  if (typeof rule.append === "function") {
24475
- output = join10(output, rule.append(self.options));
24475
+ output = join11(output, rule.append(self.options));
24476
24476
  }
24477
24477
  });
24478
24478
  return output.replace(/^[\t\r\n]+/, "").replace(/[\t\r\n\s]+$/, "");
@@ -24484,7 +24484,7 @@ var require_turndown_cjs = __commonJS({
24484
24484
  if (whitespace.leading || whitespace.trailing) content = content.trim();
24485
24485
  return whitespace.leading + rule.replacement(content, node, this.options) + whitespace.trailing;
24486
24486
  }
24487
- function join10(output, replacement) {
24487
+ function join11(output, replacement) {
24488
24488
  var s1 = trimTrailingNewlines(output);
24489
24489
  var s2 = trimLeadingNewlines(replacement);
24490
24490
  var nls = Math.max(output.length - s1.length, replacement.length - s2.length);
@@ -30311,38 +30311,38 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
30311
30311
  doc.write(`const newResult = {}`);
30312
30312
  for (const key of normalized2.keys) {
30313
30313
  if (normalized2.optionalKeys.has(key)) {
30314
- const id = ids[key];
30315
- doc.write(`const ${id} = ${parseStr(key)};`);
30314
+ const id2 = ids[key];
30315
+ doc.write(`const ${id2} = ${parseStr(key)};`);
30316
30316
  const k = esc(key);
30317
30317
  doc.write(`
30318
- if (${id}.issues.length) {
30318
+ if (${id2}.issues.length) {
30319
30319
  if (input[${k}] === undefined) {
30320
30320
  if (${k} in input) {
30321
30321
  newResult[${k}] = undefined;
30322
30322
  }
30323
30323
  } else {
30324
30324
  payload.issues = payload.issues.concat(
30325
- ${id}.issues.map((iss) => ({
30325
+ ${id2}.issues.map((iss) => ({
30326
30326
  ...iss,
30327
30327
  path: iss.path ? [${k}, ...iss.path] : [${k}],
30328
30328
  }))
30329
30329
  );
30330
30330
  }
30331
- } else if (${id}.value === undefined) {
30331
+ } else if (${id2}.value === undefined) {
30332
30332
  if (${k} in input) newResult[${k}] = undefined;
30333
30333
  } else {
30334
- newResult[${k}] = ${id}.value;
30334
+ newResult[${k}] = ${id2}.value;
30335
30335
  }
30336
30336
  `);
30337
30337
  } else {
30338
- const id = ids[key];
30339
- doc.write(`const ${id} = ${parseStr(key)};`);
30338
+ const id2 = ids[key];
30339
+ doc.write(`const ${id2} = ${parseStr(key)};`);
30340
30340
  doc.write(`
30341
- if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
30341
+ if (${id2}.issues.length) payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
30342
30342
  ...iss,
30343
30343
  path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
30344
30344
  })));`);
30345
- doc.write(`newResult[${esc(key)}] = ${id}.value`);
30345
+ doc.write(`newResult[${esc(key)}] = ${id2}.value`);
30346
30346
  }
30347
30347
  }
30348
30348
  doc.write(`payload.value = newResult;`);
@@ -32073,13 +32073,13 @@ var JSONSchemaGenerator = class {
32073
32073
  const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
32074
32074
  if (params.external) {
32075
32075
  const externalId = params.external.registry.get(entry[0])?.id;
32076
- const uriGenerator = params.external.uri ?? ((id2) => id2);
32076
+ const uriGenerator = params.external.uri ?? ((id3) => id3);
32077
32077
  if (externalId) {
32078
32078
  return { ref: uriGenerator(externalId) };
32079
32079
  }
32080
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
32081
- entry[1].defId = id;
32082
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
32080
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
32081
+ entry[1].defId = id2;
32082
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
32083
32083
  }
32084
32084
  if (entry[1] === root) {
32085
32085
  return { ref: "#" };
@@ -32127,8 +32127,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
32127
32127
  continue;
32128
32128
  }
32129
32129
  }
32130
- const id = this.metadataRegistry.get(entry[0])?.id;
32131
- if (id) {
32130
+ const id2 = this.metadataRegistry.get(entry[0])?.id;
32131
+ if (id2) {
32132
32132
  extractToDef(entry);
32133
32133
  continue;
32134
32134
  }
@@ -32182,10 +32182,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
32182
32182
  console.warn(`Invalid target: ${this.target}`);
32183
32183
  }
32184
32184
  if (params.external?.uri) {
32185
- const id = params.external.registry.get(schema)?.id;
32186
- if (!id)
32185
+ const id2 = params.external.registry.get(schema)?.id;
32186
+ if (!id2)
32187
32187
  throw new Error("Schema is missing an `id` property");
32188
- result.$id = params.external.uri(id);
32188
+ result.$id = params.external.uri(id2);
32189
32189
  }
32190
32190
  Object.assign(result, root.def);
32191
32191
  const defs = params.external?.defs ?? {};
@@ -37218,7 +37218,7 @@ var ExperimentalServerTasks = class {
37218
37218
  if (hasPreviousToolUse) {
37219
37219
  const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
37220
37220
  const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
37221
- if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
37221
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id2) => toolResultIds.has(id2))) {
37222
37222
  throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
37223
37223
  }
37224
37224
  }
@@ -37643,7 +37643,7 @@ var Server = class extends Protocol {
37643
37643
  if (hasPreviousToolUse) {
37644
37644
  const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
37645
37645
  const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
37646
- if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
37646
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id2) => toolResultIds.has(id2))) {
37647
37647
  throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
37648
37648
  }
37649
37649
  }
@@ -39604,8 +39604,8 @@ function parseRichNote(data, nativeTags = []) {
39604
39604
  styleRuns
39605
39605
  };
39606
39606
  }
39607
- function readRichNote(id) {
39608
- const pk = /^x-coredata:\/\/[0-9a-f-]+\/ICNote\/p([0-9]+)$/i.exec(id)?.[1];
39607
+ function readRichNote(id2) {
39608
+ const pk = /^x-coredata:\/\/[0-9a-f-]+\/ICNote\/p([0-9]+)$/i.exec(id2)?.[1];
39609
39609
  if (!pk) throw new Error("Invalid exact note ID");
39610
39610
  const sql = `BEGIN; SELECT hex(ZDATA) FROM ZICNOTEDATA WHERE ZNOTE=${pk}; SELECT json_group_object(ZIDENTIFIER,ZALTTEXT) FROM ZICCLOUDSYNCINGOBJECT WHERE ZNOTE1=${pk} AND ZTYPEUTI1='com.apple.notes.inlinetextattachment.hashtag'; SELECT json_group_array(json_object('id',ZIDENTIFIER,'pk',Z_PK,'type',COALESCE(ZTYPEUTI1,ZTYPEUTI),'mergeable',hex(COALESCE(ZMERGEABLEDATA1,ZMERGEABLEDATA)),'view',ZATTACHMENTVIEWTYPE)) FROM ZICCLOUDSYNCINGOBJECT WHERE ZNOTE1=${pk} OR ZNOTE=${pk}; COMMIT;`;
39611
39611
  const rows = execFileSync3("/usr/bin/sqlite3", ["-readonly", dbPath, sql], {
@@ -39630,14 +39630,14 @@ function readRichNote(id) {
39630
39630
  rich.objectData = objectData.filter((row) => rich.nativeObjectIds.includes(row.id)).sort((a, b) => a.id.localeCompare(b.id));
39631
39631
  rich.revision = createHash("sha256").update(rich.revision).update(JSON.stringify(rich.objectData)).digest("hex");
39632
39632
  rich.nativeTagObjectIds = {};
39633
- for (const id2 of rich.nativeObjectIds)
39634
- if (tagMap[id2]) {
39635
- const tag = tagMap[id2].replace(/^#/, "");
39636
- (rich.nativeTagObjectIds[tag] ||= []).push(id2);
39633
+ for (const id3 of rich.nativeObjectIds)
39634
+ if (tagMap[id3]) {
39635
+ const tag = tagMap[id3].replace(/^#/, "");
39636
+ (rich.nativeTagObjectIds[tag] ||= []).push(id3);
39637
39637
  }
39638
39638
  rich.nativeTags = [
39639
39639
  ...new Set(
39640
- rich.nativeObjectIds.flatMap((id2) => tagMap[id2] ? [tagMap[id2].replace(/^#/, "")] : [])
39640
+ rich.nativeObjectIds.flatMap((id3) => tagMap[id3] ? [tagMap[id3].replace(/^#/, "")] : [])
39641
39641
  )
39642
39642
  ];
39643
39643
  return rich;
@@ -39712,10 +39712,10 @@ function restoreNoteLinks(html, rich) {
39712
39712
  result = result.slice(0, span.start) + `<a href="${escapeAttribute(span.url)}">` + result.slice(span.start, span.end) + "</a>" + result.slice(span.end);
39713
39713
  return result;
39714
39714
  }
39715
- function enrichNoteRead(id, rawBody) {
39715
+ function enrichNoteRead(id2, rawBody) {
39716
39716
  let metadata;
39717
39717
  try {
39718
- const rich = readRichNote(id);
39718
+ const rich = readRichNote(id2);
39719
39719
  metadata = rich;
39720
39720
  const content = restoreNoteLinks(rawBody, rich);
39721
39721
  const writable = !rich.hasNativeObjects && !rich.hasChecklist;
@@ -39971,24 +39971,24 @@ function validateLength(value, maxLength, label) {
39971
39971
  }
39972
39972
  return value;
39973
39973
  }
39974
- function sanitizeId(id) {
39974
+ function sanitizeId(id2) {
39975
39975
  const coreDataPattern = /^x-coredata:\/\/[0-9A-Fa-f-]+\/IC[A-Za-z]+\/p\d+$/;
39976
39976
  const tempIdPattern = /^temp-\d+-\d+$/;
39977
- if (!coreDataPattern.test(id) && !tempIdPattern.test(id)) {
39977
+ if (!coreDataPattern.test(id2) && !tempIdPattern.test(id2)) {
39978
39978
  throw new Error(
39979
- `Invalid note ID format: "${id.substring(0, 80)}". Expected CoreData URL (x-coredata://...) or temp ID.`
39979
+ `Invalid note ID format: "${id2.substring(0, 80)}". Expected CoreData URL (x-coredata://...) or temp ID.`
39980
39980
  );
39981
39981
  }
39982
- return escapeForAppleScript(id);
39982
+ return escapeForAppleScript(id2);
39983
39983
  }
39984
- function sanitizeNoteId(id) {
39984
+ function sanitizeNoteId(id2) {
39985
39985
  const noteIdPattern = /^x-coredata:\/\/[0-9A-Fa-f-]+\/ICNote\/p\d+$/;
39986
- if (!noteIdPattern.test(id)) {
39986
+ if (!noteIdPattern.test(id2)) {
39987
39987
  throw new Error(
39988
- `Invalid note ID format: "${id.substring(0, 80)}". Expected canonical Apple Note ID (x-coredata://.../ICNote/p...).`
39988
+ `Invalid note ID format: "${id2.substring(0, 80)}". Expected canonical Apple Note ID (x-coredata://.../ICNote/p...).`
39989
39989
  );
39990
39990
  }
39991
- return escapeForAppleScript(id);
39991
+ return escapeForAppleScript(id2);
39992
39992
  }
39993
39993
  function sanitizeAccountName(account) {
39994
39994
  validateLength(account, MAX_ACCOUNT_LENGTH, "Account name");
@@ -40043,10 +40043,10 @@ function parseNotePropertiesOutput(output) {
40043
40043
  console.error("Unexpected response format: expected 6 delimited note properties");
40044
40044
  return null;
40045
40045
  }
40046
- const [title, id, createdStr, modifiedStr, sharedStr, ppStr] = parts;
40046
+ const [title, id2, createdStr, modifiedStr, sharedStr, ppStr] = parts;
40047
40047
  return {
40048
40048
  title: title.trim(),
40049
- id: id.trim(),
40049
+ id: id2.trim(),
40050
40050
  created: createdStr?.trim() ? parseAppleScriptDate(createdStr.trim()) : /* @__PURE__ */ new Date(),
40051
40051
  modified: modifiedStr?.trim() ? parseAppleScriptDate(modifiedStr.trim()) : /* @__PURE__ */ new Date(),
40052
40052
  shared: sharedStr?.trim() === "true",
@@ -40207,8 +40207,8 @@ var AppleNotesManager = class {
40207
40207
  * @param id - CoreData URL identifier for the note
40208
40208
  * @returns true if the note is password-protected, false otherwise
40209
40209
  */
40210
- isNotePasswordProtectedById(id) {
40211
- const note = this.getNoteById(id);
40210
+ isNotePasswordProtectedById(id2) {
40211
+ const note = this.getNoteById(id2);
40212
40212
  return note?.passwordProtected === true;
40213
40213
  }
40214
40214
  /**
@@ -40406,9 +40406,9 @@ var AppleNotesManager = class {
40406
40406
  const seenIds = /* @__PURE__ */ new Set();
40407
40407
  const reportedAccount = this.reportedAccount(targetAccount);
40408
40408
  for (const item of items) {
40409
- const [title, id, folder2, created, modified] = item.split(FIELD_SEP);
40409
+ const [title, id2, folder2, created, modified] = item.split(FIELD_SEP);
40410
40410
  if (!title?.trim()) continue;
40411
- const noteId3 = id?.trim() || generateFallbackId();
40411
+ const noteId3 = id2?.trim() || generateFallbackId();
40412
40412
  if (seenIds.has(noteId3)) continue;
40413
40413
  seenIds.add(noteId3);
40414
40414
  notes.push({
@@ -40470,13 +40470,13 @@ var AppleNotesManager = class {
40470
40470
  * @param id - CoreData URL identifier for the note
40471
40471
  * @returns HTML content of the note, or empty string if not found
40472
40472
  */
40473
- getNoteContentById(id) {
40474
- const safeId = sanitizeId(id);
40473
+ getNoteContentById(id2) {
40474
+ const safeId = sanitizeId(id2);
40475
40475
  const getCommand = `get body of note id "${safeId}"`;
40476
40476
  const script = buildAppLevelScript(getCommand);
40477
40477
  const result = executeAppleScript(script);
40478
40478
  if (!result.success) {
40479
- console.error(`Failed to get content of note with ID "${id}":`, result.error);
40479
+ console.error(`Failed to get content of note with ID "${id2}":`, result.error);
40480
40480
  return "";
40481
40481
  }
40482
40482
  return result.output;
@@ -40518,13 +40518,13 @@ var AppleNotesManager = class {
40518
40518
  * @param id - CoreData URL identifier for the note
40519
40519
  * @returns Plain-text content of the note, or empty string if not found
40520
40520
  */
40521
- getNotePlaintextById(id) {
40522
- const safeId = sanitizeId(id);
40521
+ getNotePlaintextById(id2) {
40522
+ const safeId = sanitizeId(id2);
40523
40523
  const getCommand = `get plaintext of note id "${safeId}"`;
40524
40524
  const script = buildAppLevelScript(getCommand);
40525
40525
  const result = executeAppleScript(script);
40526
40526
  if (!result.success) {
40527
- console.error(`Failed to get plaintext of note with ID "${id}":`, result.error);
40527
+ console.error(`Failed to get plaintext of note with ID "${id2}":`, result.error);
40528
40528
  return "";
40529
40529
  }
40530
40530
  return result.output;
@@ -40540,8 +40540,8 @@ var AppleNotesManager = class {
40540
40540
  * @param id - CoreData URL identifier for the note
40541
40541
  * @returns Note object with metadata, or null if not found
40542
40542
  */
40543
- getNoteById(id) {
40544
- const safeId = sanitizeId(id);
40543
+ getNoteById(id2) {
40544
+ const safeId = sanitizeId(id2);
40545
40545
  const getCommand = `
40546
40546
  set n to note id "${safeId}"
40547
40547
  set cd to creation date of n
@@ -40553,7 +40553,7 @@ var AppleNotesManager = class {
40553
40553
  const script = buildAppLevelScript(getCommand);
40554
40554
  const result = executeAppleScript(script);
40555
40555
  if (!result.success) {
40556
- console.error(`Failed to get note with ID "${id}":`, result.error);
40556
+ console.error(`Failed to get note with ID "${id2}":`, result.error);
40557
40557
  return null;
40558
40558
  }
40559
40559
  const parsed = parseNotePropertiesOutput(result.output);
@@ -40625,10 +40625,10 @@ var AppleNotesManager = class {
40625
40625
  * race that would exist if JavaScript checked the note and then issued a
40626
40626
  * separate unconditional `set body` command.
40627
40627
  */
40628
- updateNoteByIdIfUnchanged(id, currentTitle, expectedBody, newTitle, newContent, format = "plaintext", expectedRichRevision) {
40629
- const safeId = sanitizeNoteId(id);
40628
+ updateNoteByIdIfUnchanged(id2, currentTitle, expectedBody, newTitle, newContent, format = "plaintext", expectedRichRevision) {
40629
+ const safeId = sanitizeNoteId(id2);
40630
40630
  if (expectedRichRevision) {
40631
- const rich = readRichNote(id);
40631
+ const rich = readRichNote(id2);
40632
40632
  if (rich.revision !== expectedRichRevision) return { status: "conflict" };
40633
40633
  if (rich.hasNativeObjects || rich.hasChecklist) return { status: "attachments" };
40634
40634
  }
@@ -40657,7 +40657,7 @@ var AppleNotesManager = class {
40657
40657
  `);
40658
40658
  const result = executeMutationAppleScript(script);
40659
40659
  if (!result.success) {
40660
- console.error(`Failed guarded update for note ID "${id}":`, result.error);
40660
+ console.error(`Failed guarded update for note ID "${id2}":`, result.error);
40661
40661
  return { status: "failed" };
40662
40662
  }
40663
40663
  const status = result.output.trim();
@@ -40671,8 +40671,8 @@ var AppleNotesManager = class {
40671
40671
  * the caller reviewed. The comparison and delete are one AppleScript action,
40672
40672
  * so a concurrent edit cannot slip between the guard and deletion.
40673
40673
  */
40674
- deleteNoteByIdIfUnchanged(id, expectedBody) {
40675
- const safeId = sanitizeNoteId(id);
40674
+ deleteNoteByIdIfUnchanged(id2, expectedBody) {
40675
+ const safeId = sanitizeNoteId(id2);
40676
40676
  validateLength(expectedBody, MAX_CONTENT_LENGTH, "Expected note content");
40677
40677
  const safeExpectedBody = escapeHtmlForAppleScript(expectedBody);
40678
40678
  const script = buildAppLevelScript(`
@@ -40686,7 +40686,7 @@ var AppleNotesManager = class {
40686
40686
  `);
40687
40687
  const result = executeMutationAppleScript(script);
40688
40688
  if (!result.success) {
40689
- console.error(`Failed guarded delete for note ID "${id}":`, result.error);
40689
+ console.error(`Failed guarded delete for note ID "${id2}":`, result.error);
40690
40690
  return { status: "failed" };
40691
40691
  }
40692
40692
  const status = result.output.trim();
@@ -40778,9 +40778,9 @@ var AppleNotesManager = class {
40778
40778
  const seenIds = /* @__PURE__ */ new Set();
40779
40779
  const refs = [];
40780
40780
  for (const item of output.split(RECORD_SEP)) {
40781
- const [title, id] = item.split(FIELD_SEP);
40781
+ const [title, id2] = item.split(FIELD_SEP);
40782
40782
  if (!title?.trim()) continue;
40783
- const noteId3 = id?.trim() || generateFallbackId();
40783
+ const noteId3 = id2?.trim() || generateFallbackId();
40784
40784
  if (seenIds.has(noteId3)) continue;
40785
40785
  seenIds.add(noteId3);
40786
40786
  refs.push({ title: title.trim(), id: noteId3 });
@@ -40906,13 +40906,13 @@ var AppleNotesManager = class {
40906
40906
  const parts = item.split(FIELD_SEP);
40907
40907
  if (parts.length >= 6) {
40908
40908
  const title = parts[0].trim();
40909
- const id = parts[1].trim();
40909
+ const id2 = parts[1].trim();
40910
40910
  const createdStr = parts[2].trim();
40911
40911
  const modifiedStr = parts[3].trim();
40912
40912
  const shared = parts[4].trim() === "true";
40913
40913
  const passwordProtected = parts[5].trim() === "true";
40914
40914
  sharedNotes.push({
40915
- id,
40915
+ id: id2,
40916
40916
  title,
40917
40917
  content: "",
40918
40918
  tags: [],
@@ -40931,25 +40931,25 @@ var AppleNotesManager = class {
40931
40931
  // Folder Operations
40932
40932
  // ===========================================================================
40933
40933
  /** Rename a folder in place while preserving its identity and contents. */
40934
- renameFolderById(id, expectedName, expectedParentId, newName) {
40935
- if (!/^x-coredata:\/\/[0-9a-f-]+\/ICFolder\/p\d+$/i.test(id))
40934
+ renameFolderById(id2, expectedName, expectedParentId, newName) {
40935
+ if (!/^x-coredata:\/\/[0-9a-f-]+\/ICFolder\/p\d+$/i.test(id2))
40936
40936
  throw new Error("An exact folder ID is required");
40937
40937
  if (!newName.trim() || newName.length > 1e3 || Array.from(newName).some((char) => char.charCodeAt(0) < 32))
40938
40938
  throw new Error("Invalid folder name");
40939
40939
  const literal2 = (value) => `"${escapePlainStringForAppleScript(value)}"`;
40940
40940
  const script = `tell application "Notes"
40941
- set targetFolder to folder id ${literal2(id)}
40941
+ set targetFolder to folder id ${literal2(id2)}
40942
40942
  set parentRef to container of targetFolder
40943
40943
  set parentId to id of parentRef
40944
40944
  considering case
40945
40945
  if name of targetFolder is not ${literal2(expectedName)} or parentId is not ${literal2(expectedParentId)} then error "Folder changed; read it again"
40946
40946
  end considering
40947
40947
  repeat with sibling in folders of parentRef
40948
- if name of sibling is ${literal2(newName)} and id of sibling is not ${literal2(id)} then error "A sibling folder already has this name"
40948
+ if name of sibling is ${literal2(newName)} and id of sibling is not ${literal2(id2)} then error "A sibling folder already has this name"
40949
40949
  end repeat
40950
40950
  set name of targetFolder to ${literal2(newName)}
40951
40951
  considering case
40952
- if id of targetFolder is not ${literal2(id)} or name of targetFolder is not ${literal2(newName)} or id of container of targetFolder is not parentId then error "Rename readback failed"
40952
+ if id of targetFolder is not ${literal2(id2)} or name of targetFolder is not ${literal2(newName)} or id of container of targetFolder is not parentId then error "Rename readback failed"
40953
40953
  end considering
40954
40954
  return id of targetFolder
40955
40955
  end tell`;
@@ -40958,28 +40958,28 @@ var AppleNotesManager = class {
40958
40958
  throw new Error(
40959
40959
  result.error || "Rename outcome uncertain; read folder by ID before retrying"
40960
40960
  );
40961
- return { id, name: newName, parentId: expectedParentId };
40961
+ return { id: id2, name: newName, parentId: expectedParentId };
40962
40962
  }
40963
40963
  /** Read the exact name and parent identity used by guarded folder rename. */
40964
- getFolderById(id) {
40965
- if (!/^x-coredata:\/\/[0-9a-f-]+\/ICFolder\/p\d+$/i.test(id))
40964
+ getFolderById(id2) {
40965
+ if (!/^x-coredata:\/\/[0-9a-f-]+\/ICFolder\/p\d+$/i.test(id2))
40966
40966
  throw new Error("An exact folder ID is required");
40967
40967
  const result = executeAppleScript(`tell application "Notes"
40968
- set f to folder id "${id}"
40968
+ set f to folder id "${id2}"
40969
40969
  return (name of f) & ${AS_FIELD_SEP} & (id of container of f)
40970
40970
  end tell`);
40971
40971
  if (!result.success) throw new Error(result.error || "Folder not found");
40972
40972
  const [name, parentId] = result.output.replace(/\n$/, "").split(FIELD_SEP);
40973
40973
  if (!name || !parentId) throw new Error("Incomplete folder metadata");
40974
- return { id, name, parentId };
40974
+ return { id: id2, name, parentId };
40975
40975
  }
40976
40976
  /** Insert one file into an unchanged exact note and return Notes' attachment ID. */
40977
- addAttachmentById(id, expectedBody, filePath) {
40978
- if (!/^x-coredata:\/\/[0-9a-f-]+\/ICNote\/p\d+$/i.test(id))
40977
+ addAttachmentById(id2, expectedBody, filePath) {
40978
+ if (!/^x-coredata:\/\/[0-9a-f-]+\/ICNote\/p\d+$/i.test(id2))
40979
40979
  throw new Error("Exact note ID required");
40980
40980
  const quote = (value) => `"${escapePlainStringForAppleScript(value)}"`;
40981
40981
  const result = executeMutationAppleScript(`tell application "Notes"
40982
- set n to note id ${quote(id)}
40982
+ set n to note id ${quote(id2)}
40983
40983
  if password protected of n then error "Locked note"
40984
40984
  considering case
40985
40985
  if body of n is not ${quote(expectedBody)} and body of n is not (${quote(expectedBody)} & linefeed) then error "Note changed before attachment insertion"
@@ -41151,9 +41151,9 @@ var AppleNotesManager = class {
41151
41151
  * @param account - Account containing the destination folder (defaults to Notes.app's default account)
41152
41152
  * @returns true if the move succeeded, false otherwise
41153
41153
  */
41154
- moveNoteById(id, destinationFolder, account) {
41154
+ moveNoteById(id2, destinationFolder, account) {
41155
41155
  const targetAccount = this.resolveAccount(account);
41156
- const safeId = sanitizeNoteId(id);
41156
+ const safeId = sanitizeNoteId(id2);
41157
41157
  const destFolderRef = `${buildFolderReference(destinationFolder)} of ${AS_ACCOUNT_REF}`;
41158
41158
  const moveCommand = `
41159
41159
  ${buildAccountResolution(targetAccount)}
@@ -41177,7 +41177,7 @@ var AppleNotesManager = class {
41177
41177
  }
41178
41178
  if (result.output.trim() !== "SAFETY_MOVED") {
41179
41179
  console.error(
41180
- `Move result for note ID "${id}" did not verify destination "${destinationFolder}"`
41180
+ `Move result for note ID "${id2}" did not verify destination "${destinationFolder}"`
41181
41181
  );
41182
41182
  return false;
41183
41183
  }
@@ -41325,14 +41325,14 @@ var AppleNotesManager = class {
41325
41325
  * @param separately - Whether to open the note in a separate window
41326
41326
  * @returns true if Notes.app accepted the show command
41327
41327
  */
41328
- showNoteById(id, separately = false) {
41329
- const safeId = sanitizeId(id);
41328
+ showNoteById(id2, separately = false) {
41329
+ const safeId = sanitizeId(id2);
41330
41330
  const separatelyClause = separately ? " separately true" : "";
41331
41331
  const result = executeMutationAppleScript(
41332
41332
  buildAppLevelScript(`show note id "${safeId}"${separatelyClause}`)
41333
41333
  );
41334
41334
  if (!result.success) {
41335
- console.error(`Failed to show note with ID "${id}":`, result.error);
41335
+ console.error(`Failed to show note with ID "${id2}":`, result.error);
41336
41336
  return false;
41337
41337
  }
41338
41338
  return true;
@@ -41350,20 +41350,20 @@ var AppleNotesManager = class {
41350
41350
  * @param id - CoreData URL identifier for the note
41351
41351
  * @returns notes://showNote?identifier=<uuid> string, or null on failure
41352
41352
  */
41353
- getNoteLinkById(id) {
41354
- const note = this.getNoteById(id);
41353
+ getNoteLinkById(id2) {
41354
+ const note = this.getNoteById(id2);
41355
41355
  if (!note) return null;
41356
41356
  if (note.passwordProtected) return null;
41357
- const sqliteLink = getNoteLinkFromDB(id);
41357
+ const sqliteLink = getNoteLinkFromDB(id2);
41358
41358
  if (sqliteLink) return sqliteLink;
41359
- const safeId = sanitizeId(id);
41359
+ const safeId = sanitizeId(id2);
41360
41360
  const result = executeAppleScript(
41361
41361
  buildAppLevelScript(`return note link of (note id "${safeId}")`)
41362
41362
  );
41363
41363
  if (result.success && result.output.trim()) {
41364
41364
  return result.output.trim();
41365
41365
  }
41366
- console.error(`Failed to get note link for ID "${id}":`, result.error);
41366
+ console.error(`Failed to get note link for ID "${id2}":`, result.error);
41367
41367
  return null;
41368
41368
  }
41369
41369
  /**
@@ -41388,14 +41388,14 @@ var AppleNotesManager = class {
41388
41388
  * @param separately - Open in a separate window when supported by Notes.app
41389
41389
  * @returns true if Notes.app accepted the show command, false otherwise
41390
41390
  */
41391
- showFolderById(id, separately = false) {
41392
- const safeId = sanitizeId(id);
41391
+ showFolderById(id2, separately = false) {
41392
+ const safeId = sanitizeId(id2);
41393
41393
  const separatelyClause = separately ? " separately true" : "";
41394
41394
  const result = executeMutationAppleScript(
41395
41395
  buildAppLevelScript(`show folder id "${safeId}"${separatelyClause}`)
41396
41396
  );
41397
41397
  if (!result.success) {
41398
- console.error(`Failed to show folder with ID "${id}":`, result.error);
41398
+ console.error(`Failed to show folder with ID "${id2}":`, result.error);
41399
41399
  return false;
41400
41400
  }
41401
41401
  return true;
@@ -41410,14 +41410,14 @@ var AppleNotesManager = class {
41410
41410
  * @param separately - Open in a separate window when supported by Notes.app
41411
41411
  * @returns true if Notes.app accepted the show command, false otherwise
41412
41412
  */
41413
- showAccountById(id, separately = false) {
41414
- const safeId = sanitizeId(id);
41413
+ showAccountById(id2, separately = false) {
41414
+ const safeId = sanitizeId(id2);
41415
41415
  const separatelyClause = separately ? " separately true" : "";
41416
41416
  const result = executeMutationAppleScript(
41417
41417
  buildAppLevelScript(`show account id "${safeId}"${separatelyClause}`)
41418
41418
  );
41419
41419
  if (!result.success) {
41420
- console.error(`Failed to show account with ID "${id}":`, result.error);
41420
+ console.error(`Failed to show account with ID "${id2}":`, result.error);
41421
41421
  return false;
41422
41422
  }
41423
41423
  return true;
@@ -41692,8 +41692,8 @@ var AppleNotesManager = class {
41692
41692
  * attachments.forEach(a => console.log(`${a.name}: ${a.contentType}`));
41693
41693
  * ```
41694
41694
  */
41695
- listAttachmentsById(id) {
41696
- const safeId = sanitizeId(id);
41695
+ listAttachmentsById(id2) {
41696
+ const safeId = sanitizeId(id2);
41697
41697
  const script = `
41698
41698
  tell application "Notes"
41699
41699
  set theNote to note id "${safeId}"
@@ -41738,7 +41738,7 @@ var AppleNotesManager = class {
41738
41738
  const result = executeAppleScript(script);
41739
41739
  if (!result.success) {
41740
41740
  throw new Error(
41741
- `Failed to list attachments for note ID "${id}": ${result.error ?? "unknown AppleScript error"}`
41741
+ `Failed to list attachments for note ID "${id2}": ${result.error ?? "unknown AppleScript error"}`
41742
41742
  );
41743
41743
  }
41744
41744
  if (!result.output) {
@@ -41962,32 +41962,32 @@ var AppleNotesManager = class {
41962
41962
  /**
41963
41963
  * Result of a batch operation on a single item.
41964
41964
  */
41965
- createBatchResult(id, success, error2) {
41966
- return error2 ? { id, success, error: error2 } : { id, success };
41965
+ createBatchResult(id2, success, error2) {
41966
+ return error2 ? { id: id2, success, error: error2 } : { id: id2, success };
41967
41967
  }
41968
41968
  /**
41969
41969
  * Maps a per-item status token emitted by a batch AppleScript loop to a
41970
41970
  * BatchResult, preserving the human-readable error messages of the original
41971
41971
  * per-note implementation. See {@link batchMoveNotes}.
41972
41972
  */
41973
- mapBatchStatus(id, status, op) {
41973
+ mapBatchStatus(id2, status, op) {
41974
41974
  switch (status) {
41975
41975
  case "ok":
41976
- return this.createBatchResult(id, true);
41976
+ return this.createBatchResult(id2, true);
41977
41977
  case "pw":
41978
- return this.createBatchResult(id, false, "Note is password-protected");
41978
+ return this.createBatchResult(id2, false, "Note is password-protected");
41979
41979
  case "missing":
41980
- return this.createBatchResult(id, false, "Note not found");
41980
+ return this.createBatchResult(id2, false, "Note not found");
41981
41981
  case "fail":
41982
41982
  return this.createBatchResult(
41983
- id,
41983
+ id2,
41984
41984
  false,
41985
41985
  op === "delete" ? "Deletion failed" : "Move failed"
41986
41986
  );
41987
41987
  case "wrongfolder":
41988
- return this.createBatchResult(id, false, "Destination folder verification failed");
41988
+ return this.createBatchResult(id2, false, "Destination folder verification failed");
41989
41989
  default:
41990
- return this.createBatchResult(id, false, "Unknown error");
41990
+ return this.createBatchResult(id2, false, "Unknown error");
41991
41991
  }
41992
41992
  }
41993
41993
  /**
@@ -42015,12 +42015,12 @@ var AppleNotesManager = class {
42015
42015
  const destFolderRef = `${buildFolderReference(folder)} of ${AS_ACCOUNT_REF}`;
42016
42016
  const results = new Array(ids.length);
42017
42017
  const runnable = [];
42018
- ids.forEach((id, i) => {
42018
+ ids.forEach((id2, i) => {
42019
42019
  try {
42020
- runnable.push({ index: i, safe: sanitizeNoteId(id) });
42020
+ runnable.push({ index: i, safe: sanitizeNoteId(id2) });
42021
42021
  } catch (e) {
42022
42022
  results[i] = this.createBatchResult(
42023
- id,
42023
+ id2,
42024
42024
  false,
42025
42025
  e instanceof Error ? e.message : "Invalid note ID"
42026
42026
  );
@@ -42284,12 +42284,12 @@ var AppleNotesManager = class {
42284
42284
  * @param id - CoreData URL identifier for the note
42285
42285
  * @returns Markdown content, or empty string if not found
42286
42286
  */
42287
- getNoteMarkdownById(id) {
42288
- const html = this.getNoteContentById(id);
42287
+ getNoteMarkdownById(id2) {
42288
+ const html = this.getNoteContentById(id2);
42289
42289
  if (!html) return "";
42290
- const rich = enrichNoteRead(id, html);
42290
+ const rich = enrichNoteRead(id2, html);
42291
42291
  let markdown = this.htmlToMarkdown(rich.content);
42292
- const result = getChecklistItems(id);
42292
+ const result = getChecklistItems(id2);
42293
42293
  if (result.items) {
42294
42294
  markdown = this.enrichMarkdownWithChecklists(markdown, result.items);
42295
42295
  }
@@ -42739,8 +42739,8 @@ function registerResourcesAndPrompts(server2, manager) {
42739
42739
  "note",
42740
42740
  new ResourceTemplate("notes://note/{id}", { list: void 0 }),
42741
42741
  (uri, variables) => {
42742
- const id = decodeURIComponent(String(variables.id));
42743
- const markdown = manager.getNoteMarkdownById(id);
42742
+ const id2 = decodeURIComponent(String(variables.id));
42743
+ const markdown = manager.getNoteMarkdownById(id2);
42744
42744
  return {
42745
42745
  contents: [{ uri: uri.href, mimeType: "text/markdown", text: markdown || "(not found)" }]
42746
42746
  };
@@ -42960,8 +42960,8 @@ function parseNoteTable(compressed) {
42960
42960
  const ordering = sub(sub(entry(ref), 16), 1), array2 = sub(ordering, 1);
42961
42961
  const ids = many(array2, 2).map((a) => hex(getField(a, 2)));
42962
42962
  const map = /* @__PURE__ */ new Map();
42963
- ids.forEach((id, i) => {
42964
- const index = uuids.indexOf(id);
42963
+ ids.forEach((id2, i) => {
42964
+ const index = uuids.indexOf(id2);
42965
42965
  if (index < 0) throw new Error("Missing dimension UUID");
42966
42966
  map.set(index, i);
42967
42967
  });
@@ -43028,17 +43028,17 @@ import { tmpdir as tmpdir2 } from "node:os";
43028
43028
  import { basename, isAbsolute as isAbsolute2, join as join8 } from "node:path";
43029
43029
  var noteId = external_exports.string().regex(/^x-coredata:\/\/[0-9a-f-]+\/ICNote\/p\d+$/i);
43030
43030
  var revision = external_exports.string().regex(/^sha256:[a-f0-9]{64}$/);
43031
- function readSnapshot(manager, id) {
43032
- const note = manager.getNoteById(id);
43031
+ function readSnapshot(manager, id2) {
43032
+ const note = manager.getNoteById(id2);
43033
43033
  if (!note) throw new Error("Note not found");
43034
43034
  if (note.passwordProtected) throw new Error("Locked notes cannot receive attachments");
43035
- const body = manager.getNoteContentById(id);
43035
+ const body = manager.getNoteContentById(id2);
43036
43036
  if (!body) throw new Error("Note content is unavailable");
43037
- const enriched = enrichNoteRead(id, body);
43038
- const rich = readRichNote(id);
43037
+ const enriched = enrichNoteRead(id2, body);
43038
+ const rich = readRichNote(id2);
43039
43039
  if (!enriched.complete || enriched.revision !== rich.revision)
43040
43040
  throw new Error("Native metadata changed during read; read the note again");
43041
- return { id, title: note.title, body, rich, hash: richContentHash(body, enriched) };
43041
+ return { id: id2, title: note.title, body, rich, hash: richContentHash(body, enriched) };
43042
43042
  }
43043
43043
  function assertExistingContentPreserved(before, after) {
43044
43044
  if (before.id !== after.id || before.title !== after.title)
@@ -43048,7 +43048,7 @@ function assertExistingContentPreserved(before, after) {
43048
43048
  throw new Error("Existing note text was not preserved");
43049
43049
  if (linkSignature(before.rich.links) !== linkSignature(after.rich.links.slice(0, before.rich.links.length)))
43050
43050
  throw new Error("Existing links were not preserved");
43051
- if (before.rich.nativeObjectIds.some((id) => !after.rich.nativeObjectIds.includes(id)))
43051
+ if (before.rich.nativeObjectIds.some((id2) => !after.rich.nativeObjectIds.includes(id2)))
43052
43052
  throw new Error("Existing native object was lost");
43053
43053
  if (before.rich.nativeTags.some((tag) => !after.rich.nativeTags.includes(tag)))
43054
43054
  throw new Error("Existing native tag was lost");
@@ -43113,7 +43113,7 @@ function registerDirectOperations(server2, manager) {
43113
43113
  "get-folder-by-id",
43114
43114
  "Use when: reading the exact folder name and parent before a guarded rename.\nReturns: folder id, current name, and parent id.\nDo not use when: listing folders by path (list-folders).\nSafety: read-only.",
43115
43115
  { id: external_exports.string().max(2e3) },
43116
- ({ id }) => manager.getFolderById(id),
43116
+ ({ id: id2 }) => manager.getFolderById(id2),
43117
43117
  true
43118
43118
  );
43119
43119
  tool(
@@ -43134,28 +43134,28 @@ function registerDirectOperations(server2, manager) {
43134
43134
  "add-attachment",
43135
43135
  "Use when: adding one local file to an exact note without replacing its body.\nReturns: the new attachment id, byte count, and post-write content hash after exact byte verification.\nDo not use when: reading or exporting an existing attachment.\nSafety: requires a fresh rich revision, copies at most 64 MiB through a private temporary file, never retries insertion, and verifies existing content plus fetched bytes.",
43136
43136
  { id: noteId, expectedContentHash: revision, path: external_exports.string().min(1).max(4096) },
43137
- ({ id, expectedContentHash, path: path4 }) => {
43138
- const before = readSnapshot(manager, id);
43137
+ ({ id: id2, expectedContentHash, path: path4 }) => {
43138
+ const before = readSnapshot(manager, id2);
43139
43139
  if (before.hash !== expectedContentHash) throw new Error("Note revision changed");
43140
43140
  const bytes = localAttachment(path4);
43141
- const beforeAttachments = manager.listAttachmentsById(id);
43141
+ const beforeAttachments = manager.listAttachmentsById(id2);
43142
43142
  const directory = mkdtempSync2(join8(tmpdir2(), "notes-attachment-add-"));
43143
43143
  const temporaryFile = join8(directory, basename(path4));
43144
43144
  try {
43145
43145
  writeFileSync(temporaryFile, bytes, { mode: 384 });
43146
- if (readSnapshot(manager, id).hash !== before.hash)
43146
+ if (readSnapshot(manager, id2).hash !== before.hash)
43147
43147
  throw new Error("Note revision changed");
43148
43148
  let returnedId;
43149
43149
  let transportUncertain = false;
43150
43150
  try {
43151
- returnedId = manager.addAttachmentById(id, before.body, temporaryFile);
43151
+ returnedId = manager.addAttachmentById(id2, before.body, temporaryFile);
43152
43152
  } catch {
43153
43153
  transportUncertain = true;
43154
43154
  }
43155
- const after = readSnapshot(manager, id);
43155
+ const after = readSnapshot(manager, id2);
43156
43156
  assertExistingContentPreserved(before, after);
43157
43157
  const readInserted = () => [
43158
- ...new Map(manager.listAttachmentsById(id).map((item) => [item.id, item])).values()
43158
+ ...new Map(manager.listAttachmentsById(id2).map((item) => [item.id, item])).values()
43159
43159
  ].filter((item) => !beforeAttachments.some((existing) => existing.id === item.id));
43160
43160
  let inserted = readInserted();
43161
43161
  for (let attempt = 0; attempt < 4 && (inserted.length !== 1 || returnedId && returnedId !== inserted[0].id); attempt++) {
@@ -43168,7 +43168,7 @@ function registerDirectOperations(server2, manager) {
43168
43168
  "Attachment insertion outcome uncertain; read the exact note before retrying"
43169
43169
  );
43170
43170
  const attachmentId = inserted[0].id;
43171
- const fetched = manager.getAttachmentBase64ById(id, attachmentId);
43171
+ const fetched = manager.getAttachmentBase64ById(id2, attachmentId);
43172
43172
  const actual = typeof fetched.base64 === "string" ? Buffer.from(fetched.base64, "base64") : null;
43173
43173
  if (!actual || createHash2("sha256").update(actual).digest("hex") !== createHash2("sha256").update(bytes).digest("hex"))
43174
43174
  throw new Error(
@@ -43176,7 +43176,7 @@ function registerDirectOperations(server2, manager) {
43176
43176
  );
43177
43177
  return {
43178
43178
  ok: true,
43179
- id,
43179
+ id: id2,
43180
43180
  attachmentId,
43181
43181
  contentHash: after.hash,
43182
43182
  bytes: bytes.length,
@@ -43248,7 +43248,7 @@ function addNativeTags(request, deps) {
43248
43248
  }
43249
43249
  return text.replace(/[\s\ufffc]/gu, "");
43250
43250
  };
43251
- if (after.title !== before.title || allTags.some((tag) => !after.rich.nativeTags.includes(tag)) || textWithoutTags(before.rich.text) !== textWithoutTags(after.rich.text) || linkSignature(before.rich.links) !== linkSignature(after.rich.links) || before.rich.nativeObjectIds.some((id) => !after.rich.nativeObjectIds.includes(id)) || before.rich.hasChecklist !== after.rich.hasChecklist) {
43251
+ if (after.title !== before.title || allTags.some((tag) => !after.rich.nativeTags.includes(tag)) || textWithoutTags(before.rich.text) !== textWithoutTags(after.rich.text) || linkSignature(before.rich.links) !== linkSignature(after.rich.links) || before.rich.nativeObjectIds.some((id2) => !after.rich.nativeObjectIds.includes(id2)) || before.rich.hasChecklist !== after.rich.hasChecklist) {
43252
43252
  throw new Error(
43253
43253
  "Shortcuts ran, but exact-ID tags/text/links readback was not verified. Read the note before any retry"
43254
43254
  );
@@ -43335,20 +43335,20 @@ function registerNativeTagsBridge(server2, manager) {
43335
43335
  })
43336
43336
  );
43337
43337
  }
43338
- const read = (id) => {
43339
- const note = manager.getNoteById(id);
43338
+ const read = (id2) => {
43339
+ const note = manager.getNoteById(id2);
43340
43340
  if (!note) throw new Error("Note not found");
43341
43341
  if (note.passwordProtected) throw new Error("Locked notes cannot receive native tags");
43342
- const body = manager.getNoteContentById(id);
43342
+ const body = manager.getNoteContentById(id2);
43343
43343
  if (!body) throw new Error("Note content is unavailable");
43344
- const enriched = enrichNoteRead(id, body);
43345
- const rich = readRichNote(id);
43344
+ const enriched = enrichNoteRead(id2, body);
43345
+ const rich = readRichNote(id2);
43346
43346
  if (!enriched.complete || enriched.revision !== rich.revision)
43347
43347
  throw new Error("Native metadata changed during read; read the note again");
43348
43348
  return {
43349
43349
  contentHash: richContentHash(body, enriched),
43350
43350
  title: note.title,
43351
- plaintext: manager.getNotePlaintextById(id),
43351
+ plaintext: manager.getNotePlaintextById(id2),
43352
43352
  rich
43353
43353
  };
43354
43354
  };
@@ -43367,10 +43367,10 @@ function registerNativeTagsBridge(server2, manager) {
43367
43367
  scopeText: external_exports.string().min(12).max(500),
43368
43368
  tags: external_exports.array(external_exports.string().min(1).max(101)).min(1).max(100)
43369
43369
  },
43370
- ({ id, expectedContentHash, scopeText, tags }) => {
43371
- const initial = read(id);
43370
+ ({ id: id2, expectedContentHash, scopeText, tags }) => {
43371
+ const initial = read(id2);
43372
43372
  const result = addNativeTags(
43373
- { id, expectedContentHash, scopeText, tags, title: initial.title },
43373
+ { id: id2, expectedContentHash, scopeText, tags, title: initial.title },
43374
43374
  {
43375
43375
  read,
43376
43376
  candidates: (title, scope) => manager.listAccounts().flatMap(
@@ -43381,7 +43381,676 @@ function registerNativeTagsBridge(server2, manager) {
43381
43381
  run: runNativeTagsShortcut
43382
43382
  }
43383
43383
  );
43384
- return { ok: true, id, ...result };
43384
+ return { ok: true, id: id2, ...result };
43385
+ }
43386
+ );
43387
+ }
43388
+
43389
+ // src/services/backgroundNotes.ts
43390
+ import { execFileSync as execFileSync7 } from "node:child_process";
43391
+ import { mkdtempSync as mkdtempSync4, writeFileSync as writeFileSync3, rmSync as rmSync4 } from "node:fs";
43392
+ import { tmpdir as tmpdir4 } from "node:os";
43393
+ import { join as join10 } from "node:path";
43394
+
43395
+ // src/utils/appendMarkdown.ts
43396
+ var escape2 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
43397
+ function appendMarkdownHtml(markdown) {
43398
+ if (markdown.includes("\uE000") || markdown.includes("\uE001"))
43399
+ throw new Error("Unsupported reserved characters");
43400
+ if (Array.from(markdown).some((c) => c.charCodeAt(0) < 32 && !["\n", "\r", " "].includes(c)))
43401
+ throw new Error("Unsupported control characters");
43402
+ if (/[`~|]|^#{4,}\s|^\s*>|^\s*\[.+\]:|!\[|<\/?[a-z]/im.test(markdown))
43403
+ throw new Error(
43404
+ "Markdown append supports paragraphs, headings, flat lists, emphasis and inline links; use semantic HTML for other formatting"
43405
+ );
43406
+ const inline = (text) => {
43407
+ const links = [];
43408
+ let value = text.replace(/\[([^\]\n]+)\]\(([^()\s]+)\)/g, (_s, label, url) => {
43409
+ if (!/^(https?:\/\/|notes:\/\/|applenotes:|mailto:)/i.test(url))
43410
+ throw new Error("Unsupported Markdown link URL");
43411
+ links.push(`<a href="${escape2(url)}">${escape2(label)}</a>`);
43412
+ return `\uE000${links.length - 1}\uE001`;
43413
+ });
43414
+ value = escape2(value).replace(/\*\*([^*\n]+)\*\*/g, "<b>$1</b>").replace(/\*([^*\n]+)\*/g, "<i>$1</i>");
43415
+ if (value.includes("[") || value.includes("]") || value.includes("*"))
43416
+ throw new Error("Unsupported or unbalanced Markdown inline syntax");
43417
+ return value.replace(/\uE000(\d+)\uE001/g, (_s, i) => links[Number(i)]);
43418
+ };
43419
+ let html = "", list;
43420
+ const close = () => {
43421
+ if (list) {
43422
+ html += `</${list}>`;
43423
+ list = void 0;
43424
+ }
43425
+ };
43426
+ for (const line of markdown.replace(/\r\n/g, "\n").split("\n")) {
43427
+ if (/^\s{2,}\S/.test(line)) throw new Error("Nested lists and indented code are unsupported");
43428
+ const heading = /^(#{1,3})\s+(.+)$/.exec(line), item = /^(?:([-+*])|\d+\.)\s+(.+)$/.exec(line);
43429
+ if (item) {
43430
+ const kind = item[1] ? "ul" : "ol";
43431
+ if (list !== kind) {
43432
+ close();
43433
+ list = kind;
43434
+ html += `<${kind}>`;
43435
+ }
43436
+ html += `<li>${inline(item[2])}</li>`;
43437
+ continue;
43438
+ }
43439
+ close();
43440
+ html += heading ? `<h${heading[1].length}>${inline(heading[2])}</h${heading[1].length}>` : line.trim() ? `<div>${inline(line)}</div>` : "<div><br></div>";
43441
+ }
43442
+ close();
43443
+ return html;
43444
+ }
43445
+
43446
+ // src/services/backgroundNotes.ts
43447
+ var BACKGROUND_SHORTCUT = "Apple Notes MCP - Background Operations v5";
43448
+ var backgroundStatus = () => nativeTagsStatus(process.env.APPLE_NOTES_MCP_BACKGROUND_SHORTCUT || BACKGROUND_SHORTCUT);
43449
+ var nativeTagBridgeStatus = () => nativeTagsStatus();
43450
+ function readBackgroundSnapshot(manager, id2) {
43451
+ if (!/^x-coredata:\/\/[0-9a-f-]+\/ICNote\/p\d+$/i.test(id2))
43452
+ throw new Error("Exact note ID required");
43453
+ const note = manager.getNoteById(id2);
43454
+ if (!note) throw new Error("Note not found");
43455
+ if (note.passwordProtected) throw new Error("Locked notes are unavailable in background mode");
43456
+ const html = manager.getNoteContentById(id2);
43457
+ const enriched = enrichNoteRead(id2, html);
43458
+ const rich = readRichNote(id2);
43459
+ if (enriched.revision !== rich.revision)
43460
+ throw new Error("Note changed during read; read it again");
43461
+ return {
43462
+ id: id2,
43463
+ title: note.title,
43464
+ hash: richContentHash(html, enriched),
43465
+ html,
43466
+ rich,
43467
+ pinned: getNoteMetadata(id2).metadata?.pinned,
43468
+ checklist: getChecklistItems(id2).items || []
43469
+ };
43470
+ }
43471
+ function validateAppendContent(content, format) {
43472
+ if (!content || content.length > 1024 * 1024 || content.includes("\0"))
43473
+ throw new Error("Invalid append content (limit 1 MiB)");
43474
+ if (format === "html") {
43475
+ const allowed = /* @__PURE__ */ new Set([
43476
+ "div",
43477
+ "p",
43478
+ "br",
43479
+ "b",
43480
+ "strong",
43481
+ "i",
43482
+ "em",
43483
+ "u",
43484
+ "s",
43485
+ "del",
43486
+ "h1",
43487
+ "h2",
43488
+ "h3",
43489
+ "ul",
43490
+ "ol",
43491
+ "li",
43492
+ "a",
43493
+ "table",
43494
+ "thead",
43495
+ "tbody",
43496
+ "tr",
43497
+ "td",
43498
+ "th"
43499
+ ]);
43500
+ for (const tag of content.matchAll(/<\/?\s*([a-z][a-z0-9]*)\b([^>]*)>/gi)) {
43501
+ if (!allowed.has(tag[1].toLowerCase()))
43502
+ throw new Error(`Unsupported HTML element: ${tag[1]}`);
43503
+ let attrs = tag[2].replace(/\/$/, "").trim();
43504
+ if (tag[1].toLowerCase() === "a")
43505
+ attrs = attrs.replace(/\bhref\s*=\s*(["'])(.*?)\1/gi, (_s, _q, url) => {
43506
+ if (!/^(https?:\/\/|notes:\/\/|applenotes:|mailto:)/i.test(url) || Array.from(url).some((c) => c.charCodeAt(0) < 33))
43507
+ throw new Error("Unsupported link URL");
43508
+ return "";
43509
+ });
43510
+ if (attrs.trim())
43511
+ throw new Error(
43512
+ "Unsupported HTML attributes; use semantic formatting and explicit blank paragraphs"
43513
+ );
43514
+ }
43515
+ if (/<!--|<!|<\?|<[^>]*$/u.test(content)) throw new Error("Unsupported HTML markup");
43516
+ }
43517
+ if (format === "markdown" && /!\[|<\/?[a-z]|\]\(\s*(?:javascript|data|file):/i.test(content))
43518
+ throw new Error("Markdown images, raw HTML and local/executable links are unsupported");
43519
+ }
43520
+ function runBackgroundShortcut(input) {
43521
+ const status = backgroundStatus();
43522
+ if (!status.installed)
43523
+ throw new Error("Install the supplied Background Operations shortcut once");
43524
+ const directory = mkdtempSync4(join10(tmpdir4(), "apple-notes-background-"));
43525
+ try {
43526
+ const file = join10(directory, "request.json");
43527
+ writeFileSync3(
43528
+ file,
43529
+ JSON.stringify({
43530
+ operation: "",
43531
+ title: "",
43532
+ scopeText: "",
43533
+ text: "",
43534
+ objectId: "",
43535
+ objectName: "",
43536
+ change: "",
43537
+ otherTitle: "",
43538
+ otherScope: "",
43539
+ tag: "",
43540
+ size: "",
43541
+ ...input
43542
+ }),
43543
+ { mode: 384 }
43544
+ );
43545
+ execFileSync7("/usr/bin/shortcuts", ["run", status.identifier, "--input-path", file], {
43546
+ encoding: "utf8",
43547
+ timeout: 6e4,
43548
+ maxBuffer: 1024 * 1024,
43549
+ stdio: ["ignore", "pipe", "pipe"]
43550
+ });
43551
+ } finally {
43552
+ rmSync4(directory, { recursive: true, force: true });
43553
+ }
43554
+ }
43555
+ function backgroundDependencies(manager) {
43556
+ return {
43557
+ read: (id2) => readBackgroundSnapshot(manager, id2),
43558
+ run: runBackgroundShortcut,
43559
+ candidates: (title, scope) => manager.listAccounts().flatMap(
43560
+ (account) => manager.searchNotes(title, false, account.name).filter(
43561
+ (note) => note.title === title && !note.passwordProtected && manager.getNotePlaintextById(note.id).includes(scope)
43562
+ ).map((note) => note.id)
43563
+ )
43564
+ };
43565
+ }
43566
+ function assertPreserved(before, after, options = {}) {
43567
+ if (before.id !== after.id || before.title !== after.title)
43568
+ throw new Error("Note identity changed");
43569
+ const tidy = (s) => s.replace(/\r\n/g, "\n").replace(/[\s\ufffc]+$/gu, "");
43570
+ let oldText = tidy(before.rich.text), newText = tidy(after.rich.text);
43571
+ if (options.tagChange) {
43572
+ const escaped = options.tagChange.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
43573
+ const strip = (s) => s.replace(new RegExp(`#${escaped}(?![\\p{L}\\p{N}_-])`, "gu"), "").replace(/[\s\ufffc]/gu, "");
43574
+ oldText = strip(oldText);
43575
+ newText = strip(newText);
43576
+ }
43577
+ if (options.append ? !newText.startsWith(oldText) : newText !== oldText)
43578
+ throw new Error("Existing note text was not preserved");
43579
+ const links = options.append ? after.rich.links.slice(0, before.rich.links.length) : after.rich.links;
43580
+ if (linkSignature(before.rich.links) !== linkSignature(links))
43581
+ throw new Error("Existing links were not preserved");
43582
+ if (!options.tagChange && before.rich.nativeObjectIds.some((id2) => !after.rich.nativeObjectIds.includes(id2)))
43583
+ throw new Error("Existing native object was lost");
43584
+ if (JSON.stringify(before.checklist) !== JSON.stringify(
43585
+ options.append ? after.checklist.slice(0, before.checklist.length) : after.checklist
43586
+ ))
43587
+ throw new Error("Existing checklist items changed");
43588
+ for (const item of before.rich.checklistItems || []) {
43589
+ const actual = after.rich.checklistItems?.find((current) => current.id === item.id);
43590
+ if (!actual || actual.text !== item.text || actual.done !== item.done)
43591
+ throw new Error("Existing checklist item identity or state changed");
43592
+ }
43593
+ if (before.rich.nativeTags.filter((t) => t !== options.tagChange).some((t) => !after.rich.nativeTags.includes(t)))
43594
+ throw new Error("Existing native tag was lost");
43595
+ const allowedRemoved = options.tagChange ? before.rich.nativeTagObjectIds?.[options.tagChange] || [] : [];
43596
+ for (const object3 of before.rich.objectData || []) {
43597
+ if (allowedRemoved.includes(object3.id)) continue;
43598
+ const actual = after.rich.objectData?.find((o) => o.id === object3.id);
43599
+ if (!actual || actual.mergeable !== object3.mergeable || actual.view !== object3.view)
43600
+ throw new Error("Existing native object content or presentation changed");
43601
+ }
43602
+ if (!options.tagChange && before.rich.styleRuns && after.rich.styleRuns) {
43603
+ const end = before.rich.text.trimEnd().length;
43604
+ for (const oldRun of before.rich.styleRuns)
43605
+ for (const newRun of after.rich.styleRuns) {
43606
+ const overlapStart = Math.max(oldRun.start, newRun.start);
43607
+ const overlapEnd = Math.min(
43608
+ end,
43609
+ oldRun.start + oldRun.length,
43610
+ newRun.start + newRun.length
43611
+ );
43612
+ if (overlapStart < overlapEnd && /[^\s\ufffc]/u.test(before.rich.text.slice(overlapStart, overlapEnd)) && oldRun.signature !== newRun.signature)
43613
+ throw new Error("Existing rich formatting changed");
43614
+ }
43615
+ }
43616
+ }
43617
+ function mutateBackground(request, operation, data, verify, deps) {
43618
+ if (request.scopeText.length < 12 || request.scopeText.length > 500 || /[\r\n\0]/u.test(request.scopeText))
43619
+ throw new Error("Use a distinctive existing single-line scope of 12\u2013500 characters");
43620
+ const before = deps.read(request.id);
43621
+ if (before.hash !== request.expectedContentHash)
43622
+ throw new Error("Note revision changed; read it again");
43623
+ if (!before.rich.text.includes(request.scopeText))
43624
+ throw new Error("Scope is absent from exact note");
43625
+ const candidates = deps.candidates(before.title, request.scopeText);
43626
+ if (candidates.length !== 1 || candidates[0] !== request.id)
43627
+ throw new Error("Ambiguous note selection; nothing changed");
43628
+ if (deps.read(request.id).hash !== before.hash)
43629
+ throw new Error("Note revision changed during preflight");
43630
+ let transportUncertain = false;
43631
+ let transportMessage = "";
43632
+ try {
43633
+ deps.run({ ...data, operation, title: before.title, scopeText: request.scopeText });
43634
+ } catch (error2) {
43635
+ transportUncertain = true;
43636
+ const detail = error2;
43637
+ transportMessage = detail?.code === "ETIMEDOUT" ? "Shortcuts timed out; check for an interactive parameter or permission request" : String(detail?.stderr || detail?.message || "Shortcuts failed").trim().slice(0, 500);
43638
+ }
43639
+ const after = deps.read(request.id);
43640
+ try {
43641
+ verify(before, after);
43642
+ } catch (error2) {
43643
+ throw new Error(
43644
+ `Operation outcome uncertain; read exact note before any retry: ${error2 instanceof Error ? error2.message : "readback failed"}${transportMessage ? "; " + transportMessage : ""}`
43645
+ );
43646
+ }
43647
+ return {
43648
+ ok: true,
43649
+ id: request.id,
43650
+ previousContentHash: before.hash,
43651
+ contentHash: after.hash,
43652
+ ...transportUncertain ? {
43653
+ transportWarning: "Transport was uncertain; exact-ID readback verified the requested result"
43654
+ } : {}
43655
+ };
43656
+ }
43657
+ function assertAppendedHtmlLinks(previousCount, links, html) {
43658
+ const remaining = links.slice(previousCount);
43659
+ for (const expected of htmlLinks(html)) {
43660
+ const index = remaining.findIndex(
43661
+ (link) => linkSignature([link]) === linkSignature([expected])
43662
+ );
43663
+ if (index < 0) throw new Error("Appended HTML link not verified");
43664
+ remaining.splice(index, 1);
43665
+ }
43666
+ }
43667
+ function assertAppendedVisibleText(beforeHtml, afterHtml, expected) {
43668
+ const before = comparableVisibleText(beforeHtml);
43669
+ const after = comparableVisibleText(afterHtml);
43670
+ if (!after.startsWith(before)) throw new Error("Appended text not verified");
43671
+ const suffix = after.slice(before.length).replace(/\s+/gu, " ").trim();
43672
+ const wanted = expected.replace(/\s+/gu, " ").trim();
43673
+ if (!suffix || !suffix.includes(wanted)) throw new Error("Appended text not verified");
43674
+ }
43675
+ function appendNative(manager, request) {
43676
+ validateAppendContent(request.content, request.format);
43677
+ if (request.format === "markdown")
43678
+ return appendNative(manager, {
43679
+ ...request,
43680
+ content: appendMarkdownHtml(request.content),
43681
+ format: "html"
43682
+ });
43683
+ if (request.format === "html" && /<table\b/i.test(request.content))
43684
+ throw new Error("Use create-table for verified native table insertion");
43685
+ const op = request.format === "plaintext" ? "append-text" : request.format === "html" ? "append-html" : "append-markdown";
43686
+ const text = request.format === "html" ? "<div><br></div>" + request.content : "\n\n" + request.content;
43687
+ return mutateBackground(
43688
+ request,
43689
+ op,
43690
+ { text },
43691
+ (before, after) => {
43692
+ assertPreserved(before, after, { append: true });
43693
+ const expected = request.format === "html" ? comparableVisibleText(request.content) : request.format === "plaintext" ? request.content : null;
43694
+ if (expected) assertAppendedVisibleText(before.html, after.html, expected);
43695
+ if (request.format === "html")
43696
+ assertAppendedHtmlLinks(before.rich.links.length, after.rich.links, request.content);
43697
+ },
43698
+ backgroundDependencies(manager)
43699
+ );
43700
+ }
43701
+ function setNativeTag(manager, request) {
43702
+ const tag = normalizeNativeTags([request.tag])[0];
43703
+ const initial = readBackgroundSnapshot(manager, request.id);
43704
+ if (initial.hash !== request.expectedContentHash)
43705
+ throw new Error("Note revision changed; read it again");
43706
+ if (initial.rich.nativeTags.includes(tag) === request.present)
43707
+ return { ok: true, id: request.id, contentHash: initial.hash, changed: false };
43708
+ const deps = backgroundDependencies(manager);
43709
+ if (request.present)
43710
+ deps.run = ({ title, scopeText }) => runNativeTagsShortcut({ title, scopeText, tags: [tag] });
43711
+ return mutateBackground(
43712
+ request,
43713
+ request.present ? "add-tag" : "remove-tag",
43714
+ { tag },
43715
+ (before, after) => {
43716
+ assertPreserved(before, after, { tagChange: tag });
43717
+ if (after.rich.nativeTags.includes(tag) !== request.present)
43718
+ throw new Error("Native tag state not verified");
43719
+ const removed = before.rich.nativeObjectIds.filter(
43720
+ (id2) => !after.rich.nativeObjectIds.includes(id2)
43721
+ );
43722
+ const allowed = request.present ? [] : before.rich.nativeTagObjectIds?.[tag] || [];
43723
+ if (removed.some((id2) => !allowed.includes(id2)))
43724
+ throw new Error("Unrelated native object was lost");
43725
+ },
43726
+ deps
43727
+ );
43728
+ }
43729
+
43730
+ // src/tools/nativeOperations.ts
43731
+ var VERIFIED_BACKGROUND = /* @__PURE__ */ new Set([
43732
+ "append-native",
43733
+ "create-checklist-item",
43734
+ "create-table",
43735
+ "insert-note-link",
43736
+ "set-note-pinned",
43737
+ "remove-native-tags",
43738
+ "replace-native-tag"
43739
+ ]);
43740
+ var LIVE_VALIDATION_BLOCKERS = {};
43741
+ var signingRefusal = "Installed Shortcuts refuses to sign this Notes action (unsupported features); no background fallback is enabled";
43742
+ var UNAVAILABLE = {
43743
+ "set-checklist-item": signingRefusal,
43744
+ "delete-checklist-item": signingRefusal,
43745
+ "set-attachment-size": signingRefusal,
43746
+ "insert-mention": signingRefusal,
43747
+ "update-table-cells": "No background cell-editing action; replacing a table would change its identity and position",
43748
+ "edit-rich-note": "Native text replacement needs current UI selection; full-body rewriting is protected",
43749
+ "smart-folders": "No supported background interface for Smart Folder rules",
43750
+ "rename-tag-globally": "Cannot update Smart Folder references in background; use replace-native-tag on explicit notes",
43751
+ "sharing-permissions": "No supported background interface for sharing invitations or permissions",
43752
+ "note-lock": "Notes lock actions require the foreground and may require user authentication",
43753
+ "record-audio": "Recording requires the Notes UI",
43754
+ "transcribe-audio": "No supported background Notes transcription action",
43755
+ "scan-and-markup": "No supported background scanning or graphical markup action"
43756
+ };
43757
+ function requireValidated(name) {
43758
+ if (!VERIFIED_BACKGROUND.has(name) && process.env.APPLE_NOTES_MCP_ALLOW_UNVERIFIED !== "1")
43759
+ throw new Error(
43760
+ UNAVAILABLE[name] || LIVE_VALIDATION_BLOCKERS[name] || `${name} has not passed live background validation in this build; see get-capabilities`
43761
+ );
43762
+ }
43763
+ var id = external_exports.string().regex(/^x-coredata:\/\/[0-9a-f-]+\/ICNote\/p\d+$/i);
43764
+ var revision3 = external_exports.string().regex(/^sha256:[a-f0-9]{64}$/);
43765
+ var common = {
43766
+ id,
43767
+ expectedContentHash: revision3,
43768
+ scopeText: external_exports.string().min(12).max(500).describe(
43769
+ "Distinctive existing phrase used by Notes search. Prefer plain words without punctuation, hashtags, or paths."
43770
+ )
43771
+ };
43772
+ var htmlEscape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
43773
+ function registerNativeOperations(server2, manager) {
43774
+ function tool(name, description, input, handler, readOnly = false) {
43775
+ server2.registerTool(
43776
+ name,
43777
+ {
43778
+ description,
43779
+ inputSchema: input,
43780
+ outputSchema: external_exports.object({ ok: external_exports.boolean().optional() }).passthrough(),
43781
+ annotations: { readOnlyHint: readOnly }
43782
+ },
43783
+ (async (args) => {
43784
+ try {
43785
+ const result = handler(args);
43786
+ return {
43787
+ content: [{ type: "text", text: JSON.stringify(result) }],
43788
+ structuredContent: result
43789
+ };
43790
+ } catch (error2) {
43791
+ return {
43792
+ content: [
43793
+ {
43794
+ type: "text",
43795
+ text: error2 instanceof Error ? error2.message : "Operation failed"
43796
+ }
43797
+ ],
43798
+ isError: true
43799
+ };
43800
+ }
43801
+ })
43802
+ );
43803
+ }
43804
+ tool(
43805
+ "get-capabilities",
43806
+ "Use when: checking native background-edit support before calling a write tool.\nReturns: bridge installation, implementation, verification, availability, and specific limitations per operation.\nDo not use when: checking only the Native Tags bridge (native-tags-status).\nSafety: read-only; does not open Notes or run a mutation.",
43807
+ {},
43808
+ () => {
43809
+ let bridge;
43810
+ try {
43811
+ bridge = backgroundStatus();
43812
+ } catch {
43813
+ bridge = {
43814
+ installed: false,
43815
+ shortcut: "Apple Notes MCP - Background Operations v5",
43816
+ error: "Shortcuts helper unavailable"
43817
+ };
43818
+ }
43819
+ const native = [
43820
+ "append-native",
43821
+ "create-checklist-item",
43822
+ "create-table",
43823
+ "set-note-pinned",
43824
+ "remove-native-tags",
43825
+ "replace-native-tag",
43826
+ "insert-note-link"
43827
+ ];
43828
+ let tagBridgeInstalled = false;
43829
+ try {
43830
+ tagBridgeInstalled = nativeTagBridgeStatus().installed;
43831
+ } catch {
43832
+ }
43833
+ return {
43834
+ bridge,
43835
+ nativeTagBridgeInstalled: tagBridgeInstalled,
43836
+ mode: "background-only",
43837
+ operations: Object.fromEntries(
43838
+ native.map((name) => [
43839
+ name,
43840
+ {
43841
+ implemented: true,
43842
+ verified: VERIFIED_BACKGROUND.has(name),
43843
+ available: VERIFIED_BACKGROUND.has(name) && (!native.includes(name) || bridge.installed) && (name !== "replace-native-tag" || tagBridgeInstalled),
43844
+ reason: !VERIFIED_BACKGROUND.has(name) ? UNAVAILABLE[name] || LIVE_VALIDATION_BLOCKERS[name] || "Live validation pending; install the shortcut and complete the isolated acceptance tests" : native.includes(name) && !bridge.installed ? "Install the supplied shortcut once" : name === "replace-native-tag" && !tagBridgeInstalled ? "Install the verified Native Tags bridge for the addition phase" : void 0
43845
+ }
43846
+ ])
43847
+ ),
43848
+ unavailable: UNAVAILABLE
43849
+ };
43850
+ },
43851
+ true
43852
+ );
43853
+ tool(
43854
+ "append-native",
43855
+ "Use when: appending formatted content to a native-object note without replacing its body.\nReturns: exact-ID preservation and appended-content readback.\nDo not use when: the existing note can be safely handled by append-to-note or the scope phrase is ambiguous.\nSafety: requires a fresh revision and unique existing scope phrase of plain words; avoid punctuation, hashtags, and paths because Notes search may not resolve them literally. Supports bounded plaintext, semantic HTML, and Markdown without external fetching or automatic retries.",
43856
+ {
43857
+ ...common,
43858
+ content: external_exports.string().min(1).max(1024 * 1024),
43859
+ format: external_exports.enum(["plaintext", "html", "markdown"]).default("plaintext")
43860
+ },
43861
+ (args) => {
43862
+ requireValidated("append-native");
43863
+ return appendNative(manager, args);
43864
+ }
43865
+ );
43866
+ tool(
43867
+ "create-checklist-item",
43868
+ "Use when: appending one real unchecked Notes checklist item.\nReturns: the created checklist identity after exact-note readback.\nDo not use when: plain text is sufficient or more than one item is requested.\nSafety: preserves existing text, links, native objects, checklist identities, and formatting.",
43869
+ {
43870
+ ...common,
43871
+ text: external_exports.string().min(1).max(1e4).refine((s) => !/[\r\n\0]/u.test(s), "One line per checklist item")
43872
+ },
43873
+ (args) => {
43874
+ requireValidated("create-checklist-item");
43875
+ const result = mutateBackground(
43876
+ args,
43877
+ "create-checklist-item",
43878
+ { text: args.text },
43879
+ (before, after) => {
43880
+ assertPreserved(before, after, { append: true });
43881
+ const added = after.checklist.slice(before.checklist.length);
43882
+ if (added.length !== 1 || added[0].text !== args.text || added[0].done)
43883
+ throw new Error("Native checklist item not verified");
43884
+ },
43885
+ backgroundDependencies(manager)
43886
+ );
43887
+ return { ...result, items: readRichNote(args.id).checklistItems };
43888
+ }
43889
+ );
43890
+ tool(
43891
+ "create-table",
43892
+ "Use when: appending one native Notes table from a rectangular array of strings.\nReturns: the native table identity and decoded cells after readback.\nDo not use when: a text table is acceptable or the rows are not rectangular.\nSafety: never substitutes text; preserves existing rich content and reports failure unless the native table is verified.",
43893
+ {
43894
+ ...common,
43895
+ rows: external_exports.array(external_exports.array(external_exports.string().max(1e4)).min(1).max(100)).min(1).max(1e3)
43896
+ },
43897
+ (args) => {
43898
+ requireValidated("create-table");
43899
+ if (args.rows.some((row) => row.length !== args.rows[0].length))
43900
+ throw new Error("Table rows must have equal cell counts");
43901
+ const before = readRichNote(args.id);
43902
+ const content = "<table>" + args.rows.map(
43903
+ (row) => "<tr>" + row.map((v) => "<td>" + htmlEscape(v) + "</td>").join("") + "</tr>"
43904
+ ).join("") + "</table>";
43905
+ const result = mutateBackground(
43906
+ args,
43907
+ "append-html",
43908
+ { text: "<div><br></div>" + content },
43909
+ (oldNote, newNote) => {
43910
+ assertPreserved(oldNote, newNote, { append: true });
43911
+ const inserted = newNote.rich.objectData?.filter(
43912
+ (o) => o.type?.includes("table") && !oldNote.rich.nativeObjectIds.includes(o.id)
43913
+ ) || [];
43914
+ if (inserted.length !== 1 || JSON.stringify(parseNoteTable(Buffer.from(inserted[0].mergeable, "hex")).rows) !== JSON.stringify(args.rows))
43915
+ throw new Error("Native table cells not verified");
43916
+ },
43917
+ backgroundDependencies(manager)
43918
+ );
43919
+ const current = readRichNote(args.id);
43920
+ const added = current.objectData?.filter(
43921
+ (obj) => obj.type?.includes("table") && !before.nativeObjectIds.includes(obj.id)
43922
+ ) || [];
43923
+ if (added.length !== 1)
43924
+ throw new Error(
43925
+ "Table result uncertain; native table not verified. Read the note before retrying"
43926
+ );
43927
+ const table = parseNoteTable(Buffer.from(added[0].mergeable, "hex"));
43928
+ if (JSON.stringify(table.rows) !== JSON.stringify(args.rows))
43929
+ throw new Error("Native table cells not verified; read before retrying");
43930
+ return { ...result, table: { id: added[0].id, ...table } };
43931
+ }
43932
+ );
43933
+ tool(
43934
+ "set-note-pinned",
43935
+ "Use when: setting one exact note's pinned state.\nReturns: the verified requested state and new revision.\nDo not use when: only reading pinned metadata (get-note-metadata).\nSafety: checks expectedPinned and a fresh content revision before changing metadata; never rewrites the body.",
43936
+ { ...common, expectedPinned: external_exports.boolean(), pinned: external_exports.boolean() },
43937
+ (args) => {
43938
+ requireValidated("set-note-pinned");
43939
+ const deps = backgroundDependencies(manager);
43940
+ const s = deps.read(args.id);
43941
+ if (s.hash !== args.expectedContentHash || s.pinned !== args.expectedPinned)
43942
+ throw new Error("Note or pinned state changed; read it again");
43943
+ if (s.pinned === args.pinned)
43944
+ return { ok: true, id: args.id, pinned: s.pinned, contentHash: s.hash, changed: false };
43945
+ const run = deps.run;
43946
+ deps.run = (input) => {
43947
+ if (deps.read(args.id).pinned !== args.expectedPinned)
43948
+ throw new Error("Pinned state changed during preflight");
43949
+ run(input);
43950
+ };
43951
+ return {
43952
+ ...mutateBackground(
43953
+ args,
43954
+ "set-pinned",
43955
+ { change: args.pinned ? "add" : "remove" },
43956
+ (before, after) => {
43957
+ assertPreserved(before, after);
43958
+ if (after.pinned !== args.pinned) throw new Error("Pinned state not verified");
43959
+ },
43960
+ deps
43961
+ ),
43962
+ pinned: args.pinned
43963
+ };
43964
+ }
43965
+ );
43966
+ tool(
43967
+ "remove-native-tags",
43968
+ "Use when: removing specified native tags from one exact note.\nReturns: verified remaining tags and new revision.\nDo not use when: deleting a global tag definition or changing Smart Folder rules.\nSafety: preserves unrelated tags and native objects and never retries an uncertain mutation.",
43969
+ { ...common, tags: external_exports.array(external_exports.string().min(1).max(101)).min(1).max(100) },
43970
+ (args) => {
43971
+ requireValidated("remove-native-tags");
43972
+ let hash = args.expectedContentHash;
43973
+ const completed = [];
43974
+ for (const tag of normalizeNativeTags(args.tags)) {
43975
+ try {
43976
+ const result = setNativeTag(manager, {
43977
+ ...args,
43978
+ expectedContentHash: hash,
43979
+ tag,
43980
+ present: false
43981
+ });
43982
+ hash = result.contentHash;
43983
+ completed.push(tag);
43984
+ } catch (error2) {
43985
+ throw new Error(
43986
+ `Stopped after tags ${JSON.stringify(completed)}; read exact note before retry: ${String(error2)}`
43987
+ );
43988
+ }
43989
+ }
43990
+ return { ok: true, id: args.id, removed: completed, contentHash: hash };
43991
+ }
43992
+ );
43993
+ tool(
43994
+ "replace-native-tag",
43995
+ "Use when: replacing one native tag across an explicit list of freshly read notes.\nReturns: per-note results and remaining work after any failure.\nDo not use when: renaming global tag definitions or Smart Folder rules.\nSafety: adds and verifies the new tag before removing the old one and stops on the first uncertain result.",
43996
+ {
43997
+ notes: external_exports.array(external_exports.object(common)).min(1).max(100),
43998
+ oldTag: external_exports.string().min(1).max(101),
43999
+ newTag: external_exports.string().min(1).max(101)
44000
+ },
44001
+ (args) => {
44002
+ requireValidated("replace-native-tag");
44003
+ const [oldTag] = normalizeNativeTags([args.oldTag]);
44004
+ const [newTag] = normalizeNativeTags([args.newTag]);
44005
+ if (new Set(args.notes.map((n) => n.id)).size !== args.notes.length)
44006
+ throw new Error("Duplicate note IDs");
44007
+ for (const n of args.notes)
44008
+ if (readBackgroundSnapshot(manager, n.id).hash !== n.expectedContentHash)
44009
+ throw new Error("Note revision changed; no replacement started");
44010
+ const results = [];
44011
+ for (const n of args.notes) {
44012
+ try {
44013
+ const initial = readBackgroundSnapshot(manager, n.id);
44014
+ if (!initial.rich.nativeTags.includes(oldTag) || oldTag === newTag) {
44015
+ results.push({ id: n.id, changed: false });
44016
+ continue;
44017
+ }
44018
+ const added = setNativeTag(manager, { ...n, tag: newTag, present: true });
44019
+ const removed = setNativeTag(manager, {
44020
+ ...n,
44021
+ expectedContentHash: added.contentHash,
44022
+ tag: oldTag,
44023
+ present: false
44024
+ });
44025
+ results.push(removed);
44026
+ } catch (error2) {
44027
+ results.push({ id: n.id, ok: false, error: String(error2) });
44028
+ return { ok: false, results, remaining: args.notes.length - results.length };
44029
+ }
44030
+ }
44031
+ return { ok: true, results };
44032
+ }
44033
+ );
44034
+ tool(
44035
+ "insert-note-link",
44036
+ "Use when: appending a real Notes deep link to a native-object note.\nReturns: verified link destination and label after exact-note readback.\nDo not use when: only retrieving a deep link (get-note-link).\nSafety: retrieves the real target URL, preserves existing rich content, and creates a static label rather than a dynamic-title object.",
44037
+ { ...common, linkedNoteId: id, label: external_exports.string().min(1).max(2e3).optional() },
44038
+ (args) => {
44039
+ requireValidated("insert-note-link");
44040
+ const link = manager.getNoteLinkById(args.linkedNoteId);
44041
+ if (!link) throw new Error("Real Notes link unavailable");
44042
+ const linked = manager.getNoteById(args.linkedNoteId);
44043
+ if (!linked) throw new Error("Linked note not found");
44044
+ const result = appendNative(manager, {
44045
+ ...args,
44046
+ content: `<div><a href="${htmlEscape(link)}">${htmlEscape(args.label || linked.title)}</a></div>`,
44047
+ format: "html"
44048
+ });
44049
+ if (!readRichNote(args.id).links.some(
44050
+ (l) => l.url === link && l.text === (args.label || linked.title)
44051
+ ))
44052
+ throw new Error("Link result uncertain; read note before retrying");
44053
+ return result;
43385
44054
  }
43386
44055
  );
43387
44056
  }
@@ -43398,6 +44067,7 @@ var server = new McpServer({
43398
44067
  var notesManager = new AppleNotesManager();
43399
44068
  registerDirectOperations(server, notesManager);
43400
44069
  registerNativeTagsBridge(server, notesManager);
44070
+ registerNativeOperations(server, notesManager);
43401
44071
  function successResponse(message, structured) {
43402
44072
  const res = { content: [{ type: "text", text: message }] };
43403
44073
  if (structured) res.structuredContent = structured;
@@ -43445,17 +44115,17 @@ var noteIdInput = external_exports.string().min(1, "Note ID is required").max(MA
43445
44115
  var expectedContentHashInput = external_exports.string().regex(/^sha256:[a-f0-9]{64}$/, "expectedContentHash must come from get-note-content").describe(
43446
44116
  "Revision token returned by get-note-content for this exact ID. The mutation stops if the note changed since that read."
43447
44117
  );
43448
- function readExactNoteSnapshot(id) {
43449
- const note = notesManager.getNoteById(id);
43450
- if (!note) return { error: `Note with ID "${id}" not found` };
44118
+ function readExactNoteSnapshot(id2) {
44119
+ const note = notesManager.getNoteById(id2);
44120
+ if (!note) return { error: `Note with ID "${id2}" not found` };
43451
44121
  if (note.passwordProtected) {
43452
44122
  return {
43453
44123
  error: `Note "${note.title}" is password-protected and cannot be changed. Unlock it in Notes.app first.`
43454
44124
  };
43455
44125
  }
43456
- const body = notesManager.getNoteContentById(id);
44126
+ const body = notesManager.getNoteContentById(id2);
43457
44127
  if (!body) return { error: `Failed to read content of note "${note.title}"` };
43458
- const rich = enrichNoteRead(id, body);
44128
+ const rich = enrichNoteRead(id2, body);
43459
44129
  return { note, body, rich, contentHash: richContentHash(body, rich) };
43460
44130
  }
43461
44131
  function revisionConflictMessage(title) {
@@ -43636,28 +44306,28 @@ registerTool(
43636
44306
  truncated: external_exports.boolean().optional()
43637
44307
  }
43638
44308
  },
43639
- withErrorHandling(({ id, title, account }) => {
43640
- if (id) {
43641
- const note2 = notesManager.getNoteById(id);
44309
+ withErrorHandling(({ id: id2, title, account }) => {
44310
+ if (id2) {
44311
+ const note2 = notesManager.getNoteById(id2);
43642
44312
  if (!note2) {
43643
- return errorResponse(`Note with ID "${id}" not found`);
44313
+ return errorResponse(`Note with ID "${id2}" not found`);
43644
44314
  }
43645
44315
  if (note2.passwordProtected) {
43646
44316
  return errorResponse(
43647
44317
  `Note "${note2.title}" is password-protected and cannot be read. Unlock it in Notes.app first.`
43648
44318
  );
43649
44319
  }
43650
- const rawContent2 = notesManager.getNoteContentById(id);
44320
+ const rawContent2 = notesManager.getNoteContentById(id2);
43651
44321
  if (!rawContent2) {
43652
44322
  return errorResponse(`Failed to read content of note "${note2.title}"`);
43653
44323
  }
43654
- const rich2 = enrichNoteRead(id, rawContent2);
44324
+ const rich2 = enrichNoteRead(id2, rawContent2);
43655
44325
  const stripped2 = stripLargeInlineImages(rich2.content);
43656
44326
  const content2 = stripped2.html;
43657
44327
  const hashtags2 = parseHashtags(content2);
43658
44328
  const warning2 = [strippedImagesWarning(stripped2), rich2.warning].filter(Boolean).join("\n\n");
43659
44329
  return successResponse(warning2 ? content2 + warning2 : content2, {
43660
- id,
44330
+ id: id2,
43661
44331
  title: note2.title,
43662
44332
  content: content2,
43663
44333
  contentHash: richContentHash(rawContent2, rich2),
@@ -43665,6 +44335,11 @@ registerTool(
43665
44335
  nativeTags: rich2.nativeTags,
43666
44336
  richContentComplete: rich2.complete,
43667
44337
  writable: rich2.writable && stripped2.strippedCount === 0,
44338
+ supportedOperations: {
44339
+ fullBodyReplace: rich2.writable && stripped2.strippedCount === 0,
44340
+ nativeAppendImplemented: VERIFIED_BACKGROUND.has("append-native"),
44341
+ requiresShortcut: !rich2.writable
44342
+ },
43668
44343
  warning: rich2.warning,
43669
44344
  hashtags: hashtags2,
43670
44345
  strippedImages: stripped2.strippedCount,
@@ -43701,6 +44376,11 @@ registerTool(
43701
44376
  nativeTags: rich.nativeTags,
43702
44377
  richContentComplete: rich.complete,
43703
44378
  writable: rich.writable && stripped.strippedCount === 0,
44379
+ supportedOperations: {
44380
+ fullBodyReplace: rich.writable && stripped.strippedCount === 0,
44381
+ nativeAppendImplemented: VERIFIED_BACKGROUND.has("append-native"),
44382
+ requiresShortcut: !rich.writable
44383
+ },
43704
44384
  warning: rich.warning,
43705
44385
  hashtags,
43706
44386
  strippedImages: stripped.strippedCount,
@@ -43724,18 +44404,18 @@ registerTool(
43724
44404
  plaintext: external_exports.string().optional()
43725
44405
  }
43726
44406
  },
43727
- withErrorHandling(({ id, title, account }) => {
43728
- if (id) {
43729
- const note2 = notesManager.getNoteById(id);
44407
+ withErrorHandling(({ id: id2, title, account }) => {
44408
+ if (id2) {
44409
+ const note2 = notesManager.getNoteById(id2);
43730
44410
  if (!note2) {
43731
- return errorResponse(`Note with ID "${id}" not found`);
44411
+ return errorResponse(`Note with ID "${id2}" not found`);
43732
44412
  }
43733
44413
  if (note2.passwordProtected) {
43734
44414
  return errorResponse(
43735
44415
  `Note "${note2.title}" is password-protected and cannot be read. Unlock it in Notes.app first.`
43736
44416
  );
43737
44417
  }
43738
- const plaintext2 = notesManager.getNotePlaintextById(id);
44418
+ const plaintext2 = notesManager.getNotePlaintextById(id2);
43739
44419
  if (!plaintext2) {
43740
44420
  return errorResponse(`Failed to read plaintext of note "${note2.title}"`);
43741
44421
  }
@@ -43776,10 +44456,10 @@ registerTool(
43776
44456
  passwordProtected: external_exports.boolean().optional()
43777
44457
  }
43778
44458
  },
43779
- withErrorHandling(({ id }) => {
43780
- const note = notesManager.getNoteById(id);
44459
+ withErrorHandling(({ id: id2 }) => {
44460
+ const note = notesManager.getNoteById(id2);
43781
44461
  if (!note) {
43782
- return errorResponse(`Note with ID "${id}" not found`);
44462
+ return errorResponse(`Note with ID "${id2}" not found`);
43783
44463
  }
43784
44464
  const metadata = {
43785
44465
  id: note.id,
@@ -43837,12 +44517,12 @@ registerTool(
43837
44517
  separately: external_exports.boolean().optional()
43838
44518
  }
43839
44519
  },
43840
- withErrorHandling(({ id, separately = false }) => {
43841
- const success = notesManager.showNoteById(id, separately);
44520
+ withErrorHandling(({ id: id2, separately = false }) => {
44521
+ const success = notesManager.showNoteById(id2, separately);
43842
44522
  if (!success) {
43843
- return errorResponse(`Failed to show note with ID "${id}"`);
44523
+ return errorResponse(`Failed to show note with ID "${id2}"`);
43844
44524
  }
43845
- return successResponse(`Shown note with ID "${id}" in Notes.app`, { id, separately });
44525
+ return successResponse(`Shown note with ID "${id2}" in Notes.app`, { id: id2, separately });
43846
44526
  }, "Error showing note")
43847
44527
  );
43848
44528
  registerTool(
@@ -43860,24 +44540,24 @@ registerTool(
43860
44540
  url: external_exports.string().optional()
43861
44541
  }
43862
44542
  },
43863
- withErrorHandling(({ id, title, account }) => {
43864
- if (id) {
43865
- const note2 = notesManager.getNoteById(id);
44543
+ withErrorHandling(({ id: id2, title, account }) => {
44544
+ if (id2) {
44545
+ const note2 = notesManager.getNoteById(id2);
43866
44546
  if (!note2) {
43867
- return errorResponse(`Note with ID "${id}" not found`);
44547
+ return errorResponse(`Note with ID "${id2}" not found`);
43868
44548
  }
43869
44549
  if (note2.passwordProtected) {
43870
44550
  return errorResponse(
43871
44551
  `Note "${note2.title}" is password-protected. Unlock it in Notes.app first.`
43872
44552
  );
43873
44553
  }
43874
- const url2 = notesManager.getNoteLinkById(id);
44554
+ const url2 = notesManager.getNoteLinkById(id2);
43875
44555
  if (!url2) {
43876
44556
  return errorResponse(
43877
44557
  `Failed to get note link for "${note2.title}". The Notes database may not be accessible \u2014 grant Full Disk Access to the app that launches the server, fully quit and relaunch, then run the doctor tool. See: ${FULL_DISK_ACCESS_GUIDE_URL}. (On macOS 12\u201315 this also falls back to the AppleScript note link property.)`
43878
44558
  );
43879
44559
  }
43880
- return successResponse(`Note link: ${url2}`, { id, title: note2.title, url: url2 });
44560
+ return successResponse(`Note link: ${url2}`, { id: id2, title: note2.title, url: url2 });
43881
44561
  }
43882
44562
  if (!title) {
43883
44563
  return errorResponse("Either 'id' or 'title' is required");
@@ -43913,12 +44593,12 @@ registerTool(
43913
44593
  separately: external_exports.boolean().optional()
43914
44594
  }
43915
44595
  },
43916
- withErrorHandling(({ id, separately = false }) => {
43917
- const success = notesManager.showFolderById(id, separately);
44596
+ withErrorHandling(({ id: id2, separately = false }) => {
44597
+ const success = notesManager.showFolderById(id2, separately);
43918
44598
  if (!success) {
43919
- return errorResponse(`Failed to show folder with ID "${id}"`);
44599
+ return errorResponse(`Failed to show folder with ID "${id2}"`);
43920
44600
  }
43921
- return successResponse(`Shown folder with ID "${id}" in Notes.app`, { id, separately });
44601
+ return successResponse(`Shown folder with ID "${id2}" in Notes.app`, { id: id2, separately });
43922
44602
  }, "Error showing folder")
43923
44603
  );
43924
44604
  registerTool(
@@ -43934,12 +44614,12 @@ registerTool(
43934
44614
  separately: external_exports.boolean().optional()
43935
44615
  }
43936
44616
  },
43937
- withErrorHandling(({ id, separately = false }) => {
43938
- const success = notesManager.showAccountById(id, separately);
44617
+ withErrorHandling(({ id: id2, separately = false }) => {
44618
+ const success = notesManager.showAccountById(id2, separately);
43939
44619
  if (!success) {
43940
- return errorResponse(`Failed to show account with ID "${id}"`);
44620
+ return errorResponse(`Failed to show account with ID "${id2}"`);
43941
44621
  }
43942
- return successResponse(`Shown account with ID "${id}" in Notes.app`, { id, separately });
44622
+ return successResponse(`Shown account with ID "${id2}" in Notes.app`, { id: id2, separately });
43943
44623
  }, "Error showing account")
43944
44624
  );
43945
44625
  registerTool(
@@ -43958,17 +44638,17 @@ registerTool(
43958
44638
  },
43959
44639
  annotations: { readOnlyHint: true }
43960
44640
  },
43961
- withErrorHandling(({ id }) => {
43962
- const note = notesManager.getNoteById(id);
43963
- if (!note) return errorResponse(`Note with ID "${id}" not found`);
43964
- const body = notesManager.getNoteContentById(id);
44641
+ withErrorHandling(({ id: id2 }) => {
44642
+ const note = notesManager.getNoteById(id2);
44643
+ if (!note) return errorResponse(`Note with ID "${id2}" not found`);
44644
+ const body = notesManager.getNoteContentById(id2);
43965
44645
  if (!body) return errorResponse(`Failed to read content of note "${note.title}"`);
43966
- const rich = readRichNote(id);
44646
+ const rich = readRichNote(id2);
43967
44647
  const tables = (rich.objectData || []).filter((object3) => object3.type?.includes("table")).map((object3) => {
43968
44648
  try {
43969
44649
  return {
43970
44650
  id: object3.id,
43971
- attachmentId: id.replace(/ICNote\/p\d+$/, `ICAttachment/p${object3.pk}`),
44651
+ attachmentId: id2.replace(/ICNote\/p\d+$/, `ICAttachment/p${object3.pk}`),
43972
44652
  complete: true,
43973
44653
  ...parseNoteTable(Buffer.from(object3.mergeable, "hex"))
43974
44654
  };
@@ -43994,7 +44674,7 @@ registerTool(
43994
44674
  revision: rich.revision
43995
44675
  };
43996
44676
  return successResponse("Native objects read from the exact note", {
43997
- id,
44677
+ id: id2,
43998
44678
  contentHash: richContentHash(body, richRead),
43999
44679
  objects: rich.objects,
44000
44680
  checklistItems: rich.checklistItems,
@@ -44066,27 +44746,27 @@ registerTool(
44066
44746
  },
44067
44747
  withErrorHandling(
44068
44748
  ({
44069
- id,
44749
+ id: id2,
44070
44750
  expectedContentHash,
44071
44751
  newTitle,
44072
44752
  newContent,
44073
44753
  format = "plaintext",
44074
44754
  allowLinkChanges = false
44075
44755
  }) => {
44076
- const snapshot = readExactNoteSnapshot(id);
44756
+ const snapshot = readExactNoteSnapshot(id2);
44077
44757
  if ("error" in snapshot) return errorResponse(snapshot.error);
44078
44758
  if (snapshot.contentHash !== expectedContentHash) {
44079
44759
  return errorResponse(revisionConflictMessage(snapshot.note.title));
44080
44760
  }
44081
44761
  assertLinkedWrite(snapshot.rich, newContent, format, allowLinkChanges);
44082
- const attachments = notesManager.listAttachmentsById(id);
44762
+ const attachments = notesManager.listAttachmentsById(id2);
44083
44763
  if (attachments.length > 0) {
44084
44764
  return errorResponse(
44085
44765
  `Note "${snapshot.note.title}" has ${attachments.length} attachment(s). Full-body replacement is blocked; edit it in Notes.app.`
44086
44766
  );
44087
44767
  }
44088
44768
  const result = notesManager.updateNoteByIdIfUnchanged(
44089
- id,
44769
+ id2,
44090
44770
  snapshot.note.title,
44091
44771
  snapshot.body,
44092
44772
  newTitle,
@@ -44107,8 +44787,8 @@ registerTool(
44107
44787
  `The update result for note "${snapshot.note.title}" is uncertain. Read the exact ID before retrying.`
44108
44788
  );
44109
44789
  }
44110
- const readback = notesManager.getNoteContentById(id);
44111
- const richReadback = enrichNoteRead(id, readback || "");
44790
+ const readback = notesManager.getNoteContentById(id2);
44791
+ const richReadback = enrichNoteRead(id2, readback || "");
44112
44792
  const contentHash = readback ? richContentHash(readback, richReadback) : "";
44113
44793
  if (!richReadback.complete || linkSignature(richReadback.links) !== linkSignature(htmlLinks(result.writtenBody))) {
44114
44794
  return errorResponse(
@@ -44117,7 +44797,7 @@ registerTool(
44117
44797
  }
44118
44798
  if (!readback || comparableVisibleText(readback) !== comparableVisibleText(result.writtenBody)) {
44119
44799
  return errorResponse(
44120
- `The note accepted an update, but exact-ID readback visible text did not match. Do not retry automatically; inspect note ID ${id} in Notes.app.`
44800
+ `The note accepted an update, but exact-ID readback visible text did not match. Do not retry automatically; inspect note ID ${id2} in Notes.app.`
44121
44801
  );
44122
44802
  }
44123
44803
  const displayTitle = resolveUpdateResponseTitle(
@@ -44129,10 +44809,10 @@ registerTool(
44129
44809
  const sharedWarning = snapshot.note.shared ? "\n\n\u26A0\uFE0F This note is shared with collaborators. Your changes are visible to them." : "";
44130
44810
  const checklistWarning = detectChecklistAttempt(newContent) ?? "";
44131
44811
  return successResponse(
44132
- `Note updated; visible text verified: "${displayTitle}" [id: ${id}]${sharedWarning}${checklistWarning}`,
44812
+ `Note updated; visible text verified: "${displayTitle}" [id: ${id2}]${sharedWarning}${checklistWarning}`,
44133
44813
  {
44134
44814
  ok: true,
44135
- id,
44815
+ id: id2,
44136
44816
  title: displayTitle,
44137
44817
  shared: snapshot.note.shared ?? false,
44138
44818
  previousContentHash: expectedContentHash,
@@ -44147,11 +44827,12 @@ registerTool(
44147
44827
  registerTool(
44148
44828
  "append-to-note",
44149
44829
  {
44150
- description: "Use when: adding content to one exact note after reading it by id.\nReturns: exact id, new content hash, and visible-text readback verification.\nDo not use when: you only have a title, the note changed since the read, or it has attachments or native objects.\nSafety: append rewrites the HTML body, so it uses exact-ID, rich revision, native-object, attachment, link, and readback guards. Notes.app normalizes HTML, so rich formatting is not claimed as byte-identical.",
44830
+ description: "Use when: adding content to one exact note after reading it by id.\nReturns: exact id, new content hash, and visible-text readback verification.\nDo not use when: you only have a title or the note changed since the read.\nSafety: protected native-object notes use native end-append with scopeText; ordinary notes retain guarded HTML editing. Notes.app normalizes HTML, so rich formatting is not claimed as byte-identical.",
44151
44831
  inputSchema: {
44152
44832
  id: noteIdInput,
44153
44833
  expectedContentHash: expectedContentHashInput,
44154
44834
  content: external_exports.string().min(1, "Content to append is required").max(MAX.CONTENT).describe("Text to append to the note body"),
44835
+ scopeText: external_exports.string().min(12).max(500).optional().describe("Existing unique phrase required for native append to protected notes"),
44155
44836
  position: external_exports.enum(["after", "before"]).optional().default("after").describe(
44156
44837
  "Where to insert: 'after' appends to the end (default), 'before' prepends to the start"
44157
44838
  ),
@@ -44170,12 +44851,13 @@ registerTool(
44170
44851
  },
44171
44852
  withErrorHandling(
44172
44853
  ({
44173
- id,
44854
+ id: id2,
44174
44855
  expectedContentHash,
44175
44856
  content,
44176
44857
  position = "after",
44177
44858
  separator = "\n\n",
44178
- format = "plaintext"
44859
+ format = "plaintext",
44860
+ scopeText
44179
44861
  }) => {
44180
44862
  const contentToHtml = (text) => {
44181
44863
  if (format === "html") return text;
@@ -44190,17 +44872,32 @@ registerTool(
44190
44872
  const escaped = sep2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
44191
44873
  return `<div>${escaped}</div>`;
44192
44874
  };
44193
- const snapshot = readExactNoteSnapshot(id);
44875
+ const snapshot = readExactNoteSnapshot(id2);
44194
44876
  if ("error" in snapshot) return errorResponse(snapshot.error);
44195
44877
  if (snapshot.contentHash !== expectedContentHash) {
44196
44878
  return errorResponse(revisionConflictMessage(snapshot.note.title));
44197
44879
  }
44198
44880
  if (!snapshot.rich.writable) {
44199
- return errorResponse(
44200
- snapshot.rich.warning || `Note "${snapshot.note.title}" contains native objects that cannot be preserved by a full-body append.`
44201
- );
44881
+ if (separator !== "\n\n")
44882
+ return errorResponse("Native append supports the default blank-line separator only");
44883
+ if (position !== "after")
44884
+ return errorResponse("Native append supports the end of a note only");
44885
+ if (!scopeText)
44886
+ return errorResponse("Provide scopeText: a unique existing phrase for native append");
44887
+ if (!VERIFIED_BACKGROUND.has("append-native"))
44888
+ return errorResponse(
44889
+ "Native append has not passed live validation; see get-capabilities"
44890
+ );
44891
+ const result2 = appendNative(notesManager, {
44892
+ id: id2,
44893
+ expectedContentHash,
44894
+ scopeText,
44895
+ content,
44896
+ format
44897
+ });
44898
+ return successResponse("Native append verified without replacing existing objects", result2);
44202
44899
  }
44203
- const attachments = notesManager.listAttachmentsById(id);
44900
+ const attachments = notesManager.listAttachmentsById(id2);
44204
44901
  if (attachments.length > 0) {
44205
44902
  return errorResponse(
44206
44903
  `Note "${snapshot.note.title}" has ${attachments.length} attachment(s). Append is blocked because it rewrites the full body; edit it in Notes.app.`
@@ -44214,7 +44911,7 @@ registerTool(
44214
44911
  const sepHtml = separatorToHtml(separator);
44215
44912
  const combinedBody = position === "before" ? titleDiv + newBlock + sepHtml + bodyHtml : titleDiv + bodyHtml + sepHtml + newBlock;
44216
44913
  const result = notesManager.updateNoteByIdIfUnchanged(
44217
- id,
44914
+ id2,
44218
44915
  snapshot.note.title,
44219
44916
  snapshot.body,
44220
44917
  void 0,
@@ -44235,8 +44932,8 @@ registerTool(
44235
44932
  `The append result for note "${snapshot.note.title}" is uncertain. Read the exact ID before retrying.`
44236
44933
  );
44237
44934
  }
44238
- const readback = notesManager.getNoteContentById(id);
44239
- const richReadback = enrichNoteRead(id, readback || "");
44935
+ const readback = notesManager.getNoteContentById(id2);
44936
+ const richReadback = enrichNoteRead(id2, readback || "");
44240
44937
  const contentHash = readback ? richContentHash(readback, richReadback) : "";
44241
44938
  if (!richReadback.complete || linkSignature(richReadback.links) !== linkSignature(htmlLinks(result.writtenBody))) {
44242
44939
  return errorResponse(
@@ -44245,7 +44942,7 @@ registerTool(
44245
44942
  }
44246
44943
  if (!readback || comparableVisibleText(readback) !== comparableVisibleText(result.writtenBody)) {
44247
44944
  return errorResponse(
44248
- `The note accepted an append, but exact-ID readback visible text did not match. Do not retry automatically; inspect note ID ${id} in Notes.app.`
44945
+ `The note accepted an append, but exact-ID readback visible text did not match. Do not retry automatically; inspect note ID ${id2} in Notes.app.`
44249
44946
  );
44250
44947
  }
44251
44948
  const sharedWarning = snapshot.note.shared ? "\n\n\u26A0\uFE0F This note is shared with collaborators. Your changes are visible to them." : "";
@@ -44253,7 +44950,7 @@ registerTool(
44253
44950
  `Note appended; visible text verified: "${snapshot.note.title}"${sharedWarning}`,
44254
44951
  {
44255
44952
  ok: true,
44256
- id,
44953
+ id: id2,
44257
44954
  title: snapshot.note.title,
44258
44955
  shared: snapshot.note.shared ?? false,
44259
44956
  previousContentHash: expectedContentHash,
@@ -44281,19 +44978,19 @@ registerTool(
44281
44978
  previousContentHash: external_exports.string().optional()
44282
44979
  }
44283
44980
  },
44284
- withErrorHandling(({ id, expectedContentHash }) => {
44285
- const snapshot = readExactNoteSnapshot(id);
44981
+ withErrorHandling(({ id: id2, expectedContentHash }) => {
44982
+ const snapshot = readExactNoteSnapshot(id2);
44286
44983
  if ("error" in snapshot) return errorResponse(snapshot.error);
44287
44984
  if (snapshot.contentHash !== expectedContentHash) {
44288
44985
  return errorResponse(revisionConflictMessage(snapshot.note.title));
44289
44986
  }
44290
- const result = notesManager.deleteNoteByIdIfUnchanged(id, snapshot.body);
44987
+ const result = notesManager.deleteNoteByIdIfUnchanged(id2, snapshot.body);
44291
44988
  if (result.status === "conflict") {
44292
44989
  return errorResponse(revisionConflictMessage(snapshot.note.title));
44293
44990
  }
44294
44991
  if (result.status !== "deleted") {
44295
44992
  return errorResponse(
44296
- `The delete result for note "${snapshot.note.title}" is uncertain. Inspect exact ID ${id} before retrying.`
44993
+ `The delete result for note "${snapshot.note.title}" is uncertain. Inspect exact ID ${id2} before retrying.`
44297
44994
  );
44298
44995
  }
44299
44996
  const sharedWarning = snapshot.note.shared ? "\n\n\u26A0\uFE0F This note was shared with collaborators. They will no longer have access." : "";
@@ -44301,7 +44998,7 @@ registerTool(
44301
44998
  `Note moved to Recently Deleted: "${snapshot.note.title}"${sharedWarning}`,
44302
44999
  {
44303
45000
  ok: true,
44304
- id,
45001
+ id: id2,
44305
45002
  title: snapshot.note.title,
44306
45003
  wasShared: snapshot.note.shared ?? false,
44307
45004
  previousContentHash: expectedContentHash
@@ -44326,26 +45023,26 @@ registerTool(
44326
45023
  verified: external_exports.boolean().optional()
44327
45024
  }
44328
45025
  },
44329
- withErrorHandling(({ id, folder, account }) => {
44330
- const note = notesManager.getNoteById(id);
45026
+ withErrorHandling(({ id: id2, folder, account }) => {
45027
+ const note = notesManager.getNoteById(id2);
44331
45028
  if (!note) {
44332
- return errorResponse(`Note with ID "${id}" not found`);
45029
+ return errorResponse(`Note with ID "${id2}" not found`);
44333
45030
  }
44334
- const success = notesManager.moveNoteById(id, folder, account);
45031
+ const success = notesManager.moveNoteById(id2, folder, account);
44335
45032
  if (!success) {
44336
45033
  return errorResponse(
44337
45034
  `Failed to move note "${note.title}" to folder "${folder}". Folder may not exist.`
44338
45035
  );
44339
45036
  }
44340
- const readback = notesManager.getNoteById(id);
44341
- if (!readback || readback.id !== id) {
45037
+ const readback = notesManager.getNoteById(id2);
45038
+ if (!readback || readback.id !== id2) {
44342
45039
  return errorResponse(
44343
- `The move may have succeeded, but exact-ID readback failed. Inspect note ID ${id} before retrying.`
45040
+ `The move may have succeeded, but exact-ID readback failed. Inspect note ID ${id2} before retrying.`
44344
45041
  );
44345
45042
  }
44346
45043
  return successResponse(`Note moved and verified: "${readback.title}" -> "${folder}"`, {
44347
45044
  ok: true,
44348
- id,
45045
+ id: id2,
44349
45046
  title: readback.title,
44350
45047
  folder,
44351
45048
  verified: true
@@ -44740,13 +45437,13 @@ registerTool(
44740
45437
  count: external_exports.number().optional()
44741
45438
  }
44742
45439
  },
44743
- withErrorHandling(({ id, title, account }) => {
44744
- if (id) {
44745
- const note2 = notesManager.getNoteById(id);
45440
+ withErrorHandling(({ id: id2, title, account }) => {
45441
+ if (id2) {
45442
+ const note2 = notesManager.getNoteById(id2);
44746
45443
  if (!note2) {
44747
- return errorResponse(`Note with ID "${id}" not found`);
45444
+ return errorResponse(`Note with ID "${id2}" not found`);
44748
45445
  }
44749
- const attachments2 = notesManager.listAttachmentsById(id);
45446
+ const attachments2 = notesManager.listAttachmentsById(id2);
44750
45447
  if (attachments2.length === 0) {
44751
45448
  return successResponse(`Note "${note2.title}" has no attachments`, {
44752
45449
  attachments: [],
@@ -44804,18 +45501,18 @@ registerTool(
44804
45501
  if (notes.length === 0) {
44805
45502
  return errorResponse("No reviewed notes provided");
44806
45503
  }
44807
- const results = notes.map(({ id, expectedContentHash }) => {
44808
- const snapshot = readExactNoteSnapshot(id);
44809
- if ("error" in snapshot) return { id, success: false, error: snapshot.error };
45504
+ const results = notes.map(({ id: id2, expectedContentHash }) => {
45505
+ const snapshot = readExactNoteSnapshot(id2);
45506
+ if ("error" in snapshot) return { id: id2, success: false, error: snapshot.error };
44810
45507
  if (snapshot.contentHash !== expectedContentHash) {
44811
- return { id, success: false, error: revisionConflictMessage(snapshot.note.title) };
45508
+ return { id: id2, success: false, error: revisionConflictMessage(snapshot.note.title) };
44812
45509
  }
44813
- const result = notesManager.deleteNoteByIdIfUnchanged(id, snapshot.body);
44814
- if (result.status === "deleted") return { id, success: true };
45510
+ const result = notesManager.deleteNoteByIdIfUnchanged(id2, snapshot.body);
45511
+ if (result.status === "deleted") return { id: id2, success: true };
44815
45512
  if (result.status === "conflict") {
44816
- return { id, success: false, error: revisionConflictMessage(snapshot.note.title) };
45513
+ return { id: id2, success: false, error: revisionConflictMessage(snapshot.note.title) };
44817
45514
  }
44818
- return { id, success: false, error: "Delete result uncertain; inspect this exact ID" };
45515
+ return { id: id2, success: false, error: "Delete result uncertain; inspect this exact ID" };
44819
45516
  });
44820
45517
  const succeeded = results.filter((r) => r.success).length;
44821
45518
  const failed = results.filter((r) => !r.success).length;
@@ -45003,11 +45700,11 @@ registerTool(
45003
45700
  markdown: external_exports.string().optional()
45004
45701
  }
45005
45702
  },
45006
- withErrorHandling(({ id, title, account }) => {
45007
- if (id) {
45008
- const markdown2 = notesManager.getNoteMarkdownById(id);
45703
+ withErrorHandling(({ id: id2, title, account }) => {
45704
+ if (id2) {
45705
+ const markdown2 = notesManager.getNoteMarkdownById(id2);
45009
45706
  if (!markdown2) {
45010
- return errorResponse(`Note with ID "${id}" not found or has no content`);
45707
+ return errorResponse(`Note with ID "${id2}" not found or has no content`);
45011
45708
  }
45012
45709
  return successResponse(markdown2, { markdown: markdown2 });
45013
45710
  }
@@ -45036,17 +45733,17 @@ registerTool(
45036
45733
  total: external_exports.number().optional()
45037
45734
  }
45038
45735
  },
45039
- withErrorHandling(({ id }) => {
45040
- const note = notesManager.getNoteById(id);
45736
+ withErrorHandling(({ id: id2 }) => {
45737
+ const note = notesManager.getNoteById(id2);
45041
45738
  if (!note) {
45042
- return errorResponse(`Note with ID "${id}" not found`);
45739
+ return errorResponse(`Note with ID "${id2}" not found`);
45043
45740
  }
45044
45741
  if (note.passwordProtected) {
45045
45742
  return errorResponse(
45046
45743
  `Note "${note.title}" is password-protected and cannot be read. Unlock it in Notes.app first.`
45047
45744
  );
45048
45745
  }
45049
- const result = getChecklistItems(id);
45746
+ const result = getChecklistItems(id2);
45050
45747
  if (!result.items) {
45051
45748
  return errorResponse(result.message || "Failed to read checklist state.");
45052
45749
  }
@@ -45078,13 +45775,13 @@ registerTool(
45078
45775
  smartFolderQuery: external_exports.string().optional()
45079
45776
  }
45080
45777
  },
45081
- withErrorHandling(({ id }) => {
45082
- const { metadata, message } = getNoteMetadata(id);
45778
+ withErrorHandling(({ id: id2 }) => {
45779
+ const { metadata, message } = getNoteMetadata(id2);
45083
45780
  if (!metadata) {
45084
- return errorResponse(message || `Failed to read metadata for note "${id}"`);
45781
+ return errorResponse(message || `Failed to read metadata for note "${id2}"`);
45085
45782
  }
45086
45783
  const keys = Object.keys(metadata);
45087
- const summary = keys.length === 0 ? `No additional metadata is available for note "${id}" on this macOS version.` : keys.map((k) => `${k}: ${String(metadata[k])}`).join("\n");
45784
+ const summary = keys.length === 0 ? `No additional metadata is available for note "${id2}" on this macOS version.` : keys.map((k) => `${k}: ${String(metadata[k])}`).join("\n");
45088
45785
  return successResponse(summary, metadata);
45089
45786
  }, "Error reading note metadata")
45090
45787
  );