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

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 (54) hide show
  1. package/CHANGELOG.md +15 -11
  2. package/README.md +152 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-IWUGKLDX.js → chunk-WEGSITAH.js} +30 -14
  5. package/dist/index.js +1 -1
  6. package/package.json +2 -2
  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 +2 -2
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +217 -182
  12. package/src/__tests__/label-room-owner.test.ts +22 -0
  13. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  14. package/src/__tests__/mdm-mcp-readable.test.ts +390 -390
  15. package/src/__tests__/mirc-invite.test.ts +112 -112
  16. package/src/__tests__/mtalk.test.ts +122 -122
  17. package/src/__tests__/presence.test.ts +199 -199
  18. package/src/__tests__/server.test.ts +71 -71
  19. package/src/__tests__/tool-count-consistency.test.ts +259 -199
  20. package/src/__tests__/voice-fields.test.ts +24 -0
  21. package/src/bin/login.ts +138 -138
  22. package/src/bin/mcp.ts +145 -145
  23. package/src/config.ts +66 -66
  24. package/src/crypto/channel-e2ee.ts +288 -288
  25. package/src/crypto/mdm-session.ts +842 -842
  26. package/src/index.ts +19 -19
  27. package/src/observability/sentry.ts +79 -79
  28. package/src/providers/blob-upload.ts +162 -162
  29. package/src/providers/memory-voice.ts +79 -79
  30. package/src/providers/supabase-dm.ts +212 -202
  31. package/src/providers/supabase-voice.ts +103 -91
  32. package/src/server.ts +195 -195
  33. package/src/tools/actions.ts +166 -166
  34. package/src/tools/attachments.ts +276 -276
  35. package/src/tools/capabilities.ts +70 -70
  36. package/src/tools/channel-payload.ts +2 -2
  37. package/src/tools/embed.ts +110 -110
  38. package/src/tools/index.ts +181 -181
  39. package/src/tools/knowledge.ts +344 -344
  40. package/src/tools/mail-aliases.ts +25 -25
  41. package/src/tools/mail-provenance.ts +137 -137
  42. package/src/tools/mail.ts +403 -403
  43. package/src/tools/mdm-as-agent.ts +138 -126
  44. package/src/tools/mdm.ts +6 -4
  45. package/src/tools/mirc-edge.ts +196 -196
  46. package/src/tools/mirc-members.ts +287 -287
  47. package/src/tools/mirc-messages.ts +1 -1
  48. package/src/tools/mirc.ts +308 -308
  49. package/src/tools/mroom.ts +221 -221
  50. package/src/tools/mtalk.ts +131 -131
  51. package/src/tools/presence.ts +442 -442
  52. package/src/tools/voice-format.ts +43 -28
  53. package/src/types.ts +121 -121
  54. package/src/voice/floor.ts +132 -132
@@ -1,79 +1,79 @@
1
- /**
2
- * InMemoryVoiceProvider — a self-contained mTALK provider for local mode,
3
- * off-grid single-process use, and tests. It runs the reference floor-control
4
- * FSM (floor.ts) in process, so the PTT discipline is fully exercised without
5
- * any media server. It does NOT mint real media credentials (joinTicket returns
6
- * a local stub) — real audio transport is the network/radio provider's job.
7
- */
8
-
9
- import type {
10
- VoiceProvider,
11
- FloorSnapshot,
12
- FloorRequestResult,
13
- VoiceJoinTicket,
14
- } from "@mosadd/providers";
15
- import {
16
- createFloorState,
17
- requestFloor as fsmRequest,
18
- releaseFloor as fsmRelease,
19
- expireStale,
20
- toSnapshot,
21
- type FloorState,
22
- } from "../voice/floor.js";
23
-
24
- export class InMemoryVoiceProvider implements VoiceProvider {
25
- private readonly rooms = new Map<string, FloorState>();
26
-
27
- constructor(
28
- private readonly myId: string,
29
- /** Injectable clock for deterministic tests; defaults to wall time. */
30
- private readonly clock: () => number = () => Date.now(),
31
- ) {}
32
-
33
- async selfId(): Promise<string> {
34
- return this.myId;
35
- }
36
-
37
- async createRoom(label?: string): Promise<{ roomId: string }> {
38
- const roomId = label ? `mtalk:${label}` : `mtalk:${this.myId}`;
39
- if (!this.rooms.has(roomId)) this.rooms.set(roomId, createFloorState(roomId));
40
- return { roomId };
41
- }
42
-
43
- async joinTicket(roomId: string): Promise<VoiceJoinTicket> {
44
- this.ensure(roomId);
45
- return { token: `local:${this.myId}`, url: "local://mtalk", identity: this.myId, roomId };
46
- }
47
-
48
- async requestFloor(roomId: string): Promise<FloorRequestResult> {
49
- const state = this.ensure(roomId);
50
- const outcome = fsmRequest(state, this.myId, this.clock());
51
- return { granted: outcome.granted, position: outcome.position, snapshot: toSnapshot(state) };
52
- }
53
-
54
- async releaseFloor(roomId: string): Promise<FloorSnapshot> {
55
- const state = this.ensure(roomId);
56
- fsmRelease(state, this.myId, this.clock());
57
- return toSnapshot(state);
58
- }
59
-
60
- async floorState(roomId: string): Promise<FloorSnapshot> {
61
- const state = this.ensure(roomId);
62
- expireStale(state, this.clock());
63
- return toSnapshot(state);
64
- }
65
-
66
- /** Shared backend handle so multiple participants' providers see one room. */
67
- shareRoomsWith(other: InMemoryVoiceProvider): void {
68
- (other as unknown as { rooms: Map<string, FloorState> }).rooms = this.rooms;
69
- }
70
-
71
- private ensure(roomId: string): FloorState {
72
- let state = this.rooms.get(roomId);
73
- if (!state) {
74
- state = createFloorState(roomId);
75
- this.rooms.set(roomId, state);
76
- }
77
- return state;
78
- }
79
- }
1
+ /**
2
+ * InMemoryVoiceProvider — a self-contained mTALK provider for local mode,
3
+ * off-grid single-process use, and tests. It runs the reference floor-control
4
+ * FSM (floor.ts) in process, so the PTT discipline is fully exercised without
5
+ * any media server. It does NOT mint real media credentials (joinTicket returns
6
+ * a local stub) — real audio transport is the network/radio provider's job.
7
+ */
8
+
9
+ import type {
10
+ VoiceProvider,
11
+ FloorSnapshot,
12
+ FloorRequestResult,
13
+ VoiceJoinTicket,
14
+ } from "@mosadd/providers";
15
+ import {
16
+ createFloorState,
17
+ requestFloor as fsmRequest,
18
+ releaseFloor as fsmRelease,
19
+ expireStale,
20
+ toSnapshot,
21
+ type FloorState,
22
+ } from "../voice/floor.js";
23
+
24
+ export class InMemoryVoiceProvider implements VoiceProvider {
25
+ private readonly rooms = new Map<string, FloorState>();
26
+
27
+ constructor(
28
+ private readonly myId: string,
29
+ /** Injectable clock for deterministic tests; defaults to wall time. */
30
+ private readonly clock: () => number = () => Date.now(),
31
+ ) {}
32
+
33
+ async selfId(): Promise<string> {
34
+ return this.myId;
35
+ }
36
+
37
+ async createRoom(label?: string): Promise<{ roomId: string }> {
38
+ const roomId = label ? `mtalk:${label}` : `mtalk:${this.myId}`;
39
+ if (!this.rooms.has(roomId)) this.rooms.set(roomId, createFloorState(roomId));
40
+ return { roomId };
41
+ }
42
+
43
+ async joinTicket(roomId: string): Promise<VoiceJoinTicket> {
44
+ this.ensure(roomId);
45
+ return { token: `local:${this.myId}`, url: "local://mtalk", identity: this.myId, roomId };
46
+ }
47
+
48
+ async requestFloor(roomId: string): Promise<FloorRequestResult> {
49
+ const state = this.ensure(roomId);
50
+ const outcome = fsmRequest(state, this.myId, this.clock());
51
+ return { granted: outcome.granted, position: outcome.position, snapshot: toSnapshot(state) };
52
+ }
53
+
54
+ async releaseFloor(roomId: string): Promise<FloorSnapshot> {
55
+ const state = this.ensure(roomId);
56
+ fsmRelease(state, this.myId, this.clock());
57
+ return toSnapshot(state);
58
+ }
59
+
60
+ async floorState(roomId: string): Promise<FloorSnapshot> {
61
+ const state = this.ensure(roomId);
62
+ expireStale(state, this.clock());
63
+ return toSnapshot(state);
64
+ }
65
+
66
+ /** Shared backend handle so multiple participants' providers see one room. */
67
+ shareRoomsWith(other: InMemoryVoiceProvider): void {
68
+ (other as unknown as { rooms: Map<string, FloorState> }).rooms = this.rooms;
69
+ }
70
+
71
+ private ensure(roomId: string): FloorState {
72
+ let state = this.rooms.get(roomId);
73
+ if (!state) {
74
+ state = createFloorState(roomId);
75
+ this.rooms.set(roomId, state);
76
+ }
77
+ return state;
78
+ }
79
+ }
@@ -1,202 +1,212 @@
1
- /**
2
- * SupabaseDmProvider — the default (network) DmProvider.
3
- *
4
- * Implements the transport-agnostic `DmProvider` contract from
5
- * `@mosadd/providers` over the mosadd Supabase Edge Functions
6
- * (`message-send` / `message-list`). This is the strangler-fig network path;
7
- * a carrier-aware host injects a different DmProvider for radio.
8
- *
9
- * The provider receives OPAQUE bytes and base64-wraps them into the
10
- * `encrypted_payload` string the Edge Function expects — it does not know or
11
- * care that the bytes are (for alpha) a plaintext `mosadd.chat.v1` envelope.
12
- */
13
-
14
- import type {
15
- DmProvider,
16
- DmSendArgs,
17
- DmSendResult,
18
- DmListArgs,
19
- DmListResult,
20
- DmMessage,
21
- } from "@mosadd/providers";
22
- import { getSupabase, invokeFunction, readSupabaseEnv } from "./supabase.js";
23
-
24
- const PROTOCOL_VERSION = "mosadd.chat.v1";
25
-
26
- /**
27
- * ⛔ THE CANONICAL mDM TEXT TYPE IS `txt`. The app sends and renders `txt`; `text` is a legacy
28
- * spelling the server keeps only so old clients are not refused (message-send
29
- * CLIENT_SENDABLE_MESSAGE_TYPES, "text 18 legacy, last written 2026-07-08"). This provider kept
30
- * writing `text` for every MCP DM until 27.09 — the last writer of the legacy type.
31
- */
32
- export const MDM_TEXT_MESSAGE_TYPE = "txt";
33
-
34
- /**
35
- * ⛔ AN E2EE ENVELOPE SEALED BY MCP ON A PERSON'S KEY IS TYPED `text` — ON PURPOSE (27.09.2026).
36
- * The app's readOwnMdmMessage (apps/web/src/lib/mdmE2ee.ts, from f95557f) explains an unreadable
37
- * OWN bubble by message_type: `text` → reason "agent" („wysłane przez agenta/MCP bez kopii dla
38
- * Ciebie"), anything else → "device" („wysłane z innego urządzenia"). MCP holds an API-key seed,
39
- * never the person's app seed, so it can never write a self copy the app opens — typing its
40
- * envelope `txt` made the app tell the owner a false reason. `text` stays client-sendable in
41
- * message-send (CLIENT_SENDABLE_MESSAGE_TYPES) precisely for this lane. Plaintext stays `txt`.
42
- */
43
- export const MDM_MCP_SEALED_MESSAGE_TYPE = "text";
44
-
45
- /**
46
- * Supabase-only extras for a DM send. The transport-agnostic DmSendArgs (@mosadd/providers)
47
- * carries opaque bytes only; the network lane can additionally store the two recoverable copies
48
- * the app reads (see sealForSelf / sealForPeerRecoverable in crypto/mdm-session.ts). A radio
49
- * provider ignores these fields.
50
- */
51
- export interface DmSendExtras {
52
- messageType?: string;
53
- /** "s1." copy sealed to the sender's self-read key → `messages.self_payload`. */
54
- selfPayload?: string | null;
55
- /** "r1." copy sealed to the recipient's identity → `messages.recipient_self_payload`. */
56
- recipientSelfPayload?: string | null;
57
- }
58
- export type DmSendArgsExt = DmSendArgs & DmSendExtras;
59
-
60
- /** A listed DM plus the recoverable copies message-list returns (RLS: own copy only). */
61
- export interface DmMessageExt extends DmMessage {
62
- selfPayload?: string | null;
63
- recipientSelfPayload?: string | null;
64
- messageType?: string;
65
- }
66
-
67
- export class SupabaseDmProvider implements DmProvider {
68
- private cachedSelfId: string | null = null;
69
- private cachedSelfKind: string | null = null;
70
-
71
- /**
72
- * `identities.kind` of the caller ("human" | "agent" | …). An agent LINE owns its mDM
73
- * identity outright (its key is its only runtime); a human's identity is anchored in the app.
74
- * ensureOwnBundlePublished uses this to decide whether a stale bundle may be replaced.
75
- */
76
- async selfKind(): Promise<string | null> {
77
- await this.selfId();
78
- return this.cachedSelfKind;
79
- }
80
-
81
- /**
82
- * `identities.kind` of a PEER, or null when it cannot be read (RLS can_see_identity scopes rows
83
- * to contacts / thread co-members; a miss is not an error). mDM_send uses it exactly like the
84
- * app's ChatPanel `peerIsAgent` (theirIdent.kind === 'agent' || iAmAgent): a DM to an agent
85
- * line is sent in the clear, because the line must read it (rozkaz Króla 20.09).
86
- */
87
- async peerKind(peerId: string): Promise<string | null> {
88
- try {
89
- const sb = getSupabase();
90
- const { data, error } = await sb.from("identities").select("kind").eq("id", peerId).limit(1).maybeSingle();
91
- if (error || !data) return null;
92
- return typeof data.kind === "string" ? data.kind : null;
93
- } catch {
94
- return null;
95
- }
96
- }
97
-
98
- async selfId(): Promise<string> {
99
- if (this.cachedSelfId) return this.cachedSelfId;
100
- readSupabaseEnv(); // fail fast with an actionable error if BYOK env missing
101
- const sb = getSupabase();
102
- const { data: u, error: ue } = await sb.auth.getUser();
103
- if (ue || !u?.user) {
104
- throw new Error(
105
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
106
- );
107
- }
108
- const { data: identity, error } = await sb
109
- .from("identities")
110
- .select("id, kind")
111
- .eq("user_id", u.user.id)
112
- .maybeSingle();
113
- if (error || !identity) {
114
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
115
- }
116
- this.cachedSelfId = identity.id as string;
117
- this.cachedSelfKind = typeof identity.kind === "string" ? identity.kind : null;
118
- return this.cachedSelfId;
119
- }
120
-
121
- async send(args: DmSendArgsExt): Promise<DmSendResult> {
122
- const encrypted_payload = Buffer.from(args.payload).toString("base64");
123
- type MessageSendResponse = { message?: { id: string; created_at: string } };
124
- const data = await invokeFunction<MessageSendResponse>("message-send", {
125
- space_id: "dm",
126
- thread_id: args.threadId,
127
- encrypted_payload,
128
- message_type: args.messageType ?? MDM_TEXT_MESSAGE_TYPE,
129
- protocol_version: PROTOCOL_VERSION,
130
- recipient_account_id: args.to,
131
- reply_to_id: args.replyToId ?? null,
132
- // Same optional columns the app writes (ircApi.sendThreadMessage); omitted when absent.
133
- ...(args.selfPayload ? { self_payload: args.selfPayload } : {}),
134
- ...(args.recipientSelfPayload ? { recipient_self_payload: args.recipientSelfPayload } : {}),
135
- });
136
- if (!data?.message?.id) {
137
- throw new Error("message-send returned no message id");
138
- }
139
- return {
140
- id: data.message.id,
141
- deliveredAt: data.message.created_at ?? new Date().toISOString(),
142
- };
143
- }
144
-
145
- async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
146
- // Network key directory. Server-side fn (`prekey-bundle-publish`) is the
147
- // the mosadd hub's responsibility — it stores the opaque bundle keyed by the
148
- // caller's identity (resolved from the JWT). mosadd-os just ships bytes.
149
- await invokeFunction<{ ok: boolean }>("prekey-bundle-publish", {
150
- bundle: Buffer.from(bundle).toString("base64"),
151
- });
152
- }
153
-
154
- async fetchPrekeyBundle(peerId: string): Promise<Uint8Array | null> {
155
- type FetchResponse = { bundle?: string | null };
156
- const data = await invokeFunction<FetchResponse>("prekey-bundle-fetch", {
157
- peer_id: peerId,
158
- });
159
- if (!data?.bundle) return null;
160
- return new Uint8Array(Buffer.from(data.bundle, "base64"));
161
- }
162
-
163
- async list(args: DmListArgs): Promise<DmListResult> {
164
- type MessageListResponse = {
165
- messages?: Array<{
166
- id: string;
167
- sender_identity_id: string;
168
- thread_id: string;
169
- encrypted_payload: string;
170
- created_at: string;
171
- message_type?: string | null;
172
- self_payload?: string | null;
173
- recipient_self_payload?: string | null;
174
- }>;
175
- cursor?: string | null;
176
- has_more?: boolean;
177
- next_before?: string | null;
178
- };
179
- // message-list paginates history via `before` (a created_at marker) and returns
180
- // the next marker as `cursor` — NOT `cursor` in / `next_cursor` out.
181
- const data = await invokeFunction<MessageListResponse>("message-list", {
182
- space_id: "dm",
183
- thread_id: args.threadId,
184
- limit: args.limit ?? 50,
185
- before: args.cursor,
186
- });
187
- return {
188
- messages: (data?.messages ?? []).map((m): DmMessageExt => ({
189
- id: m.id,
190
- senderId: m.sender_identity_id,
191
- payload: new Uint8Array(Buffer.from(m.encrypted_payload, "base64")),
192
- timestamp: m.created_at,
193
- threadId: m.thread_id,
194
- messageType: m.message_type ?? undefined,
195
- selfPayload: m.self_payload ?? null,
196
- recipientSelfPayload: m.recipient_self_payload ?? null,
197
- })),
198
- // history mode (`before`) returns `next_before`; incremental (`since`) returns `cursor`+`has_more`.
199
- nextCursor: data?.next_before ?? (data?.has_more ? (data?.cursor ?? null) : null),
200
- };
201
- }
202
- }
1
+ /**
2
+ * SupabaseDmProvider — the default (network) DmProvider.
3
+ *
4
+ * Implements the transport-agnostic `DmProvider` contract from
5
+ * `@mosadd/providers` over the mosadd Supabase Edge Functions
6
+ * (`message-send` / `message-list`). This is the strangler-fig network path;
7
+ * a carrier-aware host injects a different DmProvider for radio.
8
+ *
9
+ * The provider receives OPAQUE bytes and base64-wraps them into the
10
+ * `encrypted_payload` string the Edge Function expects — it does not know or
11
+ * care that the bytes are (for alpha) a plaintext `mosadd.chat.v1` envelope.
12
+ */
13
+
14
+ import type {
15
+ DmProvider,
16
+ DmSendArgs,
17
+ DmSendResult,
18
+ DmListArgs,
19
+ DmListResult,
20
+ DmMessage,
21
+ } from "@mosadd/providers";
22
+ import { getSupabase, invokeFunction, readSupabaseEnv } from "./supabase.js";
23
+
24
+ const PROTOCOL_VERSION = "mosadd.chat.v1";
25
+
26
+ /**
27
+ * ⛔ THE CANONICAL mDM TEXT TYPE IS `txt`. The app sends and renders `txt`; `text` is a legacy
28
+ * spelling the server keeps only so old clients are not refused (message-send
29
+ * CLIENT_SENDABLE_MESSAGE_TYPES, "text 18 legacy, last written 2026-07-08"). This provider kept
30
+ * writing `text` for every MCP DM until 27.09 — the last writer of the legacy type.
31
+ */
32
+ export const MDM_TEXT_MESSAGE_TYPE = "txt";
33
+
34
+ /**
35
+ * ⛔ AN E2EE ENVELOPE SEALED BY MCP ON A PERSON'S KEY IS TYPED `text` — ON PURPOSE (27.09.2026).
36
+ * The app's readOwnMdmMessage (apps/web/src/lib/mdmE2ee.ts, from f95557f) explains an unreadable
37
+ * OWN bubble by message_type: `text` → reason "agent" („wysłane przez agenta/MCP bez kopii dla
38
+ * Ciebie"), anything else → "device" („wysłane z innego urządzenia"). MCP holds an API-key seed,
39
+ * never the person's app seed, so it can never write a self copy the app opens — typing its
40
+ * envelope `txt` made the app tell the owner a false reason. `text` stays client-sendable in
41
+ * message-send (CLIENT_SENDABLE_MESSAGE_TYPES) precisely for this lane. Plaintext stays `txt`.
42
+ */
43
+ export const MDM_MCP_SEALED_MESSAGE_TYPE = "text";
44
+
45
+ /**
46
+ * Supabase-only extras for a DM send. The transport-agnostic DmSendArgs (@mosadd/providers)
47
+ * carries opaque bytes only; the network lane can additionally store the two recoverable copies
48
+ * the app reads (see sealForSelf / sealForPeerRecoverable in crypto/mdm-session.ts). A radio
49
+ * provider ignores these fields.
50
+ */
51
+ export interface DmSendExtras {
52
+ messageType?: string;
53
+ /** "s1." copy sealed to the sender's self-read key → `messages.self_payload`. */
54
+ selfPayload?: string | null;
55
+ /** "r1." copy sealed to the recipient's identity → `messages.recipient_self_payload`. */
56
+ recipientSelfPayload?: string | null;
57
+ }
58
+ export type DmSendArgsExt = DmSendArgs & DmSendExtras;
59
+
60
+ /** A listed DM plus the recoverable copies message-list returns (RLS: own copy only). */
61
+ export interface DmMessageExt extends DmMessage {
62
+ selfPayload?: string | null;
63
+ recipientSelfPayload?: string | null;
64
+ messageType?: string;
65
+ /** 15.11: z message-list dla voice/ptt (voiceEnrich.ts w mosADD). */
66
+ transcript?: string | null;
67
+ audioUrl?: string | null;
68
+ durationMs?: number | null;
69
+ }
70
+
71
+ export class SupabaseDmProvider implements DmProvider {
72
+ private cachedSelfId: string | null = null;
73
+ private cachedSelfKind: string | null = null;
74
+
75
+ /**
76
+ * `identities.kind` of the caller ("human" | "agent" | …). An agent LINE owns its mDM
77
+ * identity outright (its key is its only runtime); a human's identity is anchored in the app.
78
+ * ensureOwnBundlePublished uses this to decide whether a stale bundle may be replaced.
79
+ */
80
+ async selfKind(): Promise<string | null> {
81
+ await this.selfId();
82
+ return this.cachedSelfKind;
83
+ }
84
+
85
+ /**
86
+ * `identities.kind` of a PEER, or null when it cannot be read (RLS can_see_identity scopes rows
87
+ * to contacts / thread co-members; a miss is not an error). mDM_send uses it exactly like the
88
+ * app's ChatPanel `peerIsAgent` (theirIdent.kind === 'agent' || iAmAgent): a DM to an agent
89
+ * line is sent in the clear, because the line must read it (rozkaz Króla 20.09).
90
+ */
91
+ async peerKind(peerId: string): Promise<string | null> {
92
+ try {
93
+ const sb = getSupabase();
94
+ const { data, error } = await sb.from("identities").select("kind").eq("id", peerId).limit(1).maybeSingle();
95
+ if (error || !data) return null;
96
+ return typeof data.kind === "string" ? data.kind : null;
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ async selfId(): Promise<string> {
103
+ if (this.cachedSelfId) return this.cachedSelfId;
104
+ readSupabaseEnv(); // fail fast with an actionable error if BYOK env missing
105
+ const sb = getSupabase();
106
+ const { data: u, error: ue } = await sb.auth.getUser();
107
+ if (ue || !u?.user) {
108
+ throw new Error(
109
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
110
+ );
111
+ }
112
+ const { data: identity, error } = await sb
113
+ .from("identities")
114
+ .select("id, kind")
115
+ .eq("user_id", u.user.id)
116
+ .maybeSingle();
117
+ if (error || !identity) {
118
+ throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
119
+ }
120
+ this.cachedSelfId = identity.id as string;
121
+ this.cachedSelfKind = typeof identity.kind === "string" ? identity.kind : null;
122
+ return this.cachedSelfId;
123
+ }
124
+
125
+ async send(args: DmSendArgsExt): Promise<DmSendResult> {
126
+ const encrypted_payload = Buffer.from(args.payload).toString("base64");
127
+ type MessageSendResponse = { message?: { id: string; created_at: string } };
128
+ const data = await invokeFunction<MessageSendResponse>("message-send", {
129
+ space_id: "dm",
130
+ thread_id: args.threadId,
131
+ encrypted_payload,
132
+ message_type: args.messageType ?? MDM_TEXT_MESSAGE_TYPE,
133
+ protocol_version: PROTOCOL_VERSION,
134
+ recipient_account_id: args.to,
135
+ reply_to_id: args.replyToId ?? null,
136
+ // Same optional columns the app writes (ircApi.sendThreadMessage); omitted when absent.
137
+ ...(args.selfPayload ? { self_payload: args.selfPayload } : {}),
138
+ ...(args.recipientSelfPayload ? { recipient_self_payload: args.recipientSelfPayload } : {}),
139
+ });
140
+ if (!data?.message?.id) {
141
+ throw new Error("message-send returned no message id");
142
+ }
143
+ return {
144
+ id: data.message.id,
145
+ deliveredAt: data.message.created_at ?? new Date().toISOString(),
146
+ };
147
+ }
148
+
149
+ async publishPrekeyBundle(bundle: Uint8Array): Promise<void> {
150
+ // Network key directory. Server-side fn (`prekey-bundle-publish`) is the
151
+ // the mosadd hub's responsibility — it stores the opaque bundle keyed by the
152
+ // caller's identity (resolved from the JWT). mosadd-os just ships bytes.
153
+ await invokeFunction<{ ok: boolean }>("prekey-bundle-publish", {
154
+ bundle: Buffer.from(bundle).toString("base64"),
155
+ });
156
+ }
157
+
158
+ async fetchPrekeyBundle(peerId: string): Promise<Uint8Array | null> {
159
+ type FetchResponse = { bundle?: string | null };
160
+ const data = await invokeFunction<FetchResponse>("prekey-bundle-fetch", {
161
+ peer_id: peerId,
162
+ });
163
+ if (!data?.bundle) return null;
164
+ return new Uint8Array(Buffer.from(data.bundle, "base64"));
165
+ }
166
+
167
+ async list(args: DmListArgs): Promise<DmListResult> {
168
+ type MessageListResponse = {
169
+ messages?: Array<{
170
+ id: string;
171
+ sender_identity_id: string;
172
+ thread_id: string;
173
+ encrypted_payload: string;
174
+ created_at: string;
175
+ message_type?: string | null;
176
+ self_payload?: string | null;
177
+ recipient_self_payload?: string | null;
178
+ transcript?: string | null;
179
+ audio_url?: string | null;
180
+ duration_ms?: number | null;
181
+ }>;
182
+ cursor?: string | null;
183
+ has_more?: boolean;
184
+ next_before?: string | null;
185
+ };
186
+ // message-list paginates history via `before` (a created_at marker) and returns
187
+ // the next marker as `cursor` — NOT `cursor` in / `next_cursor` out.
188
+ const data = await invokeFunction<MessageListResponse>("message-list", {
189
+ space_id: "dm",
190
+ thread_id: args.threadId,
191
+ limit: args.limit ?? 50,
192
+ before: args.cursor,
193
+ });
194
+ return {
195
+ messages: (data?.messages ?? []).map((m): DmMessageExt => ({
196
+ id: m.id,
197
+ senderId: m.sender_identity_id,
198
+ payload: new Uint8Array(Buffer.from(m.encrypted_payload, "base64")),
199
+ timestamp: m.created_at,
200
+ threadId: m.thread_id,
201
+ messageType: m.message_type ?? undefined,
202
+ selfPayload: m.self_payload ?? null,
203
+ recipientSelfPayload: m.recipient_self_payload ?? null,
204
+ transcript: m.transcript ?? null,
205
+ audioUrl: m.audio_url ?? null,
206
+ durationMs: m.duration_ms ?? null,
207
+ })),
208
+ // history mode (`before`) returns `next_before`; incremental (`since`) returns `cursor`+`has_more`.
209
+ nextCursor: data?.next_before ?? (data?.has_more ? (data?.cursor ?? null) : null),
210
+ };
211
+ }
212
+ }