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

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 (51) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-AWKITPZQ.js → chunk-IWUGKLDX.js} +144 -33
  5. package/dist/index.js +1 -1
  6. package/package.json +1 -1
  7. package/src/__tests__/blob-upload.test.ts +93 -93
  8. package/src/__tests__/channel-e2ee.test.ts +62 -62
  9. package/src/__tests__/flota-jawnie.test.ts +244 -0
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +182 -182
  12. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  13. package/src/__tests__/mdm-mcp-readable.test.ts +390 -284
  14. package/src/__tests__/mirc-invite.test.ts +112 -112
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/server.test.ts +71 -71
  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/channel-e2ee.ts +288 -288
  22. package/src/crypto/mdm-session.ts +842 -798
  23. package/src/index.ts +19 -19
  24. package/src/observability/sentry.ts +79 -79
  25. package/src/providers/memory-voice.ts +79 -79
  26. package/src/providers/supabase-dm.ts +202 -174
  27. package/src/providers/supabase-voice.ts +91 -91
  28. package/src/server.ts +195 -186
  29. package/src/tools/actions.ts +166 -166
  30. package/src/tools/attachments.ts +276 -276
  31. package/src/tools/capabilities.ts +70 -70
  32. package/src/tools/channel-payload.ts +69 -0
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge.ts +344 -344
  36. package/src/tools/mail-aliases.ts +25 -25
  37. package/src/tools/mail-provenance.ts +137 -137
  38. package/src/tools/mail.ts +403 -403
  39. package/src/tools/mdm-as-agent.ts +126 -126
  40. package/src/tools/mdm.ts +140 -45
  41. package/src/tools/mirc-edge.ts +196 -196
  42. package/src/tools/mirc-members.ts +287 -287
  43. package/src/tools/mirc-messages.ts +9 -13
  44. package/src/tools/mirc.ts +308 -308
  45. package/src/tools/mroom-messages.ts +4 -12
  46. package/src/tools/mroom.ts +221 -221
  47. package/src/tools/mtalk.ts +131 -131
  48. package/src/tools/presence.ts +442 -442
  49. package/src/tools/voice-format.ts +28 -28
  50. package/src/types.ts +121 -121
  51. package/src/voice/floor.ts +132 -132
@@ -1,126 +1,126 @@
1
- /**
2
- * mDM agent-attributed send — a person's session speaks AS one of THEIR agents.
3
- *
4
- * ── THE PROBLEM THIS SOLVES ──────────────────────────────────────────────────
5
- * An MCP key is bound to a USER, and the hosted gateway exchanges it for THAT
6
- * user's session. So when someone adds the connector while signed in as
7
- * themselves, their agent runtime comes up holding the OWNER'S identity. The
8
- * founder hit exactly this on 2026-08-17: his "Dispatch" agent authenticated as
9
- * him, went looking for him among his own contacts, did not find him, and
10
- * reported the agent↔agent guard as the cause. The real cost was that his mDM
11
- * had no living 1:1 thread with his dispatcher.
12
- *
13
- * With this tool the same session can post AS `dispatcher@mosadd.com`, so the
14
- * DYSPOZYTOR thread fills with messages FROM the dispatcher.
15
- *
16
- * ── AUTHORIZATION ────────────────────────────────────────────────────────────
17
- * Enforced SERVER-SIDE by the `mdm-send-as-agent` Edge Function, never here:
18
- * the named identity must be `kind='agent'`, owned by the CALLER
19
- * (`owner_user_id`), and not retired. A client-side check would be decoration —
20
- * the tool arguments are attacker-controlled by definition.
21
- *
22
- * Shape follows the accepted `mAYL_send_as_agent` precedent (owner's credential
23
- * in, agent-attributed message out). Its AUTH model was deliberately not copied:
24
- * measured 2026-08-17, `hub-claim-mint` accepts any `agent_id` string and never
25
- * compares it to an owner, so the agent name in a mAYL provenance stamp is
26
- * caller-asserted text. That gap is filed as LINEAR-5625; this tool does not
27
- * reproduce it.
28
- *
29
- * Auth transport also differs on purpose: mAYL_send_as_agent reads
30
- * `process.env.MOSADD_API_KEY`, which does not exist on the hosted multi-tenant
31
- * gateway (the key is per-request there, not process-wide). This tool goes
32
- * through `invokeFunction`, i.e. the caller's own session — so it works
33
- * identically over stdio and over mcp.mosadd.com.
34
- *
35
- * Agent DMs travel as plaintext base64 on the established agent lane (the same
36
- * path agent-dm-responder uses); this tool does not change that property.
37
- * LINEAR-5620.
38
- */
39
-
40
- import { z } from "zod";
41
- import type { MosaddTool, MosaddToolContext } from "../types.js";
42
- import { invokeFunction } from "../providers/supabase.js";
43
-
44
- const mDM_send_as_agent_input = z.object({
45
- agent: z
46
- .string()
47
- .min(1)
48
- .max(200)
49
- .describe(
50
- "Which of YOUR agents to speak as — its mosADD address (dispatcher@mosadd.com), " +
51
- "its identity id, or its display name. Must be an agent you own.",
52
- ),
53
- text: z.string().min(1).max(8000).describe("The message body, as the agent would write it."),
54
- to: z
55
- .string()
56
- .max(200)
57
- .optional()
58
- .describe(
59
- "Recipient identity id or mosADD address. Defaults to YOU (the key's owner) — " +
60
- "the common case is an agent reporting to its owner. Must be a person, not another agent.",
61
- ),
62
- silent: z
63
- .boolean()
64
- .optional()
65
- .describe("Deliver without waking a phone: the message still arrives and shows unread, only the OS push is skipped."),
66
- });
67
-
68
- const mDM_list_my_agents_input = z.object({});
69
-
70
- type SendResult = {
71
- ok: boolean;
72
- sent_as: { identity_id: string; address: string | null; display_name: string | null };
73
- to: { identity_id: string; display_name: string | null };
74
- thread_id: string;
75
- };
76
-
77
- async function mDM_send_as_agent(
78
- input: z.infer<typeof mDM_send_as_agent_input>,
79
- ctx: MosaddToolContext,
80
- ): Promise<SendResult> {
81
- ctx.log("debug", "mDM_send_as_agent", { agent: input.agent });
82
- return await invokeFunction<SendResult>("mdm-send-as-agent", {
83
- agent: input.agent,
84
- text: input.text,
85
- ...(input.to ? { to: input.to } : {}),
86
- ...(input.silent ? { silent: true } : {}),
87
- });
88
- }
89
-
90
- async function mDM_list_my_agents(
91
- _input: z.infer<typeof mDM_list_my_agents_input>,
92
- ctx: MosaddToolContext,
93
- ): Promise<{ agents: Array<{ identity_id: string; address: string | null; display_name: string | null }> }> {
94
- ctx.log("debug", "mDM_list_my_agents");
95
- return await invokeFunction("mdm-send-as-agent", { action: "list_agents" });
96
- }
97
-
98
- export const mdmAsAgentTools: MosaddTool[] = [
99
- {
100
- name: "mDM_send_as_agent",
101
- title: "Send DM as your agent",
102
- annotations: { readOnlyHint: false },
103
- requires: "network",
104
- description:
105
- "Send a direct message AS ONE OF YOUR OWN AGENTS instead of as yourself. Use this when you are an " +
106
- "agent runtime (Dispatch, Hermes, a CTO agent) connected with your owner's key: without it every " +
107
- "message you send appears to come FROM the owner, so the owner has no thread with you. Names the " +
108
- "agent by mosADD address, identity id or display name; `to` defaults to the key's owner. The server " +
109
- "verifies you OWN that agent — speaking as someone else's agent, or as another person, is refused. " +
110
- "Recipient must be a person: agent-to-agent DM stays blocked.",
111
- inputSchema: mDM_send_as_agent_input,
112
- handler: mDM_send_as_agent as MosaddTool["handler"],
113
- },
114
- {
115
- name: "mDM_list_my_agents",
116
- title: "List your agents",
117
- annotations: { readOnlyHint: true },
118
- requires: "network",
119
- description:
120
- "List the agents you are allowed to speak as with mDM_send_as_agent — every live agent owned by " +
121
- "the account behind this key, with its identity id, mosADD address and display name. Call this " +
122
- "first when you are unsure which agent identity you hold.",
123
- inputSchema: mDM_list_my_agents_input,
124
- handler: mDM_list_my_agents as MosaddTool["handler"],
125
- },
126
- ];
1
+ /**
2
+ * mDM agent-attributed send — a person's session speaks AS one of THEIR agents.
3
+ *
4
+ * ── THE PROBLEM THIS SOLVES ──────────────────────────────────────────────────
5
+ * An MCP key is bound to a USER, and the hosted gateway exchanges it for THAT
6
+ * user's session. So when someone adds the connector while signed in as
7
+ * themselves, their agent runtime comes up holding the OWNER'S identity. The
8
+ * founder hit exactly this on 2026-08-17: his "Dispatch" agent authenticated as
9
+ * him, went looking for him among his own contacts, did not find him, and
10
+ * reported the agent↔agent guard as the cause. The real cost was that his mDM
11
+ * had no living 1:1 thread with his dispatcher.
12
+ *
13
+ * With this tool the same session can post AS `dispatcher@mosadd.com`, so the
14
+ * DYSPOZYTOR thread fills with messages FROM the dispatcher.
15
+ *
16
+ * ── AUTHORIZATION ────────────────────────────────────────────────────────────
17
+ * Enforced SERVER-SIDE by the `mdm-send-as-agent` Edge Function, never here:
18
+ * the named identity must be `kind='agent'`, owned by the CALLER
19
+ * (`owner_user_id`), and not retired. A client-side check would be decoration —
20
+ * the tool arguments are attacker-controlled by definition.
21
+ *
22
+ * Shape follows the accepted `mAYL_send_as_agent` precedent (owner's credential
23
+ * in, agent-attributed message out). Its AUTH model was deliberately not copied:
24
+ * measured 2026-08-17, `hub-claim-mint` accepts any `agent_id` string and never
25
+ * compares it to an owner, so the agent name in a mAYL provenance stamp is
26
+ * caller-asserted text. That gap is filed as LINEAR-5625; this tool does not
27
+ * reproduce it.
28
+ *
29
+ * Auth transport also differs on purpose: mAYL_send_as_agent reads
30
+ * `process.env.MOSADD_API_KEY`, which does not exist on the hosted multi-tenant
31
+ * gateway (the key is per-request there, not process-wide). This tool goes
32
+ * through `invokeFunction`, i.e. the caller's own session — so it works
33
+ * identically over stdio and over mcp.mosadd.com.
34
+ *
35
+ * Agent DMs travel as plaintext base64 on the established agent lane (the same
36
+ * path agent-dm-responder uses); this tool does not change that property.
37
+ * LINEAR-5620.
38
+ */
39
+
40
+ import { z } from "zod";
41
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
42
+ import { invokeFunction } from "../providers/supabase.js";
43
+
44
+ const mDM_send_as_agent_input = z.object({
45
+ agent: z
46
+ .string()
47
+ .min(1)
48
+ .max(200)
49
+ .describe(
50
+ "Which of YOUR agents to speak as — its mosADD address (dispatcher@mosadd.com), " +
51
+ "its identity id, or its display name. Must be an agent you own.",
52
+ ),
53
+ text: z.string().min(1).max(8000).describe("The message body, as the agent would write it."),
54
+ to: z
55
+ .string()
56
+ .max(200)
57
+ .optional()
58
+ .describe(
59
+ "Recipient identity id or mosADD address. Defaults to YOU (the key's owner) — " +
60
+ "the common case is an agent reporting to its owner. Must be a person, not another agent.",
61
+ ),
62
+ silent: z
63
+ .boolean()
64
+ .optional()
65
+ .describe("Deliver without waking a phone: the message still arrives and shows unread, only the OS push is skipped."),
66
+ });
67
+
68
+ const mDM_list_my_agents_input = z.object({});
69
+
70
+ type SendResult = {
71
+ ok: boolean;
72
+ sent_as: { identity_id: string; address: string | null; display_name: string | null };
73
+ to: { identity_id: string; display_name: string | null };
74
+ thread_id: string;
75
+ };
76
+
77
+ async function mDM_send_as_agent(
78
+ input: z.infer<typeof mDM_send_as_agent_input>,
79
+ ctx: MosaddToolContext,
80
+ ): Promise<SendResult> {
81
+ ctx.log("debug", "mDM_send_as_agent", { agent: input.agent });
82
+ return await invokeFunction<SendResult>("mdm-send-as-agent", {
83
+ agent: input.agent,
84
+ text: input.text,
85
+ ...(input.to ? { to: input.to } : {}),
86
+ ...(input.silent ? { silent: true } : {}),
87
+ });
88
+ }
89
+
90
+ async function mDM_list_my_agents(
91
+ _input: z.infer<typeof mDM_list_my_agents_input>,
92
+ ctx: MosaddToolContext,
93
+ ): Promise<{ agents: Array<{ identity_id: string; address: string | null; display_name: string | null }> }> {
94
+ ctx.log("debug", "mDM_list_my_agents");
95
+ return await invokeFunction("mdm-send-as-agent", { action: "list_agents" });
96
+ }
97
+
98
+ export const mdmAsAgentTools: MosaddTool[] = [
99
+ {
100
+ name: "mDM_send_as_agent",
101
+ title: "Send DM as your agent",
102
+ annotations: { readOnlyHint: false },
103
+ requires: "network",
104
+ description:
105
+ "Send a direct message AS ONE OF YOUR OWN AGENTS instead of as yourself. Use this when you are an " +
106
+ "agent runtime (Dispatch, Hermes, a CTO agent) connected with your owner's key: without it every " +
107
+ "message you send appears to come FROM the owner, so the owner has no thread with you. Names the " +
108
+ "agent by mosADD address, identity id or display name; `to` defaults to the key's owner. The server " +
109
+ "verifies you OWN that agent — speaking as someone else's agent, or as another person, is refused. " +
110
+ "Recipient must be a person: agent-to-agent DM stays blocked.",
111
+ inputSchema: mDM_send_as_agent_input,
112
+ handler: mDM_send_as_agent as MosaddTool["handler"],
113
+ },
114
+ {
115
+ name: "mDM_list_my_agents",
116
+ title: "List your agents",
117
+ annotations: { readOnlyHint: true },
118
+ requires: "network",
119
+ description:
120
+ "List the agents you are allowed to speak as with mDM_send_as_agent — every live agent owned by " +
121
+ "the account behind this key, with its identity id, mosADD address and display name. Call this " +
122
+ "first when you are unsure which agent identity you hold.",
123
+ inputSchema: mDM_list_my_agents_input,
124
+ handler: mDM_list_my_agents as MosaddTool["handler"],
125
+ },
126
+ ];
package/src/tools/mdm.ts CHANGED
@@ -21,9 +21,9 @@ import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supab
21
21
  import {
22
22
  encryptForPeer,
23
23
  decryptFromPeer,
24
- publishOwnPrekeys,
25
24
  isE2eeEnvelope,
26
25
  ensureOwnBundlePublished,
26
+ bundlePolicyForKind,
27
27
  fetchVerifiedBundle,
28
28
  sealForSelf,
29
29
  sealForPeerRecoverable,
@@ -32,7 +32,12 @@ import {
32
32
  type OwnBundleState,
33
33
  type PublicPrekeyBundle,
34
34
  } from "../crypto/mdm-session.js";
35
- import { MDM_TEXT_MESSAGE_TYPE, type DmSendArgsExt, type DmMessageExt } from "../providers/supabase-dm.js";
35
+ import {
36
+ MDM_TEXT_MESSAGE_TYPE,
37
+ MDM_MCP_SEALED_MESSAGE_TYPE,
38
+ type DmSendArgsExt,
39
+ type DmMessageExt,
40
+ } from "../providers/supabase-dm.js";
36
41
 
37
42
  // ---- Constants ----
38
43
 
@@ -154,58 +159,125 @@ async function selfKindOf(dm: MosaddToolContext["providers"]["dm"]): Promise<str
154
159
  return typeof f === "function" ? await f.call(dm) : null;
155
160
  }
156
161
 
157
- async function mDM_send(
158
- input: z.infer<typeof mDM_send_input>,
159
- ctx: MosaddToolContext,
160
- ): Promise<{
162
+ /** A peer's identity kind when the provider can tell (Supabase lane); null = unknown. */
163
+ async function peerKindOf(dm: MosaddToolContext["providers"]["dm"], peerId: string): Promise<string | null> {
164
+ const f = (dm as { peerKind?: (id: string) => Promise<string | null> }).peerKind;
165
+ if (typeof f !== "function") return null;
166
+ try {
167
+ return await f.call(dm, peerId);
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ type MdmSendResultOut = {
161
174
  message_id: string;
162
175
  delivered_at: string;
163
176
  thread_id: string;
164
- encrypted: true;
165
- /** the sender can read this message back on any process holding the same key (self_payload) */
177
+ encrypted: boolean;
178
+ /**
179
+ * "plaintext_agent_lane": an agent line is a party, so the DM goes in the clear (rozkaz Krola
180
+ * 20.09, same rule as the app's peerIsAgent). "e2ee": human to human, X3DH + Double Ratchet.
181
+ */
182
+ mode: "plaintext_agent_lane" | "e2ee";
183
+ /**
184
+ * WHY this mode (29.09, rozkaz Krola 28.09 „sciagnij szyfrowanie z naszych rozmow"):
185
+ * "fleet_plaintext" = an agent line is a party OR it is a note to self → always in the clear;
186
+ * "human_to_human" = two people, E2EE unchanged.
187
+ */
188
+ reason: "fleet_plaintext" | "human_to_human";
189
+ /** the sender can read this message back from ANY process / ANY key of the same identity */
166
190
  sender_copy: boolean;
167
- /** the recipient can open it without a ratchet session (recipient_self_payload) */
191
+ /** the recipient can read it without a ratchet session */
168
192
  recipient_copy: boolean;
169
- /** state of this identity in the key directory after the send */
170
- identity: OwnBundleState;
171
- }> {
172
- // E2EE path (default). The plaintext is packed into the inner mosadd.chat.v1
173
- // envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
174
- // DmProvider moves without understanding. First contact fetches the peer's
175
- // published prekey bundle through the same provider (decision "1a").
193
+ /** state of this identity in the key directory (E2EE only; the plaintext lane never touches it) */
194
+ identity: OwnBundleState | "untouched";
195
+ };
196
+
197
+ async function mDM_send(
198
+ input: z.infer<typeof mDM_send_input>,
199
+ ctx: MosaddToolContext,
200
+ ): Promise<MdmSendResultOut> {
176
201
  const dm = ctx.providers.dm;
177
202
  const selfId = await dm.selfId();
178
203
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
179
-
180
204
  const keys = ctx.providers.keys;
181
205
 
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.
206
+ // ⛔ POPRAWKA 27.09.2026 (niezalezna weryfikacja toru mdm-brama). The first fix seeded the mDM
207
+ // identity from ONE API key and let an agent line (re)publish it. An identity holds MANY keys
208
+ // (general@: 8 active), so the directory flapped between per-key identities and every copy
209
+ // sealed under the previous key stopped opening. The source answer is the King's rule, not a
210
+ // better key: an agent line NEVER uses E2EE (DECYZJE-KROLA 20.09 12:56Z: linie<->linie,
211
+ // linie<->Krol, czlowiek->linia: jawnie). Plaintext is readable by every key of the line and by
212
+ // the recipient's app on every device, and no bundle is needed, so nothing can flap.
213
+ //
214
+ // ⛔ 29.09.2026 (ZERO SZYFROWANIA, rozkaz Krola 28.09 „sciagnij te jebane szyfrowanie z naszych
215
+ // rozmow w kazdym kanale i w kazdej tozsamosci"): a note to SELF (to === selfId) goes in the
216
+ // clear too. MCP sessions on the King's key sealed his own thread (11 envelopes 21.09) and the
217
+ // server now refuses envelopes there (message-send `fleet_plaintext_only`). Kinds of BOTH sides
218
+ // are read from `identities.kind` before any sealing; only person↔person stays E2EE.
219
+ const selfKind = await selfKindOf(dm);
220
+ const noteToSelf = input.to === selfId;
221
+ const peerKind = selfKind === "agent" || noteToSelf ? selfKind : await peerKindOf(dm, input.to);
222
+ if (selfKind === "agent" || peerKind === "agent" || noteToSelf) {
223
+ const payload = packPlaintextPayload(input.text);
224
+ ctx.log("debug", "mDM_send fleet plaintext (rozkaz Krola 20.09 + 28.09)", {
225
+ thread_id: threadId,
226
+ self_kind: selfKind,
227
+ peer_kind: peerKind,
228
+ note_to_self: noteToSelf,
229
+ });
230
+ const plainArgs: DmSendArgsExt = {
231
+ to: input.to,
232
+ threadId,
233
+ payload,
234
+ replyToId: input.reply_to_id,
235
+ messageType: MDM_TEXT_MESSAGE_TYPE,
236
+ };
237
+ const result = await dm.send(plainArgs);
238
+ return {
239
+ message_id: result.id,
240
+ delivered_at: result.deliveredAt,
241
+ thread_id: threadId,
242
+ encrypted: false,
243
+ mode: "plaintext_agent_lane",
244
+ reason: "fleet_plaintext",
245
+ sender_copy: true,
246
+ recipient_copy: true,
247
+ identity: "untouched",
248
+ };
249
+ }
250
+
251
+ // E2EE path (human to human, or a lane that cannot tell kinds). The plaintext is packed into
252
+ // the inner envelope, then SEALED via X3DH + Double Ratchet into an opaque envelope the
253
+ // DmProvider moves without understanding. First contact fetches the peer's published prekey
254
+ // bundle through the same provider (decision "1a").
255
+ //
256
+ // On a PERSON's key MCP writes nothing to the key directory (bundlePolicyForKind: the app owns
257
+ // a human's bundle) and no "s1." self copy: the app opens only copies sealed under its own seed,
258
+ // and an unopenable "s1." makes it state a FALSE reason ("device"/"key") for the bubble. The
259
+ // envelope is typed `text` so the app states the true one: sent by MCP, no copy for this device.
188
260
  let identity: OwnBundleState = "foreign";
189
261
  try {
190
- identity = await ensureOwnBundlePublished(keys, dm, selfId, {
191
- mayReplaceForeign: (await selfKindOf(dm)) === "agent",
192
- });
262
+ identity = await ensureOwnBundlePublished(keys, dm, selfId, bundlePolicyForKind(selfKind, { explicit: false }));
193
263
  } catch (err) {
194
264
  // Directory unreachable: the ratchet envelope still carries its own handshake, so the send
195
265
  // proceeds; only the recipient copy is skipped (it would be sealed under an unverified identity).
196
266
  ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
197
267
  }
268
+ const ourIdentityIsPublished = identity === "consistent" || identity === "published";
198
269
 
199
- // reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w którą
200
- // można by go wpakować (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
270
+ // reply-linkage jedzie w dm.send({replyToId}) — surowy tekst nie ma koperty, w ktora
271
+ // mozna by go wpakowac (zmiana formatu 2026-08-25, patrz packPlaintextPayload).
201
272
  const inner = packPlaintextPayload(input.text);
202
273
  const sealed = await encryptForPeer(keys, dm, input.to, inner);
203
274
 
204
- const selfPayload = await sealForSelf(keys, inner);
275
+ // "s1." only where the reader of that copy is MCP itself: never on a human key (see above).
276
+ const selfPayload = selfKind !== "human" && ourIdentityIsPublished ? await sealForSelf(keys, inner) : null;
205
277
  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) {
278
+ // The recipient opens "r1." with OUR PUBLISHED identity, so it is written only when the
279
+ // directory holds exactly our key. A note-to-self needs none.
280
+ if (ourIdentityIsPublished && input.to !== selfId) {
209
281
  try {
210
282
  const peer = await fetchVerifiedBundle(dm, input.to);
211
283
  if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
@@ -227,7 +299,7 @@ async function mDM_send(
227
299
  threadId,
228
300
  payload: sealed,
229
301
  replyToId: input.reply_to_id,
230
- messageType: MDM_TEXT_MESSAGE_TYPE,
302
+ messageType: MDM_MCP_SEALED_MESSAGE_TYPE,
231
303
  selfPayload,
232
304
  recipientSelfPayload,
233
305
  };
@@ -245,6 +317,8 @@ async function mDM_send(
245
317
  delivered_at: result.deliveredAt,
246
318
  thread_id: threadId,
247
319
  encrypted: true,
320
+ mode: "e2ee",
321
+ reason: "human_to_human",
248
322
  sender_copy: !!selfPayload,
249
323
  recipient_copy: !!recipientSelfPayload,
250
324
  identity,
@@ -255,15 +329,14 @@ async function mDM_send_unencrypted(
255
329
  input: z.infer<typeof mDM_send_input>,
256
330
  ctx: MosaddToolContext,
257
331
  ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: false }> {
258
- // DEPRECATED migration path: plaintext mosadd.chat.v1 envelope, no E2EE.
259
- // Kept so peers who have not yet published prekeys can still be reached
260
- // during the migration window. Will be removed once E2EE is universal.
332
+ // Plaintext send, no E2EE. ⛔ 29.09.2026: NOT deprecated — this is THE path for every
333
+ // conversation with a fleet line and with the King (rozkaz Krola 28.09). Stays forever.
261
334
  const dm = ctx.providers.dm;
262
335
  const selfId = await dm.selfId();
263
336
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
264
337
  const payload = packPlaintextPayload(input.text);
265
338
 
266
- ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
339
+ ctx.log("debug", "mDM_send_unencrypted (plaintext) via DmProvider", {
267
340
  thread_id: threadId,
268
341
  bytes: payload.byteLength,
269
342
  });
@@ -288,12 +361,34 @@ async function mDM_send_unencrypted(
288
361
  async function mDM_publish_keys(
289
362
  _input: Record<string, never>,
290
363
  ctx: MosaddToolContext,
291
- ): Promise<{ published: true; one_time_prekeys: number }> {
364
+ ): Promise<{ published: boolean; identity: OwnBundleState; one_time_prekeys: number; note?: string }> {
292
365
  // Publish the local prekey bundle so peers can start encrypted sessions with
293
366
  // us. Rides the same provider as messages (network row / radio announce).
294
- const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
295
- ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
296
- return { published: true, one_time_prekeys: oneTimePrekeyCount };
367
+ //
368
+ // ⛔ 27.09.2026: never over a PERSON's app-anchored bundle. The MCP identity is seeded from the
369
+ // API key, the app's from the login secret; replacing the app's bundle breaks every DM to that
370
+ // person on every device (bundlePolicyForKind, explicit). An empty directory may be filled.
371
+ const dm = ctx.providers.dm;
372
+ const keys = ctx.providers.keys;
373
+ const selfId = await dm.selfId();
374
+ const identity = await ensureOwnBundlePublished(
375
+ keys,
376
+ dm,
377
+ selfId,
378
+ bundlePolicyForKind(await selfKindOf(dm), { explicit: true }),
379
+ );
380
+ const { oneTimePrekeys } = await keys.getOwnMaterial();
381
+ ctx.log("debug", "mDM_publish_keys", { identity, one_time_prekeys: oneTimePrekeys.length });
382
+ if (identity === "foreign") {
383
+ return {
384
+ published: false,
385
+ identity,
386
+ one_time_prekeys: 0,
387
+ note:
388
+ "This identity already has keys published by the mosADD app. They were left untouched: replacing them from an API key would make every conversation with you unreadable in the app.",
389
+ };
390
+ }
391
+ return { published: identity === "published", identity, one_time_prekeys: oneTimePrekeys.length };
297
392
  }
298
393
 
299
394
  async function mDM_list(
@@ -536,21 +631,21 @@ export const mdmTools: MosaddTool[] = [
536
631
  },
537
632
  {
538
633
  name: "mDM_send",
539
- title: "Send encrypted DM",
634
+ title: "Send DM",
540
635
  annotations: { readOnlyHint: false },
541
636
  requires: "any",
542
637
  description:
543
- "Send an END-TO-END-ENCRYPTED direct message via mosadd mDM. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread — mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
638
+ "Send a direct message via mosadd mDM. Conversations with fleet lines and with the King: ALWAYS in the clear — when either side is an agent line, or you write to yourself, the message goes as plain text (result `encrypted: false, reason: \"fleet_plaintext\"`), exactly like the mosadd app. Only between two PEOPLE is it END-TO-END-ENCRYPTED (X3DH + Double Ratchet; the recipient must have published keys). Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Optional thread_label puts the message in a named thread — mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram.",
544
639
  inputSchema: mDM_send_input,
545
640
  handler: mDM_send as MosaddTool["handler"],
546
641
  },
547
642
  {
548
643
  name: "mDM_send_unencrypted",
549
- title: "Send unencrypted DM",
644
+ title: "Send plain-text DM",
550
645
  annotations: { readOnlyHint: false },
551
646
  requires: "any",
552
647
  description:
553
- "DEPRECATED migration-window fallback: send a direct message WITHOUT end-to-end encryption (plaintext envelope). Only use when the recipient has not yet published prekeys (mDM_send fails with that hint). Prefer mDM_send. Will be removed once E2EE is universal.",
648
+ "Send a direct message as plain text, never encrypted. Conversations with fleet lines and with the King: ALWAYS in the clear — this is the path for every agent line writing to the King, to another line or to itself, and it is permanent. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts); optional thread_label puts it in a named thread. mDM_send picks the same plain-text path by itself whenever a fleet line is a party.",
554
649
  inputSchema: mDM_send_input,
555
650
  handler: mDM_send_unencrypted as MosaddTool["handler"],
556
651
  },