@mosadd/mcp 3.0.0-alpha.53 → 3.0.0-alpha.55

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 (51) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-AWKITPZQ.js → chunk-IWUGKLDX.js} +144 -33
  5. package/dist/index.js +1 -1
  6. package/package.json +1 -1
  7. package/src/__tests__/blob-upload.test.ts +93 -93
  8. package/src/__tests__/channel-e2ee.test.ts +62 -62
  9. package/src/__tests__/flota-jawnie.test.ts +244 -0
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +182 -182
  12. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  13. package/src/__tests__/mdm-mcp-readable.test.ts +390 -284
  14. package/src/__tests__/mirc-invite.test.ts +112 -112
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/server.test.ts +71 -71
  17. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  18. package/src/bin/login.ts +138 -138
  19. package/src/bin/mcp.ts +145 -145
  20. package/src/config.ts +66 -66
  21. package/src/crypto/channel-e2ee.ts +288 -288
  22. package/src/crypto/mdm-session.ts +842 -798
  23. package/src/index.ts +19 -19
  24. package/src/observability/sentry.ts +79 -79
  25. package/src/providers/memory-voice.ts +79 -79
  26. package/src/providers/supabase-dm.ts +202 -174
  27. package/src/providers/supabase-voice.ts +91 -91
  28. package/src/server.ts +195 -186
  29. package/src/tools/actions.ts +166 -166
  30. package/src/tools/attachments.ts +276 -276
  31. package/src/tools/capabilities.ts +70 -70
  32. package/src/tools/channel-payload.ts +69 -0
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge.ts +344 -344
  36. package/src/tools/mail-aliases.ts +25 -25
  37. package/src/tools/mail-provenance.ts +137 -137
  38. package/src/tools/mail.ts +403 -403
  39. package/src/tools/mdm-as-agent.ts +126 -126
  40. package/src/tools/mdm.ts +140 -45
  41. package/src/tools/mirc-edge.ts +196 -196
  42. package/src/tools/mirc-members.ts +287 -287
  43. package/src/tools/mirc-messages.ts +9 -13
  44. package/src/tools/mirc.ts +308 -308
  45. package/src/tools/mroom-messages.ts +4 -12
  46. package/src/tools/mroom.ts +221 -221
  47. package/src/tools/mtalk.ts +131 -131
  48. package/src/tools/presence.ts +442 -442
  49. package/src/tools/voice-format.ts +28 -28
  50. package/src/types.ts +121 -121
  51. package/src/voice/floor.ts +132 -132
@@ -0,0 +1,244 @@
1
+ /**
2
+ * ZAMEK „ZERO SZYFROWANIA Z FLOTA" (29.09.2026, rozkaz Krola 28.09: „sciagnij te jebane
3
+ * szyfrowanie z naszych rozmow w kazdym kanale i w kazdej tozsamosci").
4
+ *
5
+ * Dwie reguly bramy MCP, obie zmierzone jako zepsute 28–29.09 (Public\ZERO-SZYFROWANIA-29-09,
6
+ * D1 §3 i S1 §1b):
7
+ *
8
+ * c1 — DEKODER KANALU. #adm i #command sa otwarte, bez klucza grupowego. Aplikacja zapisuje
9
+ * tekst kanalu jako goly UTF-8 w base64 (apps/web ircApi.ts `encodePayload`). Stary dekoder
10
+ * (`mirc-messages.ts` / `mroom-messages.ts` `unpackPayload`) znal tylko koperte JSON, wiec
11
+ * KAZDY wpis Krola czytal sie liniom jako "<ciphertext>" (f159c8d7, 776b3e9a na #adm).
12
+ * Teraz: jawny tekst = tekst. "<ciphertext>" zostaje tylko dla prawdziwej koperty klucza
13
+ * grupowego {iv,ciphertext,hmac}, do ktorej linia nie ma klucza (i dla bajtow nie-UTF-8).
14
+ *
15
+ * b1 — mDM_send DO FLOTY JAWNIE. Gdy ktoras strona to linia agenta ALBO to wiadomosc do siebie
16
+ * (to === selfId), wysylka idzie sciezka jawna: encrypted:false, reason:"fleet_plaintext".
17
+ * Czlowiek↔czlowiek zostaje E2EE bez zmian (koperta X3DH + Double Ratchet).
18
+ *
19
+ * Kazdy zamek sprawdzony na czerwono przed naprawa (kod alpha.54) i pod sabotazem po naprawie.
20
+ */
21
+ import { describe, expect, it, vi, beforeEach } from "vitest";
22
+ import type { DmProvider, DmListArgs, DmListResult, DmSendResult } from "@mosadd/providers";
23
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
24
+ import type { DmSendArgsExt } from "../providers/supabase-dm.js";
25
+
26
+ // ---- message-list / channel-manage stand-in (the only EFs the list tools call) ----
27
+
28
+ type StoredRow = { id: string; sender_identity_id: string; encrypted_payload: string; created_at: string };
29
+ let storedRows: StoredRow[] = [];
30
+ /** channel id → the line holds that channel's group key and opens these payloads */
31
+ let groupKeyOpens: (channelId: string, payload: string) => string | null = () => null;
32
+
33
+ vi.mock("../providers/supabase.js", async (importOriginal) => ({
34
+ ...(await importOriginal<typeof import("../providers/supabase.js")>()),
35
+ readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
36
+ invokeFunction: async (fn: string) => {
37
+ if (fn === "message-list") return { messages: storedRows, next_before: null };
38
+ throw new Error(`unexpected edge function ${fn}`);
39
+ },
40
+ }));
41
+
42
+ vi.mock("../crypto/channel-e2ee.js", async (importOriginal) => ({
43
+ ...(await importOriginal<typeof import("../crypto/channel-e2ee.js")>()),
44
+ decryptChannelPayload: async (channelId: string, payload: string) => groupKeyOpens(channelId, payload),
45
+ encryptChannelPayload: async () => null,
46
+ }));
47
+
48
+ const { mircMessagesTools } = await import("../tools/mirc-messages.js");
49
+ const { mroomMessagesTools } = await import("../tools/mroom-messages.js");
50
+ const { mdmTools } = await import("../tools/mdm.js");
51
+ const { defaultProviders } = await import("../server.js");
52
+ const { InMemoryVoiceProvider } = await import("../providers/memory-voice.js");
53
+ const { SeededMdmKeyStore, serializePublicBundle, isE2eeEnvelope, decryptFromPeer } = await import(
54
+ "../crypto/mdm-session.js"
55
+ );
56
+
57
+ const handler = (list: readonly MosaddTool[], name: string) => {
58
+ const t = list.find((x) => x.name === name);
59
+ if (!t) throw new Error(`tool ${name} not registered`);
60
+ return t.handler;
61
+ };
62
+ const noopLog: MosaddToolContext["log"] = () => {};
63
+ const listCtx = { log: noopLog } as unknown as MosaddToolContext;
64
+
65
+ /** Exactly what the app stores for a channel post: base64 of the UTF-8 bytes (ircApi encodePayload). */
66
+ const appEncode = (text: string) => Buffer.from(new TextEncoder().encode(text)).toString("base64");
67
+ const b64json = (obj: unknown) => Buffer.from(JSON.stringify(obj), "utf8").toString("base64");
68
+
69
+ const ADM = "6c251ebf-acb4-4f49-bd9a-7fc28e5cfee6";
70
+ const KING = "king-identity";
71
+ const LINE = "general-line-identity";
72
+ const PEER = "peer-human-identity";
73
+ // Synthetic (the repo is public — no real message of the King goes into a fixture): Polish
74
+ // diacritics, an em dash, an @mention, a newline and an emoji, like the King writes.
75
+ const KING_TEXT = "Kto dowodzi flotą? Zgłoście się na #adm — żółć, źdźbło 🦞\n@all baczność";
76
+
77
+ type ListOut = { messages: Array<{ id: string; text: string }> };
78
+
79
+ async function readChannel(rows: Array<[string, string]>): Promise<string[]> {
80
+ storedRows = rows.map(([id, payload], i) => ({
81
+ id,
82
+ sender_identity_id: KING,
83
+ encrypted_payload: payload,
84
+ created_at: new Date(i * 1000).toISOString(),
85
+ }));
86
+ const out = (await handler(mircMessagesTools, "mIRC_list_messages")(
87
+ { channel_id: ADM, space_id: "space-adm", limit: 50 },
88
+ listCtx,
89
+ )) as ListOut;
90
+ return out.messages.map((m) => m.text);
91
+ }
92
+
93
+ describe("c1 — dekoder kanalu: tekst Krola czyta sie jako tekst, <ciphertext> tylko dla zamknietej koperty", () => {
94
+ beforeEach(() => {
95
+ storedRows = [];
96
+ groupKeyOpens = () => null;
97
+ });
98
+
99
+ it("wpis Krola z aplikacji (goly UTF-8 w base64) na otwartym #adm → czytelny tekst, nie <ciphertext>", async () => {
100
+ const texts = await readChannel([
101
+ ["f159c8d7", appEncode(KING_TEXT)],
102
+ ["776b3e9a", appEncode("@all bacznosc")],
103
+ ]);
104
+ expect(texts).toEqual([KING_TEXT, "@all bacznosc"]);
105
+ expect(texts).not.toContain("<ciphertext>");
106
+ });
107
+
108
+ it("koperta mosadd.chat.v1 z narzedzia (linie) → jej tekst, jak dotad", async () => {
109
+ const texts = await readChannel([
110
+ ["line-1", b64json({ v: "mosadd.chat.v1", type: "text", text: "meldunek linii", reply_to: null })],
111
+ ]);
112
+ expect(texts).toEqual(["meldunek linii"]);
113
+ });
114
+
115
+ it("koperta klucza grupowego {iv,ciphertext,hmac} BEZ klucza → <ciphertext> zostaje", async () => {
116
+ const texts = await readChannel([["sealed", b64json({ iv: "AAAAAAAAAAAAAAAA", ciphertext: "c2VhbGVk", hmac: "aG1hYw==" })]]);
117
+ expect(texts).toEqual(["<ciphertext>"]);
118
+ });
119
+
120
+ it("koperta klucza grupowego, linia MA klucz → odszyfrowany tekst (sciezka bez zmian)", async () => {
121
+ const sealed = b64json({ iv: "AAAAAAAAAAAAAAAA", ciphertext: "c2VhbGVk", hmac: "aG1hYw==" });
122
+ groupKeyOpens = (_c, p) => (p === sealed ? JSON.stringify({ v: "mosadd.chat.v1", type: "text", text: "z klucza" }) : null);
123
+ expect(await readChannel([["sealed", sealed]])).toEqual(["z klucza"]);
124
+ });
125
+
126
+ it("koperta ratchetu mDM (v: mosadd.e2ee.*) wklejona w kanal → <ciphertext>", async () => {
127
+ const texts = await readChannel([["e2ee", b64json({ v: "mosadd.e2ee.v2", dh: "x", n: 0, ct: "y" })]]);
128
+ expect(texts).toEqual(["<ciphertext>"]);
129
+ });
130
+
131
+ it("bajty nie-UTF-8 → <ciphertext> (to nie slowa)", async () => {
132
+ const texts = await readChannel([["bin", Buffer.from([0xff, 0xfe, 0x00, 0x81, 0xc3]).toString("base64")]]);
133
+ expect(texts).toEqual(["<ciphertext>"]);
134
+ });
135
+
136
+ it("glos {audio, mime, dur} → znacznik notatki glosowej (formatVoiceIfAny bez zmian)", async () => {
137
+ const texts = await readChannel([["voice", b64json({ audio: "A".repeat(2000), mime: "audio/webm", dur: 4200 })]]);
138
+ expect(texts).toEqual(["[voice note — 4s]"]);
139
+ });
140
+
141
+ it("mROOM: ta sama regula — tekst z aplikacji czyta sie jako tekst", async () => {
142
+ storedRows = [{ id: "r1", sender_identity_id: KING, encrypted_payload: appEncode(KING_TEXT), created_at: new Date(0).toISOString() }];
143
+ const out = (await handler(mroomMessagesTools, "mROOM_list_messages")({ room_id: "room-1" }, listCtx)) as ListOut;
144
+ expect(out.messages.map((m) => m.text)).toEqual([KING_TEXT]);
145
+ });
146
+ });
147
+
148
+ // ---- b1: mDM_send — an in-memory backend shaped like message-send / identities / prekeys ----
149
+
150
+ type Row = { senderId: string; to: string; threadId: string; payload: Uint8Array; messageType: string };
151
+
152
+ class Backend {
153
+ readonly rows: Row[] = [];
154
+ readonly bundles = new Map<string, Uint8Array>();
155
+ readonly kinds = new Map<string, string>();
156
+ }
157
+
158
+ class Lane implements DmProvider {
159
+ constructor(private readonly b: Backend, private readonly me: string) {}
160
+ async selfId() { return this.me; }
161
+ async selfKind() { return this.b.kinds.get(this.me) ?? null; }
162
+ async peerKind(id: string) { return this.b.kinds.get(id) ?? null; }
163
+ async send(args: DmSendArgsExt): Promise<DmSendResult> {
164
+ this.b.rows.push({ senderId: this.me, to: args.to, threadId: args.threadId, payload: args.payload, messageType: args.messageType ?? "text" });
165
+ return { id: `m${this.b.rows.length}`, deliveredAt: new Date(0).toISOString() };
166
+ }
167
+ async list(_args: DmListArgs): Promise<DmListResult> { return { messages: [], nextCursor: null }; }
168
+ async publishPrekeyBundle(bundle: Uint8Array) { this.b.bundles.set(this.me, bundle); }
169
+ async fetchPrekeyBundle(peerId: string) { return this.b.bundles.get(peerId) ?? null; }
170
+ }
171
+
172
+ const KEY = "mosadd_sk_live_0123456789abcdef0123456789abcdef";
173
+ const gatewayRequest = (b: Backend, me: string): MosaddToolContext => ({
174
+ options: { mode: "cloud", hubUrl: "https://mcp.mosadd.com", apiKey: KEY },
175
+ providers: defaultProviders({ dm: new Lane(b, me), voice: new InMemoryVoiceProvider(me) }, { mdmSecret: KEY }),
176
+ log: noopLog,
177
+ });
178
+
179
+ /** A person with the app: kind human, prekey bundle published by the app at login. */
180
+ async function person(b: Backend, id: string, seedByte: number) {
181
+ const keys = new SeededMdmKeyStore(new Uint8Array(32).fill(seedByte));
182
+ b.bundles.set(id, serializePublicBundle(await keys.getOwnMaterial()));
183
+ b.kinds.set(id, "human");
184
+ return keys;
185
+ }
186
+
187
+ type SendOut = { encrypted: boolean; reason?: string; mode: string };
188
+ const send = (b: Backend, from: string, to: string, text: string) =>
189
+ handler(mdmTools, "mDM_send")({ to, text }, gatewayRequest(b, from)) as Promise<SendOut>;
190
+ const plain = (row: Row) => new TextDecoder().decode(row.payload);
191
+
192
+ describe("b1 — mDM_send: z liniami floty i z Krolem zawsze jawnie, czlowiek↔czlowiek E2EE", () => {
193
+ it("linia agenta → Krol: encrypted:false, reason fleet_plaintext, Krol czyta goly tekst", async () => {
194
+ const b = new Backend();
195
+ b.kinds.set(LINE, "agent");
196
+ await person(b, KING, 7);
197
+ const s = await send(b, LINE, KING, "meldunek");
198
+ expect(s).toMatchObject({ encrypted: false, reason: "fleet_plaintext" });
199
+ expect(b.rows.at(-1)!.messageType).toBe("txt");
200
+ expect(plain(b.rows.at(-1)!)).toBe("meldunek");
201
+ });
202
+
203
+ it("Krol (klucz czlowieka) → linia agenta: jawnie, mimo ze linia ma stary pek", async () => {
204
+ const b = new Backend();
205
+ b.kinds.set(LINE, "agent");
206
+ await person(b, KING, 7);
207
+ b.bundles.set(LINE, serializePublicBundle(await new SeededMdmKeyStore(new Uint8Array(32).fill(9)).getOwnMaterial()));
208
+ const s = await send(b, KING, LINE, "rozkaz");
209
+ expect(s).toMatchObject({ encrypted: false, reason: "fleet_plaintext" });
210
+ expect(plain(b.rows.at(-1)!)).toBe("rozkaz");
211
+ });
212
+
213
+ it("Krol pisze do SIEBIE (to === selfId) przez MCP: jawnie — zero kopert we wlasnym watku", async () => {
214
+ const b = new Backend();
215
+ await person(b, KING, 7);
216
+ const s = await send(b, KING, KING, "notatka do siebie");
217
+ expect(s).toMatchObject({ encrypted: false, reason: "fleet_plaintext" });
218
+ const row = b.rows.at(-1)!;
219
+ expect(row.threadId).toBe(`dm:${KING}:${KING}`);
220
+ expect(isE2eeEnvelope(row.payload)).toBe(false);
221
+ expect(plain(row)).toBe("notatka do siebie");
222
+ });
223
+
224
+ it("czlowiek → czlowiek: E2EE zostaje — koperta ratchetu, tekstu nie widac, odbiorca otwiera", async () => {
225
+ const b = new Backend();
226
+ await person(b, KING, 7);
227
+ const peerKeys = await person(b, PEER, 5);
228
+ const s = await send(b, KING, PEER, "tajne");
229
+ expect(s).toMatchObject({ encrypted: true, mode: "e2ee" });
230
+ expect(s.reason).not.toBe("fleet_plaintext");
231
+ const row = b.rows.at(-1)!;
232
+ expect(isE2eeEnvelope(row.payload)).toBe(true);
233
+ expect(plain(row)).not.toContain("tajne");
234
+ expect(new TextDecoder().decode(await decryptFromPeer(peerKeys, KING, row.payload))).toBe("tajne");
235
+ });
236
+
237
+ it("opisy narzedzi: mDM_send_unencrypted nie jest 'DEPRECATED / prefer mDM_send', obie mowia: floty zawsze jawnie", () => {
238
+ const d = (n: string) => mdmTools.find((t) => t.name === n)!.description;
239
+ expect(d("mDM_send_unencrypted")).not.toMatch(/DEPRECATED|Prefer mDM_send|Will be removed/i);
240
+ for (const n of ["mDM_send", "mDM_send_unencrypted"]) {
241
+ expect(d(n)).toMatch(/fleet lines and with the King: ALWAYS in the clear/);
242
+ }
243
+ });
244
+ });
@@ -1,139 +1,139 @@
1
- /**
2
- * Golden-path E2E: the day-1 "done" bar for the provider-abstraction seam.
3
- *
4
- * Proves a carrier-aware HOST (e.g. cymru-os) can inject its own transport
5
- * under mDM without mosadd-os knowing anything about that transport:
6
- * 1. host learns capabilities (comms_capabilities) and sees mDM_send = "any"
7
- * (usable off-grid over radio),
8
- * 2. host injects a fake RadioProvider,
9
- * 3. agent calls mDM_send,
10
- * 4. the opaque payload bytes actually arrive at the injected provider,
11
- * 5. they round-trip back out via mDM_list.
12
- *
13
- * This is the "is it sp, not just written" check the whole 2144 task hinges on.
14
- */
15
-
16
- import { describe, expect, it } from "vitest";
17
- import type {
18
- DmProvider,
19
- DmSendArgs,
20
- DmListArgs,
21
- DmSendResult,
22
- DmListResult,
23
- } from "@mosadd/providers";
24
- import { mdmTools } from "../tools/mdm.js";
25
- import { makeCapabilitiesTool } from "../tools/capabilities.js";
26
- import { allTools } from "../tools/index.js";
27
- import { createMosaddServer } from "../server.js";
28
- import { InMemoryMdmKeyStore } from "../crypto/mdm-session.js";
29
- import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
30
- import type { MosaddToolContext, ProviderRegistry } from "../types.js";
31
-
32
- /** Stand-in for a host-supplied radio transport: captures the bytes it's asked
33
- * to send, and replays them on list — i.e. "the message reached the link". */
34
- class FakeRadioDmProvider implements DmProvider {
35
- public readonly sent: DmSendArgs[] = [];
36
- private bundle: Uint8Array | null = null;
37
- async selfId(): Promise<string> {
38
- return "radio:self-callsign";
39
- }
40
- async send(args: DmSendArgs): Promise<DmSendResult> {
41
- this.sent.push(args);
42
- return { id: `radio-${this.sent.length}`, deliveredAt: new Date(0).toISOString() };
43
- }
44
- async list(args: DmListArgs): Promise<DmListResult> {
45
- return {
46
- messages: this.sent
47
- .filter((s) => s.threadId === args.threadId)
48
- .map((s, i) => ({
49
- id: `radio-${i + 1}`,
50
- senderId: "radio:self-callsign",
51
- payload: s.payload,
52
- timestamp: new Date(0).toISOString(),
53
- threadId: s.threadId,
54
- })),
55
- nextCursor: null,
56
- };
57
- }
58
- async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
59
- this.bundle = bundle;
60
- }
61
- async fetchPrekeyBundle(): Promise<Uint8Array | null> {
62
- return this.bundle;
63
- }
64
- }
65
-
66
- function makeCtx(providers: { dm: DmProvider; keys?: ProviderRegistry["keys"] }): MosaddToolContext {
67
- return {
68
- options: { mode: "local", hubUrl: "https://mcp.mosadd.com" },
69
- providers: {
70
- dm: providers.dm,
71
- keys: providers.keys ?? new InMemoryMdmKeyStore(),
72
- voice: new InMemoryVoiceProvider("radio:self-callsign"),
73
- },
74
- log: () => {},
75
- };
76
- }
77
-
78
- const getTool = (name: string) => {
79
- const t = mdmTools.find((x) => x.name === name);
80
- if (!t) throw new Error(`tool ${name} not found`);
81
- return t;
82
- };
83
-
84
- describe("golden path — host injects transport under mDM", () => {
85
- it("step 1: comms_capabilities reports mDM_send usable over any carrier", async () => {
86
- const capTool = makeCapabilitiesTool(allTools);
87
- const manifest = (await capTool.handler({}, makeCtx({ dm: new FakeRadioDmProvider() }))) as {
88
- by_requirement: Record<string, string[]>;
89
- };
90
- expect(manifest.by_requirement.any).toContain("mDM_send");
91
- });
92
-
93
- it("steps 2-4: the deprecated plaintext path delivers opaque bytes to the injected provider", async () => {
94
- // This proves the TRANSPORT seam (2144): mDM_send_unencrypted packs a
95
- // plaintext envelope and the bytes reach the injected provider verbatim.
96
- // (mDM_send is now E2EE — its own round-trip is covered in mdm-e2ee.test.ts.)
97
- const radio = new FakeRadioDmProvider();
98
- const ctx = makeCtx({ dm: radio });
99
-
100
- const send = getTool("mDM_send_unencrypted");
101
- const result = (await send.handler(
102
- { to: "bob-callsign", text: "rendezvous at grid 4471, 0600" },
103
- ctx,
104
- )) as { message_id: string; thread_id: string };
105
-
106
- // The bytes actually reached the transport.
107
- expect(radio.sent).toHaveLength(1);
108
- expect(radio.sent[0]!.to).toBe("bob-callsign");
109
- expect(radio.sent[0]!.payload).toBeInstanceOf(Uint8Array);
110
- expect(radio.sent[0]!.payload.byteLength).toBeGreaterThan(0);
111
- expect(result.message_id).toBe("radio-1");
112
-
113
- // The payload is opaque to the provider but carries our text under the hood.
114
- // 2026-08-25: plaintext lane is RAW utf8 text (native app format), not a JSON
115
- // envelope — packPlaintextPayload change, unpack tolerates both shapes.
116
- const decoded = Buffer.from(radio.sent[0]!.payload).toString("utf8");
117
- expect(decoded).toBe("rendezvous at grid 4471, 0600");
118
- });
119
-
120
- it("step 5: mDM_list round-trips the message back through the same provider", async () => {
121
- const radio = new FakeRadioDmProvider();
122
- const ctx = makeCtx({ dm: radio });
123
-
124
- await getTool("mDM_send_unencrypted").handler({ to: "bob-callsign", text: "ack" }, ctx);
125
- const listed = (await getTool("mDM_list").handler({ contact_id: "bob-callsign" }, ctx)) as {
126
- messages: Array<{ text: string }>;
127
- };
128
-
129
- expect(listed.messages).toHaveLength(1);
130
- expect(listed.messages[0]!.text).toBe("ack");
131
- });
132
-
133
- it("default server wires a DmProvider without a host override (no throw)", () => {
134
- // Network default path: constructing the server must not require a host to
135
- // inject anything (it falls back to the Supabase adapter).
136
- expect(() => createMosaddServer()).not.toThrow();
137
- expect(() => createMosaddServer({ providers: { dm: new FakeRadioDmProvider() } })).not.toThrow();
138
- });
139
- });
1
+ /**
2
+ * Golden-path E2E: the day-1 "done" bar for the provider-abstraction seam.
3
+ *
4
+ * Proves a carrier-aware HOST (e.g. cymru-os) can inject its own transport
5
+ * under mDM without mosadd-os knowing anything about that transport:
6
+ * 1. host learns capabilities (comms_capabilities) and sees mDM_send = "any"
7
+ * (usable off-grid over radio),
8
+ * 2. host injects a fake RadioProvider,
9
+ * 3. agent calls mDM_send,
10
+ * 4. the opaque payload bytes actually arrive at the injected provider,
11
+ * 5. they round-trip back out via mDM_list.
12
+ *
13
+ * This is the "is it sp, not just written" check the whole 2144 task hinges on.
14
+ */
15
+
16
+ import { describe, expect, it } from "vitest";
17
+ import type {
18
+ DmProvider,
19
+ DmSendArgs,
20
+ DmListArgs,
21
+ DmSendResult,
22
+ DmListResult,
23
+ } from "@mosadd/providers";
24
+ import { mdmTools } from "../tools/mdm.js";
25
+ import { makeCapabilitiesTool } from "../tools/capabilities.js";
26
+ import { allTools } from "../tools/index.js";
27
+ import { createMosaddServer } from "../server.js";
28
+ import { InMemoryMdmKeyStore } from "../crypto/mdm-session.js";
29
+ import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
30
+ import type { MosaddToolContext, ProviderRegistry } from "../types.js";
31
+
32
+ /** Stand-in for a host-supplied radio transport: captures the bytes it's asked
33
+ * to send, and replays them on list — i.e. "the message reached the link". */
34
+ class FakeRadioDmProvider implements DmProvider {
35
+ public readonly sent: DmSendArgs[] = [];
36
+ private bundle: Uint8Array | null = null;
37
+ async selfId(): Promise<string> {
38
+ return "radio:self-callsign";
39
+ }
40
+ async send(args: DmSendArgs): Promise<DmSendResult> {
41
+ this.sent.push(args);
42
+ return { id: `radio-${this.sent.length}`, deliveredAt: new Date(0).toISOString() };
43
+ }
44
+ async list(args: DmListArgs): Promise<DmListResult> {
45
+ return {
46
+ messages: this.sent
47
+ .filter((s) => s.threadId === args.threadId)
48
+ .map((s, i) => ({
49
+ id: `radio-${i + 1}`,
50
+ senderId: "radio:self-callsign",
51
+ payload: s.payload,
52
+ timestamp: new Date(0).toISOString(),
53
+ threadId: s.threadId,
54
+ })),
55
+ nextCursor: null,
56
+ };
57
+ }
58
+ async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
59
+ this.bundle = bundle;
60
+ }
61
+ async fetchPrekeyBundle(): Promise<Uint8Array | null> {
62
+ return this.bundle;
63
+ }
64
+ }
65
+
66
+ function makeCtx(providers: { dm: DmProvider; keys?: ProviderRegistry["keys"] }): MosaddToolContext {
67
+ return {
68
+ options: { mode: "local", hubUrl: "https://mcp.mosadd.com" },
69
+ providers: {
70
+ dm: providers.dm,
71
+ keys: providers.keys ?? new InMemoryMdmKeyStore(),
72
+ voice: new InMemoryVoiceProvider("radio:self-callsign"),
73
+ },
74
+ log: () => {},
75
+ };
76
+ }
77
+
78
+ const getTool = (name: string) => {
79
+ const t = mdmTools.find((x) => x.name === name);
80
+ if (!t) throw new Error(`tool ${name} not found`);
81
+ return t;
82
+ };
83
+
84
+ describe("golden path — host injects transport under mDM", () => {
85
+ it("step 1: comms_capabilities reports mDM_send usable over any carrier", async () => {
86
+ const capTool = makeCapabilitiesTool(allTools);
87
+ const manifest = (await capTool.handler({}, makeCtx({ dm: new FakeRadioDmProvider() }))) as {
88
+ by_requirement: Record<string, string[]>;
89
+ };
90
+ expect(manifest.by_requirement.any).toContain("mDM_send");
91
+ });
92
+
93
+ it("steps 2-4: the deprecated plaintext path delivers opaque bytes to the injected provider", async () => {
94
+ // This proves the TRANSPORT seam (2144): mDM_send_unencrypted packs a
95
+ // plaintext envelope and the bytes reach the injected provider verbatim.
96
+ // (mDM_send is now E2EE — its own round-trip is covered in mdm-e2ee.test.ts.)
97
+ const radio = new FakeRadioDmProvider();
98
+ const ctx = makeCtx({ dm: radio });
99
+
100
+ const send = getTool("mDM_send_unencrypted");
101
+ const result = (await send.handler(
102
+ { to: "bob-callsign", text: "rendezvous at grid 4471, 0600" },
103
+ ctx,
104
+ )) as { message_id: string; thread_id: string };
105
+
106
+ // The bytes actually reached the transport.
107
+ expect(radio.sent).toHaveLength(1);
108
+ expect(radio.sent[0]!.to).toBe("bob-callsign");
109
+ expect(radio.sent[0]!.payload).toBeInstanceOf(Uint8Array);
110
+ expect(radio.sent[0]!.payload.byteLength).toBeGreaterThan(0);
111
+ expect(result.message_id).toBe("radio-1");
112
+
113
+ // The payload is opaque to the provider but carries our text under the hood.
114
+ // 2026-08-25: plaintext lane is RAW utf8 text (native app format), not a JSON
115
+ // envelope — packPlaintextPayload change, unpack tolerates both shapes.
116
+ const decoded = Buffer.from(radio.sent[0]!.payload).toString("utf8");
117
+ expect(decoded).toBe("rendezvous at grid 4471, 0600");
118
+ });
119
+
120
+ it("step 5: mDM_list round-trips the message back through the same provider", async () => {
121
+ const radio = new FakeRadioDmProvider();
122
+ const ctx = makeCtx({ dm: radio });
123
+
124
+ await getTool("mDM_send_unencrypted").handler({ to: "bob-callsign", text: "ack" }, ctx);
125
+ const listed = (await getTool("mDM_list").handler({ contact_id: "bob-callsign" }, ctx)) as {
126
+ messages: Array<{ text: string }>;
127
+ };
128
+
129
+ expect(listed.messages).toHaveLength(1);
130
+ expect(listed.messages[0]!.text).toBe("ack");
131
+ });
132
+
133
+ it("default server wires a DmProvider without a host override (no throw)", () => {
134
+ // Network default path: constructing the server must not require a host to
135
+ // inject anything (it falls back to the Supabase adapter).
136
+ expect(() => createMosaddServer()).not.toThrow();
137
+ expect(() => createMosaddServer({ providers: { dm: new FakeRadioDmProvider() } })).not.toThrow();
138
+ });
139
+ });