@mosadd/mcp 3.0.0-alpha.7 → 3.0.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.
Files changed (68) hide show
  1. package/CHANGELOG.md +415 -0
  2. package/LICENSE +21 -201
  3. package/README.md +79 -40
  4. package/dist/bin/mcp.js +132 -8
  5. package/dist/chunk-J2S44U5R.js +4258 -0
  6. package/dist/index.d.ts +112 -8
  7. package/dist/index.js +3 -1
  8. package/package.json +19 -16
  9. package/src/__tests__/blob-upload.test.ts +93 -0
  10. package/src/__tests__/channel-e2ee.test.ts +62 -0
  11. package/src/__tests__/cli.test.ts +47 -0
  12. package/src/__tests__/fleet-plaintext.test.ts +243 -0
  13. package/src/__tests__/golden-path.test.ts +4 -2
  14. package/src/__tests__/integration.test.ts +50 -11
  15. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  16. package/src/__tests__/label-room-owner.test.ts +22 -0
  17. package/src/__tests__/mdm-e2ee.test.ts +36 -2
  18. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  19. package/src/__tests__/mirc-invite.test.ts +112 -0
  20. package/src/__tests__/mirc-voice.test.ts +82 -0
  21. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  22. package/src/__tests__/mrag-search-diagnostics.test.ts +78 -0
  23. package/src/__tests__/no-dead-host.test.ts +37 -0
  24. package/src/__tests__/presence.test.ts +199 -0
  25. package/src/__tests__/server.test.ts +11 -7
  26. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  27. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  28. package/src/__tests__/voice-fields.test.ts +24 -0
  29. package/src/bin/mcp.ts +71 -6
  30. package/src/cli.ts +100 -0
  31. package/src/crypto/channel-e2ee.ts +288 -0
  32. package/src/crypto/mdm-session.ts +479 -40
  33. package/src/index.ts +2 -2
  34. package/src/providers/blob-upload.ts +162 -0
  35. package/src/providers/supabase-dm.ts +102 -7
  36. package/src/providers/supabase-voice.ts +13 -1
  37. package/src/providers/supabase.ts +121 -10
  38. package/src/server.ts +102 -12
  39. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  40. package/src/tools/actions.ts +166 -0
  41. package/src/tools/attachments.ts +276 -0
  42. package/src/tools/capabilities.ts +2 -0
  43. package/src/tools/channel-payload.ts +69 -0
  44. package/src/tools/embed.ts +110 -0
  45. package/src/tools/index.ts +136 -6
  46. package/src/tools/knowledge-graph.ts +186 -0
  47. package/src/tools/knowledge.ts +205 -12
  48. package/src/tools/mail-agentbox.ts +155 -0
  49. package/src/tools/mail-aliases.ts +25 -0
  50. package/src/tools/mail-provenance.ts +137 -0
  51. package/src/tools/mail.ts +214 -60
  52. package/src/tools/mdm-as-agent.ts +137 -0
  53. package/src/tools/mdm-voice.ts +17 -3
  54. package/src/tools/mdm.ts +306 -58
  55. package/src/tools/mirc-edge.ts +12 -6
  56. package/src/tools/mirc-members.ts +130 -20
  57. package/src/tools/mirc-messages.ts +109 -40
  58. package/src/tools/mirc.ts +149 -11
  59. package/src/tools/mroom-messages.ts +5 -13
  60. package/src/tools/mtalk.ts +11 -1
  61. package/src/tools/murl.ts +314 -0
  62. package/src/tools/presence.ts +442 -0
  63. package/src/tools/ptt-ingest.ts +99 -0
  64. package/src/tools/threat.ts +123 -0
  65. package/src/tools/voice-format.ts +66 -0
  66. package/src/types.ts +36 -0
  67. package/src/version.ts +8 -0
  68. package/dist/chunk-EFTB743G.js +0 -1924
@@ -0,0 +1,390 @@
1
+ /**
2
+ * LOCK (27.09.2026, follow-up fix after independent verification of the mDM gateway path):
3
+ * a message sent by mDM_send from MCP must be READABLE for the sender and for the recipient — on EVERY
4
+ * key of the same identity, not only on the one that sent it — and the app must tell the TRUTH
5
+ * when it cannot show something.
6
+ *
7
+ * What was measured on 27.09:
8
+ * 1. mDM_send through the gateway created a NEW identity on every call (in-memory keystore per HTTP request).
9
+ * 2. The first fix (alpha.53) gave a stable identity per API KEY and let an agent line
10
+ * replace its bundle in the directory. An identity has MANY active keys (one agent identity: 8, all
11
+ * used within 3 days; 7 of 17 agents have several), so the bundle jumped between identities:
12
+ * the s1. copy opened only under the key that wrote it, and the r1. copies stopped
13
+ * opening for the recipient after the next send with another key.
14
+ * 3. alpha.53 also wrote `txt` + s1. under the API-key seed on a PERSON's key — the app
15
+ * (mdmE2ee.ts readOwnMdmMessage) does not open such a copy and gave a FALSE reason
16
+ * ("sent from another device" / "unlock your identity") instead of "sent by MCP".
17
+ *
18
+ * Fix at the source = the owner's rule (20.09: no E2EE on internal conversations): when one
19
+ * side of the conversation is an agent line, the DM goes IN THE CLEAR — the app does the same (peerIsAgent).
20
+ * Plain text is readable by every key of the line and by the recipient's app on every device; no bundle is
21
+ * needed, so there is nothing to replace. Person↔person stays E2EE, and MCP on a person's
22
+ * key does NOT touch the bundle from their app, writes no s1. copy and marks the envelope `text`.
23
+ *
24
+ * Real cryptography (X3DH + Double Ratchet + AES-GCM + HKDF from @mosadd/crypto), no fake
25
+ * ciphers. Every gateway "request" = a FRESH server with the given API key — like the gateway handler.
26
+ */
27
+
28
+ import { execFileSync } from "node:child_process";
29
+ import { describe, expect, it } from "vitest";
30
+ import type { DmProvider, DmListArgs, DmListResult, DmSendResult } from "@mosadd/providers";
31
+ import { deriveHkdfKey, fromBase64, toBase64 } from "@mosadd/crypto";
32
+ import { mdmTools } from "../tools/mdm.js";
33
+ import { createMosaddServer, defaultProviders } from "../server.js";
34
+ import {
35
+ SeededMdmKeyStore,
36
+ decryptFromPeer,
37
+ deriveMdmSeedFromSecret,
38
+ deriveOwnMaterialFromSeed,
39
+ encryptForPeer,
40
+ fetchVerifiedBundle,
41
+ sealForPeerRecoverable,
42
+ serializePublicBundle,
43
+ type MdmKeyStore,
44
+ } from "../crypto/mdm-session.js";
45
+ import type { DmMessageExt, DmSendArgsExt } from "../providers/supabase-dm.js";
46
+ import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
47
+ import type { MosaddToolContext } from "../types.js";
48
+
49
+ // ---- a backend shaped like message-send / message-list / prekey directory / identities ----
50
+
51
+ type Row = {
52
+ id: string;
53
+ senderId: string;
54
+ to: string;
55
+ threadId: string;
56
+ payload: Uint8Array;
57
+ messageType: string;
58
+ selfPayload: string | null;
59
+ recipientSelfPayload: string | null;
60
+ };
61
+
62
+ class Backend {
63
+ readonly rows: Row[] = [];
64
+ readonly bundles = new Map<string, Uint8Array>();
65
+ readonly kinds = new Map<string, string>();
66
+ publishes = 0;
67
+ }
68
+
69
+ class Lane implements DmProvider {
70
+ constructor(private readonly b: Backend, private readonly me: string) {}
71
+ async selfId() { return this.me; }
72
+ async selfKind() { return this.b.kinds.get(this.me) ?? null; }
73
+ async peerKind(id: string) { return this.b.kinds.get(id) ?? null; }
74
+ async send(args: DmSendArgsExt): Promise<DmSendResult> {
75
+ const id = `m${this.b.rows.length + 1}`;
76
+ this.b.rows.push({
77
+ id,
78
+ senderId: this.me,
79
+ to: args.to,
80
+ threadId: args.threadId,
81
+ payload: args.payload,
82
+ messageType: args.messageType ?? "text",
83
+ selfPayload: args.selfPayload ?? null,
84
+ recipientSelfPayload: args.recipientSelfPayload ?? null,
85
+ });
86
+ return { id, deliveredAt: new Date(0).toISOString() };
87
+ }
88
+ async list(args: DmListArgs): Promise<DmListResult> {
89
+ // message_list_v2: self_payload only to its sender, recipient_self_payload only to the others.
90
+ const messages: DmMessageExt[] = this.b.rows
91
+ .filter((r) => r.threadId === args.threadId)
92
+ .map((r) => ({
93
+ id: r.id,
94
+ senderId: r.senderId,
95
+ payload: r.payload,
96
+ timestamp: new Date(0).toISOString(),
97
+ threadId: r.threadId,
98
+ messageType: r.messageType,
99
+ selfPayload: r.senderId === this.me ? r.selfPayload : null,
100
+ recipientSelfPayload: r.senderId !== this.me ? r.recipientSelfPayload : null,
101
+ }));
102
+ return { messages, nextCursor: null };
103
+ }
104
+ async publishPrekeyBundle(bundle: Uint8Array) {
105
+ this.b.publishes += 1;
106
+ this.b.bundles.set(this.me, bundle);
107
+ }
108
+ async fetchPrekeyBundle(peerId: string) { return this.b.bundles.get(peerId) ?? null; }
109
+ }
110
+
111
+ const tool = (name: string) => {
112
+ const t = mdmTools.find((x) => x.name === name);
113
+ if (!t) throw new Error(`tool ${name} not found`);
114
+ return t.handler;
115
+ };
116
+
117
+ const noopLog: MosaddToolContext["log"] = () => {};
118
+
119
+ /** One gateway request: a FRESH provider registry built from the API key, like handler.ts. */
120
+ function gatewayRequest(b: Backend, me: string, apiKey: string): MosaddToolContext {
121
+ const providers = defaultProviders(
122
+ { dm: new Lane(b, me), voice: new InMemoryVoiceProvider(me) },
123
+ { mdmSecret: apiKey },
124
+ );
125
+ return { options: { mode: "cloud", hubUrl: "https://mcp.mosadd.com", apiKey }, providers, log: noopLog };
126
+ }
127
+
128
+ /** The app of a person: a seed-anchored keystore with its bundle published (login did it). */
129
+ async function appOf(b: Backend, me: string, seedByte: number) {
130
+ const keys = new SeededMdmKeyStore(new Uint8Array(32).fill(seedByte));
131
+ b.bundles.set(me, serializePublicBundle(await keys.getOwnMaterial()));
132
+ b.kinds.set(me, "human");
133
+ return keys;
134
+ }
135
+
136
+ /** What the app shows for a plaintext row (ircApi decodePayload: base64 → UTF-8 text). */
137
+ const appPlaintext = (row: Row) => new TextDecoder().decode(row.payload);
138
+
139
+ // ---- the app's decisions, algorithm-for-algorithm from apps/web/src/lib/mdmE2ee.ts ----
140
+ // (the drift check at the bottom compares these lines with the app's source on origin/main)
141
+
142
+ async function appOpenAesGcm(tag: string, keyBytes: Uint8Array, sealed: string | null): Promise<string | null> {
143
+ if (!sealed || !sealed.startsWith(tag)) return null;
144
+ const packed = fromBase64(sealed.slice(tag.length));
145
+ if (packed.length <= 12) return null;
146
+ const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["decrypt"]);
147
+ try {
148
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: packed.slice(0, 12) }, key, packed.slice(12));
149
+ return new TextDecoder().decode(pt);
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * readOwnMdmMessage (f95557f), for a device that holds the owner's app seed. Steps 2 (this
157
+ * device's sent memory) is empty by construction: the message was sent by MCP, not this device.
158
+ */
159
+ async function appReadOwn(
160
+ appSeed: Uint8Array,
161
+ appKeys: MdmKeyStore,
162
+ myIdentityId: string,
163
+ row: Row,
164
+ ): Promise<{ text: string; reason: null } | { text: null; reason: "key" | "agent" | "device" }> {
165
+ const selfKey = await deriveHkdfKey(appSeed, { info: new TextEncoder().encode("mosadd-mdm-self-read"), length: 32 });
166
+ const zKopii = await appOpenAesGcm("s1.", selfKey, row.selfPayload);
167
+ if (zKopii != null) return { text: zKopii, reason: null };
168
+ const maKlucz = true;
169
+ const para = row.threadId.slice(3).split(":thread:")[0]!.split(":");
170
+ const doSiebie = para.length === 2 && para[0] === myIdentityId && para[1] === myIdentityId;
171
+ if (doSiebie && maKlucz) {
172
+ try {
173
+ return { text: new TextDecoder().decode(await decryptFromPeer(appKeys, myIdentityId, row.payload)), reason: null };
174
+ } catch { /* fall through */ }
175
+ }
176
+ const kopiaDlaMnie = doSiebie || (!!row.selfPayload && row.selfPayload.startsWith("s1."));
177
+ if (!maKlucz && kopiaDlaMnie) return { text: null, reason: "key" };
178
+ return { text: null, reason: row.messageType === "text" ? "agent" : "device" };
179
+ }
180
+
181
+ const KEY_A = "mosadd_sk_live_0123456789abcdef0123456789abcdef";
182
+ const KEY_B = "mosadd_sk_live_fedcba9876543210fedcba9876543210"; // a second key, active in parallel, same line
183
+ const LINE = "agent-line-identity";
184
+ const OWNER = "owner-identity";
185
+ const PEER = "peer-human-identity";
186
+
187
+ type SendOut = {
188
+ message_id: string;
189
+ encrypted: boolean;
190
+ mode: string;
191
+ identity: string;
192
+ sender_copy: boolean;
193
+ recipient_copy: boolean;
194
+ };
195
+ type ListOut = { messages: Array<{ text: string; sender_identity_id: string; encrypted: boolean }> };
196
+
197
+ describe("mDM_send from MCP — readable on every key, true reasons in the app (lock 27.09)", () => {
198
+ it("KAT: the identity derived from the seed is bit for bit the one the app derives", async () => {
199
+ const seed = new Uint8Array(32).map((_, i) => i + 1);
200
+ const m = await deriveOwnMaterialFromSeed(seed);
201
+ // computed with @noble/curves+hashes 2.0.1 from the mosADD tree (the same ones the web client uses)
202
+ expect(toBase64(m.identity.publicKey)).toBe("kGJhDa1OHhlUYRQ0ZgztQfIucOPLxkdOK2iBJpNEWEU=");
203
+ expect(toBase64(m.signingIdentity.publicKey)).toBe("4XxF9XwcOS25C+G8oS/NGXor6ahKsOklnpq3JUQHfVY=");
204
+ expect(toBase64(m.signedPrekey.pair.publicKey)).toBe("0/QU9p52caXSkyjLx/PH4C/9A/UzOZaPRecMtVBQj0Y=");
205
+ expect(m.signedPrekey.id).toBe(1);
206
+ expect(m.oneTimePrekeys).toHaveLength(0);
207
+ expect(toBase64((await new SeededMdmKeyStore(seed).getSelfKeyBytes())!)).toBe(
208
+ "M3XnFLHiETCzgVS+X/Uvl52BhWL9l1EsorKIOXvmKjI=",
209
+ );
210
+ });
211
+
212
+ it("two gateway requests with the same key = ONE identity (not a new one per call)", async () => {
213
+ const b = new Backend();
214
+ const a = await gatewayRequest(b, LINE, KEY_A).providers.keys.getOwnMaterial();
215
+ const c = await gatewayRequest(b, LINE, KEY_A).providers.keys.getOwnMaterial();
216
+ expect(toBase64(a.identity.publicKey)).toBe(toBase64(c.identity.publicKey));
217
+ expect(toBase64(a.signedPrekey.pair.publicKey)).toBe(toBase64(c.signedPrekey.pair.publicKey));
218
+ });
219
+
220
+ it("agent line, TWO keys alternating: plain txt, every key reads everything, the owner reads in the app, directory untouched", async () => {
221
+ const b = new Backend();
222
+ b.kinds.set(LINE, "agent");
223
+ await appOf(b, OWNER, 7);
224
+
225
+ const s1 = (await tool("mDM_send")({ to: OWNER, text: "report from key A" }, gatewayRequest(b, LINE, KEY_A))) as SendOut;
226
+ const s2 = (await tool("mDM_send")({ to: OWNER, text: "report from key B" }, gatewayRequest(b, LINE, KEY_B))) as SendOut;
227
+ const s3 = (await tool("mDM_send")({ to: OWNER, text: "key A again" }, gatewayRequest(b, LINE, KEY_A))) as SendOut;
228
+ for (const s of [s1, s2, s3]) {
229
+ expect(s).toMatchObject({ encrypted: false, mode: "plaintext_agent_lane", sender_copy: true, recipient_copy: true, identity: "untouched" });
230
+ }
231
+
232
+ // Key directory: ZERO writes — the line has no bundle, so there is nothing to switch.
233
+ expect(b.publishes).toBe(0);
234
+ expect(b.bundles.has(LINE)).toBe(false);
235
+
236
+ for (const row of b.rows) {
237
+ expect(row.messageType).toBe("txt");
238
+ expect(row.selfPayload).toBeNull();
239
+ expect(row.recipientSelfPayload).toBeNull();
240
+ }
241
+ // The owner in the app, on ANY device: plain text, no keys and no ratchet.
242
+ expect(b.rows.map(appPlaintext)).toEqual(["report from key A", "report from key B", "key A again"]);
243
+
244
+ // Sender: EVERY key of the line, fresh request (empty sent memory), reads ALL three.
245
+ for (const k of [KEY_A, KEY_B]) {
246
+ const read = (await tool("mDM_list")({ contact_id: OWNER }, gatewayRequest(b, LINE, k))) as ListOut;
247
+ expect(read.messages.map((m) => m.text)).toEqual(["report from key A", "report from key B", "key A again"]);
248
+ }
249
+ });
250
+
251
+ it("the line's own thread (dm:me:me): written with key A, read with key B", async () => {
252
+ const b = new Backend();
253
+ b.kinds.set(LINE, "agent");
254
+ await tool("mDM_send")({ to: LINE, text: "note to self" }, gatewayRequest(b, LINE, KEY_A));
255
+ const row = b.rows.at(-1)!;
256
+ expect(row.threadId).toBe(`dm:${LINE}:${LINE}`);
257
+ expect(row.messageType).toBe("txt");
258
+ const read = (await tool("mDM_list")({ contact_id: LINE }, gatewayRequest(b, LINE, KEY_B))) as ListOut;
259
+ expect(read.messages.map((m) => m.text)).toEqual(["note to self"]);
260
+ expect(b.publishes).toBe(0);
261
+ });
262
+
263
+ it("a person writes through MCP TO an agent line: in the clear (like peerIsAgent in the app)", async () => {
264
+ const b = new Backend();
265
+ b.kinds.set(LINE, "agent");
266
+ await appOf(b, OWNER, 7);
267
+ const s = (await tool("mDM_send")({ to: LINE, text: "instruction" }, gatewayRequest(b, OWNER, KEY_A))) as SendOut;
268
+ expect(s.mode).toBe("plaintext_agent_lane");
269
+ expect(appPlaintext(b.rows.at(-1)!)).toBe("instruction");
270
+ const lineRead = (await tool("mDM_list")({ contact_id: OWNER }, gatewayRequest(b, LINE, KEY_B))) as ListOut;
271
+ expect(lineRead.messages.map((m) => m.text)).toEqual(["instruction"]);
272
+ });
273
+
274
+ it("a PERSON's key to a person: E2EE, app bundle untouched, no s1., type `text` — the app gives the TRUE reason", async () => {
275
+ const b = new Backend();
276
+ const ownerSeed = new Uint8Array(32).fill(7);
277
+ const ownerApp = await appOf(b, OWNER, 7);
278
+ const ownerBundle = toBase64(b.bundles.get(OWNER)!);
279
+ const peerApp = await appOf(b, PEER, 5);
280
+
281
+ const s = (await tool("mDM_send")({ to: PEER, text: "secret" }, gatewayRequest(b, OWNER, KEY_A))) as SendOut;
282
+ expect(s).toMatchObject({ encrypted: true, mode: "e2ee", identity: "foreign", sender_copy: false, recipient_copy: false });
283
+ const row = b.rows.at(-1)!;
284
+ expect(row.messageType).toBe("text");
285
+ expect(row.selfPayload).toBeNull();
286
+ expect(appPlaintext(row)).not.toContain("secret");
287
+ expect(b.publishes).toBe(0);
288
+ expect(toBase64(b.bundles.get(OWNER)!)).toBe(ownerBundle);
289
+
290
+ // The recipient reads through the ratchet (the envelope carries an X3DH header to THEIR app bundle).
291
+ expect(new TextDecoder().decode(await decryptFromPeer(peerApp, OWNER, row.payload))).toBe("secret");
292
+ // The owner in the app: no content (MCP does not know the app seed) and the reason is TRUE.
293
+ expect(await appReadOwn(ownerSeed, ownerApp, OWNER, row)).toEqual({ text: null, reason: "agent" });
294
+ });
295
+
296
+ // 29.09 (owner decision 28.09: no encryption on agent-line conversations): a note to self from MCP goes IN THE CLEAR —
297
+ // until 28.09 it was an E2EE envelope the app opened with seed keys; now there is nothing to open.
298
+ it("a person's key, note to self: plain txt — the app reads bare text on every device", async () => {
299
+ const b = new Backend();
300
+ await appOf(b, OWNER, 7);
301
+ const s = (await tool("mDM_send")({ to: OWNER, text: "note to self from MCP" }, gatewayRequest(b, OWNER, KEY_A))) as SendOut;
302
+ expect(s).toMatchObject({ encrypted: false, mode: "plaintext_agent_lane", identity: "untouched" });
303
+ const row = b.rows.at(-1)!;
304
+ expect(row.messageType).toBe("txt");
305
+ expect(row.selfPayload).toBeNull();
306
+ expect(appPlaintext(row)).toBe("note to self from MCP");
307
+ expect(b.publishes).toBe(0);
308
+ });
309
+
310
+ it("a person WITHOUT a bundle: MCP does not publish on its own (neither mDM_send nor autoPublishKeys); an explicit mDM_publish_keys may", async () => {
311
+ const b = new Backend();
312
+ b.kinds.set(OWNER, "human");
313
+ await appOf(b, PEER, 5);
314
+ const s = (await tool("mDM_send")({ to: PEER, text: "x" }, gatewayRequest(b, OWNER, KEY_A))) as SendOut;
315
+ expect(s.identity).toBe("absent");
316
+ expect(b.bundles.has(OWNER)).toBe(false);
317
+
318
+ createMosaddServer({ apiKey: KEY_A, autoPublishKeys: true, providers: { dm: new Lane(b, OWNER), voice: new InMemoryVoiceProvider(OWNER) } });
319
+ await new Promise((r) => setTimeout(r, 50));
320
+ expect(b.bundles.has(OWNER)).toBe(false);
321
+ expect(b.publishes).toBe(0);
322
+
323
+ const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, OWNER, KEY_A))) as { published: boolean; identity: string };
324
+ expect(p).toMatchObject({ published: true, identity: "published" });
325
+ });
326
+
327
+ it("an explicit mDM_publish_keys on a person's key does NOT overwrite the app bundle", async () => {
328
+ const b = new Backend();
329
+ await appOf(b, OWNER, 7);
330
+ const before = toBase64(b.bundles.get(OWNER)!);
331
+ const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, OWNER, KEY_A))) as { published: boolean; identity: string; note?: string };
332
+ expect(p).toMatchObject({ published: false, identity: "foreign" });
333
+ expect(p.note).toBeTruthy();
334
+ expect(toBase64(b.bundles.get(OWNER)!)).toBe(before);
335
+ expect(b.publishes).toBe(0);
336
+ });
337
+
338
+ it("autoPublishKeys on an agent line: zero directory writes (none of its keys switches the bundle)", async () => {
339
+ const b = new Backend();
340
+ b.kinds.set(LINE, "agent");
341
+ for (const k of [KEY_A, KEY_B]) {
342
+ createMosaddServer({ apiKey: k, autoPublishKeys: true, providers: { dm: new Lane(b, LINE), voice: new InMemoryVoiceProvider(LINE) } });
343
+ }
344
+ await new Promise((r) => setTimeout(r, 50));
345
+ expect(b.publishes).toBe(0);
346
+ expect(b.bundles.has(LINE)).toBe(false);
347
+ });
348
+
349
+ it("an old E2EE envelope from the owner with an r1. copy (line bundle from before the fix) is still readable in the gateway", async () => {
350
+ const b = new Backend();
351
+ b.kinds.set(LINE, "agent");
352
+ const owner = await appOf(b, OWNER, 7);
353
+ // the line bundle published by alpha.53 from the seed of key A
354
+ b.bundles.set(LINE, serializePublicBundle(await new SeededMdmKeyStore(await deriveMdmSeedFromSecret(KEY_A)).getOwnMaterial()));
355
+ const ownerLane = new Lane(b, OWNER);
356
+ const lineBundle = (await fetchVerifiedBundle(ownerLane, LINE))!;
357
+ const inner = new TextEncoder().encode("instruction from the owner");
358
+ await encryptForPeer(owner, ownerLane, LINE, new TextEncoder().encode("first"));
359
+ const env = await encryptForPeer(owner, ownerLane, LINE, inner);
360
+ await ownerLane.send({
361
+ to: LINE,
362
+ threadId: `dm:${[OWNER, LINE].sort().join(":")}`,
363
+ payload: env,
364
+ messageType: "txt",
365
+ recipientSelfPayload: await sealForPeerRecoverable(owner, lineBundle, inner),
366
+ });
367
+ const read = (await tool("mDM_list")({ contact_id: OWNER }, gatewayRequest(b, LINE, KEY_A))) as ListOut;
368
+ expect(read.messages.find((m) => m.sender_identity_id === OWNER)?.text).toBe("instruction from the owner");
369
+ });
370
+
371
+ // Drift guard against the app: the two rules this fix stands on, read from the app source
372
+ // on origin/main of the mosADD repo (MOSADD_WEB_REPO, else the default path below). Without that repo
373
+ // next to this one (e.g. CI without the sibling tree) the test is skipped, not blindly green.
374
+ const webRepo = process.env.MOSADD_WEB_REPO ?? "C:/Projects/mosADD";
375
+ const appSource = (path: string): string | null => {
376
+ try {
377
+ return execFileSync("git", ["-C", webRepo, "show", `origin/main:${path}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
378
+ } catch {
379
+ return null;
380
+ }
381
+ };
382
+ const mdmE2ee = appSource("apps/web/src/lib/mdmE2ee.ts");
383
+ const ircApi = appSource("apps/web/src/lib/ircApi.ts");
384
+ it.skipIf(!mdmE2ee || !ircApi)("app contract: `text` = reason agent, s1. = my own copy, agent = in the clear", () => {
385
+ expect(mdmE2ee).toContain('reason: msg.message_type === "text" ? "agent" : "device"');
386
+ expect(mdmE2ee).toContain("const kopiaDlaMnie = doSiebie || (!!msg.self_payload && msg.self_payload.startsWith(SELF_TAG));");
387
+ expect(mdmE2ee).toContain('const SELF_TAG = "s1.";');
388
+ expect(ircApi).toContain('input.threadId.startsWith("dm:") && !input.peerIsAgent');
389
+ });
390
+ });
@@ -0,0 +1,112 @@
1
+ /**
2
+ * mIRC_invite — the wrapper that lets a channel created from the toolkit STOP being mute.
3
+ *
4
+ * mIRC_join adds the KEY's identity (the account, usually a human) to a channel, while
5
+ * message-send signs channel posts with the AGENT — so until the agent itself is a member
6
+ * every post 403s `agent_not_in_channel`. channel-members-manage `invite` has done the right
7
+ * thing for a while (own agent → auto_joined, no code); the toolkit just never exposed it.
8
+ *
9
+ * Pinned here, because each would silently regress:
10
+ * 1. the tool exists, is a network tool, and its description names BOTH outcomes;
11
+ * 2. the field-name normalizer does NOT rename `role` → `new_role` for invite — the EF's
12
+ * invite branch reads `body.role`, so the rename would drop every requested role to
13
+ * "member" without an error (set-role keeps the rename: that branch reads `new_role`);
14
+ * 3. mIRC_create's `invite_agents` fan-out never forwards the field to channel-manage,
15
+ * reports per-agent failures in `invites[]`, and never throws the created channel away.
16
+ */
17
+ import { describe, it, expect, vi, beforeEach } from "vitest";
18
+ import type { MosaddTool } from "../types.js";
19
+
20
+ const CHANNEL_ID = "6d0f1c1e-1111-4a2b-9c3d-000000000001";
21
+ const AGENT_A = "0489d4c6-8727-442f-bf83-68747a469492";
22
+ const AGENT_B = "b228b6ae-dda6-4823-9882-40ea91ed1530";
23
+
24
+ const calls: { fn: string; body: Record<string, unknown> }[] = [];
25
+ let inviteReply: (body: Record<string, unknown>) => unknown = () => ({ auto_joined: true, member: {} });
26
+
27
+ vi.mock("../providers/supabase.js", () => ({
28
+ readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
29
+ invokeFunction: async (fn: string, body: Record<string, unknown>) => {
30
+ calls.push({ fn, body });
31
+ if (fn === "channel-manage") return { channel: { id: CHANNEL_ID, name: body.name } };
32
+ if (fn === "channel-members-manage") return inviteReply(body);
33
+ throw new Error(`unexpected edge function ${fn}`);
34
+ },
35
+ }));
36
+
37
+ const ctx = { log: () => {} } as never;
38
+ /** Import after the mock is registered, so the modules under test pick it up. */
39
+ const { mircMembersTools } = await import("../tools/mirc-members.js");
40
+ const { mircTools } = await import("../tools/mirc.js");
41
+
42
+ function tool(list: readonly MosaddTool[], name: string): MosaddTool {
43
+ const t = list.find((x) => x.name === name);
44
+ if (!t) throw new Error(`${name} is not registered`);
45
+ return t;
46
+ }
47
+
48
+ describe("mIRC_invite", () => {
49
+ beforeEach(() => {
50
+ calls.length = 0;
51
+ inviteReply = () => ({ auto_joined: true, member: {} });
52
+ });
53
+
54
+ it("is registered as a network tool whose description names both outcomes", () => {
55
+ const invite = tool(mircMembersTools, "mIRC_invite");
56
+ expect(invite.requires).toBe("network");
57
+ expect(invite.description).toContain("auto_joined");
58
+ expect(invite.description).toContain("invite code");
59
+ });
60
+
61
+ it("sends `role` under its own name — the EF's invite branch reads body.role, not new_role", async () => {
62
+ const invite = tool(mircMembersTools, "mIRC_invite");
63
+ await invite.handler({ channel_id: CHANNEL_ID, identity_id: AGENT_A, role: "moderator" }, ctx);
64
+ expect(calls).toHaveLength(1);
65
+ expect(calls[0].fn).toBe("channel-members-manage");
66
+ expect(calls[0].body).toMatchObject({ action: "invite", channel_id: CHANNEL_ID, target_identity_id: AGENT_A, role: "moderator" });
67
+ expect(calls[0].body).not.toHaveProperty("new_role");
68
+ expect(calls[0].body).not.toHaveProperty("identity_id");
69
+ });
70
+
71
+ it("keeps the role → new_role rename for set-role (the exemption is invite-only)", async () => {
72
+ const setRole = tool(mircMembersTools, "mIRC_set_role");
73
+ await setRole.handler({ channel_id: CHANNEL_ID, identity_id: AGENT_A, role: "admin" }, ctx);
74
+ expect(calls[0].body).toMatchObject({ action: "set-role", new_role: "admin" });
75
+ expect(calls[0].body).not.toHaveProperty("role");
76
+ });
77
+ });
78
+
79
+ describe("mIRC_create invite_agents fan-out", () => {
80
+ beforeEach(() => {
81
+ calls.length = 0;
82
+ inviteReply = () => ({ auto_joined: true, member: {} });
83
+ });
84
+
85
+ it("creates first, then invites each agent; a per-agent failure lands in invites[] and never undoes the channel", async () => {
86
+ inviteReply = (body) => {
87
+ if (body.target_identity_id === AGENT_B) throw new Error("channel-members-manage (400): Already a member of this channel");
88
+ return { auto_joined: true, member: { identity_id: body.target_identity_id } };
89
+ };
90
+ const create = tool(mircTools, "mIRC_create");
91
+ const out = (await create.handler({ name: "ops", access_mode: "open", invite_agents: [AGENT_A, AGENT_B] }, ctx)) as {
92
+ channel: { id: string };
93
+ invites: Array<{ identity_id: string; ok: boolean; auto_joined?: boolean; error?: string }>;
94
+ };
95
+ expect(out.channel.id).toBe(CHANNEL_ID);
96
+ expect(calls.map((c) => c.fn)).toEqual(["channel-manage", "channel-members-manage", "channel-members-manage"]);
97
+ // invite_agents is toolkit-side composition — channel-manage must never see it.
98
+ expect(calls[0].body).not.toHaveProperty("invite_agents");
99
+ expect(calls[1].body).toMatchObject({ action: "invite", channel_id: CHANNEL_ID, target_identity_id: AGENT_A });
100
+ expect(out.invites).toHaveLength(2);
101
+ expect(out.invites[0]).toMatchObject({ identity_id: AGENT_A, ok: true, auto_joined: true });
102
+ expect(out.invites[1]).toMatchObject({ identity_id: AGENT_B, ok: false });
103
+ expect(out.invites[1].error).toContain("Already a member");
104
+ });
105
+
106
+ it("without invite_agents behaves exactly as before — one call, no invites key", async () => {
107
+ const create = tool(mircTools, "mIRC_create");
108
+ const out = (await create.handler({ name: "ops", access_mode: "open" }, ctx)) as Record<string, unknown>;
109
+ expect(calls).toHaveLength(1);
110
+ expect(out).not.toHaveProperty("invites");
111
+ });
112
+ });
@@ -0,0 +1,82 @@
1
+ /**
2
+ * 30.11.2026 — agenci nie słyszeli PTT w kanałach mIRC. message-list (mosADD) oddaje przy notatce ptt/voice
3
+ * `transcript` uprawnieniami czytającego (RLS ptt_transcripts: członek kanału), a mIRC_list_messages wyrzucał to pole:
4
+ * agent dostawał sam „[voice note — 25s]”, choć transkrypt leżał w bazie.
5
+ *
6
+ * Pilnowane:
7
+ * 1. notatka z transkryptem → text „[voice note — 25s] <transkrypcja>” + pole voice;
8
+ * 2. notatka bez transkryptu (jeszcze się robi) → sam znacznik, voice.transcript = null;
9
+ * 3. zwykły tekst bez zmian i bez pola voice;
10
+ * 4. mDM_list składa text tą samą formułą (druga strona rozmowy słyszy).
11
+ *
12
+ * SABOTAŻ (30.11): `text: voiceText(…, glos.voice)` → `text: formatVoiceIfAny(…)` w mirc-messages.ts → czerwone 1.
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import { describe, expect, it, vi } from "vitest";
16
+ import type { MosaddTool } from "../types.js";
17
+ import { voiceText } from "../tools/voice-format.js";
18
+
19
+ const CHANNEL_ID = "d0193de5-7a77-45d0-82e6-673effcc0077";
20
+ const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
21
+ const notatka = b64(JSON.stringify({ audio: "A".repeat(4000), mime: "audio/webm", dur: 25_000 }));
22
+
23
+ vi.mock("../crypto/channel-e2ee.js", () => ({
24
+ decryptChannelPayload: async () => null,
25
+ encryptChannelPayload: async () => null,
26
+ unwrapEnvelopeText: (s: string) => s,
27
+ }));
28
+ vi.mock("../providers/supabase.js", () => ({
29
+ readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
30
+ invokeFunction: async (fn: string) => {
31
+ if (fn === "channel-manage") return { linked_space_id: "space-1" };
32
+ if (fn === "message-list") {
33
+ return {
34
+ messages: [
35
+ { id: "m-ptt", sender_identity_id: "czlowiek", encrypted_payload: notatka, created_at: "2026-11-30T01:45:43Z",
36
+ message_type: "ptt", transcript: "Szuflady mają się zamykać płynnie.", audio_url: null, duration_ms: null },
37
+ { id: "m-ptt-w-drodze", sender_identity_id: "czlowiek", encrypted_payload: notatka, created_at: "2026-11-30T01:46:00Z",
38
+ message_type: "ptt", transcript: null, audio_url: null, duration_ms: null },
39
+ { id: "m-txt", sender_identity_id: "czlowiek", encrypted_payload: b64("zwykły tekst"), created_at: "2026-11-30T01:47:00Z",
40
+ message_type: "txt" },
41
+ ],
42
+ next_before: null,
43
+ };
44
+ }
45
+ throw new Error(`unexpected edge function ${fn}`);
46
+ },
47
+ }));
48
+
49
+ const ctx = { log: () => {} } as never;
50
+ const { mircMessagesTools } = await import("../tools/mirc-messages.js");
51
+ const lista = mircMessagesTools.find((t) => t.name === "mIRC_list_messages") as MosaddTool;
52
+
53
+ describe("PTT w kanale dociera do agenta jako tekst", () => {
54
+ it("1: notatka z transkryptem → „[voice note — 25s] <transkrypcja>” + pole voice", async () => {
55
+ const r = (await lista.handler({ channel_id: CHANNEL_ID }, ctx)) as { messages: Array<Record<string, unknown>> };
56
+ const m = r.messages.find((x) => x.id === "m-ptt")!;
57
+ expect(m.text).toBe("[voice note — 25s] Szuflady mają się zamykać płynnie.");
58
+ expect(m.voice).toEqual({ transcript: "Szuflady mają się zamykać płynnie.", audio_url: null, duration_ms: null });
59
+ });
60
+
61
+ it("2: notatka bez transkryptu → sam znacznik, transcript null", async () => {
62
+ const r = (await lista.handler({ channel_id: CHANNEL_ID }, ctx)) as { messages: Array<Record<string, unknown>> };
63
+ const m = r.messages.find((x) => x.id === "m-ptt-w-drodze")!;
64
+ expect(m.text).toBe("[voice note — 25s]");
65
+ expect((m.voice as { transcript: unknown }).transcript).toBeNull();
66
+ });
67
+
68
+ it("3: zwykły tekst bez zmian i bez pola voice", async () => {
69
+ const r = (await lista.handler({ channel_id: CHANNEL_ID }, ctx)) as { messages: Array<Record<string, unknown>> };
70
+ const m = r.messages.find((x) => x.id === "m-txt")!;
71
+ expect(m.text).toBe("zwykły tekst");
72
+ expect(m).not.toHaveProperty("voice");
73
+ });
74
+
75
+ it("4: voiceText — znacznik z czasu trwania, gdy payload nie niesie znacznika; mDM_list używa tej formuły", () => {
76
+ expect(voiceText("<undecryptable>", { transcript: "raz dwa", duration_ms: 4_400 })).toBe("[voice note — 4s] raz dwa");
77
+ expect(voiceText("", { transcript: " ", duration_ms: null })).toBe("[voice note]");
78
+ expect(voiceText("tekst", undefined)).toBe("tekst");
79
+ const mdm = readFileSync(new URL("../tools/mdm.ts", import.meta.url), "utf8");
80
+ expect(mdm).toContain("m.voice ? { ...m, text: voiceText(m.text, m.voice) } : m");
81
+ });
82
+ });
@@ -0,0 +1,42 @@
1
+ /**
2
+ * mRAG_search `answer` flag — forwarded to rag-query (default false = ranked sources only, no model call).
3
+ */
4
+ import { describe, it, expect, vi, beforeEach } from "vitest";
5
+
6
+ const sent: Record<string, unknown>[] = [];
7
+
8
+ vi.mock("../providers/supabase.js", () => ({
9
+ readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
10
+ invokeFunction: (_fn: string, body: Record<string, unknown>) => {
11
+ sent.push(body);
12
+ return Promise.resolve({ answer: "", sources: [], chunks_found: 0 });
13
+ },
14
+ }));
15
+
16
+ const { knowledgeTools } = await import("../tools/knowledge.js");
17
+ const search = knowledgeTools.find((t) => t.name === "mRAG_search")!;
18
+ const ctx = { log: () => {} } as never;
19
+ const last = () => sent[sent.length - 1];
20
+
21
+ describe("mRAG_search answer flag", () => {
22
+ beforeEach(() => {
23
+ sent.length = 0;
24
+ });
25
+
26
+ it("defaults to answer:false (sources only)", async () => {
27
+ await search.handler({ query: "co pisal Jan" }, ctx);
28
+ expect(last().answer).toBe(false);
29
+ });
30
+
31
+ it("forwards answer:true", async () => {
32
+ await search.handler({ query: "co pisal Jan", answer: true }, ctx);
33
+ expect(last().answer).toBe(true);
34
+ });
35
+
36
+ it("the input schema accepts answer and documents it", () => {
37
+ const shape = (search.inputSchema as unknown as { shape: Record<string, { description?: string }> }).shape;
38
+ expect(shape.answer).toBeDefined();
39
+ expect(shape.answer.description).toMatch(/generated answer/);
40
+ expect(search.description).toMatch(/answer:true/);
41
+ });
42
+ });