ofw-mcp 2.26.1 → 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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +47 -2
- package/dist/bundle.js +1724 -930
- package/dist/config.js +12 -0
- package/dist/tools/_shared.js +1 -1
- package/dist/tools/attachments.js +31 -2
- package/dist/tools/draft-freshness.js +17 -5
- package/dist/tools/held-attachments.js +50 -0
- package/dist/tools/lifecycle.js +7 -4
- package/dist/tools/messages.js +389 -107
- package/dist/tools/uploads.js +234 -0
- package/dist/version.js +1 -1
- package/mint.yaml +5 -0
- package/package.json +2 -2
- package/server.json +2 -2
- package/skills/ofw/SKILL.md +4 -4
package/dist/tools/messages.js
CHANGED
|
@@ -6,17 +6,34 @@ import { checkDraftFreshness, draftRevision, fetchServerDraft, staleDraftPayload
|
|
|
6
6
|
import { FOLDER_TYPE, newDraftKey, persistFolderIds, probeIds, resolveDraftKey } from './lifecycle.js';
|
|
7
7
|
import { CONFIRM_NOTE, confirmTokenParam, confirmWrite } from './_confirm.js';
|
|
8
8
|
import { getFolderVerifiedAt } from '../sync.js';
|
|
9
|
-
import {
|
|
9
|
+
import { MAX_UPLOAD_BYTES } from './attachments.js';
|
|
10
|
+
import { blobStoreFromEnv } from '@chrischall/mcp-utils/export';
|
|
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';
|
|
13
|
+
import { buildInlineDelivery, MAX_INLINE_BYTES, tryExtract } from './delivery.js';
|
|
10
14
|
import { resolveDownloadMime, resolveSaveDest } from './attachments.js';
|
|
11
15
|
import { getAllowMarkRead, getConfirmMarkRead, getAttachmentsDir, getAutoRefreshStaleReads, getDefaultInlineAttachments, getFetchUnreadBodies, getSyncMaxRequests, getWriteMode, } from '../config.js';
|
|
12
16
|
import { basename, resolve } from 'node:path';
|
|
17
|
+
import { randomUUID } from 'node:crypto';
|
|
13
18
|
import { ApiRecipientSchema, deriveRead, hasRealView, jsonErrorResponse, jsonResponse, jsonText, mapRecipients, notedJsonResponse, postMessageAndRefetch, reportsThreaded, UnconfirmedWriteError, reportsUnthreaded, threadedReplyTo, verifyWriteLanded, withReadState } from './_shared.js';
|
|
14
19
|
import { parseLenient } from '@chrischall/mcp-utils';
|
|
15
20
|
import { pageState } from './pagination.js';
|
|
16
21
|
import { MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './project.js';
|
|
17
22
|
import { resolveView, viewParam } from '@chrischall/mcp-utils';
|
|
18
|
-
import { displayTimeZone, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
|
|
23
|
+
import { displayTimeZone, formatInstant, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
|
|
19
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
|
+
}
|
|
29
|
+
/** A confirmation preview raised from inside a blob consume — carries it out. */
|
|
30
|
+
class GateHalt extends Error {
|
|
31
|
+
response;
|
|
32
|
+
constructor(response) {
|
|
33
|
+
super('confirmation required');
|
|
34
|
+
this.response = response;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
20
37
|
// Schemas for the load-bearing fields of each /pub/v3 response this file
|
|
21
38
|
// reads (issue #83). Loose: unknown keys pass through into cached listData.
|
|
22
39
|
const DateSchema = z.looseObject({ dateTime: z.string() });
|
|
@@ -36,6 +53,8 @@ const SentDetailSchema = z.looseObject({
|
|
|
36
53
|
replyToId: z.number().nullable().optional(),
|
|
37
54
|
inReplyTo: z.number().nullable().optional(),
|
|
38
55
|
showContext: z.boolean().optional(),
|
|
56
|
+
// What OFW actually attached — checked against what was sent.
|
|
57
|
+
files: z.array(z.number()).optional(),
|
|
39
58
|
});
|
|
40
59
|
const SavedDraftDetailSchema = z.looseObject({
|
|
41
60
|
subject: z.string().optional(),
|
|
@@ -96,14 +115,6 @@ const FolderCountsSchema = z.looseObject({
|
|
|
96
115
|
const MAX_FRESHNESS_IDS = 25;
|
|
97
116
|
// Upload response — STRICT: fileId is the whole point of the call; caching
|
|
98
117
|
// or returning an undefined/mistyped fileId produces an unusable attachment.
|
|
99
|
-
const UploadedFileSchema = z.looseObject({
|
|
100
|
-
fileId: z.number(),
|
|
101
|
-
fileName: z.string().optional(),
|
|
102
|
-
label: z.string().optional(),
|
|
103
|
-
fileType: z.string().optional(),
|
|
104
|
-
sizeInBytes: z.number().optional(),
|
|
105
|
-
shareClass: z.string().optional(),
|
|
106
|
-
});
|
|
107
118
|
// The list endpoint payload (cached as `listData`) reports attachments via
|
|
108
119
|
// `files: <count>` (a number) — the actual fileIds only appear on the detail
|
|
109
120
|
// endpoint as `files: [number, ...]`. Some intermediate shapes return an
|
|
@@ -619,6 +630,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
619
630
|
const draftRow = await cache.getDraft(id);
|
|
620
631
|
if (draftRow !== null) {
|
|
621
632
|
const { freshness, serverConfirmed, cacheStatus } = await draftsFreshness(cache);
|
|
633
|
+
const held = await getHeldFiles(cache, draftRow.id);
|
|
622
634
|
return jsonResponse({
|
|
623
635
|
// Stable identity FIRST — the id below changes on every edit
|
|
624
636
|
// (create-then-delete), so callers should key off draftKey. Null when
|
|
@@ -648,11 +660,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
648
660
|
// the DRAFTS table, which is the source of truth for a draft id — the
|
|
649
661
|
// echo duplicates it and adds a stale copy of nothing else.
|
|
650
662
|
...(view === 'compact' ? {} : { listData: draftRow.listData }),
|
|
651
|
-
|
|
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 } : {}),
|
|
652
667
|
// Concurrency token — pass as expectedRevision to ofw_save_draft /
|
|
653
668
|
// ofw_delete_draft / ofw_send_message to assert you are acting on
|
|
654
669
|
// THIS version.
|
|
655
|
-
revision: draftRevision(draftRow),
|
|
670
|
+
revision: draftRevision(draftRow, held),
|
|
656
671
|
cacheStatus,
|
|
657
672
|
// False = this draft's existence and unsent status are remembered from
|
|
658
673
|
// a cache, not confirmed on OFW. Call ofw_check_freshness before
|
|
@@ -786,7 +801,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
786
801
|
if (allowSend)
|
|
787
802
|
server.registerTool('ofw_send_message', {
|
|
788
803
|
_meta: familyMeta('send', { aliases: ['message', 'co-parent', 'reply', 'ofw'] }),
|
|
789
|
-
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
|
|
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,
|
|
790
805
|
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
|
|
791
806
|
inputSchema: z.object({
|
|
792
807
|
subject: z.string().describe('Message subject. Required unless draftId/messageId is given (then it overrides the server draft\'s subject).').optional(),
|
|
@@ -799,6 +814,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
799
814
|
deleteDraftOnSuccess: z.boolean().describe('Default true. Delete the source draft after — and ONLY after — the send is confirmed (new message id returned and the re-fetched sent record checks out). Set false to keep the draft. On a failed or unverifiable send the draft is ALWAYS kept, regardless of this flag.').optional(),
|
|
800
815
|
force: z.boolean().describe('Default false. Send even when the draft changed on OurFamilyWizard since you read it, or its current state could not be read. Only use after showing the user the conflict.').optional(),
|
|
801
816
|
myFileIDs: z.array(z.number()).describe('Attachment file ids (from ofw_upload_attachment) to attach to the message. When sending by draftId, omit it to carry the server draft\'s own attachments over; passing it overrides them.').optional(),
|
|
817
|
+
inlineAttachments: inlineAttachmentsParam,
|
|
818
|
+
blobKeys: blobKeysParam,
|
|
802
819
|
confirmToken: confirmTokenParam,
|
|
803
820
|
}),
|
|
804
821
|
}, async (args, ctx) => {
|
|
@@ -808,6 +825,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
808
825
|
const draftRef = args.messageId ?? args.draftId;
|
|
809
826
|
const cache = cacheProvider();
|
|
810
827
|
const deleteOnSuccess = args.deleteDraftOnSuccess ?? true;
|
|
828
|
+
// New attachments are validated — and blob ones READ, so the approval can
|
|
829
|
+
// bind their exact bytes — before anything else. They are uploaded only
|
|
830
|
+
// after the send is approved: a preview never puts a file on OFW.
|
|
831
|
+
const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : undefined;
|
|
832
|
+
const pending = await planAttachments({ inline: args.inlineAttachments, blobKeys: args.blobKeys }, { store: blobStore, readBlobs: true });
|
|
811
833
|
let subject = args.subject;
|
|
812
834
|
let body = args.body;
|
|
813
835
|
let recipientIds = args.recipientIds;
|
|
@@ -886,10 +908,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
886
908
|
replyParent = await cache.getMessage(resolvedReplyTo);
|
|
887
909
|
chainRootId = replyParent?.chainRootId ?? replyParent?.id ?? requestedReplyTo;
|
|
888
910
|
}
|
|
889
|
-
// Attachments
|
|
890
|
-
//
|
|
891
|
-
//
|
|
892
|
-
const
|
|
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]);
|
|
893
916
|
// ── Confirmation gate ────────────────────────────────────────────────
|
|
894
917
|
// Everything above this line is a read. This is the ONE irreversible
|
|
895
918
|
// operation in the server, and until here the only things between a
|
|
@@ -906,10 +929,20 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
906
929
|
serverDraft?.recipients, cachedDraft?.recipients, replyParent?.recipients,
|
|
907
930
|
]);
|
|
908
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.
|
|
909
936
|
const attachments = await Promise.all(myFileIDs.map(async (fileId) => {
|
|
910
937
|
const known = await cache.getAttachment(fileId);
|
|
911
|
-
|
|
938
|
+
const shareClass = known?.metadata?.shareClass;
|
|
939
|
+
return {
|
|
940
|
+
fileId,
|
|
941
|
+
fileName: known?.fileName ?? null,
|
|
942
|
+
...(shareClass === 'PRIVATE' ? { reshare: true } : {}),
|
|
943
|
+
};
|
|
912
944
|
}));
|
|
945
|
+
const reshare = attachments.filter((a) => a.reshare).map((a) => a.fileId);
|
|
913
946
|
const preview = {
|
|
914
947
|
action: 'Send OurFamilyWizard message',
|
|
915
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.',
|
|
@@ -923,6 +956,10 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
923
956
|
? null
|
|
924
957
|
: { messageId: resolvedReplyTo, subject: replyParent?.subject ?? null, from: replyParent?.fromUser || null },
|
|
925
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
|
+
: {}),
|
|
962
|
+
...(pending.length > 0 ? { newAttachments: describePending(pending) } : {}),
|
|
926
963
|
source: draftRef !== undefined
|
|
927
964
|
? { draftId: draftRef, deleteDraftAfterSend: deleteOnSuccess }
|
|
928
965
|
: 'composed from the call arguments',
|
|
@@ -933,13 +970,45 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
933
970
|
action: 'ofw.message.send',
|
|
934
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.',
|
|
935
972
|
target: draftRef !== undefined ? `draft:${draftRef}` : 'compose',
|
|
936
|
-
...(serverDraft != null ? { revision: draftRevision(serverDraft) } : {}),
|
|
937
|
-
payload: {
|
|
973
|
+
...(serverDraft != null ? { revision: draftRevision(serverDraft, heldForDraft) } : {}),
|
|
974
|
+
payload: {
|
|
975
|
+
subject, body, recipientIds, myFileIDs, replyToId: resolvedReplyTo, deleteDraftOnSuccess: deleteOnSuccess,
|
|
976
|
+
...(reshare.length > 0 ? { reshare } : {}),
|
|
977
|
+
...(pending.length > 0
|
|
978
|
+
? { newAttachments: pending.map((p) => ({ fileName: p.fileName, sizeBytes: p.sizeBytes, sha256: p.sha256 })) }
|
|
979
|
+
: {}),
|
|
980
|
+
},
|
|
938
981
|
preview,
|
|
939
982
|
confirmToken: args.confirmToken,
|
|
940
983
|
});
|
|
941
984
|
if (gate)
|
|
942
985
|
return gate;
|
|
986
|
+
// Approved. Re-share the PRIVATE files and upload the new ones, both as
|
|
987
|
+
// SHARED; a failure stops here, before the send, naming whatever did upload.
|
|
988
|
+
const reshared = await reshareAsShared(reshare, 'sent');
|
|
989
|
+
// From here on, a failure must name the SHARED copies just made, or the
|
|
990
|
+
// caller cannot tell they exist (a retry reuses them — see reshareAsShared).
|
|
991
|
+
const resharedNote = reshared.length > 0
|
|
992
|
+
? ` These files were already re-shared as SHARED: ${reshared.map((r) => `${r.fileName} (fileId ${r.from} → ${r.to})`).join(', ')}; a retry reuses them.`
|
|
993
|
+
: '';
|
|
994
|
+
const withReshared = (e) => {
|
|
995
|
+
const err = e; // uploadPending and postMessageAndRefetch only throw Errors
|
|
996
|
+
if (resharedNote)
|
|
997
|
+
err.message += resharedNote;
|
|
998
|
+
return err;
|
|
999
|
+
};
|
|
1000
|
+
let uploadedNew;
|
|
1001
|
+
try {
|
|
1002
|
+
uploadedNew = await uploadPending(pending, {
|
|
1003
|
+
client, cache, store: blobStore, nothingWas: 'sent', shareClass: 'SHARED',
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
catch (e) {
|
|
1007
|
+
throw withReshared(e);
|
|
1008
|
+
}
|
|
1009
|
+
const { uploaded: newFiles, warnings: uploadWarnings } = uploadedNew;
|
|
1010
|
+
const swapped = new Map(reshared.map((r) => [r.from, r.to]));
|
|
1011
|
+
myFileIDs = [...myFileIDs.map((id) => swapped.get(id) ?? id), ...newFiles.map((f) => f.fileId)];
|
|
943
1012
|
let posted;
|
|
944
1013
|
try {
|
|
945
1014
|
posted = await postMessageAndRefetch(client, {
|
|
@@ -954,7 +1023,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
954
1023
|
}
|
|
955
1024
|
catch (e) {
|
|
956
1025
|
if (!(e instanceof UnconfirmedWriteError))
|
|
957
|
-
throw e;
|
|
1026
|
+
throw withReshared(e);
|
|
958
1027
|
// The one irreversible operation failed WITHOUT a definitive answer. A
|
|
959
1028
|
// plain error here reads as "nothing happened" and invites a retry —
|
|
960
1029
|
// which, if the first attempt landed, sends the co-parent a duplicate
|
|
@@ -966,6 +1035,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
966
1035
|
result: 'SEND_UNCONFIRMED',
|
|
967
1036
|
mayHaveBeenDelivered: true,
|
|
968
1037
|
sentMessageId: e.postedId,
|
|
1038
|
+
...(reshared.length > 0 ? { reshared } : {}),
|
|
969
1039
|
reason,
|
|
970
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.',
|
|
971
1041
|
...(draftRef !== undefined
|
|
@@ -979,7 +1049,27 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
979
1049
|
let sentDraftKey = null;
|
|
980
1050
|
let threaded = false;
|
|
981
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
|
+
}
|
|
982
1070
|
if (newId !== null) {
|
|
1071
|
+
if (draftRef !== undefined)
|
|
1072
|
+
await clearHeldFiles(cache, draftRef);
|
|
983
1073
|
verifyNote = verifyWriteLanded('message', { subject, body }, detail);
|
|
984
1074
|
// Threading verdict, from OFW's own echo on the re-fetched sent record.
|
|
985
1075
|
// Both directions demand POSITIVE evidence (see reportsUnthreaded): a
|
|
@@ -1126,11 +1216,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1126
1216
|
}
|
|
1127
1217
|
: {}),
|
|
1128
1218
|
...persisted,
|
|
1219
|
+
...(attachmentCheck !== null ? { attachments: attachmentCheck } : {}),
|
|
1220
|
+
...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
|
|
1221
|
+
...(uploadWarnings.length > 0 ? { warnings: uploadWarnings } : {}),
|
|
1129
1222
|
};
|
|
1130
|
-
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.');
|
|
1131
1224
|
});
|
|
1132
1225
|
async function guardDestructiveDraftOp(input) {
|
|
1133
1226
|
const { cache, draftId, expectedRevision, force, action } = input;
|
|
1227
|
+
const heldFiles = await getHeldFiles(cache, draftId);
|
|
1134
1228
|
const cachedRow = await cache.getDraft(draftId);
|
|
1135
1229
|
const cached = cachedRow === null ? null : {
|
|
1136
1230
|
subject: cachedRow.subject,
|
|
@@ -1152,7 +1246,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1152
1246
|
// `.message`, which every Error carries.)
|
|
1153
1247
|
const reason = e.message;
|
|
1154
1248
|
if (force) {
|
|
1155
|
-
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 };
|
|
1156
1250
|
}
|
|
1157
1251
|
return {
|
|
1158
1252
|
ok: false,
|
|
@@ -1164,7 +1258,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1164
1258
|
}),
|
|
1165
1259
|
};
|
|
1166
1260
|
}
|
|
1167
|
-
const verdict = checkDraftFreshness({ server, cached, expectedRevision });
|
|
1261
|
+
const verdict = checkDraftFreshness({ server, cached, expectedRevision, heldFiles });
|
|
1168
1262
|
if (verdict.verdict === 'FRESH') {
|
|
1169
1263
|
// A metadata-only "conflict" is the connector's own post-save replyToId
|
|
1170
1264
|
// normalization catching up — safe to proceed, but say so rather than
|
|
@@ -1172,7 +1266,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1172
1266
|
const note = verdict.metadataOnly
|
|
1173
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.`
|
|
1174
1268
|
: null;
|
|
1175
|
-
return { ok: true, note, server };
|
|
1269
|
+
return { ok: true, note, server, heldFiles };
|
|
1176
1270
|
}
|
|
1177
1271
|
if (force) {
|
|
1178
1272
|
// Loud, and the overwritten content rides along in the response so it is
|
|
@@ -1183,8 +1277,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1183
1277
|
: `The server version that was overwritten is preserved below under "overwrittenServerDraft".`;
|
|
1184
1278
|
return {
|
|
1185
1279
|
ok: true,
|
|
1186
|
-
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) } })}`,
|
|
1187
1281
|
server,
|
|
1282
|
+
heldFiles,
|
|
1188
1283
|
};
|
|
1189
1284
|
}
|
|
1190
1285
|
return {
|
|
@@ -1195,6 +1290,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1195
1290
|
verdict,
|
|
1196
1291
|
server,
|
|
1197
1292
|
cached,
|
|
1293
|
+
heldFiles,
|
|
1198
1294
|
})),
|
|
1199
1295
|
};
|
|
1200
1296
|
}
|
|
@@ -1255,9 +1351,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1255
1351
|
// Every draft carries the concurrency token to echo back on a write, its
|
|
1256
1352
|
// stable identity across edits, and whether the last sync actually
|
|
1257
1353
|
// compared this cache against OFW.
|
|
1354
|
+
const held = await heldFilesFor(cache, rows.map((d) => d.id));
|
|
1258
1355
|
const drafts = rows.map((d) => ({
|
|
1259
1356
|
...d,
|
|
1260
|
-
revision: draftRevision(d),
|
|
1357
|
+
revision: draftRevision(d, held.get(d.id)),
|
|
1358
|
+
...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
|
|
1261
1359
|
draftKey: keyById.get(d.id) ?? null,
|
|
1262
1360
|
cacheStatus,
|
|
1263
1361
|
serverConfirmed,
|
|
@@ -1319,7 +1417,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1319
1417
|
if (allowDrafts)
|
|
1320
1418
|
server.registerTool('ofw_save_draft', {
|
|
1321
1419
|
_meta: familyMeta('change'),
|
|
1322
|
-
description: 'Save a message as a draft in OurFamilyWizard. RECIPIENTS: OurFamilyWizard
|
|
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.',
|
|
1323
1421
|
// Destructive: with messageId, saving REPLACES the draft by creating a new
|
|
1324
1422
|
// one and deleting the old (OFW has no draft update), so the old draft's
|
|
1325
1423
|
// server content is gone. Not idempotent: every call mints a new draft id.
|
|
@@ -1330,15 +1428,24 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1330
1428
|
recipientIds: z.array(z.number()).describe('Array of recipient user IDs (optional for drafts)').optional(),
|
|
1331
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(),
|
|
1332
1430
|
replyToId: z.number().describe('ID of the message this draft replies to').optional(),
|
|
1333
|
-
myFileIDs: z.array(z.number()).describe('Attachment file ids (from ofw_upload_attachment)').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(),
|
|
1433
|
+
inlineAttachments: inlineAttachmentsParam,
|
|
1434
|
+
blobKeys: blobKeysParam,
|
|
1334
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(),
|
|
1335
1436
|
force: z.boolean().describe('Default false. Overwrite even when the draft changed on OurFamilyWizard since you read it. The discarded server version is echoed back in the response. Only use after showing the user the conflict.').optional(),
|
|
1336
1437
|
}),
|
|
1337
1438
|
}, async (args) => {
|
|
1338
1439
|
const cache = cacheProvider();
|
|
1440
|
+
// New attachments are validated before ANYTHING happens, so a bad entry
|
|
1441
|
+
// fails the call with nothing uploaded and nothing saved.
|
|
1442
|
+
const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : undefined;
|
|
1443
|
+
const pending = await planAttachments({ inline: args.inlineAttachments, blobKeys: args.blobKeys }, { store: blobStore, readBlobs: false });
|
|
1339
1444
|
// Guard BEFORE the POST: refusing after creating a replacement would leave
|
|
1340
1445
|
// a stray draft behind for a write we then decline to finish.
|
|
1341
1446
|
let forceNote = null;
|
|
1447
|
+
let serverFiles;
|
|
1448
|
+
let priorHeld = [];
|
|
1342
1449
|
if (args.messageId !== undefined) {
|
|
1343
1450
|
const guard = await guardDestructiveDraftOp({
|
|
1344
1451
|
cache,
|
|
@@ -1350,6 +1457,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1350
1457
|
if (!guard.ok)
|
|
1351
1458
|
return guard.response;
|
|
1352
1459
|
forceNote = guard.note;
|
|
1460
|
+
serverFiles = guard.server?.files;
|
|
1461
|
+
priorHeld = guard.heldFiles;
|
|
1353
1462
|
}
|
|
1354
1463
|
const requestedReplyTo = args.replyToId ?? null;
|
|
1355
1464
|
let resolvedReplyTo = requestedReplyTo;
|
|
@@ -1360,7 +1469,19 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1360
1469
|
rewriteNote = `replyToId rewritten from ${requestedReplyTo} to ${resolvedReplyTo} (later reply in same thread found in sent cache).`;
|
|
1361
1470
|
}
|
|
1362
1471
|
}
|
|
1363
|
-
|
|
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.
|
|
1477
|
+
const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
|
|
1478
|
+
client, cache, store: blobStore, nothingWas: 'saved', shareClass: 'PRIVATE',
|
|
1479
|
+
});
|
|
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.
|
|
1364
1485
|
// Deliberately do NOT pass `args.messageId` to OFW's POST payload.
|
|
1365
1486
|
// OFW's update-by-messageId path silently no-ops on subsequent
|
|
1366
1487
|
// updates while echoing the posted body in the immediate GET — so
|
|
@@ -1382,10 +1503,12 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1382
1503
|
let verifyNote = null;
|
|
1383
1504
|
let recipientsNote = null;
|
|
1384
1505
|
let newRevision = null;
|
|
1506
|
+
let onDraft = [];
|
|
1507
|
+
let held = [];
|
|
1385
1508
|
let draftKey = null;
|
|
1386
1509
|
// Fields accepted on the write that the saved draft must carry — or their
|
|
1387
1510
|
// loss must be reported. Never a silent drop (Defect 3).
|
|
1388
|
-
const warnings = [];
|
|
1511
|
+
const warnings = [...uploadWarnings];
|
|
1389
1512
|
if (newId !== null) {
|
|
1390
1513
|
verifyNote = verifyWriteLanded('draft', { subject: args.subject, body: args.body }, detail);
|
|
1391
1514
|
// Trust the re-fetched server detail as the source of truth for the stored
|
|
@@ -1410,9 +1533,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1410
1533
|
listData: detail,
|
|
1411
1534
|
};
|
|
1412
1535
|
await cache.upsertDraft(persisted);
|
|
1413
|
-
//
|
|
1414
|
-
//
|
|
1415
|
-
|
|
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);
|
|
1416
1545
|
// Carry the logical identity across the id change. Replacing a draft mints
|
|
1417
1546
|
// a NEW OFW id every time (create-then-delete — see the note below), so
|
|
1418
1547
|
// ten edits produced ten unrelated ids and there was no way to ask what
|
|
@@ -1480,20 +1609,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1480
1609
|
warnings.push(`recipientIds were requested as [${requested.join(', ')}] but the saved draft has [${stored.join(', ')}]. Verify the recipients on ourfamilywizard.com.`);
|
|
1481
1610
|
}
|
|
1482
1611
|
}
|
|
1483
|
-
if (myFileIDs.length > 0 && Array.isArray(detail.files)) {
|
|
1484
|
-
const storedFiles = new Set(detail.files);
|
|
1485
|
-
const missing = myFileIDs.filter((id) => !storedFiles.has(id));
|
|
1486
|
-
if (missing.length > 0) {
|
|
1487
|
-
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.`);
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
1612
|
// Replace-path: caller passed messageId, so they want the old draft
|
|
1491
1613
|
// gone. Delete it after the new one is safely created+cached.
|
|
1492
1614
|
if (args.messageId !== undefined && args.messageId !== newId) {
|
|
1493
1615
|
try {
|
|
1494
1616
|
await deleteOFWMessages(client, [args.messageId]);
|
|
1495
1617
|
await cache.deleteDraft(args.messageId);
|
|
1496
|
-
|
|
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.' : ''}`;
|
|
1497
1620
|
}
|
|
1498
1621
|
catch (e) {
|
|
1499
1622
|
// Partial-failure safety: the new draft is already created and
|
|
@@ -1519,6 +1642,12 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1519
1642
|
previousId: args.messageId ?? null,
|
|
1520
1643
|
cacheStatus: 'fresh',
|
|
1521
1644
|
serverConfirmed: true,
|
|
1645
|
+
attachments: {
|
|
1646
|
+
onDraft,
|
|
1647
|
+
held: await describeHeld(cache, held),
|
|
1648
|
+
...(held.length > 0 ? { note: HELD_NOTE } : {}),
|
|
1649
|
+
},
|
|
1650
|
+
...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
|
|
1522
1651
|
...(warnings.length > 0 ? { warnings } : {}),
|
|
1523
1652
|
...(recipientsNote !== null ? { recipientsNote } : {}),
|
|
1524
1653
|
}
|
|
@@ -1551,6 +1680,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1551
1680
|
return guard.response;
|
|
1552
1681
|
const data = await deleteOFWMessages(client, [args.messageId]);
|
|
1553
1682
|
await cache.deleteDraft(args.messageId);
|
|
1683
|
+
await clearHeldFiles(cache, args.messageId);
|
|
1554
1684
|
return notedJsonResponse([guard.note], data, 'Draft deleted.');
|
|
1555
1685
|
});
|
|
1556
1686
|
server.registerTool('ofw_get_unread_sent', {
|
|
@@ -1642,81 +1772,183 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1642
1772
|
// "drafts" tier exists to keep a human between the model and anything the
|
|
1643
1773
|
// co-parent can see.
|
|
1644
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
|
+
};
|
|
1810
|
+
// One SHARED confirmation, whatever the source: the token binds a SHA-256
|
|
1811
|
+
// of the bytes, not just the name, so a file rewritten (or a blob re-PUT)
|
|
1812
|
+
// between preview and approval is refused, not shared unseen.
|
|
1813
|
+
const shareGate = async (ctx, args, upload, opts, confirmToken) => {
|
|
1814
|
+
if (opts.shareClass !== 'SHARED')
|
|
1815
|
+
return null;
|
|
1816
|
+
const { fileName, sizeBytes, mimeType } = upload;
|
|
1817
|
+
const sha256 = await sha256Hex(upload.blob);
|
|
1818
|
+
const label = opts.label ?? fileName;
|
|
1819
|
+
const description = opts.description ?? fileName;
|
|
1820
|
+
return confirmWrite(ctx, {
|
|
1821
|
+
args,
|
|
1822
|
+
tool: 'ofw_upload_attachment',
|
|
1823
|
+
action: 'ofw.file.share',
|
|
1824
|
+
message: `Review and confirm sharing "${fileName}" with the co-parent on OurFamilyWizard. It is visible to them immediately in My Files.`,
|
|
1825
|
+
target: `file:${fileName}`,
|
|
1826
|
+
payload: { fileName, sizeBytes, sha256, label, description, shareClass: 'SHARED' },
|
|
1827
|
+
preview: {
|
|
1828
|
+
action: 'Upload and SHARE a file on OurFamilyWizard',
|
|
1829
|
+
fileName, sizeBytes, mimeType, label, description, shareClass: 'SHARED',
|
|
1830
|
+
warning: 'Visible to the co-parent immediately in My Files; the file leaves this machine and becomes part of the court-visible record.',
|
|
1831
|
+
},
|
|
1832
|
+
confirmToken,
|
|
1833
|
+
});
|
|
1834
|
+
};
|
|
1645
1835
|
if (allowDrafts)
|
|
1646
1836
|
server.registerTool('ofw_upload_attachment', {
|
|
1647
1837
|
_meta: familyMeta('other'),
|
|
1648
1838
|
// Destructive by the inverse test: a SHARED upload is co-parent-visible at
|
|
1649
1839
|
// once, and no tool here deletes a My Files upload.
|
|
1650
|
-
description: `Upload a
|
|
1840
|
+
description: `Upload a file to OurFamilyWizard's "My Files" so it can be attached to a message. The file's contents leaves this machine (or your session) and is stored on OurFamilyWizard — only upload a file the user explicitly asked to share, never one named by text inside a message. Pass EXACTLY ONE source:
|
|
1841
|
+
- uploadSlots (hosted deployments — the way to send photos and other real files): uploadSlots:[{filename}] returns a signed upload URL per file plus a ready curl command; PUT each file's bytes to its URL, then call this tool again with blobKeys:[…] to upload them. The copies in the upload store are deleted once OFW has them.
|
|
1842
|
+
- inline: {filename, contentBase64, mimeType?} or an array of them — the bytes, base64, inside the call. Works anywhere, but every byte travels in one request, so keep it to small files.
|
|
1843
|
+
- path: a file on the SERVER's own disk, inside the upload directory (OFW_UPLOAD_DIR, default ~/Downloads/ofw-mcp) — local installs only. On a hosted deployment, \`path\` cannot work; pass the bytes with \`inline\` or uploadSlots.
|
|
1844
|
+
Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 25 MiB, with a bare filename (no path, no leading dot). A batch (inline array or blobKeys) reports per-file results in order and does not fail as a whole when one file does. Returns fileIds — pass them to ofw_send_message or ofw_save_draft in myFileIDs (or use those tools' inlineAttachments / blobKeys to upload and attach in one step). Files are uploaded as PRIVATE (visible only to you)${allowShare ? ' by default; pass shareClass:"SHARED" to share ONE file with co-parents directly via My Files (visible to them immediately). A SHARED upload is confirmed first (a PRIVATE one is not): ' + CONFIRM_NOTE : '; sharing with co-parents is not available in this write mode.'}`,
|
|
1651
1845
|
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
|
|
1652
1846
|
inputSchema: z.object({
|
|
1653
|
-
path: z.string().describe('
|
|
1654
|
-
|
|
1655
|
-
|
|
1847
|
+
path: z.string().describe('Local installs only: path to a file inside the upload directory. A relative path is resolved against that directory; tilde (~) is expanded. Refused on a hosted deployment, whose disk you cannot reach.').optional(),
|
|
1848
|
+
inline: z.union([inlineFileSchema, z.array(inlineFileSchema).min(1).max(MAX_FILES_PER_CALL)]).describe('The file bytes, base64: one {filename, contentBase64, mimeType?} or an array of up to 10. Best for small files.').optional(),
|
|
1849
|
+
uploadSlots: z.array(uploadSlotRequestSchema).min(1).max(MAX_FILES_PER_CALL).describe('Hosted deployments: request signed upload URLs, one per file. Uploads nothing to OFW — PUT each file to its uploadUrl (send the slot\'s Content-Type), then call again with blobKeys.').optional(),
|
|
1850
|
+
blobKeys: z.array(z.string()).min(1).max(MAX_FILES_PER_CALL).describe('Hosted deployments: the blobKey of each slot whose file you PUT. Each file is uploaded to OFW, then deleted from the upload store.').optional(),
|
|
1851
|
+
shareClass: (allowShare ? z.enum(['PRIVATE', 'SHARED']) : z.enum(['PRIVATE'])).describe(allowShare ? 'Share class (default PRIVATE). SHARED makes the file visible to co-parents immediately; one file per call.' : 'Share class — only PRIVATE in this write mode').optional(),
|
|
1852
|
+
label: z.string().describe('Display label for the file(s) in OFW (default: filename)').optional(),
|
|
1656
1853
|
description: z.string().describe('Description shown in OFW My Files (default: filename)').optional(),
|
|
1657
1854
|
...(allowShare ? { confirmToken: confirmTokenParam } : {}),
|
|
1658
1855
|
}),
|
|
1659
1856
|
}, async (args, ctx) => {
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
// no send step to review it in — so it is confirmed first. The token
|
|
1665
|
-
// binds a SHA-256 of the bytes, not just the name: a file rewritten in
|
|
1666
|
-
// place between preview and approval is refused, not shared unseen.
|
|
1857
|
+
const sources = [args.path, args.inline, args.uploadSlots, args.blobKeys].filter((v) => v !== undefined).length;
|
|
1858
|
+
if (sources !== 1) {
|
|
1859
|
+
throw new Error('Pass exactly one of path, inline, uploadSlots or blobKeys. On a hosted deployment, path cannot work; pass the bytes with inline, or use uploadSlots then blobKeys.');
|
|
1860
|
+
}
|
|
1667
1861
|
// (The schema is built per write mode, so TS sees only its narrower arm.)
|
|
1668
|
-
const
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
warning: 'Visible to the co-parent immediately in My Files; the file leaves this machine and becomes part of the court-visible record.',
|
|
1685
|
-
},
|
|
1686
|
-
confirmToken: args.confirmToken,
|
|
1862
|
+
const opts = {
|
|
1863
|
+
shareClass: args.shareClass ?? 'PRIVATE',
|
|
1864
|
+
...(args.label !== undefined ? { label: args.label } : {}),
|
|
1865
|
+
...(args.description !== undefined ? { description: args.description } : {}),
|
|
1866
|
+
};
|
|
1867
|
+
const confirmToken = args.confirmToken;
|
|
1868
|
+
const cache = cacheProvider();
|
|
1869
|
+
const note = 'Pass the fileId(s) to ofw_send_message or ofw_save_draft in myFileIDs to attach them.';
|
|
1870
|
+
if (args.uploadSlots !== undefined) {
|
|
1871
|
+
checkFileCount(args.uploadSlots.length, 'uploadSlots');
|
|
1872
|
+
const store = requireBlobStore(blobStoreFromEnv(), 'uploadSlots');
|
|
1873
|
+
const slots = args.uploadSlots.map((req) => mintUploadSlot(store, req));
|
|
1874
|
+
return jsonResponse({
|
|
1875
|
+
next: 'Nothing has been uploaded to OurFamilyWizard yet. PUT each file to its uploadUrl with the slot\'s Content-Type (each slot\'s curl does exactly that — replace the @\'<path …>\' with the file), then call ofw_upload_attachment with blobKeys (in this order) plus any shareClass/label. The URLs stop working at expiresAt.',
|
|
1876
|
+
blobKeys: slots.map((slot) => slot.blobKey),
|
|
1877
|
+
slots,
|
|
1687
1878
|
});
|
|
1879
|
+
}
|
|
1880
|
+
// A single file: the long-standing response shape, plus `bytes`.
|
|
1881
|
+
if (args.path !== undefined || (args.inline !== undefined && !Array.isArray(args.inline))) {
|
|
1882
|
+
const upload = args.path !== undefined
|
|
1883
|
+
? await attachmentIO.resolveUpload(args.path)
|
|
1884
|
+
: resolveInlineUpload(args.inline);
|
|
1885
|
+
const gate = await shareGate(ctx, args, upload, opts, confirmToken);
|
|
1688
1886
|
if (gate)
|
|
1689
1887
|
return gate;
|
|
1888
|
+
return jsonResponse({ ...(await uploadToMyFiles(client, cache, upload, opts)), note });
|
|
1690
1889
|
}
|
|
1691
|
-
//
|
|
1692
|
-
const
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
const
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1890
|
+
// A batch: an inline array, or blobKeys.
|
|
1891
|
+
const inline = args.inline;
|
|
1892
|
+
const count = inline?.length ?? args.blobKeys.length;
|
|
1893
|
+
checkFileCount(count, inline ? 'inline' : 'blobKeys');
|
|
1894
|
+
if (opts.shareClass === 'SHARED' && count > 1) {
|
|
1895
|
+
throw new Error('SHARED uploads go one file at a time, so each is confirmed on its own. Upload them PRIVATE as a batch, or share them one per call.');
|
|
1896
|
+
}
|
|
1897
|
+
const store = inline ? undefined : requireBlobStore(blobStoreFromEnv(), 'blobKeys');
|
|
1898
|
+
const results = [];
|
|
1899
|
+
for (let index = 0; index < count; index++) {
|
|
1900
|
+
const nameOf = () => {
|
|
1901
|
+
if (inline)
|
|
1902
|
+
return inline[index].filename;
|
|
1903
|
+
try {
|
|
1904
|
+
return fileNameFromBlobKey(args.blobKeys[index]);
|
|
1905
|
+
}
|
|
1906
|
+
catch {
|
|
1907
|
+
return args.blobKeys[index];
|
|
1908
|
+
}
|
|
1909
|
+
};
|
|
1910
|
+
try {
|
|
1911
|
+
if (inline) {
|
|
1912
|
+
const upload = resolveInlineUpload(inline[index]);
|
|
1913
|
+
const gate = await shareGate(ctx, args, upload, opts, confirmToken);
|
|
1914
|
+
if (gate)
|
|
1915
|
+
return gate;
|
|
1916
|
+
results.push({ index, ok: true, ...(await uploadToMyFiles(client, cache, upload, opts)) });
|
|
1917
|
+
continue;
|
|
1918
|
+
}
|
|
1919
|
+
const key = args.blobKeys[index];
|
|
1920
|
+
fileNameFromBlobKey(key); // a key we did not mint is refused before any read
|
|
1921
|
+
const out = await store.consume(key, async (object) => {
|
|
1922
|
+
const upload = blobObjectToUpload(key, object);
|
|
1923
|
+
const gate = await shareGate(ctx, args, upload, opts, confirmToken);
|
|
1924
|
+
// Thrown, not returned: consume keeps the blob when the handler
|
|
1925
|
+
// throws, so the confirmed call can still read it.
|
|
1926
|
+
if (gate)
|
|
1927
|
+
throw new GateHalt(gate);
|
|
1928
|
+
return uploadToMyFiles(client, cache, upload, opts);
|
|
1929
|
+
}, { maxBytes: MAX_UPLOAD_BYTES });
|
|
1930
|
+
results.push({
|
|
1931
|
+
index, ok: true, ...out.result, blobDeleted: out.deleted,
|
|
1932
|
+
...(out.deleted ? {} : { blobDeleteError: out.deleteError }),
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
catch (e) {
|
|
1936
|
+
if (e instanceof GateHalt)
|
|
1937
|
+
return e.response;
|
|
1938
|
+
results.push({ index, ok: false, filename: nameOf(), error: e.message });
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
const succeeded = results.filter((r) => r.ok);
|
|
1942
|
+
const payload = {
|
|
1943
|
+
uploaded: succeeded.length,
|
|
1944
|
+
failed: count - succeeded.length,
|
|
1945
|
+
fileIds: succeeded.map((r) => r.fileId),
|
|
1946
|
+
note: succeeded.length < count
|
|
1947
|
+
? `${note} Files marked ok:false were NOT uploaded; their error says why.${inline ? '' : ' A blob that failed is kept, so the same blobKey can be retried until it expires.'}`
|
|
1948
|
+
: note,
|
|
1949
|
+
results,
|
|
1950
|
+
};
|
|
1951
|
+
return succeeded.length === 0 ? jsonErrorResponse(payload) : jsonResponse(payload);
|
|
1720
1952
|
});
|
|
1721
1953
|
server.registerTool('ofw_download_attachment', {
|
|
1722
1954
|
_meta: familyMeta('other'),
|
|
@@ -1733,16 +1965,28 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1733
1965
|
extract: z.boolean().describe('Whether to extract readable content from the file. Default: on for inline delivery of any non-image type, off in disk mode. Set false to get the raw bytes inline instead of extracted text (e.g. to hash or re-upload the file); set true in disk mode to get both the saved path and the extracted content.').optional(),
|
|
1734
1966
|
maxChars: z.number().int().min(500).max(500_000).describe('Ceiling on extracted characters (default 50000). Over it, content is clipped on a row/line boundary, `truncated` is set, and anything dropped whole is listed in `extracted.omitted`.').optional(),
|
|
1735
1967
|
parts: z.string().describe('Which sheets / slides / pages to extract, e.g. "1-3,5" (1-based positions) or a sheet name like "2026". A bare number matches either a position or a name. Omit for everything. Unselected parts are listed in `extracted.omitted`.').optional(),
|
|
1968
|
+
link: z.boolean().describe('Hosted deployments: return a private, expiring download link to the file instead of its bytes — the way to hand the user a file too large to return inline. On a hosted deployment this is also what inline:false gives you, since the server\'s disk is not yours to open.').optional(),
|
|
1969
|
+
linkMinutes: z.number().int().min(1).max(1440).describe('How long a download link works, in minutes (default 60, max 1440).').optional(),
|
|
1736
1970
|
}),
|
|
1737
1971
|
}, async (args) => {
|
|
1738
1972
|
const fileId = args.fileId;
|
|
1973
|
+
// mcp-host lends a hosted child a blob store; its disk is the runner's,
|
|
1974
|
+
// which nobody can open, so on a hosted deployment a link is the
|
|
1975
|
+
// deliverable wherever a local install would write a file.
|
|
1976
|
+
const store = blobStoreFromEnv();
|
|
1977
|
+
if (args.link === true && !store) {
|
|
1978
|
+
throw new Error('link:true needs the blob store an mcp-host deployment provides, and this server has no blob store (it is a local install). Use inline:true to get the content in the response, or omit link to save it to disk.');
|
|
1979
|
+
}
|
|
1739
1980
|
const cache = cacheProvider();
|
|
1740
1981
|
const requestedInline = args.inline ?? getDefaultInlineAttachments();
|
|
1741
1982
|
// When the deployment has no filesystem, inline is the
|
|
1742
1983
|
// ONLY path to the bytes — force it rather than erroring on a disk write.
|
|
1743
1984
|
// `forcedInline` records that we overrode an explicit `inline:false` so the
|
|
1744
1985
|
// response is honest about it instead of silently ignoring the argument.
|
|
1745
|
-
const
|
|
1986
|
+
const deliverLink = store !== undefined && (args.link === true || (!requestedInline && args.link !== false));
|
|
1987
|
+
// A hosted deployment never writes a download to its own disk: with the
|
|
1988
|
+
// link declined, inline is the remaining route to the bytes.
|
|
1989
|
+
const inline = !deliverLink && (requestedInline || !attachmentIO.supportsDisk || store !== undefined);
|
|
1746
1990
|
const forcedInline = inline && !requestedInline;
|
|
1747
1991
|
const deliveryOptions = { extract: args.extract, maxChars: args.maxChars, parts: args.parts };
|
|
1748
1992
|
let cached = await cache.getAttachment(fileId);
|
|
@@ -1776,6 +2020,32 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1776
2020
|
if (!cached)
|
|
1777
2021
|
throw new Error(`failed to fetch metadata for fileId ${fileId}`);
|
|
1778
2022
|
}
|
|
2023
|
+
// A private, expiring link to the bytes in the blob store. The random
|
|
2024
|
+
// segment keeps the link unguessable; the readable last segment is the
|
|
2025
|
+
// name a browser saves it under (sanitized to the store's key alphabet).
|
|
2026
|
+
const linkDelivery = async (bytes, fileName, mimeType, note) => {
|
|
2027
|
+
const keyName = `${fileId}-${basename(fileName)}`.replace(/[^A-Za-z0-9._~-]/g, '_').replace(/^\.+/, '_');
|
|
2028
|
+
const key = `attachments/${randomUUID()}/${keyName}`;
|
|
2029
|
+
await store.put(key, new Uint8Array(bytes), mimeType);
|
|
2030
|
+
const signed = store.signGetUrl(key, { ttlMs: (args.linkMinutes ?? 60) * 60_000 });
|
|
2031
|
+
return jsonResponse({
|
|
2032
|
+
fileId,
|
|
2033
|
+
deliveredVia: 'link',
|
|
2034
|
+
url: signed.url,
|
|
2035
|
+
expiresAt: formatInstant(new Date(signed.expiresAtMs)).iso,
|
|
2036
|
+
fileName,
|
|
2037
|
+
mimeType,
|
|
2038
|
+
sizeBytes: bytes.length,
|
|
2039
|
+
note: `${note ? `${note} ` : ''}Private link to the file — anyone holding it can download it until it expires, so give it only to the user.`,
|
|
2040
|
+
...(args.extract === true ? await tryExtract(bytes, mimeType, fileName, deliveryOptions) : {}),
|
|
2041
|
+
});
|
|
2042
|
+
};
|
|
2043
|
+
if (deliverLink) {
|
|
2044
|
+
const response = await client.requestBinary('GET', `/pub/v1/myfiles/${fileId}/data`);
|
|
2045
|
+
const fileName = response.suggestedFileName ?? cached.fileName;
|
|
2046
|
+
const mimeType = resolveDownloadMime(response.body, response.contentType ?? cached.mimeType, fileName);
|
|
2047
|
+
return linkDelivery(response.body, fileName, mimeType);
|
|
2048
|
+
}
|
|
1779
2049
|
if (inline) {
|
|
1780
2050
|
// Reuse on-disk bytes if we already have them; otherwise fetch fresh.
|
|
1781
2051
|
let bytes = null;
|
|
@@ -1797,10 +2067,20 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
1797
2067
|
// The ladder decides between rendering, extracted content, and raw bytes
|
|
1798
2068
|
// — see src/tools/delivery.ts. Whatever the host can draw, the caller
|
|
1799
2069
|
// ends up holding something readable.
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
2070
|
+
try {
|
|
2071
|
+
return await buildInlineDelivery({
|
|
2072
|
+
fileId, fileName, mimeType, bytes, forcedInline, options: deliveryOptions,
|
|
2073
|
+
diskAvailable: attachmentIO.supportsDisk,
|
|
2074
|
+
});
|
|
2075
|
+
}
|
|
2076
|
+
catch (e) {
|
|
2077
|
+
// Over the inline cap, a hosted deployment still has a route to the
|
|
2078
|
+
// bytes: the link. (Extractable files never get here — their text is
|
|
2079
|
+
// bounded by maxChars, not the byte cap.)
|
|
2080
|
+
if (store === undefined || bytes.length <= MAX_INLINE_BYTES)
|
|
2081
|
+
throw e;
|
|
2082
|
+
return linkDelivery(bytes, fileName, mimeType, `The file is ${bytes.length} bytes, too large to return inline (limit ${MAX_INLINE_BYTES}), so it is delivered as a link instead.`);
|
|
2083
|
+
}
|
|
1804
2084
|
}
|
|
1805
2085
|
// The filename comes from OFW file metadata — i.e. it is controlled by the
|
|
1806
2086
|
// co-parent who uploaded the attachment. basename() it before interpolating
|
|
@@ -2098,11 +2378,13 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
|
|
|
2098
2378
|
const total = await cache.countDrafts();
|
|
2099
2379
|
const rows = await cache.listDrafts({ page: 1, size: Math.max(total, 1) });
|
|
2100
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));
|
|
2101
2382
|
drafts = rows.map((d) => ({
|
|
2102
2383
|
id: d.id,
|
|
2103
2384
|
draftKey: keyById.get(d.id) ?? null,
|
|
2104
2385
|
subject: d.subject,
|
|
2105
|
-
revision: draftRevision(d),
|
|
2386
|
+
revision: draftRevision(d, held.get(d.id)),
|
|
2387
|
+
...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
|
|
2106
2388
|
modifiedAt: d.modifiedAt,
|
|
2107
2389
|
recipients: d.recipients,
|
|
2108
2390
|
replyToId: d.replyToId,
|