@mosadd/mcp 3.0.0-alpha.52 → 3.0.0-alpha.53

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 (58) hide show
  1. package/CHANGELOG.md +334 -309
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-KVN7LZFW.js → chunk-AWKITPZQ.js} +384 -103
  5. package/dist/index.d.ts +11 -1
  6. package/dist/index.js +1 -1
  7. package/package.json +9 -9
  8. package/src/__tests__/golden-path.test.ts +139 -139
  9. package/src/__tests__/integration.test.ts +182 -182
  10. package/src/__tests__/knowledge-ingest.test.ts +114 -114
  11. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  12. package/src/__tests__/mdm-mcp-readable.test.ts +284 -0
  13. package/src/__tests__/mirc-invite.test.ts +112 -112
  14. package/src/__tests__/mtalk.test.ts +122 -122
  15. package/src/__tests__/server.test.ts +71 -71
  16. package/src/__tests__/serverJsonVersion.test.ts +45 -45
  17. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  18. package/src/bin/login.ts +138 -138
  19. package/src/bin/mcp.ts +145 -145
  20. package/src/config.ts +66 -66
  21. package/src/crypto/mdm-session.ts +798 -502
  22. package/src/index.ts +19 -19
  23. package/src/observability/sentry.ts +79 -79
  24. package/src/providers/memory-voice.ts +79 -79
  25. package/src/providers/supabase-dm.ts +174 -122
  26. package/src/providers/supabase-voice.ts +91 -91
  27. package/src/providers/supabase.ts +231 -231
  28. package/src/server.ts +186 -162
  29. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -67
  30. package/src/tools/actions.ts +166 -166
  31. package/src/tools/attachments.ts +276 -276
  32. package/src/tools/capabilities.ts +70 -70
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge-graph.ts +186 -186
  36. package/src/tools/knowledge.ts +344 -344
  37. package/src/tools/mail-agentbox.ts +155 -155
  38. package/src/tools/mail-aliases.ts +25 -25
  39. package/src/tools/mail-provenance.ts +137 -137
  40. package/src/tools/mail.ts +403 -403
  41. package/src/tools/mcall.ts +216 -216
  42. package/src/tools/mdm-as-agent.ts +126 -126
  43. package/src/tools/mdm-voice.ts +220 -220
  44. package/src/tools/mdm.ts +119 -17
  45. package/src/tools/mirc-edge.ts +196 -196
  46. package/src/tools/mirc-members.ts +287 -287
  47. package/src/tools/mirc.ts +308 -308
  48. package/src/tools/mroom-messages.ts +142 -142
  49. package/src/tools/mroom.ts +221 -221
  50. package/src/tools/mtalk.ts +131 -131
  51. package/src/tools/murl.ts +314 -314
  52. package/src/tools/presence.ts +442 -442
  53. package/src/tools/ptt-ingest.ts +99 -99
  54. package/src/tools/threat.ts +123 -123
  55. package/src/types.ts +121 -121
  56. package/src/version.ts +8 -8
  57. package/src/voice/floor.ts +132 -132
  58. package/LICENSE +0 -201
@@ -1,220 +1,220 @@
1
- /**
2
- * mDM — 1:1 voice (full-duplex call + voice note).
3
- *
4
- * mDM is the PRIVATE channel: 1:1 / threaded text (mdm.ts) PLUS real-time 1:1
5
- * voice here. This is the ordinary phone-style call between two people — NOT
6
- * walkie-talkie (that's mTALK, half-duplex floor control) and NOT the telephone
7
- * network (that's mCALL / PSTN). Audio rides the same media transport the
8
- * VoiceProvider points at (LiveKit by default); these tools coordinate the room
9
- * and the call invite/hangup signalling over the DM channel.
10
- *
11
- * Flow:
12
- * caller: mDM_call_start({ to }) → creates a room, returns join creds, AND
13
- * drops a `call_invite` control message in the DM thread.
14
- * callee: sees the invite (mDM_list), then mDM_call_answer({ room_id }) → creds.
15
- * either: mDM_call_end({ room_id, to }) → drops a `call_end` control message.
16
- *
17
- * No new backend: rooms + tokens come from ctx.providers.voice (same minting
18
- * path mTALK uses); signalling reuses ctx.providers.dm.send.
19
- */
20
-
21
- import { z } from "zod";
22
- import type { MosaddTool, MosaddToolContext } from "../types.js";
23
-
24
- const PROTOCOL_VERSION = "mosadd.chat.v1";
25
-
26
- const ContactRef = z
27
- .string()
28
- .min(1)
29
- .describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
30
-
31
- const RoomId = z.string().min(1).describe("Voice room id (from mDM_call_start's call_invite).");
32
-
33
- const mDM_call_start_input = z.object({
34
- to: ContactRef,
35
- video: z.boolean().optional().describe("Request a video call instead of audio-only. Default false."),
36
- thread_label: z
37
- .string()
38
- .max(120)
39
- .regex(/^[a-zA-Z0-9._-]+$/)
40
- .optional()
41
- .describe("Optional thread label to place the call invite in. Defaults to the contact's main thread."),
42
- });
43
-
44
- const mDM_call_answer_input = z.object({ room_id: RoomId });
45
-
46
- const mDM_call_end_input = z.object({
47
- room_id: RoomId,
48
- to: ContactRef.optional().describe("If set, also drop a call_end control message in this contact's DM thread."),
49
- thread_label: z.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional(),
50
- });
51
-
52
- const mDM_voice_note_input = z.object({
53
- to: ContactRef,
54
- audio_url: z.string().url().describe("URL of the recorded audio clip (already uploaded by the client)."),
55
- duration_ms: z.number().int().positive().optional().describe("Clip length in milliseconds, if known."),
56
- mime: z.string().max(120).optional().describe("Audio MIME type, e.g. audio/ogg, audio/mpeg. Default audio/ogg."),
57
- thread_label: z.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional(),
58
- });
59
-
60
- // ---- Helpers ----
61
-
62
- /** Deterministic DM thread id (sorted pair) — must match mdm.ts dmThreadId. */
63
- function dmThreadId(selfId: string, otherId: string, label?: string): string {
64
- const [a, b] = [selfId, otherId].sort();
65
- return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
66
- }
67
-
68
- /** Pack a mosadd.chat.v1 control/voice envelope into the opaque payload bytes. */
69
- function packEnvelope(obj: Record<string, unknown>): Uint8Array {
70
- const envelope = { v: PROTOCOL_VERSION, sent_at: new Date().toISOString(), ...obj };
71
- return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
72
- }
73
-
74
- async function signalDm(
75
- ctx: MosaddToolContext,
76
- to: string,
77
- threadLabel: string | undefined,
78
- envelope: Record<string, unknown>,
79
- ): Promise<{ message_id?: string; thread_id: string }> {
80
- const dm = ctx.providers.dm;
81
- const selfId = await dm.selfId();
82
- const threadId = dmThreadId(selfId, to, threadLabel);
83
- // DmProvider.send returns DmSendResult { id, deliveredAt } — read `id` (the old
84
- // `message_id` lookup was always undefined, so the echoed id never populated).
85
- const res = await dm.send({ to, threadId, payload: packEnvelope(envelope) });
86
- return { message_id: (res as { id?: string })?.id, thread_id: threadId };
87
- }
88
-
89
- // ---- Handlers ----
90
-
91
- async function mDM_call_start(
92
- input: z.infer<typeof mDM_call_start_input>,
93
- ctx: MosaddToolContext,
94
- ): Promise<{
95
- room_id: string;
96
- token: string;
97
- url: string;
98
- identity: string;
99
- mode: "audio" | "video";
100
- invited: boolean;
101
- thread_id: string;
102
- }> {
103
- const dm = ctx.providers.dm;
104
- const selfId = await dm.selfId();
105
- const mode = input.video ? "video" : "audio";
106
-
107
- // Stable room label tied to the DM PAIR (no thread_label) so re-dials reuse one
108
- // room AND the name stays short enough that both participants' full identity ids
109
- // are always present — the livekit-token gate authorizes by full-id inclusion, so
110
- // truncating an id would lock a real participant out. (thread_label still routes
111
- // the call_invite message below, just not the room id.)
112
- const label = `dmcall-${dmThreadId(selfId, input.to).replace(/[^a-zA-Z0-9._-]/g, "-")}`.slice(0, 120);
113
- const { roomId } = await ctx.providers.voice.createRoom(label);
114
- const ticket = await ctx.providers.voice.joinTicket(roomId);
115
-
116
- let invited = false;
117
- let thread_id = dmThreadId(selfId, input.to, input.thread_label);
118
- try {
119
- const sig = await signalDm(ctx, input.to, input.thread_label, {
120
- type: "call_invite",
121
- room_id: roomId,
122
- mode,
123
- from: selfId,
124
- });
125
- thread_id = sig.thread_id;
126
- invited = true;
127
- } catch (e) {
128
- ctx.log("warn", "mDM_call_start: invite signal failed (room still usable)", {
129
- error: (e as Error).message,
130
- });
131
- }
132
-
133
- ctx.log("debug", "mDM_call_start", { room_id: roomId, mode, invited });
134
- return { room_id: roomId, token: ticket.token, url: ticket.url, identity: ticket.identity, mode, invited, thread_id };
135
- }
136
-
137
- async function mDM_call_answer(
138
- input: z.infer<typeof mDM_call_answer_input>,
139
- ctx: MosaddToolContext,
140
- ): Promise<{ room_id: string; token: string; url: string; identity: string }> {
141
- const ticket = await ctx.providers.voice.joinTicket(input.room_id);
142
- ctx.log("debug", "mDM_call_answer", { room_id: ticket.roomId, identity: ticket.identity });
143
- return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
144
- }
145
-
146
- async function mDM_call_end(
147
- input: z.infer<typeof mDM_call_end_input>,
148
- ctx: MosaddToolContext,
149
- ): Promise<{ room_id: string; signalled: boolean }> {
150
- let signalled = false;
151
- if (input.to) {
152
- try {
153
- await signalDm(ctx, input.to, input.thread_label, { type: "call_end", room_id: input.room_id });
154
- signalled = true;
155
- } catch (e) {
156
- ctx.log("warn", "mDM_call_end: hangup signal failed", { error: (e as Error).message });
157
- }
158
- }
159
- ctx.log("debug", "mDM_call_end", { room_id: input.room_id, signalled });
160
- return { room_id: input.room_id, signalled };
161
- }
162
-
163
- async function mDM_voice_note(
164
- input: z.infer<typeof mDM_voice_note_input>,
165
- ctx: MosaddToolContext,
166
- ): Promise<{ message_id?: string; thread_id: string }> {
167
- const sig = await signalDm(ctx, input.to, input.thread_label, {
168
- type: "voice_note",
169
- audio_url: input.audio_url,
170
- duration_ms: input.duration_ms ?? null,
171
- mime: input.mime ?? "audio/ogg",
172
- });
173
- ctx.log("debug", "mDM_voice_note", { thread_id: sig.thread_id });
174
- return sig;
175
- }
176
-
177
- // ---- Registration ----
178
-
179
- export const mdmVoiceTools: MosaddTool[] = [
180
- {
181
- name: "mDM_call_start",
182
- title: "Start a voice call",
183
- annotations: { readOnlyHint: false },
184
- requires: "network",
185
- description:
186
- "Start a 1:1 real-time voice (or video) call with a contact — 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.",
187
- inputSchema: mDM_call_start_input,
188
- handler: mDM_call_start as MosaddTool["handler"],
189
- },
190
- {
191
- name: "mDM_call_answer",
192
- title: "Answer a voice call",
193
- annotations: { readOnlyHint: false },
194
- requires: "network",
195
- description:
196
- "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.",
197
- inputSchema: mDM_call_answer_input,
198
- handler: mDM_call_answer as MosaddTool["handler"],
199
- },
200
- {
201
- name: "mDM_call_end",
202
- title: "End a voice call",
203
- annotations: { readOnlyHint: false },
204
- requires: "network",
205
- description:
206
- "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.",
207
- inputSchema: mDM_call_end_input,
208
- handler: mDM_call_end as MosaddTool["handler"],
209
- },
210
- {
211
- name: "mDM_voice_note",
212
- title: "Leave a voice note",
213
- annotations: { readOnlyHint: false },
214
- requires: "network",
215
- description:
216
- "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.",
217
- inputSchema: mDM_voice_note_input,
218
- handler: mDM_voice_note as MosaddTool["handler"],
219
- },
220
- ];
1
+ /**
2
+ * mDM — 1:1 voice (full-duplex call + voice note).
3
+ *
4
+ * mDM is the PRIVATE channel: 1:1 / threaded text (mdm.ts) PLUS real-time 1:1
5
+ * voice here. This is the ordinary phone-style call between two people — NOT
6
+ * walkie-talkie (that's mTALK, half-duplex floor control) and NOT the telephone
7
+ * network (that's mCALL / PSTN). Audio rides the same media transport the
8
+ * VoiceProvider points at (LiveKit by default); these tools coordinate the room
9
+ * and the call invite/hangup signalling over the DM channel.
10
+ *
11
+ * Flow:
12
+ * caller: mDM_call_start({ to }) → creates a room, returns join creds, AND
13
+ * drops a `call_invite` control message in the DM thread.
14
+ * callee: sees the invite (mDM_list), then mDM_call_answer({ room_id }) → creds.
15
+ * either: mDM_call_end({ room_id, to }) → drops a `call_end` control message.
16
+ *
17
+ * No new backend: rooms + tokens come from ctx.providers.voice (same minting
18
+ * path mTALK uses); signalling reuses ctx.providers.dm.send.
19
+ */
20
+
21
+ import { z } from "zod";
22
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
23
+
24
+ const PROTOCOL_VERSION = "mosadd.chat.v1";
25
+
26
+ const ContactRef = z
27
+ .string()
28
+ .min(1)
29
+ .describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
30
+
31
+ const RoomId = z.string().min(1).describe("Voice room id (from mDM_call_start's call_invite).");
32
+
33
+ const mDM_call_start_input = z.object({
34
+ to: ContactRef,
35
+ video: z.boolean().optional().describe("Request a video call instead of audio-only. Default false."),
36
+ thread_label: z
37
+ .string()
38
+ .max(120)
39
+ .regex(/^[a-zA-Z0-9._-]+$/)
40
+ .optional()
41
+ .describe("Optional thread label to place the call invite in. Defaults to the contact's main thread."),
42
+ });
43
+
44
+ const mDM_call_answer_input = z.object({ room_id: RoomId });
45
+
46
+ const mDM_call_end_input = z.object({
47
+ room_id: RoomId,
48
+ to: ContactRef.optional().describe("If set, also drop a call_end control message in this contact's DM thread."),
49
+ thread_label: z.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional(),
50
+ });
51
+
52
+ const mDM_voice_note_input = z.object({
53
+ to: ContactRef,
54
+ audio_url: z.string().url().describe("URL of the recorded audio clip (already uploaded by the client)."),
55
+ duration_ms: z.number().int().positive().optional().describe("Clip length in milliseconds, if known."),
56
+ mime: z.string().max(120).optional().describe("Audio MIME type, e.g. audio/ogg, audio/mpeg. Default audio/ogg."),
57
+ thread_label: z.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional(),
58
+ });
59
+
60
+ // ---- Helpers ----
61
+
62
+ /** Deterministic DM thread id (sorted pair) — must match mdm.ts dmThreadId. */
63
+ function dmThreadId(selfId: string, otherId: string, label?: string): string {
64
+ const [a, b] = [selfId, otherId].sort();
65
+ return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
66
+ }
67
+
68
+ /** Pack a mosadd.chat.v1 control/voice envelope into the opaque payload bytes. */
69
+ function packEnvelope(obj: Record<string, unknown>): Uint8Array {
70
+ const envelope = { v: PROTOCOL_VERSION, sent_at: new Date().toISOString(), ...obj };
71
+ return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
72
+ }
73
+
74
+ async function signalDm(
75
+ ctx: MosaddToolContext,
76
+ to: string,
77
+ threadLabel: string | undefined,
78
+ envelope: Record<string, unknown>,
79
+ ): Promise<{ message_id?: string; thread_id: string }> {
80
+ const dm = ctx.providers.dm;
81
+ const selfId = await dm.selfId();
82
+ const threadId = dmThreadId(selfId, to, threadLabel);
83
+ // DmProvider.send returns DmSendResult { id, deliveredAt } — read `id` (the old
84
+ // `message_id` lookup was always undefined, so the echoed id never populated).
85
+ const res = await dm.send({ to, threadId, payload: packEnvelope(envelope) });
86
+ return { message_id: (res as { id?: string })?.id, thread_id: threadId };
87
+ }
88
+
89
+ // ---- Handlers ----
90
+
91
+ async function mDM_call_start(
92
+ input: z.infer<typeof mDM_call_start_input>,
93
+ ctx: MosaddToolContext,
94
+ ): Promise<{
95
+ room_id: string;
96
+ token: string;
97
+ url: string;
98
+ identity: string;
99
+ mode: "audio" | "video";
100
+ invited: boolean;
101
+ thread_id: string;
102
+ }> {
103
+ const dm = ctx.providers.dm;
104
+ const selfId = await dm.selfId();
105
+ const mode = input.video ? "video" : "audio";
106
+
107
+ // Stable room label tied to the DM PAIR (no thread_label) so re-dials reuse one
108
+ // room AND the name stays short enough that both participants' full identity ids
109
+ // are always present — the livekit-token gate authorizes by full-id inclusion, so
110
+ // truncating an id would lock a real participant out. (thread_label still routes
111
+ // the call_invite message below, just not the room id.)
112
+ const label = `dmcall-${dmThreadId(selfId, input.to).replace(/[^a-zA-Z0-9._-]/g, "-")}`.slice(0, 120);
113
+ const { roomId } = await ctx.providers.voice.createRoom(label);
114
+ const ticket = await ctx.providers.voice.joinTicket(roomId);
115
+
116
+ let invited = false;
117
+ let thread_id = dmThreadId(selfId, input.to, input.thread_label);
118
+ try {
119
+ const sig = await signalDm(ctx, input.to, input.thread_label, {
120
+ type: "call_invite",
121
+ room_id: roomId,
122
+ mode,
123
+ from: selfId,
124
+ });
125
+ thread_id = sig.thread_id;
126
+ invited = true;
127
+ } catch (e) {
128
+ ctx.log("warn", "mDM_call_start: invite signal failed (room still usable)", {
129
+ error: (e as Error).message,
130
+ });
131
+ }
132
+
133
+ ctx.log("debug", "mDM_call_start", { room_id: roomId, mode, invited });
134
+ return { room_id: roomId, token: ticket.token, url: ticket.url, identity: ticket.identity, mode, invited, thread_id };
135
+ }
136
+
137
+ async function mDM_call_answer(
138
+ input: z.infer<typeof mDM_call_answer_input>,
139
+ ctx: MosaddToolContext,
140
+ ): Promise<{ room_id: string; token: string; url: string; identity: string }> {
141
+ const ticket = await ctx.providers.voice.joinTicket(input.room_id);
142
+ ctx.log("debug", "mDM_call_answer", { room_id: ticket.roomId, identity: ticket.identity });
143
+ return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
144
+ }
145
+
146
+ async function mDM_call_end(
147
+ input: z.infer<typeof mDM_call_end_input>,
148
+ ctx: MosaddToolContext,
149
+ ): Promise<{ room_id: string; signalled: boolean }> {
150
+ let signalled = false;
151
+ if (input.to) {
152
+ try {
153
+ await signalDm(ctx, input.to, input.thread_label, { type: "call_end", room_id: input.room_id });
154
+ signalled = true;
155
+ } catch (e) {
156
+ ctx.log("warn", "mDM_call_end: hangup signal failed", { error: (e as Error).message });
157
+ }
158
+ }
159
+ ctx.log("debug", "mDM_call_end", { room_id: input.room_id, signalled });
160
+ return { room_id: input.room_id, signalled };
161
+ }
162
+
163
+ async function mDM_voice_note(
164
+ input: z.infer<typeof mDM_voice_note_input>,
165
+ ctx: MosaddToolContext,
166
+ ): Promise<{ message_id?: string; thread_id: string }> {
167
+ const sig = await signalDm(ctx, input.to, input.thread_label, {
168
+ type: "voice_note",
169
+ audio_url: input.audio_url,
170
+ duration_ms: input.duration_ms ?? null,
171
+ mime: input.mime ?? "audio/ogg",
172
+ });
173
+ ctx.log("debug", "mDM_voice_note", { thread_id: sig.thread_id });
174
+ return sig;
175
+ }
176
+
177
+ // ---- Registration ----
178
+
179
+ export const mdmVoiceTools: MosaddTool[] = [
180
+ {
181
+ name: "mDM_call_start",
182
+ title: "Start a voice call",
183
+ annotations: { readOnlyHint: false },
184
+ requires: "network",
185
+ description:
186
+ "Start a 1:1 real-time voice (or video) call with a contact — 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.",
187
+ inputSchema: mDM_call_start_input,
188
+ handler: mDM_call_start as MosaddTool["handler"],
189
+ },
190
+ {
191
+ name: "mDM_call_answer",
192
+ title: "Answer a voice call",
193
+ annotations: { readOnlyHint: false },
194
+ requires: "network",
195
+ description:
196
+ "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.",
197
+ inputSchema: mDM_call_answer_input,
198
+ handler: mDM_call_answer as MosaddTool["handler"],
199
+ },
200
+ {
201
+ name: "mDM_call_end",
202
+ title: "End a voice call",
203
+ annotations: { readOnlyHint: false },
204
+ requires: "network",
205
+ description:
206
+ "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.",
207
+ inputSchema: mDM_call_end_input,
208
+ handler: mDM_call_end as MosaddTool["handler"],
209
+ },
210
+ {
211
+ name: "mDM_voice_note",
212
+ title: "Leave a voice note",
213
+ annotations: { readOnlyHint: false },
214
+ requires: "network",
215
+ description:
216
+ "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.",
217
+ inputSchema: mDM_voice_note_input,
218
+ handler: mDM_voice_note as MosaddTool["handler"],
219
+ },
220
+ ];
package/src/tools/mdm.ts CHANGED
@@ -23,7 +23,16 @@ import {
23
23
  decryptFromPeer,
24
24
  publishOwnPrekeys,
25
25
  isE2eeEnvelope,
26
+ ensureOwnBundlePublished,
27
+ fetchVerifiedBundle,
28
+ sealForSelf,
29
+ sealForPeerRecoverable,
30
+ openSelfSealed,
31
+ openPeerRecoverable,
32
+ type OwnBundleState,
33
+ type PublicPrekeyBundle,
26
34
  } from "../crypto/mdm-session.js";
35
+ import { MDM_TEXT_MESSAGE_TYPE, type DmSendArgsExt, type DmMessageExt } from "../providers/supabase-dm.js";
27
36
 
28
37
  // ---- Constants ----
29
38
 
@@ -139,10 +148,27 @@ function unpackPayload(payload: Uint8Array): { text: string; sent_at?: string; r
139
148
 
140
149
  // ---- Handlers ----
141
150
 
151
+ /** Does this provider know the caller's identity kind (Supabase lane)? */
152
+ async function selfKindOf(dm: MosaddToolContext["providers"]["dm"]): Promise<string | null> {
153
+ const f = (dm as { selfKind?: () => Promise<string | null> }).selfKind;
154
+ return typeof f === "function" ? await f.call(dm) : null;
155
+ }
156
+
142
157
  async function mDM_send(
143
158
  input: z.infer<typeof mDM_send_input>,
144
159
  ctx: MosaddToolContext,
145
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: true }> {
160
+ ): Promise<{
161
+ message_id: string;
162
+ delivered_at: string;
163
+ thread_id: string;
164
+ encrypted: true;
165
+ /** the sender can read this message back on any process holding the same key (self_payload) */
166
+ sender_copy: boolean;
167
+ /** the recipient can open it without a ratchet session (recipient_self_payload) */
168
+ recipient_copy: boolean;
169
+ /** state of this identity in the key directory after the send */
170
+ identity: OwnBundleState;
171
+ }> {
146
172
  // E2EE path (default). The plaintext is packed into the inner mosadd.chat.v1
147
173
  // envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
148
174
  // DmProvider moves without understanding. First contact fetches the peer's
@@ -151,25 +177,67 @@ async function mDM_send(
151
177
  const selfId = await dm.selfId();
152
178
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
153
179
 
180
+ const keys = ctx.providers.keys;
181
+
182
+ // ⛔ 27.09.2026 — the three defects measured on prod, fixed at the source:
183
+ // 1. a NEW identity per call → the keystore is seed-derived from the key (server.ts), and the
184
+ // directory is made to agree with it here (never hijacking a person's app-anchored bundle);
185
+ // 2. NO self_payload → the sender's "s1." copy, the app's exact format;
186
+ // 3. message_type "text" → "txt", the type the app writes and reads.
187
+ // Plus the recipient's "r1." copy, so the reader needs no live ratchet session on any device.
188
+ let identity: OwnBundleState = "foreign";
189
+ try {
190
+ identity = await ensureOwnBundlePublished(keys, dm, selfId, {
191
+ mayReplaceForeign: (await selfKindOf(dm)) === "agent",
192
+ });
193
+ } catch (err) {
194
+ // Directory unreachable: the ratchet envelope still carries its own handshake, so the send
195
+ // proceeds; only the recipient copy is skipped (it would be sealed under an unverified identity).
196
+ ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
197
+ }
198
+
154
199
  // reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w którą
155
200
  // można by go wpakować (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
156
201
  const inner = packPlaintextPayload(input.text);
157
- const sealed = await encryptForPeer(ctx.providers.keys, dm, input.to, inner);
202
+ const sealed = await encryptForPeer(keys, dm, input.to, inner);
203
+
204
+ const selfPayload = await sealForSelf(keys, inner);
205
+ let recipientSelfPayload: string | null = null;
206
+ // The recipient opens "r1." with OUR PUBLISHED identity — so it is written only when the
207
+ // directory holds exactly our key. A note-to-self needs none: self_payload already covers it.
208
+ if (identity !== "foreign" && input.to !== selfId) {
209
+ try {
210
+ const peer = await fetchVerifiedBundle(dm, input.to);
211
+ if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
212
+ } catch (err) {
213
+ ctx.log("warn", "mDM_send skipped the recipient copy", { error: String(err) });
214
+ }
215
+ }
158
216
 
159
- ctx.log("debug", "mDM_send E2EE via DmProvider", { thread_id: threadId, bytes: sealed.byteLength });
217
+ ctx.log("debug", "mDM_send E2EE via DmProvider", {
218
+ thread_id: threadId,
219
+ bytes: sealed.byteLength,
220
+ identity,
221
+ sender_copy: !!selfPayload,
222
+ recipient_copy: !!recipientSelfPayload,
223
+ });
160
224
 
161
- const result = await dm.send({
225
+ const sendArgs: DmSendArgsExt = {
162
226
  to: input.to,
163
227
  threadId,
164
228
  payload: sealed,
165
229
  replyToId: input.reply_to_id,
166
- });
230
+ messageType: MDM_TEXT_MESSAGE_TYPE,
231
+ selfPayload,
232
+ recipientSelfPayload,
233
+ };
234
+ const result = await dm.send(sendArgs);
167
235
 
168
236
  // Keep a LOCAL copy of our own outgoing plaintext so mDM_list can show it
169
237
  // back to the sender (the ratchet can't re-derive it on read). Best-effort:
170
238
  // only if the keystore offers the optional sent-items cache.
171
- if (ctx.providers.keys.putSentMessage) {
172
- await ctx.providers.keys.putSentMessage(result.id, inner);
239
+ if (keys.putSentMessage) {
240
+ await keys.putSentMessage(result.id, inner);
173
241
  }
174
242
 
175
243
  return {
@@ -177,6 +245,9 @@ async function mDM_send(
177
245
  delivered_at: result.deliveredAt,
178
246
  thread_id: threadId,
179
247
  encrypted: true,
248
+ sender_copy: !!selfPayload,
249
+ recipient_copy: !!recipientSelfPayload,
250
+ identity,
180
251
  };
181
252
  }
182
253
 
@@ -197,12 +268,14 @@ async function mDM_send_unencrypted(
197
268
  bytes: payload.byteLength,
198
269
  });
199
270
 
200
- const result = await dm.send({
271
+ const plainArgs: DmSendArgsExt = {
201
272
  to: input.to,
202
273
  threadId,
203
274
  payload,
204
275
  replyToId: input.reply_to_id,
205
- });
276
+ messageType: MDM_TEXT_MESSAGE_TYPE,
277
+ };
278
+ const result = await dm.send(plainArgs);
206
279
 
207
280
  return {
208
281
  message_id: result.id,
@@ -246,8 +319,21 @@ async function mDM_list(
246
319
 
247
320
  const result = await dm.list({ threadId, limit: input.limit ?? 50, cursor: input.cursor });
248
321
 
322
+ const keys = ctx.providers.keys;
323
+ // One verified bundle per sender for the "r1." copies (usually just the contact).
324
+ const bundleBySender = new Map<string, Promise<PublicPrekeyBundle | null>>();
325
+ const senderBundle = (id: string) => {
326
+ let p = bundleBySender.get(id);
327
+ if (!p) {
328
+ p = fetchVerifiedBundle(dm, id).catch(() => null);
329
+ bundleBySender.set(id, p);
330
+ }
331
+ return p;
332
+ };
333
+
249
334
  const messages = await Promise.all(
250
- result.messages.map(async (m) => {
335
+ result.messages.map(async (raw) => {
336
+ const m = raw as DmMessageExt;
251
337
  const base = {
252
338
  id: m.id,
253
339
  sender_identity_id: m.senderId,
@@ -258,17 +344,33 @@ async function mDM_list(
258
344
  if (!isE2eeEnvelope(m.payload)) {
259
345
  return { ...base, text: formatVoiceIfAny(unpackPayload(m.payload).text), encrypted: false };
260
346
  }
261
- // Our own outgoing ratchet messages aren't decryptable from our own
262
- // ratchet on read. Recover the plaintext from the local sent-items cache
263
- // (this process). If absent (e.g. a different device/process), fall back
264
- // to a marker instead of failing.
347
+ // Our own outgoing ratchet messages aren't decryptable from our own ratchet on read.
348
+ // 1) the "s1." self copy (any process holding the same key), 2) this process's sent cache,
349
+ // 3) a note-to-self is sealed to our own bundle, so our own key opens it.
265
350
  if (m.senderId === selfId) {
266
- const cached = await ctx.providers.keys.getSentMessage?.(m.id);
267
- if (cached) {
268
- return { ...base, text: formatVoiceIfAny(unpackPayload(cached).text), encrypted: true };
351
+ const own = (await openSelfSealed(keys, m.selfPayload)) ?? (await keys.getSentMessage?.(m.id));
352
+ if (own) {
353
+ return { ...base, text: formatVoiceIfAny(unpackPayload(own).text), encrypted: true };
354
+ }
355
+ if (input.contact_id === selfId) {
356
+ try {
357
+ const inner = await decryptFromPeer(keys, selfId, m.payload);
358
+ return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
359
+ } catch { /* fall through to the marker */ }
269
360
  }
270
361
  return { ...base, text: "<encrypted · sent by you>", encrypted: true };
271
362
  }
363
+ // Recipient side: the sender's "r1." copy, or our own "s1." backfill in the same column
364
+ // (the app writes it after a successful read) — neither needs a live ratchet session.
365
+ if (m.recipientSelfPayload) {
366
+ const bundle = await senderBundle(m.senderId);
367
+ const copy =
368
+ (bundle ? await openPeerRecoverable(keys, bundle, m.recipientSelfPayload) : null) ??
369
+ (await openSelfSealed(keys, m.recipientSelfPayload));
370
+ if (copy) {
371
+ return { ...base, text: formatVoiceIfAny(unpackPayload(copy).text), encrypted: true };
372
+ }
373
+ }
272
374
  try {
273
375
  const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
274
376
  return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };