ofw-mcp 2.28.0 → 2.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/read-days.js CHANGED
@@ -2,10 +2,13 @@
2
2
  //
3
3
  // Some co-parenting arrangements (a court order, a parenting-plan clause, or
4
4
  // just a personal rule) limit when OFW messages are read — e.g. "check OFW on
5
- // Mondays and Thursdays only". On the other days it is fine to see THAT a
6
- // message arrived, who sent it and its subject, but not to read it — and above
7
- // all not to mark it read, which stamps a co-parent-visible "First Viewed"
8
- // time on the record that cannot be undone.
5
+ // Mondays and Thursdays only". A no-read day exists for ONE reason: to keep an
6
+ // unread INBOX message from being marked read, which stamps a co-parent-visible
7
+ // "First Viewed" time on the record that cannot be undone. So on those days an
8
+ // unread inbox message shows only that it arrived — sender, subject, time —
9
+ // with its body and attachments withheld, and nothing that could stamp it is
10
+ // requested. Everything else stays fully readable: every sent message, every
11
+ // inbox message already read, and drafts. Blocking those protects nothing.
9
12
  //
10
13
  // Two env vars, either or both:
11
14
  // OFW_READ_DAYS allow list — reading is permitted ONLY on these days
@@ -27,7 +30,7 @@
27
30
  // ignoring the typo would keep reading on the day they meant to keep clear.
28
31
  //
29
32
  // `overrideNoReadDay` is the one way past this, per call, for when the user
30
- // explicitly asks to read anyway. It lifts ONLY the day restriction: the
33
+ // explicitly asks to read an unread message anyway. It lifts ONLY the day restriction: the
31
34
  // mark-read gates (OFW_ALLOW_MARK_READ, OFW_CONFIRM_MARK_READ, sync's
32
35
  // fetchUnreadBodies) apply exactly as on a reading day, and each use is logged
33
36
  // through auditReadOverride.
@@ -99,6 +102,8 @@ function addDays(date, n) {
99
102
  const dt = new Date(Date.UTC(y, m - 1, d + n));
100
103
  return { date: dt.toISOString().slice(0, 10), weekday: dt.getUTCDay() };
101
104
  }
105
+ /** Why a single message's body is absent on a no-read day. */
106
+ export const UNREAD_ON_NO_READ_DAY = 'UNREAD_ON_NO_READ_DAY';
102
107
  /**
103
108
  * Null when message content may be read today; otherwise a description of why
104
109
  * not, suitable for embedding in a tool response.
@@ -127,7 +132,7 @@ export function readingBlockedToday(now = new Date()) {
127
132
  today: today.date,
128
133
  weekday: WEEKDAY_LABELS[today.weekday],
129
134
  timeZone,
130
- reason: `${reason} You may see that messages arrived, who sent them, when, and their subjects — but message bodies and attachments are withheld, and nothing may be marked read on OurFamilyWizard. This is a deployment setting: respect it. Only if the user has explicitly asked to read anyway today, pass overrideNoReadDay:true to ofw_get_message, ofw_list_messages or ofw_sync_messages. Attachments stay withheld either way.`,
135
+ reason: `${reason} A no-read day only protects UNREAD inbox messages: their sender, subject and time are shown, but their bodies and attachments are withheld and nothing may mark them read on OurFamilyWizard. Sent messages, inbox messages already read, and drafts stay fully readable. This is a deployment setting: respect it. Only if the user has explicitly asked to read an unread message anyway today, pass overrideNoReadDay:true to ofw_get_message, ofw_list_messages or ofw_sync_messages. Attachments of unread messages stay withheld either way.`,
131
136
  nextReadableDay,
132
137
  };
133
138
  }
package/dist/sync.js CHANGED
@@ -221,17 +221,18 @@ async function walkPages(client, folder, folderId, opts, store) {
221
221
  const listRead = scrapeSaysRead(folder, item);
222
222
  const isInboxUnread = folder === 'inbox' && !listRead;
223
223
  if (existing) {
224
- // Heal a row cached without its body — typically one listed on a
225
- // no-read day — once fetching it can stamp nothing: a sent message, or
226
- // an inbox message OFW's list reports as read. An unread inbox body
227
- // stays the caller's explicit choice (ofw_get_message), as before.
228
- if (opts.fetchBodies && existing.body === null && !isInboxUnread) {
224
+ // Heal a row cached without its body — typically an inbox message
225
+ // first seen unread and read since — once fetching it can stamp
226
+ // nothing: a sent message, or an inbox message OFW's list reports as
227
+ // read. An unread inbox body stays the caller's explicit choice
228
+ // (ofw_get_message), as before. A no-read day does not stop this: it
229
+ // protects only unread inbox messages (read-days.ts).
230
+ if (existing.body === null && !isInboxUnread) {
229
231
  if (!budget.take()) {
230
232
  pageBudgetHit = true;
231
233
  break;
232
234
  }
233
235
  const detail = await fetchDetail(item, { subject: existing.subject, sentAt: existing.sentAt, from: senderOf(existing) }, 'GET /pub/v3/messages/{id} (body backfill)', false);
234
- opts.onBodyFetched?.(item.id);
235
236
  toUpsert.push({
236
237
  ...existing,
237
238
  body: detail.body ?? '',
@@ -255,7 +256,7 @@ async function walkPages(client, folder, folderId, opts, store) {
255
256
  // on the detail endpoint. So when a sent message has flipped to read
256
257
  // and we don't yet hold a real viewed time, re-fetch detail to capture
257
258
  // it (no body re-fetch — only the recipient view fields can change).
258
- if (opts.fetchBodies && folder === 'sent' && item.showNeverViewed === false && !hasRealView(existing.recipients)) {
259
+ if (folder === 'sent' && item.showNeverViewed === false && !hasRealView(existing.recipients)) {
259
260
  if (!budget.take()) {
260
261
  pageBudgetHit = true;
261
262
  break;
@@ -267,7 +268,7 @@ async function walkPages(client, folder, folderId, opts, store) {
267
268
  continue;
268
269
  }
269
270
  pageHadNewItem = true;
270
- const shouldFetchBody = opts.fetchBodies && (!isInboxUnread || opts.fetchUnreadBodies);
271
+ const shouldFetchBody = !isInboxUnread || opts.fetchUnreadBodies;
271
272
  let body = null;
272
273
  let fetchedBodyAt = null;
273
274
  let detailFileIds = [];
@@ -301,7 +302,8 @@ async function walkPages(client, folder, folderId, opts, store) {
301
302
  }
302
303
  // Reached for an unread inbox message only under fetchUnreadBodies.
303
304
  const detail = await fetchDetail(item, { subject: row.subject, sentAt: row.sentAt, from }, 'GET /pub/v3/messages/{id} (sync)', isInboxUnread);
304
- opts.onBodyFetched?.(item.id);
305
+ if (isInboxUnread)
306
+ opts.onUnreadBodyFetched?.(item.id);
305
307
  body = detail.body ?? '';
306
308
  fetchedBodyAt = new Date().toISOString();
307
309
  detailRecipients = detail.recipients;
@@ -372,7 +374,6 @@ async function walkPages(client, folder, folderId, opts, store) {
372
374
  * waited months can wait one more call.
373
375
  */
374
376
  export async function syncMessageFolder(client, folder, folderId, opts, store) {
375
- const fetchBodies = opts.fetchBodies ?? true;
376
377
  // No budget → unbounded (local stdio): every take() succeeds, so an ordinary
377
378
  // sync is byte-for-byte the original unbounded walk (forward pass only).
378
379
  const budget = opts.budget ?? makeBudget(Number.POSITIVE_INFINITY);
@@ -382,8 +383,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
382
383
  startPage: 1,
383
384
  stopAtCachedPage: true,
384
385
  fetchUnreadBodies: opts.fetchUnreadBodies,
385
- fetchBodies,
386
- onBodyFetched: opts.onBodyFetched,
386
+ onUnreadBodyFetched: opts.onUnreadBodyFetched,
387
387
  budget,
388
388
  }, store);
389
389
  let synced = fwd.synced;
@@ -436,8 +436,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
436
436
  startPage: savedResume ?? fwd.nextPage,
437
437
  stopAtCachedPage: false,
438
438
  fetchUnreadBodies: opts.fetchUnreadBodies,
439
- fetchBodies,
440
- onBodyFetched: opts.onBodyFetched,
439
+ onUnreadBodyFetched: opts.onUnreadBodyFetched,
441
440
  budget,
442
441
  }, store);
443
442
  synced += bf.synced;
@@ -755,11 +754,13 @@ export async function syncAll(client, opts, store) {
755
754
  const budget = makeBudget(opts.maxRequests ?? Number.POSITIVE_INFINITY);
756
755
  // Decided HERE, not by each caller, so every path into a sync — the tool,
757
756
  // a read's autoRefresh, ofw_status — honours a no-read day (read-days.ts).
757
+ // The day protects only unread inbox messages: it refuses fetchUnreadBodies
758
+ // and nothing else, so sent and already-read bodies sync as on any day.
758
759
  const noReadDay = readingBlockedToday() !== null;
759
760
  const overriding = noReadDay && opts.overrideNoReadDay === true;
760
761
  const readingBlocked = noReadDay && !overriding;
761
- const bodyFetchedIds = [];
762
- const onBodyFetched = (id) => { bodyFetchedIds.push(id); };
762
+ const openedUnreadIds = [];
763
+ const onUnreadBodyFetched = (id) => { openedUnreadIds.push(id); };
763
764
  // resolveFolderIds always makes exactly one request; the tool guarantees
764
765
  // maxRequests >= 1, so this unit is always available (result intentionally
765
766
  // ignored — we account for it without a branch that can't be reached).
@@ -790,8 +791,7 @@ export async function syncAll(client, opts, store) {
790
791
  if (folder === 'inbox') {
791
792
  const r = await syncMessageFolder(client, 'inbox', ids.inbox, {
792
793
  fetchUnreadBodies: !readingBlocked && (opts.fetchUnreadBodies ?? false),
793
- fetchBodies: !readingBlocked,
794
- onBodyFetched,
794
+ onUnreadBodyFetched,
795
795
  deep: opts.deep ?? false,
796
796
  budget,
797
797
  }, store);
@@ -805,8 +805,6 @@ export async function syncAll(client, opts, store) {
805
805
  else if (folder === 'sent') {
806
806
  const r = await syncMessageFolder(client, 'sent', ids.sent, {
807
807
  fetchUnreadBodies: false,
808
- fetchBodies: !readingBlocked,
809
- onBodyFetched,
810
808
  deep: opts.deep ?? false,
811
809
  budget,
812
810
  }, store);
@@ -830,8 +828,8 @@ export async function syncAll(client, opts, store) {
830
828
  }
831
829
  }
832
830
  const notes = [];
833
- if (readingBlocked) {
834
- notes.push('Today is a no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS): new inbox and sent messages were cached from the list only — sender, date and subject — and no message body was downloaded. The first sync on a reading day fills in bodies that can be fetched without marking anything read.');
831
+ if (readingBlocked && opts.fetchUnreadBodies === true) {
832
+ notes.push('Today is a no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS), so fetchUnreadBodies was not honoured: unread inbox messages were cached from the list only — sender, date and subject — and none was marked read. Sent and already-read messages synced as usual.');
835
833
  }
836
834
  if (draftsUnverified) {
837
835
  notes.push('The drafts folder was NOT checked against OurFamilyWizard on this call (the request budget ran out first), so no drafts count is reported and the cached drafts are marked "unverified". Cached draft bodies may be behind the server. Call ofw_sync_messages again — or ofw_sync_messages with folders:["drafts"] — before editing or deleting a draft.');
@@ -858,8 +856,12 @@ export async function syncAll(client, opts, store) {
858
856
  syncComplete: done,
859
857
  refreshed,
860
858
  notRefreshed,
861
- ...(readingBlocked ? { bodiesWithheld: true } : {}),
862
- ...(overriding ? { readOverride: true, readOverrideNote: READ_OVERRIDE_NOTE, readOverrideMessageIds: bodyFetchedIds } : {}),
859
+ // Claimed only when the override released something: like ofw_get_message
860
+ // and ofw_list_messages, a sync whose read/sent bodies needed no override
861
+ // reports none and leaves nothing to audit.
862
+ ...(overriding && openedUnreadIds.length > 0
863
+ ? { readOverride: true, readOverrideNote: READ_OVERRIDE_NOTE, readOverrideMessageIds: openedUnreadIds }
864
+ : {}),
863
865
  note,
864
866
  markedRead,
865
867
  newMessages: newMessages.slice(0, NEW_MESSAGES_CAP),
@@ -26,7 +26,8 @@ import { compactSentMessage, compactWrittenDraft, MESSAGE_VIEWS, senderOf, viewD
26
26
  const WRITE_VIEW_NOTE = 'compact omits OurFamilyWizard\'s raw `listData` echo (which repeats the body, subject, recipients and a date block) and replaces the body you just wrote with `bodyLength` + `bodySha256` (the first 16 hex characters of its SHA-256) to confirm what landed. Pass "full" for both.';
27
27
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
28
28
  import { displayTimeZone, formatInstant, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
29
- import { READ_OVERRIDE_NOTE, auditReadOverride, readingBlockedToday } from '../read-days.js';
29
+ import { READ_OVERRIDE_NOTE, UNREAD_ON_NO_READ_DAY, auditReadOverride, readingBlockedToday } from '../read-days.js';
30
+ import { BODY_FORMAT_DESCRIPTION, prepareBody } from './plain-text.js';
30
31
  /** Why a draft has no draftKey — said instead of a bare null. */
31
32
  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.';
32
33
  /** `{draftKey, draftKeyInferred?}` or `{draftKey: null, draftKeyReason}` for one draft. */
@@ -267,7 +268,7 @@ function markReadCeiling(overrideDay) {
267
268
  if (blocked !== null && !overrideDay) {
268
269
  return {
269
270
  gate: 'OFW_READ_DAYS',
270
- reason: 'Today is a no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS), so no message body was fetched. readingBlocked says when reading resumes.',
271
+ reason: 'Today is a no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS), so no unread inbox body was fetched; sent and already-read messages synced as usual. readingBlocked says when reading resumes.',
271
272
  readingBlocked: blocked,
272
273
  };
273
274
  }
@@ -367,10 +368,20 @@ async function confirmMarkRead(ctx, cached, args, overriding) {
367
368
  });
368
369
  }
369
370
  /**
370
- * A message row with its content removed, for a no-read day. The body goes,
371
- * and so do the copies of it OFW's list payload carries (`preview`, `body`) —
372
- * otherwise `view:"full"` would hand back the first lines anyway. Everything
373
- * that says a message ARRIVED (subject, sender, dates, read state) stays.
371
+ * True for the one kind of message a no-read day protects: an INBOX message
372
+ * not yet read. Its body is what fetching would mark read (stamping a
373
+ * co-parent-visible "First Viewed" time), so it is withheld on those days.
374
+ * A sent message, an already-read inbox message and a draft are not.
375
+ */
376
+ function isUnreadInbox(row) {
377
+ return row.folder === 'inbox' && !deriveRead(row);
378
+ }
379
+ /**
380
+ * An unread inbox row with its content removed, for a no-read day. The body
381
+ * goes, and so do the copies of it OFW's list payload carries (`preview`,
382
+ * `body`) — otherwise `view:"full"` would hand back the first lines anyway.
383
+ * Everything that says a message ARRIVED (subject, sender, dates, read state)
384
+ * stays, and `withheldReason` says why this one body is absent.
374
385
  */
375
386
  function withholdBody(row) {
376
387
  let listData = row.listData;
@@ -378,7 +389,7 @@ function withholdBody(row) {
378
389
  const { preview: _preview, body: _body, ...rest } = listData;
379
390
  listData = rest;
380
391
  }
381
- return { ...row, body: null, listData, bodyWithheld: true };
392
+ return { ...row, body: null, listData, bodyWithheld: true, withheldReason: UNREAD_ON_NO_READ_DAY };
382
393
  }
383
394
  /**
384
395
  * Decide whether fetching this message's body from OFW would stamp the record,
@@ -481,7 +492,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
481
492
  when: { start: 'since', end: 'until' },
482
493
  aliases: ['messages', 'inbox', 'co-parent', 'ofw', 'ourfamilywizard', 'new messages'],
483
494
  }),
484
- description: 'List messages from the local OurFamilyWizard cache. Supports filtering by folder, date range, and a substring query on subject+body. Pagination is offset-based (1-based `page`) but if you know what you want (a date range, a topic), prefer the filters over walking pages — the cache may have 1000+ messages. Results are newest-first by default; `sort:"oldest"` starts at the old end of a range instead of paging to it. Returns an explicit `complete` boolean describing the RESULT SET: true means "this is every message on OurFamilyWizard matching these filters as of freshness.asOf" — check it before asserting a count. An empty result from a cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY") rather than reported as an absence; pass autoRefresh:true to sync and answer instead. On a server-configured no-read day bodies are withheld and q matches subjects only.' + OVERRIDE_DESCRIPTION,
495
+ description: 'List messages from the local OurFamilyWizard cache. Supports filtering by folder, date range, and a substring query on subject+body. Pagination is offset-based (1-based `page`) but if you know what you want (a date range, a topic), prefer the filters over walking pages — the cache may have 1000+ messages. Results are newest-first by default; `sort:"oldest"` starts at the old end of a range instead of paging to it. Returns an explicit `complete` boolean describing the RESULT SET: true means "this is every message on OurFamilyWizard matching these filters as of freshness.asOf" — check it before asserting a count. An empty result from a cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY") rather than reported as an absence; pass autoRefresh:true to sync and answer instead. On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) only unread inbox messages are protected: each keeps its sender, subject and time but carries body:null, bodyWithheld:true, withheldReason:"UNREAD_ON_NO_READ_DAY", and q matches it by subject only (bodySearchSkipped counts those); readingBlocked, ahead of the messages, appears only when something was withheld and says when reading resumes. Sent messages and inbox messages already read are returned and searched in full, exactly as on a reading day.' + OVERRIDE_DESCRIPTION,
485
496
  // Read-only even with autoRefresh: guardedCacheRead's sync never fetches
486
497
  // unread inbox bodies, so a list call cannot stamp "First Viewed".
487
498
  annotations: { readOnlyHint: true, openWorldHint: true },
@@ -547,12 +558,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
547
558
  }
548
559
  const cache = cacheProvider();
549
560
  const folders = folder === undefined ? ['inbox', 'sent'] : [folder];
550
- // On a no-read day `q` matches subjects only: a body match would tell the
551
- // caller what a message says without ever returning it.
561
+ // On a no-read day only UNREAD INBOX messages are protected: `q` matches
562
+ // their subject alone (a body match would tell the caller what one says
563
+ // without returning it), and their bodies are withheld below. Sent and
564
+ // already-read messages are searched and returned in full.
552
565
  const noReadDay = readingBlockedToday();
553
566
  const overriding = noReadDay !== null && args.overrideNoReadDay === true;
554
567
  const blocked = overriding ? null : noReadDay;
555
- const filter = { folder, since: bounds.since, until: bounds.until, q: args.q, qSubjectOnly: blocked !== null };
568
+ const filter = { folder, since: bounds.since, until: bounds.until, q: args.q, qBodyReadOnly: blocked !== null };
556
569
  const { value, refreshed, unverifiedEmpty } = await guardedCacheRead({
557
570
  client,
558
571
  cache,
@@ -633,25 +646,45 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
633
646
  if (refreshed) {
634
647
  payload.autoRefreshed = true;
635
648
  }
636
- if (blocked !== null) {
649
+ // Per message, not a blanket refusal: only unread inbox rows are withheld.
650
+ const withheld = blocked === null ? 0 : messages.filter(isUnreadInbox).length;
651
+ // Unread inbox messages in this folder/date scope whose body `q` did not
652
+ // search. Counted in the SAME terms the filter used (never opened), and
653
+ // then narrowed by deriveRead, so a message read on the web app but never
654
+ // fetched here is not reported as one the day hid.
655
+ let bodySearchSkipped = 0;
656
+ if (blocked !== null && args.q !== undefined && args.q.length > 0 && folder !== 'sent') {
657
+ const unopened = await cache.listMessages({
658
+ folder: 'inbox', since: bounds.since, until: bounds.until, unopenedInboxOnly: true, page: 1, size: 100_000,
659
+ });
660
+ bodySearchSkipped = unopened.filter(isUnreadInbox).length;
661
+ }
662
+ if (bodySearchSkipped > 0) {
663
+ payload.bodySearchSkipped = bodySearchSkipped;
664
+ payload.bodySearchSkippedNote = `Today is a no-read day: ${bodySearchSkipped} unread inbox message${bodySearchSkipped === 1 ? ' was' : 's were'} matched against the subject only, never the body. Sent and already-read messages were searched in full.`;
665
+ }
666
+ if (blocked !== null && (withheld > 0 || bodySearchSkipped > 0)) {
637
667
  // Ahead of `messages`, for the same reason the paging state is: a reader
638
- // that stops early must still learn that every body below is withheld.
639
- payload.readingBlocked = blocked;
668
+ // that stops early must still learn that some bodies below are withheld.
669
+ payload.readingBlocked = { ...blocked, withheld };
640
670
  }
641
- if (overriding) {
642
- Object.assign(payload, readOverrideFields('ofw_list_messages', messages.filter((m) => m.body !== null).map((m) => m.id)));
671
+ // The override released something only if a returned unread inbox row had
672
+ // a body to release; a read or sent body needed no override.
673
+ const released = overriding ? messages.filter((m) => m.body !== null && isUnreadInbox(m)).map((m) => m.id) : [];
674
+ if (released.length > 0) {
675
+ Object.assign(payload, readOverrideFields('ofw_list_messages', released));
643
676
  }
644
677
  payload.freshness = freshness;
645
678
  // Projected HERE, at the last possible moment, so `returned`, `complete`
646
679
  // and every note above are computed from the rows themselves — a
647
680
  // projection must never be able to change what the response claims about
648
681
  // its own contents.
649
- payload.messages = viewMessages(view, blocked === null ? messages : messages.map(withholdBody));
682
+ payload.messages = viewMessages(view, blocked === null ? messages : messages.map((m) => (isUnreadInbox(m) ? withholdBody(m) : m)));
650
683
  return jsonResponse(payload);
651
684
  });
652
685
  server.registerTool('ofw_get_message', {
653
686
  _meta: familyMeta('lookup'),
654
- description: 'Get a single OurFamilyWizard message OR draft by ID. Reads from local cache when available; otherwise fetches from OFW — and for an UNREAD INBOX message that fetch marks it read and stamps a "First Viewed" time the co-parent can see, which is part of the record and cannot be undone. Pass allowMarkRead:false to refuse such a fetch instead (cached bodies, sent messages and already-read messages are unaffected, because none of them stamp anything). For ids that match a draft (in the drafts cache), the response carries folder="drafts" and the body/subject/recipients reflect the drafts cache (which ofw_sync_messages keeps fresh) — drafts have no `fromUser`, and `sentAt`/`fetchedBodyAt` mirror the draft\'s `modifiedAt`. For inbox/sent messages, folder is "inbox" or "sent" as before. On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) inbox/sent bodies are withheld (body:null, bodyWithheld:true, readingBlocked says when reading resumes) and OFW is never contacted. When the server runs with OFW_CONFIRM_MARK_READ=true, opening an unread inbox message first shows its subject, sender and sent time and asks the user to confirm marking it read: a confirmation prompt where the client supports one; otherwise the first call fetches NOTHING and returns that preview plus a confirmToken, and only a repeat call with that token opens the message (see MCP_CONFIRM_MODE). Show the user the preview and wait for their yes before repeating the call.' + OVERRIDE_DESCRIPTION,
687
+ description: 'Get a single OurFamilyWizard message OR draft by ID. Reads from local cache when available; otherwise fetches from OFW — and for an UNREAD INBOX message that fetch marks it read and stamps a "First Viewed" time the co-parent can see, which is part of the record and cannot be undone. Pass allowMarkRead:false to refuse such a fetch instead (cached bodies, sent messages and already-read messages are unaffected, because none of them stamp anything). For ids that match a draft (in the drafts cache), the response carries folder="drafts" and the body/subject/recipients reflect the drafts cache (which ofw_sync_messages keeps fresh) — drafts have no `fromUser`, and `sentAt`/`fetchedBodyAt` mirror the draft\'s `modifiedAt`. For inbox/sent messages, folder is "inbox" or "sent" as before. On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) only an UNREAD inbox message is protected: its body is withheld (body:null, bodyWithheld:true, withheldReason:"UNREAD_ON_NO_READ_DAY", readingBlocked says when reading resumes) and OFW is never contacted for it; an id not in the cache is refused, since fetching it could mark it read. Sent messages and inbox messages already read are returned exactly as on a reading day. When the server runs with OFW_CONFIRM_MARK_READ=true, opening an unread inbox message first shows its subject, sender and sent time and asks the user to confirm marking it read: a confirmation prompt where the client supports one; otherwise the first call fetches NOTHING and returns that preview plus a confirmToken, and only a repeat call with that token opens the message (see MCP_CONFIRM_MODE). Show the user the preview and wait for their yes before repeating the call.' + OVERRIDE_DESCRIPTION,
655
688
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
656
689
  inputSchema: z.object({
657
690
  messageId: z.string().describe('Message ID (also accepts draft IDs — drafts are routed via the drafts cache)'),
@@ -725,17 +758,22 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
725
758
  });
726
759
  }
727
760
  const cached = await cache.getMessage(id);
728
- // No-read day: answer from the cache with the body withheld, and never
729
- // touch OFW — any detail GET here could mark an unread message read.
761
+ // No-read day: protect an UNREAD INBOX message — answer from the cache
762
+ // with its body withheld and never touch OFW, since its detail GET would
763
+ // mark it read. An uncached id is refused: whether it is one is exactly
764
+ // what cannot be known without that GET. Sent and already-read messages
765
+ // fall through and are served as on any other day.
730
766
  const noReadDay = readingBlockedToday();
731
- const overriding = noReadDay !== null && args.overrideNoReadDay === true;
732
- const blocked = overriding ? null : noReadDay;
767
+ const protectedToday = noReadDay !== null && (cached === null || isUnreadInbox(cached));
768
+ // The override is "used" only when it lifts the day for THIS message.
769
+ const overriding = protectedToday && args.overrideNoReadDay === true;
770
+ const blocked = protectedToday && !overriding ? noReadDay : null;
733
771
  if (blocked !== null) {
734
772
  if (cached === null) {
735
773
  return jsonErrorResponse({
736
774
  ...blocked,
737
775
  messageId: id,
738
- hint: 'This id is not in the cache. Run ofw_sync_messages (it walks list pages, not bodies, and marks nothing read) to see its subject, sender and date.',
776
+ hint: 'This id is not in the cache, so whether it is an unread inbox message cannot be told without the request that would mark it read. Run ofw_sync_messages (it never opens an unread inbox message) to see its subject, sender and date — and, if it is sent or already read, its body.',
739
777
  });
740
778
  }
741
779
  const attachments = await cache.listAttachmentsForMessage(id);
@@ -866,6 +904,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
866
904
  inputSchema: z.object({
867
905
  subject: z.string().describe('Message subject. Required unless draftId/messageId is given (then it overrides the server draft\'s subject).').optional(),
868
906
  body: z.string().describe('Message body text. Required unless draftId/messageId is given (then it overrides the server draft\'s body — omit it to send exactly what is on OurFamilyWizard).').optional(),
907
+ bodyFormat: z.enum(['markdown', 'plain']).describe(`${BODY_FORMAT_DESCRIPTION} Applies only to a body passed here: a draft sent by id goes out exactly as it is on OurFamilyWizard.`).optional(),
869
908
  recipientIds: z.array(z.number()).describe('Array of recipient user IDs (get from ofw_get_profile). Usually required even when sending a draft: OurFamilyWizard does not persist recipients on drafts.').optional(),
870
909
  replyToId: z.number().describe('ID of the message being replied to. Defaults to the draft\'s stored reply target when sending by draftId.').optional(),
871
910
  draftId: z.number().describe('ID of an existing draft to send. The draft is re-read from OurFamilyWizard and its SERVER content is sent; missing subject/body default from it. Guarded: a draft that changed since you read it, or that was already sent/deleted, refuses rather than sending blind.').optional(),
@@ -892,7 +931,10 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
892
931
  const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : undefined;
893
932
  const pending = await planAttachments({ inline: args.inlineAttachments, blobKeys: args.blobKeys }, { store: blobStore, readBlobs: true });
894
933
  let subject = args.subject;
895
- let body = args.body;
934
+ // Only a body the CALLER supplies is converted. A draft sent by id goes
935
+ // out as it is on OFW — the artifact sent is the artifact on the server.
936
+ const prepared = args.body === undefined ? null : prepareBody(args.body, args.bodyFormat);
937
+ let body = prepared?.body;
896
938
  let recipientIds = args.recipientIds;
897
939
  let draftReplyToId = null;
898
940
  let guardNote = null;
@@ -1007,6 +1049,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1007
1049
  : {}),
1008
1050
  subject,
1009
1051
  body,
1052
+ ...(prepared?.conversion ? { bodyConversion: prepared.conversion } : {}),
1010
1053
  replyTo: resolvedReplyTo === null
1011
1054
  ? null
1012
1055
  : { messageId: resolvedReplyTo, subject: replyParent?.subject ?? null, from: replyParent?.fromUser || null },
@@ -1251,8 +1294,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1251
1294
  ...(attachmentCheck !== null ? { attachments: attachmentCheck } : {}),
1252
1295
  ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1253
1296
  ...(uploadWarnings.length > 0 ? { warnings: uploadWarnings } : {}),
1297
+ ...(prepared?.conversion ? { bodyConversion: prepared.conversion } : {}),
1254
1298
  };
1255
- return notedJsonResponse([guardNote, rewriteNote, verifyNote, threadNote, attachmentNote, unconfirmedNote, retainNote], responseObj, 'Message sent successfully.');
1299
+ return notedJsonResponse([guardNote, rewriteNote, prepared?.noteLine ?? null, verifyNote, threadNote, attachmentNote, unconfirmedNote, retainNote], responseObj, 'Message sent successfully.');
1256
1300
  });
1257
1301
  async function guardDestructiveDraftOp(input) {
1258
1302
  const { cache, draftId, expectedRevision, force, action } = input;
@@ -1460,6 +1504,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1460
1504
  inputSchema: z.object({
1461
1505
  subject: z.string().describe('Message subject'),
1462
1506
  body: z.string().describe('Message body text'),
1507
+ bodyFormat: z.enum(['markdown', 'plain']).describe(BODY_FORMAT_DESCRIPTION).optional(),
1463
1508
  recipientIds: z.array(z.number()).describe('Array of recipient user IDs (optional for drafts)').optional(),
1464
1509
  messageId: z.number().describe('ID of an existing draft to replace (the new draft will have a new id; the old is deleted)').optional(),
1465
1510
  replyToId: z.number().nullable().describe('ID of the message this draft replies to. When replacing a draft (messageId), omit it to keep the draft\'s own reply target, or pass null to make the draft a new top-level message.').optional(),
@@ -1474,6 +1519,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1474
1519
  }, async (args) => {
1475
1520
  const cache = cacheProvider();
1476
1521
  const view = resolveView(args.view, MESSAGE_VIEWS);
1522
+ const prepared = prepareBody(args.body, args.bodyFormat);
1477
1523
  // New attachments are validated before ANYTHING happens, so a bad entry
1478
1524
  // fails the call with nothing uploaded and nothing saved.
1479
1525
  const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : undefined;
@@ -1539,7 +1585,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1539
1585
  // messageId, we delete the old draft afterward (the "replace" path).
1540
1586
  const payload = {
1541
1587
  subject: args.subject,
1542
- body: args.body,
1588
+ body: prepared.body,
1543
1589
  recipientIds: args.recipientIds ?? serverRecipientIds ?? [],
1544
1590
  attachments: { myFileIDs },
1545
1591
  draft: true,
@@ -1560,7 +1606,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1560
1606
  // loss must be reported. Never a silent drop (Defect 3).
1561
1607
  const warnings = [...uploadWarnings];
1562
1608
  if (newId !== null) {
1563
- verifyNote = verifyWriteLanded('draft', { subject: args.subject, body: args.body }, detail);
1609
+ verifyNote = verifyWriteLanded('draft', { subject: args.subject, body: prepared.body }, detail);
1564
1610
  // Trust the re-fetched server detail as the source of truth for the stored
1565
1611
  // replyToId — NOT `resolvedReplyTo` (what we intended to post). OFW
1566
1612
  // normalizes/drops threading after a save, and masking that with our own
@@ -1718,12 +1764,13 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1718
1764
  ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1719
1765
  ...(warnings.length > 0 ? { warnings } : {}),
1720
1766
  ...(recipientsNote !== null ? { recipientsNote } : {}),
1767
+ ...(prepared.conversion !== null ? { bodyConversion: prepared.conversion } : {}),
1721
1768
  }
1722
1769
  : raw;
1723
1770
  const warnNote = warnings.length > 0
1724
1771
  ? `WARNING: ${warnings.join('\n\n')}`
1725
1772
  : null;
1726
- return notedJsonResponse([forceNote, rewriteNote, verifyNote, warnNote, recipientsNote, replaceNote], responseObj, 'Draft saved.');
1773
+ return notedJsonResponse([forceNote, rewriteNote, prepared.noteLine, verifyNote, warnNote, recipientsNote, replaceNote], responseObj, 'Draft saved.');
1727
1774
  });
1728
1775
  if (allowDrafts)
1729
1776
  server.registerTool('ofw_delete_draft', {
@@ -1989,7 +2036,7 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
1989
2036
  // Destructive: force:true replaces an existing file in the attachments
1990
2037
  // directory (which is also the default upload directory), and nothing
1991
2038
  // here restores what it replaced. The default refuses to overwrite.
1992
- description: 'Download an OFW message attachment by fileId and return content you can actually read. Inline delivery walks a ladder and returns the first rung that works: (1) host-renderable images (PNG/JPEG/GIF/WEBP) come back as ImageContent; (2) .xlsx/.csv/.tsv, .pdf, .docx, .pptx and text files come back as EXTRACTED CONTENT — per-sheet CSV, per-page/slide text, document text — in the response JSON under `extracted`; (3) anything else comes back as an EmbeddedResource blob of the raw bytes. Images and raw bytes are only returned inline up to 10 MiB; a larger file fails with a tool error that says how to get it instead (extracted text is unaffected — it is bounded by maxChars). The meta block names the rung as `deliveredVia` and, when it falls through to bytes, lists what was tried in `deliveryAttempts`. Reported mime types are always normalized to a bare media type (no charset/name parameters). In disk mode the bytes are saved to ~/Downloads/ofw-mcp/ and the response carries the absolute path; pass extract:true to ALSO get the extracted content in that response. The default for `inline` can be flipped server-side via the OFW_INLINE_ATTACHMENTS env var. On a hosted deployment with no filesystem, disk mode is unavailable, so inline is forced (forcedInline:true) rather than failing — a saveTo path never costs you the content. fileId comes from attachments[].fileId on ofw_get_message. Override disk destination with OFW_ATTACHMENTS_DIR or saveTo; saveTo must stay inside the attachments directory, and an existing file is never overwritten unless force:true. Re-downloading to the same path is a no-op (disk mode only).',
2039
+ description: 'Download an OFW message attachment by fileId and return content you can actually read. Inline delivery walks a ladder and returns the first rung that works: (1) host-renderable images (PNG/JPEG/GIF/WEBP) come back as ImageContent; (2) .xlsx/.csv/.tsv, .pdf, .docx, .pptx and text files come back as EXTRACTED CONTENT — per-sheet CSV, per-page/slide text, document text — in the response JSON under `extracted`; (3) anything else comes back as an EmbeddedResource blob of the raw bytes. Images and raw bytes are only returned inline up to 10 MiB; a larger file fails with a tool error that says how to get it instead (extracted text is unaffected — it is bounded by maxChars). The meta block names the rung as `deliveredVia` and, when it falls through to bytes, lists what was tried in `deliveryAttempts`. Reported mime types are always normalized to a bare media type (no charset/name parameters). In disk mode the bytes are saved to ~/Downloads/ofw-mcp/ and the response carries the absolute path; pass extract:true to ALSO get the extracted content in that response. The default for `inline` can be flipped server-side via the OFW_INLINE_ATTACHMENTS env var. On a hosted deployment with no filesystem, disk mode is unavailable, so inline is forced (forcedInline:true) rather than failing — a saveTo path never costs you the content. fileId comes from attachments[].fileId on ofw_get_message. Override disk destination with OFW_ATTACHMENTS_DIR or saveTo; saveTo must stay inside the attachments directory, and an existing file is never overwritten unless force:true. Re-downloading to the same path is a no-op (disk mode only). On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) only attachments of unread inbox messages are withheld (READING_BLOCKED, with nextReadableDay), along with files the cache cannot place; attachments of sent, already-read and draft messages download as on any day.',
1993
2040
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
1994
2041
  inputSchema: z.object({
1995
2042
  fileId: z.number().describe('Attachment file id (from ofw_get_message → attachments[].fileId)'),
@@ -2024,24 +2071,29 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2024
2071
  const forcedInline = inline && !requestedInline;
2025
2072
  const deliveryOptions = { extract: args.extract, maxChars: args.maxChars, parts: args.parts };
2026
2073
  let cached = await cache.getAttachment(fileId);
2027
- // No-read day: an attachment is message content. Only a file the cache
2028
- // knows belongs to the account holder's own DRAFTS is released; anything
2029
- // linked to an inbox/sent message — or that the cache cannot place at all
2030
- // — is refused before any request is made.
2074
+ // No-read day: an unread inbox message's attachment is its content, so it
2075
+ // is withheld with the body. A file is released only when the cache can
2076
+ // place it AND every message it is linked to is readable today — a draft,
2077
+ // a sent message, or an inbox message already read. A file on an unread
2078
+ // inbox message, or one the cache cannot place, is refused before any
2079
+ // request is made.
2031
2080
  const blocked = readingBlockedToday();
2032
2081
  if (blocked !== null) {
2033
2082
  const linked = (cached?.messageIds ?? []).filter((mid) => mid !== 0);
2034
- let draftOnly = linked.length > 0;
2083
+ let readable = linked.length > 0;
2035
2084
  for (const mid of linked) {
2036
- if ((await cache.getDraft(mid)) === null)
2037
- draftOnly = false;
2085
+ if ((await cache.getDraft(mid)) !== null)
2086
+ continue;
2087
+ const message = await cache.getMessage(mid);
2088
+ if (message === null || isUnreadInbox(message))
2089
+ readable = false;
2038
2090
  }
2039
- if (!draftOnly) {
2091
+ if (!readable) {
2040
2092
  return jsonErrorResponse({
2041
2093
  ...blocked,
2042
2094
  fileId,
2043
2095
  ...(cached ? { fileName: cached.fileName } : {}),
2044
- hint: 'Attachments on received or sent messages (or files this cache cannot place) are withheld on a no-read day. Download it on the next reading day.',
2096
+ hint: 'Attachments of unread inbox messages (and files this cache cannot place) are withheld on a no-read day. Attachments of sent, already-read and draft messages are not. Download it on the next reading day.',
2045
2097
  });
2046
2098
  }
2047
2099
  }
@@ -2165,7 +2217,7 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2165
2217
  _meta: familyMeta('other'),
2166
2218
  // Destructive: fetchUnreadBodies:true stamps a co-parent-visible "First
2167
2219
  // Viewed" time on every unread inbox message it touches — irreversible.
2168
- description: 'Sync messages from OurFamilyWizard into the local cache. A sync NEVER marks a message read unless fetchUnreadBodies is set: a new inbox message that OFW does not list as read is cached from the list (sender, date, subject) WITHOUT its body, because fetching the body is what stamps a co-parent-visible "First Viewed" time. Every response says what arrived: newMessages lists each message first cached by THIS call — inbox and sent, newest first, with read (its state before the sync) and bodyFetched; newMessagesTotal and newMessagesTruncated give the full count when more than ' + NEW_MESSAGES_CAP + ' arrived (ofw_list_messages pages through the rest). unreadInbox lists the new inbox messages that were unread when the sync began; bodyFetched:false means still unread on OFW — call ofw_get_message(id) to read one, which marks it read. If this call DID mark anything read (fetchUnreadBodies, or a stamp it detected but did not intend), the response LEADS with a warning and lists each in markedRead with reason "fetchUnreadBodies" or "unexpected"; markedRead is omitted when nothing was marked, and markedReadCount is always present. Returns counts per folder too. EVERY call re-checks the newest page first, so new messages are picked up promptly even while an old-history backfill is still running; only then does it spend what is left of its budget advancing that backfill. Pass deep:true to walk all OFW pages instead of stopping at the first all-cached page (use to backfill suspected gaps). Sync is BOUNDED and RESUMABLE: on hosted deployments a per-call OFW-request budget (env OFW_SYNC_MAX_REQUESTS, or the maxRequests argument) caps how far one call walks; when the budget is hit the response reports done:false with a note — call again with the SAME arguments to resume. done:false means older history is still being backfilled; it does NOT mean recent messages are missing. Local installs are unbounded by default (done is always true). On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) no inbox or sent message body is downloaded at all — new messages are cached from the list (sender, date, subject) and the response carries bodiesWithheld:true; the first sync on a reading day fills in those bodies, except unread inbox ones. Under overrideNoReadDay a sync fetches bodies as on a reading day; it still marks nothing read without fetchUnreadBodies:true.' + OVERRIDE_DESCRIPTION,
2220
+ description: 'Sync messages from OurFamilyWizard into the local cache. A sync NEVER marks a message read unless fetchUnreadBodies is set: a new inbox message that OFW does not list as read is cached from the list (sender, date, subject) WITHOUT its body, because fetching the body is what stamps a co-parent-visible "First Viewed" time. Every response says what arrived: newMessages lists each message first cached by THIS call — inbox and sent, newest first, with read (its state before the sync) and bodyFetched; newMessagesTotal and newMessagesTruncated give the full count when more than ' + NEW_MESSAGES_CAP + ' arrived (ofw_list_messages pages through the rest). unreadInbox lists the new inbox messages that were unread when the sync began; bodyFetched:false means still unread on OFW — call ofw_get_message(id) to read one, which marks it read. If this call DID mark anything read (fetchUnreadBodies, or a stamp it detected but did not intend), the response LEADS with a warning and lists each in markedRead with reason "fetchUnreadBodies" or "unexpected"; markedRead is omitted when nothing was marked, and markedReadCount is always present. Returns counts per folder too. EVERY call re-checks the newest page first, so new messages are picked up promptly even while an old-history backfill is still running; only then does it spend what is left of its budget advancing that backfill. Pass deep:true to walk all OFW pages instead of stopping at the first all-cached page (use to backfill suspected gaps). Sync is BOUNDED and RESUMABLE: on hosted deployments a per-call OFW-request budget (env OFW_SYNC_MAX_REQUESTS, or the maxRequests argument) caps how far one call walks; when the budget is hit the response reports done:false with a note — call again with the SAME arguments to resume. done:false means older history is still being backfilled; it does NOT mean recent messages are missing. Local installs are unbounded by default (done is always true). On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) a sync only protects unread inbox messages: it keeps syncing and fetching bodies for sent and already-read messages as on any day, and fetchUnreadBodies (argument or OFW_FETCH_UNREAD_BODIES) is refused, reported in unreadBodies.gate. Under overrideNoReadDay, fetchUnreadBodies:true on this call opens unread inbox messages as on a reading day; the env default alone does not.' + OVERRIDE_DESCRIPTION,
2169
2221
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
2170
2222
  inputSchema: z.object({
2171
2223
  folders: z.array(z.enum(['inbox', 'sent', 'drafts'])).min(1).describe('Folders to sync (default: all three). Must be non-empty if given — an empty list would sync nothing while reporting success.').optional(),
@@ -2253,9 +2305,14 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2253
2305
  for (const row of rows)
2254
2306
  markedRead.push(await openUnreadBody(client, cache, row));
2255
2307
  result.markedRead = markedRead;
2256
- if (result.readOverride) {
2308
+ // Keyed on this call's own decision, not on result.readOverride: the
2309
+ // sync claims an override only when IT opened something, and under
2310
+ // confirmation it opens nothing — these opens are the release.
2311
+ if (overriding) {
2257
2312
  const openedIds = rows.map((row) => row.id);
2258
- result.readOverrideMessageIds.push(...openedIds);
2313
+ result.readOverride = true;
2314
+ result.readOverrideNote = READ_OVERRIDE_NOTE;
2315
+ result.readOverrideMessageIds = [...(result.readOverrideMessageIds ?? []), ...openedIds];
2259
2316
  auditReadOverride('ofw_sync_messages', openedIds);
2260
2317
  }
2261
2318
  }