@mosadd/mcp 3.0.0-alpha.31 → 3.0.0-alpha.33

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 (53) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +11 -11
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-P4ENU5MW.js → chunk-IWLN5EO5.js} +665 -140
  5. package/dist/index.js +1 -1
  6. package/package.json +15 -15
  7. package/src/__tests__/golden-path.test.ts +137 -137
  8. package/src/__tests__/integration.test.ts +179 -179
  9. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  10. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  11. package/src/__tests__/mtalk.test.ts +122 -122
  12. package/src/__tests__/presence.test.ts +141 -0
  13. package/src/__tests__/server.test.ts +71 -71
  14. package/src/__tests__/tool-count-consistency.test.ts +164 -0
  15. package/src/bin/login.ts +138 -138
  16. package/src/bin/mcp.ts +145 -145
  17. package/src/config.ts +66 -66
  18. package/src/crypto/mdm-session.ts +502 -502
  19. package/src/index.ts +19 -19
  20. package/src/observability/sentry.ts +79 -79
  21. package/src/providers/blob-upload.ts +116 -116
  22. package/src/providers/memory-voice.ts +79 -79
  23. package/src/providers/supabase-dm.ts +122 -122
  24. package/src/providers/supabase-voice.ts +91 -91
  25. package/src/providers/supabase.ts +148 -148
  26. package/src/server.ts +1 -1
  27. package/src/tools/actions.ts +162 -162
  28. package/src/tools/attachments.ts +268 -268
  29. package/src/tools/capabilities.ts +68 -68
  30. package/src/tools/embed.ts +108 -108
  31. package/src/tools/index.ts +173 -104
  32. package/src/tools/knowledge-graph.ts +178 -0
  33. package/src/tools/knowledge.ts +319 -191
  34. package/src/tools/mail-agentbox.ts +147 -0
  35. package/src/tools/mail-aliases.ts +25 -25
  36. package/src/tools/mail-provenance.ts +135 -135
  37. package/src/tools/mail.ts +381 -381
  38. package/src/tools/mdm.ts +476 -479
  39. package/src/tools/mirc-edge.ts +190 -190
  40. package/src/tools/mirc-members.ts +5 -5
  41. package/src/tools/mirc-messages.ts +155 -155
  42. package/src/tools/mirc.ts +63 -3
  43. package/src/tools/mroom-messages.ts +142 -142
  44. package/src/tools/mroom.ts +221 -221
  45. package/src/tools/mtalk.ts +121 -121
  46. package/src/tools/murl.ts +4 -2
  47. package/src/tools/presence.ts +208 -0
  48. package/src/types.ts +94 -94
  49. package/src/voice/floor.ts +132 -132
  50. package/LICENSE +0 -201
  51. package/dist/bin/login.d.ts +0 -13
  52. package/dist/bin/mcp.d.ts +0 -1
  53. package/dist/index.d.ts +0 -266
@@ -416,21 +416,19 @@ async function resolveSelfIdentityId() {
416
416
  }
417
417
  return identity.id;
418
418
  }
419
- function packPlaintextPayload(text, replyToId) {
420
- const envelope = {
421
- v: PROTOCOL_VERSION,
422
- type: "text",
423
- text,
424
- reply_to: replyToId ?? null,
425
- sent_at: (/* @__PURE__ */ new Date()).toISOString()
426
- };
427
- return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
419
+ function packPlaintextPayload(text) {
420
+ return new Uint8Array(Buffer.from(text, "utf8"));
428
421
  }
429
422
  function unpackPayload(payload) {
430
423
  try {
431
- const json = Buffer.from(payload).toString("utf8");
432
- const obj = JSON.parse(json);
433
- if (typeof obj?.text === "string") return obj;
424
+ const raw = Buffer.from(payload).toString("utf8");
425
+ try {
426
+ const obj = JSON.parse(raw);
427
+ if (typeof obj?.text === "string") return obj;
428
+ } catch {
429
+ return { text: raw };
430
+ }
431
+ return { text: raw };
434
432
  } catch {
435
433
  }
436
434
  return { text: "<ciphertext>" };
@@ -786,17 +784,20 @@ var ChannelId = z3.string().min(1).max(120).describe("Channel id (UUID). Use mIR
786
784
  var AccessMode = z3.enum(["open", "password", "private"]).describe("open: anyone can join \xB7 password: join with a shared password \xB7 private: invite-only.");
787
785
  var Capabilities = z3.object({
788
786
  txt: z3.boolean().default(true),
787
+ voice: z3.boolean().default(false),
788
+ files: z3.boolean().default(false),
789
789
  ptt: z3.boolean().default(false),
790
790
  live: z3.boolean().default(false)
791
- }).describe("Which modes are enabled in this channel: txt (text), ptt (push-to-talk voice), live (live stream).").optional();
791
+ }).describe("Which modes are enabled: txt (text), voice (group voice), files (file attach), ptt (push-to-talk), live (live stream). Voice/PTT/live are server-relayed via LiveKit \u2014 NOT end-to-end encrypted.").optional();
792
792
  var mIRC_create_input = z3.object({
793
793
  name: z3.string().min(1).max(80).describe("Channel display name."),
794
794
  topic: z3.string().max(500).optional().describe("Optional channel topic/description."),
795
795
  access_mode: AccessMode.default("open"),
796
796
  password: z3.string().min(6).max(120).optional().describe("Password (only for access_mode=password)."),
797
797
  capabilities: Capabilities,
798
+ discoverable: z3.boolean().optional().describe("List this channel in the PUBLIC directory (mIRC_discover). Honoured ONLY for access_mode=open; ignored for password/private."),
798
799
  wrapped_group_key: z3.string().optional().describe(
799
- "Required for access_mode=password|private (these are E2EE channels): the channel's group key wrapped to the creator's identity key. Open channels ignore it. If omitted on a non-open channel the backend rejects the call with a 'wrapped_group_key required' error."
800
+ "Required for access_mode=password|private (these channels are provisioned for group-key text encryption on supported clients): the channel's group key wrapped to the creator's identity key. Open channels ignore it. If omitted on a non-open channel the backend rejects the call with a 'wrapped_group_key required' error."
800
801
  )
801
802
  });
802
803
  var mIRC_list_input = z3.object({
@@ -816,7 +817,18 @@ var mIRC_update_input = z3.object({
816
817
  // NOTE: access_mode was removed — channel-manage's update branch ignores it, and
817
818
  // switching an existing channel to/from an E2EE (password/private) mode needs
818
819
  // group-key handling that isn't wired yet. Recreate the channel to change mode.
819
- capabilities: Capabilities
820
+ capabilities: Capabilities,
821
+ discoverable: z3.boolean().optional().describe("Toggle public-directory listing (open channels only).")
822
+ });
823
+ var mIRC_discover_input = z3.object({
824
+ q: z3.string().max(100).optional().describe("Optional channel-name filter."),
825
+ limit: z3.number().int().min(1).max(500).default(50).optional(),
826
+ offset: z3.number().int().min(0).default(0).optional()
827
+ });
828
+ var mIRC_report_input = z3.object({
829
+ channel_id: ChannelId,
830
+ reason: z3.enum(["spam", "abuse", "harassment", "illegal", "other"]).describe("Report reason."),
831
+ detail: z3.string().max(1e3).optional().describe("Optional free-text context.")
820
832
  });
821
833
  var mIRC_delete_input = z3.object({
822
834
  channel_id: ChannelId
@@ -866,11 +878,28 @@ async function mIRC_delete(input, ctx) {
866
878
  });
867
879
  return { deleted: true };
868
880
  }
881
+ async function mIRC_discover(input, ctx) {
882
+ readSupabaseEnv();
883
+ ctx.log("debug", "mIRC_discover invoking channel-manage");
884
+ return await invokeFunction("channel-manage", {
885
+ action: "discover",
886
+ ...input
887
+ });
888
+ }
889
+ async function mIRC_report(input, ctx) {
890
+ readSupabaseEnv();
891
+ ctx.log("debug", "mIRC_report invoking report-content", { channel_id: input.channel_id });
892
+ return await invokeFunction("report-content", {
893
+ thread_id: `channel:${input.channel_id}`,
894
+ reason: input.reason,
895
+ detail: input.detail
896
+ });
897
+ }
869
898
  var mircTools = [
870
899
  {
871
900
  name: "mIRC_create",
872
901
  requires: "network",
873
- description: "Create a new persistent channel (Discord/Slack-style). Set access_mode to open (anyone joins), password (shared-password gated), or private (invite-only). capabilities controls modes (txt/ptt/live). NOTE: password and private channels are end-to-end encrypted \u2014 you must supply wrapped_group_key (the group key wrapped to your identity key); open channels do not need it.",
902
+ description: "Create a new persistent channel (Discord/Slack-style). Set access_mode to open (anyone joins), password (shared-password gated), or private (invite-only). capabilities controls modes (txt/voice/files/ptt/live; voice/ptt/live are server-relayed via LiveKit, NOT E2EE). Set discoverable:true (open channels only) to list it in the public directory. NOTE: password/private channels are provisioned for group-key TEXT encryption \u2014 supply wrapped_group_key (the group key wrapped to your identity key); open channels do not need it. The mosadd.com app encrypts/decrypts channel text with that key on supported clients; the toolkit's own mIRC_post_message posts server-readable text today (group-key parity is the next milestone). Channel voice is never E2EE.",
874
903
  inputSchema: mIRC_create_input,
875
904
  handler: mIRC_create
876
905
  },
@@ -901,6 +930,20 @@ var mircTools = [
901
930
  description: "Delete a channel and cascade-remove its members. Owner only.",
902
931
  inputSchema: mIRC_delete_input,
903
932
  handler: mIRC_delete
933
+ },
934
+ {
935
+ name: "mIRC_discover",
936
+ requires: "network",
937
+ description: "Browse the PUBLIC channel DIRECTORY \u2014 open channels whose owners opted in (discoverable=true). Returns {id, channel_key, name, description, capabilities, member_count, is_member}. Filter by name with q; paginated. Join a result with mIRC_join (open = one-click). Private/password/partner channels never appear.",
938
+ inputSchema: mIRC_discover_input,
939
+ handler: mIRC_discover
940
+ },
941
+ {
942
+ name: "mIRC_report",
943
+ requires: "network",
944
+ description: "Report a channel for abuse (spam/harassment/illegal/etc). Metadata + reason only \u2014 never message content. The reported party is the channel owner (server-derived). Use for public-directory moderation.",
945
+ inputSchema: mIRC_report_input,
946
+ handler: mIRC_report
904
947
  }
905
948
  ];
906
949
 
@@ -911,7 +954,7 @@ var MemberIdentity = z4.string().min(1).describe("Target user's identity id (UUI
911
954
  var Role = z4.enum(["superadmin", "admin", "moderator", "member"]).describe("Role to assign. owner = channel creator (not assignable); promote up to one tier below your own.");
912
955
  var mIRC_join_input = z4.object({
913
956
  channel_id: ChannelId2,
914
- password: z4.string().min(1).optional().describe("Required if the channel is access_mode=private.")
957
+ password: z4.string().min(1).optional().describe("Pass only for access_mode=password channels. Private channels cannot be joined directly (403) \u2014 use mIRC_request_access.")
915
958
  });
916
959
  var mIRC_request_access_input = z4.object({
917
960
  channel_id: ChannelId2
@@ -925,7 +968,7 @@ var mIRC_reject_request_input = z4.object({
925
968
  });
926
969
  var mIRC_approve_request_input = mIRC_reject_request_input.extend({
927
970
  wrapped_group_key: z4.string().optional().describe(
928
- "Required to approve a join to a password/private (E2EE) channel: the channel group key wrapped to the approved member's identity key. Without it the backend rejects the approval with a 'wrapped_group_key required' error. (Access requests only exist on non-open channels, so this is effectively always required.)"
971
+ "Required to approve a join to a password/private (group-key) channel: the channel group key wrapped to the approved member's identity key. Without it the backend rejects the approval with a 'wrapped_group_key required' error. (Access requests only exist on non-open channels, so this is effectively always required.)"
929
972
  )
930
973
  });
931
974
  var mIRC_kick_input = z4.object({
@@ -979,7 +1022,7 @@ var mircMembersTools = [
979
1022
  {
980
1023
  name: "mIRC_join",
981
1024
  requires: "network",
982
- description: "Join a channel as the current user. For private channels pass `password`. Returns a membership row or 409 if already a member.",
1025
+ description: "Join a channel as the current user. Pass `password` only for access_mode=password channels; private channels cannot be joined directly (403) \u2014 use mIRC_request_access + approval. Idempotent: an existing active member gets their membership row back (200, no 409).",
983
1026
  inputSchema: mIRC_join_input,
984
1027
  handler: ((input, ctx) => invokeChannelMembers("join", input, ctx))
985
1028
  },
@@ -1000,7 +1043,7 @@ var mircMembersTools = [
1000
1043
  {
1001
1044
  name: "mIRC_approve_request",
1002
1045
  requires: "network",
1003
- description: "Approve a pending access request (state=requested \u2192 active). Admins / moderators / owner only. Because access requests only exist on E2EE (password/private) channels, you must pass wrapped_group_key \u2014 the channel group key wrapped to the approved member's identity key.",
1046
+ description: "Approve a pending access request (state=requested \u2192 active). Admins / moderators / owner only. Because access requests only exist on non-open (password/private) channels, you must pass wrapped_group_key \u2014 the channel group key wrapped to the approved member's identity key.",
1004
1047
  inputSchema: mIRC_approve_request_input,
1005
1048
  handler: ((input, ctx) => invokeChannelMembers("approve-request", input, ctx))
1006
1049
  },
@@ -1035,7 +1078,7 @@ var mircMembersTools = [
1035
1078
  {
1036
1079
  name: "mIRC_set_role",
1037
1080
  requires: "network",
1038
- description: "Promote / demote a member. Roles: owner > admin > moderator > member > guest. Only owner can promote to admin; only admin+ can promote to moderator.",
1081
+ description: "Promote / demote a member. Roles: owner(100) > superadmin(90) > admin(80) > moderator(70) > member(10). No 'guest'. An actor may assign any role below their own tier \u2014 so a superadmin (not only the owner) can promote to admin.",
1039
1082
  inputSchema: mIRC_set_role_input,
1040
1083
  handler: ((input, ctx) => invokeChannelMembers("set-role", input, ctx))
1041
1084
  },
@@ -1133,7 +1176,7 @@ var mircMessagesTools = [
1133
1176
  {
1134
1177
  name: "mIRC_post_message",
1135
1178
  requires: "network",
1136
- description: "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. You must be a member of private channels (use mIRC_join first). This is how an agent actually talks in a channel \u2014 the other mIRC_* tools only manage it. NOTE (alpha): the payload is NOT end-to-end encrypted \u2014 it is plaintext base64 and is readable by the server; the mosadd.com app uses per-channel group-key encryption, so app clients cannot read these messages yet (and vice-versa). Group-key parity is planned.",
1179
+ description: "Post a text message into a persistent channel (mIRC). Pass channel_id from mIRC_create / mIRC_list; the backing space is resolved automatically. This is how an agent actually talks in a channel \u2014 the other mIRC_* tools only manage it. ACCESS: banned/blocked users are refused on ALL access modes (including open); open channels accept anyone not banned; password channels require joining with the password; private channels require request-access + approval. ENCRYPTION: this tool posts SERVER-READABLE plaintext base64 on EVERY access mode \u2014 private and password channels included; it is never end-to-end encrypted. Open channels: app clients CAN read toolkit-posted messages. Password/private channels: the mosadd.com app group-key-encrypts channel text on supported clients, but the toolkit does not hold that group key \u2014 the message still lands server-readable and app clients cannot decrypt it as channel text (group-key parity is not yet wired).",
1137
1180
  inputSchema: mIRC_post_message_input,
1138
1181
  handler: mIRC_post_message
1139
1182
  },
@@ -1464,17 +1507,168 @@ var mailTools = [
1464
1507
  }
1465
1508
  ];
1466
1509
 
1467
- // src/tools/mtalk.ts
1510
+ // src/tools/mail-provenance.ts
1468
1511
  import { z as z8 } from "zod";
1469
- var RoomLabel = z8.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe("Human-readable room label (e.g. 'ops', 'field-team'). Used to derive a stable room id.");
1470
- var RoomId2 = z8.string().min(1).describe("Room id returned by mTALK_open.");
1471
- var mTALK_open_input = z8.object({
1512
+ var DEFAULT_SUPABASE_URL2 = "https://rooffhgbxafyjcwmwpsy.supabase.co";
1513
+ function supabaseUrl2() {
1514
+ return process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ?? process.env.SUPABASE_URL?.replace(/\/$/, "") ?? DEFAULT_SUPABASE_URL2;
1515
+ }
1516
+ function hubKey2() {
1517
+ return process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? null;
1518
+ }
1519
+ var EmailAddress2 = z8.string().email().max(254);
1520
+ var mp0st_send_as_agent_input = z8.object({
1521
+ to: z8.union([EmailAddress2, z8.array(EmailAddress2).min(1).max(50)]),
1522
+ subject: z8.string().min(1).max(998),
1523
+ body_text: z8.string().max(1048576).optional(),
1524
+ body_html: z8.string().max(1048576).optional(),
1525
+ cc: z8.array(EmailAddress2).max(50).optional(),
1526
+ bcc: z8.array(EmailAddress2).max(50).optional(),
1527
+ reply_to: EmailAddress2.optional(),
1528
+ tracking: z8.boolean().optional(),
1529
+ agent_id: z8.string().min(1).max(120).describe("Stable id of the agent doing the send. Stamped as sent_by_agent_id for provenance."),
1530
+ task_id: z8.string().min(1).max(120).optional().describe("Optional id of the task/run this send belongs to. Stamped as sent_by_task_id.")
1531
+ });
1532
+ async function mintHubClaim(agentId, taskId) {
1533
+ const key = hubKey2();
1534
+ if (!key) {
1535
+ throw new Error("mAYL_send_as_agent needs MOSADD_API_KEY (hub key) to mint a provenance claim.");
1536
+ }
1537
+ const r = await fetch(`${supabaseUrl2()}/functions/v1/hub-claim-mint`, {
1538
+ method: "POST",
1539
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
1540
+ body: JSON.stringify({ agent_id: agentId, task_id: taskId ?? null })
1541
+ });
1542
+ if (!r.ok) {
1543
+ const b = await r.text().catch(() => "");
1544
+ throw new Error(`hub-claim-mint ${r.status}: ${b.slice(0, 200)}`);
1545
+ }
1546
+ const data = await r.json();
1547
+ if (!data?.access_token) throw new Error("hub-claim-mint: no access_token in response");
1548
+ return data.access_token;
1549
+ }
1550
+ async function mAYL_send_as_agent(input, ctx) {
1551
+ if (!input.body_text && !input.body_html) {
1552
+ throw new Error("mAYL_send_as_agent requires at least one of body_text or body_html.");
1553
+ }
1554
+ const claim = await mintHubClaim(input.agent_id, input.task_id);
1555
+ ctx.log("debug", "mAYL_send_as_agent invoking mp0st-send with hub-claim", { agent_id: input.agent_id });
1556
+ const { agent_id: _ai, task_id: _ti, ...mailFields } = input;
1557
+ const r = await fetch(`${supabaseUrl2()}/functions/v1/mp0st-send`, {
1558
+ method: "POST",
1559
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${claim}` },
1560
+ body: JSON.stringify(mailFields)
1561
+ });
1562
+ if (!r.ok) {
1563
+ const b = await r.text().catch(() => "");
1564
+ throw new Error(`mp0st-send ${r.status}: ${b.slice(0, 200)}`);
1565
+ }
1566
+ const res = await r.json();
1567
+ if (res.error) throw new Error(res.error);
1568
+ return {
1569
+ message_id: res.email_id ?? "",
1570
+ status: res.status ?? "sent",
1571
+ is_internal: res.is_internal ?? false,
1572
+ sent_by: "agent"
1573
+ };
1574
+ }
1575
+ var mailProvenanceTools = [
1576
+ {
1577
+ name: "mAYL_send_as_agent",
1578
+ requires: "network",
1579
+ description: "Send an email ATTRIBUTED TO THE AGENT (provenance-stamped). Unlike mAYL_send (sends as the user), this stamps sent_by='agent' plus your agent_id and optional task_id onto the email record and audit trail \u2014 so recipients and compliance can see the mail was agent-originated. Auth: presents a hub-claim JWT (needs MOSADD_API_KEY). The mp0st-send EF verifies the claim with HUB_JWT_SECRET; body trust is never granted for provenance.",
1580
+ inputSchema: mp0st_send_as_agent_input,
1581
+ handler: mAYL_send_as_agent
1582
+ }
1583
+ ];
1584
+
1585
+ // src/tools/mail-agentbox.ts
1586
+ import { z as z9 } from "zod";
1587
+ var BoxId = z9.string().min(1).describe("Agent-box id (UUID) from mAYL_agentbox_provision or mAYL_agentbox_list.");
1588
+ var agentbox_provision_input = z9.object({
1589
+ display_name: z9.string().max(120).optional().describe("Optional human label for the box (e.g. 'signup catcher'). Max 120 chars."),
1590
+ agent_id: z9.string().optional().describe("Optional identity id to attribute the box to \u2014 must be an agent identity you own."),
1591
+ kind: z9.enum(["ephemeral", "persistent"]).optional().describe("'ephemeral' (default) auto-expires + is reaped; 'persistent' never expires."),
1592
+ ttl_seconds: z9.number().int().positive().max(86400).optional().describe("Lifetime for an ephemeral box, in seconds. Default 600 (10 min). Max 86400 (24 h). Ignored for persistent.")
1593
+ });
1594
+ var agentbox_list_input = z9.object({});
1595
+ var agentbox_release_input = z9.object({ id: BoxId });
1596
+ var agentbox_extend_input = z9.object({
1597
+ id: BoxId,
1598
+ ttl_seconds: z9.number().int().positive().max(86400).optional().describe("New lifetime from NOW, in seconds. Default 600 (10 min). Max 86400 (24 h). Ephemeral boxes only.")
1599
+ });
1600
+ async function agentbox_provision(input, ctx) {
1601
+ readSupabaseEnv();
1602
+ ctx.log("debug", "mAYL_agentbox_provision invoking mayl-agentbox", { kind: input.kind ?? "ephemeral" });
1603
+ return await invokeFunction("mayl-agentbox", {
1604
+ action: "create",
1605
+ display_name: input.display_name ?? null,
1606
+ agent_id: input.agent_id ?? null,
1607
+ kind: input.kind ?? "ephemeral",
1608
+ ttl_seconds: input.ttl_seconds ?? null
1609
+ });
1610
+ }
1611
+ async function agentbox_list(_input, ctx) {
1612
+ readSupabaseEnv();
1613
+ ctx.log("debug", "mAYL_agentbox_list invoking mayl-agentbox", {});
1614
+ return await invokeFunction("mayl-agentbox", { action: "list" });
1615
+ }
1616
+ async function agentbox_release(input, ctx) {
1617
+ readSupabaseEnv();
1618
+ ctx.log("debug", "mAYL_agentbox_release invoking mayl-agentbox", { id: input.id });
1619
+ return await invokeFunction("mayl-agentbox", { action: "release", id: input.id });
1620
+ }
1621
+ async function agentbox_extend(input, ctx) {
1622
+ readSupabaseEnv();
1623
+ ctx.log("debug", "mAYL_agentbox_extend invoking mayl-agentbox", { id: input.id });
1624
+ return await invokeFunction("mayl-agentbox", {
1625
+ action: "extend",
1626
+ id: input.id,
1627
+ ttl_seconds: input.ttl_seconds ?? null
1628
+ });
1629
+ }
1630
+ var mailAgentboxTools = [
1631
+ {
1632
+ name: "mAYL_agentbox_provision",
1633
+ requires: "network",
1634
+ description: "Mint the agent its OWN real, disposable email inbox at agent-<hex>@mosadd.com that can SEND and RECEIVE. Default ephemeral with a 10-minute TTL (auto-expires + is reaped); pass kind:'persistent' for a permanent box, or ttl_seconds (max 86400) for a custom lifetime. Optional display_name + agent_id. Returns the box {id, address, expires_at}. Use the address to catch signup/verification codes or replies, then mAYL_list (filter by the box address) + mAYL_view to read what arrived. Owner-scoped; max 25 active boxes per account.",
1635
+ inputSchema: agentbox_provision_input,
1636
+ handler: agentbox_provision
1637
+ },
1638
+ {
1639
+ name: "mAYL_agentbox_list",
1640
+ requires: "network",
1641
+ description: "List your active agent inboxes (address, display_name, kind, agent_id, expires_at), newest first. Owner-scoped.",
1642
+ inputSchema: agentbox_list_input,
1643
+ handler: agentbox_list
1644
+ },
1645
+ {
1646
+ name: "mAYL_agentbox_release",
1647
+ requires: "network",
1648
+ description: "Release (delete) one of your agent inboxes by id \u2014 frees the address immediately so it stops receiving. Owner-scoped.",
1649
+ inputSchema: agentbox_release_input,
1650
+ handler: agentbox_release
1651
+ },
1652
+ {
1653
+ name: "mAYL_agentbox_extend",
1654
+ requires: "network",
1655
+ description: "Extend an EPHEMERAL agent inbox's lifetime by id (ttl_seconds counted from NOW, max 24 h). Persistent boxes never expire and cannot be extended. Owner-scoped.",
1656
+ inputSchema: agentbox_extend_input,
1657
+ handler: agentbox_extend
1658
+ }
1659
+ ];
1660
+
1661
+ // src/tools/mtalk.ts
1662
+ import { z as z10 } from "zod";
1663
+ var RoomLabel = z10.string().min(1).max(120).regex(/^[a-zA-Z0-9._-]+$/).describe("Human-readable room label (e.g. 'ops', 'field-team'). Used to derive a stable room id.");
1664
+ var RoomId2 = z10.string().min(1).describe("Room id returned by mTALK_open.");
1665
+ var mTALK_open_input = z10.object({
1472
1666
  label: RoomLabel.optional().describe("Optional label; defaults to a personal room.")
1473
1667
  });
1474
- var mTALK_join_input = z8.object({ room_id: RoomId2 });
1475
- var mTALK_press_input = z8.object({ room_id: RoomId2 });
1476
- var mTALK_release_input = z8.object({ room_id: RoomId2 });
1477
- var mTALK_state_input = z8.object({ room_id: RoomId2 });
1668
+ var mTALK_join_input = z10.object({ room_id: RoomId2 });
1669
+ var mTALK_press_input = z10.object({ room_id: RoomId2 });
1670
+ var mTALK_release_input = z10.object({ room_id: RoomId2 });
1671
+ var mTALK_state_input = z10.object({ room_id: RoomId2 });
1478
1672
  async function mTALK_open(input, ctx) {
1479
1673
  const { roomId } = await ctx.providers.voice.createRoom(input.label);
1480
1674
  ctx.log("debug", "mTALK_open", { room_id: roomId });
@@ -1538,7 +1732,7 @@ var mtalkTools = [
1538
1732
  ];
1539
1733
 
1540
1734
  // src/tools/attachments.ts
1541
- import { z as z9 } from "zod";
1735
+ import { z as z11 } from "zod";
1542
1736
 
1543
1737
  // src/providers/blob-upload.ts
1544
1738
  function defaultBucket(kind) {
@@ -1588,14 +1782,14 @@ function decodeBase64Body(b64) {
1588
1782
 
1589
1783
  // src/tools/attachments.ts
1590
1784
  var PROTOCOL_VERSION4 = "mosadd.chat.v1";
1591
- var Base64Body = z9.string().min(1).max(2e7).describe("Attachment bytes as base64 (or a data: URL). MCP is JSON-only, so binary is base64-encoded. Max ~15 MB decoded.");
1592
- var Mime = z9.string().min(1).max(120).describe("MIME type, e.g. audio/ogg, application/pdf, image/png.");
1593
- var DurationMs = z9.number().int().positive().optional().describe("Audio clip length in ms (voice only), if known.");
1594
- var Filename = z9.string().min(1).max(255).optional().describe("Original filename (file only).");
1595
- var ReplyTo = z9.string().optional().describe("Optional id of the message being replied to.");
1596
- var ContactRef3 = z9.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
1597
- var RoomId3 = z9.string().min(1).describe("Room/channel id (UUID).");
1598
- var ThreadLabel = z9.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional().describe("Optional thread label within the conversation (mDM USP: multiple threads per contact).");
1785
+ var Base64Body = z11.string().min(1).max(2e7).describe("Attachment bytes as base64 (or a data: URL). MCP is JSON-only, so binary is base64-encoded. Max ~15 MB decoded.");
1786
+ var Mime = z11.string().min(1).max(120).describe("MIME type, e.g. audio/ogg, application/pdf, image/png.");
1787
+ var DurationMs = z11.number().int().positive().optional().describe("Audio clip length in ms (voice only), if known.");
1788
+ var Filename = z11.string().min(1).max(255).optional().describe("Original filename (file only).");
1789
+ var ReplyTo = z11.string().optional().describe("Optional id of the message being replied to.");
1790
+ var ContactRef3 = z11.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
1791
+ var RoomId3 = z11.string().min(1).describe("Room/channel id (UUID).");
1792
+ var ThreadLabel = z11.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional().describe("Optional thread label within the conversation (mDM USP: multiple threads per contact).");
1599
1793
  function dmThreadId3(selfId, otherId, label) {
1600
1794
  const [a, b] = [selfId, otherId].sort();
1601
1795
  return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
@@ -1638,21 +1832,21 @@ async function resolveLinkedSpaceId2(channelId) {
1638
1832
  if (!spaceId) throw new Error(`Channel ${channelId} has no linked space yet \u2014 run mIRC_join/mIRC_list first or pass space_id.`);
1639
1833
  return spaceId;
1640
1834
  }
1641
- var mDM_send_voice_input = z9.object({
1835
+ var mDM_send_voice_input = z11.object({
1642
1836
  to: ContactRef3,
1643
1837
  audio_base64: Base64Body,
1644
1838
  mime: Mime.default("audio/ogg"),
1645
1839
  duration_ms: DurationMs,
1646
- caption: z9.string().max(2e3).optional(),
1840
+ caption: z11.string().max(2e3).optional(),
1647
1841
  thread_label: ThreadLabel,
1648
1842
  reply_to_id: ReplyTo
1649
1843
  });
1650
- var mDM_send_file_input = z9.object({
1844
+ var mDM_send_file_input = z11.object({
1651
1845
  to: ContactRef3,
1652
1846
  file_base64: Base64Body,
1653
1847
  filename: Filename,
1654
1848
  mime: Mime,
1655
- caption: z9.string().max(2e3).optional(),
1849
+ caption: z11.string().max(2e3).optional(),
1656
1850
  thread_label: ThreadLabel,
1657
1851
  reply_to_id: ReplyTo
1658
1852
  });
@@ -1698,23 +1892,23 @@ async function mDM_send_file(input, ctx) {
1698
1892
  recipient_account_id: input.to
1699
1893
  });
1700
1894
  }
1701
- var mIRC_send_voice_input = z9.object({
1895
+ var mIRC_send_voice_input = z11.object({
1702
1896
  channel_id: RoomId3,
1703
1897
  audio_base64: Base64Body,
1704
1898
  mime: Mime.default("audio/ogg"),
1705
1899
  duration_ms: DurationMs,
1706
- caption: z9.string().max(2e3).optional(),
1900
+ caption: z11.string().max(2e3).optional(),
1707
1901
  reply_to_id: ReplyTo,
1708
- space_id: z9.string().optional().describe("Backing space id. Resolved automatically if omitted.")
1902
+ space_id: z11.string().optional().describe("Backing space id. Resolved automatically if omitted.")
1709
1903
  });
1710
- var mIRC_send_file_input = z9.object({
1904
+ var mIRC_send_file_input = z11.object({
1711
1905
  channel_id: RoomId3,
1712
1906
  file_base64: Base64Body,
1713
1907
  filename: Filename,
1714
1908
  mime: Mime,
1715
- caption: z9.string().max(2e3).optional(),
1909
+ caption: z11.string().max(2e3).optional(),
1716
1910
  reply_to_id: ReplyTo,
1717
- space_id: z9.string().optional()
1911
+ space_id: z11.string().optional()
1718
1912
  });
1719
1913
  async function mIRC_send_voice(input, ctx) {
1720
1914
  const space_id = input.space_id ?? await resolveLinkedSpaceId2(input.channel_id);
@@ -1759,13 +1953,68 @@ var attachmentTools = [
1759
1953
  }
1760
1954
  ];
1761
1955
 
1956
+ // src/tools/ptt-ingest.ts
1957
+ import { z as z12 } from "zod";
1958
+ var mTALK_ingest_ptt_input = z12.object({
1959
+ audio_base64: z12.string().min(1).max(2e7).describe("Recorded PTT 'over' as base64 (a 'data:audio/\u2026;base64,\u2026' prefix is stripped if present)."),
1960
+ mime_type: z12.string().min(1).max(120).default("audio/webm").describe("MIME type of the audio. Default audio/webm (browser MediaRecorder default)."),
1961
+ direction: z12.enum(["human_to_agent", "agent_to_human"]).describe("Direction the PTT crossed: who originated, who received. 'human_to_agent' = user spoke to an agent; 'agent_to_human' = agent spoke to the user."),
1962
+ message_id: z12.string().min(1).max(120).optional().describe("Optional id of the messages_meta row this PTT belongs to. When present, links the transcript back to the message for jump-to-source from RAG."),
1963
+ thread_id: z12.string().min(1).max(120).optional().describe("Optional thread id (e.g. `chat:<channel_id>` or `dm:<a>:<b>`) so the transcript carries its conversational scope into RAG.")
1964
+ });
1965
+ async function mTALK_ingest_ptt(input, ctx) {
1966
+ readSupabaseEnv();
1967
+ const audio = input.audio_base64.replace(/^data:[^;]+;base64,/, "");
1968
+ ctx.log("debug", "mTALK_ingest_ptt invoking ptt-ingest", {
1969
+ direction: input.direction,
1970
+ thread_id: input.thread_id ?? null,
1971
+ mime_type: input.mime_type
1972
+ });
1973
+ const res = await invokeFunction("ptt-ingest", {
1974
+ audio_base64: audio,
1975
+ mime_type: input.mime_type,
1976
+ direction: input.direction,
1977
+ message_id: input.message_id ?? null,
1978
+ thread_id: input.thread_id ?? null
1979
+ });
1980
+ const status = res.status ?? "pending";
1981
+ return {
1982
+ ptt_id: res.ptt_id ?? "",
1983
+ status,
1984
+ opted_in: status !== "skipped_optout"
1985
+ };
1986
+ }
1987
+ var pttIngestTools = [
1988
+ {
1989
+ name: "mTALK_ingest_ptt",
1990
+ requires: "network",
1991
+ description: "Submit a finished PTT 'over' (push-to-talk audio segment) for transcription into the caller's RAG index \u2014 so 'what did X say on PTT?' is searchable later. The PERSISTENCE of the voice message itself (the message_meta row + fan-out) is handled by mDM_send_voice / mIRC_send_voice; this tool is the transcription bridge only. Honors per-user RAG opt-in: opted-out callers get status='skipped_optout' (no transcript stored). Auth: Supabase session JWT.",
1992
+ inputSchema: mTALK_ingest_ptt_input,
1993
+ handler: mTALK_ingest_ptt
1994
+ }
1995
+ ];
1996
+
1762
1997
  // src/tools/knowledge.ts
1763
- import { z as z10 } from "zod";
1764
- var mRAG_search_input = z10.object({
1765
- query: z10.string().min(1).max(2e3).describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
1766
- top_k: z10.number().int().min(1).max(25).optional().describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
1767
- source_types: z10.array(z10.enum(["message", "email", "call", "note", "contact"])).optional().describe("Restrict retrieval to these source types. Omit to search everything."),
1768
- thread_id: z10.string().optional().describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread).")
1998
+ import { createHash } from "crypto";
1999
+ import { z as z13 } from "zod";
2000
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2001
+ var SOURCE_ID_NAMESPACE = "1f0b6c2e-6a4d-4f7a-9c1e-0b2d3a4f5e6b";
2002
+ function uuidV5(name, namespace) {
2003
+ const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
2004
+ const digest = createHash("sha1").update(Buffer.concat([ns, Buffer.from(name, "utf8")])).digest();
2005
+ const b = Buffer.from(digest.subarray(0, 16));
2006
+ b[6] = b[6] & 15 | 80;
2007
+ b[8] = b[8] & 63 | 128;
2008
+ const h = b.toString("hex");
2009
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
2010
+ }
2011
+ var mRAG_search_input = z13.object({
2012
+ query: z13.string().min(1).max(2e3).describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
2013
+ top_k: z13.number().int().min(1).max(25).optional().describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
2014
+ source_types: z13.array(z13.enum(["message", "email", "call", "note", "contact", "file", "ptt"])).optional().describe(
2015
+ "Restrict retrieval to these source types. Omit to search everything. 'file' covers anything added with mRAG_ingest (its default, and where 'note' ingests land); 'ptt' covers push-to-talk transcripts ingested by mTALK_ingest_ptt."
2016
+ ),
2017
+ thread_id: z13.string().optional().describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread).")
1769
2018
  });
1770
2019
  async function mRAG_search(input, ctx) {
1771
2020
  readSupabaseEnv();
@@ -1782,35 +2031,81 @@ async function mRAG_search(input, ctx) {
1782
2031
  chunks_found: data.chunks_found ?? (data.sources?.length ?? 0)
1783
2032
  };
1784
2033
  }
1785
- var mRAG_ingest_input = z10.object({
1786
- content_text: z10.string().min(1).max(2e5).describe("Text to index into the user's private knowledge base (a note, document, transcript, pasted page\u2026). Chunked + embedded server-side."),
1787
- source_type: z10.enum(["file", "note", "message", "email", "contact", "call"]).optional().describe("What kind of source this is. Default 'file' (a document/note). Use 'note' for ad-hoc text."),
1788
- source_id: z10.string().optional().describe("Optional stable id for the source so re-ingests can be grouped."),
1789
- thread_id: z10.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
1790
- title: z10.string().max(300).optional().describe("Optional human title, stored in metadata.")
2034
+ var PartyArg = z13.object({
2035
+ kind: z13.enum(["identity", "account", "email", "phone", "url", "unknown"]).describe("How to read `ref`: a mosadd identity UUID, an account id, an email address, a phone number, a URL, or a plain name ('unknown')."),
2036
+ ref: z13.string().min(1).max(400).describe("The stable key this party is recognised by \u2014 identity UUID, email address, phone number, or the party's canonical name. Use the SAME ref for the same party across documents; that is what merges them into one node in the knowledge graph."),
2037
+ label: z13.string().max(300).nullish().describe("Human name to display for this party.")
2038
+ });
2039
+ var mRAG_ingest_input = z13.object({
2040
+ content_text: z13.string().min(1).max(2e5).describe("Text to index into the user's private knowledge base (a note, document, transcript, pasted page\u2026). Chunked + embedded server-side."),
2041
+ source_type: z13.enum(["file", "note", "message", "email", "contact", "call"]).optional().describe("What kind of source this is. Default 'file' (a document/note). Use 'note' for ad-hoc text."),
2042
+ source_id: z13.string().max(500).optional().describe(
2043
+ "Optional stable id for the source so re-ingests of the SAME document group together (and can be removed later with mRAG_delete). Any string works \u2014 a file path, a case number, a checksum: a non-UUID is folded into a stable id derived from it, deterministically, and the original is kept as metadata.source_ref."
2044
+ ),
2045
+ thread_id: z13.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
2046
+ title: z13.string().max(300).optional().describe("Optional human title, stored in metadata."),
2047
+ // ── Graph + file-manager fields ────────────────────────────────────────────
2048
+ // Added 2026-08-14. The backend (rag-index → enrichRagMetadata) has accepted all of these
2049
+ // since 2026-07-19; THIS tool was the only ingest path that dropped them, so everything
2050
+ // pushed through MCP landed with no parties and no event date — and therefore contributed
2051
+ // NOTHING to mRAG_graph_*, which builds its nodes from exactly these fields. A corpus could
2052
+ // be fully indexed and its graph still come back empty. See the note on the tool below.
2053
+ sender: PartyArg.optional().describe(
2054
+ "Who the document is FROM (author, filing party, sender). Becomes a node in the knowledge graph \u2014 without it this document adds no party to mRAG_graph_overview."
2055
+ ),
2056
+ recipient: PartyArg.optional().describe(
2057
+ "Who the document is TO (addressee, court, counterparty). Becomes a node in the knowledge graph, connected to `sender`."
2058
+ ),
2059
+ occurred_at: z13.string().optional().describe("ISO-8601 timestamp of WHEN the document happened (letter date, filing date, email Date header) \u2014 not when you indexed it. Drives mRAG_graph_timeline; defaults to now if omitted, which makes a 2019 filing look like it happened today."),
2060
+ direction: z13.enum(["in", "out", "self"]).optional().describe("Direction relative to the account owner: received, sent, or the owner's own note."),
2061
+ labels: z13.array(z13.string().max(120)).max(50).optional().describe("Free-text tags to attach (e.g. a case id, a jurisdiction) for later filtering."),
2062
+ name: z13.string().max(400).optional().describe("Original filename, if this came from a file (e.g. 'pozew-2019-03-11.pdf'). Its extension is what classifies the row as a document/image/audio in the file view. Distinct from `title`, which is free prose."),
2063
+ mime: z13.string().max(200).optional().describe("MIME type of the original file, if known."),
2064
+ size: z13.number().int().nonnegative().optional().describe("Size of the original file in bytes, if known."),
2065
+ metadata: z13.record(z13.string(), z13.unknown()).optional().describe("Any extra fields to store alongside the row (case id, docket number, jurisdiction, file path, checksum, sensitivity flag\u2026). Stored verbatim and returned with search hits. NOTE: this is stored server-side in plaintext like the content itself.")
1791
2066
  });
1792
2067
  async function mRAG_ingest(input, ctx) {
1793
2068
  readSupabaseEnv();
1794
2069
  const backendType = input.source_type === "note" ? "file" : input.source_type ?? "file";
1795
- ctx.log("debug", "mRAG_ingest via rag-index", { source_type: backendType });
2070
+ ctx.log("debug", "mRAG_ingest via rag-index", {
2071
+ source_type: backendType,
2072
+ has_parties: Boolean(input.sender || input.recipient),
2073
+ has_occurred_at: Boolean(input.occurred_at)
2074
+ });
2075
+ const rawSourceId = input.source_id?.trim() || null;
2076
+ const sourceId = rawSourceId && !UUID_RE.test(rawSourceId) ? uuidV5(rawSourceId, SOURCE_ID_NAMESPACE) : rawSourceId;
1796
2077
  const data = await invokeFunction("rag-index", {
1797
2078
  source_type: backendType,
1798
- source_id: input.source_id ?? null,
2079
+ source_id: sourceId,
1799
2080
  thread_id: input.thread_id ?? null,
1800
2081
  content_text: input.content_text,
1801
- metadata: { ...input.title ? { title: input.title } : {}, ingested_via: "mRAG_ingest" }
2082
+ ...input.sender ? { sender: input.sender } : {},
2083
+ ...input.recipient ? { recipient: input.recipient } : {},
2084
+ ...input.occurred_at ? { occurred_at: input.occurred_at } : {},
2085
+ ...input.direction ? { direction: input.direction } : {},
2086
+ ...input.labels?.length ? { labels: input.labels } : {},
2087
+ ...input.name ? { name: input.name } : {},
2088
+ ...input.mime ? { mime: input.mime } : {},
2089
+ ...typeof input.size === "number" ? { size: input.size } : {},
2090
+ metadata: {
2091
+ ...input.metadata ?? {},
2092
+ ...input.title ? { title: input.title } : {},
2093
+ // Only when we actually rewrote it — a caller that passed a real UUID sees no extra key.
2094
+ ...rawSourceId && rawSourceId !== sourceId ? { source_ref: rawSourceId } : {},
2095
+ ingested_via: "mRAG_ingest"
2096
+ }
1802
2097
  });
1803
2098
  return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
1804
2099
  }
1805
- var mRAG_list_sources_input = z10.object({});
2100
+ var mRAG_list_sources_input = z13.object({});
1806
2101
  async function mRAG_list_sources(_input, ctx) {
1807
2102
  readSupabaseEnv();
1808
2103
  ctx.log("debug", "mRAG_list_sources via rag-sources");
1809
2104
  return await invokeFunction("rag-sources", { action: "list" });
1810
2105
  }
1811
- var mRAG_delete_input = z10.object({
1812
- source_id: z10.string().optional().describe("Delete every indexed chunk with this source_id (from mRAG_list_sources)."),
1813
- thread_id: z10.string().optional().describe("Delete every indexed chunk associated with this thread_id.")
2106
+ var mRAG_delete_input = z13.object({
2107
+ source_id: z13.string().optional().describe("Delete every indexed chunk with this source_id (from mRAG_list_sources)."),
2108
+ thread_id: z13.string().optional().describe("Delete every indexed chunk associated with this thread_id.")
1814
2109
  }).refine((v) => v.source_id || v.thread_id, {
1815
2110
  message: "Provide source_id or thread_id \u2014 mRAG_delete refuses to purge the whole index."
1816
2111
  });
@@ -1827,7 +2122,7 @@ var knowledgeTools = [
1827
2122
  {
1828
2123
  name: "mRAG_ingest",
1829
2124
  requires: "network",
1830
- description: "Add text to the USER'S OWN private knowledge base so mRAG_search can recall it later. Pass content_text (a note, document, transcript, pasted page); it is semantically chunked, embedded (1536-d) and stored in the per-user vector index mRAG_search reads. Returns how many chunks were indexed. NOTE: indexed content is stored server-side in plaintext \u2014 NOT covered by the zero-knowledge / E2EE guarantee. Only ingest what the user opted to make searchable.",
2125
+ description: "Add text to the USER'S OWN private knowledge base so mRAG_search can recall it later. Pass content_text (a note, document, transcript, pasted page); it is semantically chunked, embedded (1536-d) and stored in the per-user vector index mRAG_search reads. Returns how many chunks were indexed. \u26A0 IF YOU ARE INDEXING A CORPUS you want to TRAVERSE (who is connected to whom, when), also pass sender / recipient / occurred_at: the knowledge graph builds its nodes from those fields alone, so documents ingested without them are searchable but contribute NOTHING to mRAG_graph_overview / _neighbors / _timeline \u2014 the graph comes back empty however many documents you loaded. Reuse the same party `ref` across documents to merge them into one node. NOTE: indexed content and metadata are stored server-side in plaintext \u2014 NOT covered by the zero-knowledge / E2EE guarantee. Only ingest what the user opted to make searchable.",
1831
2126
  inputSchema: mRAG_ingest_input,
1832
2127
  handler: mRAG_ingest
1833
2128
  },
@@ -1854,35 +2149,118 @@ var knowledgeTools = [
1854
2149
  }
1855
2150
  ];
1856
2151
 
2152
+ // src/tools/knowledge-graph.ts
2153
+ import { z as z14 } from "zod";
2154
+ async function callRpc(fn, args, ctx) {
2155
+ readSupabaseEnv();
2156
+ ctx.log("debug", `mRAG_graph via ${fn}`, args);
2157
+ const { data, error } = await getSupabase().rpc(fn, args);
2158
+ if (error) {
2159
+ throw new Error(`${fn} failed: ${error.message}${error.code ? ` (${error.code})` : ""}`);
2160
+ }
2161
+ return data;
2162
+ }
2163
+ var mRAG_graph_refresh_input = z14.object({
2164
+ max_docs: z14.number().int().min(1).max(2e4).optional().describe("Cap on source documents scanned when (re)building the graph. Default 20000 (the max).")
2165
+ });
2166
+ async function mRAG_graph_refresh(input, ctx) {
2167
+ return await callRpc("kg_refresh_me", { p_max_docs: input.max_docs ?? 2e4 }, ctx);
2168
+ }
2169
+ var mRAG_graph_overview_input = z14.object({
2170
+ limit: z14.number().int().min(1).max(200).optional().describe("Max parties to return (busiest first). Default 40, max 200.")
2171
+ });
2172
+ async function mRAG_graph_overview(input, ctx) {
2173
+ const rows = await callRpc("kg_overview", { p_limit: input.limit ?? 40 }, ctx);
2174
+ const parties = rows ?? [];
2175
+ return { parties, count: parties.length };
2176
+ }
2177
+ var mRAG_graph_neighbors_input = z14.object({
2178
+ party_id: z14.string().uuid().describe("The party whose connections to walk (a party_id from mRAG_graph_overview)."),
2179
+ depth: z14.number().int().min(1).max(2).optional().describe("Hops to walk. Hard-clamped to 2 server-side. Default 1."),
2180
+ limit: z14.number().int().min(1).max(200).optional().describe("Max neighbours to return. Clamped to 200. Default 50.")
2181
+ });
2182
+ async function mRAG_graph_neighbors(input, ctx) {
2183
+ const rows = await callRpc(
2184
+ "kg_neighbors",
2185
+ { p_party_id: input.party_id, p_depth: input.depth ?? 1, p_limit: input.limit ?? 50 },
2186
+ ctx
2187
+ );
2188
+ const neighbors = rows ?? [];
2189
+ return { neighbors, count: neighbors.length };
2190
+ }
2191
+ var mRAG_graph_timeline_input = z14.object({
2192
+ party_id: z14.string().uuid().describe("The party whose dated appearance timeline to return (a party_id from mRAG_graph_overview)."),
2193
+ limit: z14.number().int().min(1).max(200).optional().describe("Max timeline entries (newest first). Clamped to 200. Default 50.")
2194
+ });
2195
+ async function mRAG_graph_timeline(input, ctx) {
2196
+ const rows = await callRpc(
2197
+ "kg_party_timeline",
2198
+ { p_party_id: input.party_id, p_limit: input.limit ?? 50 },
2199
+ ctx
2200
+ );
2201
+ const timeline = rows ?? [];
2202
+ return { timeline, count: timeline.length };
2203
+ }
2204
+ var knowledgeGraphTools = [
2205
+ {
2206
+ name: "mRAG_graph_refresh",
2207
+ requires: "network",
2208
+ description: "(Re)build the USER'S OWN knowledge graph from their indexed data, then return what it found (counts of parties/mentions/edges). Run this first, or after new data has been ingested, so mRAG_graph_overview/neighbors/timeline reflect the latest. Built from METADATA only (who-sent-to-whom, thread membership) \u2014 never message bodies, so it does not weaken E2EE. Owner-scoped.",
2209
+ inputSchema: mRAG_graph_refresh_input,
2210
+ handler: mRAG_graph_refresh
2211
+ },
2212
+ {
2213
+ name: "mRAG_graph_overview",
2214
+ requires: "network",
2215
+ description: "List the parties (people / companies / services) in the user's knowledge graph, busiest first, each with its party_id, kind, aliases, appearance count, connection count and first/last-seen dates. This is the entry point: use a returned party_id with mRAG_graph_neighbors or mRAG_graph_timeline. Owner-scoped.",
2216
+ inputSchema: mRAG_graph_overview_input,
2217
+ handler: mRAG_graph_overview
2218
+ },
2219
+ {
2220
+ name: "mRAG_graph_neighbors",
2221
+ requires: "network",
2222
+ description: "Walk the connections of one party (from mRAG_graph_overview) \u2014 who/what it is linked to, with the edge type, how many times observed, and when. Answers 'who is connected to X, and how'. Depth is hard-clamped to 2 hops and breadth to 200 server-side. Owner-scoped.",
2223
+ inputSchema: mRAG_graph_neighbors_input,
2224
+ handler: mRAG_graph_neighbors
2225
+ },
2226
+ {
2227
+ name: "mRAG_graph_timeline",
2228
+ requires: "network",
2229
+ description: "Return the dated appearance timeline of one party (from mRAG_graph_overview) \u2014 each source (email/message/call/\u2026), its thread, the party's role, and when it occurred, newest first. Answers 'when and where did X show up'. Owner-scoped.",
2230
+ inputSchema: mRAG_graph_timeline_input,
2231
+ handler: mRAG_graph_timeline
2232
+ }
2233
+ ];
2234
+
1857
2235
  // src/tools/actions.ts
1858
- import { z as z11 } from "zod";
1859
- var formField = z11.object({
1860
- name: z11.string().min(1).max(60).describe("Field key \u2014 returned verbatim in the result."),
1861
- label: z11.string().max(120).optional().describe("Human label shown to the recipient. Defaults to `name`."),
1862
- type: z11.enum(["text", "email", "number", "textarea", "tel", "url"]).optional().describe("Input type. Default 'text'."),
1863
- required: z11.boolean().optional().describe("Whether the recipient must fill this field.")
1864
- });
1865
- var action_create_input = z11.object({
1866
- action_type: z11.enum(["confirm", "file_request", "form", "open_url", "screen_share"]).describe(
2236
+ import { z as z15 } from "zod";
2237
+ var formField = z15.object({
2238
+ name: z15.string().min(1).max(60).describe("Field key \u2014 returned verbatim in the result."),
2239
+ label: z15.string().max(120).optional().describe("Human label shown to the recipient. Defaults to `name`."),
2240
+ type: z15.enum(["text", "email", "number", "textarea", "tel", "url"]).optional().describe("Input type. Default 'text'."),
2241
+ required: z15.boolean().optional().describe("Whether the recipient must fill this field.")
2242
+ });
2243
+ var action_create_input = z15.object({
2244
+ action_type: z15.enum(["confirm", "file_request", "form", "open_url", "screen_share"]).describe(
1867
2245
  "What you want the recipient to do: 'confirm' (yes/no), 'file_request' (pick a file from their computer), 'form' (fill fields), 'open_url' (open a vetted https URL), 'screen_share' (recipient shares their screen so you can SEE it via comms_action_frame_get \u2014 view only)."
1868
2246
  ),
1869
- message: z11.string().min(1).max(2e3).describe("What you're asking \u2014 shown on the consent screen above the action UI."),
1870
- creator_label: z11.string().max(80).optional().describe("How you're identified to the recipient (e.g. your agent name). Default 'Agent'."),
2247
+ message: z15.string().min(1).max(2e3).describe("What you're asking \u2014 shown on the consent screen above the action UI."),
2248
+ creator_label: z15.string().max(80).optional().describe("How you're identified to the recipient (e.g. your agent name). Default 'Agent'."),
1871
2249
  // confirm
1872
- yes_label: z11.string().max(40).optional().describe("[confirm] Affirmative button label. Default 'Tak'."),
1873
- no_label: z11.string().max(40).optional().describe("[confirm] Negative button label. Default 'Nie'."),
2250
+ yes_label: z15.string().max(40).optional().describe("[confirm] Affirmative button label. Default 'Tak'."),
2251
+ no_label: z15.string().max(40).optional().describe("[confirm] Negative button label. Default 'Nie'."),
1874
2252
  // file_request
1875
- accept: z11.string().max(200).optional().describe("[file_request] Accepted file types (HTML accept attr, e.g. 'image/*,.pdf')."),
1876
- max_bytes: z11.number().int().positive().max(5242880).optional().describe("[file_request] Max file size in bytes (\u2264 5 MB). NOTE: the returned file is NOT yet end-to-end encrypted \u2014 do not request sensitive files until Tier 1.1 ships."),
2253
+ accept: z15.string().max(200).optional().describe("[file_request] Accepted file types (HTML accept attr, e.g. 'image/*,.pdf')."),
2254
+ max_bytes: z15.number().int().positive().max(5242880).optional().describe("[file_request] Max file size in bytes (\u2264 5 MB). NOTE: the returned file is NOT yet end-to-end encrypted \u2014 do not request sensitive files until Tier 1.1 ships."),
1877
2255
  // form
1878
- fields: z11.array(formField).min(1).max(20).optional().describe("[form] Fields to collect from the recipient."),
2256
+ fields: z15.array(formField).min(1).max(20).optional().describe("[form] Fields to collect from the recipient."),
1879
2257
  // open_url
1880
- url: z11.string().url().optional().describe("[open_url] The https URL to open. The full URL is shown to the recipient before they open it."),
2258
+ url: z15.string().url().optional().describe("[open_url] The https URL to open. The full URL is shown to the recipient before they open it."),
1881
2259
  // screen_share
1882
- max_width: z11.number().int().positive().max(1920).optional().describe("[screen_share] Max captured frame width in px (default 1280). Frames are downscaled JPEGs."),
2260
+ max_width: z15.number().int().positive().max(1920).optional().describe("[screen_share] Max captured frame width in px (default 1280). Frames are downscaled JPEGs."),
1883
2261
  // lifecycle
1884
- ttl_ms: z11.number().int().positive().optional().describe("Link lifetime in milliseconds. Default 24h, capped at 7d."),
1885
- max_uses: z11.number().int().min(1).max(50).optional().describe("How many times the link can be redeemed. Default 1 (single-use).")
2262
+ ttl_ms: z15.number().int().positive().optional().describe("Link lifetime in milliseconds. Default 24h, capped at 7d."),
2263
+ max_uses: z15.number().int().min(1).max(50).optional().describe("How many times the link can be redeemed. Default 1 (single-use).")
1886
2264
  });
1887
2265
  function buildParams(input) {
1888
2266
  switch (input.action_type) {
@@ -1923,8 +2301,8 @@ async function action_create(input, ctx) {
1923
2301
  expires_at: res.expires_at ?? ""
1924
2302
  };
1925
2303
  }
1926
- var action_frame_get_input = z11.object({
1927
- action_id: z11.string().min(1).describe("The action_id returned by comms_action_create for a 'screen_share' action you created.")
2304
+ var action_frame_get_input = z15.object({
2305
+ action_id: z15.string().min(1).describe("The action_id returned by comms_action_create for a 'screen_share' action you created.")
1928
2306
  });
1929
2307
  async function action_frame_get(input, ctx) {
1930
2308
  readSupabaseEnv();
@@ -1964,21 +2342,108 @@ var actionTools = [
1964
2342
  }
1965
2343
  ];
1966
2344
 
2345
+ // src/tools/presence.ts
2346
+ import { hostname } from "os";
2347
+ import { z as z16 } from "zod";
2348
+ var BEAT_MS = 6e4;
2349
+ var HOLD_SECONDS = 300;
2350
+ var attachments = /* @__PURE__ */ new Map();
2351
+ async function beat(env, identityId, host, mode) {
2352
+ await getSupabase(env).from("agent_bridge_heartbeat").upsert(
2353
+ { identity_id: identityId, last_seen_at: (/* @__PURE__ */ new Date()).toISOString(), host, mode },
2354
+ { onConflict: "identity_id" }
2355
+ );
2356
+ }
2357
+ async function resolveSelf(env) {
2358
+ const sb = getSupabase(env);
2359
+ const { data: u, error: ue } = await sb.auth.getUser();
2360
+ if (ue || !u?.user) {
2361
+ throw new Error(
2362
+ "Unable to resolve the current account. Set MOSADD_API_KEY (hub key) or MOSADD_USER_JWT, or run `mosadd login`."
2363
+ );
2364
+ }
2365
+ const { data, error } = await sb.from("identities").select("id, display_name").eq("user_id", u.user.id).maybeSingle();
2366
+ if (error || !data) {
2367
+ throw new Error("This account has no mosadd identity row yet \u2014 sign in to mosadd.com once to create it.");
2368
+ }
2369
+ return { id: data.id, display_name: data.display_name ?? null };
2370
+ }
2371
+ var comms_session_attach_input = z16.object({
2372
+ label: z16.string().max(120).optional().describe(
2373
+ "Short name for THIS session, shown to the owner as who is holding the line (e.g. 'CTO \u2014 Claude Code', 'dispatcher \u2014 Cowork'). Defaults to the machine name."
2374
+ ),
2375
+ release: z16.boolean().optional().describe(
2376
+ "Hand the line back immediately instead of claiming it: stops this session's keep-alive and clears the liveness row, so the 24/7 cloud stand-in resumes answering at once rather than after the hold expires. Call this when the session is finishing."
2377
+ )
2378
+ });
2379
+ async function comms_session_attach(input, ctx) {
2380
+ const env = readSupabaseEnv();
2381
+ const self = await resolveSelf(env);
2382
+ const existing = attachments.get(self.id);
2383
+ if (existing) {
2384
+ clearInterval(existing.timer);
2385
+ attachments.delete(self.id);
2386
+ }
2387
+ if (input.release) {
2388
+ ctx.log("info", "comms_session_attach: releasing line", { identity_id: self.id });
2389
+ const { error } = await getSupabase(env).from("agent_bridge_heartbeat").delete().eq("identity_id", self.id);
2390
+ if (error) throw new Error(`Could not release the line: ${error.message}`);
2391
+ return {
2392
+ attached: false,
2393
+ identity_id: self.id,
2394
+ display_name: self.display_name,
2395
+ note: "Line released. The 24/7 cloud stand-in answers this account from now on."
2396
+ };
2397
+ }
2398
+ const host = input.label?.trim() || `mcp:${hostname()}`;
2399
+ const mode = "mcp-session";
2400
+ try {
2401
+ await beat(env, self.id, host, mode);
2402
+ } catch (e) {
2403
+ throw new Error(`Could not claim the line: ${e instanceof Error ? e.message : String(e)}`);
2404
+ }
2405
+ const timer = setInterval(() => {
2406
+ void beat(env, self.id, host, mode).catch((e) => {
2407
+ ctx.log("warn", "comms_session_attach: beat failed", { identity_id: self.id, error: String(e) });
2408
+ });
2409
+ }, BEAT_MS);
2410
+ timer.unref?.();
2411
+ attachments.set(self.id, { timer, env });
2412
+ ctx.log("info", "comms_session_attach: line claimed", { identity_id: self.id, host });
2413
+ return {
2414
+ attached: true,
2415
+ identity_id: self.id,
2416
+ display_name: self.display_name,
2417
+ host,
2418
+ holds_for_seconds: HOLD_SECONDS,
2419
+ note: "This session now owns the account's reply lane; the cloud stand-in will not answer while it is held. The hold renews itself for as long as this process runs and lapses on its own if the session dies. Call again with release:true to hand it back immediately."
2420
+ };
2421
+ }
2422
+ var presenceTools = [
2423
+ {
2424
+ name: "comms_session_attach",
2425
+ requires: "network",
2426
+ description: "Claim this mosADD account's reply lane for the CURRENT agent session, so the 24/7 cloud stand-in stops answering in your place and the owner talks to you instead. Call it once at the start of a session that will answer the owner's messages; the hold renews itself while the session runs and lapses on its own if the session dies, so the account is never left looking alive when nobody is there. Pass release:true when finishing to hand the line back immediately. Owner-scoped: a session can only claim the account whose key it holds.",
2427
+ inputSchema: comms_session_attach_input,
2428
+ handler: comms_session_attach
2429
+ }
2430
+ ];
2431
+
1967
2432
  // src/tools/embed.ts
1968
- import { z as z12 } from "zod";
2433
+ import { z as z17 } from "zod";
1969
2434
  var EMBED_CDN = (process.env.MOSADD_EMBED_CDN ?? "https://embed.mosadd.com").replace(/\/+$/, "");
1970
2435
  var POSITIONS = ["inline", "sidebar-left", "sidebar-right", "floating-bl", "floating-br", "fullscreen"];
1971
2436
  var SKINS = ["default", "retro-irc-1990", "terminal", "minimal-dark", "minimal-light"];
1972
- var embed_create_input = z12.object({
1973
- channel: z12.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/).describe("The mIRC channel id everyone on the embed shares (e.g. 'acme-support'). Auto-created on first message if new."),
1974
- allowed_origins: z12.array(z12.string().min(1)).min(1).max(10).describe("REQUIRED. Domain(s) where the widget will be served \u2014 the key only works from these origins. Use the host(s) of the app you're building, e.g. ['app.acme.com','*.acme.com']. For local testing use mode:'test' and e.g. 'localhost:3000'."),
1975
- name: z12.string().max(64).optional().describe("Label for the key in the owner's dashboard. Default 'embed: <channel>'."),
1976
- position: z12.enum(POSITIONS).optional().describe("Where the widget renders. Default 'inline'."),
1977
- skin: z12.enum(SKINS).optional().describe("Visual skin. Default 'default' (mosadd-branded retro mIRC)."),
1978
- title: z12.string().max(60).optional().describe("Header title shown in the widget. Default 'mIRC'."),
1979
- anon: z12.boolean().optional().describe("Allow visitors to join with just a nick (no mosadd account). Default true."),
1980
- locale: z12.enum(["en", "pl"]).optional().describe("Widget UI language. Default 'en'."),
1981
- mode: z12.enum(["live", "test"]).optional().describe("Key mode \u2014 'test' for local/dev origins, 'live' for production. Default 'live'.")
2437
+ var embed_create_input = z17.object({
2438
+ channel: z17.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/).describe("The mIRC channel id everyone on the embed shares (e.g. 'acme-support'). Auto-created on first message if new."),
2439
+ allowed_origins: z17.array(z17.string().min(1)).min(1).max(10).describe("REQUIRED. Domain(s) where the widget will be served \u2014 the key only works from these origins. Use the host(s) of the app you're building, e.g. ['app.acme.com','*.acme.com']. For local testing use mode:'test' and e.g. 'localhost:3000'."),
2440
+ name: z17.string().max(64).optional().describe("Label for the key in the owner's dashboard. Default 'embed: <channel>'."),
2441
+ position: z17.enum(POSITIONS).optional().describe("Where the widget renders. Default 'inline'."),
2442
+ skin: z17.enum(SKINS).optional().describe("Visual skin. Default 'default' (mosadd-branded retro mIRC)."),
2443
+ title: z17.string().max(60).optional().describe("Header title shown in the widget. Default 'mIRC'."),
2444
+ anon: z17.boolean().optional().describe("Allow visitors to join with just a nick (no mosadd account). Default true."),
2445
+ locale: z17.enum(["en", "pl"]).optional().describe("Widget UI language. Default 'en'."),
2446
+ mode: z17.enum(["live", "test"]).optional().describe("Key mode \u2014 'test' for local/dev origins, 'live' for production. Default 'live'.")
1982
2447
  });
1983
2448
  var attrSafe = (s) => s.replace(/["'<>]/g, "");
1984
2449
  function buildSnippet(input, key) {
@@ -2019,16 +2484,16 @@ var embedTools = [
2019
2484
  ];
2020
2485
 
2021
2486
  // src/tools/threat.ts
2022
- import { z as z13 } from "zod";
2487
+ import { z as z18 } from "zod";
2023
2488
  import {
2024
2489
  THREAT_EVENTS,
2025
2490
  THREAT_EVENT_COUNT,
2026
2491
  evaluateEvent,
2027
2492
  getEventDef
2028
2493
  } from "@mosadd/threat-engine";
2029
- var threat_catalog_input = z13.object({
2030
- category: z13.enum(["COMINT", "ELINT", "MASINT", "CYBER", "BEHAVIORAL", "PRIVACY", "SIGINT", "OSINT", "MPOST"]).optional().describe("Filter the catalog to one intelligence-discipline category. Omit for the full catalog."),
2031
- platform: z13.enum(["apk", "ios", "pwa", "harmony"]).optional().describe("Filter to events detectable on this platform. Omit for all platforms.")
2494
+ var threat_catalog_input = z18.object({
2495
+ category: z18.enum(["COMINT", "ELINT", "MASINT", "CYBER", "BEHAVIORAL", "PRIVACY", "SIGINT", "OSINT", "MPOST"]).optional().describe("Filter the catalog to one intelligence-discipline category. Omit for the full catalog."),
2496
+ platform: z18.enum(["apk", "ios", "pwa", "harmony"]).optional().describe("Filter to events detectable on this platform. Omit for all platforms.")
2032
2497
  });
2033
2498
  async function threat_catalog(input, _ctx) {
2034
2499
  let events = THREAT_EVENTS;
@@ -2036,10 +2501,10 @@ async function threat_catalog(input, _ctx) {
2036
2501
  if (input.platform) events = events.filter((e) => e.platforms.includes(input.platform));
2037
2502
  return { count: events.length, total: THREAT_EVENT_COUNT, events };
2038
2503
  }
2039
- var threat_classify_input = z13.object({
2040
- event_type: z13.string().min(1).max(120).describe('Event type to classify, e.g. "SIM_SWAP", "AUTH_BRUTEFORCE", "TOLL_FRAUD". Case-insensitive.'),
2041
- severity: z13.string().optional().describe('Optional producer severity hint. "killswitch" \u2192 lock_account; "critical" \u2192 revoke_sessions; anything else is informational.'),
2042
- details: z13.string().max(2e3).optional().describe("Optional free-text context (informational only).")
2504
+ var threat_classify_input = z18.object({
2505
+ event_type: z18.string().min(1).max(120).describe('Event type to classify, e.g. "SIM_SWAP", "AUTH_BRUTEFORCE", "TOLL_FRAUD". Case-insensitive.'),
2506
+ severity: z18.string().optional().describe('Optional producer severity hint. "killswitch" \u2192 lock_account; "critical" \u2192 revoke_sessions; anything else is informational.'),
2507
+ details: z18.string().max(2e3).optional().describe("Optional free-text context (informational only).")
2043
2508
  });
2044
2509
  async function threat_classify(input, _ctx) {
2045
2510
  const def = getEventDef(String(input.event_type).toUpperCase());
@@ -2074,12 +2539,12 @@ var threatTools = [
2074
2539
  ];
2075
2540
 
2076
2541
  // src/tools/murl.ts
2077
- import { z as z14 } from "zod";
2542
+ import { z as z19 } from "zod";
2078
2543
  var DEFAULT_EDGE_URL2 = "https://mosadd-edge.mr-brics-33.workers.dev";
2079
2544
  function edgeUrl2() {
2080
2545
  return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL2;
2081
2546
  }
2082
- function hubKey2() {
2547
+ function hubKey3() {
2083
2548
  const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
2084
2549
  if (!key) throw new Error("MOSADD_API_KEY required for mURL tools (see `mosadd login` / hub-keys).");
2085
2550
  return key;
@@ -2097,17 +2562,17 @@ function urlToSlug(input) {
2097
2562
  const base = host.replace(/\./g, "-");
2098
2563
  return { domain: host, slug: segs.length ? `${base}__${segs.join("__")}` : base };
2099
2564
  }
2100
- var DomainArg = z14.string().min(3).max(2048).describe("A domain ('example.com') or a full URL. Keyed PER-URL: a bare domain \u2192 the domain room; a URL with a path (e.g. 'site.com/articles/abc') \u2192 that page's own room.");
2101
- var mURL_read_channel_input = z14.object({
2565
+ var DomainArg = z19.string().min(3).max(2048).describe("A domain ('example.com') or a full URL. Keyed PER-URL: a bare domain \u2192 the domain room; a URL with a path (e.g. 'site.com/articles/abc') \u2192 that page's own room.");
2566
+ var mURL_read_channel_input = z19.object({
2102
2567
  domain: DomainArg,
2103
- limit: z14.number().int().min(1).max(100).optional().describe("Recent messages to return (max 100). Default 50.")
2568
+ limit: z19.number().int().min(1).max(100).optional().describe("Recent messages to return (max 100). Default 50.")
2104
2569
  });
2105
2570
  async function mURL_read_channel(input, ctx) {
2106
2571
  const { domain, slug: slug2 } = urlToSlug(input.domain);
2107
2572
  const limit = input.limit ?? 50;
2108
2573
  ctx.log("debug", "mURL_read_channel", { domain });
2109
2574
  const r = await fetch(`${edgeUrl2()}/c/${slug2}/history?limit=${limit}`, {
2110
- headers: { Authorization: `Bearer ${hubKey2()}` }
2575
+ headers: { Authorization: `Bearer ${hubKey3()}` }
2111
2576
  });
2112
2577
  if (!r.ok) {
2113
2578
  const e = await r.text().catch(() => "");
@@ -2119,17 +2584,17 @@ async function mURL_read_channel(input, ctx) {
2119
2584
  messages: (data.messages ?? []).map((m) => ({ id: m.id, from: m.from ?? null, text: m.text, timestamp: m.ts }))
2120
2585
  };
2121
2586
  }
2122
- var mURL_post_input = z14.object({
2587
+ var mURL_post_input = z19.object({
2123
2588
  domain: DomainArg,
2124
- text: z14.string().min(1).max(2e3).describe("Message body (max 2000 chars, up to 3 lines \u2014 Worker-enforced)."),
2125
- from: z14.string().max(120).optional().describe("Sender hint shown to others (defaults to the hub-key owner / your agent name).")
2589
+ text: z19.string().min(1).max(2e3).describe("Message body (max 2000 chars, up to 3 lines \u2014 Worker-enforced)."),
2590
+ from: z19.string().max(120).optional().describe("Sender hint shown to others (defaults to the hub-key owner / your agent name).")
2126
2591
  });
2127
2592
  async function mURL_post(input, ctx) {
2128
2593
  const { domain, slug: slug2 } = urlToSlug(input.domain);
2129
2594
  ctx.log("debug", "mURL_post", { domain });
2130
2595
  const r = await fetch(`${edgeUrl2()}/c/${slug2}/send`, {
2131
2596
  method: "POST",
2132
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${hubKey2()}` },
2597
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${hubKey3()}` },
2133
2598
  body: JSON.stringify({ text: input.text, from: input.from })
2134
2599
  });
2135
2600
  if (!r.ok) {
@@ -2140,12 +2605,12 @@ async function mURL_post(input, ctx) {
2140
2605
  if (!data?.id) throw new Error("mosadd-edge: send returned no id");
2141
2606
  return { domain, message_id: data.id, posted_at: data.ts ?? Date.now() };
2142
2607
  }
2143
- var mURL_list_channels_input = z14.object({
2144
- action: z14.enum(["trending", "list", "mine"]).optional().describe("'trending' (default) = most active domain channels in the last N hours; 'list' = paginated catalogue filtered by status; 'mine' = channels you own (DNS-verified)."),
2145
- limit: z14.number().int().min(1).max(100).optional().describe("Max channels to return. Default 20."),
2146
- hours: z14.number().int().min(1).max(168).optional().describe("Trending window in hours. Default 24, max 168 (7d)."),
2147
- status: z14.enum(["open", "claimed", "blocked"]).optional().describe("For action='list': filter (default 'open')."),
2148
- cursor: z14.string().optional().describe("For action='list': pagination \u2014 pass previous response's next_cursor (created_at ISO).")
2608
+ var mURL_list_channels_input = z19.object({
2609
+ action: z19.enum(["trending", "list", "mine"]).optional().describe("'trending' (default) = most active domain channels in the last N hours; 'list' = paginated catalogue filtered by status; 'mine' = channels you own (DNS-verified)."),
2610
+ limit: z19.number().int().min(1).max(100).optional().describe("Max channels to return. Default 20."),
2611
+ hours: z19.number().int().min(1).max(168).optional().describe("Trending window in hours. Default 24, max 168 (7d)."),
2612
+ status: z19.enum(["open", "claimed", "blocked"]).optional().describe("For action='list': filter (default 'open')."),
2613
+ cursor: z19.string().optional().describe("For action='list': pagination \u2014 pass previous response's next_cursor (created_at ISO).")
2149
2614
  });
2150
2615
  async function mURL_list_channels(input, ctx) {
2151
2616
  readSupabaseEnv();
@@ -2159,7 +2624,7 @@ async function mURL_list_channels(input, ctx) {
2159
2624
  cursor: input.cursor ?? null
2160
2625
  });
2161
2626
  }
2162
- var mURL_presence_input = z14.object({ domain: DomainArg });
2627
+ var mURL_presence_input = z19.object({ domain: DomainArg });
2163
2628
  async function mURL_presence(input, ctx) {
2164
2629
  const { domain, slug: slug2 } = urlToSlug(input.domain);
2165
2630
  ctx.log("debug", "mURL_presence", { domain });
@@ -2171,10 +2636,12 @@ async function mURL_presence(input, ctx) {
2171
2636
  const data = await r.json();
2172
2637
  return { domain, count: data.count ?? 0, roster: data.roster ?? [], status: data.status ?? "open" };
2173
2638
  }
2174
- var mURL_create_input = z14.object({
2639
+ var mURL_create_input = z19.object({
2175
2640
  domain: DomainArg,
2176
- branding: z14.record(z14.string(), z14.any()).optional().describe("Optional branding JSON (e.g. display name, colour, avatar URL) shown on the channel."),
2177
- status: z14.enum(["open", "claimed", "blocked"]).optional().describe("Initial status: 'open' (default) = public agent-native room; 'claimed' = registered as yours; 'blocked' = closed.")
2641
+ branding: z19.record(z19.string(), z19.any()).optional().describe("Optional branding JSON (e.g. display name, colour, avatar URL) shown on the channel."),
2642
+ status: z19.enum(["open", "claimed", "blocked"]).optional().describe(
2643
+ "Status for a channel that does NOT exist yet: 'open' (default) = public agent-native room; 'claimed' = registered as yours; 'blocked' = closed. IGNORED if the channel already exists \u2014 murl-manage applies status only on the INSERT of a new row; on an existing row it writes owner + branding and leaves status untouched. mURL rooms auto-create on first activity, so an existing room is the common case: change its status with mURL_update."
2644
+ )
2178
2645
  });
2179
2646
  async function mURL_create(input, ctx) {
2180
2647
  readSupabaseEnv();
@@ -2187,10 +2654,10 @@ async function mURL_create(input, ctx) {
2187
2654
  status: input.status ?? null
2188
2655
  });
2189
2656
  }
2190
- var mURL_update_input = z14.object({
2657
+ var mURL_update_input = z19.object({
2191
2658
  domain: DomainArg,
2192
- branding: z14.record(z14.string(), z14.any()).optional().describe("New branding JSON to set on the channel."),
2193
- status: z14.enum(["open", "claimed", "blocked"]).optional().describe("New status: 'claimed' to mark owned, 'blocked' to close the room, 'open' to reopen.")
2659
+ branding: z19.record(z19.string(), z19.any()).optional().describe("New branding JSON to set on the channel."),
2660
+ status: z19.enum(["open", "claimed", "blocked"]).optional().describe("New status: 'claimed' to mark owned, 'blocked' to close the room, 'open' to reopen.")
2194
2661
  });
2195
2662
  async function mURL_update(input, ctx) {
2196
2663
  readSupabaseEnv();
@@ -2204,7 +2671,7 @@ async function mURL_update(input, ctx) {
2204
2671
  status: input.status ?? null
2205
2672
  });
2206
2673
  }
2207
- var mURL_delete_input = z14.object({ domain: DomainArg });
2674
+ var mURL_delete_input = z19.object({ domain: DomainArg });
2208
2675
  async function mURL_delete(input, ctx) {
2209
2676
  readSupabaseEnv();
2210
2677
  const { domain } = urlToSlug(input.domain);
@@ -2244,7 +2711,7 @@ var murlTools = [
2244
2711
  {
2245
2712
  name: "mURL_create",
2246
2713
  requires: "network",
2247
- description: "Create / claim the mURL channel for a web DOMAIN and register YOU as its owner (idempotent \u2014 returns the existing channel if you already own it; fails with 'claimed_by_other' if another account owns it). Optionally set initial branding + status. Owner-side: needs your mosADD login session (user JWT via `mosadd login`), not just a hub key \u2014 same as mURL_list_channels action='mine'. Backend: murl-manage EF.",
2714
+ description: "Create / claim the mURL channel for a web DOMAIN and register YOU as its owner (idempotent \u2014 returns the existing channel if you already own it; fails with 'claimed_by_other' if another account owns it). Optionally set branding, and `status` ONLY when the channel is being created for the first time: on a channel that already exists (mURL rooms auto-create on first activity) murl-manage writes owner + branding and IGNORES status \u2014 use mURL_update to change the status of an existing room. Owner-side: needs your mosADD login session (user JWT via `mosadd login`), not just a hub key \u2014 same as mURL_list_channels action='mine'. Backend: murl-manage EF.",
2248
2715
  inputSchema: mURL_create_input,
2249
2716
  handler: mURL_create
2250
2717
  },
@@ -2265,7 +2732,7 @@ var murlTools = [
2265
2732
  ];
2266
2733
 
2267
2734
  // src/tools/capabilities.ts
2268
- import { z as z15 } from "zod";
2735
+ import { z as z20 } from "zod";
2269
2736
  var CONTRACT_VERSION = "1.0.0";
2270
2737
  var ALL_REQUIREMENTS = ["any", "radio", "network"];
2271
2738
  function buildCapabilityManifest(tools) {
@@ -2288,7 +2755,7 @@ function makeCapabilitiesTool(channelTools2) {
2288
2755
  name: "comms_capabilities",
2289
2756
  requires: "any",
2290
2757
  description: "Discover which mosadd tools are available and what transport each requires (any | radio | network). Carrier-aware hosts (e.g. off-grid radio devices) call this once to gate the tool list to what the current carrier supports. Returns a manifest with per-tool requirements grouped by transport.",
2291
- inputSchema: z15.object({}),
2758
+ inputSchema: z20.object({}),
2292
2759
  handler: async () => buildCapabilityManifest([...channelTools2, tool])
2293
2760
  };
2294
2761
  return tool;
@@ -2307,13 +2774,71 @@ var channelTools = [
2307
2774
  ...mailTools,
2308
2775
  // mAYL_*: canonical email module (was the mp0st codename; renamed re-arch 2026-06-27)
2309
2776
  // ...mailAliasTools, // mp0st_* aliases RETIRED 2026-07-15 — mAYL is the one name; the mp0st codename is now backend-internal only
2310
- // ...mailProvenanceTools, // mAYL_send_as_agent: UNREGISTERED 2026-07-14 — hub-claim EF 404s every call; re-register when rewired onto hub-key-exchange (CTO-1 live-ping)
2777
+ // ⭐ mAYL_send_as_agent: RE-REGISTERED 2026-07-29 — proven end to end, without sending mail.
2778
+ // Unregistered since 07-14 on the note "hub-claim EF 404s every call". That note was stale in
2779
+ // the same way ptt-ingest's was: unauthenticated it returns 401 (the auth gate), not 404.
2780
+ //
2781
+ // Settled by running the whole chain rather than the convenient half:
2782
+ // 1. hub-keys with a plain user JWT issued a real `mosadd_sk_live_…` — so a user session
2783
+ // mints a hub key and no founder credential was ever needed. I had told the founder it
2784
+ // required his key; that was wrong and this is the retraction.
2785
+ // 2. hub-claim-mint with that key → 200, valid claim token, aud `mp0st-send`, 600s expiry.
2786
+ // 3. mp0st-send with the claim token and a DELIBERATELY EMPTY payload → 400 "Missing to or
2787
+ // subject". A 400 on payload validation proves the token was ACCEPTED; 401/403 would have
2788
+ // proven it was not. Auth verified end to end with zero mail sent — a diagnostic must not
2789
+ // put a real message in someone's inbox.
2790
+ // The diagnostic key was then REVOKED (revoked_at set, not deleted, so the audit trail lives).
2791
+ ...mailProvenanceTools,
2792
+ // mAYL_agentbox_provision/list/release/extend — the agent mints/lists/releases/extends its OWN
2793
+ // real, two-way, disposable inbox (agent-<hex>@mosadd.com). create_inbox parity with AgentMail,
2794
+ // on our own stack + provenance. Backs the live mayl-agentbox EF; receive path landed 2026-08-06
2795
+ // in mp0st-inbound-webhook (LINEAR-5201). Same requireUser auth as every other mAYL tool.
2796
+ ...mailAgentboxTools,
2311
2797
  ...mtalkTools,
2312
2798
  ...attachmentTools,
2313
- // ...pttIngestTools, // mTALK_ingest_ptt: UNREGISTERED 2026-07-14 — ptt-ingest EF 400s every call; re-register when payload + PTT→RAG path fixed (CTO-1 live-ping)
2799
+ // ⭐ mTALK_ingest_ptt: RE-REGISTERED 2026-07-29 — the backend finally does what the tool promises.
2800
+ // Unregistered since 07-14 on the note "ptt-ingest EF 400s every call". Re-measured 07-29: that
2801
+ // reason was stale (it returned 401, the auth gate), and an AUTHENTICATED probe then exposed the
2802
+ // real fault — 500, `Could not find the table 'public.rag_jobs'`. It authenticated, validated,
2803
+ // wrote the transcript row, and died one step later against a table dropped when the rag_events
2804
+ // v2 queue landed. Agent push-to-talk had NEVER once reached memory.
2805
+ //
2806
+ // Fixed by handing the audio to `rag-transcribe` (NOT to the v2 queue — that queue carries TEXT
2807
+ // for embedding and cannot transcribe; audio has to become words first). Verified on prod:
2808
+ // 200 {"queued":true}, edge log 200 in 2.7s where it used to 500, and the transcript row's
2809
+ // updated_at moved 4s after insert, so the backgrounded chain genuinely ran.
2810
+ //
2811
+ // Registered only AFTER that authenticated 200 — a liveness probe was never enough, because the
2812
+ // whole point of this registry is that an agent sees only tools that actually work.
2813
+ ...pttIngestTools,
2814
+ //
2815
+ // ✅ RESOLVED 2026-07-29 — both halves of this note are closed; kept as the record of how.
2816
+ // The disable note recorded a diagnosis from 2026-07-14: hub-claim "404s every call".
2817
+ // Live-probed today, unauthenticated:
2818
+ // hub-claim-mint → 401 · ptt-ingest → 401 · mp0st-send → 401 (the control, a tool that
2819
+ // IS registered and works)
2820
+ // 401 is the auth gate answering. A dead or missing function returns 404; a function that
2821
+ // rejects our payload shape returns 400. Neither happens any more, and both are ACTIVE on
2822
+ // the project. So whatever was broken in July was fixed at some point and nobody came back
2823
+ // to these lines — we advertised two capabilities as unavailable while their backends
2824
+ // answered. One of them (ptt) is now proven and registered; this is the other.
2825
+ //
2826
+ // NOT re-registering hub-claim on this evidence, deliberately. An unauthenticated 401 proves the
2827
+ // function is alive; it proves NOTHING about the authenticated path, which is where both
2828
+ // originally failed. Re-registering on a liveness probe would swap "wrongly disabled" for
2829
+ // "advertised and broken in a user's hands", which is the worse of the two.
2830
+ //
2831
+ // TO CLOSE: call each with a real hub key / session token. If they succeed, delete these
2832
+ // two comment blocks and uncomment the imports — the count moves 71 → 73 and the anti-drift
2833
+ // gate will then force every doc surface to follow. (This session cannot mint a session
2834
+ // token, so it stops here rather than guess.)
2314
2835
  ...knowledgeTools,
2836
+ ...knowledgeGraphTools,
2837
+ // mRAG_graph_*: traverse the per-user knowledge graph (kg_* RPCs) — search finds text, this walks who/what/when
2315
2838
  ...actionTools,
2316
2839
  // Action links (Tier 1): agent → user one-link browser action via action-create EF
2840
+ ...presenceTools,
2841
+ // comms_session_attach: THIS session owns the account's reply lane while it runs; the 24/7 cloud stand-in defers. Any session, any machine — no bespoke bridge on one PC.
2317
2842
  ...embedTools,
2318
2843
  // comms_embed_create: RE-REGISTERED 2026-07-17 — embed.mosadd.com/v1.js live; mints an embed key + paste-in snippet (mURL→mIRC rework P3)
2319
2844
  ...threatTools,
@@ -2497,7 +3022,7 @@ function createMosaddServer(options = {}) {
2497
3022
  const server = new McpServer(
2498
3023
  {
2499
3024
  name: "mosadd",
2500
- version: "3.0.0-alpha.31"
3025
+ version: "3.0.0-alpha.32"
2501
3026
  },
2502
3027
  {
2503
3028
  capabilities: {