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

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 (51) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-3PUOM4R5.js → chunk-IWUGKLDX.js} +54 -20
  5. package/dist/index.js +1 -1
  6. package/package.json +1 -1
  7. package/src/__tests__/blob-upload.test.ts +93 -93
  8. package/src/__tests__/channel-e2ee.test.ts +62 -62
  9. package/src/__tests__/flota-jawnie.test.ts +244 -0
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +182 -182
  12. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  13. package/src/__tests__/mdm-mcp-readable.test.ts +390 -386
  14. package/src/__tests__/mirc-invite.test.ts +112 -112
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/server.test.ts +71 -71
  17. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  18. package/src/bin/login.ts +138 -138
  19. package/src/bin/mcp.ts +145 -145
  20. package/src/config.ts +66 -66
  21. package/src/crypto/channel-e2ee.ts +288 -288
  22. package/src/crypto/mdm-session.ts +842 -842
  23. package/src/index.ts +19 -19
  24. package/src/observability/sentry.ts +79 -79
  25. package/src/providers/memory-voice.ts +79 -79
  26. package/src/providers/supabase-dm.ts +202 -202
  27. package/src/providers/supabase-voice.ts +91 -91
  28. package/src/server.ts +195 -195
  29. package/src/tools/actions.ts +166 -166
  30. package/src/tools/attachments.ts +276 -276
  31. package/src/tools/capabilities.ts +70 -70
  32. package/src/tools/channel-payload.ts +69 -0
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge.ts +344 -344
  36. package/src/tools/mail-aliases.ts +25 -25
  37. package/src/tools/mail-provenance.ts +137 -137
  38. package/src/tools/mail.ts +403 -403
  39. package/src/tools/mdm-as-agent.ts +126 -126
  40. package/src/tools/mdm.ts +26 -11
  41. package/src/tools/mirc-edge.ts +196 -196
  42. package/src/tools/mirc-members.ts +287 -287
  43. package/src/tools/mirc-messages.ts +9 -13
  44. package/src/tools/mirc.ts +308 -308
  45. package/src/tools/mroom-messages.ts +4 -12
  46. package/src/tools/mroom.ts +221 -221
  47. package/src/tools/mtalk.ts +131 -131
  48. package/src/tools/presence.ts +442 -442
  49. package/src/tools/voice-format.ts +28 -28
  50. package/src/types.ts +121 -121
  51. package/src/voice/floor.ts +132 -132
@@ -1,287 +1,287 @@
1
- /**
2
- * mIRC channel members — join, leave, invite, kick, ban, set-role, set-ptt.
3
- *
4
- * Wraps the mosadd backend's `channel-members-manage` Edge Function (audit ab6c885f),
5
- * which dispatches on the `action` body field.
6
- *
7
- * Split from packages/mcp/src/tools/mirc.ts because the channel-management
8
- * surface and the member-management surface have different ergonomics — a
9
- * model that handles roster ops shouldn't have to read past 5 'channel CRUD'
10
- * tools to find them.
11
- */
12
-
13
- import { z } from "zod";
14
- import type { MosaddTool, MosaddToolContext } from "../types.js";
15
- import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
16
-
17
- // ---- Schemas ----
18
-
19
- const ChannelId = z
20
- .string()
21
- .min(1)
22
- .max(120)
23
- .describe("Channel id (UUID). From mIRC_list / mIRC_create.");
24
-
25
- const MemberIdentity = z
26
- .string()
27
- .min(1)
28
- .describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
29
-
30
- const Role = z
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
-
34
- const mIRC_join_input = z.object({
35
- channel_id: ChannelId,
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
- });
38
-
39
- const mIRC_request_access_input = z.object({
40
- channel_id: ChannelId,
41
- });
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
-
83
- const mIRC_leave_input = z.object({
84
- channel_id: ChannelId,
85
- });
86
-
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({
91
- channel_id: ChannelId,
92
- identity_id: z.string().min(1).describe("Identity id of the requester to reject (state=requested; from mIRC_list members)."),
93
- });
94
-
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
- });
103
-
104
- const mIRC_kick_input = z.object({
105
- channel_id: ChannelId,
106
- identity_id: MemberIdentity,
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.
110
- });
111
-
112
- const mIRC_ban_input = z.object({
113
- channel_id: ChannelId,
114
- identity_id: MemberIdentity,
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.
119
- });
120
-
121
- const mIRC_unban_input = z.object({
122
- channel_id: ChannelId,
123
- identity_id: MemberIdentity,
124
- });
125
-
126
- const mIRC_set_role_input = z.object({
127
- channel_id: ChannelId,
128
- identity_id: MemberIdentity,
129
- role: Role,
130
- });
131
-
132
- const mIRC_set_ptt_input = z.object({
133
- channel_id: ChannelId,
134
- identity_id: MemberIdentity,
135
- ptt_enabled: z.boolean().describe("Allow this member to hold the PTT floor in voice mode."),
136
- });
137
-
138
- // ---- Handlers ----
139
-
140
- async function invokeChannelMembers(
141
- action: string,
142
- body: Record<string, unknown>,
143
- ctx: MosaddToolContext,
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; }
157
- readSupabaseEnv();
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;
173
- }
174
-
175
- // ---- Registration ----
176
-
177
- export const mircMembersTools: MosaddTool[] = [
178
- {
179
- name: "mIRC_join",
180
- title: "Join channel",
181
- annotations: { readOnlyHint: false },
182
- requires: "network",
183
- description:
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).",
185
- inputSchema: mIRC_join_input,
186
- handler: ((input, ctx) => invokeChannelMembers("join", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
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
- },
200
- {
201
- name: "mIRC_request_access",
202
- title: "Request channel access",
203
- annotations: { readOnlyHint: false },
204
- requires: "network",
205
- description:
206
- "Request access to a password/private channel (your membership goes to state=requested for an admin to approve).",
207
- inputSchema: mIRC_request_access_input,
208
- handler: ((input, ctx) => invokeChannelMembers("request-access", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
209
- },
210
- {
211
- name: "mIRC_leave",
212
- title: "Leave channel",
213
- annotations: { readOnlyHint: false },
214
- requires: "network",
215
- description: "Leave a channel as the current user. Owner cannot leave without transferring ownership first.",
216
- inputSchema: mIRC_leave_input,
217
- handler: ((input, ctx) => invokeChannelMembers("leave", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
218
- },
219
- {
220
- name: "mIRC_approve_request",
221
- title: "Approve access request",
222
- annotations: { readOnlyHint: false },
223
- requires: "network",
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.",
226
- inputSchema: mIRC_approve_request_input,
227
- handler: ((input, ctx) => invokeChannelMembers("approve-request", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
228
- },
229
- {
230
- name: "mIRC_reject_request",
231
- title: "Reject access request",
232
- annotations: { readOnlyHint: false },
233
- requires: "network",
234
- description: "Reject a pending access request. Admins / moderators / owner only.",
235
- inputSchema: mIRC_reject_request_input,
236
- handler: ((input, ctx) => invokeChannelMembers("reject-request", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
237
- },
238
- {
239
- name: "mIRC_kick",
240
- title: "Kick a member",
241
- annotations: { destructiveHint: true },
242
- requires: "network",
243
- description:
244
- "Remove a member from the channel. They can rejoin if not banned. Requires moderator+.",
245
- inputSchema: mIRC_kick_input,
246
- handler: ((input, ctx) => invokeChannelMembers("kick", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
247
- },
248
- {
249
- name: "mIRC_ban",
250
- title: "Ban a member",
251
- annotations: { destructiveHint: true },
252
- requires: "network",
253
- description:
254
- "Ban a member from the channel. The ban is permanent until you call mIRC_unban. Requires admin+.",
255
- inputSchema: mIRC_ban_input,
256
- handler: ((input, ctx) => invokeChannelMembers("ban", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
257
- },
258
- {
259
- name: "mIRC_unban",
260
- title: "Lift a ban",
261
- annotations: { readOnlyHint: false },
262
- requires: "network",
263
- description: "Lift a ban. Requires admin+.",
264
- inputSchema: mIRC_unban_input,
265
- handler: ((input, ctx) => invokeChannelMembers("unban", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
266
- },
267
- {
268
- name: "mIRC_set_role",
269
- title: "Set member role",
270
- annotations: { readOnlyHint: false },
271
- requires: "network",
272
- description:
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.",
274
- inputSchema: mIRC_set_role_input,
275
- handler: ((input, ctx) => invokeChannelMembers("set-role", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
276
- },
277
- {
278
- name: "mIRC_set_ptt",
279
- title: "Set push-to-talk permission",
280
- annotations: { readOnlyHint: false },
281
- requires: "network",
282
- description:
283
- "Grant or revoke PTT floor permission for a member in voice-capable channels (capabilities.ptt=true). Requires moderator+.",
284
- inputSchema: mIRC_set_ptt_input,
285
- handler: ((input, ctx) => invokeChannelMembers("set-ptt", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
286
- },
287
- ];
1
+ /**
2
+ * mIRC channel members — join, leave, invite, kick, ban, set-role, set-ptt.
3
+ *
4
+ * Wraps the mosadd backend's `channel-members-manage` Edge Function (audit ab6c885f),
5
+ * which dispatches on the `action` body field.
6
+ *
7
+ * Split from packages/mcp/src/tools/mirc.ts because the channel-management
8
+ * surface and the member-management surface have different ergonomics — a
9
+ * model that handles roster ops shouldn't have to read past 5 'channel CRUD'
10
+ * tools to find them.
11
+ */
12
+
13
+ import { z } from "zod";
14
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
15
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
16
+
17
+ // ---- Schemas ----
18
+
19
+ const ChannelId = z
20
+ .string()
21
+ .min(1)
22
+ .max(120)
23
+ .describe("Channel id (UUID). From mIRC_list / mIRC_create.");
24
+
25
+ const MemberIdentity = z
26
+ .string()
27
+ .min(1)
28
+ .describe("Target user's identity id (UUID). From mDM_list_contacts or radar logs.");
29
+
30
+ const Role = z
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
+
34
+ const mIRC_join_input = z.object({
35
+ channel_id: ChannelId,
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
+ });
38
+
39
+ const mIRC_request_access_input = z.object({
40
+ channel_id: ChannelId,
41
+ });
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
+
83
+ const mIRC_leave_input = z.object({
84
+ channel_id: ChannelId,
85
+ });
86
+
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({
91
+ channel_id: ChannelId,
92
+ identity_id: z.string().min(1).describe("Identity id of the requester to reject (state=requested; from mIRC_list members)."),
93
+ });
94
+
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
+ });
103
+
104
+ const mIRC_kick_input = z.object({
105
+ channel_id: ChannelId,
106
+ identity_id: MemberIdentity,
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.
110
+ });
111
+
112
+ const mIRC_ban_input = z.object({
113
+ channel_id: ChannelId,
114
+ identity_id: MemberIdentity,
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.
119
+ });
120
+
121
+ const mIRC_unban_input = z.object({
122
+ channel_id: ChannelId,
123
+ identity_id: MemberIdentity,
124
+ });
125
+
126
+ const mIRC_set_role_input = z.object({
127
+ channel_id: ChannelId,
128
+ identity_id: MemberIdentity,
129
+ role: Role,
130
+ });
131
+
132
+ const mIRC_set_ptt_input = z.object({
133
+ channel_id: ChannelId,
134
+ identity_id: MemberIdentity,
135
+ ptt_enabled: z.boolean().describe("Allow this member to hold the PTT floor in voice mode."),
136
+ });
137
+
138
+ // ---- Handlers ----
139
+
140
+ async function invokeChannelMembers(
141
+ action: string,
142
+ body: Record<string, unknown>,
143
+ ctx: MosaddToolContext,
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; }
157
+ readSupabaseEnv();
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;
173
+ }
174
+
175
+ // ---- Registration ----
176
+
177
+ export const mircMembersTools: MosaddTool[] = [
178
+ {
179
+ name: "mIRC_join",
180
+ title: "Join channel",
181
+ annotations: { readOnlyHint: false },
182
+ requires: "network",
183
+ description:
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).",
185
+ inputSchema: mIRC_join_input,
186
+ handler: ((input, ctx) => invokeChannelMembers("join", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
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
+ },
200
+ {
201
+ name: "mIRC_request_access",
202
+ title: "Request channel access",
203
+ annotations: { readOnlyHint: false },
204
+ requires: "network",
205
+ description:
206
+ "Request access to a password/private channel (your membership goes to state=requested for an admin to approve).",
207
+ inputSchema: mIRC_request_access_input,
208
+ handler: ((input, ctx) => invokeChannelMembers("request-access", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
209
+ },
210
+ {
211
+ name: "mIRC_leave",
212
+ title: "Leave channel",
213
+ annotations: { readOnlyHint: false },
214
+ requires: "network",
215
+ description: "Leave a channel as the current user. Owner cannot leave without transferring ownership first.",
216
+ inputSchema: mIRC_leave_input,
217
+ handler: ((input, ctx) => invokeChannelMembers("leave", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
218
+ },
219
+ {
220
+ name: "mIRC_approve_request",
221
+ title: "Approve access request",
222
+ annotations: { readOnlyHint: false },
223
+ requires: "network",
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.",
226
+ inputSchema: mIRC_approve_request_input,
227
+ handler: ((input, ctx) => invokeChannelMembers("approve-request", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
228
+ },
229
+ {
230
+ name: "mIRC_reject_request",
231
+ title: "Reject access request",
232
+ annotations: { readOnlyHint: false },
233
+ requires: "network",
234
+ description: "Reject a pending access request. Admins / moderators / owner only.",
235
+ inputSchema: mIRC_reject_request_input,
236
+ handler: ((input, ctx) => invokeChannelMembers("reject-request", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
237
+ },
238
+ {
239
+ name: "mIRC_kick",
240
+ title: "Kick a member",
241
+ annotations: { destructiveHint: true },
242
+ requires: "network",
243
+ description:
244
+ "Remove a member from the channel. They can rejoin if not banned. Requires moderator+.",
245
+ inputSchema: mIRC_kick_input,
246
+ handler: ((input, ctx) => invokeChannelMembers("kick", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
247
+ },
248
+ {
249
+ name: "mIRC_ban",
250
+ title: "Ban a member",
251
+ annotations: { destructiveHint: true },
252
+ requires: "network",
253
+ description:
254
+ "Ban a member from the channel. The ban is permanent until you call mIRC_unban. Requires admin+.",
255
+ inputSchema: mIRC_ban_input,
256
+ handler: ((input, ctx) => invokeChannelMembers("ban", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
257
+ },
258
+ {
259
+ name: "mIRC_unban",
260
+ title: "Lift a ban",
261
+ annotations: { readOnlyHint: false },
262
+ requires: "network",
263
+ description: "Lift a ban. Requires admin+.",
264
+ inputSchema: mIRC_unban_input,
265
+ handler: ((input, ctx) => invokeChannelMembers("unban", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
266
+ },
267
+ {
268
+ name: "mIRC_set_role",
269
+ title: "Set member role",
270
+ annotations: { readOnlyHint: false },
271
+ requires: "network",
272
+ description:
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.",
274
+ inputSchema: mIRC_set_role_input,
275
+ handler: ((input, ctx) => invokeChannelMembers("set-role", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
276
+ },
277
+ {
278
+ name: "mIRC_set_ptt",
279
+ title: "Set push-to-talk permission",
280
+ annotations: { readOnlyHint: false },
281
+ requires: "network",
282
+ description:
283
+ "Grant or revoke PTT floor permission for a member in voice-capable channels (capabilities.ptt=true). Requires moderator+.",
284
+ inputSchema: mIRC_set_ptt_input,
285
+ handler: ((input, ctx) => invokeChannelMembers("set-ptt", input as Record<string, unknown>, ctx)) as MosaddTool["handler"],
286
+ },
287
+ ];
@@ -13,6 +13,7 @@ import type { MosaddTool, MosaddToolContext } from "../types.js";
13
13
  import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
14
14
  import { formatVoiceIfAny } from "./voice-format.js";
15
15
  import { decryptChannelPayload, encryptChannelPayload, unwrapEnvelopeText } from "../crypto/channel-e2ee.js";
16
+ import { decodeStoredPayloadText } from "./channel-payload.js";
16
17
 
17
18
  const PROTOCOL_VERSION = "mosadd.chat.v1";
18
19
 
@@ -64,21 +65,16 @@ function buildPlaintextEnvelope(text: string, replyToId?: string): string {
64
65
  return JSON.stringify(envelope);
65
66
  }
66
67
 
67
- function unpackPayload(payload: string): { text: string } {
68
- try {
69
- const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
70
- if (typeof obj?.text === "string") return obj;
71
- } catch {
72
- /* fall through */
73
- }
74
- return { text: "<ciphertext>" };
75
- }
76
-
77
- /** Stored payload → readable text. Group-key decrypt first; legacy base64 envelope second. */
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
+ */
78
74
  async function payloadToText(channelId: string, payload: string): Promise<string> {
79
75
  const decrypted = await decryptChannelPayload(channelId, payload);
80
76
  if (decrypted !== null) return unwrapEnvelopeText(decrypted);
81
- return unpackPayload(payload).text;
77
+ return decodeStoredPayloadText(payload);
82
78
  }
83
79
 
84
80
  /** Resolve a channel's backing space id (metadata.linked_space_id) via channel-manage. */
@@ -198,7 +194,7 @@ export const mircMessagesTools: MosaddTool[] = [
198
194
  annotations: { readOnlyHint: true },
199
195
  requires: "network",
200
196
  description:
201
- "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; anything else falls back to the legacy envelope/plaintext decode.",
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>.",
202
198
  inputSchema: mIRC_list_messages_input,
203
199
  handler: mIRC_list_messages as MosaddTool["handler"],
204
200
  },