@statelyai/sky
v0.1.0-alpha.1
Published
Client SDK for Stately Sky: runtime client for hosted state machines, effect worker, and XState trace observer
Maintainers
Readme
@statelyai/sky
The client SDK for Stately Sky — an observation ledger for
XState-compatible actors running anywhere, plus an optional durable kernel.
Zero runtime dependencies; xstate is an optional peer (only needed for the
observer).
Six entry points:
| Function | Use |
| --------------------- | ------------------------------------------------------------------- |
| createSkyObserver | One-line XState inspector that streams traces to the trace service (any XState app). |
| createSkyTransport | Transport for @statelyai/sdk's createInspector({ transport }) that records into the trace service. |
| createSkyClient | Trace emitter for custom instrumentation — record sparse events/snapshots/actors from any app. |
| createSkyQueryClient| Read side: list systems/sessions/actors, read traces, get each actor's current state, mint session read tokens. |
| createSkyRuntime | Talk to the durable kernel: register logic, spawn/send actors, run effect workers. |
| createEffectWorker | Long-running worker that claims effects from the kernel's outbox and executes them. |
npm install @statelyai/sky@alphacreateSkyObserver
An XState v5 inspect observer that streams actor lifecycle, events,
snapshots, and actions to the trace service as trace records. Runtime-agnostic:
it works for any local XState app, not only Sky-hosted actors.
The shortest path is the inspect property on a client — one shared observer
for any number of actors:
import { createActor } from "xstate";
import { createSkyClient } from "@statelyai/sky";
const sky = createSkyClient({ endpoint: "http://localhost:3010", token });
const actor = createActor(machine, { inspect: sky.inspect });
actor.start();createSkyObserver remains for standalone use — pass SkyClientOptions to
construct a dedicated client (createSkyObserver({ endpoint, token })), or
{ client } to share an existing one.
Using with @statelyai/sdk
createSkyTransport is a write-only transport for the Stately inspector's
createInspector({ transport }). It records the inspector's actor tree,
events, snapshots, transitions, and actions into the trace ledger.
import { createInspector } from "@statelyai/sdk/inspect";
import { createSkyTransport } from "@statelyai/sky";
const transport = createSkyTransport({ endpoint, token });
const inspector = createInspector({ transport });
const actor = createActor(machine, { inspect: inspector.inspect }).start();
// ... later
await transport.close();With an injected transport the inspector creates no live inspector URL. To get
both the live room and the ledger, keep the default inspector and call Sky's
observer from the same callback (xstate accepts only one inspect):
const inspector = createInspector();
const sky = createSkyClient({ endpoint, token });
const actor = createActor(machine, {
inspect: (event) => {
inspector.inspect(event);
sky.inspect.next(event);
},
}).start();createSkyClient
The batching trace emitter. Buffers records and flushes them to the trace
service's /ingest endpoint on a size/interval trigger. The observer is built
on it; call it directly to instrument anything with an event → state model
— a non-XState state machine, a Temporal/Restate workflow, a backend job.
Capture can be sparse: emit any subset of events, snapshots, transitions, and
lifecycle records, in any order, and the query side degrades gracefully (an
actor with no snapshot yet has snapshot: null; one with no lifecycle record
reads status: "unknown").
import { createSkyClient } from "@statelyai/sky";
const client = createSkyClient({
endpoint: "http://localhost:3010",
token: process.env.SKY_TOKEN, // tenant is derived from the token server-side
batchSize: 100, // flush after N records (default 100)
flushIntervalMs: 1000, // …or every N ms (default 1000)
redact: (record) => record, // scrub PII before it leaves the process
onError: (error) => reportToSentry(error), // ingest failures (default: console.error)
maxQueueSize: 10_000, // drop the oldest records past this (default 10000)
});
await client.actorCreated("actor-1", { logic: "order" });
await client.eventObserved("actor-1", { type: "SUBMIT" });
await client.snapshotObserved("actor-1", { value: "submitted", context: {} });
await client.close(); // flushes the queue and stops the timerBackground flushes (the interval timer, and records emitted by the observer)
never reject; failures go to onError and the batch is requeued. Explicit
flush(), close(), and awaited record() calls still reject. The interval
timer is unref'd, so it never keeps a Node process alive — which means a
short-lived process must await client.close() (or transport.close())
before exiting, or buffered records are lost. client.onError(handler)
subscribes additional listeners and returns an unsubscribe function.
systemId and sessionId are generated when omitted and exposed on the
client — hand client.sessionId to whoever wants to watch. Apps outside
JavaScript can skip the SDK entirely and POST /ingest trace records to the
trace service over plain HTTP.
createSkyQueryClient
The read-side counterpart to createSkyClient — what an externally-built
dashboard uses to observe sessions. Point it at the trace service and a token.
import { createSkyQueryClient } from "@statelyai/sky";
const query = createSkyQueryClient({
endpoint: "http://localhost:3010", // the trace service (sky-trace)
token: process.env.SKY_TOKEN!, // a tenant token, or a session read token
});
// Discover what's been observed.
const { systems } = await query.listSystems();
const { sessions } = await query.listSessions({ systemId: systems[0] });
const { actors } = await query.listActors({ sessionId: sessions[0] });
// Read traces (all filters optional; undefined params are skipped).
const { records } = await query.getTraces({
sessionId: sessions[0],
kind: "transition.observed",
from: "2026-01-01T00:00:00Z",
limit: 100,
});
// The timeline for one actor.
const timeline = await query.getActorTimeline(actors[0], {
sessionId: sessions[0],
});
// The reconstructed actor tree for a session: status + latest snapshot.
const { actors: tree } = await query.getSessionActors(sessions[0]);
// tree[i] = { actorId, parentId, status, snapshot, snapshotAt, lastActivityAt }Non-2xx responses throw SkyApiError (with .status and .body).
Read tokens for sharing
To share a single session's live view without handing out your tenant token, mint a session-scoped read token. It only sees that one session; the server enforces the scope.
const { token, expiresAt } = await query.createSessionReadToken(sessions[0], {
expiresInSeconds: 3600, // optional
});
// Hand `token` to a viewer; they construct a query client scoped to that session:
const viewer = createSkyQueryClient({ endpoint, token });
await viewer.getSessionActors(sessions[0]);createSkyRuntime
A typed client for the (optional) durable kernel's HTTP API. Point it at a kernel endpoint and a tenant token.
import { createSkyRuntime } from "@statelyai/sky";
const runtime = createSkyRuntime({
endpoint: "http://localhost:3000",
token: process.env.SKY_TOKEN!, // from `pnpm create-tenant`
});
// Register a logic definition (plain-JSON XState machine).
const logic = await runtime.registerLogic({
name: "toggle",
definition: {
id: "toggle",
initial: "inactive",
states: {
inactive: { on: { TOGGLE: "active" } },
active: { on: { TOGGLE: "inactive" } },
},
},
});
// Spawn a durable actor from it.
const actor = await runtime.spawnActor({ logicId: logic.id });
// Send an event. Returns { status: "queued", eventId } — processing is async.
await runtime.send(actor.id, { type: "TOGGLE" });
// Read the current persisted snapshot.
const snap = await runtime.getSnapshot(actor.id);
console.log(snap.currentSnapshot.value); // "active"Extra event data is passed as fields on the event object (or via
options.payload):
await runtime.send(actor.id, { type: "SUBMIT", total: 4200 });send never throws on the documented outcomes; it returns a discriminated
result:
const result = await runtime.send(actorId, { type: "GO" });
// { status: "queued", eventId } | { status: "duplicate", idempotencyKey }
// | { status: "not-active", actorStatus }Live transitions over SSE
const sub = runtime.subscribe(actor.id, {
afterSeq: 0, // backfill from the beginning
onTransition: (t) => console.log(t.seq, t.toSnapshot.value),
onHeartbeat: () => {},
onError: (err) => console.error(err),
});
// later
sub.unsubscribe();Non-2xx responses that aren't a documented outcome throw SkyApiError (with
.status and .body).
createEffectWorker
Effects your machine emits (any action that isn't assign/raise/cancel/sendTo)
land in a durable outbox. A worker claims them, runs them, and settles them.
import { createSkyRuntime, createEffectWorker } from "@statelyai/sky";
const runtime = createSkyRuntime({ endpoint, token });
const worker = createEffectWorker(runtime, {
types: ["sendEmail"], // only claim these effect types
concurrency: 4,
async handle(effect) {
await sendEmail(effect.params);
// Optionally loop an event back into the actor and/or return a result:
return { event: { type: "EMAIL_SENT" }, result: { ok: true } };
},
});
// Throwing from handle() fails the effect with retry (up to 5 attempts).
// worker.stop() drains in-flight effects before resolving.
await worker.stop();The worker polls claimEffects, heartbeats the lease while handle runs
(default lease 30s, heartbeat at half that), then calls completeEffect or
failEffect. All of those are also exposed on the runtime if you want to build
your own worker loop.
