@mosadd/mcp 3.0.0-alpha.6 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +410 -0
- package/README.md +79 -40
- package/dist/bin/mcp.js +132 -8
- package/dist/chunk-VMMJJYXF.js +4233 -0
- package/dist/index.d.ts +110 -6
- package/dist/index.js +3 -1
- package/package.json +19 -16
- package/src/__tests__/blob-upload.test.ts +93 -0
- package/src/__tests__/channel-e2ee.test.ts +62 -0
- package/src/__tests__/cli.test.ts +47 -0
- package/src/__tests__/flota-jawnie.test.ts +244 -0
- package/src/__tests__/golden-path.test.ts +4 -2
- package/src/__tests__/integration.test.ts +50 -11
- package/src/__tests__/knowledge-ingest.test.ts +114 -0
- package/src/__tests__/label-room-owner.test.ts +22 -0
- package/src/__tests__/mdm-e2ee.test.ts +35 -1
- package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
- package/src/__tests__/mirc-invite.test.ts +112 -0
- package/src/__tests__/mrag-search-answer.test.ts +42 -0
- package/src/__tests__/no-dead-host.test.ts +37 -0
- package/src/__tests__/presence.test.ts +199 -0
- package/src/__tests__/server.test.ts +11 -7
- package/src/__tests__/serverJsonVersion.test.ts +45 -0
- package/src/__tests__/tool-count-consistency.test.ts +259 -0
- package/src/__tests__/voice-fields.test.ts +24 -0
- package/src/bin/mcp.ts +71 -6
- package/src/cli.ts +100 -0
- package/src/crypto/channel-e2ee.ts +288 -0
- package/src/crypto/mdm-session.ts +476 -37
- package/src/index.ts +2 -2
- package/src/providers/blob-upload.ts +162 -0
- package/src/providers/supabase-dm.ts +102 -7
- package/src/providers/supabase-voice.ts +13 -1
- package/src/providers/supabase.ts +121 -10
- package/src/server.ts +102 -12
- package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
- package/src/tools/actions.ts +166 -0
- package/src/tools/attachments.ts +276 -0
- package/src/tools/capabilities.ts +2 -0
- package/src/tools/channel-payload.ts +69 -0
- package/src/tools/embed.ts +110 -0
- package/src/tools/index.ts +136 -6
- package/src/tools/knowledge-graph.ts +186 -0
- package/src/tools/knowledge.ts +351 -132
- package/src/tools/mail-agentbox.ts +155 -0
- package/src/tools/mail-aliases.ts +25 -0
- package/src/tools/mail-provenance.ts +137 -0
- package/src/tools/mail.ts +284 -38
- package/src/tools/mdm-as-agent.ts +138 -0
- package/src/tools/mdm-voice.ts +17 -3
- package/src/tools/mdm.ts +303 -57
- package/src/tools/mirc-edge.ts +8 -2
- package/src/tools/mirc-members.ts +130 -20
- package/src/tools/mirc-messages.ts +80 -35
- package/src/tools/mirc.ts +149 -11
- package/src/tools/mroom-messages.ts +4 -12
- package/src/tools/mtalk.ts +11 -1
- package/src/tools/murl.ts +314 -0
- package/src/tools/presence.ts +442 -0
- package/src/tools/ptt-ingest.ts +99 -0
- package/src/tools/threat.ts +123 -0
- package/src/tools/voice-format.ts +43 -0
- package/src/types.ts +36 -0
- package/src/version.ts +8 -0
- package/LICENSE +0 -201
- package/dist/chunk-KAPG5FBN.js +0 -1844
|
@@ -0,0 +1,4233 @@
|
|
|
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 { randomUUID } from "crypto";
|
|
9
|
+
import { hostname } from "os";
|
|
10
|
+
import { createClient } from "@supabase/supabase-js";
|
|
11
|
+
var cachedSessionId = null;
|
|
12
|
+
function sessionId() {
|
|
13
|
+
const perRequest = requestEnv.getStore();
|
|
14
|
+
if (perRequest) return perRequest.sessionKey ?? "";
|
|
15
|
+
if (cachedSessionId) return cachedSessionId;
|
|
16
|
+
let host = "mcp";
|
|
17
|
+
try {
|
|
18
|
+
host = (hostname() || "mcp").slice(0, 24);
|
|
19
|
+
} catch {
|
|
20
|
+
}
|
|
21
|
+
cachedSessionId = `${host}:${randomUUID()}`;
|
|
22
|
+
return cachedSessionId;
|
|
23
|
+
}
|
|
24
|
+
var requestEnv = new AsyncLocalStorage();
|
|
25
|
+
function runWithSupabaseEnv(env, fn) {
|
|
26
|
+
return requestEnv.run(env, fn);
|
|
27
|
+
}
|
|
28
|
+
var MissingSupabaseEnvError = class extends Error {
|
|
29
|
+
constructor(missing) {
|
|
30
|
+
super(
|
|
31
|
+
`Missing Supabase credentials: ${missing.join(", ")}. Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`
|
|
32
|
+
);
|
|
33
|
+
this.name = "MissingSupabaseEnvError";
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
function readSupabaseEnv() {
|
|
37
|
+
const perRequest = requestEnv.getStore();
|
|
38
|
+
if (perRequest) return perRequest;
|
|
39
|
+
const env = (canonical, legacy) => process.env[canonical] ?? process.env[legacy];
|
|
40
|
+
const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
|
|
41
|
+
const session = loadSession();
|
|
42
|
+
const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
|
|
43
|
+
const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
|
|
44
|
+
const userJwt = userJwtEnv ?? session?.accessToken;
|
|
45
|
+
const missing = [];
|
|
46
|
+
if (!url) missing.push("MOSADD_SUPABASE_URL");
|
|
47
|
+
if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
|
|
48
|
+
if (missing.length) throw new MissingSupabaseEnvError(missing);
|
|
49
|
+
if (!userJwtEnv && session && isSessionExpired(session)) {
|
|
50
|
+
throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
|
|
51
|
+
}
|
|
52
|
+
return { url, anonKey, userJwt };
|
|
53
|
+
}
|
|
54
|
+
function getSupabase(env = readSupabaseEnv()) {
|
|
55
|
+
return createClient(env.url, env.anonKey, {
|
|
56
|
+
auth: {
|
|
57
|
+
persistSession: false,
|
|
58
|
+
autoRefreshToken: false,
|
|
59
|
+
detectSessionInUrl: false
|
|
60
|
+
},
|
|
61
|
+
// ⛔ x-mosadd-origin: KAŻDE wywołanie z toolkitu/bramy MCP niesie ten znacznik (2026-08-25,
|
|
62
|
+
// rozkaz Króla „kradną tożsamości"). Sesje agentów wpinały klucz WŁAŚCICIELA i postowały na
|
|
63
|
+
// kanałach z jego dymka (SOVEREIGN) — serwer nie miał JAK odróżnić bramy od aplikacji, bo
|
|
64
|
+
// hub-key-exchange zwraca zwykły JWT usera. Ten nagłówek to rozróżnia: message-send odrzuca
|
|
65
|
+
// post na kanał z tożsamości CZŁOWIEKA, gdy przyszedł przez bramę — z komunikatem każącym
|
|
66
|
+
// wpiąć klucz SWOJEJ linii. Aplikacja mosadd.com nigdy nie wysyła tego nagłówka.
|
|
67
|
+
global: {
|
|
68
|
+
headers: {
|
|
69
|
+
...env.userJwt ? { Authorization: `Bearer ${env.userJwt}` } : {},
|
|
70
|
+
"x-mosadd-origin": "hub-gateway",
|
|
71
|
+
// Nagłówek tylko, gdy sesja MA tożsamość — puste "" (brama bez sessionKey) nie wysyła nic,
|
|
72
|
+
// więc serwerowy strażnik 409 nie widzi fałszywych roszczeń.
|
|
73
|
+
...sessionId() ? { "x-mosadd-session": sessionId() } : {}
|
|
74
|
+
// ⛔ KTÓRA TO SESJA (2026-08-27, „każdy generał co chwilę gubi mózg"). Wszyscy generałowie
|
|
75
|
+
// wpinają się kluczem hub TEGO SAMEGO właściciela, więc dla serwera ich wywołania były
|
|
76
|
+
// nieodróżnialne — a deklaracja linii (`comms_session_attach as_agent`) trzymała JEDEN
|
|
77
|
+
// wiersz na konto. Skutek: kto wpiął się ostatni, odbierał linię wszystkim pozostałym, a
|
|
78
|
+
// ich posty na kanałach zaczynały wracać z 403. Tożsamość sesji (stdio: per proces,
|
|
79
|
+
// brama: per klucz API) pozwala dziewięciu liniom na jednym koncie nie deptać sobie po piętach.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
async function invokeFunction(fn, body) {
|
|
85
|
+
const client = getSupabase();
|
|
86
|
+
const { data, error } = await client.functions.invoke(fn, { body });
|
|
87
|
+
if (error) {
|
|
88
|
+
let msg = error instanceof Error && error.message ? error.message : `Edge function ${fn} failed`;
|
|
89
|
+
const ctx = error.context;
|
|
90
|
+
if (ctx && typeof ctx.text === "function") {
|
|
91
|
+
const res = ctx;
|
|
92
|
+
try {
|
|
93
|
+
const raw = await res.text();
|
|
94
|
+
if (raw) {
|
|
95
|
+
let detail = raw;
|
|
96
|
+
let recipe = "";
|
|
97
|
+
try {
|
|
98
|
+
const parsed = JSON.parse(raw);
|
|
99
|
+
detail = typeof parsed.error === "string" && parsed.error || typeof parsed.message === "string" && parsed.message || raw;
|
|
100
|
+
const steps = Array.isArray(parsed.next_steps) ? parsed.next_steps : [];
|
|
101
|
+
const lines = [];
|
|
102
|
+
if (typeof parsed.code === "string" && parsed.code) lines.push(`code: ${parsed.code}`);
|
|
103
|
+
if (typeof parsed.message_en === "string" && parsed.message_en && parsed.message_en !== detail) {
|
|
104
|
+
lines.push(parsed.message_en);
|
|
105
|
+
}
|
|
106
|
+
for (const raw_step of steps) {
|
|
107
|
+
const step = raw_step;
|
|
108
|
+
const who = typeof step.actor === "string" ? step.actor : "?";
|
|
109
|
+
const what = typeof step.tool === "string" && step.tool || typeof step.ui === "string" && step.ui || "";
|
|
110
|
+
if (!what) continue;
|
|
111
|
+
const why = typeof step.why === "string" ? ` \u2014 ${step.why}` : "";
|
|
112
|
+
const args = step.args && typeof step.args === "object" ? ` ${JSON.stringify(step.args)}` : "";
|
|
113
|
+
lines.push(`next (${who}): ${what}${args}${why}`);
|
|
114
|
+
}
|
|
115
|
+
if (lines.length) recipe = "\n" + lines.join("\n");
|
|
116
|
+
} catch {
|
|
117
|
+
}
|
|
118
|
+
const status = typeof res.status === "number" ? res.status : void 0;
|
|
119
|
+
msg = (status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`) + recipe;
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
throw new Error(msg);
|
|
125
|
+
}
|
|
126
|
+
if (data == null) {
|
|
127
|
+
throw new Error(`Edge function ${fn} returned no data`);
|
|
128
|
+
}
|
|
129
|
+
return data;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/tools/mdm.ts
|
|
133
|
+
import { z } from "zod";
|
|
134
|
+
|
|
135
|
+
// src/tools/voice-format.ts
|
|
136
|
+
function formatVoiceIfAny(text) {
|
|
137
|
+
try {
|
|
138
|
+
const obj = JSON.parse(text);
|
|
139
|
+
if (obj && typeof obj === "object" && typeof obj.audio === "string" && obj.audio.length > 1e3 && typeof obj.dur === "number") {
|
|
140
|
+
const s = Math.max(1, Math.round(obj.dur / 1e3));
|
|
141
|
+
return `[voice note \u2014 ${s}s]`;
|
|
142
|
+
}
|
|
143
|
+
} catch {
|
|
144
|
+
}
|
|
145
|
+
return text;
|
|
146
|
+
}
|
|
147
|
+
function voiceFields(m) {
|
|
148
|
+
if (m.messageType !== "voice" && m.messageType !== "ptt") return {};
|
|
149
|
+
return { voice: { transcript: m.transcript ?? null, audio_url: m.audioUrl ?? null, duration_ms: m.durationMs ?? null } };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/crypto/mdm-session.ts
|
|
153
|
+
import {
|
|
154
|
+
decryptBytes,
|
|
155
|
+
deriveHkdfKey,
|
|
156
|
+
deriveSharedSecret,
|
|
157
|
+
encryptBytes,
|
|
158
|
+
generateEd25519KeyPair,
|
|
159
|
+
generateX25519KeyPair,
|
|
160
|
+
initializeRatchet,
|
|
161
|
+
performX3dh,
|
|
162
|
+
performX3dhResponder,
|
|
163
|
+
ratchetReceive,
|
|
164
|
+
ratchetSend,
|
|
165
|
+
signEd25519,
|
|
166
|
+
verifyEd25519,
|
|
167
|
+
toBase64,
|
|
168
|
+
fromBase64,
|
|
169
|
+
initRatchetInitiator,
|
|
170
|
+
initRatchetResponder,
|
|
171
|
+
ratchetEncrypt,
|
|
172
|
+
ratchetDecrypt
|
|
173
|
+
} from "@mosadd/crypto";
|
|
174
|
+
var PREKEY_BUNDLE_VERSION = "mosadd.prekeys.v1";
|
|
175
|
+
var E2EE_ENVELOPE_VERSION = "mosadd.e2ee.v1";
|
|
176
|
+
var E2EE_ENVELOPE_VERSION_V2 = "mosadd.e2ee.v2";
|
|
177
|
+
var DEFAULT_ONE_TIME_PREKEYS = 8;
|
|
178
|
+
var InMemoryMdmKeyStore = class {
|
|
179
|
+
material = null;
|
|
180
|
+
oneTimeById = /* @__PURE__ */ new Map();
|
|
181
|
+
sessions = /* @__PURE__ */ new Map();
|
|
182
|
+
sentMessages = /* @__PURE__ */ new Map();
|
|
183
|
+
async getOwnMaterial() {
|
|
184
|
+
if (this.material) return this.material;
|
|
185
|
+
const identity = await generateX25519KeyPair();
|
|
186
|
+
const signingIdentity = await generateEd25519KeyPair();
|
|
187
|
+
const signedPrekeyPair = await generateX25519KeyPair();
|
|
188
|
+
const signedPrekey = { id: randomId(), pair: signedPrekeyPair };
|
|
189
|
+
const oneTimePrekeys = [];
|
|
190
|
+
for (let i = 0; i < DEFAULT_ONE_TIME_PREKEYS; i += 1) {
|
|
191
|
+
const pair = await generateX25519KeyPair();
|
|
192
|
+
const id = randomId();
|
|
193
|
+
oneTimePrekeys.push({ id, pair });
|
|
194
|
+
this.oneTimeById.set(id, pair.privateKey);
|
|
195
|
+
}
|
|
196
|
+
this.material = { identity, signingIdentity, signedPrekey, oneTimePrekeys };
|
|
197
|
+
return this.material;
|
|
198
|
+
}
|
|
199
|
+
async takeOneTimePrekey(id) {
|
|
200
|
+
const priv = this.oneTimeById.get(id);
|
|
201
|
+
if (priv) this.oneTimeById.delete(id);
|
|
202
|
+
return priv;
|
|
203
|
+
}
|
|
204
|
+
async getSession(peerId) {
|
|
205
|
+
return this.sessions.get(peerId);
|
|
206
|
+
}
|
|
207
|
+
async putSession(peerId, record) {
|
|
208
|
+
this.sessions.set(peerId, record);
|
|
209
|
+
}
|
|
210
|
+
async putSentMessage(messageId, plaintext) {
|
|
211
|
+
this.sentMessages.set(messageId, plaintext);
|
|
212
|
+
}
|
|
213
|
+
async getSentMessage(messageId) {
|
|
214
|
+
return this.sentMessages.get(messageId);
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
function randomId() {
|
|
218
|
+
return crypto.getRandomValues(new Uint32Array(1))[0];
|
|
219
|
+
}
|
|
220
|
+
var X25519_BASE_POINT = (() => {
|
|
221
|
+
const b = new Uint8Array(32);
|
|
222
|
+
b[0] = 9;
|
|
223
|
+
return b;
|
|
224
|
+
})();
|
|
225
|
+
async function x25519PairFromSeed(seed) {
|
|
226
|
+
const privateKey = seed.length === 32 ? seed : seed.slice(0, 32);
|
|
227
|
+
const publicKey = await deriveSharedSecret(privateKey, X25519_BASE_POINT);
|
|
228
|
+
return { privateKey, publicKey };
|
|
229
|
+
}
|
|
230
|
+
var utf8 = new TextEncoder();
|
|
231
|
+
async function subSeed(seed, label) {
|
|
232
|
+
return deriveHkdfKey(seed, { info: utf8.encode(label), length: 32 });
|
|
233
|
+
}
|
|
234
|
+
async function deriveOwnMaterialFromSeed(seed) {
|
|
235
|
+
const [idSeed, signSeed, spkSeed] = await Promise.all([
|
|
236
|
+
subSeed(seed, "mosadd-mdm-identity-x25519"),
|
|
237
|
+
subSeed(seed, "mosadd-mdm-signing-ed25519"),
|
|
238
|
+
subSeed(seed, "mosadd-mdm-signed-prekey-x25519")
|
|
239
|
+
]);
|
|
240
|
+
return {
|
|
241
|
+
identity: await x25519PairFromSeed(idSeed),
|
|
242
|
+
signingIdentity: await generateEd25519KeyPair(signSeed),
|
|
243
|
+
signedPrekey: { id: 1, pair: await x25519PairFromSeed(spkSeed) },
|
|
244
|
+
oneTimePrekeys: []
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
async function deriveMdmSeedFromSecret(secret) {
|
|
248
|
+
return deriveHkdfKey(utf8.encode(secret), {
|
|
249
|
+
salt: utf8.encode("mosadd-mcp-api-key"),
|
|
250
|
+
info: utf8.encode("mosadd-mdm-identity-seed"),
|
|
251
|
+
length: 32
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
var SeededMdmKeyStore = class _SeededMdmKeyStore {
|
|
255
|
+
constructor(seed) {
|
|
256
|
+
this.seed = seed;
|
|
257
|
+
if (!seed || seed.length < 32) throw new Error("SeededMdmKeyStore needs a 32-byte seed");
|
|
258
|
+
}
|
|
259
|
+
seed;
|
|
260
|
+
material = null;
|
|
261
|
+
sessions = /* @__PURE__ */ new Map();
|
|
262
|
+
sentMessages = /* @__PURE__ */ new Map();
|
|
263
|
+
static async fromSecret(secret) {
|
|
264
|
+
return new _SeededMdmKeyStore(await deriveMdmSeedFromSecret(secret));
|
|
265
|
+
}
|
|
266
|
+
getOwnMaterial() {
|
|
267
|
+
if (!this.material) this.material = deriveOwnMaterialFromSeed(this.seed);
|
|
268
|
+
return this.material;
|
|
269
|
+
}
|
|
270
|
+
async takeOneTimePrekey(_id) {
|
|
271
|
+
return void 0;
|
|
272
|
+
}
|
|
273
|
+
async getSession(peerId) {
|
|
274
|
+
return this.sessions.get(peerId);
|
|
275
|
+
}
|
|
276
|
+
async putSession(peerId, record) {
|
|
277
|
+
this.sessions.set(peerId, record);
|
|
278
|
+
}
|
|
279
|
+
async putSentMessage(messageId, plaintext) {
|
|
280
|
+
this.sentMessages.set(messageId, plaintext);
|
|
281
|
+
}
|
|
282
|
+
async getSentMessage(messageId) {
|
|
283
|
+
return this.sentMessages.get(messageId);
|
|
284
|
+
}
|
|
285
|
+
/** Same label as the web's getSelfKeyBytes ("mosadd-mdm-self-read"). */
|
|
286
|
+
async getSelfKeyBytes() {
|
|
287
|
+
return deriveHkdfKey(this.seed, { info: utf8.encode("mosadd-mdm-self-read"), length: 32 });
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
var SecretMdmKeyStore = class {
|
|
291
|
+
constructor(secret) {
|
|
292
|
+
this.secret = secret;
|
|
293
|
+
}
|
|
294
|
+
secret;
|
|
295
|
+
inner = null;
|
|
296
|
+
store() {
|
|
297
|
+
if (!this.inner) this.inner = SeededMdmKeyStore.fromSecret(this.secret);
|
|
298
|
+
return this.inner;
|
|
299
|
+
}
|
|
300
|
+
async getOwnMaterial() {
|
|
301
|
+
return (await this.store()).getOwnMaterial();
|
|
302
|
+
}
|
|
303
|
+
async takeOneTimePrekey(id) {
|
|
304
|
+
return (await this.store()).takeOneTimePrekey(id);
|
|
305
|
+
}
|
|
306
|
+
async getSession(peerId) {
|
|
307
|
+
return (await this.store()).getSession(peerId);
|
|
308
|
+
}
|
|
309
|
+
async putSession(peerId, record) {
|
|
310
|
+
return (await this.store()).putSession(peerId, record);
|
|
311
|
+
}
|
|
312
|
+
async putSentMessage(messageId, plaintext) {
|
|
313
|
+
return (await this.store()).putSentMessage(messageId, plaintext);
|
|
314
|
+
}
|
|
315
|
+
async getSentMessage(messageId) {
|
|
316
|
+
return (await this.store()).getSentMessage(messageId);
|
|
317
|
+
}
|
|
318
|
+
async getSelfKeyBytes() {
|
|
319
|
+
return (await this.store()).getSelfKeyBytes();
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
var SELF_TAG = "s1.";
|
|
323
|
+
var PEER_RECOVERABLE_TAG = "r1.";
|
|
324
|
+
var PEER_RECOVERABLE_INFO = "mosadd.mdm.recipient-recoverable.v1";
|
|
325
|
+
async function aesGcmSeal(tag, keyBytes, plaintext) {
|
|
326
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt"]);
|
|
327
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
328
|
+
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext));
|
|
329
|
+
const packed = new Uint8Array(iv.length + ct.length);
|
|
330
|
+
packed.set(iv, 0);
|
|
331
|
+
packed.set(ct, iv.length);
|
|
332
|
+
return tag + toBase64(packed);
|
|
333
|
+
}
|
|
334
|
+
async function aesGcmOpen(tag, keyBytes, sealed) {
|
|
335
|
+
if (!sealed.startsWith(tag)) return null;
|
|
336
|
+
const packed = fromBase64(sealed.slice(tag.length));
|
|
337
|
+
if (packed.length <= 12) return null;
|
|
338
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["decrypt"]);
|
|
339
|
+
const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: packed.slice(0, 12) }, key, packed.slice(12));
|
|
340
|
+
return new Uint8Array(pt);
|
|
341
|
+
}
|
|
342
|
+
async function sealForSelf(keystore, plaintext) {
|
|
343
|
+
try {
|
|
344
|
+
const keyBytes = await keystore.getSelfKeyBytes?.() ?? null;
|
|
345
|
+
if (!keyBytes) return null;
|
|
346
|
+
return await aesGcmSeal(SELF_TAG, keyBytes, plaintext);
|
|
347
|
+
} catch {
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
async function openSelfSealed(keystore, sealed) {
|
|
352
|
+
try {
|
|
353
|
+
if (!sealed) return null;
|
|
354
|
+
const keyBytes = await keystore.getSelfKeyBytes?.() ?? null;
|
|
355
|
+
if (!keyBytes) return null;
|
|
356
|
+
return await aesGcmOpen(SELF_TAG, keyBytes, sealed);
|
|
357
|
+
} catch {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
async function pairKey(keystore, otherIdentityPublicKey) {
|
|
362
|
+
const own = await keystore.getOwnMaterial();
|
|
363
|
+
const secret = await deriveSharedSecret(own.identity.privateKey, otherIdentityPublicKey);
|
|
364
|
+
return deriveHkdfKey(secret, { info: utf8.encode(PEER_RECOVERABLE_INFO), length: 32 });
|
|
365
|
+
}
|
|
366
|
+
async function sealForPeerRecoverable(keystore, peer, plaintext) {
|
|
367
|
+
try {
|
|
368
|
+
return await aesGcmSeal(PEER_RECOVERABLE_TAG, await pairKey(keystore, peer.identityPublicKey), plaintext);
|
|
369
|
+
} catch {
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async function openPeerRecoverable(keystore, sender, sealed) {
|
|
374
|
+
try {
|
|
375
|
+
if (!sealed) return null;
|
|
376
|
+
return await aesGcmOpen(PEER_RECOVERABLE_TAG, await pairKey(keystore, sender.identityPublicKey), sealed);
|
|
377
|
+
} catch {
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
async function fetchVerifiedBundle(dm, peerId) {
|
|
382
|
+
const raw = await dm.fetchPrekeyBundle(peerId);
|
|
383
|
+
if (!raw) return null;
|
|
384
|
+
const parsed = parsePublicBundle(raw);
|
|
385
|
+
return verifyPublicBundle(parsed) ? parsed : null;
|
|
386
|
+
}
|
|
387
|
+
function sameBytes(a, b) {
|
|
388
|
+
if (a.length !== b.length) return false;
|
|
389
|
+
for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
function bundlePolicyForKind(kind, opts) {
|
|
393
|
+
if (kind === "agent") {
|
|
394
|
+
return opts.explicit ? { mayPublishWhenEmpty: true, mayReplaceForeign: true } : { mayPublishWhenEmpty: false, mayReplaceForeign: false };
|
|
395
|
+
}
|
|
396
|
+
if (kind === "human") {
|
|
397
|
+
return { mayPublishWhenEmpty: opts.explicit, mayReplaceForeign: false };
|
|
398
|
+
}
|
|
399
|
+
return { mayPublishWhenEmpty: true, mayReplaceForeign: opts.explicit };
|
|
400
|
+
}
|
|
401
|
+
async function ensureOwnBundlePublished(keystore, dm, selfId, policy) {
|
|
402
|
+
const own = await keystore.getOwnMaterial();
|
|
403
|
+
const raw = await dm.fetchPrekeyBundle(selfId);
|
|
404
|
+
if (raw) {
|
|
405
|
+
let published = null;
|
|
406
|
+
try {
|
|
407
|
+
published = parsePublicBundle(raw);
|
|
408
|
+
} catch {
|
|
409
|
+
published = null;
|
|
410
|
+
}
|
|
411
|
+
if (published && sameBytes(published.identityPublicKey, own.identity.publicKey) && sameBytes(published.signingIdentityPublicKey, own.signingIdentity.publicKey) && sameBytes(published.signedPrekey.publicKey, own.signedPrekey.pair.publicKey)) {
|
|
412
|
+
return "consistent";
|
|
413
|
+
}
|
|
414
|
+
if (!policy.mayReplaceForeign) return "foreign";
|
|
415
|
+
} else if (!policy.mayPublishWhenEmpty) {
|
|
416
|
+
return "absent";
|
|
417
|
+
}
|
|
418
|
+
await dm.publishPrekeyBundle(serializePublicBundle(own));
|
|
419
|
+
return "published";
|
|
420
|
+
}
|
|
421
|
+
function bundleSigningMessage(dhIdentityPub, signedPrekeyPub) {
|
|
422
|
+
const msg = new Uint8Array(dhIdentityPub.length + signedPrekeyPub.length);
|
|
423
|
+
msg.set(dhIdentityPub, 0);
|
|
424
|
+
msg.set(signedPrekeyPub, dhIdentityPub.length);
|
|
425
|
+
return msg;
|
|
426
|
+
}
|
|
427
|
+
function serializePublicBundle(material) {
|
|
428
|
+
const signature = signEd25519(
|
|
429
|
+
material.signingIdentity.privateKey,
|
|
430
|
+
bundleSigningMessage(material.identity.publicKey, material.signedPrekey.pair.publicKey)
|
|
431
|
+
);
|
|
432
|
+
const json = JSON.stringify({
|
|
433
|
+
v: PREKEY_BUNDLE_VERSION,
|
|
434
|
+
ik: toBase64(material.identity.publicKey),
|
|
435
|
+
sik: toBase64(material.signingIdentity.publicKey),
|
|
436
|
+
spk: { id: material.signedPrekey.id, pub: toBase64(material.signedPrekey.pair.publicKey) },
|
|
437
|
+
opks: material.oneTimePrekeys.map((k) => ({ id: k.id, pub: toBase64(k.pair.publicKey) })),
|
|
438
|
+
sig: toBase64(signature)
|
|
439
|
+
});
|
|
440
|
+
return new Uint8Array(Buffer.from(json, "utf8"));
|
|
441
|
+
}
|
|
442
|
+
function parsePublicBundle(bytes) {
|
|
443
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
444
|
+
if (obj?.v !== PREKEY_BUNDLE_VERSION) {
|
|
445
|
+
throw new Error(`Unsupported prekey bundle version: ${obj?.v}`);
|
|
446
|
+
}
|
|
447
|
+
if (typeof obj.sik !== "string" || typeof obj.sig !== "string") {
|
|
448
|
+
throw new Error("Prekey bundle is missing its signing identity / signature.");
|
|
449
|
+
}
|
|
450
|
+
return {
|
|
451
|
+
identityPublicKey: fromBase64(obj.ik),
|
|
452
|
+
signingIdentityPublicKey: fromBase64(obj.sik),
|
|
453
|
+
signedPrekey: { id: obj.spk.id, publicKey: fromBase64(obj.spk.pub) },
|
|
454
|
+
oneTimePrekeys: (obj.opks ?? []).map((k) => ({
|
|
455
|
+
id: k.id,
|
|
456
|
+
publicKey: fromBase64(k.pub)
|
|
457
|
+
})),
|
|
458
|
+
signature: fromBase64(obj.sig)
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
function verifyPublicBundle(bundle) {
|
|
462
|
+
return verifyEd25519(
|
|
463
|
+
bundle.signature,
|
|
464
|
+
bundleSigningMessage(bundle.identityPublicKey, bundle.signedPrekey.publicKey),
|
|
465
|
+
bundle.signingIdentityPublicKey
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
function isE2eeEnvelope(bytes) {
|
|
469
|
+
try {
|
|
470
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
471
|
+
if (!obj?.ct) return false;
|
|
472
|
+
if (obj.v === E2EE_ENVELOPE_VERSION) return typeof obj.i === "number";
|
|
473
|
+
if (obj.v === E2EE_ENVELOPE_VERSION_V2) return typeof obj.dh === "string" && typeof obj.n === "number";
|
|
474
|
+
return false;
|
|
475
|
+
} catch {
|
|
476
|
+
return false;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
function peekEnvelopeVersion(bytes) {
|
|
480
|
+
try {
|
|
481
|
+
return JSON.parse(Buffer.from(bytes).toString("utf8"))?.v;
|
|
482
|
+
} catch {
|
|
483
|
+
return void 0;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
function serializeEnvelope(env) {
|
|
487
|
+
return new Uint8Array(Buffer.from(JSON.stringify(env), "utf8"));
|
|
488
|
+
}
|
|
489
|
+
function parseEnvelope(bytes) {
|
|
490
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
491
|
+
if (obj?.v !== E2EE_ENVELOPE_VERSION) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
|
|
492
|
+
return obj;
|
|
493
|
+
}
|
|
494
|
+
function parseEnvelopeV2(bytes) {
|
|
495
|
+
const obj = JSON.parse(Buffer.from(bytes).toString("utf8"));
|
|
496
|
+
if (obj?.v !== E2EE_ENVELOPE_VERSION_V2) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
|
|
497
|
+
return obj;
|
|
498
|
+
}
|
|
499
|
+
async function encryptForPeer(keystore, dm, peerId, plaintext) {
|
|
500
|
+
let session = await keystore.getSession(peerId);
|
|
501
|
+
if (!session) {
|
|
502
|
+
const raw = await dm.fetchPrekeyBundle(peerId);
|
|
503
|
+
if (!raw) {
|
|
504
|
+
throw new Error(
|
|
505
|
+
`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.`
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
const peer = parsePublicBundle(raw);
|
|
509
|
+
if (!verifyPublicBundle(peer)) {
|
|
510
|
+
throw new Error(
|
|
511
|
+
`Prekey bundle for "${peerId}" failed signature verification \u2014 refusing to start an encrypted session (possible tampering / man-in-the-middle).`
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
const own = await keystore.getOwnMaterial();
|
|
515
|
+
const ephemeral = await generateX25519KeyPair();
|
|
516
|
+
const opk = peer.oneTimePrekeys[0];
|
|
517
|
+
const { rootKey } = await performX3dh(own.identity.privateKey, ephemeral.privateKey, {
|
|
518
|
+
identityPublicKey: peer.identityPublicKey,
|
|
519
|
+
signedPreKeyPublicKey: peer.signedPrekey.publicKey,
|
|
520
|
+
oneTimePreKeyPublicKey: opk?.publicKey
|
|
521
|
+
});
|
|
522
|
+
const ratchet2 = await initRatchetInitiator(rootKey, peer.signedPrekey.publicKey);
|
|
523
|
+
session = {
|
|
524
|
+
ratchet2,
|
|
525
|
+
role: "initiator",
|
|
526
|
+
pendingHandshake: { ik: own.identity.publicKey, ek: ephemeral.publicKey, opkId: opk?.id }
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
if (session.ratchet2) {
|
|
530
|
+
const { header, ct: ct2 } = await ratchetEncrypt(session.ratchet2, plaintext);
|
|
531
|
+
const env2 = {
|
|
532
|
+
v: E2EE_ENVELOPE_VERSION_V2,
|
|
533
|
+
dh: toBase64(header.dh),
|
|
534
|
+
pn: header.pn,
|
|
535
|
+
n: header.n,
|
|
536
|
+
ct: ct2
|
|
537
|
+
};
|
|
538
|
+
if (session.pendingHandshake) {
|
|
539
|
+
env2.hdr = {
|
|
540
|
+
ik: toBase64(session.pendingHandshake.ik),
|
|
541
|
+
ek: toBase64(session.pendingHandshake.ek),
|
|
542
|
+
opk: session.pendingHandshake.opkId
|
|
543
|
+
};
|
|
544
|
+
session.pendingHandshake = void 0;
|
|
545
|
+
}
|
|
546
|
+
await keystore.putSession(peerId, session);
|
|
547
|
+
return serializeEnvelope(env2);
|
|
548
|
+
}
|
|
549
|
+
const step = await ratchetSend(session.ratchet);
|
|
550
|
+
const ct = await encryptBytes(step.messageKey, plaintext);
|
|
551
|
+
const env = { v: E2EE_ENVELOPE_VERSION, i: step.messageIndex, ct };
|
|
552
|
+
if (session.pendingHandshake && step.messageIndex === 0) {
|
|
553
|
+
env.hdr = {
|
|
554
|
+
ik: toBase64(session.pendingHandshake.ik),
|
|
555
|
+
ek: toBase64(session.pendingHandshake.ek),
|
|
556
|
+
opk: session.pendingHandshake.opkId
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
session.pendingHandshake = void 0;
|
|
560
|
+
await keystore.putSession(peerId, session);
|
|
561
|
+
return serializeEnvelope(env);
|
|
562
|
+
}
|
|
563
|
+
async function responderRootKey(keystore, hdr) {
|
|
564
|
+
const own = await keystore.getOwnMaterial();
|
|
565
|
+
let oneTimePreKeyPrivateKey;
|
|
566
|
+
if (hdr.opk !== void 0) {
|
|
567
|
+
oneTimePreKeyPrivateKey = await keystore.takeOneTimePrekey(hdr.opk);
|
|
568
|
+
if (!oneTimePreKeyPrivateKey) {
|
|
569
|
+
throw new Error(`Handshake references one-time prekey ${hdr.opk} which is unknown or already consumed.`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const { rootKey } = await performX3dhResponder(
|
|
573
|
+
{
|
|
574
|
+
identityPrivateKey: own.identity.privateKey,
|
|
575
|
+
signedPreKeyPrivateKey: own.signedPrekey.pair.privateKey,
|
|
576
|
+
oneTimePreKeyPrivateKey
|
|
577
|
+
},
|
|
578
|
+
{
|
|
579
|
+
initiatorIdentityPublicKey: fromBase64(hdr.ik),
|
|
580
|
+
initiatorEphemeralPublicKey: fromBase64(hdr.ek),
|
|
581
|
+
usedOneTimePreKeyId: hdr.opk
|
|
582
|
+
}
|
|
583
|
+
);
|
|
584
|
+
return rootKey;
|
|
585
|
+
}
|
|
586
|
+
async function decryptFromPeer(keystore, peerId, envelopeBytes) {
|
|
587
|
+
if (peekEnvelopeVersion(envelopeBytes) === E2EE_ENVELOPE_VERSION_V2) {
|
|
588
|
+
const env2 = parseEnvelopeV2(envelopeBytes);
|
|
589
|
+
let session2 = await keystore.getSession(peerId);
|
|
590
|
+
if (!session2) {
|
|
591
|
+
if (!env2.hdr) {
|
|
592
|
+
throw new Error(`No session with "${peerId}" and the message carries no handshake header \u2014 cannot decrypt.`);
|
|
593
|
+
}
|
|
594
|
+
const rootKey = await responderRootKey(keystore, env2.hdr);
|
|
595
|
+
const own = await keystore.getOwnMaterial();
|
|
596
|
+
const ratchet2 = await initRatchetResponder(rootKey, {
|
|
597
|
+
publicKey: own.signedPrekey.pair.publicKey,
|
|
598
|
+
privateKey: own.signedPrekey.pair.privateKey
|
|
599
|
+
});
|
|
600
|
+
session2 = { ratchet2, role: "responder" };
|
|
601
|
+
}
|
|
602
|
+
if (!session2.ratchet2) {
|
|
603
|
+
throw new Error(`Received a v2 mDM envelope but the session with "${peerId}" is v1 \u2014 refusing to mix ratchets.`);
|
|
604
|
+
}
|
|
605
|
+
const plaintext2 = await ratchetDecrypt(
|
|
606
|
+
session2.ratchet2,
|
|
607
|
+
{ dh: fromBase64(env2.dh), pn: env2.pn, n: env2.n },
|
|
608
|
+
env2.ct
|
|
609
|
+
);
|
|
610
|
+
await keystore.putSession(peerId, session2);
|
|
611
|
+
return plaintext2;
|
|
612
|
+
}
|
|
613
|
+
const env = parseEnvelope(envelopeBytes);
|
|
614
|
+
let session = await keystore.getSession(peerId);
|
|
615
|
+
if (!session) {
|
|
616
|
+
if (!env.hdr) {
|
|
617
|
+
throw new Error(`No session with "${peerId}" and the message carries no handshake header \u2014 cannot decrypt.`);
|
|
618
|
+
}
|
|
619
|
+
const rootKey = await responderRootKey(keystore, env.hdr);
|
|
620
|
+
const ratchet = await initializeRatchet(rootKey, "responder");
|
|
621
|
+
session = { ratchet, role: "responder" };
|
|
622
|
+
}
|
|
623
|
+
if (!session.ratchet) {
|
|
624
|
+
throw new Error(`Received a v1 mDM envelope but the session with "${peerId}" is v2 \u2014 refusing to mix ratchets.`);
|
|
625
|
+
}
|
|
626
|
+
const step = await ratchetReceive(session.ratchet);
|
|
627
|
+
if (step.messageIndex !== env.i) {
|
|
628
|
+
throw new Error(
|
|
629
|
+
`Out-of-order mDM message (expected ratchet index ${step.messageIndex}, got ${env.i}). Skipped-key handling is a tracked follow-up (LINEAR-2357).`
|
|
630
|
+
);
|
|
631
|
+
}
|
|
632
|
+
const plaintext = await decryptBytes(step.messageKey, env.ct);
|
|
633
|
+
await keystore.putSession(peerId, session);
|
|
634
|
+
return plaintext;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// src/providers/supabase-dm.ts
|
|
638
|
+
var PROTOCOL_VERSION = "mosadd.chat.v1";
|
|
639
|
+
var MDM_TEXT_MESSAGE_TYPE = "txt";
|
|
640
|
+
var MDM_MCP_SEALED_MESSAGE_TYPE = "text";
|
|
641
|
+
var SupabaseDmProvider = class {
|
|
642
|
+
cachedSelfId = null;
|
|
643
|
+
cachedSelfKind = null;
|
|
644
|
+
/**
|
|
645
|
+
* `identities.kind` of the caller ("human" | "agent" | …). An agent LINE owns its mDM
|
|
646
|
+
* identity outright (its key is its only runtime); a human's identity is anchored in the app.
|
|
647
|
+
* ensureOwnBundlePublished uses this to decide whether a stale bundle may be replaced.
|
|
648
|
+
*/
|
|
649
|
+
async selfKind() {
|
|
650
|
+
await this.selfId();
|
|
651
|
+
return this.cachedSelfKind;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* `identities.kind` of a PEER, or null when it cannot be read (RLS can_see_identity scopes rows
|
|
655
|
+
* to contacts / thread co-members; a miss is not an error). mDM_send uses it exactly like the
|
|
656
|
+
* app's ChatPanel `peerIsAgent` (theirIdent.kind === 'agent' || iAmAgent): a DM to an agent
|
|
657
|
+
* line is sent in the clear, because the line must read it (rozkaz Króla 20.09).
|
|
658
|
+
*/
|
|
659
|
+
async peerKind(peerId) {
|
|
660
|
+
try {
|
|
661
|
+
const sb = getSupabase();
|
|
662
|
+
const { data, error } = await sb.from("identities").select("kind").eq("id", peerId).limit(1).maybeSingle();
|
|
663
|
+
if (error || !data) return null;
|
|
664
|
+
return typeof data.kind === "string" ? data.kind : null;
|
|
665
|
+
} catch {
|
|
666
|
+
return null;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
async selfId() {
|
|
670
|
+
if (this.cachedSelfId) return this.cachedSelfId;
|
|
671
|
+
readSupabaseEnv();
|
|
672
|
+
const sb = getSupabase();
|
|
673
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
674
|
+
if (ue || !u?.user) {
|
|
675
|
+
throw new Error(
|
|
676
|
+
"Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
const { data: identity, error } = await sb.from("identities").select("id, kind").eq("user_id", u.user.id).maybeSingle();
|
|
680
|
+
if (error || !identity) {
|
|
681
|
+
throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
|
|
682
|
+
}
|
|
683
|
+
this.cachedSelfId = identity.id;
|
|
684
|
+
this.cachedSelfKind = typeof identity.kind === "string" ? identity.kind : null;
|
|
685
|
+
return this.cachedSelfId;
|
|
686
|
+
}
|
|
687
|
+
async send(args) {
|
|
688
|
+
const encrypted_payload = Buffer.from(args.payload).toString("base64");
|
|
689
|
+
const data = await invokeFunction("message-send", {
|
|
690
|
+
space_id: "dm",
|
|
691
|
+
thread_id: args.threadId,
|
|
692
|
+
encrypted_payload,
|
|
693
|
+
message_type: args.messageType ?? MDM_TEXT_MESSAGE_TYPE,
|
|
694
|
+
protocol_version: PROTOCOL_VERSION,
|
|
695
|
+
recipient_account_id: args.to,
|
|
696
|
+
reply_to_id: args.replyToId ?? null,
|
|
697
|
+
// Same optional columns the app writes (ircApi.sendThreadMessage); omitted when absent.
|
|
698
|
+
...args.selfPayload ? { self_payload: args.selfPayload } : {},
|
|
699
|
+
...args.recipientSelfPayload ? { recipient_self_payload: args.recipientSelfPayload } : {}
|
|
700
|
+
});
|
|
701
|
+
if (!data?.message?.id) {
|
|
702
|
+
throw new Error("message-send returned no message id");
|
|
703
|
+
}
|
|
704
|
+
return {
|
|
705
|
+
id: data.message.id,
|
|
706
|
+
deliveredAt: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
async publishPrekeyBundle(bundle) {
|
|
710
|
+
await invokeFunction("prekey-bundle-publish", {
|
|
711
|
+
bundle: Buffer.from(bundle).toString("base64")
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
async fetchPrekeyBundle(peerId) {
|
|
715
|
+
const data = await invokeFunction("prekey-bundle-fetch", {
|
|
716
|
+
peer_id: peerId
|
|
717
|
+
});
|
|
718
|
+
if (!data?.bundle) return null;
|
|
719
|
+
return new Uint8Array(Buffer.from(data.bundle, "base64"));
|
|
720
|
+
}
|
|
721
|
+
async list(args) {
|
|
722
|
+
const data = await invokeFunction("message-list", {
|
|
723
|
+
space_id: "dm",
|
|
724
|
+
thread_id: args.threadId,
|
|
725
|
+
limit: args.limit ?? 50,
|
|
726
|
+
before: args.cursor
|
|
727
|
+
});
|
|
728
|
+
return {
|
|
729
|
+
messages: (data?.messages ?? []).map((m) => ({
|
|
730
|
+
id: m.id,
|
|
731
|
+
senderId: m.sender_identity_id,
|
|
732
|
+
payload: new Uint8Array(Buffer.from(m.encrypted_payload, "base64")),
|
|
733
|
+
timestamp: m.created_at,
|
|
734
|
+
threadId: m.thread_id,
|
|
735
|
+
messageType: m.message_type ?? void 0,
|
|
736
|
+
selfPayload: m.self_payload ?? null,
|
|
737
|
+
recipientSelfPayload: m.recipient_self_payload ?? null,
|
|
738
|
+
transcript: m.transcript ?? null,
|
|
739
|
+
audioUrl: m.audio_url ?? null,
|
|
740
|
+
durationMs: m.duration_ms ?? null
|
|
741
|
+
})),
|
|
742
|
+
// history mode (`before`) returns `next_before`; incremental (`since`) returns `cursor`+`has_more`.
|
|
743
|
+
nextCursor: data?.next_before ?? (data?.has_more ? data?.cursor ?? null : null)
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
|
|
748
|
+
// src/tools/mdm.ts
|
|
749
|
+
var PROTOCOL_VERSION2 = "mosadd.chat.v1";
|
|
750
|
+
var ContactRef = z.string().min(1).describe(
|
|
751
|
+
"Recipient identity id (UUID). Use mDM_list_contacts first to find the right id. Future versions will accept handle/email/phone directly."
|
|
752
|
+
);
|
|
753
|
+
var ThreadSuffix = z.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe(
|
|
754
|
+
"Optional thread label within the conversation with this contact. Defaults to the contact's main thread. mosadd USP: multiple threads per contact."
|
|
755
|
+
);
|
|
756
|
+
var mDM_send_input = z.object({
|
|
757
|
+
to: ContactRef,
|
|
758
|
+
text: z.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
|
|
759
|
+
thread_label: ThreadSuffix.optional().describe(
|
|
760
|
+
"Optional thread label. If omitted, uses the default thread for this contact."
|
|
761
|
+
),
|
|
762
|
+
reply_to_id: z.string().optional().describe("Optional id of the message being replied to.")
|
|
763
|
+
});
|
|
764
|
+
var mDM_list_input = z.object({
|
|
765
|
+
contact_id: ContactRef.describe("Identity id of the contact to read messages with."),
|
|
766
|
+
thread_label: ThreadSuffix.optional(),
|
|
767
|
+
limit: z.number().int().min(1).max(200).default(50).optional(),
|
|
768
|
+
cursor: z.string().optional().describe("Opaque pagination cursor from a previous response.")
|
|
769
|
+
});
|
|
770
|
+
var mDM_list_contacts_input = z.object({
|
|
771
|
+
limit: z.number().int().min(1).max(500).default(100).optional()
|
|
772
|
+
});
|
|
773
|
+
var mDM_respond_request_input = z.object({
|
|
774
|
+
request_id: z.string().min(1),
|
|
775
|
+
action: z.enum(["accept", "reject"])
|
|
776
|
+
});
|
|
777
|
+
function dmThreadId(selfId, otherId, label) {
|
|
778
|
+
const [a, b] = [selfId, otherId].sort();
|
|
779
|
+
return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
|
|
780
|
+
}
|
|
781
|
+
async function resolveSelfIdentityId() {
|
|
782
|
+
const sb = getSupabase();
|
|
783
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
784
|
+
if (ue || !u?.user) {
|
|
785
|
+
throw new Error(
|
|
786
|
+
"Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
|
|
790
|
+
if (error || !identity) {
|
|
791
|
+
throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
|
|
792
|
+
}
|
|
793
|
+
return identity.id;
|
|
794
|
+
}
|
|
795
|
+
function packPlaintextPayload(text) {
|
|
796
|
+
return new Uint8Array(Buffer.from(text, "utf8"));
|
|
797
|
+
}
|
|
798
|
+
function unpackPayload(payload) {
|
|
799
|
+
try {
|
|
800
|
+
const raw = Buffer.from(payload).toString("utf8");
|
|
801
|
+
try {
|
|
802
|
+
const obj = JSON.parse(raw);
|
|
803
|
+
if (typeof obj?.text === "string") return obj;
|
|
804
|
+
} catch {
|
|
805
|
+
return { text: raw };
|
|
806
|
+
}
|
|
807
|
+
return { text: raw };
|
|
808
|
+
} catch {
|
|
809
|
+
}
|
|
810
|
+
return { text: "<ciphertext>" };
|
|
811
|
+
}
|
|
812
|
+
async function selfKindOf(dm) {
|
|
813
|
+
const f = dm.selfKind;
|
|
814
|
+
return typeof f === "function" ? await f.call(dm) : null;
|
|
815
|
+
}
|
|
816
|
+
async function peerKindOf(dm, peerId) {
|
|
817
|
+
const f = dm.peerKind;
|
|
818
|
+
if (typeof f !== "function") return null;
|
|
819
|
+
try {
|
|
820
|
+
return await f.call(dm, peerId);
|
|
821
|
+
} catch {
|
|
822
|
+
return null;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
async function mDM_send(input, ctx) {
|
|
826
|
+
const dm = ctx.providers.dm;
|
|
827
|
+
const selfId = await dm.selfId();
|
|
828
|
+
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
829
|
+
const keys = ctx.providers.keys;
|
|
830
|
+
const selfKind = await selfKindOf(dm);
|
|
831
|
+
const noteToSelf = input.to === selfId;
|
|
832
|
+
const peerKind = selfKind === "agent" || noteToSelf ? selfKind : await peerKindOf(dm, input.to);
|
|
833
|
+
if (selfKind === "agent" || peerKind === "agent" || noteToSelf) {
|
|
834
|
+
const payload = packPlaintextPayload(input.text);
|
|
835
|
+
ctx.log("debug", "mDM_send agent-line plaintext (owner decisions 20.09 + 28.09)", {
|
|
836
|
+
thread_id: threadId,
|
|
837
|
+
self_kind: selfKind,
|
|
838
|
+
peer_kind: peerKind,
|
|
839
|
+
note_to_self: noteToSelf
|
|
840
|
+
});
|
|
841
|
+
const plainArgs = {
|
|
842
|
+
to: input.to,
|
|
843
|
+
threadId,
|
|
844
|
+
payload,
|
|
845
|
+
replyToId: input.reply_to_id,
|
|
846
|
+
messageType: MDM_TEXT_MESSAGE_TYPE
|
|
847
|
+
};
|
|
848
|
+
const result2 = await dm.send(plainArgs);
|
|
849
|
+
return {
|
|
850
|
+
message_id: result2.id,
|
|
851
|
+
delivered_at: result2.deliveredAt,
|
|
852
|
+
thread_id: threadId,
|
|
853
|
+
encrypted: false,
|
|
854
|
+
mode: "plaintext_agent_lane",
|
|
855
|
+
reason: "fleet_plaintext",
|
|
856
|
+
sender_copy: true,
|
|
857
|
+
recipient_copy: true,
|
|
858
|
+
identity: "untouched"
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
let identity = "foreign";
|
|
862
|
+
try {
|
|
863
|
+
identity = await ensureOwnBundlePublished(keys, dm, selfId, bundlePolicyForKind(selfKind, { explicit: false }));
|
|
864
|
+
} catch (err) {
|
|
865
|
+
ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
|
|
866
|
+
}
|
|
867
|
+
const ourIdentityIsPublished = identity === "consistent" || identity === "published";
|
|
868
|
+
const inner = packPlaintextPayload(input.text);
|
|
869
|
+
const sealed = await encryptForPeer(keys, dm, input.to, inner);
|
|
870
|
+
const selfPayload = selfKind !== "human" && ourIdentityIsPublished ? await sealForSelf(keys, inner) : null;
|
|
871
|
+
let recipientSelfPayload = null;
|
|
872
|
+
if (ourIdentityIsPublished && input.to !== selfId) {
|
|
873
|
+
try {
|
|
874
|
+
const peer = await fetchVerifiedBundle(dm, input.to);
|
|
875
|
+
if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
|
|
876
|
+
} catch (err) {
|
|
877
|
+
ctx.log("warn", "mDM_send skipped the recipient copy", { error: String(err) });
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
ctx.log("debug", "mDM_send E2EE via DmProvider", {
|
|
881
|
+
thread_id: threadId,
|
|
882
|
+
bytes: sealed.byteLength,
|
|
883
|
+
identity,
|
|
884
|
+
sender_copy: !!selfPayload,
|
|
885
|
+
recipient_copy: !!recipientSelfPayload
|
|
886
|
+
});
|
|
887
|
+
const sendArgs = {
|
|
888
|
+
to: input.to,
|
|
889
|
+
threadId,
|
|
890
|
+
payload: sealed,
|
|
891
|
+
replyToId: input.reply_to_id,
|
|
892
|
+
messageType: MDM_MCP_SEALED_MESSAGE_TYPE,
|
|
893
|
+
selfPayload,
|
|
894
|
+
recipientSelfPayload
|
|
895
|
+
};
|
|
896
|
+
const result = await dm.send(sendArgs);
|
|
897
|
+
if (keys.putSentMessage) {
|
|
898
|
+
await keys.putSentMessage(result.id, inner);
|
|
899
|
+
}
|
|
900
|
+
return {
|
|
901
|
+
message_id: result.id,
|
|
902
|
+
delivered_at: result.deliveredAt,
|
|
903
|
+
thread_id: threadId,
|
|
904
|
+
encrypted: true,
|
|
905
|
+
mode: "e2ee",
|
|
906
|
+
reason: "human_to_human",
|
|
907
|
+
sender_copy: !!selfPayload,
|
|
908
|
+
recipient_copy: !!recipientSelfPayload,
|
|
909
|
+
identity
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
async function mDM_send_unencrypted(input, ctx) {
|
|
913
|
+
const dm = ctx.providers.dm;
|
|
914
|
+
const selfId = await dm.selfId();
|
|
915
|
+
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
916
|
+
const payload = packPlaintextPayload(input.text);
|
|
917
|
+
ctx.log("debug", "mDM_send_unencrypted (plaintext) via DmProvider", {
|
|
918
|
+
thread_id: threadId,
|
|
919
|
+
bytes: payload.byteLength
|
|
920
|
+
});
|
|
921
|
+
const plainArgs = {
|
|
922
|
+
to: input.to,
|
|
923
|
+
threadId,
|
|
924
|
+
payload,
|
|
925
|
+
replyToId: input.reply_to_id,
|
|
926
|
+
messageType: MDM_TEXT_MESSAGE_TYPE
|
|
927
|
+
};
|
|
928
|
+
const result = await dm.send(plainArgs);
|
|
929
|
+
return {
|
|
930
|
+
message_id: result.id,
|
|
931
|
+
delivered_at: result.deliveredAt,
|
|
932
|
+
thread_id: threadId,
|
|
933
|
+
encrypted: false
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
async function mDM_publish_keys(_input, ctx) {
|
|
937
|
+
const dm = ctx.providers.dm;
|
|
938
|
+
const keys = ctx.providers.keys;
|
|
939
|
+
const selfId = await dm.selfId();
|
|
940
|
+
const identity = await ensureOwnBundlePublished(
|
|
941
|
+
keys,
|
|
942
|
+
dm,
|
|
943
|
+
selfId,
|
|
944
|
+
bundlePolicyForKind(await selfKindOf(dm), { explicit: true })
|
|
945
|
+
);
|
|
946
|
+
const { oneTimePrekeys } = await keys.getOwnMaterial();
|
|
947
|
+
ctx.log("debug", "mDM_publish_keys", { identity, one_time_prekeys: oneTimePrekeys.length });
|
|
948
|
+
if (identity === "foreign") {
|
|
949
|
+
return {
|
|
950
|
+
published: false,
|
|
951
|
+
identity,
|
|
952
|
+
one_time_prekeys: 0,
|
|
953
|
+
note: "This identity already has keys published by the mosADD app. They were left untouched: replacing them from an API key would make every conversation with you unreadable in the app."
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
return { published: identity === "published", identity, one_time_prekeys: oneTimePrekeys.length };
|
|
957
|
+
}
|
|
958
|
+
async function mDM_list(input, ctx) {
|
|
959
|
+
const dm = ctx.providers.dm;
|
|
960
|
+
const selfId = await dm.selfId();
|
|
961
|
+
const threadId = dmThreadId(selfId, input.contact_id, input.thread_label);
|
|
962
|
+
ctx.log("debug", "mDM_list via DmProvider", { thread_id: threadId });
|
|
963
|
+
const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
|
|
964
|
+
const keys = ctx.providers.keys;
|
|
965
|
+
const bundleBySender = /* @__PURE__ */ new Map();
|
|
966
|
+
const senderBundle = (id) => {
|
|
967
|
+
let p = bundleBySender.get(id);
|
|
968
|
+
if (!p) {
|
|
969
|
+
p = fetchVerifiedBundle(dm, id).catch(() => null);
|
|
970
|
+
bundleBySender.set(id, p);
|
|
971
|
+
}
|
|
972
|
+
return p;
|
|
973
|
+
};
|
|
974
|
+
const messages = await Promise.all(
|
|
975
|
+
result.messages.map(async (raw) => {
|
|
976
|
+
const m = raw;
|
|
977
|
+
const base = {
|
|
978
|
+
id: m.id,
|
|
979
|
+
sender_identity_id: m.senderId,
|
|
980
|
+
timestamp: m.timestamp,
|
|
981
|
+
thread_id: m.threadId,
|
|
982
|
+
...voiceFields(m)
|
|
983
|
+
};
|
|
984
|
+
if (!isE2eeEnvelope(m.payload)) {
|
|
985
|
+
return { ...base, text: formatVoiceIfAny(unpackPayload(m.payload).text), encrypted: false };
|
|
986
|
+
}
|
|
987
|
+
if (m.senderId === selfId) {
|
|
988
|
+
const own = await openSelfSealed(keys, m.selfPayload) ?? await keys.getSentMessage?.(m.id);
|
|
989
|
+
if (own) {
|
|
990
|
+
return { ...base, text: formatVoiceIfAny(unpackPayload(own).text), encrypted: true };
|
|
991
|
+
}
|
|
992
|
+
if (input.contact_id === selfId) {
|
|
993
|
+
try {
|
|
994
|
+
const inner = await decryptFromPeer(keys, selfId, m.payload);
|
|
995
|
+
return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
|
|
996
|
+
} catch {
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
return { ...base, text: "<encrypted \xB7 sent by you>", encrypted: true };
|
|
1000
|
+
}
|
|
1001
|
+
if (m.recipientSelfPayload) {
|
|
1002
|
+
const bundle = await senderBundle(m.senderId);
|
|
1003
|
+
const copy = (bundle ? await openPeerRecoverable(keys, bundle, m.recipientSelfPayload) : null) ?? await openSelfSealed(keys, m.recipientSelfPayload);
|
|
1004
|
+
if (copy) {
|
|
1005
|
+
return { ...base, text: formatVoiceIfAny(unpackPayload(copy).text), encrypted: true };
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
try {
|
|
1009
|
+
const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
|
|
1010
|
+
return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
|
|
1011
|
+
} catch (err) {
|
|
1012
|
+
ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
|
|
1013
|
+
return { ...base, text: "<undecryptable>", encrypted: true };
|
|
1014
|
+
}
|
|
1015
|
+
})
|
|
1016
|
+
);
|
|
1017
|
+
return {
|
|
1018
|
+
messages,
|
|
1019
|
+
next_cursor: result.nextCursor,
|
|
1020
|
+
threads: [threadId]
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
async function mDM_list_contacts(input, ctx) {
|
|
1024
|
+
readSupabaseEnv();
|
|
1025
|
+
const selfId = await resolveSelfIdentityId();
|
|
1026
|
+
const sb = getSupabase();
|
|
1027
|
+
ctx.log("debug", "mDM_list_contacts querying contacts table", { selfId });
|
|
1028
|
+
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);
|
|
1029
|
+
if (error) {
|
|
1030
|
+
throw new Error(`Failed to list contacts: ${error.message}`);
|
|
1031
|
+
}
|
|
1032
|
+
const contacts = data.map((r) => ({
|
|
1033
|
+
identity_id: r.contact_identity_id,
|
|
1034
|
+
account_id: r.identities?.account_id ?? null,
|
|
1035
|
+
display_name: r.identities?.display_name ?? null,
|
|
1036
|
+
state: r.state
|
|
1037
|
+
}));
|
|
1038
|
+
return { contacts };
|
|
1039
|
+
}
|
|
1040
|
+
async function mDM_respond_request(input, ctx) {
|
|
1041
|
+
readSupabaseEnv();
|
|
1042
|
+
ctx.log("debug", "mDM_respond_request invoking message-request-respond", input);
|
|
1043
|
+
await invokeFunction("message-request-respond", {
|
|
1044
|
+
action: "respond",
|
|
1045
|
+
request_id: input.request_id,
|
|
1046
|
+
status: input.action === "accept" ? "accepted" : "rejected"
|
|
1047
|
+
});
|
|
1048
|
+
return { ok: true };
|
|
1049
|
+
}
|
|
1050
|
+
var mDM_publish_keys_input = z.object({});
|
|
1051
|
+
var mDM_edit_input = z.object({
|
|
1052
|
+
to: ContactRef.describe(
|
|
1053
|
+
"Recipient identity id of the conversation the message is in (needed to locate it and verify the edit won't break E2EE)."
|
|
1054
|
+
),
|
|
1055
|
+
message_id: z.string().min(1).describe("Id of the message to edit (from mDM_list)."),
|
|
1056
|
+
new_text: z.string().min(1).max(64e3).describe("Replacement message body (UTF-8). Max 64 KB."),
|
|
1057
|
+
thread_label: ThreadSuffix.optional()
|
|
1058
|
+
});
|
|
1059
|
+
var mDM_delete_input = z.object({
|
|
1060
|
+
message_id: z.string().min(1).describe("Id of the message to delete (from mDM_list).")
|
|
1061
|
+
});
|
|
1062
|
+
async function mDM_edit(input, ctx) {
|
|
1063
|
+
readSupabaseEnv();
|
|
1064
|
+
const dm = ctx.providers.dm;
|
|
1065
|
+
const selfId = await dm.selfId();
|
|
1066
|
+
const threadId = dmThreadId(selfId, input.to, input.thread_label);
|
|
1067
|
+
const recent = await dm.list({ threadId, limit: 100 });
|
|
1068
|
+
const target = recent.messages.find((m) => m.id === input.message_id);
|
|
1069
|
+
if (!target) {
|
|
1070
|
+
throw new Error(
|
|
1071
|
+
`mDM_edit could not find message ${input.message_id} in the recent history of this thread. Pass the 'to' (and 'thread_label') of the conversation the message belongs to.`
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
if (isE2eeEnvelope(target.payload)) {
|
|
1075
|
+
throw new Error(
|
|
1076
|
+
"mDM_edit cannot edit an end-to-end-encrypted message: the Double Ratchet is forward-only, so the edit can't be re-sealed and storing a new body would strip E2EE. Delete it with mDM_delete and send a replacement with mDM_send instead."
|
|
1077
|
+
);
|
|
1078
|
+
}
|
|
1079
|
+
const envelope = {
|
|
1080
|
+
v: PROTOCOL_VERSION2,
|
|
1081
|
+
type: "text",
|
|
1082
|
+
text: input.new_text,
|
|
1083
|
+
edited: true,
|
|
1084
|
+
sent_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1085
|
+
};
|
|
1086
|
+
const encrypted_payload = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
|
|
1087
|
+
ctx.log("debug", "mDM_edit via message-edit (legacy plaintext only)", { message_id: input.message_id });
|
|
1088
|
+
await invokeFunction("message-edit", { message_id: input.message_id, encrypted_payload });
|
|
1089
|
+
return { message_id: input.message_id, edited: true };
|
|
1090
|
+
}
|
|
1091
|
+
async function mDM_delete(input, ctx) {
|
|
1092
|
+
readSupabaseEnv();
|
|
1093
|
+
ctx.log("debug", "mDM_delete via message-delete", { message_id: input.message_id });
|
|
1094
|
+
await invokeFunction("message-delete", { message_id: input.message_id });
|
|
1095
|
+
return { message_id: input.message_id, deleted: true };
|
|
1096
|
+
}
|
|
1097
|
+
var mdmTools = [
|
|
1098
|
+
{
|
|
1099
|
+
name: "mDM_list_contacts",
|
|
1100
|
+
title: "List contacts",
|
|
1101
|
+
annotations: { readOnlyHint: true },
|
|
1102
|
+
requires: "any",
|
|
1103
|
+
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).",
|
|
1104
|
+
inputSchema: mDM_list_contacts_input,
|
|
1105
|
+
handler: mDM_list_contacts
|
|
1106
|
+
},
|
|
1107
|
+
{
|
|
1108
|
+
name: "mDM_publish_keys",
|
|
1109
|
+
title: "Publish encryption keys",
|
|
1110
|
+
annotations: { readOnlyHint: false },
|
|
1111
|
+
requires: "any",
|
|
1112
|
+
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.",
|
|
1113
|
+
inputSchema: mDM_publish_keys_input,
|
|
1114
|
+
handler: mDM_publish_keys
|
|
1115
|
+
},
|
|
1116
|
+
{
|
|
1117
|
+
name: "mDM_send",
|
|
1118
|
+
title: "Send DM",
|
|
1119
|
+
annotations: { readOnlyHint: false },
|
|
1120
|
+
requires: "any",
|
|
1121
|
+
description: 'Send a direct message via mosadd mDM. Conversations with fleet lines and with the King: ALWAYS in the clear \u2014 when either side is an agent line, or you write to yourself, the message goes as plain text (result `encrypted: false, reason: "fleet_plaintext"`), exactly like the mosadd app. Only between two PEOPLE is it END-TO-END-ENCRYPTED (X3DH + Double Ratchet; the recipient must have published keys). Pass `to` as the recipient\'s mosadd identity_id (look it up with mDM_list_contacts). Optional thread_label puts the message in a named thread \u2014 mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram.',
|
|
1122
|
+
inputSchema: mDM_send_input,
|
|
1123
|
+
handler: mDM_send
|
|
1124
|
+
},
|
|
1125
|
+
{
|
|
1126
|
+
name: "mDM_send_unencrypted",
|
|
1127
|
+
title: "Send plain-text DM",
|
|
1128
|
+
annotations: { readOnlyHint: false },
|
|
1129
|
+
requires: "any",
|
|
1130
|
+
description: "Send a direct message as plain text, never encrypted. Conversations with fleet lines and with the King: ALWAYS in the clear \u2014 this is the path for every agent line writing to the King, to another line or to itself, and it is permanent. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts); optional thread_label puts it in a named thread. mDM_send picks the same plain-text path by itself whenever a fleet line is a party.",
|
|
1131
|
+
inputSchema: mDM_send_input,
|
|
1132
|
+
handler: mDM_send_unencrypted
|
|
1133
|
+
},
|
|
1134
|
+
{
|
|
1135
|
+
name: "mDM_list",
|
|
1136
|
+
title: "Read direct messages",
|
|
1137
|
+
annotations: { readOnlyHint: true },
|
|
1138
|
+
requires: "any",
|
|
1139
|
+
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.",
|
|
1140
|
+
inputSchema: mDM_list_input,
|
|
1141
|
+
handler: mDM_list
|
|
1142
|
+
},
|
|
1143
|
+
{
|
|
1144
|
+
name: "mDM_respond_request",
|
|
1145
|
+
title: "Accept or decline contact request",
|
|
1146
|
+
annotations: { readOnlyHint: false },
|
|
1147
|
+
requires: "any",
|
|
1148
|
+
description: "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
|
|
1149
|
+
inputSchema: mDM_respond_request_input,
|
|
1150
|
+
handler: mDM_respond_request
|
|
1151
|
+
},
|
|
1152
|
+
{
|
|
1153
|
+
name: "mDM_edit",
|
|
1154
|
+
title: "Edit a DM",
|
|
1155
|
+
annotations: { destructiveHint: true },
|
|
1156
|
+
requires: "any",
|
|
1157
|
+
description: "Edit a direct message you sent \u2014 replace its body by message_id (pass the conversation's `to` so it can be located). NOTE: end-to-end-encrypted messages CANNOT be edited (the ratchet is forward-only) \u2014 mDM_edit refuses them and you should mDM_delete + mDM_send a replacement instead. Only legacy non-E2EE messages are editable.",
|
|
1158
|
+
inputSchema: mDM_edit_input,
|
|
1159
|
+
handler: mDM_edit
|
|
1160
|
+
},
|
|
1161
|
+
{
|
|
1162
|
+
name: "mDM_delete",
|
|
1163
|
+
title: "Delete a DM",
|
|
1164
|
+
annotations: { destructiveHint: true },
|
|
1165
|
+
requires: "any",
|
|
1166
|
+
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.",
|
|
1167
|
+
inputSchema: mDM_delete_input,
|
|
1168
|
+
handler: mDM_delete
|
|
1169
|
+
}
|
|
1170
|
+
];
|
|
1171
|
+
|
|
1172
|
+
// src/tools/mdm-as-agent.ts
|
|
1173
|
+
import { z as z2 } from "zod";
|
|
1174
|
+
var mDM_send_as_agent_input = z2.object({
|
|
1175
|
+
agent: z2.string().min(1).max(200).describe(
|
|
1176
|
+
"Which of YOUR agents to speak as \u2014 its mosADD address (<agent>@mosadd.com), its identity id, or its display name. Must be an agent you own."
|
|
1177
|
+
),
|
|
1178
|
+
text: z2.string().min(1).max(8e3).describe("The message body, as the agent would write it."),
|
|
1179
|
+
to: z2.string().max(200).optional().describe(
|
|
1180
|
+
"Recipient identity id or mosADD address. Defaults to YOU (the key's owner) \u2014 the common case is an agent reporting to its owner. Must be a person, not another agent."
|
|
1181
|
+
),
|
|
1182
|
+
thread_label: z2.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).optional().describe(
|
|
1183
|
+
"Optional thread label (same as mDM_send). Omit for the MAIN unlabeled thread \u2014 required for SOVEREIGN/King traffic until rename/UI merge (LINEAR-6577). A new label opens a new thread."
|
|
1184
|
+
),
|
|
1185
|
+
silent: z2.boolean().optional().describe("Deliver without waking a phone: the message still arrives and shows unread, only the OS push is skipped.")
|
|
1186
|
+
});
|
|
1187
|
+
var mDM_list_my_agents_input = z2.object({});
|
|
1188
|
+
async function mDM_send_as_agent(input, ctx) {
|
|
1189
|
+
ctx.log("debug", "mDM_send_as_agent", { agent: input.agent, thread_label: input.thread_label });
|
|
1190
|
+
return await invokeFunction("mdm-send-as-agent", {
|
|
1191
|
+
agent: input.agent,
|
|
1192
|
+
text: input.text,
|
|
1193
|
+
...input.to ? { to: input.to } : {},
|
|
1194
|
+
...input.thread_label ? { thread_label: input.thread_label } : {},
|
|
1195
|
+
...input.silent ? { silent: true } : {}
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
1198
|
+
async function mDM_list_my_agents(_input, ctx) {
|
|
1199
|
+
ctx.log("debug", "mDM_list_my_agents");
|
|
1200
|
+
return await invokeFunction("mdm-send-as-agent", { action: "list_agents" });
|
|
1201
|
+
}
|
|
1202
|
+
var mdmAsAgentTools = [
|
|
1203
|
+
{
|
|
1204
|
+
name: "mDM_send_as_agent",
|
|
1205
|
+
title: "Send DM as your agent",
|
|
1206
|
+
annotations: { readOnlyHint: false },
|
|
1207
|
+
requires: "network",
|
|
1208
|
+
description: "Send a direct message AS ONE OF YOUR OWN AGENTS instead of as yourself. Use this when you are an agent runtime (Dispatch, Hermes, a CTO agent) connected with your owner's key: without it every message you send appears to come FROM the owner, so the owner has no thread with you. Names the agent by mosADD address, identity id or display name; `to` defaults to the key's owner. Optional `thread_label` selects a named thread (omit = MAIN unlabeled \u2014 required for King/SOVEREIGN until rename lands). The server verifies you OWN that agent \u2014 speaking as someone else's agent, or as another person, is refused. Recipient must be a person: agent-to-agent DM stays blocked.",
|
|
1209
|
+
inputSchema: mDM_send_as_agent_input,
|
|
1210
|
+
handler: mDM_send_as_agent
|
|
1211
|
+
},
|
|
1212
|
+
{
|
|
1213
|
+
name: "mDM_list_my_agents",
|
|
1214
|
+
title: "List your agents",
|
|
1215
|
+
annotations: { readOnlyHint: true },
|
|
1216
|
+
requires: "network",
|
|
1217
|
+
description: "List the agents you are allowed to speak as with mDM_send_as_agent \u2014 every live agent owned by the account behind this key, with its identity id, mosADD address and display name. Call this first when you are unsure which agent identity you hold.",
|
|
1218
|
+
inputSchema: mDM_list_my_agents_input,
|
|
1219
|
+
handler: mDM_list_my_agents
|
|
1220
|
+
}
|
|
1221
|
+
];
|
|
1222
|
+
|
|
1223
|
+
// src/tools/mdm-voice.ts
|
|
1224
|
+
import { z as z3 } from "zod";
|
|
1225
|
+
var PROTOCOL_VERSION3 = "mosadd.chat.v1";
|
|
1226
|
+
var ContactRef2 = z3.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
|
|
1227
|
+
var RoomId = z3.string().min(1).describe("Voice room id (from mDM_call_start's call_invite).");
|
|
1228
|
+
var mDM_call_start_input = z3.object({
|
|
1229
|
+
to: ContactRef2,
|
|
1230
|
+
video: z3.boolean().optional().describe("Request a video call instead of audio-only. Default false."),
|
|
1231
|
+
thread_label: z3.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.")
|
|
1232
|
+
});
|
|
1233
|
+
var mDM_call_answer_input = z3.object({ room_id: RoomId });
|
|
1234
|
+
var mDM_call_end_input = z3.object({
|
|
1235
|
+
room_id: RoomId,
|
|
1236
|
+
to: ContactRef2.optional().describe("If set, also drop a call_end control message in this contact's DM thread."),
|
|
1237
|
+
thread_label: z3.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
|
|
1238
|
+
});
|
|
1239
|
+
var mDM_voice_note_input = z3.object({
|
|
1240
|
+
to: ContactRef2,
|
|
1241
|
+
audio_url: z3.string().url().describe("URL of the recorded audio clip (already uploaded by the client)."),
|
|
1242
|
+
duration_ms: z3.number().int().positive().optional().describe("Clip length in milliseconds, if known."),
|
|
1243
|
+
mime: z3.string().max(120).optional().describe("Audio MIME type, e.g. audio/ogg, audio/mpeg. Default audio/ogg."),
|
|
1244
|
+
thread_label: z3.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
|
|
1245
|
+
});
|
|
1246
|
+
function dmThreadId2(selfId, otherId, label) {
|
|
1247
|
+
const [a, b] = [selfId, otherId].sort();
|
|
1248
|
+
return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
|
|
1249
|
+
}
|
|
1250
|
+
function packEnvelope(obj) {
|
|
1251
|
+
const envelope = { v: PROTOCOL_VERSION3, sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...obj };
|
|
1252
|
+
return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
|
|
1253
|
+
}
|
|
1254
|
+
async function signalDm(ctx, to, threadLabel, envelope) {
|
|
1255
|
+
const dm = ctx.providers.dm;
|
|
1256
|
+
const selfId = await dm.selfId();
|
|
1257
|
+
const threadId = dmThreadId2(selfId, to, threadLabel);
|
|
1258
|
+
const res = await dm.send({ to, threadId, payload: packEnvelope(envelope) });
|
|
1259
|
+
return { message_id: res?.id, thread_id: threadId };
|
|
1260
|
+
}
|
|
1261
|
+
async function mDM_call_start(input, ctx) {
|
|
1262
|
+
const dm = ctx.providers.dm;
|
|
1263
|
+
const selfId = await dm.selfId();
|
|
1264
|
+
const mode = input.video ? "video" : "audio";
|
|
1265
|
+
const label = `dmcall-${dmThreadId2(selfId, input.to).replace(/[^a-zA-Z0-9._-]/g, "-")}`.slice(0, 120);
|
|
1266
|
+
const { roomId } = await ctx.providers.voice.createRoom(label);
|
|
1267
|
+
const ticket = await ctx.providers.voice.joinTicket(roomId);
|
|
1268
|
+
let invited = false;
|
|
1269
|
+
let thread_id = dmThreadId2(selfId, input.to, input.thread_label);
|
|
1270
|
+
try {
|
|
1271
|
+
const sig = await signalDm(ctx, input.to, input.thread_label, {
|
|
1272
|
+
type: "call_invite",
|
|
1273
|
+
room_id: roomId,
|
|
1274
|
+
mode,
|
|
1275
|
+
from: selfId
|
|
1276
|
+
});
|
|
1277
|
+
thread_id = sig.thread_id;
|
|
1278
|
+
invited = true;
|
|
1279
|
+
} catch (e) {
|
|
1280
|
+
ctx.log("warn", "mDM_call_start: invite signal failed (room still usable)", {
|
|
1281
|
+
error: e.message
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
ctx.log("debug", "mDM_call_start", { room_id: roomId, mode, invited });
|
|
1285
|
+
return { room_id: roomId, token: ticket.token, url: ticket.url, identity: ticket.identity, mode, invited, thread_id };
|
|
1286
|
+
}
|
|
1287
|
+
async function mDM_call_answer(input, ctx) {
|
|
1288
|
+
const ticket = await ctx.providers.voice.joinTicket(input.room_id);
|
|
1289
|
+
ctx.log("debug", "mDM_call_answer", { room_id: ticket.roomId, identity: ticket.identity });
|
|
1290
|
+
return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
|
|
1291
|
+
}
|
|
1292
|
+
async function mDM_call_end(input, ctx) {
|
|
1293
|
+
let signalled = false;
|
|
1294
|
+
if (input.to) {
|
|
1295
|
+
try {
|
|
1296
|
+
await signalDm(ctx, input.to, input.thread_label, { type: "call_end", room_id: input.room_id });
|
|
1297
|
+
signalled = true;
|
|
1298
|
+
} catch (e) {
|
|
1299
|
+
ctx.log("warn", "mDM_call_end: hangup signal failed", { error: e.message });
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
ctx.log("debug", "mDM_call_end", { room_id: input.room_id, signalled });
|
|
1303
|
+
return { room_id: input.room_id, signalled };
|
|
1304
|
+
}
|
|
1305
|
+
async function mDM_voice_note(input, ctx) {
|
|
1306
|
+
const sig = await signalDm(ctx, input.to, input.thread_label, {
|
|
1307
|
+
type: "voice_note",
|
|
1308
|
+
audio_url: input.audio_url,
|
|
1309
|
+
duration_ms: input.duration_ms ?? null,
|
|
1310
|
+
mime: input.mime ?? "audio/ogg"
|
|
1311
|
+
});
|
|
1312
|
+
ctx.log("debug", "mDM_voice_note", { thread_id: sig.thread_id });
|
|
1313
|
+
return sig;
|
|
1314
|
+
}
|
|
1315
|
+
var mdmVoiceTools = [
|
|
1316
|
+
{
|
|
1317
|
+
name: "mDM_call_start",
|
|
1318
|
+
title: "Start a voice call",
|
|
1319
|
+
annotations: { readOnlyHint: false },
|
|
1320
|
+
requires: "network",
|
|
1321
|
+
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.",
|
|
1322
|
+
inputSchema: mDM_call_start_input,
|
|
1323
|
+
handler: mDM_call_start
|
|
1324
|
+
},
|
|
1325
|
+
{
|
|
1326
|
+
name: "mDM_call_answer",
|
|
1327
|
+
title: "Answer a voice call",
|
|
1328
|
+
annotations: { readOnlyHint: false },
|
|
1329
|
+
requires: "network",
|
|
1330
|
+
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.",
|
|
1331
|
+
inputSchema: mDM_call_answer_input,
|
|
1332
|
+
handler: mDM_call_answer
|
|
1333
|
+
},
|
|
1334
|
+
{
|
|
1335
|
+
name: "mDM_call_end",
|
|
1336
|
+
title: "End a voice call",
|
|
1337
|
+
annotations: { readOnlyHint: false },
|
|
1338
|
+
requires: "network",
|
|
1339
|
+
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.",
|
|
1340
|
+
inputSchema: mDM_call_end_input,
|
|
1341
|
+
handler: mDM_call_end
|
|
1342
|
+
},
|
|
1343
|
+
{
|
|
1344
|
+
name: "mDM_voice_note",
|
|
1345
|
+
title: "Leave a voice note",
|
|
1346
|
+
annotations: { readOnlyHint: false },
|
|
1347
|
+
requires: "network",
|
|
1348
|
+
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.",
|
|
1349
|
+
inputSchema: mDM_voice_note_input,
|
|
1350
|
+
handler: mDM_voice_note
|
|
1351
|
+
}
|
|
1352
|
+
];
|
|
1353
|
+
|
|
1354
|
+
// src/tools/mirc.ts
|
|
1355
|
+
import { z as z5 } from "zod";
|
|
1356
|
+
|
|
1357
|
+
// src/tools/mirc-members.ts
|
|
1358
|
+
import { z as z4 } from "zod";
|
|
1359
|
+
var ChannelId = z4.string().min(1).max(120).describe("Channel id (UUID). From mIRC_list / mIRC_create.");
|
|
1360
|
+
var MemberIdentity = z4.string().min(1).describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
|
|
1361
|
+
var Role = z4.enum(["superadmin", "admin", "moderator", "member"]).describe("Role to assign. owner = channel creator (not assignable); promote up to one tier below your own.");
|
|
1362
|
+
var mIRC_join_input = z4.object({
|
|
1363
|
+
channel_id: ChannelId,
|
|
1364
|
+
password: z4.string().min(1).optional().describe("Pass only for access_mode=password channels. Private channels cannot be joined directly (403) \u2014 use mIRC_request_access.")
|
|
1365
|
+
});
|
|
1366
|
+
var mIRC_request_access_input = z4.object({
|
|
1367
|
+
channel_id: ChannelId
|
|
1368
|
+
});
|
|
1369
|
+
var InviteRole = z4.enum(["member", "moderator", "admin"]).describe("Role the invitee lands with (default member). Must be strictly below your own role \u2014 the EF applies the same tier rule as mIRC_set_role.");
|
|
1370
|
+
var mIRC_invite_input = z4.object({
|
|
1371
|
+
channel_id: ChannelId,
|
|
1372
|
+
identity_id: z4.string().min(1).describe("Identity id (UUID) of who to add. Your own agents: mDM_list_my_agents \u2192 agents[].identity_id (that list is kind=agent ONLY \u2014 a robot you own is NOT in it; take the robot's identity id from the app's Robots page). People / other people's agents: mDM_list_contacts."),
|
|
1373
|
+
role: InviteRole.optional(),
|
|
1374
|
+
wrapped_group_key: z4.string().optional().describe(
|
|
1375
|
+
"Required on password/private channels that hold a group key: the channel group key wrapped to the INVITEE's identity key (the same material mIRC_approve_request takes). Without it the EF refuses with 400 ('This channel is encrypted \u2014 unlock your vault\u2026'). Open channels: omit."
|
|
1376
|
+
),
|
|
1377
|
+
ttl_seconds: z4.number().int().min(300).max(30 * 86400).optional().describe("Lifetime of an invite CODE (code path only; ignored when the target auto-joins). Default 7 days; the EF clamps to 5 min \u2026 30 days.")
|
|
1378
|
+
});
|
|
1379
|
+
var mIRC_leave_input = z4.object({
|
|
1380
|
+
channel_id: ChannelId
|
|
1381
|
+
});
|
|
1382
|
+
var mIRC_reject_request_input = z4.object({
|
|
1383
|
+
channel_id: ChannelId,
|
|
1384
|
+
identity_id: z4.string().min(1).describe("Identity id of the requester to reject (state=requested; from mIRC_list members).")
|
|
1385
|
+
});
|
|
1386
|
+
var mIRC_approve_request_input = mIRC_reject_request_input.extend({
|
|
1387
|
+
wrapped_group_key: z4.string().optional().describe(
|
|
1388
|
+
"Required to approve a join to a password/private (group-key) channel: the channel group key wrapped to the approved member's identity key. Without it the backend rejects the approval with a 'wrapped_group_key required' error. (Access requests only exist on non-open channels, so this is effectively always required.)"
|
|
1389
|
+
)
|
|
1390
|
+
});
|
|
1391
|
+
var mIRC_kick_input = z4.object({
|
|
1392
|
+
channel_id: ChannelId,
|
|
1393
|
+
identity_id: MemberIdentity
|
|
1394
|
+
// NOTE: a `reason` field used to be advertised here but channel-members-manage
|
|
1395
|
+
// never persists it (no audit row on kick) — removed until the backend logs it
|
|
1396
|
+
// (see consistency ticket) so the tool doesn't claim an audit trail it can't deliver.
|
|
1397
|
+
});
|
|
1398
|
+
var mIRC_ban_input = z4.object({
|
|
1399
|
+
channel_id: ChannelId,
|
|
1400
|
+
identity_id: MemberIdentity
|
|
1401
|
+
// NOTE: `reason` (no storage) and `until` (timed ban) were removed — the EF ban
|
|
1402
|
+
// branch ignores both, so `until` produced a SILENT PERMANENT ban when a caller
|
|
1403
|
+
// asked for a temporary one. Ban is permanent-until-unban; enforced temp-bans +
|
|
1404
|
+
// ban audit are tracked in the consistency ticket.
|
|
1405
|
+
});
|
|
1406
|
+
var mIRC_unban_input = z4.object({
|
|
1407
|
+
channel_id: ChannelId,
|
|
1408
|
+
identity_id: MemberIdentity
|
|
1409
|
+
});
|
|
1410
|
+
var mIRC_set_role_input = z4.object({
|
|
1411
|
+
channel_id: ChannelId,
|
|
1412
|
+
identity_id: MemberIdentity,
|
|
1413
|
+
role: Role
|
|
1414
|
+
});
|
|
1415
|
+
var mIRC_set_ptt_input = z4.object({
|
|
1416
|
+
channel_id: ChannelId,
|
|
1417
|
+
identity_id: MemberIdentity,
|
|
1418
|
+
ptt_enabled: z4.boolean().describe("Allow this member to hold the PTT floor in voice mode.")
|
|
1419
|
+
});
|
|
1420
|
+
async function invokeChannelMembers(action, body, ctx) {
|
|
1421
|
+
const b = { ...body };
|
|
1422
|
+
if ("identity_id" in b) {
|
|
1423
|
+
b.target_identity_id = b.identity_id;
|
|
1424
|
+
delete b.identity_id;
|
|
1425
|
+
}
|
|
1426
|
+
if ("role" in b && action !== "invite") {
|
|
1427
|
+
b.new_role = b.role;
|
|
1428
|
+
delete b.role;
|
|
1429
|
+
}
|
|
1430
|
+
if ("ptt_enabled" in b) {
|
|
1431
|
+
b.can_ptt = b.ptt_enabled;
|
|
1432
|
+
delete b.ptt_enabled;
|
|
1433
|
+
}
|
|
1434
|
+
readSupabaseEnv();
|
|
1435
|
+
ctx.log("debug", `mIRC.${action}`, b);
|
|
1436
|
+
return await invokeFunction("channel-members-manage", { action, ...b });
|
|
1437
|
+
}
|
|
1438
|
+
async function inviteToChannel(input, ctx) {
|
|
1439
|
+
return await invokeChannelMembers("invite", input, ctx);
|
|
1440
|
+
}
|
|
1441
|
+
var mircMembersTools = [
|
|
1442
|
+
{
|
|
1443
|
+
name: "mIRC_join",
|
|
1444
|
+
title: "Join channel",
|
|
1445
|
+
annotations: { readOnlyHint: false },
|
|
1446
|
+
requires: "network",
|
|
1447
|
+
description: "Join a channel as the current user. Pass `password` only for access_mode=password channels; private channels cannot be joined directly (403) \u2014 use mIRC_request_access + approval. Idempotent: an existing active member gets their membership row back (200, no 409).",
|
|
1448
|
+
inputSchema: mIRC_join_input,
|
|
1449
|
+
handler: ((input, ctx) => invokeChannelMembers("join", input, ctx))
|
|
1450
|
+
},
|
|
1451
|
+
{
|
|
1452
|
+
// Własny agent/robot → auto_joined:true (channel_members + space_members + klucz grupy);
|
|
1453
|
+
// człowiek / cudzy agent → kod zaproszenia. Rozgałęzia SERWER (channel-members-manage), nie toolkit.
|
|
1454
|
+
name: "mIRC_invite",
|
|
1455
|
+
title: "Invite / add a member",
|
|
1456
|
+
annotations: { readOnlyHint: false },
|
|
1457
|
+
requires: "network",
|
|
1458
|
+
description: "Add someone to a channel you own or admin (owner/superadmin/admin; you cannot hand out a role equal to or above your own). TWO OUTCOMES, decided server-side by who the target is. (1) An agent or robot YOU OWN joins immediately \u2014 reply {auto_joined:true, member}: the backend writes channel_members AND the linked space_members row (both are required before its posts pass message-send) plus a channel_keys row when you pass wrapped_group_key. No code, nothing to redeem. THIS is the step that lets an agent speak in a channel: mIRC_join adds the KEY's identity (usually you, the human), while channel posts are signed by the AGENT \u2014 a channel created from the toolkit stays mute until its agent is added here (or via invite_agents on mIRC_create). (2) A human, or an agent owned by somebody else, gets an invite code \u2014 reply {invite:{code, expires_at, \u2026}}; hand the code over and they redeem it in the app (+ \u2192 I have an invite code). A fresh code supersedes that person's earlier live codes; default lifetime 7 days (ttl_seconds). Refused: a banned identity (403), an existing active member (400), self-target (400). Rate limit: 20 invites/min per caller. Password/private channels that hold a group key need wrapped_group_key (wrapped to the invitee's identity key) \u2014 the toolkit does not derive group keys, so either supply it as with mIRC_approve_request, or add the member from the mosadd.com member drawer, which wraps it for you.",
|
|
1459
|
+
inputSchema: mIRC_invite_input,
|
|
1460
|
+
handler: ((input, ctx) => inviteToChannel(input, ctx))
|
|
1461
|
+
},
|
|
1462
|
+
{
|
|
1463
|
+
name: "mIRC_request_access",
|
|
1464
|
+
title: "Request channel access",
|
|
1465
|
+
annotations: { readOnlyHint: false },
|
|
1466
|
+
requires: "network",
|
|
1467
|
+
description: "Request access to a password/private channel (your membership goes to state=requested for an admin to approve).",
|
|
1468
|
+
inputSchema: mIRC_request_access_input,
|
|
1469
|
+
handler: ((input, ctx) => invokeChannelMembers("request-access", input, ctx))
|
|
1470
|
+
},
|
|
1471
|
+
{
|
|
1472
|
+
name: "mIRC_leave",
|
|
1473
|
+
title: "Leave channel",
|
|
1474
|
+
annotations: { readOnlyHint: false },
|
|
1475
|
+
requires: "network",
|
|
1476
|
+
description: "Leave a channel as the current user. Owner cannot leave without transferring ownership first.",
|
|
1477
|
+
inputSchema: mIRC_leave_input,
|
|
1478
|
+
handler: ((input, ctx) => invokeChannelMembers("leave", input, ctx))
|
|
1479
|
+
},
|
|
1480
|
+
{
|
|
1481
|
+
name: "mIRC_approve_request",
|
|
1482
|
+
title: "Approve access request",
|
|
1483
|
+
annotations: { readOnlyHint: false },
|
|
1484
|
+
requires: "network",
|
|
1485
|
+
description: "Approve a pending access request (state=requested \u2192 active). Admins / moderators / owner only. Because access requests only exist on non-open (password/private) channels, you must pass wrapped_group_key \u2014 the channel group key wrapped to the approved member's identity key.",
|
|
1486
|
+
inputSchema: mIRC_approve_request_input,
|
|
1487
|
+
handler: ((input, ctx) => invokeChannelMembers("approve-request", input, ctx))
|
|
1488
|
+
},
|
|
1489
|
+
{
|
|
1490
|
+
name: "mIRC_reject_request",
|
|
1491
|
+
title: "Reject access request",
|
|
1492
|
+
annotations: { readOnlyHint: false },
|
|
1493
|
+
requires: "network",
|
|
1494
|
+
description: "Reject a pending access request. Admins / moderators / owner only.",
|
|
1495
|
+
inputSchema: mIRC_reject_request_input,
|
|
1496
|
+
handler: ((input, ctx) => invokeChannelMembers("reject-request", input, ctx))
|
|
1497
|
+
},
|
|
1498
|
+
{
|
|
1499
|
+
name: "mIRC_kick",
|
|
1500
|
+
title: "Kick a member",
|
|
1501
|
+
annotations: { destructiveHint: true },
|
|
1502
|
+
requires: "network",
|
|
1503
|
+
description: "Remove a member from the channel. They can rejoin if not banned. Requires moderator+.",
|
|
1504
|
+
inputSchema: mIRC_kick_input,
|
|
1505
|
+
handler: ((input, ctx) => invokeChannelMembers("kick", input, ctx))
|
|
1506
|
+
},
|
|
1507
|
+
{
|
|
1508
|
+
name: "mIRC_ban",
|
|
1509
|
+
title: "Ban a member",
|
|
1510
|
+
annotations: { destructiveHint: true },
|
|
1511
|
+
requires: "network",
|
|
1512
|
+
description: "Ban a member from the channel. The ban is permanent until you call mIRC_unban. Requires admin+.",
|
|
1513
|
+
inputSchema: mIRC_ban_input,
|
|
1514
|
+
handler: ((input, ctx) => invokeChannelMembers("ban", input, ctx))
|
|
1515
|
+
},
|
|
1516
|
+
{
|
|
1517
|
+
name: "mIRC_unban",
|
|
1518
|
+
title: "Lift a ban",
|
|
1519
|
+
annotations: { readOnlyHint: false },
|
|
1520
|
+
requires: "network",
|
|
1521
|
+
description: "Lift a ban. Requires admin+.",
|
|
1522
|
+
inputSchema: mIRC_unban_input,
|
|
1523
|
+
handler: ((input, ctx) => invokeChannelMembers("unban", input, ctx))
|
|
1524
|
+
},
|
|
1525
|
+
{
|
|
1526
|
+
name: "mIRC_set_role",
|
|
1527
|
+
title: "Set member role",
|
|
1528
|
+
annotations: { readOnlyHint: false },
|
|
1529
|
+
requires: "network",
|
|
1530
|
+
description: "Promote / demote a member. Roles: owner(100) > superadmin(90) > admin(80) > moderator(70) > member(10). No 'guest'. An actor may assign any role below their own tier \u2014 so a superadmin (not only the owner) can promote to admin.",
|
|
1531
|
+
inputSchema: mIRC_set_role_input,
|
|
1532
|
+
handler: ((input, ctx) => invokeChannelMembers("set-role", input, ctx))
|
|
1533
|
+
},
|
|
1534
|
+
{
|
|
1535
|
+
name: "mIRC_set_ptt",
|
|
1536
|
+
title: "Set push-to-talk permission",
|
|
1537
|
+
annotations: { readOnlyHint: false },
|
|
1538
|
+
requires: "network",
|
|
1539
|
+
description: "Grant or revoke PTT floor permission for a member in voice-capable channels (capabilities.ptt=true). Requires moderator+.",
|
|
1540
|
+
inputSchema: mIRC_set_ptt_input,
|
|
1541
|
+
handler: ((input, ctx) => invokeChannelMembers("set-ptt", input, ctx))
|
|
1542
|
+
}
|
|
1543
|
+
];
|
|
1544
|
+
|
|
1545
|
+
// src/tools/mirc.ts
|
|
1546
|
+
var ChannelId2 = z5.string().min(1).max(120).describe("Channel id (UUID). Use mIRC_list to discover available channels.");
|
|
1547
|
+
var AccessMode = z5.enum(["open", "password", "private"]).describe("open: anyone can join \xB7 password: join with a shared password \xB7 private: invite-only.");
|
|
1548
|
+
var Capabilities = z5.object({
|
|
1549
|
+
txt: z5.boolean().default(true),
|
|
1550
|
+
voice: z5.boolean().default(false),
|
|
1551
|
+
files: z5.boolean().default(false),
|
|
1552
|
+
ptt: z5.boolean().default(false),
|
|
1553
|
+
live: z5.boolean().default(false)
|
|
1554
|
+
}).describe("Which modes are enabled: txt (text), voice (group voice), files (file attach), ptt (push-to-talk), live (live stream). Voice/PTT/live are server-relayed via LiveKit \u2014 NOT end-to-end encrypted.").optional();
|
|
1555
|
+
var mIRC_create_input = z5.object({
|
|
1556
|
+
name: z5.string().min(1).max(80).describe("Channel display name."),
|
|
1557
|
+
topic: z5.string().max(500).optional().describe("Optional channel topic/description."),
|
|
1558
|
+
access_mode: AccessMode.default("open"),
|
|
1559
|
+
password: z5.string().min(6).max(120).optional().describe("Password (only for access_mode=password)."),
|
|
1560
|
+
capabilities: Capabilities,
|
|
1561
|
+
discoverable: z5.boolean().optional().describe("List this channel in the PUBLIC directory (mIRC_discover). Honoured ONLY for access_mode=open; ignored for password/private."),
|
|
1562
|
+
wrapped_group_key: z5.string().optional().describe(
|
|
1563
|
+
"Required for access_mode=password|private (these channels are provisioned for group-key text encryption on supported clients): the channel's group key wrapped to the creator's identity key. Open channels ignore it. If omitted on a non-open channel the backend rejects the call with a 'wrapped_group_key required' error."
|
|
1564
|
+
),
|
|
1565
|
+
invite_agents: z5.array(z5.string().min(1)).max(20).optional().describe(
|
|
1566
|
+
"Identity ids (UUID) of YOUR agents/robots to add right after the channel is created (agents: mDM_list_my_agents \u2192 agents[].identity_id; robots are not in that list \u2014 use the identity id from the app's Robots page). Each is fanned out to mIRC_invite: your own agents auto-join (auto_joined:true); anything else gets an invite code. Per-agent failures are reported in invites[] \u2014 the channel itself is still created. Max 20 per call (the invite mint is rate-limited to 20/min). On password/private channels the fan-out cannot carry a per-agent wrapped_group_key \u2014 use mIRC_invite per agent there."
|
|
1567
|
+
)
|
|
1568
|
+
});
|
|
1569
|
+
var mIRC_list_input = z5.object({
|
|
1570
|
+
limit: z5.number().int().min(1).max(500).default(100).optional(),
|
|
1571
|
+
offset: z5.number().int().min(0).default(0).optional()
|
|
1572
|
+
// NOTE: an access_mode filter was removed — channel-manage's list branch doesn't
|
|
1573
|
+
// filter by it (it was a silent no-op). Filter client-side on the returned
|
|
1574
|
+
// access_mode field. Server-side filtering is tracked in the consistency ticket.
|
|
1575
|
+
});
|
|
1576
|
+
var mIRC_get_input = z5.object({
|
|
1577
|
+
channel_id: ChannelId2
|
|
1578
|
+
});
|
|
1579
|
+
var mIRC_update_input = z5.object({
|
|
1580
|
+
channel_id: ChannelId2,
|
|
1581
|
+
name: z5.string().min(1).max(80).optional(),
|
|
1582
|
+
topic: z5.string().max(500).optional(),
|
|
1583
|
+
// NOTE: access_mode was removed — channel-manage's update branch ignores it, and
|
|
1584
|
+
// switching an existing channel to/from an E2EE (password/private) mode needs
|
|
1585
|
+
// group-key handling that isn't wired yet. Recreate the channel to change mode.
|
|
1586
|
+
capabilities: Capabilities,
|
|
1587
|
+
discoverable: z5.boolean().optional().describe("Toggle public-directory listing (open channels only).")
|
|
1588
|
+
});
|
|
1589
|
+
var mIRC_discover_input = z5.object({
|
|
1590
|
+
q: z5.string().max(100).optional().describe("Optional channel-name filter."),
|
|
1591
|
+
limit: z5.number().int().min(1).max(500).default(50).optional(),
|
|
1592
|
+
offset: z5.number().int().min(0).default(0).optional()
|
|
1593
|
+
});
|
|
1594
|
+
var mIRC_report_input = z5.object({
|
|
1595
|
+
channel_id: ChannelId2,
|
|
1596
|
+
reason: z5.enum(["spam", "abuse", "harassment", "illegal", "other"]).describe("Report reason."),
|
|
1597
|
+
detail: z5.string().max(1e3).optional().describe("Optional free-text context.")
|
|
1598
|
+
});
|
|
1599
|
+
var mIRC_delete_input = z5.object({
|
|
1600
|
+
channel_id: ChannelId2
|
|
1601
|
+
});
|
|
1602
|
+
async function mIRC_create(input, ctx) {
|
|
1603
|
+
readSupabaseEnv();
|
|
1604
|
+
ctx.log("debug", "mIRC_create invoking channel-manage", { name: input.name });
|
|
1605
|
+
const { topic, invite_agents, ...rest } = input;
|
|
1606
|
+
const payload = topic !== void 0 ? { ...rest, description: topic } : { ...rest };
|
|
1607
|
+
const created = await invokeFunction("channel-manage", {
|
|
1608
|
+
action: "create",
|
|
1609
|
+
...payload
|
|
1610
|
+
});
|
|
1611
|
+
if (!invite_agents?.length) return created;
|
|
1612
|
+
const channelId = created.channel?.id;
|
|
1613
|
+
if (typeof channelId !== "string" || !channelId) {
|
|
1614
|
+
return {
|
|
1615
|
+
...created,
|
|
1616
|
+
invites: invite_agents.map((identity_id) => ({
|
|
1617
|
+
identity_id,
|
|
1618
|
+
ok: false,
|
|
1619
|
+
error: "channel created but its id was missing from the reply \u2014 call mIRC_invite with the id from mIRC_list"
|
|
1620
|
+
}))
|
|
1621
|
+
};
|
|
1622
|
+
}
|
|
1623
|
+
const invites = [];
|
|
1624
|
+
for (const identity_id of invite_agents) {
|
|
1625
|
+
try {
|
|
1626
|
+
const result = await inviteToChannel({ channel_id: channelId, identity_id }, ctx);
|
|
1627
|
+
invites.push({ identity_id, ok: true, auto_joined: "auto_joined" in result && result.auto_joined === true, result });
|
|
1628
|
+
} catch (e) {
|
|
1629
|
+
invites.push({ identity_id, ok: false, error: e instanceof Error ? e.message : String(e) });
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
return { ...created, invites };
|
|
1633
|
+
}
|
|
1634
|
+
async function mIRC_list(input, ctx) {
|
|
1635
|
+
readSupabaseEnv();
|
|
1636
|
+
ctx.log("debug", "mIRC_list invoking channel-manage");
|
|
1637
|
+
return await invokeFunction("channel-manage", {
|
|
1638
|
+
action: "list",
|
|
1639
|
+
...input
|
|
1640
|
+
});
|
|
1641
|
+
}
|
|
1642
|
+
async function mIRC_get(input, ctx) {
|
|
1643
|
+
readSupabaseEnv();
|
|
1644
|
+
ctx.log("debug", "mIRC_get invoking channel-manage", { channel_id: input.channel_id });
|
|
1645
|
+
return await invokeFunction("channel-manage", {
|
|
1646
|
+
action: "get",
|
|
1647
|
+
channel_id: input.channel_id
|
|
1648
|
+
});
|
|
1649
|
+
}
|
|
1650
|
+
async function mIRC_update(input, ctx) {
|
|
1651
|
+
readSupabaseEnv();
|
|
1652
|
+
ctx.log("debug", "mIRC_update invoking channel-manage", { channel_id: input.channel_id });
|
|
1653
|
+
const { topic, ...rest } = input;
|
|
1654
|
+
const payload = topic !== void 0 ? { ...rest, description: topic } : { ...rest };
|
|
1655
|
+
return await invokeFunction("channel-manage", {
|
|
1656
|
+
action: "update",
|
|
1657
|
+
...payload
|
|
1658
|
+
});
|
|
1659
|
+
}
|
|
1660
|
+
async function mIRC_delete(input, ctx) {
|
|
1661
|
+
readSupabaseEnv();
|
|
1662
|
+
ctx.log("debug", "mIRC_delete invoking channel-manage", { channel_id: input.channel_id });
|
|
1663
|
+
await invokeFunction("channel-manage", {
|
|
1664
|
+
action: "delete",
|
|
1665
|
+
channel_id: input.channel_id
|
|
1666
|
+
});
|
|
1667
|
+
return { deleted: true };
|
|
1668
|
+
}
|
|
1669
|
+
async function mIRC_discover(input, ctx) {
|
|
1670
|
+
readSupabaseEnv();
|
|
1671
|
+
ctx.log("debug", "mIRC_discover invoking channel-manage");
|
|
1672
|
+
return await invokeFunction("channel-manage", {
|
|
1673
|
+
action: "discover",
|
|
1674
|
+
...input
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
async function mIRC_report(input, ctx) {
|
|
1678
|
+
readSupabaseEnv();
|
|
1679
|
+
ctx.log("debug", "mIRC_report invoking report-content", { channel_id: input.channel_id });
|
|
1680
|
+
return await invokeFunction("report-content", {
|
|
1681
|
+
thread_id: `channel:${input.channel_id}`,
|
|
1682
|
+
reason: input.reason,
|
|
1683
|
+
detail: input.detail
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
var mircTools = [
|
|
1687
|
+
{
|
|
1688
|
+
name: "mIRC_create",
|
|
1689
|
+
title: "Create channel",
|
|
1690
|
+
annotations: { readOnlyHint: false },
|
|
1691
|
+
requires: "network",
|
|
1692
|
+
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/voice/files/ptt/live; voice/ptt/live are server-relayed via LiveKit, NOT E2EE). Set discoverable:true (open channels only) to list it in the public directory. NOTE: password/private channels are provisioned for group-key TEXT encryption \u2014 supply wrapped_group_key (the group key wrapped to your identity key); open channels do not need it. The mosadd.com app encrypts/decrypts channel text with that key on supported clients; the toolkit's own mIRC_post_message posts server-readable text today (group-key parity is the next milestone). Channel voice is never E2EE. A channel WITHOUT its agent is a silent room \u2014 pass invite_agents (identity ids of your own agents, from mDM_list_my_agents) to add them in the same call, or call mIRC_invite afterwards.",
|
|
1693
|
+
inputSchema: mIRC_create_input,
|
|
1694
|
+
handler: mIRC_create
|
|
1695
|
+
},
|
|
1696
|
+
{
|
|
1697
|
+
name: "mIRC_list",
|
|
1698
|
+
title: "List your channels",
|
|
1699
|
+
annotations: { readOnlyHint: true },
|
|
1700
|
+
requires: "network",
|
|
1701
|
+
description: "List channels available to the current user.",
|
|
1702
|
+
inputSchema: mIRC_list_input,
|
|
1703
|
+
handler: mIRC_list
|
|
1704
|
+
},
|
|
1705
|
+
{
|
|
1706
|
+
name: "mIRC_get",
|
|
1707
|
+
title: "Get channel details",
|
|
1708
|
+
annotations: { readOnlyHint: true },
|
|
1709
|
+
requires: "network",
|
|
1710
|
+
description: "Get full details of a single channel by id.",
|
|
1711
|
+
inputSchema: mIRC_get_input,
|
|
1712
|
+
handler: mIRC_get
|
|
1713
|
+
},
|
|
1714
|
+
{
|
|
1715
|
+
name: "mIRC_update",
|
|
1716
|
+
title: "Update channel settings",
|
|
1717
|
+
annotations: { readOnlyHint: false },
|
|
1718
|
+
requires: "network",
|
|
1719
|
+
description: "Update channel metadata (name, topic, capabilities). Owner only. Access mode is fixed at creation \u2014 recreate the channel to change it.",
|
|
1720
|
+
inputSchema: mIRC_update_input,
|
|
1721
|
+
handler: mIRC_update
|
|
1722
|
+
},
|
|
1723
|
+
{
|
|
1724
|
+
name: "mIRC_delete",
|
|
1725
|
+
title: "Delete channel",
|
|
1726
|
+
annotations: { destructiveHint: true },
|
|
1727
|
+
requires: "network",
|
|
1728
|
+
description: "Delete a channel and cascade-remove its members. Owner only.",
|
|
1729
|
+
inputSchema: mIRC_delete_input,
|
|
1730
|
+
handler: mIRC_delete
|
|
1731
|
+
},
|
|
1732
|
+
{
|
|
1733
|
+
name: "mIRC_discover",
|
|
1734
|
+
title: "Discover public channels",
|
|
1735
|
+
annotations: { readOnlyHint: true },
|
|
1736
|
+
requires: "network",
|
|
1737
|
+
description: "Browse the PUBLIC channel DIRECTORY \u2014 open channels whose owners opted in (discoverable=true). Returns {id, channel_key, name, description, capabilities, member_count, is_member}. Filter by name with q; paginated. Join a result with mIRC_join (open = one-click). Private/password/partner channels never appear.",
|
|
1738
|
+
inputSchema: mIRC_discover_input,
|
|
1739
|
+
handler: mIRC_discover
|
|
1740
|
+
},
|
|
1741
|
+
{
|
|
1742
|
+
name: "mIRC_report",
|
|
1743
|
+
title: "Report abuse",
|
|
1744
|
+
annotations: { readOnlyHint: false },
|
|
1745
|
+
requires: "network",
|
|
1746
|
+
description: "Report a channel for abuse (spam/harassment/illegal/etc). Metadata + reason only \u2014 never message content. The reported party is the channel owner (server-derived). Use for public-directory moderation.",
|
|
1747
|
+
inputSchema: mIRC_report_input,
|
|
1748
|
+
handler: mIRC_report
|
|
1749
|
+
}
|
|
1750
|
+
];
|
|
1751
|
+
|
|
1752
|
+
// src/tools/mirc-messages.ts
|
|
1753
|
+
import { z as z6 } from "zod";
|
|
1754
|
+
|
|
1755
|
+
// src/crypto/channel-e2ee.ts
|
|
1756
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
1757
|
+
import {
|
|
1758
|
+
decryptText,
|
|
1759
|
+
encryptText,
|
|
1760
|
+
exportX25519KeyPair,
|
|
1761
|
+
fromBase64 as fromBase642,
|
|
1762
|
+
generateX25519KeyPair as generateX25519KeyPair2,
|
|
1763
|
+
toBase64 as toBase642,
|
|
1764
|
+
unwrapGroupKey
|
|
1765
|
+
} from "@mosadd/crypto";
|
|
1766
|
+
function signCiphertext(groupKey, ciphertextB64) {
|
|
1767
|
+
return createHmac("sha256", Buffer.from(groupKey)).update(ciphertextB64, "utf8").digest("base64");
|
|
1768
|
+
}
|
|
1769
|
+
async function encryptWithGroupKey(groupKey, plaintext) {
|
|
1770
|
+
const encrypted = await encryptText(groupKey, plaintext);
|
|
1771
|
+
const hmac = signCiphertext(groupKey, encrypted.ciphertext);
|
|
1772
|
+
return Buffer.from(JSON.stringify({ ...encrypted, hmac }), "utf8").toString("base64");
|
|
1773
|
+
}
|
|
1774
|
+
async function decryptWithGroupKey(groupKey, payloadB64) {
|
|
1775
|
+
try {
|
|
1776
|
+
const decoded = Buffer.from(payloadB64, "base64").toString("utf8");
|
|
1777
|
+
if (!decoded.startsWith("{")) return null;
|
|
1778
|
+
const parsed = JSON.parse(decoded);
|
|
1779
|
+
if (!parsed.iv || !parsed.ciphertext) return null;
|
|
1780
|
+
if (parsed.hmac) {
|
|
1781
|
+
const expected = createHmac("sha256", Buffer.from(groupKey)).update(parsed.ciphertext, "utf8").digest();
|
|
1782
|
+
const got = Buffer.from(parsed.hmac, "base64");
|
|
1783
|
+
if (got.length !== expected.length || !timingSafeEqual(got, expected)) return null;
|
|
1784
|
+
}
|
|
1785
|
+
return await decryptText(groupKey, { iv: parsed.iv, ciphertext: parsed.ciphertext });
|
|
1786
|
+
} catch {
|
|
1787
|
+
return null;
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
function unwrapEnvelopeText(plain) {
|
|
1791
|
+
if (plain.length > 2 && plain.startsWith("{") && plain.endsWith("}") && plain.includes("mosadd.chat")) {
|
|
1792
|
+
try {
|
|
1793
|
+
const env = JSON.parse(plain);
|
|
1794
|
+
if (typeof env.text === "string" && env.v === "mosadd.chat.v1" && (env.type === "text" || env.type === void 0)) {
|
|
1795
|
+
return env.text;
|
|
1796
|
+
}
|
|
1797
|
+
} catch {
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
return plain;
|
|
1801
|
+
}
|
|
1802
|
+
var cachedIdentity = null;
|
|
1803
|
+
var cachedLineKey = null;
|
|
1804
|
+
var provisioning = null;
|
|
1805
|
+
var groupKeyCache = /* @__PURE__ */ new Map();
|
|
1806
|
+
async function resolveIdentity() {
|
|
1807
|
+
if (cachedIdentity) return cachedIdentity;
|
|
1808
|
+
try {
|
|
1809
|
+
readSupabaseEnv();
|
|
1810
|
+
const sb = getSupabase();
|
|
1811
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
1812
|
+
if (ue || !u?.user) return null;
|
|
1813
|
+
const { data: identity, error } = await sb.from("identities").select("id, kind").eq("user_id", u.user.id).maybeSingle();
|
|
1814
|
+
if (error || !identity?.id) return null;
|
|
1815
|
+
cachedIdentity = { id: identity.id, kind: identity.kind ?? null };
|
|
1816
|
+
return cachedIdentity;
|
|
1817
|
+
} catch {
|
|
1818
|
+
return null;
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
async function syncPublishedKey(identityId, publicKeyB64) {
|
|
1822
|
+
try {
|
|
1823
|
+
const sb = getSupabase();
|
|
1824
|
+
const { data: row } = await sb.from("identities").select("signed_prekey_pub").eq("id", identityId).maybeSingle();
|
|
1825
|
+
if (row?.signed_prekey_pub === publicKeyB64) return;
|
|
1826
|
+
const { error } = await sb.from("identities").update({ signed_prekey_pub: publicKeyB64 }).eq("id", identityId);
|
|
1827
|
+
if (error) {
|
|
1828
|
+
cachedIdentity = null;
|
|
1829
|
+
}
|
|
1830
|
+
} catch {
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
async function ensureLineChannelKey() {
|
|
1834
|
+
if (cachedLineKey) return cachedLineKey;
|
|
1835
|
+
if (provisioning) return provisioning;
|
|
1836
|
+
provisioning = (async () => {
|
|
1837
|
+
try {
|
|
1838
|
+
const identity = await resolveIdentity();
|
|
1839
|
+
if (!identity) return null;
|
|
1840
|
+
if (identity.kind !== "agent" && identity.kind !== "robot") return null;
|
|
1841
|
+
const sb = getSupabase();
|
|
1842
|
+
const { data: row, error: readErr } = await sb.from("mosadd_channel_line_keys").select("public_key, private_key").eq("identity_id", identity.id).maybeSingle();
|
|
1843
|
+
if (readErr) return null;
|
|
1844
|
+
if (row?.private_key) {
|
|
1845
|
+
const key2 = { publicKey: fromBase642(row.public_key), privateKey: fromBase642(row.private_key) };
|
|
1846
|
+
await syncPublishedKey(identity.id, row.public_key);
|
|
1847
|
+
cachedLineKey = key2;
|
|
1848
|
+
return key2;
|
|
1849
|
+
}
|
|
1850
|
+
const pair = await generateX25519KeyPair2();
|
|
1851
|
+
const exported = await exportX25519KeyPair(pair);
|
|
1852
|
+
const { data: u } = await sb.auth.getUser();
|
|
1853
|
+
const userId = u?.user?.id;
|
|
1854
|
+
if (!userId) return null;
|
|
1855
|
+
await sb.from("mosadd_channel_line_keys").upsert(
|
|
1856
|
+
{ identity_id: identity.id, user_id: userId, public_key: exported.publicKey, private_key: exported.privateKey, key_version: 1 },
|
|
1857
|
+
{ onConflict: "identity_id", ignoreDuplicates: true }
|
|
1858
|
+
);
|
|
1859
|
+
const { data: winner, error: winnerErr } = await sb.from("mosadd_channel_line_keys").select("public_key, private_key").eq("identity_id", identity.id).maybeSingle();
|
|
1860
|
+
if (winnerErr || !winner?.private_key) return null;
|
|
1861
|
+
await syncPublishedKey(identity.id, winner.public_key);
|
|
1862
|
+
const key = { publicKey: fromBase642(winner.public_key), privateKey: fromBase642(winner.private_key) };
|
|
1863
|
+
cachedLineKey = key;
|
|
1864
|
+
return key;
|
|
1865
|
+
} catch {
|
|
1866
|
+
return null;
|
|
1867
|
+
}
|
|
1868
|
+
})();
|
|
1869
|
+
try {
|
|
1870
|
+
return await provisioning;
|
|
1871
|
+
} finally {
|
|
1872
|
+
provisioning = null;
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
async function getGroupKey(channelId) {
|
|
1876
|
+
const cached = groupKeyCache.get(channelId);
|
|
1877
|
+
if (cached) return cached;
|
|
1878
|
+
try {
|
|
1879
|
+
const lineKey = await ensureLineChannelKey();
|
|
1880
|
+
if (!lineKey) return null;
|
|
1881
|
+
const identity = await resolveIdentity();
|
|
1882
|
+
if (!identity) return null;
|
|
1883
|
+
const sb = getSupabase();
|
|
1884
|
+
const { data: row, error } = await sb.from("channel_keys").select("wrapped_group_key").eq("channel_id", channelId).eq("identity_id", identity.id).order("key_version", { ascending: false }).limit(1).maybeSingle();
|
|
1885
|
+
if (error || !row?.wrapped_group_key) return null;
|
|
1886
|
+
const wrapped = JSON.parse(row.wrapped_group_key);
|
|
1887
|
+
const groupKey = await unwrapGroupKey(wrapped, lineKey.privateKey);
|
|
1888
|
+
groupKeyCache.set(channelId, groupKey);
|
|
1889
|
+
return groupKey;
|
|
1890
|
+
} catch {
|
|
1891
|
+
return null;
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
async function encryptChannelPayload(channelId, plaintext) {
|
|
1895
|
+
const groupKey = await getGroupKey(channelId);
|
|
1896
|
+
if (!groupKey) return null;
|
|
1897
|
+
try {
|
|
1898
|
+
return await encryptWithGroupKey(groupKey, plaintext);
|
|
1899
|
+
} catch {
|
|
1900
|
+
return null;
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
async function decryptChannelPayload(channelId, payloadB64) {
|
|
1904
|
+
const groupKey = await getGroupKey(channelId);
|
|
1905
|
+
if (!groupKey) return null;
|
|
1906
|
+
return decryptWithGroupKey(groupKey, payloadB64);
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
// src/tools/channel-payload.ts
|
|
1910
|
+
var CIPHERTEXT_MARKER = "<ciphertext>";
|
|
1911
|
+
var STRICT_BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
1912
|
+
var CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
|
|
1913
|
+
function isSealedEnvelope(obj) {
|
|
1914
|
+
if (!obj || typeof obj !== "object") return false;
|
|
1915
|
+
const o = obj;
|
|
1916
|
+
if (typeof o.iv === "string" && typeof o.ciphertext === "string") return true;
|
|
1917
|
+
if (typeof o.v === "string" && o.v.startsWith("mosadd.e2ee")) return true;
|
|
1918
|
+
return false;
|
|
1919
|
+
}
|
|
1920
|
+
function decodeStoredPayloadText(payload) {
|
|
1921
|
+
if (typeof payload !== "string" || payload.length === 0) return "";
|
|
1922
|
+
let raw;
|
|
1923
|
+
const compact = payload.replace(/\s+/g, "");
|
|
1924
|
+
if (compact.length % 4 === 0 && STRICT_BASE64.test(compact)) {
|
|
1925
|
+
try {
|
|
1926
|
+
raw = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(compact, "base64"));
|
|
1927
|
+
} catch {
|
|
1928
|
+
return CIPHERTEXT_MARKER;
|
|
1929
|
+
}
|
|
1930
|
+
} else {
|
|
1931
|
+
raw = payload;
|
|
1932
|
+
}
|
|
1933
|
+
if (raw.startsWith("{")) {
|
|
1934
|
+
try {
|
|
1935
|
+
const obj = JSON.parse(raw);
|
|
1936
|
+
if (isSealedEnvelope(obj)) return CIPHERTEXT_MARKER;
|
|
1937
|
+
const text = obj?.text;
|
|
1938
|
+
if (typeof text === "string") return text;
|
|
1939
|
+
return raw;
|
|
1940
|
+
} catch {
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
if (CONTROL_CHARS.test(raw)) return CIPHERTEXT_MARKER;
|
|
1944
|
+
return raw;
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
// src/tools/mirc-messages.ts
|
|
1948
|
+
var PROTOCOL_VERSION4 = "mosadd.chat.v1";
|
|
1949
|
+
var ChannelId3 = z6.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
|
|
1950
|
+
var mIRC_post_message_input = z6.object({
|
|
1951
|
+
channel_id: ChannelId3,
|
|
1952
|
+
text: z6.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
|
|
1953
|
+
reply_to_id: z6.string().optional().describe("Optional id of the message being replied to."),
|
|
1954
|
+
space_id: z6.string().optional().describe("Optional backing space id. Resolved automatically from the channel if omitted."),
|
|
1955
|
+
agent: z6.string().max(200).optional().describe(
|
|
1956
|
+
"Post AS ONE OF YOUR OWN AGENTS instead of as the key's owner \u2014 its mosADD address (<agent>@mosadd.com), its identity id, or its display name. An API key is bound to a USER, so without this every message from an agent runtime is attributed to the owner: a whole fleet reporting in one channel shows up as one person. Same field name and same ownership rule as mDM_send_as_agent. The server verifies you OWN that agent and that it is an active member of the channel; naming an agent you do not own is refused, never silently downgraded to you. Omit it and attribution is unchanged."
|
|
1957
|
+
)
|
|
1958
|
+
});
|
|
1959
|
+
var mIRC_list_messages_input = z6.object({
|
|
1960
|
+
channel_id: ChannelId3,
|
|
1961
|
+
limit: z6.number().int().min(1).max(200).default(50).optional(),
|
|
1962
|
+
cursor: z6.string().optional().describe("Opaque pagination cursor from a prior list response."),
|
|
1963
|
+
space_id: z6.string().optional().describe("Optional backing space id. Resolved automatically if omitted.")
|
|
1964
|
+
});
|
|
1965
|
+
function buildPlaintextEnvelope(text, replyToId) {
|
|
1966
|
+
const envelope = {
|
|
1967
|
+
v: PROTOCOL_VERSION4,
|
|
1968
|
+
type: "text",
|
|
1969
|
+
text,
|
|
1970
|
+
reply_to: replyToId ?? null,
|
|
1971
|
+
sent_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1972
|
+
};
|
|
1973
|
+
return JSON.stringify(envelope);
|
|
1974
|
+
}
|
|
1975
|
+
async function payloadToText(channelId, payload) {
|
|
1976
|
+
const decrypted = await decryptChannelPayload(channelId, payload);
|
|
1977
|
+
if (decrypted !== null) return unwrapEnvelopeText(decrypted);
|
|
1978
|
+
return decodeStoredPayloadText(payload);
|
|
1979
|
+
}
|
|
1980
|
+
async function resolveLinkedSpaceId(channelId) {
|
|
1981
|
+
const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
|
|
1982
|
+
const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
|
|
1983
|
+
if (!spaceId) {
|
|
1984
|
+
throw new Error(
|
|
1985
|
+
`Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, or pass space_id explicitly.`
|
|
1986
|
+
);
|
|
1987
|
+
}
|
|
1988
|
+
return spaceId;
|
|
1989
|
+
}
|
|
1990
|
+
async function mIRC_post_message(input, ctx) {
|
|
1991
|
+
readSupabaseEnv();
|
|
1992
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
|
|
1993
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
1994
|
+
ctx.log("debug", "mIRC_post_message", { thread_id, space_id, agent: input.agent });
|
|
1995
|
+
const envelope = buildPlaintextEnvelope(input.text, input.reply_to_id);
|
|
1996
|
+
const encrypted = await encryptChannelPayload(input.channel_id, envelope);
|
|
1997
|
+
const payload = encrypted ?? Buffer.from(envelope, "utf8").toString("base64");
|
|
1998
|
+
const data = await invokeFunction("message-send", {
|
|
1999
|
+
space_id,
|
|
2000
|
+
thread_id,
|
|
2001
|
+
encrypted_payload: payload,
|
|
2002
|
+
message_type: "txt",
|
|
2003
|
+
protocol_version: PROTOCOL_VERSION4,
|
|
2004
|
+
reply_to_id: input.reply_to_id ?? null,
|
|
2005
|
+
// Attribution is decided SERVER-SIDE (message-send → _shared/ownedAgent.ts): you may sign only
|
|
2006
|
+
// as an agent you own. Sent only when asked for, so the wire shape is unchanged for every
|
|
2007
|
+
// existing caller — and an unresolvable agent comes back 403 rather than posting as the owner.
|
|
2008
|
+
...input.agent ? { agent: input.agent } : {}
|
|
2009
|
+
});
|
|
2010
|
+
if (!data?.message?.id) throw new Error("message-send returned no message id");
|
|
2011
|
+
return {
|
|
2012
|
+
message_id: data.message.id,
|
|
2013
|
+
delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
2014
|
+
thread_id,
|
|
2015
|
+
// Echo back WHO the message was signed as, so a caller can verify the attribution landed
|
|
2016
|
+
// instead of assuming it did.
|
|
2017
|
+
...data.sent_as ? { sent_as: data.sent_as } : {}
|
|
2018
|
+
};
|
|
2019
|
+
}
|
|
2020
|
+
async function mIRC_list_messages(input, ctx) {
|
|
2021
|
+
readSupabaseEnv();
|
|
2022
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
|
|
2023
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
2024
|
+
ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
|
|
2025
|
+
const data = await invokeFunction("message-list", {
|
|
2026
|
+
space_id,
|
|
2027
|
+
thread_id,
|
|
2028
|
+
limit: input.limit ?? 50,
|
|
2029
|
+
before: input.cursor
|
|
2030
|
+
});
|
|
2031
|
+
const messages = [];
|
|
2032
|
+
for (const m of data?.messages ?? []) {
|
|
2033
|
+
messages.push({
|
|
2034
|
+
id: m.id,
|
|
2035
|
+
sender_identity_id: m.sender_identity_id,
|
|
2036
|
+
text: formatVoiceIfAny(await payloadToText(input.channel_id, m.encrypted_payload)),
|
|
2037
|
+
timestamp: m.created_at
|
|
2038
|
+
});
|
|
2039
|
+
}
|
|
2040
|
+
return {
|
|
2041
|
+
messages,
|
|
2042
|
+
next_cursor: data?.next_before ?? data?.cursor ?? null
|
|
2043
|
+
};
|
|
2044
|
+
}
|
|
2045
|
+
var mircMessagesTools = [
|
|
2046
|
+
{
|
|
2047
|
+
name: "mIRC_post_message",
|
|
2048
|
+
title: "Post channel message",
|
|
2049
|
+
annotations: { readOnlyHint: false },
|
|
2050
|
+
requires: "network",
|
|
2051
|
+
description: "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. This is how an agent actually talks in a channel \u2014 the other mIRC_* tools only manage it. ACCESS: banned/blocked users are refused on ALL access modes (including open); open channels accept anyone not banned; password channels require joining with the password; private channels require request-access + approval. ATTRIBUTION: by default the message is signed with the identity behind the API key \u2014 and a key belongs to a USER, so an agent runtime using its owner's key posts as the OWNER. Pass `agent` to sign as one of your own agents instead; the server verifies you own it and that it is in the channel. ENCRYPTION: when your line holds the channel's group key (password/private channels where a wrapped key row exists for your identity \u2014 it is auto-provisioned on first use), the message is sealed AES-256-GCM + HMAC exactly like the app, so members read it as normal channel text. Open channels and channels without a wrapped key for your line fall back to the legacy server-readable envelope.",
|
|
2052
|
+
inputSchema: mIRC_post_message_input,
|
|
2053
|
+
handler: mIRC_post_message
|
|
2054
|
+
},
|
|
2055
|
+
{
|
|
2056
|
+
name: "mIRC_list_messages",
|
|
2057
|
+
title: "Read channel messages",
|
|
2058
|
+
annotations: { readOnlyHint: true },
|
|
2059
|
+
requires: "network",
|
|
2060
|
+
description: "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically. ENCRYPTION: messages your line can decrypt (group-key channels \u2014 auto-provisioned key material) come back as readable text; everything else is decoded as written: the app's plain text and the toolkit's JSON envelope both come back as readable text (open channels such as #adm and #command are never encrypted). Only a sealed group-key envelope your line holds no key for reads <ciphertext>.",
|
|
2061
|
+
inputSchema: mIRC_list_messages_input,
|
|
2062
|
+
handler: mIRC_list_messages
|
|
2063
|
+
}
|
|
2064
|
+
];
|
|
2065
|
+
|
|
2066
|
+
// src/tools/mirc-edge.ts
|
|
2067
|
+
import { z as z7 } from "zod";
|
|
2068
|
+
var DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
|
|
2069
|
+
var DEFAULT_SUPABASE_URL = "https://api.mosadd.com";
|
|
2070
|
+
function edgeUrl() {
|
|
2071
|
+
return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
|
|
2072
|
+
}
|
|
2073
|
+
function supabaseUrl() {
|
|
2074
|
+
return process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ?? process.env.SUPABASE_URL?.replace(/\/$/, "") ?? DEFAULT_SUPABASE_URL;
|
|
2075
|
+
}
|
|
2076
|
+
function hubKey() {
|
|
2077
|
+
const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
|
|
2078
|
+
if (!key) throw new Error("MOSADD_API_KEY required for mIRC edge tools (see mosadd login or hub-keys).");
|
|
2079
|
+
return key;
|
|
2080
|
+
}
|
|
2081
|
+
var mIRC_send_edge_input = z7.object({
|
|
2082
|
+
channel_id: z7.string().min(1).max(128).describe("Channel id (UUID). Same as mIRC_create / mIRC_list."),
|
|
2083
|
+
text: z7.string().min(1).max(64e3).describe("Message body (UTF-8, max 64 KB)."),
|
|
2084
|
+
from: z7.string().max(120).optional().describe("Sender hint shown to other clients (defaults to the hub-key owner).")
|
|
2085
|
+
});
|
|
2086
|
+
async function mIRC_send_edge(input, ctx) {
|
|
2087
|
+
ctx.log("debug", "mIRC_send_edge", { channel_id: input.channel_id });
|
|
2088
|
+
const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/send`, {
|
|
2089
|
+
method: "POST",
|
|
2090
|
+
headers: {
|
|
2091
|
+
"Content-Type": "application/json",
|
|
2092
|
+
Authorization: `Bearer ${hubKey()}`
|
|
2093
|
+
},
|
|
2094
|
+
body: JSON.stringify({ text: input.text, from: input.from })
|
|
2095
|
+
});
|
|
2096
|
+
if (!r.ok) {
|
|
2097
|
+
const errBody = await r.text().catch(() => "");
|
|
2098
|
+
throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
|
|
2099
|
+
}
|
|
2100
|
+
const data = await r.json();
|
|
2101
|
+
if (!data?.id) throw new Error("mosadd-edge: send returned no id");
|
|
2102
|
+
return { message_id: data.id, delivered_at: data.ts ?? Date.now(), channel_id: input.channel_id };
|
|
2103
|
+
}
|
|
2104
|
+
var mIRC_history_edge_input = z7.object({
|
|
2105
|
+
channel_id: z7.string().min(1).max(128).describe("Channel id (UUID)."),
|
|
2106
|
+
limit: z7.number().int().min(1).max(100).default(50).optional().describe("How many recent messages to return (max 100, the DO ring size).")
|
|
2107
|
+
});
|
|
2108
|
+
async function mIRC_history_edge(input, ctx) {
|
|
2109
|
+
const limit = input.limit ?? 50;
|
|
2110
|
+
ctx.log("debug", "mIRC_history_edge", { channel_id: input.channel_id, limit });
|
|
2111
|
+
const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/history?limit=${limit}`, {
|
|
2112
|
+
headers: { Authorization: `Bearer ${hubKey()}` }
|
|
2113
|
+
});
|
|
2114
|
+
if (!r.ok) {
|
|
2115
|
+
const errBody = await r.text().catch(() => "");
|
|
2116
|
+
throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
|
|
2117
|
+
}
|
|
2118
|
+
const data = await r.json();
|
|
2119
|
+
return {
|
|
2120
|
+
channel_id: input.channel_id,
|
|
2121
|
+
messages: (data.messages ?? []).map((m) => ({
|
|
2122
|
+
id: m.id,
|
|
2123
|
+
from: m.from ?? null,
|
|
2124
|
+
text: m.text,
|
|
2125
|
+
timestamp: m.ts
|
|
2126
|
+
}))
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
var mIRC_mint_channel_token_input = z7.object({
|
|
2130
|
+
channel_id: z7.string().min(1).max(128).describe("Channel id \u2014 the JWT will be scoped to this channel only. Must match the WS upgrade path."),
|
|
2131
|
+
user_id: z7.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).")
|
|
2132
|
+
});
|
|
2133
|
+
async function mIRC_mint_channel_token(input, ctx) {
|
|
2134
|
+
ctx.log("debug", "mIRC_mint_channel_token", { channel_id: input.channel_id });
|
|
2135
|
+
const r = await fetch(`${supabaseUrl()}/functions/v1/hub-mint-channel-token`, {
|
|
2136
|
+
method: "POST",
|
|
2137
|
+
headers: {
|
|
2138
|
+
"Content-Type": "application/json",
|
|
2139
|
+
Authorization: `Bearer ${hubKey()}`
|
|
2140
|
+
},
|
|
2141
|
+
body: JSON.stringify({ channel_id: input.channel_id, user_id: input.user_id })
|
|
2142
|
+
});
|
|
2143
|
+
if (!r.ok) {
|
|
2144
|
+
const errBody = await r.text().catch(() => "");
|
|
2145
|
+
throw new Error(`hub-mint-channel-token ${r.status}: ${errBody.slice(0, 200)}`);
|
|
2146
|
+
}
|
|
2147
|
+
const data = await r.json();
|
|
2148
|
+
if (!data?.token || !data?.expires_in || !data?.channel_id || !data?.scope) {
|
|
2149
|
+
throw new Error("hub-mint-channel-token: malformed response");
|
|
2150
|
+
}
|
|
2151
|
+
return data;
|
|
2152
|
+
}
|
|
2153
|
+
var mircEdgeTools = [
|
|
2154
|
+
{
|
|
2155
|
+
name: "mIRC_mint_channel_token",
|
|
2156
|
+
title: "Mint channel token",
|
|
2157
|
+
annotations: { readOnlyHint: false },
|
|
2158
|
+
requires: "network",
|
|
2159
|
+
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.",
|
|
2160
|
+
inputSchema: mIRC_mint_channel_token_input,
|
|
2161
|
+
handler: mIRC_mint_channel_token
|
|
2162
|
+
},
|
|
2163
|
+
{
|
|
2164
|
+
name: "mIRC_send_edge",
|
|
2165
|
+
title: "Send message (low-latency edge)",
|
|
2166
|
+
annotations: { readOnlyHint: false },
|
|
2167
|
+
requires: "network",
|
|
2168
|
+
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).",
|
|
2169
|
+
inputSchema: mIRC_send_edge_input,
|
|
2170
|
+
handler: mIRC_send_edge
|
|
2171
|
+
},
|
|
2172
|
+
{
|
|
2173
|
+
name: "mIRC_history_edge",
|
|
2174
|
+
title: "Read channel history (edge)",
|
|
2175
|
+
annotations: { readOnlyHint: true },
|
|
2176
|
+
requires: "network",
|
|
2177
|
+
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.",
|
|
2178
|
+
inputSchema: mIRC_history_edge_input,
|
|
2179
|
+
handler: mIRC_history_edge
|
|
2180
|
+
}
|
|
2181
|
+
];
|
|
2182
|
+
|
|
2183
|
+
// src/tools/mail.ts
|
|
2184
|
+
import { z as z8 } from "zod";
|
|
2185
|
+
var EmailAddress = z8.string().email().max(254).describe("RFC 5321 email address.");
|
|
2186
|
+
var MessageId = z8.string().min(1).describe("Message id (UUID) from mAYL_send or inbox.");
|
|
2187
|
+
var mp0st_send_input = z8.object({
|
|
2188
|
+
to: z8.union([EmailAddress, z8.array(EmailAddress).min(1).max(50)]).describe(
|
|
2189
|
+
"Recipient(s). Single address or array of up to 50."
|
|
2190
|
+
),
|
|
2191
|
+
subject: z8.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
|
|
2192
|
+
body_text: z8.string().max(1048576).optional().describe("Plain text body. Max 1 MB."),
|
|
2193
|
+
body_html: z8.string().max(1048576).optional().describe("HTML body. Max 1 MB."),
|
|
2194
|
+
cc: z8.array(EmailAddress).max(50).optional(),
|
|
2195
|
+
bcc: z8.array(EmailAddress).max(50).optional(),
|
|
2196
|
+
reply_to: EmailAddress.optional(),
|
|
2197
|
+
tracking: z8.boolean().optional().describe("Open-pixel + link-click tracking. Default true. Set false to send with NO tracking (privacy / GDPR-friendly)."),
|
|
2198
|
+
force_reader: z8.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."),
|
|
2199
|
+
disclose_tracking: z8.boolean().optional().describe("Default false. If true (and tracking on), append a tracking-disclosure footer to the email \u2014 recommended for GDPR/ePrivacy compliance."),
|
|
2200
|
+
watermark: z8.union([z8.boolean(), z8.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."),
|
|
2201
|
+
auto_destruct: z8.enum(["1h", "24h", "7d"]).optional().describe("Self-destruct timer: the secure-reader link expires after this window.")
|
|
2202
|
+
});
|
|
2203
|
+
var mp0st_view_input = z8.object({
|
|
2204
|
+
message_id: MessageId
|
|
2205
|
+
});
|
|
2206
|
+
var mp0st_delete_input = z8.object({
|
|
2207
|
+
message_id: MessageId
|
|
2208
|
+
});
|
|
2209
|
+
var mp0st_list_input = z8.object({
|
|
2210
|
+
direction: z8.enum(["inbound", "outbound"]).optional().describe("Filter to received (inbound) or sent (outbound) mail. Omit for both."),
|
|
2211
|
+
limit: z8.number().int().min(1).max(200).optional().describe("Max emails to return. Default 50."),
|
|
2212
|
+
before: z8.string().optional().describe("Pagination cursor: pass the previous response's next_cursor to get the next (older) page.")
|
|
2213
|
+
});
|
|
2214
|
+
var mp0st_stats_input = z8.object({
|
|
2215
|
+
message_id: MessageId
|
|
2216
|
+
});
|
|
2217
|
+
var mp0st_events_input = z8.object({
|
|
2218
|
+
message_id: MessageId
|
|
2219
|
+
});
|
|
2220
|
+
var mp0st_metrics_input = z8.object({});
|
|
2221
|
+
var mp0st_revoke_input = z8.object({
|
|
2222
|
+
message_id: MessageId,
|
|
2223
|
+
restore: z8.boolean().optional().describe("Set true to UN-revoke (restore access). Default false = revoke.")
|
|
2224
|
+
});
|
|
2225
|
+
var mp0st_audit_export_input = z8.object({
|
|
2226
|
+
message_id: MessageId
|
|
2227
|
+
});
|
|
2228
|
+
var mp0st_consent_input = z8.object({
|
|
2229
|
+
action: z8.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."),
|
|
2230
|
+
recipient: EmailAddress.optional().describe("Required for 'check' and 'optin'.")
|
|
2231
|
+
});
|
|
2232
|
+
var mp0st_notify_input = z8.object({
|
|
2233
|
+
since: z8.string().optional().describe("ISO-8601 cursor \u2014 return only events newer than this. Pass the previous response's `cursor` to poll for new activity."),
|
|
2234
|
+
limit: z8.number().int().min(1).max(200).optional().describe("Max events. Default 50.")
|
|
2235
|
+
});
|
|
2236
|
+
async function mp0st_send(input, ctx) {
|
|
2237
|
+
readSupabaseEnv();
|
|
2238
|
+
if (!input.body_text && !input.body_html) {
|
|
2239
|
+
throw new Error("mp0st_send requires at least one of body_text or body_html.");
|
|
2240
|
+
}
|
|
2241
|
+
ctx.log("debug", "mp0st_send invoking mp0st-send", { to: input.to });
|
|
2242
|
+
const res = await invokeFunction("mp0st-send", input);
|
|
2243
|
+
if (res.error) throw new Error(res.error);
|
|
2244
|
+
return { message_id: res.email_id ?? "", status: res.status ?? "sent", is_internal: res.is_internal ?? false };
|
|
2245
|
+
}
|
|
2246
|
+
async function mp0st_view(input, ctx) {
|
|
2247
|
+
readSupabaseEnv();
|
|
2248
|
+
ctx.log("debug", "mp0st_view invoking mp0st-get", { message_id: input.message_id });
|
|
2249
|
+
return await invokeFunction("mp0st-get", { message_id: input.message_id });
|
|
2250
|
+
}
|
|
2251
|
+
async function mp0st_list(input, ctx) {
|
|
2252
|
+
readSupabaseEnv();
|
|
2253
|
+
ctx.log("debug", "mp0st_list invoking mp0st-list", { direction: input.direction });
|
|
2254
|
+
return await invokeFunction("mp0st-list", {
|
|
2255
|
+
direction: input.direction ?? null,
|
|
2256
|
+
limit: input.limit ?? 50,
|
|
2257
|
+
before: input.before ?? null
|
|
2258
|
+
});
|
|
2259
|
+
}
|
|
2260
|
+
async function mp0st_delete(input, ctx) {
|
|
2261
|
+
readSupabaseEnv();
|
|
2262
|
+
ctx.log("debug", "mp0st_delete invoking mp0st-delete", { message_id: input.message_id });
|
|
2263
|
+
return await invokeFunction("mp0st-delete", {
|
|
2264
|
+
message_id: input.message_id
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
async function mp0st_stats(input, ctx) {
|
|
2268
|
+
readSupabaseEnv();
|
|
2269
|
+
ctx.log("debug", "mp0st_stats invoking mp0st-stats", { message_id: input.message_id });
|
|
2270
|
+
return await invokeFunction("mp0st-stats", {
|
|
2271
|
+
message_id: input.message_id
|
|
2272
|
+
});
|
|
2273
|
+
}
|
|
2274
|
+
async function mp0st_events(input, ctx) {
|
|
2275
|
+
readSupabaseEnv();
|
|
2276
|
+
ctx.log("debug", "mp0st_events invoking mp0st-stats", { message_id: input.message_id });
|
|
2277
|
+
return await invokeFunction("mp0st-stats", { message_id: input.message_id, events: true });
|
|
2278
|
+
}
|
|
2279
|
+
async function mp0st_metrics(_input, ctx) {
|
|
2280
|
+
readSupabaseEnv();
|
|
2281
|
+
ctx.log("debug", "mp0st_metrics invoking mp0st-stats");
|
|
2282
|
+
return await invokeFunction("mp0st-stats", {});
|
|
2283
|
+
}
|
|
2284
|
+
async function mp0st_revoke(input, ctx) {
|
|
2285
|
+
readSupabaseEnv();
|
|
2286
|
+
ctx.log("debug", "mp0st_revoke invoking mp0st-revoke", { message_id: input.message_id, restore: !!input.restore });
|
|
2287
|
+
return await invokeFunction("mp0st-revoke", {
|
|
2288
|
+
message_id: input.message_id,
|
|
2289
|
+
restore: input.restore ?? false
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2292
|
+
async function mp0st_audit_export(input, ctx) {
|
|
2293
|
+
readSupabaseEnv();
|
|
2294
|
+
ctx.log("debug", "mp0st_audit_export invoking mp0st-audit", { message_id: input.message_id });
|
|
2295
|
+
return await invokeFunction("mp0st-audit", { message_id: input.message_id });
|
|
2296
|
+
}
|
|
2297
|
+
async function mp0st_consent(input, ctx) {
|
|
2298
|
+
readSupabaseEnv();
|
|
2299
|
+
if ((input.action === "check" || input.action === "optin") && !input.recipient) {
|
|
2300
|
+
throw new Error(`mp0st_consent action '${input.action}' requires a 'recipient' email address.`);
|
|
2301
|
+
}
|
|
2302
|
+
ctx.log("debug", "mp0st_consent invoking mp0st-consent", { action: input.action });
|
|
2303
|
+
return await invokeFunction("mp0st-consent", { action: input.action, recipient: input.recipient ?? null });
|
|
2304
|
+
}
|
|
2305
|
+
async function mp0st_notify(input, ctx) {
|
|
2306
|
+
readSupabaseEnv();
|
|
2307
|
+
ctx.log("debug", "mp0st_notify invoking mp0st-notify", { since: input.since });
|
|
2308
|
+
return await invokeFunction("mp0st-notify", { action: "feed", since: input.since ?? null, limit: input.limit ?? 50 });
|
|
2309
|
+
}
|
|
2310
|
+
var mailTools = [
|
|
2311
|
+
{
|
|
2312
|
+
name: "mAYL_list",
|
|
2313
|
+
title: "List emails",
|
|
2314
|
+
annotations: { readOnlyHint: true },
|
|
2315
|
+
requires: "network",
|
|
2316
|
+
description: "List the user's mailbox (their <userId>@mosadd.com inbox/outbox) newest-first, with sender, subject, status and a short snippet. Filter by direction ('inbound' = received, 'outbound' = sent). Use the returned next_cursor with `before` to page through older mail. Call mAYL_view to read a full message body.",
|
|
2317
|
+
inputSchema: mp0st_list_input,
|
|
2318
|
+
handler: mp0st_list
|
|
2319
|
+
},
|
|
2320
|
+
{
|
|
2321
|
+
name: "mAYL_send",
|
|
2322
|
+
title: "Send email",
|
|
2323
|
+
annotations: { readOnlyHint: false },
|
|
2324
|
+
requires: "network",
|
|
2325
|
+
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').",
|
|
2326
|
+
inputSchema: mp0st_send_input,
|
|
2327
|
+
handler: mp0st_send
|
|
2328
|
+
},
|
|
2329
|
+
{
|
|
2330
|
+
name: "mAYL_view",
|
|
2331
|
+
title: "Read an email",
|
|
2332
|
+
annotations: { readOnlyHint: true },
|
|
2333
|
+
requires: "network",
|
|
2334
|
+
description: "Read the full body and metadata of an email by message_id.",
|
|
2335
|
+
inputSchema: mp0st_view_input,
|
|
2336
|
+
handler: mp0st_view
|
|
2337
|
+
},
|
|
2338
|
+
{
|
|
2339
|
+
name: "mAYL_delete",
|
|
2340
|
+
title: "Delete email",
|
|
2341
|
+
annotations: { destructiveHint: true },
|
|
2342
|
+
requires: "network",
|
|
2343
|
+
description: "Delete one of the user's emails by message_id (from mAYL_list). Soft-delete \u2014 it stops showing in mAYL_list. Owner-scoped: only your own mail.",
|
|
2344
|
+
inputSchema: mp0st_delete_input,
|
|
2345
|
+
handler: mp0st_delete
|
|
2346
|
+
},
|
|
2347
|
+
{
|
|
2348
|
+
name: "mAYL_stats",
|
|
2349
|
+
title: "Email delivery stats",
|
|
2350
|
+
annotations: { readOnlyHint: true },
|
|
2351
|
+
requires: "network",
|
|
2352
|
+
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.",
|
|
2353
|
+
inputSchema: mp0st_stats_input,
|
|
2354
|
+
handler: mp0st_stats
|
|
2355
|
+
},
|
|
2356
|
+
{
|
|
2357
|
+
name: "mAYL_events",
|
|
2358
|
+
title: "Email event trail",
|
|
2359
|
+
annotations: { readOnlyHint: true },
|
|
2360
|
+
requires: "network",
|
|
2361
|
+
description: "Raw engagement timeline for one email (by message_id): every tracked event (pixel_open, link_click, forwarded, page_view, copy/print/focus signals) with timestamp, device type and link URL. Use mAYL_stats for the rollup; use this for the per-event detail. Owner-scoped.",
|
|
2362
|
+
inputSchema: mp0st_events_input,
|
|
2363
|
+
handler: mp0st_events
|
|
2364
|
+
},
|
|
2365
|
+
{
|
|
2366
|
+
name: "mAYL_metrics",
|
|
2367
|
+
title: "Email engagement metrics",
|
|
2368
|
+
annotations: { readOnlyHint: true },
|
|
2369
|
+
requires: "network",
|
|
2370
|
+
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.",
|
|
2371
|
+
inputSchema: mp0st_metrics_input,
|
|
2372
|
+
handler: mp0st_metrics
|
|
2373
|
+
},
|
|
2374
|
+
{
|
|
2375
|
+
name: "mAYL_revoke",
|
|
2376
|
+
title: "Revoke a sent email",
|
|
2377
|
+
annotations: { destructiveHint: true },
|
|
2378
|
+
requires: "network",
|
|
2379
|
+
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.",
|
|
2380
|
+
inputSchema: mp0st_revoke_input,
|
|
2381
|
+
handler: mp0st_revoke
|
|
2382
|
+
},
|
|
2383
|
+
{
|
|
2384
|
+
name: "mAYL_audit_export",
|
|
2385
|
+
title: "Export signed audit report",
|
|
2386
|
+
annotations: { readOnlyHint: true },
|
|
2387
|
+
requires: "network",
|
|
2388
|
+
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.",
|
|
2389
|
+
inputSchema: mp0st_audit_export_input,
|
|
2390
|
+
handler: mp0st_audit_export
|
|
2391
|
+
},
|
|
2392
|
+
{
|
|
2393
|
+
name: "mAYL_consent",
|
|
2394
|
+
title: "Manage tracking opt-outs",
|
|
2395
|
+
annotations: { readOnlyHint: false },
|
|
2396
|
+
requires: "network",
|
|
2397
|
+
description: "Manage recipient tracking opt-outs (GDPR/ePrivacy). action 'list' = recipients who opted out of your tracking; 'check' {recipient} = whether one opted out; 'optin' {recipient} = re-enable. Recipients self-opt-out via the footer link in your tracked emails; mAYL_send then automatically sends them with NO pixel/link-wrap. Owner-scoped.",
|
|
2398
|
+
inputSchema: mp0st_consent_input,
|
|
2399
|
+
handler: mp0st_consent
|
|
2400
|
+
},
|
|
2401
|
+
{
|
|
2402
|
+
name: "mAYL_notify",
|
|
2403
|
+
title: "Engagement notifications feed",
|
|
2404
|
+
annotations: { readOnlyHint: true },
|
|
2405
|
+
requires: "network",
|
|
2406
|
+
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.",
|
|
2407
|
+
inputSchema: mp0st_notify_input,
|
|
2408
|
+
handler: mp0st_notify
|
|
2409
|
+
}
|
|
2410
|
+
];
|
|
2411
|
+
|
|
2412
|
+
// src/tools/mail-provenance.ts
|
|
2413
|
+
import { z as z9 } from "zod";
|
|
2414
|
+
var DEFAULT_SUPABASE_URL2 = "https://api.mosadd.com";
|
|
2415
|
+
function supabaseUrl2() {
|
|
2416
|
+
return process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ?? process.env.SUPABASE_URL?.replace(/\/$/, "") ?? DEFAULT_SUPABASE_URL2;
|
|
2417
|
+
}
|
|
2418
|
+
function hubKey2() {
|
|
2419
|
+
return process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? null;
|
|
2420
|
+
}
|
|
2421
|
+
var EmailAddress2 = z9.string().email().max(254);
|
|
2422
|
+
var mp0st_send_as_agent_input = z9.object({
|
|
2423
|
+
to: z9.union([EmailAddress2, z9.array(EmailAddress2).min(1).max(50)]),
|
|
2424
|
+
subject: z9.string().min(1).max(998),
|
|
2425
|
+
body_text: z9.string().max(1048576).optional(),
|
|
2426
|
+
body_html: z9.string().max(1048576).optional(),
|
|
2427
|
+
cc: z9.array(EmailAddress2).max(50).optional(),
|
|
2428
|
+
bcc: z9.array(EmailAddress2).max(50).optional(),
|
|
2429
|
+
reply_to: EmailAddress2.optional(),
|
|
2430
|
+
tracking: z9.boolean().optional(),
|
|
2431
|
+
agent_id: z9.string().min(1).max(120).describe("Stable id of the agent doing the send. Stamped as sent_by_agent_id for provenance."),
|
|
2432
|
+
task_id: z9.string().min(1).max(120).optional().describe("Optional id of the task/run this send belongs to. Stamped as sent_by_task_id.")
|
|
2433
|
+
});
|
|
2434
|
+
async function mintHubClaim(agentId, taskId) {
|
|
2435
|
+
const key = hubKey2();
|
|
2436
|
+
if (!key) {
|
|
2437
|
+
throw new Error("mAYL_send_as_agent needs MOSADD_API_KEY (hub key) to mint a provenance claim.");
|
|
2438
|
+
}
|
|
2439
|
+
const r = await fetch(`${supabaseUrl2()}/functions/v1/hub-claim-mint`, {
|
|
2440
|
+
method: "POST",
|
|
2441
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
|
|
2442
|
+
body: JSON.stringify({ agent_id: agentId, task_id: taskId ?? null })
|
|
2443
|
+
});
|
|
2444
|
+
if (!r.ok) {
|
|
2445
|
+
const b = await r.text().catch(() => "");
|
|
2446
|
+
throw new Error(`hub-claim-mint ${r.status}: ${b.slice(0, 200)}`);
|
|
2447
|
+
}
|
|
2448
|
+
const data = await r.json();
|
|
2449
|
+
if (!data?.access_token) throw new Error("hub-claim-mint: no access_token in response");
|
|
2450
|
+
return data.access_token;
|
|
2451
|
+
}
|
|
2452
|
+
async function mAYL_send_as_agent(input, ctx) {
|
|
2453
|
+
if (!input.body_text && !input.body_html) {
|
|
2454
|
+
throw new Error("mAYL_send_as_agent requires at least one of body_text or body_html.");
|
|
2455
|
+
}
|
|
2456
|
+
const claim = await mintHubClaim(input.agent_id, input.task_id);
|
|
2457
|
+
ctx.log("debug", "mAYL_send_as_agent invoking mp0st-send with hub-claim", { agent_id: input.agent_id });
|
|
2458
|
+
const { agent_id: _ai, task_id: _ti, ...mailFields } = input;
|
|
2459
|
+
const r = await fetch(`${supabaseUrl2()}/functions/v1/mp0st-send`, {
|
|
2460
|
+
method: "POST",
|
|
2461
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${claim}` },
|
|
2462
|
+
body: JSON.stringify(mailFields)
|
|
2463
|
+
});
|
|
2464
|
+
if (!r.ok) {
|
|
2465
|
+
const b = await r.text().catch(() => "");
|
|
2466
|
+
throw new Error(`mp0st-send ${r.status}: ${b.slice(0, 200)}`);
|
|
2467
|
+
}
|
|
2468
|
+
const res = await r.json();
|
|
2469
|
+
if (res.error) throw new Error(res.error);
|
|
2470
|
+
return {
|
|
2471
|
+
message_id: res.email_id ?? "",
|
|
2472
|
+
status: res.status ?? "sent",
|
|
2473
|
+
is_internal: res.is_internal ?? false,
|
|
2474
|
+
sent_by: "agent"
|
|
2475
|
+
};
|
|
2476
|
+
}
|
|
2477
|
+
var mailProvenanceTools = [
|
|
2478
|
+
{
|
|
2479
|
+
name: "mAYL_send_as_agent",
|
|
2480
|
+
title: "Send email as your agent",
|
|
2481
|
+
annotations: { readOnlyHint: false },
|
|
2482
|
+
requires: "network",
|
|
2483
|
+
description: "Send an email ATTRIBUTED TO THE AGENT (provenance-stamped). Unlike mAYL_send (sends as the user), this stamps sent_by='agent' plus your agent_id and optional task_id onto the email record and audit trail \u2014 so recipients and compliance can see the mail was agent-originated. Auth: presents a hub-claim JWT (needs MOSADD_API_KEY). The mp0st-send EF verifies the claim with HUB_JWT_SECRET; body trust is never granted for provenance.",
|
|
2484
|
+
inputSchema: mp0st_send_as_agent_input,
|
|
2485
|
+
handler: mAYL_send_as_agent
|
|
2486
|
+
}
|
|
2487
|
+
];
|
|
2488
|
+
|
|
2489
|
+
// src/tools/mail-agentbox.ts
|
|
2490
|
+
import { z as z10 } from "zod";
|
|
2491
|
+
var BoxId = z10.string().min(1).describe("Agent-box id (UUID) from mAYL_agentbox_provision or mAYL_agentbox_list.");
|
|
2492
|
+
var agentbox_provision_input = z10.object({
|
|
2493
|
+
display_name: z10.string().max(120).optional().describe("Optional human label for the box (e.g. 'signup catcher'). Max 120 chars."),
|
|
2494
|
+
agent_id: z10.string().optional().describe("Optional identity id to attribute the box to \u2014 must be an agent identity you own."),
|
|
2495
|
+
kind: z10.enum(["ephemeral", "persistent"]).optional().describe("'ephemeral' (default) auto-expires + is reaped; 'persistent' never expires."),
|
|
2496
|
+
ttl_seconds: z10.number().int().positive().max(86400).optional().describe("Lifetime for an ephemeral box, in seconds. Default 600 (10 min). Max 86400 (24 h). Ignored for persistent.")
|
|
2497
|
+
});
|
|
2498
|
+
var agentbox_list_input = z10.object({});
|
|
2499
|
+
var agentbox_release_input = z10.object({ id: BoxId });
|
|
2500
|
+
var agentbox_extend_input = z10.object({
|
|
2501
|
+
id: BoxId,
|
|
2502
|
+
ttl_seconds: z10.number().int().positive().max(86400).optional().describe("New lifetime from NOW, in seconds. Default 600 (10 min). Max 86400 (24 h). Ephemeral boxes only.")
|
|
2503
|
+
});
|
|
2504
|
+
async function agentbox_provision(input, ctx) {
|
|
2505
|
+
readSupabaseEnv();
|
|
2506
|
+
ctx.log("debug", "mAYL_agentbox_provision invoking mayl-agentbox", { kind: input.kind ?? "ephemeral" });
|
|
2507
|
+
return await invokeFunction("mayl-agentbox", {
|
|
2508
|
+
action: "create",
|
|
2509
|
+
display_name: input.display_name ?? null,
|
|
2510
|
+
agent_id: input.agent_id ?? null,
|
|
2511
|
+
kind: input.kind ?? "ephemeral",
|
|
2512
|
+
ttl_seconds: input.ttl_seconds ?? null
|
|
2513
|
+
});
|
|
2514
|
+
}
|
|
2515
|
+
async function agentbox_list(_input, ctx) {
|
|
2516
|
+
readSupabaseEnv();
|
|
2517
|
+
ctx.log("debug", "mAYL_agentbox_list invoking mayl-agentbox", {});
|
|
2518
|
+
return await invokeFunction("mayl-agentbox", { action: "list" });
|
|
2519
|
+
}
|
|
2520
|
+
async function agentbox_release(input, ctx) {
|
|
2521
|
+
readSupabaseEnv();
|
|
2522
|
+
ctx.log("debug", "mAYL_agentbox_release invoking mayl-agentbox", { id: input.id });
|
|
2523
|
+
return await invokeFunction("mayl-agentbox", { action: "release", id: input.id });
|
|
2524
|
+
}
|
|
2525
|
+
async function agentbox_extend(input, ctx) {
|
|
2526
|
+
readSupabaseEnv();
|
|
2527
|
+
ctx.log("debug", "mAYL_agentbox_extend invoking mayl-agentbox", { id: input.id });
|
|
2528
|
+
return await invokeFunction("mayl-agentbox", {
|
|
2529
|
+
action: "extend",
|
|
2530
|
+
id: input.id,
|
|
2531
|
+
ttl_seconds: input.ttl_seconds ?? null
|
|
2532
|
+
});
|
|
2533
|
+
}
|
|
2534
|
+
var mailAgentboxTools = [
|
|
2535
|
+
{
|
|
2536
|
+
name: "mAYL_agentbox_provision",
|
|
2537
|
+
title: "Provision disposable inbox",
|
|
2538
|
+
annotations: { readOnlyHint: false },
|
|
2539
|
+
requires: "network",
|
|
2540
|
+
description: "Mint the agent its OWN real, disposable email inbox at agent-<hex>@mosadd.com that can SEND and RECEIVE. Default ephemeral with a 10-minute TTL (auto-expires + is reaped); pass kind:'persistent' for a permanent box, or ttl_seconds (max 86400) for a custom lifetime. Optional display_name + agent_id. Returns the box {id, address, expires_at}. Use the address to catch signup/verification codes or replies, then mAYL_list (filter by the box address) + mAYL_view to read what arrived. Owner-scoped; max 25 active boxes per account.",
|
|
2541
|
+
inputSchema: agentbox_provision_input,
|
|
2542
|
+
handler: agentbox_provision
|
|
2543
|
+
},
|
|
2544
|
+
{
|
|
2545
|
+
name: "mAYL_agentbox_list",
|
|
2546
|
+
title: "List disposable inboxes",
|
|
2547
|
+
annotations: { readOnlyHint: true },
|
|
2548
|
+
requires: "network",
|
|
2549
|
+
description: "List your active agent inboxes (address, display_name, kind, agent_id, expires_at), newest first. Owner-scoped.",
|
|
2550
|
+
inputSchema: agentbox_list_input,
|
|
2551
|
+
handler: agentbox_list
|
|
2552
|
+
},
|
|
2553
|
+
{
|
|
2554
|
+
name: "mAYL_agentbox_release",
|
|
2555
|
+
title: "Release disposable inbox",
|
|
2556
|
+
annotations: { destructiveHint: true },
|
|
2557
|
+
requires: "network",
|
|
2558
|
+
description: "Release (delete) one of your agent inboxes by id \u2014 frees the address immediately so it stops receiving. Owner-scoped.",
|
|
2559
|
+
inputSchema: agentbox_release_input,
|
|
2560
|
+
handler: agentbox_release
|
|
2561
|
+
},
|
|
2562
|
+
{
|
|
2563
|
+
name: "mAYL_agentbox_extend",
|
|
2564
|
+
title: "Extend disposable inbox",
|
|
2565
|
+
annotations: { readOnlyHint: false },
|
|
2566
|
+
requires: "network",
|
|
2567
|
+
description: "Extend an EPHEMERAL agent inbox's lifetime by id (ttl_seconds counted from NOW, max 24 h). Persistent boxes never expire and cannot be extended. Owner-scoped.",
|
|
2568
|
+
inputSchema: agentbox_extend_input,
|
|
2569
|
+
handler: agentbox_extend
|
|
2570
|
+
}
|
|
2571
|
+
];
|
|
2572
|
+
|
|
2573
|
+
// src/tools/mtalk.ts
|
|
2574
|
+
import { z as z11 } from "zod";
|
|
2575
|
+
var RoomLabel = z11.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.");
|
|
2576
|
+
var RoomId2 = z11.string().min(1).describe("Room id returned by mTALK_open.");
|
|
2577
|
+
var mTALK_open_input = z11.object({
|
|
2578
|
+
label: RoomLabel.optional().describe("Optional label; defaults to a personal room.")
|
|
2579
|
+
});
|
|
2580
|
+
var mTALK_join_input = z11.object({ room_id: RoomId2 });
|
|
2581
|
+
var mTALK_press_input = z11.object({ room_id: RoomId2 });
|
|
2582
|
+
var mTALK_release_input = z11.object({ room_id: RoomId2 });
|
|
2583
|
+
var mTALK_state_input = z11.object({ room_id: RoomId2 });
|
|
2584
|
+
async function mTALK_open(input, ctx) {
|
|
2585
|
+
const { roomId } = await ctx.providers.voice.createRoom(input.label);
|
|
2586
|
+
ctx.log("debug", "mTALK_open", { room_id: roomId });
|
|
2587
|
+
return { room_id: roomId };
|
|
2588
|
+
}
|
|
2589
|
+
async function mTALK_join(input, ctx) {
|
|
2590
|
+
const ticket = await ctx.providers.voice.joinTicket(input.room_id);
|
|
2591
|
+
ctx.log("debug", "mTALK_join", { room_id: ticket.roomId, identity: ticket.identity });
|
|
2592
|
+
return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
|
|
2593
|
+
}
|
|
2594
|
+
async function mTALK_press(input, ctx) {
|
|
2595
|
+
const res = await ctx.providers.voice.requestFloor(input.room_id);
|
|
2596
|
+
ctx.log("debug", "mTALK_press", { room_id: input.room_id, granted: res.granted, position: res.position });
|
|
2597
|
+
return { granted: res.granted, position: res.position, holder: res.snapshot.holder, queue: res.snapshot.queue };
|
|
2598
|
+
}
|
|
2599
|
+
async function mTALK_release(input, ctx) {
|
|
2600
|
+
const snap = await ctx.providers.voice.releaseFloor(input.room_id);
|
|
2601
|
+
ctx.log("debug", "mTALK_release", { room_id: input.room_id, holder: snap.holder });
|
|
2602
|
+
return { holder: snap.holder, queue: snap.queue };
|
|
2603
|
+
}
|
|
2604
|
+
async function mTALK_state(input, ctx) {
|
|
2605
|
+
const snap = await ctx.providers.voice.floorState(input.room_id);
|
|
2606
|
+
return { holder: snap.holder, since: snap.since, queue: snap.queue };
|
|
2607
|
+
}
|
|
2608
|
+
var mtalkTools = [
|
|
2609
|
+
{
|
|
2610
|
+
name: "mTALK_open",
|
|
2611
|
+
title: "Open push-to-talk room",
|
|
2612
|
+
annotations: { readOnlyHint: false },
|
|
2613
|
+
requires: "any",
|
|
2614
|
+
description: "Open (or get) a push-to-talk room. Returns a stable room_id. Pass an optional label for a named room (e.g. 'ops') that you own: you and your accepted contacts can join it; omit the label for a personal room. Works over network (LiveKit) or off-grid radio depending on the host.",
|
|
2615
|
+
inputSchema: mTALK_open_input,
|
|
2616
|
+
handler: mTALK_open
|
|
2617
|
+
},
|
|
2618
|
+
{
|
|
2619
|
+
name: "mTALK_join",
|
|
2620
|
+
title: "Get PTT join credentials",
|
|
2621
|
+
annotations: { readOnlyHint: false },
|
|
2622
|
+
requires: "network",
|
|
2623
|
+
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.",
|
|
2624
|
+
inputSchema: mTALK_join_input,
|
|
2625
|
+
handler: mTALK_join
|
|
2626
|
+
},
|
|
2627
|
+
{
|
|
2628
|
+
name: "mTALK_press",
|
|
2629
|
+
title: "Press to talk (request floor)",
|
|
2630
|
+
annotations: { readOnlyHint: false },
|
|
2631
|
+
requires: "any",
|
|
2632
|
+
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.",
|
|
2633
|
+
inputSchema: mTALK_press_input,
|
|
2634
|
+
handler: mTALK_press
|
|
2635
|
+
},
|
|
2636
|
+
{
|
|
2637
|
+
name: "mTALK_release",
|
|
2638
|
+
title: "Release the floor",
|
|
2639
|
+
annotations: { readOnlyHint: false },
|
|
2640
|
+
requires: "any",
|
|
2641
|
+
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.",
|
|
2642
|
+
inputSchema: mTALK_release_input,
|
|
2643
|
+
handler: mTALK_release
|
|
2644
|
+
},
|
|
2645
|
+
{
|
|
2646
|
+
name: "mTALK_state",
|
|
2647
|
+
title: "Read PTT floor state",
|
|
2648
|
+
annotations: { readOnlyHint: true },
|
|
2649
|
+
requires: "any",
|
|
2650
|
+
description: "Read a PTT room's floor state without changing it: who is currently transmitting (holder), since when, and the waiting queue.",
|
|
2651
|
+
inputSchema: mTALK_state_input,
|
|
2652
|
+
handler: mTALK_state
|
|
2653
|
+
}
|
|
2654
|
+
];
|
|
2655
|
+
|
|
2656
|
+
// src/tools/attachments.ts
|
|
2657
|
+
import { z as z12 } from "zod";
|
|
2658
|
+
|
|
2659
|
+
// src/providers/blob-upload.ts
|
|
2660
|
+
function defaultBucket(kind) {
|
|
2661
|
+
return kind === "file" ? "chat-files" : "voice-messages";
|
|
2662
|
+
}
|
|
2663
|
+
function jwtSub(jwt) {
|
|
2664
|
+
const part = jwt.split(".")[1];
|
|
2665
|
+
if (!part) return null;
|
|
2666
|
+
try {
|
|
2667
|
+
const json = JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
|
|
2668
|
+
return typeof json?.sub === "string" && json.sub ? json.sub : null;
|
|
2669
|
+
} catch {
|
|
2670
|
+
return null;
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
function ownerFolder(userJwt) {
|
|
2674
|
+
const sub = userJwt ? jwtSub(userJwt) : null;
|
|
2675
|
+
if (!sub) {
|
|
2676
|
+
throw new Error(
|
|
2677
|
+
"blob upload refused: no user id in the session JWT \u2014 bucket policy requires foldername[1] = auth.uid(); run `mosadd login` (or set MOSADD_USER_JWT) and retry"
|
|
2678
|
+
);
|
|
2679
|
+
}
|
|
2680
|
+
return sub;
|
|
2681
|
+
}
|
|
2682
|
+
function randomId2() {
|
|
2683
|
+
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
2684
|
+
}
|
|
2685
|
+
async function uploadBlob(args) {
|
|
2686
|
+
const env = readSupabaseEnv();
|
|
2687
|
+
const sb = getSupabase();
|
|
2688
|
+
const bucket = args.bucket ?? defaultBucket(args.kind);
|
|
2689
|
+
const ext = args.filename?.split(".").pop() ?? mimeExt(args.mime);
|
|
2690
|
+
const folder = args.prefix ? args.prefix.replace(/[^a-zA-Z0-9._/-]/g, "-").replace(/^\/+|\/+$/g, "") : "";
|
|
2691
|
+
const path = [ownerFolder(env.userJwt), folder, `${randomId2()}${ext ? "." + ext : ""}`].filter(Boolean).join("/");
|
|
2692
|
+
const { error } = await sb.storage.from(bucket).upload(path, args.bytes, {
|
|
2693
|
+
contentType: args.mime,
|
|
2694
|
+
upsert: false
|
|
2695
|
+
});
|
|
2696
|
+
if (error) {
|
|
2697
|
+
throw new Error(`blob upload to ${bucket}/${path} failed: ${error.message}`);
|
|
2698
|
+
}
|
|
2699
|
+
return {
|
|
2700
|
+
kind: args.kind,
|
|
2701
|
+
bucket,
|
|
2702
|
+
path,
|
|
2703
|
+
mime: args.mime,
|
|
2704
|
+
duration_ms: args.duration_ms ?? null,
|
|
2705
|
+
key_ref: args.key_ref ?? null,
|
|
2706
|
+
filename: args.filename ?? null,
|
|
2707
|
+
size_bytes: args.bytes.byteLength
|
|
2708
|
+
};
|
|
2709
|
+
}
|
|
2710
|
+
function mimeExt(mime) {
|
|
2711
|
+
const map = {
|
|
2712
|
+
"audio/ogg": "ogg",
|
|
2713
|
+
"audio/mpeg": "mp3",
|
|
2714
|
+
"audio/mp4": "m4a",
|
|
2715
|
+
"audio/wav": "wav",
|
|
2716
|
+
"audio/webm": "webm"
|
|
2717
|
+
};
|
|
2718
|
+
return map[mime] ?? "";
|
|
2719
|
+
}
|
|
2720
|
+
function decodeBase64Body(b64) {
|
|
2721
|
+
const cleaned = b64.includes(",") && b64.startsWith("data:") ? b64.slice(b64.indexOf(",") + 1) : b64;
|
|
2722
|
+
return new Uint8Array(Buffer.from(cleaned, "base64"));
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
// src/tools/attachments.ts
|
|
2726
|
+
var PROTOCOL_VERSION5 = "mosadd.chat.v1";
|
|
2727
|
+
var Base64Body = z12.string().min(1).max(2e7).describe("Attachment bytes as base64 (or a data: URL). MCP is JSON-only, so binary is base64-encoded. Max ~15 MB decoded.");
|
|
2728
|
+
var Mime = z12.string().min(1).max(120).describe("MIME type, e.g. audio/ogg, application/pdf, image/png.");
|
|
2729
|
+
var DurationMs = z12.number().int().positive().optional().describe("Audio clip length in ms (voice only), if known.");
|
|
2730
|
+
var Filename = z12.string().min(1).max(255).optional().describe("Original filename (file only).");
|
|
2731
|
+
var ReplyTo = z12.string().optional().describe("Optional id of the message being replied to.");
|
|
2732
|
+
var ContactRef3 = z12.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
|
|
2733
|
+
var RoomId3 = z12.string().min(1).describe("Room/channel id (UUID).");
|
|
2734
|
+
var ThreadLabel = z12.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional().describe("Optional thread label within the conversation (mDM USP: multiple threads per contact).");
|
|
2735
|
+
function dmThreadId3(selfId, otherId, label) {
|
|
2736
|
+
const [a, b] = [selfId, otherId].sort();
|
|
2737
|
+
return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
|
|
2738
|
+
}
|
|
2739
|
+
async function sendAttachmentMessage(ctx, args) {
|
|
2740
|
+
readSupabaseEnv();
|
|
2741
|
+
const captionEnvelope = {
|
|
2742
|
+
v: PROTOCOL_VERSION5,
|
|
2743
|
+
type: args.message_type,
|
|
2744
|
+
text: args.caption ?? "",
|
|
2745
|
+
sent_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
2746
|
+
};
|
|
2747
|
+
const encrypted_payload = Buffer.from(JSON.stringify(captionEnvelope), "utf8").toString("base64");
|
|
2748
|
+
ctx.log("debug", "sendAttachmentMessage", {
|
|
2749
|
+
thread_id: args.thread_id,
|
|
2750
|
+
message_type: args.message_type,
|
|
2751
|
+
bucket: args.attachment.bucket
|
|
2752
|
+
});
|
|
2753
|
+
const data = await invokeFunction("message-send", {
|
|
2754
|
+
space_id: args.space_id,
|
|
2755
|
+
thread_id: args.thread_id,
|
|
2756
|
+
message_type: args.message_type,
|
|
2757
|
+
attachments: [args.attachment],
|
|
2758
|
+
// TODO(Lane A): confirm field placement
|
|
2759
|
+
encrypted_payload,
|
|
2760
|
+
protocol_version: PROTOCOL_VERSION5,
|
|
2761
|
+
recipient_account_id: args.recipient_account_id ?? null,
|
|
2762
|
+
reply_to_id: args.reply_to_id ?? null
|
|
2763
|
+
});
|
|
2764
|
+
if (!data?.message?.id) throw new Error("message-send returned no message id (attachment)");
|
|
2765
|
+
return {
|
|
2766
|
+
message_id: data.message.id,
|
|
2767
|
+
delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
2768
|
+
thread_id: args.thread_id
|
|
2769
|
+
};
|
|
2770
|
+
}
|
|
2771
|
+
async function resolveLinkedSpaceId2(channelId) {
|
|
2772
|
+
const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
|
|
2773
|
+
const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
|
|
2774
|
+
if (!spaceId) throw new Error(`Channel ${channelId} has no linked space yet \u2014 run mIRC_join/mIRC_list first or pass space_id.`);
|
|
2775
|
+
return spaceId;
|
|
2776
|
+
}
|
|
2777
|
+
var mDM_send_voice_input = z12.object({
|
|
2778
|
+
to: ContactRef3,
|
|
2779
|
+
audio_base64: Base64Body,
|
|
2780
|
+
mime: Mime.default("audio/ogg"),
|
|
2781
|
+
duration_ms: DurationMs,
|
|
2782
|
+
caption: z12.string().max(2e3).optional(),
|
|
2783
|
+
thread_label: ThreadLabel,
|
|
2784
|
+
reply_to_id: ReplyTo
|
|
2785
|
+
});
|
|
2786
|
+
var mDM_send_file_input = z12.object({
|
|
2787
|
+
to: ContactRef3,
|
|
2788
|
+
file_base64: Base64Body,
|
|
2789
|
+
filename: Filename,
|
|
2790
|
+
mime: Mime,
|
|
2791
|
+
caption: z12.string().max(2e3).optional(),
|
|
2792
|
+
thread_label: ThreadLabel,
|
|
2793
|
+
reply_to_id: ReplyTo
|
|
2794
|
+
});
|
|
2795
|
+
async function mDM_send_voice(input, ctx) {
|
|
2796
|
+
const dm = ctx.providers.dm;
|
|
2797
|
+
const selfId = await dm.selfId();
|
|
2798
|
+
const thread_id = dmThreadId3(selfId, input.to, input.thread_label);
|
|
2799
|
+
const attachment = await uploadBlob({
|
|
2800
|
+
kind: "voice",
|
|
2801
|
+
bytes: decodeBase64Body(input.audio_base64),
|
|
2802
|
+
mime: input.mime,
|
|
2803
|
+
prefix: thread_id,
|
|
2804
|
+
duration_ms: input.duration_ms
|
|
2805
|
+
});
|
|
2806
|
+
return sendAttachmentMessage(ctx, {
|
|
2807
|
+
space_id: "dm",
|
|
2808
|
+
thread_id,
|
|
2809
|
+
message_type: "voice",
|
|
2810
|
+
attachment,
|
|
2811
|
+
caption: input.caption,
|
|
2812
|
+
reply_to_id: input.reply_to_id,
|
|
2813
|
+
recipient_account_id: input.to
|
|
2814
|
+
});
|
|
2815
|
+
}
|
|
2816
|
+
async function mDM_send_file(input, ctx) {
|
|
2817
|
+
const dm = ctx.providers.dm;
|
|
2818
|
+
const selfId = await dm.selfId();
|
|
2819
|
+
const thread_id = dmThreadId3(selfId, input.to, input.thread_label);
|
|
2820
|
+
const attachment = await uploadBlob({
|
|
2821
|
+
kind: "file",
|
|
2822
|
+
bytes: decodeBase64Body(input.file_base64),
|
|
2823
|
+
mime: input.mime,
|
|
2824
|
+
prefix: thread_id,
|
|
2825
|
+
filename: input.filename
|
|
2826
|
+
});
|
|
2827
|
+
return sendAttachmentMessage(ctx, {
|
|
2828
|
+
space_id: "dm",
|
|
2829
|
+
thread_id,
|
|
2830
|
+
message_type: "file",
|
|
2831
|
+
attachment,
|
|
2832
|
+
caption: input.caption,
|
|
2833
|
+
reply_to_id: input.reply_to_id,
|
|
2834
|
+
recipient_account_id: input.to
|
|
2835
|
+
});
|
|
2836
|
+
}
|
|
2837
|
+
var mIRC_send_voice_input = z12.object({
|
|
2838
|
+
channel_id: RoomId3,
|
|
2839
|
+
audio_base64: Base64Body,
|
|
2840
|
+
mime: Mime.default("audio/ogg"),
|
|
2841
|
+
duration_ms: DurationMs,
|
|
2842
|
+
caption: z12.string().max(2e3).optional(),
|
|
2843
|
+
reply_to_id: ReplyTo,
|
|
2844
|
+
space_id: z12.string().optional().describe("Backing space id. Resolved automatically if omitted.")
|
|
2845
|
+
});
|
|
2846
|
+
var mIRC_send_file_input = z12.object({
|
|
2847
|
+
channel_id: RoomId3,
|
|
2848
|
+
file_base64: Base64Body,
|
|
2849
|
+
filename: Filename,
|
|
2850
|
+
mime: Mime,
|
|
2851
|
+
caption: z12.string().max(2e3).optional(),
|
|
2852
|
+
reply_to_id: ReplyTo,
|
|
2853
|
+
space_id: z12.string().optional()
|
|
2854
|
+
});
|
|
2855
|
+
async function mIRC_send_voice(input, ctx) {
|
|
2856
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId2(input.channel_id);
|
|
2857
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
2858
|
+
const attachment = await uploadBlob({ kind: "voice", bytes: decodeBase64Body(input.audio_base64), mime: input.mime, prefix: thread_id, duration_ms: input.duration_ms });
|
|
2859
|
+
return sendAttachmentMessage(ctx, { space_id, thread_id, message_type: "voice", attachment, caption: input.caption, reply_to_id: input.reply_to_id });
|
|
2860
|
+
}
|
|
2861
|
+
async function mIRC_send_file(input, ctx) {
|
|
2862
|
+
const space_id = input.space_id ?? await resolveLinkedSpaceId2(input.channel_id);
|
|
2863
|
+
const thread_id = `chat:${input.channel_id}`;
|
|
2864
|
+
const attachment = await uploadBlob({ kind: "file", bytes: decodeBase64Body(input.file_base64), mime: input.mime, prefix: thread_id, filename: input.filename });
|
|
2865
|
+
return sendAttachmentMessage(ctx, { space_id, thread_id, message_type: "file", attachment, caption: input.caption, reply_to_id: input.reply_to_id });
|
|
2866
|
+
}
|
|
2867
|
+
var attachmentTools = [
|
|
2868
|
+
{
|
|
2869
|
+
name: "mDM_send_voice",
|
|
2870
|
+
title: "Send a voice message",
|
|
2871
|
+
annotations: { readOnlyHint: false },
|
|
2872
|
+
requires: "network",
|
|
2873
|
+
description: "Send a VOICE note to a contact as a first-class mDM `voice` message (not a URL stub). Pass audio bytes as base64; the tool uploads to Storage and posts via message-send with the voice attachment descriptor. SCAFFOLD: mDM is client-encrypted \u2014 until the seal step ships, bytes are uploaded unsealed (TODO Lane A).",
|
|
2874
|
+
inputSchema: mDM_send_voice_input,
|
|
2875
|
+
handler: mDM_send_voice
|
|
2876
|
+
},
|
|
2877
|
+
{
|
|
2878
|
+
name: "mDM_send_file",
|
|
2879
|
+
title: "Send a file in DM",
|
|
2880
|
+
annotations: { readOnlyHint: false },
|
|
2881
|
+
requires: "network",
|
|
2882
|
+
description: "Send a FILE to a contact as a first-class mDM `file` message. Base64 bytes \u2192 Storage \u2192 message-send file attachment. SCAFFOLD: mDM E2EE seal is TODO (Lane A).",
|
|
2883
|
+
inputSchema: mDM_send_file_input,
|
|
2884
|
+
handler: mDM_send_file
|
|
2885
|
+
},
|
|
2886
|
+
{
|
|
2887
|
+
name: "mIRC_send_voice",
|
|
2888
|
+
title: "Send voice note to channel",
|
|
2889
|
+
annotations: { readOnlyHint: false },
|
|
2890
|
+
requires: "network",
|
|
2891
|
+
description: "Send a VOICE note into a persistent channel as a first-class `voice` message. Base64 audio \u2192 Storage \u2192 message-send (backing space resolved automatically).",
|
|
2892
|
+
inputSchema: mIRC_send_voice_input,
|
|
2893
|
+
handler: mIRC_send_voice
|
|
2894
|
+
},
|
|
2895
|
+
{
|
|
2896
|
+
name: "mIRC_send_file",
|
|
2897
|
+
title: "Send file to channel",
|
|
2898
|
+
annotations: { readOnlyHint: false },
|
|
2899
|
+
requires: "network",
|
|
2900
|
+
description: "Send a FILE into a persistent channel as a first-class `file` message. Base64 bytes \u2192 Storage \u2192 message-send.",
|
|
2901
|
+
inputSchema: mIRC_send_file_input,
|
|
2902
|
+
handler: mIRC_send_file
|
|
2903
|
+
}
|
|
2904
|
+
];
|
|
2905
|
+
|
|
2906
|
+
// src/tools/ptt-ingest.ts
|
|
2907
|
+
import { z as z13 } from "zod";
|
|
2908
|
+
var mTALK_ingest_ptt_input = z13.object({
|
|
2909
|
+
audio_base64: z13.string().min(1).max(2e7).describe("Recorded PTT 'over' as base64 (a 'data:audio/\u2026;base64,\u2026' prefix is stripped if present)."),
|
|
2910
|
+
mime_type: z13.string().min(1).max(120).default("audio/webm").describe("MIME type of the audio. Default audio/webm (browser MediaRecorder default)."),
|
|
2911
|
+
direction: z13.enum(["human_to_agent", "agent_to_human"]).describe("Direction the PTT crossed: who originated, who received. 'human_to_agent' = user spoke to an agent; 'agent_to_human' = agent spoke to the user."),
|
|
2912
|
+
message_id: z13.string().min(1).max(120).optional().describe("Optional id of the messages_meta row this PTT belongs to. When present, links the transcript back to the message for jump-to-source from RAG."),
|
|
2913
|
+
thread_id: z13.string().min(1).max(120).optional().describe("Optional thread id (e.g. `chat:<channel_id>` or `dm:<a>:<b>`) so the transcript carries its conversational scope into RAG.")
|
|
2914
|
+
});
|
|
2915
|
+
async function mTALK_ingest_ptt(input, ctx) {
|
|
2916
|
+
readSupabaseEnv();
|
|
2917
|
+
const audio = input.audio_base64.replace(/^data:[^;]+;base64,/, "");
|
|
2918
|
+
ctx.log("debug", "mTALK_ingest_ptt invoking ptt-ingest", {
|
|
2919
|
+
direction: input.direction,
|
|
2920
|
+
thread_id: input.thread_id ?? null,
|
|
2921
|
+
mime_type: input.mime_type
|
|
2922
|
+
});
|
|
2923
|
+
const res = await invokeFunction("ptt-ingest", {
|
|
2924
|
+
audio_base64: audio,
|
|
2925
|
+
mime_type: input.mime_type,
|
|
2926
|
+
direction: input.direction,
|
|
2927
|
+
message_id: input.message_id ?? null,
|
|
2928
|
+
thread_id: input.thread_id ?? null
|
|
2929
|
+
});
|
|
2930
|
+
const status = res.status ?? "pending";
|
|
2931
|
+
return {
|
|
2932
|
+
ptt_id: res.ptt_id ?? "",
|
|
2933
|
+
status,
|
|
2934
|
+
opted_in: status !== "skipped_optout"
|
|
2935
|
+
};
|
|
2936
|
+
}
|
|
2937
|
+
var pttIngestTools = [
|
|
2938
|
+
{
|
|
2939
|
+
name: "mTALK_ingest_ptt",
|
|
2940
|
+
title: "Transcribe PTT audio into memory",
|
|
2941
|
+
annotations: { readOnlyHint: false },
|
|
2942
|
+
requires: "network",
|
|
2943
|
+
description: "Submit a finished PTT 'over' (push-to-talk audio segment) for transcription into the caller's RAG index \u2014 so 'what did X say on PTT?' is searchable later. The PERSISTENCE of the voice message itself (the message_meta row + fan-out) is handled by mDM_send_voice / mIRC_send_voice; this tool is the transcription bridge only. Honors per-user RAG opt-in: opted-out callers get status='skipped_optout' (no transcript stored). Auth: Supabase session JWT.",
|
|
2944
|
+
inputSchema: mTALK_ingest_ptt_input,
|
|
2945
|
+
handler: mTALK_ingest_ptt
|
|
2946
|
+
}
|
|
2947
|
+
];
|
|
2948
|
+
|
|
2949
|
+
// src/tools/knowledge.ts
|
|
2950
|
+
import { createHash } from "crypto";
|
|
2951
|
+
import { z as z14 } from "zod";
|
|
2952
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
2953
|
+
var SOURCE_ID_NAMESPACE = "1f0b6c2e-6a4d-4f7a-9c1e-0b2d3a4f5e6b";
|
|
2954
|
+
function uuidV5(name, namespace) {
|
|
2955
|
+
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
|
|
2956
|
+
const digest = createHash("sha1").update(Buffer.concat([ns, Buffer.from(name, "utf8")])).digest();
|
|
2957
|
+
const b = Buffer.from(digest.subarray(0, 16));
|
|
2958
|
+
b[6] = b[6] & 15 | 80;
|
|
2959
|
+
b[8] = b[8] & 63 | 128;
|
|
2960
|
+
const h = b.toString("hex");
|
|
2961
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
2962
|
+
}
|
|
2963
|
+
var mRAG_search_input = z14.object({
|
|
2964
|
+
query: z14.string().min(1).max(2e3).describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
|
|
2965
|
+
top_k: z14.number().int().min(1).max(25).optional().describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
|
|
2966
|
+
source_types: z14.array(z14.enum(["message", "email", "call", "note", "contact", "file", "ptt"])).optional().describe(
|
|
2967
|
+
"Restrict retrieval to these source types. Omit to search everything. 'file' covers anything added with mRAG_ingest (its default, and where 'note' ingests land); 'ptt' covers push-to-talk transcripts ingested by mTALK_ingest_ptt."
|
|
2968
|
+
),
|
|
2969
|
+
thread_id: z14.string().optional().describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread)."),
|
|
2970
|
+
answer: z14.boolean().optional().describe(
|
|
2971
|
+
"Set true to also get a generated answer (answer field) grounded in the returned sources. Default false: ranked sources only, answer is empty."
|
|
2972
|
+
)
|
|
2973
|
+
});
|
|
2974
|
+
async function mRAG_search(input, ctx) {
|
|
2975
|
+
readSupabaseEnv();
|
|
2976
|
+
ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
|
|
2977
|
+
const data = await invokeFunction("rag-query", {
|
|
2978
|
+
query: input.query,
|
|
2979
|
+
top_k: input.top_k ?? 8,
|
|
2980
|
+
source_types: input.source_types ?? null,
|
|
2981
|
+
thread_id: input.thread_id ?? null,
|
|
2982
|
+
answer: input.answer ?? false
|
|
2983
|
+
});
|
|
2984
|
+
return {
|
|
2985
|
+
answer: data.answer ?? "",
|
|
2986
|
+
sources: data.sources ?? [],
|
|
2987
|
+
chunks_found: data.chunks_found ?? (data.sources?.length ?? 0)
|
|
2988
|
+
};
|
|
2989
|
+
}
|
|
2990
|
+
var PartyArg = z14.object({
|
|
2991
|
+
kind: z14.enum(["identity", "account", "email", "phone", "url", "unknown"]).describe("How to read `ref`: a mosadd identity UUID, an account id, an email address, a phone number, a URL, or a plain name ('unknown')."),
|
|
2992
|
+
ref: z14.string().min(1).max(400).describe("The stable key this party is recognised by \u2014 identity UUID, email address, phone number, or the party's canonical name. Use the SAME ref for the same party across documents; that is what merges them into one node in the knowledge graph."),
|
|
2993
|
+
label: z14.string().max(300).nullish().describe("Human name to display for this party.")
|
|
2994
|
+
});
|
|
2995
|
+
var mRAG_ingest_input = z14.object({
|
|
2996
|
+
content_text: z14.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."),
|
|
2997
|
+
source_type: z14.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."),
|
|
2998
|
+
source_id: z14.string().max(500).optional().describe(
|
|
2999
|
+
"Optional stable id for the source so re-ingests of the SAME document group together (and can be removed later with mRAG_delete). Any string works \u2014 a file path, a case number, a checksum: a non-UUID is folded into a stable id derived from it, deterministically, and the original is kept as metadata.source_ref."
|
|
3000
|
+
),
|
|
3001
|
+
thread_id: z14.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
|
|
3002
|
+
title: z14.string().max(300).optional().describe("Optional human title, stored in metadata."),
|
|
3003
|
+
// ── Graph + file-manager fields ────────────────────────────────────────────
|
|
3004
|
+
// Added 2026-08-14. The backend (rag-index → enrichRagMetadata) has accepted all of these
|
|
3005
|
+
// since 2026-07-19; THIS tool was the only ingest path that dropped them, so everything
|
|
3006
|
+
// pushed through MCP landed with no parties and no event date — and therefore contributed
|
|
3007
|
+
// NOTHING to mRAG_graph_*, which builds its nodes from exactly these fields. A corpus could
|
|
3008
|
+
// be fully indexed and its graph still come back empty. See the note on the tool below.
|
|
3009
|
+
sender: PartyArg.optional().describe(
|
|
3010
|
+
"Who the document is FROM (author, filing party, sender). Becomes a node in the knowledge graph \u2014 without it this document adds no party to mRAG_graph_overview."
|
|
3011
|
+
),
|
|
3012
|
+
recipient: PartyArg.optional().describe(
|
|
3013
|
+
"Who the document is TO (addressee, court, counterparty). Becomes a node in the knowledge graph, connected to `sender`."
|
|
3014
|
+
),
|
|
3015
|
+
occurred_at: z14.string().optional().describe("ISO-8601 timestamp of WHEN the document happened (letter date, filing date, email Date header) \u2014 not when you indexed it. Drives mRAG_graph_timeline; defaults to now if omitted, which makes a 2019 filing look like it happened today."),
|
|
3016
|
+
direction: z14.enum(["in", "out", "self"]).optional().describe("Direction relative to the account owner: received, sent, or the owner's own note."),
|
|
3017
|
+
labels: z14.array(z14.string().max(120)).max(50).optional().describe("Free-text tags to attach (e.g. a case id, a jurisdiction) for later filtering."),
|
|
3018
|
+
name: z14.string().max(400).optional().describe("Original filename, if this came from a file (e.g. 'pozew-2019-03-11.pdf'). Its extension is what classifies the row as a document/image/audio in the file view. Distinct from `title`, which is free prose."),
|
|
3019
|
+
mime: z14.string().max(200).optional().describe("MIME type of the original file, if known."),
|
|
3020
|
+
size: z14.number().int().nonnegative().optional().describe("Size of the original file in bytes, if known."),
|
|
3021
|
+
metadata: z14.record(z14.string(), z14.unknown()).optional().describe("Any extra fields to store alongside the row (case id, docket number, jurisdiction, file path, checksum, sensitivity flag\u2026). Stored verbatim and returned with search hits. NOTE: this is stored server-side in plaintext like the content itself.")
|
|
3022
|
+
});
|
|
3023
|
+
async function mRAG_ingest(input, ctx) {
|
|
3024
|
+
readSupabaseEnv();
|
|
3025
|
+
const backendType = input.source_type === "note" ? "file" : input.source_type ?? "file";
|
|
3026
|
+
ctx.log("debug", "mRAG_ingest via rag-index", {
|
|
3027
|
+
source_type: backendType,
|
|
3028
|
+
has_parties: Boolean(input.sender || input.recipient),
|
|
3029
|
+
has_occurred_at: Boolean(input.occurred_at)
|
|
3030
|
+
});
|
|
3031
|
+
const rawSourceId = input.source_id?.trim() || null;
|
|
3032
|
+
const sourceId = rawSourceId && !UUID_RE.test(rawSourceId) ? uuidV5(rawSourceId, SOURCE_ID_NAMESPACE) : rawSourceId;
|
|
3033
|
+
const data = await invokeFunction("rag-index", {
|
|
3034
|
+
source_type: backendType,
|
|
3035
|
+
source_id: sourceId,
|
|
3036
|
+
thread_id: input.thread_id ?? null,
|
|
3037
|
+
content_text: input.content_text,
|
|
3038
|
+
...input.sender ? { sender: input.sender } : {},
|
|
3039
|
+
...input.recipient ? { recipient: input.recipient } : {},
|
|
3040
|
+
...input.occurred_at ? { occurred_at: input.occurred_at } : {},
|
|
3041
|
+
...input.direction ? { direction: input.direction } : {},
|
|
3042
|
+
...input.labels?.length ? { labels: input.labels } : {},
|
|
3043
|
+
...input.name ? { name: input.name } : {},
|
|
3044
|
+
...input.mime ? { mime: input.mime } : {},
|
|
3045
|
+
...typeof input.size === "number" ? { size: input.size } : {},
|
|
3046
|
+
metadata: {
|
|
3047
|
+
...input.metadata ?? {},
|
|
3048
|
+
...input.title ? { title: input.title } : {},
|
|
3049
|
+
// Only when we actually rewrote it — a caller that passed a real UUID sees no extra key.
|
|
3050
|
+
...rawSourceId && rawSourceId !== sourceId ? { source_ref: rawSourceId } : {},
|
|
3051
|
+
ingested_via: "mRAG_ingest"
|
|
3052
|
+
}
|
|
3053
|
+
});
|
|
3054
|
+
return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
|
|
3055
|
+
}
|
|
3056
|
+
var mRAG_list_sources_input = z14.object({});
|
|
3057
|
+
async function mRAG_list_sources(_input, ctx) {
|
|
3058
|
+
readSupabaseEnv();
|
|
3059
|
+
ctx.log("debug", "mRAG_list_sources via rag-sources");
|
|
3060
|
+
return await invokeFunction("rag-sources", { action: "list" });
|
|
3061
|
+
}
|
|
3062
|
+
var mRAG_delete_input = z14.object({
|
|
3063
|
+
source_id: z14.string().optional().describe("Delete every indexed chunk with this source_id (from mRAG_list_sources)."),
|
|
3064
|
+
thread_id: z14.string().optional().describe("Delete every indexed chunk associated with this thread_id.")
|
|
3065
|
+
}).refine((v) => v.source_id || v.thread_id, {
|
|
3066
|
+
message: "Provide source_id or thread_id \u2014 mRAG_delete refuses to purge the whole index."
|
|
3067
|
+
});
|
|
3068
|
+
async function mRAG_delete(input, ctx) {
|
|
3069
|
+
readSupabaseEnv();
|
|
3070
|
+
const rawId = input.source_id?.trim() || null;
|
|
3071
|
+
const sourceId = rawId && !UUID_RE.test(rawId) ? uuidV5(rawId, SOURCE_ID_NAMESPACE) : rawId;
|
|
3072
|
+
ctx.log("debug", "mRAG_delete via rag-sources", { source_id: sourceId, source_ref: rawId, thread_id: input.thread_id });
|
|
3073
|
+
return await invokeFunction("rag-sources", {
|
|
3074
|
+
action: "delete",
|
|
3075
|
+
source_id: sourceId,
|
|
3076
|
+
thread_id: input.thread_id ?? null
|
|
3077
|
+
});
|
|
3078
|
+
}
|
|
3079
|
+
var knowledgeTools = [
|
|
3080
|
+
{
|
|
3081
|
+
name: "mRAG_ingest",
|
|
3082
|
+
title: "Ingest into memory",
|
|
3083
|
+
annotations: { readOnlyHint: false },
|
|
3084
|
+
requires: "network",
|
|
3085
|
+
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. \u26A0 IF YOU ARE INDEXING A CORPUS you want to TRAVERSE (who is connected to whom, when), also pass sender / recipient / occurred_at: the knowledge graph builds its nodes from those fields alone, so documents ingested without them are searchable but contribute NOTHING to mRAG_graph_overview / _neighbors / _timeline \u2014 the graph comes back empty however many documents you loaded. Reuse the same party `ref` across documents to merge them into one node. NOTE: indexed content and metadata are stored server-side in plaintext \u2014 NOT covered by the zero-knowledge / E2EE guarantee. Only ingest what the user opted to make searchable.",
|
|
3086
|
+
inputSchema: mRAG_ingest_input,
|
|
3087
|
+
handler: mRAG_ingest
|
|
3088
|
+
},
|
|
3089
|
+
{
|
|
3090
|
+
name: "mRAG_search",
|
|
3091
|
+
title: "Search memory",
|
|
3092
|
+
annotations: { readOnlyHint: true },
|
|
3093
|
+
requires: "network",
|
|
3094
|
+
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. By DEFAULT (via MCP) it returns the ranked source snippets only and `answer` is an empty string (answer_mode retrieve_only): fast, no model call. Pass answer:true to also get a generated answer grounded in those sources (slower, uses the model budget). If the index search runs out of time the call still succeeds and carries partial:true with partial_reason, instead of failing. 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 b",
|
|
3095
|
+
inputSchema: mRAG_search_input,
|
|
3096
|
+
handler: mRAG_search
|
|
3097
|
+
},
|
|
3098
|
+
{
|
|
3099
|
+
name: "mRAG_list_sources",
|
|
3100
|
+
title: "List memory sources",
|
|
3101
|
+
annotations: { readOnlyHint: true },
|
|
3102
|
+
requires: "network",
|
|
3103
|
+
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.",
|
|
3104
|
+
inputSchema: mRAG_list_sources_input,
|
|
3105
|
+
handler: mRAG_list_sources
|
|
3106
|
+
},
|
|
3107
|
+
{
|
|
3108
|
+
name: "mRAG_delete",
|
|
3109
|
+
title: "Delete memory source",
|
|
3110
|
+
annotations: { destructiveHint: true },
|
|
3111
|
+
requires: "network",
|
|
3112
|
+
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.",
|
|
3113
|
+
inputSchema: mRAG_delete_input,
|
|
3114
|
+
handler: mRAG_delete
|
|
3115
|
+
}
|
|
3116
|
+
];
|
|
3117
|
+
|
|
3118
|
+
// src/tools/knowledge-graph.ts
|
|
3119
|
+
import { z as z15 } from "zod";
|
|
3120
|
+
async function callRpc(fn, args, ctx) {
|
|
3121
|
+
readSupabaseEnv();
|
|
3122
|
+
ctx.log("debug", `mRAG_graph via ${fn}`, args);
|
|
3123
|
+
const { data, error } = await getSupabase().rpc(fn, args);
|
|
3124
|
+
if (error) {
|
|
3125
|
+
throw new Error(`${fn} failed: ${error.message}${error.code ? ` (${error.code})` : ""}`);
|
|
3126
|
+
}
|
|
3127
|
+
return data;
|
|
3128
|
+
}
|
|
3129
|
+
var mRAG_graph_refresh_input = z15.object({
|
|
3130
|
+
max_docs: z15.number().int().min(1).max(2e4).optional().describe("Cap on source documents scanned when (re)building the graph. Default 20000 (the max).")
|
|
3131
|
+
});
|
|
3132
|
+
async function mRAG_graph_refresh(input, ctx) {
|
|
3133
|
+
return await callRpc("kg_refresh_me", { p_max_docs: input.max_docs ?? 2e4 }, ctx);
|
|
3134
|
+
}
|
|
3135
|
+
var mRAG_graph_overview_input = z15.object({
|
|
3136
|
+
limit: z15.number().int().min(1).max(200).optional().describe("Max parties to return (busiest first). Default 40, max 200.")
|
|
3137
|
+
});
|
|
3138
|
+
async function mRAG_graph_overview(input, ctx) {
|
|
3139
|
+
const rows = await callRpc("kg_overview", { p_limit: input.limit ?? 40 }, ctx);
|
|
3140
|
+
const parties = rows ?? [];
|
|
3141
|
+
return { parties, count: parties.length };
|
|
3142
|
+
}
|
|
3143
|
+
var mRAG_graph_neighbors_input = z15.object({
|
|
3144
|
+
party_id: z15.string().uuid().describe("The party whose connections to walk (a party_id from mRAG_graph_overview)."),
|
|
3145
|
+
depth: z15.number().int().min(1).max(2).optional().describe("Hops to walk. Hard-clamped to 2 server-side. Default 1."),
|
|
3146
|
+
limit: z15.number().int().min(1).max(200).optional().describe("Max neighbours to return. Clamped to 200. Default 50.")
|
|
3147
|
+
});
|
|
3148
|
+
async function mRAG_graph_neighbors(input, ctx) {
|
|
3149
|
+
const rows = await callRpc(
|
|
3150
|
+
"kg_neighbors",
|
|
3151
|
+
{ p_party_id: input.party_id, p_depth: input.depth ?? 1, p_limit: input.limit ?? 50 },
|
|
3152
|
+
ctx
|
|
3153
|
+
);
|
|
3154
|
+
const neighbors = rows ?? [];
|
|
3155
|
+
return { neighbors, count: neighbors.length };
|
|
3156
|
+
}
|
|
3157
|
+
var mRAG_graph_timeline_input = z15.object({
|
|
3158
|
+
party_id: z15.string().uuid().describe("The party whose dated appearance timeline to return (a party_id from mRAG_graph_overview)."),
|
|
3159
|
+
limit: z15.number().int().min(1).max(200).optional().describe("Max timeline entries (newest first). Clamped to 200. Default 50.")
|
|
3160
|
+
});
|
|
3161
|
+
async function mRAG_graph_timeline(input, ctx) {
|
|
3162
|
+
const rows = await callRpc(
|
|
3163
|
+
"kg_party_timeline",
|
|
3164
|
+
{ p_party_id: input.party_id, p_limit: input.limit ?? 50 },
|
|
3165
|
+
ctx
|
|
3166
|
+
);
|
|
3167
|
+
const timeline = rows ?? [];
|
|
3168
|
+
return { timeline, count: timeline.length };
|
|
3169
|
+
}
|
|
3170
|
+
var knowledgeGraphTools = [
|
|
3171
|
+
{
|
|
3172
|
+
name: "mRAG_graph_refresh",
|
|
3173
|
+
title: "Rebuild knowledge graph",
|
|
3174
|
+
annotations: { readOnlyHint: false },
|
|
3175
|
+
requires: "network",
|
|
3176
|
+
description: "(Re)build the USER'S OWN knowledge graph from their indexed data, then return what it found (counts of parties/mentions/edges). Run this first, or after new data has been ingested, so mRAG_graph_overview/neighbors/timeline reflect the latest. Built from METADATA only (who-sent-to-whom, thread membership) \u2014 never message bodies, so it does not weaken E2EE. Owner-scoped.",
|
|
3177
|
+
inputSchema: mRAG_graph_refresh_input,
|
|
3178
|
+
handler: mRAG_graph_refresh
|
|
3179
|
+
},
|
|
3180
|
+
{
|
|
3181
|
+
name: "mRAG_graph_overview",
|
|
3182
|
+
title: "Knowledge graph overview",
|
|
3183
|
+
annotations: { readOnlyHint: true },
|
|
3184
|
+
requires: "network",
|
|
3185
|
+
description: "List the parties (people / companies / services) in the user's knowledge graph, busiest first, each with its party_id, kind, aliases, appearance count, connection count and first/last-seen dates. This is the entry point: use a returned party_id with mRAG_graph_neighbors or mRAG_graph_timeline. Owner-scoped.",
|
|
3186
|
+
inputSchema: mRAG_graph_overview_input,
|
|
3187
|
+
handler: mRAG_graph_overview
|
|
3188
|
+
},
|
|
3189
|
+
{
|
|
3190
|
+
name: "mRAG_graph_neighbors",
|
|
3191
|
+
title: "Explore graph neighbors",
|
|
3192
|
+
annotations: { readOnlyHint: true },
|
|
3193
|
+
requires: "network",
|
|
3194
|
+
description: "Walk the connections of one party (from mRAG_graph_overview) \u2014 who/what it is linked to, with the edge type, how many times observed, and when. Answers 'who is connected to X, and how'. Depth is hard-clamped to 2 hops and breadth to 200 server-side. Owner-scoped.",
|
|
3195
|
+
inputSchema: mRAG_graph_neighbors_input,
|
|
3196
|
+
handler: mRAG_graph_neighbors
|
|
3197
|
+
},
|
|
3198
|
+
{
|
|
3199
|
+
name: "mRAG_graph_timeline",
|
|
3200
|
+
title: "Knowledge graph timeline",
|
|
3201
|
+
annotations: { readOnlyHint: true },
|
|
3202
|
+
requires: "network",
|
|
3203
|
+
description: "Return the dated appearance timeline of one party (from mRAG_graph_overview) \u2014 each source (email/message/call/\u2026), its thread, the party's role, and when it occurred, newest first. Answers 'when and where did X show up'. Owner-scoped.",
|
|
3204
|
+
inputSchema: mRAG_graph_timeline_input,
|
|
3205
|
+
handler: mRAG_graph_timeline
|
|
3206
|
+
}
|
|
3207
|
+
];
|
|
3208
|
+
|
|
3209
|
+
// src/tools/actions.ts
|
|
3210
|
+
import { z as z16 } from "zod";
|
|
3211
|
+
var formField = z16.object({
|
|
3212
|
+
name: z16.string().min(1).max(60).describe("Field key \u2014 returned verbatim in the result."),
|
|
3213
|
+
label: z16.string().max(120).optional().describe("Human label shown to the recipient. Defaults to `name`."),
|
|
3214
|
+
type: z16.enum(["text", "email", "number", "textarea", "tel", "url"]).optional().describe("Input type. Default 'text'."),
|
|
3215
|
+
required: z16.boolean().optional().describe("Whether the recipient must fill this field.")
|
|
3216
|
+
});
|
|
3217
|
+
var action_create_input = z16.object({
|
|
3218
|
+
action_type: z16.enum(["confirm", "file_request", "form", "open_url", "screen_share"]).describe(
|
|
3219
|
+
"What you want the recipient to do: 'confirm' (yes/no), 'file_request' (pick a file from their computer), 'form' (fill fields), 'open_url' (open a vetted https URL), 'screen_share' (recipient shares their screen so you can SEE it via comms_action_frame_get \u2014 view only)."
|
|
3220
|
+
),
|
|
3221
|
+
message: z16.string().min(1).max(2e3).describe("What you're asking \u2014 shown on the consent screen above the action UI."),
|
|
3222
|
+
creator_label: z16.string().max(80).optional().describe("How you're identified to the recipient (e.g. your agent name). Default 'Agent'."),
|
|
3223
|
+
// confirm
|
|
3224
|
+
yes_label: z16.string().max(40).optional().describe("[confirm] Affirmative button label. Default 'Tak'."),
|
|
3225
|
+
no_label: z16.string().max(40).optional().describe("[confirm] Negative button label. Default 'Nie'."),
|
|
3226
|
+
// file_request
|
|
3227
|
+
accept: z16.string().max(200).optional().describe("[file_request] Accepted file types (HTML accept attr, e.g. 'image/*,.pdf')."),
|
|
3228
|
+
max_bytes: z16.number().int().positive().max(5242880).optional().describe("[file_request] Max file size in bytes (\u2264 5 MB). NOTE: the returned file is NOT yet end-to-end encrypted \u2014 do not request sensitive files until Tier 1.1 ships."),
|
|
3229
|
+
// form
|
|
3230
|
+
fields: z16.array(formField).min(1).max(20).optional().describe("[form] Fields to collect from the recipient."),
|
|
3231
|
+
// open_url
|
|
3232
|
+
url: z16.string().url().optional().describe("[open_url] The https URL to open. The full URL is shown to the recipient before they open it."),
|
|
3233
|
+
// screen_share
|
|
3234
|
+
max_width: z16.number().int().positive().max(1920).optional().describe("[screen_share] Max captured frame width in px (default 1280). Frames are downscaled JPEGs."),
|
|
3235
|
+
// lifecycle
|
|
3236
|
+
ttl_ms: z16.number().int().positive().optional().describe("Link lifetime in milliseconds. Default 24h, capped at 7d."),
|
|
3237
|
+
max_uses: z16.number().int().min(1).max(50).optional().describe("How many times the link can be redeemed. Default 1 (single-use).")
|
|
3238
|
+
});
|
|
3239
|
+
function buildParams(input) {
|
|
3240
|
+
switch (input.action_type) {
|
|
3241
|
+
case "confirm":
|
|
3242
|
+
return { message: input.message, yesLabel: input.yes_label, noLabel: input.no_label };
|
|
3243
|
+
case "file_request":
|
|
3244
|
+
return { message: input.message, accept: input.accept, maxBytes: input.max_bytes };
|
|
3245
|
+
case "form":
|
|
3246
|
+
if (!input.fields?.length) throw new Error("action_type 'form' requires a non-empty `fields` array.");
|
|
3247
|
+
return { message: input.message, fields: input.fields };
|
|
3248
|
+
case "open_url":
|
|
3249
|
+
if (!input.url) throw new Error("action_type 'open_url' requires `url`.");
|
|
3250
|
+
return { message: input.message, url: input.url };
|
|
3251
|
+
case "screen_share":
|
|
3252
|
+
return { message: input.message, maxWidth: input.max_width };
|
|
3253
|
+
default:
|
|
3254
|
+
return { message: input.message };
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
async function action_create(input, ctx) {
|
|
3258
|
+
readSupabaseEnv();
|
|
3259
|
+
ctx.log("debug", "action_create invoking action-create", { action_type: input.action_type });
|
|
3260
|
+
const body = {
|
|
3261
|
+
action_type: input.action_type,
|
|
3262
|
+
params: buildParams(input)
|
|
3263
|
+
};
|
|
3264
|
+
if (input.creator_label !== void 0) body.creator_label = input.creator_label;
|
|
3265
|
+
if (input.ttl_ms !== void 0) body.ttl_ms = input.ttl_ms;
|
|
3266
|
+
if (input.max_uses !== void 0) body.max_uses = input.max_uses;
|
|
3267
|
+
const res = await invokeFunction("action-create", body);
|
|
3268
|
+
if (res.error) throw new Error(res.error);
|
|
3269
|
+
if (!res.link || !res.token) throw new Error("action-create returned a malformed response (missing link/token).");
|
|
3270
|
+
return {
|
|
3271
|
+
action_id: res.action_id ?? "",
|
|
3272
|
+
token: res.token,
|
|
3273
|
+
link: res.link,
|
|
3274
|
+
action_type: res.action_type ?? input.action_type,
|
|
3275
|
+
expires_at: res.expires_at ?? ""
|
|
3276
|
+
};
|
|
3277
|
+
}
|
|
3278
|
+
var action_frame_get_input = z16.object({
|
|
3279
|
+
action_id: z16.string().min(1).describe("The action_id returned by comms_action_create for a 'screen_share' action you created.")
|
|
3280
|
+
});
|
|
3281
|
+
async function action_frame_get(input, ctx) {
|
|
3282
|
+
readSupabaseEnv();
|
|
3283
|
+
ctx.log("debug", "action_frame_get reading frame", { action_id: input.action_id });
|
|
3284
|
+
const sb = getSupabase();
|
|
3285
|
+
const { data, error } = await sb.from("action_screen_frames").select("image_jpeg, width, seq, updated_at").eq("action_id", input.action_id).maybeSingle();
|
|
3286
|
+
if (error) throw new Error(error.message);
|
|
3287
|
+
if (!data) {
|
|
3288
|
+
return { mcpContent: [{ type: "text", text: "No frame yet \u2014 the recipient hasn't started sharing their screen (or you don't own this action)." }] };
|
|
3289
|
+
}
|
|
3290
|
+
const row = data;
|
|
3291
|
+
const ageSec = Math.round((Date.now() - new Date(row.updated_at).getTime()) / 1e3);
|
|
3292
|
+
return {
|
|
3293
|
+
mcpContent: [
|
|
3294
|
+
{ type: "text", text: `Latest screen frame \u2014 seq ${row.seq}, ${row.width ?? "?"}px wide, ${ageSec}s old.` },
|
|
3295
|
+
{ type: "image", data: row.image_jpeg, mimeType: "image/jpeg" }
|
|
3296
|
+
]
|
|
3297
|
+
};
|
|
3298
|
+
}
|
|
3299
|
+
var actionTools = [
|
|
3300
|
+
{
|
|
3301
|
+
// RFC 0001: channel-agnostic capability (link is sent over ANY channel), so it
|
|
3302
|
+
// lives in the `comms_` namespace rather than a channel `m<MODULE>_` prefix.
|
|
3303
|
+
// A dedicated `mACT` module (create/get/status) is a possible RFC follow-up.
|
|
3304
|
+
name: "comms_action_create",
|
|
3305
|
+
title: "Create one-click action link",
|
|
3306
|
+
annotations: { readOnlyHint: false },
|
|
3307
|
+
requires: "network",
|
|
3308
|
+
description: "Mint a single-use, expiring action link (https://mosadd.com/do/<token>) that asks a human to DO something in their browser, with explicit consent. action_type: 'confirm' (yes/no) | 'file_request' (recipient picks a file from their computer) | 'form' (recipient fills fields you define) | 'open_url' (recipient opens a vetted https URL). Returns { action_id, token, link, expires_at }. Send the `link` to the person via mDM/mIRC/mp0st; they open it, consent, and the browser performs the action in its sandbox (no install, no OS access). The action is owned by you (the calling user). HONEST LIMITS: this is browser-sandbox only \u2014 it cannot click other apps, run programs, or read files the user didn't pick; and file_request payloads are not yet end-to-end encrypted (don't request sensitive files until Tier 1.1).",
|
|
3309
|
+
inputSchema: action_create_input,
|
|
3310
|
+
handler: action_create
|
|
3311
|
+
},
|
|
3312
|
+
{
|
|
3313
|
+
name: "comms_action_frame_get",
|
|
3314
|
+
title: "View shared screen frame",
|
|
3315
|
+
annotations: { readOnlyHint: true },
|
|
3316
|
+
requires: "network",
|
|
3317
|
+
description: "See the LATEST screen frame from a 'screen_share' action you created (pass the action_id from comms_action_create). Returns the current screenshot AS AN IMAGE you can look at, plus how old it is. The recipient must have opened the link and clicked 'share screen' first. Poll this every few seconds to watch live. VIEW ONLY \u2014 you cannot click or control their screen. Returns a 'no frame yet' note until they start sharing.",
|
|
3318
|
+
inputSchema: action_frame_get_input,
|
|
3319
|
+
handler: action_frame_get
|
|
3320
|
+
}
|
|
3321
|
+
];
|
|
3322
|
+
|
|
3323
|
+
// src/tools/presence.ts
|
|
3324
|
+
import { hostname as hostname2 } from "os";
|
|
3325
|
+
import { z as z17 } from "zod";
|
|
3326
|
+
var BEAT_MS = 6e4;
|
|
3327
|
+
var HOLD_SECONDS = 300;
|
|
3328
|
+
var UUID_RE2 = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
|
|
3329
|
+
var attachments = /* @__PURE__ */ new Map();
|
|
3330
|
+
var processBindings = /* @__PURE__ */ new Map();
|
|
3331
|
+
async function beat(env, identityId, host, mode) {
|
|
3332
|
+
await getSupabase(env).from("agent_bridge_heartbeat").upsert(
|
|
3333
|
+
{ identity_id: identityId, last_seen_at: (/* @__PURE__ */ new Date()).toISOString(), host, mode },
|
|
3334
|
+
{ onConflict: "identity_id" }
|
|
3335
|
+
);
|
|
3336
|
+
}
|
|
3337
|
+
async function resolveSelf(env) {
|
|
3338
|
+
const sb = getSupabase(env);
|
|
3339
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
3340
|
+
if (ue || !u?.user) {
|
|
3341
|
+
throw new Error(
|
|
3342
|
+
"Unable to resolve the current account. Set MOSADD_API_KEY (hub key) or MOSADD_USER_JWT, or run `mosadd login`."
|
|
3343
|
+
);
|
|
3344
|
+
}
|
|
3345
|
+
const { data, error } = await sb.from("identities").select("id, display_name, kind").eq("user_id", u.user.id).maybeSingle();
|
|
3346
|
+
if (error || !data) {
|
|
3347
|
+
throw new Error("This account has no mosadd identity row yet \u2014 sign in to mosadd.com once to create it.");
|
|
3348
|
+
}
|
|
3349
|
+
return {
|
|
3350
|
+
id: data.id,
|
|
3351
|
+
display_name: data.display_name ?? null,
|
|
3352
|
+
user_id: u.user.id,
|
|
3353
|
+
kind: data.kind ?? null
|
|
3354
|
+
};
|
|
3355
|
+
}
|
|
3356
|
+
async function resolveOwnedAgentLine(env, ownerUserId, ref) {
|
|
3357
|
+
const value = ref.trim();
|
|
3358
|
+
if (!value || /[(),]/.test(value)) return null;
|
|
3359
|
+
let q = getSupabase(env).from("identities").select("id, m0ssad_email, display_name").eq("kind", "agent").eq("owner_user_id", ownerUserId).is("retired_at", null);
|
|
3360
|
+
q = UUID_RE2.test(value) ? q.or(`id.eq.${value},m0ssad_email.eq.${value}`) : q.or(`m0ssad_email.eq.${value},display_name.eq.${value}`);
|
|
3361
|
+
const { data, error } = await q.limit(2);
|
|
3362
|
+
if (error || !data || data.length !== 1) return null;
|
|
3363
|
+
return data[0];
|
|
3364
|
+
}
|
|
3365
|
+
function stopAttachment(identityId) {
|
|
3366
|
+
const existing = attachments.get(identityId);
|
|
3367
|
+
if (existing) {
|
|
3368
|
+
clearInterval(existing.timer);
|
|
3369
|
+
attachments.delete(identityId);
|
|
3370
|
+
}
|
|
3371
|
+
}
|
|
3372
|
+
function startAttachment(env, identityId, host, mode, ctx) {
|
|
3373
|
+
const timer = setInterval(() => {
|
|
3374
|
+
void beat(env, identityId, host, mode).catch((e) => {
|
|
3375
|
+
ctx.log("warn", "comms_session_attach: beat failed", { identity_id: identityId, error: String(e) });
|
|
3376
|
+
});
|
|
3377
|
+
}, BEAT_MS);
|
|
3378
|
+
timer.unref?.();
|
|
3379
|
+
attachments.set(identityId, { timer, env });
|
|
3380
|
+
}
|
|
3381
|
+
var comms_session_attach_input = z17.object({
|
|
3382
|
+
label: z17.string().max(120).optional().describe(
|
|
3383
|
+
"Short name for THIS session, shown to the owner as who is holding the line (e.g. 'CTO \u2014 Claude Code', 'dispatcher \u2014 Cowork'). Defaults to the machine name."
|
|
3384
|
+
),
|
|
3385
|
+
as_agent: z17.string().max(200).optional().describe(
|
|
3386
|
+
"Speak as ONE OF THE OWNER'S AGENT LINES while holding the owner's key \u2014 its mosADD address (<agent>@mosadd.com), identity id, or display name. Declares ONCE per session whose line this session speaks for: the gateway then signs your CHANNEL posts as that agent automatically (no per-post `agent` field needed), and that agent's cloud stand-in defers to you. The server verifies you OWN the agent; a stranger's agent is refused. Omit to claim the key's own line, exactly as before."
|
|
3387
|
+
),
|
|
3388
|
+
release: z17.boolean().optional().describe(
|
|
3389
|
+
"Hand the line back immediately instead of claiming it: stops this session's keep-alive, clears the liveness row (and any as_agent declaration this session made), so the 24/7 cloud stand-in resumes answering at once rather than after the hold expires. Call this when the session is finishing."
|
|
3390
|
+
)
|
|
3391
|
+
});
|
|
3392
|
+
async function comms_session_attach(input, ctx) {
|
|
3393
|
+
const env = readSupabaseEnv();
|
|
3394
|
+
const self = await resolveSelf(env);
|
|
3395
|
+
const sb = getSupabase(env);
|
|
3396
|
+
if (input.release) {
|
|
3397
|
+
const toRelease = /* @__PURE__ */ new Set([self.id]);
|
|
3398
|
+
const bound = processBindings.get(self.user_id);
|
|
3399
|
+
if (bound) toRelease.add(bound);
|
|
3400
|
+
if (input.as_agent) {
|
|
3401
|
+
const agent = await resolveOwnedAgentLine(env, self.user_id, input.as_agent);
|
|
3402
|
+
if (agent) toRelease.add(agent.id);
|
|
3403
|
+
}
|
|
3404
|
+
for (const id of toRelease) {
|
|
3405
|
+
stopAttachment(id);
|
|
3406
|
+
const { error } = await sb.from("agent_bridge_heartbeat").delete().eq("identity_id", id);
|
|
3407
|
+
if (error) throw new Error(`Could not release the line: ${error.message}`);
|
|
3408
|
+
}
|
|
3409
|
+
const { error: relError } = await sb.rpc("mosadd_gateway_binding_release", {
|
|
3410
|
+
p_session_id: sessionId()
|
|
3411
|
+
});
|
|
3412
|
+
if (relError) {
|
|
3413
|
+
ctx.log("warn", "comms_session_attach: release RPC failed, line will lapse on its own", {
|
|
3414
|
+
error: relError.message
|
|
3415
|
+
});
|
|
3416
|
+
}
|
|
3417
|
+
processBindings.delete(self.user_id);
|
|
3418
|
+
ctx.log("info", "comms_session_attach: released", { identity_ids: [...toRelease] });
|
|
3419
|
+
return {
|
|
3420
|
+
attached: false,
|
|
3421
|
+
identity_id: self.id,
|
|
3422
|
+
display_name: self.display_name,
|
|
3423
|
+
note: "Line released (agent declaration cleared too). The 24/7 cloud stand-in answers from now on."
|
|
3424
|
+
};
|
|
3425
|
+
}
|
|
3426
|
+
const host = input.label?.trim() || `mcp:${hostname2()}`;
|
|
3427
|
+
const mode = "mcp-session";
|
|
3428
|
+
let lineId = self.id;
|
|
3429
|
+
let speakingAs;
|
|
3430
|
+
let przejeteOd;
|
|
3431
|
+
if (input.as_agent) {
|
|
3432
|
+
const agent = await resolveOwnedAgentLine(env, self.user_id, input.as_agent);
|
|
3433
|
+
if (!agent) {
|
|
3434
|
+
throw new Error(
|
|
3435
|
+
`No LIVE agent of yours matches "${input.as_agent}". You may only speak as an agent you OWN (its mosADD address, identity id, or display name) \u2014 never as someone else's agent or another human.`
|
|
3436
|
+
);
|
|
3437
|
+
}
|
|
3438
|
+
lineId = agent.id;
|
|
3439
|
+
speakingAs = { identity_id: agent.id, address: agent.m0ssad_email, display_name: agent.display_name };
|
|
3440
|
+
const { data: claim, error: bindError } = await sb.rpc("mosadd_gateway_binding_claim", {
|
|
3441
|
+
p_session_id: sessionId(),
|
|
3442
|
+
p_agent_identity_id: agent.id,
|
|
3443
|
+
p_agent_address: agent.m0ssad_email,
|
|
3444
|
+
p_host: host
|
|
3445
|
+
});
|
|
3446
|
+
if (bindError) throw new Error(`Could not declare the agent line: ${bindError.message}`);
|
|
3447
|
+
const wynik = claim ?? {};
|
|
3448
|
+
przejeteOd = wynik.took_over ? wynik.previous_session_id ?? null : void 0;
|
|
3449
|
+
if (wynik.took_over) {
|
|
3450
|
+
ctx.log("warn", "comms_session_attach: TOOK OVER the line from another session", {
|
|
3451
|
+
previous_session_id: wynik.previous_session_id ?? null
|
|
3452
|
+
});
|
|
3453
|
+
}
|
|
3454
|
+
processBindings.set(self.user_id, agent.id);
|
|
3455
|
+
}
|
|
3456
|
+
stopAttachment(lineId);
|
|
3457
|
+
try {
|
|
3458
|
+
await beat(env, lineId, host, mode);
|
|
3459
|
+
} catch (e) {
|
|
3460
|
+
throw new Error(`Could not claim the line: ${e instanceof Error ? e.message : String(e)}`);
|
|
3461
|
+
}
|
|
3462
|
+
startAttachment(env, lineId, host, mode, ctx);
|
|
3463
|
+
ctx.log("info", "comms_session_attach: line claimed", { identity_id: lineId, host, as_agent: speakingAs?.address });
|
|
3464
|
+
return {
|
|
3465
|
+
attached: true,
|
|
3466
|
+
identity_id: lineId,
|
|
3467
|
+
display_name: speakingAs ? speakingAs.display_name : self.display_name,
|
|
3468
|
+
...speakingAs ? { speaking_as: speakingAs } : {},
|
|
3469
|
+
host,
|
|
3470
|
+
holds_for_seconds: HOLD_SECONDS,
|
|
3471
|
+
...przejeteOd !== void 0 ? { took_over: true, previous_session_id: przejeteOd } : {},
|
|
3472
|
+
note: speakingAs ? `This session now speaks for ${speakingAs.address ?? speakingAs.identity_id}: channel posts sent through this gateway are signed as that agent automatically (an explicit \`agent\` field still wins), and the agent's cloud stand-in defers to you while the session runs. Call again with release:true to hand it back.` : "This session now owns the account's reply lane; the cloud stand-in will not answer while it is held. The hold renews itself for as long as this process runs and lapses on its own if the session dies. Call again with release:true to hand it back immediately."
|
|
3473
|
+
};
|
|
3474
|
+
}
|
|
3475
|
+
var presenceTools = [
|
|
3476
|
+
{
|
|
3477
|
+
name: "comms_session_attach",
|
|
3478
|
+
title: "Attach session to a line",
|
|
3479
|
+
annotations: { destructiveHint: false, idempotentHint: true },
|
|
3480
|
+
requires: "network",
|
|
3481
|
+
description: "Claim a mosADD reply lane for the CURRENT agent session, so the 24/7 cloud stand-in stops answering in its place and the owner talks to you instead. Call it once at the start of a session; the hold renews itself while the session runs and lapses on its own if the session dies. Holding the OWNER's key while working as one of their agent lines? Pass as_agent:'<address of YOUR line>' (e.g. <agent>@mosadd.com) \u2014 the gateway then signs your channel posts as that agent automatically for the whole session and silences that agent's stand-in; ownership is verified server-side. Pass release:true when finishing to hand everything back immediately. Owner-scoped: a session can only claim the account whose key it holds, or a line of an agent that account owns.",
|
|
3482
|
+
inputSchema: comms_session_attach_input,
|
|
3483
|
+
handler: comms_session_attach
|
|
3484
|
+
}
|
|
3485
|
+
];
|
|
3486
|
+
var lastAutoBeat = /* @__PURE__ */ new Map();
|
|
3487
|
+
var lastBindingCheck = /* @__PURE__ */ new Map();
|
|
3488
|
+
async function autoBeatFromActivity(ctx) {
|
|
3489
|
+
try {
|
|
3490
|
+
const env = readSupabaseEnv();
|
|
3491
|
+
const self = await resolveSelf(env);
|
|
3492
|
+
let lineId = null;
|
|
3493
|
+
if (self.kind === "agent") {
|
|
3494
|
+
lineId = self.id;
|
|
3495
|
+
} else if (processBindings.has(self.user_id)) {
|
|
3496
|
+
lineId = processBindings.get(self.user_id);
|
|
3497
|
+
} else {
|
|
3498
|
+
const now2 = Date.now();
|
|
3499
|
+
if (now2 - (lastBindingCheck.get(self.user_id) ?? 0) >= BEAT_MS) {
|
|
3500
|
+
lastBindingCheck.set(self.user_id, now2);
|
|
3501
|
+
const { data } = await getSupabase(env).from("mosadd_gateway_agent_binding").select("agent_identity_id, bound_at").eq("user_id", self.user_id).eq("session_id", sessionId()).maybeSingle();
|
|
3502
|
+
if (data && Date.now() - new Date(data.bound_at).getTime() <= 24 * 60 * 60 * 1e3) {
|
|
3503
|
+
lineId = data.agent_identity_id;
|
|
3504
|
+
processBindings.set(self.user_id, lineId);
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
if (!lineId) return;
|
|
3509
|
+
const now = Date.now();
|
|
3510
|
+
const last = lastAutoBeat.get(lineId) ?? 0;
|
|
3511
|
+
if (now - last < BEAT_MS) return;
|
|
3512
|
+
lastAutoBeat.set(lineId, now);
|
|
3513
|
+
await beat(env, lineId, `mcp:auto (${hostname2()})`, "mcp-activity");
|
|
3514
|
+
} catch (e) {
|
|
3515
|
+
ctx.log("debug", "autoBeatFromActivity skipped", { error: String(e) });
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
|
|
3519
|
+
// src/tools/embed.ts
|
|
3520
|
+
import { z as z18 } from "zod";
|
|
3521
|
+
var EMBED_CDN = (process.env.MOSADD_EMBED_CDN ?? "https://embed.mosadd.com").replace(/\/+$/, "");
|
|
3522
|
+
var POSITIONS = ["inline", "sidebar-left", "sidebar-right", "floating-bl", "floating-br", "fullscreen"];
|
|
3523
|
+
var SKINS = ["default", "retro-irc-1990", "terminal", "minimal-dark", "minimal-light"];
|
|
3524
|
+
var embed_create_input = z18.object({
|
|
3525
|
+
channel: z18.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/).describe("The mIRC channel id everyone on the embed shares (e.g. 'acme-support'). Auto-created on first message if new."),
|
|
3526
|
+
allowed_origins: z18.array(z18.string().min(1)).min(1).max(10).describe("REQUIRED. Domain(s) where the widget will be served \u2014 the key only works from these origins. Use the host(s) of the app you're building, e.g. ['app.acme.com','*.acme.com']. For local testing use mode:'test' and e.g. 'localhost:3000'."),
|
|
3527
|
+
name: z18.string().max(64).optional().describe("Label for the key in the owner's dashboard. Default 'embed: <channel>'."),
|
|
3528
|
+
position: z18.enum(POSITIONS).optional().describe("Where the widget renders. Default 'inline'."),
|
|
3529
|
+
skin: z18.enum(SKINS).optional().describe("Visual skin. Default 'default' (mosadd-branded retro mIRC)."),
|
|
3530
|
+
title: z18.string().max(60).optional().describe("Header title shown in the widget. Default 'mIRC'."),
|
|
3531
|
+
anon: z18.boolean().optional().describe("Allow visitors to join with just a nick (no mosadd account). Default true."),
|
|
3532
|
+
locale: z18.enum(["en", "pl"]).optional().describe("Widget UI language. Default 'en'."),
|
|
3533
|
+
mode: z18.enum(["live", "test"]).optional().describe("Key mode \u2014 'test' for local/dev origins, 'live' for production. Default 'live'.")
|
|
3534
|
+
});
|
|
3535
|
+
var attrSafe = (s) => s.replace(/["'<>]/g, "");
|
|
3536
|
+
function buildSnippet(input, key) {
|
|
3537
|
+
const attrs = [`data-channel="${attrSafe(input.channel)}"`, `data-position="${input.position ?? "inline"}"`];
|
|
3538
|
+
if (input.skin) attrs.push(`data-skin="${input.skin}"`);
|
|
3539
|
+
if (input.title) attrs.push(`data-title="${attrSafe(input.title)}"`);
|
|
3540
|
+
if (input.anon === false) attrs.push(`data-anon="false"`);
|
|
3541
|
+
if (input.locale) attrs.push(`data-locale="${input.locale}"`);
|
|
3542
|
+
return `<div id="mosadd-mirc" ${attrs.join(" ")}></div>
|
|
3543
|
+
<script src="${EMBED_CDN}/v1.js" data-key="${key}"></script>`;
|
|
3544
|
+
}
|
|
3545
|
+
async function embed_create(input, ctx) {
|
|
3546
|
+
readSupabaseEnv();
|
|
3547
|
+
ctx.log("debug", "comms_embed_create minting embed key", { channel: input.channel, origins: input.allowed_origins.length });
|
|
3548
|
+
const res = await invokeFunction("embed-keys", {
|
|
3549
|
+
name: input.name ?? `embed: ${input.channel}`,
|
|
3550
|
+
channels: [input.channel],
|
|
3551
|
+
allowed_origins: input.allowed_origins,
|
|
3552
|
+
mode: input.mode ?? "live"
|
|
3553
|
+
});
|
|
3554
|
+
if (res.error) throw new Error(res.error);
|
|
3555
|
+
if (!res.key) throw new Error("embed-keys returned no publishable key (missing `key`).");
|
|
3556
|
+
return {
|
|
3557
|
+
embed_key: res.key,
|
|
3558
|
+
channel: input.channel,
|
|
3559
|
+
allowed_origins: input.allowed_origins,
|
|
3560
|
+
snippet: buildSnippet(input, res.key)
|
|
3561
|
+
};
|
|
3562
|
+
}
|
|
3563
|
+
var embedTools = [
|
|
3564
|
+
{
|
|
3565
|
+
name: "comms_embed_create",
|
|
3566
|
+
title: "Create website embed",
|
|
3567
|
+
annotations: { readOnlyHint: false },
|
|
3568
|
+
requires: "network",
|
|
3569
|
+
description: "Embed a LIVE mosadd chat channel into an app/site you're building (great for builder-agents on Lovable/Bolt/Cursor/v0). Mints a publishable embed key scoped to a channel + the app's domain(s) and returns a ready-to-paste HTML snippet (a <div> + <script src=embed.mosadd.com/v1.js data-key=\u2026>). Visitors of the host page chat in real time (anonymous nick or mosadd login). REQUIRES `allowed_origins` \u2014 the domain(s) the app is served from (the key only works there). The publishable key is browser-safe (mints only channel-scoped JWTs); your hub key never leaves the server. Returns { embed_key, channel, allowed_origins, snippet }.",
|
|
3570
|
+
inputSchema: embed_create_input,
|
|
3571
|
+
handler: embed_create
|
|
3572
|
+
}
|
|
3573
|
+
];
|
|
3574
|
+
|
|
3575
|
+
// src/tools/threat.ts
|
|
3576
|
+
import { z as z19 } from "zod";
|
|
3577
|
+
import {
|
|
3578
|
+
THREAT_EVENTS,
|
|
3579
|
+
THREAT_EVENT_COUNT,
|
|
3580
|
+
evaluateEvent,
|
|
3581
|
+
getEventDef
|
|
3582
|
+
} from "@mosadd/threat-engine";
|
|
3583
|
+
var threat_catalog_input = z19.object({
|
|
3584
|
+
category: z19.enum(["COMINT", "ELINT", "MASINT", "CYBER", "BEHAVIORAL", "PRIVACY", "SIGINT", "OSINT", "MPOST"]).optional().describe("Filter the catalog to one intelligence-discipline category. Omit for the full catalog."),
|
|
3585
|
+
platform: z19.enum(["apk", "ios", "pwa", "harmony"]).optional().describe("Filter to events detectable on this platform. Omit for all platforms.")
|
|
3586
|
+
});
|
|
3587
|
+
async function threat_catalog(input, _ctx) {
|
|
3588
|
+
let events = THREAT_EVENTS;
|
|
3589
|
+
if (input.category) events = events.filter((e) => e.category === input.category);
|
|
3590
|
+
if (input.platform) events = events.filter((e) => e.platforms.includes(input.platform));
|
|
3591
|
+
return { count: events.length, total: THREAT_EVENT_COUNT, events };
|
|
3592
|
+
}
|
|
3593
|
+
var threat_classify_input = z19.object({
|
|
3594
|
+
event_type: z19.string().min(1).max(120).describe('Event type to classify, e.g. "SIM_SWAP", "AUTH_BRUTEFORCE", "TOLL_FRAUD". Case-insensitive.'),
|
|
3595
|
+
severity: z19.string().optional().describe('Optional producer severity hint. "killswitch" \u2192 lock_account; "critical" \u2192 revoke_sessions; anything else is informational.'),
|
|
3596
|
+
details: z19.string().max(2e3).optional().describe("Optional free-text context (informational only).")
|
|
3597
|
+
});
|
|
3598
|
+
async function threat_classify(input, _ctx) {
|
|
3599
|
+
const def = getEventDef(String(input.event_type).toUpperCase());
|
|
3600
|
+
if (def) {
|
|
3601
|
+
return {
|
|
3602
|
+
action: "monitor",
|
|
3603
|
+
severity: def.severity,
|
|
3604
|
+
reason: `${def.label} (${def.category}) \u2014 classified from the mosadd threat taxonomy. Monitor-only: surfaced for you to act on, no automatic action taken.`,
|
|
3605
|
+
known_event: true,
|
|
3606
|
+
category: def.category,
|
|
3607
|
+
label: def.label
|
|
3608
|
+
};
|
|
3609
|
+
}
|
|
3610
|
+
const decision = evaluateEvent({ eventType: input.event_type, severity: input.severity, details: input.details });
|
|
3611
|
+
return { ...decision, known_event: false, category: null, label: null };
|
|
3612
|
+
}
|
|
3613
|
+
var threatTools = [
|
|
3614
|
+
{
|
|
3615
|
+
name: "threat_catalog",
|
|
3616
|
+
title: "Threat taxonomy catalog",
|
|
3617
|
+
annotations: { readOnlyHint: true },
|
|
3618
|
+
requires: "any",
|
|
3619
|
+
description: "List the canonical mosadd threat-event taxonomy (the full radar catalog: id, category, default severity, auto-actions, per-platform availability). Filter by category or platform. Pure/offline \u2014 returns { count, total, events }. Use to discover what the defensive engine recognises.",
|
|
3620
|
+
inputSchema: threat_catalog_input,
|
|
3621
|
+
handler: threat_catalog
|
|
3622
|
+
},
|
|
3623
|
+
{
|
|
3624
|
+
name: "threat_classify",
|
|
3625
|
+
title: "Classify threat event",
|
|
3626
|
+
annotations: { readOnlyHint: true },
|
|
3627
|
+
requires: "any",
|
|
3628
|
+
description: `Classify a single telemetry event against the mosadd threat taxonomy + DECK engine. For a known event type (e.g. PROCESS_INJECTION, STINGRAY_DETECT, IMSI_CATCHER_SCAN, MEMORY_INJECTION) it returns that event's real severity (info|warning|elevated|critical|killswitch) with action="monitor" \u2014 Pegasus-class events surface as critical immediately, but the engine NEVER auto-acts (it tells you, it never disconnects/locks). Unknown strings fall back to the pure DECK decision (log_only|revoke_sessions|lock_account|suspend_did). Returns { action, severity, reason, known_event, category, label }. Deterministic, offline, no backend.`,
|
|
3629
|
+
inputSchema: threat_classify_input,
|
|
3630
|
+
handler: threat_classify
|
|
3631
|
+
}
|
|
3632
|
+
];
|
|
3633
|
+
|
|
3634
|
+
// src/tools/murl.ts
|
|
3635
|
+
import { z as z20 } from "zod";
|
|
3636
|
+
var DEFAULT_EDGE_URL2 = "https://mosadd-edge.mr-brics-33.workers.dev";
|
|
3637
|
+
function edgeUrl2() {
|
|
3638
|
+
return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL2;
|
|
3639
|
+
}
|
|
3640
|
+
function hubKey3() {
|
|
3641
|
+
const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
|
|
3642
|
+
if (!key) throw new Error("MOSADD_API_KEY required for mURL tools (see `mosadd login` / hub-keys).");
|
|
3643
|
+
return key;
|
|
3644
|
+
}
|
|
3645
|
+
function urlToSlug(input) {
|
|
3646
|
+
let s = String(input).trim().toLowerCase();
|
|
3647
|
+
s = s.replace(/^[a-z]+:\/\//, "").replace(/[?#].*$/, "");
|
|
3648
|
+
const slash = s.indexOf("/");
|
|
3649
|
+
let host = (slash >= 0 ? s.slice(0, slash) : s).replace(/:\d+$/, "");
|
|
3650
|
+
if (host.startsWith("www.")) host = host.slice(4);
|
|
3651
|
+
if (!host || !/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(host)) {
|
|
3652
|
+
throw new Error(`Invalid URL: "${input}" \u2014 pass a domain like "example.com" or a full URL.`);
|
|
3653
|
+
}
|
|
3654
|
+
const segs = (slash >= 0 ? s.slice(slash) : "").split("/").map((seg) => seg.replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "")).filter(Boolean);
|
|
3655
|
+
const base = host.replace(/\./g, "-");
|
|
3656
|
+
return { domain: host, slug: segs.length ? `${base}__${segs.join("__")}` : base };
|
|
3657
|
+
}
|
|
3658
|
+
var DomainArg = z20.string().min(3).max(2048).describe("A domain ('example.com') or a full URL. Keyed PER-URL: a bare domain \u2192 the domain room; a URL with a path (e.g. 'site.com/articles/abc') \u2192 that page's own room.");
|
|
3659
|
+
var mURL_read_channel_input = z20.object({
|
|
3660
|
+
domain: DomainArg,
|
|
3661
|
+
limit: z20.number().int().min(1).max(100).optional().describe("Recent messages to return (max 100). Default 50.")
|
|
3662
|
+
});
|
|
3663
|
+
async function mURL_read_channel(input, ctx) {
|
|
3664
|
+
const { domain, slug: slug2 } = urlToSlug(input.domain);
|
|
3665
|
+
const limit = input.limit ?? 50;
|
|
3666
|
+
ctx.log("debug", "mURL_read_channel", { domain });
|
|
3667
|
+
const r = await fetch(`${edgeUrl2()}/c/${slug2}/history?limit=${limit}`, {
|
|
3668
|
+
headers: { Authorization: `Bearer ${hubKey3()}` }
|
|
3669
|
+
});
|
|
3670
|
+
if (!r.ok) {
|
|
3671
|
+
const e = await r.text().catch(() => "");
|
|
3672
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
3673
|
+
}
|
|
3674
|
+
const data = await r.json();
|
|
3675
|
+
return {
|
|
3676
|
+
domain,
|
|
3677
|
+
messages: (data.messages ?? []).map((m) => ({ id: m.id, from: m.from ?? null, text: m.text, timestamp: m.ts }))
|
|
3678
|
+
};
|
|
3679
|
+
}
|
|
3680
|
+
var mURL_post_input = z20.object({
|
|
3681
|
+
domain: DomainArg,
|
|
3682
|
+
text: z20.string().min(1).max(2e3).describe("Message body (max 2000 chars, up to 3 lines \u2014 Worker-enforced)."),
|
|
3683
|
+
from: z20.string().max(120).optional().describe("Sender hint shown to others (defaults to the hub-key owner / your agent name).")
|
|
3684
|
+
});
|
|
3685
|
+
async function mURL_post(input, ctx) {
|
|
3686
|
+
const { domain, slug: slug2 } = urlToSlug(input.domain);
|
|
3687
|
+
ctx.log("debug", "mURL_post", { domain });
|
|
3688
|
+
const r = await fetch(`${edgeUrl2()}/c/${slug2}/send`, {
|
|
3689
|
+
method: "POST",
|
|
3690
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${hubKey3()}` },
|
|
3691
|
+
body: JSON.stringify({ text: input.text, from: input.from })
|
|
3692
|
+
});
|
|
3693
|
+
if (!r.ok) {
|
|
3694
|
+
const e = await r.text().catch(() => "");
|
|
3695
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
3696
|
+
}
|
|
3697
|
+
const data = await r.json();
|
|
3698
|
+
if (!data?.id) throw new Error("mosadd-edge: send returned no id");
|
|
3699
|
+
return { domain, message_id: data.id, posted_at: data.ts ?? Date.now() };
|
|
3700
|
+
}
|
|
3701
|
+
var mURL_list_channels_input = z20.object({
|
|
3702
|
+
action: z20.enum(["trending", "list", "mine"]).optional().describe("'trending' (default) = most active domain channels in the last N hours; 'list' = paginated catalogue filtered by status; 'mine' = channels you own (DNS-verified)."),
|
|
3703
|
+
limit: z20.number().int().min(1).max(100).optional().describe("Max channels to return. Default 20."),
|
|
3704
|
+
hours: z20.number().int().min(1).max(168).optional().describe("Trending window in hours. Default 24, max 168 (7d)."),
|
|
3705
|
+
status: z20.enum(["open", "claimed", "blocked"]).optional().describe("For action='list': filter (default 'open')."),
|
|
3706
|
+
cursor: z20.string().optional().describe("For action='list': pagination \u2014 pass previous response's next_cursor (created_at ISO).")
|
|
3707
|
+
});
|
|
3708
|
+
async function mURL_list_channels(input, ctx) {
|
|
3709
|
+
readSupabaseEnv();
|
|
3710
|
+
const action = input.action ?? "trending";
|
|
3711
|
+
ctx.log("debug", "mURL_list_channels invoking murl-channels", { action });
|
|
3712
|
+
return await invokeFunction("murl-channels", {
|
|
3713
|
+
action,
|
|
3714
|
+
limit: input.limit ?? null,
|
|
3715
|
+
hours: input.hours ?? null,
|
|
3716
|
+
status: input.status ?? null,
|
|
3717
|
+
cursor: input.cursor ?? null
|
|
3718
|
+
});
|
|
3719
|
+
}
|
|
3720
|
+
var mURL_presence_input = z20.object({ domain: DomainArg });
|
|
3721
|
+
async function mURL_presence(input, ctx) {
|
|
3722
|
+
const { domain, slug: slug2 } = urlToSlug(input.domain);
|
|
3723
|
+
ctx.log("debug", "mURL_presence", { domain });
|
|
3724
|
+
const r = await fetch(`${edgeUrl2()}/c/${slug2}/presence`);
|
|
3725
|
+
if (!r.ok) {
|
|
3726
|
+
const e = await r.text().catch(() => "");
|
|
3727
|
+
throw new Error(`mosadd-edge ${r.status}: ${e.slice(0, 200)}`);
|
|
3728
|
+
}
|
|
3729
|
+
const data = await r.json();
|
|
3730
|
+
return { domain, count: data.count ?? 0, roster: data.roster ?? [], status: data.status ?? "open" };
|
|
3731
|
+
}
|
|
3732
|
+
var mURL_create_input = z20.object({
|
|
3733
|
+
domain: DomainArg,
|
|
3734
|
+
branding: z20.record(z20.string(), z20.any()).optional().describe("Optional branding JSON (e.g. display name, colour, avatar URL) shown on the channel."),
|
|
3735
|
+
status: z20.enum(["open", "claimed", "blocked"]).optional().describe(
|
|
3736
|
+
"Status for a channel that does NOT exist yet: 'open' (default) = public agent-native room; 'claimed' = registered as yours; 'blocked' = closed. IGNORED if the channel already exists \u2014 murl-manage applies status only on the INSERT of a new row; on an existing row it writes owner + branding and leaves status untouched. mURL rooms auto-create on first activity, so an existing room is the common case: change its status with mURL_update."
|
|
3737
|
+
)
|
|
3738
|
+
});
|
|
3739
|
+
async function mURL_create(input, ctx) {
|
|
3740
|
+
readSupabaseEnv();
|
|
3741
|
+
const { domain } = urlToSlug(input.domain);
|
|
3742
|
+
ctx.log("debug", "mURL_create invoking murl-manage", { domain });
|
|
3743
|
+
return await invokeFunction("murl-manage", {
|
|
3744
|
+
action: "create",
|
|
3745
|
+
domain,
|
|
3746
|
+
branding: input.branding ?? null,
|
|
3747
|
+
status: input.status ?? null
|
|
3748
|
+
});
|
|
3749
|
+
}
|
|
3750
|
+
var mURL_update_input = z20.object({
|
|
3751
|
+
domain: DomainArg,
|
|
3752
|
+
branding: z20.record(z20.string(), z20.any()).optional().describe("New branding JSON to set on the channel."),
|
|
3753
|
+
status: z20.enum(["open", "claimed", "blocked"]).optional().describe("New status: 'claimed' to mark owned, 'blocked' to close the room, 'open' to reopen.")
|
|
3754
|
+
});
|
|
3755
|
+
async function mURL_update(input, ctx) {
|
|
3756
|
+
readSupabaseEnv();
|
|
3757
|
+
const { domain } = urlToSlug(input.domain);
|
|
3758
|
+
const slug2 = domain.replace(/\./g, "-");
|
|
3759
|
+
ctx.log("debug", "mURL_update invoking murl-manage", { domain });
|
|
3760
|
+
return await invokeFunction("murl-manage", {
|
|
3761
|
+
action: "update",
|
|
3762
|
+
slug: slug2,
|
|
3763
|
+
branding: input.branding ?? null,
|
|
3764
|
+
status: input.status ?? null
|
|
3765
|
+
});
|
|
3766
|
+
}
|
|
3767
|
+
var mURL_delete_input = z20.object({ domain: DomainArg });
|
|
3768
|
+
async function mURL_delete(input, ctx) {
|
|
3769
|
+
readSupabaseEnv();
|
|
3770
|
+
const { domain } = urlToSlug(input.domain);
|
|
3771
|
+
const slug2 = domain.replace(/\./g, "-");
|
|
3772
|
+
ctx.log("debug", "mURL_delete invoking murl-manage", { domain });
|
|
3773
|
+
return await invokeFunction("murl-manage", { action: "delete", slug: slug2 });
|
|
3774
|
+
}
|
|
3775
|
+
var murlTools = [
|
|
3776
|
+
{
|
|
3777
|
+
name: "mURL_read_channel",
|
|
3778
|
+
title: "Read domain channel",
|
|
3779
|
+
annotations: { readOnlyHint: true },
|
|
3780
|
+
requires: "network",
|
|
3781
|
+
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).",
|
|
3782
|
+
inputSchema: mURL_read_channel_input,
|
|
3783
|
+
handler: mURL_read_channel
|
|
3784
|
+
},
|
|
3785
|
+
{
|
|
3786
|
+
name: "mURL_post",
|
|
3787
|
+
title: "Post to domain channel",
|
|
3788
|
+
annotations: { readOnlyHint: false },
|
|
3789
|
+
requires: "network",
|
|
3790
|
+
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).",
|
|
3791
|
+
inputSchema: mURL_post_input,
|
|
3792
|
+
handler: mURL_post
|
|
3793
|
+
},
|
|
3794
|
+
{
|
|
3795
|
+
name: "mURL_presence",
|
|
3796
|
+
title: "Who is on a domain now",
|
|
3797
|
+
annotations: { readOnlyHint: true },
|
|
3798
|
+
requires: "network",
|
|
3799
|
+
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.",
|
|
3800
|
+
inputSchema: mURL_presence_input,
|
|
3801
|
+
handler: mURL_presence
|
|
3802
|
+
},
|
|
3803
|
+
{
|
|
3804
|
+
name: "mURL_list_channels",
|
|
3805
|
+
title: "List / trending domain channels",
|
|
3806
|
+
annotations: { readOnlyHint: true },
|
|
3807
|
+
requires: "network",
|
|
3808
|
+
description: "Discovery for mURL domain channels: 'trending' (most active in the last N hours, default 24) / 'list' (paginated catalogue, status-filtered) / 'mine' (channels you DNS-verified). Returns domain, slug, status, branding, verified_at + (for trending) messages_in_window. For who's-on-now, follow up with mURL_presence on the slug.",
|
|
3809
|
+
inputSchema: mURL_list_channels_input,
|
|
3810
|
+
handler: mURL_list_channels
|
|
3811
|
+
},
|
|
3812
|
+
{
|
|
3813
|
+
name: "mURL_create",
|
|
3814
|
+
title: "Claim domain channel",
|
|
3815
|
+
annotations: { readOnlyHint: false },
|
|
3816
|
+
requires: "network",
|
|
3817
|
+
description: "Create / claim the mURL channel for a web DOMAIN and register YOU as its owner (idempotent \u2014 returns the existing channel if you already own it; fails with 'claimed_by_other' if another account owns it). Optionally set branding, and `status` ONLY when the channel is being created for the first time: on a channel that already exists (mURL rooms auto-create on first activity) murl-manage writes owner + branding and IGNORES status \u2014 use mURL_update to change the status of an existing room. Owner-side: needs your mosADD login session (user JWT via `mosadd login`), not just a hub key \u2014 same as mURL_list_channels action='mine'. Backend: murl-manage EF.",
|
|
3818
|
+
inputSchema: mURL_create_input,
|
|
3819
|
+
handler: mURL_create
|
|
3820
|
+
},
|
|
3821
|
+
{
|
|
3822
|
+
name: "mURL_update",
|
|
3823
|
+
title: "Update domain channel",
|
|
3824
|
+
annotations: { readOnlyHint: false },
|
|
3825
|
+
requires: "network",
|
|
3826
|
+
description: "Update a mURL DOMAIN channel you own: set branding, mark it 'claimed', 'blocked' (close the room), or reopen it as 'open'. Owner-scoped \u2014 you must own the channel (claim it first with mURL_create). Needs your mosADD login session. Backend: murl-manage EF.",
|
|
3827
|
+
inputSchema: mURL_update_input,
|
|
3828
|
+
handler: mURL_update
|
|
3829
|
+
},
|
|
3830
|
+
{
|
|
3831
|
+
name: "mURL_delete",
|
|
3832
|
+
title: "Delete domain channel",
|
|
3833
|
+
annotations: { destructiveHint: true },
|
|
3834
|
+
requires: "network",
|
|
3835
|
+
description: "Delete a mURL DOMAIN channel you own (removes its domain_controls row; the room stops being served). Owner-scoped \u2014 you must own it. Needs your mosADD login session. Backend: murl-manage EF.",
|
|
3836
|
+
inputSchema: mURL_delete_input,
|
|
3837
|
+
handler: mURL_delete
|
|
3838
|
+
}
|
|
3839
|
+
];
|
|
3840
|
+
|
|
3841
|
+
// src/tools/capabilities.ts
|
|
3842
|
+
import { z as z21 } from "zod";
|
|
3843
|
+
var CONTRACT_VERSION = "1.0.0";
|
|
3844
|
+
var ALL_REQUIREMENTS = ["any", "radio", "network"];
|
|
3845
|
+
function buildCapabilityManifest(tools) {
|
|
3846
|
+
const entries = tools.map((t) => ({ name: t.name, requires: t.requires }));
|
|
3847
|
+
const by_requirement = {
|
|
3848
|
+
any: [],
|
|
3849
|
+
radio: [],
|
|
3850
|
+
network: []
|
|
3851
|
+
};
|
|
3852
|
+
for (const e of entries) by_requirement[e.requires].push(e.name);
|
|
3853
|
+
return {
|
|
3854
|
+
contract_version: CONTRACT_VERSION,
|
|
3855
|
+
requirements: ALL_REQUIREMENTS,
|
|
3856
|
+
tools: entries,
|
|
3857
|
+
by_requirement
|
|
3858
|
+
};
|
|
3859
|
+
}
|
|
3860
|
+
function makeCapabilitiesTool(channelTools2) {
|
|
3861
|
+
const tool = {
|
|
3862
|
+
name: "comms_capabilities",
|
|
3863
|
+
title: "List tool capabilities",
|
|
3864
|
+
annotations: { readOnlyHint: true },
|
|
3865
|
+
requires: "any",
|
|
3866
|
+
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.",
|
|
3867
|
+
inputSchema: z21.object({}),
|
|
3868
|
+
handler: async () => buildCapabilityManifest([...channelTools2, tool])
|
|
3869
|
+
};
|
|
3870
|
+
return tool;
|
|
3871
|
+
}
|
|
3872
|
+
|
|
3873
|
+
// src/tools/index.ts
|
|
3874
|
+
var channelTools = [
|
|
3875
|
+
...mdmTools,
|
|
3876
|
+
...mdmAsAgentTools,
|
|
3877
|
+
...mdmVoiceTools,
|
|
3878
|
+
...mircTools,
|
|
3879
|
+
...mircMembersTools,
|
|
3880
|
+
...mircMessagesTools,
|
|
3881
|
+
...mircEdgeTools,
|
|
3882
|
+
// ...mroomTools, // mROOM: killed (LINEAR-3414) — channel re-cut into ephemeral private mIRC
|
|
3883
|
+
// ...mroomMessagesTools, // mROOM: killed (LINEAR-3414)
|
|
3884
|
+
...mailTools,
|
|
3885
|
+
// mAYL_*: canonical email module (was the mp0st codename; renamed re-arch 2026-06-27)
|
|
3886
|
+
// ...mailAliasTools, // mp0st_* aliases RETIRED 2026-07-15 — mAYL is the one name; the mp0st codename is now backend-internal only
|
|
3887
|
+
// ⭐ mAYL_send_as_agent: RE-REGISTERED 2026-07-29 — proven end to end, without sending mail.
|
|
3888
|
+
// Unregistered since 07-14 on the note "hub-claim EF 404s every call". That note was stale in
|
|
3889
|
+
// the same way ptt-ingest's was: unauthenticated it returns 401 (the auth gate), not 404.
|
|
3890
|
+
//
|
|
3891
|
+
// Settled by running the whole chain rather than the convenient half:
|
|
3892
|
+
// 1. hub-keys with a plain user JWT issued a real `mosadd_sk_live_…` — so a user session
|
|
3893
|
+
// mints a hub key and no founder credential was ever needed. I had told the founder it
|
|
3894
|
+
// required his key; that was wrong and this is the retraction.
|
|
3895
|
+
// 2. hub-claim-mint with that key → 200, valid claim token, aud `mp0st-send`, 600s expiry.
|
|
3896
|
+
// 3. mp0st-send with the claim token and a DELIBERATELY EMPTY payload → 400 "Missing to or
|
|
3897
|
+
// subject". A 400 on payload validation proves the token was ACCEPTED; 401/403 would have
|
|
3898
|
+
// proven it was not. Auth verified end to end with zero mail sent — a diagnostic must not
|
|
3899
|
+
// put a real message in someone's inbox.
|
|
3900
|
+
// The diagnostic key was then REVOKED (revoked_at set, not deleted, so the audit trail lives).
|
|
3901
|
+
...mailProvenanceTools,
|
|
3902
|
+
// mAYL_agentbox_provision/list/release/extend — the agent mints/lists/releases/extends its OWN
|
|
3903
|
+
// real, two-way, disposable inbox (agent-<hex>@mosadd.com). create_inbox parity with AgentMail,
|
|
3904
|
+
// on our own stack + provenance. Backs the live mayl-agentbox EF; receive path landed 2026-08-06
|
|
3905
|
+
// in mp0st-inbound-webhook (LINEAR-5201). Same requireUser auth as every other mAYL tool.
|
|
3906
|
+
...mailAgentboxTools,
|
|
3907
|
+
...mtalkTools,
|
|
3908
|
+
...attachmentTools,
|
|
3909
|
+
// ⭐ mTALK_ingest_ptt: RE-REGISTERED 2026-07-29 — the backend finally does what the tool promises.
|
|
3910
|
+
// Unregistered since 07-14 on the note "ptt-ingest EF 400s every call". Re-measured 07-29: that
|
|
3911
|
+
// reason was stale (it returned 401, the auth gate), and an AUTHENTICATED probe then exposed the
|
|
3912
|
+
// real fault — 500, `Could not find the table 'public.rag_jobs'`. It authenticated, validated,
|
|
3913
|
+
// wrote the transcript row, and died one step later against a table dropped when the rag_events
|
|
3914
|
+
// v2 queue landed. Agent push-to-talk had NEVER once reached memory.
|
|
3915
|
+
//
|
|
3916
|
+
// Fixed by handing the audio to `rag-transcribe` (NOT to the v2 queue — that queue carries TEXT
|
|
3917
|
+
// for embedding and cannot transcribe; audio has to become words first). Verified on prod:
|
|
3918
|
+
// 200 {"queued":true}, edge log 200 in 2.7s where it used to 500, and the transcript row's
|
|
3919
|
+
// updated_at moved 4s after insert, so the backgrounded chain genuinely ran.
|
|
3920
|
+
//
|
|
3921
|
+
// Registered only AFTER that authenticated 200 — a liveness probe was never enough, because the
|
|
3922
|
+
// whole point of this registry is that an agent sees only tools that actually work.
|
|
3923
|
+
...pttIngestTools,
|
|
3924
|
+
//
|
|
3925
|
+
// ✅ RESOLVED 2026-07-29 — both halves of this note are closed; kept as the record of how.
|
|
3926
|
+
// The disable note recorded a diagnosis from 2026-07-14: hub-claim "404s every call".
|
|
3927
|
+
// Live-probed today, unauthenticated:
|
|
3928
|
+
// hub-claim-mint → 401 · ptt-ingest → 401 · mp0st-send → 401 (the control, a tool that
|
|
3929
|
+
// IS registered and works)
|
|
3930
|
+
// 401 is the auth gate answering. A dead or missing function returns 404; a function that
|
|
3931
|
+
// rejects our payload shape returns 400. Neither happens any more, and both are ACTIVE on
|
|
3932
|
+
// the project. So whatever was broken in July was fixed at some point and nobody came back
|
|
3933
|
+
// to these lines — we advertised two capabilities as unavailable while their backends
|
|
3934
|
+
// answered. One of them (ptt) is now proven and registered; this is the other.
|
|
3935
|
+
//
|
|
3936
|
+
// NOT re-registering hub-claim on this evidence, deliberately. An unauthenticated 401 proves the
|
|
3937
|
+
// function is alive; it proves NOTHING about the authenticated path, which is where both
|
|
3938
|
+
// originally failed. Re-registering on a liveness probe would swap "wrongly disabled" for
|
|
3939
|
+
// "advertised and broken in a user's hands", which is the worse of the two.
|
|
3940
|
+
//
|
|
3941
|
+
// TO CLOSE: call each with a real hub key / session token. If they succeed, delete these
|
|
3942
|
+
// two comment blocks and uncomment the imports — the count moves 71 → 73 and the anti-drift
|
|
3943
|
+
// gate will then force every doc surface to follow. (This session cannot mint a session
|
|
3944
|
+
// token, so it stops here rather than guess.)
|
|
3945
|
+
...knowledgeTools,
|
|
3946
|
+
...knowledgeGraphTools,
|
|
3947
|
+
// mRAG_graph_*: traverse the per-user knowledge graph (kg_* RPCs) — search finds text, this walks who/what/when
|
|
3948
|
+
...actionTools,
|
|
3949
|
+
// Action links (Tier 1): agent → user one-link browser action via action-create EF
|
|
3950
|
+
...presenceTools,
|
|
3951
|
+
// comms_session_attach: THIS session owns the account's reply lane while it runs; the 24/7 cloud stand-in defers. Any session, any machine — no bespoke bridge on one PC.
|
|
3952
|
+
...embedTools,
|
|
3953
|
+
// comms_embed_create: RE-REGISTERED 2026-07-17 — embed.mosadd.com/v1.js live; mints an embed key + paste-in snippet (mURL→mIRC rework P3)
|
|
3954
|
+
...threatTools,
|
|
3955
|
+
// threat_catalog + threat_classify: RE-REGISTERED 2026-07-15 (founder directive + LINEAR-3498) — pure/offline, makes the Pegasus-class classification claim a live, callable capability
|
|
3956
|
+
...murlTools
|
|
3957
|
+
// mURL: revived as a full module (founder 2026-06-27) — read/post/presence/list_channels over live domain channels
|
|
3958
|
+
// ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
|
|
3959
|
+
// mirlTools,
|
|
3960
|
+
// mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
|
|
3961
|
+
//
|
|
3962
|
+
// Each m* module registers its tools here as it ships.
|
|
3963
|
+
// RFC required to add a new m* module (see docs/rfcs/0001-module-naming.md).
|
|
3964
|
+
];
|
|
3965
|
+
var allTools = [
|
|
3966
|
+
...channelTools,
|
|
3967
|
+
// comms_capabilities: one-call discovery of every tool's `requires` flag,
|
|
3968
|
+
// so carrier-aware hosts (cymru-os) can gate the tool list by transport.
|
|
3969
|
+
makeCapabilitiesTool(channelTools)
|
|
3970
|
+
];
|
|
3971
|
+
var TOOL_COUNT = allTools.length;
|
|
3972
|
+
|
|
3973
|
+
// package.json
|
|
3974
|
+
var package_default = {
|
|
3975
|
+
name: "@mosadd/mcp",
|
|
3976
|
+
version: "3.0.0",
|
|
3977
|
+
mcpName: "io.github.hei33enberg/mosadd-mcp",
|
|
3978
|
+
description: "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions \u2014 85 tools \u2014 to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
|
|
3979
|
+
homepage: "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
|
|
3980
|
+
repository: {
|
|
3981
|
+
type: "git",
|
|
3982
|
+
url: "https://github.com/Hei33enberg/mosADD-OS.git",
|
|
3983
|
+
directory: "packages/mcp"
|
|
3984
|
+
},
|
|
3985
|
+
license: "MIT",
|
|
3986
|
+
type: "module",
|
|
3987
|
+
main: "./dist/index.js",
|
|
3988
|
+
module: "./dist/index.js",
|
|
3989
|
+
types: "./dist/index.d.ts",
|
|
3990
|
+
exports: {
|
|
3991
|
+
".": {
|
|
3992
|
+
types: "./dist/index.d.ts",
|
|
3993
|
+
import: "./dist/index.js"
|
|
3994
|
+
}
|
|
3995
|
+
},
|
|
3996
|
+
bin: {
|
|
3997
|
+
"mosadd-mcp": "./dist/bin/mcp.js",
|
|
3998
|
+
mosadd: "./dist/bin/mcp.js"
|
|
3999
|
+
},
|
|
4000
|
+
files: [
|
|
4001
|
+
"dist",
|
|
4002
|
+
"src",
|
|
4003
|
+
"README.md",
|
|
4004
|
+
"CHANGELOG.md",
|
|
4005
|
+
"LICENSE"
|
|
4006
|
+
],
|
|
4007
|
+
publishConfig: {
|
|
4008
|
+
access: "public"
|
|
4009
|
+
},
|
|
4010
|
+
scripts: {
|
|
4011
|
+
build: "tsup src/index.ts src/bin/mcp.ts src/bin/login.ts --format esm --dts --clean --shims",
|
|
4012
|
+
dev: "tsx src/bin/mcp.ts",
|
|
4013
|
+
test: "vitest run",
|
|
4014
|
+
typecheck: "tsc -p tsconfig.json --noEmit",
|
|
4015
|
+
clean: "rm -rf dist .turbo"
|
|
4016
|
+
},
|
|
4017
|
+
dependencies: {
|
|
4018
|
+
"@modelcontextprotocol/sdk": "^1.0.4",
|
|
4019
|
+
"@supabase/supabase-js": "^2.48.0",
|
|
4020
|
+
zod: "^4.3.6",
|
|
4021
|
+
"@mosadd/protocol": "3.0.0-alpha.28",
|
|
4022
|
+
"@mosadd/crypto": "3.0.0-alpha.27",
|
|
4023
|
+
"@mosadd/providers": "3.0.0-alpha.27",
|
|
4024
|
+
"@mosadd/threat-engine": "3.0.0-alpha.28"
|
|
4025
|
+
},
|
|
4026
|
+
devDependencies: {
|
|
4027
|
+
tsup: "^8.3.5",
|
|
4028
|
+
tsx: "^4.19.2",
|
|
4029
|
+
typescript: "^5.7.2",
|
|
4030
|
+
vitest: "^2.1.8"
|
|
4031
|
+
},
|
|
4032
|
+
keywords: [
|
|
4033
|
+
"mosadd",
|
|
4034
|
+
"mcp",
|
|
4035
|
+
"model-context-protocol",
|
|
4036
|
+
"agent",
|
|
4037
|
+
"claude",
|
|
4038
|
+
"cursor",
|
|
4039
|
+
"anthropic",
|
|
4040
|
+
"communication",
|
|
4041
|
+
"messaging"
|
|
4042
|
+
],
|
|
4043
|
+
engines: {
|
|
4044
|
+
node: ">=18"
|
|
4045
|
+
}
|
|
4046
|
+
};
|
|
4047
|
+
|
|
4048
|
+
// src/version.ts
|
|
4049
|
+
var PKG_VERSION = package_default.version;
|
|
4050
|
+
|
|
4051
|
+
// src/server.ts
|
|
4052
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4053
|
+
|
|
4054
|
+
// src/providers/supabase-voice.ts
|
|
4055
|
+
var ROOM_PREFIX = "mosadd-room-";
|
|
4056
|
+
var SupabaseVoiceProvider = class {
|
|
4057
|
+
cachedSelfId = null;
|
|
4058
|
+
async selfId() {
|
|
4059
|
+
if (this.cachedSelfId) return this.cachedSelfId;
|
|
4060
|
+
readSupabaseEnv();
|
|
4061
|
+
const sb = getSupabase();
|
|
4062
|
+
const { data: u, error: ue } = await sb.auth.getUser();
|
|
4063
|
+
if (ue || !u?.user) {
|
|
4064
|
+
throw new Error(
|
|
4065
|
+
"Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
|
|
4066
|
+
);
|
|
4067
|
+
}
|
|
4068
|
+
const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
|
|
4069
|
+
if (error || !identity) {
|
|
4070
|
+
throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
|
|
4071
|
+
}
|
|
4072
|
+
this.cachedSelfId = identity.id;
|
|
4073
|
+
return this.cachedSelfId;
|
|
4074
|
+
}
|
|
4075
|
+
async createRoom(label) {
|
|
4076
|
+
const self = await this.selfId();
|
|
4077
|
+
const roomId = labelRoomId(self, label);
|
|
4078
|
+
return { roomId };
|
|
4079
|
+
}
|
|
4080
|
+
async joinTicket(roomId) {
|
|
4081
|
+
const self = await this.selfId();
|
|
4082
|
+
const data = await invokeFunction("livekit-token", {
|
|
4083
|
+
roomName: roomId,
|
|
4084
|
+
identity: self
|
|
4085
|
+
});
|
|
4086
|
+
return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
|
|
4087
|
+
}
|
|
4088
|
+
async requestFloor(roomId) {
|
|
4089
|
+
return invokeFunction("mtalk-floor", { action: "request", room_id: roomId });
|
|
4090
|
+
}
|
|
4091
|
+
async releaseFloor(roomId) {
|
|
4092
|
+
const data = await invokeFunction("mtalk-floor", {
|
|
4093
|
+
action: "release",
|
|
4094
|
+
room_id: roomId
|
|
4095
|
+
});
|
|
4096
|
+
return data.snapshot;
|
|
4097
|
+
}
|
|
4098
|
+
async floorState(roomId) {
|
|
4099
|
+
const data = await invokeFunction("mtalk-floor", {
|
|
4100
|
+
action: "state",
|
|
4101
|
+
room_id: roomId
|
|
4102
|
+
});
|
|
4103
|
+
return data.snapshot;
|
|
4104
|
+
}
|
|
4105
|
+
};
|
|
4106
|
+
function labelRoomId(selfIdentityId, label) {
|
|
4107
|
+
if (!label) return `${ROOM_PREFIX}${selfIdentityId}`;
|
|
4108
|
+
return `${ROOM_PREFIX}${selfIdentityId}-${slug(label) || "room"}`;
|
|
4109
|
+
}
|
|
4110
|
+
function slug(s) {
|
|
4111
|
+
return s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 200);
|
|
4112
|
+
}
|
|
4113
|
+
|
|
4114
|
+
// src/server.ts
|
|
4115
|
+
function defaultProviders(injected, opts = {}) {
|
|
4116
|
+
return {
|
|
4117
|
+
dm: injected?.dm ?? new SupabaseDmProvider(),
|
|
4118
|
+
keys: injected?.keys ?? defaultKeyStore(opts.mdmSecret),
|
|
4119
|
+
voice: injected?.voice ?? new SupabaseVoiceProvider()
|
|
4120
|
+
};
|
|
4121
|
+
}
|
|
4122
|
+
function defaultKeyStore(secret) {
|
|
4123
|
+
const s = (secret ?? "").trim();
|
|
4124
|
+
return s ? new SecretMdmKeyStore(s) : new InMemoryMdmKeyStore();
|
|
4125
|
+
}
|
|
4126
|
+
function createMosaddServer(options = {}) {
|
|
4127
|
+
const mode = options.mode ?? (options.apiKey ? "cloud" : "local");
|
|
4128
|
+
const hubUrl = options.hubUrl ?? "https://mcp.mosadd.com";
|
|
4129
|
+
const logLevel = options.logLevel ?? "info";
|
|
4130
|
+
const providers = defaultProviders(options.providers, { mdmSecret: options.apiKey });
|
|
4131
|
+
const ctx = {
|
|
4132
|
+
options: { ...options, mode, hubUrl },
|
|
4133
|
+
providers,
|
|
4134
|
+
log: (level, msg, extra) => {
|
|
4135
|
+
if (shouldLog(level, logLevel)) {
|
|
4136
|
+
process.stderr.write(
|
|
4137
|
+
JSON.stringify({ level, msg, extra, ts: (/* @__PURE__ */ new Date()).toISOString() }) + "\n"
|
|
4138
|
+
);
|
|
4139
|
+
}
|
|
4140
|
+
}
|
|
4141
|
+
};
|
|
4142
|
+
if (options.autoPublishKeys) {
|
|
4143
|
+
void (async () => {
|
|
4144
|
+
const selfId = await providers.dm.selfId();
|
|
4145
|
+
const kind = await providers.dm.selfKind?.();
|
|
4146
|
+
return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, bundlePolicyForKind(kind, { explicit: false }));
|
|
4147
|
+
})().then((state) => ctx.log("debug", "auto-ensure mDM prekeys", { state })).catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
|
|
4148
|
+
}
|
|
4149
|
+
const server = new McpServer(
|
|
4150
|
+
{
|
|
4151
|
+
name: "mosadd",
|
|
4152
|
+
// Human-facing identity of the server itself (initialize result). The icon URLs
|
|
4153
|
+
// point at the LIVE gateway origin on purpose: clients that honour serverInfo.icons
|
|
4154
|
+
// get the brand mark without scraping the favicon, and the files ship with
|
|
4155
|
+
// the gateway's public/ folder (canon 08-26 — generated by m0ssad-3 scripts/
|
|
4156
|
+
// generate-brand-icons.py, never hand-edited).
|
|
4157
|
+
title: "mosADD \u2014 omnichannel messenger for agents",
|
|
4158
|
+
websiteUrl: "https://mosadd.com",
|
|
4159
|
+
icons: [
|
|
4160
|
+
{ src: "https://mcp.mosadd.com/favicon.svg", mimeType: "image/svg+xml", sizes: ["any"] },
|
|
4161
|
+
{ src: "https://mcp.mosadd.com/pwa-192.png", mimeType: "image/png", sizes: ["192x192"] }
|
|
4162
|
+
],
|
|
4163
|
+
version: PKG_VERSION
|
|
4164
|
+
},
|
|
4165
|
+
{
|
|
4166
|
+
capabilities: {
|
|
4167
|
+
tools: {}
|
|
4168
|
+
}
|
|
4169
|
+
}
|
|
4170
|
+
);
|
|
4171
|
+
for (const tool of allTools) {
|
|
4172
|
+
const shape = tool.inputSchema && typeof tool.inputSchema === "object" && "shape" in tool.inputSchema ? tool.inputSchema.shape : tool.inputSchema;
|
|
4173
|
+
const annotations = tool.title || tool.annotations ? { ...tool.title ? { title: tool.title } : {}, ...tool.annotations ?? {} } : void 0;
|
|
4174
|
+
const toolCallback = async (input) => {
|
|
4175
|
+
const parsed = tool.inputSchema.parse(input);
|
|
4176
|
+
try {
|
|
4177
|
+
const result = await tool.handler(parsed, ctx);
|
|
4178
|
+
void autoBeatFromActivity(ctx);
|
|
4179
|
+
const rich = result;
|
|
4180
|
+
if (rich && Array.isArray(rich.mcpContent)) {
|
|
4181
|
+
return { content: rich.mcpContent };
|
|
4182
|
+
}
|
|
4183
|
+
return {
|
|
4184
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
|
|
4185
|
+
};
|
|
4186
|
+
} catch (err) {
|
|
4187
|
+
ctx.log("error", `tool ${tool.name} failed`, { error: String(err) });
|
|
4188
|
+
return {
|
|
4189
|
+
isError: true,
|
|
4190
|
+
content: [
|
|
4191
|
+
{
|
|
4192
|
+
type: "text",
|
|
4193
|
+
text: JSON.stringify({
|
|
4194
|
+
error: err instanceof Error ? err.message : String(err),
|
|
4195
|
+
tool: tool.name
|
|
4196
|
+
})
|
|
4197
|
+
}
|
|
4198
|
+
]
|
|
4199
|
+
};
|
|
4200
|
+
}
|
|
4201
|
+
};
|
|
4202
|
+
if (annotations) {
|
|
4203
|
+
server.tool(
|
|
4204
|
+
tool.name,
|
|
4205
|
+
tool.description,
|
|
4206
|
+
shape,
|
|
4207
|
+
annotations,
|
|
4208
|
+
toolCallback
|
|
4209
|
+
);
|
|
4210
|
+
} else {
|
|
4211
|
+
server.tool(
|
|
4212
|
+
tool.name,
|
|
4213
|
+
tool.description,
|
|
4214
|
+
shape,
|
|
4215
|
+
toolCallback
|
|
4216
|
+
);
|
|
4217
|
+
}
|
|
4218
|
+
}
|
|
4219
|
+
return server;
|
|
4220
|
+
}
|
|
4221
|
+
function shouldLog(level, threshold) {
|
|
4222
|
+
const order = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
4223
|
+
return (order[level] ?? 1) >= (order[threshold] ?? 1);
|
|
4224
|
+
}
|
|
4225
|
+
|
|
4226
|
+
export {
|
|
4227
|
+
runWithSupabaseEnv,
|
|
4228
|
+
allTools,
|
|
4229
|
+
TOOL_COUNT,
|
|
4230
|
+
PKG_VERSION,
|
|
4231
|
+
defaultProviders,
|
|
4232
|
+
createMosaddServer
|
|
4233
|
+
};
|