ofw-mcp 2.29.0 → 2.30.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/sync.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { clearHeldFiles, getHeldFiles, setHeldFiles } from './tools/held-attachments.js';
2
2
  import { z } from 'zod';
3
- import { ApiRecipientSchema, draftReplyTarget, hasRealView, mapRecipients, scrapeSaysRead } from './tools/_shared.js';
3
+ import { ApiRecipientSchema, detailRecipients, draftReplyTarget, hasRealView, mapRecipients, mergeRecipients, scrapeSaysRead } from './tools/_shared.js';
4
4
  import { clearReplyToSource, setReplyToSource } from './tools/reply-source.js';
5
5
  import { senderOf } from './tools/project.js';
6
6
  import { parseLenient } from '@chrischall/mcp-utils';
@@ -77,8 +77,16 @@ async function fetchAttachmentMetaBudgeted(client, messageId, fileIds, store, bu
77
77
  await fetchAttachmentMetaForMessage(client, messageId, affordable, store);
78
78
  }
79
79
  }
80
+ /**
81
+ * A folder id as OFW sends it, normalised to the string every comparison in
82
+ * this server uses. The live /pub/v1/messageFolders payload carries NUMBERS
83
+ * (verified 2026-11-19); a string-only schema warned on every sync and passed
84
+ * the numbers through typed as strings, so `String(detail.folder.id) ===
85
+ * map.sent` in lifecycle.ts could never match a live-resolved map.
86
+ */
87
+ export const FolderIdSchema = z.union([z.string(), z.number()]).transform(String);
80
88
  const FoldersSchema = z.looseObject({
81
- systemFolders: z.array(z.looseObject({ id: z.string(), folderType: z.string() })).optional(),
89
+ systemFolders: z.array(z.looseObject({ id: FolderIdSchema, folderType: z.string() })).optional(),
82
90
  });
83
91
  export async function resolveFolderIds(client, store) {
84
92
  const data = parseLenient(FoldersSchema, await client.request('GET', '/pub/v1/messageFolders?includeFolderCounts=true'), { label: 'ofw-mcp', context: 'GET /pub/v1/messageFolders' });
@@ -233,11 +241,15 @@ async function walkPages(client, folder, folderId, opts, store) {
233
241
  break;
234
242
  }
235
243
  const detail = await fetchDetail(item, { subject: existing.subject, sentAt: existing.sentAt, from: senderOf(existing) }, 'GET /pub/v3/messages/{id} (body backfill)', false);
244
+ const checkedAt = new Date().toISOString();
236
245
  toUpsert.push({
237
246
  ...existing,
238
247
  body: detail.body ?? '',
239
- fetchedBodyAt: new Date().toISOString(),
240
- recipients: mapRecipients(detail.recipients ?? item.recipients),
248
+ fetchedBodyAt: checkedAt,
249
+ // A detail that omits recipients (or a view time) must not erase
250
+ // what the cache already recorded — and the LIST's recipients
251
+ // carry only a placeholder, so they are never a substitute.
252
+ recipients: mergeRecipients(existing.recipients, detailRecipients(detail.recipients, checkedAt)),
241
253
  listData: item,
242
254
  });
243
255
  synced++;
@@ -262,7 +274,8 @@ async function walkPages(client, folder, folderId, opts, store) {
262
274
  break;
263
275
  }
264
276
  const detail = parseLenient(DetailResponseSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (view-status refresh)' });
265
- toUpsert.push({ ...existing, recipients: mapRecipients(detail.recipients), listData: item });
277
+ const recipients = mergeRecipients(existing.recipients, detailRecipients(detail.recipients, new Date().toISOString()));
278
+ toUpsert.push({ ...existing, recipients, listData: item });
266
279
  synced++;
267
280
  }
268
281
  continue;
@@ -278,7 +291,7 @@ async function walkPages(client, folder, folderId, opts, store) {
278
291
  // the row from the list would cache viewedAt:null for a message that was
279
292
  // already read by the time we first saw it — reporting "never viewed" for
280
293
  // a message OFW shows as read, until a later sync's refresh healed it.
281
- let detailRecipients;
294
+ let detailRecipientsRaw;
282
295
  // The row as the list describes it; the detail (if fetched) fills in
283
296
  // body and real view times below.
284
297
  const row = {
@@ -287,7 +300,7 @@ async function walkPages(client, folder, folderId, opts, store) {
287
300
  subject: item.subject ?? '(no subject)',
288
301
  fromUser: item.from?.name ?? '',
289
302
  sentAt: item.date?.dateTime ?? nowNaiveWallClock(),
290
- recipients: mapRecipients(item.recipients),
303
+ recipients: mapRecipients(item.recipients, { source: 'list' }),
291
304
  body: null,
292
305
  fetchedBodyAt: null,
293
306
  replyToId: null,
@@ -306,7 +319,7 @@ async function walkPages(client, folder, folderId, opts, store) {
306
319
  opts.onUnreadBodyFetched?.(item.id);
307
320
  body = detail.body ?? '';
308
321
  fetchedBodyAt = new Date().toISOString();
309
- detailRecipients = detail.recipients;
322
+ detailRecipientsRaw = detail.recipients;
310
323
  if (Array.isArray(detail.files) && detail.files.length > 0) {
311
324
  detailFileIds = detail.files;
312
325
  }
@@ -327,8 +340,8 @@ async function walkPages(client, folder, folderId, opts, store) {
327
340
  });
328
341
  row.body = body;
329
342
  row.fetchedBodyAt = fetchedBodyAt;
330
- if (detailRecipients)
331
- row.recipients = mapRecipients(detailRecipients);
343
+ if (detailRecipientsRaw)
344
+ row.recipients = mergeRecipients(row.recipients, detailRecipients(detailRecipientsRaw, fetchedBodyAt));
332
345
  toUpsert.push(row);
333
346
  synced++;
334
347
  if (detailFileIds.length > 0) {
@@ -173,6 +173,10 @@ const TIMESTAMP_KEYS = new Set([
173
173
  // OFW: UTC instants we stamp ourselves.
174
174
  'fetchedBodyAt',
175
175
  'fetchedAt',
176
+ // When the detail behind a recipient's `viewedAt` was read (issue #448).
177
+ // NOT `viewedPlaceholder`: that is OFW's raw epoch-zero placeholder, kept
178
+ // verbatim precisely so it can never be rendered as a real time.
179
+ 'viewedAtCheckedAt',
176
180
  'syncedAt',
177
181
  'downloadedAt',
178
182
  'recordedAt',
@@ -70,24 +70,80 @@ export const ApiRecipientSchema = z.looseObject({
70
70
  }).optional(),
71
71
  viewed: z.looseObject({ dateTime: z.string() }).nullable().optional(),
72
72
  });
73
- // Translates OFW API recipient shape into the cache's normalized Recipient.
74
- // Used wherever we surface or persist recipients (sync, get_message, send,
75
- // save_draft).
76
- //
77
- // `viewedAt` is the recipient's true "First Viewed" time, or null if not yet
78
- // viewed. Only the DETAIL endpoint (/pub/v3/messages/{id}) carries a real
79
- // timestamp; the LIST endpoint returns an epoch-zero PLACEHOLDER
80
- // ("1970-01-01T00:00:00") in the SAME field even for read messages (on the
81
- // list, read status lives in the flags — `read` for inbox, `showNeverViewed`
82
- // for sent; see scrapeSaysRead — not the timestamp). So treat
83
- // the epoch placeholder as "no real view time" — otherwise a list-sourced row
84
- // reports a bogus 1970 read time. A detail re-fetch is what fills in the truth.
85
- export function mapRecipients(items) {
73
+ export function mapRecipients(items, origin) {
86
74
  return (items ?? []).map((r) => {
87
75
  const dt = r.viewed?.dateTime;
88
- const viewedAt = typeof dt === 'string' && !dt.startsWith('1970-01-01') ? dt : null;
89
- return { userId: r.user?.userId ?? r.user?.id ?? 0, name: r.user?.name ?? '', viewedAt };
76
+ const placeholder = typeof dt === 'string' && dt.startsWith('1970-01-01');
77
+ const viewedAt = typeof dt === 'string' && !placeholder ? dt : null;
78
+ const out = { userId: r.user?.userId ?? r.user?.id ?? 0, name: r.user?.name ?? '', viewedAt };
79
+ if (origin) {
80
+ out.viewedAtSource = origin.source;
81
+ if (origin.source === 'detail' && origin.checkedAt !== undefined)
82
+ out.viewedAtCheckedAt = origin.checkedAt;
83
+ if (placeholder)
84
+ out.viewedPlaceholder = dt;
85
+ }
86
+ return out;
87
+ });
88
+ }
89
+ /**
90
+ * A detail payload's recipients, labelled as read from the detail at
91
+ * `checkedAt` — or null when the payload reported none (absent or empty), so
92
+ * {@link mergeRecipients} keeps what the cache already knew.
93
+ */
94
+ export function detailRecipients(items, checkedAt) {
95
+ return items && items.length > 0 ? mapRecipients(items, { source: 'detail', checkedAt }) : null;
96
+ }
97
+ function sameRecipient(a, b) {
98
+ if (a.userId !== 0 && b.userId !== 0)
99
+ return a.userId === b.userId;
100
+ return a.name !== '' && a.name === b.name;
101
+ }
102
+ /**
103
+ * Combine freshly fetched recipients with what the cache already held, so an
104
+ * INCOMPLETE OFW response can never erase evidence (issue #448).
105
+ *
106
+ * - No recipients reported (absent or `[]`) → the cached set stands; a message
107
+ * always has recipients, so an empty array is "not echoed", not "none".
108
+ * - A recipient the fresh payload gives no real view time, where the cache
109
+ * holds one → the cached time is carried forward WITH its original
110
+ * provenance (`viewedAtSource`/`viewedAtCheckedAt`), so a reader can tell it
111
+ * was not re-observed by this fetch. "First Viewed" cannot be withdrawn, so
112
+ * a payload that omits it is incomplete, not a correction.
113
+ *
114
+ * Membership otherwise follows the fresh payload.
115
+ */
116
+ export function mergeRecipients(prior, fresh) {
117
+ if (fresh === null || fresh.length === 0)
118
+ return prior ?? [];
119
+ const priorList = prior ?? [];
120
+ return fresh.map((r) => {
121
+ if (hasRealView([r]))
122
+ return r;
123
+ const match = priorList.find((p) => sameRecipient(p, r) && hasRealView([p]));
124
+ if (!match)
125
+ return r;
126
+ const carried = { userId: r.userId, name: r.name, viewedAt: match.viewedAt };
127
+ if (match.viewedAtSource !== undefined)
128
+ carried.viewedAtSource = match.viewedAtSource;
129
+ if (match.viewedAtCheckedAt !== undefined)
130
+ carried.viewedAtCheckedAt = match.viewedAtCheckedAt;
131
+ return carried;
132
+ });
133
+ }
134
+ export function withViewOrigin(row, callStartedAtMs) {
135
+ const recipients = row.recipients.map((r) => {
136
+ let viewedAtOrigin;
137
+ if (r.viewedAtSource === 'detail') {
138
+ const at = r.viewedAtCheckedAt === undefined ? NaN : Date.parse(r.viewedAtCheckedAt);
139
+ viewedAtOrigin = at >= callStartedAtMs ? 'detail-this-call' : 'detail-cached';
140
+ }
141
+ else {
142
+ viewedAtOrigin = r.viewedAtSource ?? 'unrecorded';
143
+ }
144
+ return { ...r, viewedAtOrigin };
90
145
  });
146
+ return { ...row, recipients };
91
147
  }
92
148
  // True if any recipient has a *real* "First Viewed" time — i.e. present and
93
149
  // not the epoch-zero placeholder. After mapRecipients a fresh `viewedAt` is
@@ -0,0 +1,198 @@
1
+ import { z } from 'zod';
2
+ import { parseLenient, pruneUndefined } from '@chrischall/mcp-utils';
3
+ import { ApiRecipientSchema, mapRecipients } from './_shared.js';
4
+ import { briefDate, briefLine } from './hints.js';
5
+ import { offsetState, readUpstreamPaging } from './pagination.js';
6
+ /**
7
+ * Messages in folders the cache does not hold (issue #453).
8
+ *
9
+ * The cache syncs three folders: inbox, sent and drafts. OurFamilyWizard has
10
+ * more — user-created folders, plus system folders such as Archived and Action
11
+ * Items — and a message the account holder files into one of them leaves the
12
+ * inbox, so before this it was unreachable from every tool. And
13
+ * `ofw_list_message_folders` advertised "folder IDs needed to call
14
+ * ofw_list_messages", which then refused every one of them.
15
+ *
16
+ * These are read LIVE, one list page per call, and never cached. The list
17
+ * endpoint is what the sync already walks: it carries no body and stamps
18
+ * nothing, so reading a folder this way can never mark a message read. Bodies
19
+ * stay behind `ofw_get_message`, with every gate it applies.
20
+ */
21
+ const FolderEntrySchema = z.looseObject({
22
+ // Numeric on the live payload (verified 2026-11-19), strings in older fixtures.
23
+ id: z.union([z.number(), z.string()]).optional(),
24
+ name: z.string().optional(),
25
+ folderType: z.string().optional(),
26
+ });
27
+ const FoldersSchema = z.looseObject({
28
+ systemFolders: z.array(FolderEntrySchema).optional(),
29
+ userFolders: z.array(FolderEntrySchema).optional(),
30
+ });
31
+ /**
32
+ * Resolve a caller's folder (an OFW id or a folder name) against OFW's live
33
+ * folder list. One request. An id or name that matches nothing is UNKNOWN,
34
+ * never an empty folder: OFW answers a list request for a folder that does not
35
+ * exist with an empty page, which would read as "no messages".
36
+ */
37
+ export async function resolveMessageFolder(client, arg) {
38
+ const data = parseLenient(FoldersSchema, await client.request('GET', '/pub/v1/messageFolders?includeFolderCounts=true'), { label: 'ofw-mcp', context: 'GET /pub/v1/messageFolders (ofw_list_messages folder)' });
39
+ const toFolder = (user) => (f) => f.id === undefined ? null : { id: String(f.id), name: f.name ?? null, folderType: f.folderType ?? null, user };
40
+ const all = [
41
+ ...(data?.systemFolders ?? []).map(toFolder(false)),
42
+ ...(data?.userFolders ?? []).map(toFolder(true)),
43
+ ].filter((f) => f !== null);
44
+ const wanted = arg.trim();
45
+ let matches = all.filter((f) => f.id === wanted);
46
+ if (matches.length === 0) {
47
+ const lower = wanted.toLowerCase();
48
+ matches = all.filter((f) => f.name !== null && f.name.trim().toLowerCase() === lower);
49
+ }
50
+ if (matches.length !== 1) {
51
+ return { kind: 'unknown', available: matches.length > 1 ? matches : all, ambiguous: matches.length > 1 };
52
+ }
53
+ const [folder] = matches;
54
+ if (folder.folderType === 'INBOX')
55
+ return { kind: 'cached', folder: 'inbox' };
56
+ if (folder.folderType === 'SENT_MESSAGES')
57
+ return { kind: 'cached', folder: 'sent' };
58
+ if (folder.folderType === 'DRAFTS')
59
+ return { kind: 'drafts' };
60
+ return { kind: 'live', folder };
61
+ }
62
+ const ListItemSchema = z.looseObject({
63
+ id: z.number(),
64
+ subject: z.string(),
65
+ date: z.looseObject({ dateTime: z.string() }).optional(),
66
+ recipients: z.array(ApiRecipientSchema).optional(),
67
+ });
68
+ const ListResponseSchema = z.looseObject({ data: z.array(ListItemSchema).optional() });
69
+ function asRecord(value) {
70
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : null;
71
+ }
72
+ function nameOf(value) {
73
+ const name = asRecord(value)?.name;
74
+ return typeof name === 'string' && name !== '' ? name : null;
75
+ }
76
+ /**
77
+ * Fetch ONE list page of a folder, newest (or oldest) first. One request, no
78
+ * detail GETs: the list carries no body, so nothing is marked read.
79
+ */
80
+ export async function fetchFolderPage(client, folder, opts) {
81
+ const direction = opts.sort === 'oldest' ? 'asc' : 'desc';
82
+ const raw = await client.request('GET', `/pub/v3/messages?folders=${encodeURIComponent(folder.id)}&page=${opts.page}&size=${opts.size}&sort=date&sortDirection=${direction}`);
83
+ // Lenient: a mismatch warns on stderr and the raw payload flows on, so each
84
+ // item is read defensively below rather than trusted to the schema.
85
+ parseLenient(ListResponseSchema, raw, { label: 'ofw-mcp', context: 'GET /pub/v3/messages?folders={folder}' });
86
+ const items = asRecord(raw)?.data ?? [];
87
+ const upstream = readUpstreamPaging(raw);
88
+ const messages = [];
89
+ for (const entry of items) {
90
+ const it = asRecord(entry);
91
+ if (it === null || typeof it.id !== 'number')
92
+ continue;
93
+ const files = it.files;
94
+ const dateTime = asRecord(it.date)?.dateTime;
95
+ const message = pruneUndefined({
96
+ id: it.id,
97
+ folderId: folder.id,
98
+ folderName: folder.name,
99
+ subject: typeof it.subject === 'string' ? it.subject : '',
100
+ from: nameOf(it.author) ?? nameOf(it.from),
101
+ sentAt: typeof dateTime === 'string' ? dateTime : null,
102
+ recipients: mapRecipients(Array.isArray(it.recipients) ? it.recipients : [], { source: 'list', checkedAt: opts.checkedAt }),
103
+ read: typeof it.read === 'boolean' ? it.read : null,
104
+ replied: typeof it.replied === 'boolean' ? it.replied : undefined,
105
+ files: typeof files === 'number' ? files : Array.isArray(files) ? files.length : undefined,
106
+ });
107
+ if (opts.full) {
108
+ const { preview: _preview, body: _body, ...listData } = it;
109
+ message.listData = listData;
110
+ }
111
+ messages.push(message);
112
+ }
113
+ const { hasMore } = offsetState({
114
+ start: (opts.page - 1) * opts.size,
115
+ max: opts.size,
116
+ returned: items.length,
117
+ total: upstream.total,
118
+ last: upstream.last,
119
+ base: 0,
120
+ });
121
+ return {
122
+ messages,
123
+ returned: messages.length,
124
+ skipped: items.length - messages.length,
125
+ total: upstream.total,
126
+ hasMore,
127
+ nextPage: hasMore ? opts.page + 1 : null,
128
+ };
129
+ }
130
+ /** One folder message as a brief line: `<sender>: <subject> — <sent> — read|unread`. */
131
+ export function folderMessageBrief(m, tz) {
132
+ const status = m.read === null ? 'read state unknown' : m.read ? 'read' : 'unread';
133
+ return briefLine(m.from ? `${m.from}: ${m.subject}` : m.subject, briefDate(m.sentAt, tz), status);
134
+ }
135
+ /**
136
+ * The largest page a live folder read asks OFW for: the size the sync walks
137
+ * with, so it is known to be honoured. A bigger request OFW silently capped
138
+ * would come back short and read as the last page.
139
+ */
140
+ export const LIVE_FOLDER_MAX_PAGE = 50;
141
+ const sightingKey = (id) => `folder_sighting:${id}`;
142
+ export async function recordFolderSightings(store, messages, seenAt) {
143
+ for (const m of messages) {
144
+ const sighting = {
145
+ folderId: m.folderId, folderName: m.folderName, subject: m.subject, from: m.from, sentAt: m.sentAt, read: m.read, seenAt,
146
+ };
147
+ await store.setMeta(sightingKey(m.id), JSON.stringify(sighting));
148
+ }
149
+ }
150
+ /** The recorded sighting for an id, or null — including for a record that does not parse. */
151
+ export async function getFolderSighting(store, id) {
152
+ const raw = await store.getMeta(sightingKey(id));
153
+ if (raw === null)
154
+ return null;
155
+ let value;
156
+ try {
157
+ value = JSON.parse(raw);
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ const r = asRecord(value);
163
+ if (r === null || typeof r.folderId !== 'string' || typeof r.subject !== 'string')
164
+ return null;
165
+ const str = (v) => (typeof v === 'string' ? v : null);
166
+ return {
167
+ folderId: r.folderId,
168
+ folderName: str(r.folderName),
169
+ subject: r.subject,
170
+ from: str(r.from),
171
+ sentAt: str(r.sentAt),
172
+ read: typeof r.read === 'boolean' ? r.read : null,
173
+ seenAt: str(r.seenAt),
174
+ };
175
+ }
176
+ /**
177
+ * A sighting as a row the mark-read gates can judge — NEVER stored. It is
178
+ * shaped as an inbox row because that is the conservative reading: only OFW's
179
+ * explicit `read: true` counts as read (scrapeSaysRead), so a missing flag, or
180
+ * a sent message whose list flag means something else, fails closed to
181
+ * "would stamp" — a false unread costs a confirmation, a false read stamps
182
+ * the record.
183
+ */
184
+ export function sightingGateRow(id, s) {
185
+ return {
186
+ id,
187
+ folder: 'inbox',
188
+ subject: s.subject,
189
+ fromUser: s.from ?? '',
190
+ sentAt: s.sentAt ?? '(time unknown)',
191
+ recipients: [],
192
+ body: null,
193
+ fetchedBodyAt: null,
194
+ replyToId: null,
195
+ chainRootId: null,
196
+ listData: { read: s.read === true, sightedInFolder: s.folderName ?? s.folderId },
197
+ };
198
+ }