ofw-mcp 2.21.0 → 2.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -94,7 +94,7 @@ var require_buffer_util = __commonJS({
94
94
  buffer[i] ^= mask[i & 3];
95
95
  }
96
96
  }
97
- function toArrayBuffer(buf) {
97
+ function toArrayBuffer2(buf) {
98
98
  if (buf.length === buf.buffer.byteLength) {
99
99
  return buf.buffer;
100
100
  }
@@ -117,7 +117,7 @@ var require_buffer_util = __commonJS({
117
117
  module.exports = {
118
118
  concat,
119
119
  mask: _mask,
120
- toArrayBuffer,
120
+ toArrayBuffer: toArrayBuffer2,
121
121
  toBuffer,
122
122
  unmask: _unmask
123
123
  };
@@ -784,7 +784,7 @@ var require_receiver = __commonJS({
784
784
  kStatusCode,
785
785
  kWebSocket
786
786
  } = require_constants();
787
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
787
+ var { concat, toArrayBuffer: toArrayBuffer2, unmask } = require_buffer_util();
788
788
  var { isValidStatusCode, isValidUTF8 } = require_validation2();
789
789
  var FastBuffer = Buffer[Symbol.species];
790
790
  var GET_INFO = 0;
@@ -1263,7 +1263,7 @@ var require_receiver = __commonJS({
1263
1263
  if (this._binaryType === "nodebuffer") {
1264
1264
  data = concat(fragments, messageLength);
1265
1265
  } else if (this._binaryType === "arraybuffer") {
1266
- data = toArrayBuffer(concat(fragments, messageLength));
1266
+ data = toArrayBuffer2(concat(fragments, messageLength));
1267
1267
  } else if (this._binaryType === "blob") {
1268
1268
  data = new Blob(fragments);
1269
1269
  } else {
@@ -7394,7 +7394,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
7394
7394
  }
7395
7395
  return propValues;
7396
7396
  });
7397
- const isObject2 = isObject;
7397
+ const isObject3 = isObject;
7398
7398
  const catchall = def.catchall;
7399
7399
  let value;
7400
7400
  const memo3 = globalConfig.memoizer;
@@ -7402,7 +7402,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
7402
7402
  inst._zod.parse = (payload, ctx) => {
7403
7403
  value ?? (value = _normalized.value);
7404
7404
  const input2 = payload.value;
7405
- if (!isObject2(input2)) {
7405
+ if (!isObject3(input2)) {
7406
7406
  payload.issues.push({
7407
7407
  expected: "object",
7408
7408
  code: "invalid_type",
@@ -7450,15 +7450,15 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
7450
7450
  const syms = normalized.symbolKeys;
7451
7451
  const doc = new Doc(["payload", "ctx"], { shape, inst, memo: memo3, syms });
7452
7452
  const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
7453
- const prefixStr = (id, k) => `
7454
- let ${id}_ab = false;
7455
- for (let i = 0; i < ${id}.issues.length; i++) {
7456
- const iss = ${id}.issues[i];
7453
+ const prefixStr = (id2, k) => `
7454
+ let ${id2}_ab = false;
7455
+ for (let i = 0; i < ${id2}.issues.length; i++) {
7456
+ const iss = ${id2}.issues[i];
7457
7457
  iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
7458
7458
  payload.issues.push(iss);
7459
- if (iss.continue !== true) ${id}_ab = true;
7459
+ if (iss.continue !== true) ${id2}_ab = true;
7460
7460
  }
7461
- if (${id}_ab && ctx && ctx.abortEarly) {
7461
+ if (${id2}_ab && ctx && ctx.abortEarly) {
7462
7462
  payload.value = newResult;
7463
7463
  return payload;
7464
7464
  }`;
@@ -7472,34 +7472,34 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
7472
7472
  for (const key of normalized.allKeys) {
7473
7473
  if (key === "__proto__")
7474
7474
  continue;
7475
- const id = ids[key];
7475
+ const id2 = ids[key];
7476
7476
  const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
7477
7477
  const isPresent = `${k} in input`;
7478
7478
  const schema = shape[key];
7479
7479
  const optin = schema?._zod?.optin;
7480
7480
  const isOptionalIn = optin !== void 0;
7481
7481
  const isOptionalOut = schema?._zod?.optout === "optional";
7482
- doc.write(`const ${id} = ${parseStr(k)};`);
7482
+ doc.write(`const ${id2} = ${parseStr(k)};`);
7483
7483
  if (isOptionalIn && isOptionalOut) {
7484
- const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
7484
+ const assign = optin === "optional" ? `${id2}_present` : `${id2}.value !== undefined || ${id2}_present`;
7485
7485
  doc.write(`
7486
- const ${id}_present = ${isPresent};
7487
- if (!${id}.issues.length || ${id}_present) {
7488
- if (${id}.issues.length) {${prefixStr(id, k)}
7486
+ const ${id2}_present = ${isPresent};
7487
+ if (!${id2}.issues.length || ${id2}_present) {
7488
+ if (${id2}.issues.length) {${prefixStr(id2, k)}
7489
7489
  }
7490
7490
 
7491
7491
  if (${assign}) {
7492
- newResult[${k}] = ${id}.value;
7492
+ newResult[${k}] = ${id2}.value;
7493
7493
  }
7494
7494
  }
7495
7495
 
7496
7496
  `);
7497
7497
  } else if (!isOptionalIn) {
7498
7498
  doc.write(`
7499
- const ${id}_present = ${isPresent};
7500
- if (${id}.issues.length) {${prefixStr(id, k)}
7499
+ const ${id2}_present = ${isPresent};
7500
+ if (${id2}.issues.length) {${prefixStr(id2, k)}
7501
7501
  }
7502
- if (!${id}_present && !${id}.issues.length) {
7502
+ if (!${id2}_present && !${id2}.issues.length) {
7503
7503
  payload.issues.push({
7504
7504
  code: "invalid_type",
7505
7505
  expected: "nonoptional",
@@ -7512,22 +7512,22 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
7512
7512
  }
7513
7513
  }
7514
7514
 
7515
- if (${id}_present) {
7516
- newResult[${k}] = ${id}.value;
7515
+ if (${id2}_present) {
7516
+ newResult[${k}] = ${id2}.value;
7517
7517
  }
7518
7518
 
7519
7519
  `);
7520
7520
  } else {
7521
7521
  doc.write(`
7522
- if (${id}.issues.length) {${prefixStr(id, k)}
7522
+ if (${id2}.issues.length) {${prefixStr(id2, k)}
7523
7523
  }
7524
7524
  `);
7525
7525
  if (optin === "defaulted") {
7526
- doc.write(`newResult[${k}] = ${id}.value;`);
7526
+ doc.write(`newResult[${k}] = ${id2}.value;`);
7527
7527
  } else {
7528
7528
  doc.write(`
7529
- if (${id}.value !== undefined || ${isPresent}) {
7530
- newResult[${k}] = ${id}.value;
7529
+ if (${id2}.value !== undefined || ${isPresent}) {
7530
+ newResult[${k}] = ${id2}.value;
7531
7531
  }
7532
7532
  `);
7533
7533
  }
@@ -7538,7 +7538,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
7538
7538
  return doc.compile();
7539
7539
  };
7540
7540
  let fastpass;
7541
- const isObject2 = isObject;
7541
+ const isObject3 = isObject;
7542
7542
  const jit = !globalConfig.jitless;
7543
7543
  const allowsEval2 = allowsEval;
7544
7544
  const fastEnabled = jit && allowsEval2.value;
@@ -7547,7 +7547,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
7547
7547
  inst._zod.parse = (payload, ctx) => {
7548
7548
  value ?? (value = _normalized.value);
7549
7549
  const input2 = payload.value;
7550
- if (!isObject2(input2)) {
7550
+ if (!isObject3(input2)) {
7551
7551
  payload.issues.push({
7552
7552
  expected: "object",
7553
7553
  code: "invalid_type",
@@ -8899,7 +8899,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
8899
8899
  var NONE = 0;
8900
8900
  var ASSUMED = 1;
8901
8901
  var PROVEN = 2;
8902
- function isRecursive(inst, stack, resolve7) {
8902
+ function isRecursive(inst, stack, resolve8) {
8903
8903
  const cached2 = recursive.get(inst);
8904
8904
  if (cached2 !== void 0)
8905
8905
  return cached2 ? PROVEN : NONE;
@@ -8909,7 +8909,7 @@ function isRecursive(inst, stack, resolve7) {
8909
8909
  let result = NONE;
8910
8910
  const check2 = (child) => {
8911
8911
  if (result !== PROVEN && child?._zod) {
8912
- const answer = isRecursive(child, stack, resolve7);
8912
+ const answer = isRecursive(child, stack, resolve8);
8913
8913
  if (answer > result)
8914
8914
  result = answer;
8915
8915
  }
@@ -8920,7 +8920,7 @@ function isRecursive(inst, stack, resolve7) {
8920
8920
  const desc = Object.getOwnPropertyDescriptor(sh, key);
8921
8921
  if (spread && !desc.enumerable)
8922
8922
  continue;
8923
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve7) : NONE;
8923
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve8) : NONE;
8924
8924
  if (child > answer)
8925
8925
  answer = child;
8926
8926
  }
@@ -8984,7 +8984,7 @@ function isRecursive(inst, stack, resolve7) {
8984
8984
  break;
8985
8985
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
8986
8986
  case "lazy": {
8987
- const inner = def._cachedInner ?? (resolve7 ? inst._zod.innerType : void 0);
8987
+ const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
8988
8988
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
8989
8989
  break;
8990
8990
  }
@@ -19555,26 +19555,26 @@ function extractDefs(ctx, schema) {
19555
19555
  return;
19556
19556
  const idToSchema = /* @__PURE__ */ new Map();
19557
19557
  for (const entry of ctx.seen.entries()) {
19558
- const id = ctx.metadataRegistry.get(entry[0])?.id;
19559
- if (id) {
19560
- const existing = idToSchema.get(id);
19558
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
19559
+ if (id2) {
19560
+ const existing = idToSchema.get(id2);
19561
19561
  if (existing && existing !== entry[0]) {
19562
- throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
19562
+ throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
19563
19563
  }
19564
- idToSchema.set(id, entry[0]);
19564
+ idToSchema.set(id2, entry[0]);
19565
19565
  }
19566
19566
  }
19567
19567
  const makeURI = (entry) => {
19568
19568
  const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
19569
19569
  if (ctx.external) {
19570
19570
  const externalId = ctx.external.registry.get(entry[0])?.id;
19571
- const uriGenerator = ctx.external.uri ?? ((id2) => id2);
19571
+ const uriGenerator = ctx.external.uri ?? ((id3) => id3);
19572
19572
  if (externalId) {
19573
19573
  return { ref: uriGenerator(externalId) };
19574
19574
  }
19575
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
19576
- entry[1].defId = id;
19577
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };
19575
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
19576
+ entry[1].defId = id2;
19577
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id2)}` };
19578
19578
  }
19579
19579
  const uriPrefix = `#`;
19580
19580
  const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
@@ -19622,8 +19622,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
19622
19622
  continue;
19623
19623
  }
19624
19624
  }
19625
- const id = ctx.metadataRegistry.get(entry[0])?.id;
19626
- if (id) {
19625
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
19626
+ if (id2) {
19627
19627
  extractToDef(entry);
19628
19628
  continue;
19629
19629
  }
@@ -19856,10 +19856,10 @@ function finalize(ctx, schema) {
19856
19856
  } else {
19857
19857
  }
19858
19858
  if (ctx.external?.uri) {
19859
- const id = ctx.external.registry.get(schema)?.id;
19860
- if (!id)
19859
+ const id2 = ctx.external.registry.get(schema)?.id;
19860
+ if (!id2)
19861
19861
  throw new Error("Schema is missing an `id` property");
19862
- result.$id = ctx.external.uri(id);
19862
+ result.$id = ctx.external.uri(id2);
19863
19863
  }
19864
19864
  assignProps(result, root.defId ? root.schema : root.def ?? root.schema);
19865
19865
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
@@ -20465,7 +20465,7 @@ function stringifyKeyNames(bySchema, json2, visited) {
20465
20465
  const values = json2.enum ?? (json2.const !== void 0 ? [json2.const] : void 0);
20466
20466
  if (!numericType && !values?.some((v) => typeof v === "number"))
20467
20467
  return json2;
20468
- const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json2;
20468
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id: id2, ...rest } = json2;
20469
20469
  if (rest.enum)
20470
20470
  rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
20471
20471
  else if (typeof rest.const === "number")
@@ -25610,8 +25610,8 @@ var REF_REWRITE_NAME_MAP_KEYS = /* @__PURE__ */ new Set([
25610
25610
  "dependentSchemas",
25611
25611
  "dependencies"
25612
25612
  ]);
25613
- function establishesNewBase(id) {
25614
- return id !== void 0 && !(typeof id === "string" && id.startsWith("#"));
25613
+ function establishesNewBase(id2) {
25614
+ return id2 !== void 0 && !(typeof id2 === "string" && id2.startsWith("#"));
25615
25615
  }
25616
25616
  function wrapOutputSchemaForLegacy(natural) {
25617
25617
  const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0;
@@ -27946,14 +27946,14 @@ function inputRequiredRoundsExceededMessage(method, maxRounds) {
27946
27946
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
27947
27947
  }
27948
27948
  function sleep(ms, signal) {
27949
- return new Promise((resolve7, reject) => {
27949
+ return new Promise((resolve8, reject) => {
27950
27950
  if (signal?.aborted) {
27951
27951
  reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));
27952
27952
  return;
27953
27953
  }
27954
27954
  const timer = setTimeout(() => {
27955
27955
  signal?.removeEventListener("abort", onAbort);
27956
- resolve7();
27956
+ resolve8();
27957
27957
  }, ms);
27958
27958
  const onAbort = () => {
27959
27959
  clearTimeout(timer);
@@ -28752,7 +28752,7 @@ var Protocol = class {
28752
28752
  const flowStartedAt = Date.now();
28753
28753
  let onAbort;
28754
28754
  let cleanupMessageId;
28755
- return new Promise((resolve7, reject) => {
28755
+ return new Promise((resolve8, reject) => {
28756
28756
  const earlyReject = (error62) => {
28757
28757
  reject(error62);
28758
28758
  };
@@ -28821,7 +28821,7 @@ var Protocol = class {
28821
28821
  }
28822
28822
  if (decoded.kind === "invalid") return reject(decoded.error);
28823
28823
  if (decoded.kind === "input_required") {
28824
- if (options?.allowInputRequired === true) return resolve7(manualInputRequiredValue(decoded));
28824
+ if (options?.allowInputRequired === true) return resolve8(manualInputRequiredValue(decoded));
28825
28825
  const flow = {
28826
28826
  codec: codec2,
28827
28827
  request,
@@ -28833,11 +28833,11 @@ var Protocol = class {
28833
28833
  params
28834
28834
  }, resultSchema, legOptions)
28835
28835
  };
28836
- return resolve7(this._resolveNonCompleteResult(decoded, flow));
28836
+ return resolve8(this._resolveNonCompleteResult(decoded, flow));
28837
28837
  }
28838
28838
  const result = decoded.result;
28839
28839
  validateStandardSchema(resultSchema, result).then((parseResult) => {
28840
- if (parseResult.success) resolve7(parseResult.data);
28840
+ if (parseResult.success) resolve8(parseResult.data);
28841
28841
  else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));
28842
28842
  }, reject);
28843
28843
  });
@@ -31128,9 +31128,9 @@ var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
31128
31128
  }
31129
31129
  return count;
31130
31130
  }
31131
- function getFullPath(resolver, id = "", normalize) {
31132
- if (normalize !== false) id = normalizeId(id);
31133
- return _getFullPath(resolver, resolver.parse(id));
31131
+ function getFullPath(resolver, id2 = "", normalize) {
31132
+ if (normalize !== false) id2 = normalizeId(id2);
31133
+ return _getFullPath(resolver, resolver.parse(id2));
31134
31134
  }
31135
31135
  exports.getFullPath = getFullPath;
31136
31136
  function _getFullPath(resolver, p) {
@@ -31138,13 +31138,13 @@ var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
31138
31138
  }
31139
31139
  exports._getFullPath = _getFullPath;
31140
31140
  const TRAILING_SLASH_HASH = /#\/?$/;
31141
- function normalizeId(id) {
31142
- return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
31141
+ function normalizeId(id2) {
31142
+ return id2 ? id2.replace(TRAILING_SLASH_HASH, "") : "";
31143
31143
  }
31144
31144
  exports.normalizeId = normalizeId;
31145
- function resolveUrl(resolver, baseId, id) {
31146
- id = normalizeId(id);
31147
- return resolver.resolve(baseId, id);
31145
+ function resolveUrl(resolver, baseId, id2) {
31146
+ id2 = normalizeId(id2);
31147
+ return resolver.resolve(baseId, id2);
31148
31148
  }
31149
31149
  exports.resolveUrl = resolveUrl;
31150
31150
  const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
@@ -31753,7 +31753,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
31753
31753
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
31754
31754
  const schOrFunc = root.refs[ref];
31755
31755
  if (schOrFunc) return schOrFunc;
31756
- let _sch = resolve7.call(this, root, ref);
31756
+ let _sch = resolve8.call(this, root, ref);
31757
31757
  if (_sch === void 0) {
31758
31758
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
31759
31759
  const { schemaId } = this.opts;
@@ -31779,7 +31779,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
31779
31779
  function sameSchemaEnv(s1, s2) {
31780
31780
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
31781
31781
  }
31782
- function resolve7(root, ref) {
31782
+ function resolve8(root, ref) {
31783
31783
  let sch;
31784
31784
  while (typeof (sch = this.refs[ref]) == "string") ref = sch;
31785
31785
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
@@ -31789,8 +31789,8 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
31789
31789
  const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
31790
31790
  let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
31791
31791
  if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root);
31792
- const id = (0, resolve_1.normalizeId)(refPath);
31793
- const schOrRef = this.refs[id] || this.schemas[id];
31792
+ const id2 = (0, resolve_1.normalizeId)(refPath);
31793
+ const schOrRef = this.refs[id2] || this.schemas[id2];
31794
31794
  if (typeof schOrRef == "string") {
31795
31795
  const sch = resolveSchema.call(this, root, schOrRef);
31796
31796
  if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return;
@@ -31798,7 +31798,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => {
31798
31798
  }
31799
31799
  if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return;
31800
31800
  if (!schOrRef.validate) compileSchema.call(this, schOrRef);
31801
- if (id === (0, resolve_1.normalizeId)(ref)) {
31801
+ if (id2 === (0, resolve_1.normalizeId)(ref)) {
31802
31802
  const { schema } = schOrRef;
31803
31803
  const { schemaId } = this.opts;
31804
31804
  const schId = schema[schemaId];
@@ -32229,7 +32229,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32229
32229
  else if (typeof uri === "object") uri = parse3(serialize(uri, options), options);
32230
32230
  return uri;
32231
32231
  }
32232
- function resolve7(baseURI, relativeURI, options) {
32232
+ function resolve8(baseURI, relativeURI, options) {
32233
32233
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
32234
32234
  const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);
32235
32235
  schemelessOptions.skipEscape = true;
@@ -32403,7 +32403,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
32403
32403
  const fastUri = {
32404
32404
  SCHEMES,
32405
32405
  normalize,
32406
- resolve: resolve7,
32406
+ resolve: resolve8,
32407
32407
  resolveComponent,
32408
32408
  equal,
32409
32409
  serialize,
@@ -32666,13 +32666,13 @@ var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
32666
32666
  for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema);
32667
32667
  return this;
32668
32668
  }
32669
- let id;
32669
+ let id2;
32670
32670
  if (typeof schema === "object") {
32671
32671
  const { schemaId } = this.opts;
32672
- id = schema[schemaId];
32673
- if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`);
32672
+ id2 = schema[schemaId];
32673
+ if (id2 !== void 0 && typeof id2 != "string") throw new Error(`schema ${schemaId} must be string`);
32674
32674
  }
32675
- key = (0, resolve_1.normalizeId)(key || id);
32675
+ key = (0, resolve_1.normalizeId)(key || id2);
32676
32676
  this._checkUnique(key);
32677
32677
  this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
32678
32678
  return this;
@@ -32737,11 +32737,11 @@ var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
32737
32737
  case "object": {
32738
32738
  const cacheKey = schemaKeyRef;
32739
32739
  this._cache.delete(cacheKey);
32740
- let id = schemaKeyRef[this.opts.schemaId];
32741
- if (id) {
32742
- id = (0, resolve_1.normalizeId)(id);
32743
- delete this.schemas[id];
32744
- delete this.refs[id];
32740
+ let id2 = schemaKeyRef[this.opts.schemaId];
32741
+ if (id2) {
32742
+ id2 = (0, resolve_1.normalizeId)(id2);
32743
+ delete this.schemas[id2];
32744
+ delete this.refs[id2];
32745
32745
  }
32746
32746
  return this;
32747
32747
  }
@@ -32833,14 +32833,14 @@ var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
32833
32833
  }
32834
32834
  }
32835
32835
  _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
32836
- let id;
32836
+ let id2;
32837
32837
  const { schemaId } = this.opts;
32838
- if (typeof schema == "object") id = schema[schemaId];
32838
+ if (typeof schema == "object") id2 = schema[schemaId];
32839
32839
  else if (this.opts.jtd) throw new Error("schema must be object");
32840
32840
  else if (typeof schema != "boolean") throw new Error("schema must be object or boolean");
32841
32841
  let sch = this._cache.get(schema);
32842
32842
  if (sch !== void 0) return sch;
32843
- baseId = (0, resolve_1.normalizeId)(id || baseId);
32843
+ baseId = (0, resolve_1.normalizeId)(id2 || baseId);
32844
32844
  const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
32845
32845
  sch = new compile_1.SchemaEnv({
32846
32846
  schema,
@@ -32857,8 +32857,8 @@ var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
32857
32857
  if (validateSchema) this.validateSchema(schema, true);
32858
32858
  return sch;
32859
32859
  }
32860
- _checkUnique(id) {
32861
- if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`);
32860
+ _checkUnique(id2) {
32861
+ if (this.schemas[id2] || this.refs[id2]) throw new Error(`schema with key or id "${id2}" already exists`);
32862
32862
  }
32863
32863
  _compileSchemaEnv(sch) {
32864
32864
  if (sch.meta) this._compileMetaSchema(sch);
@@ -36278,8 +36278,8 @@ var StdioListenRouter = class {
36278
36278
  if (serverInfo !== void 0) this._serverInfo = serverInfo;
36279
36279
  }
36280
36280
  /** Whether `id` is an active listen subscription on this connection. */
36281
- has(id) {
36282
- return this._subs.has(id);
36281
+ has(id2) {
36282
+ return this._subs.has(id2);
36283
36283
  }
36284
36284
  /**
36285
36285
  * Serve one inbound `subscriptions/listen` request: registers the
@@ -36323,8 +36323,8 @@ var StdioListenRouter = class {
36323
36323
  * `true` when a subscription was removed. After this call NOTHING further
36324
36324
  * is delivered for that subscription id (the post-cancel hardening).
36325
36325
  */
36326
- cancel(id) {
36327
- return this._subs.delete(id);
36326
+ cancel(id2) {
36327
+ return this._subs.delete(id2);
36328
36328
  }
36329
36329
  /**
36330
36330
  * Route an outbound notification through the active subscriptions.
@@ -36356,13 +36356,13 @@ var StdioListenRouter = class {
36356
36356
  */
36357
36357
  teardownAll() {
36358
36358
  const out = [];
36359
- for (const id of this._subs.keys()) out.push({
36359
+ for (const id2 of this._subs.keys()) out.push({
36360
36360
  jsonrpc: "2.0",
36361
- id,
36361
+ id: id2,
36362
36362
  result: {
36363
36363
  resultType: "complete",
36364
36364
  _meta: {
36365
- [SUBSCRIPTION_ID_META_KEY]: id,
36365
+ [SUBSCRIPTION_ID_META_KEY]: id2,
36366
36366
  ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo }
36367
36367
  }
36368
36368
  }
@@ -37001,7 +37001,7 @@ var Server = class extends Protocol {
37001
37001
  if (hasPreviousToolUse) {
37002
37002
  const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
37003
37003
  const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
37004
- if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match");
37004
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id2) => toolResultIds.has(id2))) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match");
37005
37005
  }
37006
37006
  }
37007
37007
  const hasTools = Boolean(params.tools || params.toolChoice);
@@ -37865,7 +37865,7 @@ var StdioServerTransport = class {
37865
37865
  }
37866
37866
  send(message) {
37867
37867
  if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed"));
37868
- return new Promise((resolve7, reject) => {
37868
+ return new Promise((resolve8, reject) => {
37869
37869
  const json2 = serializeMessage(message);
37870
37870
  let settled = false;
37871
37871
  const onError = (error62) => {
@@ -37880,14 +37880,14 @@ var StdioServerTransport = class {
37880
37880
  settled = true;
37881
37881
  this._stdout.off("error", onError);
37882
37882
  this._stdout.off("drain", onDrain);
37883
- resolve7();
37883
+ resolve8();
37884
37884
  };
37885
37885
  this._stdout.once("error", onError);
37886
37886
  if (this._stdout.write(json2)) {
37887
37887
  if (settled) return;
37888
37888
  settled = true;
37889
37889
  this._stdout.off("error", onError);
37890
- resolve7();
37890
+ resolve8();
37891
37891
  } else if (!settled) this._stdout.once("drain", onDrain);
37892
37892
  });
37893
37893
  }
@@ -37910,8 +37910,8 @@ var StdioConnectionChannel = class {
37910
37910
  }
37911
37911
  async send(message, options) {
37912
37912
  if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
37913
- const { id } = message;
37914
- if (id !== void 0) this._settle(id);
37913
+ const { id: id2 } = message;
37914
+ if (id2 !== void 0) this._settle(id2);
37915
37915
  }
37916
37916
  if (this._closed) return;
37917
37917
  if (this._outboundIntercept?.(message) === "handled") return;
@@ -37941,14 +37941,14 @@ var StdioConnectionChannel = class {
37941
37941
  */
37942
37942
  async whenRequestsAnswered(timeoutMs) {
37943
37943
  if (this._closed || this._pendingRequests.size === 0) return true;
37944
- return await new Promise((resolve7) => {
37944
+ return await new Promise((resolve8) => {
37945
37945
  const waiter = () => {
37946
37946
  clearTimeout(timer);
37947
- resolve7(true);
37947
+ resolve8(true);
37948
37948
  };
37949
37949
  const timer = setTimeout(() => {
37950
37950
  this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter);
37951
- resolve7(false);
37951
+ resolve8(false);
37952
37952
  }, timeoutMs);
37953
37953
  this._drainWaiters.push(waiter);
37954
37954
  });
@@ -37964,8 +37964,8 @@ var StdioConnectionChannel = class {
37964
37964
  this.onclose?.();
37965
37965
  }
37966
37966
  }
37967
- _settle(id) {
37968
- this._pendingRequests.delete(id);
37967
+ _settle(id2) {
37968
+ this._pendingRequests.delete(id2);
37969
37969
  if (this._pendingRequests.size === 0) this._releaseDrainWaiters();
37970
37970
  }
37971
37971
  _releaseDrainWaiters() {
@@ -38021,9 +38021,9 @@ function serveStdio(factory, options = {}) {
38021
38021
  } catch {
38022
38022
  }
38023
38023
  };
38024
- const writeErrorResponse = (id, code2, message, data) => wire.send({
38024
+ const writeErrorResponse = (id2, code2, message, data) => wire.send({
38025
38025
  jsonrpc: "2.0",
38026
- id,
38026
+ id: id2,
38027
38027
  error: {
38028
38028
  code: code2,
38029
38029
  message,
@@ -40118,11 +40118,11 @@ async function withFileLock(lockPath, fn, opts = {}) {
40118
40118
  }
40119
40119
  if (r === "unlockable")
40120
40120
  break;
40121
- await new Promise((resolve7) => {
40121
+ await new Promise((resolve8) => {
40122
40122
  const done = () => {
40123
40123
  clearTimeout(timer);
40124
40124
  signal?.removeEventListener("abort", done);
40125
- resolve7();
40125
+ resolve8();
40126
40126
  };
40127
40127
  const timer = setTimeout(done, pollMs);
40128
40128
  signal?.addEventListener("abort", done, { once: true });
@@ -40725,12 +40725,12 @@ var PROTOCOL_VERSION = 4;
40725
40725
  var HKDF_SESSION_INFO = "fetchproxy/4.0.0/session";
40726
40726
  var enc = new TextEncoder();
40727
40727
  function helloSignaturePayload(mcpId, sessionNonce, sessionPub, answersExtNonce) {
40728
- const id = enc.encode(mcpId);
40729
- const out = new Uint8Array(id.length + sessionNonce.length + sessionPub.length + answersExtNonce.length);
40730
- out.set(id, 0);
40731
- out.set(sessionNonce, id.length);
40732
- out.set(sessionPub, id.length + sessionNonce.length);
40733
- out.set(answersExtNonce, id.length + sessionNonce.length + sessionPub.length);
40728
+ const id2 = enc.encode(mcpId);
40729
+ const out = new Uint8Array(id2.length + sessionNonce.length + sessionPub.length + answersExtNonce.length);
40730
+ out.set(id2, 0);
40731
+ out.set(sessionNonce, id2.length);
40732
+ out.set(sessionPub, id2.length + sessionNonce.length);
40733
+ out.set(answersExtNonce, id2.length + sessionNonce.length + sessionPub.length);
40734
40734
  return out;
40735
40735
  }
40736
40736
  var ANSWERS_NO_EXT_SESSION = new Uint8Array(32);
@@ -40808,8 +40808,8 @@ function generateMcpId(serverName, version2) {
40808
40808
  const rand = randomHex(8);
40809
40809
  return `${serverName}:${version2}:${rand}`;
40810
40810
  }
40811
- function isValidMcpId(id) {
40812
- return typeof id === "string" && ID_RE.test(id);
40811
+ function isValidMcpId(id2) {
40812
+ return typeof id2 === "string" && ID_RE.test(id2);
40813
40813
  }
40814
40814
  function randomHex(bytes) {
40815
40815
  const arr = new Uint8Array(bytes);
@@ -42431,7 +42431,7 @@ var DEFAULT_BIND_TIMEOUT_MS = 5e3;
42431
42431
  async function electRole(opts) {
42432
42432
  const server = createServer();
42433
42433
  const bindTimeoutMs = opts.bindTimeoutMs ?? DEFAULT_BIND_TIMEOUT_MS;
42434
- return new Promise((resolve7, reject) => {
42434
+ return new Promise((resolve8, reject) => {
42435
42435
  let timer;
42436
42436
  const clearBindTimer = () => {
42437
42437
  if (timer) {
@@ -42447,7 +42447,7 @@ async function electRole(opts) {
42447
42447
  server.close();
42448
42448
  } catch {
42449
42449
  }
42450
- resolve7({ role: "peer" });
42450
+ resolve8({ role: "peer" });
42451
42451
  } else {
42452
42452
  reject(e);
42453
42453
  }
@@ -42455,7 +42455,7 @@ async function electRole(opts) {
42455
42455
  const onListening = () => {
42456
42456
  clearBindTimer();
42457
42457
  server.removeListener("error", onError);
42458
- resolve7({ role: "host", server });
42458
+ resolve8({ role: "host", server });
42459
42459
  };
42460
42460
  server.once("error", onError);
42461
42461
  server.once("listening", onListening);
@@ -42805,13 +42805,13 @@ async function generateIdentity() {
42805
42805
  createdAt: Date.now()
42806
42806
  };
42807
42807
  }
42808
- function serializeIdentity(id) {
42808
+ function serializeIdentity(id2) {
42809
42809
  return JSON.stringify({
42810
- x25519Priv: toB64(id.x25519Priv),
42811
- x25519Pub: toB64(id.x25519Pub),
42812
- ed25519Priv: toB64(id.ed25519Priv),
42813
- ed25519Pub: toB64(id.ed25519Pub),
42814
- createdAt: id.createdAt
42810
+ x25519Priv: toB64(id2.x25519Priv),
42811
+ x25519Pub: toB64(id2.x25519Pub),
42812
+ ed25519Priv: toB64(id2.ed25519Priv),
42813
+ ed25519Pub: toB64(id2.ed25519Pub),
42814
+ createdAt: id2.createdAt
42815
42815
  }, null, 2);
42816
42816
  }
42817
42817
  function parseIdentity(text) {
@@ -42867,9 +42867,9 @@ async function loadOrCreateIdentity(serverName, dir = defaultIdentityDir()) {
42867
42867
  let unreadable = null;
42868
42868
  let recovered = false;
42869
42869
  for (let attempt = 0; attempt < 5; attempt++) {
42870
- const id = await generateIdentity();
42871
- if (await publishIdentityIfAbsent(dir, serverName, id))
42872
- return id;
42870
+ const id2 = await generateIdentity();
42871
+ if (await publishIdentityIfAbsent(dir, serverName, id2))
42872
+ return id2;
42873
42873
  try {
42874
42874
  return parseIdentity(await readFile(path, "utf8"));
42875
42875
  } catch (e) {
@@ -42892,12 +42892,12 @@ async function loadOrCreateIdentity(serverName, dir = defaultIdentityDir()) {
42892
42892
  throw new Error(`fetchproxy: could not create an identity for ${JSON.stringify(serverName)} in ${dir}`);
42893
42893
  }
42894
42894
  var NO_HARD_LINKS = /* @__PURE__ */ new Set(["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS"]);
42895
- async function publishIdentityIfAbsent(dir, serverName, id) {
42895
+ async function publishIdentityIfAbsent(dir, serverName, id2) {
42896
42896
  const path = identityFilePath(dir, serverName);
42897
42897
  await sweepStagingFiles(dir, serverName, { olderThanMs: 6e4 });
42898
42898
  const tmp = `${path}.${randomBytes5(STAGING_BYTES).toString("hex")}.tmp`;
42899
42899
  try {
42900
- await writeFile(tmp, serializeIdentity(id), { mode: 384, flag: "wx" });
42900
+ await writeFile(tmp, serializeIdentity(id2), { mode: 384, flag: "wx" });
42901
42901
  await chmod(tmp, 384);
42902
42902
  try {
42903
42903
  await link(tmp, path);
@@ -42906,7 +42906,7 @@ async function publishIdentityIfAbsent(dir, serverName, id) {
42906
42906
  if (code2 === void 0 || !NO_HARD_LINKS.has(code2))
42907
42907
  throw e;
42908
42908
  try {
42909
- await writeFile(path, serializeIdentity(id), { mode: 384, flag: "wx" });
42909
+ await writeFile(path, serializeIdentity(id2), { mode: 384, flag: "wx" });
42910
42910
  } catch (writeErr) {
42911
42911
  if (writeErr.code !== "EEXIST") {
42912
42912
  await rm(path, { force: true }).catch(() => void 0);
@@ -43346,10 +43346,10 @@ async function startHost(opts) {
43346
43346
  function resetSessionPromise() {
43347
43347
  ownRetryableRefusal = false;
43348
43348
  ownSessionSettled = false;
43349
- ownSessionReady = new Promise((resolve7, reject) => {
43349
+ ownSessionReady = new Promise((resolve8, reject) => {
43350
43350
  resolveOwnSession = (st) => {
43351
43351
  ownSessionSettled = true;
43352
- resolve7(st);
43352
+ resolve8(st);
43353
43353
  };
43354
43354
  rejectOwnSession = (e) => {
43355
43355
  ownSessionSettled = true;
@@ -43783,7 +43783,7 @@ async function startHost(opts) {
43783
43783
  });
43784
43784
  });
43785
43785
  return {
43786
- close: () => new Promise((resolve7) => {
43786
+ close: () => new Promise((resolve8) => {
43787
43787
  for (const client2 of wss.clients) {
43788
43788
  try {
43789
43789
  client2.terminate();
@@ -43791,7 +43791,7 @@ async function startHost(opts) {
43791
43791
  }
43792
43792
  }
43793
43793
  wss.close(() => {
43794
- opts.httpServer.close(() => resolve7());
43794
+ opts.httpServer.close(() => resolve8());
43795
43795
  });
43796
43796
  }),
43797
43797
  sendOwnInner: async (inner) => {
@@ -43833,11 +43833,11 @@ async function startPeer(opts) {
43833
43833
  maxPayload: opts.maxPayloadBytes ?? MAX_PAYLOAD_BYTES
43834
43834
  });
43835
43835
  const dialTimeoutMs = opts.dialTimeoutMs ?? PEER_DIAL_TIMEOUT_MS;
43836
- await new Promise((resolve7, reject) => {
43836
+ await new Promise((resolve8, reject) => {
43837
43837
  let timer;
43838
43838
  const onOpen = () => {
43839
43839
  cleanup();
43840
- resolve7();
43840
+ resolve8();
43841
43841
  };
43842
43842
  const onError = (e) => {
43843
43843
  cleanup();
@@ -43928,10 +43928,10 @@ async function startPeer(opts) {
43928
43928
  function resetSessionPromise() {
43929
43929
  retryableRefusal = false;
43930
43930
  sessionPromiseSettled = false;
43931
- sessionPromise = new Promise((resolve7, reject) => {
43931
+ sessionPromise = new Promise((resolve8, reject) => {
43932
43932
  resolveFirstReady = (st) => {
43933
43933
  sessionPromiseSettled = true;
43934
- resolve7(st);
43934
+ resolve8(st);
43935
43935
  };
43936
43936
  rejectFirstReady = (e) => {
43937
43937
  sessionPromiseSettled = true;
@@ -45140,17 +45140,17 @@ var FetchproxyServer = class {
45140
45140
  }
45141
45141
  } catch (err) {
45142
45142
  if ("id" in inner && typeof inner.id === "number") {
45143
- const { id } = inner;
45144
- this.pending.delete(id);
45145
- this.pendingReadCookies.delete(id);
45146
- this.pendingStorage.delete(id);
45147
- this.pendingWriteCookies.delete(id);
45148
- this.pendingCapture.delete(id);
45149
- this.pendingRedirect.delete(id);
45150
- this.pendingDownload.delete(id);
45151
- this.pendingIdb.delete(id);
45152
- this.pendingDomList.delete(id);
45153
- this.pendingGraphql.delete(id);
45143
+ const { id: id2 } = inner;
45144
+ this.pending.delete(id2);
45145
+ this.pendingReadCookies.delete(id2);
45146
+ this.pendingStorage.delete(id2);
45147
+ this.pendingWriteCookies.delete(id2);
45148
+ this.pendingCapture.delete(id2);
45149
+ this.pendingRedirect.delete(id2);
45150
+ this.pendingDownload.delete(id2);
45151
+ this.pendingIdb.delete(id2);
45152
+ this.pendingDomList.delete(id2);
45153
+ this.pendingGraphql.delete(id2);
45154
45154
  }
45155
45155
  throw err;
45156
45156
  }
@@ -45161,10 +45161,10 @@ var FetchproxyServer = class {
45161
45161
  * the throwing surface is the convenience methods.
45162
45162
  */
45163
45163
  async _fetchOnceWithTimeout(init, fetchOpts = {}) {
45164
- const id = this.nextRequestId++;
45165
- const inner = { type: "request", id, op: "fetch", init };
45166
- const pending = this.guardPending(new Promise((resolve7) => {
45167
- this.pending.set(id, resolve7);
45164
+ const id2 = this.nextRequestId++;
45165
+ const inner = { type: "request", id: id2, op: "fetch", init };
45166
+ const pending = this.guardPending(new Promise((resolve8) => {
45167
+ this.pending.set(id2, resolve8);
45168
45168
  }));
45169
45169
  try {
45170
45170
  await this.sendInnerFrame(inner, {
@@ -45196,13 +45196,13 @@ var FetchproxyServer = class {
45196
45196
  try {
45197
45197
  return await Promise.race([
45198
45198
  pending,
45199
- new Promise((resolve7) => {
45199
+ new Promise((resolve8) => {
45200
45200
  timer = setTimeout(() => {
45201
- this.pending.delete(id);
45201
+ this.pending.delete(id2);
45202
45202
  const elapsedMs = Date.now() - start;
45203
45203
  const base = `fetchproxy: ${init.url} did not respond within ${timeoutMs}ms`;
45204
45204
  const error62 = isRetrySafeOnTimeout(init.method, fetchOpts.retryOnTimeout) ? base : withNotResentNote(base);
45205
- resolve7({
45205
+ resolve8({
45206
45206
  ok: false,
45207
45207
  error: error62,
45208
45208
  kind: "timeout",
@@ -45262,7 +45262,7 @@ var FetchproxyServer = class {
45262
45262
  });
45263
45263
  return pending;
45264
45264
  }
45265
- async _withVerbTimeout(pending, pendingMap, id, url2, requestedTimeoutMs, retrySafe = true) {
45265
+ async _withVerbTimeout(pending, pendingMap, id2, url2, requestedTimeoutMs, retrySafe = true) {
45266
45266
  const transportMs = this.opts.fetchTimeoutMs;
45267
45267
  if (transportMs === void 0 || transportMs <= 0)
45268
45268
  return pending;
@@ -45275,7 +45275,7 @@ var FetchproxyServer = class {
45275
45275
  pending,
45276
45276
  new Promise((_resolve, reject) => {
45277
45277
  timer = setTimeout(() => {
45278
- pendingMap.delete(id);
45278
+ pendingMap.delete(id2);
45279
45279
  reject(new FetchproxyTimeoutError({
45280
45280
  url: url2,
45281
45281
  timeoutMs,
@@ -45612,7 +45612,7 @@ var FetchproxyServer = class {
45612
45612
  assertSubdomainLabel(opts.subdomain);
45613
45613
  const baseDomain = this.resolveBaseDomain(opts.domain);
45614
45614
  const host = opts.subdomain ? `${opts.subdomain}.${baseDomain}` : baseDomain;
45615
- const id = this.nextRequestId++;
45615
+ const id2 = this.nextRequestId++;
45616
45616
  let inner;
45617
45617
  if (opts.keys !== void 0) {
45618
45618
  this.assertScopeSubset(opts.keys, this.opts.cookieKeys, "cookieKeys");
@@ -45625,16 +45625,16 @@ var FetchproxyServer = class {
45625
45625
  keys: [...opts.keys],
45626
45626
  ...cookiePath !== void 0 ? { path: cookiePath } : {}
45627
45627
  };
45628
- inner = { type: "request", id, op: "read_cookies", init: initV3 };
45628
+ inner = { type: "request", id: id2, op: "read_cookies", init: initV3 };
45629
45629
  } else {
45630
45630
  const tabUrl = `https://${host}/`;
45631
- inner = { type: "request", id, op: "read_cookies", init: { tabUrl } };
45631
+ inner = { type: "request", id: id2, op: "read_cookies", init: { tabUrl } };
45632
45632
  }
45633
- const pending = this.guardPending(new Promise((resolve7) => {
45634
- this.pendingReadCookies.set(id, resolve7);
45633
+ const pending = this.guardPending(new Promise((resolve8) => {
45634
+ this.pendingReadCookies.set(id2, resolve8);
45635
45635
  }));
45636
45636
  await this.sendInnerFrame(inner);
45637
- const result = await this._withVerbTimeout(pending, this.pendingReadCookies, id, `https://${host}`);
45637
+ const result = await this._withVerbTimeout(pending, this.pendingReadCookies, id2, `https://${host}`);
45638
45638
  if (!result.ok) {
45639
45639
  throw protocolErrorFrom(result.error);
45640
45640
  }
@@ -45676,10 +45676,10 @@ var FetchproxyServer = class {
45676
45676
  const host = opts.subdomain ? `${opts.subdomain}.${baseDomain}` : baseDomain;
45677
45677
  this.assertScopeSubset(names, this.opts.cookieKeys, "cookieKeys");
45678
45678
  const cookiePath = normalizeCookiePath(opts.path);
45679
- const id = this.nextRequestId++;
45679
+ const id2 = this.nextRequestId++;
45680
45680
  const inner = {
45681
45681
  type: "request",
45682
- id,
45682
+ id: id2,
45683
45683
  op: "write_cookies",
45684
45684
  init: {
45685
45685
  // Bare origin, same invariant as the read path: a path must never be
@@ -45689,14 +45689,14 @@ var FetchproxyServer = class {
45689
45689
  ...cookiePath !== void 0 ? { path: cookiePath } : {}
45690
45690
  }
45691
45691
  };
45692
- const pending = this.guardPending(new Promise((resolve7, reject) => {
45693
- this.pendingWriteCookies.set(id, { resolve: resolve7, reject });
45692
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
45693
+ this.pendingWriteCookies.set(id2, { resolve: resolve8, reject });
45694
45694
  }));
45695
45695
  await this.sendInnerFrame(inner);
45696
45696
  return this._withVerbTimeout(
45697
45697
  pending,
45698
45698
  this.pendingWriteCookies,
45699
- id,
45699
+ id2,
45700
45700
  `https://${host}`,
45701
45701
  void 0,
45702
45702
  // A write: never re-sent after an ambiguous timeout.
@@ -45749,10 +45749,10 @@ var FetchproxyServer = class {
45749
45749
  assertSubdomainLabel(opts.subdomain);
45750
45750
  const baseDomain = this.resolveBaseDomain(opts.domain);
45751
45751
  const host = opts.subdomain ? `${opts.subdomain}.${baseDomain}` : baseDomain;
45752
- const id = this.nextRequestId++;
45752
+ const id2 = this.nextRequestId++;
45753
45753
  const inner = {
45754
45754
  type: "request",
45755
- id,
45755
+ id: id2,
45756
45756
  op,
45757
45757
  init: {
45758
45758
  origin: `https://${host}`,
@@ -45760,11 +45760,11 @@ var FetchproxyServer = class {
45760
45760
  ...opts.pointers ? { pointers: { ...opts.pointers } } : {}
45761
45761
  }
45762
45762
  };
45763
- const pending = this.guardPending(new Promise((resolve7, reject) => {
45764
- this.pendingStorage.set(id, { resolve: resolve7, reject });
45763
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
45764
+ this.pendingStorage.set(id2, { resolve: resolve8, reject });
45765
45765
  }));
45766
45766
  await this.sendInnerFrame(inner);
45767
- return this._withVerbTimeout(pending, this.pendingStorage, id, `https://${host}`);
45767
+ return this._withVerbTimeout(pending, this.pendingStorage, id2, `https://${host}`);
45768
45768
  }
45769
45769
  /**
45770
45770
  * 0.3.0+: snapshot the next outgoing request's named header. Single-
@@ -45807,10 +45807,10 @@ var FetchproxyServer = class {
45807
45807
  return this.withLazyRevive("capture_request_header", `https://${resolved.host}${resolved.path ?? "/*"}`, () => this._captureRequestHeaderOnce(callOpts));
45808
45808
  }
45809
45809
  async _captureRequestHeaderOnce(opts) {
45810
- const id = this.nextRequestId++;
45810
+ const id2 = this.nextRequestId++;
45811
45811
  const inner = {
45812
45812
  type: "request",
45813
- id,
45813
+ id: id2,
45814
45814
  op: "capture_request_header",
45815
45815
  init: {
45816
45816
  host: opts.host,
@@ -45819,14 +45819,14 @@ var FetchproxyServer = class {
45819
45819
  ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {}
45820
45820
  }
45821
45821
  };
45822
- const pending = this.guardPending(new Promise((resolve7, reject) => {
45823
- this.pendingCapture.set(id, { resolve: resolve7, reject });
45822
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
45823
+ this.pendingCapture.set(id2, { resolve: resolve8, reject });
45824
45824
  }));
45825
45825
  await this.sendInnerFrame(inner);
45826
45826
  return this._withVerbTimeout(
45827
45827
  pending,
45828
45828
  this.pendingCapture,
45829
- id,
45829
+ id2,
45830
45830
  `https://${opts.host}${opts.path ?? "/*"}`,
45831
45831
  // #237: this GOVERNS the deadline (window + reply grace, floored at the
45832
45832
  // transport bound). Under #277 it did not, and was passed only so the
@@ -45856,10 +45856,10 @@ var FetchproxyServer = class {
45856
45856
  return this.withLazyRevive("capture_redirect", `https://${opts.host}${opts.path ?? "/*"}`, () => this._captureRedirectOnce(opts));
45857
45857
  }
45858
45858
  async _captureRedirectOnce(opts) {
45859
- const id = this.nextRequestId++;
45859
+ const id2 = this.nextRequestId++;
45860
45860
  const inner = {
45861
45861
  type: "request",
45862
- id,
45862
+ id: id2,
45863
45863
  op: "capture_redirect",
45864
45864
  init: {
45865
45865
  host: opts.host,
@@ -45867,14 +45867,14 @@ var FetchproxyServer = class {
45867
45867
  ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {}
45868
45868
  }
45869
45869
  };
45870
- const pending = this.guardPending(new Promise((resolve7, reject) => {
45871
- this.pendingRedirect.set(id, { resolve: resolve7, reject });
45870
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
45871
+ this.pendingRedirect.set(id2, { resolve: resolve8, reject });
45872
45872
  }));
45873
45873
  await this.sendInnerFrame(inner);
45874
45874
  return this._withVerbTimeout(
45875
45875
  pending,
45876
45876
  this.pendingRedirect,
45877
- id,
45877
+ id2,
45878
45878
  `https://${opts.host}${opts.path ?? "/*"}`,
45879
45879
  // #237: this GOVERNS the deadline (window + reply grace, floored at the
45880
45880
  // transport bound). Under #277 it did not, and was passed only so the
@@ -45952,10 +45952,10 @@ var FetchproxyServer = class {
45952
45952
  }
45953
45953
  }
45954
45954
  async _downloadOnce(opts) {
45955
- const id = this.nextRequestId++;
45955
+ const id2 = this.nextRequestId++;
45956
45956
  const inner = {
45957
45957
  type: "request",
45958
- id,
45958
+ id: id2,
45959
45959
  op: "download",
45960
45960
  init: {
45961
45961
  url: opts.url,
@@ -45963,14 +45963,14 @@ var FetchproxyServer = class {
45963
45963
  ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {}
45964
45964
  }
45965
45965
  };
45966
- const pending = this.guardPending(new Promise((resolve7, reject) => {
45967
- this.pendingDownload.set(id, { resolve: resolve7, reject });
45966
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
45967
+ this.pendingDownload.set(id2, { resolve: resolve8, reject });
45968
45968
  }));
45969
45969
  await this.sendInnerFrame(inner);
45970
45970
  return this._withVerbTimeout(
45971
45971
  pending,
45972
45972
  this.pendingDownload,
45973
- id,
45973
+ id2,
45974
45974
  opts.url,
45975
45975
  // `download` takes a per-call timeoutMs like the two capture verbs, so
45976
45976
  // it is governed by it like them (#237). It used to hit the identical
@@ -46012,10 +46012,10 @@ var FetchproxyServer = class {
46012
46012
  throw new Error(`FetchproxyServer.readIndexedDb: (origin=${origin}, database=${JSON.stringify(opts.database)}, store=${JSON.stringify(opts.store)}) not declared in indexedDbScopes`);
46013
46013
  }
46014
46014
  this.assertScopeSubset(opts.keys, decl.keys, "indexedDbScopes.keys");
46015
- const id = this.nextRequestId++;
46015
+ const id2 = this.nextRequestId++;
46016
46016
  const inner = {
46017
46017
  type: "request",
46018
- id,
46018
+ id: id2,
46019
46019
  op: "read_indexed_db",
46020
46020
  init: {
46021
46021
  origin,
@@ -46024,11 +46024,11 @@ var FetchproxyServer = class {
46024
46024
  keys: [...opts.keys]
46025
46025
  }
46026
46026
  };
46027
- const pending = this.guardPending(new Promise((resolve7, reject) => {
46028
- this.pendingIdb.set(id, { resolve: resolve7, reject });
46027
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
46028
+ this.pendingIdb.set(id2, { resolve: resolve8, reject });
46029
46029
  }));
46030
46030
  await this.sendInnerFrame(inner);
46031
- return this._withVerbTimeout(pending, this.pendingIdb, id, origin);
46031
+ return this._withVerbTimeout(pending, this.pendingIdb, id2, origin);
46032
46032
  }
46033
46033
  /**
46034
46034
  * 1.4.0+: read declared DOM values from the user's signed-in tab.
@@ -46057,18 +46057,18 @@ var FetchproxyServer = class {
46057
46057
  const baseDomain = this.resolveBaseDomain(opts.domain);
46058
46058
  const host = opts.subdomain ? `${opts.subdomain}.${baseDomain}` : baseDomain;
46059
46059
  const origin = `https://${host}`;
46060
- const id = this.nextRequestId++;
46060
+ const id2 = this.nextRequestId++;
46061
46061
  const inner = {
46062
46062
  type: "request",
46063
- id,
46063
+ id: id2,
46064
46064
  op: "read_dom",
46065
46065
  init: { origin, names: [...opts.names] }
46066
46066
  };
46067
- const pending = this.guardPending(new Promise((resolve7, reject) => {
46068
- this.pendingStorage.set(id, { resolve: resolve7, reject });
46067
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
46068
+ this.pendingStorage.set(id2, { resolve: resolve8, reject });
46069
46069
  }));
46070
46070
  await this.sendInnerFrame(inner);
46071
- return this._withVerbTimeout(pending, this.pendingStorage, id, origin);
46071
+ return this._withVerbTimeout(pending, this.pendingStorage, id2, origin);
46072
46072
  }
46073
46073
  /**
46074
46074
  * 3.1.0+: read a declared REPEATED DOM structure from the user's
@@ -46103,18 +46103,18 @@ var FetchproxyServer = class {
46103
46103
  const baseDomain = this.resolveBaseDomain(opts.domain);
46104
46104
  const host = opts.subdomain ? `${opts.subdomain}.${baseDomain}` : baseDomain;
46105
46105
  const origin = `https://${host}`;
46106
- const id = this.nextRequestId++;
46106
+ const id2 = this.nextRequestId++;
46107
46107
  const inner = {
46108
46108
  type: "request",
46109
- id,
46109
+ id: id2,
46110
46110
  op: "read_dom_list",
46111
46111
  init: { origin, name: opts.name }
46112
46112
  };
46113
- const pending = this.guardPending(new Promise((resolve7, reject) => {
46114
- this.pendingDomList.set(id, { resolve: resolve7, reject });
46113
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
46114
+ this.pendingDomList.set(id2, { resolve: resolve8, reject });
46115
46115
  }));
46116
46116
  await this.sendInnerFrame(inner);
46117
- return this._withVerbTimeout(pending, this.pendingDomList, id, origin);
46117
+ return this._withVerbTimeout(pending, this.pendingDomList, id2, origin);
46118
46118
  }
46119
46119
  /**
46120
46120
  * 1.x+: run a declared GraphQL operation through the page's own Apollo
@@ -46145,10 +46145,10 @@ var FetchproxyServer = class {
46145
46145
  }
46146
46146
  await this.ensureConnected();
46147
46147
  this.throwIfPendingPair();
46148
- const id = this.nextRequestId++;
46148
+ const id2 = this.nextRequestId++;
46149
46149
  const inner = {
46150
46150
  type: "request",
46151
- id,
46151
+ id: id2,
46152
46152
  op: "graphql_query",
46153
46153
  init: {
46154
46154
  name: opts.name,
@@ -46156,12 +46156,12 @@ var FetchproxyServer = class {
46156
46156
  ...opts.tabUrl !== void 0 ? { tabUrl: opts.tabUrl } : {}
46157
46157
  }
46158
46158
  };
46159
- const pending = this.guardPending(new Promise((resolve7, reject) => {
46160
- this.pendingGraphql.set(id, { resolve: resolve7, reject });
46159
+ const pending = this.guardPending(new Promise((resolve8, reject) => {
46160
+ this.pendingGraphql.set(id2, { resolve: resolve8, reject });
46161
46161
  }));
46162
46162
  const retrySafe = opts.retryOnTimeout === true;
46163
46163
  await this.sendInnerFrame(inner, { resendable: retrySafe });
46164
- return this._withVerbTimeout(pending, this.pendingGraphql, id, opts.name, void 0, retrySafe);
46164
+ return this._withVerbTimeout(pending, this.pendingGraphql, id2, opts.name, void 0, retrySafe);
46165
46165
  }
46166
46166
  assertScopeSubset(requested, declared, label) {
46167
46167
  const undeclared = undeclaredKeys(requested, declared);
@@ -46361,9 +46361,9 @@ var FetchproxyServer = class {
46361
46361
  }
46362
46362
  }
46363
46363
  rejectAllPending(reason = "extension disconnected", keep = /* @__PURE__ */ new Set()) {
46364
- for (const id of this.allPendingIds()) {
46365
- if (!keep.has(id))
46366
- this.rejectPendingId(id, reason);
46364
+ for (const id2 of this.allPendingIds()) {
46365
+ if (!keep.has(id2))
46366
+ this.rejectPendingId(id2, reason);
46367
46367
  }
46368
46368
  if (keep.size === 0)
46369
46369
  this.resendable.clear();
@@ -46372,8 +46372,8 @@ var FetchproxyServer = class {
46372
46372
  allPendingIds() {
46373
46373
  const ids = [];
46374
46374
  for (const map2 of this.pendingMaps())
46375
- for (const id of map2.keys())
46376
- ids.push(id);
46375
+ for (const id2 of map2.keys())
46376
+ ids.push(id2);
46377
46377
  return ids;
46378
46378
  }
46379
46379
  pendingMaps() {
@@ -46390,16 +46390,16 @@ var FetchproxyServer = class {
46390
46390
  this.pendingGraphql
46391
46391
  ];
46392
46392
  }
46393
- isPendingId(id) {
46394
- return this.pendingMaps().some((m) => m.has(id));
46393
+ isPendingId(id2) {
46394
+ return this.pendingMaps().some((m) => m.has(id2));
46395
46395
  }
46396
46396
  /** Fail the one awaiter registered under `id`, in its own map's shape. */
46397
- rejectPendingId(id, reason) {
46397
+ rejectPendingId(id2, reason) {
46398
46398
  const err = new FetchproxyProtocolError(reason);
46399
- this.resendable.delete(id);
46400
- const fetchCb = this.pending.get(id);
46399
+ this.resendable.delete(id2);
46400
+ const fetchCb = this.pending.get(id2);
46401
46401
  if (fetchCb) {
46402
- this.pending.delete(id);
46402
+ this.pending.delete(id2);
46403
46403
  fetchCb({
46404
46404
  ok: false,
46405
46405
  error: err.message,
@@ -46408,9 +46408,9 @@ var FetchproxyServer = class {
46408
46408
  });
46409
46409
  return;
46410
46410
  }
46411
- const cookieCb = this.pendingReadCookies.get(id);
46411
+ const cookieCb = this.pendingReadCookies.get(id2);
46412
46412
  if (cookieCb) {
46413
- this.pendingReadCookies.delete(id);
46413
+ this.pendingReadCookies.delete(id2);
46414
46414
  cookieCb({ ok: false, error: err.message });
46415
46415
  return;
46416
46416
  }
@@ -46424,9 +46424,9 @@ var FetchproxyServer = class {
46424
46424
  this.pendingDownload,
46425
46425
  this.pendingGraphql
46426
46426
  ]) {
46427
- const entry = map2.get(id);
46427
+ const entry = map2.get(id2);
46428
46428
  if (entry) {
46429
- map2.delete(id);
46429
+ map2.delete(id2);
46430
46430
  entry.reject(err);
46431
46431
  return;
46432
46432
  }
@@ -46435,9 +46435,9 @@ var FetchproxyServer = class {
46435
46435
  noteResendable(inner) {
46436
46436
  this.resendable.set(inner.id, inner);
46437
46437
  if (this.resendable.size > 256) {
46438
- for (const id of [...this.resendable.keys()]) {
46439
- if (!this.isPendingId(id))
46440
- this.resendable.delete(id);
46438
+ for (const id2 of [...this.resendable.keys()]) {
46439
+ if (!this.isPendingId(id2))
46440
+ this.resendable.delete(id2);
46441
46441
  }
46442
46442
  }
46443
46443
  }
@@ -46452,29 +46452,29 @@ var FetchproxyServer = class {
46452
46452
  */
46453
46453
  async recoverFromHostLoss() {
46454
46454
  const toResend = /* @__PURE__ */ new Map();
46455
- for (const [id, inner] of this.resendable) {
46456
- if (this.isPendingId(id))
46457
- toResend.set(id, inner);
46455
+ for (const [id2, inner] of this.resendable) {
46456
+ if (this.isPendingId(id2))
46457
+ toResend.set(id2, inner);
46458
46458
  }
46459
46459
  this.resendable.clear();
46460
46460
  this.rejectAllPending("fetchproxy: the MCP process holding the bridge port exited while this request was in flight. It was not re-sent because it may already have run in the browser \u2014 check before retrying.", new Set(toResend.keys()));
46461
46461
  if (toResend.size === 0)
46462
46462
  return;
46463
- const lost = (id, e) => this.rejectPendingId(id, `fetchproxy: the bridge host exited and reconnecting failed: ${e instanceof Error ? e.message : String(e)}`);
46463
+ const lost = (id2, e) => this.rejectPendingId(id2, `fetchproxy: the bridge host exited and reconnecting failed: ${e instanceof Error ? e.message : String(e)}`);
46464
46464
  try {
46465
46465
  await this.ensureConnected();
46466
46466
  } catch (e) {
46467
- for (const id of toResend.keys())
46468
- lost(id, e);
46467
+ for (const id2 of toResend.keys())
46468
+ lost(id2, e);
46469
46469
  return;
46470
46470
  }
46471
- for (const [id, inner] of toResend) {
46472
- if (!this.isPendingId(id))
46471
+ for (const [id2, inner] of toResend) {
46472
+ if (!this.isPendingId(id2))
46473
46473
  continue;
46474
46474
  try {
46475
46475
  await this.resendInnerFrame(inner);
46476
46476
  } catch (e) {
46477
- lost(id, e);
46477
+ lost(id2, e);
46478
46478
  }
46479
46479
  }
46480
46480
  }
@@ -47063,7 +47063,7 @@ function describeTokenlessLogin(record2) {
47063
47063
 
47064
47064
  // src/version.ts
47065
47065
  var SERVER_NAME = "ofw-mcp";
47066
- var VERSION = "2.21.0";
47066
+ var VERSION = "2.23.0";
47067
47067
 
47068
47068
  // src/auth.ts
47069
47069
  function fetchproxyDisabled() {
@@ -47437,6 +47437,17 @@ function displayTimeZone() {
47437
47437
  if (configured && isValidTimeZone(configured)) return configured;
47438
47438
  return DEFAULT_DISPLAY_TZ;
47439
47439
  }
47440
+ function resolveTimeZoneArg(tz) {
47441
+ const requested = tz?.trim();
47442
+ if (!requested) return displayTimeZone();
47443
+ if (/^(?:UTC|GMT)?[+-]\d/i.test(requested)) {
47444
+ throw new Error(`timeZone "${requested}" is a fixed offset, which is an hour wrong for half the year once DST changes. Pass an IANA zone such as America/Chicago.`);
47445
+ }
47446
+ if (!isValidTimeZone(requested)) {
47447
+ throw new Error(`timeZone "${requested}" is not a recognised IANA zone. Pass one such as America/Chicago or Europe/London.`);
47448
+ }
47449
+ return requested;
47450
+ }
47440
47451
  function offsetAt(instant, tz) {
47441
47452
  const w = wallPartsIn(instant, tz);
47442
47453
  const asUTC = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second, instant.getUTCMilliseconds());
@@ -47646,12 +47657,12 @@ function normalizeTimestampsInValue(value, tz = displayTimeZone()) {
47646
47657
  }
47647
47658
 
47648
47659
  // src/tools/_shared.ts
47649
- function jsonResponse(data) {
47650
- return minifiedResult(normalizeTimestampsInValue(data));
47660
+ function jsonResponse(data, tz) {
47661
+ return minifiedResult(normalizeTimestampsInValue(data, tz));
47651
47662
  }
47652
47663
  var textResponse = rawTextResult;
47653
- function jsonText(data) {
47654
- return JSON.stringify(normalizeTimestampsInValue(data));
47664
+ function jsonText(data, tz) {
47665
+ return JSON.stringify(normalizeTimestampsInValue(data, tz));
47655
47666
  }
47656
47667
  function notedJsonResponse(notes, data, fallback) {
47657
47668
  const text = data ? jsonText(data) : fallback;
@@ -47714,7 +47725,6 @@ function withReadState(row) {
47714
47725
  const listData = typeof row.listData === "object" && row.listData !== null ? { ...row.listData, read, showNeverViewed: !read } : row.listData;
47715
47726
  return { ...row, read, listData };
47716
47727
  }
47717
- var expandPath2 = expandPath;
47718
47728
  function verifyWriteLanded(kind, sent, persisted) {
47719
47729
  const mismatches = [];
47720
47730
  if (typeof persisted.subject !== "string" || !persisted.subject.includes(sent.subject)) {
@@ -47760,7 +47770,7 @@ function unconfirmedWriteResponse(e, opts) {
47760
47770
  remedy: `Do NOT retry blindly \u2014 a second attempt can put a duplicate on the co-parent-visible record. First check with ${opts.checkWith}${fallback}, and retry only once you have confirmed it did not land.`
47761
47771
  });
47762
47772
  }
47763
- async function postMessageAndRefetch(client2, payload, detailSchema, ctx) {
47773
+ async function postMessageAndRefetch(client2, payload, detailSchema2, ctx) {
47764
47774
  let posted;
47765
47775
  try {
47766
47776
  posted = await client2.request("POST", "/pub/v3/messages", payload);
@@ -47772,20 +47782,20 @@ async function postMessageAndRefetch(client2, payload, detailSchema, ctx) {
47772
47782
  posted,
47773
47783
  { label: "ofw-mcp", context: `POST /pub/v3/messages (${ctx})`, mode: "strict" }
47774
47784
  );
47775
- const id = typeof raw?.id === "number" ? raw.id : typeof raw?.entityId === "number" ? raw.entityId : null;
47776
- if (id === null) return { id: null, detail: null, raw };
47785
+ const id2 = typeof raw?.id === "number" ? raw.id : typeof raw?.entityId === "number" ? raw.entityId : null;
47786
+ if (id2 === null) return { id: null, detail: null, raw };
47777
47787
  let fetched;
47778
47788
  try {
47779
- fetched = await client2.request("GET", `/pub/v3/messages/${id}`);
47789
+ fetched = await client2.request("GET", `/pub/v3/messages/${id2}`);
47780
47790
  } catch (e) {
47781
- throw new UnconfirmedWriteError(id, e);
47791
+ throw new UnconfirmedWriteError(id2, e);
47782
47792
  }
47783
47793
  const detail = parseLenient(
47784
- detailSchema,
47794
+ detailSchema2,
47785
47795
  fetched,
47786
47796
  { label: "ofw-mcp", context: `GET /pub/v3/messages/{id} (${ctx})`, mode: "strict" }
47787
47797
  );
47788
- return { id, detail, raw };
47798
+ return { id: id2, detail, raw };
47789
47799
  }
47790
47800
 
47791
47801
  // src/tools/user.ts
@@ -48303,8 +48313,8 @@ async function syncDrafts(client2, draftsFolderId, store, budget) {
48303
48313
  }
48304
48314
  }
48305
48315
  const seenIds = new Set(ids);
48306
- for (const id of await store.listDraftIds()) {
48307
- if (!seenIds.has(id)) await store.deleteDraft(id);
48316
+ for (const id2 of await store.listDraftIds()) {
48317
+ if (!seenIds.has(id2)) await store.deleteDraft(id2);
48308
48318
  }
48309
48319
  const now = (/* @__PURE__ */ new Date()).toISOString();
48310
48320
  await setDraftsCacheStatus(store, "fresh");
@@ -48649,14 +48659,14 @@ var ServerDraftSchema = external_exports.looseObject({
48649
48659
  function isNotFound(e) {
48650
48660
  return e instanceof Error && /OFW API error: 404\b/.test(e.message);
48651
48661
  }
48652
- async function fetchMessageSnapshot(client2, id) {
48662
+ async function fetchMessageSnapshot(client2, id2) {
48653
48663
  let raw;
48654
48664
  try {
48655
- raw = await client2.request("GET", `/pub/v3/messages/${id}`);
48665
+ raw = await client2.request("GET", `/pub/v3/messages/${id2}`);
48656
48666
  } catch (e) {
48657
48667
  if (isNotFound(e)) return null;
48658
48668
  throw new DraftFreshnessError(
48659
- `could not read the current state of draft ${id} from OurFamilyWizard: ${e.message}`
48669
+ `could not read the current state of draft ${id2} from OurFamilyWizard: ${e.message}`
48660
48670
  );
48661
48671
  }
48662
48672
  if (raw === null || raw === void 0) return null;
@@ -48678,8 +48688,8 @@ async function fetchMessageSnapshot(client2, id) {
48678
48688
  dateTime: detail.date?.dateTime ?? null
48679
48689
  };
48680
48690
  }
48681
- async function fetchServerDraft(client2, id) {
48682
- return (await fetchMessageSnapshot(client2, id))?.content ?? null;
48691
+ async function fetchServerDraft(client2, id2) {
48692
+ return (await fetchMessageSnapshot(client2, id2))?.content ?? null;
48683
48693
  }
48684
48694
  var SUBSTANTIVE_FIELDS = ["subject", "body", "recipients"];
48685
48695
  function substantiveChanges(changed) {
@@ -48846,11 +48856,11 @@ function stateNote(state, cachedAsDraft, folderName) {
48846
48856
  async function probeIds(client2, store, ids, opts) {
48847
48857
  const draftsById = new Map((await store.getDrafts(ids)).map((d) => [d.id, d]));
48848
48858
  const messagesById = new Map((await store.getMessages(ids)).map((m) => [m.id, m]));
48849
- const prepared = ids.map((id) => {
48850
- const cachedDraft = draftsById.get(id) ?? null;
48851
- const cachedMessage = cachedDraft === null ? messagesById.get(id) ?? null : null;
48859
+ const prepared = ids.map((id2) => {
48860
+ const cachedDraft = draftsById.get(id2) ?? null;
48861
+ const cachedMessage = cachedDraft === null ? messagesById.get(id2) ?? null : null;
48852
48862
  return {
48853
- id,
48863
+ id: id2,
48854
48864
  cachedDraft,
48855
48865
  cachedMessage,
48856
48866
  skip: !opts.allowMarkRead && probeWouldStamp(cachedDraft, cachedMessage)
@@ -48879,15 +48889,15 @@ async function probeIds(client2, store, ids, opts) {
48879
48889
  return { items, requests };
48880
48890
  }
48881
48891
  async function probeOne(client2, prepared, map2, draftKey) {
48882
- const { id, cachedDraft } = prepared;
48892
+ const { id: id2, cachedDraft } = prepared;
48883
48893
  let snapshot;
48884
48894
  try {
48885
- snapshot = await fetchMessageSnapshot(client2, id);
48895
+ snapshot = await fetchMessageSnapshot(client2, id2);
48886
48896
  } catch (e) {
48887
48897
  return {
48888
48898
  requests: 1,
48889
48899
  item: {
48890
- id,
48900
+ id: id2,
48891
48901
  error: "FRESHNESS_CHECK_FAILED",
48892
48902
  message: e.message,
48893
48903
  inSync: null,
@@ -48917,7 +48927,7 @@ async function probeOne(client2, prepared, map2, draftKey) {
48917
48927
  return {
48918
48928
  requests: 1,
48919
48929
  item: {
48920
- id,
48930
+ id: id2,
48921
48931
  state,
48922
48932
  folder: snapshot?.folderName ?? null,
48923
48933
  sentAt: state === "sent" ? snapshot?.dateTime ?? null : null,
@@ -48943,6 +48953,13 @@ function newDraftKey() {
48943
48953
  // src/tools/_confirm.ts
48944
48954
  var CONFIRM_NOTE = "Asks the user to confirm first: a confirmation prompt where the client supports one; otherwise the first call performs NO write and returns a preview of exactly what would happen plus a confirmToken, and only a repeat call with that token proceeds (see MCP_CONFIRM_MODE).";
48945
48955
  function confirmWrite2(ctx, opts) {
48956
+ const { confirmToken: _confirmToken, ...args } = opts.args;
48957
+ const subject = {
48958
+ target: opts.target,
48959
+ ...opts.revision !== void 0 ? { revision: opts.revision } : {},
48960
+ payload: opts.payload,
48961
+ preview: opts.preview
48962
+ };
48946
48963
  return requireConfirmationWithFallback(
48947
48964
  ctx,
48948
48965
  confirmationFromEnv({
@@ -48954,14 +48971,9 @@ function confirmWrite2(ctx, opts) {
48954
48971
  // One OFW account per process (OFW_USERNAME / the captured session), so
48955
48972
  // there is no principal to distinguish; mcp-utils 3 makes saying so explicit.
48956
48973
  account: void 0,
48957
- args: opts.args,
48974
+ args: { tool: opts.tool, action: opts.action, args, ...subject },
48958
48975
  confirmToken: opts.confirmToken,
48959
- subject: () => ({
48960
- target: opts.target,
48961
- ...opts.revision !== void 0 ? { revision: opts.revision } : {},
48962
- payload: opts.payload,
48963
- preview: opts.preview
48964
- })
48976
+ subject: () => subject
48965
48977
  })
48966
48978
  );
48967
48979
  }
@@ -49152,10 +49164,10 @@ async function readRels(zip, partPath) {
49152
49164
  if (!xml) return [];
49153
49165
  const rels = [];
49154
49166
  for (const el of elements(xml, "Relationship")) {
49155
- const id = attr(el.attrs, "Id");
49167
+ const id2 = attr(el.attrs, "Id");
49156
49168
  const target = attr(el.attrs, "Target");
49157
- if (!id || !target) continue;
49158
- rels.push({ id, target: resolvePartPath(dir, target), type: attr(el.attrs, "Type") ?? "" });
49169
+ if (!id2 || !target) continue;
49170
+ rels.push({ id: id2, target: resolvePartPath(dir, target), type: attr(el.attrs, "Type") ?? "" });
49159
49171
  }
49160
49172
  return rels;
49161
49173
  }
@@ -49203,15 +49215,15 @@ async function readStyles(zip, dir) {
49203
49215
  if (!xml) return { dateStyles: [] };
49204
49216
  const custom2 = /* @__PURE__ */ new Map();
49205
49217
  for (const el of elements(xml, "numFmt")) {
49206
- const id = Number(attr(el.attrs, "numFmtId"));
49218
+ const id2 = Number(attr(el.attrs, "numFmtId"));
49207
49219
  const code2 = attr(el.attrs, "formatCode");
49208
- if (Number.isFinite(id) && code2 !== null) custom2.set(id, code2);
49220
+ if (Number.isFinite(id2) && code2 !== null) custom2.set(id2, code2);
49209
49221
  }
49210
49222
  const dateStyles = [];
49211
49223
  for (const block of elements(xml, "cellXfs")) {
49212
49224
  for (const xf of elements(block.inner, "xf")) {
49213
- const id = Number(attr(xf.attrs, "numFmtId") ?? "0");
49214
- dateStyles.push(isDateFormat(id, custom2.get(id)));
49225
+ const id2 = Number(attr(xf.attrs, "numFmtId") ?? "0");
49226
+ dateStyles.push(isDateFormat(id2, custom2.get(id2)));
49215
49227
  }
49216
49228
  }
49217
49229
  return { dateStyles };
@@ -49876,11 +49888,21 @@ async function extractAttachment(bytes, mimeType, fileName, opts = {}) {
49876
49888
 
49877
49889
  // src/tools/attachments.ts
49878
49890
  import { chmodSync as chmodSync3, readFileSync as readFileSync4, realpathSync as realpathSync3, statSync as statSync3, mkdirSync as mkdirSync5, unlinkSync as unlinkSync5 } from "node:fs";
49879
- import { basename as basename2, dirname as dirname6, extname, isAbsolute as isAbsolute6, relative as relative2, resolve as resolve5, sep as sep2 } from "node:path";
49891
+ import { basename as basename2, dirname as dirname6, extname, isAbsolute as isAbsolute6, join as join11, relative as relative2, resolve as resolve5, sep as sep2 } from "node:path";
49880
49892
  function isWithin(root, candidate) {
49881
49893
  const rel = relative2(root, candidate);
49882
49894
  return rel !== "" && !rel.startsWith("..") && !isAbsolute6(rel);
49883
49895
  }
49896
+ function resolveSaveDest(root, saveTo, defaultName) {
49897
+ if (!saveTo) return join11(root, defaultName);
49898
+ const isDirArg = saveTo.endsWith("/") || saveTo.endsWith("\\");
49899
+ const abs = resolve5(root, saveTo.startsWith("~") ? expandPath(saveTo) : saveTo);
49900
+ const dest = isDirArg ? join11(abs, defaultName) : abs;
49901
+ if (!isWithin(root, dest)) {
49902
+ throw new Error(`Refusing to save to ${dest}: it is outside the attachments directory (${root}). Files can only be written inside it \u2014 pass a path or subdirectory under it, or set OFW_ATTACHMENTS_DIR to move it.`);
49903
+ }
49904
+ return dest;
49905
+ }
49884
49906
  var MIME_BY_EXT = {
49885
49907
  ".pdf": "application/pdf",
49886
49908
  ".png": "image/png",
@@ -50073,7 +50095,7 @@ async function buildInlineDelivery(input2) {
50073
50095
  }
50074
50096
 
50075
50097
  // src/tools/messages.ts
50076
- import { basename as basename3, join as join11, resolve as resolve6 } from "node:path";
50098
+ import { basename as basename3, resolve as resolve6 } from "node:path";
50077
50099
 
50078
50100
  // src/tools/pagination.ts
50079
50101
  function pageState(input2) {
@@ -50360,7 +50382,7 @@ async function describeRecipients(cache, recipientIds, known) {
50360
50382
  }
50361
50383
  };
50362
50384
  known.forEach(learn);
50363
- if (recipientIds.some((id) => !names.has(id))) {
50385
+ if (recipientIds.some((id2) => !names.has(id2))) {
50364
50386
  for (const row of await cache.listMessages({ page: 1, size: 200 })) learn(row.recipients);
50365
50387
  }
50366
50388
  return recipientIds.map((userId) => ({ userId, name: names.get(userId) ?? null }));
@@ -50505,10 +50527,10 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
50505
50527
  })
50506
50528
  })
50507
50529
  }, async (args) => {
50508
- const id = Number(args.messageId);
50530
+ const id2 = Number(args.messageId);
50509
50531
  const view = resolveView(args.view, MESSAGE_VIEWS);
50510
50532
  const cache = cacheProvider();
50511
- const draftRow = await cache.getDraft(id);
50533
+ const draftRow = await cache.getDraft(id2);
50512
50534
  if (draftRow !== null) {
50513
50535
  const { freshness: freshness2, serverConfirmed, cacheStatus } = await draftsFreshness(cache);
50514
50536
  return jsonResponse({
@@ -50553,17 +50575,17 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
50553
50575
  freshness: freshness2
50554
50576
  });
50555
50577
  }
50556
- const cached2 = await cache.getMessage(id);
50578
+ const cached2 = await cache.getMessage(id2);
50557
50579
  const blocked = readingBlockedToday();
50558
50580
  if (blocked !== null) {
50559
50581
  if (cached2 === null) {
50560
50582
  return jsonErrorResponse({
50561
50583
  ...blocked,
50562
- messageId: id,
50584
+ messageId: id2,
50563
50585
  hint: "This id is not in the cache. Run ofw_sync_messages (it walks list pages, not bodies, and marks nothing read) to see its subject, sender and date."
50564
50586
  });
50565
50587
  }
50566
- const attachments2 = await cache.listAttachmentsForMessage(id);
50588
+ const attachments2 = await cache.listAttachmentsForMessage(id2);
50567
50589
  const freshness2 = await buildFreshness(cache, { source: "cache", folders: [cached2.folder] });
50568
50590
  return jsonResponse({
50569
50591
  readingBlocked: blocked,
@@ -50578,7 +50600,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
50578
50600
  try {
50579
50601
  const detail2 = parseLenient(
50580
50602
  MessageDetailSchema,
50581
- await client2.request("GET", `/pub/v3/messages/${id}`),
50603
+ await client2.request("GET", `/pub/v3/messages/${id2}`),
50582
50604
  { label: "ofw-mcp", context: "GET /pub/v3/messages/{id} (view-status refresh)" }
50583
50605
  );
50584
50606
  const recipients = mapRecipients(detail2.recipients);
@@ -50591,17 +50613,17 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
50591
50613
  } catch {
50592
50614
  }
50593
50615
  }
50594
- let attachments2 = await cache.listAttachmentsForMessage(id);
50616
+ let attachments2 = await cache.listAttachmentsForMessage(id2);
50595
50617
  if (attachments2.length === 0 && listDataHintsAtFiles(row2.listData)) {
50596
50618
  try {
50597
50619
  const detail2 = parseLenient(
50598
50620
  DetailFilesSchema,
50599
- await client2.request("GET", `/pub/v3/messages/${id}`),
50621
+ await client2.request("GET", `/pub/v3/messages/${id2}`),
50600
50622
  { label: "ofw-mcp", context: "GET /pub/v3/messages/{id} (attachment backfill)" }
50601
50623
  );
50602
50624
  if (Array.isArray(detail2.files) && detail2.files.length > 0) {
50603
- await fetchAttachmentMetaForMessage(client2, id, detail2.files, cache);
50604
- attachments2 = await cache.listAttachmentsForMessage(id);
50625
+ await fetchAttachmentMetaForMessage(client2, id2, detail2.files, cache);
50626
+ attachments2 = await cache.listAttachmentsForMessage(id2);
50605
50627
  }
50606
50628
  } catch {
50607
50629
  }
@@ -50700,7 +50722,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
50700
50722
  (s) => s !== null && s !== void 0 && s.recipients.some((r) => r.userId !== 0)
50701
50723
  );
50702
50724
  if (source != null) {
50703
- recipientIds = [...new Set(source.recipients.map((r) => r.userId).filter((id) => id !== 0))];
50725
+ recipientIds = [...new Set(source.recipients.map((r) => r.userId).filter((id2) => id2 !== 0))];
50704
50726
  }
50705
50727
  }
50706
50728
  }
@@ -51178,7 +51200,7 @@ ${jsonText(
51178
51200
  }
51179
51201
  if (myFileIDs.length > 0 && Array.isArray(detail.files)) {
51180
51202
  const storedFiles = new Set(detail.files);
51181
- const missing = myFileIDs.filter((id) => !storedFiles.has(id));
51203
+ const missing = myFileIDs.filter((id2) => !storedFiles.has(id2));
51182
51204
  if (missing.length > 0) {
51183
51205
  warnings.push(
51184
51206
  `Attachment fileId(s) ${missing.join(", ")} were requested in myFileIDs but are not attached to the saved draft. Re-upload or re-attach if needed.`
@@ -51451,19 +51473,9 @@ ${jsonText(
51451
51473
  diskAvailable: attachmentIO.supportsDisk
51452
51474
  });
51453
51475
  }
51454
- let dest;
51455
51476
  const safeName = basename3(cached2.fileName);
51456
51477
  const root = resolve6(getAttachmentsDir());
51457
- if (args.saveTo) {
51458
- const isDirArg = args.saveTo.endsWith("/") || args.saveTo.endsWith("\\");
51459
- const abs = resolve6(root, args.saveTo.startsWith("~") ? expandPath2(args.saveTo) : args.saveTo);
51460
- dest = isDirArg ? join11(abs, `${fileId}-${safeName}`) : abs;
51461
- if (!isWithin(root, dest)) {
51462
- throw new Error(`Refusing to save to ${dest}: it is outside the attachments directory (${root}). Downloads can only be written inside it \u2014 pass a path or subdirectory under it, or set OFW_ATTACHMENTS_DIR to move it.`);
51463
- }
51464
- } else {
51465
- dest = join11(root, `${fileId}-${safeName}`);
51466
- }
51478
+ const dest = resolveSaveDest(root, args.saveTo, `${fileId}-${safeName}`);
51467
51479
  const extractOnDisk = args.extract === true;
51468
51480
  if (!args.force && cached2.downloadedPath === dest) {
51469
51481
  const onDisk = extractOnDisk ? attachmentIO.readDownloaded(dest) : null;
@@ -51601,7 +51613,7 @@ ${jsonText(
51601
51613
  const requestedKeys = args.draftKeys ?? [];
51602
51614
  const wantInventory = args.includeDraftInventory ?? (requestedIds.length === 0 && requestedKeys.length === 0);
51603
51615
  const allTargets = [
51604
- ...requestedIds.map((id) => ({ kind: "id", id })),
51616
+ ...requestedIds.map((id2) => ({ kind: "id", id: id2 })),
51605
51617
  ...requestedKeys.map((draftKey) => ({ kind: "draftKey", draftKey }))
51606
51618
  ];
51607
51619
  const targets = allTargets.slice(0, MAX_FRESHNESS_IDS);
@@ -51714,10 +51726,341 @@ function decorate(item) {
51714
51726
  }
51715
51727
  async function deleteOFWMessages(client2, ids) {
51716
51728
  const form = new FormData();
51717
- for (const id of ids) form.append("messageIds", String(id));
51729
+ for (const id2 of ids) form.append("messageIds", String(id2));
51718
51730
  return client2.request("DELETE", "/pub/v1/messages", form);
51719
51731
  }
51720
51732
 
51733
+ // node_modules/@chrischall/mcp-utils/dist/export/blob.js
51734
+ import { createHmac as createHmac4 } from "node:crypto";
51735
+ var BLOB_DEFAULT_TTL_MS = 60 * 60 * 1e3;
51736
+ var BLOB_MAX_TTL_MS = 24 * 60 * 60 * 1e3;
51737
+ var MAX_KEY_LENGTH = 1024;
51738
+ var SAFE_SEGMENT = /^[A-Za-z0-9._~-]+$/;
51739
+ function configError(reason) {
51740
+ return new McpToolError(`MCP_BLOB_BASE_URL is not usable: ${reason}.`, {
51741
+ hint: "It should look like https://<host>/b/<registrationId> \u2014 check the deployment's environment.",
51742
+ kind: "unknown"
51743
+ });
51744
+ }
51745
+ function parseBase(baseUrl) {
51746
+ let parsed;
51747
+ try {
51748
+ parsed = new URL(baseUrl);
51749
+ } catch {
51750
+ throw configError("not a valid URL");
51751
+ }
51752
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
51753
+ throw configError("scheme must be http(s)");
51754
+ if (parsed.username || parsed.password)
51755
+ throw configError("must not contain credentials");
51756
+ if (parsed.search || parsed.hash)
51757
+ throw configError("must not contain a query or fragment");
51758
+ const path = parsed.pathname.replace(/^\/+|\/+$/g, "");
51759
+ const prefix = path.startsWith("b/") ? path.slice(2) : path;
51760
+ if (!prefix || prefix === "b")
51761
+ throw configError("has no registration path");
51762
+ return { base: `${parsed.origin}/${path}`, prefix };
51763
+ }
51764
+ function badInput(message) {
51765
+ return new McpToolError(message, { kind: "unknown" });
51766
+ }
51767
+ function encodeKey(key) {
51768
+ if (typeof key !== "string" || key.length === 0)
51769
+ throw badInput("Blob key must be a non-empty string.");
51770
+ if (key.length > MAX_KEY_LENGTH)
51771
+ throw badInput(`Blob key is longer than ${MAX_KEY_LENGTH} characters.`);
51772
+ const segments = key.split("/");
51773
+ for (const seg of segments) {
51774
+ if (seg === "" || seg === "." || seg === ".." || !SAFE_SEGMENT.test(seg)) {
51775
+ throw badInput('Blob key must be relative, slash-separated segments of [A-Za-z0-9._~-] with no empty, "." or ".." segment.');
51776
+ }
51777
+ }
51778
+ return segments.map(encodeURIComponent).join("/");
51779
+ }
51780
+ function checkContentType(contentType) {
51781
+ if (typeof contentType !== "string" || contentType.length === 0 || /[\x00-\x1f\x7f]/.test(contentType)) {
51782
+ throw badInput("Blob content type must be a non-empty string without control characters.");
51783
+ }
51784
+ }
51785
+ function expiry(opts) {
51786
+ const ttl = opts?.ttlMs ?? BLOB_DEFAULT_TTL_MS;
51787
+ if (!Number.isFinite(ttl) || ttl <= 0 || ttl > BLOB_MAX_TTL_MS) {
51788
+ throw badInput(`Blob link TTL must be between 1 ms and ${BLOB_MAX_TTL_MS} ms (24h); the gateway refuses longer.`);
51789
+ }
51790
+ return Math.floor((opts?.now ?? Date.now()) + ttl);
51791
+ }
51792
+ function toArrayBuffer(view) {
51793
+ const buf = view.buffer;
51794
+ if (buf instanceof ArrayBuffer && view.byteOffset === 0 && view.byteLength === buf.byteLength)
51795
+ return buf;
51796
+ return view.slice().buffer;
51797
+ }
51798
+ function createBlobStore(opts) {
51799
+ const { base, prefix } = parseBase(opts.baseUrl);
51800
+ const signingKey = opts.signingKey;
51801
+ const sign2 = (payload) => createHmac4("sha256", signingKey).update(payload).digest("base64url");
51802
+ const link2 = (encodedKey, exp, sig) => `${base}/${encodedKey}?exp=${exp}&sig=${encodeURIComponent(sig)}`;
51803
+ const signGetUrl = (key, o) => {
51804
+ const encoded = encodeKey(key);
51805
+ const exp = expiry(o);
51806
+ return { url: link2(encoded, exp, sign2(`${prefix}/${key}
51807
+ ${exp}`)), expiresAtMs: exp };
51808
+ };
51809
+ const signPutUrl = (key, contentType, o) => {
51810
+ const encoded = encodeKey(key);
51811
+ checkContentType(contentType);
51812
+ const exp = expiry(o);
51813
+ return { url: link2(encoded, exp, sign2(`put\0${prefix}/${key}\0${contentType}\0${exp}`)), expiresAtMs: exp };
51814
+ };
51815
+ const put = async (key, body, contentType, o = {}) => {
51816
+ const { url: url2 } = signPutUrl(key, contentType, o);
51817
+ const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
51818
+ const doFetch = o.fetchImpl ?? fetch;
51819
+ let res;
51820
+ try {
51821
+ res = await doFetch(url2, {
51822
+ method: "PUT",
51823
+ headers: { "content-type": contentType },
51824
+ body: toArrayBuffer(bytes),
51825
+ ...o.signal ? { signal: o.signal } : {}
51826
+ });
51827
+ } catch (cause) {
51828
+ if (o.signal?.aborted)
51829
+ throw cause;
51830
+ throw new McpToolError(`Blob store upload of ${key} did not complete (network error).`, {
51831
+ kind: "transport"
51832
+ });
51833
+ }
51834
+ if (!res.ok) {
51835
+ throw new McpToolError(`Blob store upload of ${key} failed (HTTP ${res.status}).`, {
51836
+ kind: "http",
51837
+ status: res.status
51838
+ });
51839
+ }
51840
+ return { key, bytes: bytes.byteLength };
51841
+ };
51842
+ return { baseUrl: base, prefix, signGetUrl, signPutUrl, put };
51843
+ }
51844
+ function blobStoreFromEnv(env = process.env) {
51845
+ const baseUrl = readEnvVar("MCP_BLOB_BASE_URL", { env });
51846
+ const signingKey = readEnvVar("MCP_BLOB_SIGNING_KEY", { env });
51847
+ if (!baseUrl || !signingKey)
51848
+ return void 0;
51849
+ return createBlobStore({ baseUrl, signingKey });
51850
+ }
51851
+
51852
+ // node_modules/@chrischall/mcp-utils/dist/export/zip.js
51853
+ var CRC_TABLE = (() => {
51854
+ const table = new Uint32Array(256);
51855
+ for (let n = 0; n < 256; n++) {
51856
+ let c = n;
51857
+ for (let k = 0; k < 8; k++)
51858
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
51859
+ table[n] = c >>> 0;
51860
+ }
51861
+ return table;
51862
+ })();
51863
+
51864
+ // node_modules/@chrischall/mcp-utils/dist/export/sink.js
51865
+ var EXPORT_BLOB_MAX_BYTES = 256 * 1024 * 1024;
51866
+
51867
+ // src/tools/calendar.ts
51868
+ import { randomUUID as randomUUID2 } from "node:crypto";
51869
+ import { resolve as resolve7 } from "node:path";
51870
+
51871
+ // src/tools/calendar-ics.ts
51872
+ var CALENDAR_ITEM_TYPES = ["EVENT", "CONNECTED_EVENT", "TRANSITION", "SCHEDULE"];
51873
+ var isObject2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
51874
+ function itemsOf(data) {
51875
+ const items = isObject2(data) ? data.calendarItems : void 0;
51876
+ return Array.isArray(items) ? items.filter(isObject2) : [];
51877
+ }
51878
+ function filterCalendarTypes(data, types) {
51879
+ if (!types?.length || !isObject2(data)) return data;
51880
+ const wanted = new Set(types);
51881
+ const { calendarItems: _items, guardianData, ...rest } = data;
51882
+ const out = { ...rest };
51883
+ if (Array.isArray(data.calendarItems)) {
51884
+ out.calendarItems = data.calendarItems.filter((i) => isObject2(i) && wanted.has(String(i.type)));
51885
+ }
51886
+ if (wanted.has("SCHEDULE") && guardianData !== void 0) out.guardianData = guardianData;
51887
+ return out;
51888
+ }
51889
+ function escapeText(value) {
51890
+ return value.replace(/\\/g, "\\\\").replace(/\r\n|\r|\n/g, "\\n").replace(/;/g, "\\;").replace(/,/g, "\\,");
51891
+ }
51892
+ function fold(line) {
51893
+ const out = [];
51894
+ let current = "";
51895
+ let size = 0;
51896
+ for (const char of line) {
51897
+ const bytes = Buffer.byteLength(char, "utf8");
51898
+ if (size + bytes > 75) {
51899
+ out.push(current);
51900
+ current = " ";
51901
+ size = 1;
51902
+ }
51903
+ current += char;
51904
+ size += bytes;
51905
+ }
51906
+ out.push(current);
51907
+ return out.join("\r\n");
51908
+ }
51909
+ var utcStamp = (d) => d.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
51910
+ function dateTimeOf(item, field) {
51911
+ const value = item[field];
51912
+ return isObject2(value) && typeof value.dateTime === "string" ? value.dateTime : void 0;
51913
+ }
51914
+ function instantOf(item, field, tz) {
51915
+ const raw = dateTimeOf(item, field);
51916
+ return raw === void 0 ? null : parseTimestampValue(field, raw, tz);
51917
+ }
51918
+ function wallDateOf(item, field) {
51919
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(dateTimeOf(item, field) ?? "");
51920
+ return m && parseTimestampValue(field, `${m[0]}T00:00:00`, "UTC") ? `${m[1]}${m[2]}${m[3]}` : null;
51921
+ }
51922
+ function nextDay(yyyymmdd) {
51923
+ const d = new Date(Date.UTC(Number(yyyymmdd.slice(0, 4)), Number(yyyymmdd.slice(4, 6)) - 1, Number(yyyymmdd.slice(6)) + 1));
51924
+ return d.toISOString().slice(0, 10).replace(/-/g, "");
51925
+ }
51926
+ var idOf = (item) => Number.isSafeInteger(item.id) && item.id > 0 ? item.id : null;
51927
+ function parentOf(value) {
51928
+ if (!isObject2(value) || typeof value.userId !== "number") return null;
51929
+ const name = typeof value.name === "string" && value.name.trim() ? value.name.trim() : `parent ${value.userId}`;
51930
+ return { userId: value.userId, name };
51931
+ }
51932
+ function buildCalendarIcs(data, opts) {
51933
+ const tz = opts.timeZone;
51934
+ const stamp = utcStamp(opts.now ?? /* @__PURE__ */ new Date());
51935
+ const omitted = [];
51936
+ const vevents = [];
51937
+ const issued = /* @__PURE__ */ new Map();
51938
+ let events = 0;
51939
+ let custodyPeriods = 0;
51940
+ const vevent = (uid, props) => ["BEGIN:VEVENT", `UID:${uid}@ofw-mcp`, `DTSTAMP:${stamp}`, ...props, "END:VEVENT"];
51941
+ const transitions = [];
51942
+ for (const item of itemsOf(data)) {
51943
+ const type = typeof item.type === "string" ? item.type : null;
51944
+ const id2 = type === "TRANSITION" ? null : idOf(item);
51945
+ const omit2 = (reason) => omitted.push({ type, id: id2, reason });
51946
+ if (type === "TRANSITION") {
51947
+ const at = instantOf(item, "startDate", tz);
51948
+ if (!at) {
51949
+ omit2("unreadable_time");
51950
+ continue;
51951
+ }
51952
+ transitions.push({ at, from: parentOf(item.transitionStartParent), to: parentOf(item.transitionEndParent) });
51953
+ continue;
51954
+ }
51955
+ if (type !== "EVENT" && type !== "CONNECTED_EVENT") {
51956
+ omit2("unsupported_type");
51957
+ continue;
51958
+ }
51959
+ if (id2 === null) {
51960
+ omit2("no_id");
51961
+ continue;
51962
+ }
51963
+ let when;
51964
+ let startKey;
51965
+ let signature;
51966
+ if (item.allDay === true) {
51967
+ const start = wallDateOf(item, "startDate");
51968
+ const end = wallDateOf(item, "endDate");
51969
+ if (!start || !end) {
51970
+ omit2("unreadable_time");
51971
+ continue;
51972
+ }
51973
+ if (end < start) {
51974
+ omit2("ends_before_start");
51975
+ continue;
51976
+ }
51977
+ when = [`DTSTART;VALUE=DATE:${start}`, `DTEND;VALUE=DATE:${nextDay(end)}`];
51978
+ startKey = start;
51979
+ signature = `${start}/${end}`;
51980
+ } else {
51981
+ const start = instantOf(item, "startDate", tz);
51982
+ const end = instantOf(item, "endDate", tz);
51983
+ if (!start || !end) {
51984
+ omit2("unreadable_time");
51985
+ continue;
51986
+ }
51987
+ if (end < start) {
51988
+ omit2("ends_before_start");
51989
+ continue;
51990
+ }
51991
+ when = [`DTSTART:${utcStamp(start)}`, `DTEND:${utcStamp(end)}`];
51992
+ startKey = utcStamp(start);
51993
+ signature = `${startKey}/${utcStamp(end)}`;
51994
+ }
51995
+ const title = typeof item.title === "string" && item.title.trim() ? item.title : "(untitled)";
51996
+ signature += `/${title}`;
51997
+ const base = type === "EVENT" ? `ofw-event-${id2}` : `ofw-connected-${String(item.connectedCalendarSubscriptionId ?? "unknown")}-${id2}`;
51998
+ let uid = item.repeating === true ? `${base}-${startKey}` : base;
51999
+ if (issued.has(uid)) {
52000
+ if (issued.get(uid) === signature) {
52001
+ omit2("duplicate");
52002
+ continue;
52003
+ }
52004
+ uid = `${base}-${startKey}`;
52005
+ if (issued.has(uid)) {
52006
+ omit2("duplicate");
52007
+ continue;
52008
+ }
52009
+ }
52010
+ issued.set(uid, signature);
52011
+ const props = [...when, `SUMMARY:${escapeText(title)}`];
52012
+ if (typeof item.location === "string" && item.location.trim()) props.push(`LOCATION:${escapeText(item.location)}`);
52013
+ if (typeof item.notes === "string" && item.notes.trim()) props.push(`DESCRIPTION:${escapeText(item.notes)}`);
52014
+ vevents.push(vevent(uid, props));
52015
+ events += 1;
52016
+ }
52017
+ transitions.sort((a, b) => a.at.getTime() - b.at.getTime());
52018
+ transitions.forEach((t, i) => {
52019
+ const owner = t.to;
52020
+ if (!owner) return;
52021
+ const next = transitions[i + 1];
52022
+ if (!next) {
52023
+ omitted.push({ type: "TRANSITION", id: null, reason: "no_end" });
52024
+ return;
52025
+ }
52026
+ if (next.from && next.from.userId !== owner.userId) {
52027
+ omitted.push({ type: "TRANSITION", id: null, reason: "handoff_mismatch" });
52028
+ return;
52029
+ }
52030
+ const clippedHead = t.from === null;
52031
+ const clippedTail = next.to === null;
52032
+ const uid = clippedHead ? `ofw-custody-${owner.userId}-until-${utcStamp(next.at)}` : `ofw-custody-${owner.userId}-${utcStamp(t.at)}`;
52033
+ const notes = [
52034
+ clippedHead ? "Starts before the exported range." : `Handoff from ${t.from.name}.`,
52035
+ ...clippedTail ? ["Continues past the exported range."] : []
52036
+ ];
52037
+ vevents.push(vevent(uid, [
52038
+ `DTSTART:${utcStamp(t.at)}`,
52039
+ `DTEND:${utcStamp(next.at)}`,
52040
+ `SUMMARY:${escapeText(`Parenting time: ${owner.name}`)}`,
52041
+ `DESCRIPTION:${escapeText(notes.join(" "))}`,
52042
+ "TRANSP:TRANSPARENT"
52043
+ ]));
52044
+ custodyPeriods += 1;
52045
+ });
52046
+ const lines = [
52047
+ "BEGIN:VCALENDAR",
52048
+ "VERSION:2.0",
52049
+ "PRODID:-//ofw-mcp//Calendar//EN",
52050
+ "CALSCALE:GREGORIAN",
52051
+ "METHOD:PUBLISH",
52052
+ "X-WR-CALNAME:OurFamilyWizard",
52053
+ `X-WR-TIMEZONE:${tz}`,
52054
+ ...vevents.flat(),
52055
+ "END:VCALENDAR"
52056
+ ];
52057
+ return {
52058
+ ics: lines.map(fold).join("\r\n") + "\r\n",
52059
+ counts: { events, custodyPeriods, omitted: omitted.length },
52060
+ omitted
52061
+ };
52062
+ }
52063
+
51721
52064
  // src/tools/calendar.ts
51722
52065
  var ofwDate = external_exports.looseObject({ dateTime: external_exports.string() });
51723
52066
  var userRef = external_exports.looseObject({ userId: external_exports.number() });
@@ -51801,7 +52144,7 @@ function detailToWriteArgs(d) {
51801
52144
  var SHARED = "shared with co-parent";
51802
52145
  var PRIVATE = "private (only you)";
51803
52146
  function describeEvent(a, names = /* @__PURE__ */ new Map()) {
51804
- const who = (id) => ({ userId: id, name: names.get(id) ?? null });
52147
+ const who = (id2) => ({ userId: id2, name: names.get(id2) ?? null });
51805
52148
  const out = {
51806
52149
  title: a.title,
51807
52150
  startDate: a.startDate,
@@ -51811,7 +52154,7 @@ function describeEvent(a, names = /* @__PURE__ */ new Map()) {
51811
52154
  };
51812
52155
  if (a.location) out.location = a.location;
51813
52156
  if (a.notes) out.notes = a.notes;
51814
- if (a.children !== void 0) out.children = a.children.map((id) => who(id));
52157
+ if (a.children !== void 0) out.children = a.children.map((id2) => who(id2));
51815
52158
  if (a.eventParentId !== void 0) out.eventParent = who(a.eventParentId);
51816
52159
  if (a.dropOffParentId !== void 0) out.dropOffParent = who(a.dropOffParentId);
51817
52160
  if (a.pickUpParentId !== void 0) out.pickUpParent = who(a.pickUpParentId);
@@ -51825,23 +52168,108 @@ function namesIn(d) {
51825
52168
  }
51826
52169
  return names;
51827
52170
  }
51828
- function registerCalendarTools(server, client2) {
52171
+ var calendarRangeFields = {
52172
+ startDate: external_exports.string().describe("Start date YYYY-MM-DD"),
52173
+ endDate: external_exports.string().describe("End date YYYY-MM-DD"),
52174
+ types: external_exports.array(external_exports.enum(CALENDAR_ITEM_TYPES)).describe('Keep only these: EVENT, CONNECTED_EVENT (from a subscribed outside calendar), TRANSITION (custody handoffs; in .ics they become "Parenting time" periods), SCHEDULE (the per-day custody grid, JSON only). Default: everything').optional(),
52175
+ timeZone: external_exports.string().describe("IANA zone of the user's OFW account, e.g. America/Chicago. OFW reports wall-clock times with no zone; this is the zone they are read and shown in. Default: the server's DISPLAY_TZ").optional()
52176
+ };
52177
+ var detailedCalendarSchema = external_exports.looseObject({
52178
+ calendarItems: external_exports.array(external_exports.looseObject({ type: external_exports.string(), startDate: external_exports.looseObject({ dateTime: external_exports.string() }) }))
52179
+ });
52180
+ async function readDetailedCalendar(client2, startDate, endDate) {
52181
+ const path = `/pub/v1/calendar/detailed?startDate=${encodeURIComponent(startDate)}&endDate=${encodeURIComponent(endDate)}`;
52182
+ return parseLenient(detailedCalendarSchema, await client2.request("GET", path), { label: "ofw-mcp", context: "GET /pub/v1/calendar/detailed" });
52183
+ }
52184
+ function icsSummary(built, args, timeZone) {
52185
+ return {
52186
+ format: "ics",
52187
+ events: built.counts.events,
52188
+ custodyPeriods: built.counts.custodyPeriods,
52189
+ omittedCount: built.counts.omitted,
52190
+ startDate: args.startDate,
52191
+ endDate: args.endDate,
52192
+ timeZone,
52193
+ ...args.types?.length ? { types: args.types } : {},
52194
+ ...built.omitted.length ? { omitted: built.omitted } : {},
52195
+ snapshot: "Static: it does not update when OurFamilyWizard changes. Re-importing a later export updates events in place."
52196
+ };
52197
+ }
52198
+ function registerCalendarTools(server, client2, attachmentIO = new NodeAttachmentIO()) {
51829
52199
  const allowWrites = getCalendarWritesAllowed();
51830
52200
  server.registerTool("ofw_list_events", {
51831
- description: "List OurFamilyWizard calendar events in a date range",
52201
+ description: 'List OurFamilyWizard calendar items in a date range: events, connected (subscribed outside-calendar) events, custody handoffs (TRANSITION) and the per-day custody grid (guardianData, type SCHEDULE). Pass `types` to keep only some of them \u2014 the custody grid is most of a response\'s weight, so leave SCHEDULE out unless you need who-has-the-children per day. Times are OFW wall clock in the account\'s zone, rendered with an offset in `timeZone` (default: the server\'s DISPLAY_TZ). format:"ics" returns an iCalendar (.ics) text you can show or save \u2014 events, all-day events, and each custody period as a "Parenting time" event \u2014 after a short JSON summary of what was included and what was left out. To get a file or download link instead, use ofw_save_calendar_ics.',
51832
52202
  annotations: { readOnlyHint: true, openWorldHint: true },
51833
52203
  inputSchema: external_exports.object({
51834
- startDate: external_exports.string().describe("Start date YYYY-MM-DD"),
51835
- endDate: external_exports.string().describe("End date YYYY-MM-DD"),
51836
- detailed: external_exports.boolean().describe("Return full event details (default false)").optional()
52204
+ ...calendarRangeFields,
52205
+ detailed: external_exports.boolean().describe('Return full event details (default false). Ignored for format:"ics", which always reads the detailed calendar').optional(),
52206
+ format: external_exports.enum(["json", "ics"]).describe("json (default): the OFW payload. ics: a summary block, then the iCalendar text").optional()
51837
52207
  })
51838
52208
  }, async (args) => {
51839
- const variant = args.detailed ? "detailed" : "basic";
51840
- const data = await client2.request(
51841
- "GET",
51842
- `/pub/v1/calendar/${variant}?startDate=${encodeURIComponent(args.startDate)}&endDate=${encodeURIComponent(args.endDate)}`
51843
- );
51844
- return jsonResponse(data);
52209
+ const timeZone = resolveTimeZoneArg(args.timeZone);
52210
+ const ics = args.format === "ics";
52211
+ const raw = await (ics || args.detailed ? readDetailedCalendar(client2, args.startDate, args.endDate) : client2.request("GET", `/pub/v1/calendar/basic?startDate=${encodeURIComponent(args.startDate)}&endDate=${encodeURIComponent(args.endDate)}`));
52212
+ const data = filterCalendarTypes(raw, args.types);
52213
+ if (ics) {
52214
+ const built = buildCalendarIcs(data, { timeZone });
52215
+ return {
52216
+ content: [
52217
+ { type: "text", text: jsonText(icsSummary(built, args, timeZone), timeZone) },
52218
+ { type: "text", text: built.ics }
52219
+ ]
52220
+ };
52221
+ }
52222
+ return jsonResponse(data, timeZone);
52223
+ });
52224
+ server.registerTool("ofw_save_calendar_ics", {
52225
+ description: `Save an OurFamilyWizard date range as an iCalendar (.ics) file the user can import into Google, Apple or Outlook calendar \u2014 events, all-day events, and each custody period as a "Parenting time" event (OFW's own export leaves the parenting schedule out). Same filters as ofw_list_events. On a hosted connector the file is uploaded and you get a private download link that expires (default 1 hour); locally it is written inside the attachments directory (OFW_ATTACHMENTS_DIR, default ~/Downloads/ofw-mcp) and you get its path. Never overwrites an existing file. The file is a snapshot: it does not update when OFW changes, and re-importing a later export updates events in place (stable UIDs).`,
52226
+ // Additive: it adds a new local file (or a new uploaded object) and never
52227
+ // replaces one. Nothing reaches OFW.
52228
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
52229
+ inputSchema: external_exports.object({
52230
+ ...calendarRangeFields,
52231
+ saveTo: external_exports.string().describe("Local installs only: path or directory (trailing /) INSIDE the attachments directory; relative paths resolve against it. Default: <attachments dir>/ofw-calendar-<start>_<end>-<time>.ics. Ignored on a hosted connector").optional(),
52232
+ linkMinutes: external_exports.number().int().min(1).max(1440).describe("Hosted connector only: how long the download link works, in minutes (default 60, max 1440)").optional()
52233
+ })
52234
+ }, async (args) => {
52235
+ const timeZone = resolveTimeZoneArg(args.timeZone);
52236
+ const data = filterCalendarTypes(await readDetailedCalendar(client2, args.startDate, args.endDate), args.types);
52237
+ const now = /* @__PURE__ */ new Date();
52238
+ const built = buildCalendarIcs(data, { timeZone, now });
52239
+ const summary = icsSummary(built, args, timeZone);
52240
+ const fileName = `ofw-calendar-${args.startDate}_${args.endDate}-${now.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z.ics`;
52241
+ const blob = blobStoreFromEnv();
52242
+ if (blob) {
52243
+ const key = `calendar/${randomUUID2()}/${fileName}`;
52244
+ await blob.put(key, built.ics, "text/calendar");
52245
+ const link2 = blob.signGetUrl(key, { ttlMs: (args.linkMinutes ?? 60) * 6e4 });
52246
+ return jsonResponse({
52247
+ delivered: "link",
52248
+ url: link2.url,
52249
+ expiresAt: formatInstant(new Date(link2.expiresAtMs), timeZone).iso,
52250
+ ...summary,
52251
+ note: `Private link to the .ics \u2014 anyone holding it can download the file until it expires, so give it only to the user.${args.saveTo ? " saveTo is ignored on a hosted connector." : ""}`
52252
+ }, timeZone);
52253
+ }
52254
+ if (!attachmentIO.supportsDisk) {
52255
+ return {
52256
+ content: [
52257
+ { type: "text", text: jsonText({ delivered: "inline", forcedInline: true, ...summary, note: "No disk or download store on this deployment, so the calendar is returned inline instead." }, timeZone) },
52258
+ { type: "text", text: built.ics }
52259
+ ]
52260
+ };
52261
+ }
52262
+ const root = resolve7(getAttachmentsDir());
52263
+ const path = resolveSaveDest(root, args.saveTo, fileName);
52264
+ try {
52265
+ await attachmentIO.writeDownload(path, Buffer.from(built.ics, "utf8"), { root, overwrite: false });
52266
+ } catch (e) {
52267
+ if (e instanceof Error && /already exists/.test(e.message)) {
52268
+ throw new Error(`Refusing to overwrite ${path}: a file already exists there. Choose another saveTo, or omit it for a fresh timestamped name.`);
52269
+ }
52270
+ throw e;
52271
+ }
52272
+ return jsonResponse({ delivered: "disk", path, ...summary }, timeZone);
51845
52273
  });
51846
52274
  if (allowWrites) server.registerTool("ofw_create_event", {
51847
52275
  description: "Create a calendar event in OurFamilyWizard. Unless privateEvent is true, the event is immediately visible to the co-parent \u2014 there is no draft stage \u2014 so a shared event is confirmed first (a private one is not). If the request fails without a definitive answer the result is EVENT_UNCONFIRMED: the event may already exist, so do NOT retry until ofw_list_events shows it did not land. " + CONFIRM_NOTE,
@@ -51914,8 +52342,8 @@ function registerCalendarTools(server, client2) {
51914
52342
  })
51915
52343
  }, async (args, ctx) => {
51916
52344
  const { eventId, confirmToken, ...changes } = args;
51917
- const id = encodeURIComponent(eventId);
51918
- const rawDetail = await client2.request("GET", `/pub/v3/events/${id}`);
52345
+ const id2 = encodeURIComponent(eventId);
52346
+ const rawDetail = await client2.request("GET", `/pub/v3/events/${id2}`);
51919
52347
  const current = parseLenient(eventDetailSchema, rawDetail, { label: "ofw-mcp", context: `GET /pub/v3/events/${eventId}`, mode: "strict" });
51920
52348
  const defined = Object.fromEntries(Object.entries(changes).filter(([, v]) => v !== void 0));
51921
52349
  const base = detailToWriteArgs(current);
@@ -51943,7 +52371,7 @@ function registerCalendarTools(server, client2) {
51943
52371
  if (gate) return gate;
51944
52372
  }
51945
52373
  try {
51946
- await requestWrite(client2, "PUT", `/pub/v3/events/${id}`, payload);
52374
+ await requestWrite(client2, "PUT", `/pub/v3/events/${id2}`, payload);
51947
52375
  } catch (e) {
51948
52376
  if (!(e instanceof UnconfirmedWriteError)) throw e;
51949
52377
  return unconfirmedWriteResponse(e, {
@@ -51953,7 +52381,7 @@ function registerCalendarTools(server, client2) {
51953
52381
  });
51954
52382
  }
51955
52383
  try {
51956
- const rawAfter = await client2.request("GET", `/pub/v3/events/${id}`);
52384
+ const rawAfter = await client2.request("GET", `/pub/v3/events/${id2}`);
51957
52385
  const event = parseLenient(eventDetailSchema, rawAfter, { label: "ofw-mcp", context: `GET /pub/v3/events/${eventId} (post-update)`, mode: "strict" });
51958
52386
  return jsonResponse({ note: "Event updated; returning re-fetched event state.", event });
51959
52387
  } catch (e) {
@@ -51974,8 +52402,8 @@ function registerCalendarTools(server, client2) {
51974
52402
  })
51975
52403
  }, async (args, ctx) => {
51976
52404
  const includeFuture = args.includeFuture ?? false;
51977
- const id = encodeURIComponent(args.eventId);
51978
- const rawDetail = await client2.request("GET", `/pub/v3/events/${id}`);
52405
+ const id2 = encodeURIComponent(args.eventId);
52406
+ const rawDetail = await client2.request("GET", `/pub/v3/events/${id2}`);
51979
52407
  const current = parseLenient(eventDetailSchema, rawDetail, { label: "ofw-mcp", context: `GET /pub/v3/events/${args.eventId}`, mode: "strict" });
51980
52408
  if (current.publicFlag) {
51981
52409
  const base = detailToWriteArgs(current);
@@ -52000,7 +52428,7 @@ function registerCalendarTools(server, client2) {
52000
52428
  if (gate) return gate;
52001
52429
  }
52002
52430
  try {
52003
- await requestWrite(client2, "DELETE", `/pub/v3/events/${id}?includeFuture=${includeFuture}`);
52431
+ await requestWrite(client2, "DELETE", `/pub/v3/events/${id2}?includeFuture=${includeFuture}`);
52004
52432
  } catch (e) {
52005
52433
  if (!(e instanceof UnconfirmedWriteError)) throw e;
52006
52434
  return unconfirmedWriteResponse(e, {
@@ -52013,6 +52441,169 @@ function registerCalendarTools(server, client2) {
52013
52441
  });
52014
52442
  }
52015
52443
 
52444
+ // src/tools/expense-reimbursement.ts
52445
+ var money = external_exports.number().nonnegative().refine((v) => Number.isSafeInteger(Math.round(v * 100)) && v === Math.round(v * 100) / 100, "Must be an exact, safe cent amount");
52446
+ var id = external_exports.number().int().positive();
52447
+ var detailSchema = external_exports.looseObject({
52448
+ id,
52449
+ title: external_exports.string().min(1).refine((v) => v.trim().length > 0),
52450
+ author: external_exports.looseObject({ userId: id }),
52451
+ payer: external_exports.looseObject({ userId: id }),
52452
+ private: external_exports.boolean(),
52453
+ paymentType: external_exports.string(),
52454
+ amount: external_exports.looseObject({ total: money.refine((v) => v > 0), totalOwed: money, leftToPay: money }),
52455
+ status: external_exports.string().min(1),
52456
+ statusInfo: external_exports.looseObject({ baseStatus: external_exports.string(), subStatus: external_exports.literal("NONE") }),
52457
+ category: external_exports.looseObject({ id, split: external_exports.looseObject({ parentSplit: external_exports.string(), coparentSplit: external_exports.string() }) }),
52458
+ children: external_exports.array(external_exports.looseObject({ userId: id })).min(1)
52459
+ }).refine(
52460
+ (d) => d.amount.leftToPay <= d.amount.totalOwed && d.amount.totalOwed <= d.amount.total,
52461
+ "Inconsistent expense balances"
52462
+ );
52463
+ function immutableRevision(d) {
52464
+ const { status: _status, statusInfo: _info, paymentType: _type, amount, ...rest } = d;
52465
+ const {
52466
+ leftToPay: _balance,
52467
+ leftToPayFmt: _balanceFmt,
52468
+ description: _description,
52469
+ color: _color,
52470
+ ...amountRest
52471
+ } = amount;
52472
+ return stateRevision({ ...rest, amount: amountRest });
52473
+ }
52474
+ function registerExpenseReimbursementTool(server, client2) {
52475
+ server.registerTool("ofw_mark_expense_reimbursed", {
52476
+ description: "Irreversibly mark the FULL remaining expense balance reimbursed externally. Records an already completed outside-OFW reimbursement only: does NOT send money or use bank/payment endpoints; no partial amounts. Requires expectedRemainingAmount (currency units, positive exact cents) matching the current leftToPay, NOT the full expense total. Reads the current expense, binds the entire detail to confirmation, rechecks immediately before writing, then verifies paid status and unchanged fields. Cannot be undone. On EXPENSE_REIMBURSEMENT_UNCONFIRMED, mayHaveLanded=true: inspect the OFW Expenses log before any retry; never replay blindly. " + CONFIRM_NOTE,
52477
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
52478
+ inputSchema: external_exports.object({
52479
+ expenseId: id.describe("Existing expense entity id"),
52480
+ expectedRemainingAmount: money.refine((v) => v > 0, "Must be positive").describe("Full remaining external reimbursement in currency units (e.g. 48.50); must match leftToPay, not the expense total"),
52481
+ confirmToken: confirmTokenParam
52482
+ })
52483
+ }, async (args, ctx) => {
52484
+ const path = `/pub/v2/expense/expenses/${args.expenseId}`;
52485
+ const read = async () => {
52486
+ const d = parseLenient(
52487
+ detailSchema,
52488
+ await client2.request("GET", path),
52489
+ { label: "ofw-mcp", context: `GET ${path} (mark reimbursed)`, mode: "strict" }
52490
+ );
52491
+ if (d.id !== args.expenseId) throw new Error("Expense id does not match the requested expense");
52492
+ return d;
52493
+ };
52494
+ let current;
52495
+ try {
52496
+ current = await read();
52497
+ } catch {
52498
+ return jsonErrorResponse({
52499
+ result: "EXPENSE_REIMBURSEMENT_REFUSED",
52500
+ expenseId: args.expenseId,
52501
+ reason: "Could not safely read the expense identity, status, parties and balances. Nothing was sent."
52502
+ });
52503
+ }
52504
+ const base = current.statusInfo.baseStatus;
52505
+ if (base === "PAID" && current.amount.leftToPay === 0) {
52506
+ return jsonResponse({
52507
+ result: "ALREADY_PAID",
52508
+ expenseId: args.expenseId,
52509
+ changed: false,
52510
+ note: "OFW already reports paid with zero remaining balance. No write or money transfer was performed."
52511
+ });
52512
+ }
52513
+ if (!["OPEN", "APPROVED", "PARTIAL"].includes(base) || current.amount.leftToPay <= 0) {
52514
+ return jsonErrorResponse({
52515
+ result: "EXPENSE_REIMBURSEMENT_REFUSED",
52516
+ expenseId: args.expenseId,
52517
+ reason: "Only OPEN, APPROVED or PARTIAL expenses with subStatus NONE and positive remaining balance are supported. Nothing was sent."
52518
+ });
52519
+ }
52520
+ if (Math.round(current.amount.leftToPay * 100) !== Math.round(args.expectedRemainingAmount * 100)) {
52521
+ return jsonErrorResponse({
52522
+ result: "EXPENSE_REMAINING_AMOUNT_MISMATCH",
52523
+ expenseId: args.expenseId,
52524
+ expectedRemainingAmount: args.expectedRemainingAmount,
52525
+ remainingAmount: current.amount.leftToPay,
52526
+ total: current.amount.total,
52527
+ reason: "Approve the full remaining balance, not the original expense total or a partial payment. Nothing was sent."
52528
+ });
52529
+ }
52530
+ const payload = { status: "MARKED_REIMBURSED" };
52531
+ const revision = stateRevision(current);
52532
+ const gate = await confirmWrite2(ctx, {
52533
+ args,
52534
+ tool: "ofw_mark_expense_reimbursed",
52535
+ action: "ofw.expense.mark-reimbursed",
52536
+ target: `expense:${args.expenseId}`,
52537
+ revision,
52538
+ payload,
52539
+ confirmToken: args.confirmToken,
52540
+ message: `Mark "${current.title}" fully reimbursed externally (${current.amount.leftToPay}). This cannot be undone and does not transfer money.`,
52541
+ preview: {
52542
+ expenseId: args.expenseId,
52543
+ title: current.title,
52544
+ authorUserId: current.author.userId,
52545
+ payerUserId: current.payer.userId,
52546
+ category: current.category,
52547
+ children: current.children,
52548
+ private: current.private,
52549
+ total: current.amount.total,
52550
+ totalOwed: current.amount.totalOwed,
52551
+ remainingAmount: current.amount.leftToPay,
52552
+ status: current.status,
52553
+ statusInfo: current.statusInfo,
52554
+ paymentType: current.paymentType,
52555
+ warning: "Mark the FULL remaining balance reimbursed outside OFW. This cannot be undone. No money is transferred; no bank/payment action is performed."
52556
+ }
52557
+ });
52558
+ if (gate) return gate;
52559
+ try {
52560
+ if (stateRevision(await read()) !== revision) {
52561
+ return jsonErrorResponse({
52562
+ result: "EXPENSE_CHANGED",
52563
+ expenseId: args.expenseId,
52564
+ reason: "The expense changed after confirmation. Nothing was sent. Review it again before confirming."
52565
+ });
52566
+ }
52567
+ } catch {
52568
+ return jsonErrorResponse({
52569
+ result: "EXPENSE_REIMBURSEMENT_REFUSED",
52570
+ expenseId: args.expenseId,
52571
+ reason: "The immediate pre-write check failed. Nothing was sent."
52572
+ });
52573
+ }
52574
+ try {
52575
+ await requestWrite(client2, "PUT", `${path}/status`, payload);
52576
+ } catch (e) {
52577
+ if (!(e instanceof UnconfirmedWriteError)) throw e;
52578
+ return unconfirmedWriteResponse(e, {
52579
+ result: "EXPENSE_REIMBURSEMENT_UNCONFIRMED",
52580
+ what: `mark expense ${args.expenseId} reimbursed`,
52581
+ checkWith: "the Expenses log on ourfamilywizard.com"
52582
+ });
52583
+ }
52584
+ try {
52585
+ const after = await read();
52586
+ if (after.statusInfo.baseStatus !== "PAID" || after.amount.leftToPay !== 0 || after.paymentType !== "Marked reimbursed" || immutableRevision(after) !== immutableRevision(current)) {
52587
+ throw new Error("Paid status, external reimbursement marker, zero balance or unchanged expense fields could not be verified");
52588
+ }
52589
+ return jsonResponse({
52590
+ result: "EXPENSE_MARKED_REIMBURSED",
52591
+ expenseId: args.expenseId,
52592
+ verified: true,
52593
+ reimbursedAmount: current.amount.leftToPay,
52594
+ remainingAmount: 0,
52595
+ moneyTransferred: false
52596
+ });
52597
+ } catch (e) {
52598
+ return unconfirmedWriteResponse(new UnconfirmedWriteError(args.expenseId, e), {
52599
+ result: "EXPENSE_REIMBURSEMENT_UNCONFIRMED",
52600
+ what: `verify reimbursement of expense ${args.expenseId}`,
52601
+ checkWith: "the Expenses log on ourfamilywizard.com"
52602
+ });
52603
+ }
52604
+ });
52605
+ }
52606
+
52016
52607
  // src/tools/expenses.ts
52017
52608
  var UploadedExpenseFileSchema = external_exports.looseObject({
52018
52609
  fileId: external_exports.number(),
@@ -52131,7 +52722,7 @@ var refId = (v, key) => positiveInt(v) ?? (isRecord2(v) ? positiveInt(v[key]) ??
52131
52722
  var idList = (v, key) => {
52132
52723
  if (!Array.isArray(v)) return void 0;
52133
52724
  const ids = v.map((x) => refId(x, key));
52134
- return ids.every((id) => id !== void 0) ? ids : void 0;
52725
+ return ids.every((id2) => id2 !== void 0) ? ids : void 0;
52135
52726
  };
52136
52727
  function readExpenseState(raw) {
52137
52728
  const d = isRecord2(raw) && isRecord2(raw.data) ? raw.data : raw;
@@ -52167,6 +52758,7 @@ function registerExpenseTools(server, client2, attachmentIO) {
52167
52758
  const uploadOnly = getExpenseUploadOnly();
52168
52759
  const checkIn = uploadOnly ? "the Expenses log on ourfamilywizard.com (ofw_list_expenses is not available in this deployment)" : "ofw_list_expenses";
52169
52760
  const allowWrites = writeMode === "all";
52761
+ if (allowWrites && !uploadOnly) registerExpenseReimbursementTool(server, client2);
52170
52762
  const allowReceiptUploads = allowWrites && attachmentIO !== void 0;
52171
52763
  if (!uploadOnly) server.registerTool("ofw_get_expense_totals", {
52172
52764
  description: "Get OurFamilyWizard expense summary totals (owed/paid)",
@@ -52760,8 +53352,8 @@ var OFWCacheCore = class {
52760
53352
  for (const row of rows) this.upsertMessage(row);
52761
53353
  });
52762
53354
  }
52763
- getMessage(id) {
52764
- const r = this.db.get("SELECT * FROM messages WHERE id = ?", [id]);
53355
+ getMessage(id2) {
53356
+ const r = this.db.get("SELECT * FROM messages WHERE id = ?", [id2]);
52765
53357
  return r ? rowFromDb(r) : null;
52766
53358
  }
52767
53359
  /**
@@ -52784,8 +53376,8 @@ var OFWCacheCore = class {
52784
53376
  * `ofw_get_message` (which would have wrongly classified it as `inbox`)
52785
53377
  * — the drafts table is the authoritative source for that id now.
52786
53378
  */
52787
- deleteMessage(id) {
52788
- this.db.run("DELETE FROM messages WHERE id = ?", [id]);
53379
+ deleteMessage(id2) {
53380
+ this.db.run("DELETE FROM messages WHERE id = ?", [id2]);
52789
53381
  }
52790
53382
  listMessages(opts) {
52791
53383
  const { where, params } = buildMessageFilter(opts);
@@ -52833,8 +53425,8 @@ var OFWCacheCore = class {
52833
53425
  for (const row of rows) this.upsertDraft(row);
52834
53426
  });
52835
53427
  }
52836
- getDraft(id) {
52837
- const r = this.db.get("SELECT * FROM drafts WHERE id = ?", [id]);
53428
+ getDraft(id2) {
53429
+ const r = this.db.get("SELECT * FROM drafts WHERE id = ?", [id2]);
52838
53430
  return r ? draftFromDb(r) : null;
52839
53431
  }
52840
53432
  /**
@@ -52863,8 +53455,8 @@ var OFWCacheCore = class {
52863
53455
  const r = this.db.get("SELECT COUNT(*) as n FROM drafts", []);
52864
53456
  return r?.n ?? 0;
52865
53457
  }
52866
- deleteDraft(id) {
52867
- this.db.run("DELETE FROM drafts WHERE id = ?", [id]);
53458
+ deleteDraft(id2) {
53459
+ this.db.run("DELETE FROM drafts WHERE id = ?", [id2]);
52868
53460
  }
52869
53461
  listDraftIds() {
52870
53462
  const rows = this.db.all("SELECT id FROM drafts", []);
@@ -52890,8 +53482,8 @@ var OFWCacheCore = class {
52890
53482
  ]
52891
53483
  );
52892
53484
  }
52893
- getDraftLineageById(id) {
52894
- const r = this.db.get("SELECT * FROM draft_lineage WHERE id = ?", [id]);
53485
+ getDraftLineageById(id2) {
53486
+ const r = this.db.get("SELECT * FROM draft_lineage WHERE id = ?", [id2]);
52895
53487
  return r ? lineageFromDb(r) : null;
52896
53488
  }
52897
53489
  /**
@@ -53026,14 +53618,14 @@ var LocalCacheStore = class {
53026
53618
  async upsertMessages(rows) {
53027
53619
  this.core.upsertMessages(rows);
53028
53620
  }
53029
- async getMessage(id) {
53030
- return this.core.getMessage(id);
53621
+ async getMessage(id2) {
53622
+ return this.core.getMessage(id2);
53031
53623
  }
53032
53624
  async getMessages(ids) {
53033
53625
  return this.core.getMessages(ids);
53034
53626
  }
53035
- async deleteMessage(id) {
53036
- this.core.deleteMessage(id);
53627
+ async deleteMessage(id2) {
53628
+ this.core.deleteMessage(id2);
53037
53629
  }
53038
53630
  async listMessages(opts) {
53039
53631
  return this.core.listMessages(opts);
@@ -53047,8 +53639,8 @@ var LocalCacheStore = class {
53047
53639
  async upsertDrafts(rows) {
53048
53640
  this.core.upsertDrafts(rows);
53049
53641
  }
53050
- async getDraft(id) {
53051
- return this.core.getDraft(id);
53642
+ async getDraft(id2) {
53643
+ return this.core.getDraft(id2);
53052
53644
  }
53053
53645
  async getDrafts(ids) {
53054
53646
  return this.core.getDrafts(ids);
@@ -53059,8 +53651,8 @@ var LocalCacheStore = class {
53059
53651
  async countDrafts() {
53060
53652
  return this.core.countDrafts();
53061
53653
  }
53062
- async deleteDraft(id) {
53063
- this.core.deleteDraft(id);
53654
+ async deleteDraft(id2) {
53655
+ this.core.deleteDraft(id2);
53064
53656
  }
53065
53657
  async listDraftIds() {
53066
53658
  return this.core.listDraftIds();
@@ -53068,8 +53660,8 @@ var LocalCacheStore = class {
53068
53660
  async recordDraftLineage(row) {
53069
53661
  this.core.recordDraftLineage(row);
53070
53662
  }
53071
- async getDraftLineageById(id) {
53072
- return this.core.getDraftLineageById(id);
53663
+ async getDraftLineageById(id2) {
53664
+ return this.core.getDraftLineageById(id2);
53073
53665
  }
53074
53666
  async getDraftLineageByIds(ids) {
53075
53667
  return this.core.getDraftLineageByIds(ids);
@@ -53186,11 +53778,12 @@ var nodeCacheProvider = () => nodeCache ??= OFWCache.open(getCacheDbPath());
53186
53778
  var nodeAttachmentIO = new NodeAttachmentIO();
53187
53779
  var expenseRegistrar = (server, deps) => registerExpenseTools(server, deps, nodeAttachmentIO);
53188
53780
  var messageRegistrar = (server, deps) => registerMessageTools(server, deps, nodeCacheProvider, nodeAttachmentIO);
53781
+ var calendarRegistrar = (server, deps) => registerCalendarTools(server, deps, nodeAttachmentIO);
53189
53782
  var tools = selectToolRegistrars({
53190
53783
  healthcheck: registerHealthcheckTools,
53191
53784
  user: registerUserTools,
53192
53785
  messages: messageRegistrar,
53193
- calendar: registerCalendarTools,
53786
+ calendar: calendarRegistrar,
53194
53787
  expenses: expenseRegistrar,
53195
53788
  journal: registerJournalTools
53196
53789
  });