@mosadd/mcp 3.0.0-alpha.4 → 3.0.0-alpha.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +298 -0
  2. package/README.md +70 -36
  3. package/dist/bin/mcp.js +42 -3
  4. package/dist/chunk-7ZAAJ52G.js +3475 -0
  5. package/dist/index.d.ts +115 -6
  6. package/dist/index.js +7 -3
  7. package/package.json +8 -5
  8. package/src/__tests__/golden-path.test.ts +139 -137
  9. package/src/__tests__/integration.test.ts +179 -178
  10. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  11. package/src/__tests__/mdm-e2ee.test.ts +212 -178
  12. package/src/__tests__/mtalk.test.ts +122 -122
  13. package/src/__tests__/presence.test.ts +178 -0
  14. package/src/__tests__/server.test.ts +71 -67
  15. package/src/__tests__/tool-count-consistency.test.ts +164 -0
  16. package/src/bin/login.ts +138 -138
  17. package/src/bin/mcp.ts +145 -97
  18. package/src/config.ts +66 -66
  19. package/src/crypto/mdm-session.ts +502 -403
  20. package/src/index.ts +19 -17
  21. package/src/observability/sentry.ts +79 -79
  22. package/src/providers/blob-upload.ts +116 -0
  23. package/src/providers/memory-voice.ts +79 -79
  24. package/src/providers/supabase-dm.ts +122 -117
  25. package/src/providers/supabase-voice.ts +91 -91
  26. package/src/providers/supabase.ts +155 -96
  27. package/src/server.ts +60 -9
  28. package/src/tools/actions.ts +166 -0
  29. package/src/tools/attachments.ts +276 -0
  30. package/src/tools/capabilities.ts +70 -68
  31. package/src/tools/embed.ts +110 -0
  32. package/src/tools/index.ts +177 -43
  33. package/src/tools/knowledge-graph.ts +186 -0
  34. package/src/tools/knowledge.ts +327 -91
  35. package/src/tools/mail-agentbox.ts +155 -0
  36. package/src/tools/mail-aliases.ts +25 -0
  37. package/src/tools/mail-provenance.ts +137 -0
  38. package/src/tools/mail.ts +403 -89
  39. package/src/tools/mcall.ts +216 -0
  40. package/src/tools/mdm-as-agent.ts +126 -0
  41. package/src/tools/mdm-voice.ts +220 -0
  42. package/src/tools/mdm.ts +494 -392
  43. package/src/tools/mirc-edge.ts +196 -0
  44. package/src/tools/mirc-members.ts +61 -20
  45. package/src/tools/mirc-messages.ts +185 -151
  46. package/src/tools/mirc.ts +104 -10
  47. package/src/tools/mroom-messages.ts +142 -142
  48. package/src/tools/mroom.ts +221 -189
  49. package/src/tools/mtalk.ts +131 -121
  50. package/src/tools/murl.ts +314 -0
  51. package/src/tools/presence.ts +333 -0
  52. package/src/tools/ptt-ingest.ts +99 -0
  53. package/src/tools/threat.ts +123 -0
  54. package/src/types.ts +121 -85
  55. package/src/version.ts +8 -0
  56. package/src/voice/floor.ts +132 -132
  57. package/dist/chunk-YDFU6S5E.js +0 -1471
@@ -1,91 +1,327 @@
1
- /**
2
- * mKB — Knowledge Base (RAG): search and reason over the user's own mosadd data.
3
- *
4
- * This is the developer-facing surface of the RAG pipeline that already runs
5
- * inside the mosadd backend: every message/email/call is embedded into a
6
- * private per-user vector index (rag_embeddings) with hybrid vector + BM25
7
- * retrieval, Cohere reranking, and a freshness lane for just-sent items. The
8
- * `mKB_search` tool lets an AGENT query that index — semantic recall over
9
- * the user's communications — WITHOUT the mosadd.com app. It is the dev-product
10
- * form of RAG (decision C): the same engine, exposed as one MCP tool.
11
- *
12
- * Wired to the m0ssad-3 `rag-query` Edge Function. The answer + cited sources
13
- * come back grounded strictly in the user's indexed data (no fabrication).
14
- *
15
- * Plan note: on the hosted hub this tool is gated by plan (free = off,
16
- * pro/team = on); BYOK/self-host runs it against the user's own backend. Gating
17
- * is enforced at the hub, not in this tool.
18
- */
19
-
20
- import { z } from "zod";
21
- import type { MosaddTool, MosaddToolContext } from "../types.js";
22
- import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
23
-
24
- const mKB_search_input = z.object({
25
- query: z
26
- .string()
27
- .min(1)
28
- .max(2_000)
29
- .describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
30
- top_k: z
31
- .number()
32
- .int()
33
- .min(1)
34
- .max(25)
35
- .optional()
36
- .describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
37
- source_types: z
38
- .array(z.enum(["message", "email", "call", "note", "contact"]))
39
- .optional()
40
- .describe("Restrict retrieval to these source types. Omit to search everything."),
41
- thread_id: z
42
- .string()
43
- .optional()
44
- .describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread)."),
45
- });
46
-
47
- interface RagSource {
48
- source_type: string;
49
- source_id: string;
50
- thread_id: string | null;
51
- similarity: number;
52
- snippet: string;
53
- created_at: string;
54
- }
55
-
56
- async function mKB_search(
57
- input: z.infer<typeof mKB_search_input>,
58
- ctx: MosaddToolContext,
59
- ): Promise<{ answer: string; sources: RagSource[]; chunks_found: number }> {
60
- readSupabaseEnv();
61
- ctx.log("debug", "mKB_search via rag-query", { top_k: input.top_k ?? 8 });
62
-
63
- type RagQueryResponse = {
64
- answer?: string;
65
- sources?: RagSource[];
66
- chunks_found?: number;
67
- };
68
- const data = await invokeFunction<RagQueryResponse>("rag-query", {
69
- query: input.query,
70
- top_k: input.top_k ?? 8,
71
- source_types: input.source_types ?? null,
72
- thread_id: input.thread_id ?? null,
73
- });
74
-
75
- return {
76
- answer: data.answer ?? "",
77
- sources: data.sources ?? [],
78
- chunks_found: data.chunks_found ?? (data.sources?.length ?? 0),
79
- };
80
- }
81
-
82
- export const knowledgeTools: MosaddTool[] = [
83
- {
84
- name: "mKB_search",
85
- requires: "network",
86
- description:
87
- "Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private RAG index — hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. Returns an answer plus the source snippets it used. This is agent memory (mKB = knowledge base) over the user's communications, available outside the mosadd app.",
88
- inputSchema: mKB_search_input,
89
- handler: mKB_search as MosaddTool["handler"],
90
- },
91
- ];
1
+ /**
2
+ * mRAG — Knowledge Base (RAG): search and reason over the user's own mosadd data.
3
+ *
4
+ * This is the developer-facing surface of the RAG pipeline that already runs
5
+ * inside the mosadd backend: every message/email/call is embedded into a
6
+ * private per-user vector index (rag_embeddings) with hybrid vector + BM25
7
+ * retrieval, Cohere reranking, and a freshness lane for just-sent items. The
8
+ * `mRAG_search` tool lets an AGENT query that index — semantic recall over
9
+ * the user's communications — WITHOUT the mosadd.com app. It is the dev-product
10
+ * form of RAG (decision C): the same engine, exposed as one MCP tool.
11
+ *
12
+ * Wired to the mosadd backend's `rag-query` Edge Function. The answer + cited sources
13
+ * come back grounded strictly in the user's indexed data (no fabrication).
14
+ *
15
+ * Plan note: on the hosted hub this tool is gated by plan (free = off,
16
+ * pro/team = on); BYOK/self-host runs it against the user's own backend. Gating
17
+ * is enforced at the hub, not in this tool.
18
+ */
19
+
20
+ import { createHash } from "node:crypto";
21
+ import { z } from "zod";
22
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
23
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
24
+
25
+ // ── source_id: free-form for the caller, a UUID on the wire ──────────────────
26
+ // `user_embeddings.source_id` is a **uuid** column (measured on prod 2026-08-14). This tool has
27
+ // always advertised source_id as "an optional stable id so re-ingests can be grouped" and typed it
28
+ // as a plain string — so the natural thing to pass (a file path, a case number, a docket id) made
29
+ // the INSERT blow up and the whole call came back as an opaque `rag-index (500): Internal error`.
30
+ // Bisected that day: every other field succeeded, `source_id: "bisect-1"` alone failed. It would
31
+ // have hit the legal-corpus ingest on document #1, with an error message pointing nowhere.
32
+ //
33
+ // Rather than push the problem onto every caller ("bring your own UUID"), a non-UUID id is folded
34
+ // into a DETERMINISTIC UUIDv5. Same input → same uuid, for ever, so grouping and mRAG_delete keep
35
+ // working on natural keys; a caller that already passes a real UUID is untouched. The original
36
+ // string is preserved as `metadata.source_ref` so it comes back with search hits and nothing is
37
+ // silently renamed behind the user's back.
38
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
39
+
40
+ /** Fixed namespace for mosadd mRAG source ids. Changing it would orphan every previously grouped source. */
41
+ const SOURCE_ID_NAMESPACE = "1f0b6c2e-6a4d-4f7a-9c1e-0b2d3a4f5e6b";
42
+
43
+ /** RFC 4122 v5 (SHA-1, namespaced). Small enough to keep here rather than add a dependency. */
44
+ function uuidV5(name: string, namespace: string): string {
45
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
46
+ const digest = createHash("sha1").update(Buffer.concat([ns, Buffer.from(name, "utf8")])).digest();
47
+ const b = Buffer.from(digest.subarray(0, 16));
48
+ b[6] = (b[6] & 0x0f) | 0x50; // version 5
49
+ b[8] = (b[8] & 0x3f) | 0x80; // RFC 4122 variant
50
+ const h = b.toString("hex");
51
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
52
+ }
53
+
54
+ const mRAG_search_input = z.object({
55
+ query: z
56
+ .string()
57
+ .min(1)
58
+ .max(2_000)
59
+ .describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
60
+ top_k: z
61
+ .number()
62
+ .int()
63
+ .min(1)
64
+ .max(25)
65
+ .optional()
66
+ .describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
67
+ source_types: z
68
+ // ⚠ MUST stay a superset of everything that can REACH the index, or a filter
69
+ // silently hides data the user owns. Until 2026-08-11 this enum was missing
70
+ // "file" and "ptt" while the index held both — `file` is what mRAG_ingest itself
71
+ // writes (it is the DEFAULT source_type, and "note" is mapped onto it), and `ptt`
72
+ // is what mTALK_ingest_ptt writes once a push-to-talk transcript lands. Measured
73
+ // on prod that day: email 4098 · call 233 · note 187 · message 86 · file 49 · ptt 14
74
+ // — i.e. 63 rows were unreachable by any source_types filter. Add a value HERE
75
+ // whenever a new writer starts stamping a new source_type.
76
+ .array(z.enum(["message", "email", "call", "note", "contact", "file", "ptt"]))
77
+ .optional()
78
+ .describe(
79
+ "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.",
80
+ ),
81
+ thread_id: z
82
+ .string()
83
+ .optional()
84
+ .describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread)."),
85
+ });
86
+
87
+ interface RagSource {
88
+ source_type: string;
89
+ source_id: string;
90
+ thread_id: string | null;
91
+ similarity: number;
92
+ snippet: string;
93
+ created_at: string;
94
+ }
95
+
96
+ async function mRAG_search(
97
+ input: z.infer<typeof mRAG_search_input>,
98
+ ctx: MosaddToolContext,
99
+ ): Promise<{ answer: string; sources: RagSource[]; chunks_found: number }> {
100
+ readSupabaseEnv();
101
+ ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
102
+
103
+ type RagQueryResponse = {
104
+ answer?: string;
105
+ sources?: RagSource[];
106
+ chunks_found?: number;
107
+ };
108
+ const data = await invokeFunction<RagQueryResponse>("rag-query", {
109
+ query: input.query,
110
+ top_k: input.top_k ?? 8,
111
+ source_types: input.source_types ?? null,
112
+ thread_id: input.thread_id ?? null,
113
+ });
114
+
115
+ return {
116
+ answer: data.answer ?? "",
117
+ sources: data.sources ?? [],
118
+ chunks_found: data.chunks_found ?? (data.sources?.length ?? 0),
119
+ };
120
+ }
121
+
122
+ /**
123
+ * A person / company / address a document involves.
124
+ *
125
+ * Polymorphic on purpose: mail carries an address, mDM carries an identity UUID, a court filing
126
+ * carries a party name — all three flow through the SAME `{ kind, ref, label }` shape so one
127
+ * filter matches any of them. Mirrors `Party` in the backend's _shared/enrichRagMetadata.ts.
128
+ */
129
+ const PartyArg = z.object({
130
+ kind: z
131
+ .enum(["identity", "account", "email", "phone", "url", "unknown"])
132
+ .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')."),
133
+ ref: z
134
+ .string()
135
+ .min(1)
136
+ .max(400)
137
+ .describe("The stable key this party is recognised by — 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."),
138
+ label: z.string().max(300).nullish().describe("Human name to display for this party."),
139
+ });
140
+
141
+ const mRAG_ingest_input = z.object({
142
+ content_text: z
143
+ .string()
144
+ .min(1)
145
+ .max(200_000)
146
+ .describe("Text to index into the user's private knowledge base (a note, document, transcript, pasted page…). Chunked + embedded server-side."),
147
+ source_type: z
148
+ .enum(["file", "note", "message", "email", "contact", "call"])
149
+ .optional()
150
+ .describe("What kind of source this is. Default 'file' (a document/note). Use 'note' for ad-hoc text."),
151
+ source_id: z
152
+ .string()
153
+ .max(500)
154
+ .optional()
155
+ .describe(
156
+ "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 — 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.",
157
+ ),
158
+ thread_id: z.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
159
+ title: z.string().max(300).optional().describe("Optional human title, stored in metadata."),
160
+ // ── Graph + file-manager fields ────────────────────────────────────────────
161
+ // Added 2026-08-14. The backend (rag-index → enrichRagMetadata) has accepted all of these
162
+ // since 2026-07-19; THIS tool was the only ingest path that dropped them, so everything
163
+ // pushed through MCP landed with no parties and no event date — and therefore contributed
164
+ // NOTHING to mRAG_graph_*, which builds its nodes from exactly these fields. A corpus could
165
+ // be fully indexed and its graph still come back empty. See the note on the tool below.
166
+ sender: PartyArg.optional().describe(
167
+ "Who the document is FROM (author, filing party, sender). Becomes a node in the knowledge graph — without it this document adds no party to mRAG_graph_overview.",
168
+ ),
169
+ recipient: PartyArg.optional().describe(
170
+ "Who the document is TO (addressee, court, counterparty). Becomes a node in the knowledge graph, connected to `sender`.",
171
+ ),
172
+ occurred_at: z
173
+ .string()
174
+ .optional()
175
+ .describe("ISO-8601 timestamp of WHEN the document happened (letter date, filing date, email Date header) — not when you indexed it. Drives mRAG_graph_timeline; defaults to now if omitted, which makes a 2019 filing look like it happened today."),
176
+ direction: z
177
+ .enum(["in", "out", "self"])
178
+ .optional()
179
+ .describe("Direction relative to the account owner: received, sent, or the owner's own note."),
180
+ labels: z
181
+ .array(z.string().max(120))
182
+ .max(50)
183
+ .optional()
184
+ .describe("Free-text tags to attach (e.g. a case id, a jurisdiction) for later filtering."),
185
+ name: z
186
+ .string()
187
+ .max(400)
188
+ .optional()
189
+ .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."),
190
+ mime: z.string().max(200).optional().describe("MIME type of the original file, if known."),
191
+ size: z.number().int().nonnegative().optional().describe("Size of the original file in bytes, if known."),
192
+ metadata: z
193
+ .record(z.string(), z.unknown())
194
+ .optional()
195
+ .describe("Any extra fields to store alongside the row (case id, docket number, jurisdiction, file path, checksum, sensitivity flag…). Stored verbatim and returned with search hits. NOTE: this is stored server-side in plaintext like the content itself."),
196
+ });
197
+
198
+ async function mRAG_ingest(
199
+ input: z.infer<typeof mRAG_ingest_input>,
200
+ ctx: MosaddToolContext,
201
+ ): Promise<{ indexed: number; chunk_count: number }> {
202
+ readSupabaseEnv();
203
+ // rag-index accepts a fixed source_type set; map "note" → "file".
204
+ const backendType = input.source_type === "note" ? "file" : (input.source_type ?? "file");
205
+ ctx.log("debug", "mRAG_ingest via rag-index", {
206
+ source_type: backendType,
207
+ has_parties: Boolean(input.sender || input.recipient),
208
+ has_occurred_at: Boolean(input.occurred_at),
209
+ });
210
+ // The enrichment fields are TOP-LEVEL on the rag-index request, not inside `metadata` — the
211
+ // function destructures them by name and hands them to enrichRagMetadata, which is what stamps
212
+ // metadata.sender / .recipient / .occurred_at in the canonical shape kg_refresh_me reads.
213
+ // Passing them inside `metadata` would land them via `passthrough` and happen to work today,
214
+ // but it would bypass the canonical stamping (and its `sender.ref` validation) — so send them
215
+ // where the contract says they go. Undefined keys are omitted rather than sent as null, so a
216
+ // caller that passes none produces byte-identical requests to before this change.
217
+ const rawSourceId = input.source_id?.trim() || null;
218
+ const sourceId = rawSourceId && !UUID_RE.test(rawSourceId) ? uuidV5(rawSourceId, SOURCE_ID_NAMESPACE) : rawSourceId;
219
+ const data = await invokeFunction<{ indexed?: number; chunk_count?: number }>("rag-index", {
220
+ source_type: backendType,
221
+ source_id: sourceId,
222
+ thread_id: input.thread_id ?? null,
223
+ content_text: input.content_text,
224
+ ...(input.sender ? { sender: input.sender } : {}),
225
+ ...(input.recipient ? { recipient: input.recipient } : {}),
226
+ ...(input.occurred_at ? { occurred_at: input.occurred_at } : {}),
227
+ ...(input.direction ? { direction: input.direction } : {}),
228
+ ...(input.labels?.length ? { labels: input.labels } : {}),
229
+ ...(input.name ? { name: input.name } : {}),
230
+ ...(input.mime ? { mime: input.mime } : {}),
231
+ ...(typeof input.size === "number" ? { size: input.size } : {}),
232
+ metadata: {
233
+ ...(input.metadata ?? {}),
234
+ ...(input.title ? { title: input.title } : {}),
235
+ // Only when we actually rewrote it — a caller that passed a real UUID sees no extra key.
236
+ ...(rawSourceId && rawSourceId !== sourceId ? { source_ref: rawSourceId } : {}),
237
+ ingested_via: "mRAG_ingest",
238
+ },
239
+ });
240
+ return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
241
+ }
242
+
243
+ const mRAG_list_sources_input = z.object({});
244
+
245
+ interface RagSourceEntry {
246
+ source_type: string;
247
+ source_id: string | null;
248
+ thread_id: string | null;
249
+ title: string | null;
250
+ chunks: number;
251
+ first_indexed: string;
252
+ last_indexed: string;
253
+ }
254
+
255
+ async function mRAG_list_sources(
256
+ _input: z.infer<typeof mRAG_list_sources_input>,
257
+ ctx: MosaddToolContext,
258
+ ): Promise<{ sources: RagSourceEntry[]; total_sources: number; total_chunks: number }> {
259
+ readSupabaseEnv();
260
+ ctx.log("debug", "mRAG_list_sources via rag-sources");
261
+ return await invokeFunction("rag-sources", { action: "list" });
262
+ }
263
+
264
+ const mRAG_delete_input = z
265
+ .object({
266
+ source_id: z.string().optional().describe("Delete every indexed chunk with this source_id (from mRAG_list_sources)."),
267
+ thread_id: z.string().optional().describe("Delete every indexed chunk associated with this thread_id."),
268
+ })
269
+ .refine((v) => v.source_id || v.thread_id, {
270
+ message: "Provide source_id or thread_id — mRAG_delete refuses to purge the whole index.",
271
+ });
272
+
273
+ async function mRAG_delete(
274
+ input: z.infer<typeof mRAG_delete_input>,
275
+ ctx: MosaddToolContext,
276
+ ): Promise<{ ok: true; deleted: number; source_id: string | null; thread_id: string | null }> {
277
+ readSupabaseEnv();
278
+ ctx.log("debug", "mRAG_delete via rag-sources", { source_id: input.source_id, thread_id: input.thread_id });
279
+ return await invokeFunction("rag-sources", {
280
+ action: "delete",
281
+ source_id: input.source_id ?? null,
282
+ thread_id: input.thread_id ?? null,
283
+ });
284
+ }
285
+
286
+ export const knowledgeTools: MosaddTool[] = [
287
+ {
288
+ name: "mRAG_ingest",
289
+ title: "Ingest into memory",
290
+ annotations: { readOnlyHint: false },
291
+ requires: "network",
292
+ description:
293
+ "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. ⚠ 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 — 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 — NOT covered by the zero-knowledge / E2EE guarantee. Only ingest what the user opted to make searchable.",
294
+ inputSchema: mRAG_ingest_input,
295
+ handler: mRAG_ingest as MosaddTool["handler"],
296
+ },
297
+ {
298
+ name: "mRAG_search",
299
+ title: "Search memory",
300
+ annotations: { readOnlyHint: true },
301
+ requires: "network",
302
+ description:
303
+ "Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private per-user RAG index — hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. Returns an answer plus the source snippets it used. This is agent memory (mRAG = RAG over your own data) over the user's communications, available outside the mosadd app. NOTE: RAG requires content to be indexed server-side in plaintext, so anything searchable here is NOT covered by the zero-knowledge / E2EE guarantee — only data the user has explicitly opted into indexing is searchable. See docs/security/e2ee-posture.md.",
304
+ inputSchema: mRAG_search_input,
305
+ handler: mRAG_search as MosaddTool["handler"],
306
+ },
307
+ {
308
+ name: "mRAG_list_sources",
309
+ title: "List memory sources",
310
+ annotations: { readOnlyHint: true },
311
+ requires: "network",
312
+ description:
313
+ "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.",
314
+ inputSchema: mRAG_list_sources_input,
315
+ handler: mRAG_list_sources as MosaddTool["handler"],
316
+ },
317
+ {
318
+ name: "mRAG_delete",
319
+ title: "Delete memory source",
320
+ annotations: { destructiveHint: true },
321
+ requires: "network",
322
+ description:
323
+ "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.",
324
+ inputSchema: mRAG_delete_input,
325
+ handler: mRAG_delete as MosaddTool["handler"],
326
+ },
327
+ ];
@@ -0,0 +1,155 @@
1
+ /**
2
+ * mAYL agent inboxes — disposable, two-way mailboxes an agent can mint for itself.
3
+ *
4
+ * Backed by the mosADD `mayl-agentbox` Edge Function (owner-scoped CRUD over
5
+ * public.mayl_agent_boxes) + the mp0st-inbound-webhook receive path. A box is a REAL
6
+ * address `agent-<hex>@mosadd.com` that can both SEND (via mAYL_send's from-selector)
7
+ * and — since 2026-08-06 — RECEIVE (inbound mail resolves the box → the owner account).
8
+ *
9
+ * This is the mosADD answer to AgentMail's `create_inbox`: the agent gets its own real
10
+ * inbox on demand, but inside an E2EE messenger where the agent is already a first-class
11
+ * contact and every send carries cryptographic provenance — not a bare third-party API.
12
+ *
13
+ * Auth is identical to every other mAYL tool: invokeFunction sends the caller's
14
+ * `Authorization: Bearer <userJwt>`, which mayl-agentbox validates via requireUser
15
+ * (auth.uid() owner-scoping). No new auth surface.
16
+ */
17
+
18
+ import { z } from "zod";
19
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
20
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
21
+
22
+ // ---- Schemas ----
23
+
24
+ const BoxId = z.string().min(1).describe("Agent-box id (UUID) from mAYL_agentbox_provision or mAYL_agentbox_list.");
25
+
26
+ const agentbox_provision_input = z.object({
27
+ display_name: z
28
+ .string()
29
+ .max(120)
30
+ .optional()
31
+ .describe("Optional human label for the box (e.g. 'signup catcher'). Max 120 chars."),
32
+ agent_id: z
33
+ .string()
34
+ .optional()
35
+ .describe("Optional identity id to attribute the box to — must be an agent identity you own."),
36
+ kind: z
37
+ .enum(["ephemeral", "persistent"])
38
+ .optional()
39
+ .describe("'ephemeral' (default) auto-expires + is reaped; 'persistent' never expires."),
40
+ ttl_seconds: z
41
+ .number()
42
+ .int()
43
+ .positive()
44
+ .max(86_400)
45
+ .optional()
46
+ .describe("Lifetime for an ephemeral box, in seconds. Default 600 (10 min). Max 86400 (24 h). Ignored for persistent."),
47
+ });
48
+
49
+ const agentbox_list_input = z.object({});
50
+
51
+ const agentbox_release_input = z.object({ id: BoxId });
52
+
53
+ const agentbox_extend_input = z.object({
54
+ id: BoxId,
55
+ ttl_seconds: z
56
+ .number()
57
+ .int()
58
+ .positive()
59
+ .max(86_400)
60
+ .optional()
61
+ .describe("New lifetime from NOW, in seconds. Default 600 (10 min). Max 86400 (24 h). Ephemeral boxes only."),
62
+ });
63
+
64
+ // ---- Handlers ----
65
+
66
+ async function agentbox_provision(
67
+ input: z.infer<typeof agentbox_provision_input>,
68
+ ctx: MosaddToolContext,
69
+ ): Promise<Record<string, unknown>> {
70
+ readSupabaseEnv();
71
+ ctx.log("debug", "mAYL_agentbox_provision invoking mayl-agentbox", { kind: input.kind ?? "ephemeral" });
72
+ return await invokeFunction("mayl-agentbox", {
73
+ action: "create",
74
+ display_name: input.display_name ?? null,
75
+ agent_id: input.agent_id ?? null,
76
+ kind: input.kind ?? "ephemeral",
77
+ ttl_seconds: input.ttl_seconds ?? null,
78
+ });
79
+ }
80
+
81
+ async function agentbox_list(
82
+ _input: z.infer<typeof agentbox_list_input>,
83
+ ctx: MosaddToolContext,
84
+ ): Promise<Record<string, unknown>> {
85
+ readSupabaseEnv();
86
+ ctx.log("debug", "mAYL_agentbox_list invoking mayl-agentbox", {});
87
+ return await invokeFunction("mayl-agentbox", { action: "list" });
88
+ }
89
+
90
+ async function agentbox_release(
91
+ input: z.infer<typeof agentbox_release_input>,
92
+ ctx: MosaddToolContext,
93
+ ): Promise<Record<string, unknown>> {
94
+ readSupabaseEnv();
95
+ ctx.log("debug", "mAYL_agentbox_release invoking mayl-agentbox", { id: input.id });
96
+ return await invokeFunction("mayl-agentbox", { action: "release", id: input.id });
97
+ }
98
+
99
+ async function agentbox_extend(
100
+ input: z.infer<typeof agentbox_extend_input>,
101
+ ctx: MosaddToolContext,
102
+ ): Promise<Record<string, unknown>> {
103
+ readSupabaseEnv();
104
+ ctx.log("debug", "mAYL_agentbox_extend invoking mayl-agentbox", { id: input.id });
105
+ return await invokeFunction("mayl-agentbox", {
106
+ action: "extend",
107
+ id: input.id,
108
+ ttl_seconds: input.ttl_seconds ?? null,
109
+ });
110
+ }
111
+
112
+ // ---- Registration ----
113
+
114
+ export const mailAgentboxTools: MosaddTool[] = [
115
+ {
116
+ name: "mAYL_agentbox_provision",
117
+ title: "Provision disposable inbox",
118
+ annotations: { readOnlyHint: false },
119
+ requires: "network",
120
+ description:
121
+ "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.",
122
+ inputSchema: agentbox_provision_input,
123
+ handler: agentbox_provision as MosaddTool["handler"],
124
+ },
125
+ {
126
+ name: "mAYL_agentbox_list",
127
+ title: "List disposable inboxes",
128
+ annotations: { readOnlyHint: true },
129
+ requires: "network",
130
+ description:
131
+ "List your active agent inboxes (address, display_name, kind, agent_id, expires_at), newest first. Owner-scoped.",
132
+ inputSchema: agentbox_list_input,
133
+ handler: agentbox_list as MosaddTool["handler"],
134
+ },
135
+ {
136
+ name: "mAYL_agentbox_release",
137
+ title: "Release disposable inbox",
138
+ annotations: { destructiveHint: true },
139
+ requires: "network",
140
+ description:
141
+ "Release (delete) one of your agent inboxes by id — frees the address immediately so it stops receiving. Owner-scoped.",
142
+ inputSchema: agentbox_release_input,
143
+ handler: agentbox_release as MosaddTool["handler"],
144
+ },
145
+ {
146
+ name: "mAYL_agentbox_extend",
147
+ title: "Extend disposable inbox",
148
+ annotations: { readOnlyHint: false },
149
+ requires: "network",
150
+ description:
151
+ "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.",
152
+ inputSchema: agentbox_extend_input,
153
+ handler: agentbox_extend as MosaddTool["handler"],
154
+ },
155
+ ];
@@ -0,0 +1,25 @@
1
+ // =============================================================================
2
+ // mail-aliases.ts — back-compat mp0st_* aliases for mAYL_* tools
3
+ // =============================================================================
4
+ // The mosADD re-arch (2026-06-27) renamed the email module from `mp0st` to
5
+ // `mAYL` (LINEAR-3938 / 3985). The canonical tool names are mAYL_* — see
6
+ // `tools/mail.ts`. THIS module exposes back-compat aliases so any agent already
7
+ // wired to mp0st_send / mp0st_view / etc. KEEPS WORKING in this release.
8
+ //
9
+ // Rule: never drop an alias in the release that adds its replacement — live
10
+ // agents would 404. mp0st_* aliases stay through alpha.25 and the next minor;
11
+ // flag for removal goes into the a later release's notes.
12
+ // =============================================================================
13
+
14
+ import type { MosaddTool } from "../types.js";
15
+ import { mailTools } from "./mail.js";
16
+
17
+ /** Same handlers/schemas as `mailTools`, but registered under the legacy mp0st_* names. */
18
+ export const mailAliasTools: MosaddTool[] = mailTools.map((tool) => ({
19
+ ...tool,
20
+ name: tool.name.replace(/^mAYL_/, "mp0st_"),
21
+ description:
22
+ `[DEPRECATED — use ${tool.name} instead. mp0st_* aliases stay through alpha.25 ` +
23
+ `for back-compat; will be removed in a later alpha.] ` +
24
+ tool.description,
25
+ }));