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

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 (58) hide show
  1. package/CHANGELOG.md +334 -309
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-KVN7LZFW.js → chunk-AWKITPZQ.js} +384 -103
  5. package/dist/index.d.ts +11 -1
  6. package/dist/index.js +1 -1
  7. package/package.json +9 -9
  8. package/src/__tests__/golden-path.test.ts +139 -139
  9. package/src/__tests__/integration.test.ts +182 -182
  10. package/src/__tests__/knowledge-ingest.test.ts +114 -114
  11. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  12. package/src/__tests__/mdm-mcp-readable.test.ts +284 -0
  13. package/src/__tests__/mirc-invite.test.ts +112 -112
  14. package/src/__tests__/mtalk.test.ts +122 -122
  15. package/src/__tests__/server.test.ts +71 -71
  16. package/src/__tests__/serverJsonVersion.test.ts +45 -45
  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/mdm-session.ts +798 -502
  22. package/src/index.ts +19 -19
  23. package/src/observability/sentry.ts +79 -79
  24. package/src/providers/memory-voice.ts +79 -79
  25. package/src/providers/supabase-dm.ts +174 -122
  26. package/src/providers/supabase-voice.ts +91 -91
  27. package/src/providers/supabase.ts +231 -231
  28. package/src/server.ts +186 -162
  29. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -67
  30. package/src/tools/actions.ts +166 -166
  31. package/src/tools/attachments.ts +276 -276
  32. package/src/tools/capabilities.ts +70 -70
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge-graph.ts +186 -186
  36. package/src/tools/knowledge.ts +344 -344
  37. package/src/tools/mail-agentbox.ts +155 -155
  38. package/src/tools/mail-aliases.ts +25 -25
  39. package/src/tools/mail-provenance.ts +137 -137
  40. package/src/tools/mail.ts +403 -403
  41. package/src/tools/mcall.ts +216 -216
  42. package/src/tools/mdm-as-agent.ts +126 -126
  43. package/src/tools/mdm-voice.ts +220 -220
  44. package/src/tools/mdm.ts +119 -17
  45. package/src/tools/mirc-edge.ts +196 -196
  46. package/src/tools/mirc-members.ts +287 -287
  47. package/src/tools/mirc.ts +308 -308
  48. package/src/tools/mroom-messages.ts +142 -142
  49. package/src/tools/mroom.ts +221 -221
  50. package/src/tools/mtalk.ts +131 -131
  51. package/src/tools/murl.ts +314 -314
  52. package/src/tools/presence.ts +442 -442
  53. package/src/tools/ptt-ingest.ts +99 -99
  54. package/src/tools/threat.ts +123 -123
  55. package/src/types.ts +121 -121
  56. package/src/version.ts +8 -8
  57. package/src/voice/floor.ts +132 -132
  58. package/LICENSE +0 -201
@@ -0,0 +1,284 @@
1
+ /**
2
+ * ZAMEK (27.09.2026, nastepstwo LINEAR-6089): koperta wyslana przez mDM_send z MCP ma byc
3
+ * CZYTELNA — u nadawcy i u odbiorcy — a nie tylko „zaszyfrowana".
4
+ *
5
+ * Zmierzone na prod 27.09: mDM_send przez brame mcp.mosadd.com
6
+ * 1. przy kazdym wywolaniu rodzil NOWA tozsamosc (InMemoryMdmKeyStore na zadanie HTTP),
7
+ * 2. nie zapisywal self_payload ani recipient_self_payload,
8
+ * 3. pisal message_type "text" zamiast "txt".
9
+ * Skutek: nadawca nie odczyta wlasnej wiadomosci nigdy wiecej, odbiorca tylko przez ratchet.
10
+ *
11
+ * Prawdziwa kryptografia (X3DH + Double Ratchet + AES-GCM + HKDF z @mosadd/crypto), zero atrap
12
+ * szyfru. Kazde "zadanie" bramy = SWIEZY serwer z tym samym kluczem API — dokladnie jak handler
13
+ * bramy (createMosaddServer per request). Otwieracze "s1."/"r1." w tym pliku sa WIERNA KOPIA
14
+ * algorytmu aplikacji (apps/web/src/lib/mdmE2ee.ts: tryReadOwnSelf / tryOpenPeerRecoverable),
15
+ * a wektory KAT policzone bibliotekami aplikacji (@noble 2.0.1 z drzewa mosADD).
16
+ */
17
+
18
+ import { describe, expect, it } from "vitest";
19
+ import type { DmProvider, DmListArgs, DmListResult, DmSendResult } from "@mosadd/providers";
20
+ import { deriveHkdfKey, deriveSharedSecret, fromBase64, toBase64 } from "@mosadd/crypto";
21
+ import { mdmTools } from "../tools/mdm.js";
22
+ import { defaultProviders } from "../server.js";
23
+ import {
24
+ SeededMdmKeyStore,
25
+ decryptFromPeer,
26
+ deriveOwnMaterialFromSeed,
27
+ parsePublicBundle,
28
+ serializePublicBundle,
29
+ type MdmKeyStore,
30
+ } from "../crypto/mdm-session.js";
31
+ import type { DmMessageExt, DmSendArgsExt } from "../providers/supabase-dm.js";
32
+ import { InMemoryVoiceProvider } from "../providers/memory-voice.js";
33
+ import type { MosaddToolContext } from "../types.js";
34
+
35
+ // ---- a backend shaped like message-send / message-list / prekey directory ----
36
+
37
+ type Row = {
38
+ id: string;
39
+ senderId: string;
40
+ to: string;
41
+ threadId: string;
42
+ payload: Uint8Array;
43
+ messageType: string;
44
+ selfPayload: string | null;
45
+ recipientSelfPayload: string | null;
46
+ };
47
+
48
+ class Backend {
49
+ readonly rows: Row[] = [];
50
+ readonly bundles = new Map<string, Uint8Array>();
51
+ readonly kinds = new Map<string, string>();
52
+ }
53
+
54
+ class Lane implements DmProvider {
55
+ constructor(private readonly b: Backend, private readonly me: string) {}
56
+ async selfId() { return this.me; }
57
+ async selfKind() { return this.b.kinds.get(this.me) ?? null; }
58
+ async send(args: DmSendArgsExt): Promise<DmSendResult> {
59
+ const id = `m${this.b.rows.length + 1}`;
60
+ this.b.rows.push({
61
+ id,
62
+ senderId: this.me,
63
+ to: args.to,
64
+ threadId: args.threadId,
65
+ payload: args.payload,
66
+ messageType: args.messageType ?? "text",
67
+ selfPayload: args.selfPayload ?? null,
68
+ recipientSelfPayload: args.recipientSelfPayload ?? null,
69
+ });
70
+ return { id, deliveredAt: new Date(0).toISOString() };
71
+ }
72
+ async list(args: DmListArgs): Promise<DmListResult> {
73
+ // message_list_v2: self_payload only to its sender, recipient_self_payload only to the others.
74
+ const messages: DmMessageExt[] = this.b.rows
75
+ .filter((r) => r.threadId === args.threadId)
76
+ .map((r) => ({
77
+ id: r.id,
78
+ senderId: r.senderId,
79
+ payload: r.payload,
80
+ timestamp: new Date(0).toISOString(),
81
+ threadId: r.threadId,
82
+ messageType: r.messageType,
83
+ selfPayload: r.senderId === this.me ? r.selfPayload : null,
84
+ recipientSelfPayload: r.senderId !== this.me ? r.recipientSelfPayload : null,
85
+ }));
86
+ return { messages, nextCursor: null };
87
+ }
88
+ async publishPrekeyBundle(bundle: Uint8Array) { this.b.bundles.set(this.me, bundle); }
89
+ async fetchPrekeyBundle(peerId: string) { return this.b.bundles.get(peerId) ?? null; }
90
+ }
91
+
92
+ const tool = (name: string) => {
93
+ const t = mdmTools.find((x) => x.name === name);
94
+ if (!t) throw new Error(`tool ${name} not found`);
95
+ return t.handler;
96
+ };
97
+
98
+ const noopLog: MosaddToolContext["log"] = () => {};
99
+
100
+ /** One gateway request: a FRESH provider registry built from the API key, like handler.ts. */
101
+ function gatewayRequest(b: Backend, me: string, apiKey: string): MosaddToolContext {
102
+ const providers = defaultProviders(
103
+ { dm: new Lane(b, me), voice: new InMemoryVoiceProvider(me) },
104
+ { mdmSecret: apiKey },
105
+ );
106
+ return { options: { mode: "cloud", hubUrl: "https://mcp.mosadd.com", apiKey }, providers, log: noopLog };
107
+ }
108
+
109
+ /** The app of a person: a seed-anchored keystore with its bundle published (login did it). */
110
+ async function appOf(b: Backend, me: string, seedByte: number) {
111
+ const keys = new SeededMdmKeyStore(new Uint8Array(32).fill(seedByte));
112
+ b.bundles.set(me, serializePublicBundle(await keys.getOwnMaterial()));
113
+ b.kinds.set(me, "human");
114
+ return keys;
115
+ }
116
+
117
+ // ---- the app's openers, copied algorithm-for-algorithm from apps/web/src/lib/mdmE2ee.ts ----
118
+
119
+ async function appOpenAesGcm(tag: string, keyBytes: Uint8Array, sealed: string | null): Promise<string | null> {
120
+ if (!sealed || !sealed.startsWith(tag)) return null;
121
+ const packed = fromBase64(sealed.slice(tag.length));
122
+ if (packed.length <= 12) return null;
123
+ const key = await crypto.subtle.importKey("raw", keyBytes as BufferSource, { name: "AES-GCM" }, false, ["decrypt"]);
124
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: packed.slice(0, 12) }, key, packed.slice(12));
125
+ return new TextDecoder().decode(pt);
126
+ }
127
+
128
+ /** tryOpenPeerRecoverable: HKDF(ECDH(my IK priv, SENDER's PUBLISHED IK), info) → AES-GCM. */
129
+ async function appOpenRecipientCopy(b: Backend, me: MdmKeyStore, senderId: string, sealed: string | null) {
130
+ const raw = b.bundles.get(senderId);
131
+ if (!raw) return null;
132
+ const sender = parsePublicBundle(raw);
133
+ const own = await me.getOwnMaterial();
134
+ const secret = await deriveSharedSecret(own.identity.privateKey, sender.identityPublicKey);
135
+ const k = await deriveHkdfKey(secret, {
136
+ info: new TextEncoder().encode("mosadd.mdm.recipient-recoverable.v1"),
137
+ length: 32,
138
+ });
139
+ return appOpenAesGcm("r1.", k, sealed);
140
+ }
141
+
142
+ /** tryReadOwnSelf: HKDF(seed, "mosadd-mdm-self-read") → AES-GCM over "s1.". */
143
+ async function appOpenSelfCopy(seed: Uint8Array, sealed: string | null) {
144
+ const k = await deriveHkdfKey(seed, { info: new TextEncoder().encode("mosadd-mdm-self-read"), length: 32 });
145
+ return appOpenAesGcm("s1.", k, sealed);
146
+ }
147
+
148
+ const API_KEY = "mosadd_sk_live_0123456789abcdef0123456789abcdef";
149
+ const LINE = "general-line-identity";
150
+ const KING = "king-identity";
151
+
152
+ describe("mDM_send z MCP — koperta czytelna u nadawcy i u odbiorcy (zamek 27.09)", () => {
153
+ it("KAT: tozsamosc z ziarna jest bit w bit ta, ktora wylicza aplikacja", async () => {
154
+ const seed = new Uint8Array(32).map((_, i) => i + 1);
155
+ const m = await deriveOwnMaterialFromSeed(seed);
156
+ // policzone @noble/curves+hashes 2.0.1 z drzewa mosADD (tych samych, na ktorych stoi web)
157
+ expect(toBase64(m.identity.publicKey)).toBe("kGJhDa1OHhlUYRQ0ZgztQfIucOPLxkdOK2iBJpNEWEU=");
158
+ expect(toBase64(m.signingIdentity.publicKey)).toBe("4XxF9XwcOS25C+G8oS/NGXor6ahKsOklnpq3JUQHfVY=");
159
+ expect(toBase64(m.signedPrekey.pair.publicKey)).toBe("0/QU9p52caXSkyjLx/PH4C/9A/UzOZaPRecMtVBQj0Y=");
160
+ expect(m.signedPrekey.id).toBe(1);
161
+ expect(m.oneTimePrekeys).toHaveLength(0);
162
+ expect(toBase64((await new SeededMdmKeyStore(seed).getSelfKeyBytes())!)).toBe(
163
+ "M3XnFLHiETCzgVS+X/Uvl52BhWL9l1EsorKIOXvmKjI=",
164
+ );
165
+ });
166
+
167
+ it("dwa zadania bramy z tym samym kluczem = JEDNA tozsamosc (nie nowa co wywolanie)", async () => {
168
+ const b = new Backend();
169
+ const a = await gatewayRequest(b, LINE, API_KEY).providers.keys.getOwnMaterial();
170
+ const c = await gatewayRequest(b, LINE, API_KEY).providers.keys.getOwnMaterial();
171
+ expect(toBase64(a.identity.publicKey)).toBe(toBase64(c.identity.publicKey));
172
+ expect(toBase64(a.signedPrekey.pair.publicKey)).toBe(toBase64(c.signedPrekey.pair.publicKey));
173
+ const other = await gatewayRequest(b, LINE, API_KEY + "ff").providers.keys.getOwnMaterial();
174
+ expect(toBase64(other.identity.publicKey)).not.toBe(toBase64(a.identity.publicKey));
175
+ });
176
+
177
+ it("wysylka linii do Krola: txt + self_payload + recipient_self_payload; oboje czytaja po nowym zadaniu", async () => {
178
+ const b = new Backend();
179
+ b.kinds.set(LINE, "agent");
180
+ const kingSeed = new Uint8Array(32).fill(7);
181
+ const king = await appOf(b, KING, 7);
182
+
183
+ const sent = (await tool("mDM_send")({ to: KING, text: "meldunek: brama czytelna" }, gatewayRequest(b, LINE, API_KEY))) as {
184
+ sender_copy: boolean; recipient_copy: boolean; identity: string; message_id: string;
185
+ };
186
+ expect(sent).toMatchObject({ sender_copy: true, recipient_copy: true });
187
+ expect(["published", "consistent"]).toContain(sent.identity);
188
+
189
+ const row = b.rows.at(-1)!;
190
+ expect(row.messageType).toBe("txt");
191
+ expect(row.selfPayload).toMatch(/^s1\./);
192
+ expect(row.recipientSelfPayload).toMatch(/^r1\./);
193
+ // ciphertext na drucie, nie tekst
194
+ expect(Buffer.from(row.payload).toString("utf8")).not.toContain("meldunek");
195
+ expect(row.selfPayload).not.toContain("meldunek");
196
+
197
+ // NADAWCA: nowe zadanie bramy (inna lambda, pusta pamiec wyslanych) czyta swoja wiadomosc.
198
+ const lineRead = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, API_KEY))) as {
199
+ messages: Array<{ text: string; sender_identity_id: string }>;
200
+ };
201
+ expect(lineRead.messages.map((m) => m.text)).toEqual(["meldunek: brama czytelna"]);
202
+
203
+ // ODBIORCA w aplikacji, BEZ sesji ratchetu (nowe urzadzenie): kopia r1. algorytmem aplikacji.
204
+ expect(await appOpenRecipientCopy(b, king, LINE, row.recipientSelfPayload)).toBe("meldunek: brama czytelna");
205
+ // ODBIORCA przez ratchet (koperta niesie naglowek X3DH do opublikowanego peku Krola).
206
+ const viaRatchet = await decryptFromPeer(new SeededMdmKeyStore(kingSeed), LINE, row.payload);
207
+ expect(new TextDecoder().decode(viaRatchet)).toBe("meldunek: brama czytelna");
208
+
209
+ // Druga wysylka z NOWEGO zadania: ta sama tozsamosc -> pek w katalogu sie nie zmienia.
210
+ const bundleBefore = toBase64(b.bundles.get(LINE)!);
211
+ const second = (await tool("mDM_send")({ to: KING, text: "drugi" }, gatewayRequest(b, LINE, API_KEY))) as { identity: string };
212
+ expect(second.identity).toBe("consistent");
213
+ expect(toBase64(b.bundles.get(LINE)!)).toBe(bundleBefore);
214
+ expect(await appOpenRecipientCopy(b, king, LINE, b.rows.at(-1)!.recipientSelfPayload)).toBe("drugi");
215
+ });
216
+
217
+ it("watek wlasny linii (dm:ja:ja): nadawca czyta z nowego zadania, kopia s1. otwiera sie algorytmem aplikacji", async () => {
218
+ const b = new Backend();
219
+ b.kinds.set(LINE, "agent");
220
+ await tool("mDM_send")({ to: LINE, text: "notatka do siebie" }, gatewayRequest(b, LINE, API_KEY));
221
+ const row = b.rows.at(-1)!;
222
+ expect(row.threadId).toBe(`dm:${LINE}:${LINE}`);
223
+ expect(row.messageType).toBe("txt");
224
+ expect(row.selfPayload).toMatch(/^s1\./);
225
+
226
+ const read = (await tool("mDM_list")({ contact_id: LINE }, gatewayRequest(b, LINE, API_KEY))) as {
227
+ messages: Array<{ text: string }>;
228
+ };
229
+ expect(read.messages.map((m) => m.text)).toEqual(["notatka do siebie"]);
230
+
231
+ // To samo ziarno w aplikacji otwiera kopie wlasna jej algorytmem (tryReadOwnSelf).
232
+ const { deriveMdmSeedFromSecret } = await import("../crypto/mdm-session.js");
233
+ expect(await appOpenSelfCopy(await deriveMdmSeedFromSecret(API_KEY), row.selfPayload)).toBe("notatka do siebie");
234
+ });
235
+
236
+ it("linia agenta ze starym losowym pekiem: pek zastapiony; pek CZLOWIEKA z aplikacji nigdy nie nadpisany", async () => {
237
+ // agent: martwy pek po dawnym losowym przebiegu -> zastapiony stala tozsamoscia
238
+ const b = new Backend();
239
+ b.kinds.set(LINE, "agent");
240
+ const stale = serializePublicBundle(await new SeededMdmKeyStore(new Uint8Array(32).fill(99)).getOwnMaterial());
241
+ b.bundles.set(LINE, stale);
242
+ await appOf(b, KING, 7);
243
+ const r = (await tool("mDM_send")({ to: KING, text: "x" }, gatewayRequest(b, LINE, API_KEY))) as { identity: string };
244
+ expect(r.identity).toBe("published");
245
+ expect(toBase64(b.bundles.get(LINE)!)).not.toBe(toBase64(stale));
246
+
247
+ // czlowiek (klucz Krola uzyty przez agenta): pek aplikacji zostaje, kopii r1. nie ma (bylaby pod zla tozsamoscia)
248
+ const h = new Backend();
249
+ const kingApp = serializePublicBundle(await (await appOf(h, KING, 7)).getOwnMaterial());
250
+ await appOf(h, "peer", 5);
251
+ const hr = (await tool("mDM_send")({ to: "peer", text: "y" }, gatewayRequest(h, KING, API_KEY))) as {
252
+ identity: string; recipient_copy: boolean; sender_copy: boolean;
253
+ };
254
+ expect(hr).toMatchObject({ identity: "foreign", recipient_copy: false, sender_copy: true });
255
+ expect(toBase64(h.bundles.get(KING)!)).toBe(toBase64(kingApp));
256
+ expect(h.rows.at(-1)!.messageType).toBe("txt");
257
+ });
258
+
259
+ it("odbior w MCP: wiadomosc Krola z kopia r1. czytelna w bramie bez sesji ratchetu", async () => {
260
+ const b = new Backend();
261
+ b.kinds.set(LINE, "agent");
262
+ const king = await appOf(b, KING, 7);
263
+ // linia publikuje swoj pek (pierwsze zadanie), Krol pisze z aplikacji z kopia r1.
264
+ await tool("mDM_send")({ to: KING, text: "hej" }, gatewayRequest(b, LINE, API_KEY));
265
+ const { sealForPeerRecoverable, fetchVerifiedBundle, encryptForPeer } = await import("../crypto/mdm-session.js");
266
+ const kingLane = new Lane(b, KING);
267
+ const lineBundle = (await fetchVerifiedBundle(kingLane, LINE))!;
268
+ const inner = new TextEncoder().encode("rozkaz od Krola");
269
+ // ratchet Krola jest juz daleko (n>=1, bez naglowka) — brama go nie ma; ratuje ja r1.
270
+ await encryptForPeer(king, kingLane, LINE, new TextEncoder().encode("pierwsza"));
271
+ const env = await encryptForPeer(king, kingLane, LINE, inner);
272
+ await kingLane.send({
273
+ to: LINE,
274
+ threadId: `dm:${[KING, LINE].sort().join(":")}`,
275
+ payload: env,
276
+ messageType: "txt",
277
+ recipientSelfPayload: await sealForPeerRecoverable(king, lineBundle, inner),
278
+ });
279
+ const read = (await tool("mDM_list")({ contact_id: KING }, gatewayRequest(b, LINE, API_KEY))) as {
280
+ messages: Array<{ text: string; sender_identity_id: string }>;
281
+ };
282
+ expect(read.messages.find((m) => m.sender_identity_id === KING)?.text).toBe("rozkaz od Krola");
283
+ });
284
+ });
@@ -1,112 +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
- });
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
+ });