@mosadd/mcp 3.0.0-alpha.6 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +410 -0
  2. package/README.md +79 -40
  3. package/dist/bin/mcp.js +132 -8
  4. package/dist/chunk-VMMJJYXF.js +4233 -0
  5. package/dist/index.d.ts +110 -6
  6. package/dist/index.js +3 -1
  7. package/package.json +19 -16
  8. package/src/__tests__/blob-upload.test.ts +93 -0
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/cli.test.ts +47 -0
  11. package/src/__tests__/flota-jawnie.test.ts +244 -0
  12. package/src/__tests__/golden-path.test.ts +4 -2
  13. package/src/__tests__/integration.test.ts +50 -11
  14. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  15. package/src/__tests__/label-room-owner.test.ts +22 -0
  16. package/src/__tests__/mdm-e2ee.test.ts +35 -1
  17. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  18. package/src/__tests__/mirc-invite.test.ts +112 -0
  19. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  20. package/src/__tests__/no-dead-host.test.ts +37 -0
  21. package/src/__tests__/presence.test.ts +199 -0
  22. package/src/__tests__/server.test.ts +11 -7
  23. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  24. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  25. package/src/__tests__/voice-fields.test.ts +24 -0
  26. package/src/bin/mcp.ts +71 -6
  27. package/src/cli.ts +100 -0
  28. package/src/crypto/channel-e2ee.ts +288 -0
  29. package/src/crypto/mdm-session.ts +476 -37
  30. package/src/index.ts +2 -2
  31. package/src/providers/blob-upload.ts +162 -0
  32. package/src/providers/supabase-dm.ts +102 -7
  33. package/src/providers/supabase-voice.ts +13 -1
  34. package/src/providers/supabase.ts +121 -10
  35. package/src/server.ts +102 -12
  36. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  37. package/src/tools/actions.ts +166 -0
  38. package/src/tools/attachments.ts +276 -0
  39. package/src/tools/capabilities.ts +2 -0
  40. package/src/tools/channel-payload.ts +69 -0
  41. package/src/tools/embed.ts +110 -0
  42. package/src/tools/index.ts +136 -6
  43. package/src/tools/knowledge-graph.ts +186 -0
  44. package/src/tools/knowledge.ts +351 -132
  45. package/src/tools/mail-agentbox.ts +155 -0
  46. package/src/tools/mail-aliases.ts +25 -0
  47. package/src/tools/mail-provenance.ts +137 -0
  48. package/src/tools/mail.ts +284 -38
  49. package/src/tools/mdm-as-agent.ts +138 -0
  50. package/src/tools/mdm-voice.ts +17 -3
  51. package/src/tools/mdm.ts +303 -57
  52. package/src/tools/mirc-edge.ts +8 -2
  53. package/src/tools/mirc-members.ts +130 -20
  54. package/src/tools/mirc-messages.ts +80 -35
  55. package/src/tools/mirc.ts +149 -11
  56. package/src/tools/mroom-messages.ts +4 -12
  57. package/src/tools/mtalk.ts +11 -1
  58. package/src/tools/murl.ts +314 -0
  59. package/src/tools/presence.ts +442 -0
  60. package/src/tools/ptt-ingest.ts +99 -0
  61. package/src/tools/threat.ts +123 -0
  62. package/src/tools/voice-format.ts +43 -0
  63. package/src/types.ts +36 -0
  64. package/src/version.ts +8 -0
  65. package/LICENSE +0 -201
  66. package/dist/chunk-KAPG5FBN.js +0 -1844
package/src/tools/mdm.ts CHANGED
@@ -10,19 +10,34 @@
10
10
  * their own Supabase URL + anon key + a session JWT via env vars (BYOK).
11
11
  *
12
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
13
+ * threat-radar middleware in front, and replace the plaintext
14
14
  * encrypted_payload with real X3DH + Double Ratchet via @mosadd/crypto.
15
15
  */
16
16
 
17
17
  import { z } from "zod";
18
18
  import type { MosaddTool, MosaddToolContext } from "../types.js";
19
+ import { formatVoiceIfAny, voiceFields } from "./voice-format.js";
19
20
  import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supabase.js";
20
21
  import {
21
22
  encryptForPeer,
22
23
  decryptFromPeer,
23
- publishOwnPrekeys,
24
24
  isE2eeEnvelope,
25
+ ensureOwnBundlePublished,
26
+ bundlePolicyForKind,
27
+ fetchVerifiedBundle,
28
+ sealForSelf,
29
+ sealForPeerRecoverable,
30
+ openSelfSealed,
31
+ openPeerRecoverable,
32
+ type OwnBundleState,
33
+ type PublicPrekeyBundle,
25
34
  } from "../crypto/mdm-session.js";
35
+ import {
36
+ MDM_TEXT_MESSAGE_TYPE,
37
+ MDM_MCP_SEALED_MESSAGE_TYPE,
38
+ type DmSendArgsExt,
39
+ type DmMessageExt,
40
+ } from "../providers/supabase-dm.js";
26
41
 
27
42
  // ---- Constants ----
28
43
 
@@ -115,24 +130,21 @@ async function resolveSelfIdentityId(): Promise<string> {
115
130
  * Receivers in the mosadd consumer app understand this `mosadd.chat.v1` shape.
116
131
  * V0.2: replace with @mosadd/crypto Double Ratchet wrap.
117
132
  */
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"));
133
+ function packPlaintextPayload(text: string): Uint8Array {
134
+ // Pure text bytes so the consumer app displays clean message text directly
135
+ return new Uint8Array(Buffer.from(text, "utf8"));
129
136
  }
130
137
 
131
138
  function unpackPayload(payload: Uint8Array): { text: string; sent_at?: string; reply_to?: string | null } {
132
139
  try {
133
- const json = Buffer.from(payload).toString("utf8");
134
- const obj = JSON.parse(json);
135
- if (typeof obj?.text === "string") return obj;
140
+ const raw = Buffer.from(payload).toString("utf8");
141
+ try {
142
+ const obj = JSON.parse(raw);
143
+ if (typeof obj?.text === "string") return obj;
144
+ } catch {
145
+ return { text: raw };
146
+ }
147
+ return { text: raw };
136
148
  } catch {
137
149
  /* fall through */
138
150
  }
@@ -141,35 +153,163 @@ function unpackPayload(payload: Uint8Array): { text: string; sent_at?: string; r
141
153
 
142
154
  // ---- Handlers ----
143
155
 
156
+ /** Does this provider know the caller's identity kind (Supabase lane)? */
157
+ async function selfKindOf(dm: MosaddToolContext["providers"]["dm"]): Promise<string | null> {
158
+ const f = (dm as { selfKind?: () => Promise<string | null> }).selfKind;
159
+ return typeof f === "function" ? await f.call(dm) : null;
160
+ }
161
+
162
+ /** A peer's identity kind when the provider can tell (Supabase lane); null = unknown. */
163
+ async function peerKindOf(dm: MosaddToolContext["providers"]["dm"], peerId: string): Promise<string | null> {
164
+ const f = (dm as { peerKind?: (id: string) => Promise<string | null> }).peerKind;
165
+ if (typeof f !== "function") return null;
166
+ try {
167
+ return await f.call(dm, peerId);
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ type MdmSendResultOut = {
174
+ message_id: string;
175
+ delivered_at: string;
176
+ thread_id: string;
177
+ encrypted: boolean;
178
+ /**
179
+ * "plaintext_agent_lane": an agent line is a party, so the DM goes in the clear (rozkaz Krola
180
+ * 20.09, same rule as the app's peerIsAgent). "e2ee": human to human, X3DH + Double Ratchet.
181
+ */
182
+ mode: "plaintext_agent_lane" | "e2ee";
183
+ /**
184
+ * WHY this mode (29.09, rozkaz Krola 28.09 „sciagnij szyfrowanie z naszych rozmow"):
185
+ * "fleet_plaintext" = an agent line is a party OR it is a note to self → always in the clear;
186
+ * "human_to_human" = two people, E2EE unchanged.
187
+ */
188
+ reason: "fleet_plaintext" | "human_to_human";
189
+ /** the sender can read this message back from ANY process / ANY key of the same identity */
190
+ sender_copy: boolean;
191
+ /** the recipient can read it without a ratchet session */
192
+ recipient_copy: boolean;
193
+ /** state of this identity in the key directory (E2EE only; the plaintext lane never touches it) */
194
+ identity: OwnBundleState | "untouched";
195
+ };
196
+
144
197
  async function mDM_send(
145
198
  input: z.infer<typeof mDM_send_input>,
146
199
  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").
200
+ ): Promise<MdmSendResultOut> {
152
201
  const dm = ctx.providers.dm;
153
202
  const selfId = await dm.selfId();
154
203
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
204
+ const keys = ctx.providers.keys;
205
+
206
+ // ⛔ POPRAWKA 27.09.2026 (niezalezna weryfikacja toru mdm-brama). The first fix seeded the mDM
207
+ // identity from ONE API key and let an agent line (re)publish it. An identity holds MANY keys
208
+ // (general@: 8 active), so the directory flapped between per-key identities and every copy
209
+ // sealed under the previous key stopped opening. The source answer is the King's rule, not a
210
+ // better key: an agent line NEVER uses E2EE (DECYZJE-KROLA 20.09 12:56Z: linie<->linie,
211
+ // linie<->Krol, czlowiek->linia: jawnie). Plaintext is readable by every key of the line and by
212
+ // the recipient's app on every device, and no bundle is needed, so nothing can flap.
213
+ //
214
+ // 29.09.2026 (owner decision 28.09: no encryption on agent-line conversations, in any channel or
215
+ // identity): a note to SELF (to === selfId) goes in the
216
+ // clear too. MCP sessions on the King's key sealed his own thread (11 envelopes 21.09) and the
217
+ // server now refuses envelopes there (message-send `fleet_plaintext_only`). Kinds of BOTH sides
218
+ // are read from `identities.kind` before any sealing; only person↔person stays E2EE.
219
+ const selfKind = await selfKindOf(dm);
220
+ const noteToSelf = input.to === selfId;
221
+ const peerKind = selfKind === "agent" || noteToSelf ? selfKind : await peerKindOf(dm, input.to);
222
+ if (selfKind === "agent" || peerKind === "agent" || noteToSelf) {
223
+ const payload = packPlaintextPayload(input.text);
224
+ ctx.log("debug", "mDM_send agent-line plaintext (owner decisions 20.09 + 28.09)", {
225
+ thread_id: threadId,
226
+ self_kind: selfKind,
227
+ peer_kind: peerKind,
228
+ note_to_self: noteToSelf,
229
+ });
230
+ const plainArgs: DmSendArgsExt = {
231
+ to: input.to,
232
+ threadId,
233
+ payload,
234
+ replyToId: input.reply_to_id,
235
+ messageType: MDM_TEXT_MESSAGE_TYPE,
236
+ };
237
+ const result = await dm.send(plainArgs);
238
+ return {
239
+ message_id: result.id,
240
+ delivered_at: result.deliveredAt,
241
+ thread_id: threadId,
242
+ encrypted: false,
243
+ mode: "plaintext_agent_lane",
244
+ reason: "fleet_plaintext",
245
+ sender_copy: true,
246
+ recipient_copy: true,
247
+ identity: "untouched",
248
+ };
249
+ }
155
250
 
156
- const inner = packPlaintextPayload(input.text, input.reply_to_id);
157
- const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
251
+ // E2EE path (human to human, or a lane that cannot tell kinds). The plaintext is packed into
252
+ // the inner envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
253
+ // DmProvider moves without understanding. First contact fetches the peer's published prekey
254
+ // bundle through the same provider (decision "1a").
255
+ //
256
+ // On a PERSON's key MCP writes nothing to the key directory (bundlePolicyForKind: the app owns
257
+ // a human's bundle) and no "s1." self copy: the app opens only copies sealed under its own seed,
258
+ // and an unopenable "s1." makes it state a FALSE reason ("device"/"key") for the bubble. The
259
+ // envelope is typed `text` so the app states the true one: sent by MCP, no copy for this device.
260
+ let identity: OwnBundleState = "foreign";
261
+ try {
262
+ identity = await ensureOwnBundlePublished(keys, dm, selfId, bundlePolicyForKind(selfKind, { explicit: false }));
263
+ } catch (err) {
264
+ // Directory unreachable: the ratchet envelope still carries its own handshake, so the send
265
+ // proceeds; only the recipient copy is skipped (it would be sealed under an unverified identity).
266
+ ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
267
+ }
268
+ const ourIdentityIsPublished = identity === "consistent" || identity === "published";
269
+
270
+ // reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w ktora
271
+ // mozna by go wpakowac (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
272
+ const inner = packPlaintextPayload(input.text);
273
+ const sealed = await encryptForPeer(keys, dm, input.to, inner);
274
+
275
+ // "s1." only where the reader of that copy is MCP itself: never on a human key (see above).
276
+ const selfPayload = selfKind !== "human" && ourIdentityIsPublished ? await sealForSelf(keys, inner) : null;
277
+ let recipientSelfPayload: string | null = null;
278
+ // The recipient opens "r1." with OUR PUBLISHED identity, so it is written only when the
279
+ // directory holds exactly our key. A note-to-self needs none.
280
+ if (ourIdentityIsPublished && input.to !== selfId) {
281
+ try {
282
+ const peer = await fetchVerifiedBundle(dm, input.to);
283
+ if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
284
+ } catch (err) {
285
+ ctx.log("warn", "mDM_send skipped the recipient copy", { error: String(err) });
286
+ }
287
+ }
158
288
 
159
- ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
289
+ ctx.log("debug", "mDM_send E2EE via DmProvider", {
290
+ thread_id: threadId,
291
+ bytes: sealed.byteLength,
292
+ identity,
293
+ sender_copy: !!selfPayload,
294
+ recipient_copy: !!recipientSelfPayload,
295
+ });
160
296
 
161
- const result = await dm.send({
297
+ const sendArgs: DmSendArgsExt = {
162
298
  to: input.to,
163
299
  threadId,
164
300
  payload: sealed,
165
301
  replyToId: input.reply_to_id,
166
- });
302
+ messageType: MDM_MCP_SEALED_MESSAGE_TYPE,
303
+ selfPayload,
304
+ recipientSelfPayload,
305
+ };
306
+ const result = await dm.send(sendArgs);
167
307
 
168
308
  // Keep a LOCAL copy of our own outgoing plaintext so mDM_list can show it
169
309
  // back to the sender (the ratchet can't re-derive it on read). Best-effort:
170
310
  // 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);
311
+ if (keys.putSentMessage) {
312
+ await keys.putSentMessage(result.id, inner);
173
313
  }
174
314
 
175
315
  return {
@@ -177,6 +317,11 @@ async function mDM_send(
177
317
  delivered_at: result.deliveredAt,
178
318
  thread_id: threadId,
179
319
  encrypted: true,
320
+ mode: "e2ee",
321
+ reason: "human_to_human",
322
+ sender_copy: !!selfPayload,
323
+ recipient_copy: !!recipientSelfPayload,
324
+ identity,
180
325
  };
181
326
  }
182
327
 
@@ -184,25 +329,26 @@ async function mDM_send_unencrypted(
184
329
  input: z.infer<typeof mDM_send_input>,
185
330
  ctx: MosaddToolContext,
186
331
  ): 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.
332
+ // Plaintext send, no E2EE. ⛔ 29.09.2026: NOT deprecated — this is THE path for every
333
+ // conversation with a fleet line and with the King (rozkaz Krola 28.09). Stays forever.
190
334
  const dm = ctx.providers.dm;
191
335
  const selfId = await dm.selfId();
192
336
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
193
- const payload = packPlaintextPayload(input.text, input.reply_to_id);
337
+ const payload = packPlaintextPayload(input.text);
194
338
 
195
- ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
339
+ ctx.log("debug", "mDM_send_unencrypted (plaintext) via DmProvider", {
196
340
  thread_id: threadId,
197
341
  bytes: payload.byteLength,
198
342
  });
199
343
 
200
- const result = await dm.send({
344
+ const plainArgs: DmSendArgsExt = {
201
345
  to: input.to,
202
346
  threadId,
203
347
  payload,
204
348
  replyToId: input.reply_to_id,
205
- });
349
+ messageType: MDM_TEXT_MESSAGE_TYPE,
350
+ };
351
+ const result = await dm.send(plainArgs);
206
352
 
207
353
  return {
208
354
  message_id: result.id,
@@ -215,12 +361,34 @@ async function mDM_send_unencrypted(
215
361
  async function mDM_publish_keys(
216
362
  _input: Record<string, never>,
217
363
  ctx: MosaddToolContext,
218
- ): Promise<{ published: true; one_time_prekeys: number }> {
364
+ ): Promise<{ published: boolean; identity: OwnBundleState; one_time_prekeys: number; note?: string }> {
219
365
  // Publish the local prekey bundle so peers can start encrypted sessions with
220
366
  // 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 };
367
+ //
368
+ // ⛔ 27.09.2026: never over a PERSON's app-anchored bundle. The MCP identity is seeded from the
369
+ // API key, the app's from the login secret; replacing the app's bundle breaks every DM to that
370
+ // person on every device (bundlePolicyForKind, explicit). An empty directory may be filled.
371
+ const dm = ctx.providers.dm;
372
+ const keys = ctx.providers.keys;
373
+ const selfId = await dm.selfId();
374
+ const identity = await ensureOwnBundlePublished(
375
+ keys,
376
+ dm,
377
+ selfId,
378
+ bundlePolicyForKind(await selfKindOf(dm), { explicit: true }),
379
+ );
380
+ const { oneTimePrekeys } = await keys.getOwnMaterial();
381
+ ctx.log("debug", "mDM_publish_keys", { identity, one_time_prekeys: oneTimePrekeys.length });
382
+ if (identity === "foreign") {
383
+ return {
384
+ published: false,
385
+ identity,
386
+ one_time_prekeys: 0,
387
+ note:
388
+ "This identity already has keys published by the mosADD app. They were left untouched: replacing them from an API key would make every conversation with you unreadable in the app.",
389
+ };
390
+ }
391
+ return { published: identity === "published", identity, one_time_prekeys: oneTimePrekeys.length };
224
392
  }
225
393
 
226
394
  async function mDM_list(
@@ -234,6 +402,7 @@ async function mDM_list(
234
402
  timestamp: string;
235
403
  thread_id: string;
236
404
  encrypted: boolean;
405
+ voice?: { transcript: string | null; audio_url: string | null; duration_ms: number | null };
237
406
  }>;
238
407
  next_cursor: string | null;
239
408
  threads: string[];
@@ -246,32 +415,62 @@ async function mDM_list(
246
415
 
247
416
  const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
248
417
 
418
+ const keys = ctx.providers.keys;
419
+ // One verified bundle per sender for the "r1." copies (usually just the contact).
420
+ const bundleBySender = new Map<string, Promise<PublicPrekeyBundle | null>>();
421
+ const senderBundle = (id: string) => {
422
+ let p = bundleBySender.get(id);
423
+ if (!p) {
424
+ p = fetchVerifiedBundle(dm, id).catch(() => null);
425
+ bundleBySender.set(id, p);
426
+ }
427
+ return p;
428
+ };
429
+
249
430
  const messages = await Promise.all(
250
- result.messages.map(async (m) => {
431
+ result.messages.map(async (raw) => {
432
+ const m = raw as DmMessageExt;
251
433
  const base = {
252
434
  id: m.id,
253
435
  sender_identity_id: m.senderId,
254
436
  timestamp: m.timestamp,
255
437
  thread_id: m.threadId,
438
+ ...voiceFields(m),
256
439
  };
257
440
  // Legacy plaintext envelope (deprecated path) — unpack directly.
258
441
  if (!isE2eeEnvelope(m.payload)) {
259
- return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
442
+ return { ...base, text: formatVoiceIfAny(unpackPayload(m.payload).text), encrypted: false };
260
443
  }
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.
444
+ // Our own outgoing ratchet messages aren't decryptable from our own ratchet on read.
445
+ // 1) the "s1." self copy (any process holding the same key), 2) this process's sent cache,
446
+ // 3) a note-to-self is sealed to our own bundle, so our own key opens it.
265
447
  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 };
448
+ const own = (await openSelfSealed(keys, m.selfPayload)) ?? (await keys.getSentMessage?.(m.id));
449
+ if (own) {
450
+ return { ...base, text: formatVoiceIfAny(unpackPayload(own).text), encrypted: true };
451
+ }
452
+ if (input.contact_id === selfId) {
453
+ try {
454
+ const inner = await decryptFromPeer(keys, selfId, m.payload);
455
+ return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
456
+ } catch { /* fall through to the marker */ }
269
457
  }
270
458
  return { ...base, text: "<encrypted · sent by you>", encrypted: true };
271
459
  }
460
+ // Recipient side: the sender's "r1." copy, or our own "s1." backfill in the same column
461
+ // (the app writes it after a successful read) — neither needs a live ratchet session.
462
+ if (m.recipientSelfPayload) {
463
+ const bundle = await senderBundle(m.senderId);
464
+ const copy =
465
+ (bundle ? await openPeerRecoverable(keys, bundle, m.recipientSelfPayload) : null) ??
466
+ (await openSelfSealed(keys, m.recipientSelfPayload));
467
+ if (copy) {
468
+ return { ...base, text: formatVoiceIfAny(unpackPayload(copy).text), encrypted: true };
469
+ }
470
+ }
272
471
  try {
273
472
  const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
274
- return { ...base, text: unpackPayload(inner).text, encrypted: true };
473
+ return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
275
474
  } catch (err) {
276
475
  ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
277
476
  return { ...base, text: "<undecryptable>", encrypted: true };
@@ -329,9 +528,12 @@ async function mDM_respond_request(
329
528
  ): Promise<{ ok: true }> {
330
529
  readSupabaseEnv();
331
530
  ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
531
+ // message-request-respond expects action:"respond" + status accepted/rejected
532
+ // (not action:"accept"/"reject"). Map it.
332
533
  await invokeFunction<{ ok: boolean }>("message-request-respond", {
534
+ action: "respond",
333
535
  request_id: input.request_id,
334
- action: input.action,
536
+ status: input.action === "accept" ? "accepted" : "rejected",
335
537
  });
336
538
  return { ok: true };
337
539
  }
@@ -339,8 +541,12 @@ async function mDM_respond_request(
339
541
  const mDM_publish_keys_input = z.object({});
340
542
 
341
543
  const mDM_edit_input = z.object({
544
+ to: ContactRef.describe(
545
+ "Recipient identity id of the conversation the message is in (needed to locate it and verify the edit won't break E2EE).",
546
+ ),
342
547
  message_id: z.string().min(1).describe("Id of the message to edit (from mDM_list)."),
343
548
  new_text: z.string().min(1).max(64_000).describe("Replacement message body (UTF-8). Max 64 KB."),
549
+ thread_label: ThreadSuffix.optional(),
344
550
  });
345
551
 
346
552
  const mDM_delete_input = z.object({
@@ -352,9 +558,33 @@ async function mDM_edit(
352
558
  ctx: MosaddToolContext,
353
559
  ): Promise<{ message_id: string; edited: true }> {
354
560
  readSupabaseEnv();
355
- // Wire format = base64(JSON envelope), matching the EF (which atob()s it).
356
- // NOTE: stored server-readable (like mDM_send_unencrypted). On an E2EE thread
357
- // this does NOT re-seal the message — prefer delete + re-send for ciphertext.
561
+ const dm = ctx.providers.dm;
562
+ const selfId = await dm.selfId();
563
+ const threadId = dmThreadId(selfId, input.to, input.thread_label);
564
+
565
+ // Locate the target message before editing. mDM is E2EE by default and the
566
+ // Double Ratchet is FORWARD-ONLY (strict in-order, no skipped keys) — an edit
567
+ // cannot be re-sealed (the recipient's ratchet has already advanced past this
568
+ // message, so a re-encrypt would decrypt as <undecryptable>), and writing a
569
+ // fresh plaintext body would SILENTLY STRIP E2EE. So only legacy plaintext
570
+ // messages are editable; E2EE messages must be deleted + re-sent.
571
+ const recent = await dm.list({ threadId, limit: 100 });
572
+ const target = recent.messages.find((m) => m.id === input.message_id);
573
+ if (!target) {
574
+ throw new Error(
575
+ `mDM_edit could not find message ${input.message_id} in the recent history of this thread. ` +
576
+ `Pass the 'to' (and 'thread_label') of the conversation the message belongs to.`,
577
+ );
578
+ }
579
+ if (isE2eeEnvelope(target.payload)) {
580
+ throw new Error(
581
+ "mDM_edit cannot edit an end-to-end-encrypted message: the Double Ratchet is forward-only, so the edit " +
582
+ "can't be re-sealed and storing a new body would strip E2EE. Delete it with mDM_delete and send a " +
583
+ "replacement with mDM_send instead.",
584
+ );
585
+ }
586
+
587
+ // Legacy plaintext message — a plaintext edit matches its (non-E2EE) storage.
358
588
  const envelope = {
359
589
  v: PROTOCOL_VERSION,
360
590
  type: "text",
@@ -363,7 +593,7 @@ async function mDM_edit(
363
593
  sent_at: new Date().toISOString(),
364
594
  };
365
595
  const encrypted_payload = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
366
- ctx.log("debug", "mDM_edit via message-edit", { message_id: input.message_id });
596
+ ctx.log("debug", "mDM_edit via message-edit (legacy plaintext only)", { message_id: input.message_id });
367
597
  await invokeFunction("message-edit", { message_id: input.message_id, encrypted_payload });
368
598
  return { message_id: input.message_id, edited: true };
369
599
  }
@@ -383,6 +613,8 @@ async function mDM_delete(
383
613
  export const mdmTools: MosaddTool[] = [
384
614
  {
385
615
  name: "mDM_list_contacts",
616
+ title: "List contacts",
617
+ annotations: { readOnlyHint: true },
386
618
  requires: "any",
387
619
  description:
388
620
  "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).",
@@ -391,6 +623,8 @@ export const mdmTools: MosaddTool[] = [
391
623
  },
392
624
  {
393
625
  name: "mDM_publish_keys",
626
+ title: "Publish encryption keys",
627
+ annotations: { readOnlyHint: false },
394
628
  requires: "any",
395
629
  description:
396
630
  "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.",
@@ -399,22 +633,28 @@ export const mdmTools: MosaddTool[] = [
399
633
  },
400
634
  {
401
635
  name: "mDM_send",
636
+ title: "Send DM",
637
+ annotations: { readOnlyHint: false },
402
638
  requires: "any",
403
639
  description:
404
- "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.",
640
+ "Send a direct message via mosadd mDM. Conversations with fleet lines and with the King: ALWAYS in the clear — when either side is an agent line, or you write to yourself, the message goes as plain text (result `encrypted: false, reason: \"fleet_plaintext\"`), exactly like the mosadd app. Only between two PEOPLE is it END-TO-END-ENCRYPTED (X3DH + Double Ratchet; the recipient must have published keys). Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Optional thread_label puts the message in a named thread — mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram.",
405
641
  inputSchema: mDM_send_input,
406
642
  handler: mDM_send as MosaddTool["handler"],
407
643
  },
408
644
  {
409
645
  name: "mDM_send_unencrypted",
646
+ title: "Send plain-text DM",
647
+ annotations: { readOnlyHint: false },
410
648
  requires: "any",
411
649
  description:
412
- "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.",
650
+ "Send a direct message as plain text, never encrypted. Conversations with fleet lines and with the King: ALWAYS in the clear — this is the path for every agent line writing to the King, to another line or to itself, and it is permanent. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts); optional thread_label puts it in a named thread. mDM_send picks the same plain-text path by itself whenever a fleet line is a party.",
413
651
  inputSchema: mDM_send_input,
414
652
  handler: mDM_send_unencrypted as MosaddTool["handler"],
415
653
  },
416
654
  {
417
655
  name: "mDM_list",
656
+ title: "Read direct messages",
657
+ annotations: { readOnlyHint: true },
418
658
  requires: "any",
419
659
  description:
420
660
  "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.",
@@ -423,6 +663,8 @@ export const mdmTools: MosaddTool[] = [
423
663
  },
424
664
  {
425
665
  name: "mDM_respond_request",
666
+ title: "Accept or decline contact request",
667
+ annotations: { readOnlyHint: false },
426
668
  requires: "any",
427
669
  description:
428
670
  "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
@@ -431,14 +673,18 @@ export const mdmTools: MosaddTool[] = [
431
673
  },
432
674
  {
433
675
  name: "mDM_edit",
676
+ title: "Edit a DM",
677
+ annotations: { destructiveHint: true },
434
678
  requires: "any",
435
679
  description:
436
- "Edit a direct message you sent — replace its body by message_id (from mDM_list). Stores a server-readable edited body; on an end-to-end-encrypted thread this does not re-encrypt, so for E2EE prefer deleting and re-sending.",
680
+ "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.",
437
681
  inputSchema: mDM_edit_input,
438
682
  handler: mDM_edit as MosaddTool["handler"],
439
683
  },
440
684
  {
441
685
  name: "mDM_delete",
686
+ title: "Delete a DM",
687
+ annotations: { destructiveHint: true },
442
688
  requires: "any",
443
689
  description:
444
690
  "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.",
@@ -22,14 +22,14 @@
22
22
  * - RECOMMENDED (LINEAR-2675/E6): server calls `mIRC_mint_channel_token` to
23
23
  * exchange the hub key for a 5-min channel-scoped JWT, then the browser
24
24
  * opens the WS with `Sec-WebSocket-Protocol: mosadd.v1, bearer.<jwt>`.
25
- * The hub key never leaves the server. Recipe: `apps/edge/README.md`.
25
+ * The hub key never leaves the server. (The edge Worker is part of the hosted service since 2026-09-29.)
26
26
  */
27
27
 
28
28
  import { z } from "zod";
29
29
  import type { MosaddTool, MosaddToolContext } from "../types.js";
30
30
 
31
31
  const DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
32
- const DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
32
+ const DEFAULT_SUPABASE_URL = "https://api.mosadd.com";
33
33
 
34
34
  function edgeUrl(): string {
35
35
  return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
@@ -165,6 +165,8 @@ async function mIRC_mint_channel_token(
165
165
  export const mircEdgeTools: MosaddTool[] = [
166
166
  {
167
167
  name: "mIRC_mint_channel_token",
168
+ title: "Mint channel token",
169
+ annotations: { readOnlyHint: false },
168
170
  requires: "network",
169
171
  description:
170
172
  "Exchange the hub key (MOSADD_API_KEY) for a short-lived (5min), channel-scoped JWT. Returns { token, expires_in, channel_id, scope }. The token is safe to hand to a browser to open a WS via `Sec-WebSocket-Protocol: mosadd.v1, bearer.<token>`. The hub key NEVER leaves the server. Use this from any server-side route (Next.js /api/chat-token, Express, etc.) before showing chat in a browser. Required by LINEAR-2675/E6 to avoid leaking the hub key into CDN access logs.",
@@ -173,6 +175,8 @@ export const mircEdgeTools: MosaddTool[] = [
173
175
  },
174
176
  {
175
177
  name: "mIRC_send_edge",
178
+ title: "Send message (low-latency edge)",
179
+ annotations: { readOnlyHint: false },
176
180
  requires: "network",
177
181
  description:
178
182
  "Send a text message into a persistent channel via the mosadd-edge Cloudflare Worker (Durable Object backend). Sub-100ms global fan-out to all WebSocket subscribers of the channel + async flush to Supabase as system-of-record (idempotent). Use this when you want native realtime push without polling. Parallel to mIRC_post_message (Supabase path); pick one per channel. Auth: MOSADD_API_KEY env (hub key).",
@@ -181,6 +185,8 @@ export const mircEdgeTools: MosaddTool[] = [
181
185
  },
182
186
  {
183
187
  name: "mIRC_history_edge",
188
+ title: "Read channel history (edge)",
189
+ annotations: { readOnlyHint: true },
184
190
  requires: "network",
185
191
  description:
186
192
  "Read the last N (max 100) messages held in the channel's Durable Object ring buffer at the edge. Hot path is the DO, not Supabase — same data lands in messages_meta via async flush, so cold reads / pagination beyond 100 should use mIRC_list_messages.",