@mosadd/mcp 3.0.0 → 3.0.2

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 (40) hide show
  1. package/CHANGELOG.md +420 -410
  2. package/LICENSE +21 -0
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-VMMJJYXF.js → chunk-I3FSPQ4G.js} +78 -30
  5. package/dist/index.d.ts +6 -6
  6. package/dist/index.js +1 -1
  7. package/package.json +1 -1
  8. package/src/__tests__/blob-upload.test.ts +1 -1
  9. package/src/__tests__/{flota-jawnie.test.ts → fleet-plaintext.test.ts} +59 -60
  10. package/src/__tests__/integration.test.ts +1 -1
  11. package/src/__tests__/mdm-e2ee.test.ts +3 -3
  12. package/src/__tests__/mdm-mcp-readable.test.ts +95 -95
  13. package/src/__tests__/mirc-files.test.ts +80 -0
  14. package/src/__tests__/mirc-invite.test.ts +1 -1
  15. package/src/__tests__/mirc-voice.test.ts +82 -0
  16. package/src/__tests__/mrag-search-diagnostics.test.ts +78 -0
  17. package/src/__tests__/presence.test.ts +2 -2
  18. package/src/__tests__/server.test.ts +3 -3
  19. package/src/__tests__/tool-count-consistency.test.ts +4 -4
  20. package/src/crypto/channel-e2ee.ts +1 -1
  21. package/src/crypto/mdm-session.ts +14 -14
  22. package/src/providers/supabase-dm.ts +6 -1
  23. package/src/providers/supabase.ts +8 -8
  24. package/src/server.ts +4 -4
  25. package/src/tools/channel-payload.ts +3 -3
  26. package/src/tools/index.ts +13 -13
  27. package/src/tools/knowledge.ts +384 -351
  28. package/src/tools/mail-aliases.ts +1 -1
  29. package/src/tools/mail-provenance.ts +1 -1
  30. package/src/tools/mdm-as-agent.ts +3 -4
  31. package/src/tools/mdm.ts +19 -14
  32. package/src/tools/mirc-edge.ts +4 -4
  33. package/src/tools/mirc-members.ts +1 -1
  34. package/src/tools/mirc-messages.ts +41 -12
  35. package/src/tools/mirc.ts +1 -1
  36. package/src/tools/mroom-messages.ts +1 -1
  37. package/src/tools/presence.ts +10 -10
  38. package/src/tools/ptt-ingest.ts +1 -1
  39. package/src/tools/threat.ts +1 -1
  40. package/src/tools/voice-format.ts +53 -7
@@ -2,7 +2,7 @@
2
2
  // mail-aliases.ts — back-compat mp0st_* aliases for mAYL_* tools
3
3
  // =============================================================================
4
4
  // The mosADD re-arch (2026-06-27) renamed the email module from `mp0st` to
5
- // `mAYL` (LINEAR-3938 / 3985). The canonical tool names are mAYL_* — see
5
+ // `mAYL`. The canonical tool names are mAYL_* — see
6
6
  // `tools/mail.ts`. THIS module exposes back-compat aliases so any agent already
7
7
  // wired to mp0st_send / mp0st_view / etc. KEEPS WORKING in this release.
8
8
  //
@@ -65,7 +65,7 @@ const mp0st_send_as_agent_input = z.object({
65
65
  * Exchange the hub key for an HS256 hub-claim JWT that authorizes agent-attributed
66
66
  * mail sends. The `mp0st-send` EF verifies this token with HUB_JWT_SECRET and reads
67
67
  * `agent_id` + `task_id` from its claims authoritatively (body fields are NOT trusted
68
- * for provenance). LINEAR-3991.
68
+ * for provenance).
69
69
  */
70
70
  async function mintHubClaim(agentId: string, taskId?: string): Promise<string> {
71
71
  const key = hubKey();
@@ -23,7 +23,7 @@
23
23
  * in, agent-attributed message out). Its AUTH model was deliberately not copied:
24
24
  * measured 2026-08-17, `hub-claim-mint` accepts any `agent_id` string and never
25
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
26
+ * caller-asserted text. That gap is tracked separately; this tool does not
27
27
  * reproduce it.
28
28
  *
29
29
  * Auth transport also differs on purpose: mAYL_send_as_agent reads
@@ -34,7 +34,6 @@
34
34
  *
35
35
  * Agent DMs travel as plaintext base64 on the established agent lane (the same
36
36
  * path agent-dm-responder uses); this tool does not change that property.
37
- * LINEAR-5620.
38
37
  */
39
38
 
40
39
  import { z } from "zod";
@@ -67,7 +66,7 @@ const mDM_send_as_agent_input = z.object({
67
66
  .optional()
68
67
  .describe(
69
68
  "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.",
69
+ "account-owner traffic. A new label opens a new thread.",
71
70
  ),
72
71
  silent: z
73
72
  .boolean()
@@ -117,7 +116,7 @@ export const mdmAsAgentTools: MosaddTool[] = [
117
116
  "agent runtime (Dispatch, Hermes, a CTO agent) connected with your owner's key: without it every " +
118
117
  "message you send appears to come FROM the owner, so the owner has no thread with you. Names the " +
119
118
  "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 " +
119
+ "`thread_label` selects a named thread (omit = MAIN unlabeled — required for the account owner until " +
121
120
  "rename lands). The server verifies you OWN that agent — speaking as someone else's agent, or as " +
122
121
  "another person, is refused. Recipient must be a person: agent-to-agent DM stays blocked.",
123
122
  inputSchema: mDM_send_as_agent_input,
package/src/tools/mdm.ts CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { z } from "zod";
18
18
  import type { MosaddTool, MosaddToolContext } from "../types.js";
19
- import { formatVoiceIfAny, voiceFields } from "./voice-format.js";
19
+ import { formatVoiceIfAny, voiceFields, voiceText, type MessageAttachment } from "./voice-format.js";
20
20
  import { invokeFunction, getSupabase, readSupabaseEnv } from "../providers/supabase.js";
21
21
  import {
22
22
  encryptForPeer,
@@ -176,12 +176,12 @@ type MdmSendResultOut = {
176
176
  thread_id: string;
177
177
  encrypted: boolean;
178
178
  /**
179
- * "plaintext_agent_lane": an agent line is a party, so the DM goes in the clear (rozkaz Krola
179
+ * "plaintext_agent_lane": an agent line is a party, so the DM goes in the clear (owner decision
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
183
  /**
184
- * WHY this mode (29.09, rozkaz Krola 28.09 „sciagnij szyfrowanie z naszych rozmow"):
184
+ * WHY this mode (29.09, owner decision 28.09: no encryption on agent-line conversations):
185
185
  * "fleet_plaintext" = an agent line is a party OR it is a note to self → always in the clear;
186
186
  * "human_to_human" = two people, E2EE unchanged.
187
187
  */
@@ -203,17 +203,17 @@ async function mDM_send(
203
203
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
204
204
  const keys = ctx.providers.keys;
205
205
 
206
- // ⛔ POPRAWKA 27.09.2026 (niezalezna weryfikacja toru mdm-brama). The first fix seeded the mDM
206
+ // ⛔ FIX 27.09.2026 (after independent verification of the mDM gateway path). The first fix seeded the mDM
207
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
208
+ // (one agent identity: 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 owner's rule, not a
210
+ // better key: an agent line NEVER uses E2EE (owner decision 20.09: line<->line,
211
+ // line<->owner and person->line are all in the clear). Plaintext is readable by every key of the line and by
212
212
  // the recipient's app on every device, and no bundle is needed, so nothing can flap.
213
213
  //
214
214
  // 29.09.2026 (owner decision 28.09: no encryption on agent-line conversations, in any channel or
215
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
216
+ // clear too. MCP sessions on the owner's key sealed the owner's own thread (11 envelopes 21.09) and the
217
217
  // server now refuses envelopes there (message-send `fleet_plaintext_only`). Kinds of BOTH sides
218
218
  // are read from `identities.kind` before any sealing; only person↔person stays E2EE.
219
219
  const selfKind = await selfKindOf(dm);
@@ -330,7 +330,7 @@ async function mDM_send_unencrypted(
330
330
  ctx: MosaddToolContext,
331
331
  ): Promise<{ message_id: string; delivered_at: string; thread_id: string; encrypted: false }> {
332
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.
333
+ // conversation with a fleet line and with the account owner (owner decision 28.09). Stays forever.
334
334
  const dm = ctx.providers.dm;
335
335
  const selfId = await dm.selfId();
336
336
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
@@ -403,6 +403,7 @@ async function mDM_list(
403
403
  thread_id: string;
404
404
  encrypted: boolean;
405
405
  voice?: { transcript: string | null; audio_url: string | null; duration_ms: number | null };
406
+ attachments?: MessageAttachment[];
406
407
  }>;
407
408
  next_cursor: string | null;
408
409
  threads: string[];
@@ -427,7 +428,7 @@ async function mDM_list(
427
428
  return p;
428
429
  };
429
430
 
430
- const messages = await Promise.all(
431
+ const surowe = await Promise.all(
431
432
  result.messages.map(async (raw) => {
432
433
  const m = raw as DmMessageExt;
433
434
  const base = {
@@ -436,6 +437,8 @@ async function mDM_list(
436
437
  timestamp: m.timestamp,
437
438
  thread_id: m.threadId,
438
439
  ...voiceFields(m),
440
+ // 30.11: pliki (zrzut, dokument) z podpisanym adresem ~1 h — prawa czytającego (strona rozmowy)
441
+ ...(m.files?.length ? { attachments: m.files } : {}),
439
442
  };
440
443
  // Legacy plaintext envelope (deprecated path) — unpack directly.
441
444
  if (!isE2eeEnvelope(m.payload)) {
@@ -477,6 +480,8 @@ async function mDM_list(
477
480
  }
478
481
  }),
479
482
  );
483
+ // 30.11.2026: druga strona mDM ma USŁYSZEĆ głosówkę — `text` = „[voice note — Ns] <transkrypcja>” (voice-format.ts).
484
+ const messages = surowe.map((m) => (m.voice ? { ...m, text: voiceText(m.text, m.voice) } : m));
480
485
 
481
486
  return {
482
487
  messages,
@@ -637,7 +642,7 @@ export const mdmTools: MosaddTool[] = [
637
642
  annotations: { readOnlyHint: false },
638
643
  requires: "any",
639
644
  description:
640
- "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.",
645
+ "Send a direct message via mosadd mDM. Conversations with agent lines and with the account owner: 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.",
641
646
  inputSchema: mDM_send_input,
642
647
  handler: mDM_send as MosaddTool["handler"],
643
648
  },
@@ -647,7 +652,7 @@ export const mdmTools: MosaddTool[] = [
647
652
  annotations: { readOnlyHint: false },
648
653
  requires: "any",
649
654
  description:
650
- "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.",
655
+ "Send a direct message as plain text, never encrypted. Conversations with agent lines and with the account owner: ALWAYS in the clear — this is the path for every agent line writing to the account owner, 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.",
651
656
  inputSchema: mDM_send_input,
652
657
  handler: mDM_send_unencrypted as MosaddTool["handler"],
653
658
  },
@@ -657,7 +662,7 @@ export const mdmTools: MosaddTool[] = [
657
662
  annotations: { readOnlyHint: true },
658
663
  requires: "any",
659
664
  description:
660
- "List recent direct messages with a specific contact. Pass contact_id as the identity_id from mDM_list_contacts. Decrypts end-to-end-encrypted messages from the contact automatically; legacy plaintext messages are shown as-is. Optionally filter to a single thread_label.",
665
+ "List recent direct messages with a specific contact. Pass contact_id as the identity_id from mDM_list_contacts. Decrypts end-to-end-encrypted messages from the contact automatically; legacy plaintext messages are shown as-is. Optionally filter to a single thread_label. FILES: a screenshot or document in the conversation comes back in `attachments: [{name, mime, size, url}]` — `url` is a signed link valid for about an hour, fetch it to see the file; an encrypted file has `encrypted: true` and no url. VOICE: a voice message has `voice: {transcript, audio_url, duration_ms}` and `text` reads \"[voice note — 25s] <transcript>\".",
661
666
  inputSchema: mDM_list_input,
662
667
  handler: mDM_list as MosaddTool["handler"],
663
668
  },
@@ -1,5 +1,5 @@
1
1
  /**
2
- * mIRC edge — Cloudflare Worker + Durable Object backend (LINEAR-2675/2680).
2
+ * mIRC edge — Cloudflare Worker + Durable Object backend.
3
3
  *
4
4
  * Parallel to mirc-messages.ts (Supabase path). These tools talk directly to
5
5
  * the mosadd-edge Worker → ChannelDO via REST. Use them when you want:
@@ -19,7 +19,7 @@
19
19
  *
20
20
  * - DEPRECATED, server-side only: `wss://${EDGE}/c/${channelId}/ws?k=<hub_key>`.
21
21
  * Don't use from a browser — `?k=` lands in CF access logs.
22
- * - RECOMMENDED (LINEAR-2675/E6): server calls `mIRC_mint_channel_token` to
22
+ * - RECOMMENDED: 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
25
  * The hub key never leaves the server. (The edge Worker is part of the hosted service since 2026-09-29.)
@@ -116,7 +116,7 @@ async function mIRC_history_edge(
116
116
  };
117
117
  }
118
118
 
119
- // ── mint_channel_token (LINEAR-2675/E6) ─────────────────────────────────────
119
+ // ── mint_channel_token ─────────────────────────────────────────────────────
120
120
  //
121
121
  // Server-side helper: exchange the long-lived hub key for a short-lived,
122
122
  // channel-scoped JWT that's safe to ship to a browser. The Worker validates
@@ -169,7 +169,7 @@ export const mircEdgeTools: MosaddTool[] = [
169
169
  annotations: { readOnlyHint: false },
170
170
  requires: "network",
171
171
  description:
172
- "Exchange the hub key (MOSADD_API_KEY) for a short-lived (5min), channel-scoped JWT. Returns { token, expires_in, channel_id, scope }. The token is safe to hand to a browser to open a WS via `Sec-WebSocket-Protocol: mosadd.v1, bearer.<token>`. The hub key NEVER leaves the server. Use this from any server-side route (Next.js /api/chat-token, Express, etc.) before showing chat in a browser. Required by LINEAR-2675/E6 to avoid leaking the hub key into CDN access logs.",
172
+ "Exchange the hub key (MOSADD_API_KEY) for a short-lived (5min), channel-scoped JWT. Returns { token, expires_in, channel_id, scope }. The token is safe to hand to a browser to open a WS via `Sec-WebSocket-Protocol: mosadd.v1, bearer.<token>`. The hub key NEVER leaves the server. Use this from any server-side route (Next.js /api/chat-token, Express, etc.) before showing chat in a browser. Required to avoid leaking the hub key into CDN access logs.",
173
173
  inputSchema: mIRC_mint_channel_token_input,
174
174
  handler: mIRC_mint_channel_token as MosaddTool["handler"],
175
175
  },
@@ -44,7 +44,7 @@ const mIRC_request_access_input = z.object({
44
44
  // Wraps channel-members-manage `invite`, which forks on WHO the target is:
45
45
  // · an agent/robot the CALLER OWNS → membership is written NOW — channel_members + the linked
46
46
  // space_members row (+ a channel_keys row when wrapped_group_key is given) — and the reply is
47
- // { auto_joined: true, member }. No code, nothing to redeem (LINEAR-5596: a code minted for
47
+ // { auto_joined: true, member }. No code, nothing to redeem (a code minted for
48
48
  // your own agent is a dead letter — it has no keyboard to paste it into);
49
49
  // · a human, or an agent owned by somebody ELSE → the reply is { invite: { code, … } }: an
50
50
  // invite code (kod zaproszenia) the recipient redeems in the app ("+ → I have an invite code").
@@ -11,7 +11,7 @@
11
11
  import { z } from "zod";
12
12
  import type { MosaddTool, MosaddToolContext } from "../types.js";
13
13
  import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
- import { formatVoiceIfAny } from "./voice-format.js";
14
+ import { attachmentsFrom, formatVoiceIfAny, voiceFields, voiceText, type MessageAttachment } from "./voice-format.js";
15
15
  import { decryptChannelPayload, encryptChannelPayload, unwrapEnvelopeText } from "../crypto/channel-e2ee.js";
16
16
  import { decodeStoredPayloadText } from "./channel-payload.js";
17
17
 
@@ -51,7 +51,7 @@ const mIRC_list_messages_input = z.object({
51
51
 
52
52
  // Channel messages on password/private channels are group-key encrypted when the
53
53
  // line holds the channel's group key (channel_keys row wrapped to the line's
54
- // identity — F4/LINEAR-5934). Open channels have no key → the legacy server-readable
54
+ // identity — F4). Open channels have no key → the legacy server-readable
55
55
  // envelope below. The envelope JSON is the PLAINTEXT inside the group-key seal, so
56
56
  // the app unwraps toolkit posts into the same bubble shape as before.
57
57
  function buildPlaintextEnvelope(text: string, replyToId?: string): string {
@@ -67,8 +67,8 @@ function buildPlaintextEnvelope(text: string, replyToId?: string): string {
67
67
 
68
68
  /**
69
69
  * Stored payload → readable text. Group-key decrypt first; then the plain decode, which reads BOTH
70
- * the toolkit's JSON envelope AND the app's raw UTF-8 text (29.09: the King's posts on the open
71
- * #adm/#command used to come back as "<ciphertext>"). "<ciphertext>" is left only for a sealed
70
+ * the toolkit's JSON envelope AND the app's raw UTF-8 text (29.09: the owner's posts on the open
71
+ * ops channels used to come back as "<ciphertext>"). "<ciphertext>" is left only for a sealed
72
72
  * envelope this line holds no key for (channel-payload.ts).
73
73
  */
74
74
  async function payloadToText(channelId: string, payload: string): Promise<string> {
@@ -135,20 +135,39 @@ async function mIRC_post_message(
135
135
  };
136
136
  }
137
137
 
138
+ type MircListedMessage = {
139
+ id: string;
140
+ sender_identity_id: string;
141
+ text: string;
142
+ timestamp: string;
143
+ voice?: { transcript: string | null; audio_url: string | null; duration_ms: number | null };
144
+ attachments?: MessageAttachment[];
145
+ };
146
+
138
147
  async function mIRC_list_messages(
139
148
  input: z.infer<typeof mIRC_list_messages_input>,
140
149
  ctx: MosaddToolContext,
141
- ): Promise<{
142
- messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }>;
143
- next_cursor: string | null;
144
- }> {
150
+ ): Promise<{ messages: MircListedMessage[]; next_cursor: string | null }> {
145
151
  readSupabaseEnv();
146
152
  const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
147
153
  const thread_id = `chat:${input.channel_id}`;
148
154
  ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
149
155
 
156
+ // 30.11.2026: message-list (mosADD) dokłada do voice/ptt transcript / audio_url / duration_ms uprawnieniami czytającego
157
+ // (RLS: członek kanału). Do dziś ten kanał je wyrzucał — agent w kanale widział „[voice note — 25s]” i nie słyszał
158
+ // PTT, choć mDM_list ma te pola od 15.11.
150
159
  type MessageListResponse = {
151
- messages?: Array<{ id: string; sender_identity_id: string; encrypted_payload: string; created_at: string }>;
160
+ messages?: Array<{
161
+ id: string;
162
+ sender_identity_id: string;
163
+ encrypted_payload: string;
164
+ created_at: string;
165
+ message_type?: string | null;
166
+ transcript?: string | null;
167
+ audio_url?: string | null;
168
+ duration_ms?: number | null;
169
+ files?: unknown;
170
+ }>;
152
171
  next_before?: string | null;
153
172
  cursor?: string | null;
154
173
  };
@@ -161,13 +180,23 @@ async function mIRC_list_messages(
161
180
  before: input.cursor,
162
181
  });
163
182
 
164
- const messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }> = [];
183
+ const messages: MircListedMessage[] = [];
165
184
  for (const m of data?.messages ?? []) {
185
+ const glos = voiceFields({
186
+ messageType: m.message_type ?? undefined,
187
+ transcript: m.transcript ?? null,
188
+ audioUrl: m.audio_url ?? null,
189
+ durationMs: m.duration_ms ?? null,
190
+ });
191
+ const pliki = attachmentsFrom(m.files);
166
192
  messages.push({
167
193
  id: m.id,
168
194
  sender_identity_id: m.sender_identity_id,
169
- text: formatVoiceIfAny(await payloadToText(input.channel_id, m.encrypted_payload)),
195
+ text: voiceText(formatVoiceIfAny(await payloadToText(input.channel_id, m.encrypted_payload)), glos.voice),
170
196
  timestamp: m.created_at,
197
+ ...glos,
198
+ // 30.11: zrzut / plik przy wiadomości — podpisany adres ~1 h z message-list, prawa czytającego (członek kanału)
199
+ ...(pliki ? { attachments: pliki } : {}),
171
200
  });
172
201
  }
173
202
 
@@ -194,7 +223,7 @@ export const mircMessagesTools: MosaddTool[] = [
194
223
  annotations: { readOnlyHint: true },
195
224
  requires: "network",
196
225
  description:
197
- "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically. ENCRYPTION: messages your line can decrypt (group-key channels — auto-provisioned key material) come back as readable text; everything else is decoded as written: the app's plain text and the toolkit's JSON envelope both come back as readable text (open channels such as #adm and #command are never encrypted). Only a sealed group-key envelope your line holds no key for reads <ciphertext>.",
226
+ "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically. ENCRYPTION: messages your line can decrypt (group-key channels — auto-provisioned key material) come back as readable text; everything else is decoded as written: the app's plain text and the toolkit's JSON envelope both come back as readable text (open channels such as coordination channels are never encrypted). Only a sealed group-key envelope your line holds no key for reads <ciphertext>. FILES: a screenshot or document sent with a message comes back in `attachments: [{name, mime, size, url}]` — `url` is a signed link valid for about an hour, fetch it to see the file; an encrypted file has `encrypted: true` and no url. VOICE: a voice message has `voice: {transcript, audio_url, duration_ms}` and `text` reads \"[voice note — 25s] <transcript>\".",
198
227
  inputSchema: mIRC_list_messages_input,
199
228
  handler: mIRC_list_messages as MosaddTool["handler"],
200
229
  },
package/src/tools/mirc.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * IRC-style persistent channels (Discord/Slack semantics). Channels live forever
5
5
  * until deleted, members come and go. Ephemeral / no-account / single-action
6
- * channels are PRESETS of mIRC (planned: LINEAR-3523 — TTL `expires_at` +
6
+ * channels are PRESETS of mIRC (planned: TTL `expires_at` +
7
7
  * guest-link + voice), not a separate module. The killed mROOM is absorbed here.
8
8
  *
9
9
  * Phase 1 alpha: wired to the mosadd backend's `channel-manage` Edge Function (strangler-fig).
@@ -7,7 +7,7 @@
7
7
  * RLS policies apply room-membership checks rather than DM contact checks.
8
8
  *
9
9
  * Voice in rooms (PTT, audio) lands separately via mTALK_start_session
10
- * over the WebRTC daemon — see LINEAR-2145.
10
+ * over the WebRTC daemon.
11
11
  */
12
12
 
13
13
  import { z } from "zod";
@@ -295,14 +295,14 @@ async function comms_session_attach(
295
295
 
296
296
  // The signing declaration message-send reads (migration 20260826210000). RLS re-checks
297
297
  // ownership in its WITH CHECK; message-send re-validates AGAIN per post (defence in depth).
298
- // ⛔ ARBITER W SQL, NIE SUROWY UPSERT (LINEAR-5879 · LINEAR-5895 B1). Migracja założyła
299
- // `mosadd_gateway_binding_claim` 05.09, ale NIC jej nie wołało — połowa roboty leżała martwa
300
- // w bazie, a klient dalej pisał wiersz ręcznie. Różnica NIE jest kosmetyczna:
301
- // · funkcja SPRAWDZA, że linia jest TWOJA, żywa i typu `agent` (`not_your_agent_line`),
302
- // zamiast polegać wyłącznie na RLS w WITH CHECK;
303
- // · funkcja WIE, że odebrała linię innej sesji, i mówi to w `took_over` — surowy upsert
304
- // robił dokładnie to samo PO CICHU. To jest ta cisza, przez którą dwie sesje na jednym
305
- // kluczu podpisywały się nawzajem przez 30 godzin, a obie meldowały sukces.
298
+ // ⛔ ARBITER IN SQL, NOT A RAW UPSERT. The migration created
299
+ // `mosadd_gateway_binding_claim` on 05.09, but NOTHING called it — half the work lay dead
300
+ // in the database while the client kept writing the row by hand. The difference is NOT cosmetic:
301
+ // · the function CHECKS that the line is YOURS, alive and of kind `agent` (`not_your_agent_line`),
302
+ // instead of relying only on RLS in WITH CHECK;
303
+ // · the function KNOWS it took the line over from another session and says so in `took_over` — the
304
+ // raw upsert did exactly the same SILENTLY. That silence is why two sessions on one
305
+ // key kept signing over each other for 30 hours while both reported success.
306
306
  const { data: claim, error: bindError } = await sb.rpc("mosadd_gateway_binding_claim", {
307
307
  p_session_id: sessionId(),
308
308
  p_agent_identity_id: agent.id,
@@ -369,8 +369,8 @@ export const presenceTools: MosaddTool[] = [
369
369
  ];
370
370
 
371
371
  /**
372
- * AUTO-PAROWANIE (2026-08-26, rozkaz Króla po tygodniu „żywa sesja Dyspozytora nie jest
373
- * podpięta"): the founder kept talking to cloud stand-ins because LIVE sessions never
372
+ * AUTO-PAIRING (2026-08-26, after a week of "the live dispatcher session is not
373
+ * attached"): the founder kept talking to cloud stand-ins because LIVE sessions never
374
374
  * remembered to call comms_session_attach. A model cannot be relied on to remember a
375
375
  * handshake — so the handshake stops being the model's job: the server calls THIS after
376
376
  * every successful tool call. Any session that is actually DOING something on an agent
@@ -13,7 +13,7 @@
13
13
  *
14
14
  * Auth: standard Supabase session JWT (the caller's RAG opt-in is read from
15
15
  * their account; opted-out callers get status='skipped_optout').
16
- * LINEAR-3998 (P4.1 PTT unify) — re-arch 2026-06-27.
16
+ * P4.1 PTT unify — re-arch 2026-06-27.
17
17
  */
18
18
  import { z } from "zod";
19
19
  import type { MosaddTool, MosaddToolContext } from "../types.js";
@@ -11,7 +11,7 @@
11
11
  * backend. There is no surveillance, no data collection — it classifies an event
12
12
  * the caller already has and returns a defensive recommendation.
13
13
  *
14
- * Founder decision (LINEAR-3498): the catalog is real and must be a real MCP
14
+ * Founder decision: the catalog is real and must be a real MCP
15
15
  * tool, not detoxed away. (The AUDIT-B detox concerns the dead "anti-Pegasus"
16
16
  * MARKETING framing, not this classification engine.)
17
17
  */
@@ -1,12 +1,12 @@
1
1
  /**
2
- * voice-format — W4 (rozkaz Króla 16.09): głos do agenta ma czytać się jak notka,
3
- * nie jak 500 KB base64 w polu text.
2
+ * voice-format — W4 (owner decision 16.09): a voice message to an agent should read like a note,
3
+ * not like 500 KB of base64 in the text field.
4
4
  *
5
- * Wiadomości voice/ptt (message_type "voice"/"ptt") niosą payload w kształcie
6
- * { audio, mime, dur } (base64 webm/mp4). Do tej pory mDM_list/mIRC_list_messages
7
- * zwracały ten surowy JSON jako text — agent widział śmieć zamiast nagrania.
8
- * Teraz dostaje zwięzły marker z czasem trwania. Audio zostaje w payloadzie;
9
- * kto chce odsłuchać, sięga po narzędzie głosowe (mDM_voice_note / transkrypcję).
5
+ * Voice/PTT messages (message_type "voice"/"ptt") carry a payload shaped
6
+ * { audio, mime, dur } (base64 webm/mp4). Until then mDM_list/mIRC_list_messages
7
+ * returned that raw JSON as text — the agent saw garbage instead of a recording.
8
+ * Now it gets a short marker with the duration. The audio stays in the payload;
9
+ * whoever wants to listen uses a voice tool (mDM_voice_note / transcription).
10
10
  */
11
11
  export function formatVoiceIfAny(text: string): string {
12
12
  try {
@@ -41,3 +41,49 @@ export function voiceFields(m: {
41
41
  if (m.messageType !== "voice" && m.messageType !== "ptt") return {};
42
42
  return { voice: { transcript: m.transcript ?? null, audio_url: m.audioUrl ?? null, duration_ms: m.durationMs ?? null } };
43
43
  }
44
+
45
+ const VOICE_MARKER = /^\[voice note — \d+s\]$/;
46
+
47
+ /**
48
+ * 30.11.2026 — agent ma USŁYSZEĆ PTT, nie zobaczyć podpis. Agenci czytają `text` (nasłuch, skille, mosty) —
49
+ * pole `voice` widział tylko ten, kto o nie zapytał. Dla głosówki `text` = znacznik + transkrypt:
50
+ * „[voice note — 25s] <transkrypcja>”. Bez transkryptu (jeszcze się robi / nagranie bez mowy) zostaje sam znacznik.
51
+ * Transkrypt przychodzi z message-list uprawnieniami CZYTAJĄCEGO (RLS ptt_transcripts: uczestnik wątku / członek kanału),
52
+ * więc obcy nie dostaje go ani w `voice`, ani w `text`.
53
+ */
54
+ export function voiceText(
55
+ text: string,
56
+ voice?: { transcript: string | null; duration_ms: number | null } | null,
57
+ ): string {
58
+ if (!voice) return text;
59
+ const marker = VOICE_MARKER.test(text)
60
+ ? text
61
+ : typeof voice.duration_ms === "number" && voice.duration_ms > 0
62
+ ? `[voice note — ${Math.max(1, Math.round(voice.duration_ms / 1000))}s]`
63
+ : "[voice note]";
64
+ const t = typeof voice.transcript === "string" ? voice.transcript.trim() : "";
65
+ return t ? `${marker} ${t}` : marker;
66
+ }
67
+
68
+ /** 30.11.2026 — plik w wiadomości (zrzut przy tekście, mDM_send_file, stary JSON kompozytora): message-list (mosADD)
69
+ * oddaje `files` z podpisanym adresem (~1 h) uprawnieniami czytającego; tu idą do agenta jako `attachments`.
70
+ * Zaszyfrowany plik: `encrypted: true`, `url: null`. */
71
+ export type MessageAttachment = { name: string; mime: string; size: number | null; url: string | null; encrypted?: true };
72
+
73
+ export function attachmentsFrom(raw: unknown): MessageAttachment[] | undefined {
74
+ if (!Array.isArray(raw)) return undefined;
75
+ const out: MessageAttachment[] = [];
76
+ for (const f of raw.slice(0, 20)) {
77
+ if (!f || typeof f !== "object") continue;
78
+ const r = f as Record<string, unknown>;
79
+ const url = typeof r.url === "string" && /^https:\/\//.test(r.url) ? r.url : null;
80
+ out.push({
81
+ name: typeof r.name === "string" && r.name ? r.name : "file",
82
+ mime: typeof r.mime === "string" && r.mime ? r.mime : "application/octet-stream",
83
+ size: typeof r.size === "number" && Number.isFinite(r.size) ? r.size : null,
84
+ url,
85
+ ...(r.encrypted === true ? { encrypted: true as const } : {}),
86
+ });
87
+ }
88
+ return out.length ? out : undefined;
89
+ }