@mosadd/mcp 3.0.0-alpha.7 → 3.0.1

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 (68) hide show
  1. package/CHANGELOG.md +415 -0
  2. package/LICENSE +21 -201
  3. package/README.md +79 -40
  4. package/dist/bin/mcp.js +132 -8
  5. package/dist/chunk-J2S44U5R.js +4258 -0
  6. package/dist/index.d.ts +112 -8
  7. package/dist/index.js +3 -1
  8. package/package.json +19 -16
  9. package/src/__tests__/blob-upload.test.ts +93 -0
  10. package/src/__tests__/channel-e2ee.test.ts +62 -0
  11. package/src/__tests__/cli.test.ts +47 -0
  12. package/src/__tests__/fleet-plaintext.test.ts +243 -0
  13. package/src/__tests__/golden-path.test.ts +4 -2
  14. package/src/__tests__/integration.test.ts +50 -11
  15. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  16. package/src/__tests__/label-room-owner.test.ts +22 -0
  17. package/src/__tests__/mdm-e2ee.test.ts +36 -2
  18. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  19. package/src/__tests__/mirc-invite.test.ts +112 -0
  20. package/src/__tests__/mirc-voice.test.ts +82 -0
  21. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  22. package/src/__tests__/mrag-search-diagnostics.test.ts +78 -0
  23. package/src/__tests__/no-dead-host.test.ts +37 -0
  24. package/src/__tests__/presence.test.ts +199 -0
  25. package/src/__tests__/server.test.ts +11 -7
  26. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  27. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  28. package/src/__tests__/voice-fields.test.ts +24 -0
  29. package/src/bin/mcp.ts +71 -6
  30. package/src/cli.ts +100 -0
  31. package/src/crypto/channel-e2ee.ts +288 -0
  32. package/src/crypto/mdm-session.ts +479 -40
  33. package/src/index.ts +2 -2
  34. package/src/providers/blob-upload.ts +162 -0
  35. package/src/providers/supabase-dm.ts +102 -7
  36. package/src/providers/supabase-voice.ts +13 -1
  37. package/src/providers/supabase.ts +121 -10
  38. package/src/server.ts +102 -12
  39. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  40. package/src/tools/actions.ts +166 -0
  41. package/src/tools/attachments.ts +276 -0
  42. package/src/tools/capabilities.ts +2 -0
  43. package/src/tools/channel-payload.ts +69 -0
  44. package/src/tools/embed.ts +110 -0
  45. package/src/tools/index.ts +136 -6
  46. package/src/tools/knowledge-graph.ts +186 -0
  47. package/src/tools/knowledge.ts +205 -12
  48. package/src/tools/mail-agentbox.ts +155 -0
  49. package/src/tools/mail-aliases.ts +25 -0
  50. package/src/tools/mail-provenance.ts +137 -0
  51. package/src/tools/mail.ts +214 -60
  52. package/src/tools/mdm-as-agent.ts +137 -0
  53. package/src/tools/mdm-voice.ts +17 -3
  54. package/src/tools/mdm.ts +306 -58
  55. package/src/tools/mirc-edge.ts +12 -6
  56. package/src/tools/mirc-members.ts +130 -20
  57. package/src/tools/mirc-messages.ts +109 -40
  58. package/src/tools/mirc.ts +149 -11
  59. package/src/tools/mroom-messages.ts +5 -13
  60. package/src/tools/mtalk.ts +11 -1
  61. package/src/tools/murl.ts +314 -0
  62. package/src/tools/presence.ts +442 -0
  63. package/src/tools/ptt-ingest.ts +99 -0
  64. package/src/tools/threat.ts +123 -0
  65. package/src/tools/voice-format.ts +66 -0
  66. package/src/types.ts +36 -0
  67. package/src/version.ts +8 -0
  68. package/dist/chunk-EFTB743G.js +0 -1924
@@ -0,0 +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
+ }
@@ -17,13 +17,87 @@ import type {
17
17
  DmSendResult,
18
18
  DmListArgs,
19
19
  DmListResult,
20
+ DmMessage,
20
21
  } from "@mosadd/providers";
21
22
  import { getSupabase, invokeFunction, readSupabaseEnv } from "./supabase.js";
22
23
 
23
24
  const PROTOCOL_VERSION = "mosadd.chat.v1";
24
25
 
26
+ /**
27
+ * ⛔ THE CANONICAL mDM TEXT TYPE IS `txt`. The app sends and renders `txt`; `text` is a legacy
28
+ * spelling the server keeps only so old clients are not refused (message-send
29
+ * CLIENT_SENDABLE_MESSAGE_TYPES, "text 18 legacy, last written 2026-07-08"). This provider kept
30
+ * writing `text` for every MCP DM until 27.09 — the last writer of the legacy type.
31
+ */
32
+ export const MDM_TEXT_MESSAGE_TYPE = "txt";
33
+
34
+ /**
35
+ * ⛔ AN E2EE ENVELOPE SEALED BY MCP ON A PERSON'S KEY IS TYPED `text` — ON PURPOSE (27.09.2026).
36
+ * The app's readOwnMdmMessage (apps/web/src/lib/mdmE2ee.ts, from f95557f) explains an unreadable
37
+ * OWN bubble by message_type: `text` → reason "agent" („wysłane przez agenta/MCP bez kopii dla
38
+ * Ciebie"), anything else → "device" („wysłane z innego urządzenia"). MCP holds an API-key seed,
39
+ * never the person's app seed, so it can never write a self copy the app opens — typing its
40
+ * envelope `txt` made the app tell the owner a false reason. `text` stays client-sendable in
41
+ * message-send (CLIENT_SENDABLE_MESSAGE_TYPES) precisely for this lane. Plaintext stays `txt`.
42
+ */
43
+ export const MDM_MCP_SEALED_MESSAGE_TYPE = "text";
44
+
45
+ /**
46
+ * Supabase-only extras for a DM send. The transport-agnostic DmSendArgs (@mosadd/providers)
47
+ * carries opaque bytes only; the network lane can additionally store the two recoverable copies
48
+ * the app reads (see sealForSelf / sealForPeerRecoverable in crypto/mdm-session.ts). A radio
49
+ * provider ignores these fields.
50
+ */
51
+ export interface DmSendExtras {
52
+ messageType?: string;
53
+ /** "s1." copy sealed to the sender's self-read key → `messages.self_payload`. */
54
+ selfPayload?: string | null;
55
+ /** "r1." copy sealed to the recipient's identity → `messages.recipient_self_payload`. */
56
+ recipientSelfPayload?: string | null;
57
+ }
58
+ export type DmSendArgsExt = DmSendArgs & DmSendExtras;
59
+
60
+ /** A listed DM plus the recoverable copies message-list returns (RLS: own copy only). */
61
+ export interface DmMessageExt extends DmMessage {
62
+ selfPayload?: string | null;
63
+ recipientSelfPayload?: string | null;
64
+ messageType?: string;
65
+ /** 15.11: z message-list dla voice/ptt (voiceEnrich.ts w mosADD). */
66
+ transcript?: string | null;
67
+ audioUrl?: string | null;
68
+ durationMs?: number | null;
69
+ }
70
+
25
71
  export class SupabaseDmProvider implements DmProvider {
26
72
  private cachedSelfId: string | null = null;
73
+ private cachedSelfKind: string | null = null;
74
+
75
+ /**
76
+ * `identities.kind` of the caller ("human" | "agent" | …). An agent LINE owns its mDM
77
+ * identity outright (its key is its only runtime); a human's identity is anchored in the app.
78
+ * ensureOwnBundlePublished uses this to decide whether a stale bundle may be replaced.
79
+ */
80
+ async selfKind(): Promise<string | null> {
81
+ await this.selfId();
82
+ return this.cachedSelfKind;
83
+ }
84
+
85
+ /**
86
+ * `identities.kind` of a PEER, or null when it cannot be read (RLS can_see_identity scopes rows
87
+ * to contacts / thread co-members; a miss is not an error). mDM_send uses it exactly like the
88
+ * app's ChatPanel `peerIsAgent` (theirIdent.kind === 'agent' || iAmAgent): a DM to an agent
89
+ * line is sent in the clear, because the line must read it (owner decision 20.09).
90
+ */
91
+ async peerKind(peerId: string): Promise<string | null> {
92
+ try {
93
+ const sb = getSupabase();
94
+ const { data, error } = await sb.from("identities").select("kind").eq("id", peerId).limit(1).maybeSingle();
95
+ if (error || !data) return null;
96
+ return typeof data.kind === "string" ? data.kind : null;
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
27
101
 
28
102
  async selfId(): Promise<string> {
29
103
  if (this.cachedSelfId) return this.cachedSelfId;
@@ -37,27 +111,31 @@ export class SupabaseDmProvider implements DmProvider {
37
111
  }
38
112
  const { data: identity, error } = await sb
39
113
  .from("identities")
40
- .select("id")
114
+ .select("id, kind")
41
115
  .eq("user_id", u.user.id)
42
116
  .maybeSingle();
43
117
  if (error || !identity) {
44
118
  throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
45
119
  }
46
120
  this.cachedSelfId = identity.id as string;
121
+ this.cachedSelfKind = typeof identity.kind === "string" ? identity.kind : null;
47
122
  return this.cachedSelfId;
48
123
  }
49
124
 
50
- async send(args: DmSendArgs): Promise<DmSendResult> {
125
+ async send(args: DmSendArgsExt): Promise<DmSendResult> {
51
126
  const encrypted_payload = Buffer.from(args.payload).toString("base64");
52
127
  type MessageSendResponse = { message?: { id: string; created_at: string } };
53
128
  const data = await invokeFunction<MessageSendResponse>("message-send", {
54
129
  space_id: "dm",
55
130
  thread_id: args.threadId,
56
131
  encrypted_payload,
57
- message_type: "text",
132
+ message_type: args.messageType ?? MDM_TEXT_MESSAGE_TYPE,
58
133
  protocol_version: PROTOCOL_VERSION,
59
134
  recipient_account_id: args.to,
60
135
  reply_to_id: args.replyToId ?? null,
136
+ // Same optional columns the app writes (ircApi.sendThreadMessage); omitted when absent.
137
+ ...(args.selfPayload ? { self_payload: args.selfPayload } : {}),
138
+ ...(args.recipientSelfPayload ? { recipient_self_payload: args.recipientSelfPayload } : {}),
61
139
  });
62
140
  if (!data?.message?.id) {
63
141
  throw new Error("message-send returned no message id");
@@ -94,24 +172,41 @@ export class SupabaseDmProvider implements DmProvider {
94
172
  thread_id: string;
95
173
  encrypted_payload: string;
96
174
  created_at: string;
175
+ message_type?: string | null;
176
+ self_payload?: string | null;
177
+ recipient_self_payload?: string | null;
178
+ transcript?: string | null;
179
+ audio_url?: string | null;
180
+ duration_ms?: number | null;
97
181
  }>;
98
- next_cursor?: string | null;
182
+ cursor?: string | null;
183
+ has_more?: boolean;
184
+ next_before?: string | null;
99
185
  };
186
+ // message-list paginates history via `before` (a created_at marker) and returns
187
+ // the next marker as `cursor` — NOT `cursor` in / `next_cursor` out.
100
188
  const data = await invokeFunction<MessageListResponse>("message-list", {
101
189
  space_id: "dm",
102
190
  thread_id: args.threadId,
103
191
  limit: args.limit ?? 50,
104
- cursor: args.cursor,
192
+ before: args.cursor,
105
193
  });
106
194
  return {
107
- messages: (data?.messages ?? []).map((m) => ({
195
+ messages: (data?.messages ?? []).map((m): DmMessageExt => ({
108
196
  id: m.id,
109
197
  senderId: m.sender_identity_id,
110
198
  payload: new Uint8Array(Buffer.from(m.encrypted_payload, "base64")),
111
199
  timestamp: m.created_at,
112
200
  threadId: m.thread_id,
201
+ messageType: m.message_type ?? undefined,
202
+ selfPayload: m.self_payload ?? null,
203
+ recipientSelfPayload: m.recipient_self_payload ?? null,
204
+ transcript: m.transcript ?? null,
205
+ audioUrl: m.audio_url ?? null,
206
+ durationMs: m.duration_ms ?? null,
113
207
  })),
114
- nextCursor: data?.next_cursor ?? null,
208
+ // history mode (`before`) returns `next_before`; incremental (`since`) returns `cursor`+`has_more`.
209
+ nextCursor: data?.next_before ?? (data?.has_more ? (data?.cursor ?? null) : null),
115
210
  };
116
211
  }
117
212
  }
@@ -45,7 +45,7 @@ export class SupabaseVoiceProvider implements VoiceProvider {
45
45
 
46
46
  async createRoom(label?: string): Promise<{ roomId: string }> {
47
47
  const self = await this.selfId();
48
- const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
48
+ const roomId = labelRoomId(self, label);
49
49
  // Floor row is created lazily by mtalk-floor on first request; nothing to do
50
50
  // here beyond returning the canonical id.
51
51
  return { roomId };
@@ -82,6 +82,18 @@ export class SupabaseVoiceProvider implements VoiceProvider {
82
82
  }
83
83
  }
84
84
 
85
+ /**
86
+ * 15.11.2026 — nazwa pokoju PTT. Bez etykiety: pokój osobisty `mosadd-room-<id>`. Z etykietą:
87
+ * `mosadd-room-<id otwierającego>-<etykieta>` — właściciel jest w nazwie, więc bramka
88
+ * (mosADD `livekit-token/labelRoom.ts`) wpuszcza właściciela i jego kontakty, a obcy nie przejmie
89
+ * pokoju wejściem jako pierwszy. Dawne `mosadd-room-<etykieta>` było jedną nazwą dla wszystkich
90
+ * kont bez właściciela → 403 dla każdego.
91
+ */
92
+ export function labelRoomId(selfIdentityId: string, label?: string): string {
93
+ if (!label) return `${ROOM_PREFIX}${selfIdentityId}`;
94
+ return `${ROOM_PREFIX}${selfIdentityId}-${slug(label) || "room"}`;
95
+ }
96
+
85
97
  function slug(s: string): string {
86
98
  return s
87
99
  .toLowerCase()
@@ -10,13 +10,42 @@
10
10
  */
11
11
 
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
+ import { randomUUID } from "node:crypto";
14
+ import { hostname } from "node:os";
13
15
  import { createClient, type SupabaseClient } from "@supabase/supabase-js";
14
16
  import { loadSession, isSessionExpired } from "../config.js";
15
17
 
18
+ /**
19
+ * Tożsamość TEGO procesu — stała przez całe życie sesji, nowa przy każdym starcie.
20
+ *
21
+ * ⛔ NIE MOŻE być pochodną konta ani hosta. Dwie sesje generałów potrafią stać na tej samej
22
+ * maszynie i pod tym samym kontem (box floty), więc identyfikator z hosta zlepiłby je z powrotem
23
+ * w jedną — czyli odtworzył dokładnie ten błąd, który to naprawia. Nazwa hosta zostaje tylko jako
24
+ * czytelny przedrostek do diagnostyki; o rozróżnieniu decyduje losowy ogon.
25
+ */
26
+ let cachedSessionId: string | null = null;
27
+ export function sessionId(): string {
28
+ // ⛔ BRAMA HOSTOWANA ≠ PROCES (audyt 2026-08-27). Na mcp.mosadd.com jeden proces lambdy obsługuje
29
+ // WIELU najemców, a kolejne wywołania tej samej rozmowy potrafią trafić w RÓŻNE procesy — więc
30
+ // tożsamość per-proces byłaby tam jednocześnie wspólna (wyciek między najemcami) i niestała
31
+ // (fałszywe 409 przy każdym przełączeniu instancji). W kontekście bramy prawda żyje w ALS:
32
+ // brama wyznacza stabilny `sessionKey` per klucz API; brak klucza = puste "" (semantyka legacy,
33
+ // zero roszczeń per-sesja). Losowy identyfikator per-proces zostaje TYLKO dla stdio.
34
+ const perRequest = requestEnv.getStore();
35
+ if (perRequest) return perRequest.sessionKey ?? "";
36
+ if (cachedSessionId) return cachedSessionId;
37
+ let host = "mcp";
38
+ try { host = (hostname() || "mcp").slice(0, 24); } catch { /* bez nazwy hosta też działa */ }
39
+ cachedSessionId = `${host}:${randomUUID()}`;
40
+ return cachedSessionId;
41
+ }
42
+
16
43
  export interface SupabaseEnv {
17
44
  url: string;
18
45
  anonKey: string;
19
46
  userJwt?: string;
47
+ /** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
48
+ sessionKey?: string;
20
49
  }
21
50
 
22
51
  /**
@@ -85,11 +114,27 @@ export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClien
85
114
  autoRefreshToken: false,
86
115
  detectSessionInUrl: false,
87
116
  },
88
- global: env.userJwt
89
- ? {
90
- headers: { Authorization: `Bearer ${env.userJwt}` },
91
- }
92
- : undefined,
117
+ // ⛔ x-mosadd-origin: EVERY call from the toolkit / MCP gateway carries this marker (2026-08-25,
118
+ // after agent sessions were found speaking as their owner). Agent sessions plugged in the OWNER's
119
+ // key and posted on channels from the owner's own bubble — the server had NO WAY to tell the gateway
120
+ // from the app, because hub-key-exchange returns an ordinary user JWT. This header tells them apart:
121
+ // message-send refuses a channel post from a PERSON's identity when it came through the gateway, with
122
+ // a message telling the caller to plug in its OWN line's key. The mosadd.com app never sends this header.
123
+ global: {
124
+ headers: {
125
+ ...(env.userJwt ? { Authorization: `Bearer ${env.userJwt}` } : {}),
126
+ "x-mosadd-origin": "hub-gateway",
127
+ // The header only when the session HAS an identity — an empty "" (gateway without sessionKey) sends
128
+ // nothing, so the server-side 409 guard sees no false claims.
129
+ ...(sessionId() ? { "x-mosadd-session": sessionId() } : {}),
130
+ // ⛔ KTÓRA TO SESJA (2026-08-27, „każdy generał co chwilę gubi mózg"). Wszyscy generałowie
131
+ // wpinają się kluczem hub TEGO SAMEGO właściciela, więc dla serwera ich wywołania były
132
+ // nieodróżnialne — a deklaracja linii (`comms_session_attach as_agent`) trzymała JEDEN
133
+ // wiersz na konto. Skutek: kto wpiął się ostatni, odbierał linię wszystkim pozostałym, a
134
+ // ich posty na kanałach zaczynały wracać z 403. Tożsamość sesji (stdio: per proces,
135
+ // brama: per klucz API) pozwala dziewięciu liniom na jednym koncie nie deptać sobie po piętach.
136
+ },
137
+ },
93
138
  });
94
139
  }
95
140
 
@@ -105,12 +150,78 @@ export async function invokeFunction<T = unknown>(
105
150
  const client = getSupabase();
106
151
  const { data, error } = await client.functions.invoke<T>(fn, { body });
107
152
  if (error) {
108
- const msg =
109
- error instanceof Error
153
+ // supabase-js throws FunctionsHttpError for any non-2xx, whose `.message`
154
+ // is the FIXED generic string "Edge Function returned a non-2xx status
155
+ // code" — the *real* reason (e.g. {"error":"wrapped_group_key required"},
156
+ // "forbidden", an RLS denial) lives in `error.context`, a Response. Read it
157
+ // so the agent gets an actionable message (and the HTTP status) it can
158
+ // reason about and self-correct on, instead of the same opaque sentence
159
+ // for every failure across mDM/mIRC/mp0st/mRAG/prekey/message-list.
160
+ let msg =
161
+ error instanceof Error && error.message
110
162
  ? error.message
111
- : typeof (error as { message?: unknown })?.message === "string"
112
- ? (error as { message: string }).message
113
- : `Edge function ${fn} failed`;
163
+ : `Edge function ${fn} failed`;
164
+ const ctx = (error as { context?: unknown }).context;
165
+ if (ctx && typeof (ctx as Response).text === "function") {
166
+ const res = ctx as Response;
167
+ try {
168
+ const raw = await res.text();
169
+ if (raw) {
170
+ let detail = raw;
171
+ let recipe = "";
172
+ try {
173
+ const parsed = JSON.parse(raw) as {
174
+ error?: unknown;
175
+ message?: unknown;
176
+ code?: unknown;
177
+ message_en?: unknown;
178
+ next_steps?: unknown;
179
+ };
180
+ detail =
181
+ (typeof parsed.error === "string" && parsed.error) ||
182
+ (typeof parsed.message === "string" && parsed.message) ||
183
+ raw;
184
+ // ⛔ The refusal CONTRACT (supabase/functions/_shared/errors.ts) travels as
185
+ // { code, message_en, message_pl, next_steps[] }. Until 2026-09-04 this block read
186
+ // `error` alone and threw the rest away — so the server said "here is exactly what to
187
+ // do next" and the agent received one flat sentence. The recipe is the whole point of
188
+ // the contract: it is written FOR a machine to act on. Measured on production the same
189
+ // day: mIRC_post_message with someone else's agent returned only
190
+ // "message-send (403): agent_not_owned" — code, both messages and 2 next_steps dropped.
191
+ // Rendered below as plain text because that is what an MCP tool error carries.
192
+ const steps = Array.isArray(parsed.next_steps) ? parsed.next_steps : [];
193
+ const lines: string[] = [];
194
+ if (typeof parsed.code === "string" && parsed.code) lines.push(`code: ${parsed.code}`);
195
+ if (typeof parsed.message_en === "string" && parsed.message_en && parsed.message_en !== detail) {
196
+ lines.push(parsed.message_en);
197
+ }
198
+ for (const raw_step of steps) {
199
+ const step = raw_step as { actor?: unknown; tool?: unknown; ui?: unknown; args?: unknown; why?: unknown };
200
+ const who = typeof step.actor === "string" ? step.actor : "?";
201
+ const what =
202
+ (typeof step.tool === "string" && step.tool) ||
203
+ (typeof step.ui === "string" && step.ui) ||
204
+ "";
205
+ if (!what) continue;
206
+ const why = typeof step.why === "string" ? ` — ${step.why}` : "";
207
+ const args =
208
+ step.args && typeof step.args === "object"
209
+ ? ` ${JSON.stringify(step.args)}`
210
+ : "";
211
+ lines.push(`next (${who}): ${what}${args}${why}`);
212
+ }
213
+ if (lines.length) recipe = "\n" + lines.join("\n");
214
+ } catch {
215
+ // non-JSON body — use the raw text as-is
216
+ }
217
+ const status = typeof res.status === "number" ? res.status : undefined;
218
+ // First line stays byte-for-byte what callers have always matched on; the recipe follows.
219
+ msg = (status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`) + recipe;
220
+ }
221
+ } catch {
222
+ // body already consumed or unreadable — keep the generic message
223
+ }
224
+ }
114
225
  throw new Error(msg);
115
226
  }
116
227
  if (data == null) {