@mosadd/mcp 3.0.0-alpha.4 → 3.0.0-alpha.40

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +298 -0
  2. package/README.md +70 -36
  3. package/dist/bin/mcp.js +42 -3
  4. package/dist/chunk-7ZAAJ52G.js +3475 -0
  5. package/dist/index.d.ts +115 -6
  6. package/dist/index.js +7 -3
  7. package/package.json +8 -5
  8. package/src/__tests__/golden-path.test.ts +139 -137
  9. package/src/__tests__/integration.test.ts +179 -178
  10. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  11. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  12. package/src/__tests__/mtalk.test.ts +122 -122
  13. package/src/__tests__/presence.test.ts +178 -0
  14. package/src/__tests__/server.test.ts +71 -67
  15. package/src/__tests__/tool-count-consistency.test.ts +164 -0
  16. package/src/bin/login.ts +138 -138
  17. package/src/bin/mcp.ts +145 -97
  18. package/src/config.ts +66 -66
  19. package/src/crypto/mdm-session.ts +502 -403
  20. package/src/index.ts +19 -17
  21. package/src/observability/sentry.ts +79 -79
  22. package/src/providers/blob-upload.ts +116 -0
  23. package/src/providers/memory-voice.ts +79 -79
  24. package/src/providers/supabase-dm.ts +122 -117
  25. package/src/providers/supabase-voice.ts +91 -91
  26. package/src/providers/supabase.ts +155 -96
  27. package/src/server.ts +60 -9
  28. package/src/tools/actions.ts +166 -0
  29. package/src/tools/attachments.ts +276 -0
  30. package/src/tools/capabilities.ts +70 -68
  31. package/src/tools/embed.ts +110 -0
  32. package/src/tools/index.ts +177 -43
  33. package/src/tools/knowledge-graph.ts +186 -0
  34. package/src/tools/knowledge.ts +327 -91
  35. package/src/tools/mail-agentbox.ts +155 -0
  36. package/src/tools/mail-aliases.ts +25 -0
  37. package/src/tools/mail-provenance.ts +137 -0
  38. package/src/tools/mail.ts +403 -89
  39. package/src/tools/mcall.ts +216 -0
  40. package/src/tools/mdm-as-agent.ts +126 -0
  41. package/src/tools/mdm-voice.ts +220 -0
  42. package/src/tools/mdm.ts +494 -392
  43. package/src/tools/mirc-edge.ts +196 -0
  44. package/src/tools/mirc-members.ts +61 -20
  45. package/src/tools/mirc-messages.ts +185 -151
  46. package/src/tools/mirc.ts +104 -10
  47. package/src/tools/mroom-messages.ts +142 -142
  48. package/src/tools/mroom.ts +221 -189
  49. package/src/tools/mtalk.ts +131 -121
  50. package/src/tools/murl.ts +314 -0
  51. package/src/tools/presence.ts +333 -0
  52. package/src/tools/ptt-ingest.ts +99 -0
  53. package/src/tools/threat.ts +123 -0
  54. package/src/types.ts +121 -85
  55. package/src/version.ts +8 -0
  56. package/src/voice/floor.ts +132 -132
  57. package/dist/chunk-YDFU6S5E.js +0 -1471
package/src/tools/mdm.ts CHANGED
@@ -1,392 +1,494 @@
1
- /**
2
- * mDM — Direct Messages.
3
- *
4
- * USP: multi-thread per contact. Within one contact you can spin up multiple
5
- * threads for clarity (the way GitHub Issues handles conversations), unlike
6
- * WhatsApp/Telegram which collapse everything into a single chat.
7
- *
8
- * Phase 1 alpha: wired to the m0ssad-3 Supabase Edge Functions as a
9
- * strangler-fig step (`message-send`, `message-list`). The user supplies
10
- * their own Supabase URL + anon key + a session JWT via env vars (BYOK).
11
- *
12
- * Phase 2 will route through the hosted gateway (mcp.mosadd.com) with the
13
- * 167-event radar middleware in front, and replace the plaintext
14
- * encrypted_payload with real X3DH + Double Ratchet via @mosadd/crypto.
15
- */
16
-
17
- import { z } from "zod";
18
- import type { MosaddTool, MosaddToolContext } from "../types.js";
19
- import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supabase.js";
20
- import {
21
- encryptForPeer,
22
- decryptFromPeer,
23
- publishOwnPrekeys,
24
- isE2eeEnvelope,
25
- } from "../crypto/mdm-session.js";
26
-
27
- // ---- Constants ----
28
-
29
- const PROTOCOL_VERSION = "mosadd.chat.v1";
30
-
31
- // ---- Schemas ----
32
-
33
- const ContactRef = z
34
- .string()
35
- .min(1)
36
- .describe(
37
- "Recipient identity id (UUID). Use mDM_list_contacts first to find the right id. Future versions will accept handle/email/phone directly.",
38
- );
39
-
40
- const ThreadSuffix = z
41
- .string()
42
- .min(1)
43
- .max(120)
44
- .regex(/^[a-zA-Z0-9._-]+$/)
45
- .describe(
46
- "Optional thread label within the conversation with this contact. Defaults to the contact's main thread. mosadd USP: multiple threads per contact.",
47
- );
48
-
49
- const mDM_send_input = z.object({
50
- to: ContactRef,
51
- text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
52
- thread_label: ThreadSuffix.optional().describe(
53
- "Optional thread label. If omitted, uses the default thread for this contact.",
54
- ),
55
- reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
56
- });
57
-
58
- const mDM_list_input = z.object({
59
- contact_id: ContactRef.describe("Identity id of the contact to read messages with."),
60
- thread_label: ThreadSuffix.optional(),
61
- limit: z.number().int().min(1).max(200).default(50).optional(),
62
- cursor: z.string().optional().describe("Opaque pagination cursor from a previous response."),
63
- });
64
-
65
- const mDM_list_contacts_input = z.object({
66
- limit: z.number().int().min(1).max(500).default(100).optional(),
67
- });
68
-
69
- const mDM_respond_request_input = z.object({
70
- request_id: z.string().min(1),
71
- action: z.enum(["accept", "reject"]),
72
- });
73
-
74
- // ---- Helpers ----
75
-
76
- /**
77
- * Deterministic DM thread id from a pair of identities. Sorts lexicographically
78
- * so both peers compute the same id regardless of who sends first.
79
- *
80
- * dmThreadId("alice", "bob") === dmThreadId("bob", "alice") === "dm:alice:bob"
81
- * dmThreadId("alice", "bob", "work") === "dm:alice:bob:work"
82
- */
83
- function dmThreadId(selfId: string, otherId: string, label?: string): string {
84
- const [a, b] = [selfId, otherId].sort();
85
- return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
86
- }
87
-
88
- /**
89
- * Resolve the current user's identity row from their JWT-authed Supabase client.
90
- * Returns the identity id (NOT the auth user id — they differ).
91
- */
92
- async function resolveSelfIdentityId(): Promise<string> {
93
- const sb = getSupabase();
94
- const { data: u, error: ue } = await sb.auth.getUser();
95
- if (ue || !u?.user) {
96
- throw new Error(
97
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
98
- );
99
- }
100
- const { data: identity, error } = await sb
101
- .from("identities")
102
- .select("id")
103
- .eq("user_id", u.user.id)
104
- .maybeSingle();
105
- if (error || !identity) {
106
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
107
- }
108
- return identity.id as string;
109
- }
110
-
111
- /**
112
- * Pack message body into the encrypted_payload string the Edge Function expects.
113
- *
114
- * ALPHA: not actually encrypted — wraps plaintext in JSON + base64.
115
- * Receivers in the m0ssad-3 app understand this `mosadd.chat.v1` shape.
116
- * V0.2: replace with @mosadd/crypto Double Ratchet wrap.
117
- */
118
- function packPlaintextPayload(text: string, replyToId?: string): Uint8Array {
119
- const envelope = {
120
- v: PROTOCOL_VERSION,
121
- type: "text",
122
- text,
123
- reply_to: replyToId ?? null,
124
- sent_at: new Date().toISOString(),
125
- };
126
- // OPAQUE bytes handed to the DmProvider — the provider does not interpret
127
- // them. Today: utf8 JSON. V0.2: @mosadd/crypto Double Ratchet ciphertext.
128
- return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
129
- }
130
-
131
- function unpackPayload(payload: Uint8Array): { text: string; sent_at?: string; reply_to?: string | null } {
132
- try {
133
- const json = Buffer.from(payload).toString("utf8");
134
- const obj = JSON.parse(json);
135
- if (typeof obj?.text === "string") return obj;
136
- } catch {
137
- /* fall through */
138
- }
139
- return { text: "<ciphertext>" };
140
- }
141
-
142
- // ---- Handlers ----
143
-
144
- async function mDM_send(
145
- input: z.infer<typeof mDM_send_input>,
146
- ctx: MosaddToolContext,
147
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: true }> {
148
- // E2EE path (default). The plaintext is packed into the inner mosadd.chat.v1
149
- // envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
150
- // DmProvider moves without understanding. First contact fetches the peer's
151
- // published prekey bundle through the same provider (decision "1a").
152
- const dm = ctx.providers.dm;
153
- const selfId = await dm.selfId();
154
- const threadId = dmThreadId(selfId, input.to, input.thread_label);
155
-
156
- const inner = packPlaintextPayload(input.text, input.reply_to_id);
157
- const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
158
-
159
- ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
160
-
161
- const result = await dm.send({
162
- to: input.to,
163
- threadId,
164
- payload: sealed,
165
- replyToId: input.reply_to_id,
166
- });
167
-
168
- // Keep a LOCAL copy of our own outgoing plaintext so mDM_list can show it
169
- // back to the sender (the ratchet can't re-derive it on read). Best-effort:
170
- // only if the keystore offers the optional sent-items cache.
171
- if (ctx.providers.keys.putSentMessage) {
172
- await ctx.providers.keys.putSentMessage(result.id, inner);
173
- }
174
-
175
- return {
176
- message_id: result.id,
177
- delivered_at: result.deliveredAt,
178
- thread_id: threadId,
179
- encrypted: true,
180
- };
181
- }
182
-
183
- async function mDM_send_unencrypted(
184
- input: z.infer<typeof mDM_send_input>,
185
- ctx: MosaddToolContext,
186
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: false }> {
187
- // DEPRECATED migration path: plaintext mosadd.chat.v1 envelope, no E2EE.
188
- // Kept so peers who have not yet published prekeys can still be reached
189
- // during the migration window. Will be removed once E2EE is universal.
190
- const dm = ctx.providers.dm;
191
- const selfId = await dm.selfId();
192
- const threadId = dmThreadId(selfId, input.to, input.thread_label);
193
- const payload = packPlaintextPayload(input.text, input.reply_to_id);
194
-
195
- ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
196
- thread_id: threadId,
197
- bytes: payload.byteLength,
198
- });
199
-
200
- const result = await dm.send({
201
- to: input.to,
202
- threadId,
203
- payload,
204
- replyToId: input.reply_to_id,
205
- });
206
-
207
- return {
208
- message_id: result.id,
209
- delivered_at: result.deliveredAt,
210
- thread_id: threadId,
211
- encrypted: false,
212
- };
213
- }
214
-
215
- async function mDM_publish_keys(
216
- _input: Record<string, never>,
217
- ctx: MosaddToolContext,
218
- ): Promise<{ published: true; one_time_prekeys: number }> {
219
- // Publish the local prekey bundle so peers can start encrypted sessions with
220
- // us. Rides the same provider as messages (network row / radio announce).
221
- const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
222
- ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
223
- return { published: true, one_time_prekeys: oneTimePrekeyCount };
224
- }
225
-
226
- async function mDM_list(
227
- input: z.infer<typeof mDM_list_input>,
228
- ctx: MosaddToolContext,
229
- ): Promise<{
230
- messages: Array<{
231
- id: string;
232
- sender_identity_id: string;
233
- text: string;
234
- timestamp: string;
235
- thread_id: string;
236
- encrypted: boolean;
237
- }>;
238
- next_cursor: string | null;
239
- threads: string[];
240
- }> {
241
- const dm = ctx.providers.dm;
242
- const selfId = await dm.selfId();
243
- const threadId = dmThreadId(selfId, input.contact_id, input.thread_label);
244
-
245
- ctx.log("debug", "mDM_list via DmProvider", { thread_id: threadId });
246
-
247
- const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
248
-
249
- const messages = await Promise.all(
250
- result.messages.map(async (m) => {
251
- const base = {
252
- id: m.id,
253
- sender_identity_id: m.senderId,
254
- timestamp: m.timestamp,
255
- thread_id: m.threadId,
256
- };
257
- // Legacy plaintext envelope (deprecated path) — unpack directly.
258
- if (!isE2eeEnvelope(m.payload)) {
259
- return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
260
- }
261
- // Our own outgoing ratchet messages aren't decryptable from our own
262
- // ratchet on read. Recover the plaintext from the local sent-items cache
263
- // (this process). If absent (e.g. a different device/process), fall back
264
- // to a marker instead of failing.
265
- if (m.senderId === selfId) {
266
- const cached = await ctx.providers.keys.getSentMessage?.(m.id);
267
- if (cached) {
268
- return { ...base, text: unpackPayload(cached).text, encrypted: true };
269
- }
270
- return { ...base, text: "<encrypted · sent by you>", encrypted: true };
271
- }
272
- try {
273
- const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
274
- return { ...base, text: unpackPayload(inner).text, encrypted: true };
275
- } catch (err) {
276
- ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
277
- return { ...base, text: "<undecryptable>", encrypted: true };
278
- }
279
- }),
280
- );
281
-
282
- return {
283
- messages,
284
- next_cursor: result.nextCursor,
285
- threads: [threadId],
286
- };
287
- }
288
-
289
- async function mDM_list_contacts(
290
- input: z.infer<typeof mDM_list_contacts_input>,
291
- ctx: MosaddToolContext,
292
- ): Promise<{
293
- contacts: Array<{ identity_id: string; account_id: string | null; display_name: string | null; state: string }>;
294
- }> {
295
- readSupabaseEnv();
296
- const selfId = await resolveSelfIdentityId();
297
- const sb = getSupabase();
298
-
299
- ctx.log("debug", "mDM_list_contacts querying contacts table", { selfId });
300
-
301
- const { data, error } = await sb
302
- .from("contacts")
303
- .select("contact_identity_id, state, identities:contact_identity_id(account_id, display_name)")
304
- .eq("owner_identity_id", selfId)
305
- .limit(input.limit ?? 100);
306
-
307
- if (error) {
308
- throw new Error(`Failed to list contacts: ${error.message}`);
309
- }
310
-
311
- type Row = {
312
- contact_identity_id: string;
313
- state: string;
314
- identities?: { account_id?: string | null; display_name?: string | null } | null;
315
- };
316
- const contacts = (data as unknown as Row[]).map((r) => ({
317
- identity_id: r.contact_identity_id,
318
- account_id: r.identities?.account_id ?? null,
319
- display_name: r.identities?.display_name ?? null,
320
- state: r.state,
321
- }));
322
-
323
- return { contacts };
324
- }
325
-
326
- async function mDM_respond_request(
327
- input: z.infer<typeof mDM_respond_request_input>,
328
- ctx: MosaddToolContext,
329
- ): Promise<{ ok: true }> {
330
- readSupabaseEnv();
331
- ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
332
- await invokeFunction<{ ok: boolean }>("message-request-respond", {
333
- request_id: input.request_id,
334
- action: input.action,
335
- });
336
- return { ok: true };
337
- }
338
-
339
- const mDM_publish_keys_input = z.object({});
340
-
341
- // ---- Registration ----
342
-
343
- export const mdmTools: MosaddTool[] = [
344
- {
345
- name: "mDM_list_contacts",
346
- requires: "any",
347
- description:
348
- "List the user's mosadd contacts. Returns identity_id (use this for mDM_send / mDM_list), account handle, display name, and contact state (pending, accepted, blocked).",
349
- inputSchema: mDM_list_contacts_input,
350
- handler: mDM_list_contacts as MosaddTool["handler"],
351
- },
352
- {
353
- name: "mDM_publish_keys",
354
- requires: "any",
355
- description:
356
- "Publish your mDM prekey bundle so other people can start an end-to-end-encrypted conversation with you. Run this once after sign-in (and to replenish one-time prekeys). Rides the same transport as messages, so it works over network or off-grid radio.",
357
- inputSchema: mDM_publish_keys_input,
358
- handler: mDM_publish_keys as MosaddTool["handler"],
359
- },
360
- {
361
- name: "mDM_send",
362
- requires: "any",
363
- description:
364
- "Send an END-TO-END-ENCRYPTED direct message via mosadd mDM. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread — mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
365
- inputSchema: mDM_send_input,
366
- handler: mDM_send as MosaddTool["handler"],
367
- },
368
- {
369
- name: "mDM_send_unencrypted",
370
- requires: "any",
371
- description:
372
- "DEPRECATED migration-window fallback: send a direct message WITHOUT end-to-end encryption (plaintext envelope). Only use when the recipient has not yet published prekeys (mDM_send fails with that hint). Prefer mDM_send. Will be removed once E2EE is universal.",
373
- inputSchema: mDM_send_input,
374
- handler: mDM_send_unencrypted as MosaddTool["handler"],
375
- },
376
- {
377
- name: "mDM_list",
378
- requires: "any",
379
- description:
380
- "List recent direct messages with a specific contact. Pass contact_id as the identity_id from mDM_list_contacts. Decrypts end-to-end-encrypted messages from the contact automatically; legacy plaintext messages are shown as-is. Optionally filter to a single thread_label.",
381
- inputSchema: mDM_list_input,
382
- handler: mDM_list as MosaddTool["handler"],
383
- },
384
- {
385
- name: "mDM_respond_request",
386
- requires: "any",
387
- description:
388
- "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
389
- inputSchema: mDM_respond_request_input,
390
- handler: mDM_respond_request as MosaddTool["handler"],
391
- },
392
- ];
1
+ /**
2
+ * mDM — Direct Messages.
3
+ *
4
+ * USP: multi-thread per contact. Within one contact you can spin up multiple
5
+ * threads for clarity (the way GitHub Issues handles conversations), unlike
6
+ * WhatsApp/Telegram which collapse everything into a single chat.
7
+ *
8
+ * Phase 1 alpha: wired to the mosadd Supabase Edge Functions as a
9
+ * strangler-fig step (`message-send`, `message-list`). The user supplies
10
+ * their own Supabase URL + anon key + a session JWT via env vars (BYOK).
11
+ *
12
+ * Phase 2 will route through the hosted gateway (mcp.mosadd.com) with the
13
+ * threat-radar middleware in front, and replace the plaintext
14
+ * encrypted_payload with real X3DH + Double Ratchet via @mosadd/crypto.
15
+ */
16
+
17
+ import { z } from "zod";
18
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
19
+ import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supabase.js";
20
+ import {
21
+ encryptForPeer,
22
+ decryptFromPeer,
23
+ publishOwnPrekeys,
24
+ isE2eeEnvelope,
25
+ } from "../crypto/mdm-session.js";
26
+
27
+ // ---- Constants ----
28
+
29
+ const PROTOCOL_VERSION = "mosadd.chat.v1";
30
+
31
+ // ---- Schemas ----
32
+
33
+ const ContactRef = z
34
+ .string()
35
+ .min(1)
36
+ .describe(
37
+ "Recipient identity id (UUID). Use mDM_list_contacts first to find the right id. Future versions will accept handle/email/phone directly.",
38
+ );
39
+
40
+ const ThreadSuffix = z
41
+ .string()
42
+ .min(1)
43
+ .max(120)
44
+ .regex(/^[a-zA-Z0-9._-]+$/)
45
+ .describe(
46
+ "Optional thread label within the conversation with this contact. Defaults to the contact's main thread. mosadd USP: multiple threads per contact.",
47
+ );
48
+
49
+ const mDM_send_input = z.object({
50
+ to: ContactRef,
51
+ text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
52
+ thread_label: ThreadSuffix.optional().describe(
53
+ "Optional thread label. If omitted, uses the default thread for this contact.",
54
+ ),
55
+ reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
56
+ });
57
+
58
+ const mDM_list_input = z.object({
59
+ contact_id: ContactRef.describe("Identity id of the contact to read messages with."),
60
+ thread_label: ThreadSuffix.optional(),
61
+ limit: z.number().int().min(1).max(200).default(50).optional(),
62
+ cursor: z.string().optional().describe("Opaque pagination cursor from a previous response."),
63
+ });
64
+
65
+ const mDM_list_contacts_input = z.object({
66
+ limit: z.number().int().min(1).max(500).default(100).optional(),
67
+ });
68
+
69
+ const mDM_respond_request_input = z.object({
70
+ request_id: z.string().min(1),
71
+ action: z.enum(["accept", "reject"]),
72
+ });
73
+
74
+ // ---- Helpers ----
75
+
76
+ /**
77
+ * Deterministic DM thread id from a pair of identities. Sorts lexicographically
78
+ * so both peers compute the same id regardless of who sends first.
79
+ *
80
+ * dmThreadId("alice", "bob") === dmThreadId("bob", "alice") === "dm:alice:bob"
81
+ * dmThreadId("alice", "bob", "work") === "dm:alice:bob:work"
82
+ */
83
+ function dmThreadId(selfId: string, otherId: string, label?: string): string {
84
+ const [a, b] = [selfId, otherId].sort();
85
+ return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
86
+ }
87
+
88
+ /**
89
+ * Resolve the current user's identity row from their JWT-authed Supabase client.
90
+ * Returns the identity id (NOT the auth user id — they differ).
91
+ */
92
+ async function resolveSelfIdentityId(): Promise<string> {
93
+ const sb = getSupabase();
94
+ const { data: u, error: ue } = await sb.auth.getUser();
95
+ if (ue || !u?.user) {
96
+ throw new Error(
97
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
98
+ );
99
+ }
100
+ const { data: identity, error } = await sb
101
+ .from("identities")
102
+ .select("id")
103
+ .eq("user_id", u.user.id)
104
+ .maybeSingle();
105
+ if (error || !identity) {
106
+ throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
107
+ }
108
+ return identity.id as string;
109
+ }
110
+
111
+ /**
112
+ * Pack message body into the encrypted_payload string the Edge Function expects.
113
+ *
114
+ * ALPHA: not actually encrypted — wraps plaintext in JSON + base64.
115
+ * Receivers in the mosadd consumer app understand this `mosadd.chat.v1` shape.
116
+ * V0.2: replace with @mosadd/crypto Double Ratchet wrap.
117
+ */
118
+ function packPlaintextPayload(text: string): Uint8Array {
119
+ // Pure text bytes so the consumer app displays clean message text directly
120
+ return new Uint8Array(Buffer.from(text, "utf8"));
121
+ }
122
+
123
+ function unpackPayload(payload: Uint8Array): { text: string; sent_at?: string; reply_to?: string | null } {
124
+ try {
125
+ const raw = Buffer.from(payload).toString("utf8");
126
+ try {
127
+ const obj = JSON.parse(raw);
128
+ if (typeof obj?.text === "string") return obj;
129
+ } catch {
130
+ return { text: raw };
131
+ }
132
+ return { text: raw };
133
+ } catch {
134
+ /* fall through */
135
+ }
136
+ return { text: "<ciphertext>" };
137
+ }
138
+
139
+ // ---- Handlers ----
140
+
141
+ async function mDM_send(
142
+ input: z.infer<typeof mDM_send_input>,
143
+ ctx: MosaddToolContext,
144
+ ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: true }> {
145
+ // E2EE path (default). The plaintext is packed into the inner mosadd.chat.v1
146
+ // envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
147
+ // DmProvider moves without understanding. First contact fetches the peer's
148
+ // published prekey bundle through the same provider (decision "1a").
149
+ const dm = ctx.providers.dm;
150
+ const selfId = await dm.selfId();
151
+ const threadId = dmThreadId(selfId, input.to, input.thread_label);
152
+
153
+ // reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w którą
154
+ // można by go wpakować (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
155
+ const inner = packPlaintextPayload(input.text);
156
+ const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
157
+
158
+ ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
159
+
160
+ const result = await dm.send({
161
+ to: input.to,
162
+ threadId,
163
+ payload: sealed,
164
+ replyToId: input.reply_to_id,
165
+ });
166
+
167
+ // Keep a LOCAL copy of our own outgoing plaintext so mDM_list can show it
168
+ // back to the sender (the ratchet can't re-derive it on read). Best-effort:
169
+ // only if the keystore offers the optional sent-items cache.
170
+ if (ctx.providers.keys.putSentMessage) {
171
+ await ctx.providers.keys.putSentMessage(result.id, inner);
172
+ }
173
+
174
+ return {
175
+ message_id: result.id,
176
+ delivered_at: result.deliveredAt,
177
+ thread_id: threadId,
178
+ encrypted: true,
179
+ };
180
+ }
181
+
182
+ async function mDM_send_unencrypted(
183
+ input: z.infer<typeof mDM_send_input>,
184
+ ctx: MosaddToolContext,
185
+ ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: false }> {
186
+ // DEPRECATED migration path: plaintext mosadd.chat.v1 envelope, no E2EE.
187
+ // Kept so peers who have not yet published prekeys can still be reached
188
+ // during the migration window. Will be removed once E2EE is universal.
189
+ const dm = ctx.providers.dm;
190
+ const selfId = await dm.selfId();
191
+ const threadId = dmThreadId(selfId, input.to, input.thread_label);
192
+ const payload = packPlaintextPayload(input.text);
193
+
194
+ ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
195
+ thread_id: threadId,
196
+ bytes: payload.byteLength,
197
+ });
198
+
199
+ const result = await dm.send({
200
+ to: input.to,
201
+ threadId,
202
+ payload,
203
+ replyToId: input.reply_to_id,
204
+ });
205
+
206
+ return {
207
+ message_id: result.id,
208
+ delivered_at: result.deliveredAt,
209
+ thread_id: threadId,
210
+ encrypted: false,
211
+ };
212
+ }
213
+
214
+ async function mDM_publish_keys(
215
+ _input: Record<string, never>,
216
+ ctx: MosaddToolContext,
217
+ ): Promise<{ published: true; one_time_prekeys: number }> {
218
+ // Publish the local prekey bundle so peers can start encrypted sessions with
219
+ // us. Rides the same provider as messages (network row / radio announce).
220
+ const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
221
+ ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
222
+ return { published: true, one_time_prekeys: oneTimePrekeyCount };
223
+ }
224
+
225
+ async function mDM_list(
226
+ input: z.infer<typeof mDM_list_input>,
227
+ ctx: MosaddToolContext,
228
+ ): Promise<{
229
+ messages: Array<{
230
+ id: string;
231
+ sender_identity_id: string;
232
+ text: string;
233
+ timestamp: string;
234
+ thread_id: string;
235
+ encrypted: boolean;
236
+ }>;
237
+ next_cursor: string | null;
238
+ threads: string[];
239
+ }> {
240
+ const dm = ctx.providers.dm;
241
+ const selfId = await dm.selfId();
242
+ const threadId = dmThreadId(selfId, input.contact_id, input.thread_label);
243
+
244
+ ctx.log("debug", "mDM_list via DmProvider", { thread_id: threadId });
245
+
246
+ const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
247
+
248
+ const messages = await Promise.all(
249
+ result.messages.map(async (m) => {
250
+ const base = {
251
+ id: m.id,
252
+ sender_identity_id: m.senderId,
253
+ timestamp: m.timestamp,
254
+ thread_id: m.threadId,
255
+ };
256
+ // Legacy plaintext envelope (deprecated path) — unpack directly.
257
+ if (!isE2eeEnvelope(m.payload)) {
258
+ return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
259
+ }
260
+ // Our own outgoing ratchet messages aren't decryptable from our own
261
+ // ratchet on read. Recover the plaintext from the local sent-items cache
262
+ // (this process). If absent (e.g. a different device/process), fall back
263
+ // to a marker instead of failing.
264
+ if (m.senderId === selfId) {
265
+ const cached = await ctx.providers.keys.getSentMessage?.(m.id);
266
+ if (cached) {
267
+ return { ...base, text: unpackPayload(cached).text, encrypted: true };
268
+ }
269
+ return { ...base, text: "<encrypted · sent by you>", encrypted: true };
270
+ }
271
+ try {
272
+ const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
273
+ return { ...base, text: unpackPayload(inner).text, encrypted: true };
274
+ } catch (err) {
275
+ ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
276
+ return { ...base, text: "<undecryptable>", encrypted: true };
277
+ }
278
+ }),
279
+ );
280
+
281
+ return {
282
+ messages,
283
+ next_cursor: result.nextCursor,
284
+ threads: [threadId],
285
+ };
286
+ }
287
+
288
+ async function mDM_list_contacts(
289
+ input: z.infer<typeof mDM_list_contacts_input>,
290
+ ctx: MosaddToolContext,
291
+ ): Promise<{
292
+ contacts: Array<{ identity_id: string; account_id: string | null; display_name: string | null; state: string }>;
293
+ }> {
294
+ readSupabaseEnv();
295
+ const selfId = await resolveSelfIdentityId();
296
+ const sb = getSupabase();
297
+
298
+ ctx.log("debug", "mDM_list_contacts querying contacts table", { selfId });
299
+
300
+ const { data, error } = await sb
301
+ .from("contacts")
302
+ .select("contact_identity_id, state, identities:contact_identity_id(account_id, display_name)")
303
+ .eq("owner_identity_id", selfId)
304
+ .limit(input.limit ?? 100);
305
+
306
+ if (error) {
307
+ throw new Error(`Failed to list contacts: ${error.message}`);
308
+ }
309
+
310
+ type Row = {
311
+ contact_identity_id: string;
312
+ state: string;
313
+ identities?: { account_id?: string | null; display_name?: string | null } | null;
314
+ };
315
+ const contacts = (data as unknown as Row[]).map((r) => ({
316
+ identity_id: r.contact_identity_id,
317
+ account_id: r.identities?.account_id ?? null,
318
+ display_name: r.identities?.display_name ?? null,
319
+ state: r.state,
320
+ }));
321
+
322
+ return { contacts };
323
+ }
324
+
325
+ async function mDM_respond_request(
326
+ input: z.infer<typeof mDM_respond_request_input>,
327
+ ctx: MosaddToolContext,
328
+ ): Promise<{ ok: true }> {
329
+ readSupabaseEnv();
330
+ ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
331
+ // message-request-respond expects action:"respond" + status accepted/rejected
332
+ // (not action:"accept"/"reject"). Map it.
333
+ await invokeFunction<{ ok: boolean }>("message-request-respond", {
334
+ action: "respond",
335
+ request_id: input.request_id,
336
+ status: input.action === "accept" ? "accepted" : "rejected",
337
+ });
338
+ return { ok: true };
339
+ }
340
+
341
+ const mDM_publish_keys_input = z.object({});
342
+
343
+ const mDM_edit_input = z.object({
344
+ to: ContactRef.describe(
345
+ "Recipient identity id of the conversation the message is in (needed to locate it and verify the edit won't break E2EE).",
346
+ ),
347
+ message_id: z.string().min(1).describe("Id of the message to edit (from mDM_list)."),
348
+ new_text: z.string().min(1).max(64_000).describe("Replacement message body (UTF-8). Max 64 KB."),
349
+ thread_label: ThreadSuffix.optional(),
350
+ });
351
+
352
+ const mDM_delete_input = z.object({
353
+ message_id: z.string().min(1).describe("Id of the message to delete (from mDM_list)."),
354
+ });
355
+
356
+ async function mDM_edit(
357
+ input: z.infer<typeof mDM_edit_input>,
358
+ ctx: MosaddToolContext,
359
+ ): Promise<{ message_id: string; edited: true }> {
360
+ readSupabaseEnv();
361
+ const dm = ctx.providers.dm;
362
+ const selfId = await dm.selfId();
363
+ const threadId = dmThreadId(selfId, input.to, input.thread_label);
364
+
365
+ // Locate the target message before editing. mDM is E2EE by default and the
366
+ // Double Ratchet is FORWARD-ONLY (strict in-order, no skipped keys) — an edit
367
+ // cannot be re-sealed (the recipient's ratchet has already advanced past this
368
+ // message, so a re-encrypt would decrypt as <undecryptable>), and writing a
369
+ // fresh plaintext body would SILENTLY STRIP E2EE. So only legacy plaintext
370
+ // messages are editable; E2EE messages must be deleted + re-sent.
371
+ const recent = await dm.list({ threadId, limit: 100 });
372
+ const target = recent.messages.find((m) => m.id === input.message_id);
373
+ if (!target) {
374
+ throw new Error(
375
+ `mDM_edit could not find message ${input.message_id} in the recent history of this thread. ` +
376
+ `Pass the 'to' (and 'thread_label') of the conversation the message belongs to.`,
377
+ );
378
+ }
379
+ if (isE2eeEnvelope(target.payload)) {
380
+ throw new Error(
381
+ "mDM_edit cannot edit an end-to-end-encrypted message: the Double Ratchet is forward-only, so the edit " +
382
+ "can't be re-sealed and storing a new body would strip E2EE. Delete it with mDM_delete and send a " +
383
+ "replacement with mDM_send instead.",
384
+ );
385
+ }
386
+
387
+ // Legacy plaintext message — a plaintext edit matches its (non-E2EE) storage.
388
+ const envelope = {
389
+ v: PROTOCOL_VERSION,
390
+ type: "text",
391
+ text: input.new_text,
392
+ edited: true,
393
+ sent_at: new Date().toISOString(),
394
+ };
395
+ const encrypted_payload = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
396
+ ctx.log("debug", "mDM_edit via message-edit (legacy plaintext only)", { message_id: input.message_id });
397
+ await invokeFunction("message-edit", { message_id: input.message_id, encrypted_payload });
398
+ return { message_id: input.message_id, edited: true };
399
+ }
400
+
401
+ async function mDM_delete(
402
+ input: z.infer<typeof mDM_delete_input>,
403
+ ctx: MosaddToolContext,
404
+ ): Promise<{ message_id: string; deleted: true }> {
405
+ readSupabaseEnv();
406
+ ctx.log("debug", "mDM_delete via message-delete", { message_id: input.message_id });
407
+ await invokeFunction("message-delete", { message_id: input.message_id });
408
+ return { message_id: input.message_id, deleted: true };
409
+ }
410
+
411
+ // ---- Registration ----
412
+
413
+ export const mdmTools: MosaddTool[] = [
414
+ {
415
+ name: "mDM_list_contacts",
416
+ title: "List contacts",
417
+ annotations: { readOnlyHint: true },
418
+ requires: "any",
419
+ description:
420
+ "List the user's mosadd contacts. Returns identity_id (use this for mDM_send / mDM_list), account handle, display name, and contact state (pending, accepted, blocked).",
421
+ inputSchema: mDM_list_contacts_input,
422
+ handler: mDM_list_contacts as MosaddTool["handler"],
423
+ },
424
+ {
425
+ name: "mDM_publish_keys",
426
+ title: "Publish encryption keys",
427
+ annotations: { readOnlyHint: false },
428
+ requires: "any",
429
+ description:
430
+ "Publish your mDM prekey bundle so other people can start an end-to-end-encrypted conversation with you. Run this once after sign-in (and to replenish one-time prekeys). Rides the same transport as messages, so it works over network or off-grid radio.",
431
+ inputSchema: mDM_publish_keys_input,
432
+ handler: mDM_publish_keys as MosaddTool["handler"],
433
+ },
434
+ {
435
+ name: "mDM_send",
436
+ title: "Send encrypted DM",
437
+ annotations: { readOnlyHint: false },
438
+ requires: "any",
439
+ description:
440
+ "Send an END-TO-END-ENCRYPTED direct message via mosadd mDM. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread — mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
441
+ inputSchema: mDM_send_input,
442
+ handler: mDM_send as MosaddTool["handler"],
443
+ },
444
+ {
445
+ name: "mDM_send_unencrypted",
446
+ title: "Send unencrypted DM",
447
+ annotations: { readOnlyHint: false },
448
+ requires: "any",
449
+ description:
450
+ "DEPRECATED migration-window fallback: send a direct message WITHOUT end-to-end encryption (plaintext envelope). Only use when the recipient has not yet published prekeys (mDM_send fails with that hint). Prefer mDM_send. Will be removed once E2EE is universal.",
451
+ inputSchema: mDM_send_input,
452
+ handler: mDM_send_unencrypted as MosaddTool["handler"],
453
+ },
454
+ {
455
+ name: "mDM_list",
456
+ title: "Read direct messages",
457
+ annotations: { readOnlyHint: true },
458
+ requires: "any",
459
+ description:
460
+ "List recent direct messages with a specific contact. Pass contact_id as the identity_id from mDM_list_contacts. Decrypts end-to-end-encrypted messages from the contact automatically; legacy plaintext messages are shown as-is. Optionally filter to a single thread_label.",
461
+ inputSchema: mDM_list_input,
462
+ handler: mDM_list as MosaddTool["handler"],
463
+ },
464
+ {
465
+ name: "mDM_respond_request",
466
+ title: "Accept or decline contact request",
467
+ annotations: { readOnlyHint: false },
468
+ requires: "any",
469
+ description:
470
+ "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
471
+ inputSchema: mDM_respond_request_input,
472
+ handler: mDM_respond_request as MosaddTool["handler"],
473
+ },
474
+ {
475
+ name: "mDM_edit",
476
+ title: "Edit a DM",
477
+ annotations: { destructiveHint: true },
478
+ requires: "any",
479
+ description:
480
+ "Edit a direct message you sent — replace its body by message_id (pass the conversation's `to` so it can be located). NOTE: end-to-end-encrypted messages CANNOT be edited (the ratchet is forward-only) — mDM_edit refuses them and you should mDM_delete + mDM_send a replacement instead. Only legacy non-E2EE messages are editable.",
481
+ inputSchema: mDM_edit_input,
482
+ handler: mDM_edit as MosaddTool["handler"],
483
+ },
484
+ {
485
+ name: "mDM_delete",
486
+ title: "Delete a DM",
487
+ annotations: { destructiveHint: true },
488
+ requires: "any",
489
+ description:
490
+ "Delete a direct message you sent by message_id (from mDM_list). Soft-deletes server-side so it stops showing in mDM_list for both sides.",
491
+ inputSchema: mDM_delete_input,
492
+ handler: mDM_delete as MosaddTool["handler"],
493
+ },
494
+ ];