Skip to content

[kyo-slack] add Slack Socket Mode module - #1673

Merged
fwbrasil merged 6 commits into
mainfrom
kyo-slack-socket-mode
Jun 16, 2026
Merged

fwbrasil merged 6 commits into
mainfrom
kyo-slack-socket-mode

Conversation

@fwbrasil

Copy link
Copy Markdown
Collaborator

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.open handshake, the envelope framing, the per-envelope ack protocol (Slack re-delivers anything it does not see acked within roughly three seconds), reconnect on a routine disconnect, and a bot-token Web API client for the replies a handler sends back.

Solution

A new kyo-slack module. A live connection is the opaque type Slack, 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 a Slack the caller drives with receive and tears down with close.

The loop streams typed SlackEnvelope values into the handler: EventsApi, Interactive, SlashCommand, Hello, and Disconnect, with an Unknown case carrying the raw frame so no envelope type is dropped. The handler returns one SlackAck, 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 within config.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 a response_url POST.

From inside the handler, a bot-token Web API client is callable through the ambient token that run/receive binds around the loop body: Slack.chatPostMessage/chatPostEphemeral/chatUpdate, the views.* methods, Slack.authTest, and Slack.custom for an unmodeled method.

Reconnect is driven by config.reconnect, defaulting to Overlap: the fresh engine's transport is brought up live before the old one stops, and a bounded rolling seen-envelope_id window 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. Immediate accepts a gap for new frames; Off ends cleanly on a routine disconnect. A disconnect carrying link_disabled is terminal under every policy and ends the loop with SlackTerminalException.

Failures surface through the sealed SlackException hierarchy (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 uses Maybe, Result, and Chunk throughout and is cross-platform across JVM, JS, Native, and Wasm.

Notes

The receive/run/reconnect/Web-API paths are driven against an in-memory SlackTransport backend bound through a Local, 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.open returns 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 sets failOnError = false and branches on the decoded ok, mapping a 429 to SlackRateLimitException. SlackEnvelope.DisconnectReason and the Unknown envelope/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-http and kyo-schema, ships a doctest-verified README and a module CONTRIBUTING.md, and is wired into the JVM, JS, Native, and Wasm aggregates in build.sbt.

@fwbrasil
fwbrasil force-pushed the kyo-slack-socket-mode branch from f70aea7 to de03ba4 Compare June 14, 2026 18:08
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
fwbrasil force-pushed the kyo-slack-socket-mode branch from de03ba4 to fce546d Compare June 15, 2026 01:41
@fwbrasil
fwbrasil merged commit 25cbc92 into main Jun 16, 2026
@fwbrasil
fwbrasil deleted the kyo-slack-socket-mode branch June 16, 2026 16:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant