@mosadd/mcp 3.0.0-alpha.7 → 3.0.0

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 (66) hide show
  1. package/CHANGELOG.md +410 -0
  2. package/README.md +79 -40
  3. package/dist/bin/mcp.js +132 -8
  4. package/dist/chunk-VMMJJYXF.js +4233 -0
  5. package/dist/index.d.ts +110 -6
  6. package/dist/index.js +3 -1
  7. package/package.json +19 -16
  8. package/src/__tests__/blob-upload.test.ts +93 -0
  9. package/src/__tests__/channel-e2ee.test.ts +62 -0
  10. package/src/__tests__/cli.test.ts +47 -0
  11. package/src/__tests__/flota-jawnie.test.ts +244 -0
  12. package/src/__tests__/golden-path.test.ts +4 -2
  13. package/src/__tests__/integration.test.ts +50 -11
  14. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  15. package/src/__tests__/label-room-owner.test.ts +22 -0
  16. package/src/__tests__/mdm-e2ee.test.ts +35 -1
  17. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  18. package/src/__tests__/mirc-invite.test.ts +112 -0
  19. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  20. package/src/__tests__/no-dead-host.test.ts +37 -0
  21. package/src/__tests__/presence.test.ts +199 -0
  22. package/src/__tests__/server.test.ts +11 -7
  23. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  24. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  25. package/src/__tests__/voice-fields.test.ts +24 -0
  26. package/src/bin/mcp.ts +71 -6
  27. package/src/cli.ts +100 -0
  28. package/src/crypto/channel-e2ee.ts +288 -0
  29. package/src/crypto/mdm-session.ts +476 -37
  30. package/src/index.ts +2 -2
  31. package/src/providers/blob-upload.ts +162 -0
  32. package/src/providers/supabase-dm.ts +102 -7
  33. package/src/providers/supabase-voice.ts +13 -1
  34. package/src/providers/supabase.ts +121 -10
  35. package/src/server.ts +102 -12
  36. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  37. package/src/tools/actions.ts +166 -0
  38. package/src/tools/attachments.ts +276 -0
  39. package/src/tools/capabilities.ts +2 -0
  40. package/src/tools/channel-payload.ts +69 -0
  41. package/src/tools/embed.ts +110 -0
  42. package/src/tools/index.ts +136 -6
  43. package/src/tools/knowledge-graph.ts +186 -0
  44. package/src/tools/knowledge.ts +351 -191
  45. package/src/tools/mail-agentbox.ts +155 -0
  46. package/src/tools/mail-aliases.ts +25 -0
  47. package/src/tools/mail-provenance.ts +137 -0
  48. package/src/tools/mail.ts +214 -60
  49. package/src/tools/mdm-as-agent.ts +138 -0
  50. package/src/tools/mdm-voice.ts +17 -3
  51. package/src/tools/mdm.ts +303 -57
  52. package/src/tools/mirc-edge.ts +8 -2
  53. package/src/tools/mirc-members.ts +130 -20
  54. package/src/tools/mirc-messages.ts +80 -35
  55. package/src/tools/mirc.ts +149 -11
  56. package/src/tools/mroom-messages.ts +4 -12
  57. package/src/tools/mtalk.ts +11 -1
  58. package/src/tools/murl.ts +314 -0
  59. package/src/tools/presence.ts +442 -0
  60. package/src/tools/ptt-ingest.ts +99 -0
  61. package/src/tools/threat.ts +123 -0
  62. package/src/tools/voice-format.ts +43 -0
  63. package/src/types.ts +36 -0
  64. package/src/version.ts +8 -0
  65. package/LICENSE +0 -201
  66. package/dist/chunk-EFTB743G.js +0 -1924
@@ -1,5 +1,5 @@
1
1
  /**
2
- * mIRC channel members — join, leave, kick, ban, set-role, set-ptt.
2
+ * mIRC channel members — join, leave, invite, kick, ban, set-role, set-ptt.
3
3
  *
4
4
  * Wraps the mosadd backend's `channel-members-manage` Edge Function (audit ab6c885f),
5
5
  * which dispatches on the `action` body field.
@@ -28,42 +28,94 @@ const MemberIdentity = z
28
28
  .describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
29
29
 
30
30
  const Role = z
31
- .enum(["owner", "admin", "moderator", "member", "guest"])
32
- .describe("Member role within the channel.");
31
+ .enum(["superadmin", "admin", "moderator", "member"])
32
+ .describe("Role to assign. owner = channel creator (not assignable); promote up to one tier below your own.");
33
33
 
34
34
  const mIRC_join_input = z.object({
35
35
  channel_id: ChannelId,
36
- password: z.string().min(1).optional().describe("Required if the channel is access_mode=private."),
36
+ password: z.string().min(1).optional().describe("Pass only for access_mode=password channels. Private channels cannot be joined directly (403) — use mIRC_request_access."),
37
37
  });
38
38
 
39
39
  const mIRC_request_access_input = z.object({
40
40
  channel_id: ChannelId,
41
- message: z.string().max(500).optional().describe("Optional note for the channel owner explaining why."),
42
41
  });
43
42
 
43
+ // ---- mIRC_invite ----
44
+ // Wraps channel-members-manage `invite`, which forks on WHO the target is:
45
+ // · an agent/robot the CALLER OWNS → membership is written NOW — channel_members + the linked
46
+ // space_members row (+ a channel_keys row when wrapped_group_key is given) — and the reply is
47
+ // { auto_joined: true, member }. No code, nothing to redeem (LINEAR-5596: a code minted for
48
+ // your own agent is a dead letter — it has no keyboard to paste it into);
49
+ // · a human, or an agent owned by somebody ELSE → the reply is { invite: { code, … } }: an
50
+ // invite code (kod zaproszenia) the recipient redeems in the app ("+ → I have an invite code").
51
+ // Why this tool is P0: mIRC_join adds the KEY's identity (the account — usually the human), while
52
+ // message-send signs channel posts with the AGENT. So every channel created from the toolkit was
53
+ // MUTE — its agent was never a member and each post 403'd agent_not_in_channel — until someone
54
+ // opened the app's member drawer. This is that drawer, callable.
55
+ const InviteRole = z
56
+ .enum(["member", "moderator", "admin"])
57
+ .describe("Role the invitee lands with (default member). Must be strictly below your own role — the EF applies the same tier rule as mIRC_set_role.");
58
+
59
+ const mIRC_invite_input = z.object({
60
+ channel_id: ChannelId,
61
+ identity_id: z
62
+ .string()
63
+ .min(1)
64
+ .describe("Identity id (UUID) of who to add. Your own agents: mDM_list_my_agents → agents[].identity_id (that list is kind=agent ONLY — a robot you own is NOT in it; take the robot's identity id from the app's Robots page). People / other people's agents: mDM_list_contacts."),
65
+ role: InviteRole.optional(),
66
+ wrapped_group_key: z
67
+ .string()
68
+ .optional()
69
+ .describe(
70
+ "Required on password/private channels that hold a group key: the channel group key wrapped to the INVITEE's identity key (the same material mIRC_approve_request takes). Without it the EF refuses with 400 ('This channel is encrypted — unlock your vault…'). Open channels: omit.",
71
+ ),
72
+ ttl_seconds: z
73
+ .number()
74
+ .int()
75
+ .min(300)
76
+ .max(30 * 86400)
77
+ .optional()
78
+ .describe("Lifetime of an invite CODE (code path only; ignored when the target auto-joins). Default 7 days; the EF clamps to 5 min … 30 days."),
79
+ });
80
+
81
+ export type MircInviteInput = z.infer<typeof mIRC_invite_input>;
82
+
44
83
  const mIRC_leave_input = z.object({
45
84
  channel_id: ChannelId,
46
85
  });
47
86
 
48
- const mIRC_approve_request_input = z.object({
87
+ // EF channel-members-manage reads `target_identity_id` (the normalizer below maps
88
+ // identity_id → target_identity_id). The old `request_id` field was ignored →
89
+ // 400 "target_identity_id required" on every approve/reject.
90
+ const mIRC_reject_request_input = z.object({
49
91
  channel_id: ChannelId,
50
- request_id: z.string().min(1).describe("Pending request id."),
92
+ identity_id: z.string().min(1).describe("Identity id of the requester to reject (state=requested; from mIRC_list members)."),
51
93
  });
52
94
 
53
- const mIRC_reject_request_input = mIRC_approve_request_input;
95
+ const mIRC_approve_request_input = mIRC_reject_request_input.extend({
96
+ wrapped_group_key: z
97
+ .string()
98
+ .optional()
99
+ .describe(
100
+ "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.)",
101
+ ),
102
+ });
54
103
 
55
104
  const mIRC_kick_input = z.object({
56
105
  channel_id: ChannelId,
57
106
  identity_id: MemberIdentity,
58
- reason: z.string().max(500).optional(),
107
+ // NOTE: a `reason` field used to be advertised here but channel-members-manage
108
+ // never persists it (no audit row on kick) — removed until the backend logs it
109
+ // (see consistency ticket) so the tool doesn't claim an audit trail it can't deliver.
59
110
  });
60
111
 
61
112
  const mIRC_ban_input = z.object({
62
113
  channel_id: ChannelId,
63
114
  identity_id: MemberIdentity,
64
- reason: z.string().max(500).optional(),
65
- /** Optional unban deadline (ISO-8601). Omit for permanent ban. */
66
- until: z.string().optional(),
115
+ // NOTE: `reason` (no storage) and `until` (timed ban) were removed — the EF ban
116
+ // branch ignores both, so `until` produced a SILENT PERMANENT ban when a caller
117
+ // asked for a temporary one. Ban is permanent-until-unban; enforced temp-bans +
118
+ // ban audit are tracked in the consistency ticket.
67
119
  });
68
120
 
69
121
  const mIRC_unban_input = z.object({
@@ -90,9 +142,34 @@ async function invokeChannelMembers(
90
142
  body: Record<string, unknown>,
91
143
  ctx: MosaddToolContext,
92
144
  ): Promise<unknown> {
145
+ // Map the toolkit's intuitive input field names to the exact ones the
146
+ // channel-members-manage Edge Function reads. Without this, kick/ban/unban/
147
+ // set-role/set-ptt all 400 ("target_identity_id required"), set-role is
148
+ // ignored, and set-ptt silently disables PTT (missing can_ptt → false).
149
+ const b: Record<string, unknown> = { ...body };
150
+ if ("identity_id" in b) { b.target_identity_id = b.identity_id; delete b.identity_id; }
151
+ // ⛔ PUŁAPKA role → new_role. set-role reads `new_role`, but the EF's `invite` branch reads
152
+ // `body.role` (channel-members-manage: `const inviteRole = … body?.role …`). Renaming here would
153
+ // silently drop the requested role — every invite would land as "member" with no error anywhere —
154
+ // so for invite the field goes through under its own name.
155
+ if ("role" in b && action !== "invite") { b.new_role = b.role; delete b.role; }
156
+ if ("ptt_enabled" in b) { b.can_ptt = b.ptt_enabled; delete b.ptt_enabled; }
93
157
  readSupabaseEnv();
94
- ctx.log("debug", `mIRC.${action}`, body);
95
- return await invokeFunction("channel-members-manage", { action, ...body });
158
+ ctx.log("debug", `mIRC.${action}`, b);
159
+ return await invokeFunction("channel-members-manage", { action, ...b });
160
+ }
161
+
162
+ /** Reply of channel-members-manage `invite` — two branches, see the mIRC_invite note above. */
163
+ export type MircInviteResult =
164
+ | { auto_joined: true; member: unknown }
165
+ | { invite: { id: string; code: string; token_prefix: string; role: string; target_identity_id: string; expires_at: string } };
166
+
167
+ /**
168
+ * ONE path to the EF, shared by mIRC_invite and mIRC_create's `invite_agents` fan-out — so the
169
+ * field-name normalizer (and its invite exemption) cannot be bypassed by a second copy.
170
+ */
171
+ export async function inviteToChannel(input: MircInviteInput, ctx: MosaddToolContext): Promise<MircInviteResult> {
172
+ return (await invokeChannelMembers("invite", input as Record<string, unknown>, ctx)) as MircInviteResult;
96
173
  }
97
174
 
98
175
  // ---- Registration ----
@@ -100,22 +177,40 @@ async function invokeChannelMembers(
100
177
  export const mircMembersTools: MosaddTool[] = [
101
178
  {
102
179
  name: "mIRC_join",
180
+ title: "Join channel",
181
+ annotations: { readOnlyHint: false },
103
182
  requires: "network",
104
183
  description:
105
- "Join a channel as the current user. For private channels pass `password`. Returns a membership row or 409 if already a member.",
184
+ "Join a channel as the current user. Pass `password` only for access_mode=password channels; private channels cannot be joined directly (403) — use mIRC_request_access + approval. Idempotent: an existing active member gets their membership row back (200, no 409).",
106
185
  inputSchema: mIRC_join_input,
107
186
  handler: ((input, ctx) => invokeChannelMembers("join", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
108
187
  },
188
+ {
189
+ // Własny agent/robot → auto_joined:true (channel_members + space_members + klucz grupy);
190
+ // człowiek / cudzy agent → kod zaproszenia. Rozgałęzia SERWER (channel-members-manage), nie toolkit.
191
+ name: "mIRC_invite",
192
+ title: "Invite / add a member",
193
+ annotations: { readOnlyHint: false },
194
+ requires: "network",
195
+ description:
196
+ "Add someone to a channel you own or admin (owner/superadmin/admin; you cannot hand out a role equal to or above your own). TWO OUTCOMES, decided server-side by who the target is. (1) An agent or robot YOU OWN joins immediately — reply {auto_joined:true, member}: the backend writes channel_members AND the linked space_members row (both are required before its posts pass message-send) plus a channel_keys row when you pass wrapped_group_key. No code, nothing to redeem. THIS is the step that lets an agent speak in a channel: mIRC_join adds the KEY's identity (usually you, the human), while channel posts are signed by the AGENT — a channel created from the toolkit stays mute until its agent is added here (or via invite_agents on mIRC_create). (2) A human, or an agent owned by somebody else, gets an invite code — reply {invite:{code, expires_at, …}}; hand the code over and they redeem it in the app (+ → I have an invite code). A fresh code supersedes that person's earlier live codes; default lifetime 7 days (ttl_seconds). Refused: a banned identity (403), an existing active member (400), self-target (400). Rate limit: 20 invites/min per caller. Password/private channels that hold a group key need wrapped_group_key (wrapped to the invitee's identity key) — the toolkit does not derive group keys, so either supply it as with mIRC_approve_request, or add the member from the mosadd.com member drawer, which wraps it for you.",
197
+ inputSchema: mIRC_invite_input,
198
+ handler: ((input, ctx) => inviteToChannel(input as MircInviteInput, ctx)) as MosaddTool["handler"],
199
+ },
109
200
  {
110
201
  name: "mIRC_request_access",
202
+ title: "Request channel access",
203
+ annotations: { readOnlyHint: false },
111
204
  requires: "network",
112
205
  description:
113
- "Request access to an invite_only channel. Owner / admins get a notification with the optional message.",
206
+ "Request access to a password/private channel (your membership goes to state=requested for an admin to approve).",
114
207
  inputSchema: mIRC_request_access_input,
115
208
  handler: ((input, ctx) => invokeChannelMembers("request-access", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
116
209
  },
117
210
  {
118
211
  name: "mIRC_leave",
212
+ title: "Leave channel",
213
+ annotations: { readOnlyHint: false },
119
214
  requires: "network",
120
215
  description: "Leave a channel as the current user. Owner cannot leave without transferring ownership first.",
121
216
  inputSchema: mIRC_leave_input,
@@ -123,13 +218,18 @@ export const mircMembersTools: MosaddTool[] = [
123
218
  },
124
219
  {
125
220
  name: "mIRC_approve_request",
221
+ title: "Approve access request",
222
+ annotations: { readOnlyHint: false },
126
223
  requires: "network",
127
- description: "Approve a pending access request. Admins / moderators / owner only.",
224
+ description:
225
+ "Approve a pending access request (state=requested → active). Admins / moderators / owner only. Because access requests only exist on non-open (password/private) channels, you must pass wrapped_group_key — the channel group key wrapped to the approved member's identity key.",
128
226
  inputSchema: mIRC_approve_request_input,
129
227
  handler: ((input, ctx) => invokeChannelMembers("approve-request", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
130
228
  },
131
229
  {
132
230
  name: "mIRC_reject_request",
231
+ title: "Reject access request",
232
+ annotations: { readOnlyHint: false },
133
233
  requires: "network",
134
234
  description: "Reject a pending access request. Admins / moderators / owner only.",
135
235
  inputSchema: mIRC_reject_request_input,
@@ -137,22 +237,28 @@ export const mircMembersTools: MosaddTool[] = [
137
237
  },
138
238
  {
139
239
  name: "mIRC_kick",
240
+ title: "Kick a member",
241
+ annotations: { destructiveHint: true },
140
242
  requires: "network",
141
243
  description:
142
- "Remove a member from the channel. They can rejoin if not banned. Requires moderator+. `reason` is logged to channel-event-log.",
244
+ "Remove a member from the channel. They can rejoin if not banned. Requires moderator+.",
143
245
  inputSchema: mIRC_kick_input,
144
246
  handler: ((input, ctx) => invokeChannelMembers("kick", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
145
247
  },
146
248
  {
147
249
  name: "mIRC_ban",
250
+ title: "Ban a member",
251
+ annotations: { destructiveHint: true },
148
252
  requires: "network",
149
253
  description:
150
- "Ban a member from the channel. They cannot rejoin until unbanned. `until` (ISO-8601) for time-bound ban; omit for permanent. Requires admin+.",
254
+ "Ban a member from the channel. The ban is permanent until you call mIRC_unban. Requires admin+.",
151
255
  inputSchema: mIRC_ban_input,
152
256
  handler: ((input, ctx) => invokeChannelMembers("ban", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
153
257
  },
154
258
  {
155
259
  name: "mIRC_unban",
260
+ title: "Lift a ban",
261
+ annotations: { readOnlyHint: false },
156
262
  requires: "network",
157
263
  description: "Lift a ban. Requires admin+.",
158
264
  inputSchema: mIRC_unban_input,
@@ -160,14 +266,18 @@ export const mircMembersTools: MosaddTool[] = [
160
266
  },
161
267
  {
162
268
  name: "mIRC_set_role",
269
+ title: "Set member role",
270
+ annotations: { readOnlyHint: false },
163
271
  requires: "network",
164
272
  description:
165
- "Promote / demote a member. Roles: owner > admin > moderator > member > guest. Only owner can promote to admin; only admin+ can promote to moderator.",
273
+ "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 — so a superadmin (not only the owner) can promote to admin.",
166
274
  inputSchema: mIRC_set_role_input,
167
275
  handler: ((input, ctx) => invokeChannelMembers("set-role", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
168
276
  },
169
277
  {
170
278
  name: "mIRC_set_ptt",
279
+ title: "Set push-to-talk permission",
280
+ annotations: { readOnlyHint: false },
171
281
  requires: "network",
172
282
  description:
173
283
  "Grant or revoke PTT floor permission for a member in voice-capable channels (capabilities.ptt=true). Requires moderator+.",
@@ -1,20 +1,19 @@
1
1
  /**
2
- * mIRC text mode — post + list messages inside a persistent channel.
2
+ * mIRC text mode — post + list messages inside a channel.
3
3
  *
4
4
  * Channel messages route through the same the mosadd backend's `message-send` / `message-list`
5
- * Edge Functions as DMs and rooms, but with `thread_id: 'chat:<channelId>'` so the
5
+ * Edge Functions as DMs, but with `thread_id: 'chat:<channelId>'` so the
6
6
  * RLS / access checks apply channel-membership rules. Each channel is linked to a
7
7
  * backing space (`metadata.linked_space_id`); message-send needs that space id, so
8
8
  * these tools resolve it from the channel automatically (or accept an override).
9
- *
10
- * Until now mIRC exposed only channel *management* (create/join/moderate) — there
11
- * was no way to actually post or read a channel's messages from MCP. These two
12
- * tools close that gap (the mROOM channels had it; mIRC did not).
13
9
  */
14
10
 
15
11
  import { z } from "zod";
16
12
  import type { MosaddTool, MosaddToolContext } from "../types.js";
17
13
  import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
+ import { formatVoiceIfAny } from "./voice-format.js";
15
+ import { decryptChannelPayload, encryptChannelPayload, unwrapEnvelopeText } from "../crypto/channel-e2ee.js";
16
+ import { decodeStoredPayloadText } from "./channel-payload.js";
18
17
 
19
18
  const PROTOCOL_VERSION = "mosadd.chat.v1";
20
19
 
@@ -28,6 +27,19 @@ const mIRC_post_message_input = z.object({
28
27
  .string()
29
28
  .optional()
30
29
  .describe("Optional backing space id. Resolved automatically from the channel if omitted."),
30
+ agent: z
31
+ .string()
32
+ .max(200)
33
+ .optional()
34
+ .describe(
35
+ "Post AS ONE OF YOUR OWN AGENTS instead of as the key's owner — its mosADD address " +
36
+ "(<agent>@mosadd.com), its identity id, or its display name. An API key is bound to a USER, " +
37
+ "so without this every message from an agent runtime is attributed to the owner: a whole fleet " +
38
+ "reporting in one channel shows up as one person. Same field name and same ownership rule as " +
39
+ "mDM_send_as_agent. The server verifies you OWN that agent and that it is an active member of " +
40
+ "the channel; naming an agent you do not own is refused, never silently downgraded to you. " +
41
+ "Omit it and attribution is unchanged.",
42
+ ),
31
43
  });
32
44
 
33
45
  const mIRC_list_messages_input = z.object({
@@ -37,12 +49,12 @@ const mIRC_list_messages_input = z.object({
37
49
  space_id: z.string().optional().describe("Optional backing space id. Resolved automatically if omitted."),
38
50
  });
39
51
 
40
- // ALPHA: channel messages are NOT end-to-end encrypted here — the body is wrapped
41
- // in a JSON envelope and base64-encoded (server-readable). The mosadd.com app
42
- // encrypts channel messages with a per-channel group key, so app clients cannot
43
- // decrypt these dev-posted plaintext payloads (and vice-versa) until the toolkit
44
- // adopts the same group-key scheme. See docs/security/e2ee-posture.md.
45
- function packPlaintextPayload(text: string, replyToId?: string): string {
52
+ // Channel messages on password/private channels are group-key encrypted when the
53
+ // line holds the channel's group key (channel_keys row wrapped to the line's
54
+ // identity — F4/LINEAR-5934). Open channels have no key → the legacy server-readable
55
+ // envelope below. The envelope JSON is the PLAINTEXT inside the group-key seal, so
56
+ // the app unwraps toolkit posts into the same bubble shape as before.
57
+ function buildPlaintextEnvelope(text: string, replyToId?: string): string {
46
58
  const envelope = {
47
59
  v: PROTOCOL_VERSION,
48
60
  type: "text",
@@ -50,17 +62,19 @@ function packPlaintextPayload(text: string, replyToId?: string): string {
50
62
  reply_to: replyToId ?? null,
51
63
  sent_at: new Date().toISOString(),
52
64
  };
53
- return Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
65
+ return JSON.stringify(envelope);
54
66
  }
55
67
 
56
- function unpackPayload(payload: string): { text: string } {
57
- try {
58
- const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
59
- if (typeof obj?.text === "string") return obj;
60
- } catch {
61
- /* fall through */
62
- }
63
- return { text: "<ciphertext>" };
68
+ /**
69
+ * Stored payload → readable text. Group-key decrypt first; then the plain decode, which reads BOTH
70
+ * the toolkit's JSON envelope AND the app's raw UTF-8 text (29.09: the King's posts on the open
71
+ * #adm/#command used to come back as "<ciphertext>"). "<ciphertext>" is left only for a sealed
72
+ * envelope this line holds no key for (channel-payload.ts).
73
+ */
74
+ async function payloadToText(channelId: string, payload: string): Promise<string> {
75
+ const decrypted = await decryptChannelPayload(channelId, payload);
76
+ if (decrypted !== null) return unwrapEnvelopeText(decrypted);
77
+ return decodeStoredPayloadText(payload);
64
78
  }
65
79
 
66
80
  /** Resolve a channel's backing space id (metadata.linked_space_id) via channel-manage. */
@@ -80,26 +94,45 @@ async function resolveLinkedSpaceId(channelId: string): Promise<string> {
80
94
  return spaceId;
81
95
  }
82
96
 
97
+ type SentAs = { identity_id: string; address: string | null; display_name: string | null };
98
+
83
99
  async function mIRC_post_message(
84
100
  input: z.infer<typeof mIRC_post_message_input>,
85
101
  ctx: MosaddToolContext,
86
- ): Promise<{ message_id: string; delivered_at: string; thread_id: string }> {
102
+ ): Promise<{ message_id: string; delivered_at: string; thread_id: string; sent_as?: SentAs }> {
87
103
  readSupabaseEnv();
88
104
  const space_id = input.space_id ?? (await resolveLinkedSpaceId(input.channel_id));
89
105
  const thread_id = `chat:${input.channel_id}`;
90
- ctx.log("debug", "mIRC_post_message", { thread_id, space_id });
106
+ ctx.log("debug", "mIRC_post_message", { thread_id, space_id, agent: input.agent });
107
+
108
+ // Group-key seal when the line holds the channel's key (password/private channels).
109
+ // Fallback = legacy server-readable envelope (open channels / no key yet).
110
+ const envelope = buildPlaintextEnvelope(input.text, input.reply_to_id);
111
+ const encrypted = await encryptChannelPayload(input.channel_id, envelope);
112
+ const payload = encrypted ?? Buffer.from(envelope, "utf8").toString("base64");
91
113
 
92
- const data = await invokeFunction<{ message?: { id: string; created_at: string } }>("message-send", {
114
+ const data = await invokeFunction<{ message?: { id: string; created_at: string }; sent_as?: SentAs }>("message-send", {
93
115
  space_id,
94
116
  thread_id,
95
- encrypted_payload: packPlaintextPayload(input.text, input.reply_to_id),
117
+ encrypted_payload: payload,
96
118
  message_type: "txt",
97
119
  protocol_version: PROTOCOL_VERSION,
98
120
  reply_to_id: input.reply_to_id ?? null,
121
+ // Attribution is decided SERVER-SIDE (message-send → _shared/ownedAgent.ts): you may sign only
122
+ // as an agent you own. Sent only when asked for, so the wire shape is unchanged for every
123
+ // existing caller — and an unresolvable agent comes back 403 rather than posting as the owner.
124
+ ...(input.agent ? { agent: input.agent } : {}),
99
125
  });
100
126
 
101
127
  if (!data?.message?.id) throw new Error("message-send returned no message id");
102
- return { message_id: data.message.id, delivered_at: data.message.created_at ?? new Date().toISOString(), thread_id };
128
+ return {
129
+ message_id: data.message.id,
130
+ delivered_at: data.message.created_at ?? new Date().toISOString(),
131
+ thread_id,
132
+ // Echo back WHO the message was signed as, so a caller can verify the attribution landed
133
+ // instead of assuming it did.
134
+ ...(data.sent_as ? { sent_as: data.sent_as } : {}),
135
+ };
103
136
  }
104
137
 
105
138
  async function mIRC_list_messages(
@@ -116,40 +149,52 @@ async function mIRC_list_messages(
116
149
 
117
150
  type MessageListResponse = {
118
151
  messages?: Array<{ id: string; sender_identity_id: string; encrypted_payload: string; created_at: string }>;
119
- next_cursor?: string | null;
152
+ next_before?: string | null;
153
+ cursor?: string | null;
120
154
  };
155
+ // message-list reads `before` (history) / `since` (incremental) — NOT `cursor`.
156
+ // Sending `cursor` left `before` unset → every call returned the newest page.
121
157
  const data = await invokeFunction<MessageListResponse>("message-list", {
122
158
  space_id,
123
159
  thread_id,
124
160
  limit: input.limit ?? 50,
125
- cursor: input.cursor,
161
+ before: input.cursor,
126
162
  });
127
163
 
128
- return {
129
- messages: (data?.messages ?? []).map((m) => ({
164
+ const messages: Array<{ id: string; sender_identity_id: string; text: string; timestamp: string }> = [];
165
+ for (const m of data?.messages ?? []) {
166
+ messages.push({
130
167
  id: m.id,
131
168
  sender_identity_id: m.sender_identity_id,
132
- text: unpackPayload(m.encrypted_payload).text,
169
+ text: formatVoiceIfAny(await payloadToText(input.channel_id, m.encrypted_payload)),
133
170
  timestamp: m.created_at,
134
- })),
135
- next_cursor: data?.next_cursor ?? null,
171
+ });
172
+ }
173
+
174
+ return {
175
+ messages,
176
+ next_cursor: data?.next_before ?? data?.cursor ?? null,
136
177
  };
137
178
  }
138
179
 
139
180
  export const mircMessagesTools: MosaddTool[] = [
140
181
  {
141
182
  name: "mIRC_post_message",
183
+ title: "Post channel message",
184
+ annotations: { readOnlyHint: false },
142
185
  requires: "network",
143
186
  description:
144
- "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 — the other mIRC_* tools only manage it. NOTE (alpha): the payload is NOT end-to-end encrypted — 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.",
187
+ "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 — 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. ATTRIBUTION: by default the message is signed with the identity behind the API key — and a key belongs to a USER, so an agent runtime using its owner's key posts as the OWNER. Pass `agent` to sign as one of your own agents instead; the server verifies you own it and that it is in the channel. ENCRYPTION: when your line holds the channel's group key (password/private channels where a wrapped key row exists for your identity — it is auto-provisioned on first use), the message is sealed AES-256-GCM + HMAC exactly like the app, so members read it as normal channel text. Open channels and channels without a wrapped key for your line fall back to the legacy server-readable envelope.",
145
188
  inputSchema: mIRC_post_message_input,
146
189
  handler: mIRC_post_message as MosaddTool["handler"],
147
190
  },
148
191
  {
149
192
  name: "mIRC_list_messages",
193
+ title: "Read channel messages",
194
+ annotations: { readOnlyHint: true },
150
195
  requires: "network",
151
196
  description:
152
- "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically.",
197
+ "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically. ENCRYPTION: messages your line can decrypt (group-key channels — auto-provisioned key material) come back as readable text; everything else is decoded as written: the app's plain text and the toolkit's JSON envelope both come back as readable text (open channels such as #adm and #command are never encrypted). Only a sealed group-key envelope your line holds no key for reads <ciphertext>.",
153
198
  inputSchema: mIRC_list_messages_input,
154
199
  handler: mIRC_list_messages as MosaddTool["handler"],
155
200
  },