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