ChatAdapter unstable
What a chat platform adapter implements.
An adapter is a set of Ops plus a static Descriptor of what the
platform supports. Adapters register in the Registry, which Chat
routes through by thread.platform.
Details
- Every op exists on every platform. Where the platform has no equivalent
the op fails with
Unsupported, naming the capability. - A post notifies nobody unless asked: mentions in Markdown do not notify by default.
- Length is checked before the call, with
checkMessageLength, in the unit the descriptor'smeasurecounts. - Adapters retry
retryfailures withretrySafeand never retryuncertainones.
Error Handling
Retries an adapter request with the policy adapters share.
Details
- Only failures whose retry value is
retryare retried, up to three times.uncertainanddeniedfailures are returned at once. - The wait is the error's
retryAfterwhen it has one, otherwise an exponential backoff from 500 milliseconds. - Inside
Chat.withoutRetriesthe request runs once.
Signature
declare function retrySafe<A, R>(effect: Effect<A, ChatError, R>): Effect<A, ChatError, R>Layers
Creates the layer that registers an adapter in the Registry.
When to use
Use when building an adapter package's layer. A platform that is off is a layer left out.
Signature
declare function layer<E, R>(adapter: Effect<ChatAdapter, E, R>): Layer<never, E, Registry | Exclude<R, Scope>>Models
What an adapter package builds: the platform's ops, its descriptor and, when the platform has one, its native stream.
Signature
interface ChatAdapter extends Ops { readonly descriptor: Descriptor; readonly nativeStream?: NativeStream;}Static description of a platform: its capabilities and limits, readable without a call to the platform.
Details
- An op whose capability is missing from
capabilitiesfails withUnsupported. limits.messageLengthis the platform's own limit for one message, in the platform's own unit. Where every message also carries a fixed overhead that the text does not, such as a card's structure, it is that limit less a fixed reservation for the overhead, and the adapter's docs give both numbers.measuregives what a Markdown string costs againstlimits.messageLengthandlimits.streamLength. It is pure and makes no call to the platform. It is an upper bound, never less than what the adapter sends for the text, and it adds up:measure(a + b) <= measure(a) + measure(b). It measures ASCII letters at one each.measuretakes theactionsa message carries as an optional second argument. Where text and elements share one budget (Slack) they add to the cost, and elsewhere the argument is ignored. With it,measure(md, actions) <= measure(md) + measure("", actions), so a caller can set room aside for the elements before it cuts the text,measure(md, actions) >= measure(md), andmeasure(md, [])ismeasure(md). Ameasurewith one parameter fits the type.limits.minWriteIntervalis the default floor between two writes to one thread, for streamed and multi-part posts.limits.streamLengthandlimits.streamAgeapply to native streams only.streamLengthis never more thanmessageLength, so a stream's text always fits anedit.limits.actionsPerMessage,limits.actionDataLength,limits.modalMetadataLengthandlimits.modalFieldsare there exactly when the matching capability is (buttonsfor the first two,modalsfor the last two). Each is the platform's number in the platform's unit, asmessageLengthis. Where the platform publishes none, it is the adapter's own cap, documented as the adapter's, and set so that a message holding every element at its cap still fitsmessageLength. The adapter checks them exactly and failsTooLarge: before the call for a message's elements, and before it opens a modal.limits.followUpAgeis there exactly whencommandsis: how long after a command itsfollowUpstill works.
Gotchas
Title and label limits of a modal are not on the descriptor. The adapter checks them the same way, and its docs list them.
Signature
interface Descriptor { readonly capabilities: ReadonlySet<"getUser" | "edit" | "delete" | "fetchMessage" | "history" | "download" | "startThread" | "getThread" | "opener" | "files" | "replyTo" | "nativeStream" | "buttons" | "selects" | "modals" | "modalErrors" | "commands" | "ephemeral">; readonly limits: { readonly actionDataLength?: number; readonly actionsPerMessage?: number; readonly filesPerMessage: number; readonly followUpAge?: Duration; readonly messageLength: number; readonly minWriteInterval: Duration; readonly modalFields?: number; readonly modalMetadataLength?: number; readonly streamAge?: Duration; readonly streamLength?: number; readonly uploadBytes: number; }; readonly measure: (markdown: string, actions?: readonly Array<{ readonly _tag: "Button"; readonly id: string; readonly label: string; readonly style?: "default" | "primary" | "danger"; readonly value?: string; } | { readonly _tag: "LinkButton"; readonly label: string; readonly url: string; } | { readonly _tag: "Select"; readonly id: string; readonly options: readonly Array<{ readonly label: string; readonly value: string; }>; readonly placeholder?: string; readonly selected?: string; }>) => number; readonly platform: string;}A file to upload with a post.
Signature
interface File { readonly content: Uint8Array; readonly contentType: string; readonly name: string;}A platform's native streaming of one message, used by ChatMarkdown.stream
when present. It is adapter-facing and not on Chat.
Details
startfails withUnsupportedwhen the platform refuses the feature for this thread or recipient, and the caller falls back to post-then-edit. It holds nothing back: all ofmarkdownis sent. Do not endmarkdowninside a surrogate pair: a lone surrogate is sent as U+FFFD.appendis never retried by the adapter.openmeans the text was added apart from its lastheldUTF-16 code units,stoppedmeans nothing was added because a user stopped the stream, andclosedmeans nothing was added because the stream is closed or expired.heldcounts the trailing code units the adapter could not send yet, such as an unclosed<or a high surrogate whose other half has not arrived. The caller keepsmarkdown.slice(markdown.length - held)and sends it again at the front of the next append.flushholds nothing back and sends a lone surrogate as U+FFFD. ATooLargefailure means nothing was added and the stream is still open.stopcloses the stream.stoppedsays whether a user had clicked stop on it. It succeeds withstopped: falseon a stream that is already closed.continuesonstartis the message id of the reply's previous part, absent for a reply's first message. It tells the adapter which reply the stream belongs to, so state kept per reply, such as a rate limit's backoff, carries over a rotation and never passes to another reply.
Signature
interface NativeStream { readonly append: (thread: { readonly id: string; readonly platform: string; }, messageId: string, markdown: string, options?: { readonly flush?: boolean; }) => Effect<{ readonly held: number; readonly state: "open" | "stopped" | "closed"; }, ChatError>; readonly start: (thread: { readonly id: string; readonly platform: string; }, options: { readonly continues?: string; readonly markdown: string; readonly recipient?: string; readonly replyTo?: { readonly authorId?: string; readonly isSelf?: boolean; readonly messageId: string; }; }) => Effect<Posted, ChatError>; readonly stop: (thread: { readonly id: string; readonly platform: string; }, messageId: string, options: { readonly end: "done" | "rotating"; }) => Effect<{ readonly stopped: boolean; }, ChatError>;}The operations of one platform. Chat has the same ops, routed by
thread.platform.
Details
posttakes standard Markdown that must fitlimits.messageLength. It never splits or truncates: the adapter checks the length itself and fails withTooLargewithout calling the platform. Mentions in it notify nobody.- A
postshows no link preview unless requested through the adapter's scopedwithPostOptions. This rule does not cover edits or native streams. fetchMessagefails withNotFoundfor a message that is gone.historypages lazily.backwardruns newest to oldest,forwardoldest to newest, andfromis exclusive. A thread's oldest message is its opener, whosethreadis the thread's parent: the one message in a thread's history that is not addressed to that thread. Without an opener, history starts at the first reply, whether the opener was deleted or the platform's thread root is not a message. Abackwardread that stops early has not reached the opener:openerreads it by itself.downloadfails withTooLargeas soon as more thanmaxBytesarrive. It streams, so a file is never held whole unless the caller asks:Stream.mkUint8Arraycollects the stream into one array.startThreadreturns the thread undermessageId, created when there is none. It is get-or-create, and the only way from an opener to its thread.openeris the message a thread hangs off:Nonefor a channel or direct address, or when it was deleted.actionsis a flat list of elements beside the Markdown, and the adapter lays out the rows. A platform without an element failsUnsupportedbefore the call, namingbuttonsorselects. Aneditreplaces the whole message, so an edit withoutactionsremoves them.followUpsends the answer a command'sDeferpromised, to whoever itsvisibilitynames. It is routed bydeferred.command.threadand never retried. It takes no files, andwithPostOptionsdoes not reach it. The contract is one call per deferral: a second posts another message on Slack and replaces the first on Discord. An adapter does not stop it, andChatTest's fake fails it. It failsNotFoundwith detailinteraction_expiredpastlimits.followUpAge, andUnsupportedwithoutcommands.
Signature
interface Ops { readonly delete: (thread: { readonly id: string; readonly platform: string; }, messageId: string) => Effect<void, ChatError>; readonly download: (thread: { readonly id: string; readonly platform: string; }, attachment: { readonly contentType?: string; readonly id: string; readonly name?: string; readonly size?: number; }, options: { readonly maxBytes: number; }) => Stream<Uint8Array<ArrayBufferLike>, ChatError>; readonly edit: (thread: { readonly id: string; readonly platform: string; }, messageId: string, content: { readonly actions?: readonly Array<{ readonly _tag: "Button"; readonly id: string; readonly label: string; readonly style?: "default" | "primary" | "danger"; readonly value?: string; } | { readonly _tag: "LinkButton"; readonly label: string; readonly url: string; } | { readonly _tag: "Select"; readonly id: string; readonly options: readonly Array<{ readonly label: string; readonly value: string; }>; readonly placeholder?: string; readonly selected?: string; }>; readonly markdown: string; }) => Effect<void, ChatError>; readonly fetchMessage: (thread: { readonly id: string; readonly platform: string; }, messageId: string) => Effect<{ readonly attachments: readonly Array<{ readonly contentType?: string; readonly id: string; readonly name?: string; readonly size?: number; }>; readonly author: { readonly id: string; readonly isBot: boolean; readonly isSelf: boolean; readonly name?: string; }; readonly id: string; readonly mentions: readonly Array<{ readonly end: number; readonly id: string; readonly isSelf: boolean; readonly kind: "role" | "user" | "channel" | "broadcast"; readonly start: number; }>; readonly raw: Json; readonly replyTo?: { readonly authorId?: string; readonly isSelf?: boolean; readonly messageId: string; }; readonly text: string; readonly thread: { readonly id: string; readonly platform: string; }; readonly timestamp: Utc; }, ChatError>; readonly followUp: (deferred: { readonly _tag: "Defer"; readonly command: { readonly _tag: "CommandInvoked"; readonly id: string; readonly raw: Json; readonly text: string; readonly thread: { readonly id: string; readonly platform: string; }; readonly userId: string; }; readonly visibility: "public" | "ephemeral"; }, content: { readonly actions?: readonly Array<{ readonly _tag: "Button"; readonly id: string; readonly label: string; readonly style?: "default" | "primary" | "danger"; readonly value?: string; } | { readonly _tag: "LinkButton"; readonly label: string; readonly url: string; } | { readonly _tag: "Select"; readonly id: string; readonly options: readonly Array<{ readonly label: string; readonly value: string; }>; readonly placeholder?: string; readonly selected?: string; }>; readonly markdown: string; }) => Effect<void, ChatError>; readonly getThread: (thread: { readonly id: string; readonly platform: string; }) => Effect<ThreadInfo, ChatError>; readonly getUser: (id: string, options?: { readonly in?: { readonly id: string; readonly platform: string; }; }) => Effect<User, ChatError>; readonly history: (thread: { readonly id: string; readonly platform: string; }, options: { readonly direction: "backward" | "forward"; readonly from?: string; }) => Stream<{ readonly attachments: readonly Array<{ readonly contentType?: string; readonly id: string; readonly name?: string; readonly size?: number; }>; readonly author: { readonly id: string; readonly isBot: boolean; readonly isSelf: boolean; readonly name?: string; }; readonly id: string; readonly mentions: readonly Array<{ readonly end: number; readonly id: string; readonly isSelf: boolean; readonly kind: "role" | "user" | "channel" | "broadcast"; readonly start: number; }>; readonly raw: Json; readonly replyTo?: { readonly authorId?: string; readonly isSelf?: boolean; readonly messageId: string; }; readonly text: string; readonly thread: { readonly id: string; readonly platform: string; }; readonly timestamp: Utc; }, ChatError>; readonly opener: (thread: { readonly id: string; readonly platform: string; }) => Effect<Option<{ readonly attachments: readonly Array<{ readonly contentType?: string; readonly id: string; readonly name?: string; readonly size?: number; }>; readonly author: { readonly id: string; readonly isBot: boolean; readonly isSelf: boolean; readonly name?: string; }; readonly id: string; readonly mentions: readonly Array<{ readonly end: number; readonly id: string; readonly isSelf: boolean; readonly kind: "role" | "user" | "channel" | "broadcast"; readonly start: number; }>; readonly raw: Json; readonly replyTo?: { readonly authorId?: string; readonly isSelf?: boolean; readonly messageId: string; }; readonly text: string; readonly thread: { readonly id: string; readonly platform: string; }; readonly timestamp: Utc; }>, ChatError>; readonly post: (thread: { readonly id: string; readonly platform: string; }, content: { readonly actions?: readonly Array<{ readonly _tag: "Button"; readonly id: string; readonly label: string; readonly style?: "default" | "primary" | "danger"; readonly value?: string; } | { readonly _tag: "LinkButton"; readonly label: string; readonly url: string; } | { readonly _tag: "Select"; readonly id: string; readonly options: readonly Array<{ readonly label: string; readonly value: string; }>; readonly placeholder?: string; readonly selected?: string; }>; readonly files?: readonly Array<File>; readonly markdown: string; readonly replyTo?: { readonly authorId?: string; readonly isSelf?: boolean; readonly messageId: string; }; }) => Effect<Posted, ChatError>; readonly startThread: (thread: { readonly id: string; readonly platform: string; }, messageId: string, options?: { readonly name?: string; }) => Effect<{ readonly id: string; readonly platform: string; }, ChatError>;}The message a successful post created.
Signature
interface Posted { readonly id: string; readonly thread: { readonly id: string; readonly platform: string; }; readonly timestamp: Utc;}What the platform says about an address.
Signature
interface ThreadInfo { readonly createdAt?: Utc; readonly kind: "channel" | "thread" | "direct"; readonly name?: string; readonly parent?: { readonly id: string; readonly platform: string; }; readonly raw: Json; readonly thread: { readonly id: string; readonly platform: string; }; readonly topic?: string;}A user as the platform reports them.
Details
nameis the guild nick wheninwas given and the platform has one.rawis the platform's own record of the user. What the model has no field for, such as a Slack user's team or a Discord member's roles, is read from there. Each adapter documents what itsrawholds.
Signature
interface User { readonly id: string; readonly isBot: boolean; readonly isSelf: boolean; readonly name: string; readonly raw: Json;}Services
Service that holds the adapters by platform. Chat.layer provides it.
Details
get fails with NoAdapter for a platform with no adapter registered.
Registering a second adapter for a platform replaces the first.
Signature
declare class Registry extends Shape<"effect/chat/ChatAdapter/Registry", { readonly descriptors: Effect<readonly Array<Descriptor>>; readonly get: (platform: string) => Effect<ChatAdapter, ChatError>; readonly register: (adapter: ChatAdapter) => Effect<void>;}, this> { constructor(_: never);}Validation
checkMessageLength
unstableFails with TooLarge when Markdown does not fit the descriptor's
limits.messageLength, measured with the descriptor's measure.
When to use
Use when implementing post, edit and NativeStream.start in an adapter,
so a message that is too long fails without a call to the platform.
Details
Pass the string the adapter is about to send, after escaping. For a
measure that counts what escaping adds, measuring the escaped string
gives the exact cost, so a post is neither refused when the platform would
take it nor passed when the platform would refuse it on length. Pass the
message's actions too, so they are measured with it.
Signature
declare function checkMessageLength(descriptor: Descriptor, op: string, markdown: string, actions?: readonly Array<{ readonly _tag: "Button"; readonly id: string; readonly label: string; readonly style?: "default" | "primary" | "danger"; readonly value?: string;} | { readonly _tag: "LinkButton"; readonly label: string; readonly url: string;} | { readonly _tag: "Select"; readonly id: string; readonly options: readonly Array<{ readonly label: string; readonly value: string; }>; readonly placeholder?: string; readonly selected?: string;}>): Effect<void, ChatError>