@mosadd/mcp 3.0.0-alpha.5 → 3.0.0-alpha.51

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 (64) hide show
  1. package/CHANGELOG.md +309 -0
  2. package/LICENSE +201 -201
  3. package/README.md +150 -126
  4. package/dist/bin/mcp.js +42 -3
  5. package/dist/chunk-BTAIZKYT.js +3800 -0
  6. package/dist/index.d.ts +118 -5
  7. package/dist/index.js +7 -3
  8. package/package.json +10 -7
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/golden-path.test.ts +139 -137
  11. package/src/__tests__/integration.test.ts +182 -178
  12. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  14. package/src/__tests__/mirc-invite.test.ts +112 -0
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/presence.test.ts +199 -0
  17. package/src/__tests__/server.test.ts +71 -67
  18. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  19. package/src/__tests__/tool-count-consistency.test.ts +199 -0
  20. package/src/bin/login.ts +138 -138
  21. package/src/bin/mcp.ts +145 -97
  22. package/src/config.ts +66 -66
  23. package/src/crypto/channel-e2ee.ts +288 -0
  24. package/src/crypto/mdm-session.ts +502 -403
  25. package/src/index.ts +19 -17
  26. package/src/observability/sentry.ts +79 -79
  27. package/src/providers/blob-upload.ts +116 -0
  28. package/src/providers/memory-voice.ts +79 -79
  29. package/src/providers/supabase-dm.ts +122 -117
  30. package/src/providers/supabase-voice.ts +91 -91
  31. package/src/providers/supabase.ts +231 -96
  32. package/src/server.ts +162 -105
  33. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  34. package/src/tools/actions.ts +166 -0
  35. package/src/tools/attachments.ts +276 -0
  36. package/src/tools/capabilities.ts +70 -68
  37. package/src/tools/embed.ts +110 -0
  38. package/src/tools/index.ts +181 -51
  39. package/src/tools/knowledge-graph.ts +186 -0
  40. package/src/tools/knowledge.ts +344 -132
  41. package/src/tools/mail-agentbox.ts +155 -0
  42. package/src/tools/mail-aliases.ts +25 -0
  43. package/src/tools/mail-provenance.ts +137 -0
  44. package/src/tools/mail.ts +403 -157
  45. package/src/tools/mcall.ts +216 -216
  46. package/src/tools/mdm-as-agent.ts +126 -0
  47. package/src/tools/mdm-voice.ts +220 -206
  48. package/src/tools/mdm.ts +73 -26
  49. package/src/tools/mirc-edge.ts +196 -190
  50. package/src/tools/mirc-members.ts +287 -177
  51. package/src/tools/mirc-messages.ts +76 -27
  52. package/src/tools/mirc.ts +308 -170
  53. package/src/tools/mroom-messages.ts +142 -142
  54. package/src/tools/mroom.ts +221 -221
  55. package/src/tools/mtalk.ts +131 -121
  56. package/src/tools/murl.ts +314 -0
  57. package/src/tools/presence.ts +442 -0
  58. package/src/tools/ptt-ingest.ts +99 -0
  59. package/src/tools/threat.ts +123 -0
  60. package/src/tools/voice-format.ts +28 -0
  61. package/src/types.ts +121 -85
  62. package/src/version.ts +8 -0
  63. package/src/voice/floor.ts +132 -132
  64. package/dist/chunk-4C36JDTJ.js +0 -1836
@@ -1,1836 +0,0 @@
1
- import {
2
- isSessionExpired,
3
- loadSession
4
- } from "./chunk-Z7WR52GE.js";
5
-
6
- // src/tools/mdm.ts
7
- import { z } from "zod";
8
-
9
- // src/providers/supabase.ts
10
- import { createClient } from "@supabase/supabase-js";
11
- var MissingSupabaseEnvError = class extends Error {
12
- constructor(missing) {
13
- super(
14
- `Missing Supabase credentials: ${missing.join(", ")}. Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`
15
- );
16
- this.name = "MissingSupabaseEnvError";
17
- }
18
- };
19
- function readSupabaseEnv() {
20
- const env = (canonical, legacy) => process.env[canonical] ?? process.env[legacy];
21
- const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
22
- const session = loadSession();
23
- const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
24
- const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
25
- const userJwt = userJwtEnv ?? session?.accessToken;
26
- const missing = [];
27
- if (!url) missing.push("MOSADD_SUPABASE_URL");
28
- if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
29
- if (missing.length) throw new MissingSupabaseEnvError(missing);
30
- if (!userJwtEnv && session && isSessionExpired(session)) {
31
- throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
32
- }
33
- return { url, anonKey, userJwt };
34
- }
35
- function getSupabase(env = readSupabaseEnv()) {
36
- return createClient(env.url, env.anonKey, {
37
- auth: {
38
- persistSession: false,
39
- autoRefreshToken: false,
40
- detectSessionInUrl: false
41
- },
42
- global: env.userJwt ? {
43
- headers: { Authorization: `Bearer ${env.userJwt}` }
44
- } : void 0
45
- });
46
- }
47
- async function invokeFunction(fn, body) {
48
- const client = getSupabase();
49
- const { data, error } = await client.functions.invoke(fn, { body });
50
- if (error) {
51
- const msg = error instanceof Error ? error.message : typeof error?.message === "string" ? error.message : `Edge function ${fn} failed`;
52
- throw new Error(msg);
53
- }
54
- if (data == null) {
55
- throw new Error(`Edge function ${fn} returned no data`);
56
- }
57
- return data;
58
- }
59
-
60
- // src/crypto/mdm-session.ts
61
- import {
62
- decryptBytes,
63
- encryptBytes,
64
- generateEd25519KeyPair,
65
- generateX25519KeyPair,
66
- initializeRatchet,
67
- performX3dh,
68
- performX3dhResponder,
69
- ratchetReceive,
70
- ratchetSend,
71
- signEd25519,
72
- verifyEd25519,
73
- toBase64,
74
- fromBase64
75
- } from "@mosadd/crypto";
76
- var PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1";
77
- var E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1";
78
- var DEFAULT_ONE_TIME_PREKEYS = 8;
79
- var InMemoryMdmKeyStore = class {
80
- material = null;
81
- oneTimeById = /* @__PURE__ */ new Map();
82
- sessions = /* @__PURE__ */ new Map();
83
- sentMessages = /* @__PURE__ */ new Map();
84
- async getOwnMaterial() {
85
- if (this.material) return this.material;
86
- const identity = await generateX25519KeyPair();
87
- const signingIdentity = await generateEd25519KeyPair();
88
- const signedPrekeyPair = await generateX25519KeyPair();
89
- const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
90
- const oneTimePrekeys = [];
91
- for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
92
- const pair = await generateX25519KeyPair();
93
- const id = randomId();
94
- oneTimePrekeys.push({ id, pair });
95
- this.oneTimeById.set(id, pair.privateKey);
96
- }
97
- this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
98
- return this.material;
99
- }
100
- async takeOneTimePrekey(id) {
101
- const priv = this.oneTimeById.get(id);
102
- if (priv) this.oneTimeById.delete(id);
103
- return priv;
104
- }
105
- async getSession(peerId) {
106
- return this.sessions.get(peerId);
107
- }
108
- async putSession(peerId, record) {
109
- this.sessions.set(peerId, record);
110
- }
111
- async putSentMessage(messageId, plaintext) {
112
- this.sentMessages.set(messageId, plaintext);
113
- }
114
- async getSentMessage(messageId) {
115
- return this.sentMessages.get(messageId);
116
- }
117
- };
118
- function randomId() {
119
- return crypto.getRandomValues(new Uint32Array(1))[0];
120
- }
121
- function bundleSigningMessage(dhIdentityPub, signedPrekeyPub) {
122
- const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
123
- msg.set(dhIdentityPub, 0);
124
- msg.set(signedPrekeyPub, dhIdentityPub.length);
125
- return msg;
126
- }
127
- function serializePublicBundle(material) {
128
- const signature = signEd25519(
129
- material.signingIdentity.privateKey,
130
- bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey)
131
- );
132
- const json = JSON.stringify({
133
- v: PREKEY_BUNDLE_VERSION,
134
- ik: toBase64(material.identity.publicKey),
135
- sik: toBase64(material.signingIdentity.publicKey),
136
- spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
137
- opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
138
- sig: toBase64(signature)
139
- });
140
- return new Uint8Array(Buffer.from(json, "utf8"));
141
- }
142
- function parsePublicBundle(bytes) {
143
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
144
- if (obj?.v !== PREKEY_BUNDLE_VERSION) {
145
- throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
146
- }
147
- if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
148
- throw new Error("Prekey bundle is missing its signing identity / signature.");
149
- }
150
- return {
151
- identityPublicKey: fromBase64(obj.ik),
152
- signingIdentityPublicKey: fromBase64(obj.sik),
153
- signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
154
- oneTimePrekeys: (obj.opks ?? []).map((k) => ({
155
- id: k.id,
156
- publicKey: fromBase64(k.pub)
157
- })),
158
- signature: fromBase64(obj.sig)
159
- };
160
- }
161
- function verifyPublicBundle(bundle) {
162
- return verifyEd25519(
163
- bundle.signature,
164
- bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
165
- bundle.signingIdentityPublicKey
166
- );
167
- }
168
- function isE2eeEnvelope(bytes) {
169
- try {
170
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
171
- return obj?.v === E2EE_ENVELOPE_VERSION && typeof obj?.i === "number" && !!obj?.ct;
172
- } catch {
173
- return false;
174
- }
175
- }
176
- function serializeEnvelope(env) {
177
- return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
178
- }
179
- function parseEnvelope(bytes) {
180
- const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
181
- if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
182
- return obj;
183
- }
184
- async function publishOwnPrekeys(keystore, dm) {
185
- const material = await keystore.getOwnMaterial();
186
- await dm.publishPrekeyBundle(serializePublicBundle(material));
187
- return { oneTimePrekeyCount: material.oneTimePrekeys.length };
188
- }
189
- async function encryptForPeer(keystore, dm, peerId, plaintext) {
190
- let session = await keystore.getSession(peerId);
191
- if (!session) {
192
- const raw = await dm.fetchPrekeyBundle(peerId);
193
- if (!raw) {
194
- throw new Error(
195
- `Peer "${peerId}" has not published a prekey bundle yet, so an encrypted session cannot be established. Ask them to run mDM_publish_keys, or use mDM_send_unencrypted (deprecated) for the migration window.`
196
- );
197
- }
198
- const peer = parsePublicBundle(raw);
199
- if (!verifyPublicBundle(peer)) {
200
- throw new Error(
201
- `Prekey bundle for "${peerId}" failed signature verification \u2014 refusing to start an encrypted session (possible tampering / man-in-the-middle).`
202
- );
203
- }
204
- const own = await keystore.getOwnMaterial();
205
- const ephemeral = await generateX25519KeyPair();
206
- const opk = peer.oneTimePrekeys[0];
207
- const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
208
- identityPublicKey: peer.identityPublicKey,
209
- signedPreKeyPublicKey: peer.signedPrekey.publicKey,
210
- oneTimePreKeyPublicKey: opk?.publicKey
211
- });
212
- const ratchet = await initializeRatchet(rootKey, "initiator");
213
- session = {
214
- ratchet,
215
- role: "initiator",
216
- pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id }
217
- };
218
- }
219
- const step = await ratchetSend(session.ratchet);
220
- const ct = await encryptBytes(step.messageKey, plaintext);
221
- const env = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
222
- if (session.pendingHandshake && step.messageIndex === 0) {
223
- env.hdr = {
224
- ik: toBase64(session.pendingHandshake.ik),
225
- ek: toBase64(session.pendingHandshake.ek),
226
- opk: session.pendingHandshake.opkId
227
- };
228
- }
229
- session.pendingHandshake = void 0;
230
- await keystore.putSession(peerId, session);
231
- return serializeEnvelope(env);
232
- }
233
- async function decryptFromPeer(keystore, peerId, envelopeBytes) {
234
- const env = parseEnvelope(envelopeBytes);
235
- let session = await keystore.getSession(peerId);
236
- if (!session) {
237
- if (!env.hdr) {
238
- throw new Error(
239
- `No session with "${peerId}" and the message carries no handshake header \u2014 cannot decrypt.`
240
- );
241
- }
242
- const own = await keystore.getOwnMaterial();
243
- let oneTimePreKeyPrivateKey;
244
- if (env.hdr.opk !== void 0) {
245
- oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(env.hdr.opk);
246
- if (!oneTimePreKeyPrivateKey) {
247
- throw new Error(
248
- `Handshake references one-time prekey ${env.hdr.opk} which is unknown or already consumed.`
249
- );
250
- }
251
- }
252
- const { rootKey } = await performX3dhResponder(
253
- {
254
- identityPrivateKey: own.identity.privateKey,
255
- signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
256
- oneTimePreKeyPrivateKey
257
- },
258
- {
259
- initiatorIdentityPublicKey: fromBase64(env.hdr.ik),
260
- initiatorEphemeralPublicKey: fromBase64(env.hdr.ek),
261
- usedOneTimePreKeyId: env.hdr.opk
262
- }
263
- );
264
- const ratchet = await initializeRatchet(rootKey, "responder");
265
- session = { ratchet, role: "responder" };
266
- }
267
- const step = await ratchetReceive(session.ratchet);
268
- if (step.messageIndex !== env.i) {
269
- throw new Error(
270
- `Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). Skipped-key handling is a tracked follow-up (LINEAR-2357).`
271
- );
272
- }
273
- const plaintext = await decryptBytes(step.messageKey, env.ct);
274
- await keystore.putSession(peerId, session);
275
- return plaintext;
276
- }
277
-
278
- // src/tools/mdm.ts
279
- var PROTOCOL_VERSION = "mosadd.chat.v1";
280
- var ContactRef = z.string().min(1).describe(
281
- "Recipient identity id (UUID). Use mDM_list_contacts first to find the right id. Future versions will accept handle/email/phone directly."
282
- );
283
- var ThreadSuffix = z.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe(
284
- "Optional thread label within the conversation with this contact. Defaults to the contact's main thread. mosadd USP: multiple threads per contact."
285
- );
286
- var mDM_send_input = z.object({
287
- to: ContactRef,
288
- text: z.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
289
- thread_label: ThreadSuffix.optional().describe(
290
- "Optional thread label. If omitted, uses the default thread for this contact."
291
- ),
292
- reply_to_id: z.string().optional().describe("Optional id of the message being replied to.")
293
- });
294
- var mDM_list_input = z.object({
295
- contact_id: ContactRef.describe("Identity id of the contact to read messages with."),
296
- thread_label: ThreadSuffix.optional(),
297
- limit: z.number().int().min(1).max(200).default(50).optional(),
298
- cursor: z.string().optional().describe("Opaque pagination cursor from a previous response.")
299
- });
300
- var mDM_list_contacts_input = z.object({
301
- limit: z.number().int().min(1).max(500).default(100).optional()
302
- });
303
- var mDM_respond_request_input = z.object({
304
- request_id: z.string().min(1),
305
- action: z.enum(["accept", "reject"])
306
- });
307
- function dmThreadId(selfId, otherId, label) {
308
- const [a, b] = [selfId, otherId].sort();
309
- return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
310
- }
311
- async function resolveSelfIdentityId() {
312
- const sb = getSupabase();
313
- const { data: u, error: ue } = await sb.auth.getUser();
314
- if (ue || !u?.user) {
315
- throw new Error(
316
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
317
- );
318
- }
319
- const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
320
- if (error || !identity) {
321
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
322
- }
323
- return identity.id;
324
- }
325
- function packPlaintextPayload(text, replyToId) {
326
- const envelope = {
327
- v: PROTOCOL_VERSION,
328
- type: "text",
329
- text,
330
- reply_to: replyToId ?? null,
331
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
332
- };
333
- return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
334
- }
335
- function unpackPayload(payload) {
336
- try {
337
- const json = Buffer.from(payload).toString("utf8");
338
- const obj = JSON.parse(json);
339
- if (typeof obj?.text === "string") return obj;
340
- } catch {
341
- }
342
- return { text: "<ciphertext>" };
343
- }
344
- async function mDM_send(input, ctx) {
345
- const dm = ctx.providers.dm;
346
- const selfId = await dm.selfId();
347
- const threadId = dmThreadId(selfId, input.to, input.thread_label);
348
- const inner = packPlaintextPayload(input.text, input.reply_to_id);
349
- const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
350
- ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
351
- const result = await dm.send({
352
- to: input.to,
353
- threadId,
354
- payload: sealed,
355
- replyToId: input.reply_to_id
356
- });
357
- if (ctx.providers.keys.putSentMessage) {
358
- await ctx.providers.keys.putSentMessage(result.id, inner);
359
- }
360
- return {
361
- message_id: result.id,
362
- delivered_at: result.deliveredAt,
363
- thread_id: threadId,
364
- encrypted: true
365
- };
366
- }
367
- async function mDM_send_unencrypted(input, ctx) {
368
- const dm = ctx.providers.dm;
369
- const selfId = await dm.selfId();
370
- const threadId = dmThreadId(selfId, input.to, input.thread_label);
371
- const payload = packPlaintextPayload(input.text, input.reply_to_id);
372
- ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
373
- thread_id: threadId,
374
- bytes: payload.byteLength
375
- });
376
- const result = await dm.send({
377
- to: input.to,
378
- threadId,
379
- payload,
380
- replyToId: input.reply_to_id
381
- });
382
- return {
383
- message_id: result.id,
384
- delivered_at: result.deliveredAt,
385
- thread_id: threadId,
386
- encrypted: false
387
- };
388
- }
389
- async function mDM_publish_keys(_input, ctx) {
390
- const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
391
- ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
392
- return { published: true, one_time_prekeys: oneTimePrekeyCount };
393
- }
394
- async function mDM_list(input, ctx) {
395
- const dm = ctx.providers.dm;
396
- const selfId = await dm.selfId();
397
- const threadId = dmThreadId(selfId, input.contact_id, input.thread_label);
398
- ctx.log("debug", "mDM_list via DmProvider", { thread_id: threadId });
399
- const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
400
- const messages = await Promise.all(
401
- result.messages.map(async (m) => {
402
- const base = {
403
- id: m.id,
404
- sender_identity_id: m.senderId,
405
- timestamp: m.timestamp,
406
- thread_id: m.threadId
407
- };
408
- if (!isE2eeEnvelope(m.payload)) {
409
- return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
410
- }
411
- if (m.senderId === selfId) {
412
- const cached = await ctx.providers.keys.getSentMessage?.(m.id);
413
- if (cached) {
414
- return { ...base, text: unpackPayload(cached).text, encrypted: true };
415
- }
416
- return { ...base, text: "<encrypted \xB7 sent by you>", encrypted: true };
417
- }
418
- try {
419
- const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
420
- return { ...base, text: unpackPayload(inner).text, encrypted: true };
421
- } catch (err) {
422
- ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
423
- return { ...base, text: "<undecryptable>", encrypted: true };
424
- }
425
- })
426
- );
427
- return {
428
- messages,
429
- next_cursor: result.nextCursor,
430
- threads: [threadId]
431
- };
432
- }
433
- async function mDM_list_contacts(input, ctx) {
434
- readSupabaseEnv();
435
- const selfId = await resolveSelfIdentityId();
436
- const sb = getSupabase();
437
- ctx.log("debug", "mDM_list_contacts querying contacts table", { selfId });
438
- const { data, error } = await sb.from("contacts").select("contact_identity_id, state, identities:contact_identity_id(account_id, display_name)").eq("owner_identity_id", selfId).limit(input.limit ?? 100);
439
- if (error) {
440
- throw new Error(`Failed to list contacts: ${error.message}`);
441
- }
442
- const contacts = data.map((r) => ({
443
- identity_id: r.contact_identity_id,
444
- account_id: r.identities?.account_id ?? null,
445
- display_name: r.identities?.display_name ?? null,
446
- state: r.state
447
- }));
448
- return { contacts };
449
- }
450
- async function mDM_respond_request(input, ctx) {
451
- readSupabaseEnv();
452
- ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
453
- await invokeFunction("message-request-respond", {
454
- request_id: input.request_id,
455
- action: input.action
456
- });
457
- return { ok: true };
458
- }
459
- var mDM_publish_keys_input = z.object({});
460
- var mDM_edit_input = z.object({
461
- message_id: z.string().min(1).describe("Id of the message to edit (from mDM_list)."),
462
- new_text: z.string().min(1).max(64e3).describe("Replacement message body (UTF-8). Max 64 KB.")
463
- });
464
- var mDM_delete_input = z.object({
465
- message_id: z.string().min(1).describe("Id of the message to delete (from mDM_list).")
466
- });
467
- async function mDM_edit(input, ctx) {
468
- readSupabaseEnv();
469
- const envelope = {
470
- v: PROTOCOL_VERSION,
471
- type: "text",
472
- text: input.new_text,
473
- edited: true,
474
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
475
- };
476
- const encrypted_payload = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
477
- ctx.log("debug", "mDM_edit via message-edit", { message_id: input.message_id });
478
- await invokeFunction("message-edit", { message_id: input.message_id, encrypted_payload });
479
- return { message_id: input.message_id, edited: true };
480
- }
481
- async function mDM_delete(input, ctx) {
482
- readSupabaseEnv();
483
- ctx.log("debug", "mDM_delete via message-delete", { message_id: input.message_id });
484
- await invokeFunction("message-delete", { message_id: input.message_id });
485
- return { message_id: input.message_id, deleted: true };
486
- }
487
- var mdmTools = [
488
- {
489
- name: "mDM_list_contacts",
490
- requires: "any",
491
- description: "List the user's mosadd contacts. Returns identity_id (use this for mDM_send / mDM_list), account handle, display name, and contact state (pending, accepted, blocked).",
492
- inputSchema: mDM_list_contacts_input,
493
- handler: mDM_list_contacts
494
- },
495
- {
496
- name: "mDM_publish_keys",
497
- requires: "any",
498
- description: "Publish your mDM prekey bundle so other people can start an end-to-end-encrypted conversation with you. Run this once after sign-in (and to replenish one-time prekeys). Rides the same transport as messages, so it works over network or off-grid radio.",
499
- inputSchema: mDM_publish_keys_input,
500
- handler: mDM_publish_keys
501
- },
502
- {
503
- name: "mDM_send",
504
- requires: "any",
505
- description: "Send an END-TO-END-ENCRYPTED direct message via mosadd mDM. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread \u2014 mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
506
- inputSchema: mDM_send_input,
507
- handler: mDM_send
508
- },
509
- {
510
- name: "mDM_send_unencrypted",
511
- requires: "any",
512
- description: "DEPRECATED migration-window fallback: send a direct message WITHOUT end-to-end encryption (plaintext envelope). Only use when the recipient has not yet published prekeys (mDM_send fails with that hint). Prefer mDM_send. Will be removed once E2EE is universal.",
513
- inputSchema: mDM_send_input,
514
- handler: mDM_send_unencrypted
515
- },
516
- {
517
- name: "mDM_list",
518
- requires: "any",
519
- description: "List recent direct messages with a specific contact. Pass contact_id as the identity_id from mDM_list_contacts. Decrypts end-to-end-encrypted messages from the contact automatically; legacy plaintext messages are shown as-is. Optionally filter to a single thread_label.",
520
- inputSchema: mDM_list_input,
521
- handler: mDM_list
522
- },
523
- {
524
- name: "mDM_respond_request",
525
- requires: "any",
526
- description: "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
527
- inputSchema: mDM_respond_request_input,
528
- handler: mDM_respond_request
529
- },
530
- {
531
- name: "mDM_edit",
532
- requires: "any",
533
- description: "Edit a direct message you sent \u2014 replace its body by message_id (from mDM_list). Stores a server-readable edited body; on an end-to-end-encrypted thread this does not re-encrypt, so for E2EE prefer deleting and re-sending.",
534
- inputSchema: mDM_edit_input,
535
- handler: mDM_edit
536
- },
537
- {
538
- name: "mDM_delete",
539
- requires: "any",
540
- description: "Delete a direct message you sent by message_id (from mDM_list). Soft-deletes server-side so it stops showing in mDM_list for both sides.",
541
- inputSchema: mDM_delete_input,
542
- handler: mDM_delete
543
- }
544
- ];
545
-
546
- // src/tools/mdm-voice.ts
547
- import { z as z2 } from "zod";
548
- var PROTOCOL_VERSION2 = "mosadd.chat.v1";
549
- var ContactRef2 = z2.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
550
- var RoomId = z2.string().min(1).describe("Voice room id (from mDM_call_start's call_invite).");
551
- var mDM_call_start_input = z2.object({
552
- to: ContactRef2,
553
- video: z2.boolean().optional().describe("Request a video call instead of audio-only. Default false."),
554
- thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional().describe("Optional thread label to place the call invite in. Defaults to the contact's main thread.")
555
- });
556
- var mDM_call_answer_input = z2.object({ room_id: RoomId });
557
- var mDM_call_end_input = z2.object({
558
- room_id: RoomId,
559
- to: ContactRef2.optional().describe("If set, also drop a call_end control message in this contact's DM thread."),
560
- thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
561
- });
562
- var mDM_voice_note_input = z2.object({
563
- to: ContactRef2,
564
- audio_url: z2.string().url().describe("URL of the recorded audio clip (already uploaded by the client)."),
565
- duration_ms: z2.number().int().positive().optional().describe("Clip length in milliseconds, if known."),
566
- mime: z2.string().max(120).optional().describe("Audio MIME type, e.g. audio/ogg, audio/mpeg. Default audio/ogg."),
567
- thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
568
- });
569
- function dmThreadId2(selfId, otherId, label) {
570
- const [a, b] = [selfId, otherId].sort();
571
- return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
572
- }
573
- function packEnvelope(obj) {
574
- const envelope = { v: PROTOCOL_VERSION2, sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...obj };
575
- return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
576
- }
577
- async function signalDm(ctx, to, threadLabel, envelope) {
578
- const dm = ctx.providers.dm;
579
- const selfId = await dm.selfId();
580
- const threadId = dmThreadId2(selfId, to, threadLabel);
581
- const res = await dm.send({ to, threadId, payload: packEnvelope(envelope) });
582
- return { message_id: res?.message_id, thread_id: threadId };
583
- }
584
- async function mDM_call_start(input, ctx) {
585
- const dm = ctx.providers.dm;
586
- const selfId = await dm.selfId();
587
- const mode = input.video ? "video" : "audio";
588
- const label = `dmcall-${dmThreadId2(selfId, input.to, input.thread_label).replace(/[^a-zA-Z0-9._-]/g, "-")}`.slice(0, 120);
589
- const { roomId } = await ctx.providers.voice.createRoom(label);
590
- const ticket = await ctx.providers.voice.joinTicket(roomId);
591
- let invited = false;
592
- let thread_id = dmThreadId2(selfId, input.to, input.thread_label);
593
- try {
594
- const sig = await signalDm(ctx, input.to, input.thread_label, {
595
- type: "call_invite",
596
- room_id: roomId,
597
- mode,
598
- from: selfId
599
- });
600
- thread_id = sig.thread_id;
601
- invited = true;
602
- } catch (e) {
603
- ctx.log("warn", "mDM_call_start: invite signal failed (room still usable)", {
604
- error: e.message
605
- });
606
- }
607
- ctx.log("debug", "mDM_call_start", { room_id: roomId, mode, invited });
608
- return { room_id: roomId, token: ticket.token, url: ticket.url, identity: ticket.identity, mode, invited, thread_id };
609
- }
610
- async function mDM_call_answer(input, ctx) {
611
- const ticket = await ctx.providers.voice.joinTicket(input.room_id);
612
- ctx.log("debug", "mDM_call_answer", { room_id: ticket.roomId, identity: ticket.identity });
613
- return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
614
- }
615
- async function mDM_call_end(input, ctx) {
616
- let signalled = false;
617
- if (input.to) {
618
- try {
619
- await signalDm(ctx, input.to, input.thread_label, { type: "call_end", room_id: input.room_id });
620
- signalled = true;
621
- } catch (e) {
622
- ctx.log("warn", "mDM_call_end: hangup signal failed", { error: e.message });
623
- }
624
- }
625
- ctx.log("debug", "mDM_call_end", { room_id: input.room_id, signalled });
626
- return { room_id: input.room_id, signalled };
627
- }
628
- async function mDM_voice_note(input, ctx) {
629
- const sig = await signalDm(ctx, input.to, input.thread_label, {
630
- type: "voice_note",
631
- audio_url: input.audio_url,
632
- duration_ms: input.duration_ms ?? null,
633
- mime: input.mime ?? "audio/ogg"
634
- });
635
- ctx.log("debug", "mDM_voice_note", { thread_id: sig.thread_id });
636
- return sig;
637
- }
638
- var mdmVoiceTools = [
639
- {
640
- name: "mDM_call_start",
641
- requires: "network",
642
- description: "Start a 1:1 real-time voice (or video) call with a contact \u2014 the ordinary full-duplex phone-style call (NOT walkie-talkie mTALK, NOT PSTN mCALL). Creates a room, returns join credentials (token + media url), and drops a `call_invite` control message in the DM thread so the contact can answer. Set video:true for video.",
643
- inputSchema: mDM_call_start_input,
644
- handler: mDM_call_start
645
- },
646
- {
647
- name: "mDM_call_answer",
648
- requires: "network",
649
- description: "Answer an incoming 1:1 call by its room_id (from the call_invite seen via mDM_list). Returns join credentials (token + media url) for the same room.",
650
- inputSchema: mDM_call_answer_input,
651
- handler: mDM_call_answer
652
- },
653
- {
654
- name: "mDM_call_end",
655
- requires: "network",
656
- description: "End a 1:1 call. The audio leg ends when clients disconnect; pass `to` to also drop a `call_end` (hangup) control message in the contact's DM thread.",
657
- inputSchema: mDM_call_end_input,
658
- handler: mDM_call_end
659
- },
660
- {
661
- name: "mDM_voice_note",
662
- requires: "network",
663
- description: "Send an asynchronous voice note to a contact: references an already-uploaded audio clip (audio_url) and posts it as a `voice_note` message in the DM thread. Use for fire-and-forget voice instead of a live call.",
664
- inputSchema: mDM_voice_note_input,
665
- handler: mDM_voice_note
666
- }
667
- ];
668
-
669
- // src/tools/mirc.ts
670
- import { z as z3 } from "zod";
671
- var ChannelId = z3.string().min(1).max(120).describe("Channel id (UUID). Use mIRC_list to discover available channels.");
672
- var AccessMode = z3.enum(["open", "password", "private"]).describe("open: anyone can join \xB7 password: join with a shared password \xB7 private: invite-only.");
673
- var Capabilities = z3.object({
674
- txt: z3.boolean().default(true),
675
- ptt: z3.boolean().default(false),
676
- live: z3.boolean().default(false)
677
- }).describe("Which modes are enabled in this channel: txt (text), ptt (push-to-talk voice), live (live stream).").optional();
678
- var mIRC_create_input = z3.object({
679
- name: z3.string().min(1).max(80).describe("Channel display name."),
680
- topic: z3.string().max(500).optional().describe("Optional channel topic/description."),
681
- access_mode: AccessMode.default("open"),
682
- password: z3.string().min(6).max(120).optional().describe("Password (only for access_mode=password)."),
683
- capabilities: Capabilities
684
- });
685
- var mIRC_list_input = z3.object({
686
- limit: z3.number().int().min(1).max(500).default(100).optional(),
687
- offset: z3.number().int().min(0).default(0).optional(),
688
- access_mode: AccessMode.optional().describe("Filter to a single access mode.")
689
- });
690
- var mIRC_get_input = z3.object({
691
- channel_id: ChannelId
692
- });
693
- var mIRC_update_input = z3.object({
694
- channel_id: ChannelId,
695
- name: z3.string().min(1).max(80).optional(),
696
- topic: z3.string().max(500).optional(),
697
- access_mode: AccessMode.optional(),
698
- capabilities: Capabilities
699
- });
700
- var mIRC_delete_input = z3.object({
701
- channel_id: ChannelId
702
- });
703
- async function mIRC_create(input, ctx) {
704
- readSupabaseEnv();
705
- ctx.log("debug", "mIRC_create invoking channel-manage", { name: input.name });
706
- return await invokeFunction("channel-manage", {
707
- action: "create",
708
- ...input
709
- });
710
- }
711
- async function mIRC_list(input, ctx) {
712
- readSupabaseEnv();
713
- ctx.log("debug", "mIRC_list invoking channel-manage");
714
- return await invokeFunction("channel-manage", {
715
- action: "list",
716
- ...input
717
- });
718
- }
719
- async function mIRC_get(input, ctx) {
720
- readSupabaseEnv();
721
- ctx.log("debug", "mIRC_get invoking channel-manage", { channel_id: input.channel_id });
722
- return await invokeFunction("channel-manage", {
723
- action: "get",
724
- channel_id: input.channel_id
725
- });
726
- }
727
- async function mIRC_update(input, ctx) {
728
- readSupabaseEnv();
729
- ctx.log("debug", "mIRC_update invoking channel-manage", { channel_id: input.channel_id });
730
- return await invokeFunction("channel-manage", {
731
- action: "update",
732
- ...input
733
- });
734
- }
735
- async function mIRC_delete(input, ctx) {
736
- readSupabaseEnv();
737
- ctx.log("debug", "mIRC_delete invoking channel-manage", { channel_id: input.channel_id });
738
- await invokeFunction("channel-manage", {
739
- action: "delete",
740
- channel_id: input.channel_id
741
- });
742
- return { deleted: true };
743
- }
744
- var mircTools = [
745
- {
746
- name: "mIRC_create",
747
- requires: "network",
748
- description: "Create a new persistent channel (Discord/Slack-style). Set access_mode to open (anyone joins), password (shared-password gated), or private (invite-only). capabilities controls modes (txt/ptt/live).",
749
- inputSchema: mIRC_create_input,
750
- handler: mIRC_create
751
- },
752
- {
753
- name: "mIRC_list",
754
- requires: "network",
755
- description: "List channels available to the current user. Optionally filter by access_mode.",
756
- inputSchema: mIRC_list_input,
757
- handler: mIRC_list
758
- },
759
- {
760
- name: "mIRC_get",
761
- requires: "network",
762
- description: "Get full details of a single channel by id.",
763
- inputSchema: mIRC_get_input,
764
- handler: mIRC_get
765
- },
766
- {
767
- name: "mIRC_update",
768
- requires: "network",
769
- description: "Update channel metadata (name, topic, access_mode, capabilities). Owner only.",
770
- inputSchema: mIRC_update_input,
771
- handler: mIRC_update
772
- },
773
- {
774
- name: "mIRC_delete",
775
- requires: "network",
776
- description: "Delete a channel and cascade-remove its members. Owner only.",
777
- inputSchema: mIRC_delete_input,
778
- handler: mIRC_delete
779
- }
780
- ];
781
-
782
- // src/tools/mirc-members.ts
783
- import { z as z4 } from "zod";
784
- var ChannelId2 = z4.string().min(1).max(120).describe("Channel id (UUID). From mIRC_list / mIRC_create.");
785
- var MemberIdentity = z4.string().min(1).describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
786
- var Role = z4.enum(["owner", "admin", "moderator", "member", "guest"]).describe("Member role within the channel.");
787
- var mIRC_join_input = z4.object({
788
- channel_id: ChannelId2,
789
- password: z4.string().min(1).optional().describe("Required if the channel is access_mode=private.")
790
- });
791
- var mIRC_request_access_input = z4.object({
792
- channel_id: ChannelId2,
793
- message: z4.string().max(500).optional().describe("Optional note for the channel owner explaining why.")
794
- });
795
- var mIRC_leave_input = z4.object({
796
- channel_id: ChannelId2
797
- });
798
- var mIRC_approve_request_input = z4.object({
799
- channel_id: ChannelId2,
800
- request_id: z4.string().min(1).describe("Pending request id.")
801
- });
802
- var mIRC_reject_request_input = mIRC_approve_request_input;
803
- var mIRC_kick_input = z4.object({
804
- channel_id: ChannelId2,
805
- identity_id: MemberIdentity,
806
- reason: z4.string().max(500).optional()
807
- });
808
- var mIRC_ban_input = z4.object({
809
- channel_id: ChannelId2,
810
- identity_id: MemberIdentity,
811
- reason: z4.string().max(500).optional(),
812
- /** Optional unban deadline (ISO-8601). Omit for permanent ban. */
813
- until: z4.string().optional()
814
- });
815
- var mIRC_unban_input = z4.object({
816
- channel_id: ChannelId2,
817
- identity_id: MemberIdentity
818
- });
819
- var mIRC_set_role_input = z4.object({
820
- channel_id: ChannelId2,
821
- identity_id: MemberIdentity,
822
- role: Role
823
- });
824
- var mIRC_set_ptt_input = z4.object({
825
- channel_id: ChannelId2,
826
- identity_id: MemberIdentity,
827
- ptt_enabled: z4.boolean().describe("Allow this member to hold the PTT floor in voice mode.")
828
- });
829
- async function invokeChannelMembers(action, body, ctx) {
830
- readSupabaseEnv();
831
- ctx.log("debug", `mIRC.${action}`, body);
832
- return await invokeFunction("channel-members-manage", { action, ...body });
833
- }
834
- var mircMembersTools = [
835
- {
836
- name: "mIRC_join",
837
- requires: "network",
838
- description: "Join a channel as the current user. For private channels pass `password`. Returns a membership row or 409 if already a member.",
839
- inputSchema: mIRC_join_input,
840
- handler: ((input, ctx) => invokeChannelMembers("join", input, ctx))
841
- },
842
- {
843
- name: "mIRC_request_access",
844
- requires: "network",
845
- description: "Request access to an invite_only channel. Owner / admins get a notification with the optional message.",
846
- inputSchema: mIRC_request_access_input,
847
- handler: ((input, ctx) => invokeChannelMembers("request-access", input, ctx))
848
- },
849
- {
850
- name: "mIRC_leave",
851
- requires: "network",
852
- description: "Leave a channel as the current user. Owner cannot leave without transferring ownership first.",
853
- inputSchema: mIRC_leave_input,
854
- handler: ((input, ctx) => invokeChannelMembers("leave", input, ctx))
855
- },
856
- {
857
- name: "mIRC_approve_request",
858
- requires: "network",
859
- description: "Approve a pending access request. Admins / moderators / owner only.",
860
- inputSchema: mIRC_approve_request_input,
861
- handler: ((input, ctx) => invokeChannelMembers("approve-request", input, ctx))
862
- },
863
- {
864
- name: "mIRC_reject_request",
865
- requires: "network",
866
- description: "Reject a pending access request. Admins / moderators / owner only.",
867
- inputSchema: mIRC_reject_request_input,
868
- handler: ((input, ctx) => invokeChannelMembers("reject-request", input, ctx))
869
- },
870
- {
871
- name: "mIRC_kick",
872
- requires: "network",
873
- description: "Remove a member from the channel. They can rejoin if not banned. Requires moderator+. `reason` is logged to channel-event-log.",
874
- inputSchema: mIRC_kick_input,
875
- handler: ((input, ctx) => invokeChannelMembers("kick", input, ctx))
876
- },
877
- {
878
- name: "mIRC_ban",
879
- requires: "network",
880
- description: "Ban a member from the channel. They cannot rejoin until unbanned. `until` (ISO-8601) for time-bound ban; omit for permanent. Requires admin+.",
881
- inputSchema: mIRC_ban_input,
882
- handler: ((input, ctx) => invokeChannelMembers("ban", input, ctx))
883
- },
884
- {
885
- name: "mIRC_unban",
886
- requires: "network",
887
- description: "Lift a ban. Requires admin+.",
888
- inputSchema: mIRC_unban_input,
889
- handler: ((input, ctx) => invokeChannelMembers("unban", input, ctx))
890
- },
891
- {
892
- name: "mIRC_set_role",
893
- requires: "network",
894
- description: "Promote / demote a member. Roles: owner > admin > moderator > member > guest. Only owner can promote to admin; only admin+ can promote to moderator.",
895
- inputSchema: mIRC_set_role_input,
896
- handler: ((input, ctx) => invokeChannelMembers("set-role", input, ctx))
897
- },
898
- {
899
- name: "mIRC_set_ptt",
900
- requires: "network",
901
- description: "Grant or revoke PTT floor permission for a member in voice-capable channels (capabilities.ptt=true). Requires moderator+.",
902
- inputSchema: mIRC_set_ptt_input,
903
- handler: ((input, ctx) => invokeChannelMembers("set-ptt", input, ctx))
904
- }
905
- ];
906
-
907
- // src/tools/mirc-messages.ts
908
- import { z as z5 } from "zod";
909
- var PROTOCOL_VERSION3 = "mosadd.chat.v1";
910
- var ChannelId3 = z5.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
911
- var mIRC_post_message_input = z5.object({
912
- channel_id: ChannelId3,
913
- text: z5.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
914
- reply_to_id: z5.string().optional().describe("Optional id of the message being replied to."),
915
- space_id: z5.string().optional().describe("Optional backing space id. Resolved automatically from the channel if omitted.")
916
- });
917
- var mIRC_list_messages_input = z5.object({
918
- channel_id: ChannelId3,
919
- limit: z5.number().int().min(1).max(200).default(50).optional(),
920
- cursor: z5.string().optional().describe("Opaque pagination cursor from a prior list response."),
921
- space_id: z5.string().optional().describe("Optional backing space id. Resolved automatically if omitted.")
922
- });
923
- function packPlaintextPayload2(text, replyToId) {
924
- const envelope = {
925
- v: PROTOCOL_VERSION3,
926
- type: "text",
927
- text,
928
- reply_to: replyToId ?? null,
929
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
930
- };
931
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
932
- }
933
- function unpackPayload2(payload) {
934
- try {
935
- const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
936
- if (typeof obj?.text === "string") return obj;
937
- } catch {
938
- }
939
- return { text: "<ciphertext>" };
940
- }
941
- async function resolveLinkedSpaceId(channelId) {
942
- const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
943
- const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
944
- if (!spaceId) {
945
- throw new Error(
946
- `Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, or pass space_id explicitly.`
947
- );
948
- }
949
- return spaceId;
950
- }
951
- async function mIRC_post_message(input, ctx) {
952
- readSupabaseEnv();
953
- const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
954
- const thread_id = `chat:${input.channel_id}`;
955
- ctx.log("debug", "mIRC_post_message", { thread_id, space_id });
956
- const data = await invokeFunction("message-send", {
957
- space_id,
958
- thread_id,
959
- encrypted_payload: packPlaintextPayload2(input.text, input.reply_to_id),
960
- message_type: "txt",
961
- protocol_version: PROTOCOL_VERSION3,
962
- reply_to_id: input.reply_to_id ?? null
963
- });
964
- if (!data?.message?.id) throw new Error("message-send returned no message id");
965
- return { message_id: data.message.id, delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(), thread_id };
966
- }
967
- async function mIRC_list_messages(input, ctx) {
968
- readSupabaseEnv();
969
- const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
970
- const thread_id = `chat:${input.channel_id}`;
971
- ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
972
- const data = await invokeFunction("message-list", {
973
- space_id,
974
- thread_id,
975
- limit: input.limit ?? 50,
976
- cursor: input.cursor
977
- });
978
- return {
979
- messages: (data?.messages ?? []).map((m) => ({
980
- id: m.id,
981
- sender_identity_id: m.sender_identity_id,
982
- text: unpackPayload2(m.encrypted_payload).text,
983
- timestamp: m.created_at
984
- })),
985
- next_cursor: data?.next_cursor ?? null
986
- };
987
- }
988
- var mircMessagesTools = [
989
- {
990
- name: "mIRC_post_message",
991
- requires: "network",
992
- description: "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. You must be a member of private channels (use mIRC_join first). This is how an agent actually talks in a channel \u2014 the other mIRC_* tools only manage it. NOTE (alpha): the payload is NOT end-to-end encrypted \u2014 it is plaintext base64 and is readable by the server; the mosadd.com app uses per-channel group-key encryption, so app clients cannot read these messages yet (and vice-versa). Group-key parity is planned.",
993
- inputSchema: mIRC_post_message_input,
994
- handler: mIRC_post_message
995
- },
996
- {
997
- name: "mIRC_list_messages",
998
- requires: "network",
999
- description: "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
1000
- inputSchema: mIRC_list_messages_input,
1001
- handler: mIRC_list_messages
1002
- }
1003
- ];
1004
-
1005
- // src/tools/mirc-edge.ts
1006
- import { z as z6 } from "zod";
1007
- var DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
1008
- var DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
1009
- function edgeUrl() {
1010
- return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
1011
- }
1012
- function supabaseUrl() {
1013
- return process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ?? process.env.SUPABASE_URL?.replace(/\/$/, "") ?? DEFAULT_SUPABASE_URL;
1014
- }
1015
- function hubKey() {
1016
- const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
1017
- if (!key) throw new Error("MOSADD_API_KEY required for mIRC edge tools (see mosadd login or hub-keys).");
1018
- return key;
1019
- }
1020
- var mIRC_send_edge_input = z6.object({
1021
- channel_id: z6.string().min(1).max(128).describe("Channel id (UUID). Same as mIRC_create / mIRC_list."),
1022
- text: z6.string().min(1).max(64e3).describe("Message body (UTF-8, max 64 KB)."),
1023
- from: z6.string().max(120).optional().describe("Sender hint shown to other clients (defaults to the hub-key owner).")
1024
- });
1025
- async function mIRC_send_edge(input, ctx) {
1026
- ctx.log("debug", "mIRC_send_edge", { channel_id: input.channel_id });
1027
- const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/send`, {
1028
- method: "POST",
1029
- headers: {
1030
- "Content-Type": "application/json",
1031
- Authorization: `Bearer ${hubKey()}`
1032
- },
1033
- body: JSON.stringify({ text: input.text, from: input.from })
1034
- });
1035
- if (!r.ok) {
1036
- const errBody = await r.text().catch(() => "");
1037
- throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
1038
- }
1039
- const data = await r.json();
1040
- if (!data?.id) throw new Error("mosadd-edge: send returned no id");
1041
- return { message_id: data.id, delivered_at: data.ts ?? Date.now(), channel_id: input.channel_id };
1042
- }
1043
- var mIRC_history_edge_input = z6.object({
1044
- channel_id: z6.string().min(1).max(128).describe("Channel id (UUID)."),
1045
- limit: z6.number().int().min(1).max(100).default(50).optional().describe("How many recent messages to return (max 100, the DO ring size).")
1046
- });
1047
- async function mIRC_history_edge(input, ctx) {
1048
- const limit = input.limit ?? 50;
1049
- ctx.log("debug", "mIRC_history_edge", { channel_id: input.channel_id, limit });
1050
- const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/history?limit=${limit}`, {
1051
- headers: { Authorization: `Bearer ${hubKey()}` }
1052
- });
1053
- if (!r.ok) {
1054
- const errBody = await r.text().catch(() => "");
1055
- throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
1056
- }
1057
- const data = await r.json();
1058
- return {
1059
- channel_id: input.channel_id,
1060
- messages: (data.messages ?? []).map((m) => ({
1061
- id: m.id,
1062
- from: m.from ?? null,
1063
- text: m.text,
1064
- timestamp: m.ts
1065
- }))
1066
- };
1067
- }
1068
- var mIRC_mint_channel_token_input = z6.object({
1069
- channel_id: z6.string().min(1).max(128).describe("Channel id \u2014 the JWT will be scoped to this channel only. Must match the WS upgrade path."),
1070
- user_id: z6.string().min(1).max(120).optional().describe("Optional end-user id. Stamped onto messages as 'from'. Useful when one hub key fronts many end-users (relay topology).")
1071
- });
1072
- async function mIRC_mint_channel_token(input, ctx) {
1073
- ctx.log("debug", "mIRC_mint_channel_token", { channel_id: input.channel_id });
1074
- const r = await fetch(`${supabaseUrl()}/functions/v1/hub-mint-channel-token`, {
1075
- method: "POST",
1076
- headers: {
1077
- "Content-Type": "application/json",
1078
- Authorization: `Bearer ${hubKey()}`
1079
- },
1080
- body: JSON.stringify({ channel_id: input.channel_id, user_id: input.user_id })
1081
- });
1082
- if (!r.ok) {
1083
- const errBody = await r.text().catch(() => "");
1084
- throw new Error(`hub-mint-channel-token ${r.status}: ${errBody.slice(0, 200)}`);
1085
- }
1086
- const data = await r.json();
1087
- if (!data?.token || !data?.expires_in || !data?.channel_id || !data?.scope) {
1088
- throw new Error("hub-mint-channel-token: malformed response");
1089
- }
1090
- return data;
1091
- }
1092
- var mircEdgeTools = [
1093
- {
1094
- name: "mIRC_mint_channel_token",
1095
- requires: "network",
1096
- description: "Exchange the hub key (MOSADD_API_KEY) for a short-lived (5min), channel-scoped JWT. Returns { token, expires_in, channel_id, scope }. The token is safe to hand to a browser to open a WS via `Sec-WebSocket-Protocol: mosadd.v1, bearer.<token>`. The hub key NEVER leaves the server. Use this from any server-side route (Next.js /api/chat-token, Express, etc.) before showing chat in a browser. Required by LINEAR-2675/E6 to avoid leaking the hub key into CDN access logs.",
1097
- inputSchema: mIRC_mint_channel_token_input,
1098
- handler: mIRC_mint_channel_token
1099
- },
1100
- {
1101
- name: "mIRC_send_edge",
1102
- requires: "network",
1103
- description: "Send a text message into a persistent channel via the mosadd-edge Cloudflare Worker (Durable Object backend). Sub-100ms global fan-out to all WebSocket subscribers of the channel + async flush to Supabase as system-of-record (idempotent). Use this when you want native realtime push without polling. Parallel to mIRC_post_message (Supabase path); pick one per channel. Auth: MOSADD_API_KEY env (hub key).",
1104
- inputSchema: mIRC_send_edge_input,
1105
- handler: mIRC_send_edge
1106
- },
1107
- {
1108
- name: "mIRC_history_edge",
1109
- requires: "network",
1110
- description: "Read the last N (max 100) messages held in the channel's Durable Object ring buffer at the edge. Hot path is the DO, not Supabase \u2014 same data lands in messages_meta via async flush, so cold reads / pagination beyond 100 should use mIRC_list_messages.",
1111
- inputSchema: mIRC_history_edge_input,
1112
- handler: mIRC_history_edge
1113
- }
1114
- ];
1115
-
1116
- // src/tools/mroom.ts
1117
- import { z as z7 } from "zod";
1118
- var RoomId2 = z7.string().min(1).describe("Private room id (UUID).");
1119
- var mROOM_voice_join_input = z7.object({
1120
- room_id: RoomId2,
1121
- video: z7.boolean().optional().describe("Request video instead of audio-only. Default false.")
1122
- });
1123
- var mROOM_create_input = z7.object({
1124
- ttl_seconds: z7.number().int().min(60).max(86400 * 30).default(86400).optional().describe("Time-to-live in seconds. Defaults to 24 h. Max 30 days.")
1125
- });
1126
- var mROOM_join_input = z7.object({
1127
- room_id: RoomId2
1128
- });
1129
- var mROOM_close_input = z7.object({
1130
- room_id: RoomId2
1131
- });
1132
- var mROOM_leave_input = z7.object({
1133
- room_id: RoomId2
1134
- });
1135
- var mROOM_list_input = z7.object({});
1136
- var mROOM_create_guest_link_input = z7.object({
1137
- room_id: RoomId2,
1138
- display_name: z7.string().min(1).max(80).describe("Display name the guest will appear under. They never sign up \u2014 this is the only identifier."),
1139
- ttl_seconds: z7.number().int().min(60).max(86400 * 7).default(3600).optional().describe("How long the guest token is valid. Default 1 h, max 7 days.")
1140
- });
1141
- async function mROOM_create(input, ctx) {
1142
- readSupabaseEnv();
1143
- const expires_at = new Date(Date.now() + (input.ttl_seconds ?? 86400) * 1e3).toISOString();
1144
- ctx.log("debug", "mROOM_create invoking privroom-manage", { expires_at });
1145
- return await invokeFunction("privroom-manage", {
1146
- action: "create",
1147
- expires_at
1148
- });
1149
- }
1150
- async function mROOM_join(input, ctx) {
1151
- readSupabaseEnv();
1152
- ctx.log("debug", "mROOM_join invoking privroom-manage", { room_id: input.room_id });
1153
- return await invokeFunction("privroom-manage", {
1154
- action: "join",
1155
- room_id: input.room_id
1156
- });
1157
- }
1158
- async function mROOM_close(input, ctx) {
1159
- readSupabaseEnv();
1160
- ctx.log("debug", "mROOM_close invoking privroom-manage", { room_id: input.room_id });
1161
- return await invokeFunction("privroom-manage", {
1162
- action: "close",
1163
- room_id: input.room_id
1164
- });
1165
- }
1166
- async function mROOM_leave(input, ctx) {
1167
- readSupabaseEnv();
1168
- ctx.log("debug", "mROOM_leave invoking privroom-manage", { room_id: input.room_id });
1169
- return await invokeFunction("privroom-manage", {
1170
- action: "leave",
1171
- room_id: input.room_id
1172
- });
1173
- }
1174
- async function mROOM_list(_input, ctx) {
1175
- readSupabaseEnv();
1176
- ctx.log("debug", "mROOM_list invoking privroom-manage");
1177
- return await invokeFunction("privroom-manage", { action: "list" });
1178
- }
1179
- async function mROOM_create_guest_link(input, ctx) {
1180
- readSupabaseEnv();
1181
- ctx.log("debug", "mROOM_create_guest_link invoking privroom-guest-token", {
1182
- room_id: input.room_id
1183
- });
1184
- const result = await invokeFunction("privroom-guest-token", {
1185
- room_id: input.room_id,
1186
- display_name: input.display_name,
1187
- ttl_seconds: input.ttl_seconds ?? 3600
1188
- });
1189
- return {
1190
- token: result.token,
1191
- join_url: `https://mosadd.com/r/${input.room_id}?t=${result.token}`,
1192
- expires_at: result.expires_at
1193
- };
1194
- }
1195
- async function mROOM_voice_join(input, ctx) {
1196
- const ticket = await ctx.providers.voice.joinTicket(input.room_id);
1197
- ctx.log("debug", "mROOM_voice_join", { room_id: ticket.roomId, identity: ticket.identity });
1198
- return {
1199
- room_id: ticket.roomId,
1200
- token: ticket.token,
1201
- url: ticket.url,
1202
- identity: ticket.identity,
1203
- mode: input.video ? "video" : "audio"
1204
- };
1205
- }
1206
- var mroomTools = [
1207
- {
1208
- name: "mROOM_create",
1209
- requires: "network",
1210
- description: "Create an ephemeral private room. Auto-joins the creator. Defaults to 24 h TTL \u2014 pass ttl_seconds to override.",
1211
- inputSchema: mROOM_create_input,
1212
- handler: mROOM_create
1213
- },
1214
- {
1215
- name: "mROOM_create_guest_link",
1216
- requires: "network",
1217
- description: "USP: Generate a short-lived join link that lets a person enter the room WITHOUT a mosadd account. Returns { token, join_url, expires_at }. Share the join_url out-of-band (email, SMS, QR). Use case: support call, live-stream after-party, anonymous tipline.",
1218
- inputSchema: mROOM_create_guest_link_input,
1219
- handler: mROOM_create_guest_link
1220
- },
1221
- {
1222
- name: "mROOM_join",
1223
- requires: "network",
1224
- description: "Join an existing private room (current user, not a guest).",
1225
- inputSchema: mROOM_join_input,
1226
- handler: mROOM_join
1227
- },
1228
- {
1229
- name: "mROOM_leave",
1230
- requires: "network",
1231
- description: "Leave a private room.",
1232
- inputSchema: mROOM_leave_input,
1233
- handler: mROOM_leave
1234
- },
1235
- {
1236
- name: "mROOM_close",
1237
- requires: "network",
1238
- description: "Close a private room and remove all members. Founder only.",
1239
- inputSchema: mROOM_close_input,
1240
- handler: mROOM_close
1241
- },
1242
- {
1243
- name: "mROOM_list",
1244
- requires: "network",
1245
- description: "List private rooms the current user belongs to.",
1246
- inputSchema: mROOM_list_input,
1247
- handler: mROOM_list
1248
- },
1249
- {
1250
- name: "mROOM_voice_join",
1251
- requires: "network",
1252
- description: "Join an mROOM's full-duplex GROUP voice (everyone can talk \u2014 no walkie-talkie floor; that's mTALK). Returns media credentials (token + url) for the room's audio/video transport. Be a room member first (mROOM_join or a guest link). Set video:true for video.",
1253
- inputSchema: mROOM_voice_join_input,
1254
- handler: mROOM_voice_join
1255
- }
1256
- ];
1257
-
1258
- // src/tools/mroom-messages.ts
1259
- import { z as z8 } from "zod";
1260
- var PROTOCOL_VERSION4 = "mosadd.chat.v1";
1261
- var RoomId3 = z8.string().min(1).describe("Private room id (UUID). From mROOM_create / mROOM_list.");
1262
- var mROOM_send_message_input = z8.object({
1263
- room_id: RoomId3,
1264
- text: z8.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
1265
- reply_to_id: z8.string().optional().describe("Optional id of the message being replied to.")
1266
- });
1267
- var mROOM_list_messages_input = z8.object({
1268
- room_id: RoomId3,
1269
- limit: z8.number().int().min(1).max(200).default(50).optional(),
1270
- cursor: z8.string().optional().describe("Opaque pagination cursor from a prior list response.")
1271
- });
1272
- function packPlaintextPayload3(text, replyToId) {
1273
- const envelope = {
1274
- v: PROTOCOL_VERSION4,
1275
- type: "text",
1276
- text,
1277
- reply_to: replyToId ?? null,
1278
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
1279
- };
1280
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
1281
- }
1282
- function unpackPayload3(payload) {
1283
- try {
1284
- const json = Buffer.from(payload, "base64").toString("utf8");
1285
- const obj = JSON.parse(json);
1286
- if (typeof obj?.text === "string") return obj;
1287
- } catch {
1288
- }
1289
- return { text: "<ciphertext>" };
1290
- }
1291
- async function mROOM_send_message(input, ctx) {
1292
- readSupabaseEnv();
1293
- const thread_id = `privroom:${input.room_id}`;
1294
- ctx.log("debug", "mROOM_send_message", { thread_id });
1295
- const data = await invokeFunction(
1296
- "message-send",
1297
- {
1298
- space_id: "rooms",
1299
- thread_id,
1300
- encrypted_payload: packPlaintextPayload3(input.text, input.reply_to_id),
1301
- message_type: "text",
1302
- protocol_version: PROTOCOL_VERSION4,
1303
- reply_to_id: input.reply_to_id ?? null
1304
- }
1305
- );
1306
- if (!data?.message?.id) {
1307
- throw new Error("message-send returned no message id");
1308
- }
1309
- return {
1310
- message_id: data.message.id,
1311
- delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
1312
- thread_id
1313
- };
1314
- }
1315
- async function mROOM_list_messages(input, ctx) {
1316
- readSupabaseEnv();
1317
- const thread_id = `privroom:${input.room_id}`;
1318
- ctx.log("debug", "mROOM_list_messages", { thread_id });
1319
- const data = await invokeFunction("message-list", {
1320
- space_id: "rooms",
1321
- thread_id,
1322
- limit: input.limit ?? 50,
1323
- cursor: input.cursor
1324
- });
1325
- return {
1326
- messages: (data?.messages ?? []).map((m) => ({
1327
- id: m.id,
1328
- sender_identity_id: m.sender_identity_id,
1329
- text: unpackPayload3(m.encrypted_payload).text,
1330
- timestamp: m.created_at
1331
- })),
1332
- next_cursor: data?.next_cursor ?? null
1333
- };
1334
- }
1335
- var mroomMessagesTools = [
1336
- {
1337
- name: "mROOM_send_message",
1338
- requires: "network",
1339
- description: "Send a text message into a private room. Authorisation: must be a member (or guest with a valid token). Alpha payload is plaintext base64; v0.2 wraps with Double Ratchet.",
1340
- inputSchema: mROOM_send_message_input,
1341
- handler: mROOM_send_message
1342
- },
1343
- {
1344
- name: "mROOM_list_messages",
1345
- requires: "network",
1346
- description: "List recent text messages in a private room. Cursor-paginated, newest first.",
1347
- inputSchema: mROOM_list_messages_input,
1348
- handler: mROOM_list_messages
1349
- }
1350
- ];
1351
-
1352
- // src/tools/mail.ts
1353
- import { z as z9 } from "zod";
1354
- var EmailAddress = z9.string().email().max(254).describe("RFC 5321 email address.");
1355
- var MessageId = z9.string().min(1).describe("Message id (UUID) from mAIL_send or inbox.");
1356
- var mAIL_send_input = z9.object({
1357
- to: z9.union([EmailAddress, z9.array(EmailAddress).min(1).max(50)]).describe(
1358
- "Recipient(s). Single address or array of up to 50."
1359
- ),
1360
- subject: z9.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
1361
- body_text: z9.string().max(1048576).optional().describe("Plain text body. Max 1 MB."),
1362
- body_html: z9.string().max(1048576).optional().describe("HTML body. Max 1 MB."),
1363
- cc: z9.array(EmailAddress).max(50).optional(),
1364
- bcc: z9.array(EmailAddress).max(50).optional(),
1365
- reply_to: EmailAddress.optional()
1366
- });
1367
- var mAIL_view_input = z9.object({
1368
- message_id: MessageId
1369
- });
1370
- var mAIL_delete_input = z9.object({
1371
- message_id: MessageId
1372
- });
1373
- var mAIL_list_input = z9.object({
1374
- direction: z9.enum(["inbound", "outbound"]).optional().describe("Filter to received (inbound) or sent (outbound) mail. Omit for both."),
1375
- limit: z9.number().int().min(1).max(200).optional().describe("Max emails to return. Default 50."),
1376
- before: z9.string().optional().describe("Pagination cursor: pass the previous response's next_cursor to get the next (older) page.")
1377
- });
1378
- async function mAIL_send(input, ctx) {
1379
- readSupabaseEnv();
1380
- if (!input.body_text && !input.body_html) {
1381
- throw new Error("mAIL_send requires at least one of body_text or body_html.");
1382
- }
1383
- ctx.log("debug", "mAIL_send invoking mp0st-send", { to: input.to });
1384
- return await invokeFunction("mp0st-send", input);
1385
- }
1386
- async function mAIL_view(input, ctx) {
1387
- readSupabaseEnv();
1388
- ctx.log("debug", "mAIL_view invoking mp0st-view", { message_id: input.message_id });
1389
- return await invokeFunction("mp0st-view", { message_id: input.message_id });
1390
- }
1391
- async function mAIL_list(input, ctx) {
1392
- readSupabaseEnv();
1393
- ctx.log("debug", "mAIL_list invoking mp0st-list", { direction: input.direction });
1394
- return await invokeFunction("mp0st-list", {
1395
- direction: input.direction ?? null,
1396
- limit: input.limit ?? 50,
1397
- before: input.before ?? null
1398
- });
1399
- }
1400
- async function mAIL_delete(input, ctx) {
1401
- readSupabaseEnv();
1402
- ctx.log("debug", "mAIL_delete invoking mp0st-delete", { message_id: input.message_id });
1403
- return await invokeFunction("mp0st-delete", {
1404
- message_id: input.message_id
1405
- });
1406
- }
1407
- var mailTools = [
1408
- {
1409
- name: "mAIL_list",
1410
- requires: "network",
1411
- description: "List the user's mailbox (their <userId>@mosadd.com inbox/outbox) newest-first, with sender, subject, status and a short snippet. Filter by direction ('inbound' = received, 'outbound' = sent). Use the returned next_cursor with `before` to page through older mail. Call mAIL_view to read a full message body.",
1412
- inputSchema: mAIL_list_input,
1413
- handler: mAIL_list
1414
- },
1415
- {
1416
- name: "mAIL_send",
1417
- requires: "network",
1418
- description: "Send an email from the user's mosadd address (<userId>@mosadd.com). Pass body_text or body_html (or both). Supports cc, bcc, reply_to.",
1419
- inputSchema: mAIL_send_input,
1420
- handler: mAIL_send
1421
- },
1422
- {
1423
- name: "mAIL_view",
1424
- requires: "network",
1425
- description: "Read the full body and metadata of an email by message_id.",
1426
- inputSchema: mAIL_view_input,
1427
- handler: mAIL_view
1428
- },
1429
- {
1430
- name: "mAIL_delete",
1431
- requires: "network",
1432
- description: "Delete one of the user's emails by message_id (from mAIL_list). Soft-delete \u2014 it stops showing in mAIL_list. Owner-scoped: only your own mail.",
1433
- inputSchema: mAIL_delete_input,
1434
- handler: mAIL_delete
1435
- }
1436
- ];
1437
-
1438
- // src/tools/mtalk.ts
1439
- import { z as z10 } from "zod";
1440
- var RoomLabel = z10.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe("Human-readable room label (e.g. 'ops', 'field-team'). Used to derive a stable room id.");
1441
- var RoomId4 = z10.string().min(1).describe("Room id returned by mTALK_open.");
1442
- var mTALK_open_input = z10.object({
1443
- label: RoomLabel.optional().describe("Optional label; defaults to a personal room.")
1444
- });
1445
- var mTALK_join_input = z10.object({ room_id: RoomId4 });
1446
- var mTALK_press_input = z10.object({ room_id: RoomId4 });
1447
- var mTALK_release_input = z10.object({ room_id: RoomId4 });
1448
- var mTALK_state_input = z10.object({ room_id: RoomId4 });
1449
- async function mTALK_open(input, ctx) {
1450
- const { roomId } = await ctx.providers.voice.createRoom(input.label);
1451
- ctx.log("debug", "mTALK_open", { room_id: roomId });
1452
- return { room_id: roomId };
1453
- }
1454
- async function mTALK_join(input, ctx) {
1455
- const ticket = await ctx.providers.voice.joinTicket(input.room_id);
1456
- ctx.log("debug", "mTALK_join", { room_id: ticket.roomId, identity: ticket.identity });
1457
- return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
1458
- }
1459
- async function mTALK_press(input, ctx) {
1460
- const res = await ctx.providers.voice.requestFloor(input.room_id);
1461
- ctx.log("debug", "mTALK_press", { room_id: input.room_id, granted: res.granted, position: res.position });
1462
- return { granted: res.granted, position: res.position, holder: res.snapshot.holder, queue: res.snapshot.queue };
1463
- }
1464
- async function mTALK_release(input, ctx) {
1465
- const snap = await ctx.providers.voice.releaseFloor(input.room_id);
1466
- ctx.log("debug", "mTALK_release", { room_id: input.room_id, holder: snap.holder });
1467
- return { holder: snap.holder, queue: snap.queue };
1468
- }
1469
- async function mTALK_state(input, ctx) {
1470
- const snap = await ctx.providers.voice.floorState(input.room_id);
1471
- return { holder: snap.holder, since: snap.since, queue: snap.queue };
1472
- }
1473
- var mtalkTools = [
1474
- {
1475
- name: "mTALK_open",
1476
- requires: "any",
1477
- description: "Open (or get) a push-to-talk room. Returns a stable room_id. Pass an optional label to share a named room (e.g. 'ops'); omit it for a personal room. Works over network (LiveKit) or off-grid radio depending on the host.",
1478
- inputSchema: mTALK_open_input,
1479
- handler: mTALK_open
1480
- },
1481
- {
1482
- name: "mTALK_join",
1483
- requires: "network",
1484
- description: "Get credentials (token + media URL) to join a PTT room's audio transport. Hand these to a human or bot client to connect. The agent itself drives the floor with mTALK_press / mTALK_release.",
1485
- inputSchema: mTALK_join_input,
1486
- handler: mTALK_join
1487
- },
1488
- {
1489
- name: "mTALK_press",
1490
- requires: "any",
1491
- description: "Press push-to-talk: request the floor in a room. Half-duplex \u2014 if no one is transmitting you are GRANTED the floor (granted=true) and may speak; otherwise you are queued FIFO and `position` tells you where you are. Call mTALK_release when done. A holder who never releases is auto-bumped after the anti-hog timeout.",
1492
- inputSchema: mTALK_press_input,
1493
- handler: mTALK_press
1494
- },
1495
- {
1496
- name: "mTALK_release",
1497
- requires: "any",
1498
- description: "Release push-to-talk: give up the floor (or cancel your queued request). If you held the floor, the next participant in the queue is promoted automatically. Returns the new holder and queue.",
1499
- inputSchema: mTALK_release_input,
1500
- handler: mTALK_release
1501
- },
1502
- {
1503
- name: "mTALK_state",
1504
- requires: "any",
1505
- description: "Read a PTT room's floor state without changing it: who is currently transmitting (holder), since when, and the waiting queue.",
1506
- inputSchema: mTALK_state_input,
1507
- handler: mTALK_state
1508
- }
1509
- ];
1510
-
1511
- // src/tools/knowledge.ts
1512
- import { z as z11 } from "zod";
1513
- var mRAG_search_input = z11.object({
1514
- query: z11.string().min(1).max(2e3).describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
1515
- top_k: z11.number().int().min(1).max(25).optional().describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
1516
- source_types: z11.array(z11.enum(["message", "email", "call", "note", "contact"])).optional().describe("Restrict retrieval to these source types. Omit to search everything."),
1517
- thread_id: z11.string().optional().describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread).")
1518
- });
1519
- async function mRAG_search(input, ctx) {
1520
- readSupabaseEnv();
1521
- ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
1522
- const data = await invokeFunction("rag-query", {
1523
- query: input.query,
1524
- top_k: input.top_k ?? 8,
1525
- source_types: input.source_types ?? null,
1526
- thread_id: input.thread_id ?? null
1527
- });
1528
- return {
1529
- answer: data.answer ?? "",
1530
- sources: data.sources ?? [],
1531
- chunks_found: data.chunks_found ?? (data.sources?.length ?? 0)
1532
- };
1533
- }
1534
- var mRAG_ingest_input = z11.object({
1535
- content_text: z11.string().min(1).max(2e5).describe("Text to index into the user's private knowledge base (a note, document, transcript, pasted page\u2026). Chunked + embedded server-side."),
1536
- source_type: z11.enum(["file", "note", "message", "email", "contact", "call"]).optional().describe("What kind of source this is. Default 'file' (a document/note). Use 'note' for ad-hoc text."),
1537
- source_id: z11.string().optional().describe("Optional stable id for the source so re-ingests can be grouped."),
1538
- thread_id: z11.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
1539
- title: z11.string().max(300).optional().describe("Optional human title, stored in metadata.")
1540
- });
1541
- async function mRAG_ingest(input, ctx) {
1542
- readSupabaseEnv();
1543
- const backendType = input.source_type === "note" ? "file" : input.source_type ?? "file";
1544
- ctx.log("debug", "mRAG_ingest via rag-index", { source_type: backendType });
1545
- const data = await invokeFunction("rag-index", {
1546
- source_type: backendType,
1547
- source_id: input.source_id ?? null,
1548
- thread_id: input.thread_id ?? null,
1549
- content_text: input.content_text,
1550
- metadata: { ...input.title ? { title: input.title } : {}, ingested_via: "mRAG_ingest" }
1551
- });
1552
- return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
1553
- }
1554
- var knowledgeTools = [
1555
- {
1556
- name: "mRAG_ingest",
1557
- requires: "network",
1558
- description: "Add text to the USER'S OWN private knowledge base so mRAG_search can recall it later. Pass content_text (a note, document, transcript, pasted page); it is semantically chunked, embedded (1536-d) and stored in the per-user vector index mRAG_search reads. Returns how many chunks were indexed. NOTE: indexed content is stored server-side in plaintext \u2014 NOT covered by the zero-knowledge / E2EE guarantee. Only ingest what the user opted to make searchable.",
1559
- inputSchema: mRAG_ingest_input,
1560
- handler: mRAG_ingest
1561
- },
1562
- {
1563
- name: "mRAG_search",
1564
- requires: "network",
1565
- description: "Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private per-user RAG index \u2014 hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. Returns an answer plus the source snippets it used. This is agent memory (mRAG = RAG over your own data) over the user's communications, available outside the mosadd app. NOTE: RAG requires content to be indexed server-side in plaintext, so anything searchable here is NOT covered by the zero-knowledge / E2EE guarantee \u2014 only data the user has explicitly opted into indexing is searchable. See docs/security/e2ee-posture.md.",
1566
- inputSchema: mRAG_search_input,
1567
- handler: mRAG_search
1568
- }
1569
- ];
1570
-
1571
- // src/tools/capabilities.ts
1572
- import { z as z12 } from "zod";
1573
- var CONTRACT_VERSION = "1.0.0";
1574
- var ALL_REQUIREMENTS = ["any", "radio", "network"];
1575
- function buildCapabilityManifest(tools) {
1576
- const entries = tools.map((t) => ({ name: t.name, requires: t.requires }));
1577
- const by_requirement = {
1578
- any: [],
1579
- radio: [],
1580
- network: []
1581
- };
1582
- for (const e of entries) by_requirement[e.requires].push(e.name);
1583
- return {
1584
- contract_version: CONTRACT_VERSION,
1585
- requirements: ALL_REQUIREMENTS,
1586
- tools: entries,
1587
- by_requirement
1588
- };
1589
- }
1590
- function makeCapabilitiesTool(channelTools2) {
1591
- const tool = {
1592
- name: "comms_capabilities",
1593
- requires: "any",
1594
- description: "Discover which mosadd tools are available and what transport each requires (any | radio | network). Carrier-aware hosts (e.g. off-grid radio devices) call this once to gate the tool list to what the current carrier supports. Returns a manifest with per-tool requirements grouped by transport.",
1595
- inputSchema: z12.object({}),
1596
- handler: async () => buildCapabilityManifest([...channelTools2, tool])
1597
- };
1598
- return tool;
1599
- }
1600
-
1601
- // src/tools/index.ts
1602
- var channelTools = [
1603
- ...mdmTools,
1604
- ...mdmVoiceTools,
1605
- ...mircTools,
1606
- ...mircMembersTools,
1607
- ...mircMessagesTools,
1608
- ...mircEdgeTools,
1609
- ...mroomTools,
1610
- ...mroomMessagesTools,
1611
- ...mailTools,
1612
- ...mtalkTools,
1613
- ...knowledgeTools
1614
- // ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
1615
- // mirlTools,
1616
- // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
1617
- //
1618
- // Each m* module registers its tools here as it ships.
1619
- // RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
1620
- ];
1621
- var allTools = [
1622
- ...channelTools,
1623
- // comms_capabilities: one-call discovery of every tool's `requires` flag,
1624
- // so carrier-aware hosts (cymru-os) can gate the tool list by transport.
1625
- makeCapabilitiesTool(channelTools)
1626
- ];
1627
-
1628
- // src/server.ts
1629
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1630
-
1631
- // src/providers/supabase-dm.ts
1632
- var PROTOCOL_VERSION5 = "mosadd.chat.v1";
1633
- var SupabaseDmProvider = class {
1634
- cachedSelfId = null;
1635
- async selfId() {
1636
- if (this.cachedSelfId) return this.cachedSelfId;
1637
- readSupabaseEnv();
1638
- const sb = getSupabase();
1639
- const { data: u, error: ue } = await sb.auth.getUser();
1640
- if (ue || !u?.user) {
1641
- throw new Error(
1642
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
1643
- );
1644
- }
1645
- const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
1646
- if (error || !identity) {
1647
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
1648
- }
1649
- this.cachedSelfId = identity.id;
1650
- return this.cachedSelfId;
1651
- }
1652
- async send(args) {
1653
- const encrypted_payload = Buffer.from(args.payload).toString("base64");
1654
- const data = await invokeFunction("message-send", {
1655
- space_id: "dm",
1656
- thread_id: args.threadId,
1657
- encrypted_payload,
1658
- message_type: "text",
1659
- protocol_version: PROTOCOL_VERSION5,
1660
- recipient_account_id: args.to,
1661
- reply_to_id: args.replyToId ?? null
1662
- });
1663
- if (!data?.message?.id) {
1664
- throw new Error("message-send returned no message id");
1665
- }
1666
- return {
1667
- id: data.message.id,
1668
- deliveredAt: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
1669
- };
1670
- }
1671
- async publishPrekeyBundle(bundle) {
1672
- await invokeFunction("prekey-bundle-publish", {
1673
- bundle: Buffer.from(bundle).toString("base64")
1674
- });
1675
- }
1676
- async fetchPrekeyBundle(peerId) {
1677
- const data = await invokeFunction("prekey-bundle-fetch", {
1678
- peer_id: peerId
1679
- });
1680
- if (!data?.bundle) return null;
1681
- return new Uint8Array(Buffer.from(data.bundle, "base64"));
1682
- }
1683
- async list(args) {
1684
- const data = await invokeFunction("message-list", {
1685
- space_id: "dm",
1686
- thread_id: args.threadId,
1687
- limit: args.limit ?? 50,
1688
- cursor: args.cursor
1689
- });
1690
- return {
1691
- messages: (data?.messages ?? []).map((m) => ({
1692
- id: m.id,
1693
- senderId: m.sender_identity_id,
1694
- payload: new Uint8Array(Buffer.from(m.encrypted_payload, "base64")),
1695
- timestamp: m.created_at,
1696
- threadId: m.thread_id
1697
- })),
1698
- nextCursor: data?.next_cursor ?? null
1699
- };
1700
- }
1701
- };
1702
-
1703
- // src/providers/supabase-voice.ts
1704
- var ROOM_PREFIX = "mosadd-room-";
1705
- var SupabaseVoiceProvider = class {
1706
- cachedSelfId = null;
1707
- async selfId() {
1708
- if (this.cachedSelfId) return this.cachedSelfId;
1709
- readSupabaseEnv();
1710
- const sb = getSupabase();
1711
- const { data: u, error: ue } = await sb.auth.getUser();
1712
- if (ue || !u?.user) {
1713
- throw new Error(
1714
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
1715
- );
1716
- }
1717
- const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
1718
- if (error || !identity) {
1719
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
1720
- }
1721
- this.cachedSelfId = identity.id;
1722
- return this.cachedSelfId;
1723
- }
1724
- async createRoom(label) {
1725
- const self = await this.selfId();
1726
- const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
1727
- return { roomId };
1728
- }
1729
- async joinTicket(roomId) {
1730
- const self = await this.selfId();
1731
- const data = await invokeFunction("livekit-token", {
1732
- roomName: roomId,
1733
- identity: self
1734
- });
1735
- return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
1736
- }
1737
- async requestFloor(roomId) {
1738
- return invokeFunction("mtalk-floor", { action: "request", room_id: roomId });
1739
- }
1740
- async releaseFloor(roomId) {
1741
- const data = await invokeFunction("mtalk-floor", {
1742
- action: "release",
1743
- room_id: roomId
1744
- });
1745
- return data.snapshot;
1746
- }
1747
- async floorState(roomId) {
1748
- const data = await invokeFunction("mtalk-floor", {
1749
- action: "state",
1750
- room_id: roomId
1751
- });
1752
- return data.snapshot;
1753
- }
1754
- };
1755
- function slug(s) {
1756
- return s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 200);
1757
- }
1758
-
1759
- // src/server.ts
1760
- function defaultProviders(injected) {
1761
- return {
1762
- dm: injected?.dm ?? new SupabaseDmProvider(),
1763
- keys: injected?.keys ?? new InMemoryMdmKeyStore(),
1764
- voice: injected?.voice ?? new SupabaseVoiceProvider()
1765
- };
1766
- }
1767
- function createMosaddServer(options = {}) {
1768
- const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
1769
- const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
1770
- const logLevel = options.logLevel ?? "info";
1771
- const providers = defaultProviders(options.providers);
1772
- const ctx = {
1773
- options: { ...options, mode, hubUrl },
1774
- providers,
1775
- log: (level, msg, extra) => {
1776
- if (shouldLog(level, logLevel)) {
1777
- process.stderr.write(
1778
- JSON.stringify({ level, msg, extra, ts: (/* @__PURE__ */ new Date()).toISOString() }) + "\n"
1779
- );
1780
- }
1781
- }
1782
- };
1783
- const server = new McpServer(
1784
- {
1785
- name: "mosadd",
1786
- version: "3.0.0-alpha.0"
1787
- },
1788
- {
1789
- capabilities: {
1790
- tools: {}
1791
- }
1792
- }
1793
- );
1794
- for (const tool of allTools) {
1795
- const shape = tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema ? tool.inputSchema.shape : tool.inputSchema;
1796
- server.tool(
1797
- tool.name,
1798
- tool.description,
1799
- shape,
1800
- async (input) => {
1801
- const parsed = tool.inputSchema.parse(input);
1802
- try {
1803
- const result = await tool.handler(parsed, ctx);
1804
- return {
1805
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1806
- };
1807
- } catch (err) {
1808
- ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
1809
- return {
1810
- isError: true,
1811
- content: [
1812
- {
1813
- type: "text",
1814
- text: JSON.stringify({
1815
- error: err instanceof Error ? err.message : String(err),
1816
- tool: tool.name
1817
- })
1818
- }
1819
- ]
1820
- };
1821
- }
1822
- }
1823
- );
1824
- }
1825
- return server;
1826
- }
1827
- function shouldLog(level, threshold) {
1828
- const order = { debug: 0, info: 1, warn: 2, error: 3 };
1829
- return (order[level] ?? 1) >= (order[threshold] ?? 1);
1830
- }
1831
-
1832
- export {
1833
- allTools,
1834
- defaultProviders,
1835
- createMosaddServer
1836
- };