@mosadd/mcp 3.0.0-alpha.3 → 3.0.0-alpha.5

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 (38) hide show
  1. package/README.md +126 -116
  2. package/dist/bin/mcp.js +1 -1
  3. package/dist/{chunk-HD5RLE5K.js → chunk-4C36JDTJ.js} +734 -91
  4. package/dist/index.d.ts +26 -3
  5. package/dist/index.js +1 -1
  6. package/package.json +5 -5
  7. package/src/__tests__/golden-path.test.ts +137 -132
  8. package/src/__tests__/integration.test.ts +178 -175
  9. package/src/__tests__/mdm-e2ee.test.ts +178 -149
  10. package/src/__tests__/mtalk.test.ts +122 -0
  11. package/src/__tests__/server.test.ts +67 -67
  12. package/src/bin/login.ts +138 -138
  13. package/src/bin/mcp.ts +97 -97
  14. package/src/config.ts +66 -66
  15. package/src/crypto/mdm-session.ts +403 -378
  16. package/src/index.ts +17 -17
  17. package/src/observability/sentry.ts +79 -79
  18. package/src/providers/memory-voice.ts +79 -0
  19. package/src/providers/supabase-dm.ts +117 -117
  20. package/src/providers/supabase-voice.ts +91 -0
  21. package/src/providers/supabase.ts +96 -96
  22. package/src/server.ts +105 -103
  23. package/src/tools/capabilities.ts +68 -68
  24. package/src/tools/index.ts +51 -37
  25. package/src/tools/knowledge.ts +132 -0
  26. package/src/tools/mail.ts +157 -89
  27. package/src/tools/mcall.ts +216 -0
  28. package/src/tools/mdm-voice.ts +206 -0
  29. package/src/tools/mdm.ts +448 -379
  30. package/src/tools/mirc-edge.ts +190 -0
  31. package/src/tools/mirc-members.ts +177 -177
  32. package/src/tools/mirc-messages.ts +156 -0
  33. package/src/tools/mirc.ts +170 -170
  34. package/src/tools/mroom-messages.ts +142 -142
  35. package/src/tools/mroom.ts +221 -189
  36. package/src/tools/mtalk.ts +121 -0
  37. package/src/types.ts +85 -79
  38. package/src/voice/floor.ts +132 -0
@@ -80,6 +80,7 @@ var InMemoryMdmKeyStore = class {
80
80
  material = null;
81
81
  oneTimeById = /* @__PURE__ */ new Map();
82
82
  sessions = /* @__PURE__ */ new Map();
83
+ sentMessages = /* @__PURE__ */ new Map();
83
84
  async getOwnMaterial() {
84
85
  if (this.material) return this.material;
85
86
  const identity = await generateX25519KeyPair();
@@ -107,6 +108,12 @@ var InMemoryMdmKeyStore = class {
107
108
  async putSession(peerId, record) {
108
109
  this.sessions.set(peerId, record);
109
110
  }
111
+ async putSentMessage(messageId, plaintext) {
112
+ this.sentMessages.set(messageId, plaintext);
113
+ }
114
+ async getSentMessage(messageId) {
115
+ return this.sentMessages.get(messageId);
116
+ }
110
117
  };
111
118
  function randomId() {
112
119
  return crypto.getRandomValues(new Uint32Array(1))[0];
@@ -347,6 +354,9 @@ async function mDM_send(input, ctx) {
347
354
  payload: sealed,
348
355
  replyToId: input.reply_to_id
349
356
  });
357
+ if (ctx.providers.keys.putSentMessage) {
358
+ await ctx.providers.keys.putSentMessage(result.id, inner);
359
+ }
350
360
  return {
351
361
  message_id: result.id,
352
362
  delivered_at: result.deliveredAt,
@@ -399,6 +409,10 @@ async function mDM_list(input, ctx) {
399
409
  return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
400
410
  }
401
411
  if (m.senderId === selfId) {
412
+ const cached = await ctx.providers.keys.getSentMessage?.(m.id);
413
+ if (cached) {
414
+ return { ...base, text: unpackPayload(cached).text, encrypted: true };
415
+ }
402
416
  return { ...base, text: "<encrypted \xB7 sent by you>", encrypted: true };
403
417
  }
404
418
  try {
@@ -443,6 +457,33 @@ async function mDM_respond_request(input, ctx) {
443
457
  return { ok: true };
444
458
  }
445
459
  var mDM_publish_keys_input = z.object({});
460
+ var mDM_edit_input = z.object({
461
+ message_id: z.string().min(1).describe("Id of the message to edit (from mDM_list)."),
462
+ new_text: z.string().min(1).max(64e3).describe("Replacement message body (UTF-8). Max 64 KB.")
463
+ });
464
+ var mDM_delete_input = z.object({
465
+ message_id: z.string().min(1).describe("Id of the message to delete (from mDM_list).")
466
+ });
467
+ async function mDM_edit(input, ctx) {
468
+ readSupabaseEnv();
469
+ const envelope = {
470
+ v: PROTOCOL_VERSION,
471
+ type: "text",
472
+ text: input.new_text,
473
+ edited: true,
474
+ sent_at: (/* @__PURE__ */ new Date()).toISOString()
475
+ };
476
+ const encrypted_payload = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
477
+ ctx.log("debug", "mDM_edit via message-edit", { message_id: input.message_id });
478
+ await invokeFunction("message-edit", { message_id: input.message_id, encrypted_payload });
479
+ return { message_id: input.message_id, edited: true };
480
+ }
481
+ async function mDM_delete(input, ctx) {
482
+ readSupabaseEnv();
483
+ ctx.log("debug", "mDM_delete via message-delete", { message_id: input.message_id });
484
+ await invokeFunction("message-delete", { message_id: input.message_id });
485
+ return { message_id: input.message_id, deleted: true };
486
+ }
446
487
  var mdmTools = [
447
488
  {
448
489
  name: "mDM_list_contacts",
@@ -485,41 +526,178 @@ var mdmTools = [
485
526
  description: "Accept or reject an incoming DM request from a contact who is not yet in the user's whitelist.",
486
527
  inputSchema: mDM_respond_request_input,
487
528
  handler: mDM_respond_request
529
+ },
530
+ {
531
+ name: "mDM_edit",
532
+ requires: "any",
533
+ description: "Edit a direct message you sent \u2014 replace its body by message_id (from mDM_list). Stores a server-readable edited body; on an end-to-end-encrypted thread this does not re-encrypt, so for E2EE prefer deleting and re-sending.",
534
+ inputSchema: mDM_edit_input,
535
+ handler: mDM_edit
536
+ },
537
+ {
538
+ name: "mDM_delete",
539
+ requires: "any",
540
+ description: "Delete a direct message you sent by message_id (from mDM_list). Soft-deletes server-side so it stops showing in mDM_list for both sides.",
541
+ inputSchema: mDM_delete_input,
542
+ handler: mDM_delete
488
543
  }
489
544
  ];
490
545
 
491
- // src/tools/mirc.ts
546
+ // src/tools/mdm-voice.ts
492
547
  import { z as z2 } from "zod";
493
- var ChannelId = z2.string().min(1).max(120).describe("Channel id (UUID). Use mIRC_list to discover available channels.");
494
- var AccessMode = z2.enum(["public", "private", "invite_only"]).describe("public: anyone joins \xB7 private: requires invite + password \xB7 invite_only: invite only.");
495
- var Capabilities = z2.object({
496
- txt: z2.boolean().default(true),
497
- ptt: z2.boolean().default(false),
498
- live: z2.boolean().default(false)
548
+ var PROTOCOL_VERSION2 = "mosadd.chat.v1";
549
+ var ContactRef2 = z2.string().min(1).describe("Recipient identity id (UUID). Use mDM_list_contacts to find it.");
550
+ var RoomId = z2.string().min(1).describe("Voice room id (from mDM_call_start's call_invite).");
551
+ var mDM_call_start_input = z2.object({
552
+ to: ContactRef2,
553
+ video: z2.boolean().optional().describe("Request a video call instead of audio-only. Default false."),
554
+ thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional().describe("Optional thread label to place the call invite in. Defaults to the contact's main thread.")
555
+ });
556
+ var mDM_call_answer_input = z2.object({ room_id: RoomId });
557
+ var mDM_call_end_input = z2.object({
558
+ room_id: RoomId,
559
+ to: ContactRef2.optional().describe("If set, also drop a call_end control message in this contact's DM thread."),
560
+ thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
561
+ });
562
+ var mDM_voice_note_input = z2.object({
563
+ to: ContactRef2,
564
+ audio_url: z2.string().url().describe("URL of the recorded audio clip (already uploaded by the client)."),
565
+ duration_ms: z2.number().int().positive().optional().describe("Clip length in milliseconds, if known."),
566
+ mime: z2.string().max(120).optional().describe("Audio MIME type, e.g. audio/ogg, audio/mpeg. Default audio/ogg."),
567
+ thread_label: z2.string().max(120).regex(/^[a-zA-Z0-9._-]+$/).optional()
568
+ });
569
+ function dmThreadId2(selfId, otherId, label) {
570
+ const [a, b] = [selfId, otherId].sort();
571
+ return label ? `dm:${a}:${b}:${label}` : `dm:${a}:${b}`;
572
+ }
573
+ function packEnvelope(obj) {
574
+ const envelope = { v: PROTOCOL_VERSION2, sent_at: (/* @__PURE__ */ new Date()).toISOString(), ...obj };
575
+ return new Uint8Array(Buffer.from(JSON.stringify(envelope), "utf8"));
576
+ }
577
+ async function signalDm(ctx, to, threadLabel, envelope) {
578
+ const dm = ctx.providers.dm;
579
+ const selfId = await dm.selfId();
580
+ const threadId = dmThreadId2(selfId, to, threadLabel);
581
+ const res = await dm.send({ to, threadId, payload: packEnvelope(envelope) });
582
+ return { message_id: res?.message_id, thread_id: threadId };
583
+ }
584
+ async function mDM_call_start(input, ctx) {
585
+ const dm = ctx.providers.dm;
586
+ const selfId = await dm.selfId();
587
+ const mode = input.video ? "video" : "audio";
588
+ const label = `dmcall-${dmThreadId2(selfId, input.to, input.thread_label).replace(/[^a-zA-Z0-9._-]/g, "-")}`.slice(0, 120);
589
+ const { roomId } = await ctx.providers.voice.createRoom(label);
590
+ const ticket = await ctx.providers.voice.joinTicket(roomId);
591
+ let invited = false;
592
+ let thread_id = dmThreadId2(selfId, input.to, input.thread_label);
593
+ try {
594
+ const sig = await signalDm(ctx, input.to, input.thread_label, {
595
+ type: "call_invite",
596
+ room_id: roomId,
597
+ mode,
598
+ from: selfId
599
+ });
600
+ thread_id = sig.thread_id;
601
+ invited = true;
602
+ } catch (e) {
603
+ ctx.log("warn", "mDM_call_start: invite signal failed (room still usable)", {
604
+ error: e.message
605
+ });
606
+ }
607
+ ctx.log("debug", "mDM_call_start", { room_id: roomId, mode, invited });
608
+ return { room_id: roomId, token: ticket.token, url: ticket.url, identity: ticket.identity, mode, invited, thread_id };
609
+ }
610
+ async function mDM_call_answer(input, ctx) {
611
+ const ticket = await ctx.providers.voice.joinTicket(input.room_id);
612
+ ctx.log("debug", "mDM_call_answer", { room_id: ticket.roomId, identity: ticket.identity });
613
+ return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
614
+ }
615
+ async function mDM_call_end(input, ctx) {
616
+ let signalled = false;
617
+ if (input.to) {
618
+ try {
619
+ await signalDm(ctx, input.to, input.thread_label, { type: "call_end", room_id: input.room_id });
620
+ signalled = true;
621
+ } catch (e) {
622
+ ctx.log("warn", "mDM_call_end: hangup signal failed", { error: e.message });
623
+ }
624
+ }
625
+ ctx.log("debug", "mDM_call_end", { room_id: input.room_id, signalled });
626
+ return { room_id: input.room_id, signalled };
627
+ }
628
+ async function mDM_voice_note(input, ctx) {
629
+ const sig = await signalDm(ctx, input.to, input.thread_label, {
630
+ type: "voice_note",
631
+ audio_url: input.audio_url,
632
+ duration_ms: input.duration_ms ?? null,
633
+ mime: input.mime ?? "audio/ogg"
634
+ });
635
+ ctx.log("debug", "mDM_voice_note", { thread_id: sig.thread_id });
636
+ return sig;
637
+ }
638
+ var mdmVoiceTools = [
639
+ {
640
+ name: "mDM_call_start",
641
+ requires: "network",
642
+ description: "Start a 1:1 real-time voice (or video) call with a contact \u2014 the ordinary full-duplex phone-style call (NOT walkie-talkie mTALK, NOT PSTN mCALL). Creates a room, returns join credentials (token + media url), and drops a `call_invite` control message in the DM thread so the contact can answer. Set video:true for video.",
643
+ inputSchema: mDM_call_start_input,
644
+ handler: mDM_call_start
645
+ },
646
+ {
647
+ name: "mDM_call_answer",
648
+ requires: "network",
649
+ description: "Answer an incoming 1:1 call by its room_id (from the call_invite seen via mDM_list). Returns join credentials (token + media url) for the same room.",
650
+ inputSchema: mDM_call_answer_input,
651
+ handler: mDM_call_answer
652
+ },
653
+ {
654
+ name: "mDM_call_end",
655
+ requires: "network",
656
+ description: "End a 1:1 call. The audio leg ends when clients disconnect; pass `to` to also drop a `call_end` (hangup) control message in the contact's DM thread.",
657
+ inputSchema: mDM_call_end_input,
658
+ handler: mDM_call_end
659
+ },
660
+ {
661
+ name: "mDM_voice_note",
662
+ requires: "network",
663
+ description: "Send an asynchronous voice note to a contact: references an already-uploaded audio clip (audio_url) and posts it as a `voice_note` message in the DM thread. Use for fire-and-forget voice instead of a live call.",
664
+ inputSchema: mDM_voice_note_input,
665
+ handler: mDM_voice_note
666
+ }
667
+ ];
668
+
669
+ // src/tools/mirc.ts
670
+ import { z as z3 } from "zod";
671
+ var ChannelId = z3.string().min(1).max(120).describe("Channel id (UUID). Use mIRC_list to discover available channels.");
672
+ var AccessMode = z3.enum(["open", "password", "private"]).describe("open: anyone can join \xB7 password: join with a shared password \xB7 private: invite-only.");
673
+ var Capabilities = z3.object({
674
+ txt: z3.boolean().default(true),
675
+ ptt: z3.boolean().default(false),
676
+ live: z3.boolean().default(false)
499
677
  }).describe("Which modes are enabled in this channel: txt (text), ptt (push-to-talk voice), live (live stream).").optional();
500
- var mIRC_create_input = z2.object({
501
- name: z2.string().min(1).max(80).describe("Channel display name."),
502
- topic: z2.string().max(500).optional().describe("Optional channel topic/description."),
503
- access_mode: AccessMode.default("public"),
504
- password: z2.string().min(6).max(120).optional().describe("Password (only for access_mode=private)."),
678
+ var mIRC_create_input = z3.object({
679
+ name: z3.string().min(1).max(80).describe("Channel display name."),
680
+ topic: z3.string().max(500).optional().describe("Optional channel topic/description."),
681
+ access_mode: AccessMode.default("open"),
682
+ password: z3.string().min(6).max(120).optional().describe("Password (only for access_mode=password)."),
505
683
  capabilities: Capabilities
506
684
  });
507
- var mIRC_list_input = z2.object({
508
- limit: z2.number().int().min(1).max(500).default(100).optional(),
509
- offset: z2.number().int().min(0).default(0).optional(),
685
+ var mIRC_list_input = z3.object({
686
+ limit: z3.number().int().min(1).max(500).default(100).optional(),
687
+ offset: z3.number().int().min(0).default(0).optional(),
510
688
  access_mode: AccessMode.optional().describe("Filter to a single access mode.")
511
689
  });
512
- var mIRC_get_input = z2.object({
690
+ var mIRC_get_input = z3.object({
513
691
  channel_id: ChannelId
514
692
  });
515
- var mIRC_update_input = z2.object({
693
+ var mIRC_update_input = z3.object({
516
694
  channel_id: ChannelId,
517
- name: z2.string().min(1).max(80).optional(),
518
- topic: z2.string().max(500).optional(),
695
+ name: z3.string().min(1).max(80).optional(),
696
+ topic: z3.string().max(500).optional(),
519
697
  access_mode: AccessMode.optional(),
520
698
  capabilities: Capabilities
521
699
  });
522
- var mIRC_delete_input = z2.object({
700
+ var mIRC_delete_input = z3.object({
523
701
  channel_id: ChannelId
524
702
  });
525
703
  async function mIRC_create(input, ctx) {
@@ -567,7 +745,7 @@ var mircTools = [
567
745
  {
568
746
  name: "mIRC_create",
569
747
  requires: "network",
570
- description: "Create a new persistent channel (Discord/Slack-style). Set access_mode to public for open join, private for password-gated, invite_only for explicit invites. capabilities controls modes (txt/ptt/live).",
748
+ 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).",
571
749
  inputSchema: mIRC_create_input,
572
750
  handler: mIRC_create
573
751
  },
@@ -602,51 +780,51 @@ var mircTools = [
602
780
  ];
603
781
 
604
782
  // src/tools/mirc-members.ts
605
- import { z as z3 } from "zod";
606
- var ChannelId2 = z3.string().min(1).max(120).describe("Channel id (UUID). From mIRC_list / mIRC_create.");
607
- var MemberIdentity = z3.string().min(1).describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
608
- var Role = z3.enum(["owner", "admin", "moderator", "member", "guest"]).describe("Member role within the channel.");
609
- var mIRC_join_input = z3.object({
783
+ import { z as z4 } from "zod";
784
+ var ChannelId2 = z4.string().min(1).max(120).describe("Channel id (UUID). From mIRC_list / mIRC_create.");
785
+ var MemberIdentity = z4.string().min(1).describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
786
+ var Role = z4.enum(["owner", "admin", "moderator", "member", "guest"]).describe("Member role within the channel.");
787
+ var mIRC_join_input = z4.object({
610
788
  channel_id: ChannelId2,
611
- password: z3.string().min(1).optional().describe("Required if the channel is access_mode=private.")
789
+ password: z4.string().min(1).optional().describe("Required if the channel is access_mode=private.")
612
790
  });
613
- var mIRC_request_access_input = z3.object({
791
+ var mIRC_request_access_input = z4.object({
614
792
  channel_id: ChannelId2,
615
- message: z3.string().max(500).optional().describe("Optional note for the channel owner explaining why.")
793
+ message: z4.string().max(500).optional().describe("Optional note for the channel owner explaining why.")
616
794
  });
617
- var mIRC_leave_input = z3.object({
795
+ var mIRC_leave_input = z4.object({
618
796
  channel_id: ChannelId2
619
797
  });
620
- var mIRC_approve_request_input = z3.object({
798
+ var mIRC_approve_request_input = z4.object({
621
799
  channel_id: ChannelId2,
622
- request_id: z3.string().min(1).describe("Pending request id.")
800
+ request_id: z4.string().min(1).describe("Pending request id.")
623
801
  });
624
802
  var mIRC_reject_request_input = mIRC_approve_request_input;
625
- var mIRC_kick_input = z3.object({
803
+ var mIRC_kick_input = z4.object({
626
804
  channel_id: ChannelId2,
627
805
  identity_id: MemberIdentity,
628
- reason: z3.string().max(500).optional()
806
+ reason: z4.string().max(500).optional()
629
807
  });
630
- var mIRC_ban_input = z3.object({
808
+ var mIRC_ban_input = z4.object({
631
809
  channel_id: ChannelId2,
632
810
  identity_id: MemberIdentity,
633
- reason: z3.string().max(500).optional(),
811
+ reason: z4.string().max(500).optional(),
634
812
  /** Optional unban deadline (ISO-8601). Omit for permanent ban. */
635
- until: z3.string().optional()
813
+ until: z4.string().optional()
636
814
  });
637
- var mIRC_unban_input = z3.object({
815
+ var mIRC_unban_input = z4.object({
638
816
  channel_id: ChannelId2,
639
817
  identity_id: MemberIdentity
640
818
  });
641
- var mIRC_set_role_input = z3.object({
819
+ var mIRC_set_role_input = z4.object({
642
820
  channel_id: ChannelId2,
643
821
  identity_id: MemberIdentity,
644
822
  role: Role
645
823
  });
646
- var mIRC_set_ptt_input = z3.object({
824
+ var mIRC_set_ptt_input = z4.object({
647
825
  channel_id: ChannelId2,
648
826
  identity_id: MemberIdentity,
649
- ptt_enabled: z3.boolean().describe("Allow this member to hold the PTT floor in voice mode.")
827
+ ptt_enabled: z4.boolean().describe("Allow this member to hold the PTT floor in voice mode.")
650
828
  });
651
829
  async function invokeChannelMembers(action, body, ctx) {
652
830
  readSupabaseEnv();
@@ -726,26 +904,239 @@ var mircMembersTools = [
726
904
  }
727
905
  ];
728
906
 
907
+ // src/tools/mirc-messages.ts
908
+ import { z as z5 } from "zod";
909
+ var PROTOCOL_VERSION3 = "mosadd.chat.v1";
910
+ var ChannelId3 = z5.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
911
+ var mIRC_post_message_input = z5.object({
912
+ channel_id: ChannelId3,
913
+ text: z5.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
914
+ reply_to_id: z5.string().optional().describe("Optional id of the message being replied to."),
915
+ space_id: z5.string().optional().describe("Optional backing space id. Resolved automatically from the channel if omitted.")
916
+ });
917
+ var mIRC_list_messages_input = z5.object({
918
+ channel_id: ChannelId3,
919
+ limit: z5.number().int().min(1).max(200).default(50).optional(),
920
+ cursor: z5.string().optional().describe("Opaque pagination cursor from a prior list response."),
921
+ space_id: z5.string().optional().describe("Optional backing space id. Resolved automatically if omitted.")
922
+ });
923
+ function packPlaintextPayload2(text, replyToId) {
924
+ const envelope = {
925
+ v: PROTOCOL_VERSION3,
926
+ type: "text",
927
+ text,
928
+ reply_to: replyToId ?? null,
929
+ sent_at: (/* @__PURE__ */ new Date()).toISOString()
930
+ };
931
+ return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
932
+ }
933
+ function unpackPayload2(payload) {
934
+ try {
935
+ const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
936
+ if (typeof obj?.text === "string") return obj;
937
+ } catch {
938
+ }
939
+ return { text: "<ciphertext>" };
940
+ }
941
+ async function resolveLinkedSpaceId(channelId) {
942
+ const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
943
+ const spaceId = data?.linked_space_id ?? data?.channel?.metadata?.linked_space_id;
944
+ if (!spaceId) {
945
+ throw new Error(
946
+ `Channel ${channelId} has no linked space yet. Run mIRC_list (which repairs linked spaces) or mIRC_join first, or pass space_id explicitly.`
947
+ );
948
+ }
949
+ return spaceId;
950
+ }
951
+ async function mIRC_post_message(input, ctx) {
952
+ readSupabaseEnv();
953
+ const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
954
+ const thread_id = `chat:${input.channel_id}`;
955
+ ctx.log("debug", "mIRC_post_message", { thread_id, space_id });
956
+ const data = await invokeFunction("message-send", {
957
+ space_id,
958
+ thread_id,
959
+ encrypted_payload: packPlaintextPayload2(input.text, input.reply_to_id),
960
+ message_type: "txt",
961
+ protocol_version: PROTOCOL_VERSION3,
962
+ reply_to_id: input.reply_to_id ?? null
963
+ });
964
+ if (!data?.message?.id) throw new Error("message-send returned no message id");
965
+ return { message_id: data.message.id, delivered_at: data.message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(), thread_id };
966
+ }
967
+ async function mIRC_list_messages(input, ctx) {
968
+ readSupabaseEnv();
969
+ const space_id = input.space_id ?? await resolveLinkedSpaceId(input.channel_id);
970
+ const thread_id = `chat:${input.channel_id}`;
971
+ ctx.log("debug", "mIRC_list_messages", { thread_id, space_id });
972
+ const data = await invokeFunction("message-list", {
973
+ space_id,
974
+ thread_id,
975
+ limit: input.limit ?? 50,
976
+ cursor: input.cursor
977
+ });
978
+ return {
979
+ messages: (data?.messages ?? []).map((m) => ({
980
+ id: m.id,
981
+ sender_identity_id: m.sender_identity_id,
982
+ text: unpackPayload2(m.encrypted_payload).text,
983
+ timestamp: m.created_at
984
+ })),
985
+ next_cursor: data?.next_cursor ?? null
986
+ };
987
+ }
988
+ var mircMessagesTools = [
989
+ {
990
+ name: "mIRC_post_message",
991
+ requires: "network",
992
+ 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.",
993
+ inputSchema: mIRC_post_message_input,
994
+ handler: mIRC_post_message
995
+ },
996
+ {
997
+ name: "mIRC_list_messages",
998
+ requires: "network",
999
+ description: "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
1000
+ inputSchema: mIRC_list_messages_input,
1001
+ handler: mIRC_list_messages
1002
+ }
1003
+ ];
1004
+
1005
+ // src/tools/mirc-edge.ts
1006
+ import { z as z6 } from "zod";
1007
+ var DEFAULT_EDGE_URL = "https://mosadd-edge.mr-brics-33.workers.dev";
1008
+ var DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
1009
+ function edgeUrl() {
1010
+ return process.env.MOSADD_EDGE_URL?.replace(/\/$/, "") ?? DEFAULT_EDGE_URL;
1011
+ }
1012
+ function supabaseUrl() {
1013
+ return process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ?? process.env.SUPABASE_URL?.replace(/\/$/, "") ?? DEFAULT_SUPABASE_URL;
1014
+ }
1015
+ function hubKey() {
1016
+ const key = process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? "";
1017
+ if (!key) throw new Error("MOSADD_API_KEY required for mIRC edge tools (see mosadd login or hub-keys).");
1018
+ return key;
1019
+ }
1020
+ var mIRC_send_edge_input = z6.object({
1021
+ channel_id: z6.string().min(1).max(128).describe("Channel id (UUID). Same as mIRC_create / mIRC_list."),
1022
+ text: z6.string().min(1).max(64e3).describe("Message body (UTF-8, max 64 KB)."),
1023
+ from: z6.string().max(120).optional().describe("Sender hint shown to other clients (defaults to the hub-key owner).")
1024
+ });
1025
+ async function mIRC_send_edge(input, ctx) {
1026
+ ctx.log("debug", "mIRC_send_edge", { channel_id: input.channel_id });
1027
+ const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/send`, {
1028
+ method: "POST",
1029
+ headers: {
1030
+ "Content-Type": "application/json",
1031
+ Authorization: `Bearer ${hubKey()}`
1032
+ },
1033
+ body: JSON.stringify({ text: input.text, from: input.from })
1034
+ });
1035
+ if (!r.ok) {
1036
+ const errBody = await r.text().catch(() => "");
1037
+ throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
1038
+ }
1039
+ const data = await r.json();
1040
+ if (!data?.id) throw new Error("mosadd-edge: send returned no id");
1041
+ return { message_id: data.id, delivered_at: data.ts ?? Date.now(), channel_id: input.channel_id };
1042
+ }
1043
+ var mIRC_history_edge_input = z6.object({
1044
+ channel_id: z6.string().min(1).max(128).describe("Channel id (UUID)."),
1045
+ limit: z6.number().int().min(1).max(100).default(50).optional().describe("How many recent messages to return (max 100, the DO ring size).")
1046
+ });
1047
+ async function mIRC_history_edge(input, ctx) {
1048
+ const limit = input.limit ?? 50;
1049
+ ctx.log("debug", "mIRC_history_edge", { channel_id: input.channel_id, limit });
1050
+ const r = await fetch(`${edgeUrl()}/c/${input.channel_id}/history?limit=${limit}`, {
1051
+ headers: { Authorization: `Bearer ${hubKey()}` }
1052
+ });
1053
+ if (!r.ok) {
1054
+ const errBody = await r.text().catch(() => "");
1055
+ throw new Error(`mosadd-edge ${r.status}: ${errBody.slice(0, 200)}`);
1056
+ }
1057
+ const data = await r.json();
1058
+ return {
1059
+ channel_id: input.channel_id,
1060
+ messages: (data.messages ?? []).map((m) => ({
1061
+ id: m.id,
1062
+ from: m.from ?? null,
1063
+ text: m.text,
1064
+ timestamp: m.ts
1065
+ }))
1066
+ };
1067
+ }
1068
+ var mIRC_mint_channel_token_input = z6.object({
1069
+ channel_id: z6.string().min(1).max(128).describe("Channel id \u2014 the JWT will be scoped to this channel only. Must match the WS upgrade path."),
1070
+ user_id: z6.string().min(1).max(120).optional().describe("Optional end-user id. Stamped onto messages as 'from'. Useful when one hub key fronts many end-users (relay topology).")
1071
+ });
1072
+ async function mIRC_mint_channel_token(input, ctx) {
1073
+ ctx.log("debug", "mIRC_mint_channel_token", { channel_id: input.channel_id });
1074
+ const r = await fetch(`${supabaseUrl()}/functions/v1/hub-mint-channel-token`, {
1075
+ method: "POST",
1076
+ headers: {
1077
+ "Content-Type": "application/json",
1078
+ Authorization: `Bearer ${hubKey()}`
1079
+ },
1080
+ body: JSON.stringify({ channel_id: input.channel_id, user_id: input.user_id })
1081
+ });
1082
+ if (!r.ok) {
1083
+ const errBody = await r.text().catch(() => "");
1084
+ throw new Error(`hub-mint-channel-token ${r.status}: ${errBody.slice(0, 200)}`);
1085
+ }
1086
+ const data = await r.json();
1087
+ if (!data?.token || !data?.expires_in || !data?.channel_id || !data?.scope) {
1088
+ throw new Error("hub-mint-channel-token: malformed response");
1089
+ }
1090
+ return data;
1091
+ }
1092
+ var mircEdgeTools = [
1093
+ {
1094
+ name: "mIRC_mint_channel_token",
1095
+ requires: "network",
1096
+ description: "Exchange the hub key (MOSADD_API_KEY) for a short-lived (5min), channel-scoped JWT. Returns { token, expires_in, channel_id, scope }. The token is safe to hand to a browser to open a WS via `Sec-WebSocket-Protocol: mosadd.v1, bearer.<token>`. The hub key NEVER leaves the server. Use this from any server-side route (Next.js /api/chat-token, Express, etc.) before showing chat in a browser. Required by LINEAR-2675/E6 to avoid leaking the hub key into CDN access logs.",
1097
+ inputSchema: mIRC_mint_channel_token_input,
1098
+ handler: mIRC_mint_channel_token
1099
+ },
1100
+ {
1101
+ name: "mIRC_send_edge",
1102
+ requires: "network",
1103
+ description: "Send a text message into a persistent channel via the mosadd-edge Cloudflare Worker (Durable Object backend). Sub-100ms global fan-out to all WebSocket subscribers of the channel + async flush to Supabase as system-of-record (idempotent). Use this when you want native realtime push without polling. Parallel to mIRC_post_message (Supabase path); pick one per channel. Auth: MOSADD_API_KEY env (hub key).",
1104
+ inputSchema: mIRC_send_edge_input,
1105
+ handler: mIRC_send_edge
1106
+ },
1107
+ {
1108
+ name: "mIRC_history_edge",
1109
+ requires: "network",
1110
+ description: "Read the last N (max 100) messages held in the channel's Durable Object ring buffer at the edge. Hot path is the DO, not Supabase \u2014 same data lands in messages_meta via async flush, so cold reads / pagination beyond 100 should use mIRC_list_messages.",
1111
+ inputSchema: mIRC_history_edge_input,
1112
+ handler: mIRC_history_edge
1113
+ }
1114
+ ];
1115
+
729
1116
  // src/tools/mroom.ts
730
- import { z as z4 } from "zod";
731
- var RoomId = z4.string().min(1).describe("Private room id (UUID).");
732
- var mROOM_create_input = z4.object({
733
- ttl_seconds: z4.number().int().min(60).max(86400 * 30).default(86400).optional().describe("Time-to-live in seconds. Defaults to 24 h. Max 30 days.")
1117
+ import { z as z7 } from "zod";
1118
+ var RoomId2 = z7.string().min(1).describe("Private room id (UUID).");
1119
+ var mROOM_voice_join_input = z7.object({
1120
+ room_id: RoomId2,
1121
+ video: z7.boolean().optional().describe("Request video instead of audio-only. Default false.")
734
1122
  });
735
- var mROOM_join_input = z4.object({
736
- room_id: RoomId
1123
+ var mROOM_create_input = z7.object({
1124
+ ttl_seconds: z7.number().int().min(60).max(86400 * 30).default(86400).optional().describe("Time-to-live in seconds. Defaults to 24 h. Max 30 days.")
737
1125
  });
738
- var mROOM_close_input = z4.object({
739
- room_id: RoomId
1126
+ var mROOM_join_input = z7.object({
1127
+ room_id: RoomId2
740
1128
  });
741
- var mROOM_leave_input = z4.object({
742
- room_id: RoomId
1129
+ var mROOM_close_input = z7.object({
1130
+ room_id: RoomId2
743
1131
  });
744
- var mROOM_list_input = z4.object({});
745
- var mROOM_create_guest_link_input = z4.object({
746
- room_id: RoomId,
747
- display_name: z4.string().min(1).max(80).describe("Display name the guest will appear under. They never sign up \u2014 this is the only identifier."),
748
- ttl_seconds: z4.number().int().min(60).max(86400 * 7).default(3600).optional().describe("How long the guest token is valid. Default 1 h, max 7 days.")
1132
+ var mROOM_leave_input = z7.object({
1133
+ room_id: RoomId2
1134
+ });
1135
+ var mROOM_list_input = z7.object({});
1136
+ var mROOM_create_guest_link_input = z7.object({
1137
+ room_id: RoomId2,
1138
+ display_name: z7.string().min(1).max(80).describe("Display name the guest will appear under. They never sign up \u2014 this is the only identifier."),
1139
+ ttl_seconds: z7.number().int().min(60).max(86400 * 7).default(3600).optional().describe("How long the guest token is valid. Default 1 h, max 7 days.")
749
1140
  });
750
1141
  async function mROOM_create(input, ctx) {
751
1142
  readSupabaseEnv();
@@ -801,6 +1192,17 @@ async function mROOM_create_guest_link(input, ctx) {
801
1192
  expires_at: result.expires_at
802
1193
  };
803
1194
  }
1195
+ async function mROOM_voice_join(input, ctx) {
1196
+ const ticket = await ctx.providers.voice.joinTicket(input.room_id);
1197
+ ctx.log("debug", "mROOM_voice_join", { room_id: ticket.roomId, identity: ticket.identity });
1198
+ return {
1199
+ room_id: ticket.roomId,
1200
+ token: ticket.token,
1201
+ url: ticket.url,
1202
+ identity: ticket.identity,
1203
+ mode: input.video ? "video" : "audio"
1204
+ };
1205
+ }
804
1206
  var mroomTools = [
805
1207
  {
806
1208
  name: "mROOM_create",
@@ -843,26 +1245,33 @@ var mroomTools = [
843
1245
  description: "List private rooms the current user belongs to.",
844
1246
  inputSchema: mROOM_list_input,
845
1247
  handler: mROOM_list
1248
+ },
1249
+ {
1250
+ name: "mROOM_voice_join",
1251
+ requires: "network",
1252
+ description: "Join an mROOM's full-duplex GROUP voice (everyone can talk \u2014 no walkie-talkie floor; that's mTALK). Returns media credentials (token + url) for the room's audio/video transport. Be a room member first (mROOM_join or a guest link). Set video:true for video.",
1253
+ inputSchema: mROOM_voice_join_input,
1254
+ handler: mROOM_voice_join
846
1255
  }
847
1256
  ];
848
1257
 
849
1258
  // src/tools/mroom-messages.ts
850
- import { z as z5 } from "zod";
851
- var PROTOCOL_VERSION2 = "mosadd.chat.v1";
852
- var RoomId2 = z5.string().min(1).describe("Private room id (UUID). From mROOM_create / mROOM_list.");
853
- var mROOM_send_message_input = z5.object({
854
- room_id: RoomId2,
855
- text: z5.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
856
- reply_to_id: z5.string().optional().describe("Optional id of the message being replied to.")
1259
+ import { z as z8 } from "zod";
1260
+ var PROTOCOL_VERSION4 = "mosadd.chat.v1";
1261
+ var RoomId3 = z8.string().min(1).describe("Private room id (UUID). From mROOM_create / mROOM_list.");
1262
+ var mROOM_send_message_input = z8.object({
1263
+ room_id: RoomId3,
1264
+ text: z8.string().min(1).max(64e3).describe("Message body (UTF-8). Max 64 KB."),
1265
+ reply_to_id: z8.string().optional().describe("Optional id of the message being replied to.")
857
1266
  });
858
- var mROOM_list_messages_input = z5.object({
859
- room_id: RoomId2,
860
- limit: z5.number().int().min(1).max(200).default(50).optional(),
861
- cursor: z5.string().optional().describe("Opaque pagination cursor from a prior list response.")
1267
+ var mROOM_list_messages_input = z8.object({
1268
+ room_id: RoomId3,
1269
+ limit: z8.number().int().min(1).max(200).default(50).optional(),
1270
+ cursor: z8.string().optional().describe("Opaque pagination cursor from a prior list response.")
862
1271
  });
863
- function packPlaintextPayload2(text, replyToId) {
1272
+ function packPlaintextPayload3(text, replyToId) {
864
1273
  const envelope = {
865
- v: PROTOCOL_VERSION2,
1274
+ v: PROTOCOL_VERSION4,
866
1275
  type: "text",
867
1276
  text,
868
1277
  reply_to: replyToId ?? null,
@@ -870,7 +1279,7 @@ function packPlaintextPayload2(text, replyToId) {
870
1279
  };
871
1280
  return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
872
1281
  }
873
- function unpackPayload2(payload) {
1282
+ function unpackPayload3(payload) {
874
1283
  try {
875
1284
  const json = Buffer.from(payload, "base64").toString("utf8");
876
1285
  const obj = JSON.parse(json);
@@ -888,9 +1297,9 @@ async function mROOM_send_message(input, ctx) {
888
1297
  {
889
1298
  space_id: "rooms",
890
1299
  thread_id,
891
- encrypted_payload: packPlaintextPayload2(input.text, input.reply_to_id),
1300
+ encrypted_payload: packPlaintextPayload3(input.text, input.reply_to_id),
892
1301
  message_type: "text",
893
- protocol_version: PROTOCOL_VERSION2,
1302
+ protocol_version: PROTOCOL_VERSION4,
894
1303
  reply_to_id: input.reply_to_id ?? null
895
1304
  }
896
1305
  );
@@ -917,7 +1326,7 @@ async function mROOM_list_messages(input, ctx) {
917
1326
  messages: (data?.messages ?? []).map((m) => ({
918
1327
  id: m.id,
919
1328
  sender_identity_id: m.sender_identity_id,
920
- text: unpackPayload2(m.encrypted_payload).text,
1329
+ text: unpackPayload3(m.encrypted_payload).text,
921
1330
  timestamp: m.created_at
922
1331
  })),
923
1332
  next_cursor: data?.next_cursor ?? null
@@ -941,23 +1350,31 @@ var mroomMessagesTools = [
941
1350
  ];
942
1351
 
943
1352
  // src/tools/mail.ts
944
- import { z as z6 } from "zod";
945
- var EmailAddress = z6.string().email().max(254).describe("RFC 5321 email address.");
946
- var MessageId = z6.string().min(1).describe("Message id (UUID) from mAIL_send or inbox.");
947
- var mAIL_send_input = z6.object({
948
- to: z6.union([EmailAddress, z6.array(EmailAddress).min(1).max(50)]).describe(
1353
+ import { z as z9 } from "zod";
1354
+ var EmailAddress = z9.string().email().max(254).describe("RFC 5321 email address.");
1355
+ var MessageId = z9.string().min(1).describe("Message id (UUID) from mAIL_send or inbox.");
1356
+ var mAIL_send_input = z9.object({
1357
+ to: z9.union([EmailAddress, z9.array(EmailAddress).min(1).max(50)]).describe(
949
1358
  "Recipient(s). Single address or array of up to 50."
950
1359
  ),
951
- subject: z6.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
952
- body_text: z6.string().max(1048576).optional().describe("Plain text body. Max 1 MB."),
953
- body_html: z6.string().max(1048576).optional().describe("HTML body. Max 1 MB."),
954
- cc: z6.array(EmailAddress).max(50).optional(),
955
- bcc: z6.array(EmailAddress).max(50).optional(),
1360
+ subject: z9.string().min(1).max(998).describe("Email subject line. Max 998 chars (RFC 5322)."),
1361
+ body_text: z9.string().max(1048576).optional().describe("Plain text body. Max 1 MB."),
1362
+ body_html: z9.string().max(1048576).optional().describe("HTML body. Max 1 MB."),
1363
+ cc: z9.array(EmailAddress).max(50).optional(),
1364
+ bcc: z9.array(EmailAddress).max(50).optional(),
956
1365
  reply_to: EmailAddress.optional()
957
1366
  });
958
- var mAIL_view_input = z6.object({
1367
+ var mAIL_view_input = z9.object({
1368
+ message_id: MessageId
1369
+ });
1370
+ var mAIL_delete_input = z9.object({
959
1371
  message_id: MessageId
960
1372
  });
1373
+ var mAIL_list_input = z9.object({
1374
+ direction: z9.enum(["inbound", "outbound"]).optional().describe("Filter to received (inbound) or sent (outbound) mail. Omit for both."),
1375
+ limit: z9.number().int().min(1).max(200).optional().describe("Max emails to return. Default 50."),
1376
+ before: z9.string().optional().describe("Pagination cursor: pass the previous response's next_cursor to get the next (older) page.")
1377
+ });
961
1378
  async function mAIL_send(input, ctx) {
962
1379
  readSupabaseEnv();
963
1380
  if (!input.body_text && !input.body_html) {
@@ -971,7 +1388,30 @@ async function mAIL_view(input, ctx) {
971
1388
  ctx.log("debug", "mAIL_view invoking mp0st-view", { message_id: input.message_id });
972
1389
  return await invokeFunction("mp0st-view", { message_id: input.message_id });
973
1390
  }
1391
+ async function mAIL_list(input, ctx) {
1392
+ readSupabaseEnv();
1393
+ ctx.log("debug", "mAIL_list invoking mp0st-list", { direction: input.direction });
1394
+ return await invokeFunction("mp0st-list", {
1395
+ direction: input.direction ?? null,
1396
+ limit: input.limit ?? 50,
1397
+ before: input.before ?? null
1398
+ });
1399
+ }
1400
+ async function mAIL_delete(input, ctx) {
1401
+ readSupabaseEnv();
1402
+ ctx.log("debug", "mAIL_delete invoking mp0st-delete", { message_id: input.message_id });
1403
+ return await invokeFunction("mp0st-delete", {
1404
+ message_id: input.message_id
1405
+ });
1406
+ }
974
1407
  var mailTools = [
1408
+ {
1409
+ name: "mAIL_list",
1410
+ requires: "network",
1411
+ description: "List the user's mailbox (their <userId>@mosadd.com inbox/outbox) newest-first, with sender, subject, status and a short snippet. Filter by direction ('inbound' = received, 'outbound' = sent). Use the returned next_cursor with `before` to page through older mail. Call mAIL_view to read a full message body.",
1412
+ inputSchema: mAIL_list_input,
1413
+ handler: mAIL_list
1414
+ },
975
1415
  {
976
1416
  name: "mAIL_send",
977
1417
  requires: "network",
@@ -985,11 +1425,151 @@ var mailTools = [
985
1425
  description: "Read the full body and metadata of an email by message_id.",
986
1426
  inputSchema: mAIL_view_input,
987
1427
  handler: mAIL_view
1428
+ },
1429
+ {
1430
+ name: "mAIL_delete",
1431
+ requires: "network",
1432
+ description: "Delete one of the user's emails by message_id (from mAIL_list). Soft-delete \u2014 it stops showing in mAIL_list. Owner-scoped: only your own mail.",
1433
+ inputSchema: mAIL_delete_input,
1434
+ handler: mAIL_delete
1435
+ }
1436
+ ];
1437
+
1438
+ // src/tools/mtalk.ts
1439
+ import { z as z10 } from "zod";
1440
+ 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.");
1441
+ var RoomId4 = z10.string().min(1).describe("Room id returned by mTALK_open.");
1442
+ var mTALK_open_input = z10.object({
1443
+ label: RoomLabel.optional().describe("Optional label; defaults to a personal room.")
1444
+ });
1445
+ var mTALK_join_input = z10.object({ room_id: RoomId4 });
1446
+ var mTALK_press_input = z10.object({ room_id: RoomId4 });
1447
+ var mTALK_release_input = z10.object({ room_id: RoomId4 });
1448
+ var mTALK_state_input = z10.object({ room_id: RoomId4 });
1449
+ async function mTALK_open(input, ctx) {
1450
+ const { roomId } = await ctx.providers.voice.createRoom(input.label);
1451
+ ctx.log("debug", "mTALK_open", { room_id: roomId });
1452
+ return { room_id: roomId };
1453
+ }
1454
+ async function mTALK_join(input, ctx) {
1455
+ const ticket = await ctx.providers.voice.joinTicket(input.room_id);
1456
+ ctx.log("debug", "mTALK_join", { room_id: ticket.roomId, identity: ticket.identity });
1457
+ return { room_id: ticket.roomId, token: ticket.token, url: ticket.url, identity: ticket.identity };
1458
+ }
1459
+ async function mTALK_press(input, ctx) {
1460
+ const res = await ctx.providers.voice.requestFloor(input.room_id);
1461
+ ctx.log("debug", "mTALK_press", { room_id: input.room_id, granted: res.granted, position: res.position });
1462
+ return { granted: res.granted, position: res.position, holder: res.snapshot.holder, queue: res.snapshot.queue };
1463
+ }
1464
+ async function mTALK_release(input, ctx) {
1465
+ const snap = await ctx.providers.voice.releaseFloor(input.room_id);
1466
+ ctx.log("debug", "mTALK_release", { room_id: input.room_id, holder: snap.holder });
1467
+ return { holder: snap.holder, queue: snap.queue };
1468
+ }
1469
+ async function mTALK_state(input, ctx) {
1470
+ const snap = await ctx.providers.voice.floorState(input.room_id);
1471
+ return { holder: snap.holder, since: snap.since, queue: snap.queue };
1472
+ }
1473
+ var mtalkTools = [
1474
+ {
1475
+ name: "mTALK_open",
1476
+ requires: "any",
1477
+ description: "Open (or get) a push-to-talk room. Returns a stable room_id. Pass an optional label to share a named room (e.g. 'ops'); omit it for a personal room. Works over network (LiveKit) or off-grid radio depending on the host.",
1478
+ inputSchema: mTALK_open_input,
1479
+ handler: mTALK_open
1480
+ },
1481
+ {
1482
+ name: "mTALK_join",
1483
+ requires: "network",
1484
+ description: "Get credentials (token + media URL) to join a PTT room's audio transport. Hand these to a human or bot client to connect. The agent itself drives the floor with mTALK_press / mTALK_release.",
1485
+ inputSchema: mTALK_join_input,
1486
+ handler: mTALK_join
1487
+ },
1488
+ {
1489
+ name: "mTALK_press",
1490
+ requires: "any",
1491
+ description: "Press push-to-talk: request the floor in a room. Half-duplex \u2014 if no one is transmitting you are GRANTED the floor (granted=true) and may speak; otherwise you are queued FIFO and `position` tells you where you are. Call mTALK_release when done. A holder who never releases is auto-bumped after the anti-hog timeout.",
1492
+ inputSchema: mTALK_press_input,
1493
+ handler: mTALK_press
1494
+ },
1495
+ {
1496
+ name: "mTALK_release",
1497
+ requires: "any",
1498
+ description: "Release push-to-talk: give up the floor (or cancel your queued request). If you held the floor, the next participant in the queue is promoted automatically. Returns the new holder and queue.",
1499
+ inputSchema: mTALK_release_input,
1500
+ handler: mTALK_release
1501
+ },
1502
+ {
1503
+ name: "mTALK_state",
1504
+ requires: "any",
1505
+ description: "Read a PTT room's floor state without changing it: who is currently transmitting (holder), since when, and the waiting queue.",
1506
+ inputSchema: mTALK_state_input,
1507
+ handler: mTALK_state
1508
+ }
1509
+ ];
1510
+
1511
+ // src/tools/knowledge.ts
1512
+ import { z as z11 } from "zod";
1513
+ var mRAG_search_input = z11.object({
1514
+ query: z11.string().min(1).max(2e3).describe("Natural-language question to answer from the user's own indexed messages/emails/calls/notes."),
1515
+ top_k: z11.number().int().min(1).max(25).optional().describe("Max number of source chunks to retrieve and ground the answer in. Default 8."),
1516
+ source_types: z11.array(z11.enum(["message", "email", "call", "note", "contact"])).optional().describe("Restrict retrieval to these source types. Omit to search everything."),
1517
+ thread_id: z11.string().optional().describe("Optional: restrict retrieval to a single thread id (e.g. a dm:/chat: thread).")
1518
+ });
1519
+ async function mRAG_search(input, ctx) {
1520
+ readSupabaseEnv();
1521
+ ctx.log("debug", "mRAG_search via rag-query", { top_k: input.top_k ?? 8 });
1522
+ const data = await invokeFunction("rag-query", {
1523
+ query: input.query,
1524
+ top_k: input.top_k ?? 8,
1525
+ source_types: input.source_types ?? null,
1526
+ thread_id: input.thread_id ?? null
1527
+ });
1528
+ return {
1529
+ answer: data.answer ?? "",
1530
+ sources: data.sources ?? [],
1531
+ chunks_found: data.chunks_found ?? (data.sources?.length ?? 0)
1532
+ };
1533
+ }
1534
+ var mRAG_ingest_input = z11.object({
1535
+ content_text: z11.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."),
1536
+ source_type: z11.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."),
1537
+ source_id: z11.string().optional().describe("Optional stable id for the source so re-ingests can be grouped."),
1538
+ thread_id: z11.string().optional().describe("Optional thread id to associate this knowledge with (e.g. a dm:/chat: thread)."),
1539
+ title: z11.string().max(300).optional().describe("Optional human title, stored in metadata.")
1540
+ });
1541
+ async function mRAG_ingest(input, ctx) {
1542
+ readSupabaseEnv();
1543
+ const backendType = input.source_type === "note" ? "file" : input.source_type ?? "file";
1544
+ ctx.log("debug", "mRAG_ingest via rag-index", { source_type: backendType });
1545
+ const data = await invokeFunction("rag-index", {
1546
+ source_type: backendType,
1547
+ source_id: input.source_id ?? null,
1548
+ thread_id: input.thread_id ?? null,
1549
+ content_text: input.content_text,
1550
+ metadata: { ...input.title ? { title: input.title } : {}, ingested_via: "mRAG_ingest" }
1551
+ });
1552
+ return { indexed: data.indexed ?? 0, chunk_count: data.chunk_count ?? 0 };
1553
+ }
1554
+ var knowledgeTools = [
1555
+ {
1556
+ name: "mRAG_ingest",
1557
+ requires: "network",
1558
+ 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.",
1559
+ inputSchema: mRAG_ingest_input,
1560
+ handler: mRAG_ingest
1561
+ },
1562
+ {
1563
+ name: "mRAG_search",
1564
+ requires: "network",
1565
+ description: "Search and answer questions over the USER'S OWN mosadd data (messages, emails, calls, notes) with a private per-user RAG index \u2014 hybrid vector + keyword retrieval, reranked, grounded in cited sources (no fabrication). Use it to recall 'what did X say about Y', summarize a thread, or pull facts the user has received. Returns an answer plus the source snippets it used. This is agent memory (mRAG = RAG over your own data) over the user's communications, available outside the mosadd app. NOTE: RAG requires content to be indexed server-side in plaintext, so anything searchable here is NOT covered by the zero-knowledge / E2EE guarantee \u2014 only data the user has explicitly opted into indexing is searchable. See docs/security/e2ee-posture.md.",
1566
+ inputSchema: mRAG_search_input,
1567
+ handler: mRAG_search
988
1568
  }
989
1569
  ];
990
1570
 
991
1571
  // src/tools/capabilities.ts
992
- import { z as z7 } from "zod";
1572
+ import { z as z12 } from "zod";
993
1573
  var CONTRACT_VERSION = "1.0.0";
994
1574
  var ALL_REQUIREMENTS = ["any", "radio", "network"];
995
1575
  function buildCapabilityManifest(tools) {
@@ -1012,7 +1592,7 @@ function makeCapabilitiesTool(channelTools2) {
1012
1592
  name: "comms_capabilities",
1013
1593
  requires: "any",
1014
1594
  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.",
1015
- inputSchema: z7.object({}),
1595
+ inputSchema: z12.object({}),
1016
1596
  handler: async () => buildCapabilityManifest([...channelTools2, tool])
1017
1597
  };
1018
1598
  return tool;
@@ -1021,12 +1601,18 @@ function makeCapabilitiesTool(channelTools2) {
1021
1601
  // src/tools/index.ts
1022
1602
  var channelTools = [
1023
1603
  ...mdmTools,
1604
+ ...mdmVoiceTools,
1024
1605
  ...mircTools,
1025
1606
  ...mircMembersTools,
1607
+ ...mircMessagesTools,
1608
+ ...mircEdgeTools,
1026
1609
  ...mroomTools,
1027
1610
  ...mroomMessagesTools,
1028
- ...mailTools
1029
- // mtalkTools, mcallTools, mirlTools,
1611
+ ...mailTools,
1612
+ ...mtalkTools,
1613
+ ...knowledgeTools
1614
+ // ...mcallTools, // mCALL: carrier-pending (no telephony carrier live) — re-register when a carrier is configured
1615
+ // mirlTools,
1030
1616
  // mmatrixTools, mdiscordTools, mtelegramTools, mslackTools, msignalTools,
1031
1617
  //
1032
1618
  // Each m* module registers its tools here as it ships.
@@ -1043,7 +1629,7 @@ var allTools = [
1043
1629
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1044
1630
 
1045
1631
  // src/providers/supabase-dm.ts
1046
- var PROTOCOL_VERSION3 = "mosadd.chat.v1";
1632
+ var PROTOCOL_VERSION5 = "mosadd.chat.v1";
1047
1633
  var SupabaseDmProvider = class {
1048
1634
  cachedSelfId = null;
1049
1635
  async selfId() {
@@ -1070,7 +1656,7 @@ var SupabaseDmProvider = class {
1070
1656
  thread_id: args.threadId,
1071
1657
  encrypted_payload,
1072
1658
  message_type: "text",
1073
- protocol_version: PROTOCOL_VERSION3,
1659
+ protocol_version: PROTOCOL_VERSION5,
1074
1660
  recipient_account_id: args.to,
1075
1661
  reply_to_id: args.replyToId ?? null
1076
1662
  });
@@ -1114,11 +1700,68 @@ var SupabaseDmProvider = class {
1114
1700
  }
1115
1701
  };
1116
1702
 
1703
+ // src/providers/supabase-voice.ts
1704
+ var ROOM_PREFIX = "mosadd-room-";
1705
+ var SupabaseVoiceProvider = class {
1706
+ cachedSelfId = null;
1707
+ async selfId() {
1708
+ if (this.cachedSelfId) return this.cachedSelfId;
1709
+ readSupabaseEnv();
1710
+ const sb = getSupabase();
1711
+ const { data: u, error: ue } = await sb.auth.getUser();
1712
+ if (ue || !u?.user) {
1713
+ throw new Error(
1714
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token."
1715
+ );
1716
+ }
1717
+ const { data: identity, error } = await sb.from("identities").select("id").eq("user_id", u.user.id).maybeSingle();
1718
+ if (error || !identity) {
1719
+ throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
1720
+ }
1721
+ this.cachedSelfId = identity.id;
1722
+ return this.cachedSelfId;
1723
+ }
1724
+ async createRoom(label) {
1725
+ const self = await this.selfId();
1726
+ const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
1727
+ return { roomId };
1728
+ }
1729
+ async joinTicket(roomId) {
1730
+ const self = await this.selfId();
1731
+ const data = await invokeFunction("livekit-token", {
1732
+ roomName: roomId,
1733
+ identity: self
1734
+ });
1735
+ return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
1736
+ }
1737
+ async requestFloor(roomId) {
1738
+ return invokeFunction("mtalk-floor", { action: "request", room_id: roomId });
1739
+ }
1740
+ async releaseFloor(roomId) {
1741
+ const data = await invokeFunction("mtalk-floor", {
1742
+ action: "release",
1743
+ room_id: roomId
1744
+ });
1745
+ return data.snapshot;
1746
+ }
1747
+ async floorState(roomId) {
1748
+ const data = await invokeFunction("mtalk-floor", {
1749
+ action: "state",
1750
+ room_id: roomId
1751
+ });
1752
+ return data.snapshot;
1753
+ }
1754
+ };
1755
+ function slug(s) {
1756
+ return s.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 200);
1757
+ }
1758
+
1117
1759
  // src/server.ts
1118
1760
  function defaultProviders(injected) {
1119
1761
  return {
1120
1762
  dm: injected?.dm ?? new SupabaseDmProvider(),
1121
- keys: injected?.keys ?? new InMemoryMdmKeyStore()
1763
+ keys: injected?.keys ?? new InMemoryMdmKeyStore(),
1764
+ voice: injected?.voice ?? new SupabaseVoiceProvider()
1122
1765
  };
1123
1766
  }
1124
1767
  function createMosaddServer(options = {}) {