@relaymessenger/sdk 0.3.6-staging.2 → 0.3.6-staging.20

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.
package/README.md CHANGED
@@ -2,6 +2,100 @@
2
2
 
3
3
  TypeScript client for Relay v1.
4
4
 
5
+ ## Selection
6
+
7
+ The SDK exposes `SelectionPart`, `SelectionPartResponse` (including read-only
8
+ viewer-relative `has_responded`), and `SelectionResponsePart` through the
9
+ existing message and event unions.
10
+
11
+ ```ts
12
+ import { partsWithSelection } from "@relaymessenger/sdk";
13
+
14
+ const parts = partsWithSelection("Which topics interest you?", {
15
+ type: "selection",
16
+ options: [
17
+ { value: "research", label: "Research" },
18
+ { value: "design", label: "Design" },
19
+ ],
20
+ });
21
+ // Send with relay.chats.messages.send(chatId, { message: { parts, idempotency_key } }).
22
+ ```
23
+
24
+ `selectionPart` validates an options array or complete part, returning a
25
+ normalized part or an error string. Options are limited to 25, trimmed labels
26
+ to 80 characters, and explicit case-sensitive ASCII token values to 100.
27
+ Unknown fields, duplicate values, and blank labels are rejected.
28
+ `partsWithSelection` also requires nonblank question text.
29
+
30
+ Selection inherits existing Chat membership rules: at most one human user,
31
+ with multiple agents allowed. Only the human user can respond; agents cannot.
32
+ The durable per-user response claim applies across that user's devices and
33
+ idempotency keys, without expanding group membership.
34
+
35
+ `answerMessages` accepts a `selection` fenced JSON block containing the options
36
+ array. It keeps invalid blocks as text with an error and never combines a
37
+ selection with buttons. Existing buttons retain their behavior.
38
+
39
+ The person opens the prompt, checks any number of options and submits them
40
+ once; checking sends nothing and only the submit does. A person answers a given
41
+ selection once, and reopening it afterwards shows what they chose without
42
+ letting them change it.
43
+
44
+ The user's new reply is exactly literal `• ` + each selected source label
45
+ joined with `\n`, then
46
+ `{ type: "selection_response", selected_values: ["research", "design"] }`,
47
+ in source-option order, with explicit `reply_to.message_id` and `part_index`.
48
+ The user client keeps its existing outgoing idempotency identity for retries.
49
+ The server also accepts exact legacy comma-joined source labels only for
50
+ compatibility. iOS may draw a checkmark in place of each bullet and repeat the
51
+ prompt's title, as presentation only, but portable text stays bulleted.
52
+ Metadata has no additional display text. Use `selected_values` and the source
53
+ reply target to dispatch your own handler, rather than splitting labels.
54
+ Signed webhook `unwrap` and WebSocket `onEvent` default types expose this
55
+ metadata after narrowing to `message.received`.
56
+
57
+ The CLI, Pi, OpenClaw, the Claude Code channel, MCP, and the Chat SDK adapter
58
+ include selection guidance and structured inbound discovery.
59
+ `selectionReply(parts, replyTo)` discovers values and the explicit source target.
60
+
61
+ ## Invoice
62
+
63
+ Only a verified agent can send an `invoice` part, and it must be the only part
64
+ of its Message. The `url` is your own Stripe-hosted checkout page on one of
65
+ `INVOICE_CHECKOUT_HOSTS` (`checkout`, `buy`, `book`, `donate` or
66
+ `invoice.stripe.com`); Relay never touches the money.
67
+
68
+ ```ts
69
+ import { invoicePart } from "@relaymessenger/sdk";
70
+
71
+ const invoice = invoicePart({
72
+ title: "House blend, 250 g",
73
+ amount: 2400, // minor units
74
+ currency: "usd",
75
+ goods: "physical", // "digital" for anything delivered in chat or used in an app
76
+ url: "https://buy.stripe.com/test_123",
77
+ });
78
+ if (typeof invoice === "string") throw new Error(invoice);
79
+ await relay.chats.messages.send(chatId, {
80
+ message: { parts: [invoice], idempotency_key: crypto.randomUUID() },
81
+ });
82
+ ```
83
+
84
+ `invoicePart` applies the server's checks (title, amount, currency, goods,
85
+ Stripe checkout url, optional `recurring` of up to 3 years) and returns a
86
+ normalized part or an error string. When your Stripe webhook learns the
87
+ outcome, move the card with
88
+ `relay.messages.invoice.update(messageId, { status: "succeeded" })`; only the
89
+ sending agent may.
90
+
91
+ `answerMessages` accepts one `invoice` fenced JSON block and sends it as its
92
+ own Message after the words. A second invoice, or an invoice beside buttons or
93
+ a selection, stays text with an error. `INVOICE_GUIDANCE` is the
94
+ when-to-invoice text the CLI, Pi, OpenClaw, MCP and the Claude Code channel
95
+ carry; the text bridges also carry `INVOICE_BLOCK_INSTRUCTION`.
96
+
97
+ ## Chat permissions
98
+
5
99
  Relay Chats support one human user with one or more agents. Contacts, Handles,
6
100
  and Participants remain generic API types, but selectable participants are
7
101
  agents. Agent-to-agent Chats remain supported. This Agent SDK does not expose phone address-book syncing, mutual
@@ -65,6 +159,46 @@ await relay.chats.messages.send(chatId, {
65
159
  });
66
160
  ```
67
161
 
162
+ ## Show task activity
163
+
164
+ Start activity when the work starts. Image generation uses `🖼️ Generating image`;
165
+ voice-note generation uses `🎙️ Generating voice note`.
166
+
167
+ ```ts
168
+ const state = await relay.chats.setActivity(chatId, {
169
+ text: "Generating image",
170
+ emoji: "🖼️",
171
+ });
172
+ const activityId = state.activity!.id;
173
+ ```
174
+
175
+ Renew every 60 seconds only while that task remains active. The same ID guards
176
+ updates against replacing a newer task; a replaced or cleared ID returns 409.
177
+ Each successful update renews the 90-second safety lease:
178
+
179
+ ```ts
180
+ await relay.chats.setActivity(chatId, {
181
+ text: "Generating image",
182
+ emoji: "🖼️",
183
+ activity_id: activityId,
184
+ });
185
+ ```
186
+
187
+ Clear when work completes, fails, or is cancelled. Guard cleanup with the task
188
+ ID so an old task cannot clear a newer one. Missing or replaced activity is a
189
+ successful no-op:
190
+
191
+ ```ts
192
+ await relay.chats.clearActivity(chatId, { activity_id: activityId });
193
+ const current = await relay.chats.getActivity(chatId);
194
+ ```
195
+
196
+ GET reads your own state. Text allows 1–21 visible characters and at most
197
+ 1024 UTF-8 bytes; `emoji` is one Unicode emoji or `null`. Response `version`
198
+ is a string and `activity` is an object or `null`. Chat handles may also carry
199
+ `activity_version` and `activity`. Typing remains `chats.startTyping` and
200
+ `chats.stopTyping`; activity does not add an agent event or polling transport.
201
+
68
202
  ## Share your Contact Card
69
203
 
70
204
  ```ts
@@ -107,6 +241,7 @@ Available resource methods:
107
241
  - `webhookEvents.list`
108
242
  - `webhookSubscriptions.create`, `retrieve`, `update`, `list`, `delete`
109
243
  - `contactCard.create`, `retrieve`, `update`
244
+ - `contacts.lookup({ handle })`
110
245
  - `blockedHandles.list`, `block`, `unblock`
111
246
  - `websocket.run`
112
247
 
@@ -179,28 +314,53 @@ attachment rules are at <https://docs.relayapp.im>.
179
314
  ## Individual audio Calls (staging)
180
315
 
181
316
  Calls join one user and one agent in an existing individual Chat. Use
182
- `relay.calls.create(chatId, { to: [handle], mode: "audio" }, { idempotencyKey })`;
317
+ `relay.calls.create(chatId, { to: [handle] }, { idempotencyKey })`;
183
318
  keep the same key and body when retrying an uncertain create response.
184
319
 
185
- `relay.calls` also exposes `retrieve`, `list`, `accept`, `decline`, `end`, and
186
- `connected`. Receive typed `call.created`, `call.updated`, and `call.ended`
187
- events through the existing signed Webhook or Agent WebSocket.
188
-
189
- After accepting a Call, an agent creates its audio connection with
190
- `relay.calls.connections.create(callId, { transport: "websocket" })`.
191
- The returned `connection.url` and short-lived `connection.token` belong to
192
- that Call's media socket. Connect using `Authorization: Bearer <token>`.
193
- They do not replace the Agent Token used for REST requests.
194
-
195
- Media uses raw PCM16 little-endian, 48 kHz stereo binary frames. The server
196
- sends JSON `start` with the format, then `ready`. Send `{"type":"clear"}` to
197
- discard unsent speech. An `ended` frame terminates the media socket. This
198
- socket is separate from `relay.websocket.run`, which carries durable events.
199
-
200
- WebRTC clients use the same `connections.create` resource with an SDP offer
201
- and microphone MID, then `connections.subscribe` and
202
- `connections.renegotiate`. The SDK exposes no media-provider credentials,
203
- session IDs, model configuration, or audio generation.
320
+ `relay.calls` also exposes `retrieve`, `list`, `room`, and `end`. Receive typed
321
+ `call.created`, `call.updated`, and `call.ended` events through the existing
322
+ signed Webhook or acknowledged Agent WebSocket. Agents do not configure a call
323
+ URL; receiving `call.created` and joining that Call's room is the answer path.
324
+
325
+ Every participant holds one signaling socket to the Call room.
326
+ `relay.calls.room(callId)` targets `GET /v1/calls/{callId}/room` with the same
327
+ bearer as every REST route. Register handlers, call `connect()`, and the SDK
328
+ sends `join`; `room.state` then tracks the latest `roomState`. Nothing is polled
329
+ and no audio bytes pass through this WebSocket.
330
+
331
+ ```ts
332
+ const room = relay.calls.room(event.data.call.id);
333
+ room.on("roomState", ({ call, participants }) => {
334
+ // Each participant has track: "audio" | null, muted and connected state.
335
+ });
336
+ room.on("answer", ({ session_description }) => {
337
+ // Apply Relay's answer to the local WebRTC publication.
338
+ });
339
+ room.on("offer", ({ session_description, track }) => {
340
+ // Relay subscribed this participant to the other side's `audio` track.
341
+ // Apply the offer, create a WebRTC answer, gather ICE, then send it:
342
+ room.send({ type: "answer", session_description: { type: "answer", sdp } });
343
+ });
344
+ room.on("ended", ({ reason }) => { /* the socket closes right after */ });
345
+ await room.connect(); // sends { type: "join" }; a callee answers here
346
+ ```
347
+
348
+ The stable client frames are `join`, `offer`, `answer`, `connected`,
349
+ `userUpdate`, `end`, and `heartbeat`. A publishing `offer` has exactly one
350
+ `tracks` entry, `{ mid, name: "audio" }`. Stable server frames are `roomState`,
351
+ `answer`, `offer` with `track: "audio"`, `ended`, and `error`; every
352
+ `roomState.participants[]` item reports `track: "audio" | null`. The SDK sends
353
+ `heartbeat` every 15 seconds until `close()`. `connected()`, `userUpdate()` and
354
+ `end()` are convenience methods for those frames, and `reconnect()` replaces
355
+ the signaling socket without first dropping the old one.
356
+
357
+ WebRTC carries the audio. Relay's server owns SFU/provider details, so clients
358
+ only exchange SDP in the room protocol and never receive Cloudflare
359
+ credentials, session IDs, or ICE-provider configuration. Node agents that want
360
+ this SDP/ICE and PCM plumbing handled for them can use
361
+ `@relaymessenger/livekit`, whose provider-neutral `RelayCallTransport` uses a
362
+ standards-compatible Node WebRTC binding and whose LiveKit adapter plugs the
363
+ result into LiveKit Agents audio input/output.
204
364
 
205
365
  ## Webhooks
206
366
 
@@ -0,0 +1,69 @@
1
+ import type { ButtonsPart } from "./types.js";
2
+ /**
3
+ * The fence tag a text-only agent uses to put buttons under its answer. The
4
+ * block body is the `items` array of a `buttons` part, exactly as the API
5
+ * takes it, so an agent that has read the contract needs nothing else:
6
+ *
7
+ * ```buttons
8
+ * [{"label": "Approve"}, {"label": "Open report", "url": "https://..."}]
9
+ * ```
10
+ */
11
+ export declare const BUTTONS_FENCE = "buttons";
12
+ /**
13
+ * When an agent should send buttons. One text, carried verbatim by every
14
+ * runtime's tool description or prompt, so a person gets buttons under the
15
+ * same conditions whichever agent they talk to. The rules are the ones the
16
+ * messaging platforms give their own business agents: Apple's quick replies
17
+ * ("avoid expecting customers to type responses that could be handled with a
18
+ * tap", 2 to 5 options), Google's RCS suggestions ("design for the most
19
+ * common responses"; never "mimic phone trees"), WhatsApp's reply and
20
+ * call-to-action buttons (distinct options; one call to action). The line
21
+ * between a url button and a link is Messenger's ("use URL buttons for tasks
22
+ * that you want completed on your website (for example, purchases, or
23
+ * account linking)") and Apple's ("all URLs should be sent as Rich Links";
24
+ * product pages, support articles, self-serve resources): a task goes on a
25
+ * button, a thing to look at goes out as a link card.
26
+ */
27
+ export declare const BUTTONS_GUIDANCE: string;
28
+ /**
29
+ * How a text-only agent puts buttons under its answer: the same words for
30
+ * every bridge that sends the agent's final text for it.
31
+ */
32
+ export declare const BUTTONS_BLOCK_INSTRUCTION: string;
33
+ /** The server's limits (Discord's button limits): items 1..5, label 1..80, url <= 2048. */
34
+ export declare const BUTTONS_MAX_ITEMS = 5;
35
+ export declare const BUTTON_LABEL_MAX_LENGTH = 80;
36
+ export declare const BUTTON_URL_MAX_LENGTH = 2048;
37
+ export interface SplitButtons {
38
+ /** The answer with the fenced block removed and the edges trimmed. */
39
+ text: string;
40
+ /** The buttons part the block described, when there was a valid one. */
41
+ buttons?: ButtonsPart;
42
+ /** Why a block that was there could not be used. The text then keeps it. */
43
+ error?: string;
44
+ }
45
+ /**
46
+ * Turns a decoded value, an array of items or a whole part, into a `buttons`
47
+ * part, or explains why it cannot. The checks are the server's own, so a bad
48
+ * value fails here with a readable reason instead of a 400 from the API.
49
+ */
50
+ export declare const buttonsPart: (parsed: unknown) => ButtonsPart | string;
51
+ /** Parses the body of a buttons block, JSON, into a `buttons` part. */
52
+ export declare const parseButtonsBlock: (body: string) => ButtonsPart | string;
53
+ /**
54
+ * Lifts the first ```buttons block out of an agent's answer. The text around
55
+ * it becomes the text part; the block becomes the buttons part. When the
56
+ * block is malformed, the answer is returned untouched with `error` set, so
57
+ * the person still gets the words and the operator sees why.
58
+ */
59
+ export declare const splitButtons: (answer: string) => SplitButtons;
60
+ /**
61
+ * The parts a text answer with optional buttons becomes: the text first, when
62
+ * there is any, then the buttons. A buttons-only message is one the server
63
+ * accepts, so an answer that is nothing but the block sends just the buttons.
64
+ */
65
+ export declare const partsWithButtons: (text: string, buttons: ButtonsPart | undefined, limit?: number) => Array<{
66
+ type: "text";
67
+ value: string;
68
+ } | ButtonsPart>;
69
+ //# sourceMappingURL=buttons.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buttons.d.ts","sourceRoot":"","sources":["../src/buttons.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,WAAW,EAAE,MAAM,YAAY,CAAC;AAE1D;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa,YAAY,CAAC;AAEvC;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,gBAAgB,QAQlB,CAAC;AAEZ;;;GAGG;AACH,eAAO,MAAM,yBAAyB,QAGwB,CAAC;AAE/D,2FAA2F;AAC3F,eAAO,MAAM,iBAAiB,IAAI,CAAC;AACnC,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,eAAO,MAAM,qBAAqB,OAAQ,CAAC;AAE3C,MAAM,WAAW,YAAY;IAC3B,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,wEAAwE;IACxE,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,4EAA4E;IAC5E,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAgCD;;;;GAIG;AACH,eAAO,MAAM,WAAW,GAAI,QAAQ,OAAO,KAAG,WAAW,GAAG,MAiB3D,CAAC;AAEF,uEAAuE;AACvE,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,KAAG,WAAW,GAAG,MAQ9D,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,MAAM,KAAG,YAU7C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,GAC3B,MAAM,MAAM,EACZ,SAAS,WAAW,GAAG,SAAS,EAChC,cAAgC,KAC/B,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,WAAW,CAGrD,CAAC"}
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The fence tag a text-only agent uses to put buttons under its answer. The
3
+ * block body is the `items` array of a `buttons` part, exactly as the API
4
+ * takes it, so an agent that has read the contract needs nothing else:
5
+ *
6
+ * ```buttons
7
+ * [{"label": "Approve"}, {"label": "Open report", "url": "https://..."}]
8
+ * ```
9
+ */
10
+ export const BUTTONS_FENCE = "buttons";
11
+ /**
12
+ * When an agent should send buttons. One text, carried verbatim by every
13
+ * runtime's tool description or prompt, so a person gets buttons under the
14
+ * same conditions whichever agent they talk to. The rules are the ones the
15
+ * messaging platforms give their own business agents: Apple's quick replies
16
+ * ("avoid expecting customers to type responses that could be handled with a
17
+ * tap", 2 to 5 options), Google's RCS suggestions ("design for the most
18
+ * common responses"; never "mimic phone trees"), WhatsApp's reply and
19
+ * call-to-action buttons (distinct options; one call to action). The line
20
+ * between a url button and a link is Messenger's ("use URL buttons for tasks
21
+ * that you want completed on your website (for example, purchases, or
22
+ * account linking)") and Apple's ("all URLs should be sent as Rich Links";
23
+ * product pages, support articles, self-serve resources): a task goes on a
24
+ * button, a thing to look at goes out as a link card.
25
+ */
26
+ export const BUTTONS_GUIDANCE = [
27
+ "Send buttons when your message ends with a question the person can answer by picking one of 2 to 5 short options you already know: yes or no, choosing between things you named, picking a next step, or a multiple-choice question in a quiz. Each label is a complete answer, so a tap replaces typing. Put the question in text beside the buttons.",
28
+ "Send one button when there is one thing to do next. A url button is for a task the person completes on a web page: pay, sign in, connect an account, open their booking or order, track a package. Its label names the action, not the site. A plain button confirms one step: Start, Done, Continue. Do not ask \"ready?\" when a single button does the job.",
29
+ "A link is for something the person will look at or read: an article, a listing, a video, a place, a product page, a support article. Send it as a link on its own, so it draws as a card with the page's title and image; never paste a bare URL into your words, and send one link per message. When the page is where the person does something, send a url button; when the page is the thing you are showing them, send a link.",
30
+ "Do not send buttons when the answer is open-ended, when your options are not the full set of likely answers, or when you are not asking anything and there is nothing to do. One question or one action per message; never a menu of things you can do, and never as decoration.",
31
+ "If you would otherwise write \"reply 1, 2 or 3\" or list choices for the person to type, send buttons instead. If the person asks for buttons, send them.",
32
+ "A tap comes back to you as an ordinary message whose text is the label. Labels are at most 80 characters.",
33
+ "Buttons disappear once tapped.",
34
+ ].join(" ");
35
+ /**
36
+ * How a text-only agent puts buttons under its answer: the same words for
37
+ * every bridge that sends the agent's final text for it.
38
+ */
39
+ export const BUTTONS_BLOCK_INSTRUCTION = "To put buttons under your answer, end it with a fenced code block tagged `" + BUTTONS_FENCE + "` "
40
+ + "holding a JSON array of 1 to 5 items, each {\"label\": \"...\"} or {\"label\": \"...\", \"url\": \"https://...\"}. "
41
+ + "The block is removed from the text and drawn as buttons.";
42
+ /** The server's limits (Discord's button limits): items 1..5, label 1..80, url <= 2048. */
43
+ export const BUTTONS_MAX_ITEMS = 5;
44
+ export const BUTTON_LABEL_MAX_LENGTH = 80;
45
+ export const BUTTON_URL_MAX_LENGTH = 2_048;
46
+ const FENCE = new RegExp("(^|\\n)[ \\t]*```[ \\t]*" + BUTTONS_FENCE + "[ \\t]*\\r?\\n([\\s\\S]*?)\\r?\\n[ \\t]*```[ \\t]*(?=\\r?\\n|$)", "u");
47
+ const asItem = (value, index) => {
48
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
49
+ return `item ${index + 1} is not an object`;
50
+ }
51
+ const record = value;
52
+ const keys = Object.keys(record).filter((key) => key !== "label" && key !== "url");
53
+ if (keys.length > 0)
54
+ return `item ${index + 1} has unknown field ${keys[0]}`;
55
+ const { label, url } = record;
56
+ if (typeof label !== "string" || label.length === 0)
57
+ return `item ${index + 1} needs a label`;
58
+ if (label.length > BUTTON_LABEL_MAX_LENGTH) {
59
+ return `item ${index + 1} label is over ${BUTTON_LABEL_MAX_LENGTH} characters`;
60
+ }
61
+ if (url === undefined)
62
+ return { label };
63
+ if (typeof url !== "string" || url.length > BUTTON_URL_MAX_LENGTH) {
64
+ return `item ${index + 1} url is not a string of at most ${BUTTON_URL_MAX_LENGTH} characters`;
65
+ }
66
+ try {
67
+ const parsed = new URL(url);
68
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
69
+ throw new Error();
70
+ }
71
+ catch {
72
+ return `item ${index + 1} url is not an http(s) URL`;
73
+ }
74
+ return { url, label };
75
+ };
76
+ /**
77
+ * Turns a decoded value, an array of items or a whole part, into a `buttons`
78
+ * part, or explains why it cannot. The checks are the server's own, so a bad
79
+ * value fails here with a readable reason instead of a 400 from the API.
80
+ */
81
+ export const buttonsPart = (parsed) => {
82
+ const wrapped = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
83
+ ? parsed
84
+ : undefined;
85
+ const items = Array.isArray(parsed) ? parsed : Array.isArray(wrapped?.items) ? wrapped.items : undefined;
86
+ if (items === undefined)
87
+ return "the buttons block must be a JSON array of items";
88
+ if (items.length === 0)
89
+ return "the buttons block has no items";
90
+ if (items.length > BUTTONS_MAX_ITEMS) {
91
+ return `the buttons block has ${items.length} items; the most is ${BUTTONS_MAX_ITEMS}`;
92
+ }
93
+ const result = [];
94
+ for (const [index, value] of items.entries()) {
95
+ const item = asItem(value, index);
96
+ if (typeof item === "string")
97
+ return item;
98
+ result.push(item);
99
+ }
100
+ return { type: "buttons", items: result };
101
+ };
102
+ /** Parses the body of a buttons block, JSON, into a `buttons` part. */
103
+ export const parseButtonsBlock = (body) => {
104
+ let parsed;
105
+ try {
106
+ parsed = JSON.parse(body);
107
+ }
108
+ catch {
109
+ return "the buttons block is not valid JSON";
110
+ }
111
+ return buttonsPart(parsed);
112
+ };
113
+ /**
114
+ * Lifts the first ```buttons block out of an agent's answer. The text around
115
+ * it becomes the text part; the block becomes the buttons part. When the
116
+ * block is malformed, the answer is returned untouched with `error` set, so
117
+ * the person still gets the words and the operator sees why.
118
+ */
119
+ export const splitButtons = (answer) => {
120
+ const match = FENCE.exec(answer);
121
+ if (!match)
122
+ return { text: answer };
123
+ const parsed = parseButtonsBlock(match[2] ?? "");
124
+ if (typeof parsed === "string")
125
+ return { text: answer, error: parsed };
126
+ const start = match.index + (match[1]?.length ?? 0);
127
+ const before = answer.slice(0, start).replace(/\s+$/u, "");
128
+ const after = answer.slice(match.index + match[0].length).replace(/^\s+/u, "");
129
+ const text = before && after ? `${before}\n\n${after}` : before || after;
130
+ return { text, buttons: parsed };
131
+ };
132
+ /**
133
+ * The parts a text answer with optional buttons becomes: the text first, when
134
+ * there is any, then the buttons. A buttons-only message is one the server
135
+ * accepts, so an answer that is nothing but the block sends just the buttons.
136
+ */
137
+ export const partsWithButtons = (text, buttons, limit = Number.POSITIVE_INFINITY) => [
138
+ ...(text.length > 0 ? [{ type: "text", value: text.slice(0, limit) }] : []),
139
+ ...(buttons ? [buttons] : []),
140
+ ];
141
+ //# sourceMappingURL=buttons.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buttons.js","sourceRoot":"","sources":["../src/buttons.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AAEvC;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,wVAAwV;IACxV,gWAAgW;IAChW,qaAAqa;IACra,kRAAkR;IAClR,2JAA2J;IAC3J,2GAA2G;IAC3G,gCAAgC;CACjC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAEZ;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GACpC,4EAA4E,GAAG,aAAa,GAAG,IAAI;MACjG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AAC,CAAC,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC;IACpD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IAC3D,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IAC/E,MAAM,IAAI,GAAG,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC;IACzE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;AACnC,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,IAAY,EACZ,OAAgC,EAChC,KAAK,GAAG,MAAM,CAAC,iBAAiB,EACsB,EAAE,CAAC;IACzD,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IACpF,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;CAC9B,CAAC"}
@@ -0,0 +1,97 @@
1
+ import type { CallRoomClientFrame, CallRoomEndedFrame, CallRoomErrorFrame, CallRoomServerAnswerFrame, CallRoomServerFrame, CallRoomStateFrame, CallRoomSubscriptionOfferFrame } from "./types.js";
2
+ import type { WebSocketConstructor } from "./websocket.js";
3
+ export interface CallRoomOptions {
4
+ /** Abort closes the signaling socket without ending the Call. */
5
+ signal?: AbortSignal;
6
+ /** Override the Node WebSocket implementation, primarily for tests. */
7
+ WebSocket?: WebSocketConstructor;
8
+ /** Client heartbeat cadence. Relay's room heartbeat frame has no payload. */
9
+ heartbeatIntervalMs?: number;
10
+ }
11
+ export interface CallRoomCloseEvent {
12
+ code: number;
13
+ reason: string;
14
+ wasClean: boolean;
15
+ }
16
+ /**
17
+ * The room socket dropped, or an attempt to open one failed, and the room
18
+ * opens a new one after `delayMs`. Media rides the SFU, not this socket, so the
19
+ * Call and its WebRTC session continue; nothing is re-offered.
20
+ */
21
+ export interface CallRoomReconnectingEvent {
22
+ /** 1 for the first retry; the count resets once a socket stays open 5 s. */
23
+ attempt: number;
24
+ delayMs: number;
25
+ /** The close that caused the retry; absent when an attempt failed before opening. */
26
+ close?: CallRoomCloseEvent;
27
+ /** Why the failed attempt did not open (connect timeout, handshake error). */
28
+ error?: Error;
29
+ }
30
+ export type CallRoomConnectionState = "idle" | "connecting" | "open" | "reconnecting" | "closed";
31
+ export type CallRoomEventMap = {
32
+ open: [];
33
+ reconnecting: [CallRoomReconnectingEvent];
34
+ roomState: [CallRoomStateFrame];
35
+ offer: [CallRoomSubscriptionOfferFrame];
36
+ answer: [CallRoomServerAnswerFrame];
37
+ ended: [CallRoomEndedFrame];
38
+ error: [CallRoomErrorFrame | Error];
39
+ /** The room socket closed and the room will not reopen it by itself. */
40
+ close: [CallRoomCloseEvent];
41
+ };
42
+ type CallRoomEvent = keyof CallRoomEventMap;
43
+ type Listener<K extends CallRoomEvent> = (...args: CallRoomEventMap[K]) => void;
44
+ /**
45
+ * Validate one server frame before exposing it to application code. Relay's
46
+ * runtime may echo the exact heartbeat frame without waking the Call room; that
47
+ * transport heartbeat is intentionally ignored and is not part of the public
48
+ * server-frame union.
49
+ */
50
+ export declare const parseCallRoomServerFrame: (value: unknown) => CallRoomServerFrame | null;
51
+ /**
52
+ * Authenticated JSON signaling socket for one Relay Call participant.
53
+ *
54
+ * The room reopens its socket after any close that neither this client nor the
55
+ * server asked for, with PartySocket's numbers (PROTOCOL.md section 5): first
56
+ * retry after 3000 ms, then x1.3, capped at 10000 ms, a 4000 ms connect
57
+ * timeout, the retry count reset once a socket stays open 5000 ms, and no
58
+ * retry limit. On every open it sends `join`, then `userUpdate` with the last
59
+ * muted/video state, then the frames queued while closed. Media is never
60
+ * re-offered by a socket-only reconnect.
61
+ */
62
+ export declare class CallRoom {
63
+ #private;
64
+ readonly callID: string;
65
+ readonly url: string;
66
+ state: CallRoomStateFrame | null;
67
+ constructor(callID: string, baseURL: string, apiKey: string, options?: CallRoomOptions);
68
+ /** `reconnecting` while the room waits to reopen a dropped socket. */
69
+ get connectionState(): CallRoomConnectionState;
70
+ on<K extends CallRoomEvent>(event: K, listener: Listener<K>): this;
71
+ off<K extends CallRoomEvent>(event: K, listener: Listener<K>): this;
72
+ /** Resolves on the first open; a failed attempt is retried, not thrown. */
73
+ connect(): Promise<void>;
74
+ /**
75
+ * Open a new signaling socket now, keeping application/WebRTC state alive.
76
+ * Relay accepts the new authenticated socket before the previous one closes,
77
+ * so an active Call is not interpreted as having lost its participant. Same
78
+ * path as the automatic reconnect (PartySocket `reconnect()`: retry count
79
+ * reset, no delay); if the new socket fails while the old one is still open,
80
+ * the old one stays and this rejects.
81
+ */
82
+ reconnect(): Promise<void>;
83
+ /**
84
+ * Send one frame. While the socket is reopening the frame is queued and sent
85
+ * after `join` on the next open (PartySocket's queue); heartbeats are dropped.
86
+ */
87
+ send(frame: CallRoomClientFrame): void;
88
+ connected(): void;
89
+ userUpdate(update: {
90
+ muted: boolean;
91
+ video?: boolean;
92
+ }): void;
93
+ end(): void;
94
+ close(code?: number, reason?: string): void;
95
+ }
96
+ export {};
97
+ //# sourceMappingURL=call-room.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"call-room.d.ts","sourceRoot":"","sources":["../src/call-room.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,mBAAmB,EACnB,kBAAkB,EAElB,kBAAkB,EAElB,yBA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