@mosadd/mcp 3.0.0-alpha.3 → 3.0.0-alpha.31
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.
- package/CHANGELOG.md +224 -0
- package/README.md +150 -116
- package/dist/bin/mcp.js +42 -3
- package/dist/chunk-P4ENU5MW.js +2556 -0
- package/dist/index.d.ts +99 -7
- package/dist/index.js +7 -3
- package/package.json +10 -7
- package/src/__tests__/golden-path.test.ts +137 -132
- package/src/__tests__/integration.test.ts +179 -175
- package/src/__tests__/mdm-e2ee.test.ts +212 -149
- package/src/__tests__/mtalk.test.ts +122 -0
- package/src/__tests__/server.test.ts +71 -67
- package/src/bin/login.ts +138 -138
- package/src/bin/mcp.ts +145 -97
- package/src/config.ts +66 -66
- package/src/crypto/mdm-session.ts +502 -378
- package/src/index.ts +19 -17
- package/src/observability/sentry.ts +79 -79
- package/src/providers/blob-upload.ts +116 -0
- package/src/providers/memory-voice.ts +79 -0
- package/src/providers/supabase-dm.ts +122 -117
- package/src/providers/supabase-voice.ts +91 -0
- package/src/providers/supabase.ts +148 -96
- package/src/server.ts +123 -103
- package/src/tools/actions.ts +162 -0
- package/src/tools/attachments.ts +268 -0
- package/src/tools/capabilities.ts +68 -68
- package/src/tools/embed.ts +108 -0
- package/src/tools/index.ts +104 -37
- package/src/tools/knowledge.ts +191 -0
- package/src/tools/mail-aliases.ts +25 -0
- package/src/tools/mail-provenance.ts +135 -0
- package/src/tools/mail.ts +381 -89
- package/src/tools/mcall.ts +216 -0
- package/src/tools/mdm-voice.ts +212 -0
- package/src/tools/mdm.ts +479 -379
- package/src/tools/mirc-edge.ts +190 -0
- package/src/tools/mirc-members.ts +198 -177
- package/src/tools/mirc-messages.ts +155 -0
- package/src/tools/mirc.ts +190 -170
- package/src/tools/mroom-messages.ts +142 -142
- package/src/tools/mroom.ts +221 -189
- package/src/tools/mtalk.ts +121 -0
- package/src/tools/murl.ts +298 -0
- package/src/tools/ptt-ingest.ts +97 -0
- package/src/tools/threat.ts +119 -0
- package/src/types.ts +94 -79
- package/src/voice/floor.ts +132 -0
- package/dist/chunk-HD5RLE5K.js +0 -1193
|
@@ -0,0 +1,2556 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isSessionExpired,
|
|
3
|
+
loadSession
|
|
4
|
+
} from "./chunk-Z7WR52GE.js";
|
|
5
|
+
|
|
6
|
+
// src/providers/supabase.ts
|
|
7
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
8
|
+
import { createClient } from "@supabase/supabase-js";
|
|
9
|
+
var requestEnv = new AsyncLocalStorage();
|
|
10
|
+
function runWithSupabaseEnv(env, fn) {
|
|
11
|
+
return requestEnv.run(env, fn);
|
|
12
|
+
}
|
|
13
|
+
var MissingSupabaseEnvError = class extends Error {
|
|
14
|
+
constructor(missing) {
|
|
15
|
+
super(
|
|
16
|
+
`Missing Supabase credentials: ${missing.join(", ")}. Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`
|
|
17
|
+
);
|
|
18
|
+
this.name = "MissingSupabaseEnvError";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
function readSupabaseEnv() {
|
|
22
|
+
const perRequest = requestEnv.getStore();
|
|
23
|
+
if (perRequest) return perRequest;
|
|
24
|
+
const env = (canonical, legacy) => process.env[canonical] ?? process.env[legacy];
|
|
25
|
+
const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
|
|
26
|
+
const session = loadSession();
|
|
27
|
+
const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
|
|
28
|
+
const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
|
|
29
|
+
const userJwt = userJwtEnv ?? session?.accessToken;
|
|
30
|
+
const missing = [];
|
|
31
|
+
if (!url) missing.push("MOSADD_SUPABASE_URL");
|
|
32
|
+
if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
|
|
33
|
+
if (missing.length) throw new MissingSupabaseEnvError(missing);
|
|
34
|
+
if (!userJwtEnv && session && isSessionExpired(session)) {
|
|
35
|
+
throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
|
|
36
|
+
}
|
|
37
|
+
return { url, anonKey, userJwt };
|
|
38
|
+
}
|
|
39
|
+
function getSupabase(env = readSupabaseEnv()) {
|
|
40
|
+
return createClient(env.url, env.anonKey, {
|
|
41
|
+
auth: {
|
|
42
|
+
persistSession: false,
|
|
43
|
+
autoRefreshToken: false,
|
|
44
|
+
detectSessionInUrl: false
|
|
45
|
+
},
|
|
46
|
+
global: env.userJwt ? {
|
|
47
|
+
headers: { Authorization: `Bearer ${env.userJwt}` }
|
|
48
|
+
} : void 0
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async function invokeFunction(fn, body) {
|
|
52
|
+
const client = getSupabase();
|
|
53
|
+
const { data, error } = await client.functions.invoke(fn, { body });
|
|
54
|
+
if (error) {
|
|
55
|
+
let msg = error instanceof Error && error.message ? error.message : `Edge function ${fn} failed`;
|
|
56
|
+
const ctx = error.context;
|
|
57
|
+
if (ctx && typeof ctx.text === "function") {
|
|
58
|
+
const res = ctx;
|
|
59
|
+
try {
|
|
60
|
+
const raw = await res.text();
|
|
61
|
+
if (raw) {
|
|
62
|
+
let detail = raw;
|
|
63
|
+
try {
|
|
64
|
+
const parsed = JSON.parse(raw);
|
|
65
|
+
detail = typeof parsed.error === "string" && parsed.error || typeof parsed.message === "string" && parsed.message || raw;
|
|
66
|
+
} catch {
|
|
67
|
+
}
|
|
68
|
+
const status = typeof res.status === "number" ? res.status : void 0;
|
|
69
|
+
msg = status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`;
|
|
70
|
+
}
|
|
71
|
+
} catch {
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
throw new Error(msg);
|
|
75
|
+
}
|
|
76
|
+
if (data == null) {
|
|
77
|
+
throw new Error(`Edge function ${fn} returned no data`);
|
|
78
|
+
}
|
|
79
|
+
return data;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/tools/mdm.ts
|
|
83
|
+
import { z } from "zod";
|
|
84
|
+
|
|
85
|
+
// src/crypto/mdm-session.ts
|
|
86
|
+
import {
|
|
87
|
+
decryptBytes,
|
|
88
|
+
encryptBytes,
|
|
89
|
+
generateEd25519KeyPair,
|
|
90
|
+
generateX25519KeyPair,
|
|
91
|
+
initializeRatchet,
|
|
92
|
+
performX3dh,
|
|
93
|
+
performX3dhResponder,
|
|
94
|
+
ratchetReceive,
|
|
95
|
+
ratchetSend,
|
|
96
|
+
signEd25519,
|
|
97
|
+
verifyEd25519,
|
|
98
|
+
toBase64,
|
|
99
|
+
fromBase64,
|
|
100
|
+
initRatchetInitiator,
|
|
101
|
+
initRatchetResponder,
|
|
102
|
+
ratchetEncrypt,
|
|
103
|
+
ratchetDecrypt
|
|
104
|
+
} from "@mosadd/crypto";
|
|
105
|
+
var PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1";
|
|
106
|
+
var E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1";
|
|
107
|
+
var E2EE_ENVELOPE_VERSION_V2 = "mosadd.e2ee.v2";
|
|
108
|
+
var DEFAULT_ONE_TIME_PREKEYS = 8;
|
|
109
|
+
var InMemoryMdmKeyStore = class {
|
|
110
|
+
material = null;
|
|
111
|
+
oneTimeById = /* @__PURE__ */ new Map();
|
|
112
|
+
sessions = /* @__PURE__ */ new Map();
|
|
113
|
+
sentMessages = /* @__PURE__ */ new Map();
|
|
114
|
+
async getOwnMaterial() {
|
|
115
|
+
if (this.material) return this.material;
|
|
116
|
+
const identity = await generateX25519KeyPair();
|
|
117
|
+
const signingIdentity = await generateEd25519KeyPair();
|
|
118
|
+
const signedPrekeyPair = await generateX25519KeyPair();
|
|
119
|
+
const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
|
|
120
|
+
const oneTimePrekeys = [];
|
|
121
|
+
for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
|
|
122
|
+
const pair = await generateX25519KeyPair();
|
|
123
|
+
const id = randomId();
|
|
124
|
+
oneTimePrekeys.push({ id, pair });
|
|
125
|
+
this.oneTimeById.set(id, pair.privateKey);
|
|
126
|
+
}
|
|
127
|
+
this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
|
|
128
|
+
return this.material;
|
|
129
|
+
}
|
|
130
|
+
async takeOneTimePrekey(id) {
|
|
131
|
+
const priv = this.oneTimeById.get(id);
|
|
132
|
+
if (priv) this.oneTimeById.delete(id);
|
|
133
|
+
return priv;
|
|
134
|
+
}
|
|
135
|
+
async getSession(peerId) {
|
|
136
|
+
return this.sessions.get(peerId);
|
|
137
|
+
}
|
|
138
|
+
async putSession(peerId, record) {
|
|
139
|
+
this.sessions.set(peerId, record);
|
|
140
|
+
}
|
|
141
|
+
async putSentMessage(messageId, plaintext) {
|
|
142
|
+
this.sentMessages.set(messageId, plaintext);
|
|
143
|
+
}
|
|
144
|
+
async getSentMessage(messageId) {
|
|
145
|
+
return this.sentMessages.get(messageId);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
function randomId() {
|
|
149
|
+
return crypto.getRandomValues(new Uint32Array(1))[0];
|
|
150
|
+
}
|
|
151
|
+
function bundleSigningMessage(dhIdentityPub, signedPrekeyPub) {
|
|
152
|
+
const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
|
|
153
|
+
msg.set(dhIdentityPub, 0);
|
|
154
|
+
msg.set(signedPrekeyPub, dhIdentityPub.length);
|
|
155
|
+
return msg;
|
|
156
|
+
}
|
|
157
|
+
function serializePublicBundle(material) {
|
|
158
|
+
const signature = signEd25519(
|
|
159
|
+
material.signingIdentity.privateKey,
|
|
160
|
+
bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey)
|
|
161
|
+
);
|
|
162
|
+
const json = JSON.stringify({
|
|
163
|
+
v: PREKEY_BUNDLE_VERSION,
|
|
164
|
+
ik: toBase64(material.identity.publicKey),
|
|
165
|
+
sik: toBase64(material.signingIdentity.publicKey),
|
|
166
|
+
spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
|
|
167
|
+
opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
|
|
168
|
+
sig: toBase64(signature)
|
|
169
|
+
});
|
|
170
|
+
return new Uint8Array(Buffer.from(json, "utf8"));
|
|
171
|
+
}
|
|
172
|
+
function parsePublicBundle(bytes) {
|
|
173
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
174
|
+
if (obj?.v !== PREKEY_BUNDLE_VERSION) {
|
|
175
|
+
throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
|
|
176
|
+
}
|
|
177
|
+
if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
|
|
178
|
+
throw new Error("Prekey bundle is missing its signing identity / signature.");
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
identityPublicKey: fromBase64(obj.ik),
|
|
182
|
+
signingIdentityPublicKey: fromBase64(obj.sik),
|
|
183
|
+
signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
|
|
184
|
+
oneTimePrekeys: (obj.opks ?? []).map((k) => ({
|
|
185
|
+
id: k.id,
|
|
186
|
+
publicKey: fromBase64(k.pub)
|
|
187
|
+
})),
|
|
188
|
+
signature: fromBase64(obj.sig)
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function verifyPublicBundle(bundle) {
|
|
192
|
+
return verifyEd25519(
|
|
193
|
+
bundle.signature,
|
|
194
|
+
bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
|
|
195
|
+
bundle.signingIdentityPublicKey
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
function isE2eeEnvelope(bytes) {
|
|
199
|
+
try {
|
|
200
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
201
|
+
if (!obj?.ct) return false;
|
|
202
|
+
if (obj.v === E2EE_ENVELOPE_VERSION) return typeof obj.i === "number";
|
|
203
|
+
if (obj.v === E2EE_ENVELOPE_VERSION_V2) return typeof obj.dh === "string" && typeof obj.n === "number";
|
|
204
|
+
return false;
|
|
205
|
+
} catch {
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function peekEnvelopeVersion(bytes) {
|
|
210
|
+
try {
|
|
211
|
+
return JSON.parse(Buffer.from(bytes).toString("utf8"))?.v;
|
|
212
|
+
} catch {
|
|
213
|
+
return void 0;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function serializeEnvelope(env) {
|
|
217
|
+
return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
|
|
218
|
+
}
|
|
219
|
+
function parseEnvelope(bytes) {
|
|
220
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
221
|
+
if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
|
|
222
|
+
return obj;
|
|
223
|
+
}
|
|
224
|
+
function parseEnvelopeV2(bytes) {
|
|
225
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
226
|
+
if (obj?.v !== E2EE_ENVELOPE_VERSION_V2) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
|
|
227
|
+
return obj;
|
|
228
|
+
}
|
|
229
|
+
async function publishOwnPrekeys(keystore, dm) {
|
|
230
|
+
const material = await keystore.getOwnMaterial();
|
|
231
|
+
await dm.publishPrekeyBundle(serializePublicBundle(material));
|
|
232
|
+
return { oneTimePrekeyCount: material.oneTimePrekeys.length };
|
|
233
|
+
}
|
|
234
|
+
async function encryptForPeer(keystore, dm, peerId, plaintext) {
|
|
235
|
+
let session = await keystore.getSession(peerId);
|
|
236
|
+
if (!session) {
|
|
237
|
+
const raw = await dm.fetchPrekeyBundle(peerId);
|
|
238
|
+
if (!raw) {
|
|
239
|
+
throw new Error(
|
|
240
|
+
`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.`
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
const peer = parsePublicBundle(raw);
|
|
244
|
+
if (!verifyPublicBundle(peer)) {
|
|
245
|
+
throw new Error(
|
|
246
|
+
`Prekey bundle for "${peerId}" failed signature verification \u2014 refusing to start an encrypted session (possible tampering / man-in-the-middle).`
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
const own = await keystore.getOwnMaterial();
|
|
250
|
+
const ephemeral = await generateX25519KeyPair();
|
|
251
|
+
const opk = peer.oneTimePrekeys[0];
|
|
252
|
+
const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
|
|
253
|
+
identityPublicKey: peer.identityPublicKey,
|
|
254
|
+
signedPreKeyPublicKey: peer.signedPrekey.publicKey,
|
|
255
|
+
oneTimePreKeyPublicKey: opk?.publicKey
|
|
256
|
+
});
|
|
257
|
+
const ratchet2 = await initRatchetInitiator(rootKey, peer.signedPrekey.publicKey);
|
|
258
|
+
session = {
|
|
259
|
+
ratchet2,
|
|
260
|
+
role: "initiator",
|
|
261
|
+
pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id }
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
if (session.ratchet2) {
|
|
265
|
+
const { header, ct: ct2 } = await ratchetEncrypt(session.ratchet2, plaintext);
|
|
266
|
+
const env2 = {
|
|
267
|
+
v: E2EE_ENVELOPE_VERSION_V2,
|
|
268
|
+
dh: toBase64(header.dh),
|
|
269
|
+
pn: header.pn,
|
|
270
|
+
n: header.n,
|
|
271
|
+
ct: ct2
|
|
272
|
+
};
|
|
273
|
+
if (session.pendingHandshake) {
|
|
274
|
+
env2.hdr = {
|
|
275
|
+
ik: toBase64(session.pendingHandshake.ik),
|
|
276
|
+
ek: toBase64(session.pendingHandshake.ek),
|
|
277
|
+
opk: session.pendingHandshake.opkId
|
|
278
|
+
};
|
|
279
|
+
session.pendingHandshake = void 0;
|
|
280
|
+
}
|
|
281
|
+
await keystore.putSession(peerId, session);
|
|
282
|
+
return serializeEnvelope(env2);
|
|
283
|
+
}
|
|
284
|
+
const step = await ratchetSend(session.ratchet);
|
|
285
|
+
const ct = await encryptBytes(step.messageKey, plaintext);
|
|
286
|
+
const env = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
|
|
287
|
+
if (session.pendingHandshake && step.messageIndex === 0) {
|
|
288
|
+
env.hdr = {
|
|
289
|
+
ik: toBase64(session.pendingHandshake.ik),
|
|
290
|
+
ek: toBase64(session.pendingHandshake.ek),
|
|
291
|
+
opk: session.pendingHandshake.opkId
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
session.pendingHandshake = void 0;
|
|
295
|
+
await keystore.putSession(peerId, session);
|
|
296
|
+
return serializeEnvelope(env);
|
|
297
|
+
}
|
|
298
|
+
async function responderRootKey(keystore, hdr) {
|
|
299
|
+
const own = await keystore.getOwnMaterial();
|
|
300
|
+
let oneTimePreKeyPrivateKey;
|
|
301
|
+
if (hdr.opk !== void 0) {
|
|
302
|
+
oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(hdr.opk);
|
|
303
|
+
if (!oneTimePreKeyPrivateKey) {
|
|
304
|
+
throw new Error(`Handshake references one-time prekey ${hdr.opk} which is unknown or already consumed.`);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const { rootKey } = await performX3dhResponder(
|
|
308
|
+
{
|
|
309
|
+
identityPrivateKey: own.identity.privateKey,
|
|
310
|
+
signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
|
|
311
|
+
oneTimePreKeyPrivateKey
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
initiatorIdentityPublicKey: fromBase64(hdr.ik),
|
|
315
|
+
initiatorEphemeralPublicKey: fromBase64(hdr.ek),
|
|
316
|
+
usedOneTimePreKeyId: hdr.opk
|
|
317
|
+
}
|
|
318
|
+
);
|
|
319
|
+
return rootKey;
|
|
320
|
+
}
|
|
321
|
+
async function decryptFromPeer(keystore, peerId, envelopeBytes) {
|
|
322
|
+
if (peekEnvelopeVersion(envelopeBytes) === E2EE_ENVELOPE_VERSION_V2) {
|
|
323
|
+
const env2 = parseEnvelopeV2(envelopeBytes);
|
|
324
|
+
let session2 = await keystore.getSession(peerId);
|
|
325
|
+
if (!session2) {
|
|
326
|
+
if (!env2.hdr) {
|
|
327
|
+
throw new Error(`No session with "${peerId}" and the message carries no handshake header \u2014 cannot decrypt.`);
|
|
328
|
+
}
|
|
329
|
+
const rootKey = await responderRootKey(keystore, env2.hdr);
|
|
330
|
+
const own = await keystore.getOwnMaterial();
|
|
331
|
+
const ratchet2 = await initRatchetResponder(rootKey, {
|
|
332
|
+
publicKey: own.signedPrekey.pair.publicKey,
|
|
333
|
+
privateKey: own.signedPrekey.pair.privateKey
|
|
334
|
+
});
|
|
335
|
+
session2 = { ratchet2, role: "responder" };
|
|
336
|
+
}
|
|
337
|
+
if (!session2.ratchet2) {
|
|
338
|
+
throw new Error(`Received a v2 mDM envelope but the session with "${peerId}" is v1 \u2014 refusing to mix ratchets.`);
|
|
339
|
+
}
|
|
340
|
+
const plaintext2 = await ratchetDecrypt(
|
|
341
|
+
session2.ratchet2,
|
|
342
|
+
{ dh: fromBase64(env2.dh), pn: env2.pn, n: env2.n },
|
|
343
|
+
env2.ct
|
|
344
|
+
);
|
|
345
|
+
await keystore.putSession(peerId, session2);
|
|
346
|
+
return plaintext2;
|
|
347
|
+
}
|
|
348
|
+
const env = parseEnvelope(envelopeBytes);
|
|
349
|
+
let session = await keystore.getSession(peerId);
|
|
350
|
+
if (!session) {
|
|
351
|
+
if (!env.hdr) {
|
|
352
|
+
throw new Error(`No session with "${peerId}" and the message carries no handshake header \u2014 cannot decrypt.`);
|
|
353
|
+
}
|
|
354
|
+
const rootKey = await responderRootKey(keystore, env.hdr);
|
|
355
|
+
const ratchet = await initializeRatchet(rootKey, "responder");
|
|
356
|
+
session = { ratchet, role: "responder" };
|
|
357
|
+
}
|
|
358
|
+
if (!session.ratchet) {
|
|
359
|
+
throw new Error(`Received a v1 mDM envelope but the session with "${peerId}" is v2 \u2014 refusing to mix ratchets.`);
|
|
360
|
+
}
|
|
361
|
+
const step = await ratchetReceive(session.ratchet);
|
|
362
|
+
if (step.messageIndex !== env.i) {
|
|
363
|
+
throw new Error(
|
|
364
|
+
`Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). Skipped-key handling is a tracked follow-up (LINEAR-2357).`
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
const plaintext = await decryptBytes(step.messageKey, env.ct);
|
|
368
|
+
await keystore.putSession(peerId, session);
|
|
369
|
+
return plaintext;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/tools/mdm.ts
|
|
373
|
+
var PROTOCOL_VERSION = "mosadd.chat.v1";
|
|
374
|
+
var ContactRef = z.string().min(1).describe(
|
|
375
|
+
"Recipient identity id (UUID). Use mDM_list_contacts first to find the right id. Future versions will accept handle/email/phone directly."
|
|
376
|
+
);
|
|
377
|
+
var ThreadSuffix = z.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe(
|
|
378
|
+
"Optional thread label within the conversation with this contact. Defaults to the contact's main thread. mosadd USP: multiple threads per contact."
|
|
379
|
+
);
|
|
380
|
+
var mDM_send_input = z.object({
|
|
381
|
+
to: ContactRef,
|
|
382
|
+
text: z.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
|
|
383
|
+
thread_label: ThreadSuffix.optional().describe(
|
|
384
|
+
"Optional thread label. If omitted, uses the default thread for this contact."
|
|
385
|
+
),
|
|
386
|
+
reply_to_id: z.string().optional().describe("Optional id of the message being replied to.")
|
|
387
|
+
});
|
|
388
|
+
var mDM_list_input = z.object({
|
|
389
|
+
contact_id: ContactRef.describe("Identity id of the contact to read messages with."),
|
|
390
|
+
thread_label: ThreadSuffix.optional(),
|
|
391
|
+
limit: z.number().int().min(1).max(200).default(50).optional(),
|
|
392
|
+
cursor: z.string().optional().describe("Opaque pagination cursor from a previous response.")
|
|
393
|
+
});
|
|
394
|
+
var mDM_list_contacts_input = z.object({
|
|
395
|
+
limit: z.number().int().min(1).max(500).default(100).optional()
|
|
396
|
+
});
|
|
397
|
+
var mDM_respond_request_input = z.object({
|
|
398
|
+
request_id: z.string().min(1),
|
|
399
|
+
action: z.enum(["accept", "reject"])
|
|
400
|
+
});
|
|
401
|
+
function dmThreadId(selfId, otherId, label) {
|
|
402
|
+
const [a, b] = [selfId, otherId].sort();
|
|
403
|
+
return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
|
|
404
|
+
}
|
|
405
|
+
async function resolveSelfIdentityId() {
|
|
406
|
+
const sb = getSupabase();
|
|
407
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
408
|
+
if (ue || !u?.user) {
|
|
409
|
+
throw new Error(
|
|
410
|
+
"Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
|
|
414
|
+
if (error || !identity) {
|
|
415
|
+
throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
|
|
416
|
+
}
|
|
417
|
+
return identity.id;
|
|
418
|
+
}
|
|
419
|
+
function packPlaintextPayload(text, replyToId) {
|
|
420
|
+
const envelope = {
|
|
421
|
+
v: PROTOCOL_VERSION,
|
|
422
|
+
type: "text",
|
|
423
|
+
text,
|
|
424
|
+
reply_to: replyToId ?? null,
|
|
425
|
+
sent_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
426
|
+
};
|
|
427
|
+
return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
|
|
428
|
+
}
|
|
429
|
+
function unpackPayload(payload) {
|
|
430
|
+
try {
|
|
431
|
+
const json = Buffer.from(payload).toString("utf8");
|
|
432
|
+
const obj = JSON.parse(json);
|
|
433
|
+
if (typeof obj?.text === "string") return obj;
|
|
434
|
+
} catch {
|
|
435
|
+
}
|
|
436
|
+
return { text: "<ciphertext>" };
|
|
437
|
+
}
|
|
438
|
+
async function mDM_send(input, ctx) {
|
|
439
|
+
const dm = ctx.providers.dm;
|
|
440
|
+
const selfId = await dm.selfId();
|
|
441
|
+
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
442
|
+
const inner = packPlaintextPayload(input.text, input.reply_to_id);
|
|
443
|
+
const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
|
|
444
|
+
ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
|
|
445
|
+
const result = await dm.send({
|
|
446
|
+
to: input.to,
|
|
447
|
+
threadId,
|
|
448
|
+
payload: sealed,
|
|
449
|
+
replyToId: input.reply_to_id
|
|
450
|
+
});
|
|
451
|
+
if (ctx.providers.keys.putSentMessage) {
|
|
452
|
+
await ctx.providers.keys.putSentMessage(result.id, inner);
|
|
453
|
+
}
|
|
454
|
+
return {
|
|
455
|
+
message_id: result.id,
|
|
456
|
+
delivered_at: result.deliveredAt,
|
|
457
|
+
thread_id: threadId,
|
|
458
|
+
encrypted: true
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
async function mDM_send_unencrypted(input, ctx) {
|
|
462
|
+
const dm = ctx.providers.dm;
|
|
463
|
+
const selfId = await dm.selfId();
|
|
464
|
+
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
465
|
+
const payload = packPlaintextPayload(input.text, input.reply_to_id);
|
|
466
|
+
ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
|
|
467
|
+
thread_id: threadId,
|
|
468
|
+
bytes: payload.byteLength
|
|
469
|
+
});
|
|
470
|
+
const result = await dm.send({
|
|
471
|
+
to: input.to,
|
|
472
|
+
threadId,
|
|
473
|
+
payload,
|
|
474
|
+
replyToId: input.reply_to_id
|
|
475
|
+
});
|
|
476
|
+
return {
|
|
477
|
+
message_id: result.id,
|
|
478
|
+
delivered_at: result.deliveredAt,
|
|
479
|
+
thread_id: threadId,
|
|
480
|
+
encrypted: false
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
async function mDM_publish_keys(_input, ctx) {
|
|
484
|
+
const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
|
|
485
|
+
ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
|
|
486
|
+
return { published: true, one_time_prekeys: oneTimePrekeyCount };
|
|
487
|
+
}
|
|
488
|
+
async function mDM_list(input, ctx) {
|
|
489
|
+
const dm = ctx.providers.dm;
|
|
490
|
+
const selfId = await dm.selfId();
|
|
491
|
+
const threadId = dmThreadId(selfId, input.contact_id, input.thread_label);
|
|
492
|
+
ctx.log("debug", "mDM_list via DmProvider", { thread_id: threadId });
|
|
493
|
+
const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
|
|
494
|
+
const messages = await Promise.all(
|
|
495
|
+
result.messages.map(async (m) => {
|
|
496
|
+
const base = {
|
|
497
|
+
id: m.id,
|
|
498
|
+
sender_identity_id: m.senderId,
|
|
499
|
+
timestamp: m.timestamp,
|
|
500
|
+
thread_id: m.threadId
|
|
501
|
+
};
|
|
502
|
+
if (!isE2eeEnvelope(m.payload)) {
|
|
503
|
+
return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
|
|
504
|
+
}
|
|
505
|
+
if (m.senderId === selfId) {
|
|
506
|
+
const cached = await ctx.providers.keys.getSentMessage?.(m.id);
|
|
507
|
+
if (cached) {
|
|
508
|
+
return { ...base, text: unpackPayload(cached).text, encrypted: true };
|
|
509
|
+
}
|
|
510
|
+
return { ...base, text: "<encrypted \xB7 sent by you>", encrypted: true };
|
|
511
|
+
}
|
|
512
|
+
try {
|
|
513
|
+
const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
|
|
514
|
+
return { ...base, text: unpackPayload(inner).text, encrypted: true };
|
|
515
|
+
} catch (err) {
|
|
516
|
+
ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
|
|
517
|
+
return { ...base, text: "<undecryptable>", encrypted: true };
|
|
518
|
+
}
|
|
519
|
+
})
|
|
520
|
+
);
|
|
521
|
+
return {
|
|
522
|
+
messages,
|
|
523
|
+
next_cursor: result.nextCursor,
|
|
524
|
+
threads: [threadId]
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
async function mDM_list_contacts(input, ctx) {
|
|
528
|
+
readSupabaseEnv();
|
|
529
|
+
const selfId = await resolveSelfIdentityId();
|
|
530
|
+
const sb = getSupabase();
|
|
531
|
+
ctx.log("debug", "mDM_list_contacts querying contacts table", { selfId });
|
|
532
|
+
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);
|
|
533
|
+
if (error) {
|
|
534
|
+
throw new Error(`Failed to list contacts: ${error.message}`);
|
|
535
|
+
}
|
|
536
|
+
const contacts = data.map((r) => ({
|
|
537
|
+
identity_id: r.contact_identity_id,
|
|
538
|
+
account_id: r.identities?.account_id ?? null,
|
|
539
|
+
display_name: r.identities?.display_name ?? null,
|
|
540
|
+
state: r.state
|
|
541
|
+
}));
|
|
542
|
+
return { contacts };
|
|
543
|
+
}
|
|
544
|
+
async function mDM_respond_request(input, ctx) {
|
|
545
|
+
readSupabaseEnv();
|
|
546
|
+
ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
|
|
547
|
+
await invokeFunction("message-request-respond", {
|
|
548
|
+
action: "respond",
|
|
549
|
+
request_id: input.request_id,
|
|
550
|
+
status: input.action === "accept" ? "accepted" : "rejected"
|
|
551
|
+
});
|
|
552
|
+
return { ok: true };
|
|
553
|
+
}
|
|
554
|
+
var mDM_publish_keys_input = z.object({});
|
|
555
|
+
var mDM_edit_input = z.object({
|
|
556
|
+
to: ContactRef.describe(
|
|
557
|
+
"Recipient identity id of the conversation the message is in (needed to locate it and verify the edit won't break E2EE)."
|
|
558
|
+
),
|
|
559
|
+
message_id: z.string().min(1).describe("Id of the message to edit (from mDM_list)."),
|
|
560
|
+
new_text: z.string().min(1).max(64e3).describe("Replacement message body (UTF-8). Max 64 KB."),
|
|
561
|
+
thread_label: ThreadSuffix.optional()
|
|
562
|
+
});
|
|
563
|
+
var mDM_delete_input = z.object({
|
|
564
|
+
message_id: z.string().min(1).describe("Id of the message to delete (from mDM_list).")
|
|
565
|
+
});
|
|
566
|
+
async function mDM_edit(input, ctx) {
|
|
567
|
+
readSupabaseEnv();
|
|
568
|
+
const dm = ctx.providers.dm;
|
|
569
|
+
const selfId = await dm.selfId();
|
|
570
|
+
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
571
|
+
const recent = await dm.list({ threadId, limit: 100 });
|
|
572
|
+
const target = recent.messages.find((m) => m.id === input.message_id);
|
|
573
|
+
if (!target) {
|
|
574
|
+
throw new Error(
|
|
575
|
+
`mDM_edit could not find message ${input.message_id} in the recent history of this thread. Pass the 'to' (and 'thread_label') of the conversation the message belongs to.`
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
if (isE2eeEnvelope(target.payload)) {
|
|
579
|
+
throw new Error(
|
|
580
|
+
"mDM_edit cannot edit an end-to-end-encrypted message: the Double Ratchet is forward-only, so the edit can't be re-sealed and storing a new body would strip E2EE. Delete it with mDM_delete and send a replacement with mDM_send instead."
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
const envelope = {
|
|
584
|
+
v: PROTOCOL_VERSION,
|
|
585
|
+
type: "text",
|
|
586
|
+
text: input.new_text,
|
|
587
|
+
edited: true,
|
|
588
|
+
sent_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
589
|
+
};
|
|
590
|
+
const encrypted_payload = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
|
|
591
|
+
ctx.log("debug", "mDM_edit via message-edit (legacy plaintext only)", { message_id: input.message_id });
|
|
592
|
+
await invokeFunction("message-edit", { message_id: input.message_id, encrypted_payload });
|
|
593
|
+
return { message_id: input.message_id, edited: true };
|
|
594
|
+
}
|
|
595
|
+
async function mDM_delete(input, ctx) {
|
|
596
|
+
readSupabaseEnv();
|
|
597
|
+
ctx.log("debug", "mDM_delete via message-delete", { message_id: input.message_id });
|
|
598
|
+
await invokeFunction("message-delete", { message_id: input.message_id });
|
|
599
|
+
return { message_id: input.message_id, deleted: true };
|
|
600
|
+
}
|
|
601
|
+
var mdmTools = [
|
|
602
|
+
{
|
|
603
|
+
name: "mDM_list_contacts",
|
|
604
|
+
requires: "any",
|
|
605
|
+
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).",
|
|
606
|
+
inputSchema: mDM_list_contacts_input,
|
|
607
|
+
handler: mDM_list_contacts
|
|
608
|
+
},
|
|
609
|
+
{
|
|
610
|
+
name: "mDM_publish_keys",
|
|
611
|
+
requires: "any",
|
|
612
|
+
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.",
|
|
613
|
+
inputSchema: mDM_publish_keys_input,
|
|
614
|
+
handler: mDM_publish_keys
|
|
615
|
+
},
|
|
616
|
+
{
|
|
617
|
+
name: "mDM_send",
|
|
618
|
+
requires: "any",
|
|
619
|
+
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.",
|
|
620
|
+
inputSchema: mDM_send_input,
|
|
621
|
+
handler: mDM_send
|
|
622
|
+
},
|
|
623
|
+
{
|
|
624
|
+
name: "mDM_send_unencrypted",
|
|
625
|
+
requires: "any",
|
|
626
|
+
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.",
|
|
627
|
+
inputSchema: mDM_send_input,
|
|
628
|
+
handler: mDM_send_unencrypted
|
|
629
|
+
},
|
|
630
|
+
{
|
|
631
|
+
name: "mDM_list",
|
|
632
|
+
requires: "any",
|
|
633
|
+
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.",
|
|
634
|
+
inputSchema: mDM_list_input,
|
|
635
|
+
handler: mDM_list
|
|
636
|
+
},
|
|
637
|
+
{
|
|
638
|
+
name: "mDM_respond_request",
|
|
639
|
+
requires: "any",
|
|
640
|
+
description: "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
|
|
641
|
+
inputSchema: mDM_respond_request_input,
|
|
642
|
+
handler: mDM_respond_request
|
|
643
|
+
},
|
|
644
|
+
{
|
|
645
|
+
name: "mDM_edit",
|
|
646
|
+
requires: "any",
|
|
647
|
+
description: "Edit a direct message you sent \u2014 replace its body by message_id (pass the conversation's `to` so it can be located). NOTE: end-to-end-encrypted messages CANNOT be edited (the ratchet is forward-only) \u2014 mDM_edit refuses them and you should mDM_delete + mDM_send a replacement instead. Only legacy non-E2EE messages are editable.",
|
|
648
|
+
inputSchema: mDM_edit_input,
|
|
649
|
+
handler: mDM_edit
|
|
650
|
+
},
|
|
651
|
+
{
|
|
652
|
+
name: "mDM_delete",
|
|
653
|
+
requires: "any",
|
|
654
|
+
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.",
|
|
655
|
+
inputSchema: mDM_delete_input,
|
|
656
|
+
handler: mDM_delete
|
|
657
|
+
}
|
|
658
|
+
];
|
|
659
|
+
|
|
660
|
+
// src/tools/mdm-voice.ts
|
|
661
|
+
import { z as z2 } from "zod";
|
|
662
|
+
var PROTOCOL_VERSION2 = "mosadd.chat.v1";
|
|
663
|
+
var ContactRef2 = z2.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
|
|
664
|
+
var RoomId = z2.string().min(1).describe("Voice room id (from mDM_call_start's call_invite).");
|
|
665
|
+
var mDM_call_start_input = z2.object({
|
|
666
|
+
to: ContactRef2,
|
|
667
|
+
video: z2.boolean().optional().describe("Request a video call instead of audio-only. Default false."),
|
|
668
|
+
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.")
|
|
669
|
+
});
|
|
670
|
+
var mDM_call_answer_input = z2.object({ room_id: RoomId });
|
|
671
|
+
var mDM_call_end_input = z2.object({
|
|
672
|
+
room_id: RoomId,
|
|
673
|
+
to: ContactRef2.optional().describe("If set, also drop a call_end control message in this contact's DM thread."),
|
|
674
|
+
thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
|
|
675
|
+
});
|
|
676
|
+
var mDM_voice_note_input = z2.object({
|
|
677
|
+
to: ContactRef2,
|
|
678
|
+
audio_url: z2.string().url().describe("URL of the recorded audio clip (already uploaded by the client)."),
|
|
679
|
+
duration_ms: z2.number().int().positive().optional().describe("Clip length in milliseconds, if known."),
|
|
680
|
+
mime: z2.string().max(120).optional().describe("Audio MIME type, e.g. audio/ogg, audio/mpeg. Default audio/ogg."),
|
|
681
|
+
thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
|
|
682
|
+
});
|
|
683
|
+
function dmThreadId2(selfId, otherId, label) {
|
|
684
|
+
const [a, b] = [selfId, otherId].sort();
|
|
685
|
+
return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
|
|
686
|
+
}
|
|
687
|
+
function packEnvelope(obj) {
|
|
688
|
+
const envelope = { v: PROTOCOL_VERSION2, sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...obj };
|
|
689
|
+
return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
|
|
690
|
+
}
|
|
691
|
+
async function signalDm(ctx, to, threadLabel, envelope) {
|
|
692
|
+
const dm = ctx.providers.dm;
|
|
693
|
+
const selfId = await dm.selfId();
|
|
694
|
+
const threadId = dmThreadId2(selfId, to, threadLabel);
|
|
695
|
+
const res = await dm.send({ to, threadId, payload: packEnvelope(envelope) });
|
|
696
|
+
return { message_id: res?.id, thread_id: threadId };
|
|
697
|
+
}
|
|
698
|
+
async function mDM_call_start(input, ctx) {
|
|
699
|
+
const dm = ctx.providers.dm;
|
|
700
|
+
const selfId = await dm.selfId();
|
|
701
|
+
const mode = input.video ? "video" : "audio";
|
|
702
|
+
const label = `dmcall-${dmThreadId2(selfId, input.to).replace(/[^a-zA-Z0-9._-]/g, "-")}`.slice(0, 120);
|
|
703
|
+
const { roomId } = await ctx.providers.voice.createRoom(label);
|
|
704
|
+
const ticket = await ctx.providers.voice.joinTicket(roomId);
|
|
705
|
+
let invited = false;
|
|
706
|
+
let thread_id = dmThreadId2(selfId, input.to, input.thread_label);
|
|
707
|
+
try {
|
|
708
|
+
const sig = await signalDm(ctx, input.to, input.thread_label, {
|
|
709
|
+
type: "call_invite",
|
|
710
|
+
room_id: roomId,
|
|
711
|
+
mode,
|
|
712
|
+
from: selfId
|
|
713
|
+
});
|
|
714
|
+
thread_id = sig.thread_id;
|
|
715
|
+
invited = true;
|
|
716
|
+
} catch (e) {
|
|
717
|
+
ctx.log("warn", "mDM_call_start: invite signal failed (room still usable)", {
|
|
718
|
+
error: e.message
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
ctx.log("debug", "mDM_call_start", { room_id: roomId, mode, invited });
|
|
722
|
+
return { room_id: roomId, token: ticket.token, url: ticket.url, identity: ticket.identity, mode, invited, thread_id };
|
|
723
|
+
}
|
|
724
|
+
async function mDM_call_answer(input, ctx) {
|
|
725
|
+
const ticket = await ctx.providers.voice.joinTicket(input.room_id);
|
|
726
|
+
ctx.log("debug", "mDM_call_answer", { room_id: ticket.roomId, identity: ticket.identity });
|
|
727
|
+
return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
|
|
728
|
+
}
|
|
729
|
+
async function mDM_call_end(input, ctx) {
|
|
730
|
+
let signalled = false;
|
|
731
|
+
if (input.to) {
|
|
732
|
+
try {
|
|
733
|
+
await signalDm(ctx, input.to, input.thread_label, { type: "call_end", room_id: input.room_id });
|
|
734
|
+
signalled = true;
|
|
735
|
+
} catch (e) {
|
|
736
|
+
ctx.log("warn", "mDM_call_end: hangup signal failed", { error: e.message });
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
ctx.log("debug", "mDM_call_end", { room_id: input.room_id, signalled });
|
|
740
|
+
return { room_id: input.room_id, signalled };
|
|
741
|
+
}
|
|
742
|
+
async function mDM_voice_note(input, ctx) {
|
|
743
|
+
const sig = await signalDm(ctx, input.to, input.thread_label, {
|
|
744
|
+
type: "voice_note",
|
|
745
|
+
audio_url: input.audio_url,
|
|
746
|
+
duration_ms: input.duration_ms ?? null,
|
|
747
|
+
mime: input.mime ?? "audio/ogg"
|
|
748
|
+
});
|
|
749
|
+
ctx.log("debug", "mDM_voice_note", { thread_id: sig.thread_id });
|
|
750
|
+
return sig;
|
|
751
|
+
}
|
|
752
|
+
var mdmVoiceTools = [
|
|
753
|
+
{
|
|
754
|
+
name: "mDM_call_start",
|
|
755
|
+
requires: "network",
|
|
756
|
+
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.",
|
|
757
|
+
inputSchema: mDM_call_start_input,
|
|
758
|
+
handler: mDM_call_start
|
|
759
|
+
},
|
|
760
|
+
{
|
|
761
|
+
name: "mDM_call_answer",
|
|
762
|
+
requires: "network",
|
|
763
|
+
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.",
|
|
764
|
+
inputSchema: mDM_call_answer_input,
|
|
765
|
+
handler: mDM_call_answer
|
|
766
|
+
},
|
|
767
|
+
{
|
|
768
|
+
name: "mDM_call_end",
|
|
769
|
+
requires: "network",
|
|
770
|
+
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.",
|
|
771
|
+
inputSchema: mDM_call_end_input,
|
|
772
|
+
handler: mDM_call_end
|
|
773
|
+
},
|
|
774
|
+
{
|
|
775
|
+
name: "mDM_voice_note",
|
|
776
|
+
requires: "network",
|
|
777
|
+
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.",
|
|
778
|
+
inputSchema: mDM_voice_note_input,
|
|
779
|
+
handler: mDM_voice_note
|
|
780
|
+
}
|
|
781
|
+
];
|
|
782
|
+
|
|
783
|
+
// src/tools/mirc.ts
|
|
784
|
+
import { z as z3 } from "zod";
|
|
785
|
+
var ChannelId = z3.string().min(1).max(120).describe("Channel id (UUID). Use mIRC_list to discover available channels.");
|
|
786
|
+
var AccessMode = z3.enum(["open", "password", "private"]).describe("open: anyone can join \xB7 password: join with a shared password \xB7 private: invite-only.");
|
|
787
|
+
var Capabilities = z3.object({
|
|
788
|
+
txt: z3.boolean().default(true),
|
|
789
|
+
ptt: z3.boolean().default(false),
|
|
790
|
+
live: z3.boolean().default(false)
|
|
791
|
+
}).describe("Which modes are enabled in this channel: txt (text), ptt (push-to-talk voice), live (live stream).").optional();
|
|
792
|
+
var mIRC_create_input = z3.object({
|
|
793
|
+
name: z3.string().min(1).max(80).describe("Channel display name."),
|
|
794
|
+
topic: z3.string().max(500).optional().describe("Optional channel topic/description."),
|
|
795
|
+
access_mode: AccessMode.default("open"),
|
|
796
|
+
password: z3.string().min(6).max(120).optional().describe("Password (only for access_mode=password)."),
|
|
797
|
+
capabilities: Capabilities,
|
|
798
|
+
wrapped_group_key: z3.string().optional().describe(
|
|
799
|
+
"Required for access_mode=password|private (these are E2EE channels): the channel's group key wrapped to the creator's identity key. Open channels ignore it. If omitted on a non-open channel the backend rejects the call with a 'wrapped_group_key required' error."
|
|
800
|
+
)
|
|
801
|
+
});
|
|
802
|
+
var mIRC_list_input = z3.object({
|
|
803
|
+
limit: z3.number().int().min(1).max(500).default(100).optional(),
|
|
804
|
+
offset: z3.number().int().min(0).default(0).optional()
|
|
805
|
+
// NOTE: an access_mode filter was removed — channel-manage's list branch doesn't
|
|
806
|
+
// filter by it (it was a silent no-op). Filter client-side on the returned
|
|
807
|
+
// access_mode field. Server-side filtering is tracked in the consistency ticket.
|
|
808
|
+
});
|
|
809
|
+
var mIRC_get_input = z3.object({
|
|
810
|
+
channel_id: ChannelId
|
|
811
|
+
});
|
|
812
|
+
var mIRC_update_input = z3.object({
|
|
813
|
+
channel_id: ChannelId,
|
|
814
|
+
name: z3.string().min(1).max(80).optional(),
|
|
815
|
+
topic: z3.string().max(500).optional(),
|
|
816
|
+
// NOTE: access_mode was removed — channel-manage's update branch ignores it, and
|
|
817
|
+
// switching an existing channel to/from an E2EE (password/private) mode needs
|
|
818
|
+
// group-key handling that isn't wired yet. Recreate the channel to change mode.
|
|
819
|
+
capabilities: Capabilities
|
|
820
|
+
});
|
|
821
|
+
var mIRC_delete_input = z3.object({
|
|
822
|
+
channel_id: ChannelId
|
|
823
|
+
});
|
|
824
|
+
async function mIRC_create(input, ctx) {
|
|
825
|
+
readSupabaseEnv();
|
|
826
|
+
ctx.log("debug", "mIRC_create invoking channel-manage", { name: input.name });
|
|
827
|
+
const { topic, ...rest } = input;
|
|
828
|
+
const payload = topic !== void 0 ? { ...rest, description: topic } : { ...rest };
|
|
829
|
+
return await invokeFunction("channel-manage", {
|
|
830
|
+
action: "create",
|
|
831
|
+
...payload
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
async function mIRC_list(input, ctx) {
|
|
835
|
+
readSupabaseEnv();
|
|
836
|
+
ctx.log("debug", "mIRC_list invoking channel-manage");
|
|
837
|
+
return await invokeFunction("channel-manage", {
|
|
838
|
+
action: "list",
|
|
839
|
+
...input
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
async function mIRC_get(input, ctx) {
|
|
843
|
+
readSupabaseEnv();
|
|
844
|
+
ctx.log("debug", "mIRC_get invoking channel-manage", { channel_id: input.channel_id });
|
|
845
|
+
return await invokeFunction("channel-manage", {
|
|
846
|
+
action: "get",
|
|
847
|
+
channel_id: input.channel_id
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
async function mIRC_update(input, ctx) {
|
|
851
|
+
readSupabaseEnv();
|
|
852
|
+
ctx.log("debug", "mIRC_update invoking channel-manage", { channel_id: input.channel_id });
|
|
853
|
+
const { topic, ...rest } = input;
|
|
854
|
+
const payload = topic !== void 0 ? { ...rest, description: topic } : { ...rest };
|
|
855
|
+
return await invokeFunction("channel-manage", {
|
|
856
|
+
action: "update",
|
|
857
|
+
...payload
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
async function mIRC_delete(input, ctx) {
|
|
861
|
+
readSupabaseEnv();
|
|
862
|
+
ctx.log("debug", "mIRC_delete invoking channel-manage", { channel_id: input.channel_id });
|
|
863
|
+
await invokeFunction("channel-manage", {
|
|
864
|
+
action: "delete",
|
|
865
|
+
channel_id: input.channel_id
|
|
866
|
+
});
|
|
867
|
+
return { deleted: true };
|
|
868
|
+
}
|
|
869
|
+
var mircTools = [
|
|
870
|
+
{
|
|
871
|
+
name: "mIRC_create",
|
|
872
|
+
requires: "network",
|
|
873
|
+
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). NOTE: password and private channels are end-to-end encrypted \u2014 you must supply wrapped_group_key (the group key wrapped to your identity key); open channels do not need it.",
|
|
874
|
+
inputSchema: mIRC_create_input,
|
|
875
|
+
handler: mIRC_create
|
|
876
|
+
},
|
|
877
|
+
{
|
|
878
|
+
name: "mIRC_list",
|
|
879
|
+
requires: "network",
|
|
880
|
+
description: "List channels available to the current user.",
|
|
881
|
+
inputSchema: mIRC_list_input,
|
|
882
|
+
handler: mIRC_list
|
|
883
|
+
},
|
|
884
|
+
{
|
|
885
|
+
name: "mIRC_get",
|
|
886
|
+
requires: "network",
|
|
887
|
+
description: "Get full details of a single channel by id.",
|
|
888
|
+
inputSchema: mIRC_get_input,
|
|
889
|
+
handler: mIRC_get
|
|
890
|
+
},
|
|
891
|
+
{
|
|
892
|
+
name: "mIRC_update",
|
|
893
|
+
requires: "network",
|
|
894
|
+
description: "Update channel metadata (name, topic, capabilities). Owner only. Access mode is fixed at creation \u2014 recreate the channel to change it.",
|
|
895
|
+
inputSchema: mIRC_update_input,
|
|
896
|
+
handler: mIRC_update
|
|
897
|
+
},
|
|
898
|
+
{
|
|
899
|
+
name: "mIRC_delete",
|
|
900
|
+
requires: "network",
|
|
901
|
+
description: "Delete a channel and cascade-remove its members. Owner only.",
|
|
902
|
+
inputSchema: mIRC_delete_input,
|
|
903
|
+
handler: mIRC_delete
|
|
904
|
+
}
|
|
905
|
+
];
|
|
906
|
+
|
|
907
|
+
// src/tools/mirc-members.ts
|
|
908
|
+
import { z as z4 } from "zod";
|
|
909
|
+
var ChannelId2 = z4.string().min(1).max(120).describe("Channel id (UUID). From mIRC_list / mIRC_create.");
|
|
910
|
+
var MemberIdentity = z4.string().min(1).describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
|
|
911
|
+
var Role = z4.enum(["superadmin", "admin", "moderator", "member"]).describe("Role to assign. owner = channel creator (not assignable); promote up to one tier below your own.");
|
|
912
|
+
var mIRC_join_input = z4.object({
|
|
913
|
+
channel_id: ChannelId2,
|
|
914
|
+
password: z4.string().min(1).optional().describe("Required if the channel is access_mode=private.")
|
|
915
|
+
});
|
|
916
|
+
var mIRC_request_access_input = z4.object({
|
|
917
|
+
channel_id: ChannelId2
|
|
918
|
+
});
|
|
919
|
+
var mIRC_leave_input = z4.object({
|
|
920
|
+
channel_id: ChannelId2
|
|
921
|
+
});
|
|
922
|
+
var mIRC_reject_request_input = z4.object({
|
|
923
|
+
channel_id: ChannelId2,
|
|
924
|
+
identity_id: z4.string().min(1).describe("Identity id of the requester to reject (state=requested; from mIRC_list members).")
|
|
925
|
+
});
|
|
926
|
+
var mIRC_approve_request_input = mIRC_reject_request_input.extend({
|
|
927
|
+
wrapped_group_key: z4.string().optional().describe(
|
|
928
|
+
"Required to approve a join to a password/private (E2EE) channel: the channel group key wrapped to the approved member's identity key. Without it the backend rejects the approval with a 'wrapped_group_key required' error. (Access requests only exist on non-open channels, so this is effectively always required.)"
|
|
929
|
+
)
|
|
930
|
+
});
|
|
931
|
+
var mIRC_kick_input = z4.object({
|
|
932
|
+
channel_id: ChannelId2,
|
|
933
|
+
identity_id: MemberIdentity
|
|
934
|
+
// NOTE: a `reason` field used to be advertised here but channel-members-manage
|
|
935
|
+
// never persists it (no audit row on kick) — removed until the backend logs it
|
|
936
|
+
// (see consistency ticket) so the tool doesn't claim an audit trail it can't deliver.
|
|
937
|
+
});
|
|
938
|
+
var mIRC_ban_input = z4.object({
|
|
939
|
+
channel_id: ChannelId2,
|
|
940
|
+
identity_id: MemberIdentity
|
|
941
|
+
// NOTE: `reason` (no storage) and `until` (timed ban) were removed — the EF ban
|
|
942
|
+
// branch ignores both, so `until` produced a SILENT PERMANENT ban when a caller
|
|
943
|
+
// asked for a temporary one. Ban is permanent-until-unban; enforced temp-bans +
|
|
944
|
+
// ban audit are tracked in the consistency ticket.
|
|
945
|
+
});
|
|
946
|
+
var mIRC_unban_input = z4.object({
|
|
947
|
+
channel_id: ChannelId2,
|
|
948
|
+
identity_id: MemberIdentity
|
|
949
|
+
});
|
|
950
|
+
var mIRC_set_role_input = z4.object({
|
|
951
|
+
channel_id: ChannelId2,
|
|
952
|
+
identity_id: MemberIdentity,
|
|
953
|
+
role: Role
|
|
954
|
+
});
|
|
955
|
+
var mIRC_set_ptt_input = z4.object({
|
|
956
|
+
channel_id: ChannelId2,
|
|
957
|
+
identity_id: MemberIdentity,
|
|
958
|
+
ptt_enabled: z4.boolean().describe("Allow this member to hold the PTT floor in voice mode.")
|
|
959
|
+
});
|
|
960
|
+
async function invokeChannelMembers(action, body, ctx) {
|
|
961
|
+
const b = { ...body };
|
|
962
|
+
if ("identity_id" in b) {
|
|
963
|
+
b.target_identity_id = b.identity_id;
|
|
964
|
+
delete b.identity_id;
|
|
965
|
+
}
|
|
966
|
+
if ("role" in b) {
|
|
967
|
+
b.new_role = b.role;
|
|
968
|
+
delete b.role;
|
|
969
|
+
}
|
|
970
|
+
if ("ptt_enabled" in b) {
|
|
971
|
+
b.can_ptt = b.ptt_enabled;
|
|
972
|
+
delete b.ptt_enabled;
|
|
973
|
+
}
|
|
974
|
+
readSupabaseEnv();
|
|
975
|
+
ctx.log("debug", `mIRC.${action}`, b);
|
|
976
|
+
return await invokeFunction("channel-members-manage", { action, ...b });
|
|
977
|
+
}
|
|
978
|
+
var mircMembersTools = [
|
|
979
|
+
{
|
|
980
|
+
name: "mIRC_join",
|
|
981
|
+
requires: "network",
|
|
982
|
+
description: "Join a channel as the current user. For private channels pass `password`. Returns a membership row or 409 if already a member.",
|
|
983
|
+
inputSchema: mIRC_join_input,
|
|
984
|
+
handler: ((input, ctx) => invokeChannelMembers("join", input, ctx))
|
|
985
|
+
},
|
|
986
|
+
{
|
|
987
|
+
name: "mIRC_request_access",
|
|
988
|
+
requires: "network",
|
|
989
|
+
description: "Request access to a password/private channel (your membership goes to state=requested for an admin to approve).",
|
|
990
|
+
inputSchema: mIRC_request_access_input,
|
|
991
|
+
handler: ((input, ctx) => invokeChannelMembers("request-access", input, ctx))
|
|
992
|
+
},
|
|
993
|
+
{
|
|
994
|
+
name: "mIRC_leave",
|
|
995
|
+
requires: "network",
|
|
996
|
+
description: "Leave a channel as the current user. Owner cannot leave without transferring ownership first.",
|
|
997
|
+
inputSchema: mIRC_leave_input,
|
|
998
|
+
handler: ((input, ctx) => invokeChannelMembers("leave", input, ctx))
|
|
999
|
+
},
|
|
1000
|
+
{
|
|
1001
|
+
name: "mIRC_approve_request",
|
|
1002
|
+
requires: "network",
|
|
1003
|
+
description: "Approve a pending access request (state=requested \u2192 active). Admins / moderators / owner only. Because access requests only exist on E2EE (password/private) channels, you must pass wrapped_group_key \u2014 the channel group key wrapped to the approved member's identity key.",
|
|
1004
|
+
inputSchema: mIRC_approve_request_input,
|
|
1005
|
+
handler: ((input, ctx) => invokeChannelMembers("approve-request", input, ctx))
|
|
1006
|
+
},
|
|
1007
|
+
{
|
|
1008
|
+
name: "mIRC_reject_request",
|
|
1009
|
+
requires: "network",
|
|
1010
|
+
description: "Reject a pending access request. Admins / moderators / owner only.",
|
|
1011
|
+
inputSchema: mIRC_reject_request_input,
|
|
1012
|
+
handler: ((input, ctx) => invokeChannelMembers("reject-request", input, ctx))
|
|
1013
|
+
},
|
|
1014
|
+
{
|
|
1015
|
+
name: "mIRC_kick",
|
|
1016
|
+
requires: "network",
|
|
1017
|
+
description: "Remove a member from the channel. They can rejoin if not banned. Requires moderator+.",
|
|
1018
|
+
inputSchema: mIRC_kick_input,
|
|
1019
|
+
handler: ((input, ctx) => invokeChannelMembers("kick", input, ctx))
|
|
1020
|
+
},
|
|
1021
|
+
{
|
|
1022
|
+
name: "mIRC_ban",
|
|
1023
|
+
requires: "network",
|
|
1024
|
+
description: "Ban a member from the channel. The ban is permanent until you call mIRC_unban. Requires admin+.",
|
|
1025
|
+
inputSchema: mIRC_ban_input,
|
|
1026
|
+
handler: ((input, ctx) => invokeChannelMembers("ban", input, ctx))
|
|
1027
|
+
},
|
|
1028
|
+
{
|
|
1029
|
+
name: "mIRC_unban",
|
|
1030
|
+
requires: "network",
|
|
1031
|
+
description: "Lift a ban. Requires admin+.",
|
|
1032
|
+
inputSchema: mIRC_unban_input,
|
|
1033
|
+
handler: ((input, ctx) => invokeChannelMembers("unban", input, ctx))
|
|
1034
|
+
},
|
|
1035
|
+
{
|
|
1036
|
+
name: "mIRC_set_role",
|
|
1037
|
+
requires: "network",
|
|
1038
|
+
description: "Promote / demote a member. Roles: owner > admin > moderator > member > guest. Only owner can promote to admin; only admin+ can promote to moderator.",
|
|
1039
|
+
inputSchema: mIRC_set_role_input,
|
|
1040
|
+
handler: ((input, ctx) => invokeChannelMembers("set-role", input, ctx))
|
|
1041
|
+
},
|
|
1042
|
+
{
|
|
1043
|
+
name: "mIRC_set_ptt",
|
|
1044
|
+
requires: "network",
|
|
1045
|
+
description: "Grant or revoke PTT floor permission for a member in voice-capable channels (capabilities.ptt=true). Requires moderator+.",
|
|
1046
|
+
inputSchema: mIRC_set_ptt_input,
|
|
1047
|
+
handler: ((input, ctx) => invokeChannelMembers("set-ptt", input, ctx))
|
|
1048
|
+
}
|
|
1049
|
+
];
|
|
1050
|
+
|
|
1051
|
+
// src/tools/mirc-messages.ts
|
|
1052
|
+
import { z as z5 } from "zod";
|
|
1053
|
+
var PROTOCOL_VERSION3 = "mosadd.chat.v1";
|
|
1054
|
+
var ChannelId3 = z5.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
|
|
1055
|
+
var mIRC_post_message_input = z5.object({
|
|
1056
|
+
channel_id: ChannelId3,
|
|
1057
|
+
text: z5.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
|
|
1058
|
+
reply_to_id: z5.string().optional().describe("Optional id of the message being replied to."),
|
|
1059
|
+
space_id: z5.string().optional().describe("Optional backing space id. Resolved automatically from the channel if omitted.")
|
|
1060
|
+
});
|
|
1061
|
+
var mIRC_list_messages_input = z5.object({
|
|
1062
|
+
channel_id: ChannelId3,
|
|
1063
|
+
limit: z5.number().int().min(1).max(200).default(50).optional(),
|
|
1064
|
+
cursor: z5.string().optional().describe("Opaque pagination cursor from a prior list response."),
|
|
1065
|
+
space_id: z5.string().optional().describe("Optional backing space id. Resolved automatically if omitted.")
|
|
1066
|
+
});
|
|
1067
|
+
function packPlaintextPayload2(text, replyToId) {
|
|
1068
|
+
const envelope = {
|
|
1069
|
+
v: PROTOCOL_VERSION3,
|
|
1070
|
+
type: "text",
|
|
1071
|
+
text,
|
|
1072
|
+
reply_to: replyToId ?? null,
|
|
1073
|
+
sent_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1074
|
+
};
|
|
1075
|
+
return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
|
|
1076
|
+
}
|
|
1077
|
+
function unpackPayload2(payload) {
|
|
1078
|
+
try {
|
|
1079
|
+
const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
|
|
1080
|
+
if (typeof obj?.text === "string") return obj;
|
|
1081
|
+
} catch {
|
|
1082
|
+
}
|
|
1083
|
+
return { text: "<ciphertext>" };
|
|
1084
|
+
}
|
|
1085
|
+
async function resolveLinkedSpaceId(channelId) {
|
|
1086
|
+
const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
|
|
1087
|
+
const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
|
|
1088
|
+
if (!spaceId) {
|
|
1089
|
+
throw new Error(
|
|
1090
|
+
`Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, or pass space_id explicitly.`
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
return spaceId;
|
|
1094
|
+
}
|
|
1095
|
+
async function mIRC_post_message(input, ctx) {
|
|
1096
|
+
readSupabaseEnv();
|
|
1097
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
|
|
1098
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
1099
|
+
ctx.log("debug", "mIRC_post_message", { thread_id, space_id });
|
|
1100
|
+
const data = await invokeFunction("message-send", {
|
|
1101
|
+
space_id,
|
|
1102
|
+
thread_id,
|
|
1103
|
+
encrypted_payload: packPlaintextPayload2(input.text, input.reply_to_id),
|
|
1104
|
+
message_type: "txt",
|
|
1105
|
+
protocol_version: PROTOCOL_VERSION3,
|
|
1106
|
+
reply_to_id: input.reply_to_id ?? null
|
|
1107
|
+
});
|
|
1108
|
+
if (!data?.message?.id) throw new Error("message-send returned no message id");
|
|
1109
|
+
return { message_id: data.message.id, delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(), thread_id };
|
|
1110
|
+
}
|
|
1111
|
+
async function mIRC_list_messages(input, ctx) {
|
|
1112
|
+
readSupabaseEnv();
|
|
1113
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
|
|
1114
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
1115
|
+
ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
|
|
1116
|
+
const data = await invokeFunction("message-list", {
|
|
1117
|
+
space_id,
|
|
1118
|
+
thread_id,
|
|
1119
|
+
limit: input.limit ?? 50,
|
|
1120
|
+
before: input.cursor
|
|
1121
|
+
});
|
|
1122
|
+
return {
|
|
1123
|
+
messages: (data?.messages ?? []).map((m) => ({
|
|
1124
|
+
id: m.id,
|
|
1125
|
+
sender_identity_id: m.sender_identity_id,
|
|
1126
|
+
text: unpackPayload2(m.encrypted_payload).text,
|
|
1127
|
+
timestamp: m.created_at
|
|
1128
|
+
})),
|
|
1129
|
+
next_cursor: data?.next_before ?? data?.cursor ?? null
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
var mircMessagesTools = [
|
|
1133
|
+
{
|
|
1134
|
+
name: "mIRC_post_message",
|
|
1135
|
+
requires: "network",
|
|
1136
|
+
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.",
|
|
1137
|
+
inputSchema: mIRC_post_message_input,
|
|
1138
|
+
handler: mIRC_post_message
|
|
1139
|
+
},
|
|
1140
|
+
{
|
|
1141
|
+
name: "mIRC_list_messages",
|
|
1142
|
+
requires: "network",
|
|
1143
|
+
description: "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
|
|
1144
|
+
inputSchema: mIRC_list_messages_input,
|
|
1145
|
+
handler: mIRC_list_messages
|
|
1146
|
+
}
|
|
1147
|
+
];
|
|
1148
|
+
|
|
1149
|
+
// src/tools/mirc-edge.ts
|
|
1150
|
+
import { z as z6 } from "zod";
|
|
1151
|
+
var DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
|
|
1152
|
+
var DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
|
|
1153
|
+
function edgeUrl() {
|
|
1154
|
+
return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
|
|
1155
|
+
}
|
|
1156
|
+
function supabaseUrl() {
|
|
1157
|
+
return process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ?? process.env.SUPABASE_URL?.replace(/\/$/, "") ?? DEFAULT_SUPABASE_URL;
|
|
1158
|
+
}
|
|
1159
|
+
function hubKey() {
|
|
1160
|
+
const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
|
|
1161
|
+
if (!key) throw new Error("MOSADD_API_KEY required for mIRC edge tools (see mosadd login or hub-keys).");
|
|
1162
|
+
return key;
|
|
1163
|
+
}
|
|
1164
|
+
var mIRC_send_edge_input = z6.object({
|
|
1165
|
+
channel_id: z6.string().min(1).max(128).describe("Channel id (UUID). Same as mIRC_create / mIRC_list."),
|
|
1166
|
+
text: z6.string().min(1).max(64e3).describe("Message body (UTF-8, max 64 KB)."),
|
|
1167
|
+
from: z6.string().max(120).optional().describe("Sender hint shown to other clients (defaults to the hub-key owner).")
|
|
1168
|
+
});
|
|
1169
|
+
async function mIRC_send_edge(input, ctx) {
|
|
1170
|
+
ctx.log("debug", "mIRC_send_edge", { channel_id: input.channel_id });
|
|
1171
|
+
const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/send`, {
|
|
1172
|
+
method: "POST",
|
|
1173
|
+
headers: {
|
|
1174
|
+
"Content-Type": "application/json",
|
|
1175
|
+
Authorization: `Bearer ${hubKey()}`
|
|
1176
|
+
},
|
|
1177
|
+
body: JSON.stringify({ text: input.text, from: input.from })
|
|
1178
|
+
});
|
|
1179
|
+
if (!r.ok) {
|
|
1180
|
+
const errBody = await r.text().catch(() => "");
|
|
1181
|
+
throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
|
|
1182
|
+
}
|
|
1183
|
+
const data = await r.json();
|
|
1184
|
+
if (!data?.id) throw new Error("mosadd-edge: send returned no id");
|
|
1185
|
+
return { message_id: data.id, delivered_at: data.ts ?? Date.now(), channel_id: input.channel_id };
|
|
1186
|
+
}
|
|
1187
|
+
var mIRC_history_edge_input = z6.object({
|
|
1188
|
+
channel_id: z6.string().min(1).max(128).describe("Channel id (UUID)."),
|
|
1189
|
+
limit: z6.number().int().min(1).max(100).default(50).optional().describe("How many recent messages to return (max 100, the DO ring size).")
|
|
1190
|
+
});
|
|
1191
|
+
async function mIRC_history_edge(input, ctx) {
|
|
1192
|
+
const limit = input.limit ?? 50;
|
|
1193
|
+
ctx.log("debug", "mIRC_history_edge", { channel_id: input.channel_id, limit });
|
|
1194
|
+
const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/history?limit=${limit}`, {
|
|
1195
|
+
headers: { Authorization: `Bearer ${hubKey()}` }
|
|
1196
|
+
});
|
|
1197
|
+
if (!r.ok) {
|
|
1198
|
+
const errBody = await r.text().catch(() => "");
|
|
1199
|
+
throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
|
|
1200
|
+
}
|
|
1201
|
+
const data = await r.json();
|
|
1202
|
+
return {
|
|
1203
|
+
channel_id: input.channel_id,
|
|
1204
|
+
messages: (data.messages ?? []).map((m) => ({
|
|
1205
|
+
id: m.id,
|
|
1206
|
+
from: m.from ?? null,
|
|
1207
|
+
text: m.text,
|
|
1208
|
+
timestamp: m.ts
|
|
1209
|
+
}))
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
var mIRC_mint_channel_token_input = z6.object({
|
|
1213
|
+
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."),
|
|
1214
|
+
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).")
|
|
1215
|
+
});
|
|
1216
|
+
async function mIRC_mint_channel_token(input, ctx) {
|
|
1217
|
+
ctx.log("debug", "mIRC_mint_channel_token", { channel_id: input.channel_id });
|
|
1218
|
+
const r = await fetch(`${supabaseUrl()}/functions/v1/hub-mint-channel-token`, {
|
|
1219
|
+
method: "POST",
|
|
1220
|
+
headers: {
|
|
1221
|
+
"Content-Type": "application/json",
|
|
1222
|
+
Authorization: `Bearer ${hubKey()}`
|
|
1223
|
+
},
|
|
1224
|
+
body: JSON.stringify({ channel_id: input.channel_id, user_id: input.user_id })
|
|
1225
|
+
});
|
|
1226
|
+
if (!r.ok) {
|
|
1227
|
+
const errBody = await r.text().catch(() => "");
|
|
1228
|
+
throw new Error(`hub-mint-channel-token ${r.status}: ${errBody.slice(0, 200)}`);
|
|
1229
|
+
}
|
|
1230
|
+
const data = await r.json();
|
|
1231
|
+
if (!data?.token || !data?.expires_in || !data?.channel_id || !data?.scope) {
|
|
1232
|
+
throw new Error("hub-mint-channel-token: malformed response");
|
|
1233
|
+
}
|
|
1234
|
+
return data;
|
|
1235
|
+
}
|
|
1236
|
+
var mircEdgeTools = [
|
|
1237
|
+
{
|
|
1238
|
+
name: "mIRC_mint_channel_token",
|
|
1239
|
+
requires: "network",
|
|
1240
|
+
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.",
|
|
1241
|
+
inputSchema: mIRC_mint_channel_token_input,
|
|
1242
|
+
handler: mIRC_mint_channel_token
|
|
1243
|
+
},
|
|
1244
|
+
{
|
|
1245
|
+
name: "mIRC_send_edge",
|
|
1246
|
+
requires: "network",
|
|
1247
|
+
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).",
|
|
1248
|
+
inputSchema: mIRC_send_edge_input,
|
|
1249
|
+
handler: mIRC_send_edge
|
|
1250
|
+
},
|
|
1251
|
+
{
|
|
1252
|
+
name: "mIRC_history_edge",
|
|
1253
|
+
requires: "network",
|
|
1254
|
+
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.",
|
|
1255
|
+
inputSchema: mIRC_history_edge_input,
|
|
1256
|
+
handler: mIRC_history_edge
|
|
1257
|
+
}
|
|
1258
|
+
];
|
|
1259
|
+
|
|
1260
|
+
// src/tools/mail.ts
|
|
1261
|
+
import { z as z7 } from "zod";
|
|
1262
|
+
var EmailAddress = z7.string().email().max(254).describe("RFC 5321 email address.");
|
|
1263
|
+
var MessageId = z7.string().min(1).describe("Message id (UUID) from mAYL_send or inbox.");
|
|
1264
|
+
var mp0st_send_input = z7.object({
|
|
1265
|
+
to: z7.union([EmailAddress, z7.array(EmailAddress).min(1).max(50)]).describe(
|
|
1266
|
+
"Recipient(s). Single address or array of up to 50."
|
|
1267
|
+
),
|
|
1268
|
+
subject: z7.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
|
|
1269
|
+
body_text: z7.string().max(1048576).optional().describe("Plain text body. Max 1 MB."),
|
|
1270
|
+
body_html: z7.string().max(1048576).optional().describe("HTML body. Max 1 MB."),
|
|
1271
|
+
cc: z7.array(EmailAddress).max(50).optional(),
|
|
1272
|
+
bcc: z7.array(EmailAddress).max(50).optional(),
|
|
1273
|
+
reply_to: EmailAddress.optional(),
|
|
1274
|
+
tracking: z7.boolean().optional().describe("Open-pixel + link-click tracking. Default true. Set false to send with NO tracking (privacy / GDPR-friendly)."),
|
|
1275
|
+
force_reader: z7.boolean().optional().describe("Default false. If true, the email body is a stub only and the recipient must open it in mosadd's secure reader \u2014 maximizes tracking (print/copy/time-on-read become observable). Best for confidential / legal mail."),
|
|
1276
|
+
disclose_tracking: z7.boolean().optional().describe("Default false. If true (and tracking on), append a tracking-disclosure footer to the email \u2014 recommended for GDPR/ePrivacy compliance."),
|
|
1277
|
+
watermark: z7.union([z7.boolean(), z7.string().max(120)]).optional().describe("Inject a faint recipient watermark into the secure reader (shows in screenshots/prints). Pass true to watermark with the recipient address, or a custom string."),
|
|
1278
|
+
auto_destruct: z7.enum(["1h", "24h", "7d"]).optional().describe("Self-destruct timer: the secure-reader link expires after this window.")
|
|
1279
|
+
});
|
|
1280
|
+
var mp0st_view_input = z7.object({
|
|
1281
|
+
message_id: MessageId
|
|
1282
|
+
});
|
|
1283
|
+
var mp0st_delete_input = z7.object({
|
|
1284
|
+
message_id: MessageId
|
|
1285
|
+
});
|
|
1286
|
+
var mp0st_list_input = z7.object({
|
|
1287
|
+
direction: z7.enum(["inbound", "outbound"]).optional().describe("Filter to received (inbound) or sent (outbound) mail. Omit for both."),
|
|
1288
|
+
limit: z7.number().int().min(1).max(200).optional().describe("Max emails to return. Default 50."),
|
|
1289
|
+
before: z7.string().optional().describe("Pagination cursor: pass the previous response's next_cursor to get the next (older) page.")
|
|
1290
|
+
});
|
|
1291
|
+
var mp0st_stats_input = z7.object({
|
|
1292
|
+
message_id: MessageId
|
|
1293
|
+
});
|
|
1294
|
+
var mp0st_events_input = z7.object({
|
|
1295
|
+
message_id: MessageId
|
|
1296
|
+
});
|
|
1297
|
+
var mp0st_metrics_input = z7.object({});
|
|
1298
|
+
var mp0st_revoke_input = z7.object({
|
|
1299
|
+
message_id: MessageId,
|
|
1300
|
+
restore: z7.boolean().optional().describe("Set true to UN-revoke (restore access). Default false = revoke.")
|
|
1301
|
+
});
|
|
1302
|
+
var mp0st_audit_export_input = z7.object({
|
|
1303
|
+
message_id: MessageId
|
|
1304
|
+
});
|
|
1305
|
+
var mp0st_consent_input = z7.object({
|
|
1306
|
+
action: z7.enum(["list", "check", "optin"]).describe("'list' = recipients who opted out of your tracking; 'check' = is one recipient opted out; 'optin' = re-enable tracking for a recipient."),
|
|
1307
|
+
recipient: EmailAddress.optional().describe("Required for 'check' and 'optin'.")
|
|
1308
|
+
});
|
|
1309
|
+
var mp0st_notify_input = z7.object({
|
|
1310
|
+
since: z7.string().optional().describe("ISO-8601 cursor \u2014 return only events newer than this. Pass the previous response's `cursor` to poll for new activity."),
|
|
1311
|
+
limit: z7.number().int().min(1).max(200).optional().describe("Max events. Default 50.")
|
|
1312
|
+
});
|
|
1313
|
+
async function mp0st_send(input, ctx) {
|
|
1314
|
+
readSupabaseEnv();
|
|
1315
|
+
if (!input.body_text && !input.body_html) {
|
|
1316
|
+
throw new Error("mp0st_send requires at least one of body_text or body_html.");
|
|
1317
|
+
}
|
|
1318
|
+
ctx.log("debug", "mp0st_send invoking mp0st-send", { to: input.to });
|
|
1319
|
+
const res = await invokeFunction("mp0st-send", input);
|
|
1320
|
+
if (res.error) throw new Error(res.error);
|
|
1321
|
+
return { message_id: res.email_id ?? "", status: res.status ?? "sent", is_internal: res.is_internal ?? false };
|
|
1322
|
+
}
|
|
1323
|
+
async function mp0st_view(input, ctx) {
|
|
1324
|
+
readSupabaseEnv();
|
|
1325
|
+
ctx.log("debug", "mp0st_view invoking mp0st-get", { message_id: input.message_id });
|
|
1326
|
+
return await invokeFunction("mp0st-get", { message_id: input.message_id });
|
|
1327
|
+
}
|
|
1328
|
+
async function mp0st_list(input, ctx) {
|
|
1329
|
+
readSupabaseEnv();
|
|
1330
|
+
ctx.log("debug", "mp0st_list invoking mp0st-list", { direction: input.direction });
|
|
1331
|
+
return await invokeFunction("mp0st-list", {
|
|
1332
|
+
direction: input.direction ?? null,
|
|
1333
|
+
limit: input.limit ?? 50,
|
|
1334
|
+
before: input.before ?? null
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
async function mp0st_delete(input, ctx) {
|
|
1338
|
+
readSupabaseEnv();
|
|
1339
|
+
ctx.log("debug", "mp0st_delete invoking mp0st-delete", { message_id: input.message_id });
|
|
1340
|
+
return await invokeFunction("mp0st-delete", {
|
|
1341
|
+
message_id: input.message_id
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
async function mp0st_stats(input, ctx) {
|
|
1345
|
+
readSupabaseEnv();
|
|
1346
|
+
ctx.log("debug", "mp0st_stats invoking mp0st-stats", { message_id: input.message_id });
|
|
1347
|
+
return await invokeFunction("mp0st-stats", {
|
|
1348
|
+
message_id: input.message_id
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
async function mp0st_events(input, ctx) {
|
|
1352
|
+
readSupabaseEnv();
|
|
1353
|
+
ctx.log("debug", "mp0st_events invoking mp0st-stats", { message_id: input.message_id });
|
|
1354
|
+
return await invokeFunction("mp0st-stats", { message_id: input.message_id, events: true });
|
|
1355
|
+
}
|
|
1356
|
+
async function mp0st_metrics(_input, ctx) {
|
|
1357
|
+
readSupabaseEnv();
|
|
1358
|
+
ctx.log("debug", "mp0st_metrics invoking mp0st-stats");
|
|
1359
|
+
return await invokeFunction("mp0st-stats", {});
|
|
1360
|
+
}
|
|
1361
|
+
async function mp0st_revoke(input, ctx) {
|
|
1362
|
+
readSupabaseEnv();
|
|
1363
|
+
ctx.log("debug", "mp0st_revoke invoking mp0st-revoke", { message_id: input.message_id, restore: !!input.restore });
|
|
1364
|
+
return await invokeFunction("mp0st-revoke", {
|
|
1365
|
+
message_id: input.message_id,
|
|
1366
|
+
restore: input.restore ?? false
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
async function mp0st_audit_export(input, ctx) {
|
|
1370
|
+
readSupabaseEnv();
|
|
1371
|
+
ctx.log("debug", "mp0st_audit_export invoking mp0st-audit", { message_id: input.message_id });
|
|
1372
|
+
return await invokeFunction("mp0st-audit", { message_id: input.message_id });
|
|
1373
|
+
}
|
|
1374
|
+
async function mp0st_consent(input, ctx) {
|
|
1375
|
+
readSupabaseEnv();
|
|
1376
|
+
if ((input.action === "check" || input.action === "optin") && !input.recipient) {
|
|
1377
|
+
throw new Error(`mp0st_consent action '${input.action}' requires a 'recipient' email address.`);
|
|
1378
|
+
}
|
|
1379
|
+
ctx.log("debug", "mp0st_consent invoking mp0st-consent", { action: input.action });
|
|
1380
|
+
return await invokeFunction("mp0st-consent", { action: input.action, recipient: input.recipient ?? null });
|
|
1381
|
+
}
|
|
1382
|
+
async function mp0st_notify(input, ctx) {
|
|
1383
|
+
readSupabaseEnv();
|
|
1384
|
+
ctx.log("debug", "mp0st_notify invoking mp0st-notify", { since: input.since });
|
|
1385
|
+
return await invokeFunction("mp0st-notify", { action: "feed", since: input.since ?? null, limit: input.limit ?? 50 });
|
|
1386
|
+
}
|
|
1387
|
+
var mailTools = [
|
|
1388
|
+
{
|
|
1389
|
+
name: "mAYL_list",
|
|
1390
|
+
requires: "network",
|
|
1391
|
+
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 mAYL_view to read a full message body.",
|
|
1392
|
+
inputSchema: mp0st_list_input,
|
|
1393
|
+
handler: mp0st_list
|
|
1394
|
+
},
|
|
1395
|
+
{
|
|
1396
|
+
name: "mAYL_send",
|
|
1397
|
+
requires: "network",
|
|
1398
|
+
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. Monitoring/legal options: tracking (open+click, default on; set false for no tracking), force_reader (stub email \u2192 recipient opens in mosadd's secure reader, unlocking print/copy/time-on-read tracking + revoke), watermark (recipient watermark visible in screenshots/prints), disclose_tracking (GDPR footer), auto_destruct ('1h'|'24h'|'7d').",
|
|
1399
|
+
inputSchema: mp0st_send_input,
|
|
1400
|
+
handler: mp0st_send
|
|
1401
|
+
},
|
|
1402
|
+
{
|
|
1403
|
+
name: "mAYL_view",
|
|
1404
|
+
requires: "network",
|
|
1405
|
+
description: "Read the full body and metadata of an email by message_id.",
|
|
1406
|
+
inputSchema: mp0st_view_input,
|
|
1407
|
+
handler: mp0st_view
|
|
1408
|
+
},
|
|
1409
|
+
{
|
|
1410
|
+
name: "mAYL_delete",
|
|
1411
|
+
requires: "network",
|
|
1412
|
+
description: "Delete one of the user's emails by message_id (from mAYL_list). Soft-delete \u2014 it stops showing in mAYL_list. Owner-scoped: only your own mail.",
|
|
1413
|
+
inputSchema: mp0st_delete_input,
|
|
1414
|
+
handler: mp0st_delete
|
|
1415
|
+
},
|
|
1416
|
+
{
|
|
1417
|
+
name: "mAYL_stats",
|
|
1418
|
+
requires: "network",
|
|
1419
|
+
description: "Engagement summary for one sent email (by message_id): open_count, unique_opens, click_count, whether it was likely forwarded, first/last opened time, and a breakdown of tracked event types. Opens/clicks are real (tracking pixel + link-wrap); forward detection is best-effort (IP-subnet diversity). Owner-scoped.",
|
|
1420
|
+
inputSchema: mp0st_stats_input,
|
|
1421
|
+
handler: mp0st_stats
|
|
1422
|
+
},
|
|
1423
|
+
{
|
|
1424
|
+
name: "mAYL_events",
|
|
1425
|
+
requires: "network",
|
|
1426
|
+
description: "Raw engagement timeline for one email (by message_id): every tracked event (pixel_open, link_click, forwarded, page_view, copy/print/focus signals) with timestamp, device type and link URL. Use mAYL_stats for the rollup; use this for the per-event detail. Owner-scoped.",
|
|
1427
|
+
inputSchema: mp0st_events_input,
|
|
1428
|
+
handler: mp0st_events
|
|
1429
|
+
},
|
|
1430
|
+
{
|
|
1431
|
+
name: "mAYL_metrics",
|
|
1432
|
+
requires: "network",
|
|
1433
|
+
description: "Mailbox-wide engagement aggregate across the user's sent mail: total_sent, opened_emails, open_rate_pct, total_opens, total_clicks, forwarded_emails. Owner-scoped.",
|
|
1434
|
+
inputSchema: mp0st_metrics_input,
|
|
1435
|
+
handler: mp0st_metrics
|
|
1436
|
+
},
|
|
1437
|
+
{
|
|
1438
|
+
name: "mAYL_revoke",
|
|
1439
|
+
requires: "network",
|
|
1440
|
+
description: "Revoke (recall) a sent email's secure-reader access by message_id \u2014 the recipient can no longer open the full message via the mosadd reader link (Virtru-style recall, immediate). Pass restore:true to re-enable. HONEST LIMIT: cannot un-send or claw back content the recipient already read, copied, or screenshotted \u2014 only disables future reader access. Owner-scoped.",
|
|
1441
|
+
inputSchema: mp0st_revoke_input,
|
|
1442
|
+
handler: mp0st_revoke
|
|
1443
|
+
},
|
|
1444
|
+
{
|
|
1445
|
+
name: "mAYL_audit_export",
|
|
1446
|
+
requires: "network",
|
|
1447
|
+
description: "Export a tamper-evident engagement audit report for one sent email (RMail-style): full event trail (opens, clicks, reader print/copy/forward signals) + totals, plus an HMAC-SHA256 signature over the canonical JSON so the report can be proven unaltered. For legal/compliance use. HONEST LIMIT: proves what mosadd observed; it is not a qualified delivery receipt (ERDS). Owner-scoped.",
|
|
1448
|
+
inputSchema: mp0st_audit_export_input,
|
|
1449
|
+
handler: mp0st_audit_export
|
|
1450
|
+
},
|
|
1451
|
+
{
|
|
1452
|
+
name: "mAYL_consent",
|
|
1453
|
+
requires: "network",
|
|
1454
|
+
description: "Manage recipient tracking opt-outs (GDPR/ePrivacy). action 'list' = recipients who opted out of your tracking; 'check' {recipient} = whether one opted out; 'optin' {recipient} = re-enable. Recipients self-opt-out via the footer link in your tracked emails; mAYL_send then automatically sends them with NO pixel/link-wrap. Owner-scoped.",
|
|
1455
|
+
inputSchema: mp0st_consent_input,
|
|
1456
|
+
handler: mp0st_consent
|
|
1457
|
+
},
|
|
1458
|
+
{
|
|
1459
|
+
name: "mAYL_notify",
|
|
1460
|
+
requires: "network",
|
|
1461
|
+
description: "Recent engagement feed across ALL your sent mail \u2014 the 'who just opened/clicked my mail' notifications stream (opens, clicks, forwards, reader print/copy signals), newest first, each with the email subject + recipient. Poll: pass the returned `cursor` back as `since` to get only new activity. Owner-scoped.",
|
|
1462
|
+
inputSchema: mp0st_notify_input,
|
|
1463
|
+
handler: mp0st_notify
|
|
1464
|
+
}
|
|
1465
|
+
];
|
|
1466
|
+
|
|
1467
|
+
// src/tools/mtalk.ts
|
|
1468
|
+
import { z as z8 } from "zod";
|
|
1469
|
+
var RoomLabel = z8.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.");
|
|
1470
|
+
var RoomId2 = z8.string().min(1).describe("Room id returned by mTALK_open.");
|
|
1471
|
+
var mTALK_open_input = z8.object({
|
|
1472
|
+
label: RoomLabel.optional().describe("Optional label; defaults to a personal room.")
|
|
1473
|
+
});
|
|
1474
|
+
var mTALK_join_input = z8.object({ room_id: RoomId2 });
|
|
1475
|
+
var mTALK_press_input = z8.object({ room_id: RoomId2 });
|
|
1476
|
+
var mTALK_release_input = z8.object({ room_id: RoomId2 });
|
|
1477
|
+
var mTALK_state_input = z8.object({ room_id: RoomId2 });
|
|
1478
|
+
async function mTALK_open(input, ctx) {
|
|
1479
|
+
const { roomId } = await ctx.providers.voice.createRoom(input.label);
|
|
1480
|
+
ctx.log("debug", "mTALK_open", { room_id: roomId });
|
|
1481
|
+
return { room_id: roomId };
|
|
1482
|
+
}
|
|
1483
|
+
async function mTALK_join(input, ctx) {
|
|
1484
|
+
const ticket = await ctx.providers.voice.joinTicket(input.room_id);
|
|
1485
|
+
ctx.log("debug", "mTALK_join", { room_id: ticket.roomId, identity: ticket.identity });
|
|
1486
|
+
return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
|
|
1487
|
+
}
|
|
1488
|
+
async function mTALK_press(input, ctx) {
|
|
1489
|
+
const res = await ctx.providers.voice.requestFloor(input.room_id);
|
|
1490
|
+
ctx.log("debug", "mTALK_press", { room_id: input.room_id, granted: res.granted, position: res.position });
|
|
1491
|
+
return { granted: res.granted, position: res.position, holder: res.snapshot.holder, queue: res.snapshot.queue };
|
|
1492
|
+
}
|
|
1493
|
+
async function mTALK_release(input, ctx) {
|
|
1494
|
+
const snap = await ctx.providers.voice.releaseFloor(input.room_id);
|
|
1495
|
+
ctx.log("debug", "mTALK_release", { room_id: input.room_id, holder: snap.holder });
|
|
1496
|
+
return { holder: snap.holder, queue: snap.queue };
|
|
1497
|
+
}
|
|
1498
|
+
async function mTALK_state(input, ctx) {
|
|
1499
|
+
const snap = await ctx.providers.voice.floorState(input.room_id);
|
|
1500
|
+
return { holder: snap.holder, since: snap.since, queue: snap.queue };
|
|
1501
|
+
}
|
|
1502
|
+
var mtalkTools = [
|
|
1503
|
+
{
|
|
1504
|
+
name: "mTALK_open",
|
|
1505
|
+
requires: "any",
|
|
1506
|
+
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.",
|
|
1507
|
+
inputSchema: mTALK_open_input,
|
|
1508
|
+
handler: mTALK_open
|
|
1509
|
+
},
|
|
1510
|
+
{
|
|
1511
|
+
name: "mTALK_join",
|
|
1512
|
+
requires: "network",
|
|
1513
|
+
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.",
|
|
1514
|
+
inputSchema: mTALK_join_input,
|
|
1515
|
+
handler: mTALK_join
|
|
1516
|
+
},
|
|
1517
|
+
{
|
|
1518
|
+
name: "mTALK_press",
|
|
1519
|
+
requires: "any",
|
|
1520
|
+
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.",
|
|
1521
|
+
inputSchema: mTALK_press_input,
|
|
1522
|
+
handler: mTALK_press
|
|
1523
|
+
},
|
|
1524
|
+
{
|
|
1525
|
+
name: "mTALK_release",
|
|
1526
|
+
requires: "any",
|
|
1527
|
+
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.",
|
|
1528
|
+
inputSchema: mTALK_release_input,
|
|
1529
|
+
handler: mTALK_release
|
|
1530
|
+
},
|
|
1531
|
+
{
|
|
1532
|
+
name: "mTALK_state",
|
|
1533
|
+
requires: "any",
|
|
1534
|
+
description: "Read a PTT room's floor state without changing it: who is currently transmitting (holder), since when, and the waiting queue.",
|
|
1535
|
+
inputSchema: mTALK_state_input,
|
|
1536
|
+
handler: mTALK_state
|
|
1537
|
+
}
|
|
1538
|
+
];
|
|
1539
|
+
|
|
1540
|
+
// src/tools/attachments.ts
|
|
1541
|
+
import { z as z9 } from "zod";
|
|
1542
|
+
|
|
1543
|
+
// src/providers/blob-upload.ts
|
|
1544
|
+
function defaultBucket(kind) {
|
|
1545
|
+
return kind === "file" ? "file-blobs" : "voice-blobs";
|
|
1546
|
+
}
|
|
1547
|
+
function randomId2() {
|
|
1548
|
+
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
1549
|
+
}
|
|
1550
|
+
async function uploadBlob(args) {
|
|
1551
|
+
readSupabaseEnv();
|
|
1552
|
+
const sb = getSupabase();
|
|
1553
|
+
const bucket = args.bucket ?? defaultBucket(args.kind);
|
|
1554
|
+
const ext = args.filename?.split(".").pop() ?? mimeExt(args.mime);
|
|
1555
|
+
const path = `${args.prefix ? args.prefix.replace(/[^a-zA-Z0-9._/-]/g, "-") + "/" : ""}${randomId2()}${ext ? "." + ext : ""}`;
|
|
1556
|
+
const { error } = await sb.storage.from(bucket).upload(path, args.bytes, {
|
|
1557
|
+
contentType: args.mime,
|
|
1558
|
+
upsert: false
|
|
1559
|
+
});
|
|
1560
|
+
if (error) {
|
|
1561
|
+
throw new Error(`blob upload to ${bucket}/${path} failed: ${error.message}`);
|
|
1562
|
+
}
|
|
1563
|
+
return {
|
|
1564
|
+
kind: args.kind,
|
|
1565
|
+
bucket,
|
|
1566
|
+
path,
|
|
1567
|
+
mime: args.mime,
|
|
1568
|
+
duration_ms: args.duration_ms ?? null,
|
|
1569
|
+
key_ref: args.key_ref ?? null,
|
|
1570
|
+
filename: args.filename ?? null,
|
|
1571
|
+
size_bytes: args.bytes.byteLength
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
function mimeExt(mime) {
|
|
1575
|
+
const map = {
|
|
1576
|
+
"audio/ogg": "ogg",
|
|
1577
|
+
"audio/mpeg": "mp3",
|
|
1578
|
+
"audio/mp4": "m4a",
|
|
1579
|
+
"audio/wav": "wav",
|
|
1580
|
+
"audio/webm": "webm"
|
|
1581
|
+
};
|
|
1582
|
+
return map[mime] ?? "";
|
|
1583
|
+
}
|
|
1584
|
+
function decodeBase64Body(b64) {
|
|
1585
|
+
const cleaned = b64.includes(",") && b64.startsWith("data:") ? b64.slice(b64.indexOf(",") + 1) : b64;
|
|
1586
|
+
return new Uint8Array(Buffer.from(cleaned, "base64"));
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
// src/tools/attachments.ts
|
|
1590
|
+
var PROTOCOL_VERSION4 = "mosadd.chat.v1";
|
|
1591
|
+
var Base64Body = z9.string().min(1).max(2e7).describe("Attachment bytes as base64 (or a data: URL). MCP is JSON-only, so binary is base64-encoded. Max ~15 MB decoded.");
|
|
1592
|
+
var Mime = z9.string().min(1).max(120).describe("MIME type, e.g. audio/ogg, application/pdf, image/png.");
|
|
1593
|
+
var DurationMs = z9.number().int().positive().optional().describe("Audio clip length in ms (voice only), if known.");
|
|
1594
|
+
var Filename = z9.string().min(1).max(255).optional().describe("Original filename (file only).");
|
|
1595
|
+
var ReplyTo = z9.string().optional().describe("Optional id of the message being replied to.");
|
|
1596
|
+
var ContactRef3 = z9.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
|
|
1597
|
+
var RoomId3 = z9.string().min(1).describe("Room/channel id (UUID).");
|
|
1598
|
+
var ThreadLabel = z9.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional().describe("Optional thread label within the conversation (mDM USP: multiple threads per contact).");
|
|
1599
|
+
function dmThreadId3(selfId, otherId, label) {
|
|
1600
|
+
const [a, b] = [selfId, otherId].sort();
|
|
1601
|
+
return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
|
|
1602
|
+
}
|
|
1603
|
+
async function sendAttachmentMessage(ctx, args) {
|
|
1604
|
+
readSupabaseEnv();
|
|
1605
|
+
const captionEnvelope = {
|
|
1606
|
+
v: PROTOCOL_VERSION4,
|
|
1607
|
+
type: args.message_type,
|
|
1608
|
+
text: args.caption ?? "",
|
|
1609
|
+
sent_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1610
|
+
};
|
|
1611
|
+
const encrypted_payload = Buffer.from(JSON.stringify(captionEnvelope), "utf8").toString("base64");
|
|
1612
|
+
ctx.log("debug", "sendAttachmentMessage", {
|
|
1613
|
+
thread_id: args.thread_id,
|
|
1614
|
+
message_type: args.message_type,
|
|
1615
|
+
bucket: args.attachment.bucket
|
|
1616
|
+
});
|
|
1617
|
+
const data = await invokeFunction("message-send", {
|
|
1618
|
+
space_id: args.space_id,
|
|
1619
|
+
thread_id: args.thread_id,
|
|
1620
|
+
message_type: args.message_type,
|
|
1621
|
+
attachments: [args.attachment],
|
|
1622
|
+
// TODO(Lane A): confirm field placement
|
|
1623
|
+
encrypted_payload,
|
|
1624
|
+
protocol_version: PROTOCOL_VERSION4,
|
|
1625
|
+
recipient_account_id: args.recipient_account_id ?? null,
|
|
1626
|
+
reply_to_id: args.reply_to_id ?? null
|
|
1627
|
+
});
|
|
1628
|
+
if (!data?.message?.id) throw new Error("message-send returned no message id (attachment)");
|
|
1629
|
+
return {
|
|
1630
|
+
message_id: data.message.id,
|
|
1631
|
+
delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1632
|
+
thread_id: args.thread_id
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
async function resolveLinkedSpaceId2(channelId) {
|
|
1636
|
+
const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
|
|
1637
|
+
const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
|
|
1638
|
+
if (!spaceId) throw new Error(`Channel ${channelId} has no linked space yet \u2014 run mIRC_join/mIRC_list first or pass space_id.`);
|
|
1639
|
+
return spaceId;
|
|
1640
|
+
}
|
|
1641
|
+
var mDM_send_voice_input = z9.object({
|
|
1642
|
+
to: ContactRef3,
|
|
1643
|
+
audio_base64: Base64Body,
|
|
1644
|
+
mime: Mime.default("audio/ogg"),
|
|
1645
|
+
duration_ms: DurationMs,
|
|
1646
|
+
caption: z9.string().max(2e3).optional(),
|
|
1647
|
+
thread_label: ThreadLabel,
|
|
1648
|
+
reply_to_id: ReplyTo
|
|
1649
|
+
});
|
|
1650
|
+
var mDM_send_file_input = z9.object({
|
|
1651
|
+
to: ContactRef3,
|
|
1652
|
+
file_base64: Base64Body,
|
|
1653
|
+
filename: Filename,
|
|
1654
|
+
mime: Mime,
|
|
1655
|
+
caption: z9.string().max(2e3).optional(),
|
|
1656
|
+
thread_label: ThreadLabel,
|
|
1657
|
+
reply_to_id: ReplyTo
|
|
1658
|
+
});
|
|
1659
|
+
async function mDM_send_voice(input, ctx) {
|
|
1660
|
+
const dm = ctx.providers.dm;
|
|
1661
|
+
const selfId = await dm.selfId();
|
|
1662
|
+
const thread_id = dmThreadId3(selfId, input.to, input.thread_label);
|
|
1663
|
+
const attachment = await uploadBlob({
|
|
1664
|
+
kind: "voice",
|
|
1665
|
+
bytes: decodeBase64Body(input.audio_base64),
|
|
1666
|
+
mime: input.mime,
|
|
1667
|
+
prefix: thread_id,
|
|
1668
|
+
duration_ms: input.duration_ms
|
|
1669
|
+
});
|
|
1670
|
+
return sendAttachmentMessage(ctx, {
|
|
1671
|
+
space_id: "dm",
|
|
1672
|
+
thread_id,
|
|
1673
|
+
message_type: "voice",
|
|
1674
|
+
attachment,
|
|
1675
|
+
caption: input.caption,
|
|
1676
|
+
reply_to_id: input.reply_to_id,
|
|
1677
|
+
recipient_account_id: input.to
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
async function mDM_send_file(input, ctx) {
|
|
1681
|
+
const dm = ctx.providers.dm;
|
|
1682
|
+
const selfId = await dm.selfId();
|
|
1683
|
+
const thread_id = dmThreadId3(selfId, input.to, input.thread_label);
|
|
1684
|
+
const attachment = await uploadBlob({
|
|
1685
|
+
kind: "file",
|
|
1686
|
+
bytes: decodeBase64Body(input.file_base64),
|
|
1687
|
+
mime: input.mime,
|
|
1688
|
+
prefix: thread_id,
|
|
1689
|
+
filename: input.filename
|
|
1690
|
+
});
|
|
1691
|
+
return sendAttachmentMessage(ctx, {
|
|
1692
|
+
space_id: "dm",
|
|
1693
|
+
thread_id,
|
|
1694
|
+
message_type: "file",
|
|
1695
|
+
attachment,
|
|
1696
|
+
caption: input.caption,
|
|
1697
|
+
reply_to_id: input.reply_to_id,
|
|
1698
|
+
recipient_account_id: input.to
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
var mIRC_send_voice_input = z9.object({
|
|
1702
|
+
channel_id: RoomId3,
|
|
1703
|
+
audio_base64: Base64Body,
|
|
1704
|
+
mime: Mime.default("audio/ogg"),
|
|
1705
|
+
duration_ms: DurationMs,
|
|
1706
|
+
caption: z9.string().max(2e3).optional(),
|
|
1707
|
+
reply_to_id: ReplyTo,
|
|
1708
|
+
space_id: z9.string().optional().describe("Backing space id. Resolved automatically if omitted.")
|
|
1709
|
+
});
|
|
1710
|
+
var mIRC_send_file_input = z9.object({
|
|
1711
|
+
channel_id: RoomId3,
|
|
1712
|
+
file_base64: Base64Body,
|
|
1713
|
+
filename: Filename,
|
|
1714
|
+
mime: Mime,
|
|
1715
|
+
caption: z9.string().max(2e3).optional(),
|
|
1716
|
+
reply_to_id: ReplyTo,
|
|
1717
|
+
space_id: z9.string().optional()
|
|
1718
|
+
});
|
|
1719
|
+
async function mIRC_send_voice(input, ctx) {
|
|
1720
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId2(input.channel_id);
|
|
1721
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
1722
|
+
const attachment = await uploadBlob({ kind: "voice", bytes: decodeBase64Body(input.audio_base64), mime: input.mime, prefix: thread_id, duration_ms: input.duration_ms });
|
|
1723
|
+
return sendAttachmentMessage(ctx, { space_id, thread_id, message_type: "voice", attachment, caption: input.caption, reply_to_id: input.reply_to_id });
|
|
1724
|
+
}
|
|
1725
|
+
async function mIRC_send_file(input, ctx) {
|
|
1726
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId2(input.channel_id);
|
|
1727
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
1728
|
+
const attachment = await uploadBlob({ kind: "file", bytes: decodeBase64Body(input.file_base64), mime: input.mime, prefix: thread_id, filename: input.filename });
|
|
1729
|
+
return sendAttachmentMessage(ctx, { space_id, thread_id, message_type: "file", attachment, caption: input.caption, reply_to_id: input.reply_to_id });
|
|
1730
|
+
}
|
|
1731
|
+
var attachmentTools = [
|
|
1732
|
+
{
|
|
1733
|
+
name: "mDM_send_voice",
|
|
1734
|
+
requires: "network",
|
|
1735
|
+
description: "Send a VOICE note to a contact as a first-class mDM `voice` message (not a URL stub). Pass audio bytes as base64; the tool uploads to Storage and posts via message-send with the voice attachment descriptor. SCAFFOLD: mDM is client-encrypted \u2014 until the seal step ships, bytes are uploaded unsealed (TODO Lane A).",
|
|
1736
|
+
inputSchema: mDM_send_voice_input,
|
|
1737
|
+
handler: mDM_send_voice
|
|
1738
|
+
},
|
|
1739
|
+
{
|
|
1740
|
+
name: "mDM_send_file",
|
|
1741
|
+
requires: "network",
|
|
1742
|
+
description: "Send a FILE to a contact as a first-class mDM `file` message. Base64 bytes \u2192 Storage \u2192 message-send file attachment. SCAFFOLD: mDM E2EE seal is TODO (Lane A).",
|
|
1743
|
+
inputSchema: mDM_send_file_input,
|
|
1744
|
+
handler: mDM_send_file
|
|
1745
|
+
},
|
|
1746
|
+
{
|
|
1747
|
+
name: "mIRC_send_voice",
|
|
1748
|
+
requires: "network",
|
|
1749
|
+
description: "Send a VOICE note into a persistent channel as a first-class `voice` message. Base64 audio \u2192 Storage \u2192 message-send (backing space resolved automatically).",
|
|
1750
|
+
inputSchema: mIRC_send_voice_input,
|
|
1751
|
+
handler: mIRC_send_voice
|
|
1752
|
+
},
|
|
1753
|
+
{
|
|
1754
|
+
name: "mIRC_send_file",
|
|
1755
|
+
requires: "network",
|
|
1756
|
+
description: "Send a FILE into a persistent channel as a first-class `file` message. Base64 bytes \u2192 Storage \u2192 message-send.",
|
|
1757
|
+
inputSchema: mIRC_send_file_input,
|
|
1758
|
+
handler: mIRC_send_file
|
|
1759
|
+
}
|
|
1760
|
+
];
|
|
1761
|
+
|
|
1762
|
+
// src/tools/knowledge.ts
|
|
1763
|
+
import { z as z10 } from "zod";
|
|
1764
|
+
var mRAG_search_input = z10.object({
|
|
1765
|
+
query: z10.string().min(1).max(2e3).describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
|
|
1766
|
+
top_k: z10.number().int().min(1).max(25).optional().describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
|
|
1767
|
+
source_types: z10.array(z10.enum(["message", "email", "call", "note", "contact"])).optional().describe("Restrict retrieval to these source types. Omit to search everything."),
|
|
1768
|
+
thread_id: z10.string().optional().describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread).")
|
|
1769
|
+
});
|
|
1770
|
+
async function mRAG_search(input, ctx) {
|
|
1771
|
+
readSupabaseEnv();
|
|
1772
|
+
ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
|
|
1773
|
+
const data = await invokeFunction("rag-query", {
|
|
1774
|
+
query: input.query,
|
|
1775
|
+
top_k: input.top_k ?? 8,
|
|
1776
|
+
source_types: input.source_types ?? null,
|
|
1777
|
+
thread_id: input.thread_id ?? null
|
|
1778
|
+
});
|
|
1779
|
+
return {
|
|
1780
|
+
answer: data.answer ?? "",
|
|
1781
|
+
sources: data.sources ?? [],
|
|
1782
|
+
chunks_found: data.chunks_found ?? (data.sources?.length ?? 0)
|
|
1783
|
+
};
|
|
1784
|
+
}
|
|
1785
|
+
var mRAG_ingest_input = z10.object({
|
|
1786
|
+
content_text: z10.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."),
|
|
1787
|
+
source_type: z10.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."),
|
|
1788
|
+
source_id: z10.string().optional().describe("Optional stable id for the source so re-ingests can be grouped."),
|
|
1789
|
+
thread_id: z10.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
|
|
1790
|
+
title: z10.string().max(300).optional().describe("Optional human title, stored in metadata.")
|
|
1791
|
+
});
|
|
1792
|
+
async function mRAG_ingest(input, ctx) {
|
|
1793
|
+
readSupabaseEnv();
|
|
1794
|
+
const backendType = input.source_type === "note" ? "file" : input.source_type ?? "file";
|
|
1795
|
+
ctx.log("debug", "mRAG_ingest via rag-index", { source_type: backendType });
|
|
1796
|
+
const data = await invokeFunction("rag-index", {
|
|
1797
|
+
source_type: backendType,
|
|
1798
|
+
source_id: input.source_id ?? null,
|
|
1799
|
+
thread_id: input.thread_id ?? null,
|
|
1800
|
+
content_text: input.content_text,
|
|
1801
|
+
metadata: { ...input.title ? { title: input.title } : {}, ingested_via: "mRAG_ingest" }
|
|
1802
|
+
});
|
|
1803
|
+
return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
|
|
1804
|
+
}
|
|
1805
|
+
var mRAG_list_sources_input = z10.object({});
|
|
1806
|
+
async function mRAG_list_sources(_input, ctx) {
|
|
1807
|
+
readSupabaseEnv();
|
|
1808
|
+
ctx.log("debug", "mRAG_list_sources via rag-sources");
|
|
1809
|
+
return await invokeFunction("rag-sources", { action: "list" });
|
|
1810
|
+
}
|
|
1811
|
+
var mRAG_delete_input = z10.object({
|
|
1812
|
+
source_id: z10.string().optional().describe("Delete every indexed chunk with this source_id (from mRAG_list_sources)."),
|
|
1813
|
+
thread_id: z10.string().optional().describe("Delete every indexed chunk associated with this thread_id.")
|
|
1814
|
+
}).refine((v) => v.source_id || v.thread_id, {
|
|
1815
|
+
message: "Provide source_id or thread_id \u2014 mRAG_delete refuses to purge the whole index."
|
|
1816
|
+
});
|
|
1817
|
+
async function mRAG_delete(input, ctx) {
|
|
1818
|
+
readSupabaseEnv();
|
|
1819
|
+
ctx.log("debug", "mRAG_delete via rag-sources", { source_id: input.source_id, thread_id: input.thread_id });
|
|
1820
|
+
return await invokeFunction("rag-sources", {
|
|
1821
|
+
action: "delete",
|
|
1822
|
+
source_id: input.source_id ?? null,
|
|
1823
|
+
thread_id: input.thread_id ?? null
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
var knowledgeTools = [
|
|
1827
|
+
{
|
|
1828
|
+
name: "mRAG_ingest",
|
|
1829
|
+
requires: "network",
|
|
1830
|
+
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.",
|
|
1831
|
+
inputSchema: mRAG_ingest_input,
|
|
1832
|
+
handler: mRAG_ingest
|
|
1833
|
+
},
|
|
1834
|
+
{
|
|
1835
|
+
name: "mRAG_search",
|
|
1836
|
+
requires: "network",
|
|
1837
|
+
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.",
|
|
1838
|
+
inputSchema: mRAG_search_input,
|
|
1839
|
+
handler: mRAG_search
|
|
1840
|
+
},
|
|
1841
|
+
{
|
|
1842
|
+
name: "mRAG_list_sources",
|
|
1843
|
+
requires: "network",
|
|
1844
|
+
description: "List what is currently indexed in the user's private knowledge base, grouped by source (source_type, source_id, thread_id, title) with per-source chunk counts and first/last indexed timestamps. Use it to see what mRAG_search can recall, and to find a source_id to remove with mRAG_delete. Owner-scoped.",
|
|
1845
|
+
inputSchema: mRAG_list_sources_input,
|
|
1846
|
+
handler: mRAG_list_sources
|
|
1847
|
+
},
|
|
1848
|
+
{
|
|
1849
|
+
name: "mRAG_delete",
|
|
1850
|
+
requires: "network",
|
|
1851
|
+
description: "Remove indexed content from the user's knowledge base by source_id or thread_id (from mRAG_list_sources). Deletes every embedded chunk for that source so mRAG_search can no longer recall it. Requires source_id or thread_id (will not purge the whole index). Returns the number of chunks deleted. Owner-scoped.",
|
|
1852
|
+
inputSchema: mRAG_delete_input,
|
|
1853
|
+
handler: mRAG_delete
|
|
1854
|
+
}
|
|
1855
|
+
];
|
|
1856
|
+
|
|
1857
|
+
// src/tools/actions.ts
|
|
1858
|
+
import { z as z11 } from "zod";
|
|
1859
|
+
var formField = z11.object({
|
|
1860
|
+
name: z11.string().min(1).max(60).describe("Field key \u2014 returned verbatim in the result."),
|
|
1861
|
+
label: z11.string().max(120).optional().describe("Human label shown to the recipient. Defaults to `name`."),
|
|
1862
|
+
type: z11.enum(["text", "email", "number", "textarea", "tel", "url"]).optional().describe("Input type. Default 'text'."),
|
|
1863
|
+
required: z11.boolean().optional().describe("Whether the recipient must fill this field.")
|
|
1864
|
+
});
|
|
1865
|
+
var action_create_input = z11.object({
|
|
1866
|
+
action_type: z11.enum(["confirm", "file_request", "form", "open_url", "screen_share"]).describe(
|
|
1867
|
+
"What you want the recipient to do: 'confirm' (yes/no), 'file_request' (pick a file from their computer), 'form' (fill fields), 'open_url' (open a vetted https URL), 'screen_share' (recipient shares their screen so you can SEE it via comms_action_frame_get \u2014 view only)."
|
|
1868
|
+
),
|
|
1869
|
+
message: z11.string().min(1).max(2e3).describe("What you're asking \u2014 shown on the consent screen above the action UI."),
|
|
1870
|
+
creator_label: z11.string().max(80).optional().describe("How you're identified to the recipient (e.g. your agent name). Default 'Agent'."),
|
|
1871
|
+
// confirm
|
|
1872
|
+
yes_label: z11.string().max(40).optional().describe("[confirm] Affirmative button label. Default 'Tak'."),
|
|
1873
|
+
no_label: z11.string().max(40).optional().describe("[confirm] Negative button label. Default 'Nie'."),
|
|
1874
|
+
// file_request
|
|
1875
|
+
accept: z11.string().max(200).optional().describe("[file_request] Accepted file types (HTML accept attr, e.g. 'image/*,.pdf')."),
|
|
1876
|
+
max_bytes: z11.number().int().positive().max(5242880).optional().describe("[file_request] Max file size in bytes (\u2264 5 MB). NOTE: the returned file is NOT yet end-to-end encrypted \u2014 do not request sensitive files until Tier 1.1 ships."),
|
|
1877
|
+
// form
|
|
1878
|
+
fields: z11.array(formField).min(1).max(20).optional().describe("[form] Fields to collect from the recipient."),
|
|
1879
|
+
// open_url
|
|
1880
|
+
url: z11.string().url().optional().describe("[open_url] The https URL to open. The full URL is shown to the recipient before they open it."),
|
|
1881
|
+
// screen_share
|
|
1882
|
+
max_width: z11.number().int().positive().max(1920).optional().describe("[screen_share] Max captured frame width in px (default 1280). Frames are downscaled JPEGs."),
|
|
1883
|
+
// lifecycle
|
|
1884
|
+
ttl_ms: z11.number().int().positive().optional().describe("Link lifetime in milliseconds. Default 24h, capped at 7d."),
|
|
1885
|
+
max_uses: z11.number().int().min(1).max(50).optional().describe("How many times the link can be redeemed. Default 1 (single-use).")
|
|
1886
|
+
});
|
|
1887
|
+
function buildParams(input) {
|
|
1888
|
+
switch (input.action_type) {
|
|
1889
|
+
case "confirm":
|
|
1890
|
+
return { message: input.message, yesLabel: input.yes_label, noLabel: input.no_label };
|
|
1891
|
+
case "file_request":
|
|
1892
|
+
return { message: input.message, accept: input.accept, maxBytes: input.max_bytes };
|
|
1893
|
+
case "form":
|
|
1894
|
+
if (!input.fields?.length) throw new Error("action_type 'form' requires a non-empty `fields` array.");
|
|
1895
|
+
return { message: input.message, fields: input.fields };
|
|
1896
|
+
case "open_url":
|
|
1897
|
+
if (!input.url) throw new Error("action_type 'open_url' requires `url`.");
|
|
1898
|
+
return { message: input.message, url: input.url };
|
|
1899
|
+
case "screen_share":
|
|
1900
|
+
return { message: input.message, maxWidth: input.max_width };
|
|
1901
|
+
default:
|
|
1902
|
+
return { message: input.message };
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
async function action_create(input, ctx) {
|
|
1906
|
+
readSupabaseEnv();
|
|
1907
|
+
ctx.log("debug", "action_create invoking action-create", { action_type: input.action_type });
|
|
1908
|
+
const body = {
|
|
1909
|
+
action_type: input.action_type,
|
|
1910
|
+
params: buildParams(input)
|
|
1911
|
+
};
|
|
1912
|
+
if (input.creator_label !== void 0) body.creator_label = input.creator_label;
|
|
1913
|
+
if (input.ttl_ms !== void 0) body.ttl_ms = input.ttl_ms;
|
|
1914
|
+
if (input.max_uses !== void 0) body.max_uses = input.max_uses;
|
|
1915
|
+
const res = await invokeFunction("action-create", body);
|
|
1916
|
+
if (res.error) throw new Error(res.error);
|
|
1917
|
+
if (!res.link || !res.token) throw new Error("action-create returned a malformed response (missing link/token).");
|
|
1918
|
+
return {
|
|
1919
|
+
action_id: res.action_id ?? "",
|
|
1920
|
+
token: res.token,
|
|
1921
|
+
link: res.link,
|
|
1922
|
+
action_type: res.action_type ?? input.action_type,
|
|
1923
|
+
expires_at: res.expires_at ?? ""
|
|
1924
|
+
};
|
|
1925
|
+
}
|
|
1926
|
+
var action_frame_get_input = z11.object({
|
|
1927
|
+
action_id: z11.string().min(1).describe("The action_id returned by comms_action_create for a 'screen_share' action you created.")
|
|
1928
|
+
});
|
|
1929
|
+
async function action_frame_get(input, ctx) {
|
|
1930
|
+
readSupabaseEnv();
|
|
1931
|
+
ctx.log("debug", "action_frame_get reading frame", { action_id: input.action_id });
|
|
1932
|
+
const sb = getSupabase();
|
|
1933
|
+
const { data, error } = await sb.from("action_screen_frames").select("image_jpeg, width, seq, updated_at").eq("action_id", input.action_id).maybeSingle();
|
|
1934
|
+
if (error) throw new Error(error.message);
|
|
1935
|
+
if (!data) {
|
|
1936
|
+
return { mcpContent: [{ type: "text", text: "No frame yet \u2014 the recipient hasn't started sharing their screen (or you don't own this action)." }] };
|
|
1937
|
+
}
|
|
1938
|
+
const row = data;
|
|
1939
|
+
const ageSec = Math.round((Date.now() - new Date(row.updated_at).getTime()) / 1e3);
|
|
1940
|
+
return {
|
|
1941
|
+
mcpContent: [
|
|
1942
|
+
{ type: "text", text: `Latest screen frame \u2014 seq ${row.seq}, ${row.width ?? "?"}px wide, ${ageSec}s old.` },
|
|
1943
|
+
{ type: "image", data: row.image_jpeg, mimeType: "image/jpeg" }
|
|
1944
|
+
]
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1947
|
+
var actionTools = [
|
|
1948
|
+
{
|
|
1949
|
+
// RFC 0001: channel-agnostic capability (link is sent over ANY channel), so it
|
|
1950
|
+
// lives in the `comms_` namespace rather than a channel `m<MODULE>_` prefix.
|
|
1951
|
+
// A dedicated `mACT` module (create/get/status) is a possible RFC follow-up.
|
|
1952
|
+
name: "comms_action_create",
|
|
1953
|
+
requires: "network",
|
|
1954
|
+
description: "Mint a single-use, expiring action link (https://mosadd.com/do/<token>) that asks a human to DO something in their browser, with explicit consent. action_type: 'confirm' (yes/no) | 'file_request' (recipient picks a file from their computer) | 'form' (recipient fills fields you define) | 'open_url' (recipient opens a vetted https URL). Returns { action_id, token, link, expires_at }. Send the `link` to the person via mDM/mIRC/mp0st; they open it, consent, and the browser performs the action in its sandbox (no install, no OS access). The action is owned by you (the calling user). HONEST LIMITS: this is browser-sandbox only \u2014 it cannot click other apps, run programs, or read files the user didn't pick; and file_request payloads are not yet end-to-end encrypted (don't request sensitive files until Tier 1.1).",
|
|
1955
|
+
inputSchema: action_create_input,
|
|
1956
|
+
handler: action_create
|
|
1957
|
+
},
|
|
1958
|
+
{
|
|
1959
|
+
name: "comms_action_frame_get",
|
|
1960
|
+
requires: "network",
|
|
1961
|
+
description: "See the LATEST screen frame from a 'screen_share' action you created (pass the action_id from comms_action_create). Returns the current screenshot AS AN IMAGE you can look at, plus how old it is. The recipient must have opened the link and clicked 'share screen' first. Poll this every few seconds to watch live. VIEW ONLY \u2014 you cannot click or control their screen. Returns a 'no frame yet' note until they start sharing.",
|
|
1962
|
+
inputSchema: action_frame_get_input,
|
|
1963
|
+
handler: action_frame_get
|
|
1964
|
+
}
|
|
1965
|
+
];
|
|
1966
|
+
|
|
1967
|
+
// src/tools/embed.ts
|
|
1968
|
+
import { z as z12 } from "zod";
|
|
1969
|
+
var EMBED_CDN = (process.env.MOSADD_EMBED_CDN ?? "https://embed.mosadd.com").replace(/\/+$/, "");
|
|
1970
|
+
var POSITIONS = ["inline", "sidebar-left", "sidebar-right", "floating-bl", "floating-br", "fullscreen"];
|
|
1971
|
+
var SKINS = ["default", "retro-irc-1990", "terminal", "minimal-dark", "minimal-light"];
|
|
1972
|
+
var embed_create_input = z12.object({
|
|
1973
|
+
channel: z12.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/).describe("The mIRC channel id everyone on the embed shares (e.g. 'acme-support'). Auto-created on first message if new."),
|
|
1974
|
+
allowed_origins: z12.array(z12.string().min(1)).min(1).max(10).describe("REQUIRED. Domain(s) where the widget will be served \u2014 the key only works from these origins. Use the host(s) of the app you're building, e.g. ['app.acme.com','*.acme.com']. For local testing use mode:'test' and e.g. 'localhost:3000'."),
|
|
1975
|
+
name: z12.string().max(64).optional().describe("Label for the key in the owner's dashboard. Default 'embed: <channel>'."),
|
|
1976
|
+
position: z12.enum(POSITIONS).optional().describe("Where the widget renders. Default 'inline'."),
|
|
1977
|
+
skin: z12.enum(SKINS).optional().describe("Visual skin. Default 'default' (mosadd-branded retro mIRC)."),
|
|
1978
|
+
title: z12.string().max(60).optional().describe("Header title shown in the widget. Default 'mIRC'."),
|
|
1979
|
+
anon: z12.boolean().optional().describe("Allow visitors to join with just a nick (no mosadd account). Default true."),
|
|
1980
|
+
locale: z12.enum(["en", "pl"]).optional().describe("Widget UI language. Default 'en'."),
|
|
1981
|
+
mode: z12.enum(["live", "test"]).optional().describe("Key mode \u2014 'test' for local/dev origins, 'live' for production. Default 'live'.")
|
|
1982
|
+
});
|
|
1983
|
+
var attrSafe = (s) => s.replace(/["'<>]/g, "");
|
|
1984
|
+
function buildSnippet(input, key) {
|
|
1985
|
+
const attrs = [`data-channel="${attrSafe(input.channel)}"`, `data-position="${input.position ?? "inline"}"`];
|
|
1986
|
+
if (input.skin) attrs.push(`data-skin="${input.skin}"`);
|
|
1987
|
+
if (input.title) attrs.push(`data-title="${attrSafe(input.title)}"`);
|
|
1988
|
+
if (input.anon === false) attrs.push(`data-anon="false"`);
|
|
1989
|
+
if (input.locale) attrs.push(`data-locale="${input.locale}"`);
|
|
1990
|
+
return `<div id="mosadd-mirc" ${attrs.join(" ")}></div>
|
|
1991
|
+
<script src="${EMBED_CDN}/v1.js" data-key="${key}"></script>`;
|
|
1992
|
+
}
|
|
1993
|
+
async function embed_create(input, ctx) {
|
|
1994
|
+
readSupabaseEnv();
|
|
1995
|
+
ctx.log("debug", "comms_embed_create minting embed key", { channel: input.channel, origins: input.allowed_origins.length });
|
|
1996
|
+
const res = await invokeFunction("embed-keys", {
|
|
1997
|
+
name: input.name ?? `embed: ${input.channel}`,
|
|
1998
|
+
channels: [input.channel],
|
|
1999
|
+
allowed_origins: input.allowed_origins,
|
|
2000
|
+
mode: input.mode ?? "live"
|
|
2001
|
+
});
|
|
2002
|
+
if (res.error) throw new Error(res.error);
|
|
2003
|
+
if (!res.key) throw new Error("embed-keys returned no publishable key (missing `key`).");
|
|
2004
|
+
return {
|
|
2005
|
+
embed_key: res.key,
|
|
2006
|
+
channel: input.channel,
|
|
2007
|
+
allowed_origins: input.allowed_origins,
|
|
2008
|
+
snippet: buildSnippet(input, res.key)
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
var embedTools = [
|
|
2012
|
+
{
|
|
2013
|
+
name: "comms_embed_create",
|
|
2014
|
+
requires: "network",
|
|
2015
|
+
description: "Embed a LIVE mosadd chat channel into an app/site you're building (great for builder-agents on Lovable/Bolt/Cursor/v0). Mints a publishable embed key scoped to a channel + the app's domain(s) and returns a ready-to-paste HTML snippet (a <div> + <script src=embed.mosadd.com/v1.js data-key=\u2026>). Visitors of the host page chat in real time (anonymous nick or mosadd login). REQUIRES `allowed_origins` \u2014 the domain(s) the app is served from (the key only works there). The publishable key is browser-safe (mints only channel-scoped JWTs); your hub key never leaves the server. Returns { embed_key, channel, allowed_origins, snippet }.",
|
|
2016
|
+
inputSchema: embed_create_input,
|
|
2017
|
+
handler: embed_create
|
|
2018
|
+
}
|
|
2019
|
+
];
|
|
2020
|
+
|
|
2021
|
+
// src/tools/threat.ts
|
|
2022
|
+
import { z as z13 } from "zod";
|
|
2023
|
+
import {
|
|
2024
|
+
THREAT_EVENTS,
|
|
2025
|
+
THREAT_EVENT_COUNT,
|
|
2026
|
+
evaluateEvent,
|
|
2027
|
+
getEventDef
|
|
2028
|
+
} from "@mosadd/threat-engine";
|
|
2029
|
+
var threat_catalog_input = z13.object({
|
|
2030
|
+
category: z13.enum(["COMINT", "ELINT", "MASINT", "CYBER", "BEHAVIORAL", "PRIVACY", "SIGINT", "OSINT", "MPOST"]).optional().describe("Filter the catalog to one intelligence-discipline category. Omit for the full catalog."),
|
|
2031
|
+
platform: z13.enum(["apk", "ios", "pwa", "harmony"]).optional().describe("Filter to events detectable on this platform. Omit for all platforms.")
|
|
2032
|
+
});
|
|
2033
|
+
async function threat_catalog(input, _ctx) {
|
|
2034
|
+
let events = THREAT_EVENTS;
|
|
2035
|
+
if (input.category) events = events.filter((e) => e.category === input.category);
|
|
2036
|
+
if (input.platform) events = events.filter((e) => e.platforms.includes(input.platform));
|
|
2037
|
+
return { count: events.length, total: THREAT_EVENT_COUNT, events };
|
|
2038
|
+
}
|
|
2039
|
+
var threat_classify_input = z13.object({
|
|
2040
|
+
event_type: z13.string().min(1).max(120).describe('Event type to classify, e.g. "SIM_SWAP", "AUTH_BRUTEFORCE", "TOLL_FRAUD". Case-insensitive.'),
|
|
2041
|
+
severity: z13.string().optional().describe('Optional producer severity hint. "killswitch" \u2192 lock_account; "critical" \u2192 revoke_sessions; anything else is informational.'),
|
|
2042
|
+
details: z13.string().max(2e3).optional().describe("Optional free-text context (informational only).")
|
|
2043
|
+
});
|
|
2044
|
+
async function threat_classify(input, _ctx) {
|
|
2045
|
+
const def = getEventDef(String(input.event_type).toUpperCase());
|
|
2046
|
+
if (def) {
|
|
2047
|
+
return {
|
|
2048
|
+
action: "monitor",
|
|
2049
|
+
severity: def.severity,
|
|
2050
|
+
reason: `${def.label} (${def.category}) \u2014 classified from the mosadd threat taxonomy. Monitor-only: surfaced for you to act on, no automatic action taken.`,
|
|
2051
|
+
known_event: true,
|
|
2052
|
+
category: def.category,
|
|
2053
|
+
label: def.label
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
const decision = evaluateEvent({ eventType: input.event_type, severity: input.severity, details: input.details });
|
|
2057
|
+
return { ...decision, known_event: false, category: null, label: null };
|
|
2058
|
+
}
|
|
2059
|
+
var threatTools = [
|
|
2060
|
+
{
|
|
2061
|
+
name: "threat_catalog",
|
|
2062
|
+
requires: "any",
|
|
2063
|
+
description: "List the canonical mosadd threat-event taxonomy (the full radar catalog: id, category, default severity, auto-actions, per-platform availability). Filter by category or platform. Pure/offline \u2014 returns { count, total, events }. Use to discover what the defensive engine recognises.",
|
|
2064
|
+
inputSchema: threat_catalog_input,
|
|
2065
|
+
handler: threat_catalog
|
|
2066
|
+
},
|
|
2067
|
+
{
|
|
2068
|
+
name: "threat_classify",
|
|
2069
|
+
requires: "any",
|
|
2070
|
+
description: `Classify a single telemetry event against the mosadd threat taxonomy + DECK engine. For a known event type (e.g. PROCESS_INJECTION, STINGRAY_DETECT, IMSI_CATCHER_SCAN, MEMORY_INJECTION) it returns that event's real severity (info|warning|elevated|critical|killswitch) with action="monitor" \u2014 Pegasus-class events surface as critical immediately, but the engine NEVER auto-acts (it tells you, it never disconnects/locks). Unknown strings fall back to the pure DECK decision (log_only|revoke_sessions|lock_account|suspend_did). Returns { action, severity, reason, known_event, category, label }. Deterministic, offline, no backend.`,
|
|
2071
|
+
inputSchema: threat_classify_input,
|
|
2072
|
+
handler: threat_classify
|
|
2073
|
+
}
|
|
2074
|
+
];
|
|
2075
|
+
|
|
2076
|
+
// src/tools/murl.ts
|
|
2077
|
+
import { z as z14 } from "zod";
|
|
2078
|
+
var DEFAULT_EDGE_URL2 = "https://mosadd-edge.mr-brics-33.workers.dev";
|
|
2079
|
+
function edgeUrl2() {
|
|
2080
|
+
return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL2;
|
|
2081
|
+
}
|
|
2082
|
+
function hubKey2() {
|
|
2083
|
+
const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
|
|
2084
|
+
if (!key) throw new Error("MOSADD_API_KEY required for mURL tools (see `mosadd login` / hub-keys).");
|
|
2085
|
+
return key;
|
|
2086
|
+
}
|
|
2087
|
+
function urlToSlug(input) {
|
|
2088
|
+
let s = String(input).trim().toLowerCase();
|
|
2089
|
+
s = s.replace(/^[a-z]+:\/\//, "").replace(/[?#].*$/, "");
|
|
2090
|
+
const slash = s.indexOf("/");
|
|
2091
|
+
let host = (slash >= 0 ? s.slice(0, slash) : s).replace(/:\d+$/, "");
|
|
2092
|
+
if (host.startsWith("www.")) host = host.slice(4);
|
|
2093
|
+
if (!host || !/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(host)) {
|
|
2094
|
+
throw new Error(`Invalid URL: "${input}" \u2014 pass a domain like "example.com" or a full URL.`);
|
|
2095
|
+
}
|
|
2096
|
+
const segs = (slash >= 0 ? s.slice(slash) : "").split("/").map((seg) => seg.replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "")).filter(Boolean);
|
|
2097
|
+
const base = host.replace(/\./g, "-");
|
|
2098
|
+
return { domain: host, slug: segs.length ? `${base}__${segs.join("__")}` : base };
|
|
2099
|
+
}
|
|
2100
|
+
var DomainArg = z14.string().min(3).max(2048).describe("A domain ('example.com') or a full URL. Keyed PER-URL: a bare domain \u2192 the domain room; a URL with a path (e.g. 'site.com/articles/abc') \u2192 that page's own room.");
|
|
2101
|
+
var mURL_read_channel_input = z14.object({
|
|
2102
|
+
domain: DomainArg,
|
|
2103
|
+
limit: z14.number().int().min(1).max(100).optional().describe("Recent messages to return (max 100). Default 50.")
|
|
2104
|
+
});
|
|
2105
|
+
async function mURL_read_channel(input, ctx) {
|
|
2106
|
+
const { domain, slug: slug2 } = urlToSlug(input.domain);
|
|
2107
|
+
const limit = input.limit ?? 50;
|
|
2108
|
+
ctx.log("debug", "mURL_read_channel", { domain });
|
|
2109
|
+
const r = await fetch(`${edgeUrl2()}/c/${slug2}/history?limit=${limit}`, {
|
|
2110
|
+
headers: { Authorization: `Bearer ${hubKey2()}` }
|
|
2111
|
+
});
|
|
2112
|
+
if (!r.ok) {
|
|
2113
|
+
const e = await r.text().catch(() => "");
|
|
2114
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
2115
|
+
}
|
|
2116
|
+
const data = await r.json();
|
|
2117
|
+
return {
|
|
2118
|
+
domain,
|
|
2119
|
+
messages: (data.messages ?? []).map((m) => ({ id: m.id, from: m.from ?? null, text: m.text, timestamp: m.ts }))
|
|
2120
|
+
};
|
|
2121
|
+
}
|
|
2122
|
+
var mURL_post_input = z14.object({
|
|
2123
|
+
domain: DomainArg,
|
|
2124
|
+
text: z14.string().min(1).max(2e3).describe("Message body (max 2000 chars, up to 3 lines \u2014 Worker-enforced)."),
|
|
2125
|
+
from: z14.string().max(120).optional().describe("Sender hint shown to others (defaults to the hub-key owner / your agent name).")
|
|
2126
|
+
});
|
|
2127
|
+
async function mURL_post(input, ctx) {
|
|
2128
|
+
const { domain, slug: slug2 } = urlToSlug(input.domain);
|
|
2129
|
+
ctx.log("debug", "mURL_post", { domain });
|
|
2130
|
+
const r = await fetch(`${edgeUrl2()}/c/${slug2}/send`, {
|
|
2131
|
+
method: "POST",
|
|
2132
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${hubKey2()}` },
|
|
2133
|
+
body: JSON.stringify({ text: input.text, from: input.from })
|
|
2134
|
+
});
|
|
2135
|
+
if (!r.ok) {
|
|
2136
|
+
const e = await r.text().catch(() => "");
|
|
2137
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
2138
|
+
}
|
|
2139
|
+
const data = await r.json();
|
|
2140
|
+
if (!data?.id) throw new Error("mosadd-edge: send returned no id");
|
|
2141
|
+
return { domain, message_id: data.id, posted_at: data.ts ?? Date.now() };
|
|
2142
|
+
}
|
|
2143
|
+
var mURL_list_channels_input = z14.object({
|
|
2144
|
+
action: z14.enum(["trending", "list", "mine"]).optional().describe("'trending' (default) = most active domain channels in the last N hours; 'list' = paginated catalogue filtered by status; 'mine' = channels you own (DNS-verified)."),
|
|
2145
|
+
limit: z14.number().int().min(1).max(100).optional().describe("Max channels to return. Default 20."),
|
|
2146
|
+
hours: z14.number().int().min(1).max(168).optional().describe("Trending window in hours. Default 24, max 168 (7d)."),
|
|
2147
|
+
status: z14.enum(["open", "claimed", "blocked"]).optional().describe("For action='list': filter (default 'open')."),
|
|
2148
|
+
cursor: z14.string().optional().describe("For action='list': pagination \u2014 pass previous response's next_cursor (created_at ISO).")
|
|
2149
|
+
});
|
|
2150
|
+
async function mURL_list_channels(input, ctx) {
|
|
2151
|
+
readSupabaseEnv();
|
|
2152
|
+
const action = input.action ?? "trending";
|
|
2153
|
+
ctx.log("debug", "mURL_list_channels invoking murl-channels", { action });
|
|
2154
|
+
return await invokeFunction("murl-channels", {
|
|
2155
|
+
action,
|
|
2156
|
+
limit: input.limit ?? null,
|
|
2157
|
+
hours: input.hours ?? null,
|
|
2158
|
+
status: input.status ?? null,
|
|
2159
|
+
cursor: input.cursor ?? null
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
var mURL_presence_input = z14.object({ domain: DomainArg });
|
|
2163
|
+
async function mURL_presence(input, ctx) {
|
|
2164
|
+
const { domain, slug: slug2 } = urlToSlug(input.domain);
|
|
2165
|
+
ctx.log("debug", "mURL_presence", { domain });
|
|
2166
|
+
const r = await fetch(`${edgeUrl2()}/c/${slug2}/presence`);
|
|
2167
|
+
if (!r.ok) {
|
|
2168
|
+
const e = await r.text().catch(() => "");
|
|
2169
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
2170
|
+
}
|
|
2171
|
+
const data = await r.json();
|
|
2172
|
+
return { domain, count: data.count ?? 0, roster: data.roster ?? [], status: data.status ?? "open" };
|
|
2173
|
+
}
|
|
2174
|
+
var mURL_create_input = z14.object({
|
|
2175
|
+
domain: DomainArg,
|
|
2176
|
+
branding: z14.record(z14.string(), z14.any()).optional().describe("Optional branding JSON (e.g. display name, colour, avatar URL) shown on the channel."),
|
|
2177
|
+
status: z14.enum(["open", "claimed", "blocked"]).optional().describe("Initial status: 'open' (default) = public agent-native room; 'claimed' = registered as yours; 'blocked' = closed.")
|
|
2178
|
+
});
|
|
2179
|
+
async function mURL_create(input, ctx) {
|
|
2180
|
+
readSupabaseEnv();
|
|
2181
|
+
const { domain } = urlToSlug(input.domain);
|
|
2182
|
+
ctx.log("debug", "mURL_create invoking murl-manage", { domain });
|
|
2183
|
+
return await invokeFunction("murl-manage", {
|
|
2184
|
+
action: "create",
|
|
2185
|
+
domain,
|
|
2186
|
+
branding: input.branding ?? null,
|
|
2187
|
+
status: input.status ?? null
|
|
2188
|
+
});
|
|
2189
|
+
}
|
|
2190
|
+
var mURL_update_input = z14.object({
|
|
2191
|
+
domain: DomainArg,
|
|
2192
|
+
branding: z14.record(z14.string(), z14.any()).optional().describe("New branding JSON to set on the channel."),
|
|
2193
|
+
status: z14.enum(["open", "claimed", "blocked"]).optional().describe("New status: 'claimed' to mark owned, 'blocked' to close the room, 'open' to reopen.")
|
|
2194
|
+
});
|
|
2195
|
+
async function mURL_update(input, ctx) {
|
|
2196
|
+
readSupabaseEnv();
|
|
2197
|
+
const { domain } = urlToSlug(input.domain);
|
|
2198
|
+
const slug2 = domain.replace(/\./g, "-");
|
|
2199
|
+
ctx.log("debug", "mURL_update invoking murl-manage", { domain });
|
|
2200
|
+
return await invokeFunction("murl-manage", {
|
|
2201
|
+
action: "update",
|
|
2202
|
+
slug: slug2,
|
|
2203
|
+
branding: input.branding ?? null,
|
|
2204
|
+
status: input.status ?? null
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2207
|
+
var mURL_delete_input = z14.object({ domain: DomainArg });
|
|
2208
|
+
async function mURL_delete(input, ctx) {
|
|
2209
|
+
readSupabaseEnv();
|
|
2210
|
+
const { domain } = urlToSlug(input.domain);
|
|
2211
|
+
const slug2 = domain.replace(/\./g, "-");
|
|
2212
|
+
ctx.log("debug", "mURL_delete invoking murl-manage", { domain });
|
|
2213
|
+
return await invokeFunction("murl-manage", { action: "delete", slug: slug2 });
|
|
2214
|
+
}
|
|
2215
|
+
var murlTools = [
|
|
2216
|
+
{
|
|
2217
|
+
name: "mURL_read_channel",
|
|
2218
|
+
requires: "network",
|
|
2219
|
+
description: "Read the live chat channel for a web DOMAIN (mURL \u2014 'IRC for URLs'). Returns the most recent messages humans and agents have posted about that domain. Use it to get real-time, crowd-sourced context before acting on a site \u2014 e.g. scam warnings, promo codes, outage reports, 'is this legit?'. The channel auto-exists for any domain. Auth: MOSADD_API_KEY (hub key).",
|
|
2220
|
+
inputSchema: mURL_read_channel_input,
|
|
2221
|
+
handler: mURL_read_channel
|
|
2222
|
+
},
|
|
2223
|
+
{
|
|
2224
|
+
name: "mURL_post",
|
|
2225
|
+
requires: "network",
|
|
2226
|
+
description: "Post a message into a web DOMAIN's mURL chat channel \u2014 leave context for the humans and agents who visit that site next (a finding, warning, tip, or coordination note). Sub-100ms global fan-out to everyone currently on the channel. Auth: MOSADD_API_KEY (hub key).",
|
|
2227
|
+
inputSchema: mURL_post_input,
|
|
2228
|
+
handler: mURL_post
|
|
2229
|
+
},
|
|
2230
|
+
{
|
|
2231
|
+
name: "mURL_presence",
|
|
2232
|
+
requires: "network",
|
|
2233
|
+
description: "Who is on a domain's mURL channel right now: live participant count + roster nicknames + channel status (open/claimed/blocked). Public (no key needed). Use it to gauge whether a domain has an active audience before posting.",
|
|
2234
|
+
inputSchema: mURL_presence_input,
|
|
2235
|
+
handler: mURL_presence
|
|
2236
|
+
},
|
|
2237
|
+
{
|
|
2238
|
+
name: "mURL_list_channels",
|
|
2239
|
+
requires: "network",
|
|
2240
|
+
description: "Discovery for mURL domain channels: 'trending' (most active in the last N hours, default 24) / 'list' (paginated catalogue, status-filtered) / 'mine' (channels you DNS-verified). Returns domain, slug, status, branding, verified_at + (for trending) messages_in_window. For who's-on-now, follow up with mURL_presence on the slug.",
|
|
2241
|
+
inputSchema: mURL_list_channels_input,
|
|
2242
|
+
handler: mURL_list_channels
|
|
2243
|
+
},
|
|
2244
|
+
{
|
|
2245
|
+
name: "mURL_create",
|
|
2246
|
+
requires: "network",
|
|
2247
|
+
description: "Create / claim the mURL channel for a web DOMAIN and register YOU as its owner (idempotent \u2014 returns the existing channel if you already own it; fails with 'claimed_by_other' if another account owns it). Optionally set initial branding + status. Owner-side: needs your mosADD login session (user JWT via `mosadd login`), not just a hub key \u2014 same as mURL_list_channels action='mine'. Backend: murl-manage EF.",
|
|
2248
|
+
inputSchema: mURL_create_input,
|
|
2249
|
+
handler: mURL_create
|
|
2250
|
+
},
|
|
2251
|
+
{
|
|
2252
|
+
name: "mURL_update",
|
|
2253
|
+
requires: "network",
|
|
2254
|
+
description: "Update a mURL DOMAIN channel you own: set branding, mark it 'claimed', 'blocked' (close the room), or reopen it as 'open'. Owner-scoped \u2014 you must own the channel (claim it first with mURL_create). Needs your mosADD login session. Backend: murl-manage EF.",
|
|
2255
|
+
inputSchema: mURL_update_input,
|
|
2256
|
+
handler: mURL_update
|
|
2257
|
+
},
|
|
2258
|
+
{
|
|
2259
|
+
name: "mURL_delete",
|
|
2260
|
+
requires: "network",
|
|
2261
|
+
description: "Delete a mURL DOMAIN channel you own (removes its domain_controls row; the room stops being served). Owner-scoped \u2014 you must own it. Needs your mosADD login session. Backend: murl-manage EF.",
|
|
2262
|
+
inputSchema: mURL_delete_input,
|
|
2263
|
+
handler: mURL_delete
|
|
2264
|
+
}
|
|
2265
|
+
];
|
|
2266
|
+
|
|
2267
|
+
// src/tools/capabilities.ts
|
|
2268
|
+
import { z as z15 } from "zod";
|
|
2269
|
+
var CONTRACT_VERSION = "1.0.0";
|
|
2270
|
+
var ALL_REQUIREMENTS = ["any", "radio", "network"];
|
|
2271
|
+
function buildCapabilityManifest(tools) {
|
|
2272
|
+
const entries = tools.map((t) => ({ name: t.name, requires: t.requires }));
|
|
2273
|
+
const by_requirement = {
|
|
2274
|
+
any: [],
|
|
2275
|
+
radio: [],
|
|
2276
|
+
network: []
|
|
2277
|
+
};
|
|
2278
|
+
for (const e of entries) by_requirement[e.requires].push(e.name);
|
|
2279
|
+
return {
|
|
2280
|
+
contract_version: CONTRACT_VERSION,
|
|
2281
|
+
requirements: ALL_REQUIREMENTS,
|
|
2282
|
+
tools: entries,
|
|
2283
|
+
by_requirement
|
|
2284
|
+
};
|
|
2285
|
+
}
|
|
2286
|
+
function makeCapabilitiesTool(channelTools2) {
|
|
2287
|
+
const tool = {
|
|
2288
|
+
name: "comms_capabilities",
|
|
2289
|
+
requires: "any",
|
|
2290
|
+
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.",
|
|
2291
|
+
inputSchema: z15.object({}),
|
|
2292
|
+
handler: async () => buildCapabilityManifest([...channelTools2, tool])
|
|
2293
|
+
};
|
|
2294
|
+
return tool;
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
// src/tools/index.ts
|
|
2298
|
+
var channelTools = [
|
|
2299
|
+
...mdmTools,
|
|
2300
|
+
...mdmVoiceTools,
|
|
2301
|
+
...mircTools,
|
|
2302
|
+
...mircMembersTools,
|
|
2303
|
+
...mircMessagesTools,
|
|
2304
|
+
...mircEdgeTools,
|
|
2305
|
+
// ...mroomTools, // mROOM: killed (LINEAR-3414) — channel re-cut into ephemeral private mIRC
|
|
2306
|
+
// ...mroomMessagesTools, // mROOM: killed (LINEAR-3414)
|
|
2307
|
+
...mailTools,
|
|
2308
|
+
// mAYL_*: canonical email module (was the mp0st codename; renamed re-arch 2026-06-27)
|
|
2309
|
+
// ...mailAliasTools, // mp0st_* aliases RETIRED 2026-07-15 — mAYL is the one name; the mp0st codename is now backend-internal only
|
|
2310
|
+
// ...mailProvenanceTools, // mAYL_send_as_agent: UNREGISTERED 2026-07-14 — hub-claim EF 404s every call; re-register when rewired onto hub-key-exchange (CTO-1 live-ping)
|
|
2311
|
+
...mtalkTools,
|
|
2312
|
+
...attachmentTools,
|
|
2313
|
+
// ...pttIngestTools, // mTALK_ingest_ptt: UNREGISTERED 2026-07-14 — ptt-ingest EF 400s every call; re-register when payload + PTT→RAG path fixed (CTO-1 live-ping)
|
|
2314
|
+
...knowledgeTools,
|
|
2315
|
+
...actionTools,
|
|
2316
|
+
// Action links (Tier 1): agent → user one-link browser action via action-create EF
|
|
2317
|
+
...embedTools,
|
|
2318
|
+
// comms_embed_create: RE-REGISTERED 2026-07-17 — embed.mosadd.com/v1.js live; mints an embed key + paste-in snippet (mURL→mIRC rework P3)
|
|
2319
|
+
...threatTools,
|
|
2320
|
+
// threat_catalog + threat_classify: RE-REGISTERED 2026-07-15 (founder directive + LINEAR-3498) — pure/offline, makes the Pegasus-class classification claim a live, callable capability
|
|
2321
|
+
...murlTools
|
|
2322
|
+
// mURL: revived as a full module (founder 2026-06-27) — read/post/presence/list_channels over live domain channels
|
|
2323
|
+
// ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
|
|
2324
|
+
// mirlTools,
|
|
2325
|
+
// mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
|
|
2326
|
+
//
|
|
2327
|
+
// Each m* module registers its tools here as it ships.
|
|
2328
|
+
// RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
|
|
2329
|
+
];
|
|
2330
|
+
var allTools = [
|
|
2331
|
+
...channelTools,
|
|
2332
|
+
// comms_capabilities: one-call discovery of every tool's `requires` flag,
|
|
2333
|
+
// so carrier-aware hosts (cymru-os) can gate the tool list by transport.
|
|
2334
|
+
makeCapabilitiesTool(channelTools)
|
|
2335
|
+
];
|
|
2336
|
+
var TOOL_COUNT = allTools.length;
|
|
2337
|
+
|
|
2338
|
+
// src/server.ts
|
|
2339
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2340
|
+
|
|
2341
|
+
// src/providers/supabase-dm.ts
|
|
2342
|
+
var PROTOCOL_VERSION5 = "mosadd.chat.v1";
|
|
2343
|
+
var SupabaseDmProvider = class {
|
|
2344
|
+
cachedSelfId = null;
|
|
2345
|
+
async selfId() {
|
|
2346
|
+
if (this.cachedSelfId) return this.cachedSelfId;
|
|
2347
|
+
readSupabaseEnv();
|
|
2348
|
+
const sb = getSupabase();
|
|
2349
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
2350
|
+
if (ue || !u?.user) {
|
|
2351
|
+
throw new Error(
|
|
2352
|
+
"Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
|
|
2353
|
+
);
|
|
2354
|
+
}
|
|
2355
|
+
const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
|
|
2356
|
+
if (error || !identity) {
|
|
2357
|
+
throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
|
|
2358
|
+
}
|
|
2359
|
+
this.cachedSelfId = identity.id;
|
|
2360
|
+
return this.cachedSelfId;
|
|
2361
|
+
}
|
|
2362
|
+
async send(args) {
|
|
2363
|
+
const encrypted_payload = Buffer.from(args.payload).toString("base64");
|
|
2364
|
+
const data = await invokeFunction("message-send", {
|
|
2365
|
+
space_id: "dm",
|
|
2366
|
+
thread_id: args.threadId,
|
|
2367
|
+
encrypted_payload,
|
|
2368
|
+
message_type: "text",
|
|
2369
|
+
protocol_version: PROTOCOL_VERSION5,
|
|
2370
|
+
recipient_account_id: args.to,
|
|
2371
|
+
reply_to_id: args.replyToId ?? null
|
|
2372
|
+
});
|
|
2373
|
+
if (!data?.message?.id) {
|
|
2374
|
+
throw new Error("message-send returned no message id");
|
|
2375
|
+
}
|
|
2376
|
+
return {
|
|
2377
|
+
id: data.message.id,
|
|
2378
|
+
deliveredAt: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
async publishPrekeyBundle(bundle) {
|
|
2382
|
+
await invokeFunction("prekey-bundle-publish", {
|
|
2383
|
+
bundle: Buffer.from(bundle).toString("base64")
|
|
2384
|
+
});
|
|
2385
|
+
}
|
|
2386
|
+
async fetchPrekeyBundle(peerId) {
|
|
2387
|
+
const data = await invokeFunction("prekey-bundle-fetch", {
|
|
2388
|
+
peer_id: peerId
|
|
2389
|
+
});
|
|
2390
|
+
if (!data?.bundle) return null;
|
|
2391
|
+
return new Uint8Array(Buffer.from(data.bundle, "base64"));
|
|
2392
|
+
}
|
|
2393
|
+
async list(args) {
|
|
2394
|
+
const data = await invokeFunction("message-list", {
|
|
2395
|
+
space_id: "dm",
|
|
2396
|
+
thread_id: args.threadId,
|
|
2397
|
+
limit: args.limit ?? 50,
|
|
2398
|
+
before: args.cursor
|
|
2399
|
+
});
|
|
2400
|
+
return {
|
|
2401
|
+
messages: (data?.messages ?? []).map((m) => ({
|
|
2402
|
+
id: m.id,
|
|
2403
|
+
senderId: m.sender_identity_id,
|
|
2404
|
+
payload: new Uint8Array(Buffer.from(m.encrypted_payload, "base64")),
|
|
2405
|
+
timestamp: m.created_at,
|
|
2406
|
+
threadId: m.thread_id
|
|
2407
|
+
})),
|
|
2408
|
+
// history mode (`before`) returns `next_before`; incremental (`since`) returns `cursor`+`has_more`.
|
|
2409
|
+
nextCursor: data?.next_before ?? (data?.has_more ? data?.cursor ?? null : null)
|
|
2410
|
+
};
|
|
2411
|
+
}
|
|
2412
|
+
};
|
|
2413
|
+
|
|
2414
|
+
// src/providers/supabase-voice.ts
|
|
2415
|
+
var ROOM_PREFIX = "mosadd-room-";
|
|
2416
|
+
var SupabaseVoiceProvider = class {
|
|
2417
|
+
cachedSelfId = null;
|
|
2418
|
+
async selfId() {
|
|
2419
|
+
if (this.cachedSelfId) return this.cachedSelfId;
|
|
2420
|
+
readSupabaseEnv();
|
|
2421
|
+
const sb = getSupabase();
|
|
2422
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
2423
|
+
if (ue || !u?.user) {
|
|
2424
|
+
throw new Error(
|
|
2425
|
+
"Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
|
|
2426
|
+
);
|
|
2427
|
+
}
|
|
2428
|
+
const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
|
|
2429
|
+
if (error || !identity) {
|
|
2430
|
+
throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
|
|
2431
|
+
}
|
|
2432
|
+
this.cachedSelfId = identity.id;
|
|
2433
|
+
return this.cachedSelfId;
|
|
2434
|
+
}
|
|
2435
|
+
async createRoom(label) {
|
|
2436
|
+
const self = await this.selfId();
|
|
2437
|
+
const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
|
|
2438
|
+
return { roomId };
|
|
2439
|
+
}
|
|
2440
|
+
async joinTicket(roomId) {
|
|
2441
|
+
const self = await this.selfId();
|
|
2442
|
+
const data = await invokeFunction("livekit-token", {
|
|
2443
|
+
roomName: roomId,
|
|
2444
|
+
identity: self
|
|
2445
|
+
});
|
|
2446
|
+
return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
|
|
2447
|
+
}
|
|
2448
|
+
async requestFloor(roomId) {
|
|
2449
|
+
return invokeFunction("mtalk-floor", { action: "request", room_id: roomId });
|
|
2450
|
+
}
|
|
2451
|
+
async releaseFloor(roomId) {
|
|
2452
|
+
const data = await invokeFunction("mtalk-floor", {
|
|
2453
|
+
action: "release",
|
|
2454
|
+
room_id: roomId
|
|
2455
|
+
});
|
|
2456
|
+
return data.snapshot;
|
|
2457
|
+
}
|
|
2458
|
+
async floorState(roomId) {
|
|
2459
|
+
const data = await invokeFunction("mtalk-floor", {
|
|
2460
|
+
action: "state",
|
|
2461
|
+
room_id: roomId
|
|
2462
|
+
});
|
|
2463
|
+
return data.snapshot;
|
|
2464
|
+
}
|
|
2465
|
+
};
|
|
2466
|
+
function slug(s) {
|
|
2467
|
+
return s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 200);
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
// src/server.ts
|
|
2471
|
+
function defaultProviders(injected) {
|
|
2472
|
+
return {
|
|
2473
|
+
dm: injected?.dm ?? new SupabaseDmProvider(),
|
|
2474
|
+
keys: injected?.keys ?? new InMemoryMdmKeyStore(),
|
|
2475
|
+
voice: injected?.voice ?? new SupabaseVoiceProvider()
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
function createMosaddServer(options = {}) {
|
|
2479
|
+
const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
|
|
2480
|
+
const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
|
|
2481
|
+
const logLevel = options.logLevel ?? "info";
|
|
2482
|
+
const providers = defaultProviders(options.providers);
|
|
2483
|
+
const ctx = {
|
|
2484
|
+
options: { ...options, mode, hubUrl },
|
|
2485
|
+
providers,
|
|
2486
|
+
log: (level, msg, extra) => {
|
|
2487
|
+
if (shouldLog(level, logLevel)) {
|
|
2488
|
+
process.stderr.write(
|
|
2489
|
+
JSON.stringify({ level, msg, extra, ts: (/* @__PURE__ */ new Date()).toISOString() }) + "\n"
|
|
2490
|
+
);
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
};
|
|
2494
|
+
if (options.autoPublishKeys) {
|
|
2495
|
+
void publishOwnPrekeys(providers.keys, providers.dm).then((r) => ctx.log("debug", "auto-published mDM prekeys", { one_time_prekeys: r.oneTimePrekeyCount })).catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
|
|
2496
|
+
}
|
|
2497
|
+
const server = new McpServer(
|
|
2498
|
+
{
|
|
2499
|
+
name: "mosadd",
|
|
2500
|
+
version: "3.0.0-alpha.31"
|
|
2501
|
+
},
|
|
2502
|
+
{
|
|
2503
|
+
capabilities: {
|
|
2504
|
+
tools: {}
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
);
|
|
2508
|
+
for (const tool of allTools) {
|
|
2509
|
+
const shape = tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema ? tool.inputSchema.shape : tool.inputSchema;
|
|
2510
|
+
server.tool(
|
|
2511
|
+
tool.name,
|
|
2512
|
+
tool.description,
|
|
2513
|
+
shape,
|
|
2514
|
+
async (input) => {
|
|
2515
|
+
const parsed = tool.inputSchema.parse(input);
|
|
2516
|
+
try {
|
|
2517
|
+
const result = await tool.handler(parsed, ctx);
|
|
2518
|
+
const rich = result;
|
|
2519
|
+
if (rich && Array.isArray(rich.mcpContent)) {
|
|
2520
|
+
return { content: rich.mcpContent };
|
|
2521
|
+
}
|
|
2522
|
+
return {
|
|
2523
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
2524
|
+
};
|
|
2525
|
+
} catch (err) {
|
|
2526
|
+
ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
|
|
2527
|
+
return {
|
|
2528
|
+
isError: true,
|
|
2529
|
+
content: [
|
|
2530
|
+
{
|
|
2531
|
+
type: "text",
|
|
2532
|
+
text: JSON.stringify({
|
|
2533
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2534
|
+
tool: tool.name
|
|
2535
|
+
})
|
|
2536
|
+
}
|
|
2537
|
+
]
|
|
2538
|
+
};
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
);
|
|
2542
|
+
}
|
|
2543
|
+
return server;
|
|
2544
|
+
}
|
|
2545
|
+
function shouldLog(level, threshold) {
|
|
2546
|
+
const order = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
2547
|
+
return (order[level] ?? 1) >= (order[threshold] ?? 1);
|
|
2548
|
+
}
|
|
2549
|
+
|
|
2550
|
+
export {
|
|
2551
|
+
runWithSupabaseEnv,
|
|
2552
|
+
allTools,
|
|
2553
|
+
TOOL_COUNT,
|
|
2554
|
+
defaultProviders,
|
|
2555
|
+
createMosaddServer
|
|
2556
|
+
};
|