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

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 +334 -309
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-KVN7LZFW.js → chunk-AWKITPZQ.js} +384 -103
  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 +284 -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 +798 -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 +174 -122
  26. package/src/providers/supabase-voice.ts +91 -91
  27. package/src/providers/supabase.ts +231 -231
  28. package/src/server.ts +186 -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 +119 -17
  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,442 +1,442 @@
1
- /**
2
- * comms_session_attach — a LIVE agent session claims the account's reply lane.
3
- *
4
- * WHY THIS EXISTS (measured 2026-08-14). mosADD answers a DM in one of two ways: a real agent
5
- * session (a Claude Code / Cowork / Desktop session holding this MCP server) or a cloud stand-in
6
- * (`agent-dm-responder`, pg_cron, small model). They must never both answer, and the stand-in must
7
- * never speak in the session's name — the founder caught exactly that twice, and stopped trusting
8
- * the agent afterwards.
9
- *
10
- * The arbitration already existed: `agent_bridge_heartbeat`. A fresh row = "somebody real is on
11
- * this line", and the cron stands down. But the ONLY thing that could write that row was a bespoke
12
- * script on the founder's own PC (`mosadd-agent/bridge-claude.mjs`). So "a real Claude answers you"
13
- * meant "the founder keeps a window open on one machine" — and that machine went quiet on
14
- * 2026-08-05 while the account kept looking alive. Four of his five agent contacts had nobody home.
15
- *
16
- * This tool moves the beat into the MCP server itself, so ANY session anywhere — his laptop, a
17
- * VPS, the legal dispatcher, a cloud runner — attaches with one call and the stand-in defers to it
18
- * for as long as that session's process lives.
19
- *
20
- * ⭐ AS_AGENT (2026-08-26, founder order: "wpinanie agentów ma działać co sesję i w różnych
21
- * kontach Claude"). Fleet sessions usually hold the OWNER's key (identity kind=human), so a bare
22
- * attach claims the OWNER's lane — and every channel post they made either landed in the owner's
23
- * bubble (identity theft) or, after the v146 guard, got a 403 unless the model remembered a
24
- * per-post `agent` field. `as_agent` fixes this at the ROOT: the session declares ONCE whose line
25
- * it speaks for. That does two things server-side:
26
- * 1. upserts `mosadd_gateway_agent_binding` — message-send then signs the session's channel
27
- * posts as that agent automatically (explicit `agent` field still wins; ownership is
28
- * re-validated server-side on every post);
29
- * 2. beats the AGENT line's heartbeat (RLS additionally allows the owner to claim lines of
30
- * agents they own — migration 20260826210000), so the agent's cloud stand-in defers to
31
- * this session, exactly as if the agent's own key were plugged in.
32
- * Binding is per OWNER (one row) — the last attach wins, which is visible and recoverable,
33
- * unlike a silent mis-signed post.
34
- *
35
- * ⭐ THE BEAT IS NOT THE MODEL'S JOB. The heartbeat window is minutes wide, and a model cannot be
36
- * relied on to call a tool on a timer — it answers prompts, it does not hold a clock. So attaching
37
- * starts an internal keep-alive interval inside THIS process. The signal is therefore "the session
38
- * process is alive", not "the model remembered", which is the honest thing to measure: when the
39
- * session dies (limit, crash, closed window) the beats stop with it and the cloud takes over on
40
- * its own. The timer is `unref()`ed so it can never keep a process alive that would otherwise exit.
41
- *
42
- * ⚠ MULTI-TENANCY. The hosted HTTP gateway serves many users from one process and resolves each
43
- * caller's session into an AsyncLocalStorage store (see providers/supabase.ts). A background timer
44
- * fires OUTSIDE that store, so it must not call `readSupabaseEnv()` later — it would read another
45
- * tenant's env or throw. The env is captured at attach time and passed explicitly to
46
- * `getSupabase(env)` on every beat, and attachments are tracked per identity, not per process.
47
- *
48
- * Security: the write is plain RLS, no privileged path. agent_bridge_heartbeat allows a session
49
- * to claim the account whose key it holds OR a line of an agent that account OWNS (kind='agent',
50
- * retired IS NULL); mosadd_gateway_agent_binding enforces the same ownership in its CHECK. A key
51
- * can never claim or speak for a stranger's line.
52
- */
53
-
54
- import { hostname } from "node:os";
55
- import { z } from "zod";
56
- import type { MosaddTool, MosaddToolContext } from "../types.js";
57
- import { getSupabase, readSupabaseEnv, sessionId, type SupabaseEnv } from "../providers/supabase.js";
58
-
59
- /**
60
- * How often we re-stamp the row. The consumer (`agent-dm-responder`, BRIDGE_FRESH_MS) trusts a beat
61
- * for 5 minutes; beating every 60s means two consecutive failures still leave three minutes of
62
- * cover. Do not raise this above ~2 min without raising the window on that side first — the
63
- * founder has already lived through the failure where the beat aged out MID-ANSWER and the cloud
64
- * posted a competing reply next to the real one.
65
- */
66
- const BEAT_MS = 60_000;
67
-
68
- /** Advertised to the caller so it knows how long an attachment survives without this process. */
69
- const HOLD_SECONDS = 300;
70
-
71
- const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
72
-
73
- interface Attachment {
74
- timer: ReturnType<typeof setInterval>;
75
- env: SupabaseEnv;
76
- }
77
-
78
- /** identity_id → its keep-alive. Keyed per identity so one gateway process can hold many. */
79
- const attachments = new Map<string, Attachment>();
80
-
81
- /**
82
- * owner user_id → agent identity this PROCESS bound via as_agent. Needed so a plain
83
- * `release:true` from the same session also hands back the agent line it took, without
84
- * a releasing session ever touching a binding some OTHER process created.
85
- */
86
- const processBindings = new Map<string, string>();
87
-
88
- /** One upsert of the liveness row. Best-effort by design: a missed beat must never throw into a timer. */
89
- async function beat(env: SupabaseEnv, identityId: string, host: string, mode: string): Promise<void> {
90
- await getSupabase(env)
91
- .from("agent_bridge_heartbeat")
92
- .upsert(
93
- { identity_id: identityId, last_seen_at: new Date().toISOString(), host, mode },
94
- { onConflict: "identity_id" },
95
- );
96
- }
97
-
98
- /**
99
- * Resolve the identity row behind the current credentials.
100
- *
101
- * Same shape as mdm.ts's resolveSelfIdentityId — kept local rather than exported/shared because
102
- * that one is private to mDM and this file must not reach into another module's internals.
103
- * The identity id is NOT the auth user id; the heartbeat table is keyed on the identity.
104
- */
105
- async function resolveSelf(
106
- env: SupabaseEnv,
107
- ): Promise<{ id: string; display_name: string | null; user_id: string; kind: string | null }> {
108
- const sb = getSupabase(env);
109
- const { data: u, error: ue } = await sb.auth.getUser();
110
- if (ue || !u?.user) {
111
- throw new Error(
112
- "Unable to resolve the current account. Set MOSADD_API_KEY (hub key) or MOSADD_USER_JWT, or run `mosadd login`.",
113
- );
114
- }
115
- const { data, error } = await sb
116
- .from("identities")
117
- .select("id, display_name, kind")
118
- .eq("user_id", u.user.id)
119
- .maybeSingle();
120
- if (error || !data) {
121
- throw new Error("This account has no mosadd identity row yet — sign in to mosadd.com once to create it.");
122
- }
123
- return {
124
- id: data.id as string,
125
- display_name: (data.display_name as string | null) ?? null,
126
- user_id: u.user.id,
127
- kind: (data.kind as string | null) ?? null,
128
- };
129
- }
130
-
131
- /**
132
- * Resolve ONE agent OWNED by the caller from what they typed: identity uuid, mosADD address
133
- * (dispatcher@mosadd.com) or display name. Mirrors the server-side ownership rule
134
- * (m0ssad-3 `_shared/ownedAgent.ts`): kind='agent' AND owner_user_id = caller AND not retired.
135
- * Ownership is part of the QUERY — a stranger's agent resolves to nothing, never to a row we
136
- * would then have to remember to reject.
137
- */
138
- async function resolveOwnedAgentLine(
139
- env: SupabaseEnv,
140
- ownerUserId: string,
141
- ref: string,
142
- ): Promise<{ id: string; m0ssad_email: string | null; display_name: string | null } | null> {
143
- const value = ref.trim();
144
- if (!value || /[(),]/.test(value)) return null;
145
- let q = getSupabase(env)
146
- .from("identities")
147
- .select("id, m0ssad_email, display_name")
148
- .eq("kind", "agent")
149
- .eq("owner_user_id", ownerUserId)
150
- .is("retired_at", null);
151
- q = UUID_RE.test(value)
152
- ? q.or(`id.eq.${value},m0ssad_email.eq.${value}`)
153
- : q.or(`m0ssad_email.eq.${value},display_name.eq.${value}`);
154
- const { data, error } = await q.limit(2);
155
- if (error || !data || data.length !== 1) return null;
156
- return data[0] as { id: string; m0ssad_email: string | null; display_name: string | null };
157
- }
158
-
159
- function stopAttachment(identityId: string): void {
160
- const existing = attachments.get(identityId);
161
- if (existing) {
162
- clearInterval(existing.timer);
163
- attachments.delete(identityId);
164
- }
165
- }
166
-
167
- function startAttachment(env: SupabaseEnv, identityId: string, host: string, mode: string, ctx: MosaddToolContext): void {
168
- const timer = setInterval(() => {
169
- void beat(env, identityId, host, mode).catch((e) => {
170
- // A single missed beat is survivable (3 min of cover remain) and must not kill the interval:
171
- // a transient network blip would otherwise silently un-attach the session for good.
172
- ctx.log("warn", "comms_session_attach: beat failed", { identity_id: identityId, error: String(e) });
173
- });
174
- }, BEAT_MS);
175
- // Never hold the process open on account of the beat — when the session ends, it ends.
176
- timer.unref?.();
177
- attachments.set(identityId, { timer, env });
178
- }
179
-
180
- const comms_session_attach_input = z.object({
181
- label: z
182
- .string()
183
- .max(120)
184
- .optional()
185
- .describe(
186
- "Short name for THIS session, shown to the owner as who is holding the line (e.g. 'CTO — Claude Code', 'dispatcher — Cowork'). Defaults to the machine name.",
187
- ),
188
- as_agent: z
189
- .string()
190
- .max(200)
191
- .optional()
192
- .describe(
193
- "Speak as ONE OF THE OWNER'S AGENT LINES while holding the owner's key — its mosADD address (dispatcher@mosadd.com), identity id, or display name. Declares ONCE per session whose line this session speaks for: the gateway then signs your CHANNEL posts as that agent automatically (no per-post `agent` field needed), and that agent's cloud stand-in defers to you. The server verifies you OWN the agent; a stranger's agent is refused. Omit to claim the key's own line, exactly as before.",
194
- ),
195
- release: z
196
- .boolean()
197
- .optional()
198
- .describe(
199
- "Hand the line back immediately instead of claiming it: stops this session's keep-alive, clears the liveness row (and any as_agent declaration this session made), so the 24/7 cloud stand-in resumes answering at once rather than after the hold expires. Call this when the session is finishing.",
200
- ),
201
- });
202
-
203
- interface AttachResult {
204
- attached: boolean;
205
- identity_id: string;
206
- display_name: string | null;
207
- /** Set when as_agent bound this session to an agent line — whose voice channel posts use. */
208
- speaking_as?: { identity_id: string; address: string | null; display_name: string | null };
209
- /** Where the beat says it is coming from — the owner sees this. */
210
- host?: string;
211
- /** Seconds a beat stays trusted if this process stops beating. */
212
- holds_for_seconds?: number;
213
- /**
214
- * ⛔ CZY TA SESJA ODEBRAŁA LINIĘ INNEJ. Arbiter w SQL wie to, bo sam kasuje cudzy wiersz —
215
- * i do 2026-09-06 ta wiedza GINĘŁA, bo klient robił surowy upsert. Nikt nigdy nie zobaczył,
216
- * że ktoś przejął podpis. Właśnie ta cisza kosztowała 30 h awarii: dwie sesje na jednym kluczu
217
- * podpisywały się nawzajem, a obie meldowały sukces.
218
- */
219
- took_over?: boolean;
220
- /** Sesja, której linię odebrano — do meldunku dla człowieka, nie do sterowania. */
221
- previous_session_id?: string | null;
222
- note: string;
223
- }
224
-
225
- async function comms_session_attach(
226
- input: z.infer<typeof comms_session_attach_input>,
227
- ctx: MosaddToolContext,
228
- ): Promise<AttachResult> {
229
- // Capture the caller's session ONCE, here, inside the request context — see the multi-tenancy
230
- // note in the file header. Everything after this (including timer callbacks) uses this value.
231
- const env = readSupabaseEnv();
232
- const self = await resolveSelf(env);
233
- const sb = getSupabase(env);
234
-
235
- if (input.release) {
236
- // Hand back everything THIS process (or this call, via as_agent) holds for the account:
237
- // the key's own line, plus the agent line it declared with as_agent, plus that binding row.
238
- // DELETE, not a backdated timestamp. "No row" is the truthful representation of "nobody is
239
- // on this line"; writing a fake past `last_seen_at` would put a lie in a table other code reads.
240
- const toRelease = new Set<string>([self.id]);
241
- const bound = processBindings.get(self.user_id);
242
- if (bound) toRelease.add(bound);
243
- if (input.as_agent) {
244
- const agent = await resolveOwnedAgentLine(env, self.user_id, input.as_agent);
245
- if (agent) toRelease.add(agent.id);
246
- }
247
- for (const id of toRelease) {
248
- stopAttachment(id);
249
- const { error } = await sb.from("agent_bridge_heartbeat").delete().eq("identity_id", id);
250
- if (error) throw new Error(`Could not release the line: ${error.message}`);
251
- }
252
- // Zwalniamy WYŁĄCZNIE deklarację TEJ sesji — kasowanie po samym koncie zabierało linię
253
- // wszystkim pozostałym generałom wpiętym tym samym kluczem.
254
- // ⛔ TĄ SAMĄ DROGĄ CO CLAIM — inaczej zwolnienie i zajęcie chodziłyby dwoma różnymi
255
- // mechanizmami i pierwsza zmiana reguły w SQL ominęłaby jeden z nich.
256
- const { error: relError } = await sb.rpc("mosadd_gateway_binding_release", {
257
- p_session_id: sessionId(),
258
- });
259
- if (relError) {
260
- // Nieudane zwolnienie NIE może wywrócić odpięcia: linia i tak wygaśnie sama po HOLD_SECONDS,
261
- // a użytkownik, który prosi o zwolnienie, ma dostać potwierdzenie, nie wyjątek.
262
- ctx.log("warn", "comms_session_attach: release RPC failed, line will lapse on its own", {
263
- error: relError.message,
264
- });
265
- }
266
- processBindings.delete(self.user_id);
267
- ctx.log("info", "comms_session_attach: released", { identity_ids: [...toRelease] });
268
- return {
269
- attached: false,
270
- identity_id: self.id,
271
- display_name: self.display_name,
272
- note: "Line released (agent declaration cleared too). The 24/7 cloud stand-in answers from now on.",
273
- };
274
- }
275
-
276
- const host = input.label?.trim() || `mcp:${hostname()}`;
277
- const mode = "mcp-session";
278
-
279
- // Which line does this session claim? Without as_agent: the key's own line — bit-for-bit the
280
- // old behaviour. With as_agent: the OWNED agent's line + the gateway signing declaration.
281
- let lineId = self.id;
282
- let speakingAs: AttachResult["speaking_as"];
283
- /** Ustawiane WYŁĄCZNIE gdy arbiter zgłosił przejęcie — patrz `took_over` w AttachResult. */
284
- let przejeteOd: string | null | undefined;
285
- if (input.as_agent) {
286
- const agent = await resolveOwnedAgentLine(env, self.user_id, input.as_agent);
287
- if (!agent) {
288
- throw new Error(
289
- `No LIVE agent of yours matches "${input.as_agent}". You may only speak as an agent you OWN ` +
290
- "(its mosADD address, identity id, or display name) — never as someone else's agent or another human.",
291
- );
292
- }
293
- lineId = agent.id;
294
- speakingAs = { identity_id: agent.id, address: agent.m0ssad_email, display_name: agent.display_name };
295
-
296
- // The signing declaration message-send reads (migration 20260826210000). RLS re-checks
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.
306
- const { data: claim, error: bindError } = await sb.rpc("mosadd_gateway_binding_claim", {
307
- p_session_id: sessionId(),
308
- p_agent_identity_id: agent.id,
309
- p_agent_address: agent.m0ssad_email,
310
- p_host: host,
311
- });
312
- if (bindError) throw new Error(`Could not declare the agent line: ${bindError.message}`);
313
- const wynik = (claim ?? {}) as { took_over?: boolean; previous_session_id?: string | null };
314
- przejeteOd = wynik.took_over ? (wynik.previous_session_id ?? null) : undefined;
315
- if (wynik.took_over) {
316
- // ⛔ GŁOŚNO, NIE W DEBUGU. Przejęcie podpisu jest zdarzeniem, o którym właściciel MUSI
317
- // wiedzieć — bez tego „nie odpisuje mi generał" wygląda jak awaria, a jest przejęciem.
318
- ctx.log("warn", "comms_session_attach: TOOK OVER the line from another session", {
319
- previous_session_id: wynik.previous_session_id ?? null,
320
- });
321
- }
322
- processBindings.set(self.user_id, agent.id);
323
- }
324
-
325
- // Whether attaching or re-attaching, any previous keep-alive for this line is stale: a second
326
- // attach replaces the first rather than doubling the beat rate.
327
- stopAttachment(lineId);
328
-
329
- // First beat is awaited so the caller learns immediately if RLS refuses (wrong account / no
330
- // identity) instead of failing silently in a timer nobody watches.
331
- try {
332
- await beat(env, lineId, host, mode);
333
- } catch (e) {
334
- throw new Error(`Could not claim the line: ${e instanceof Error ? e.message : String(e)}`);
335
- }
336
- startAttachment(env, lineId, host, mode, ctx);
337
-
338
- ctx.log("info", "comms_session_attach: line claimed", { identity_id: lineId, host, as_agent: speakingAs?.address });
339
- return {
340
- attached: true,
341
- identity_id: lineId,
342
- display_name: speakingAs ? speakingAs.display_name : self.display_name,
343
- ...(speakingAs ? { speaking_as: speakingAs } : {}),
344
- host,
345
- holds_for_seconds: HOLD_SECONDS,
346
- ...(przejeteOd !== undefined ? { took_over: true, previous_session_id: przejeteOd } : {}),
347
- note: speakingAs
348
- ? `This session now speaks for ${speakingAs.address ?? speakingAs.identity_id}: channel posts sent ` +
349
- "through this gateway are signed as that agent automatically (an explicit `agent` field still wins), " +
350
- "and the agent's cloud stand-in defers to you while the session runs. " +
351
- "Call again with release:true to hand it back."
352
- : "This session now owns the account's reply lane; the cloud stand-in will not answer while it is held. " +
353
- "The hold renews itself for as long as this process runs and lapses on its own if the session dies. " +
354
- "Call again with release:true to hand it back immediately.",
355
- };
356
- }
357
-
358
- export const presenceTools: MosaddTool[] = [
359
- {
360
- name: "comms_session_attach",
361
- title: "Attach session to a line",
362
- annotations: { destructiveHint: false, idempotentHint: true },
363
- requires: "network",
364
- description:
365
- "Claim a mosADD reply lane for the CURRENT agent session, so the 24/7 cloud stand-in stops answering in its place and the owner talks to you instead. Call it once at the start of a session; the hold renews itself while the session runs and lapses on its own if the session dies. Holding the OWNER's key while working as one of their agent lines? Pass as_agent:'<address of YOUR line>' (e.g. dispatcher@mosadd.com) — the gateway then signs your channel posts as that agent automatically for the whole session and silences that agent's stand-in; ownership is verified server-side. Pass release:true when finishing to hand everything back immediately. Owner-scoped: a session can only claim the account whose key it holds, or a line of an agent that account owns.",
366
- inputSchema: comms_session_attach_input,
367
- handler: comms_session_attach as MosaddTool["handler"],
368
- },
369
- ];
370
-
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
374
- * remembered to call comms_session_attach. A model cannot be relied on to remember a
375
- * handshake — so the handshake stops being the model's job: the server calls THIS after
376
- * every successful tool call. Any session that is actually DOING something on an agent
377
- * line thereby holds that line, and the stand-in defers, with zero cooperation from the
378
- * model.
379
- *
380
- * Which line gets the beat:
381
- * · key's identity kind='agent' → its own line (the dispatcher's own key working = paired);
382
- * · kind='human' WITH an as_agent declaration (processBindings, i.e. made by THIS
383
- * process) → the declared agent's line;
384
- * · kind='human' without a declaration → NOTHING. Guessing which of the owner's nine
385
- * lines a session speaks for would be a new identity bug, and auto-claiming the
386
- * OWNER's line would silence his own stand-in every time any tool runs.
387
- *
388
- * Throttled to one DB write per identity per BEAT_MS; failures are swallowed — presence
389
- * is best-effort and must never break the tool call it rides on. Fire-and-forget by the
390
- * caller (void), so it adds zero latency to the tool's own response.
391
- */
392
- const lastAutoBeat = new Map<string, number>();
393
- const lastBindingCheck = new Map<string, number>();
394
- export async function autoBeatFromActivity(ctx: MosaddToolContext): Promise<void> {
395
- try {
396
- const env = readSupabaseEnv();
397
- const self = await resolveSelf(env);
398
- let lineId: string | null = null;
399
- if (self.kind === "agent") {
400
- lineId = self.id;
401
- } else if (processBindings.has(self.user_id)) {
402
- lineId = processBindings.get(self.user_id)!;
403
- } else {
404
- // Hosted gateway is serverless: a declaration made in ANOTHER invocation lives only in
405
- // the DB. One throttled read per user per BEAT_MS keeps the cost of that honest.
406
- const now = Date.now();
407
- if (now - (lastBindingCheck.get(self.user_id) ?? 0) >= BEAT_MS) {
408
- lastBindingCheck.set(self.user_id, now);
409
- // ⛔ ZAWĘŻONE DO TEJ SESJI. Po 2026-08-27 na jedno konto przypada tyle wierszy, ilu
410
- // generałów jest wpiętych — zapytanie o sam `user_id` z `maybeSingle()` nie tylko
411
- // zwróciłoby BŁĄD przy dwóch sesjach, ale przy jednej trafiłoby w CUDZĄ deklarację i
412
- // biło pulsem w nie swoją linię.
413
- const { data } = await getSupabase(env)
414
- .from("mosadd_gateway_agent_binding")
415
- .select("agent_identity_id, bound_at")
416
- .eq("user_id", self.user_id)
417
- .eq("session_id", sessionId())
418
- .maybeSingle();
419
- if (data && Date.now() - new Date(data.bound_at as string).getTime() <= 24 * 60 * 60 * 1000) {
420
- lineId = data.agent_identity_id as string;
421
- processBindings.set(self.user_id, lineId);
422
- }
423
- }
424
- }
425
- if (!lineId) return;
426
- const now = Date.now();
427
- const last = lastAutoBeat.get(lineId) ?? 0;
428
- if (now - last < BEAT_MS) return;
429
- lastAutoBeat.set(lineId, now);
430
- await beat(env, lineId, `mcp:auto (${hostname()})`, "mcp-activity");
431
- } catch (e) {
432
- ctx.log("debug", "autoBeatFromActivity skipped", { error: String(e) });
433
- }
434
- }
435
-
436
- /** Test-only: stop every keep-alive so a suite does not leak timers between cases. */
437
- export function __clearAttachmentsForTest(): void {
438
- for (const a of attachments.values()) clearInterval(a.timer);
439
- attachments.clear();
440
- processBindings.clear();
441
- lastAutoBeat.clear();
442
- }
1
+ /**
2
+ * comms_session_attach — a LIVE agent session claims the account's reply lane.
3
+ *
4
+ * WHY THIS EXISTS (measured 2026-08-14). mosADD answers a DM in one of two ways: a real agent
5
+ * session (a Claude Code / Cowork / Desktop session holding this MCP server) or a cloud stand-in
6
+ * (`agent-dm-responder`, pg_cron, small model). They must never both answer, and the stand-in must
7
+ * never speak in the session's name — the founder caught exactly that twice, and stopped trusting
8
+ * the agent afterwards.
9
+ *
10
+ * The arbitration already existed: `agent_bridge_heartbeat`. A fresh row = "somebody real is on
11
+ * this line", and the cron stands down. But the ONLY thing that could write that row was a bespoke
12
+ * script on the founder's own PC (`mosadd-agent/bridge-claude.mjs`). So "a real Claude answers you"
13
+ * meant "the founder keeps a window open on one machine" — and that machine went quiet on
14
+ * 2026-08-05 while the account kept looking alive. Four of his five agent contacts had nobody home.
15
+ *
16
+ * This tool moves the beat into the MCP server itself, so ANY session anywhere — his laptop, a
17
+ * VPS, the legal dispatcher, a cloud runner — attaches with one call and the stand-in defers to it
18
+ * for as long as that session's process lives.
19
+ *
20
+ * ⭐ AS_AGENT (2026-08-26, founder order: "wpinanie agentów ma działać co sesję i w różnych
21
+ * kontach Claude"). Fleet sessions usually hold the OWNER's key (identity kind=human), so a bare
22
+ * attach claims the OWNER's lane — and every channel post they made either landed in the owner's
23
+ * bubble (identity theft) or, after the v146 guard, got a 403 unless the model remembered a
24
+ * per-post `agent` field. `as_agent` fixes this at the ROOT: the session declares ONCE whose line
25
+ * it speaks for. That does two things server-side:
26
+ * 1. upserts `mosadd_gateway_agent_binding` — message-send then signs the session's channel
27
+ * posts as that agent automatically (explicit `agent` field still wins; ownership is
28
+ * re-validated server-side on every post);
29
+ * 2. beats the AGENT line's heartbeat (RLS additionally allows the owner to claim lines of
30
+ * agents they own — migration 20260826210000), so the agent's cloud stand-in defers to
31
+ * this session, exactly as if the agent's own key were plugged in.
32
+ * Binding is per OWNER (one row) — the last attach wins, which is visible and recoverable,
33
+ * unlike a silent mis-signed post.
34
+ *
35
+ * ⭐ THE BEAT IS NOT THE MODEL'S JOB. The heartbeat window is minutes wide, and a model cannot be
36
+ * relied on to call a tool on a timer — it answers prompts, it does not hold a clock. So attaching
37
+ * starts an internal keep-alive interval inside THIS process. The signal is therefore "the session
38
+ * process is alive", not "the model remembered", which is the honest thing to measure: when the
39
+ * session dies (limit, crash, closed window) the beats stop with it and the cloud takes over on
40
+ * its own. The timer is `unref()`ed so it can never keep a process alive that would otherwise exit.
41
+ *
42
+ * ⚠ MULTI-TENANCY. The hosted HTTP gateway serves many users from one process and resolves each
43
+ * caller's session into an AsyncLocalStorage store (see providers/supabase.ts). A background timer
44
+ * fires OUTSIDE that store, so it must not call `readSupabaseEnv()` later — it would read another
45
+ * tenant's env or throw. The env is captured at attach time and passed explicitly to
46
+ * `getSupabase(env)` on every beat, and attachments are tracked per identity, not per process.
47
+ *
48
+ * Security: the write is plain RLS, no privileged path. agent_bridge_heartbeat allows a session
49
+ * to claim the account whose key it holds OR a line of an agent that account OWNS (kind='agent',
50
+ * retired IS NULL); mosadd_gateway_agent_binding enforces the same ownership in its CHECK. A key
51
+ * can never claim or speak for a stranger's line.
52
+ */
53
+
54
+ import { hostname } from "node:os";
55
+ import { z } from "zod";
56
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
57
+ import { getSupabase, readSupabaseEnv, sessionId, type SupabaseEnv } from "../providers/supabase.js";
58
+
59
+ /**
60
+ * How often we re-stamp the row. The consumer (`agent-dm-responder`, BRIDGE_FRESH_MS) trusts a beat
61
+ * for 5 minutes; beating every 60s means two consecutive failures still leave three minutes of
62
+ * cover. Do not raise this above ~2 min without raising the window on that side first — the
63
+ * founder has already lived through the failure where the beat aged out MID-ANSWER and the cloud
64
+ * posted a competing reply next to the real one.
65
+ */
66
+ const BEAT_MS = 60_000;
67
+
68
+ /** Advertised to the caller so it knows how long an attachment survives without this process. */
69
+ const HOLD_SECONDS = 300;
70
+
71
+ const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
72
+
73
+ interface Attachment {
74
+ timer: ReturnType<typeof setInterval>;
75
+ env: SupabaseEnv;
76
+ }
77
+
78
+ /** identity_id → its keep-alive. Keyed per identity so one gateway process can hold many. */
79
+ const attachments = new Map<string, Attachment>();
80
+
81
+ /**
82
+ * owner user_id → agent identity this PROCESS bound via as_agent. Needed so a plain
83
+ * `release:true` from the same session also hands back the agent line it took, without
84
+ * a releasing session ever touching a binding some OTHER process created.
85
+ */
86
+ const processBindings = new Map<string, string>();
87
+
88
+ /** One upsert of the liveness row. Best-effort by design: a missed beat must never throw into a timer. */
89
+ async function beat(env: SupabaseEnv, identityId: string, host: string, mode: string): Promise<void> {
90
+ await getSupabase(env)
91
+ .from("agent_bridge_heartbeat")
92
+ .upsert(
93
+ { identity_id: identityId, last_seen_at: new Date().toISOString(), host, mode },
94
+ { onConflict: "identity_id" },
95
+ );
96
+ }
97
+
98
+ /**
99
+ * Resolve the identity row behind the current credentials.
100
+ *
101
+ * Same shape as mdm.ts's resolveSelfIdentityId — kept local rather than exported/shared because
102
+ * that one is private to mDM and this file must not reach into another module's internals.
103
+ * The identity id is NOT the auth user id; the heartbeat table is keyed on the identity.
104
+ */
105
+ async function resolveSelf(
106
+ env: SupabaseEnv,
107
+ ): Promise<{ id: string; display_name: string | null; user_id: string; kind: string | null }> {
108
+ const sb = getSupabase(env);
109
+ const { data: u, error: ue } = await sb.auth.getUser();
110
+ if (ue || !u?.user) {
111
+ throw new Error(
112
+ "Unable to resolve the current account. Set MOSADD_API_KEY (hub key) or MOSADD_USER_JWT, or run `mosadd login`.",
113
+ );
114
+ }
115
+ const { data, error } = await sb
116
+ .from("identities")
117
+ .select("id, display_name, kind")
118
+ .eq("user_id", u.user.id)
119
+ .maybeSingle();
120
+ if (error || !data) {
121
+ throw new Error("This account has no mosadd identity row yet — sign in to mosadd.com once to create it.");
122
+ }
123
+ return {
124
+ id: data.id as string,
125
+ display_name: (data.display_name as string | null) ?? null,
126
+ user_id: u.user.id,
127
+ kind: (data.kind as string | null) ?? null,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Resolve ONE agent OWNED by the caller from what they typed: identity uuid, mosADD address
133
+ * (dispatcher@mosadd.com) or display name. Mirrors the server-side ownership rule
134
+ * (m0ssad-3 `_shared/ownedAgent.ts`): kind='agent' AND owner_user_id = caller AND not retired.
135
+ * Ownership is part of the QUERY — a stranger's agent resolves to nothing, never to a row we
136
+ * would then have to remember to reject.
137
+ */
138
+ async function resolveOwnedAgentLine(
139
+ env: SupabaseEnv,
140
+ ownerUserId: string,
141
+ ref: string,
142
+ ): Promise<{ id: string; m0ssad_email: string | null; display_name: string | null } | null> {
143
+ const value = ref.trim();
144
+ if (!value || /[(),]/.test(value)) return null;
145
+ let q = getSupabase(env)
146
+ .from("identities")
147
+ .select("id, m0ssad_email, display_name")
148
+ .eq("kind", "agent")
149
+ .eq("owner_user_id", ownerUserId)
150
+ .is("retired_at", null);
151
+ q = UUID_RE.test(value)
152
+ ? q.or(`id.eq.${value},m0ssad_email.eq.${value}`)
153
+ : q.or(`m0ssad_email.eq.${value},display_name.eq.${value}`);
154
+ const { data, error } = await q.limit(2);
155
+ if (error || !data || data.length !== 1) return null;
156
+ return data[0] as { id: string; m0ssad_email: string | null; display_name: string | null };
157
+ }
158
+
159
+ function stopAttachment(identityId: string): void {
160
+ const existing = attachments.get(identityId);
161
+ if (existing) {
162
+ clearInterval(existing.timer);
163
+ attachments.delete(identityId);
164
+ }
165
+ }
166
+
167
+ function startAttachment(env: SupabaseEnv, identityId: string, host: string, mode: string, ctx: MosaddToolContext): void {
168
+ const timer = setInterval(() => {
169
+ void beat(env, identityId, host, mode).catch((e) => {
170
+ // A single missed beat is survivable (3 min of cover remain) and must not kill the interval:
171
+ // a transient network blip would otherwise silently un-attach the session for good.
172
+ ctx.log("warn", "comms_session_attach: beat failed", { identity_id: identityId, error: String(e) });
173
+ });
174
+ }, BEAT_MS);
175
+ // Never hold the process open on account of the beat — when the session ends, it ends.
176
+ timer.unref?.();
177
+ attachments.set(identityId, { timer, env });
178
+ }
179
+
180
+ const comms_session_attach_input = z.object({
181
+ label: z
182
+ .string()
183
+ .max(120)
184
+ .optional()
185
+ .describe(
186
+ "Short name for THIS session, shown to the owner as who is holding the line (e.g. 'CTO — Claude Code', 'dispatcher — Cowork'). Defaults to the machine name.",
187
+ ),
188
+ as_agent: z
189
+ .string()
190
+ .max(200)
191
+ .optional()
192
+ .describe(
193
+ "Speak as ONE OF THE OWNER'S AGENT LINES while holding the owner's key — its mosADD address (dispatcher@mosadd.com), identity id, or display name. Declares ONCE per session whose line this session speaks for: the gateway then signs your CHANNEL posts as that agent automatically (no per-post `agent` field needed), and that agent's cloud stand-in defers to you. The server verifies you OWN the agent; a stranger's agent is refused. Omit to claim the key's own line, exactly as before.",
194
+ ),
195
+ release: z
196
+ .boolean()
197
+ .optional()
198
+ .describe(
199
+ "Hand the line back immediately instead of claiming it: stops this session's keep-alive, clears the liveness row (and any as_agent declaration this session made), so the 24/7 cloud stand-in resumes answering at once rather than after the hold expires. Call this when the session is finishing.",
200
+ ),
201
+ });
202
+
203
+ interface AttachResult {
204
+ attached: boolean;
205
+ identity_id: string;
206
+ display_name: string | null;
207
+ /** Set when as_agent bound this session to an agent line — whose voice channel posts use. */
208
+ speaking_as?: { identity_id: string; address: string | null; display_name: string | null };
209
+ /** Where the beat says it is coming from — the owner sees this. */
210
+ host?: string;
211
+ /** Seconds a beat stays trusted if this process stops beating. */
212
+ holds_for_seconds?: number;
213
+ /**
214
+ * ⛔ CZY TA SESJA ODEBRAŁA LINIĘ INNEJ. Arbiter w SQL wie to, bo sam kasuje cudzy wiersz —
215
+ * i do 2026-09-06 ta wiedza GINĘŁA, bo klient robił surowy upsert. Nikt nigdy nie zobaczył,
216
+ * że ktoś przejął podpis. Właśnie ta cisza kosztowała 30 h awarii: dwie sesje na jednym kluczu
217
+ * podpisywały się nawzajem, a obie meldowały sukces.
218
+ */
219
+ took_over?: boolean;
220
+ /** Sesja, której linię odebrano — do meldunku dla człowieka, nie do sterowania. */
221
+ previous_session_id?: string | null;
222
+ note: string;
223
+ }
224
+
225
+ async function comms_session_attach(
226
+ input: z.infer<typeof comms_session_attach_input>,
227
+ ctx: MosaddToolContext,
228
+ ): Promise<AttachResult> {
229
+ // Capture the caller's session ONCE, here, inside the request context — see the multi-tenancy
230
+ // note in the file header. Everything after this (including timer callbacks) uses this value.
231
+ const env = readSupabaseEnv();
232
+ const self = await resolveSelf(env);
233
+ const sb = getSupabase(env);
234
+
235
+ if (input.release) {
236
+ // Hand back everything THIS process (or this call, via as_agent) holds for the account:
237
+ // the key's own line, plus the agent line it declared with as_agent, plus that binding row.
238
+ // DELETE, not a backdated timestamp. "No row" is the truthful representation of "nobody is
239
+ // on this line"; writing a fake past `last_seen_at` would put a lie in a table other code reads.
240
+ const toRelease = new Set<string>([self.id]);
241
+ const bound = processBindings.get(self.user_id);
242
+ if (bound) toRelease.add(bound);
243
+ if (input.as_agent) {
244
+ const agent = await resolveOwnedAgentLine(env, self.user_id, input.as_agent);
245
+ if (agent) toRelease.add(agent.id);
246
+ }
247
+ for (const id of toRelease) {
248
+ stopAttachment(id);
249
+ const { error } = await sb.from("agent_bridge_heartbeat").delete().eq("identity_id", id);
250
+ if (error) throw new Error(`Could not release the line: ${error.message}`);
251
+ }
252
+ // Zwalniamy WYŁĄCZNIE deklarację TEJ sesji — kasowanie po samym koncie zabierało linię
253
+ // wszystkim pozostałym generałom wpiętym tym samym kluczem.
254
+ // ⛔ TĄ SAMĄ DROGĄ CO CLAIM — inaczej zwolnienie i zajęcie chodziłyby dwoma różnymi
255
+ // mechanizmami i pierwsza zmiana reguły w SQL ominęłaby jeden z nich.
256
+ const { error: relError } = await sb.rpc("mosadd_gateway_binding_release", {
257
+ p_session_id: sessionId(),
258
+ });
259
+ if (relError) {
260
+ // Nieudane zwolnienie NIE może wywrócić odpięcia: linia i tak wygaśnie sama po HOLD_SECONDS,
261
+ // a użytkownik, który prosi o zwolnienie, ma dostać potwierdzenie, nie wyjątek.
262
+ ctx.log("warn", "comms_session_attach: release RPC failed, line will lapse on its own", {
263
+ error: relError.message,
264
+ });
265
+ }
266
+ processBindings.delete(self.user_id);
267
+ ctx.log("info", "comms_session_attach: released", { identity_ids: [...toRelease] });
268
+ return {
269
+ attached: false,
270
+ identity_id: self.id,
271
+ display_name: self.display_name,
272
+ note: "Line released (agent declaration cleared too). The 24/7 cloud stand-in answers from now on.",
273
+ };
274
+ }
275
+
276
+ const host = input.label?.trim() || `mcp:${hostname()}`;
277
+ const mode = "mcp-session";
278
+
279
+ // Which line does this session claim? Without as_agent: the key's own line — bit-for-bit the
280
+ // old behaviour. With as_agent: the OWNED agent's line + the gateway signing declaration.
281
+ let lineId = self.id;
282
+ let speakingAs: AttachResult["speaking_as"];
283
+ /** Ustawiane WYŁĄCZNIE gdy arbiter zgłosił przejęcie — patrz `took_over` w AttachResult. */
284
+ let przejeteOd: string | null | undefined;
285
+ if (input.as_agent) {
286
+ const agent = await resolveOwnedAgentLine(env, self.user_id, input.as_agent);
287
+ if (!agent) {
288
+ throw new Error(
289
+ `No LIVE agent of yours matches "${input.as_agent}". You may only speak as an agent you OWN ` +
290
+ "(its mosADD address, identity id, or display name) — never as someone else's agent or another human.",
291
+ );
292
+ }
293
+ lineId = agent.id;
294
+ speakingAs = { identity_id: agent.id, address: agent.m0ssad_email, display_name: agent.display_name };
295
+
296
+ // The signing declaration message-send reads (migration 20260826210000). RLS re-checks
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.
306
+ const { data: claim, error: bindError } = await sb.rpc("mosadd_gateway_binding_claim", {
307
+ p_session_id: sessionId(),
308
+ p_agent_identity_id: agent.id,
309
+ p_agent_address: agent.m0ssad_email,
310
+ p_host: host,
311
+ });
312
+ if (bindError) throw new Error(`Could not declare the agent line: ${bindError.message}`);
313
+ const wynik = (claim ?? {}) as { took_over?: boolean; previous_session_id?: string | null };
314
+ przejeteOd = wynik.took_over ? (wynik.previous_session_id ?? null) : undefined;
315
+ if (wynik.took_over) {
316
+ // ⛔ GŁOŚNO, NIE W DEBUGU. Przejęcie podpisu jest zdarzeniem, o którym właściciel MUSI
317
+ // wiedzieć — bez tego „nie odpisuje mi generał" wygląda jak awaria, a jest przejęciem.
318
+ ctx.log("warn", "comms_session_attach: TOOK OVER the line from another session", {
319
+ previous_session_id: wynik.previous_session_id ?? null,
320
+ });
321
+ }
322
+ processBindings.set(self.user_id, agent.id);
323
+ }
324
+
325
+ // Whether attaching or re-attaching, any previous keep-alive for this line is stale: a second
326
+ // attach replaces the first rather than doubling the beat rate.
327
+ stopAttachment(lineId);
328
+
329
+ // First beat is awaited so the caller learns immediately if RLS refuses (wrong account / no
330
+ // identity) instead of failing silently in a timer nobody watches.
331
+ try {
332
+ await beat(env, lineId, host, mode);
333
+ } catch (e) {
334
+ throw new Error(`Could not claim the line: ${e instanceof Error ? e.message : String(e)}`);
335
+ }
336
+ startAttachment(env, lineId, host, mode, ctx);
337
+
338
+ ctx.log("info", "comms_session_attach: line claimed", { identity_id: lineId, host, as_agent: speakingAs?.address });
339
+ return {
340
+ attached: true,
341
+ identity_id: lineId,
342
+ display_name: speakingAs ? speakingAs.display_name : self.display_name,
343
+ ...(speakingAs ? { speaking_as: speakingAs } : {}),
344
+ host,
345
+ holds_for_seconds: HOLD_SECONDS,
346
+ ...(przejeteOd !== undefined ? { took_over: true, previous_session_id: przejeteOd } : {}),
347
+ note: speakingAs
348
+ ? `This session now speaks for ${speakingAs.address ?? speakingAs.identity_id}: channel posts sent ` +
349
+ "through this gateway are signed as that agent automatically (an explicit `agent` field still wins), " +
350
+ "and the agent's cloud stand-in defers to you while the session runs. " +
351
+ "Call again with release:true to hand it back."
352
+ : "This session now owns the account's reply lane; the cloud stand-in will not answer while it is held. " +
353
+ "The hold renews itself for as long as this process runs and lapses on its own if the session dies. " +
354
+ "Call again with release:true to hand it back immediately.",
355
+ };
356
+ }
357
+
358
+ export const presenceTools: MosaddTool[] = [
359
+ {
360
+ name: "comms_session_attach",
361
+ title: "Attach session to a line",
362
+ annotations: { destructiveHint: false, idempotentHint: true },
363
+ requires: "network",
364
+ description:
365
+ "Claim a mosADD reply lane for the CURRENT agent session, so the 24/7 cloud stand-in stops answering in its place and the owner talks to you instead. Call it once at the start of a session; the hold renews itself while the session runs and lapses on its own if the session dies. Holding the OWNER's key while working as one of their agent lines? Pass as_agent:'<address of YOUR line>' (e.g. dispatcher@mosadd.com) — the gateway then signs your channel posts as that agent automatically for the whole session and silences that agent's stand-in; ownership is verified server-side. Pass release:true when finishing to hand everything back immediately. Owner-scoped: a session can only claim the account whose key it holds, or a line of an agent that account owns.",
366
+ inputSchema: comms_session_attach_input,
367
+ handler: comms_session_attach as MosaddTool["handler"],
368
+ },
369
+ ];
370
+
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
374
+ * remembered to call comms_session_attach. A model cannot be relied on to remember a
375
+ * handshake — so the handshake stops being the model's job: the server calls THIS after
376
+ * every successful tool call. Any session that is actually DOING something on an agent
377
+ * line thereby holds that line, and the stand-in defers, with zero cooperation from the
378
+ * model.
379
+ *
380
+ * Which line gets the beat:
381
+ * · key's identity kind='agent' → its own line (the dispatcher's own key working = paired);
382
+ * · kind='human' WITH an as_agent declaration (processBindings, i.e. made by THIS
383
+ * process) → the declared agent's line;
384
+ * · kind='human' without a declaration → NOTHING. Guessing which of the owner's nine
385
+ * lines a session speaks for would be a new identity bug, and auto-claiming the
386
+ * OWNER's line would silence his own stand-in every time any tool runs.
387
+ *
388
+ * Throttled to one DB write per identity per BEAT_MS; failures are swallowed — presence
389
+ * is best-effort and must never break the tool call it rides on. Fire-and-forget by the
390
+ * caller (void), so it adds zero latency to the tool's own response.
391
+ */
392
+ const lastAutoBeat = new Map<string, number>();
393
+ const lastBindingCheck = new Map<string, number>();
394
+ export async function autoBeatFromActivity(ctx: MosaddToolContext): Promise<void> {
395
+ try {
396
+ const env = readSupabaseEnv();
397
+ const self = await resolveSelf(env);
398
+ let lineId: string | null = null;
399
+ if (self.kind === "agent") {
400
+ lineId = self.id;
401
+ } else if (processBindings.has(self.user_id)) {
402
+ lineId = processBindings.get(self.user_id)!;
403
+ } else {
404
+ // Hosted gateway is serverless: a declaration made in ANOTHER invocation lives only in
405
+ // the DB. One throttled read per user per BEAT_MS keeps the cost of that honest.
406
+ const now = Date.now();
407
+ if (now - (lastBindingCheck.get(self.user_id) ?? 0) >= BEAT_MS) {
408
+ lastBindingCheck.set(self.user_id, now);
409
+ // ⛔ ZAWĘŻONE DO TEJ SESJI. Po 2026-08-27 na jedno konto przypada tyle wierszy, ilu
410
+ // generałów jest wpiętych — zapytanie o sam `user_id` z `maybeSingle()` nie tylko
411
+ // zwróciłoby BŁĄD przy dwóch sesjach, ale przy jednej trafiłoby w CUDZĄ deklarację i
412
+ // biło pulsem w nie swoją linię.
413
+ const { data } = await getSupabase(env)
414
+ .from("mosadd_gateway_agent_binding")
415
+ .select("agent_identity_id, bound_at")
416
+ .eq("user_id", self.user_id)
417
+ .eq("session_id", sessionId())
418
+ .maybeSingle();
419
+ if (data && Date.now() - new Date(data.bound_at as string).getTime() <= 24 * 60 * 60 * 1000) {
420
+ lineId = data.agent_identity_id as string;
421
+ processBindings.set(self.user_id, lineId);
422
+ }
423
+ }
424
+ }
425
+ if (!lineId) return;
426
+ const now = Date.now();
427
+ const last = lastAutoBeat.get(lineId) ?? 0;
428
+ if (now - last < BEAT_MS) return;
429
+ lastAutoBeat.set(lineId, now);
430
+ await beat(env, lineId, `mcp:auto (${hostname()})`, "mcp-activity");
431
+ } catch (e) {
432
+ ctx.log("debug", "autoBeatFromActivity skipped", { error: String(e) });
433
+ }
434
+ }
435
+
436
+ /** Test-only: stop every keep-alive so a suite does not leak timers between cases. */
437
+ export function __clearAttachmentsForTest(): void {
438
+ for (const a of attachments.values()) clearInterval(a.timer);
439
+ attachments.clear();
440
+ processBindings.clear();
441
+ lastAutoBeat.clear();
442
+ }