ofw-mcp 2.27.1 → 2.27.3

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.
@@ -6,7 +6,7 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "OurFamilyWizard tools for Claude Code",
9
- "version": "2.27.1"
9
+ "version": "2.27.3"
10
10
  },
11
11
  "plugins": [
12
12
  {
@@ -14,7 +14,7 @@
14
14
  "displayName": "OurFamilyWizard",
15
15
  "source": "./",
16
16
  "description": "OurFamilyWizard co-parenting tools for Claude — messages, calendar, expenses, and journal via MCP",
17
- "version": "2.27.1",
17
+ "version": "2.27.3",
18
18
  "author": {
19
19
  "name": "Chris Chall"
20
20
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ofw",
3
3
  "displayName": "OurFamilyWizard",
4
- "version": "2.27.1",
4
+ "version": "2.27.3",
5
5
  "description": "OurFamilyWizard co-parenting tools for Claude — messages, calendar, expenses, and journal via MCP",
6
6
  "author": {
7
7
  "name": "Chris Chall"
package/README.md CHANGED
@@ -199,7 +199,7 @@ Every source has the same limits: up to 10 files per call, each non-empty and at
199
199
 
200
200
  To upload and attach in one step, give `ofw_save_draft` or `ofw_send_message` `inlineAttachments` (the same `{filename, contentBase64, mimeType?}` entries) or `blobKeys`. Every entry is validated before anything is uploaded.
201
201
 
202
- **Drafts don't hold attachments on OurFamilyWizard.** OFW drops files from a saved draft, and its own web app only attaches them when the message is sent. So `ofw_save_draft` *holds* a draft's files on this server: they show under `attachments.held`, are kept across edits (`removeFileIDs` drops one), change the draft's `revision`, and are attached when you send the draft with `ofw_send_message(draftId)`. You won't see them on the draft in the OFW web app. On send, every attachment goes out `SHARED`, as the web app does it. New files are uploaded `SHARED`, and files known to be `PRIVATE` are re-shared as `SHARED`, both only after you approve the send; the approval is bound to each new file's SHA-256. The response then checks the sent message and reports any file OFW left off.
202
+ **Drafts don't hold attachments on OurFamilyWizard.** OFW drops files from a saved draft, and its own web app only attaches them when the message is sent. So `ofw_save_draft` *holds* a draft's files on this server: they show under `attachments.held`, are kept across edits (`removeFileIDs` drops one), change the draft's `revision`, and are attached when you send the draft with `ofw_send_message(draftId)`. You won't see them on the draft in the OFW web app. On send, files are attached as they are (PRIVATE files attach fine), and new files are uploaded `PRIVATE` only after you approve the send, with the approval bound to each new file's SHA-256. The response then checks the sent message and reports any file OFW left off.
203
203
 
204
204
  On a hosted connector, `ofw_download_attachment` with `inline:false` (or `link:true`) returns a private download link that expires after `linkMinutes` (default 60), instead of a path on the server's disk. Inline images over 10 MiB fall back to a link too.
205
205
 
package/dist/bundle.js CHANGED
@@ -47852,7 +47852,7 @@ function describeTokenlessLogin(record2) {
47852
47852
 
47853
47853
  // src/version.ts
47854
47854
  var SERVER_NAME = "ofw-mcp";
47855
- var VERSION = "2.27.1";
47855
+ var VERSION = "2.27.3";
47856
47856
 
47857
47857
  // src/auth.ts
47858
47858
  function fetchproxyDisabled() {
@@ -48685,6 +48685,34 @@ function registerHealthcheckTools(server, client2) {
48685
48685
  });
48686
48686
  }
48687
48687
 
48688
+ // src/tools/held-attachments.ts
48689
+ var key = (draftId) => `draft_held_files:${draftId}`;
48690
+ function uniqueIds(ids) {
48691
+ return [...new Set(ids)];
48692
+ }
48693
+ async function getHeldFiles(cache, draftId) {
48694
+ const raw = await cache.getMeta(key(draftId));
48695
+ if (!raw) return [];
48696
+ try {
48697
+ const parsed = JSON.parse(raw);
48698
+ return Array.isArray(parsed) ? parsed.filter((v) => Number.isInteger(v)) : [];
48699
+ } catch {
48700
+ return [];
48701
+ }
48702
+ }
48703
+ async function setHeldFiles(cache, draftId, ids) {
48704
+ await cache.setMeta(key(draftId), JSON.stringify(uniqueIds(ids)));
48705
+ }
48706
+ async function clearHeldFiles(cache, draftId) {
48707
+ await cache.setMeta(key(draftId), "[]");
48708
+ }
48709
+ async function heldFilesFor(cache, draftIds) {
48710
+ const out = /* @__PURE__ */ new Map();
48711
+ for (const id2 of draftIds) out.set(id2, await getHeldFiles(cache, id2));
48712
+ return out;
48713
+ }
48714
+ var HELD_NOTE = "OurFamilyWizard drafts do not store attachments, so these files are held with this draft by this server and attached when you send it with ofw_send_message (draftId). They are not visible on the draft in the OurFamilyWizard web app.";
48715
+
48688
48716
  // src/read-days.ts
48689
48717
  var WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
48690
48718
  var WEEKDAY_LABELS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
@@ -49073,6 +49101,27 @@ async function getFolderVerifiedAt(store, folder) {
49073
49101
  async function markFolderVerified(store, folder, at = (/* @__PURE__ */ new Date()).toISOString()) {
49074
49102
  await store.setMeta(folderVerifiedAtKey(folder), at);
49075
49103
  }
49104
+ async function inferReplacedDraftLineage(store, vanishedIds, newRows) {
49105
+ if (vanishedIds.length === 0 || newRows.length === 0) return;
49106
+ for (const goneId of vanishedIds) {
49107
+ const gone = await store.getDraft(goneId);
49108
+ const key2 = (await store.getDraftLineageById(goneId))?.draftKey;
49109
+ const held = await getHeldFiles(store, goneId);
49110
+ if (!key2 && held.length === 0) continue;
49111
+ const matches = newRows.filter((r) => r.subject === gone.subject && r.body === gone.body && r.replyToId === gone.replyToId);
49112
+ if (matches.length !== 1) continue;
49113
+ const target = matches[0];
49114
+ if (await store.getDraftLineageById(target.id)) continue;
49115
+ if (key2) {
49116
+ await store.recordDraftLineage({ id: target.id, draftKey: key2, previousId: goneId, recordedAt: (/* @__PURE__ */ new Date()).toISOString() });
49117
+ await store.setMeta(`draft_key_inferred:${target.id}`, "1");
49118
+ }
49119
+ if (held.length > 0) {
49120
+ await setHeldFiles(store, target.id, [...held, ...await getHeldFiles(store, target.id)]);
49121
+ await clearHeldFiles(store, goneId);
49122
+ }
49123
+ }
49124
+ }
49076
49125
  async function syncDrafts(client2, draftsFolderId, store, budget) {
49077
49126
  const b = budget ?? makeBudget(Number.POSITIVE_INFINITY);
49078
49127
  const defer = async () => {
@@ -49131,9 +49180,9 @@ async function syncDrafts(client2, draftsFolderId, store, budget) {
49131
49180
  }
49132
49181
  }
49133
49182
  const seenIds = new Set(ids);
49134
- for (const id2 of await store.listDraftIds()) {
49135
- if (!seenIds.has(id2)) await store.deleteDraft(id2);
49136
- }
49183
+ const vanished = (await store.listDraftIds()).filter((id2) => !seenIds.has(id2));
49184
+ await inferReplacedDraftLineage(store, vanished, rows.filter((r) => !existingById.has(r.id)));
49185
+ for (const id2 of vanished) await store.deleteDraft(id2);
49137
49186
  const now = (/* @__PURE__ */ new Date()).toISOString();
49138
49187
  await setDraftsCacheStatus(store, "fresh");
49139
49188
  await store.setSyncState("drafts", { lastSyncAt: now, newestId: null, resumePage: null });
@@ -49615,34 +49664,6 @@ function staleDraftPayload(input2) {
49615
49664
  };
49616
49665
  }
49617
49666
 
49618
- // src/tools/held-attachments.ts
49619
- var key = (draftId) => `draft_held_files:${draftId}`;
49620
- function uniqueIds(ids) {
49621
- return [...new Set(ids)];
49622
- }
49623
- async function getHeldFiles(cache, draftId) {
49624
- const raw = await cache.getMeta(key(draftId));
49625
- if (!raw) return [];
49626
- try {
49627
- const parsed = JSON.parse(raw);
49628
- return Array.isArray(parsed) ? parsed.filter((v) => Number.isInteger(v)) : [];
49629
- } catch {
49630
- return [];
49631
- }
49632
- }
49633
- async function setHeldFiles(cache, draftId, ids) {
49634
- await cache.setMeta(key(draftId), JSON.stringify(uniqueIds(ids)));
49635
- }
49636
- async function clearHeldFiles(cache, draftId) {
49637
- await cache.setMeta(key(draftId), "[]");
49638
- }
49639
- async function heldFilesFor(cache, draftIds) {
49640
- const out = /* @__PURE__ */ new Map();
49641
- for (const id2 of draftIds) out.set(id2, await getHeldFiles(cache, id2));
49642
- return out;
49643
- }
49644
- var HELD_NOTE = "OurFamilyWizard drafts do not store attachments, so these files are held with this draft by this server and attached when you send it with ofw_send_message (draftId). They are not visible on the draft in the OurFamilyWizard web app.";
49645
-
49646
49667
  // src/tools/lifecycle.ts
49647
49668
  var FOLDER_TYPE = {
49648
49669
  inbox: "INBOX",
@@ -50062,7 +50083,7 @@ function toArrayBuffer(view) {
50062
50083
  const buf = view.buffer;
50063
50084
  if (buf instanceof ArrayBuffer && view.byteOffset === 0 && view.byteLength === buf.byteLength)
50064
50085
  return buf;
50065
- return view.slice().buffer;
50086
+ return Uint8Array.prototype.slice.call(view).buffer;
50066
50087
  }
50067
50088
  function createBlobStore(opts) {
50068
50089
  const { base, prefix } = parseBase(opts.baseUrl);
@@ -50334,6 +50355,10 @@ function uploadFileNameFromKey(key2, opts = {}) {
50334
50355
  return sanitizeUploadFilename(Buffer.from(match[1], "base64url").toString("utf8"));
50335
50356
  }
50336
50357
 
50358
+ // node_modules/@chrischall/mcp-utils/dist/export/deliver.js
50359
+ var INLINE_DELIVERY_MAX_BYTES = 10 * 1024 * 1024;
50360
+ var DELIVERY_LINK_DEFAULT_TTL_MS = 60 * 60 * 1e3;
50361
+
50337
50362
  // src/tools/uploads.ts
50338
50363
  import { createHash as createHash6 } from "node:crypto";
50339
50364
  var MAX_FILES_PER_CALL = MAX_UPLOAD_FILES;
@@ -50427,10 +50452,10 @@ function requireBlobStore(store, what) {
50427
50452
  throw new Error(`${what} needs the blob store an mcp-host deployment provides, and this server has no blob store (it is a local install). Pass a \`path\` inside the upload directory, or the bytes with \`inline\`.`);
50428
50453
  }
50429
50454
  var inlineAttachmentsParam = external_exports.array(inlineFileSchema).max(MAX_FILES_PER_CALL).describe(
50430
- "Files to attach, supplied as base64 BYTES ({filename, contentBase64, mimeType?}). Each is uploaded to My Files (PRIVATE when a draft holds it; SHARED when sent, as the web app attaches files) and attached alongside any myFileIDs. Use for small files; on a hosted deployment, larger files (phone photos) go faster through ofw_upload_attachment uploadSlots + blobKeys here. Every entry is validated before anything is uploaded."
50455
+ "Files to attach, supplied as base64 BYTES ({filename, contentBase64, mimeType?}). Each is uploaded to My Files as PRIVATE and attached alongside any myFileIDs (a send attaches PRIVATE files as they are). Use for small files; on a hosted deployment, larger files (phone photos) go faster through ofw_upload_attachment uploadSlots + blobKeys here. Every entry is validated before anything is uploaded."
50431
50456
  ).optional();
50432
50457
  var blobKeysParam = external_exports.array(external_exports.string()).max(MAX_FILES_PER_CALL).describe(
50433
- "Hosted deployments: blobKeys from ofw_upload_attachment uploadSlots whose files you have already PUT. Each is uploaded to My Files (PRIVATE when a draft holds it; SHARED when sent), attached alongside any myFileIDs, and deleted from the upload store."
50458
+ "Hosted deployments: blobKeys from ofw_upload_attachment uploadSlots whose files you have already PUT. Each is uploaded to My Files as PRIVATE, attached alongside any myFileIDs, and deleted from the upload store."
50434
50459
  ).optional();
50435
50460
  async function planAttachments(input2, opts) {
50436
50461
  const inline = input2.inline ?? [];
@@ -51611,6 +51636,17 @@ function viewOne(view, row) {
51611
51636
  }
51612
51637
 
51613
51638
  // src/tools/messages.ts
51639
+ var DRAFT_KEY_NULL_REASON = "No draftKey: this draft was not saved through this server's cache \u2014 it may have been created in the OurFamilyWizard web app or replaced from another session \u2014 so its lineage is unknown. The next ofw_save_draft on it starts a new key.";
51640
+ async function describeDraftKey(cache, id2) {
51641
+ const row = await cache.getDraftLineageById(id2);
51642
+ if (!row) return { draftKey: null, draftKeyReason: DRAFT_KEY_NULL_REASON };
51643
+ return { draftKey: row.draftKey, ...await cache.getMeta(`draft_key_inferred:${id2}`) === "1" ? { draftKeyInferred: true } : {} };
51644
+ }
51645
+ async function inferredDraftKeys(cache, ids) {
51646
+ const out = /* @__PURE__ */ new Set();
51647
+ for (const id2 of ids) if (await cache.getMeta(`draft_key_inferred:${id2}`) === "1") out.add(id2);
51648
+ return out;
51649
+ }
51614
51650
  async function describeHeld(cache, ids) {
51615
51651
  return Promise.all(ids.map(async (fileId) => ({ fileId, fileName: (await cache.getAttachment(fileId))?.fileName ?? null, held: true })));
51616
51652
  }
@@ -52007,7 +52043,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
52007
52043
  // (create-then-delete), so callers should key off draftKey. Null when
52008
52044
  // this draft was never written through this tool (e.g. authored in
52009
52045
  // the web app).
52010
- draftKey: (await cache.getDraftLineageById(draftRow.id))?.draftKey ?? null,
52046
+ ...await describeDraftKey(cache, draftRow.id),
52011
52047
  id: draftRow.id,
52012
52048
  folder: "drafts",
52013
52049
  subject: draftRow.subject,
@@ -52142,7 +52178,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
52142
52178
  });
52143
52179
  if (allowSend) server.registerTool("ofw_send_message", {
52144
52180
  _meta: familyMeta("send", { aliases: ["message", "co-parent", "reply", "ofw"] }),
52145
- description: "Send a message via OurFamilyWizard \u2014 the ONE irreversible operation here, so it carries the strongest guard. TO SEND AN EXISTING DRAFT (the safe default): pass draftId (or messageId \u2014 same thing). The tool re-reads the draft from OFW and sends the SERVER'S version, so what goes out is what is on OurFamilyWizard, not what this session remembers \u2014 subject/body act only as explicit overrides. It is guarded exactly like ofw_save_draft: pass expectedRevision to assert which version you are sending; if the draft changed on OFW since you read it \u2014 or no longer exists (it may already have been SENT) \u2014 the send is REFUSED with the current server content echoed back, and nothing goes out. RECIPIENTS: OurFamilyWizard does not persist recipients on drafts, so recipientIds is usually still required at send time (ids from ofw_get_profile). After the send is CONFIRMED (OFW returned the new message id and the re-fetched sent record matches what was posted), the source draft is deleted automatically; pass deleteDraftOnSuccess:false to keep it. On ANY failure or ambiguity the draft is never deleted \u2014 the response carries draftRetained:true with the reason. If the send request times out or drops without a definitive answer, the result is SEND_UNCONFIRMED: the message may already have been delivered, so do NOT retry until a sent-folder sync (or ourfamilywizard.com) shows it did not go out. TO COMPOSE FROM SCRATCH: supply subject/body/recipientIds with no draftId. If replyToId is provided (or inherited from the draft), the cache may rewrite it to the latest reply in the same thread (a note is included when this happens). ATTACHMENTS: OurFamilyWizard keeps no files on drafts, so when sending by draftId the files ofw_save_draft HELD for it are attached automatically; myFileIDs (from ofw_upload_attachment) overrides them, or attaches files on a fresh compose; inlineAttachments/blobKeys upload new ones. Every attachment goes out SHARED, as the web app sends them: new files are uploaded SHARED and files known to be PRIVATE are re-shared as SHARED, both only after the send is approved. The response verifies them against the sent message (attachments.verified/missing). The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. " + CONFIRM_NOTE,
52181
+ description: "Send a message via OurFamilyWizard \u2014 the ONE irreversible operation here, so it carries the strongest guard. TO SEND AN EXISTING DRAFT (the safe default): pass draftId (or messageId \u2014 same thing). The tool re-reads the draft from OFW and sends the SERVER'S version, so what goes out is what is on OurFamilyWizard, not what this session remembers \u2014 subject/body act only as explicit overrides. It is guarded exactly like ofw_save_draft: pass expectedRevision to assert which version you are sending; if the draft changed on OFW since you read it \u2014 or no longer exists (it may already have been SENT) \u2014 the send is REFUSED with the current server content echoed back, and nothing goes out. RECIPIENTS: OurFamilyWizard does not persist recipients on drafts, so recipientIds is usually still required at send time (ids from ofw_get_profile). After the send is CONFIRMED (OFW returned the new message id and the re-fetched sent record matches what was posted), the source draft is deleted automatically; pass deleteDraftOnSuccess:false to keep it. On ANY failure or ambiguity the draft is never deleted \u2014 the response carries draftRetained:true with the reason. If the send request times out or drops without a definitive answer, the result is SEND_UNCONFIRMED: the message may already have been delivered, so do NOT retry until a sent-folder sync (or ourfamilywizard.com) shows it did not go out. TO COMPOSE FROM SCRATCH: supply subject/body/recipientIds with no draftId. If replyToId is provided (or inherited from the draft), the cache may rewrite it to the latest reply in the same thread (a note is included when this happens). ATTACHMENTS: OurFamilyWizard keeps no files on drafts, so when sending by draftId the files ofw_save_draft HELD for it are attached automatically; myFileIDs (from ofw_upload_attachment) overrides them, or attaches files on a fresh compose; inlineAttachments/blobKeys upload new ones. Files are attached as they are (PRIVATE files attach fine); new files are uploaded PRIVATE, only after the send is approved. The response verifies them against the sent message (attachments.verified/missing). The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. " + CONFIRM_NOTE,
52146
52182
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
52147
52183
  inputSchema: external_exports.object({
52148
52184
  subject: external_exports.string().describe("Message subject. Required unless draftId/messageId is given (then it overrides the server draft's subject).").optional(),
@@ -52240,14 +52276,8 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
52240
52276
  const unresolved = to.filter((r) => r.name === null).map((r) => r.userId);
52241
52277
  const attachments = await Promise.all(myFileIDs.map(async (fileId) => {
52242
52278
  const known = await cache.getAttachment(fileId);
52243
- const shareClass = known?.metadata?.shareClass;
52244
- return {
52245
- fileId,
52246
- fileName: known?.fileName ?? null,
52247
- ...shareClass === "PRIVATE" ? { reshare: true } : {}
52248
- };
52279
+ return { fileId, fileName: known?.fileName ?? null };
52249
52280
  }));
52250
- const reshare = attachments.filter((a) => a.reshare).map((a) => a.fileId);
52251
52281
  const preview = {
52252
52282
  action: "Send OurFamilyWizard message",
52253
52283
  warning: "Irreversible: once sent, the message is delivered to the recipient(s) and becomes part of the court-visible record. It cannot be recalled or edited.",
@@ -52257,7 +52287,6 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
52257
52287
  body,
52258
52288
  replyTo: resolvedReplyTo === null ? null : { messageId: resolvedReplyTo, subject: replyParent?.subject ?? null, from: replyParent?.fromUser || null },
52259
52289
  attachments,
52260
- ...reshare.length > 0 ? { reshareNote: `${reshare.length} PRIVATE file(s) will be re-shared as SHARED on approval so OurFamilyWizard attaches them \u2014 the web app attaches every message file as SHARED.` } : {},
52261
52290
  ...pending.length > 0 ? { newAttachments: describePending(pending) } : {},
52262
52291
  source: draftRef !== void 0 ? { draftId: draftRef, deleteDraftAfterSend: deleteOnSuccess } : "composed from the call arguments"
52263
52292
  };
@@ -52275,35 +52304,20 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
52275
52304
  myFileIDs,
52276
52305
  replyToId: resolvedReplyTo,
52277
52306
  deleteDraftOnSuccess: deleteOnSuccess,
52278
- ...reshare.length > 0 ? { reshare } : {},
52279
52307
  ...pending.length > 0 ? { newAttachments: pending.map((p) => ({ fileName: p.fileName, sizeBytes: p.sizeBytes, sha256: p.sha256 })) } : {}
52280
52308
  },
52281
52309
  preview,
52282
52310
  confirmToken: args.confirmToken
52283
52311
  });
52284
52312
  if (gate) return gate;
52285
- const reshared = await reshareAsShared(reshare, "sent");
52286
- const resharedNote = reshared.length > 0 ? ` These files were already re-shared as SHARED: ${reshared.map((r) => `${r.fileName} (fileId ${r.from} \u2192 ${r.to})`).join(", ")}; a retry reuses them.` : "";
52287
- const withReshared = (e) => {
52288
- const err = e;
52289
- if (resharedNote) err.message += resharedNote;
52290
- return err;
52291
- };
52292
- let uploadedNew;
52293
- try {
52294
- uploadedNew = await uploadPending(pending, {
52295
- client: client2,
52296
- cache,
52297
- store: blobStore,
52298
- nothingWas: "sent",
52299
- shareClass: "SHARED"
52300
- });
52301
- } catch (e) {
52302
- throw withReshared(e);
52303
- }
52304
- const { uploaded: newFiles, warnings: uploadWarnings } = uploadedNew;
52305
- const swapped = new Map(reshared.map((r) => [r.from, r.to]));
52306
- myFileIDs = [...myFileIDs.map((id2) => swapped.get(id2) ?? id2), ...newFiles.map((f) => f.fileId)];
52313
+ const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
52314
+ client: client2,
52315
+ cache,
52316
+ store: blobStore,
52317
+ nothingWas: "sent",
52318
+ shareClass: "PRIVATE"
52319
+ });
52320
+ myFileIDs = [...myFileIDs, ...newFiles.map((f) => f.fileId)];
52307
52321
  let posted;
52308
52322
  try {
52309
52323
  posted = await postMessageAndRefetch(client2, {
@@ -52316,13 +52330,12 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
52316
52330
  replyToId: resolvedReplyTo
52317
52331
  }, SentDetailSchema, "ofw_send_message");
52318
52332
  } catch (e) {
52319
- if (!(e instanceof UnconfirmedWriteError)) throw withReshared(e);
52333
+ if (!(e instanceof UnconfirmedWriteError)) throw e;
52320
52334
  const reason = e.postedId !== null ? `OFW accepted the send (message id ${e.postedId}) but re-reading it to confirm failed: ${e.message}. The message WAS very likely delivered.` : `The send request failed without a definitive answer from OFW: ${e.message}. The message MAY HAVE BEEN DELIVERED to the recipient.`;
52321
52335
  return jsonErrorResponse({
52322
52336
  result: "SEND_UNCONFIRMED",
52323
52337
  mayHaveBeenDelivered: true,
52324
52338
  sentMessageId: e.postedId,
52325
- ...reshared.length > 0 ? { reshared } : {},
52326
52339
  reason,
52327
52340
  remedy: 'Do NOT retry the send blindly. First run ofw_sync_messages with folders:["sent"] and look for this subject/body among the newest sent messages (or check ourfamilywizard.com). Retry only once you have confirmed it did not go out.',
52328
52341
  ...draftRef !== void 0 ? { draftRetained: true, draftId: draftRef } : {}
@@ -52342,8 +52355,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
52342
52355
  attachmentCheck = {
52343
52356
  onMessage,
52344
52357
  verified: onMessage === null ? null : missing.length === 0,
52345
- ...missing.length > 0 ? { missing } : {},
52346
- ...reshared.length > 0 ? { reshared } : {}
52358
+ ...missing.length > 0 ? { missing } : {}
52347
52359
  };
52348
52360
  if (missing.length > 0) {
52349
52361
  attachmentNote = `WARNING: the message was SENT, but OurFamilyWizard did not attach fileId(s) ${missing.join(", ")}. It cannot be edited; send the missing file(s) in a follow-up message.`;
@@ -52570,11 +52582,13 @@ ${jsonText(
52570
52582
  (await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey])
52571
52583
  );
52572
52584
  const held = await heldFilesFor(cache, rows.map((d) => d.id));
52585
+ const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
52573
52586
  const drafts2 = rows.map((d) => ({
52574
52587
  ...d,
52575
52588
  revision: draftRevision(d, held.get(d.id)),
52576
52589
  ...held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {},
52577
52590
  draftKey: keyById.get(d.id) ?? null,
52591
+ ...inferred.has(d.id) ? { draftKeyInferred: true } : {},
52578
52592
  cacheStatus,
52579
52593
  serverConfirmed: serverConfirmed2,
52580
52594
  asOf: freshness2.asOf
@@ -52656,6 +52670,7 @@ ${jsonText(
52656
52670
  let forceNote = null;
52657
52671
  let serverFiles;
52658
52672
  let priorHeld = [];
52673
+ let serverRecipientIds;
52659
52674
  if (args.messageId !== void 0) {
52660
52675
  const guard = await guardDestructiveDraftOp({
52661
52676
  cache,
@@ -52668,6 +52683,8 @@ ${jsonText(
52668
52683
  forceNote = guard.note;
52669
52684
  serverFiles = guard.server?.files;
52670
52685
  priorHeld = guard.heldFiles;
52686
+ const kept = (guard.server?.recipients ?? []).map((r) => r.userId).filter((id2) => id2 !== 0);
52687
+ if (kept.length > 0) serverRecipientIds = [...new Set(kept)];
52671
52688
  }
52672
52689
  const requestedReplyTo = args.replyToId ?? null;
52673
52690
  let resolvedReplyTo = requestedReplyTo;
@@ -52695,7 +52712,7 @@ ${jsonText(
52695
52712
  const payload = {
52696
52713
  subject: args.subject,
52697
52714
  body: args.body,
52698
- recipientIds: args.recipientIds ?? [],
52715
+ recipientIds: args.recipientIds ?? serverRecipientIds ?? [],
52699
52716
  attachments: { myFileIDs },
52700
52717
  draft: true,
52701
52718
  includeOriginal: resolvedReplyTo !== null,
@@ -52916,37 +52933,6 @@ ${jsonText(
52916
52933
  return jsonResponse(payload);
52917
52934
  });
52918
52935
  const allowShare = writeMode === "all";
52919
- const reshareAsShared = async (ids, nothingWas) => {
52920
- const cache = cacheProvider();
52921
- const done = [];
52922
- for (const from of ids) {
52923
- const known = await cache.getAttachment(from);
52924
- const fileName = known.fileName;
52925
- const prior = Number(await cache.getMeta(`reshared_as:${from}`));
52926
- if (Number.isInteger(prior) && prior > 0) {
52927
- done.push({ from, to: prior, fileName, reused: true });
52928
- continue;
52929
- }
52930
- try {
52931
- const res = await client2.requestBinary("GET", `/pub/v1/myfiles/${from}/data`);
52932
- const mimeType = resolveDownloadMime(res.body, res.contentType ?? known.mimeType, fileName);
52933
- const up = await uploadToMyFiles(client2, cache, {
52934
- blob: new Blob([new Uint8Array(res.body)], { type: mimeType }),
52935
- fileName,
52936
- mimeType,
52937
- sizeBytes: res.body.length
52938
- }, { shareClass: "SHARED", label: known.label });
52939
- await cache.setMeta(`reshared_as:${from}`, String(up.fileId));
52940
- done.push({ from, to: up.fileId, fileName });
52941
- } catch (e) {
52942
- const so = done.map((d) => `${d.fileName} (fileId ${d.from} \u2192 ${d.to})`);
52943
- throw new Error(
52944
- `Attachment ${fileName} (fileId ${from}) could not be re-shared as SHARED: ${e.message}. Nothing was ${nothingWas}.` + (so.length > 0 ? ` Already re-shared: ${so.join(", ")} \u2014 pass the new fileIds in myFileIDs when you retry.` : "")
52945
- );
52946
- }
52947
- }
52948
- return done;
52949
- };
52950
52936
  const shareGate = async (ctx, args, upload, opts, confirmToken) => {
52951
52937
  if (opts.shareClass !== "SHARED") return null;
52952
52938
  const { fileName, sizeBytes, mimeType } = upload;
@@ -53407,9 +53393,11 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
53407
53393
  (await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey])
53408
53394
  );
53409
53395
  const held = await heldFilesFor(cache, rows.map((d) => d.id));
53396
+ const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
53410
53397
  drafts = rows.map((d) => ({
53411
53398
  id: d.id,
53412
53399
  draftKey: keyById.get(d.id) ?? null,
53400
+ ...inferred.has(d.id) ? { draftKeyInferred: true } : {},
53413
53401
  subject: d.subject,
53414
53402
  revision: draftRevision(d, held.get(d.id)),
53415
53403
  ...held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {},
package/dist/sync.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { clearHeldFiles, getHeldFiles, setHeldFiles } from './tools/held-attachments.js';
1
2
  import { z } from 'zod';
2
3
  import { ApiRecipientSchema, hasRealView, mapRecipients, threadedReplyTo } from './tools/_shared.js';
3
4
  import { parseLenient } from '@chrischall/mcp-utils';
@@ -434,6 +435,43 @@ export async function getFolderVerifiedAt(store, folder) {
434
435
  export async function markFolderVerified(store, folder, at = new Date().toISOString()) {
435
436
  await store.setMeta(folderVerifiedAtKey(folder), at);
436
437
  }
438
+ /**
439
+ * A draft replaced OUTSIDE this cache — by another session or deployment
440
+ * (create-then-delete there), or in the web app — vanishes here while a new
441
+ * id appears, and the stable `draftKey` plus the attachments held for it would
442
+ * be lost with the old id. When EXACTLY ONE new draft carries the vanished
443
+ * draft's subject, body and reply target, it is the same message: move the
444
+ * key and the held files across, marked `draft_key_inferred:<id>`. Anything
445
+ * ambiguous (two candidates, changed content, a new draft that already has a
446
+ * lineage) is left unlinked — a wrong guess would hand one message's
447
+ * identity and attachments to another, which is worse than none.
448
+ */
449
+ async function inferReplacedDraftLineage(store, vanishedIds, newRows) {
450
+ if (vanishedIds.length === 0 || newRows.length === 0)
451
+ return;
452
+ for (const goneId of vanishedIds) {
453
+ // A vanished id came from this cache's own draft list, so its row exists.
454
+ const gone = (await store.getDraft(goneId));
455
+ const key = (await store.getDraftLineageById(goneId))?.draftKey;
456
+ const held = await getHeldFiles(store, goneId);
457
+ if (!key && held.length === 0)
458
+ continue;
459
+ const matches = newRows.filter((r) => r.subject === gone.subject && r.body === gone.body && r.replyToId === gone.replyToId);
460
+ if (matches.length !== 1)
461
+ continue;
462
+ const target = matches[0];
463
+ if (await store.getDraftLineageById(target.id))
464
+ continue;
465
+ if (key) {
466
+ await store.recordDraftLineage({ id: target.id, draftKey: key, previousId: goneId, recordedAt: new Date().toISOString() });
467
+ await store.setMeta(`draft_key_inferred:${target.id}`, '1');
468
+ }
469
+ if (held.length > 0) {
470
+ await setHeldFiles(store, target.id, [...held, ...(await getHeldFiles(store, target.id))]);
471
+ await clearHeldFiles(store, goneId);
472
+ }
473
+ }
474
+ }
437
475
  export async function syncDrafts(client, draftsFolderId, store, budget) {
438
476
  // No budget → unbounded (local stdio): identical to the original walk.
439
477
  const b = budget ?? makeBudget(Number.POSITIVE_INFINITY);
@@ -514,10 +552,10 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
514
552
  }
515
553
  }
516
554
  const seenIds = new Set(ids);
517
- for (const id of await store.listDraftIds()) {
518
- if (!seenIds.has(id))
519
- await store.deleteDraft(id);
520
- }
555
+ const vanished = (await store.listDraftIds()).filter((id) => !seenIds.has(id));
556
+ await inferReplacedDraftLineage(store, vanished, rows.filter((r) => !existingById.has(r.id)));
557
+ for (const id of vanished)
558
+ await store.deleteDraft(id);
521
559
  // The complete walk fetched every draft's DETAIL and reconciled deletions, so
522
560
  // the cache is now known-equal to the server. Only here is `synced: 0`
523
561
  // truthful as "verified no changes" — and only here may reads report the
@@ -22,6 +22,23 @@ import { MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './pr
22
22
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
23
23
  import { displayTimeZone, formatInstant, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
24
24
  import { readingBlockedToday } from '../read-days.js';
25
+ /** Why a draft has no draftKey — said instead of a bare null. */
26
+ export const DRAFT_KEY_NULL_REASON = 'No draftKey: this draft was not saved through this server\'s cache — it may have been created in the OurFamilyWizard web app or replaced from another session — so its lineage is unknown. The next ofw_save_draft on it starts a new key.';
27
+ /** `{draftKey, draftKeyInferred?}` or `{draftKey: null, draftKeyReason}` for one draft. */
28
+ async function describeDraftKey(cache, id) {
29
+ const row = await cache.getDraftLineageById(id);
30
+ if (!row)
31
+ return { draftKey: null, draftKeyReason: DRAFT_KEY_NULL_REASON };
32
+ return { draftKey: row.draftKey, ...((await cache.getMeta(`draft_key_inferred:${id}`)) === '1' ? { draftKeyInferred: true } : {}) };
33
+ }
34
+ /** The ids whose draftKey was carried over by inference (see syncDrafts). */
35
+ async function inferredDraftKeys(cache, ids) {
36
+ const out = new Set();
37
+ for (const id of ids)
38
+ if ((await cache.getMeta(`draft_key_inferred:${id}`)) === '1')
39
+ out.add(id);
40
+ return out;
41
+ }
25
42
  /** Held file ids → `{fileId, fileName, held: true}`, names from the attachment cache (null when unknown). */
26
43
  async function describeHeld(cache, ids) {
27
44
  return Promise.all(ids.map(async (fileId) => ({ fileId, fileName: (await cache.getAttachment(fileId))?.fileName ?? null, held: true })));
@@ -636,7 +653,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
636
653
  // (create-then-delete), so callers should key off draftKey. Null when
637
654
  // this draft was never written through this tool (e.g. authored in
638
655
  // the web app).
639
- draftKey: (await cache.getDraftLineageById(draftRow.id))?.draftKey ?? null,
656
+ ...(await describeDraftKey(cache, draftRow.id)),
640
657
  id: draftRow.id,
641
658
  folder: 'drafts',
642
659
  subject: draftRow.subject,
@@ -801,7 +818,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
801
818
  if (allowSend)
802
819
  server.registerTool('ofw_send_message', {
803
820
  _meta: familyMeta('send', { aliases: ['message', 'co-parent', 'reply', 'ofw'] }),
804
- description: 'Send a message via OurFamilyWizard — the ONE irreversible operation here, so it carries the strongest guard. TO SEND AN EXISTING DRAFT (the safe default): pass draftId (or messageId — same thing). The tool re-reads the draft from OFW and sends the SERVER\'S version, so what goes out is what is on OurFamilyWizard, not what this session remembers — subject/body act only as explicit overrides. It is guarded exactly like ofw_save_draft: pass expectedRevision to assert which version you are sending; if the draft changed on OFW since you read it — or no longer exists (it may already have been SENT) — the send is REFUSED with the current server content echoed back, and nothing goes out. RECIPIENTS: OurFamilyWizard does not persist recipients on drafts, so recipientIds is usually still required at send time (ids from ofw_get_profile). After the send is CONFIRMED (OFW returned the new message id and the re-fetched sent record matches what was posted), the source draft is deleted automatically; pass deleteDraftOnSuccess:false to keep it. On ANY failure or ambiguity the draft is never deleted — the response carries draftRetained:true with the reason. If the send request times out or drops without a definitive answer, the result is SEND_UNCONFIRMED: the message may already have been delivered, so do NOT retry until a sent-folder sync (or ourfamilywizard.com) shows it did not go out. TO COMPOSE FROM SCRATCH: supply subject/body/recipientIds with no draftId. If replyToId is provided (or inherited from the draft), the cache may rewrite it to the latest reply in the same thread (a note is included when this happens). ATTACHMENTS: OurFamilyWizard keeps no files on drafts, so when sending by draftId the files ofw_save_draft HELD for it are attached automatically; myFileIDs (from ofw_upload_attachment) overrides them, or attaches files on a fresh compose; inlineAttachments/blobKeys upload new ones. Every attachment goes out SHARED, as the web app sends them: new files are uploaded SHARED and files known to be PRIVATE are re-shared as SHARED, both only after the send is approved. The response verifies them against the sent message (attachments.verified/missing). The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. ' + CONFIRM_NOTE,
821
+ description: 'Send a message via OurFamilyWizard — the ONE irreversible operation here, so it carries the strongest guard. TO SEND AN EXISTING DRAFT (the safe default): pass draftId (or messageId — same thing). The tool re-reads the draft from OFW and sends the SERVER\'S version, so what goes out is what is on OurFamilyWizard, not what this session remembers — subject/body act only as explicit overrides. It is guarded exactly like ofw_save_draft: pass expectedRevision to assert which version you are sending; if the draft changed on OFW since you read it — or no longer exists (it may already have been SENT) — the send is REFUSED with the current server content echoed back, and nothing goes out. RECIPIENTS: OurFamilyWizard does not persist recipients on drafts, so recipientIds is usually still required at send time (ids from ofw_get_profile). After the send is CONFIRMED (OFW returned the new message id and the re-fetched sent record matches what was posted), the source draft is deleted automatically; pass deleteDraftOnSuccess:false to keep it. On ANY failure or ambiguity the draft is never deleted — the response carries draftRetained:true with the reason. If the send request times out or drops without a definitive answer, the result is SEND_UNCONFIRMED: the message may already have been delivered, so do NOT retry until a sent-folder sync (or ourfamilywizard.com) shows it did not go out. TO COMPOSE FROM SCRATCH: supply subject/body/recipientIds with no draftId. If replyToId is provided (or inherited from the draft), the cache may rewrite it to the latest reply in the same thread (a note is included when this happens). ATTACHMENTS: OurFamilyWizard keeps no files on drafts, so when sending by draftId the files ofw_save_draft HELD for it are attached automatically; myFileIDs (from ofw_upload_attachment) overrides them, or attaches files on a fresh compose; inlineAttachments/blobKeys upload new ones. Files are attached as they are (PRIVATE files attach fine); new files are uploaded PRIVATE, only after the send is approved. The response verifies them against the sent message (attachments.verified/missing). The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. ' + CONFIRM_NOTE,
805
822
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
806
823
  inputSchema: z.object({
807
824
  subject: z.string().describe('Message subject. Required unless draftId/messageId is given (then it overrides the server draft\'s subject).').optional(),
@@ -929,20 +946,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
929
946
  serverDraft?.recipients, cachedDraft?.recipients, replyParent?.recipients,
930
947
  ]);
931
948
  const unresolved = to.filter((r) => r.name === null).map((r) => r.userId);
932
- // The web app attaches every message file as SHARED, and a send with a
933
- // PRIVATE one is not known to keep it — so a file the cache KNOWS is
934
- // PRIVATE is re-uploaded as SHARED after approval. Unknown share class:
935
- // passed through untouched, never guessed at.
949
+ // Files are attached as they are. A send keeps PRIVATE files (verified
950
+ // live: four PRIVATE fileIds all came back on the sent message), so no
951
+ // file is re-uploaded — a re-upload as SHARED would leave an extra,
952
+ // co-parent-visible copy in My Files for nothing.
936
953
  const attachments = await Promise.all(myFileIDs.map(async (fileId) => {
937
954
  const known = await cache.getAttachment(fileId);
938
- const shareClass = known?.metadata?.shareClass;
939
- return {
940
- fileId,
941
- fileName: known?.fileName ?? null,
942
- ...(shareClass === 'PRIVATE' ? { reshare: true } : {}),
943
- };
955
+ return { fileId, fileName: known?.fileName ?? null };
944
956
  }));
945
- const reshare = attachments.filter((a) => a.reshare).map((a) => a.fileId);
946
957
  const preview = {
947
958
  action: 'Send OurFamilyWizard message',
948
959
  warning: 'Irreversible: once sent, the message is delivered to the recipient(s) and becomes part of the court-visible record. It cannot be recalled or edited.',
@@ -956,9 +967,6 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
956
967
  ? null
957
968
  : { messageId: resolvedReplyTo, subject: replyParent?.subject ?? null, from: replyParent?.fromUser || null },
958
969
  attachments,
959
- ...(reshare.length > 0
960
- ? { reshareNote: `${reshare.length} PRIVATE file(s) will be re-shared as SHARED on approval so OurFamilyWizard attaches them — the web app attaches every message file as SHARED.` }
961
- : {}),
962
970
  ...(pending.length > 0 ? { newAttachments: describePending(pending) } : {}),
963
971
  source: draftRef !== undefined
964
972
  ? { draftId: draftRef, deleteDraftAfterSend: deleteOnSuccess }
@@ -973,7 +981,6 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
973
981
  ...(serverDraft != null ? { revision: draftRevision(serverDraft, heldForDraft) } : {}),
974
982
  payload: {
975
983
  subject, body, recipientIds, myFileIDs, replyToId: resolvedReplyTo, deleteDraftOnSuccess: deleteOnSuccess,
976
- ...(reshare.length > 0 ? { reshare } : {}),
977
984
  ...(pending.length > 0
978
985
  ? { newAttachments: pending.map((p) => ({ fileName: p.fileName, sizeBytes: p.sizeBytes, sha256: p.sha256 })) }
979
986
  : {}),
@@ -983,32 +990,13 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
983
990
  });
984
991
  if (gate)
985
992
  return gate;
986
- // Approved. Re-share the PRIVATE files and upload the new ones, both as
987
- // SHARED; a failure stops here, before the send, naming whatever did upload.
988
- const reshared = await reshareAsShared(reshare, 'sent');
989
- // From here on, a failure must name the SHARED copies just made, or the
990
- // caller cannot tell they exist (a retry reuses them — see reshareAsShared).
991
- const resharedNote = reshared.length > 0
992
- ? ` These files were already re-shared as SHARED: ${reshared.map((r) => `${r.fileName} (fileId ${r.from} → ${r.to})`).join(', ')}; a retry reuses them.`
993
- : '';
994
- const withReshared = (e) => {
995
- const err = e; // uploadPending and postMessageAndRefetch only throw Errors
996
- if (resharedNote)
997
- err.message += resharedNote;
998
- return err;
999
- };
1000
- let uploadedNew;
1001
- try {
1002
- uploadedNew = await uploadPending(pending, {
1003
- client, cache, store: blobStore, nothingWas: 'sent', shareClass: 'SHARED',
1004
- });
1005
- }
1006
- catch (e) {
1007
- throw withReshared(e);
1008
- }
1009
- const { uploaded: newFiles, warnings: uploadWarnings } = uploadedNew;
1010
- const swapped = new Map(reshared.map((r) => [r.from, r.to]));
1011
- myFileIDs = [...myFileIDs.map((id) => swapped.get(id) ?? id), ...newFiles.map((f) => f.fileId)];
993
+ // Approved. Upload the new files (PRIVATE — the send itself shares them
994
+ // with the recipient); a failure stops here, before the send, naming
995
+ // whatever did upload.
996
+ const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
997
+ client, cache, store: blobStore, nothingWas: 'sent', shareClass: 'PRIVATE',
998
+ });
999
+ myFileIDs = [...myFileIDs, ...newFiles.map((f) => f.fileId)];
1012
1000
  let posted;
1013
1001
  try {
1014
1002
  posted = await postMessageAndRefetch(client, {
@@ -1023,7 +1011,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1023
1011
  }
1024
1012
  catch (e) {
1025
1013
  if (!(e instanceof UnconfirmedWriteError))
1026
- throw withReshared(e);
1014
+ throw e;
1027
1015
  // The one irreversible operation failed WITHOUT a definitive answer. A
1028
1016
  // plain error here reads as "nothing happened" and invites a retry —
1029
1017
  // which, if the first attempt landed, sends the co-parent a duplicate
@@ -1035,7 +1023,6 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1035
1023
  result: 'SEND_UNCONFIRMED',
1036
1024
  mayHaveBeenDelivered: true,
1037
1025
  sentMessageId: e.postedId,
1038
- ...(reshared.length > 0 ? { reshared } : {}),
1039
1026
  reason,
1040
1027
  remedy: 'Do NOT retry the send blindly. First run ofw_sync_messages with folders:["sent"] and look for this subject/body among the newest sent messages (or check ourfamilywizard.com). Retry only once you have confirmed it did not go out.',
1041
1028
  ...(draftRef !== undefined
@@ -1058,7 +1045,6 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1058
1045
  onMessage,
1059
1046
  verified: onMessage === null ? null : missing.length === 0,
1060
1047
  ...(missing.length > 0 ? { missing } : {}),
1061
- ...(reshared.length > 0 ? { reshared } : {}),
1062
1048
  };
1063
1049
  if (missing.length > 0) {
1064
1050
  attachmentNote = `WARNING: the message was SENT, but OurFamilyWizard did not attach fileId(s) ${missing.join(', ')}. It cannot be edited; send the missing file(s) in a follow-up message.`;
@@ -1352,11 +1338,13 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1352
1338
  // stable identity across edits, and whether the last sync actually
1353
1339
  // compared this cache against OFW.
1354
1340
  const held = await heldFilesFor(cache, rows.map((d) => d.id));
1341
+ const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
1355
1342
  const drafts = rows.map((d) => ({
1356
1343
  ...d,
1357
1344
  revision: draftRevision(d, held.get(d.id)),
1358
1345
  ...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
1359
1346
  draftKey: keyById.get(d.id) ?? null,
1347
+ ...(inferred.has(d.id) ? { draftKeyInferred: true } : {}),
1360
1348
  cacheStatus,
1361
1349
  serverConfirmed,
1362
1350
  asOf: freshness.asOf,
@@ -1446,6 +1434,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1446
1434
  let forceNote = null;
1447
1435
  let serverFiles;
1448
1436
  let priorHeld = [];
1437
+ let serverRecipientIds;
1449
1438
  if (args.messageId !== undefined) {
1450
1439
  const guard = await guardDestructiveDraftOp({
1451
1440
  cache,
@@ -1459,6 +1448,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1459
1448
  forceNote = guard.note;
1460
1449
  serverFiles = guard.server?.files;
1461
1450
  priorHeld = guard.heldFiles;
1451
+ // OFW does keep recipients on a draft when they were posted (observed
1452
+ // live), so a replace that names none must not post [] and drop them.
1453
+ const kept = (guard.server?.recipients ?? []).map((r) => r.userId).filter((id) => id !== 0);
1454
+ if (kept.length > 0)
1455
+ serverRecipientIds = [...new Set(kept)];
1462
1456
  }
1463
1457
  const requestedReplyTo = args.replyToId ?? null;
1464
1458
  let resolvedReplyTo = requestedReplyTo;
@@ -1473,7 +1467,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1473
1467
  // attachments are the set HELD for it here: what was held before, anything
1474
1468
  // OFW did report, the caller's myFileIDs, and new uploads — de-duplicated,
1475
1469
  // minus removeFileIDs. New uploads happen after the guard, so a refused
1476
- // replace uploads nothing. They are PRIVATE until the send re-shares them.
1470
+ // replace uploads nothing. They stay PRIVATE: a send attaches PRIVATE files as they are.
1477
1471
  const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
1478
1472
  client, cache, store: blobStore, nothingWas: 'saved', shareClass: 'PRIVATE',
1479
1473
  });
@@ -1491,7 +1485,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1491
1485
  const payload = {
1492
1486
  subject: args.subject,
1493
1487
  body: args.body,
1494
- recipientIds: args.recipientIds ?? [],
1488
+ recipientIds: args.recipientIds ?? serverRecipientIds ?? [],
1495
1489
  attachments: { myFileIDs },
1496
1490
  draft: true,
1497
1491
  includeOriginal: resolvedReplyTo !== null,
@@ -1772,41 +1766,6 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1772
1766
  // "drafts" tier exists to keep a human between the model and anything the
1773
1767
  // co-parent can see.
1774
1768
  const allowShare = writeMode === 'all';
1775
- // Re-upload files the cache knows are PRIVATE as SHARED — the share class
1776
- // the web app gives every message attachment. The bytes come from the
1777
- // account's own My Files copy (no read state; not a message body). Throws
1778
- // before the send on any failure, naming what was already re-shared.
1779
- const reshareAsShared = async (ids, nothingWas) => {
1780
- const cache = cacheProvider();
1781
- const done = [];
1782
- for (const from of ids) {
1783
- const known = await cache.getAttachment(from);
1784
- const fileName = known.fileName;
1785
- // A file already re-shared by an earlier attempt (one that then failed
1786
- // before sending) is reused, not re-uploaded: every re-upload is another
1787
- // co-parent-visible copy in My Files.
1788
- const prior = Number(await cache.getMeta(`reshared_as:${from}`));
1789
- if (Number.isInteger(prior) && prior > 0) {
1790
- done.push({ from, to: prior, fileName, reused: true });
1791
- continue;
1792
- }
1793
- try {
1794
- const res = await client.requestBinary('GET', `/pub/v1/myfiles/${from}/data`);
1795
- const mimeType = resolveDownloadMime(res.body, res.contentType ?? known.mimeType, fileName);
1796
- const up = await uploadToMyFiles(client, cache, {
1797
- blob: new Blob([new Uint8Array(res.body)], { type: mimeType }), fileName, mimeType, sizeBytes: res.body.length,
1798
- }, { shareClass: 'SHARED', label: known.label });
1799
- await cache.setMeta(`reshared_as:${from}`, String(up.fileId));
1800
- done.push({ from, to: up.fileId, fileName });
1801
- }
1802
- catch (e) {
1803
- const so = done.map((d) => `${d.fileName} (fileId ${d.from} → ${d.to})`);
1804
- throw new Error(`Attachment ${fileName} (fileId ${from}) could not be re-shared as SHARED: ${e.message}. Nothing was ${nothingWas}.`
1805
- + (so.length > 0 ? ` Already re-shared: ${so.join(', ')} — pass the new fileIds in myFileIDs when you retry.` : ''));
1806
- }
1807
- }
1808
- return done;
1809
- };
1810
1769
  // One SHARED confirmation, whatever the source: the token binds a SHA-256
1811
1770
  // of the bytes, not just the name, so a file rewritten (or a blob re-PUT)
1812
1771
  // between preview and approval is refused, not shared unseen.
@@ -2379,9 +2338,11 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2379
2338
  const rows = await cache.listDrafts({ page: 1, size: Math.max(total, 1) });
2380
2339
  const keyById = new Map((await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey]));
2381
2340
  const held = await heldFilesFor(cache, rows.map((d) => d.id));
2341
+ const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
2382
2342
  drafts = rows.map((d) => ({
2383
2343
  id: d.id,
2384
2344
  draftKey: keyById.get(d.id) ?? null,
2345
+ ...(inferred.has(d.id) ? { draftKeyInferred: true } : {}),
2385
2346
  subject: d.subject,
2386
2347
  revision: draftRevision(d, held.get(d.id)),
2387
2348
  ...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
@@ -153,10 +153,10 @@ export function requireBlobStore(store, what) {
153
153
  }
154
154
  // ── Attaching in one step (ofw_save_draft / ofw_send_message) ────────────
155
155
  export const inlineAttachmentsParam = z.array(inlineFileSchema).max(MAX_FILES_PER_CALL).describe('Files to attach, supplied as base64 BYTES ({filename, contentBase64, mimeType?}). Each is uploaded to My Files '
156
- + '(PRIVATE when a draft holds it; SHARED when sent, as the web app attaches files) and attached alongside any myFileIDs. Use for small files; on a hosted deployment, larger files (phone photos) go faster '
156
+ + 'as PRIVATE and attached alongside any myFileIDs (a send attaches PRIVATE files as they are). Use for small files; on a hosted deployment, larger files (phone photos) go faster '
157
157
  + 'through ofw_upload_attachment uploadSlots + blobKeys here. Every entry is validated before anything is uploaded.').optional();
158
158
  export const blobKeysParam = z.array(z.string()).max(MAX_FILES_PER_CALL).describe('Hosted deployments: blobKeys from ofw_upload_attachment uploadSlots whose files you have already PUT. Each is uploaded to '
159
- + 'My Files (PRIVATE when a draft holds it; SHARED when sent), attached alongside any myFileIDs, and deleted from the upload store.').optional();
159
+ + 'My Files as PRIVATE, attached alongside any myFileIDs, and deleted from the upload store.').optional();
160
160
  /**
161
161
  * Validate every new attachment BEFORE anything is uploaded, so a bad entry
162
162
  * fails the call with nothing half-done. With `readBlobs`, blob objects are
package/dist/version.js CHANGED
@@ -4,4 +4,4 @@
4
4
  // package.json drift. Importing these instead of package.json keeps the whole
5
5
  // manifest — npm scripts included — out of dist/bundle.js.
6
6
  export const SERVER_NAME = 'ofw-mcp';
7
- export const VERSION = '2.27.1'; // x-release-please-version
7
+ export const VERSION = '2.27.3'; // x-release-please-version
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofw-mcp",
3
- "version": "2.27.1",
3
+ "version": "2.27.3",
4
4
  "license": "MIT",
5
5
  "mcpName": "io.github.chrischall/ofw-mcp",
6
6
  "description": "OurFamilyWizard MCP server for Claude — developed and maintained by AI (Claude Code)",
@@ -34,7 +34,7 @@
34
34
  "typecheck": "tsc -p tsconfig.json --noEmit"
35
35
  },
36
36
  "dependencies": {
37
- "@chrischall/mcp-utils": "^3.6.0",
37
+ "@chrischall/mcp-utils": "^3.7.2",
38
38
  "@fetchproxy/bootstrap": "^3.6.2",
39
39
  "@modelcontextprotocol/server": "^2.3.0",
40
40
  "dotenv": "^18.0.0",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/ofw-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "2.27.1",
9
+ "version": "2.27.3",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.27.1",
14
+ "version": "2.27.3",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -94,7 +94,7 @@ Always pass `--config ~/.mcporter/mcporter.json` unless a local `config/mcporter
94
94
  | `ofw_list_message_folders` | List OFW folders with unread counts. Most reads use the cache; this is mainly for folder IDs and live unread counts. |
95
95
  | `ofw_list_messages(folderId?, since?, until?, q?, sort?, page?, size?, autoRefresh?, view?)` | Cache-backed list. Supports folder ("inbox"/"sent"/"both"), date range, and substring search. `sort:"oldest"` starts at the old end of a range instead of paging to it (default `"newest"`). Returns `complete` for the RESULT SET plus **`nextPage`** (null when done) — and the paging keys come FIRST in the JSON, before `messages`. `returned` carries the record count as a scalar, beside `total`. An **empty** result from a non-fresh cache is refused (`UNVERIFIED_EMPTY`) — pass `autoRefresh:true` to sync and answer instead. |
96
96
  | `ofw_get_message(messageId, allowMarkRead?, view?)` | Read a message OR draft body. Cache-first. Ids in the drafts cache return `folder: "drafts"`. ⚠️ Falls through to OFW for unread inbox messages, which marks them read AND stamps a "First Viewed" time the co-parent can see — irreversible. Pass `allowMarkRead:false` to refuse that fetch instead; cached, sent and already-read messages are unaffected. If the server runs with `OFW_CONFIRM_MARK_READ`, the first call returns a preview (subject, sender, sent time) instead of the body: show it to the user and repeat the call with its `confirmToken` only after they say yes. On a server-configured no-read day (`readingBlocked` / `READING_BLOCKED` in the response) the body is withheld (`bodyWithheld: true`) — report the sender, date and subject, say when `nextReadableDay` is, and do not try to work around it. |
97
- | `ofw_send_message(draftId?, subject?, body?, recipientIds?, replyToId?, expectedRevision?, deleteDraftOnSuccess?, myFileIDs?, inlineAttachments?, blobKeys?, force?)` | Send a message — **the one irreversible operation**. Preferred path: pass `draftId` (+ `expectedRevision`) to send an existing draft **as it exists on the server** — the tool re-reads it from OFW first and refuses if it changed since you read it (or was already sent/deleted); `subject`/`body` become optional overrides. `recipientIds` is usually still required: OFW does not store recipients on drafts. After a **confirmed** send the draft is auto-deleted (`deleteDraftOnSuccess:false` to keep it); on any failure or ambiguity it is retained and the response says why (`draftRetained`). Response leads with `sentMessageId`, `draftKey`, `threaded`, `draftDeleted`. Compose from scratch by passing `subject`/`body`/`recipientIds` with no `draftId`. Sending a draft attaches its held files. Everything goes out SHARED (new files uploaded SHARED, PRIVATE ones re-shared), only after approval, and the response's `attachments.verified`/`missing` says what OFW actually attached. |
97
+ | `ofw_send_message(draftId?, subject?, body?, recipientIds?, replyToId?, expectedRevision?, deleteDraftOnSuccess?, myFileIDs?, inlineAttachments?, blobKeys?, force?)` | Send a message — **the one irreversible operation**. Preferred path: pass `draftId` (+ `expectedRevision`) to send an existing draft **as it exists on the server** — the tool re-reads it from OFW first and refuses if it changed since you read it (or was already sent/deleted); `subject`/`body` become optional overrides. `recipientIds` is usually still required: OFW does not store recipients on drafts. After a **confirmed** send the draft is auto-deleted (`deleteDraftOnSuccess:false` to keep it); on any failure or ambiguity it is retained and the response says why (`draftRetained`). Response leads with `sentMessageId`, `draftKey`, `threaded`, `draftDeleted`. Compose from scratch by passing `subject`/`body`/`recipientIds` with no `draftId`. Sending a draft attaches its held files as they are (PRIVATE files attach fine); new files upload PRIVATE only after approval, and the response's `attachments.verified`/`missing` says what OFW actually attached. A replace without `recipientIds` keeps the draft's recipients. A draft with no `draftKey` says why (`draftKeyReason`). |
98
98
  | `ofw_get_unread_sent(page?, size?, autoRefresh?)` | Sent messages your co-parent hasn't read yet (from cache). Leads with `complete`/`hasMore`/`nextPage`, then `scanned`/`total`, then `unread`; an empty sent cache that is not fresh is refused rather than reported as "nothing sent". |
99
99
  | `ofw_list_drafts(page?, size?, verify?, autoRefresh?, view?)` | Leads with `complete`/`hasMore`/`nextPage`; `drafts` comes last. List saved drafts, **auto-verified**: when the cache is not verified-fresh a cheap drafts sync runs first (default `verify:true`), so one call answers server-confirmed. `verify:false` serves straight from cache. Each draft carries `serverConfirmed`, `revision` and `draftKey`. Returns `complete` — **check it before saying "you have N drafts"**. See [Freshness](#freshness). |
100
100
  | `ofw_save_draft(subject, body, recipientIds?, messageId?, replyToId?, myFileIDs?, removeFileIDs?, inlineAttachments?, blobKeys?, expectedRevision?, force?)` | Create a new draft. Pass `messageId` to **replace** an existing draft: the tool creates a fresh draft and deletes the old one (OFW's update-in-place endpoint silently no-ops). The returned `id` is the NEW id; the response leads with `draftKey`, which stays the same across every edit — **track that, not the id**. Note: OFW does **not** store recipients on drafts — `recipientIds` are accepted but come back empty (a one-line NOTE says so; supply them at send time instead). Threading warnings fire only on genuine drops — a draft echoing `inReplyTo`/`showContext` IS threaded. **OFW drafts can't hold files**: attachments are HELD by the server (`attachments.held`), kept across edits (`removeFileIDs` drops one), and attached when the draft is sent. They don't appear on the draft in the OFW web app; that's expected. `inlineAttachments`/`blobKeys` upload and add new files in the same call. |