Repository navigation
[kyo-slack] add Slack Socket Mode module - #1673
Merged
Merged
Conversation
fwbrasil
force-pushed
the
kyo-slack-socket-mode
branch
from
June 14, 2026 18:08
f70aea7 to
de03ba4
Compare
Kyo had no way to build a Slack app: a Socket Mode integration needs a WebSocket client that connects over `wss`, streams typed inbound envelopes, acks each one exactly once, reconnects without losing or duplicating envelopes, and calls the Slack Web API from inside a handler. The kyo-http WebSocket client also had three client-side correctness bugs that prevented a real Socket Mode connection from working at all (see Notes). A new `kyo-slack` module: a typed Socket Mode client. Cross-platform across JVM, JS, Native, and Wasm. `Slack` is opaque so a caller cannot fabricate a connection. Two entry points: - `Slack.run(config)(handler)`: scope-managed. Opens the socket, runs the receive loop under the reconnect policy, and tears everything down on scope exit (including an engine a rotation swapped in). - `Slack.init(config)`: manually managed, returning a live `Slack` the caller drives with `receive` and tears down with `close`. `close` is idempotent and total, mirroring `HttpWebSocket.close`. The receive loop yields `SlackEnvelope` values: `EventsApi`, `Interactive`, `SlashCommand`, `Hello`, `Disconnect`, and `Unknown` (which carries the raw frame for any unmodeled type, so no inbound data is dropped). The handler returns one `SlackAck` per envelope and the framework emits exactly one wire ack from the returned value. There is no public ack method, so forgetting to ack and double-acking are unrepresentable. `SlackAck` carries the inline response shapes: `Ack`, `ViewResponse`, `CommandResponse`, and `BlockActionsResponse`. `config.ackDeadline` bounds the handler: if it does not return in time, the framework emits the bare `SlackAck.Ack` and race-cancels the still-running handler so no second ack goes out. `Hello` and `Disconnect` carry no envelope id and are delivered but never acked. `Slack.chatPostMessage`/`chatPostEphemeral`/`chatUpdate`, `viewsOpen`/`viewsUpdate`/`viewsPublish`, `authTest`, and `custom` (a typed escape over any method via `Schema`). Callable from inside the handler: the bot token is bound as an ambient around the loop body on both the scoped `run` and the `init` + `receive` path, so a handler call resolves the token without threading it. `SlackBlock` is an ADT (`Section`, `Header`, `Divider`, `Context`, `Actions`, `Input`, `Image`; `Button`/`TextInput`/`Select` elements; `Text` objects), with `SlackBlock.Raw` as the single escape for a block type not yet modeled. `SlackMessage` and `SlackView` carry `blocks: Chunk[SlackBlock]` and the framework renders them to a native Block Kit JSON array, so no raw JSON string appears in the public API. `SlackBlock.dsl` provides concise builders. `config.reconnect` selects `Overlap` (default: confirm the fresh connection is live before stopping the old one, so no envelope is lost across the rollover), `Immediate` (close then reopen, accepting a brief gap), or `Off`. A routine disconnect rotates the socket while preserving at-most-once and at-least-once delivery across the rollover. The `link_disabled` disconnect reason is terminal under every policy and ends the loop with `SlackTerminalException`. Errors are the sealed `SlackException` base with six leaves (handshake, transport, decode, web-api, rate-limit, terminal), modeled on `HttpException`. Tokens are two distinct opaque types, `SlackToken.AppLevel` (opens the socket) and `SlackToken.Bot` (authenticates the Web API), not interchangeable, and neither carries a `Schema` or a `toString` that renders the secret. Identifiers are opaque types under `SlackId` so a mismatched id is a compile error at a call site. `Maybe`, `Result`, and `Chunk` throughout. An in-memory `SlackTransport` drives the full receive/ack/reconnect path cross-platform; `.notNative` live tests run the same path over a real kyo-http WebSocket and HTTP server. A doctest-verified README and a module CONTRIBUTING.md document the surface, and six runnable `*Demo` examples (one concept each) share a `Demos` helper. Three correctness fixes to the kyo-http WebSocket client were required for a real Socket Mode connection, each covered by a regression test: - `HttpUrl` did not recognize the `ws`/`wss` schemes, so a `wss://` url resolved to port 80 over plaintext. `HttpUrl.isTlsScheme` and the default-port logic now treat `wss` as TLS/443 and `ws` as plaintext/80, and `ssl` returns true for `wss`. - The WebSocket upgrade dropped the url query string. Slack's connection ticket lives in the query, so the client now carries it into the upgrade request-target and the server now carries it into the handler's request url (readable via `req.query`). - The client did not mask the auto-Pong it sends in reply to a server Ping; RFC 6455 section 5.1 requires a client to mask every frame, and Slack closed the socket with code 1002. `WebSocketCodec.readFrameWith` now takes a `mask` argument carrying the caller's client/server role and masks the auto-Pong accordingly. `SlackEnvelope.DisconnectReason` and `SlackAck`/`ViewAction` model only the valid Slack wire values; an unrecognized disconnect reason decodes to `Unknown(raw)` rather than failing, keeping the receive loop forward-safe against new wire values.
fwbrasil
force-pushed
the
kyo-slack-socket-mode
branch
from
June 15, 2026 01:41
de03ba4 to
fce546d
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Kyo has no Slack integration. Socket Mode is Slack's recommended way for a bot to connect: the app opens an outbound WebSocket and receives events, interactivity, and slash commands over it, with no public HTTP endpoint to host. Standing that up by hand means owning the
apps.connections.openhandshake, the envelope framing, the per-envelope ack protocol (Slack re-delivers anything it does not see acked within roughly three seconds), reconnect on a routinedisconnect, and a bot-token Web API client for the replies a handler sends back.Solution
A new
kyo-slackmodule. A live connection is the opaque typeSlack, so a caller cannot fabricate one.Two entry points open the socket:
Slack.run(config)(handler)is the scope-managed entry: it runs the receive loop and the scope finalizer tears down whatever engine is active at exit.Slack.init(config)is the manually-managed entry, returning aSlackthe caller drives withreceiveand tears down withclose.The loop streams typed
SlackEnvelopevalues into the handler:EventsApi,Interactive,SlashCommand,Hello, andDisconnect, with anUnknowncase carrying the raw frame so no envelope type is dropped. The handler returns oneSlackAck, and the framework emits exactly one wire ack per ackable envelope from that returned value. There is no public ack method, so forgetting to ack and double-acking are unrepresentable. If the handler does not return withinconfig.ackDeadline, the framework emits the bare ack and race-cancels the still-running handler, so a late payload ack is never sent; long work belongs in a forked fiber or aresponse_urlPOST.From inside the handler, a bot-token Web API client is callable through the ambient token that
run/receivebinds around the loop body:Slack.chatPostMessage/chatPostEphemeral/chatUpdate, theviews.*methods,Slack.authTest, andSlack.customfor an unmodeled method.Reconnect is driven by
config.reconnect, defaulting toOverlap: the fresh engine's transport is brought up live before the old one stops, and a bounded rolling seen-envelope_idwindow plus a residue drain of the old engine's already-buffered frames together guarantee no inbound envelope is lost across the rollover and none is delivered twice.Immediateaccepts a gap for new frames;Offends cleanly on a routine disconnect. Adisconnectcarryinglink_disabledis terminal under every policy and ends the loop withSlackTerminalException.Failures surface through the sealed
SlackExceptionhierarchy (SlackHandshakeException,SlackTransportException,SlackDecodeException,SlackWebApiException,SlackRateLimitException,SlackTerminalException); the web-api and rate-limit leaves carry the Slack error code and the parsed backoff as typed fields. Identifiers and tokens are opaque types (SlackId.*,SlackTs,SlackToken.AppLevel/Bot) so distinct id kinds and the two token capabilities cannot be interchanged, and a token value never renders in a message or a decoded frame. The surface usesMaybe,Result, andChunkthroughout and is cross-platform across JVM, JS, Native, and Wasm.Notes
The receive/run/reconnect/Web-API paths are driven against an in-memory
SlackTransportbackend bound through aLocal, so the full cross-platform suite exercises framing, acking, and rotation without a real socket. A separate set of.notNative-gated live tests run the same paths over a real kyo-http WebSocket and HTTP server (the in-process server is unavailable on Native).apps.connections.openreturns its wss url in a 2xx body, which kyo-http leaves on the raw text body rather than decoding; the handshake reads the full text response and decodes it explicitly for that reason. A Web API call signals errors as HTTP 200 with{"ok":false}, so the request path setsfailOnError = falseand branches on the decodedok, mapping a 429 toSlackRateLimitException.SlackEnvelope.DisconnectReasonand theUnknownenvelope/event cases preserve unrecognized wire values instead of failing, so a new Slack frame type does not break an existing deployment.The module depends on
kyo-httpandkyo-schema, ships a doctest-verified README and a moduleCONTRIBUTING.md, and is wired into the JVM, JS, Native, and Wasm aggregates inbuild.sbt.