ofw-mcp 2.27.0 → 2.27.1

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.
@@ -9,6 +9,7 @@ import { getFolderVerifiedAt } from '../sync.js';
9
9
  import { MAX_UPLOAD_BYTES } from './attachments.js';
10
10
  import { blobStoreFromEnv } from '@chrischall/mcp-utils/export';
11
11
  import { blobKeysParam, blobObjectToUpload, checkFileCount, describePending, fileNameFromBlobKey, inlineAttachmentsParam, inlineFileSchema, MAX_FILES_PER_CALL, mintUploadSlot, planAttachments, requireBlobStore, resolveInlineUpload, sha256Hex, uploadPending, uploadSlotRequestSchema, uploadToMyFiles, } from './uploads.js';
12
+ import { clearHeldFiles, getHeldFiles, heldFilesFor, HELD_NOTE, setHeldFiles, uniqueIds } from './held-attachments.js';
12
13
  import { buildInlineDelivery, MAX_INLINE_BYTES, tryExtract } from './delivery.js';
13
14
  import { resolveDownloadMime, resolveSaveDest } from './attachments.js';
14
15
  import { getAllowMarkRead, getConfirmMarkRead, getAttachmentsDir, getAutoRefreshStaleReads, getDefaultInlineAttachments, getFetchUnreadBodies, getSyncMaxRequests, getWriteMode, } from '../config.js';
@@ -21,6 +22,10 @@ import { MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './pr
21
22
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
22
23
  import { displayTimeZone, formatInstant, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
23
24
  import { readingBlockedToday } from '../read-days.js';
25
+ /** Held file ids → `{fileId, fileName, held: true}`, names from the attachment cache (null when unknown). */
26
+ async function describeHeld(cache, ids) {
27
+ return Promise.all(ids.map(async (fileId) => ({ fileId, fileName: (await cache.getAttachment(fileId))?.fileName ?? null, held: true })));
28
+ }
24
29
  /** A confirmation preview raised from inside a blob consume — carries it out. */
25
30
  class GateHalt extends Error {
26
31
  response;
@@ -48,6 +53,8 @@ const SentDetailSchema = z.looseObject({
48
53
  replyToId: z.number().nullable().optional(),
49
54
  inReplyTo: z.number().nullable().optional(),
50
55
  showContext: z.boolean().optional(),
56
+ // What OFW actually attached — checked against what was sent.
57
+ files: z.array(z.number()).optional(),
51
58
  });
52
59
  const SavedDraftDetailSchema = z.looseObject({
53
60
  subject: z.string().optional(),
@@ -623,6 +630,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
623
630
  const draftRow = await cache.getDraft(id);
624
631
  if (draftRow !== null) {
625
632
  const { freshness, serverConfirmed, cacheStatus } = await draftsFreshness(cache);
633
+ const held = await getHeldFiles(cache, draftRow.id);
626
634
  return jsonResponse({
627
635
  // Stable identity FIRST — the id below changes on every edit
628
636
  // (create-then-delete), so callers should key off draftKey. Null when
@@ -652,11 +660,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
652
660
  // the DRAFTS table, which is the source of truth for a draft id — the
653
661
  // echo duplicates it and adds a stale copy of nothing else.
654
662
  ...(view === 'compact' ? {} : { listData: draftRow.listData }),
655
- attachments: [],
663
+ // OFW keeps no files on a draft; these are the ones HELD for it here
664
+ // and attached when it is sent (held-attachments.ts).
665
+ attachments: await describeHeld(cache, held),
666
+ ...(held.length > 0 ? { attachmentsNote: HELD_NOTE } : {}),
656
667
  // Concurrency token — pass as expectedRevision to ofw_save_draft /
657
668
  // ofw_delete_draft / ofw_send_message to assert you are acting on
658
669
  // THIS version.
659
- revision: draftRevision(draftRow),
670
+ revision: draftRevision(draftRow, held),
660
671
  cacheStatus,
661
672
  // False = this draft's existence and unsent status are remembered from
662
673
  // a cache, not confirmed on OFW. Call ofw_check_freshness before
@@ -790,7 +801,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
790
801
  if (allowSend)
791
802
  server.registerTool('ofw_send_message', {
792
803
  _meta: familyMeta('send', { aliases: ['message', 'co-parent', 'reply', 'ofw'] }),
793
- 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: when sending by draftId, the server draft\'s own attachments carry over automatically; myFileIDs (from ofw_upload_attachment) overrides or attaches files on a fresh compose. The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. ' + CONFIRM_NOTE,
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,
794
805
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
795
806
  inputSchema: z.object({
796
807
  subject: z.string().describe('Message subject. Required unless draftId/messageId is given (then it overrides the server draft\'s subject).').optional(),
@@ -897,10 +908,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
897
908
  replyParent = await cache.getMessage(resolvedReplyTo);
898
909
  chainRootId = replyParent?.chainRootId ?? replyParent?.id ?? requestedReplyTo;
899
910
  }
900
- // Attachments carry over from the SERVER draft the guard read — sending
901
- // "the draft as it exists on the server" includes its files, or the send
902
- // would silently strip them. Explicit myFileIDs still overrides.
903
- let myFileIDs = args.myFileIDs ?? serverDraft?.files ?? [];
911
+ // Attachments: the files HELD for this draft (OFW keeps none on a draft —
912
+ // held-attachments.ts) plus any the server draft does report. An explicit
913
+ // myFileIDs still overrides both.
914
+ const heldForDraft = draftRef !== undefined ? await getHeldFiles(cache, draftRef) : [];
915
+ let myFileIDs = args.myFileIDs ?? uniqueIds([...(serverDraft?.files ?? []), ...heldForDraft]);
904
916
  // ── Confirmation gate ────────────────────────────────────────────────
905
917
  // Everything above this line is a read. This is the ONE irreversible
906
918
  // operation in the server, and until here the only things between a
@@ -917,10 +929,20 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
917
929
  serverDraft?.recipients, cachedDraft?.recipients, replyParent?.recipients,
918
930
  ]);
919
931
  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.
920
936
  const attachments = await Promise.all(myFileIDs.map(async (fileId) => {
921
937
  const known = await cache.getAttachment(fileId);
922
- return { fileId, fileName: known?.fileName ?? null };
938
+ const shareClass = known?.metadata?.shareClass;
939
+ return {
940
+ fileId,
941
+ fileName: known?.fileName ?? null,
942
+ ...(shareClass === 'PRIVATE' ? { reshare: true } : {}),
943
+ };
923
944
  }));
945
+ const reshare = attachments.filter((a) => a.reshare).map((a) => a.fileId);
924
946
  const preview = {
925
947
  action: 'Send OurFamilyWizard message',
926
948
  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.',
@@ -934,6 +956,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
934
956
  ? null
935
957
  : { messageId: resolvedReplyTo, subject: replyParent?.subject ?? null, from: replyParent?.fromUser || null },
936
958
  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
+ : {}),
937
962
  ...(pending.length > 0 ? { newAttachments: describePending(pending) } : {}),
938
963
  source: draftRef !== undefined
939
964
  ? { draftId: draftRef, deleteDraftAfterSend: deleteOnSuccess }
@@ -945,9 +970,10 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
945
970
  action: 'ofw.message.send',
946
971
  message: 'Review and confirm this OurFamilyWizard message. Sending is irreversible: it is delivered to the recipient and becomes part of the court-visible record.',
947
972
  target: draftRef !== undefined ? `draft:${draftRef}` : 'compose',
948
- ...(serverDraft != null ? { revision: draftRevision(serverDraft) } : {}),
973
+ ...(serverDraft != null ? { revision: draftRevision(serverDraft, heldForDraft) } : {}),
949
974
  payload: {
950
975
  subject, body, recipientIds, myFileIDs, replyToId: resolvedReplyTo, deleteDraftOnSuccess: deleteOnSuccess,
976
+ ...(reshare.length > 0 ? { reshare } : {}),
951
977
  ...(pending.length > 0
952
978
  ? { newAttachments: pending.map((p) => ({ fileName: p.fileName, sizeBytes: p.sizeBytes, sha256: p.sha256 })) }
953
979
  : {}),
@@ -957,12 +983,32 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
957
983
  });
958
984
  if (gate)
959
985
  return gate;
960
- // Approved. Upload the new files (PRIVATE) now; a failure stops here,
961
- // before the send, naming whatever did upload.
962
- const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
963
- client, cache, store: blobStore, nothingWas: 'sent',
964
- });
965
- myFileIDs = [...myFileIDs, ...newFiles.map((f) => f.fileId)];
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)];
966
1012
  let posted;
967
1013
  try {
968
1014
  posted = await postMessageAndRefetch(client, {
@@ -977,7 +1023,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
977
1023
  }
978
1024
  catch (e) {
979
1025
  if (!(e instanceof UnconfirmedWriteError))
980
- throw e;
1026
+ throw withReshared(e);
981
1027
  // The one irreversible operation failed WITHOUT a definitive answer. A
982
1028
  // plain error here reads as "nothing happened" and invites a retry —
983
1029
  // which, if the first attempt landed, sends the co-parent a duplicate
@@ -989,6 +1035,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
989
1035
  result: 'SEND_UNCONFIRMED',
990
1036
  mayHaveBeenDelivered: true,
991
1037
  sentMessageId: e.postedId,
1038
+ ...(reshared.length > 0 ? { reshared } : {}),
992
1039
  reason,
993
1040
  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.',
994
1041
  ...(draftRef !== undefined
@@ -1002,7 +1049,27 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1002
1049
  let sentDraftKey = null;
1003
1050
  let threaded = false;
1004
1051
  let threadNote = null;
1052
+ let attachmentCheck = null;
1053
+ let attachmentNote = null;
1054
+ if (newId !== null && myFileIDs.length > 0) {
1055
+ const onMessage = Array.isArray(detail.files) ? detail.files : null;
1056
+ const missing = onMessage === null ? [] : myFileIDs.filter((id) => !onMessage.includes(id));
1057
+ attachmentCheck = {
1058
+ onMessage,
1059
+ verified: onMessage === null ? null : missing.length === 0,
1060
+ ...(missing.length > 0 ? { missing } : {}),
1061
+ ...(reshared.length > 0 ? { reshared } : {}),
1062
+ };
1063
+ if (missing.length > 0) {
1064
+ 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.`;
1065
+ }
1066
+ else if (onMessage === null) {
1067
+ attachmentNote = 'NOTE: OurFamilyWizard did not report the sent message\'s attachments, so they could not be verified. Check the sent message on ourfamilywizard.com.';
1068
+ }
1069
+ }
1005
1070
  if (newId !== null) {
1071
+ if (draftRef !== undefined)
1072
+ await clearHeldFiles(cache, draftRef);
1006
1073
  verifyNote = verifyWriteLanded('message', { subject, body }, detail);
1007
1074
  // Threading verdict, from OFW's own echo on the re-fetched sent record.
1008
1075
  // Both directions demand POSITIVE evidence (see reportsUnthreaded): a
@@ -1149,13 +1216,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1149
1216
  }
1150
1217
  : {}),
1151
1218
  ...persisted,
1219
+ ...(attachmentCheck !== null ? { attachments: attachmentCheck } : {}),
1152
1220
  ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1153
1221
  ...(uploadWarnings.length > 0 ? { warnings: uploadWarnings } : {}),
1154
1222
  };
1155
- return notedJsonResponse([guardNote, rewriteNote, verifyNote, threadNote, unconfirmedNote, retainNote], responseObj, 'Message sent successfully.');
1223
+ return notedJsonResponse([guardNote, rewriteNote, verifyNote, threadNote, attachmentNote, unconfirmedNote, retainNote], responseObj, 'Message sent successfully.');
1156
1224
  });
1157
1225
  async function guardDestructiveDraftOp(input) {
1158
1226
  const { cache, draftId, expectedRevision, force, action } = input;
1227
+ const heldFiles = await getHeldFiles(cache, draftId);
1159
1228
  const cachedRow = await cache.getDraft(draftId);
1160
1229
  const cached = cachedRow === null ? null : {
1161
1230
  subject: cachedRow.subject,
@@ -1177,7 +1246,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1177
1246
  // `.message`, which every Error carries.)
1178
1247
  const reason = e.message;
1179
1248
  if (force) {
1180
- return { ok: true, note: `WARNING: force:true — proceeded with ${action} on draft ${draftId} even though its current state could not be read from OurFamilyWizard (${reason}). Any newer server-side version was destroyed and is NOT recoverable from this response.`, server: undefined };
1249
+ return { ok: true, note: `WARNING: force:true — proceeded with ${action} on draft ${draftId} even though its current state could not be read from OurFamilyWizard (${reason}). Any newer server-side version was destroyed and is NOT recoverable from this response.`, server: undefined, heldFiles };
1181
1250
  }
1182
1251
  return {
1183
1252
  ok: false,
@@ -1189,7 +1258,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1189
1258
  }),
1190
1259
  };
1191
1260
  }
1192
- const verdict = checkDraftFreshness({ server, cached, expectedRevision });
1261
+ const verdict = checkDraftFreshness({ server, cached, expectedRevision, heldFiles });
1193
1262
  if (verdict.verdict === 'FRESH') {
1194
1263
  // A metadata-only "conflict" is the connector's own post-save replyToId
1195
1264
  // normalization catching up — safe to proceed, but say so rather than
@@ -1197,7 +1266,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1197
1266
  const note = verdict.metadataOnly
1198
1267
  ? `NOTE: draft ${draftId} was treated as current for this ${action}. Since you read it, OurFamilyWizard normalized connector-authored metadata (${verdict.changedFields.join(', ')}); the subject, body and recipients are unchanged, so this is not a conflict.`
1199
1268
  : null;
1200
- return { ok: true, note, server };
1269
+ return { ok: true, note, server, heldFiles };
1201
1270
  }
1202
1271
  if (force) {
1203
1272
  // Loud, and the overwritten content rides along in the response so it is
@@ -1208,8 +1277,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1208
1277
  : `The server version that was overwritten is preserved below under "overwrittenServerDraft".`;
1209
1278
  return {
1210
1279
  ok: true,
1211
- note: `WARNING: force:true overrode a ${verdict.verdict} freshness verdict on draft ${draftId}. ${verdict.reason} ${echoed}\n\n${jsonText({ overwrittenServerDraft: server === null ? null : { ...server, revision: draftRevision(server) } })}`,
1280
+ note: `WARNING: force:true overrode a ${verdict.verdict} freshness verdict on draft ${draftId}. ${verdict.reason} ${echoed}\n\n${jsonText({ overwrittenServerDraft: server === null ? null : { ...server, revision: draftRevision(server, heldFiles) } })}`,
1212
1281
  server,
1282
+ heldFiles,
1213
1283
  };
1214
1284
  }
1215
1285
  return {
@@ -1220,6 +1290,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1220
1290
  verdict,
1221
1291
  server,
1222
1292
  cached,
1293
+ heldFiles,
1223
1294
  })),
1224
1295
  };
1225
1296
  }
@@ -1280,9 +1351,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1280
1351
  // Every draft carries the concurrency token to echo back on a write, its
1281
1352
  // stable identity across edits, and whether the last sync actually
1282
1353
  // compared this cache against OFW.
1354
+ const held = await heldFilesFor(cache, rows.map((d) => d.id));
1283
1355
  const drafts = rows.map((d) => ({
1284
1356
  ...d,
1285
- revision: draftRevision(d),
1357
+ revision: draftRevision(d, held.get(d.id)),
1358
+ ...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
1286
1359
  draftKey: keyById.get(d.id) ?? null,
1287
1360
  cacheStatus,
1288
1361
  serverConfirmed,
@@ -1344,7 +1417,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1344
1417
  if (allowDrafts)
1345
1418
  server.registerTool('ofw_save_draft', {
1346
1419
  _meta: familyMeta('change'),
1347
- description: 'Save a message as a draft in OurFamilyWizard. RECIPIENTS: OurFamilyWizard does NOT persist recipients on drafts — recipientIds are accepted but the saved draft comes back with none (documented OFW behavior, noted once in the response, not warned about; supply recipientIds at send time instead). IDENTITY: the response leads with `draftKey`, the stable identity that survives editing — key off it, because the `id` changes on EVERY edit (replacing a draft creates a NEW draft and deletes the old one; OFW\'s update-in-place endpoint silently no-ops, so we never use it). Pass messageId to replace an existing draft; the response.id will be the NEW id, and a transparency NOTE documents the swap and which fields were carried over. THREADING: if replyToId is provided, the cache may rewrite it to the latest reply in the thread (note included). The threading verdict is read from OFW\'s full echo (replyToId/inReplyTo/showContext) — a warning appears ONLY when the reply linkage was genuinely dropped or re-targeted, and the response\'s top-level replyToId/inReplyTo always agree with its listData. Attach files via myFileIDs (from ofw_upload_attachment). After saving, the tool re-fetches the draft from OFW, and the returned `revision` reflects that authoritative state (so it will match on your next edit). SAFETY: because replacing DESTROYS the old draft rather than merging, passing messageId first re-reads that draft from OFW and REFUSES the write if its subject/body/recipients changed since you read it (drafts edited in the OFW web app do not bump any timestamp, so the local cache can be silently behind). A pure replyToId normalization by OFW is NOT treated as a conflict. The refusal returns the current server body under serverBody — merge your edit into it and retry with expectedRevision.',
1420
+ description: 'Save a message as a draft in OurFamilyWizard. RECIPIENTS: OurFamilyWizard has not reliably kept recipients on drafts (when the saved draft comes back with none it is noted once, not warned about) — supply recipientIds at send time as well. ATTACHMENTS: OurFamilyWizard does not store files on drafts, so myFileIDs / inlineAttachments / blobKeys are HELD with the draft by this server (carried across edits, de-duplicated; removeFileIDs drops one), shown under attachments.held, folded into `revision`, and attached when the draft is sent with ofw_send_message(draftId). They are not visible on the draft in the OurFamilyWizard web app. IDENTITY: the response leads with `draftKey`, the stable identity that survives editing — key off it, because the `id` changes on EVERY edit (replacing a draft creates a NEW draft and deletes the old one; OFW\'s update-in-place endpoint silently no-ops, so we never use it). Pass messageId to replace an existing draft; the response.id will be the NEW id, and a transparency NOTE documents the swap and which fields were carried over. THREADING: if replyToId is provided, the cache may rewrite it to the latest reply in the thread (note included). The threading verdict is read from OFW\'s full echo (replyToId/inReplyTo/showContext) — a warning appears ONLY when the reply linkage was genuinely dropped or re-targeted, and the response\'s top-level replyToId/inReplyTo always agree with its listData. After saving, the tool re-fetches the draft from OFW, and the returned `revision` reflects that authoritative state (so it will match on your next edit). SAFETY: because replacing DESTROYS the old draft rather than merging, passing messageId first re-reads that draft from OFW and REFUSES the write if its subject/body/recipients changed since you read it (drafts edited in the OFW web app do not bump any timestamp, so the local cache can be silently behind). A pure replyToId normalization by OFW is NOT treated as a conflict. The refusal returns the current server body under serverBody — merge your edit into it and retry with expectedRevision.',
1348
1421
  // Destructive: with messageId, saving REPLACES the draft by creating a new
1349
1422
  // one and deleting the old (OFW has no draft update), so the old draft's
1350
1423
  // server content is gone. Not idempotent: every call mints a new draft id.
@@ -1355,7 +1428,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1355
1428
  recipientIds: z.array(z.number()).describe('Array of recipient user IDs (optional for drafts)').optional(),
1356
1429
  messageId: z.number().describe('ID of an existing draft to replace (the new draft will have a new id; the old is deleted)').optional(),
1357
1430
  replyToId: z.number().describe('ID of the message this draft replies to').optional(),
1358
- myFileIDs: z.array(z.number()).describe('Attachment file ids (from ofw_upload_attachment). When replacing a draft (messageId), omit it to KEEP the draft\'s current attachments; passing it replaces them.').optional(),
1431
+ myFileIDs: z.array(z.number()).describe('Attachment file ids (from ofw_upload_attachment) to attach. OurFamilyWizard does not store attachments on drafts, so they are HELD with this draft by this server and attached when you send it with ofw_send_message(draftId). When replacing a draft (messageId), the files already held are kept and these are added (de-duplicated); use removeFileIDs to drop one.').optional(),
1432
+ removeFileIDs: z.array(z.number()).describe('When replacing a draft: held attachment file ids to drop.').optional(),
1359
1433
  inlineAttachments: inlineAttachmentsParam,
1360
1434
  blobKeys: blobKeysParam,
1361
1435
  expectedRevision: z.string().describe('With messageId: the `revision` you got from ofw_list_drafts/ofw_get_message for that draft. Asserts you are replacing THAT version. If the draft changed on OFW since, the write is refused and the current server body is returned. Omit and the tool compares the server against the local cache instead — omitting never means "overwrite anyway".').optional(),
@@ -1371,6 +1445,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1371
1445
  // a stray draft behind for a write we then decline to finish.
1372
1446
  let forceNote = null;
1373
1447
  let serverFiles;
1448
+ let priorHeld = [];
1374
1449
  if (args.messageId !== undefined) {
1375
1450
  const guard = await guardDestructiveDraftOp({
1376
1451
  cache,
@@ -1383,6 +1458,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1383
1458
  return guard.response;
1384
1459
  forceNote = guard.note;
1385
1460
  serverFiles = guard.server?.files;
1461
+ priorHeld = guard.heldFiles;
1386
1462
  }
1387
1463
  const requestedReplyTo = args.replyToId ?? null;
1388
1464
  let resolvedReplyTo = requestedReplyTo;
@@ -1393,15 +1469,19 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1393
1469
  rewriteNote = `replyToId rewritten from ${requestedReplyTo} to ${resolvedReplyTo} (later reply in same thread found in sent cache).`;
1394
1470
  }
1395
1471
  }
1396
- // Replacing a draft creates a NEW one, so its files must be posted again
1397
- // or the edit silently strips them: they carry over from the server copy
1398
- // the guard just read (an explicit myFileIDs still replaces them, as on
1399
- // send). New uploads go on top, after the guard, so a refused replace
1400
- // uploads nothing.
1472
+ // OFW keeps no files on a draft (held-attachments.ts), so the draft's
1473
+ // attachments are the set HELD for it here: what was held before, anything
1474
+ // OFW did report, the caller's myFileIDs, and new uploads — de-duplicated,
1475
+ // minus removeFileIDs. New uploads happen after the guard, so a refused
1476
+ // replace uploads nothing. They are PRIVATE until the send re-shares them.
1401
1477
  const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
1402
- client, cache, store: blobStore, nothingWas: 'saved',
1478
+ client, cache, store: blobStore, nothingWas: 'saved', shareClass: 'PRIVATE',
1403
1479
  });
1404
- const myFileIDs = [...(args.myFileIDs ?? serverFiles ?? []), ...newFiles.map((f) => f.fileId)];
1480
+ const removed = new Set(args.removeFileIDs ?? []);
1481
+ const myFileIDs = uniqueIds([
1482
+ ...priorHeld, ...(serverFiles ?? []), ...(args.myFileIDs ?? []), ...newFiles.map((f) => f.fileId),
1483
+ ]).filter((id) => !removed.has(id));
1484
+ // Posted anyway: should OFW ever keep them on the draft, they show there.
1405
1485
  // Deliberately do NOT pass `args.messageId` to OFW's POST payload.
1406
1486
  // OFW's update-by-messageId path silently no-ops on subsequent
1407
1487
  // updates while echoing the posted body in the immediate GET — so
@@ -1423,6 +1503,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1423
1503
  let verifyNote = null;
1424
1504
  let recipientsNote = null;
1425
1505
  let newRevision = null;
1506
+ let onDraft = [];
1507
+ let held = [];
1426
1508
  let draftKey = null;
1427
1509
  // Fields accepted on the write that the saved draft must carry — or their
1428
1510
  // loss must be reported. Never a silent drop (Defect 3).
@@ -1451,9 +1533,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1451
1533
  listData: detail,
1452
1534
  };
1453
1535
  await cache.upsertDraft(persisted);
1454
- // The revision is now computed from the server-authoritative detail, so it
1455
- // is the value a subsequent read/verify will observe (Defect 1).
1456
- newRevision = draftRevision(persisted);
1536
+ // What OFW actually kept on the draft (in practice none), and what is
1537
+ // therefore held here for the send.
1538
+ onDraft = Array.isArray(detail.files) ? detail.files : [];
1539
+ held = myFileIDs.filter((id) => !onDraft.includes(id));
1540
+ await setHeldFiles(cache, newId, held);
1541
+ // The revision is computed from the server-authoritative detail plus the
1542
+ // held files, so it is the value a subsequent read/verify will observe
1543
+ // (Defect 1) — and it moves when only the attachments change.
1544
+ newRevision = draftRevision(persisted, held);
1457
1545
  // Carry the logical identity across the id change. Replacing a draft mints
1458
1546
  // a NEW OFW id every time (create-then-delete — see the note below), so
1459
1547
  // ten edits produced ten unrelated ids and there was no way to ask what
@@ -1521,20 +1609,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1521
1609
  warnings.push(`recipientIds were requested as [${requested.join(', ')}] but the saved draft has [${stored.join(', ')}]. Verify the recipients on ourfamilywizard.com.`);
1522
1610
  }
1523
1611
  }
1524
- if (myFileIDs.length > 0 && Array.isArray(detail.files)) {
1525
- const storedFiles = new Set(detail.files);
1526
- const missing = myFileIDs.filter((id) => !storedFiles.has(id));
1527
- if (missing.length > 0) {
1528
- warnings.push(`Attachment fileId(s) ${missing.join(', ')} were requested in myFileIDs but are not attached to the saved draft. Re-upload or re-attach if needed.`);
1529
- }
1530
- }
1531
1612
  // Replace-path: caller passed messageId, so they want the old draft
1532
1613
  // gone. Delete it after the new one is safely created+cached.
1533
1614
  if (args.messageId !== undefined && args.messageId !== newId) {
1534
1615
  try {
1535
1616
  await deleteOFWMessages(client, [args.messageId]);
1536
1617
  await cache.deleteDraft(args.messageId);
1537
- replaceNote = `NOTE: ofw_save_draft replaced draft ${args.messageId} via create-then-delete. The new draft id is ${newId}; the old draft has been deleted. The draftKey is UNCHANGED — key off it rather than the volatile id, which changes on every edit. (OFW's update-in-place endpoint silently no-ops on subsequent updates, so we never use it.) Fields carried over to the new draft: subject, body, recipients (${persisted.recipients.length}), replyToId (${persisted.replyToId === null ? 'none' : persisted.replyToId}), attachments (${myFileIDs.length}).${warnings.length > 0 ? ' See warnings above for any field OurFamilyWizard did not carry over.' : ''}`;
1618
+ await clearHeldFiles(cache, args.messageId);
1619
+ replaceNote = `NOTE: ofw_save_draft replaced draft ${args.messageId} via create-then-delete. The new draft id is ${newId}; the old draft has been deleted. The draftKey is UNCHANGED — key off it rather than the volatile id, which changes on every edit. (OFW's update-in-place endpoint silently no-ops on subsequent updates, so we never use it.) Fields carried over to the new draft: subject, body, recipients (${persisted.recipients.length}), replyToId (${persisted.replyToId === null ? 'none' : persisted.replyToId}), attachments: ${onDraft.length} on the draft, ${held.length} held for send.${warnings.length > 0 ? ' See warnings above for any field OurFamilyWizard did not carry over.' : ''}`;
1538
1620
  }
1539
1621
  catch (e) {
1540
1622
  // Partial-failure safety: the new draft is already created and
@@ -1560,6 +1642,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1560
1642
  previousId: args.messageId ?? null,
1561
1643
  cacheStatus: 'fresh',
1562
1644
  serverConfirmed: true,
1645
+ attachments: {
1646
+ onDraft,
1647
+ held: await describeHeld(cache, held),
1648
+ ...(held.length > 0 ? { note: HELD_NOTE } : {}),
1649
+ },
1563
1650
  ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1564
1651
  ...(warnings.length > 0 ? { warnings } : {}),
1565
1652
  ...(recipientsNote !== null ? { recipientsNote } : {}),
@@ -1593,6 +1680,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1593
1680
  return guard.response;
1594
1681
  const data = await deleteOFWMessages(client, [args.messageId]);
1595
1682
  await cache.deleteDraft(args.messageId);
1683
+ await clearHeldFiles(cache, args.messageId);
1596
1684
  return notedJsonResponse([guard.note], data, 'Draft deleted.');
1597
1685
  });
1598
1686
  server.registerTool('ofw_get_unread_sent', {
@@ -1684,6 +1772,41 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1684
1772
  // "drafts" tier exists to keep a human between the model and anything the
1685
1773
  // co-parent can see.
1686
1774
  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
+ };
1687
1810
  // One SHARED confirmation, whatever the source: the token binds a SHA-256
1688
1811
  // of the bytes, not just the name, so a file rewritten (or a blob re-PUT)
1689
1812
  // between preview and approval is refused, not shared unseen.
@@ -2255,11 +2378,13 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2255
2378
  const total = await cache.countDrafts();
2256
2379
  const rows = await cache.listDrafts({ page: 1, size: Math.max(total, 1) });
2257
2380
  const keyById = new Map((await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey]));
2381
+ const held = await heldFilesFor(cache, rows.map((d) => d.id));
2258
2382
  drafts = rows.map((d) => ({
2259
2383
  id: d.id,
2260
2384
  draftKey: keyById.get(d.id) ?? null,
2261
2385
  subject: d.subject,
2262
- revision: draftRevision(d),
2386
+ revision: draftRevision(d, held.get(d.id)),
2387
+ ...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
2263
2388
  modifiedAt: d.modifiedAt,
2264
2389
  recipients: d.recipients,
2265
2390
  replyToId: d.replyToId,