@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,202 +1,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
- }
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
+ }
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,91 +1,91 @@
1
- /**
2
- * SupabaseVoiceProvider — the default (network) mTALK provider.
3
- *
4
- * Audio media: a LiveKit room, credentials minted by the existing
5
- * `livekit-token` Edge Function. Floor control: the `mtalk-floor` Edge Function
6
- * holds the AUTHORITATIVE per-room floor state (running the same reference FSM
7
- * as floor.ts) and broadcasts changes over Supabase Realtime for sub-100ms PTT
8
- * grant. mosadd-os just asks and relays the answer.
9
- */
10
-
11
- import type {
12
- VoiceProvider,
13
- FloorSnapshot,
14
- FloorRequestResult,
15
- VoiceJoinTicket,
16
- } from "@mosadd/providers";
17
- import { getSupabase, invokeFunction, readSupabaseEnv } from "./supabase.js";
18
-
19
- const ROOM_PREFIX = "mosadd-room-";
20
-
21
- export class SupabaseVoiceProvider implements VoiceProvider {
22
- private cachedSelfId: string | null = null;
23
-
24
- async selfId(): Promise<string> {
25
- if (this.cachedSelfId) return this.cachedSelfId;
26
- readSupabaseEnv();
27
- const sb = getSupabase();
28
- const { data: u, error: ue } = await sb.auth.getUser();
29
- if (ue || !u?.user) {
30
- throw new Error(
31
- "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
32
- );
33
- }
34
- const { data: identity, error } = await sb
35
- .from("identities")
36
- .select("id")
37
- .eq("user_id", u.user.id)
38
- .maybeSingle();
39
- if (error || !identity) {
40
- throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
41
- }
42
- this.cachedSelfId = identity.id as string;
43
- return this.cachedSelfId;
44
- }
45
-
46
- async createRoom(label?: string): Promise<{ roomId: string }> {
47
- const self = await this.selfId();
48
- const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
49
- // Floor row is created lazily by mtalk-floor on first request; nothing to do
50
- // here beyond returning the canonical id.
51
- return { roomId };
52
- }
53
-
54
- async joinTicket(roomId: string): Promise<VoiceJoinTicket> {
55
- const self = await this.selfId();
56
- type TokenResp = { token: string; url: string; roomName: string; identity: string };
57
- const data = await invokeFunction<TokenResp>("livekit-token", {
58
- roomName: roomId,
59
- identity: self,
60
- });
61
- return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
62
- }
63
-
64
- async requestFloor(roomId: string): Promise<FloorRequestResult> {
65
- return invokeFunction<FloorRequestResult>("mtalk-floor", { action: "request", room_id: roomId });
66
- }
67
-
68
- async releaseFloor(roomId: string): Promise<FloorSnapshot> {
69
- const data = await invokeFunction<{ snapshot: FloorSnapshot }>("mtalk-floor", {
70
- action: "release",
71
- room_id: roomId,
72
- });
73
- return data.snapshot;
74
- }
75
-
76
- async floorState(roomId: string): Promise<FloorSnapshot> {
77
- const data = await invokeFunction<{ snapshot: FloorSnapshot }>("mtalk-floor", {
78
- action: "state",
79
- room_id: roomId,
80
- });
81
- return data.snapshot;
82
- }
83
- }
84
-
85
- function slug(s: string): string {
86
- return s
87
- .toLowerCase()
88
- .replace(/[^a-z0-9._-]+/g, "-")
89
- .replace(/^-+|-+$/g, "")
90
- .slice(0, 200);
91
- }
1
+ /**
2
+ * SupabaseVoiceProvider — the default (network) mTALK provider.
3
+ *
4
+ * Audio media: a LiveKit room, credentials minted by the existing
5
+ * `livekit-token` Edge Function. Floor control: the `mtalk-floor` Edge Function
6
+ * holds the AUTHORITATIVE per-room floor state (running the same reference FSM
7
+ * as floor.ts) and broadcasts changes over Supabase Realtime for sub-100ms PTT
8
+ * grant. mosadd-os just asks and relays the answer.
9
+ */
10
+
11
+ import type {
12
+ VoiceProvider,
13
+ FloorSnapshot,
14
+ FloorRequestResult,
15
+ VoiceJoinTicket,
16
+ } from "@mosadd/providers";
17
+ import { getSupabase, invokeFunction, readSupabaseEnv } from "./supabase.js";
18
+
19
+ const ROOM_PREFIX = "mosadd-room-";
20
+
21
+ export class SupabaseVoiceProvider implements VoiceProvider {
22
+ private cachedSelfId: string | null = null;
23
+
24
+ async selfId(): Promise<string> {
25
+ if (this.cachedSelfId) return this.cachedSelfId;
26
+ readSupabaseEnv();
27
+ const sb = getSupabase();
28
+ const { data: u, error: ue } = await sb.auth.getUser();
29
+ if (ue || !u?.user) {
30
+ throw new Error(
31
+ "Unable to resolve current user. Ensure MOSADD_USER_JWT is set to a valid Supabase session token.",
32
+ );
33
+ }
34
+ const { data: identity, error } = await sb
35
+ .from("identities")
36
+ .select("id")
37
+ .eq("user_id", u.user.id)
38
+ .maybeSingle();
39
+ if (error || !identity) {
40
+ throw new Error("Current user has no mosadd identity row. Sign in to mosadd.com first.");
41
+ }
42
+ this.cachedSelfId = identity.id as string;
43
+ return this.cachedSelfId;
44
+ }
45
+
46
+ async createRoom(label?: string): Promise<{ roomId: string }> {
47
+ const self = await this.selfId();
48
+ const roomId = `${ROOM_PREFIX}${label ? slug(label) : self}`;
49
+ // Floor row is created lazily by mtalk-floor on first request; nothing to do
50
+ // here beyond returning the canonical id.
51
+ return { roomId };
52
+ }
53
+
54
+ async joinTicket(roomId: string): Promise<VoiceJoinTicket> {
55
+ const self = await this.selfId();
56
+ type TokenResp = { token: string; url: string; roomName: string; identity: string };
57
+ const data = await invokeFunction<TokenResp>("livekit-token", {
58
+ roomName: roomId,
59
+ identity: self,
60
+ });
61
+ return { token: data.token, url: data.url, identity: data.identity, roomId: data.roomName };
62
+ }
63
+
64
+ async requestFloor(roomId: string): Promise<FloorRequestResult> {
65
+ return invokeFunction<FloorRequestResult>("mtalk-floor", { action: "request", room_id: roomId });
66
+ }
67
+
68
+ async releaseFloor(roomId: string): Promise<FloorSnapshot> {
69
+ const data = await invokeFunction<{ snapshot: FloorSnapshot }>("mtalk-floor", {
70
+ action: "release",
71
+ room_id: roomId,
72
+ });
73
+ return data.snapshot;
74
+ }
75
+
76
+ async floorState(roomId: string): Promise<FloorSnapshot> {
77
+ const data = await invokeFunction<{ snapshot: FloorSnapshot }>("mtalk-floor", {
78
+ action: "state",
79
+ room_id: roomId,
80
+ });
81
+ return data.snapshot;
82
+ }
83
+ }
84
+
85
+ function slug(s: string): string {
86
+ return s
87
+ .toLowerCase()
88
+ .replace(/[^a-z0-9._-]+/g, "-")
89
+ .replace(/^-+|-+$/g, "")
90
+ .slice(0, 200);
91
+ }