import { Message, type Adapter, type AdapterPostableMessage, type Attachment, type ChatInstance, type EmojiValue, type FetchOptions, type FetchResult, type FormattedContent, type RawMessage, type StreamChunk, type ThreadInfo, type UserInfo, type WebhookOptions } from "chat"; import { RelayClient } from "./client.js"; import type { RelayClientOptions } from "./client.js"; import { type RelayCredential } from "./credentials.js"; import type { RelayOutgoingPart, RelayRawMessage, RelayThreadId } from "./types.js"; export declare const RELAY_ADAPTER_NAME = "relay"; /** * Bounds on the forward walk that serves a backward `fetchMessages`. The page * size is the contract's maximum (`contracts/relay-openapi.yaml`, `getMessages` * `limit` maximum 100), so the walk reaches the tail in the fewest requests * Relay allows. */ export declare const RELAY_BACKWARD_WALK_PAGE_SIZE = 100; export declare const RELAY_BACKWARD_WALK_MAX_PAGES = 10; /** * How many Chat kinds one adapter remembers for {@link RelayAdapter.isDM}. * A Chat is created direct or group and never changes, so an entry never goes * stale; the bound exists only so a long-lived agent cannot grow the memo * without limit. */ export declare const RELAY_CHAT_KIND_CACHE_LIMIT = 1000; export interface RelayIdempotencyKeyContext { chatId: string; parts: ReadonlyArray; replyToMessageId?: string; threadId: string; } export type RelayIdempotencyKeyResolver = (context: RelayIdempotencyKeyContext) => string | Promise; export interface RelayAdapterOptions extends Omit { /** * Relay Agent Token or per-call resolver. * Defaults to `RELAY_AGENT_TOKEN`. */ token?: RelayCredential; /** * Standard Webhooks signing secret or per-delivery resolver. * Defaults to `RELAY_WEBHOOK_SECRET`. */ webhookSecret?: RelayCredential; /** * Disable Chat SDK surface typing for runtimes that own typing UX. * Defaults to true. */ typing?: boolean; /** Display name shown to Chat SDK handlers. */ userName?: string; /** This Relay agent Contact UUID, when known. */ agentId?: string; /** Standard Webhooks timestamp tolerance in seconds. */ signatureToleranceSeconds?: number; /** * Mark the Relay chat read as soon as an inbound message is verified, * before the event reaches Chat SDK dispatch. * * A read receipt is a statement about delivery, not about the answer, so a * debounce window, a queue or a model turn must never delay it. Turn this on * whenever the agent uses a `concurrency` strategy that defers the handler, * or whenever the read should land within a second of the send. * * Defaults to false, which leaves the read to the handler. */ markReadOnReceipt?: boolean; /** * Cancel the chat's running turn when a newer inbound message arrives, * before the new event reaches Chat SDK dispatch. * * A person who sends again while the agent is answering has changed the * question. Finishing the old answer spends a model turn on a question that * no longer stands and posts a reply to nothing. This calls * `ChatInstance.abortTurn(threadId)`, so the running turn's `thread.signal` * fires and the deferring `concurrency` strategy hands the newer message to * a fresh turn. * * Requires `supportsTurnCancellation`, which this adapter sets. Defaults to * false, which lets the running turn finish. */ abortActiveTurnOnReceipt?: boolean; /** * Stable key source for posts made outside an inbound webhook turn. * Inbound turns always derive keys from event_id plus send ordinal. */ idempotencyKeyResolver?: RelayIdempotencyKeyResolver; /** Controlled client injection for tests and custom transports. */ client?: RelayClient; } /** * Relay adapter for `chat@4.41.0`, limited to the locked public v1 contract. */ export declare class RelayAdapter implements Adapter { readonly name = "relay"; readonly userName: string; readonly botUserId?: string; readonly lockScope: "thread"; readonly persistThreadHistory = false; /** * Publish active turns so `ChatInstance.abortTurn(threadId)` cancels work * running in another process that shares the configured state adapter. A * Relay send is one idempotent HTTP request, so an aborted turn leaves no * partial bubble to reconcile. */ readonly supportsTurnCancellation = true; readonly typing: boolean; readonly client: RelayClient; private readonly abortActiveTurnOnReceipt; private readonly markReadOnReceipt; private readonly signatureToleranceSeconds?; private readonly webhookSecret; private readonly idempotencyKeyResolver; private readonly turns; /** * Chat UUID to `is_group`, as Relay reported it. * * `isDM` must answer synchronously, and Relay's stable thread ID carries * only the Chat UUID by design, so the answer has to come from somewhere * the adapter already learned it. Every path that reads a Chat from Relay * records the flag here: inbound webhook dispatch, `fetchThread`, and * `onThreadSubscribe`. * * This is a memo of an immutable Relay fact — a Chat is created direct or * group and never changes — not a delivery record and not persistence. It * is bounded so a long-lived agent in many chats cannot grow it without * limit. */ private readonly chatIsGroup; private chat?; constructor(options?: RelayAdapterOptions); initialize(chat: ChatInstance): Promise; /** * Report a non-fatal condition through Chat's logger once initialized, and * through the console before that, so a warning is never lost to whichever * side of `initialize` it happens on. */ private readonly unknownEventTypes; private reportUnknownEventType; private warn; encodeThreadId(data: RelayThreadId): string; decodeThreadId(threadId: string): RelayThreadId; channelIdFromThreadId(threadId: string): string; renderFormatted(content: FormattedContent): string; /** * Build the Chat SDK `fetchData` closure for one Relay media part. * * The download runs through this adapter's own Relay client, so a consumer * supplied `fetch` (Workers, a proxy, a test double) serves attachment bytes * exactly as it serves every other Relay call. */ private attachmentData; /** * Mint a replacement download URL for an attachment id. * * Returns `undefined` when the call cannot produce one and the caller still * holds a fallback URL; rethrows when there is nothing to fall back to, so a * genuine authorization or not-found failure is never swallowed. */ private freshDownloadUrl; /** * Build the `fetchData` closure for an attachment that survived a queue. * * The stored URL may already have expired, so the id is tried first: Relay * mints a new download link on every `GET /v1/attachments/{attachmentId}`. * The serialized URL is the fallback for the one case the id cannot cover — * an attachment whose `fetchMetadata` predates this adapter version. */ private rehydratedAttachmentData; /** * Rebuild `fetchData` on an attachment that survived serialization. * * `Message.toJSON()` drops `data` and `fetchData`, so Chat SDK calls this * when a queue or debounce strategy rehydrates a Message. A Relay download * URL expires 60 minutes after Relay minted it, and a queue can hold a * Message for longer, so this re-mints from `fetchMetadata.attachmentId` and * falls back to the stored URL only when the id call cannot serve one. */ rehydrateAttachment(attachment: Attachment): Attachment; parseMessage(raw: RelayRawMessage): Message; private unsupported; private send; private sendInTurn; private resolveExternalIdempotencyKey; private noopResult; /** * A tap on a Button of a Chat SDK Card reaches `chat.onAction` with the * Button's id and value, as https://chat-sdk.dev/docs/actions documents, * and not the message handlers, as the official WhatsApp adapter does for * its reply buttons. `messageId` is the Message holding the card. A reply * to a native Relay card (an id this adapter did not encode) is not an * action and stays a message. Returns whether the event was an action. */ private dispatchCardAction; private isMentioned; /** * Record what Relay said about a Chat's kind. Re-recording a known chat * refreshes its position so the bound evicts the least recently learned. */ private rememberChatKind; /** * Whether a thread is a direct conversation rather than a group. * * Chat SDK asks synchronously, and Relay's stable thread ID carries only * the Chat UUID, so this answers from what the adapter has already learned: * an inbound webhook dispatch, a `fetchThread`, or `onThreadSubscribe`. * * A chat this adapter has never seen answers `false` and says so on the * debug log. `false` is the safe direction — it is the group answer, so a * handler gates on mentions rather than replying to everything — and * `fetchThread(threadId)` settles the question for good. */ isDM(threadId: string): boolean; /** * Learn a thread's kind when Chat SDK subscribes to it, so `isDM` answers * correctly from the first handler call rather than after the first fetch. */ onThreadSubscribe(threadId: string): Promise; postMessage(threadId: string, message: AdapterPostableMessage): Promise>; /** Native Relay components use the same webhook-turn ordering, idempotency * and external key requirement as ordinary Chat SDK posts. */ postMessageParts(threadId: string, parts: readonly RelayOutgoingPart[], replyToMessageId?: string): Promise>; postChannelMessage(channelId: string, message: AdapterPostableMessage): Promise>; reply(threadId: string, messageId: string, message: AdapterPostableMessage): Promise>; editMessage(threadId: string, messageId: string, _message: AdapterPostableMessage): Promise>; deleteMessage(threadId: string, messageId: string): Promise; addReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise; removeReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise; startTyping(threadId: string): Promise; endTyping(threadId: string): Promise; markAsRead(threadId: string, messageId: string): Promise; /** * Fetch messages from a Relay chat. * * `forward` is Relay's native shape: one `GET /v1/chats/{id}/messages` per * call, and `nextCursor` is Relay's own cursor pointing at newer messages. * * `backward` — the Chat SDK default, and what `thread.fetchMessages()` asks * for when loading a chat view — has no native Relay equivalent, because * the public contract publishes exactly one opaque cursor and it advances * oldest-to-newest. It is served by walking forward to the tail and keeping * the newest `limit` messages seen. * * **The cost is real and worth knowing before you call it.** One backward * call issues up to {@link RELAY_BACKWARD_WALK_MAX_PAGES} requests of * {@link RELAY_BACKWARD_WALK_PAGE_SIZE} messages each — up to 10 round * trips covering 1000 messages — rather than the single request `forward` * costs. Chats shorter than one page cost exactly one request, which is the * common case. * * If the walk reaches the end of the chat, the result is exactly the most * recent `limit` messages and there is no `nextCursor`: Relay cannot * address older messages, so there is no further backward page to offer. * * If the walk is cut short by the page cap, the messages are the newest the * bounded walk could reach and `nextCursor` carries Relay's live forward * cursor. Passing it back as `cursor` resumes the walk from that point * rather than moving to older messages, so repeated calls converge on the * true tail. That is the opposite of the generic backward contract, and it * is the only meaning Relay's single forward cursor can carry. * * Messages are returned oldest-first within the page in every direction, as * the interface requires. */ fetchMessages(threadId: string, options?: FetchOptions): Promise>; fetchChannelMessages(channelId: string, options?: FetchOptions): Promise>; fetchMessage(threadId: string, messageId: string): Promise | null>; fetchThread(threadId: string): Promise; fetchChannelInfo(channelId: string): Promise<{ channelVisibility: import("chat").ChannelVisibility | undefined; id: string; isDM: boolean | undefined; metadata: Record; name?: string | undefined; }>; getChannelVisibility(): "private"; getUser(_userId: string): Promise; openDM(_userId: string): Promise; stream(threadId: string, stream: AsyncIterable): Promise | null>; handleWebhook(request: Request, options?: WebhookOptions): Promise; /** * Stamp the Relay read receipt for one inbound chat. * * A failed read never blocks the webhook's 2xx. Holding the response open * for it would make Relay time the delivery out and redeliver, which costs * the agent a retry to buy a receipt that Relay will re-request anyway. */ private readOnReceipt; /** * Cancel the chat's running turn, if there is one. * * `abortTurn` is a no-op when nothing is active, so a burst's first message * costs one state read. A failure is logged and never blocks the delivery: * the worst case is that the superseded turn finishes and posts, which is * the behaviour of an agent without this option. */ private abortOnReceipt; /** * The Message a person's swipe-reply names, as Chat SDK's own * `Message.replyTo`, so a model sees what the reply answers. * * Relay's wire carries a reply as a bare pointer, `reply_to: { message_id, * part_index }`, so the target is read once through GET /v1/messages/{id}. * Telegram's Chat SDK adapter fills `replyTo` the same way from the quoted * `reply_to_message` its webhook embeds. * * A reply names one bubble. When the target has more than one part, only * the named part is kept, the rule Relay's iOS app uses to draw the quote * (Relay-iOS `MessageReply.targetsExactPart`). * * A target that is gone, or a read that fails, never blocks the delivery: * the Message is dispatched without `replyTo`, the policy the adapter keeps * for its other reads around a delivery (`readOnReceipt`). */ private replyTarget; private initializedChat; private dispatch; } export declare function createRelayAdapter(options?: RelayAdapterOptions): RelayAdapter; //# sourceMappingURL=adapter.d.ts.map