@mosadd/mcp 3.0.0-alpha.32 → 3.0.0-alpha.33

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 (52) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +11 -11
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-KX34DDJB.js → chunk-IWLN5EO5.js} +614 -134
  5. package/dist/index.js +1 -1
  6. package/package.json +15 -15
  7. package/src/__tests__/golden-path.test.ts +137 -137
  8. package/src/__tests__/integration.test.ts +179 -179
  9. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  10. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  11. package/src/__tests__/mtalk.test.ts +122 -122
  12. package/src/__tests__/presence.test.ts +141 -0
  13. package/src/__tests__/server.test.ts +71 -71
  14. package/src/__tests__/tool-count-consistency.test.ts +121 -1
  15. package/src/bin/login.ts +138 -138
  16. package/src/bin/mcp.ts +145 -145
  17. package/src/config.ts +66 -66
  18. package/src/crypto/mdm-session.ts +502 -502
  19. package/src/index.ts +19 -19
  20. package/src/observability/sentry.ts +79 -79
  21. package/src/providers/blob-upload.ts +116 -116
  22. package/src/providers/memory-voice.ts +79 -79
  23. package/src/providers/supabase-dm.ts +122 -122
  24. package/src/providers/supabase-voice.ts +91 -91
  25. package/src/providers/supabase.ts +148 -148
  26. package/src/tools/actions.ts +162 -162
  27. package/src/tools/attachments.ts +268 -268
  28. package/src/tools/capabilities.ts +68 -68
  29. package/src/tools/embed.ts +108 -108
  30. package/src/tools/index.ts +173 -104
  31. package/src/tools/knowledge-graph.ts +178 -0
  32. package/src/tools/knowledge.ts +319 -191
  33. package/src/tools/mail-agentbox.ts +147 -0
  34. package/src/tools/mail-aliases.ts +25 -25
  35. package/src/tools/mail-provenance.ts +135 -135
  36. package/src/tools/mail.ts +381 -381
  37. package/src/tools/mdm.ts +476 -479
  38. package/src/tools/mirc-edge.ts +190 -190
  39. package/src/tools/mirc-members.ts +2 -2
  40. package/src/tools/mirc-messages.ts +155 -155
  41. package/src/tools/mirc.ts +2 -2
  42. package/src/tools/mroom-messages.ts +142 -142
  43. package/src/tools/mroom.ts +221 -221
  44. package/src/tools/mtalk.ts +121 -121
  45. package/src/tools/murl.ts +4 -2
  46. package/src/tools/presence.ts +208 -0
  47. package/src/types.ts +94 -94
  48. package/src/voice/floor.ts +132 -132
  49. package/LICENSE +0 -201
  50. package/dist/bin/login.d.ts +0 -13
  51. package/dist/bin/mcp.d.ts +0 -1
  52. package/dist/index.d.ts +0 -266
@@ -1,155 +1,155 @@
1
- /**
2
- * mIRC text mode — post + list messages inside a channel.
3
- *
4
- * Channel messages route through the same the mosadd backend's `message-send` / `message-list`
5
- * Edge Functions as DMs, but with `thread_id: 'chat:<channelId>'` so the
6
- * RLS / access checks apply channel-membership rules. Each channel is linked to a
7
- * backing space (`metadata.linked_space_id`); message-send needs that space id, so
8
- * these tools resolve it from the channel automatically (or accept an override).
9
- */
10
-
11
- import { z } from "zod";
12
- import type { MosaddTool, MosaddToolContext } from "../types.js";
13
- import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
-
15
- const PROTOCOL_VERSION = "mosadd.chat.v1";
16
-
17
- const ChannelId = z.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
18
-
19
- const mIRC_post_message_input = z.object({
20
- channel_id: ChannelId,
21
- text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
22
- reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
23
- space_id: z
24
- .string()
25
- .optional()
26
- .describe("Optional backing space id. Resolved automatically from the channel if omitted."),
27
- });
28
-
29
- const mIRC_list_messages_input = z.object({
30
- channel_id: ChannelId,
31
- limit: z.number().int().min(1).max(200).default(50).optional(),
32
- cursor: z.string().optional().describe("Opaque pagination cursor from a prior list response."),
33
- space_id: z.string().optional().describe("Optional backing space id. Resolved automatically if omitted."),
34
- });
35
-
36
- // ALPHA: channel messages are NOT end-to-end encrypted here — the body is wrapped
37
- // in a JSON envelope and base64-encoded (server-readable). The mosadd.com app
38
- // encrypts channel messages with a per-channel group key, so app clients cannot
39
- // decrypt these dev-posted plaintext payloads (and vice-versa) until the toolkit
40
- // adopts the same group-key scheme. See docs/security/e2ee-posture.md.
41
- function packPlaintextPayload(text: string, replyToId?: string): string {
42
- const envelope = {
43
- v: PROTOCOL_VERSION,
44
- type: "text",
45
- text,
46
- reply_to: replyToId ?? null,
47
- sent_at: new Date().toISOString(),
48
- };
49
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
50
- }
51
-
52
- function unpackPayload(payload: string): { text: string } {
53
- try {
54
- const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
55
- if (typeof obj?.text === "string") return obj;
56
- } catch {
57
- /* fall through */
58
- }
59
- return { text: "<ciphertext>" };
60
- }
61
-
62
- /** Resolve a channel's backing space id (metadata.linked_space_id) via channel-manage. */
63
- async function resolveLinkedSpaceId(channelId: string): Promise<string> {
64
- type GetResponse = {
65
- channel?: { metadata?: { linked_space_id?: string } | null };
66
- linked_space_id?: string;
67
- };
68
- const data = await invokeFunction<GetResponse>("channel-manage", { action: "get", channel_id: channelId });
69
- const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
70
- if (!spaceId) {
71
- throw new Error(
72
- `Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, ` +
73
- `or pass space_id explicitly.`,
74
- );
75
- }
76
- return spaceId;
77
- }
78
-
79
- async function mIRC_post_message(
80
- input: z.infer<typeof mIRC_post_message_input>,
81
- ctx: MosaddToolContext,
82
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string }> {
83
- readSupabaseEnv();
84
- const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
85
- const thread_id = `chat:${input.channel_id}`;
86
- ctx.log("debug", "mIRC_post_message", { thread_id, space_id });
87
-
88
- const data = await invokeFunction<{ message?: { id: string; created_at: string } }>("message-send", {
89
- space_id,
90
- thread_id,
91
- encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
92
- message_type: "txt",
93
- protocol_version: PROTOCOL_VERSION,
94
- reply_to_id: input.reply_to_id ?? null,
95
- });
96
-
97
- if (!data?.message?.id) throw new Error("message-send returned no message id");
98
- return { message_id: data.message.id, delivered_at: data.message.created_at ?? new Date().toISOString(), thread_id };
99
- }
100
-
101
- async function mIRC_list_messages(
102
- input: z.infer<typeof mIRC_list_messages_input>,
103
- ctx: MosaddToolContext,
104
- ): Promise<{
105
- messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }>;
106
- next_cursor: string | null;
107
- }> {
108
- readSupabaseEnv();
109
- const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
110
- const thread_id = `chat:${input.channel_id}`;
111
- ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
112
-
113
- type MessageListResponse = {
114
- messages?: Array<{ id: string; sender_identity_id: string; encrypted_payload: string; created_at: string }>;
115
- next_before?: string | null;
116
- cursor?: string | null;
117
- };
118
- // message-list reads `before` (history) / `since` (incremental) — NOT `cursor`.
119
- // Sending `cursor` left `before` unset → every call returned the newest page.
120
- const data = await invokeFunction<MessageListResponse>("message-list", {
121
- space_id,
122
- thread_id,
123
- limit: input.limit ?? 50,
124
- before: input.cursor,
125
- });
126
-
127
- return {
128
- messages: (data?.messages ?? []).map((m) => ({
129
- id: m.id,
130
- sender_identity_id: m.sender_identity_id,
131
- text: unpackPayload(m.encrypted_payload).text,
132
- timestamp: m.created_at,
133
- })),
134
- next_cursor: data?.next_before ?? data?.cursor ?? null,
135
- };
136
- }
137
-
138
- export const mircMessagesTools: MosaddTool[] = [
139
- {
140
- name: "mIRC_post_message",
141
- requires: "network",
142
- description:
143
- "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 — 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. ENCRYPTION: OPEN channels are server-readable plaintext base64 — app clients CAN read toolkit-posted messages. Password/private channels use per-channel group-key E2EE text in the mosadd.com app; toolkit interop on those (group-key parity) is not yet wired.",
144
- inputSchema: mIRC_post_message_input,
145
- handler: mIRC_post_message as MosaddTool["handler"],
146
- },
147
- {
148
- name: "mIRC_list_messages",
149
- requires: "network",
150
- description:
151
- "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
152
- inputSchema: mIRC_list_messages_input,
153
- handler: mIRC_list_messages as MosaddTool["handler"],
154
- },
155
- ];
1
+ /**
2
+ * mIRC text mode — post + list messages inside a channel.
3
+ *
4
+ * Channel messages route through the same the mosadd backend's `message-send` / `message-list`
5
+ * Edge Functions as DMs, but with `thread_id: 'chat:<channelId>'` so the
6
+ * RLS / access checks apply channel-membership rules. Each channel is linked to a
7
+ * backing space (`metadata.linked_space_id`); message-send needs that space id, so
8
+ * these tools resolve it from the channel automatically (or accept an override).
9
+ */
10
+
11
+ import { z } from "zod";
12
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
13
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
+
15
+ const PROTOCOL_VERSION = "mosadd.chat.v1";
16
+
17
+ const ChannelId = z.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
18
+
19
+ const mIRC_post_message_input = z.object({
20
+ channel_id: ChannelId,
21
+ text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
22
+ reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
23
+ space_id: z
24
+ .string()
25
+ .optional()
26
+ .describe("Optional backing space id. Resolved automatically from the channel if omitted."),
27
+ });
28
+
29
+ const mIRC_list_messages_input = z.object({
30
+ channel_id: ChannelId,
31
+ limit: z.number().int().min(1).max(200).default(50).optional(),
32
+ cursor: z.string().optional().describe("Opaque pagination cursor from a prior list response."),
33
+ space_id: z.string().optional().describe("Optional backing space id. Resolved automatically if omitted."),
34
+ });
35
+
36
+ // ALPHA: channel messages are NOT end-to-end encrypted here — the body is wrapped
37
+ // in a JSON envelope and base64-encoded (server-readable). The mosadd.com app
38
+ // encrypts channel messages with a per-channel group key, so app clients cannot
39
+ // decrypt these dev-posted plaintext payloads (and vice-versa) until the toolkit
40
+ // adopts the same group-key scheme. See docs/security/e2ee-posture.md.
41
+ function packPlaintextPayload(text: string, replyToId?: string): string {
42
+ const envelope = {
43
+ v: PROTOCOL_VERSION,
44
+ type: "text",
45
+ text,
46
+ reply_to: replyToId ?? null,
47
+ sent_at: new Date().toISOString(),
48
+ };
49
+ return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
50
+ }
51
+
52
+ function unpackPayload(payload: string): { text: string } {
53
+ try {
54
+ const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
55
+ if (typeof obj?.text === "string") return obj;
56
+ } catch {
57
+ /* fall through */
58
+ }
59
+ return { text: "<ciphertext>" };
60
+ }
61
+
62
+ /** Resolve a channel's backing space id (metadata.linked_space_id) via channel-manage. */
63
+ async function resolveLinkedSpaceId(channelId: string): Promise<string> {
64
+ type GetResponse = {
65
+ channel?: { metadata?: { linked_space_id?: string } | null };
66
+ linked_space_id?: string;
67
+ };
68
+ const data = await invokeFunction<GetResponse>("channel-manage", { action: "get", channel_id: channelId });
69
+ const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
70
+ if (!spaceId) {
71
+ throw new Error(
72
+ `Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, ` +
73
+ `or pass space_id explicitly.`,
74
+ );
75
+ }
76
+ return spaceId;
77
+ }
78
+
79
+ async function mIRC_post_message(
80
+ input: z.infer<typeof mIRC_post_message_input>,
81
+ ctx: MosaddToolContext,
82
+ ): Promise<{ message_id: string; delivered_at: string; thread_id: string }> {
83
+ readSupabaseEnv();
84
+ const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
85
+ const thread_id = `chat:${input.channel_id}`;
86
+ ctx.log("debug", "mIRC_post_message", { thread_id, space_id });
87
+
88
+ const data = await invokeFunction<{ message?: { id: string; created_at: string } }>("message-send", {
89
+ space_id,
90
+ thread_id,
91
+ encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
92
+ message_type: "txt",
93
+ protocol_version: PROTOCOL_VERSION,
94
+ reply_to_id: input.reply_to_id ?? null,
95
+ });
96
+
97
+ if (!data?.message?.id) throw new Error("message-send returned no message id");
98
+ return { message_id: data.message.id, delivered_at: data.message.created_at ?? new Date().toISOString(), thread_id };
99
+ }
100
+
101
+ async function mIRC_list_messages(
102
+ input: z.infer<typeof mIRC_list_messages_input>,
103
+ ctx: MosaddToolContext,
104
+ ): Promise<{
105
+ messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }>;
106
+ next_cursor: string | null;
107
+ }> {
108
+ readSupabaseEnv();
109
+ const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
110
+ const thread_id = `chat:${input.channel_id}`;
111
+ ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
112
+
113
+ type MessageListResponse = {
114
+ messages?: Array<{ id: string; sender_identity_id: string; encrypted_payload: string; created_at: string }>;
115
+ next_before?: string | null;
116
+ cursor?: string | null;
117
+ };
118
+ // message-list reads `before` (history) / `since` (incremental) — NOT `cursor`.
119
+ // Sending `cursor` left `before` unset → every call returned the newest page.
120
+ const data = await invokeFunction<MessageListResponse>("message-list", {
121
+ space_id,
122
+ thread_id,
123
+ limit: input.limit ?? 50,
124
+ before: input.cursor,
125
+ });
126
+
127
+ return {
128
+ messages: (data?.messages ?? []).map((m) => ({
129
+ id: m.id,
130
+ sender_identity_id: m.sender_identity_id,
131
+ text: unpackPayload(m.encrypted_payload).text,
132
+ timestamp: m.created_at,
133
+ })),
134
+ next_cursor: data?.next_before ?? data?.cursor ?? null,
135
+ };
136
+ }
137
+
138
+ export const mircMessagesTools: MosaddTool[] = [
139
+ {
140
+ name: "mIRC_post_message",
141
+ requires: "network",
142
+ description:
143
+ "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 — 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. ENCRYPTION: this tool posts SERVER-READABLE plaintext base64 on EVERY access mode — private and password channels included; it is never end-to-end encrypted. Open channels: app clients CAN read toolkit-posted messages. Password/private channels: the mosadd.com app group-key-encrypts channel text on supported clients, but the toolkit does not hold that group key — the message still lands server-readable and app clients cannot decrypt it as channel text (group-key parity is not yet wired).",
144
+ inputSchema: mIRC_post_message_input,
145
+ handler: mIRC_post_message as MosaddTool["handler"],
146
+ },
147
+ {
148
+ name: "mIRC_list_messages",
149
+ requires: "network",
150
+ description:
151
+ "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
152
+ inputSchema: mIRC_list_messages_input,
153
+ handler: mIRC_list_messages as MosaddTool["handler"],
154
+ },
155
+ ];
package/src/tools/mirc.ts CHANGED
@@ -52,7 +52,7 @@ const mIRC_create_input = z.object({
52
52
  .string()
53
53
  .optional()
54
54
  .describe(
55
- "Required for access_mode=password|private (these are E2EE channels): the channel's group key wrapped to the creator's identity key. Open channels ignore it. If omitted on a non-open channel the backend rejects the call with a 'wrapped_group_key required' error.",
55
+ "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.",
56
56
  ),
57
57
  });
58
58
 
@@ -198,7 +198,7 @@ export const mircTools: MosaddTool[] = [
198
198
  name: "mIRC_create",
199
199
  requires: "network",
200
200
  description:
201
- "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 and private channels have end-to-end encrypted TEXT — supply wrapped_group_key (the group key wrapped to your identity key); open channels do not need it. Channel voice is never E2EE.",
201
+ "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 — 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.",
202
202
  inputSchema: mIRC_create_input,
203
203
  handler: mIRC_create as MosaddTool["handler"],
204
204
  },
@@ -1,142 +1,142 @@
1
- /**
2
- * mROOM text mode — send + list messages inside a private room.
3
- *
4
- * mROOM_send_message and mROOM_list_messages route through the same
5
- * the mosadd backend's `message-send` / `message-list` Edge Functions that mDM uses,
6
- * but with `space_id: 'rooms'` and `thread_id: 'privroom:<room_id>'` so the
7
- * RLS policies apply room-membership checks rather than DM contact checks.
8
- *
9
- * Voice in rooms (PTT, audio) lands separately via mTALK_start_session
10
- * over the WebRTC daemon — see LINEAR-2145.
11
- */
12
-
13
- import { z } from "zod";
14
- import type { MosaddTool, MosaddToolContext } from "../types.js";
15
- import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
16
-
17
- const PROTOCOL_VERSION = "mosadd.chat.v1";
18
-
19
- const RoomId = z.string().min(1).describe("Private room id (UUID). From mROOM_create / mROOM_list.");
20
-
21
- const mROOM_send_message_input = z.object({
22
- room_id: RoomId,
23
- text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
24
- reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
25
- });
26
-
27
- const mROOM_list_messages_input = z.object({
28
- room_id: RoomId,
29
- limit: z.number().int().min(1).max(200).default(50).optional(),
30
- cursor: z.string().optional().describe("Opaque pagination cursor from a prior list response."),
31
- });
32
-
33
- function packPlaintextPayload(text: string, replyToId?: string): string {
34
- const envelope = {
35
- v: PROTOCOL_VERSION,
36
- type: "text",
37
- text,
38
- reply_to: replyToId ?? null,
39
- sent_at: new Date().toISOString(),
40
- };
41
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
42
- }
43
-
44
- function unpackPayload(payload: string): { text: string } {
45
- try {
46
- const json = Buffer.from(payload, "base64").toString("utf8");
47
- const obj = JSON.parse(json);
48
- if (typeof obj?.text === "string") return obj;
49
- } catch {
50
- /* fall through */
51
- }
52
- return { text: "<ciphertext>" };
53
- }
54
-
55
- async function mROOM_send_message(
56
- input: z.infer<typeof mROOM_send_message_input>,
57
- ctx: MosaddToolContext,
58
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string }> {
59
- readSupabaseEnv();
60
- const thread_id = `privroom:${input.room_id}`;
61
- ctx.log("debug", "mROOM_send_message", { thread_id });
62
-
63
- const data = await invokeFunction<{ message?: { id: string; created_at: string } }>(
64
- "message-send",
65
- {
66
- space_id: "rooms",
67
- thread_id,
68
- encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
69
- message_type: "text",
70
- protocol_version: PROTOCOL_VERSION,
71
- reply_to_id: input.reply_to_id ?? null,
72
- },
73
- );
74
-
75
- if (!data?.message?.id) {
76
- throw new Error("message-send returned no message id");
77
- }
78
-
79
- return {
80
- message_id: data.message.id,
81
- delivered_at: data.message.created_at ?? new Date().toISOString(),
82
- thread_id,
83
- };
84
- }
85
-
86
- async function mROOM_list_messages(
87
- input: z.infer<typeof mROOM_list_messages_input>,
88
- ctx: MosaddToolContext,
89
- ): Promise<{
90
- messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }>;
91
- next_cursor: string | null;
92
- }> {
93
- readSupabaseEnv();
94
- const thread_id = `privroom:${input.room_id}`;
95
- ctx.log("debug", "mROOM_list_messages", { thread_id });
96
-
97
- type MessageListResponse = {
98
- messages?: Array<{
99
- id: string;
100
- sender_identity_id: string;
101
- encrypted_payload: string;
102
- created_at: string;
103
- }>;
104
- next_cursor?: string | null;
105
- };
106
-
107
- const data = await invokeFunction<MessageListResponse>("message-list", {
108
- space_id: "rooms",
109
- thread_id,
110
- limit: input.limit ?? 50,
111
- cursor: input.cursor,
112
- });
113
-
114
- return {
115
- messages: (data?.messages ?? []).map((m) => ({
116
- id: m.id,
117
- sender_identity_id: m.sender_identity_id,
118
- text: unpackPayload(m.encrypted_payload).text,
119
- timestamp: m.created_at,
120
- })),
121
- next_cursor: data?.next_cursor ?? null,
122
- };
123
- }
124
-
125
- export const mroomMessagesTools: MosaddTool[] = [
126
- {
127
- name: "mROOM_send_message",
128
- requires: "network",
129
- description:
130
- "Send a text message into a private room. Authorisation: must be a member (or guest with a valid token). Alpha payload is plaintext base64; v0.2 wraps with Double Ratchet.",
131
- inputSchema: mROOM_send_message_input,
132
- handler: mROOM_send_message as MosaddTool["handler"],
133
- },
134
- {
135
- name: "mROOM_list_messages",
136
- requires: "network",
137
- description:
138
- "List recent text messages in a private room. Cursor-paginated, newest first.",
139
- inputSchema: mROOM_list_messages_input,
140
- handler: mROOM_list_messages as MosaddTool["handler"],
141
- },
142
- ];
1
+ /**
2
+ * mROOM text mode — send + list messages inside a private room.
3
+ *
4
+ * mROOM_send_message and mROOM_list_messages route through the same
5
+ * the mosadd backend's `message-send` / `message-list` Edge Functions that mDM uses,
6
+ * but with `space_id: 'rooms'` and `thread_id: 'privroom:<room_id>'` so the
7
+ * RLS policies apply room-membership checks rather than DM contact checks.
8
+ *
9
+ * Voice in rooms (PTT, audio) lands separately via mTALK_start_session
10
+ * over the WebRTC daemon — see LINEAR-2145.
11
+ */
12
+
13
+ import { z } from "zod";
14
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
15
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
16
+
17
+ const PROTOCOL_VERSION = "mosadd.chat.v1";
18
+
19
+ const RoomId = z.string().min(1).describe("Private room id (UUID). From mROOM_create / mROOM_list.");
20
+
21
+ const mROOM_send_message_input = z.object({
22
+ room_id: RoomId,
23
+ text: z.string().min(1).max(64_000).describe("Message body (UTF-8). Max 64 KB."),
24
+ reply_to_id: z.string().optional().describe("Optional id of the message being replied to."),
25
+ });
26
+
27
+ const mROOM_list_messages_input = z.object({
28
+ room_id: RoomId,
29
+ limit: z.number().int().min(1).max(200).default(50).optional(),
30
+ cursor: z.string().optional().describe("Opaque pagination cursor from a prior list response."),
31
+ });
32
+
33
+ function packPlaintextPayload(text: string, replyToId?: string): string {
34
+ const envelope = {
35
+ v: PROTOCOL_VERSION,
36
+ type: "text",
37
+ text,
38
+ reply_to: replyToId ?? null,
39
+ sent_at: new Date().toISOString(),
40
+ };
41
+ return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
42
+ }
43
+
44
+ function unpackPayload(payload: string): { text: string } {
45
+ try {
46
+ const json = Buffer.from(payload, "base64").toString("utf8");
47
+ const obj = JSON.parse(json);
48
+ if (typeof obj?.text === "string") return obj;
49
+ } catch {
50
+ /* fall through */
51
+ }
52
+ return { text: "<ciphertext>" };
53
+ }
54
+
55
+ async function mROOM_send_message(
56
+ input: z.infer<typeof mROOM_send_message_input>,
57
+ ctx: MosaddToolContext,
58
+ ): Promise<{ message_id: string; delivered_at: string; thread_id: string }> {
59
+ readSupabaseEnv();
60
+ const thread_id = `privroom:${input.room_id}`;
61
+ ctx.log("debug", "mROOM_send_message", { thread_id });
62
+
63
+ const data = await invokeFunction<{ message?: { id: string; created_at: string } }>(
64
+ "message-send",
65
+ {
66
+ space_id: "rooms",
67
+ thread_id,
68
+ encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
69
+ message_type: "text",
70
+ protocol_version: PROTOCOL_VERSION,
71
+ reply_to_id: input.reply_to_id ?? null,
72
+ },
73
+ );
74
+
75
+ if (!data?.message?.id) {
76
+ throw new Error("message-send returned no message id");
77
+ }
78
+
79
+ return {
80
+ message_id: data.message.id,
81
+ delivered_at: data.message.created_at ?? new Date().toISOString(),
82
+ thread_id,
83
+ };
84
+ }
85
+
86
+ async function mROOM_list_messages(
87
+ input: z.infer<typeof mROOM_list_messages_input>,
88
+ ctx: MosaddToolContext,
89
+ ): Promise<{
90
+ messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }>;
91
+ next_cursor: string | null;
92
+ }> {
93
+ readSupabaseEnv();
94
+ const thread_id = `privroom:${input.room_id}`;
95
+ ctx.log("debug", "mROOM_list_messages", { thread_id });
96
+
97
+ type MessageListResponse = {
98
+ messages?: Array<{
99
+ id: string;
100
+ sender_identity_id: string;
101
+ encrypted_payload: string;
102
+ created_at: string;
103
+ }>;
104
+ next_cursor?: string | null;
105
+ };
106
+
107
+ const data = await invokeFunction<MessageListResponse>("message-list", {
108
+ space_id: "rooms",
109
+ thread_id,
110
+ limit: input.limit ?? 50,
111
+ cursor: input.cursor,
112
+ });
113
+
114
+ return {
115
+ messages: (data?.messages ?? []).map((m) => ({
116
+ id: m.id,
117
+ sender_identity_id: m.sender_identity_id,
118
+ text: unpackPayload(m.encrypted_payload).text,
119
+ timestamp: m.created_at,
120
+ })),
121
+ next_cursor: data?.next_cursor ?? null,
122
+ };
123
+ }
124
+
125
+ export const mroomMessagesTools: MosaddTool[] = [
126
+ {
127
+ name: "mROOM_send_message",
128
+ requires: "network",
129
+ description:
130
+ "Send a text message into a private room. Authorisation: must be a member (or guest with a valid token). Alpha payload is plaintext base64; v0.2 wraps with Double Ratchet.",
131
+ inputSchema: mROOM_send_message_input,
132
+ handler: mROOM_send_message as MosaddTool["handler"],
133
+ },
134
+ {
135
+ name: "mROOM_list_messages",
136
+ requires: "network",
137
+ description:
138
+ "List recent text messages in a private room. Cursor-paginated, newest first.",
139
+ inputSchema: mROOM_list_messages_input,
140
+ handler: mROOM_list_messages as MosaddTool["handler"],
141
+ },
142
+ ];