@mosadd/mcp 3.0.0-alpha.7 → 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 -191
  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 +214 -60
  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-EFTB743G.js +0 -1924
@@ -0,0 +1,390 @@
1
+ /**
2
+ * ZAMEK (27.09.2026, nastepstwo LINEAR-6089, POPRAWKA po niezaleznej weryfikacji toru mdm-brama):
3
+ * wiadomosc wyslana przez mDM_send z MCP ma byc CZYTELNA u nadawcy i u odbiorcy — na KAZDYM
4
+ * kluczu tej samej tozsamosci, nie tylko na tym, ktory ja wyslal — a aplikacja ma mowic PRAWDE,
5
+ * gdy czegos pokazac nie moze.
6
+ *
7
+ * Co zmierzono 27.09:
8
+ * 1. mDM_send przez brame rodzil NOWA tozsamosc co wywolanie (keystore w pamieci na zadanie HTTP).
9
+ * 2. Pierwsza poprawka (alpha.53) dala tozsamosc stala per KLUCZ API i pozwolila linii agenta
10
+ * podmieniac pek w katalogu. Tozsamosc ma WIELE aktywnych kluczy (general@: 8, wszystkie
11
+ * uzywane w 3 dni; 7 z 17 agentow ma po kilka), wiec pek przeskakiwal miedzy tozsamosciami:
12
+ * kopia s1. otwierala sie tylko pod kluczem, ktory ja zapisal, a kopie r1. przestawaly sie
13
+ * otwierac u odbiorcy po nastepnej wysylce innym kluczem.
14
+ * 3. alpha.53 pisala tez `txt` + s1. pod ziarnem z klucza API na kluczu CZLOWIEKA — aplikacja
15
+ * (mdmE2ee.ts readOwnMdmMessage) nie otwiera takiej kopii i podawala FALSZYWY powod
16
+ * („wyslane z innego urzadzenia" / „odblokuj tozsamosc") zamiast „wyslane przez MCP".
17
+ *
18
+ * Naprawa u zrodla = regula Krola (DECYZJE-KROLA 20.09 12:56Z „E2EE wewnetrzne = zero"): gdy
19
+ * strona rozmowy jest linia agenta, DM idzie JAWNIE — tak samo robi aplikacja (peerIsAgent).
20
+ * Jawny tekst czyta kazdy klucz linii i aplikacja odbiorcy na kazdym urzadzeniu; pek nie jest
21
+ * potrzebny, wiec nie ma czego podmieniac. Czlowiek↔czlowiek zostaje E2EE, a MCP na kluczu
22
+ * czlowieka NIE rusza jego peku z aplikacji, nie pisze kopii s1. i znakuje koperte `text`.
23
+ *
24
+ * Prawdziwa kryptografia (X3DH + Double Ratchet + AES-GCM + HKDF z @mosadd/crypto), zero atrap
25
+ * szyfru. Kazde "zadanie" bramy = SWIEZY serwer z danym kluczem API — jak handler bramy.
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"; // druga, rownolegle aktywna, ta sama linia
183
+ const LINE = "general-line-identity";
184
+ const KING = "king-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 z MCP — czytelne na kazdym kluczu, prawdziwe powody w aplikacji (zamek 27.09)", () => {
198
+ it("KAT: tozsamosc z ziarna jest bit w bit ta, ktora wylicza aplikacja", async () => {
199
+ const seed = new Uint8Array(32).map((_, i) => i + 1);
200
+ const m = await deriveOwnMaterialFromSeed(seed);
201
+ // policzone @noble/curves+hashes 2.0.1 z drzewa mosADD (tych samych, na ktorych stoi web)
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("dwa zadania bramy z tym samym kluczem = JEDNA tozsamosc (nie nowa co wywolanie)", 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("linia agenta, DWA klucze naprzemiennie: jawny txt, kazdy klucz czyta wszystko, Krol czyta w aplikacji, katalog nietkniety", async () => {
221
+ const b = new Backend();
222
+ b.kinds.set(LINE, "agent");
223
+ await appOf(b, KING, 7);
224
+
225
+ const s1 = (await tool("mDM_send")({ to: KING, text: "meldunek z klucza A" }, gatewayRequest(b, LINE, KEY_A))) as SendOut;
226
+ const s2 = (await tool("mDM_send")({ to: KING, text: "meldunek z klucza B" }, gatewayRequest(b, LINE, KEY_B))) as SendOut;
227
+ const s3 = (await tool("mDM_send")({ to: KING, text: "znow klucz A" }, 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
+ // Katalog kluczy: ZERO zapisow — pek linii nie istnieje, wiec nie ma czego przestawiac.
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
+ // Krol w aplikacji, na DOWOLNYM urzadzeniu: jawny tekst, bez kluczy i bez ratchetu.
242
+ expect(b.rows.map(appPlaintext)).toEqual(["meldunek z klucza A", "meldunek z klucza B", "znow klucz A"]);
243
+
244
+ // Nadawca: KAZDY klucz linii, swieze zadanie (pusta pamiec wyslanych), czyta WSZYSTKIE trzy.
245
+ for (const k of [KEY_A, KEY_B]) {
246
+ const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, k))) as ListOut;
247
+ expect(read.messages.map((m) => m.text)).toEqual(["meldunek z klucza A", "meldunek z klucza B", "znow klucz A"]);
248
+ }
249
+ });
250
+
251
+ it("watek wlasny linii (dm:ja:ja): zapis kluczem A, odczyt kluczem B", async () => {
252
+ const b = new Backend();
253
+ b.kinds.set(LINE, "agent");
254
+ await tool("mDM_send")({ to: LINE, text: "notatka do siebie" }, 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(["notatka do siebie"]);
260
+ expect(b.publishes).toBe(0);
261
+ });
262
+
263
+ it("czlowiek pisze przez MCP DO linii agenta: jawnie (jak peerIsAgent w aplikacji)", async () => {
264
+ const b = new Backend();
265
+ b.kinds.set(LINE, "agent");
266
+ await appOf(b, KING, 7);
267
+ const s = (await tool("mDM_send")({ to: LINE, text: "rozkaz" }, gatewayRequest(b, KING, KEY_A))) as SendOut;
268
+ expect(s.mode).toBe("plaintext_agent_lane");
269
+ expect(appPlaintext(b.rows.at(-1)!)).toBe("rozkaz");
270
+ const lineRead = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, KEY_B))) as ListOut;
271
+ expect(lineRead.messages.map((m) => m.text)).toEqual(["rozkaz"]);
272
+ });
273
+
274
+ it("klucz CZLOWIEKA do czlowieka: E2EE, pek z aplikacji nietkniety, bez s1., typ `text` — aplikacja mowi PRAWDZIWY powod", async () => {
275
+ const b = new Backend();
276
+ const kingSeed = new Uint8Array(32).fill(7);
277
+ const kingApp = await appOf(b, KING, 7);
278
+ const kingBundle = toBase64(b.bundles.get(KING)!);
279
+ const peerApp = await appOf(b, PEER, 5);
280
+
281
+ const s = (await tool("mDM_send")({ to: PEER, text: "tajne" }, gatewayRequest(b, KING, 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("tajne");
287
+ expect(b.publishes).toBe(0);
288
+ expect(toBase64(b.bundles.get(KING)!)).toBe(kingBundle);
289
+
290
+ // Odbiorca czyta przez ratchet (koperta niesie naglowek X3DH do JEGO peku z aplikacji).
291
+ expect(new TextDecoder().decode(await decryptFromPeer(peerApp, KING, row.payload))).toBe("tajne");
292
+ // Wlasciciel w aplikacji: tresci nie ma (MCP nie zna ziarna aplikacji) i powod jest PRAWDZIWY.
293
+ expect(await appReadOwn(kingSeed, kingApp, KING, row)).toEqual({ text: null, reason: "agent" });
294
+ });
295
+
296
+ // 29.09 (ZERO SZYFROWANIA, rozkaz Krola 28.09): notatka do siebie z MCP idzie JAWNIE — do 28.09
297
+ // byla koperta E2EE, ktora aplikacja otwierala kluczami z ziarna; teraz nie ma czego otwierac.
298
+ it("klucz czlowieka, notatka do siebie: jawny txt — aplikacja czyta goly tekst na kazdym urzadzeniu", async () => {
299
+ const b = new Backend();
300
+ await appOf(b, KING, 7);
301
+ const s = (await tool("mDM_send")({ to: KING, text: "do siebie z MCP" }, gatewayRequest(b, KING, 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("do siebie z MCP");
307
+ expect(b.publishes).toBe(0);
308
+ });
309
+
310
+ it("czlowiek BEZ peku: MCP nie publikuje sam (ani mDM_send, ani autoPublishKeys); jawne mDM_publish_keys moze", async () => {
311
+ const b = new Backend();
312
+ b.kinds.set(KING, "human");
313
+ await appOf(b, PEER, 5);
314
+ const s = (await tool("mDM_send")({ to: PEER, text: "x" }, gatewayRequest(b, KING, KEY_A))) as SendOut;
315
+ expect(s.identity).toBe("absent");
316
+ expect(b.bundles.has(KING)).toBe(false);
317
+
318
+ createMosaddServer({ apiKey: KEY_A, autoPublishKeys: true, providers: { dm: new Lane(b, KING), voice: new InMemoryVoiceProvider(KING) } });
319
+ await new Promise((r) => setTimeout(r, 50));
320
+ expect(b.bundles.has(KING)).toBe(false);
321
+ expect(b.publishes).toBe(0);
322
+
323
+ const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, KING, KEY_A))) as { published: boolean; identity: string };
324
+ expect(p).toMatchObject({ published: true, identity: "published" });
325
+ });
326
+
327
+ it("jawne mDM_publish_keys na kluczu czlowieka NIE nadpisuje peku z aplikacji", async () => {
328
+ const b = new Backend();
329
+ await appOf(b, KING, 7);
330
+ const before = toBase64(b.bundles.get(KING)!);
331
+ const p = (await tool("mDM_publish_keys")({}, gatewayRequest(b, KING, 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(KING)!)).toBe(before);
335
+ expect(b.publishes).toBe(0);
336
+ });
337
+
338
+ it("autoPublishKeys na linii agenta: zero zapisow w katalogu (zaden z jej kluczy nie przestawia peku)", 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("stara koperta E2EE od Krola z kopia r1. (pek linii sprzed poprawki) dalej czytelna w bramie", async () => {
350
+ const b = new Backend();
351
+ b.kinds.set(LINE, "agent");
352
+ const king = await appOf(b, KING, 7);
353
+ // pek linii opublikowany przez alpha.53 z ziarna klucza A
354
+ b.bundles.set(LINE, serializePublicBundle(await new SeededMdmKeyStore(await deriveMdmSeedFromSecret(KEY_A)).getOwnMaterial()));
355
+ const kingLane = new Lane(b, KING);
356
+ const lineBundle = (await fetchVerifiedBundle(kingLane, LINE))!;
357
+ const inner = new TextEncoder().encode("rozkaz od Krola");
358
+ await encryptForPeer(king, kingLane, LINE, new TextEncoder().encode("pierwsza"));
359
+ const env = await encryptForPeer(king, kingLane, LINE, inner);
360
+ await kingLane.send({
361
+ to: LINE,
362
+ threadId: `dm:${[KING, LINE].sort().join(":")}`,
363
+ payload: env,
364
+ messageType: "txt",
365
+ recipientSelfPayload: await sealForPeerRecoverable(king, lineBundle, inner),
366
+ });
367
+ const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, KEY_A))) as ListOut;
368
+ expect(read.messages.find((m) => m.sender_identity_id === KING)?.text).toBe("rozkaz od Krola");
369
+ });
370
+
371
+ // Straznik rozjazdu z aplikacja: dwie reguly, na ktorych stoi ta poprawka, czytane ze zrodla
372
+ // aplikacji na origin/main repo mosADD (MOSADD_WEB_REPO albo C:/Projects/mosADD). Bez repo obok
373
+ // (np. CI bez siostrzanego drzewa) — pominiety, nie zielony na slepo.
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)("kontrakt aplikacji: `text` = powod agent, s1. = kopia dla mnie, agent = jawnie", () => {
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 since LINEAR-5596 (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,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
+ });
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The old cloud (`rooffhgbxafyjcwmwpsy.supabase.co`) is dead; the live backend is `https://api.mosadd.com`.
3
+ * A published package that defaults to the dead host breaks `MOSADD_API_KEY` login (hub-key-exchange never answers),
4
+ * so no source file may carry the old host as a URL. Comments that merely name the project id are fine.
5
+ */
6
+ import { describe, it, expect } from "vitest";
7
+ import { readdirSync, readFileSync, statSync } from "node:fs";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "..");
12
+ const DEAD = /https?:\/\/rooffhgbxafyjcwmwpsy\.supabase\.co/i;
13
+
14
+ function walk(dir: string): string[] {
15
+ return readdirSync(dir).flatMap((n) => {
16
+ const p = join(dir, n);
17
+ if (n === "__tests__" || n === "node_modules") return [];
18
+ return statSync(p).isDirectory() ? walk(p) : /\.(ts|tsx|mjs|js)$/.test(n) ? [p] : [];
19
+ });
20
+ }
21
+
22
+ describe("no dead backend host in the package source", () => {
23
+ it("no source file carries the old supabase host as a URL", () => {
24
+ const hits = walk(SRC).filter((f) => DEAD.test(readFileSync(f, "utf8")));
25
+ expect(hits, `dead host found in: ${hits.join(", ")}`).toEqual([]);
26
+ });
27
+
28
+ it("the default hub-key-exchange endpoint is api.mosadd.com", () => {
29
+ const src = readFileSync(join(SRC, "bin", "mcp.ts"), "utf8");
30
+ expect(src).toMatch(/DEFAULT_EXCHANGE\s*=\s*"https:\/\/api\.mosadd\.com\/functions\/v1\/hub-key-exchange"/);
31
+ });
32
+
33
+ it("the gate fires: the dead host would be caught", () => {
34
+ expect(DEAD.test('const X = "https://rooffhgbxafyjcwmwpsy.supabase.co/functions/v1/hub-key-exchange";')).toBe(true);
35
+ expect(DEAD.test("// project rooffhgbxafyjcwmwpsy, 16.09")).toBe(false);
36
+ });
37
+ });