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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +363 -309
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-KVN7LZFW.js → chunk-3PUOM4R5.js} +470 -112
  5. package/dist/index.d.ts +11 -1
  6. package/dist/index.js +1 -1
  7. package/package.json +9 -9
  8. package/src/__tests__/golden-path.test.ts +139 -139
  9. package/src/__tests__/integration.test.ts +182 -182
  10. package/src/__tests__/knowledge-ingest.test.ts +114 -114
  11. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  12. package/src/__tests__/mdm-mcp-readable.test.ts +386 -0
  13. package/src/__tests__/mirc-invite.test.ts +112 -112
  14. package/src/__tests__/mtalk.test.ts +122 -122
  15. package/src/__tests__/server.test.ts +71 -71
  16. package/src/__tests__/serverJsonVersion.test.ts +45 -45
  17. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  18. package/src/bin/login.ts +138 -138
  19. package/src/bin/mcp.ts +145 -145
  20. package/src/config.ts +66 -66
  21. package/src/crypto/mdm-session.ts +842 -502
  22. package/src/index.ts +19 -19
  23. package/src/observability/sentry.ts +79 -79
  24. package/src/providers/memory-voice.ts +79 -79
  25. package/src/providers/supabase-dm.ts +202 -122
  26. package/src/providers/supabase-voice.ts +91 -91
  27. package/src/providers/supabase.ts +231 -231
  28. package/src/server.ts +195 -162
  29. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -67
  30. package/src/tools/actions.ts +166 -166
  31. package/src/tools/attachments.ts +276 -276
  32. package/src/tools/capabilities.ts +70 -70
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge-graph.ts +186 -186
  36. package/src/tools/knowledge.ts +344 -344
  37. package/src/tools/mail-agentbox.ts +155 -155
  38. package/src/tools/mail-aliases.ts +25 -25
  39. package/src/tools/mail-provenance.ts +137 -137
  40. package/src/tools/mail.ts +403 -403
  41. package/src/tools/mcall.ts +216 -216
  42. package/src/tools/mdm-as-agent.ts +126 -126
  43. package/src/tools/mdm-voice.ts +220 -220
  44. package/src/tools/mdm.ts +211 -29
  45. package/src/tools/mirc-edge.ts +196 -196
  46. package/src/tools/mirc-members.ts +287 -287
  47. package/src/tools/mirc.ts +308 -308
  48. package/src/tools/mroom-messages.ts +142 -142
  49. package/src/tools/mroom.ts +221 -221
  50. package/src/tools/mtalk.ts +131 -131
  51. package/src/tools/murl.ts +314 -314
  52. package/src/tools/presence.ts +442 -442
  53. package/src/tools/ptt-ingest.ts +99 -99
  54. package/src/tools/threat.ts +123 -123
  55. package/src/types.ts +121 -121
  56. package/src/version.ts +8 -8
  57. package/src/voice/floor.ts +132 -132
  58. package/LICENSE +0 -201
@@ -1,231 +1,231 @@
1
- /**
2
- * Supabase provider for the alpha MCP server.
3
- *
4
- * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
5
- * via env vars. The MCP server creates a per-request Supabase client and
6
- * invokes the mosadd Edge Functions on the user's behalf.
7
- *
8
- * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
9
- * holds keys server-side via the BYOK broker.
10
- */
11
-
12
- import { AsyncLocalStorage } from "node:async_hooks";
13
- import { randomUUID } from "node:crypto";
14
- import { hostname } from "node:os";
15
- import { createClient, type SupabaseClient } from "@supabase/supabase-js";
16
- import { loadSession, isSessionExpired } from "../config.js";
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
-
43
- export interface SupabaseEnv {
44
- url: string;
45
- anonKey: string;
46
- userJwt?: string;
47
- /** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
48
- sessionKey?: string;
49
- }
50
-
51
- /**
52
- * Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
53
- *
54
- * stdio runs one user per process, so credentials live in process.env. The
55
- * hosted gateway serves MANY users from one process — sharing process.env would
56
- * leak user A's JWT into user B's concurrent request. The gateway instead
57
- * resolves the caller's session (Bearer api key → hub-key-exchange) and runs the
58
- * whole request inside `runWithSupabaseEnv(env, …)`; `readSupabaseEnv()` reads
59
- * this store first and falls back to process.env, so stdio is unaffected.
60
- */
61
- const requestEnv = new AsyncLocalStorage<SupabaseEnv>();
62
-
63
- /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
64
- export function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T {
65
- return requestEnv.run(env, fn);
66
- }
67
-
68
- export class MissingSupabaseEnvError extends Error {
69
- constructor(missing: string[]) {
70
- super(
71
- `Missing Supabase credentials: ${missing.join(", ")}. ` +
72
- `Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
73
- );
74
- this.name = "MissingSupabaseEnvError";
75
- }
76
- }
77
-
78
- export function readSupabaseEnv(): SupabaseEnv {
79
- // Hosted HTTP gateway: a per-request session set via runWithSupabaseEnv wins
80
- // over any process-global env (multi-tenant safety). stdio has no store → falls
81
- // through to the env/login resolution below.
82
- const perRequest = requestEnv.getStore();
83
- if (perRequest) return perRequest;
84
-
85
- // Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
86
- // honored (deprecated) so anyone who set them before the brand sweep keeps
87
- // working. Env vars take precedence; fall back to the session saved by
88
- // `mosadd login`.
89
- const env = (canonical: string, legacy: string): string | undefined =>
90
- process.env[canonical] ?? process.env[legacy];
91
- const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
92
-
93
- const session = loadSession();
94
- const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
95
- const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
96
- const userJwt = userJwtEnv ?? session?.accessToken;
97
-
98
- const missing: string[] = [];
99
- if (!url) missing.push("MOSADD_SUPABASE_URL");
100
- if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
101
- if (missing.length) throw new MissingSupabaseEnvError(missing);
102
-
103
- // Surface an expired `mosadd login` token early with an actionable message.
104
- if (!userJwtEnv && session && isSessionExpired(session)) {
105
- throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
106
- }
107
- return { url: url!, anonKey: anonKey!, userJwt };
108
- }
109
-
110
- export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
111
- return createClient(env.url, env.anonKey, {
112
- auth: {
113
- persistSession: false,
114
- autoRefreshToken: false,
115
- detectSessionInUrl: false,
116
- },
117
- // ⛔ x-mosadd-origin: KAŻDE wywołanie z toolkitu/bramy MCP niesie ten znacznik (2026-08-25,
118
- // rozkaz Króla „kradną tożsamości"). Sesje agentów wpinały klucz WŁAŚCICIELA i postowały na
119
- // kanałach z jego dymka (SOVEREIGN) — serwer nie miał JAK odróżnić bramy od aplikacji, bo
120
- // hub-key-exchange zwraca zwykły JWT usera. Ten nagłówek to rozróżnia: message-send odrzuca
121
- // post na kanał z tożsamości CZŁOWIEKA, gdy przyszedł przez bramę — z komunikatem każącym
122
- // wpiąć klucz SWOJEJ linii. Aplikacja mosadd.com nigdy nie wysyła tego nagłówka.
123
- global: {
124
- headers: {
125
- ...(env.userJwt ? { Authorization: `Bearer ${env.userJwt}` } : {}),
126
- "x-mosadd-origin": "hub-gateway",
127
- // Nagłówek tylko, gdy sesja MA tożsamość — puste "" (brama bez sessionKey) nie wysyła nic,
128
- // więc serwerowy strażnik 409 nie widzi fałszywych roszczeń.
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
- },
138
- });
139
- }
140
-
141
- /**
142
- * Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
143
- * normalized error handling so MCP tool handlers can throw clean errors that
144
- * agents can reason about.
145
- */
146
- export async function invokeFunction<T = unknown>(
147
- fn: string,
148
- body: Record<string, unknown>,
149
- ): Promise<T> {
150
- const client = getSupabase();
151
- const { data, error } = await client.functions.invoke<T>(fn, { body });
152
- if (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
162
- ? error.message
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
- }
225
- throw new Error(msg);
226
- }
227
- if (data == null) {
228
- throw new Error(`Edge function ${fn} returned no data`);
229
- }
230
- return data;
231
- }
1
+ /**
2
+ * Supabase provider for the alpha MCP server.
3
+ *
4
+ * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
5
+ * via env vars. The MCP server creates a per-request Supabase client and
6
+ * invokes the mosadd Edge Functions on the user's behalf.
7
+ *
8
+ * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
9
+ * holds keys server-side via the BYOK broker.
10
+ */
11
+
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+ import { randomUUID } from "node:crypto";
14
+ import { hostname } from "node:os";
15
+ import { createClient, type SupabaseClient } from "@supabase/supabase-js";
16
+ import { loadSession, isSessionExpired } from "../config.js";
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
+
43
+ export interface SupabaseEnv {
44
+ url: string;
45
+ anonKey: string;
46
+ userJwt?: string;
47
+ /** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
48
+ sessionKey?: string;
49
+ }
50
+
51
+ /**
52
+ * Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
53
+ *
54
+ * stdio runs one user per process, so credentials live in process.env. The
55
+ * hosted gateway serves MANY users from one process — sharing process.env would
56
+ * leak user A's JWT into user B's concurrent request. The gateway instead
57
+ * resolves the caller's session (Bearer api key → hub-key-exchange) and runs the
58
+ * whole request inside `runWithSupabaseEnv(env, …)`; `readSupabaseEnv()` reads
59
+ * this store first and falls back to process.env, so stdio is unaffected.
60
+ */
61
+ const requestEnv = new AsyncLocalStorage<SupabaseEnv>();
62
+
63
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
64
+ export function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T {
65
+ return requestEnv.run(env, fn);
66
+ }
67
+
68
+ export class MissingSupabaseEnvError extends Error {
69
+ constructor(missing: string[]) {
70
+ super(
71
+ `Missing Supabase credentials: ${missing.join(", ")}. ` +
72
+ `Run \`mosadd login\`, or set MOSADD_SUPABASE_URL, MOSADD_SUPABASE_ANON_KEY and MOSADD_USER_JWT.`,
73
+ );
74
+ this.name = "MissingSupabaseEnvError";
75
+ }
76
+ }
77
+
78
+ export function readSupabaseEnv(): SupabaseEnv {
79
+ // Hosted HTTP gateway: a per-request session set via runWithSupabaseEnv wins
80
+ // over any process-global env (multi-tenant safety). stdio has no store → falls
81
+ // through to the env/login resolution below.
82
+ const perRequest = requestEnv.getStore();
83
+ if (perRequest) return perRequest;
84
+
85
+ // Canonical env vars are MOSADD_*; the legacy M0SSAD_* names are still
86
+ // honored (deprecated) so anyone who set them before the brand sweep keeps
87
+ // working. Env vars take precedence; fall back to the session saved by
88
+ // `mosadd login`.
89
+ const env = (canonical: string, legacy: string): string | undefined =>
90
+ process.env[canonical] ?? process.env[legacy];
91
+ const userJwtEnv = env("MOSADD_USER_JWT", "M0SSAD_USER_JWT");
92
+
93
+ const session = loadSession();
94
+ const url = env("MOSADD_SUPABASE_URL", "M0SSAD_SUPABASE_URL") ?? session?.url;
95
+ const anonKey = env("MOSADD_SUPABASE_ANON_KEY", "M0SSAD_SUPABASE_ANON_KEY") ?? session?.anonKey;
96
+ const userJwt = userJwtEnv ?? session?.accessToken;
97
+
98
+ const missing: string[] = [];
99
+ if (!url) missing.push("MOSADD_SUPABASE_URL");
100
+ if (!anonKey) missing.push("MOSADD_SUPABASE_ANON_KEY");
101
+ if (missing.length) throw new MissingSupabaseEnvError(missing);
102
+
103
+ // Surface an expired `mosadd login` token early with an actionable message.
104
+ if (!userJwtEnv && session && isSessionExpired(session)) {
105
+ throw new Error("Your mosadd session has expired. Run `mosadd login` again to refresh it.");
106
+ }
107
+ return { url: url!, anonKey: anonKey!, userJwt };
108
+ }
109
+
110
+ export function getSupabase(env: SupabaseEnv = readSupabaseEnv()): SupabaseClient {
111
+ return createClient(env.url, env.anonKey, {
112
+ auth: {
113
+ persistSession: false,
114
+ autoRefreshToken: false,
115
+ detectSessionInUrl: false,
116
+ },
117
+ // ⛔ x-mosadd-origin: KAŻDE wywołanie z toolkitu/bramy MCP niesie ten znacznik (2026-08-25,
118
+ // rozkaz Króla „kradną tożsamości"). Sesje agentów wpinały klucz WŁAŚCICIELA i postowały na
119
+ // kanałach z jego dymka (SOVEREIGN) — serwer nie miał JAK odróżnić bramy od aplikacji, bo
120
+ // hub-key-exchange zwraca zwykły JWT usera. Ten nagłówek to rozróżnia: message-send odrzuca
121
+ // post na kanał z tożsamości CZŁOWIEKA, gdy przyszedł przez bramę — z komunikatem każącym
122
+ // wpiąć klucz SWOJEJ linii. Aplikacja mosadd.com nigdy nie wysyła tego nagłówka.
123
+ global: {
124
+ headers: {
125
+ ...(env.userJwt ? { Authorization: `Bearer ${env.userJwt}` } : {}),
126
+ "x-mosadd-origin": "hub-gateway",
127
+ // Nagłówek tylko, gdy sesja MA tożsamość — puste "" (brama bez sessionKey) nie wysyła nic,
128
+ // więc serwerowy strażnik 409 nie widzi fałszywych roszczeń.
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
+ },
138
+ });
139
+ }
140
+
141
+ /**
142
+ * Invoke a the legacy mosadd consumer-app repo Edge Function. Wraps `supabase.functions.invoke` with
143
+ * normalized error handling so MCP tool handlers can throw clean errors that
144
+ * agents can reason about.
145
+ */
146
+ export async function invokeFunction<T = unknown>(
147
+ fn: string,
148
+ body: Record<string, unknown>,
149
+ ): Promise<T> {
150
+ const client = getSupabase();
151
+ const { data, error } = await client.functions.invoke<T>(fn, { body });
152
+ if (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
162
+ ? error.message
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
+ }
225
+ throw new Error(msg);
226
+ }
227
+ if (data == null) {
228
+ throw new Error(`Edge function ${fn} returned no data`);
229
+ }
230
+ return data;
231
+ }