@mosadd/mcp 3.0.0-alpha.54 → 3.0.0-alpha.56

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.
@@ -1,162 +1,162 @@
1
- /**
2
- * Voice/file blob upload helper.
3
- *
4
- * The `message-send` contract carries voice/ptt/file bodies via an
5
- * `attachments[]` array of `{ kind, bucket, path, mime, duration_ms, key_ref }`
6
- * descriptors. The actual bytes must be uploaded to Supabase Storage FIRST; the
7
- * message row only references them by `{ bucket, path }`.
8
- *
9
- * This module centralises that upload so every channel's voice/file/ptt tool
10
- * (mDM, mIRC) produces an identical attachment descriptor.
11
- *
12
- * STATUS: scaffold. The Storage upload path below is real (supabase-js
13
- * `storage.from(bucket).upload`), but two things are TODO and gated on the
14
- * Lane A / CTO backend contract:
15
- * - DONE 2026-09-16: bucket names + write policy CONFIRMED against the live
16
- * project (see defaultBucket()/ownerFolder()). The old defaults
17
- * ('file-blobs', 'voice-blobs') did not exist in the project, so EVERY
18
- * file/voice send from MCP died with `Bucket not found` — reproduced on
19
- * mDM_send_file, mIRC_send_file and mDM_send_voice before the fix.
20
- * - TODO(Lane A): mDM voice is CLIENT-ENCRYPTED — the bytes must be sealed
21
- * (per-recipient, via @mosadd/crypto) before upload and `key_ref` must point
22
- * at the wrapped content key. Today this helper uploads the bytes as-is and
23
- * sets key_ref:null. Do NOT use for mDM voice until the seal step lands.
24
- */
25
-
26
- import { getSupabase, readSupabaseEnv } from "./supabase.js";
27
-
28
- export type AttachmentKind = "voice" | "file" | "ptt";
29
-
30
- /** The descriptor shape `message-send` expects inside `attachments[]`. */
31
- export interface AttachmentDescriptor {
32
- kind: AttachmentKind;
33
- bucket: string;
34
- path: string;
35
- mime: string;
36
- duration_ms?: number | null;
37
- /** Reference to the wrapped content-encryption key (E2EE channels only). */
38
- key_ref?: string | null;
39
- /** Original filename, for `kind:'file'`. */
40
- filename?: string | null;
41
- size_bytes?: number | null;
42
- }
43
-
44
- export interface UploadBlobArgs {
45
- kind: AttachmentKind;
46
- /** Raw bytes to upload. Caller is responsible for any E2EE sealing first. */
47
- bytes: Uint8Array;
48
- mime: string;
49
- /** Storage bucket. Defaults: voice/ptt → 'voice-blobs', file → 'file-blobs'. */
50
- bucket?: string;
51
- /** Sub-path prefix inside the bucket (e.g. the thread id). */
52
- prefix?: string;
53
- duration_ms?: number | null;
54
- filename?: string | null;
55
- /** Reference to the wrapped content key, when the caller pre-sealed the bytes. */
56
- key_ref?: string | null;
57
- }
58
-
59
- function defaultBucket(kind: AttachmentKind): string {
60
- // ⛔ TYLKO BUCKETY, KTÓRE ISTNIEJĄ I PRZYJMĄ TEN JWT (potwierdzone na żywym
61
- // projekcie rooffhgbxafyjcwmwpsy, 16.09):
62
- // chat-files → bucket istnieje (limit 100 MB). INSERT policy
63
- // "Users upload chat files": (storage.foldername(name))[1] = auth.uid()
64
- // SELECT policy dopuszcza też członka wątku: is_thread_member(auth.uid(), foldername[2])
65
- // voice-messages → bucket istnieje. INSERT policy
66
- // "Users can upload voice messages": foldername(name)[1] = auth.uid()
67
- // Poprzednie domyślne ('file-blobs' dla file, 'voice-blobs' dla voice/ptt) NIE
68
- // ISTNIEJĄ w projekcie — stąd "Bucket not found" na mDM_send_file, mIRC_send_file
69
- // i mDM_send_voice. Nazwy są tu jednym źródłem prawdy: gdy bucket zniknie,
70
- // zawodzi JAWNIE, a nie po cichu ląduje w innym miejscu.
71
- return kind === "file" ? "chat-files" : "voice-messages";
72
- }
73
-
74
- /** `sub` z JWT tej sesji, czyli `auth.uid()` — PIERWSZY segment ścieżki.
75
- *
76
- * ⛔ NIE OZDOBA I NIE OPCJA. Jedyny segment, który sprawdzają polityki INSERT obu
77
- * bucketów: `(storage.foldername(name))[1] = auth.uid()`. Ścieżka bez segmentu
78
- * użytkownika (`<thread>/<uuid>.ext`, jak było) przechodzi upload do momentu,
79
- * w którym baza odrzuca wiersz — czyli wysyłka pliku jest ZAWSZE martwa, i to
80
- * komunikatem, który nie mówi dlaczego. Ta sama konwencja co w aplikacji:
81
- * `apps/web/src/lib/ircApi.ts: uploadChatFile()` → `<user.id>/<thread>/<ts>_<nazwa>`.
82
- */
83
- function jwtSub(jwt: string): string | null {
84
- const part = jwt.split(".")[1];
85
- if (!part) return null;
86
- try {
87
- const json = JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
88
- return typeof json?.sub === "string" && json.sub ? json.sub : null;
89
- } catch {
90
- return null;
91
- }
92
- }
93
-
94
- function ownerFolder(userJwt: string | undefined): string {
95
- const sub = userJwt ? jwtSub(userJwt) : null;
96
- if (!sub) {
97
- throw new Error(
98
- "blob upload refused: no user id in the session JWT — bucket policy requires foldername[1] = auth.uid(); run `mosadd login` (or set MOSADD_USER_JWT) and retry",
99
- );
100
- }
101
- return sub;
102
- }
103
-
104
- function randomId(): string {
105
- // crypto.randomUUID is available on Node >=18 (package engines floor).
106
- return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
107
- }
108
-
109
- /**
110
- * Upload bytes to Supabase Storage and return the attachment descriptor to embed
111
- * in `message-send`'s `attachments[]`.
112
- */
113
- export async function uploadBlob(args: UploadBlobArgs): Promise<AttachmentDescriptor> {
114
- const env = readSupabaseEnv();
115
- const sb = getSupabase();
116
- const bucket = args.bucket ?? defaultBucket(args.kind);
117
- const ext = args.filename?.split(".").pop() ?? mimeExt(args.mime);
118
- // ⛔ KOLEJNOŚĆ SEGMENTÓW JEST CZĘŚCIĄ KONTRAKTU Z POLITYKĄ: <auth.uid()>/<wątek>/<uuid>.<ext>.
119
- const folder = args.prefix ? args.prefix.replace(/[^a-zA-Z0-9._/-]/g, "-").replace(/^\/+|\/+$/g, "") : "";
120
- const path = [ownerFolder(env.userJwt), folder, `${randomId()}${ext ? "." + ext : ""}`]
121
- .filter(Boolean).join("/");
122
-
123
- const { error } = await sb.storage.from(bucket).upload(path, args.bytes, {
124
- contentType: args.mime,
125
- upsert: false,
126
- });
127
- if (error) {
128
- throw new Error(`blob upload to ${bucket}/${path} failed: ${error.message}`);
129
- }
130
-
131
- return {
132
- kind: args.kind,
133
- bucket,
134
- path,
135
- mime: args.mime,
136
- duration_ms: args.duration_ms ?? null,
137
- key_ref: args.key_ref ?? null,
138
- filename: args.filename ?? null,
139
- size_bytes: args.bytes.byteLength,
140
- };
141
- }
142
-
143
- function mimeExt(mime: string): string {
144
- const map: Record<string, string> = {
145
- "audio/ogg": "ogg",
146
- "audio/mpeg": "mp3",
147
- "audio/mp4": "m4a",
148
- "audio/wav": "wav",
149
- "audio/webm": "webm",
150
- };
151
- return map[mime] ?? "";
152
- }
153
-
154
- /**
155
- * Decode a base64 / data-URL string into bytes. Agents hand us audio/file
156
- * content as base64 (MCP is JSON-only — no binary channel), so every voice/file
157
- * tool funnels through this.
158
- */
159
- export function decodeBase64Body(b64: string): Uint8Array {
160
- const cleaned = b64.includes(",") && b64.startsWith("data:") ? b64.slice(b64.indexOf(",") + 1) : b64;
161
- return new Uint8Array(Buffer.from(cleaned, "base64"));
162
- }
1
+ /**
2
+ * Voice/file blob upload helper.
3
+ *
4
+ * The `message-send` contract carries voice/ptt/file bodies via an
5
+ * `attachments[]` array of `{ kind, bucket, path, mime, duration_ms, key_ref }`
6
+ * descriptors. The actual bytes must be uploaded to Supabase Storage FIRST; the
7
+ * message row only references them by `{ bucket, path }`.
8
+ *
9
+ * This module centralises that upload so every channel's voice/file/ptt tool
10
+ * (mDM, mIRC) produces an identical attachment descriptor.
11
+ *
12
+ * STATUS: scaffold. The Storage upload path below is real (supabase-js
13
+ * `storage.from(bucket).upload`), but two things are TODO and gated on the
14
+ * Lane A / CTO backend contract:
15
+ * - DONE 2026-09-16: bucket names + write policy CONFIRMED against the live
16
+ * project (see defaultBucket()/ownerFolder()). The old defaults
17
+ * ('file-blobs', 'voice-blobs') did not exist in the project, so EVERY
18
+ * file/voice send from MCP died with `Bucket not found` — reproduced on
19
+ * mDM_send_file, mIRC_send_file and mDM_send_voice before the fix.
20
+ * - TODO(Lane A): mDM voice is CLIENT-ENCRYPTED — the bytes must be sealed
21
+ * (per-recipient, via @mosadd/crypto) before upload and `key_ref` must point
22
+ * at the wrapped content key. Today this helper uploads the bytes as-is and
23
+ * sets key_ref:null. Do NOT use for mDM voice until the seal step lands.
24
+ */
25
+
26
+ import { getSupabase, readSupabaseEnv } from "./supabase.js";
27
+
28
+ export type AttachmentKind = "voice" | "file" | "ptt";
29
+
30
+ /** The descriptor shape `message-send` expects inside `attachments[]`. */
31
+ export interface AttachmentDescriptor {
32
+ kind: AttachmentKind;
33
+ bucket: string;
34
+ path: string;
35
+ mime: string;
36
+ duration_ms?: number | null;
37
+ /** Reference to the wrapped content-encryption key (E2EE channels only). */
38
+ key_ref?: string | null;
39
+ /** Original filename, for `kind:'file'`. */
40
+ filename?: string | null;
41
+ size_bytes?: number | null;
42
+ }
43
+
44
+ export interface UploadBlobArgs {
45
+ kind: AttachmentKind;
46
+ /** Raw bytes to upload. Caller is responsible for any E2EE sealing first. */
47
+ bytes: Uint8Array;
48
+ mime: string;
49
+ /** Storage bucket. Defaults: voice/ptt → 'voice-blobs', file → 'file-blobs'. */
50
+ bucket?: string;
51
+ /** Sub-path prefix inside the bucket (e.g. the thread id). */
52
+ prefix?: string;
53
+ duration_ms?: number | null;
54
+ filename?: string | null;
55
+ /** Reference to the wrapped content key, when the caller pre-sealed the bytes. */
56
+ key_ref?: string | null;
57
+ }
58
+
59
+ function defaultBucket(kind: AttachmentKind): string {
60
+ // ⛔ TYLKO BUCKETY, KTÓRE ISTNIEJĄ I PRZYJMĄ TEN JWT (potwierdzone na żywym
61
+ // projekcie rooffhgbxafyjcwmwpsy, 16.09):
62
+ // chat-files → bucket istnieje (limit 100 MB). INSERT policy
63
+ // "Users upload chat files": (storage.foldername(name))[1] = auth.uid()
64
+ // SELECT policy dopuszcza też członka wątku: is_thread_member(auth.uid(), foldername[2])
65
+ // voice-messages → bucket istnieje. INSERT policy
66
+ // "Users can upload voice messages": foldername(name)[1] = auth.uid()
67
+ // Poprzednie domyślne ('file-blobs' dla file, 'voice-blobs' dla voice/ptt) NIE
68
+ // ISTNIEJĄ w projekcie — stąd "Bucket not found" na mDM_send_file, mIRC_send_file
69
+ // i mDM_send_voice. Nazwy są tu jednym źródłem prawdy: gdy bucket zniknie,
70
+ // zawodzi JAWNIE, a nie po cichu ląduje w innym miejscu.
71
+ return kind === "file" ? "chat-files" : "voice-messages";
72
+ }
73
+
74
+ /** `sub` z JWT tej sesji, czyli `auth.uid()` — PIERWSZY segment ścieżki.
75
+ *
76
+ * ⛔ NIE OZDOBA I NIE OPCJA. Jedyny segment, który sprawdzają polityki INSERT obu
77
+ * bucketów: `(storage.foldername(name))[1] = auth.uid()`. Ścieżka bez segmentu
78
+ * użytkownika (`<thread>/<uuid>.ext`, jak było) przechodzi upload do momentu,
79
+ * w którym baza odrzuca wiersz — czyli wysyłka pliku jest ZAWSZE martwa, i to
80
+ * komunikatem, który nie mówi dlaczego. Ta sama konwencja co w aplikacji:
81
+ * `apps/web/src/lib/ircApi.ts: uploadChatFile()` → `<user.id>/<thread>/<ts>_<nazwa>`.
82
+ */
83
+ function jwtSub(jwt: string): string | null {
84
+ const part = jwt.split(".")[1];
85
+ if (!part) return null;
86
+ try {
87
+ const json = JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
88
+ return typeof json?.sub === "string" && json.sub ? json.sub : null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ function ownerFolder(userJwt: string | undefined): string {
95
+ const sub = userJwt ? jwtSub(userJwt) : null;
96
+ if (!sub) {
97
+ throw new Error(
98
+ "blob upload refused: no user id in the session JWT — bucket policy requires foldername[1] = auth.uid(); run `mosadd login` (or set MOSADD_USER_JWT) and retry",
99
+ );
100
+ }
101
+ return sub;
102
+ }
103
+
104
+ function randomId(): string {
105
+ // crypto.randomUUID is available on Node >=18 (package engines floor).
106
+ return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
107
+ }
108
+
109
+ /**
110
+ * Upload bytes to Supabase Storage and return the attachment descriptor to embed
111
+ * in `message-send`'s `attachments[]`.
112
+ */
113
+ export async function uploadBlob(args: UploadBlobArgs): Promise<AttachmentDescriptor> {
114
+ const env = readSupabaseEnv();
115
+ const sb = getSupabase();
116
+ const bucket = args.bucket ?? defaultBucket(args.kind);
117
+ const ext = args.filename?.split(".").pop() ?? mimeExt(args.mime);
118
+ // ⛔ KOLEJNOŚĆ SEGMENTÓW JEST CZĘŚCIĄ KONTRAKTU Z POLITYKĄ: <auth.uid()>/<wątek>/<uuid>.<ext>.
119
+ const folder = args.prefix ? args.prefix.replace(/[^a-zA-Z0-9._/-]/g, "-").replace(/^\/+|\/+$/g, "") : "";
120
+ const path = [ownerFolder(env.userJwt), folder, `${randomId()}${ext ? "." + ext : ""}`]
121
+ .filter(Boolean).join("/");
122
+
123
+ const { error } = await sb.storage.from(bucket).upload(path, args.bytes, {
124
+ contentType: args.mime,
125
+ upsert: false,
126
+ });
127
+ if (error) {
128
+ throw new Error(`blob upload to ${bucket}/${path} failed: ${error.message}`);
129
+ }
130
+
131
+ return {
132
+ kind: args.kind,
133
+ bucket,
134
+ path,
135
+ mime: args.mime,
136
+ duration_ms: args.duration_ms ?? null,
137
+ key_ref: args.key_ref ?? null,
138
+ filename: args.filename ?? null,
139
+ size_bytes: args.bytes.byteLength,
140
+ };
141
+ }
142
+
143
+ function mimeExt(mime: string): string {
144
+ const map: Record<string, string> = {
145
+ "audio/ogg": "ogg",
146
+ "audio/mpeg": "mp3",
147
+ "audio/mp4": "m4a",
148
+ "audio/wav": "wav",
149
+ "audio/webm": "webm",
150
+ };
151
+ return map[mime] ?? "";
152
+ }
153
+
154
+ /**
155
+ * Decode a base64 / data-URL string into bytes. Agents hand us audio/file
156
+ * content as base64 (MCP is JSON-only — no binary channel), so every voice/file
157
+ * tool funnels through this.
158
+ */
159
+ export function decodeBase64Body(b64: string): Uint8Array {
160
+ const cleaned = b64.includes(",") && b64.startsWith("data:") ? b64.slice(b64.indexOf(",") + 1) : b64;
161
+ return new Uint8Array(Buffer.from(cleaned, "base64"));
162
+ }
package/src/server.ts CHANGED
@@ -98,7 +98,7 @@ export function createMosaddServer(options: MosaddServerOptions = {}) {
98
98
  // Human-facing identity of the server itself (initialize result). The icon URLs
99
99
  // point at the LIVE gateway origin on purpose: clients that honour serverInfo.icons
100
100
  // get the brand mark without scraping the favicon, and the files ship with
101
- // apps/mcp-http/public (canon 08-26 — generated by m0ssad-3 scripts/
101
+ // the gateway's public/ folder (canon 08-26 — generated by m0ssad-3 scripts/
102
102
  // generate-brand-icons.py, never hand-edited).
103
103
  title: "mosADD — omnichannel messenger for agents",
104
104
  websiteUrl: "https://mosadd.com",
@@ -0,0 +1,69 @@
1
+ /**
2
+ * channel-payload — stored channel/room payload (base64) → the text a reader should see.
3
+ *
4
+ * Plaintext for agent lines since 29.09 (owner decision 28.09: no encryption on agent-line conversations,
5
+ * in any channel or identity). #adm and #command are OPEN channels with no group key,
6
+ * yet every line reading them through this gateway saw the King's posts as "<ciphertext>". Nothing
7
+ * was encrypted: the app stores channel text as plain UTF-8 in base64 (apps/web ircApi.ts
8
+ * `encodePayload`), while the old decoder here understood ONLY a JSON `mosadd.chat.v1` envelope
9
+ * and stamped everything else "<ciphertext>". Measured 28.09–29.09 on #adm (f159c8d7, 776b3e9a).
10
+ *
11
+ * Rule now (same as mdm.ts `unpackPayload` and the mKEEPER bridge `decodePayload.mjs`):
12
+ * - JSON envelope with `text` → that text (toolkit posts, unchanged)
13
+ * - sealed envelope a reader cannot open:
14
+ * group-key seal {iv, ciphertext, hmac?} → "<ciphertext>"
15
+ * mDM ratchet envelope v: "mosadd.e2ee.*" → "<ciphertext>"
16
+ * - any other JSON (e.g. voice {audio, mime, dur}) → raw JSON, so `formatVoiceIfAny` can shape it
17
+ * - plain UTF-8 text → the text itself (what the app wrote)
18
+ * - bytes that are not UTF-8 / carry control characters → "<ciphertext>" (opaque, not words)
19
+ *
20
+ * Never throws.
21
+ */
22
+
23
+ export const CIPHERTEXT_MARKER = "<ciphertext>";
24
+
25
+ const STRICT_BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
26
+ // C0 controls except TAB / LF / CR, plus DEL: a "text" that carries them is bytes, not words.
27
+ // eslint-disable-next-line no-control-regex
28
+ const CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
29
+
30
+ /** A sealed envelope nobody without the key can read (group-key seal or mDM ratchet). */
31
+ export function isSealedEnvelope(obj: unknown): boolean {
32
+ if (!obj || typeof obj !== "object") return false;
33
+ const o = obj as Record<string, unknown>;
34
+ if (typeof o.iv === "string" && typeof o.ciphertext === "string") return true;
35
+ if (typeof o.v === "string" && o.v.startsWith("mosadd.e2ee")) return true;
36
+ return false;
37
+ }
38
+
39
+ /** Stored payload (base64 of UTF-8, as message-list returns it) → readable text. */
40
+ export function decodeStoredPayloadText(payload: string | null | undefined): string {
41
+ if (typeof payload !== "string" || payload.length === 0) return "";
42
+
43
+ let raw: string;
44
+ const compact = payload.replace(/\s+/g, "");
45
+ if (compact.length % 4 === 0 && STRICT_BASE64.test(compact)) {
46
+ try {
47
+ raw = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(compact, "base64"));
48
+ } catch {
49
+ return CIPHERTEXT_MARKER; // opaque bytes, not UTF-8
50
+ }
51
+ } else {
52
+ raw = payload; // a row stored as raw text, not base64
53
+ }
54
+
55
+ if (raw.startsWith("{")) {
56
+ try {
57
+ const obj = JSON.parse(raw) as unknown;
58
+ if (isSealedEnvelope(obj)) return CIPHERTEXT_MARKER;
59
+ const text = (obj as { text?: unknown } | null)?.text;
60
+ if (typeof text === "string") return text;
61
+ return raw;
62
+ } catch {
63
+ /* plain text that happens to start with "{" */
64
+ }
65
+ }
66
+
67
+ if (CONTROL_CHARS.test(raw)) return CIPHERTEXT_MARKER;
68
+ return raw;
69
+ }
@@ -12,7 +12,7 @@
12
12
  * never enters the browser. The action is owned by the calling user (user-JWT
13
13
  * scoped — `mosadd login` / MOSADD_USER_JWT / hub-key exchange).
14
14
  *
15
- * Reuses the shipped embed infra (apps/embed widget + embed-keys + mirc-embed-token).
15
+ * Reuses the shipped embed infra (the embed.mosadd.com widget + embed-keys + mirc-embed-token).
16
16
  * RFC 0001: channel-agnostic capability → `comms_` namespace (not an m<MODULE>_ prefix).
17
17
  */
18
18
 
@@ -10,7 +10,7 @@
10
10
  * reported the agent↔agent guard as the cause. The real cost was that his mDM
11
11
  * had no living 1:1 thread with his dispatcher.
12
12
  *
13
- * With this tool the same session can post AS `dispatcher@mosadd.com`, so the
13
+ * With this tool the same session can post AS one of the owner's agents (`<agent>@mosadd.com`), so the
14
14
  * DYSPOZYTOR thread fills with messages FROM the dispatcher.
15
15
  *
16
16
  * ── AUTHORIZATION ────────────────────────────────────────────────────────────
@@ -47,7 +47,7 @@ const mDM_send_as_agent_input = z.object({
47
47
  .min(1)
48
48
  .max(200)
49
49
  .describe(
50
- "Which of YOUR agents to speak as — its mosADD address (dispatcher@mosadd.com), " +
50
+ "Which of YOUR agents to speak as — its mosADD address (<agent>@mosadd.com), " +
51
51
  "its identity id, or its display name. Must be an agent you own.",
52
52
  ),
53
53
  text: z.string().min(1).max(8000).describe("The message body, as the agent would write it."),
@@ -59,6 +59,16 @@ const mDM_send_as_agent_input = z.object({
59
59
  "Recipient identity id or mosADD address. Defaults to YOU (the key's owner) — " +
60
60
  "the common case is an agent reporting to its owner. Must be a person, not another agent.",
61
61
  ),
62
+ thread_label: z
63
+ .string()
64
+ .min(1)
65
+ .max(120)
66
+ .regex(/^[a-zA-Z0-9._-]+$/)
67
+ .optional()
68
+ .describe(
69
+ "Optional thread label (same as mDM_send). Omit for the MAIN unlabeled thread — required for " +
70
+ "SOVEREIGN/King traffic until rename/UI merge (LINEAR-6577). A new label opens a new thread.",
71
+ ),
62
72
  silent: z
63
73
  .boolean()
64
74
  .optional()
@@ -78,11 +88,12 @@ async function mDM_send_as_agent(
78
88
  input: z.infer<typeof mDM_send_as_agent_input>,
79
89
  ctx: MosaddToolContext,
80
90
  ): Promise<SendResult> {
81
- ctx.log("debug", "mDM_send_as_agent", { agent: input.agent });
91
+ ctx.log("debug", "mDM_send_as_agent", { agent: input.agent, thread_label: input.thread_label });
82
92
  return await invokeFunction<SendResult>("mdm-send-as-agent", {
83
93
  agent: input.agent,
84
94
  text: input.text,
85
95
  ...(input.to ? { to: input.to } : {}),
96
+ ...(input.thread_label ? { thread_label: input.thread_label } : {}),
86
97
  ...(input.silent ? { silent: true } : {}),
87
98
  });
88
99
  }
@@ -105,9 +116,10 @@ export const mdmAsAgentTools: MosaddTool[] = [
105
116
  "Send a direct message AS ONE OF YOUR OWN AGENTS instead of as yourself. Use this when you are an " +
106
117
  "agent runtime (Dispatch, Hermes, a CTO agent) connected with your owner's key: without it every " +
107
118
  "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.",
119
+ "agent by mosADD address, identity id or display name; `to` defaults to the key's owner. Optional " +
120
+ "`thread_label` selects a named thread (omit = MAIN unlabeled — required for King/SOVEREIGN until " +
121
+ "rename lands). The server verifies you OWN that agent — speaking as someone else's agent, or as " +
122
+ "another person, is refused. Recipient must be a person: agent-to-agent DM stays blocked.",
111
123
  inputSchema: mDM_send_as_agent_input,
112
124
  handler: mDM_send_as_agent as MosaddTool["handler"],
113
125
  },
package/src/tools/mdm.ts CHANGED
@@ -180,6 +180,12 @@ type MdmSendResultOut = {
180
180
  * 20.09, same rule as the app's peerIsAgent). "e2ee": human to human, X3DH + Double Ratchet.
181
181
  */
182
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";
183
189
  /** the sender can read this message back from ANY process / ANY key of the same identity */
184
190
  sender_copy: boolean;
185
191
  /** the recipient can read it without a ratchet session */
@@ -204,14 +210,22 @@ async function mDM_send(
204
210
  // better key: an agent line NEVER uses E2EE (DECYZJE-KROLA 20.09 12:56Z: linie<->linie,
205
211
  // linie<->Krol, czlowiek->linia: jawnie). Plaintext is readable by every key of the line and by
206
212
  // the recipient's app on every device, and no bundle is needed, so nothing can flap.
213
+ //
214
+ // 29.09.2026 (owner decision 28.09: no encryption on agent-line conversations, in any channel or
215
+ // identity): 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.
207
219
  const selfKind = await selfKindOf(dm);
208
- const peerKind = selfKind === "agent" || input.to === selfId ? selfKind : await peerKindOf(dm, input.to);
209
- if (selfKind === "agent" || peerKind === "agent") {
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) {
210
223
  const payload = packPlaintextPayload(input.text);
211
- ctx.log("debug", "mDM_send plaintext agent lane (rozkaz Krola 20.09)", {
224
+ ctx.log("debug", "mDM_send agent-line plaintext (owner decisions 20.09 + 28.09)", {
212
225
  thread_id: threadId,
213
226
  self_kind: selfKind,
214
227
  peer_kind: peerKind,
228
+ note_to_self: noteToSelf,
215
229
  });
216
230
  const plainArgs: DmSendArgsExt = {
217
231
  to: input.to,
@@ -227,6 +241,7 @@ async function mDM_send(
227
241
  thread_id: threadId,
228
242
  encrypted: false,
229
243
  mode: "plaintext_agent_lane",
244
+ reason: "fleet_plaintext",
230
245
  sender_copy: true,
231
246
  recipient_copy: true,
232
247
  identity: "untouched",
@@ -303,6 +318,7 @@ async function mDM_send(
303
318
  thread_id: threadId,
304
319
  encrypted: true,
305
320
  mode: "e2ee",
321
+ reason: "human_to_human",
306
322
  sender_copy: !!selfPayload,
307
323
  recipient_copy: !!recipientSelfPayload,
308
324
  identity,
@@ -313,15 +329,14 @@ async function mDM_send_unencrypted(
313
329
  input: z.infer<typeof mDM_send_input>,
314
330
  ctx: MosaddToolContext,
315
331
  ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: false }> {
316
- // DEPRECATED migration path: plaintext mosadd.chat.v1 envelope, no E2EE.
317
- // Kept so peers who have not yet published prekeys can still be reached
318
- // 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.
319
334
  const dm = ctx.providers.dm;
320
335
  const selfId = await dm.selfId();
321
336
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
322
337
  const payload = packPlaintextPayload(input.text);
323
338
 
324
- ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
339
+ ctx.log("debug", "mDM_send_unencrypted (plaintext) via DmProvider", {
325
340
  thread_id: threadId,
326
341
  bytes: payload.byteLength,
327
342
  });
@@ -616,21 +631,21 @@ export const mdmTools: MosaddTool[] = [
616
631
  },
617
632
  {
618
633
  name: "mDM_send",
619
- title: "Send encrypted DM",
634
+ title: "Send DM",
620
635
  annotations: { readOnlyHint: false },
621
636
  requires: "any",
622
637
  description:
623
- "Send a direct message via mosadd mDM. Between two PEOPLE it is END-TO-END-ENCRYPTED; when either side is an agent line it goes in the clear (mosadd rule: agents must read their DMs), exactly like the mosadd app. 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.",
624
639
  inputSchema: mDM_send_input,
625
640
  handler: mDM_send as MosaddTool["handler"],
626
641
  },
627
642
  {
628
643
  name: "mDM_send_unencrypted",
629
- title: "Send unencrypted DM",
644
+ title: "Send plain-text DM",
630
645
  annotations: { readOnlyHint: false },
631
646
  requires: "any",
632
647
  description:
633
- "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.",
634
649
  inputSchema: mDM_send_input,
635
650
  handler: mDM_send_unencrypted as MosaddTool["handler"],
636
651
  },
@@ -22,7 +22,7 @@
22
22
  * - RECOMMENDED (LINEAR-2675/E6): server calls `mIRC_mint_channel_token` to
23
23
  * exchange the hub key for a 5-min channel-scoped JWT, then the browser
24
24
  * opens the WS with `Sec-WebSocket-Protocol: mosadd.v1, bearer.<jwt>`.
25
- * The hub key never leaves the server. Recipe: `apps/edge/README.md`.
25
+ * The hub key never leaves the server. (The edge Worker is part of the hosted service since 2026-09-29.)
26
26
  */
27
27
 
28
28
  import { z } from "zod";