Docs menu

Tools

SDKs

The three SDKs that drive channelstack without a test framework, and the control API they share. The Vitest plugin and pytest-channelstack are built on the TypeScript and Python SDKs; in a test, use them instead (Vitest plugin, pytest).

The same scenario in each#

A person mentions the app in a channel, and the script reads the app's reply in the thread.

import { connect } from "channelstack/client";await using client = await connect({ mode: "auto" });await using session = await client.openSession({ name: "example" });const slack = await session.slack();const ana = await slack.createUser({ name: "Ana" });const channel = await slack.createChannel({ participants: [ana, slack.app] });const msg = await ana.say("@my-agent hi", { channel });const reply = await msg.thread.waitForReply({ from: "my-agent" });console.log(reply.text);

Install#

LanguagePackageInstallNeeds
TypeScriptchannelstack, import channelstack (or channelstack/client)npm i -D channelstackNode 22 or later
Pythonchannelstackpip install channelstackPython 3.12 or later
Rustchannelstack cratecargo add channelstackEdition 2024, a Tokio runtime (cargo add tokio --features macros,rt-multi-thread)

To start a server (modes auto and start), an SDK needs the server binary:

LanguageBinary
TypeScriptCHANNELSTACK_SERVER_BIN, else the platform package installed with channelstack (@channelstack/server-<platform>-<arch>, an optional dependency)
Python, RustCHANNELSTACK_SERVER_BIN, else channelstack on the PATH

To only attach to a running server (mode attach), no binary is needed.

Connecting#

LanguageSignature
TypeScriptconnect(options?: { mode?: "auto" | "attach" | "start"; server?: string; token?: string }): Promise<Channelstack>
Pythonasync def connect(*, mode: Literal["auto", "attach", "start"] = "auto", server: str | None = None, token: str | None = None) -> Channelstack
Rustasync fn connect(mode: Mode) -> Result<Channelstack>, and async fn connect_with(mode: Mode, server: Option<&str>, token: Option<&str>) -> Result<Channelstack>
OptionDefaultMeaning
modeautoSee Modes. Rust: Mode::Auto, Mode::Attach, Mode::Start
serverCHANNELSTACK_URL, else the URL in <home>/server.jsonThe server to attach to
tokenCHANNELSTACK_TOKEN, else server.json's token when its URL is serverThe control API token. Passing it keeps it out of the environment

On connect, the SDK reads the server's /status and refuses a server whose major version differs from its own.

Modes#

ModeServer runningNo server running
autoAttachesStarts a private one
attachAttachesFails
startStarts a private one anywayStarts a private one

A server is running when it answers GET /_channelstack/status with the token within 2 seconds. A private server runs as channelstack start --no-portless --port 0 --server-file <temporary file>: a free loopback port, its token in a private file, never the shared server.json. It inherits the process's environment, and stops when the client closes.

The client and the session#

Everything a script does happens in a session: a scope in the server's one shared world that owns what it creates. Closing the session removes it all.

Channelstack (the client)Does
openSession({ name? })Opens a session
env({ proxy? })The app's env vars, as channelstack env prints them
status(){ ready, version, drivers }
reset()Drops all state on every channel. Avoid in parallel use
uiLoginLink()A one-time UI link, as channelstack ui prints
close()Closes the connection, and stops the server if this client started it
SessionDoes
sessionIdThe session's id
slack(), github(), linear(), notion(), resend(), google(), discord()The channel fixtures for this session (Slack, GitHub, Linear, Notion, Resend, Google, Discord)
quiet(){ busy, quietForMs, open }: what negative checks wait on
events({ since? })The session's event log: actions, deliveries with every attempt, the app's API calls
close()Closes the session and removes everything it created

Naming#

The handles and their methods are generated from the same routes, so the names match across languages, in each language's own style.

TypeScriptPythonRust
MethodscamelCase: waitForReplysnake_case: wait_for_replysnake_case: wait_for_reply
Fieldsproperties: msg.text, msg.postedAtattributes: msg.text, msg.posted_atgetters: msg.text(), msg.posted_at()
Positional argumentsana.say("hi", …)ana.say("hi", …)ana.say("hi")
Optionsa trailing object: { channel }keyword arguments: channel=channelbuilder methods: .channel(&channel)
The from option{ from: "my-agent" }from_="my-agent" (from is a keyword).from("my-agent")
Running a callawaitawait.await, or .send().await
Handles as argumentsthe handlethe handle&impl Handle; a mixed list as vec![&ana as &dyn Handle, &slack.app()]
Fields that are one of several handle typesthe handlethe handleJSON (serde_json::Value): msg.author()["kind"]
Durations"3s" or milliseconds"3s" or milliseconds"3s"
Options objects (createUser){ name: "Ana", displayName: "…" }name="Ana", display_name="…".name("Ana").display_name("…")

The API reference (client, Slack, GitHub, Linear, Notion, Resend, Google, Discord, OpenAI) lists every member, with each call in TypeScript and Python.

Waits#

The SDKs never sleep a fixed time: every wait polls until its condition holds, and fails after a timeout.

WaitReturns
waitForReply, waitForMessage, waitForComment, waitForActivityThe next new item matching the filter, after the last one this handle returned
latestReply, latestCommentWaits for one, then for the app to be quiet, then returns the latest
waitForModal, waitForState, waitForCall, settled, endedThe first state that matches
SettingDefault
timeout10s
Poll interval50ms
quietFor (the latest… waits)750ms

A wait that runs out of time raises WaitTimeoutError (TypeScript, Python) or Error::Timeout (Rust): Timed out after 10000ms waiting for a reply from my-agent.

Errors#

A refusal of the control API carries a stable error code.

LanguageBaseSpecific
TypeScriptChannelstackError: code, status, message, dataOne class per code: NotInChannelError, UnsupportedInLiveError, …
PythonChannelstackError: code, status, message, dataThe same class names
RustError::Api { code, status, message, data }, error.code()channelstack::codes::NOT_IN_CHANNEL, …

Rust's Error also has Http (the server couldn't be reached), Launch (finding or starting the server failed), Timeout, Invalid (an argument it can't send) and Files (a fixture file or directory a test named that isn't there, or a file where a directory belongs). A connection that is refused while the server starts is retried for 5 seconds. Every code is listed in Errors.

Disposal#

TypeScriptPythonRust
Clientawait using client = await connect(), or await client.close()async with await connect() as client, or await client.close()client.close().await
Sessionawait using session = …, or await session.close()async with await client.open_session() as sessionsession.close().await?
SlackFaultawait using fault = …, or await fault.undo()async with await slack.fault(…)fault.undo().await?

Disposing never raises for a handle that is already gone. Everything else a session created is removed with it.

Live credentials#

When a script leaves token out of createUser, every SDK reads it from CHANNELSTACK_<CHANNEL>_USER_<NAME>_TOKEN (GitHub: <LOGIN>) and sends it to the server once. Unset, the person is fake. See Environment variables.

The control API#

The SDKs are thin: each is generated from the server's routes, over a small hand-written runtime (transport, launcher, waits, durations, credentials). Anything that speaks HTTP can use the same API.

Base<server URL>/_channelstack, e.g. https://channelstack.localhost/_channelstack
AuthAuthorization: Bearer <token>, the token from server.json (or CHANNELSTACK_TOKEN)
BodiesJSON in, JSON out
Errors{ "error": "<code>", "message": "…", "data": { … } } with the code's HTTP status
SpecOpenAPI 3.1 at spec/openapi.json in the repository
curl -s -H "Authorization: Bearer $CHANNELSTACK_TOKEN" \
  https://channelstack.localhost/_channelstack/status

Session routes live under /sessions/{session}, a channel's under /sessions/{session}/<channel>. For example, ana.say("hi", { channel }) is:

curl -s -X POST -H "Authorization: Bearer $CHANNELSTACK_TOKEN" -H "content-type: application/json" \
  -d '{"message":{"text":"hi"},"channel":"C08E1F2G3H4"}' \
  https://channelstack.localhost/_channelstack/sessions/$SESSION/slack/users/U08B5K2M9QX/say

The spec carries x-channelstack-* extensions the generators read:

ExtensionSays
x-channelstack-resourceA schema whose values are handles (SlackUser, Session)
x-channelstack-factory, x-channelstack-methodThe SDK method an operation becomes, and on which handle
x-channelstack-refA field that takes a handle and sends its id
x-channelstack-error-codesThe error codes an operation can return
x-channelstack-stabilitystable (the server and session routes) or experimental (the channel routes and the UI link)
x-channelstack-liveHow it behaves on a live channel: unsupported, or requires the browser actor or proxy mode
x-channelstack-credentialAn optional credential the SDKs read from the environment when it is left out

One tag releases the server, the spec and every SDK at the same version.

Suggest changes to this page