The official browser-first TypeScript SDK for Crowded Kingdoms. CrowdyJS gives you typed clients for the whole platform: identity and studio administration (the Management surface), world data (the Game surface), the UDP proxy realtime stream, and ck-exec, where an app's server code runs — all behind one unified GraphQL API.
Authentication follows a two-token model: an identity session token for
account and admin operations, and short-lived app-scoped tokens for
gameplay, minted per app through client.portal.
Start here:
- SDK guide — the canonical walkthrough of everything in this README.
- Build a game — a hands-on tutorial from sign-in to a playable voxel game.
- Platform overview — how a client session flows through the platform.
npm install @crowdedkingdoms/crowdyjsServer compatibility. A release selects fields the Application API it was built against has, so it needs that Application API or newer; promote the Application API before the SDK on each tier.
| CrowdyJS | Needs the Application API (ck-api) |
|---|---|
| 18.43.0 | v2.96.0 or later: every call that answers an app token selects playerPass (portal.mintAppToken, exchangeCode, refresh, exchangeManagedPlayerAssertion, signInWithMinecraft), and portal.playerPass, exec.callAsPolicy, and exec.setCallAsPolicy are new. Through 18.42.0 those token calls needed v2.90.0. ExecConnection.vouch needs hub servers on ck-exec 0.27.0. Every other call needs what 18.42.0 needs |
| 18.42.0 | v2.95.0 or later: managedPlayers.settings selects fleetSessionsOpen, and fleetSessions.list, voxels.count, voxels.delete, and voxels.deleteUntilComplete are new. An organization admin's fleetSessions.close and a refresh sent again after a lost answer rely on v2.95.0 too. Every other call needs what 18.41.0 needs. The client uses the address a refresh answers, a rule made for v2.95.1 and later (see Token refresh during gameplay) |
| 18.41.0 | v2.90.0 or later: every call that answers an app token selects userId (portal.mintAppToken, exchangeCode, refresh, exchangeManagedPlayerAssertion, signInWithMinecraft), and managedPlayers.deleteMany is new. Through 18.40.1 those token calls needed v2.85.0. managedPlayers.settings selects the fleet limits of v2.89.0, and exec.orgComputeCeiling reads v2.88.0's. A fleet session's not-present reports need realtime servers v0.51.0 |
| 18.40.1 | as 18.40.0 |
| 18.40.0 | as 18.39.0; client.fleetSessions and exec.connectAsServer need v2.89.0 or later (see Game servers: fleet sessions) |
| 18.39.1 | as 18.39.0 |
| 18.39.0 | v2.85.0 or later (selects applicationApiUrl, applicationApiWsUrl and platformConfig's sharedApplicationApi*; the gameApi* names stay as deprecated aliases until January 1, 2027) |
| 18.33.0 | v2.73.0 or later (exec's mod builds, mods and CLIENT halves select studioProjectId and studioRevision; exec.modClientStarter, crowdyStudio.links) |
| 18.32.0 | v2.70.0 or later (chunks.get and chunks.byDistance select Chunk.voxelsUpdatedAt) |
| 18.31.1 | as 18.31.0 |
| 18.31.0 | v2.69.0 or later (chunks.get selects VoxelState.updatedAt) |
| 18.30.0 | as 18.29.0 (ChunkStore reads boxes and since: v2.67.0) |
| 18.29.0 | v2.68.0 or later for the GraphQL proxy (udpNotifications selects ChunkChangedNotification) |
| 18.28.0 | v2.67.0 or later (gameApps.nearbyGrids selects permissionKeys) |
| 18.27.0 | v2.64.0 or later (isEmailConfirmationRequiredError reads a code v2.65.0 sends) |
| 18.26.0 | v2.64.0 or later (app reads and apps.update select idleTimeoutSeconds and effectiveIdleTimeoutSeconds) |
| 18.25.0 | v2.61.0 or later (app reads and apps.update select hasSafetyModerator; platform.territoryPolicies selects regionCode) |
| 18.24.0 | v2.60.0 or later (users.me selects ageBracket and country; app reads and apps.update select the safety log and age fields; the teen safety calls). auth.recordPlayerConsents with both flags and auth.playerLegalAcceptance() without an app work against older releases |
| 18.22.0 | v2.58.0 or later (ExecInstance.orphaned) |
| 18.11.0 | what 18.10.0 needs; the Game Kit's hub modules need the app to run the starter pack of a compute toolchain with ckx-sdk 0.10.0 (kit.topology deploys it) |
| 18.10.0 | the release after v2.43.1 (channel and team bans); the access-ended close needs ck-exec 0.16 |
| 18.9.0 | the release after v2.40.2 (InputLogSession.missingRecords) |
| 18.8.0 | v2.40.2 or later (ExecBuild.sdkVersion) |
| 18.7.0 | v2.40.0 or later (runtimeGate, channel audio) |
| 18.6.0 | v2.39.0 or later (every app read selects replayLoggingEnabled) |
CrowdyJS targets browsers by default and uses native fetch, WebSocket,
crypto, btoa, and atob. Node tools can still use the SDK, but must
provide browser-compatible globals when opening realtime connections (e.g.
pass webSocketImpl on Node ≤ 21 for subscriptions).
import {
BrowserLocalStorageTokenStore,
createCrowdyClient,
} from '@crowdedkingdoms/crowdyjs';
const client = createCrowdyClient({
// One API: identity, studio admin, world data and the UDP proxy.
httpUrl: 'https://api.example.com/graphql',
wsUrl: 'wss://api.example.com/graphql',
tokenStore: new BrowserLocalStorageTokenStore(),
realtime: {
retryAttempts: 8,
waitTimeoutMs: 5000,
},
});
// A browser game on its own domain signs players in through Crowded Kingdoms'
// HOSTED sign-in: the player types their password into Studio, never into your
// page, and your client comes back holding a token confined to your app.
await client.session.restore();
const entered = await client.portal.handleSignInCallback(); // no-op without ?code=
if (!entered && !client.session.getToken()) {
// On your "Sign in with Crowded Kingdoms" button:
await client.portal.signIn({ appId, redirectUri: `${location.origin}/auth/callback` });
return; // the browser is navigating to Studio
}
// The client now holds an app-scoped token: gameplay reads and the UDP proxy run on it.
const me = await client.users.me();
console.log(me.email);Your game's origin must be registered under the app's redirect URIs (in Studio,
the app's Settings > Sign-in & redirect URIs); that one entry admits it to CORS
and to the hosted sign-in return. Direct sign-in (client.auth.login / register /
magic link / social) is served only to first-party pages (Studio) and to
non-browser callers (Node, CLI, tests); from any other browser origin the API
answers HOSTED_SIGN_IN_REQUIRED (isHostedSignInRequiredError). See
Authentication.
There is one endpoint. managementUrl was removed in v14 — see
MIGRATION.md.
Sign-in returns an identity session token good for account, studio admin and token minting, and rejected for gameplay. Each game is entered with a short-lived app-scoped token confined to that one app, so a game stack never receives the player's full session.
Which flow you use depends on where your code runs (ck-api v1.88.0, 2026-09-08):
| your code runs... | sign in with | then |
|---|---|---|
| in a browser, on your own domain (every customer game) | portal.signIn -> Studio -> portal.handleSignInCallback |
the client already holds the app token |
| in a browser, on the first-party host (Studio) | auth.login / magic link / social |
portal.mintAppToken(appId) |
| outside a browser (Node, CLI, CrowdyCPP, tests) | auth.login / auth.register |
portal.mintAppToken(appId) |
| anywhere, for players of an organization that runs its own accounts | the organization signs its player in: its server mints with an org token, or its sign-in service signs an assertion | portal.adoptAppToken(response) / portal.exchangeManagedPlayerAssertion(...) — see Org-managed players |
The first row is the only one a game on its own domain can take: the direct
sign-in mutations are refused from a non-first-party browser origin with
HOSTED_SIGN_IN_REQUIRED. The reason is the player's password: a form on a
customer's domain that collects it is indistinguishable, to the platform and to
the player, from a phishing page.
Every player stores the terms and an age attestation before playing (ck-api
v2.35.0, 2026-10-07). Until they do, portal.mintAppToken,
portal.createAuthorizationCode and portal.refresh answer
LEGAL_ACCEPTANCE_REQUIRED (isLegalAcceptanceRequiredError;
legalAcceptanceRequiredOf(err).missingDocuments names what is missing). On the first row
Studio's /authorize asks for everything, so a browser game only has to send the player
back through portal.signIn when a refresh is refused that way. On the other rows,
show the documents with your own checkbox, each linked (client.auth.playerLegalDocuments()
and, since ck-api v2.60.0, the app's own client.auth.appRequiredDocuments(appId)), then call
client.auth.recordPlayerConsents({ acceptLegal: true, attestAgeOfMajority: true, appId })
before minting; client.auth.playerLegalAcceptance({ appId }) says whether that is still
needed. auth.register takes the same fields, and a browser page must send them.
See MIGRATION.md.
A new password account confirms its email before it plays (ck-api v2.65.0, 2026-11-11).
Until the player opens the link auth.register emailed, those same three calls answer
EMAIL_CONFIRMATION_REQUIRED (isEmailConfirmationRequiredError). Studio's /authorize
handles it on the first row; a native client shows "check your inbox" and offers
client.auth.resendConfirmationEmail(email). Accounts made before 2026-11-11, managed
players, staff and dev or test accounts made with a provisioning token are not asked.
The player gate (ck-api v2.60.0, the teen safety program) runs at every mint and
refresh: a country Crowded Kingdoms does not serve is refused TERRITORY_NOT_SUPPORTED
(territoryNotSupportedOf(err)?.country), an account with no age AGE_REQUIRED
(ageRequiredOf), an age the app or the country does not admit AGE_REQUIREMENT_NOT_MET
(ageRequirementNotMetOf), and a player under 18 in an app without its safety log
SAFETY_LOG_REQUIRED (safetyLogRequiredOf), or (ck-api v2.61.0) in an app whose organization
has appointed no safety moderator SAFETY_MODERATOR_REQUIRED (safetyModeratorRequiredOf).
Ask the date of birth and the country on a neutral screen: it shows no age, and only a player
under 18 sees the line that a parent or guardian agreed. Send the answers with
auth.register({ ..., birthDate, country, parentalConfirmation }), or
auth.recordPlayerAge({ birthDate, country, parentalConfirmation }) for an account that has
none. No refusal names an age and the SDK's readers surface none: tell the player they cannot
play this, without a number, and do not offer the date again. Since v2.61.0 the same client
(address and user agent) is refused at sign-up and recordPlayerAge for 24 hours after an age
refusal, and an account that answers recordPlayerAge under 13 is deleted. users.me() reports
ageBracket and country, and platform.territoryPolicies() (public) lists the countries and,
since v2.61.0, regions (regionCode, ISO 3166-2: a country with a region listed is checked by
region), so a sign-up form can say a place is not served before an account exists. The age is
optional until the platform admits players under 18; until then the 18+ attestation still
applies.
Crowded Kingdoms no longer hosts games (retired 2026-10-29), so a customer's game always runs on its own domain and takes the first row. See Hosting your game.
Hosted sign-in (browser game, own domain) is OAuth2 Authorization Code + PKCE; the verifier never leaves your origin and your page never sees a credential:
const game = createCrowdyClient({ httpUrl: apiUrl, wsUrl,
tokenStore: new BrowserLocalStorageTokenStore('crowdyjs:app:' + appId) });
// Boot: finish a sign-in we are returning from (no-op without ?code=).
const entered = await game.portal.handleSignInCallback();
// "Sign in with Crowded Kingdoms" button: go to Studio's hosted page and come back.
await game.portal.signIn({ appId, redirectUri: `${location.origin}/auth/callback` });
// -> Studio /authorize (the player signs in there, consents if the app is not trusted)
// -> back to redirectUri?code=...&state=... -> handleSignInCallback() abovesignIn derives the hosted page from the API host you configured
(ck.<tier>.crowdedkingdoms.com -> studio.<tier>.crowdedkingdoms.com/authorize,
localhost:3000 -> localhost:3001); pass authorizeUrl to override. Your
redirectUri's origin must be one of the app's registered redirect URIs.
beginEntry / completeEntry are the same steps without the defaults.
Direct sign-in + mint (first-party page or non-browser). Use two clients: an
identity client (session token) and a per-game client (app token). They never
share a token store, and they need not share a URL — mintAppToken returns the
endpoint for the app's own datacenter.
const identity = createCrowdyClient({
httpUrl: apiUrl,
tokenStore: new BrowserLocalStorageTokenStore('crowdyjs:session'),
});
await identity.auth.login({ email, password }); // or register / magic link / social
const t = await identity.portal.mintAppToken(appId);
const game = createCrowdyClient({
httpUrl: t.applicationApiUrl!,
wsUrl: t.applicationApiWsUrl!,
tokenStore: new BrowserLocalStorageTokenStore('crowdyjs:app:' + appId),
});
game.setToken(t.token);
game.world(appId).subscribe({ actorUpdate: (n) => { /* ... */ } });Game-to-game routes through Studio's hosted page for a fresh per-game token.
Notes:
portal.mintAppToken(appId)returns the token plusapplicationApiUrl/applicationApiWsUrl/expiresAt; it does not store the token on the identity client — set it on the per-game client.- Every app-token answer carries
userId(18.41.0, Application API v2.90.0): the user the token signs in, the idusers.me()returns.portal.mintAppToken,exchangeCode,refresh,exchangeManagedPlayerAssertion, andsignInWithMinecraftall return it, so nomecall is needed to learn it. - Each client's
AuthStateis observed by both its HTTP client and its realtime socket, so HTTP and WebSocket auth never drift within a client. client.session.restore()reads from the configuredtokenStore.BrowserLocalStorageTokenStoreis provided; bring your ownTokenStorefor SSR or Node. PKCE state usesBrowserSessionPkceStoreby default.- Use
client.auth.setToken(token)to seed a token externally (e.g. when restoring auth from a non-default storage).
Deeper reading: Portals & app-scoped tokens and Sign in.
An organization that runs its own accounts can sign its players in to its own apps itself
(18.16.0, cks-game-api #557). The player never types a Crowded Kingdoms password, and Crowded
Kingdoms holds no email or password for it: the organization vouches for the player and the
device gets the player's own app token, which plays exactly like any other. An org-managed
player has no session and no wallet, plays only its organization's apps, and its mods are paid
for by the organization where it switched them on (managedPlayers.setAppMods). An operator
turns the feature on for an organization.
The organization accepts the Org-Managed Players Addendum first (18.17.0, ck-api v2.53.0).
An admin of the organization accepts it once in Studio (Org > Players); until then every
sign-in, refresh and provision answers ORG_LEGAL_ACCEPTANCE_REQUIRED
(orgLegalAcceptanceRequiredOf(err)), which neither the player nor your server can fix.
managedPlayers.settings(orgId) reports termsAccepted, the current termsVersion and its
termsUrl. The SDK does not wrap the acceptance: it binds the organization, so a person makes
it in Studio. From 18.41.0 the same call reports the organization's fleet limits, and needs
Application API v2.89.0: fleetSessionsEnabled, maxFleetSessions, and maxFleetPlayers.
From the organization's server, with an org token. Create the token in Studio (or
organizations.createToken({ orgId, scopes: ['players:mint'], appIds: [appId] })) and keep it
on the server: it signs in any of the organization's players, and the API refuses one sent
with an Origin header. The SDK deliberately has no wrapper for the mint; it is one request:
// your server, after your own sign-in succeeded
const res = await fetch('https://ck.dev.crowdedkingdoms.com/graphql', {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${process.env.CK_ORG_TOKEN}` },
body: JSON.stringify({
query: `mutation($i: MintManagedPlayerTokenInput!) { mintManagedPlayerToken(input: $i) {
token gameTokenId userId appId expiresAt applicationApiUrl applicationApiWsUrl discoveryUrl launchUrl } }`,
variables: {
i: {
appId,
externalId: account.id,
gamertag: account.displayName,
ageYears: account.ageYears, // whole years, as your organization knows them
country: account.country, // ISO 3166-1 alpha-2
region: account.region, // ISO 3166-2 (UA-30), where the country is checked by region
},
},
}),
});
const { data } = await res.json();
// send data.mintManagedPlayerToken to the player's device// the player's device
const access = await fetch('/api/crowded-kingdoms/token').then((r) => r.json());
const game = createCrowdyClient({ httpUrl: access.applicationApiUrl, wsUrl: access.applicationApiWsUrl });
game.portal.adoptAppToken(access); // refuses an org token by mistake
game.world(appId).subscribe({ actorUpdate: (n) => { /* ... */ } });externalId is your own stable account id (not an email); the first sign-in creates the player
and the same id is always the same player. The token refreshes (refreshGameplayToken) until
the sign-in's lifetime ends (sessionTtlSeconds, at most the organization's setting); then the
device asks your server again.
Age and country (ck-api v2.60.0). Send the player's ageYears and country with every
sign-in, and region (ISO 3166-2, v2.61.0) where the country is checked by region (the regions
platform.territoryPolicies() lists; Ukraine's today): on the mint's input
(MintManagedPlayerTokenInput, exported as a type) or as the assertion's claims
(ManagedPlayerAssertionClaims). Crowded Kingdoms stores an age bracket and the country on the
player and applies a minor's defaults itself. A country or region it does not serve, or a
missing region it needs, is refused TERRITORY_NOT_SUPPORTED, and an age under the app's, the
country's or the platform's youngest AGE_REQUIREMENT_NOT_MET, before the player exists; then
the same player is refused for 24 hours whatever is sent, and a player that exists and is said
to be under 13 is deleted. A refresh is refused once the stored bracket is wholly below the
app's youngest age. The age and country are optional while every managed player is 18 or older
under the Org-Managed Players Addendum (left out, the player counts as an adult) and required
once the platform admits players under 18 (AGE_REQUIRED without an age).
With a signed assertion. Register a public key once
(managedPlayers.registerSigningKey({ orgId, kid, algorithm: 'EdDSA', publicJwk, issuer }));
your sign-in service signs a short JWS per player (iss, aud: 'ck:app:<appId>', sub your
account id, iat, exp at most 300 s later, a fresh jti, optionally gamertag, and
ageYears, country and region as above: ManagedPlayerAssertionClaims) and the device trades it,
without your server calling Crowded Kingdoms:
const access = await game.portal.exchangeManagedPlayerAssertion({ appId, assertion });Each assertion works once; a refusal reads with assertionRejectedOf(err)?.reason
(expired, replayed, signature, …).
Administration takes an org admin's session with manage_players:
client.managedPlayers.list / get / provision (up to 500 a call: pre-provision before a
launch) / update (rename, disable, enable) / endSessions / delete, settings (the
operator-set limits and the addendum), signingKeys / registerSigningKey / revokeSigningKey, and
appModsEnabled / setAppMods (manage_billing). From your server, an org token with
players:manage also works for the player operations.
deleteMany(orgId, externalIds) (18.41.0, Application API v2.90.0) deletes 1 to 100 players
in one call, with the authorization delete takes. Its answer counts deleted, notFound,
and held, and lists each external id with its outcome: DELETED, NOT_FOUND, or
LEGAL_HOLD. A held player is kept and does not fail the call, so read the outcomes. organizations.revokeToken(id, { endSessions: true })
also ends the sessions a token signed in.
Before an app token expires, call game.refreshGameplayToken() while gameplay
is active. It closes the old-token UDP proxy, refreshes and stores the token,
and opens the new-token proxy while existing realtime handlers resubscribe in
place. It deliberately stops on the first failed stage: if the old proxy cannot
confirm disconnect, no refresh is attempted; if refresh fails, the old token is
retained; if the new proxy connect fails, the fresh token remains stored —
surface the error and retry game.udp.connect() instead of rotating again.
A refresh whose answer is lost is sent again (18.42.0, Application API v2.95.0).
After a refresh the old token stays valid for one minute, or until its own expiry if
that is sooner. A refresh sent again with the old token in that minute answers the same
new token. portal.refresh() uses this: when a refresh gets no answer (a network
failure, a timeout, or a gateway's 502, 503, or 504), it sends the refresh again with
the token it still holds, up to twice, 0.5 and 2 seconds apart.
- A refusal is an answer. The SDK sends a refused refresh once and throws the refusal.
- If every send fails, the client still holds the old token. Call
refreshGameplayToken()orportal.refresh()again within the minute and the answer is the same new token. - After the minute the old token is refused, and the player signs in again.
- Signing out with either token ends both.
- An Application API before v2.95.0 ends the old token at once. There a refresh sent again after a lost answer is refused.
- Every send of one refresh goes to one address: the endpoint the first send went to, whatever moved the client meanwhile.
The client uses the address a refresh answers (18.42.0, Application API v2.95.1). A
refresh is answered with the address of the API instance that answered it, for as long as
that instance stays in service. So applicationApiUrl in a refresh answer differs from the
endpoint in use in two cases only: the instance is about to be removed, or the client
called through the shared origin. An instance that is about to be removed keeps answering
for longer than a token's lifetime, so a client that refreshes on time is told where to go
before the instance is gone.
- Requests move first. When the answer names another address, the client's next
request goes there, and the realtime connection opens there the next time it opens
(
applicationApiWsUrl). - A refresh closes nothing. While a realtime connection is open or opening, requests and the connection both stay where they are. An instance that is leaving tells that connection, and the client then moves both together, as before.
refreshGameplayToken()on the binary relay follows the answer. It closes the relay before the refresh and opens it after, so the relay opens at the answered address.- An address the client could not reach in the last five minutes is not followed, and neither is one that fails the rule for every address a server names: see One rule for an address a server names.
followRefreshAddress: falsein the client's configuration keeps the client on the endpoint you gave it. Use it in a page whose content policy names only the shared origin.- Against an Application API before v2.95.1 a refresh answer names the instance with the
fewest realtime connections, another one most of the time. Each such address serves the
app, but clients that only make requests are not counted, so they can all be sent to one
instance. Set
followRefreshAddress: falseon such clients against an older API.
game.portal.refresh() remains available for clients with no active UDP
lifecycle to preserve. A native (direct-UDP) client should pass the server it
is connected to — game.portal.refresh({ ip4, clientPort }), the pair
serverWithLeastClients handed it — so the Application API (v1.83.7+) authorizes the
new token on that same Buddy and answers authorizedServer: when it is set,
keep the socket and sign with the new token; when it is null, place again with
serverWithLeastClients. A Buddy silently drops datagrams for a token it was
never told about, so a native refresh without it is a re-placement.
The teen safety program (18.24.0, ck-api v2.60.0). The platform enforces a player's voice and video scopes, contacts and blocks on the realtime servers, and keeps the app's safety log; your game shows the player the controls, the recording notice and the indicator. Everything a player does here takes the app token, on the game client:
// The safety log: show a notice before the player first speaks or appears on camera while
// voice or video is recorded, and an indicator while it is.
const recording = await game.apps.recording(appId); // { enabled, voice, video }
if (recording?.voice || recording?.video) showRecordingNoticeAndIndicator(recording);
// Voice and video: who the player sends to and hears from (OFF, CONTACTS, EVERYONE).
const settings = await game.safety.commSettings(appId);
await game.safety.setCommSettings(appId, { voiceReceive: 'CONTACTS' });
// Contacts (mutual, per app: what CONTACTS admits), blocks and reports.
await game.safety.requestContact(appId, otherUserId);
await game.safety.acceptContact(appId, requesterUserId);
await game.safety.block(appId, otherUserId);
await game.safety.fileReport({ appId, reportedUserId, reason: 'HARASSMENT', details, occurredAt: new Date() });- Scopes.
commSettingsreturns the EFFECTIVE scopes the servers enforce, the player'schoices, and what policy allows (voiceAllowed,videoAllowed). A player can only lower them. An adult may choose anything (EVERYONEby default); a player under 18 (isMinor) has each mediumOFFuntil a parent consents, then at mostCONTACTS.safety.requestParentalConsent(appId, 'VOICE' | 'VIDEO', parentEmail)asks a parent through the platform's consent service (PARENTAL_CONSENT_UNAVAILABLE:parentalConsentUnavailableOf(err)?.reasonisnot_configured,provider_refusedorprovider_unavailable). - Contacts.
contacts,contactRequests(INCOMING, thenOUTGOING),requestContact,acceptContact,removeContact(removes, declines or cancels). - Blocks.
block,unblock,blocks: nothing passes between the two players, either way, and the blocked player is not told (its contact requests are answered as usual and dropped). A hub that carries one player's words or media to another asks first (ck-exec'splayers.blocked), because the realtime servers pass what a hub emits. - Reports.
fileReportcovers both players' recorded sessions from 15 minutes beforeoccurredAt, and the platform preserves them for the app's moderators.SOCIAL_LIMIT_REACHED(socialLimitReachedOf) refuses past 100 waiting requests, 1,000 contacts or 1,000 blocks. - Every change reaches the player's live sessions within a second.
Moderators hold moderate_safety on the app (an organization role, or the org's admins)
and use their identity session: client.moderation.reports(appId, { status }) (open
CHILD_SAFETY reports first), resolveReport(appId, reportId, outcome) and
escalateReport(appId, reportId, ncmecReportId). A report's sessions are the recorded sessions
it covers; a moderator reads them with inputLog.messages on an app token for the app, while the
report is open or escalated, and every read is audited. An app that admits players under 18
needs an appointed moderator (ck-api v2.61.0): a member whose own role grants
moderate_safety (an admin alone does not count), or its minors are refused
SAFETY_MODERATOR_REQUIRED. apps.app(appId).hasSafetyModerator tells the organization's
members whether it has one (null for anyone else).
A player's own records. On an app with the safety log a player reads what it sent itself:
inputLog.sessions(appId) without a filter lists its own sessions, and inputLog.messages(appId, gameTokenId) reads one. On an app that admits players under 18, manage_apps reads nothing
more, and every read is audited (ck-api v2.61.0).
App admins (manage_apps): apps.update(appId, { replayLoggingEnabled, replayLoggingRecordsVoice, replayLoggingRecordsVideo, minPlayerAge }) (an app that admits
players under 18 must keep its safety log: SAFETY_LOG_REQUIRED), and
apps.setRequiredDocuments(appId, documents) for the app's own documents, which its players
accept on top of the platform's.
Crowded Kingdoms' own apps sign Minecraft players in: portal.minecraftChallenge(appId), a
Mojang session join by the Minecraft client itself, then portal.signInWithMinecraft({ appId, username, serverId, birthDate, country, parentalConfirmation, acceptedDocuments }). Any other app
is refused FORBIDDEN.
- Sign in on the identity client with
client.auth(login/register), or restore a stored session withclient.session.restore(). This yields the session token, which gameplay rejects. - Mint an app-scoped token for the app (
identity.portal.mintAppToken(appId), or the PKCE portal flow across origins) and build a per-game client holding it (game.setToken(token)). The gameplay steps below run on that game client. - Subscribe to UDP proxy notifications with
game.udp.subscribe(handlers, appId)—appIdis required (the SDK opens the realtime socket on demand and scopes it to that app). - Join a chunk by sending an initial actor update.
- Send actor, voxel, text, audio, video, and client-event updates through
game.udpor the higher-levelgame.world(appId)helpers. - Before the app token expires, call
game.refreshGameplayToken(). - Call
client.close()(andgame.close()) when disposing the SDK instances.
Game-client surface (end-user, browser-safe):
| Sub-client | What it does |
|---|---|
client.auth |
Sign-in: login / register (email + password, with the age answers birthDate / country / parentalConfirmation), magic link, social/OIDC. Passwords: requestPasswordReset / resetPassword, changePassword, and setInitialPassword for an account created by magic link or a social provider (added in 15.1.0). Log out, and linked identities (myIdentities, linkIdentity/unlinkIdentity). The terms and the age: playerLegalDocuments, appRequiredDocuments, recordPlayerConsents, playerLegalAcceptance, recordPlayerAge; a developer's: developerLegalDocuments, recordDeveloperConsents, developerLegalAcceptance. No dev bypass — devLogin was removed in 15.0.0 and DEV_AUTH_BYPASS is gone from every tier. |
client.users |
me (with ageBracket and country), updateGamertag, profile reads; playerProfile / playerProfiles (up to 100) for other players' public { userId, gamertag, disambiguation }. |
client.safety |
The player's own controls in an app (app token): voice and video scopes (commSettings, setCommSettings), a parent's consent (requestParentalConsent), contacts, blocks and reports (fileReport). See Player safety. |
client.session |
Token store, restore(), getToken(), manual setToken(). |
client.portal |
App-scoped token minting (mintAppToken) and the cross-origin PKCE entry flow (beginEntry / handleAuthorizeRequest / completeEntry / refresh). playerPass() answers a player pass for the app token in hand (18.43.0). For an org-managed player, adoptAppToken stores the token its organization minted and exchangeManagedPlayerAssertion trades the organization's signed assertion. Crowded Kingdoms' own apps sign Minecraft players in (minecraftChallenge, signInWithMinecraft). |
client.hosting |
Deprecated. Crowded Kingdoms no longer hosts games (retired 2026-10-29): the hosting API answers CONTENT_HOSTING_DISABLED on every tier, and its reads return null or an empty list. The methods (claim, beginPublish / completePublish / abandonPublish, setEnabled, game(slug), listed()) and the Node helper publishDirectory (@crowdedkingdoms/crowdyjs/hosting) remain in the package. See Hosting your game. |
client.platform |
Public platform configuration (config()) and the territory list (territoryPolicies()). |
client.serverStatus |
gameClientBootstrap(appId) — per-app version info, UDP status, spatial limits. |
client.chunks, client.voxels, client.actors, client.avatars, client.state |
World data reads + writes: terrain/LODs, voxel edit + history/rollback, durable actors, avatars, per-user app state blobs. client.voxels also counts and removes an app's recorded edits (18.42.0): see Recorded voxel edits. |
client.host |
Game-host election (get, amIHost) + actor liveness heartbeat. amIHost is UI convenience only — a hub decides host-only actions from its caller. |
client.teleport |
Teleport requests. |
client.inputLog |
The input log (18.6.0): sessions(appId) and messages(appId, gameTokenId) read the client inputs recorded for an app with replay logging on (apps.update(appId, { replayLoggingEnabled: true })). A player reads their own; manage_apps reads every session. Keep paging while hasNextPage is true. |
client.channels, client.teams |
Messaging channels and app-scoped player teams (membership + roles). |
client.exec |
ck-exec: an app's server code as hubs and spokes. connect(appId, { nodeType, key }) opens a player's connection to an execution host; the ExecConnection it returns has call, callRaw, subscribe, ping, onReconnect and close, with MessagePack payloads, and it reconnects and renews subscriptions by itself. starters / build / deploy build and deploy an app (manage_compute); logs, instances, versions, activateVersion, setEnabled, restartType and status operate it, and orgComputeCeiling(orgId) reads what each of the organization's apps may run; mod* are players' mods on grids they own, and modClient*, gridClientMods, consentClientMod, trustAuthor, revokeClientModConsent and revokeAuthorTrust their CLIENT halves. See ck-exec. |
client.playerWallet |
Player spend: balance, ledger, hourly charges, spend caps, card setup, auto-recharge. A ck-exec mod's compute is billed here, to its owner. |
client.marketplace |
Player-authorized grid claims (claimGridOwnership, claimGridChunk, releaseClaimedGrid, requests and invites) and studio moderation of player code (admission queue, listing administration, claim policy). Mods publish and install through client.exec. |
client.crowdyStudio |
Cloud project, personal-library, and common-file APIs for Crowdy Studio: target-scoped files, metadata/module names, optimistic revisions, copy-by-value imports, atomic saves. |
client.crowdyStudioGitHub |
Optional GitHub repository for a Crowdy Studio project: status, bind (push the project in, or take the repository), unbind, refresh, layout (with kind: a mod or a Construct game), tree, getFile, batched getFiles, commit-guarded putFile / deleteFile, and commitFiles (many changes as one commit). While bound the repository is the working tree and every Studio save commits; the project's files are the server's mirror at github.sha. Never required. |
client.udp |
UDP proxy subscriptions + spatial mutations (sendActorUpdate, sendVoxelUpdate, sendAudioPacket, sendVideoPacket / sendVideoFrame, sendTextPacket, sendClientEvent, sendSingleActorMessage, sendChannelMessage, sendRangedChannelMessage). |
client.realtime |
Connection status, manual connect() / disconnect(), onStatus() listener, and receiveStats(): what the client received and dropped. |
client.refreshGameplayToken() |
Safely rotates an active game client's app token (see Token refresh). |
client.rediscoverEndpoint() |
Asks the shared origin where the client's app is served and moves there, with what you could not reach (18.42.0). The client does this by itself when its requests or its realtime connection get no answer. client.activeAppId() is the app it asks about. See Surviving the loss of an instance. |
client.world(appId) |
Higher-level helpers for browser games (actor.join, actor.sendState, actor.sendText, actor.sendToActor). |
client.kit(appId) |
Game Kit: typed clients for the ck-exec starter hubs (world, matchmaking, sessions, NPCs and pets) on one shared connection, their topology, realtime conventions, and parties, guilds and chat (kit.social) — see Game Kit. |
createWorldSession(client, appId, config) |
World Stores: opt-in, SDK-managed game state from the @crowdedkingdoms/crowdyjs/stores subpath — see World Stores. |
Studio-admin surface (privileged; drive with an org admin's session, or an org token for the managed-player calls
and the fleet session calls, grouped under client.admin and mirrored at the top level):
| Sub-client | What it does |
|---|---|
client.organizations |
Orgs, members, RBAC roles, org API tokens (with scopes and appIds for org-managed players). |
client.managedPlayers |
Org-managed players: list, provision, rename, disable, end sessions, delete; assertion signing keys; whether the org pays for their mods in an app; where the org stands on the addendum. See Org-managed players. |
client.fleetSessions |
For an organization's own game servers (18.40.0): open, refresh, and close a fleet session with the organization's org token, and list the open ones (18.42.0). An admin of the organization lists them and closes any of them with a session. The session itself is FleetSession from @crowdedkingdoms/crowdyjs/fleet (Node), and client.exec.connectAsServer opens the server's hub connection. An org token and a fleet token stay on a server your organization runs. See Game servers: fleet sessions. |
client.apps |
App registry, discovery + routing (create, routeFor, marketplace), visibility, and player-code admission mode / allow-list administration. The safety log's state for players (recording, readable with an app token) and the app's own documents (setRequiredDocuments). |
client.moderation |
An app's safety reports for its moderators (moderate_safety): reports, resolveReport, escalateReport. See Player safety. |
client.appAccess |
Access tiers + per-user grants, and the feature keys a tier grants (defineFeature, grantTierFeature, tierFeatures, …), which a hub checks with the node API's players.features; timed bans (suspend, unsuspend) and resyncTierGridPermissions. |
client.billing |
Org wallet + per-app spend budgets. |
client.payments |
Payment checkouts (wallet top-ups, plan purchases). |
client.quotas |
Usage quotas at the org/app scope. |
client.usage |
Replication + GraphQL usage reporting. |
client.sharedEnvironment |
Publish to shared, runtime gating, spend caps, auto-billing. |
client.gameApps |
App grids (createGrid / deleteGrid), first-class grid ownership (ownership / assignOwnership / transferOwnership), and grid runtime-permission administration, including open grids (setOpenPermissions / openPermissions, 18.1.0): the keys a grid grants every player, which a zone everyone may build in needs, since the most specific grid over a chunk decides who builds there. |
The SDK is for normal clients, and designed for production. It carries what players,
developers and org-admins call, and nothing only a super-admin or a platform operator can
call: those fields are in the API, and platform tooling calls them directly (18.0.1 removed
the last wrappers; see MIGRATION.md). There is no client.operator, and
infrastructure operations live in the separate infra-control-plane service.
Auth, user reads and the studio-admin surface use the identity session token; the world/UDP surfaces require an app-scoped token for that app. Both go to the same endpoint.
CrowdyJS wraps the full public API surface — every
non-deprecated public root field has a typed method, with Relay *Connection
cursor-pagination variants alongside the legacy offset lists. The SDK never
relaxes server-side authorization: exposing an operation here just gives you a
typed wrapper; the caller still needs the right token and permission. Drive
privileged surfaces from a studio backend with an org-scoped or admin token,
not from an untrusted browser.
mintAppToken returns applicationApiUrl / applicationApiWsUrl, so you rarely need a
separate routing query. When you do (e.g. pre-flight discovery), query the
app's routing fields:
query AppForRouting($appId: BigInt!) {
app(appId: $appId) {
appId
splitMode
deploymentTarget
applicationApiUrl
}
}applicationApiUrl is populated for both dedicated (splitMode) and shared
(deploymentTarget: "shared") apps. When it's set, build a second
CrowdyClient with httpUrl: applicationApiUrl (and the matching wsUrl) holding
that app's app-scoped token, then drive gameplay through that client. Apps
with no applicationApiUrl keep working against the default httpUrl you
configured. See Loading an app's Application API.
subscribe takes the handlers and a required appId (second argument).
The Application API scopes the realtime session to that app and rejects an
app-agnostic subscription with a RealtimeConnectionEvent
(code: 'APP_ID_REQUIRED'); a missing or invalid gameplay token is rejected
with AUTH_REQUIRED. Run one client per app (each holding that app's
app-scoped token) when a player is in multiple apps at once.
const appId = '1';
const unsubscribe = client.udp.subscribe(
{
actorUpdate: (event) => {
console.log(event.uuid, event.state);
},
voxelUpdate: (event) => { /* ... */ },
text: (event) => { /* ... */ },
audio: (event) => { /* ... */ },
video: (event) => {
// One webcam fragment; feed a VideoFrameAssembler to get whole frames.
const frame = assembler.ingest(event.uuid, decodeBase64(event.videoData));
if (frame) drawJpeg(event.uuid, frame.bytes);
},
actorLeft: (event) => {
// The server says this actor is gone (about 5 s after its last update).
// World Stores do this for you: `session.actors.onLeave` fires at once.
removeAvatar(event.uuid);
},
clientEvent: (event) => { /* ... */ },
serverEvent: (event) => { /* ... */ },
genericSpatial: (event) => {
// An app-defined spatial payload (opcode 140): binary relay only, see below.
console.log(event.uuid, event.payload); // payload is base64
},
singleActorMessage: (event) => {
// A direct actor-to-actor message addressed to you.
console.log(event.uuid, event.payload); // payload is base64
},
channelMessage: (event) => {
// A message broadcast on a channel you're subscribed to.
console.log(event.channelId, event.payload); // payload is base64
},
genericError: (event) => {
console.warn(event.sequenceNumber, event.errorCode);
},
connectionEvent: (event) => {
console.warn(event.code, event.message);
},
error: (error) => {
console.error(error.code, error.message);
},
},
appId,
);
// Or use the world helper, which passes its appId automatically:
// client.world(appId).subscribe(handlers);
client.realtime.onStatus((status) => {
console.log('realtime:', status);
});
// Later:
unsubscribe();The SDK uses the graphql-transport-ws protocol through graphql-ws,
reconnects with backoff, re-reads the current token before reconnecting, and
resubscribes automatically. RealtimeConnectionEvent carries a retryable
flag: UDP_PROXY_CONNECTION_FAILED is transient (back off and resubscribe),
while AUTH_REQUIRED / APP_ID_REQUIRED must be fixed by the caller first.
Unsubscribing stops delivery only; call client.udp.disconnect() to close the
UDP proxy session.
A session that goes 15 minutes without gameplay input ends, and the SDK does not
reconnect it (18.26.0). The replication server releases a player who sends no movement,
edits, messages, voice or video for the app's idle timeout (effectiveIdleTimeoutSeconds
on the app: 900 unless the app sets its own with apps.update({ idleTimeoutSeconds }), and
never when it sets 0). Keep-alives and keyframes that repeat an unchanged state do not count.
The status becomes inactive on both transports (relay close GAMEPLAY_IDLE_CLOSE_CODE,
4410, or the IDLE_TIMEOUT_CODE connection event). Reconnect on the player's next input:
client.realtime.onStatus((status) => {
if (status === 'inactive') showPausedOverlay(); // the player stepped away
});
onPlayerInput(() => {
if (client.realtime.status() === 'inactive') client.realtime.connect();
});genericSpatial receives opcode 140 (GENERIC_SPATIAL_1), an app-defined spatial payload the
server fans out without reading — what client.udp.sendGenericSpatial and CrowdyCPP's
Connection::sendGenericSpatial send. It travels only on the binary relay
(realtime: { binaryTransport: true }): the GraphQL udpNotifications union has no member for
it, so the GraphQL proxy drops it and a client on that transport never sees one. A World Stores
session carries it on its bus too: session.context.on('genericSpatial', …).
// Binary relay only (there is no GraphQL mutation for opcode 140), after udp.subscribe.
await client.udp.sendGenericSpatial({
appId,
chunk: { x: '0', y: '0', z: '0' },
uuid: myActorUuid, // 32 ASCII characters
payload: encodeBase64(bytes), // at most 1,123 bytes decoded
// distance defaults to 8, decayRate to 0
});Off the relay sendGenericSpatial throws CrowdyRealtimeError (BINARY_RELAY_UNAVAILABLE,
retryable: false) and sends nothing; a payload over GENERIC_SPATIAL_MAX_PAYLOAD_BYTES
throws RangeError.
From 18.41.0 a player's realtime client makes the checks a fleet session makes. What it can check depends on the transport.
On the binary relay (realtime: { binaryTransport: true }) the client receives each
datagram as the realtime server sent it, so it verifies the datagram's HMAC with the player's
app token before a handler runs. No option turns the check off. In this table a spatial
notification is any notification except a channel message, channel audio, and a refused
send.
| What arrives | What the client does | Counter |
|---|---|---|
| A signed bundle whose HMAC fails | Drops the whole bundle | hmacFailures |
| A spatial notification whose own HMAC fails | Drops it | hmacFailures |
| A spatial notification with no signature, outside a signed bundle | Drops it. The realtime servers sign every spatial notification they send. | unsigned |
| A frame the client cannot read | Drops it | malformed |
| A channel message or channel audio outside a signed bundle | Delivers it. These two have no field for a signature. | none |
| A refused send | Delivers it to genericError, with verified |
errorsReceived, unverifiedErrorsReceived |
On the GraphQL subscription (the default transport) the client receives objects that the Application API read from those datagrams. No signature reaches the client, so on this transport the client trusts the Application API, over TLS.
On both transports the client drops a notification that names another app than the one
you subscribed for, and counts it (wrongApp). Such a notification settles no awaited send
and reaches no handler. A channel message, a refused send, and a connection event name no
app, and the client delivers them. The Application API applies the same rule to the GraphQL
subscription before it sends.
genericError receives a second argument, verified:
client.udp.subscribe(
{
genericError: (event, verified) => {
console.warn(event.sequenceNumber, event.errorCode, verified);
},
},
appId,
);verifiedis true when the refusal arrived on the binary relay inside a bundle the client verified.verifiedis false today on both transports. The realtime servers send a player's session each refusal alone, as 3 bytes with no room for a signature.- A refusal changes one thing. It rejects the awaited send whose sequence number it names. The connection, the status, and the token stay as they were, whatever the code.
- Treat an unverified
TOKEN_EXPIREDas a hint. Refresh the app token through the Application API and act on that answer.
client.realtime.receiveStats() returns the seven counters: hmacFailures, unsigned,
malformed, wrongApp, errorsReceived, unauthorizedReceived, and
unverifiedErrorsReceived. Report a count above 0 in wrongApp, unsigned, or
hmacFailures to Crowded Kingdoms. The SDK logs a warning at the first drop it counts in one
of those three, and again each time that count doubles.
The relay's check is asynchronous, so a notification reaches its handler after the check, in the order the datagrams arrived.
If your environment uses direct connect, set realtime.discoveryUrl. Under
direct connect mintAppToken hands the client ONE api instance, and without a way
to ask for another the client cannot leave it: it re-dials a dead host until its
retries run out and then sits there, connected to nothing.
const bootstrap = await client.udp.gameClientBootstrap(appId);
const client = createCrowdyClient({
httpUrl: bootstrap.applicationApiUrl,
wsUrl: bootstrap.applicationApiWsUrl,
realtime: {
// The LOAD BALANCER, not the instance above. A discovery URL that dies with
// the instance it exists to replace is worse than none.
discoveryUrl: bootstrap.discoveryUrl,
},
});That is the whole integration — the SDK builds re-discovery from the URL itself,
so recovery does not depend on every game remembering to write a callback. Pass an
explicit realtime.rediscover only to override it (e.g. createMintRediscover
when you hold an identity client and would rather re-mint than reuse a token near
expiry).
Requires 13.9.0 or later, and the version matters more than it looks. Before
13.9.0 the escalation to re-discovery was reachable only by a client that had
NEVER connected: a session that was working and then lost its instance re-dialled
one dead address forever, logging only Binary relay socket error. Setting
discoveryUrl on an older build therefore changes nothing in the case you set it
for. ck-api must be v1.20.0+ to return discoveryUrl at all.
Pass a logger. Everything the SDK knows about losing an instance it says
through that logger, including an explicit warning when it cannot move. With none
wired, a client that failed to re-discover and one that never tried look
identical.
Requests re-discover too (18.42.0). The client counts the requests in a row that got no
answer: a network failure, a timeout, or a gateway's 502, 503, or 504 with no GraphQL
errors. Any answer starts the count again, whatever it says, and a request you aborted
counts for nothing. At realtime.rediscoverAfterFailures (3 by default, the number the
realtime connection uses for its own failed connections) the client asks the shared origin
where its app is served, and moves there: its requests, and its realtime connection with
them. So a client that only makes requests, with no udp.subscribe, leaves an instance
that has gone.
- The request that failed is not sent again. A mutation that timed out may have been applied. Your next request goes to the new address.
- The client knows its app from its realtime subscription, from an app token it stored
(
portal.exchangeCode,refresh,adoptAppToken,exchangeManagedPlayerAssertion,signInWithMinecraft), or fromappIdin its configuration.client.activeAppId()returns it. A client that knows no app logs one warning and stays where it is: give a client you handed a minted token withsetTokenitsappId. - The client remembers the addresses it could not reach: eight at most, five minutes
each. When the shared origin's answer names one of them, the client moves to the shared
origin itself (
discoveryUrl), which has just answered. Requests then go through the shared origin until something moves the client again. - The shared origin's answer is followed by one rule, the rule for every address a
server names (below). An answer that fails it is logged and not followed. A
realtime.rediscovercallback of your own is your word, and is followed as it is. realtime.rediscoverAfterFailures: 0switches the requests' count off. A client with nodiscoveryUrland norediscovercallback never re-discovers, as before.- The question waits 10 seconds at most (or the client's
timeoutwhen that is shorter). The request that reached the count waits for it before it fails.
You can say what you could not reach, and learn what happened.
const result = await game.rediscoverEndpoint({ unreachable: ['https://ck-api-3.example.com'] });
// { moved, endpoint, onSharedOrigin, nowhereElse }rediscoverEndpoint treats the address in use as one you could not reach. moved says the
client is on another endpoint now, endpoint is the GraphQL endpoint in use, onSharedOrigin
says that endpoint is the shared origin, and nowhereElse says the client asked and had
nowhere to go. It never throws. A bare GraphQLClient gets the same signal from
setUnreachableHandler(afterFailures, handler).
A client is told where to go in four ways: a WRONG_DATACENTER refusal, the binary relay's
request to reconnect elsewhere, the shared origin's answer to a re-discovery (and the move
to the shared origin itself), and the address a token refresh answers. Each move takes the
client's token with it, so the client follows a named address only when all of this holds
(18.42.0):
| The rule | Followed | Not followed |
|---|---|---|
| The address is on the estate the client is on: the same host, or the same site (the last two labels of the name) | ck.example.com to ck-api-2.example.com |
ck.example.com to ck.example.org, or to ck.example.com.other.example |
| When either host is an IP address, the two are the same host | 203.0.113.1 to 203.0.113.1:8443 |
203.0.113.1 to 203.0.113.2, or a name to an IP address |
A client on https or wss stays on https or wss |
https to https or wss; http to http (local development) |
https to http or ws |
- An address that fails the rule is logged and not followed. The client stays where it is.
- A
WRONG_DATACENTERrefusal that fails it comes back to you as it is, with no retry. Through 18.41.0 the client followed any address such a refusal named. - Both addresses of a move are checked: the one for requests and the one for the WebSocket.
- An address your own code names is your word: a
realtime.rediscovercallback, orclient.graphql.setEndpoint.
const response = await client.udp.sendActorUpdateAndWait({
appId: '1',
chunk: { x: '0', y: '0', z: '0' },
uuid: '0123456789abcdef0123456789abcdef',
state: 'AA==', // base64-encoded payload
distance: 8,
decayRate: 1,
});
console.log(response.__typename, response.sequenceNumber);The plain sendActorUpdate, sendVoxelUpdate, sendAudioPacket,
sendTextPacket, and sendClientEvent methods return the GraphQL mutation
result immediately. The AndWait variants allocate a sequenceNumber when
one is missing and wait for either a matching notification or
GenericErrorResponse, timing the wait from when the send was accepted. The
first awaited send of each session (the first connect, a reconnect, or a move to
another instance) is retried once with a fresh sequenceNumber if it is refused
UNAUTHORIZED or, for the actor and voxel updates the server echoes, if it times
out (UDP_SEQUENCE_TIMEOUT), which is how a realtime server older than v0.42.0
answers a session's first message. An actor or voxel update still waiting when
the client reconnects or moves to another instance is resent as soon as the new
session is up, rather than at its timeout, since its echo went to the session it
left; that is its one retry. A send whose sequenceNumber you chose is
not retried, and an audio, text or event send's timeout (its normal success) is
never retried. sendChannelMessage broadcasts an opaque payload on a
channel. sendRangedChannelMessage publishes on a channel too, but only members
with a live actor within maxDistance chunks (straight-line distance between
chunk coordinates) of chunk receive it; they get the same channelMessage
notification.
sendVoxelUpdate takes the app's signed 16-bit positions and type and a state of
at most 1,024 bytes (RangeError otherwise, nothing sent). Buddy v0.37.0 echoes
every accepted voxel edit back to its sender as a voxelUpdate, so a game reading
those sees its own edits; World Stores' ChunkStore applies that echo once. A
paused app's sends are refused with UDP error 33, APP_PAUSED.
With realtime: { binaryTransport: true } the SDK signs each message itself
and, since 17.1, packs the messages sent within realtime.bundleWindowMs
(default 1 ms) into one MESSAGE_BUNDLE datagram — the same framing the
server uses for its notifications, accepted on the uplink by Buddy v0.27.0+. A
lone message goes out unwrapped. Call client.udp.flushSends() at the end of a
frame to put that frame's sends on the wire without waiting for the window;
the ...AndWait variants and disconnect() flush on their own.
client.realtime.binaryRelayStats() reports messages, frames, bundles and
bytes. realtime: { bundleSends: false } restores one datagram per message;
the GraphQL transport is unaffected either way.
// Delivered only to the actor whose UUID matches `targetUuid`; you must know
// that actor's current chunk. Fire-and-forget — the sender gets no echo. The
// target receives a `SingleActorMessageNotification` on its subscription.
await client.udp.sendSingleActorMessage({
appId: '1',
chunk: { x: '7', y: '1', z: '2' }, // the TARGET actor's chunk
targetUuid: '0123456789abcdef0123456789abcdef',
payload: 'aGVsbG8=', // base64; embed sender identity here if you need it
});sendAudioPacket carries whatever bytes it is given, and a game with a voice format of its own
keeps it. The voice helpers are an optional one that both SDKs share (CrowdyCPP's
crowdy/media/voice_frames.hpp, held to the same cases in test/unit/fixtures/voice-frames.json):
a 10-byte header in front of each codec frame, little-endian — the version (1), the codec (0 raw,
1 Opus 48 kHz mono, 2 G.711 µ-law 8 kHz), a u16 seq, a u32 timestamp in codec samples, the
frame's duration in milliseconds and two talk-spurt flags (bit 0 the first packet after silence,
bit 1 the last before it). A reader refuses a packet shorter than the header or of another
version. VoicePacketizer numbers one sender's frames; VoiceJitterBuffer puts each sender's
packets back in order, plays them out 60 ms (targetDelayMs) after the first packet of a talk
spurt arrived, reports a frame that never came as a gap, drops one that arrives after its
playout time, and holds at most 64 frames a sender.
import {
VoiceCodec, VoiceJitterBuffer, VoicePacketizer, decodeBase64, encodeBase64,
} from '@crowdedkingdoms/crowdyjs';
const packetizer = new VoicePacketizer({ codec: VoiceCodec.OPUS, frameMs: 20 });
// Every 20 ms while the player talks (`opusFrame` from a WebCodecs AudioEncoder):
await client.udp.sendAudioPacket({
appId, chunk, uuid: me.uuid,
audioData: encodeBase64(packetizer.packetize(opusFrame, { last: talkKeyReleased })),
});
// ...and packetizer.skip() for every 20 ms of silence that is not sent.
const voices = new VoiceJitterBuffer();
client.udp.subscribe({
audio: (n) => voices.push(n.uuid, decodeBase64(n.audioData), performance.now()),
actorLeft: (n) => voices.forget(n.uuid),
}, appId);
// From the audio clock, at least once a frame:
for (const slot of voices.poll(performance.now())) {
if (slot.gap) conceal(slot.key, slot.frameMs); // the frame never came
else play(slot.key, slot.codec, slot.frame!);
}The SDK ships no codec. A browser encodes and decodes Opus with WebCodecs (AudioEncoder /
AudioDecoder, codec: 'opus', 48 kHz, one channel; check AudioEncoder.isConfigSupported
first) and falls back to G.711 µ-law where it has none; media/voice-frames.ts has the settings.
Where a voice sits in the world (panning, distance attenuation) stays the game's.
sendAudioPacket reaches players near a chunk. sendChannelAudio (Buddy v0.37.0) reaches every
active member of a channel wherever they are: opcode 35 on the binary relay, the
sendChannelAudio mutation otherwise, at most 1,024 payload bytes. The sender needs the channel's
send_voice (channels.create({ ..., membersCanSpeak: true }) gives it to the member role) and the
app's use_voice_chat; without them the server answers UNAUTHORIZED on the subscription. There is
no echo. Members get a channelAudio notification; key the jitter buffer by channel and sender so
one player in two channels is two streams. It arrives on the binary relay and on the GraphQL
transport alike.
const party = new VoicePacketizer({ codec: VoiceCodec.OPUS, frameMs: 20 });
await client.udp.sendChannelAudio({
channelId, uuid: me.uuid,
payload: encodeBase64(party.packetize(opusFrame, { last: talkKeyReleased })),
});
const partyVoices = new VoiceJitterBuffer();
client.udp.subscribe({
channelAudio: (n) =>
partyVoices.push(`${n.channelId}:${n.uuid}`, decodeBase64(n.audioData), performance.now()),
}, appId);
// ...poll(performance.now()) from the audio clock as above.const world = client.world('1');
const actor = world.actor();
await actor.join({ x: '0', y: '0', z: '0' });
await actor.sendState('AA==');
await actor.sendText('hello nearby players');
// Direct message to one other actor (you supply its UUID + current chunk):
await actor.sendToActor(
'0123456789abcdef0123456789abcdef',
'aGVsbG8=', // base64 payload
{ x: '7', y: '1', z: '2' },
);The world helpers are thin wrappers over client.udp.* with the appId
pre-bound — convenient for browser games. Advanced callers can always use
client.udp.* with the generated GraphQL input types directly.
Every voxel a player places or breaks is recorded as an edit, one for each voxel position
that holds one. client.voxels.listByDistance reads the edits back, and client.chunks.get
applies them to the chunk it returns. With SDK 18.42.0 and Application API v2.95.0,
client.voxels also counts an app's recorded edits and removes them. Both need
manage_apps on the app: call them with an app token of an account that holds it, as you
call voxels.rollback.
// How much does the app's edit log hold?
const { edits, chunks } = await game.voxels.count({ appId });
// What would a removal take? A removal is a dry run unless you pass dryRun: false.
const preview = await game.voxels.delete({ appId, lowChunk, highChunk });
// Remove the edits in the box. One call removes for a bounded time, so repeat until complete.
const done = await game.voxels.deleteUntilComplete({ appId, lowChunk, highChunk, dryRun: false });
if (!done.complete) {
// maxCalls was reached first: call again with the same input.
}| Call | Application API | Answer |
|---|---|---|
count(selection) |
voxelUpdateCount |
edits (a decimal string) and chunks |
delete(input) |
deleteVoxelUpdates |
dryRun, edits and chunks (removed by this call, or in a dry run what matches), and complete |
deleteUntilComplete(input, { maxCalls? }) |
deleteVoxelUpdates, called again until complete |
dryRun, the summed edits and chunks, calls, and complete |
- A selection is a box, a time window, or both. The box is
lowChunkandhighChunk, both inclusive, of any size. The window isfromandto, both inclusive, on each edit'screatedAt. An edit carries the time of its last write: a position edited twice has the later time, and a reverted edit has the time of the rollback.countwith only anappIdcounts every edit of the app. - A removal is a dry run unless you pass
dryRun: false. The Application API's default is a dry run, and the SDK sendsdryRunonly when you give it. A dry run removes nothing and answers what the same call withdryRun: falsewould remove. - Removed edits cannot be brought back. A later
voxels.rollbackdoes not restore them. - A removal with no selection is refused. To remove every edit of the app, pass
everything: true.everything: truetogether with a box or a window is refused too. - One call removes for a bounded time, about 15 seconds at the longest. When
completeis false, matching edits are left: call again with the same input.deleteUntilCompletedoes that for up tomaxCallscalls (VOXEL_UPDATES_DELETE_MAX_CALLS, 40, unless you pass your own) and sumseditsas a BigInt. Itschunksis the sum of each call's number, so a chunk that two calls removed from is counted twice. - Where an edit is removed, the chunk reads as it did before the edit: its stored grid
if it has one, otherwise whatever the game generates there. Stored chunk grids are not
touched. The edit history (
voxels.history) keeps every edit and records each removal. - The app's hubs hear a removal as they hear any voxel change, unless one call removed edits from more than 2,048 chunks. A hub that mirrors the world reads it again after a removal that large.
Keeping a region current with since. Pass voxels.listByDistance the newest
createdAt you have read, less a few seconds. An edit's createdAt is the time it was
taken, and it becomes readable a moment later, so a read from exactly the newest time can
miss an edit taken just before it and stored just after. Reading the overlap again returns
edits you already hold.
| What happened | Does a read with since show it? |
|---|---|
| A new edit, or a position edited again | Yes |
An edit reverted by voxels.rollback |
Yes. The reverted edit carries the rollback's time |
A whole-chunk write (chunks.update) that replaced a chunk's earlier edits |
No. The chunk's own time moves: read chunks.byDistance with its since |
Edits removed by voxels.delete |
No. Read the region again after a removal |
A grid is a box of chunks a player can own. Code running in a grid is confined
to it: spatial messages that originate in it, the grid's own channels, and a
grid event bus. Its server side is a ck-exec mod (client.exec.mod*).
const plot = client.grid(appId, gridId);
await plot.mintToken(); // learns the box; a grid-scoped token
await plot.channels.create('plot-chat'); // a grid channel (owner only)
await plot.send.text({ chunk: { x: 4, y: 0, z: 0 }, uuid, text: 'hi', distance: 2 });
plot.send.text({ chunk: { x: 9, y: 0, z: 0 }, uuid, text: 'x' }); // throws GridScopeErrorJS grid programs run the full SDK in a network-less sandbox; the page relays them with a grid token they never see:
// sandbox (iframe / worker)
import { createGridProgramClient } from '@crowdedkingdoms/crowdyjs/grid-program';
const { client, grid } = await createGridProgramClient(port);
// page
import { hostGridProgram } from '@crowdedkingdoms/crowdyjs/grid-program';
await hostGridProgram({ port, scope: client.grid(appId, gridId), graphqlUrl, graphqlWsUrl });startGridMod runs either a mod's CLIENT half (WASM) or a JS grid program
behind one interface, and ExecClientHalves runs a whole grid's CLIENT halves
(see A mod's CLIENT half). createGridHostCalls answers
a CLIENT half's host calls through CrowdyJS confined to the grid. The ones only
the game can answer need its knowledge: local.actorsInChunk for
actors_list*, local.avatarChunk (where an avatar's live actor is) for
avatar_state_get, local.gridPermissionKeys with the visiting player's
userId for grid_permission_check, local.drainPointerClicks for
pointer_clicks, and local.page(fn, args) for the calls the page holds (the
player's input, body and sends, mod-owned actors, the scene and presentation;
18.3.0); without its hook such a call is refused as not offered. The
Game Model, sessions and grid state calls went with the legacy engines in
18.0.0: the broker refuses them.
What a CLIENT half is told and sent is someone else's code talking, so the page
holds it to rules of its own (18.0.2): grid_permission_check answers only for
the player's four code-permission keys (GRID_PERMISSION_CHECK_KEYS) and
refuses any other key instead of answering false, because a game knows no other
key for a grid; voxel_set takes a voxel inside its chunk (0-15) and a type
0-255, or the ranges the game sets with createGridHostCalls({ voxelBounds }) for a world
whose positions and types are other signed 16-bit values (18.7.0); and a half's spatial and
channel sends go out as an actor uuid the page
derives for the grid from the one the half names (clientHalfActorUuid), so a
half can never move the player's avatar or speak as another player. The broker
refuses a call that names its chunk a second way (chunk, chunk_x, …): route
on the fields the broker checks, x/y/z or chunkX/chunkY/chunkZ.
The core client is a thin transport; the World Stores layer
(@crowdedkingdoms/crowdyjs/stores) adds the source-of-truth data structures
every game otherwise hand-writes: actor registries, chunk/voxel caches, error
attribution, message inboxes, host tracking, and typed durable-state wrappers
— all driven by ONE shared udpNotifications subscription and ONE scheduler.
import {
createWorldSession, structCodec, f32, u8, jsonCodec, workerTicker,
} from '@crowdedkingdoms/crowdyjs/stores';
// Describe your replication state ONCE (binary layouts, declaratively):
const poseCodec = structCodec({
x: f32(), y: f32(), z: f32(), yaw: f32(),
flags: u8(), held: u8(),
});
const session = createWorldSession(game, appId, {
ticker: workerTicker(), // keep 5 Hz sends even in backgrounded tabs
self: { codec: poseCodec, initialState: { x: 0, y: 0, z: 0, yaw: 0, flags: 0, held: 0 } },
actors: { codec: poseCodec, staleAfterMs: 12_000, historySize: 2 },
errors: true,
chunks: { voxelStateCodec: jsonCodec<MyVoxelMeta>() },
});
// Your actor: uuid minted + persisted, presence sent at 5 Hz with
// send-on-change dedup; just update the typed state from your game loop.
await session.self.join({ x: '0', y: '0', z: '0' });
session.self.patchState({ x: 12.5, yaw: 1.57 });
console.log(session.self.status, session.self.lastAck?.state);
// Everyone else: typed, self-filtered, staleness-managed — render from it.
// A departure the server announces (ActorLeftNotification, Buddy v0.25.0)
// removes the actor and fires `onLeave` immediately; the 12 s reaper is the
// fallback for a lost datagram. A later update for the same uuid is a rejoin.
for (const actor of session.actors.list()) {
render(actor.uuid, actor.state, actor.samples); // samples → interpolation
}
// Terrain: cached, hydrated, realtime-merged, optimistically editable.
await session.chunks.ensureAround({ x: 0, y: 0, z: 0 }, 3);
await session.chunks.setVoxel({ chunk: { x: 0, y: 0, z: 0 }, x: 1, y: 2, z: 3, voxelType: 7 });
// Server-reported send errors, attributed to what you sent:
session.errors.onError((e) => console.warn(e.errorCode, e.send?.kind));
session.dispose();The available stores are self (your actor + send loop), actors (remote
actor registry with lanes/history/staleness), errors (attributed send
errors), chunks (chunk/voxel cache with realtime merge + worldgen
write-back), channelInbox / actorInbox (message inboxes), events (typed
event router), host (host tracking), and save / avatar (typed durable
state).
A voxel edit that is not a chunk write-back (a hub's or mod's world.set_voxels, updateVoxel,
another player's realtime voxel update) reaches a reload only through hydration: getChunk
returns it in voxelStates, and the bulk load's voxels never hold it. The store hydrates when
it has a voxelStateCodec; without one, set chunks: { hydrateVoxelStates: true }.
chunks is a helper for 16×16×16 chunks with one byte per voxel. Voxel positions and types are
the app's signed 16-bit values, which the platform does not check: an edit the dense grid cannot
hold (a type outside 0-255, a position outside 0-15), whether a realtime update, a hydrated
voxelStates entry or a local setVoxel, is kept whole in the chunk's overlay (keyed by
voxelKey(x, y, z)) instead of being truncated into voxels, and voxelTypeAt / voxelStateAt
return it (18.7.0). A game with other addressing reads the raw voxelUpdate events and
chunks.get's voxelStates.
A chunk write-back the server refuses (a visitor on someone else's plot, a safe zone, a closed
wilderness) is dropped, not retried; one that fails for a reason that can clear is tried five
times. Listen with session.chunks.onWriteBackFailed(...) to undo or flag the edit (18.0.4).
Every store is opt-in twice over: only configured stores are constructed
(and only they exist on the session's TYPE — session.host without
host: ... in the config is a compile error), and the layer lives behind the
./stores subpath with "sideEffects": false, so unimported stores never
reach your bundle. Reads are synchronous snapshots and writes happen on
WebSocket events (not requestAnimationFrame), so render loops read freely
and a backgrounded tab keeps ingesting updates; pass workerTicker() to also
keep timer-driven sends at full rate while hidden. See the
World Stores guide.
client.kit(appId) (18.11.0) is the client half of the game kit: typed clients for the
ck-exec starter hubs, the server half (ckx_sdk::kit and the starter packs, which an
app deploys with kit.topology). An app's code is a tree under its root hub; the kit's
modules are the tree's starter types:
| Module | Hub (starter) | What it does |
|---|---|---|
kit.world |
world (world-tick, the root) |
conditions (time of day, night, weather, liveops modifiers) and nodes (resource nodes) mirrored; harvest; for developers schedule / cancel liveops events |
kit.matchmaking.queue(name) |
matchmaker |
join with a rating, alone or as a party matched whole (the leader names the members; each confirms with leader); accept / decline; place and onMatched with the session key |
kit.sessions.open(key) |
session |
lobby, ready, the host's startGame, act in turn under a time limit; the hub scores and names the winner; state mirrored |
kit.npcs.area(key) / areaAt(x, z) |
npcs (npc-mobs) |
an area's mobs, NPCs and pets mirrored; attack (the hub decides reach, cooldown, damage), talk; pets: adopt, rename, summon, dismiss, release, myPets |
kit.leaderboards.board(name) |
leaderboard |
the top mirrored; top, around, me, season; scores come from the hubs that decided them (submit is for developers and hubs), seasons roll on a schedule (18.12.0) |
kit.tables.table(key) |
deck |
a card table: the table mirrored, the caller's hand as private state; join, start, play, draw, pass in the hub's turn order |
kit.tactics.battle(key) |
tactics |
a grid battle in phases: move, attack, endTurn for the player's units; the hub's units act when every player ended the phase |
kit.encounters.encounter(key) |
director |
waves down a lane on the hub's clock, build towers (the lane must stay open), hit with a cooldown, a boss with phases |
kit.minigames.duel(key) |
minigame |
two-player duels of hidden throws, revealed together; throw, rematch |
kit.instances.run(key) |
instance |
a private run for one party: open (seeded floors), invite, join, enter each room, descend; permadeath and expiry; depth to a leaderboard |
kit.arenas.arena(key) |
arena |
real-time fights: join as a class, move (the hub's warden keeps what the speed allows), cast (cooldown, resource, range; projectiles and areas land on the hub's ticks) |
kit.racing.race(key) / ball(key) |
race, ball (racing) |
races (gates in order, laps, splits, places, the winner's ghost) and ball games (claim, pass, shoot, goals) on reported positions the warden keeps |
kit.territory.map(key) / zone(key) |
territory, zone (territory) |
control points a faction captures by standing on them (the hub reads where players are), and a circle that shrinks and wears down whoever is outside |
kit.player and its views: kit.inventory, kit.wallet, kit.progression, kit.achievements, kit.quests, kit.crafting, kit.loot, kit.production |
player (keyed by the player's id) |
the caller's own hub: stacks and mail, soft currencies, levels and public profiles, achievements, quests with tutorials (step for the counters a client may report), crafting, loot with pity, idle production; private parts read again when the hub says they changed (18.13.0) |
kit.shops.at(key), kit.market.at(key), kit.trades.at(key) |
market |
vendors with stock and restocks (buy, sell), order books (order, cancel, book), trades between two players (open, offer, accept, decline); what a player puts up is held in their own hub, and a call that could not reach it is refused unavailable and sent again |
kit.topology |
— | composes a manifest from exec.starters (the types picked, what they hang under and call), checks the tree, builds and deploys (developers, manage_compute) |
kit.spectate, kit.emotes, kit.shards |
— | a viewer's heartbeat so the world's messages reach it; emotes as client events every kit client reads; shard keys as the hubs compute them |
kit.social |
— | parties, guilds and chat rooms over teams and channels |
const kit = game.kit(appId); // one per app, one shared connection
const q = kit.matchmaking.queue('ranked');
q.onMatched(async (key) => {
const match = kit.sessions.open(key);
match.state.subscribe((s) => render(s)); // mirrored: snapshot, then each change
await match.watch();
await match.join();
await match.ready();
});
await q.join({ rating: 1200 });
q.watch(); // the queue never names who waits; ask
// ...on the player's turn:
await kit.sessions.open(key).act({ points: 2 }); // sent with an action id: played once- One connection (
kit.runtime) carries every module's calls and subscriptions, opened when first needed ({ connect }for affinity or a WebSocket on Node,{ developer: true }for admin endpoints,{ connection }to bring your own). It paces what it sends under the gateway's 120 per 10 s (callBudget), waits out a rate-limited refusal, and sends a call again when it did not run, or, when it carries an action id, after an unknown outcome; the hub answers a resent action once. - Mirrors (
HubState,CollectionMirror) subscribe, then ask the hub for a snapshot, and apply what follows in order; a new instance epoch or a gap in a collection's deltas takes a fresh snapshot, and so does a reconnect. Each is a store:get()andsubscribe(fn), the shape React'suseSyncExternalStoretakes.PrivateStatereads what only its player may see with a call, again whenever the hub says it changed for them. - Refusals are
KitError(aCrowdyExecErrorwith statusAppError) with acodeto branch on:not_your_turn,cooldown,full,forbidden, ... (KIT_CODES). A call with an action id refusedunavailable(a hub it needed did not answer) is sent again (18.13.0). - The economy is not a ledger. Items and soft currency are hub state; a transfer between players is steps each hub answers once. See the Game Kit's economy page before you put anything of real value in it.
- Kit types are the hubs' MessagePack maps as they arrive, field names and all
(
time_of_day,expires_in_ms), the same in CrowdyCPP and CrowdyPy. - Realtime: hubs show server-driven actors through the realtime tier;
kitActorCodec,withKitActors(playerCodec)andkitActorLanes()plug them into World Stores'actorsbeside players, andkitEventCodecs()/parseKitServerEventread server events. The registry (wire.ts, fromckx_sdk::kit::wire) numbers them 77 and 90-101 with camelCase JSON bodies; an app's own start at 1000. The 48-byte engine pose (enginePoseCodec,engineLanes) stays for hubs that show actors with it. runOptimisticActionapplies an action locally, asks a referee (a hub endpoint) and rolls back on a denial; passkit.runtime.call(..., { action: actionId })its id.
The protocol is held to ck-exec's golden record of the starters
(test/unit/fixtures/kit-protocol.json): every module call and topic in it is replayed in
test/unit/game-kit.test.mjs. The blueprints, kit.deploy, the engines and the model-backed
helpers went with the game model in 18.0.0; the hub modules replace them. See the
Game Kit docs and
MIGRATION.md.
ck-exec runs an app's server code as hubs (stateful, one instance per key) and spokes (stateless, replicated) on execution hosts. A player connects to one host and calls any node of the app through it:
// The session token is the app's app-scoped token (client.portal.mintAppToken).
const exec = await client.exec.connect(appId, { nodeType: 'arena', key: 'm1' });
const state = await exec.call('arena', 'm1', 'state'); // MessagePack both ways
const stop = await exec.subscribe('arena', 'm1', 'hp', (push) => {
render(push.value); // decoded payload
});
exec.onReconnect((host) => console.log('moved to', host));-
connectasks the Application API for a host (execConnect) and opens a WebSocket to its gateway. WithnodeTypeandkey, the player lands on the host that runs that instance. On runtimes without a globalWebSocket(Node before 22), pass one:{ WebSocket }from thewspackage. -
The connect token rides in the gateway URL, so
connectdials only a gatewayexecGatewayRefusal(applicationApiUrl, gatewayUrl)passes:wss:when the Application API ishttps:, and on the Application API's estate or the platform's (a loopback Application API may name a loopback gateway, as ck-exec's local cluster does). Any other is refusedUnavailablewithout being dialed (18.1.0). -
A gateway that refuses the connect token answers the upgrade
HTTP 401with its reason. Under Node'swspackageconnectthrowsDeniedwith that reason; a browser cannot read a refused upgrade, so there it isUnavailable.HTTP 429(more than 16 sessions to one app through one gateway) isUnavailablewith its reason underws(18.1.0). -
A refused call throws
CrowdyExecError:statusis the platform's (AppErrorcarries the handler's own message;Busy,Moved,UnavailableandRateLimitedareretryable). The SDK does not retryBusy. A gateway refuses a player's calls over 120 per 10 s (per app and host) asBusywithrateLimitedtrue andretryAfterMsset; wait that long before calling again, since calling sooner is refused again:try { await exec.call('arena', 'm1', 'hit'); } catch (e) { if (e instanceof CrowdyExecError && e.rateLimited) await new Promise((r) => setTimeout(r, e.retryAfterMs ?? 1_000)); else throw e; }
-
When the host goes away, the connection asks for a host again, reconnects and renews every subscription; a call caught by it, or answered
Moved, is tried once more. -
ExecConnection.open(gatewayUrl, token)connects with a connect token you already have (tools and tests), without reconnecting. It dials the URL it is given. -
client.exec.deploy({ appId, root, types })takes each node type's compiled module (wasm: Uint8Array) with its manifest fields, sends each distinct module once, and makes the version active. -
Operating it (
view_compute_diagnostics):logs(appId, { nodeType, key, maxLevel, flow }), where each line'sflowis the call it was written in, sologs(appId, { flow })follows one client call through every hub and host;versions(appId)with each version'smanifestJsonand parsedmanifest(a spawn seed shows asseed_bytes);endpointStats(appId, { nodeType, sinceMinutes }), calls per endpoint by outcome (calls,appErrors,busy,denied,deadlineExceeded,otherErrors) with latency overtimedCalls(default the last 60 minutes, at most 7 days). -
The organization's compute ceiling (18.41.0, Application API v2.88.0):
orgComputeCeiling(orgId)reads what each of the organization's apps may run in one datacenter once the organization is funded. It needsview_compute_diagnosticson the organization.Field Meaning maxInstancesInstances one app may have placed at once maxReservedMbMemory, in MB, one app's instances may reserve at once operatorSet,reason,updatedAtWhether a Crowded Kingdoms operator set the two numbers for this organization, why, and when defaultMaxInstances,defaultMaxReservedMbThe platform's numbers for a funded organization fundedWhether the organization is funded now. While it is false, its apps keep the free tier limits, which status(appId)reports.
Integers above 2^53 decode as number and lose precision unless you pass
{ decode: { useBigInt64: true } }. A call's whole numbers outside 32 bits (a timestamp in
milliseconds, a player id) go out as 64-bit integers (18.11.0; before, as floats, which a
hub's integer fields refuse). The wire format is in the
ck-exec docs.
A mod (a player's code on a grid they own: modBuild, modDeploy) can carry a CLIENT
half (17.14.0): browser WASM from one crowdy-client-sdk crate, which the mod's grid serves
to visitors who consent to it or trust its author. It runs in the visitor's
PlayerCodeBroker, in a worker with no DOM, token or network, and it is the only kind of
player module the broker runs since 18.0.0.
// The mod's owner builds one crowdy-client-sdk crate and attaches it to the mod.
const queued = await client.exec.modClientBuild(appId, { name: 'hud', files }); // kind 'client'
const built = await client.exec.waitForModBuild(appId, queued.buildId);
const half = await client.exec.modClientDeploy(appId, gridId, 'shop', built.buildId);A visitor's page lists what the grid serves (gridClientMods: each CLIENT half's capability
summary and hash, its author's union and hash, and whether the player consented or trusts the
author), asks the player, consents (consentClientMod(appId, modId, capabilityHash), or
trustAuthor(appId, gridId, authorId, authorCapabilityHash) once per author) and fetches the
module (modClientArtifactBytes(appId, modId): its bytes checked against digest, its fuel
budget and tick interval). A stale hash is CONFLICT. The module is served only to a player
holding run_client_code who stands in the grid now, every refusal is NOT_FOUND, and a
player may fetch a mod's 12 times a minute, so cache it by digest. ExecClientHalves does
all of that:
import { ExecClientHalves } from '@crowdedkingdoms/crowdyjs';
const halves = new ExecClientHalves({
exec: client.exec,
appId,
workerUrl, // the platform glue worker, same origin
onHostCall: (call) => hostCalls(call), // e.g. createGridHostCalls({ scope, client })
onPresentation: (p, mod) => hud.set({ source: mod.modId, label: mod.name, payload: p.payload }),
onLog: (line, mod) => devConsole.append(mod.name, line.level, line.message), // text, never HTML
confirm: (prompt) => window.confirm(describe(prompt)), // once per author; ask: 'mod' for each
onStopped: (mod) => hud.remove(mod.modId),
});
halves.enterGrid({ gridId, low, high }); // the grid the player stands in; null to leave
setInterval(() => void halves.refresh().catch(console.warn), 10_000);
// The page calls a running CLIENT half's handle_invoke; the reply is the module's bytes.
const reply = await halves.invoke(modId, new TextEncoder().encode('{"ask":"score"}'));
// The player takes an agreement back: one CLIENT half, or everything by its author here.
await halves.revoke(modId);
await halves.forgetAuthor(authorId);The player can take back what they agreed to (18.0.3): revoke(modId) stops a CLIENT half
and takes back their consent to it (exec.revokeClientModConsent), and when it ran because they
trust its author, that trust too, consenting instead to the author's other running halves so
those keep running; forgetAuthor(authorId) stops all of the author's halves on the grid and
takes back the trust with every consent to them there (exec.revokeAuthorTrust). Either way
what was taken back is not asked about again on the grid until it changes (a new visit asks
again). A game shows both beside each running CLIENT half.
Each refresh stops the CLIENT halves whose mod is gone or whose digest, capability hash or
tick interval changed, asks about the rest, and starts the consented ones in a broker. The
broker allows at most the host calls crowdy-client-sdk makes (EXEC_CLIENT_HOST_CALLS: no Game
Model, sessions or grid_state_*), offers exactly the CLIENT ABI imports
(EXEC_CLIENT_ABI_IMPORTS) and runs a module only with its digest, its fuel budget and
consentedHostCalls, the host calls of the summary the player consented to: a call outside them
is refused, even one whose name the module assembled at run time. A CLIENT half's
crowdy::log lines reach onLog at most 20 a second and 1,000 characters each (then a warn
counts what was dropped); invoke sends at most 256 KiB each way and is refused while the
module is not running. NOT_FOUND holds a CLIENT half back 15 s and RATE_LIMITED 60 s. The
grid's owner is asked about their own CLIENT halves like anyone; answer yes in confirm when
prompt.authorId is the player. See
CLIENT halves.
A fleet session is one realtime session that a game server opens for itself and uses for every player on that server. A player signs in once, when they join the game. When the player moves to another of your servers, that server starts to carry them with one UDP message, and neither server calls the Application API.
A fleet session runs on a server your organization runs. Your organization's org token
opens it, and its fleet token signs for every player the session carries. An org token and a
fleet token never go into a browser page or a game client. A game on a player's device uses
client.udp with that player's own app token.
SDK 18.40.0 carries fleet sessions. They need Application API v2.89.0 or later, realtime
servers v0.50.3, and ck-exec 0.25.0 for the hub connection. All three have been on dev,
test, and prod since November 26, 2026. Fleet sessions stay off for an organization until a
Crowded Kingdoms operator switches them on, and the organization also needs
org-managed players. Until then, the Application API refuses
fleetSessions.open with FORBIDDEN.
The session is FleetSession, from the Node entry point @crowdedkingdoms/crowdyjs/fleet.
It talks to the realtime server over UDP (node:dgram), which a page cannot open, so no
other entry point of the package imports it. Importing it where node:dgram does not exist
throws.
import { createCrowdyClient } from '@crowdedkingdoms/crowdyjs';
import { FleetSession } from '@crowdedkingdoms/crowdyjs/fleet';
// A client for this server, holding the org token (cko_…, scope fleet:session).
// Give it no tokenStore: the org token stays where your server keeps its secrets.
const api = createCrowdyClient({ httpUrl: 'https://ck.dev.crowdedkingdoms.com' });
api.setToken(process.env.CK_ORG_TOKEN);
const fleet = new FleetSession({
session: await api.fleetSessions.open(appId), // one session for each game server
handlers: {
actorUpdate: (n) => world.apply(n), // state arrives once for the session
text: (n, players) => players?.forEach((p) => chat.deliver(p, n)), // only these players
released: (r) => roster.remove(r.playerGameTokenId), // the platform ended a carry
},
});
await fleet.connect();
// A player joined this server. `player` is the app token your server minted for them
// (mintManagedPlayerToken): its token and its gameTokenId.
const carry = await fleet.carry({ token: player.token, gameTokenId: player.gameTokenId });
if (carry.carried) {
await fleet.sendActorUpdate(player.gameTokenId, { chunk, uuid, state });
}
// The player left the game.
await fleet.release(player.gameTokenId);
// In your loop: keep the session, and follow it to another realtime server.
if (fleet.refreshDue()) {
await fleet.applyRefresh(await api.fleetSessions.refresh(fleet.refreshInput()));
}
// The server stops.
await api.fleetSessions.close({ appId: fleet.appId, gameTokenId: fleet.gameTokenId });
fleet.close();client.fleetSessions (also client.admin.fleetSessions) wraps the four Application API
calls. A game server makes them with the org token as the client's bearer. With an org
token, each refuses to run in a browser page or a page's worker: it runs on Node, Bun, Deno,
and server-side workers (the Cloudflare Workers runtime and Vercel's Edge Runtime).
| Call | Application API | Answer |
|---|---|---|
open(appId) |
openFleetSession |
token (64 characters), gameTokenId, appId, expiresAt (24 hours away), maxPlayers, and the realtime server (ip4, ip6, clientPort) |
refresh({ appId, gameTokenId, currentServer? }) |
refreshFleetSession |
The same token and gameTokenId, with expiresAt moved to 24 hours from now |
close({ appId, gameTokenId }) |
closeFleetSession |
true when a session was ended |
list(orgId, { appId? }) |
fleetSessions |
The organization's open sessions (18.42.0, Application API v2.95.0): each one's gameTokenId, appId, orgTokenId, maxPlayers, openedAt, refreshedAt, and expiresAt |
- One org token owns a session.
refreshandclosework with the org token that opened the session. Another org token of the same organization getsNOT_FOUNDfromrefreshandfalsefromclose. An admin of the organization closes any of its sessions: see A killed server leaves its session open. - Revoking an org token ends what it opened: every fleet session and every hub connection.
- A session ends at its
expiresAtwhen it is neither refreshed nor closed: 24 hours after it was opened or last refreshed. - Limits. An organization holds a limited number of fleet sessions at once, and a
session carries a limited number of players.
managedPlayers.settings(orgId)reports the organization's numbers (maxFleetSessionsandmaxFleetPlayers, 18.41.0) and how many sessions it holds now (fleetSessionsOpen, 18.42.0). The answer'smaxPlayersis the session's own number. Open one session for each game server. - The fleet token is a signing key. The Application API does not accept it as a bearer.
FleetSession makes no Application API call. A server that calls the API with its own HTTP
client gives FleetSession the same fields.
A game server that stops cleanly closes its session. A server that is killed leaves its session open, and the session counts toward the organization's sessions until it expires, up to 24 hours later. With SDK 18.42.0 and Application API v2.95.0 you list the open sessions and end the ones that stopped servers left.
// `api` holds the org token that opened the sessions. An admin's client works the same way.
const open = await api.fleetSessions.list(orgId, { appId });
// A game server refreshes its session once 12 of its 24 hours have passed
// (fleet.refreshDue()). A session kept longer ago than that belongs to a server that has gone.
const refreshIntervalMs = 12 * 60 * 60 * 1000;
const marginMs = 60 * 60 * 1000;
for (const session of open) {
const kept = Date.parse(session.refreshedAt);
if (Date.now() - kept > refreshIntervalMs + marginMs) {
await api.fleetSessions.close({ appId: session.appId, gameTokenId: session.gameTokenId });
}
}- Who lists. An org token with scope
fleet:sessionlists its own organization's sessions. Its app list, if it has one, limits what it sees. An admin of the organization lists them with a session that holdsmanage_players. - Who closes. An org token closes the sessions it opened, so a fleet whose servers
share one org token ends a stopped server's session from any server. An admin of the
organization, with a session that holds
manage_players, closes any session of the organization, whichever org token opened it. Another org token still getsfalse. - A listed session carries no token.
orgTokenIdis the id of the org token that opened the session. A session's token is given once, to the server that opened it. refreshedAtis when the session was opened or last refreshed, andexpiresAtis 24 hours after it. The list does not say whether a server is connected to a session now.managedPlayers.settings(orgId)reportsfleetSessionsOpen: the sessions the organization holds now, over all its apps.maxFleetSessionsis the most it may hold, so the difference is how many more it may open.settingsneeds Application API v2.95.0 from 18.42.0 on.- An admin's session runs in a page. With a session as the bearer,
listandcloserun in a browser page. With an org token they refuse to, as every org-token call does.
fleet.carry({ token, gameTokenId }) sends FLEET_CARRY. The message names the player's
gameTokenId and carries a proof that your server holds the player's token: an HMAC keyed
with that token over the session's gameTokenId, the player's gameTokenId, and the time.
The promise resolves with how the carry ended:
status |
Meaning |
|---|---|
carried |
The session carries the player. userId is the player's user id. |
noLiveToken |
The realtime servers know no live token by that id: it expired, the sign-in ended, or it belongs to another app. The session asked twice before it settled on this answer. |
otherOrganization |
The token belongs to another organization's player. |
proofFailed |
The proof or its time failed. A clock more than 30 seconds from the server's fails too. |
sessionFull |
The session carries as many players as it may (maxPlayers). |
timedOut |
No answer came within 5 seconds of the first send. |
refused |
A status this version of the SDK does not know. wireStatus has the byte. |
tableFull |
Nothing was sent: the session's table already holds maxPlayers rows and 32 more, carried players and waiting carries together. Release players who left. |
released, closed |
You called release for the player, or close, while the carry was waiting. |
- An unanswered carry is sent again every 250 ms, each time with a new time and a new
proof (
carryRetryMs,carryTimeoutMs). - A carry answered "no live token" is sent once more, 250 ms later, with a new time and a new proof. The promise settles on the answer to that second send.
- Carries are paced. The session sends at most 60
FLEET_CARRYmessages a second, first sends and retries together (maxCarriesPerSecond). The realtime servers drop a session's carries past 64 a second without an answer. - A crossing is a carry on the next server. Stop sending for the player on this server,
then give the next server the player's token over your own link. Its session carries the
player, and this session's
releasedhandler fires with reason 1. - After you refresh a player's token, call
carry({ token, gameTokenId, replaces })with the new token, the newgameTokenId, and thegameTokenIdthe player was carried under asreplaces. The next section covers what happens to the player's sends meanwhile. fleet.release(gameTokenId)sendsFLEET_RELEASEwhen the player leaves the game. The message has no answer. If it is lost, the carry stays on the platform until another session carries the player, their sign-in ends, or they idle out.
The released handler reports a carry the platform ended, with its reason: 1 another
session carries the player, 2 the player's sign-in ended or their token expired, 5 the
player sent no gameplay input for the app's idle timeout (15 minutes unless the app sets its
own).
The platform sends FLEET_RELEASED once. The message can be lost, and it can arrive up to
about 6 seconds after the carry ended, so released may fire late or never. After a
crossing, UNAUTHORIZED on the previous server's next send for the player is the sign that
the other session carries them. For a few milliseconds after a crossing, and rarely for up
to about 5 seconds, the previous session's sends for the player are still accepted, which
is why your server stops sending before it hands the player off.
A player's token expires. Whoever holds the token refreshes it with refreshAppToken
before then, and the answer has a new token and a new gameTokenId. Carry the player again
with both, and name the id the player is carried under now. If a refresh gets no answer,
send it again with the token you still hold: within a minute the answer is the same new
token (Application API v2.95.0; see
Token refresh during gameplay).
const result = await fleet.carry({
token: refreshed.token,
gameTokenId: refreshed.gameTokenId,
replaces: previousGameTokenId,
});- The player stays carried throughout. The carry made with the old token stands until
the new one takes effect, and the player keeps their actors and their idle clock. No
releasedevent fires. - Every send names the new id from the moment the new
FLEET_CARRYis sent. The session does this for you: a send you make with either id goes out under the old id before that moment and under the new id after it. A send that names the new id and arrives before the carry took effect waits for the carry. - Use the new id once the promise resolves
carried. From then on the old id names nobody: a send with it rejects withFleetNotCarriedError, andfleet.carriesanswers false for it. - A late message about the old id changes nothing. The session ignores a
FLEET_RELEASEDor a carry's answer that names an id it replaced, and counts it (replacedIdFramesinfleet.stats()). - A refused replacement leaves the player carried under the old id until the platform
ends that carry, which the
releasedhandler reports. A replacement with no answer in 5 seconds ends the carry under both ids, and the promise resolvestimedOut.
A carry with a new token and no replaces also ends with the player carried under the
new id, with a gap on the way. The session learns that the two tokens are one player only
from the carry's answer. Until that answer arrives its sends name the old id, and the
platform refuses the ones that arrive after the new carry took effect. Pass replaces.
The sends of client.udp have a FleetSession form that takes the carried player's
gameTokenId first: sendActorUpdate, sendVoxelUpdate, sendClientEvent,
sendTextPacket, sendAudioPacket, sendVideoPacket, sendGenericSpatial,
sendSingleActorMessage, sendChannelMessage, sendChannelAudio,
sendRangedChannelMessage, and setSpeakers. sendHeartbeat keeps one of the player's
actors present. Each send resolves with the sequence number it was sent under.
- The message is the one that player's own session would send. Its tail carries the
player's
gameTokenId, and its HMAC is keyed with the fleet token. - The platform applies the player's own rules to it: their permissions, blocks, age rules, speaker lists, and a budget of 500 messages a second with bursts to 1,000.
- A send for a player the session does not carry rejects with
FleetNotCarriedErrorand puts nothing on the wire. - Under its own
gameTokenIdthe session sends four kinds of message: its capabilities,FLEET_CARRY,FLEET_RELEASE, and its keepalive. The realtime servers answer any otherUNAUTHORIZED.
The session keeps itself alive with a heartbeat every 2 seconds (keepAliveIntervalMs). It
also keeps a carried player's actors present: an actor you sent an update for gets a
heartbeat under the player's id after 2 seconds without a message (actorHeartbeatMs),
until you call fleet.forgetActor(player, uuid) or the carry ends. A heartbeat is not
gameplay input, and neither is voice or video. A carried player who sends no gameplay input
for the app's idle timeout is released with reason 5, and the session stays.
Realtime servers from v0.51.0 accept a keepalive only where the player's actor update would
be accepted. v0.51.0 has been on the dev tier since November 27, 2026; test and production
follow.
Where a carried player has no access, the server answers every keepalive for the player's
actor UNAUTHORIZED, inside the session's signed bundle. The actor is not present there,
other players are not told of it, and the session is sent nothing of the place. The session
stays connected and still carries the player.
From 18.41.0 the session makes one report for the player, the actor, and the place, an
ActorNotPresent (uuid, chunk, sequence, verified, playerGameTokenId):
| When | What you get | |
|---|---|---|
notPresent(report) |
Once, at the first refused keepalive | The report. fleet.notPresent(player, uuid) returns it while it stands |
notPresentEnded(report, 'accepted') |
A keepalive there had no refusal for 3 seconds | The actor is present |
notPresentEnded(report, 'moved') |
The actor's next keepalive or update named another chunk | Nothing is known of the new place yet |
notPresentEnded(report, 'stopped') |
No keepalive left for the actor there for 30 seconds, you called forgetActor, or the session no longer holds the player |
The report is over |
genericErrorstill receives every refusal. Its third argument,keepalive, is true for one that answers a keepalive, so a handler that reads every refusal can tell the repeats.fleet.stats()counts them inkeepalivesRefusedand the reports innotPresentReports.- The session keeps the keepalives at the same rate: one every 2 seconds for each actor, never faster, and it does not stop. Once access is granted, the next keepalive is accepted within about 6 seconds, with no new sign-in.
- Nothing else changes. The session's status, its server, and the carry stay as they were, and the session carries nobody again because of a refused keepalive.
- A report needs a verified refusal whose sequence number only that keepalive used in
the last 3 seconds. The sequence number is one byte shared by everything the session
sends, so a session that sends more than about 85 messages a second makes no report, and
keepalivesRefusedstill counts. - Access that is removed takes effect at the player's next token refresh, at most 30 minutes later, as it does for updates.
- Unchanged: apps where every region is open, paused apps, an idle player's first keepalive after a move or a reconnect, and the session's own keepalive. The server does not count a refused keepalive as gameplay input or as data in.
A player's own client (client.udp, World Stores, the Game Kit) sends no keepalive message.
It keeps an actor present with actor updates, which the realtime servers judge as before,
so v0.51.0 changes nothing for it.
Each handler receives the notification and the players it is for.
- State arrives once for the session, with
playersnull, when at least one carried player may receive it: actor updates and departures, voxel edits, events, app-defined spatial messages, and chunk changes. A carried player is in range of something once one of their actors stands near it: a session whose players have no actor yet is sent no state. - Communications arrive with a list of the carried players who may receive them, at most 32 in one message: spatial voice, text and video, direct messages, channel messages, and channel audio. Deliver each to the listed players and to nobody else. A block, an age rule, a speaker list, or a missing permission takes a player off the list.
- A client's event or an app-defined spatial message arrives with a list when only some of your players in range may receive it, and plain when all of them may.
- Your own players' state is not sent back to you.
fleetOwnState: true(orfleet.setFleetOwnState(true)) asks for it when another of your players is in range. With it off, two things still reach the session that caused them: a voxel edit it sent, and the departure of its own player's actor. - State about a player you carry is stale. Your server is the authority on its own players. Just after a crossing, the session can receive a few updates for the player it now carries that the previous server sent a moment before. Drop state whose actor belongs to a player the session carries.
FleetSession verifies everything it receives with the fleet token before a handler runs,
and no option turns that off. A frame that fails is dropped and counted in fleet.stats()
(hmacFailures, unsigned, malformed). A notification that names another app than the session's is dropped and counted
too (wrongApp), since a session is in one app. The one exception is a refusal of a send,
which the next section covers. The largest datagram a fleet session is sent is 1,242 bytes.
The genericError handler receives a refused send and two more arguments: verified, and
keepalive (true when the refusal answers a keepalive; see
A refused keepalive is reported once). A refusal is
3 bytes: the message type, the sequence number of the send, and a code. It names no player,
so match its sequence number against the numbers your sends resolved with.
verifiedis true for a refusal that arrived inside a bundle the session verified with the fleet token. Realtime servers from v0.50.3 send a fleet session every refusal that way.verifiedis false for a refusal that arrived alone. 3 bytes leave no room for a signature, so anyone who can reach the session's socket could have sent it. Treat one as a hint: stop sending for that player, then carry the player again or check their access through the Application API, and act on that answer. A carry's answer is always verified.- The session changes nothing on a refusal, whatever its code and whether or not it is verified. Your code decides what a refusal means for the player.
TOKEN_EXPIREDis about a carried player's token. A send that lands just before the player's token expires is answeredTOKEN_EXPIRED, andreleasedfollows with reason 2. The fleet token's own expiry reaches thesessionReleasedhandler with reason 2, in a signed message.
UNAUTHORIZED has nine causes, and the refusal does not say which one applies:
| Why the send was refused | What to do |
|---|---|
It names the player's previous gameTokenId after a carry with a refreshed token took effect |
FleetSession names the new id for you. With the codecs alone, name the new id. |
| The session no longer carries the player: you released them, they idled out, their sign-in ended, or another session carries them | Carry the player again if your server should still serve them. |
| The player lacks a permission the message needs: access to the app, voice, video, text, direct messages, or voxel writes | Grant the permission, or stop sending that kind of message for the player. |
| The platform could not read the permissions for that part of the world within 2 seconds, or too many sends were waiting for them | Send again. |
| The actor belongs to another player | Send for an actor only under the player who owns it. |
| The platform could not confirm whose actor it is within 2 seconds | Send again. |
| A communication rule refuses the message: a minor's direct message, or a kind of communication that is switched off | Nothing. The message is not delivered. |
| The player's access to the app was suspended or ended | Stop serving the player. |
The message went under the session's own gameTokenId and is not one of its four kinds |
Send it under a carried player's id. FleetSession never sends one. |
Three other outcomes of a send are not UNAUTHORIZED:
- A player over their message budget gets no answer. The message is dropped.
- A player whose token expired gets
TOKEN_EXPIRED, thenreleasedwith reason 2. - A paused app gets
APP_PAUSED.
fleet.refreshDue() is true once 12 of the session's 24 hours have passed. It is also true
as soon as the realtime server tells the session to connect to another server, releases it,
or says nothing for 45 seconds (the moveOrdered and sessionReleased handlers). Call
refreshFleetSession then, with fleet.refreshInput(), and give the answer to
fleet.applyRefresh.
The realtime server signs both messages, and the session acts on them only after it has
verified them. sessionReleased carries a reason: 0 means the fleet token was revoked (the
session was closed through the Application API, or its organization token was revoked), 2
means the fleet token expired, and 1, 3, and 4 mean the server stopped serving the session
(it heard nothing from the session, it shed load, or it moved the session). Every reason
makes a refresh due.
refreshInput()names the server the session is on, so the session stays there while that server still serves the app. After a move order it names no server, and the answer'sserveris the next one.currentServerholds one address and the port: the server'sip4, or itsip6when it has noip4(18.41.0; naming anip6needs Application API v2.90.0).fleetSessions.refreshsends one address when you pass a session answer's wholeserver.- The same server: the carries stand. The session sends its capabilities at once, because after a refresh the server sends the session nothing until it hears from it.
- Another server, or the same one after it released the session or went quiet: the
session connects, sends its capabilities, and carries every player again with a new time
and proof, paced as above. Until a player's answer arrives, sends for that player reject
with
FleetNotCarriedError. Each answer reaches thecarryResulthandler. - A refresh refused
NOT_FOUNDmeans the session ended. Open a new one and carry your players again. - A session closed through the Application API is told. If
closeFleetSessionends a session while itsFleetSessionis still open, the realtime server sends it a signed release with reason 0 within seconds:sessionReleasedfires,refreshDue()turns true, andrefreshFleetSessionthen answersNOT_FOUND. Open a new session and carry your players again. That one message can be lost. The session also sends its capabilities every 15 seconds and expects a signed acknowledgement of each, so about 45 seconds after the close (silenceTimeoutMs)refreshDue()turns true andmoveOrderedfires in any case.
client.exec.connectAsServer(appId) opens one hub connection for the game server, with the
org token as the client's bearer. Its plain calls are the server's own, and callAs makes a
call for one of your players:
const hubs = await api.exec.connectAsServer(appId);
await hubs.call('lobby', '', 'report', { players: roster.size }); // the server's own call
await hubs.callAs(carry.userId, 'player', playerKey, 'grant', { gold: 10 }); // for a player- A hub sees
Caller::Org, with the player the server named or none. Crowded Kingdoms checks that the connection is your organization's. The player a call names is your organization's word, so a hub treatsCaller::Org { player }as "this organization's server says so". playeris the player's user id (FleetCarryResult.userId), as abigint, a decimal string, or a safe integer.- Limits. A server connection has a budget of 2,000 calls a second, and an organization holds at most 256 server connections to one app on one execution host.
- Hubs built with ckx-sdk before 0.15 answer such a call
Denieduntil they are built again. - On any other connection
callAsis refused locally withDenied, and nothing is sent. - An app can require the player's pass for
callAs. See A call for a player can require the player's pass. - The connection reconnects with a fresh server connect token, as a player's does.
onAccessEndedfires when the org token is revoked or fleet sessions are switched off. On Node before 22, pass{ WebSocket }from thewspackage, as forconnect.
By default the hubs take your server's word for the player a callAs names. That fits your
organization's own managed players. For people who play with their own Crowded Kingdoms
accounts, an app can require proof: a player pass. A pass is a signed statement from
Crowded Kingdoms that this player is signed in to this app. With SDK 18.43.0, Application
API v2.96.0, and hub servers on ck-exec 0.27.0, your server shows the pass on its hub
connection, and the app's hubs then take its calls for that player.
// Every answer that carries an app token carries the player's pass.
const pass = signIn.playerPass; // or: (await playerClient.portal.playerPass()).pass
const shown = await hubs.vouch(signIn.userId, pass);
if (!shown.ok) console.warn(shown.error.passInvalid ? 'the pass was not taken' : shown.error.status);
try {
await hubs.callAs(signIn.userId, 'player', playerKey, 'grant', { gold: 10 });
} catch (err) {
if (err.passRequired) {
// No live pass for this player on this connection: vouch, then call again.
}
}
// The app's developer turns the requirement on, after its servers vouch.
await studio.exec.setCallAsPolicy({ appId, requiresPass: true });| Call | What it does |
|---|---|
AppTokenResponse.playerPass |
The pass for the token's player and app, on every answer that carries an app token. Null when hubs are not set up on the tier |
portal.playerPass() |
{ pass, expiresAt } for the app token the client holds, when your server was given a token without its answer |
hubs.vouch(player, pass) |
Shows the pass on a server connection. Resolves { ok: true }, or { ok: false, error } with the refusal |
exec.callAsPolicy(appId) |
{ appId, requiresPass }: whether the app requires a pass |
exec.setCallAsPolicy({ appId, requiresPass }) |
Sets it. Needs manage_apps on the app, with a person's session |
- The SDK never vouches by itself. Your server calls
vouch. A hub server before ck-exec 0.27.0 ends a session that is sent a message it does not know. Vouch where the hub servers check passes:setCallAsPolicy({ requiresPass: true })succeeds only there, and answersFEATURE_DISABLEDelsewhere. - A pass belongs to the connection. Vouch again for each player after a reconnect
(
hubs.onReconnect), and after each refresh of the player's token, with the pass that refresh answered. A later vouch for a player replaces the earlier one. - A pass expires when its app token does, 30 minutes at most. A
callAsafter that is refused until you vouch with a newer pass. - Two refusals are readable on the error.
err.passRequiredis true for acallAsthe app refused for want of a pass, before any handler ran.error.passInvalidis true for a vouch whose pass was not taken: it expired, or it is for another player, app, or organization. Both areDenied, withPASS_REQUIRED:orPASS_INVALID:at the start of the message. portal.playerPass()takes the player's app token as the bearer. The SDK sends the token the client holds and the Application API refuses another kind: a session token withAPP_TOKEN_REQUIRED(appTokenRequiredOf(err)), an org token withORG_TOKEN_NOT_ALLOWED. An org token is what a pass is proof against, so it cannot ask for one.- The setting takes a person's session. An org token and an app token are refused, so
a server's credential cannot switch the requirement off.
setCallAsPolicyanswersNOT_FOUNDfor an app with no hubs deployed. A change reaches the hubs within about a minute and needs no deploy. - Turn the requirement on last, after your servers vouch. From then on a call for a player without a pass is refused.
- With the requirement off nothing changes. A vouch is taken and
callAsworks with or without one. - A vouch counts as 4 calls of the connection's call budget.
- Keep passes on your servers and out of your logs. A pass signs nobody in and opens no connection: it lets your organization's own server make hub calls for that player in that app.
- Not in this release: a sign-out does not end a pass. A pass stays good until it expires, 30 minutes at most, also after the player signs out or loses access to the app. No new pass is issued once the token is gone.
The fleetSessions calls and exec.serverEndpoint raise CrowdyGraphQLError. Branch on
extensions.code with these readers:
extensions.code |
Meaning | Reader |
|---|---|---|
ORG_TOKEN_REQUIRED |
The bearer is not an org token | orgTokenRequiredOf(err) |
ORG_TOKEN_NOT_ALLOWED |
The request came from a browser (it carried an Origin header) |
err.code |
FLEET_SESSION_LIMIT |
open: the organization holds as many sessions as it may |
fleetSessionLimitOf(err) |
NOT_FOUND |
refresh: the session expired, was closed, or was opened with another org token |
fleetSessionNotFoundOf(err) |
PLATFORM_BUSY |
The platform could not start the call in time. Wait retryAfterMs, then call again |
platformBusyOf(err) |
ORG_LEGAL_ACCEPTANCE_REQUIRED |
An admin has not accepted the current Org-Managed Players Addendum | orgLegalAcceptanceRequiredOf(err) |
FORBIDDEN |
Fleet sessions are not switched on for the organization, or the org token lacks the fleet:session scope. list and close with a session: the user does not hold manage_players in the organization. list: the app is not one of the organization's |
err.code |
SCOPE_MISSING |
The app is not in the org token's app list. list: the org token belongs to another organization |
err.code |
- Never log the answers of
fleetSessions.open,fleetSessions.refresh, orexec.serverEndpoint. The first two contain the fleet token, and the third contains a hub connect token. AFleetSessionshows no token when you log or serialize it. - The hub connect token travels in the WebSocket URL's query string, as a player's does. It lasts one minute, and the connection asks for a new one at each reconnect. Keep that URL out of your logs too.
- A replayed
FLEET_RELEASEDmakes the session report a player released. The frame is signed, so a copy that someone captured verifies when it is sent again. If the player is still on your server, carry them again. - The UDP socket is connected to the realtime server's address, so the operating system drops datagrams from any other address before the session sees them.
A server on another JavaScript runtime can build and read the messages itself, over its
own UDP socket. The root entry point exports the codecs, which use WebCrypto and no I/O: createFleetSignContext,
carriedPlayerContext (the signing context that gives any serialize* function the tail
of a carried player's message), fleetCarryProof, serializeFleetCarry,
serializeFleetRelease, serializeActorHeartbeat, and parseFleetDatagram, which
verifies a datagram and returns its carry results, releases, deliveries, and notifications.
Crowded Kingdoms no longer hosts games: on 2026-10-29 it retired Crowdy Games, with
the shell that framed published games, the Overworld lobby and the content CDN. Build
your game and serve the built files from your own origin, on any static host that can
set response headers. Then, in Studio, open the app's
Settings > Sign-in & redirect URIs: add your sign-in return URL on that origin
(for example https://play.example.com/auth/callback) as a redirect URI, and set the
origin as the app's Launch URL. The redirect URI is what admits the origin to CORS
and to the hosted sign-in return, so portal.signIn works there as in the
Quick start.
Host your game
has the requirements and recipes.
client.hosting, uploadPublishFiles, publishDirectory and manifestForDirectory
(the @crowdedkingdoms/crowdyjs/hosting entry point), and EmbeddedHost
(client.embeddedHost) remain in the package but are deprecated. The hosting API
answers CONTENT_HOSTING_DISABLED on every tier and its reads return null or an empty
list, so a publish step that calls them fails; remove it from your build. With no
shell to frame a game, EmbeddedHost.hello() resolves null and portal.signIn takes
the normal path.
Crowdy Studio is the in-game SERVER/CLIENT Rust authoring surface for player
code: cloud projects with target-scoped files, optimistic-concurrency
autosave, draft/live/stop orchestration, and a Monaco editor backed by a local
Rust language worker. The worker receives source files and the embedded
platform index (the ckx-sdk and crowdy-client-sdk symbols) only — never a
credential and never a server connection. A CLIENT half runs through
PlayerCodeBroker, which keeps tokens on the page, allow-lists host calls
(narrowed to what the player consented to), and locally clamps chunk-targeted
effects to the owned grid before the normal SDK path reaches server
authorization. It takes what the platform served with the module, and ticks it
only when tickIntervalMs is set (omit or 0 is invoke-only):
import { PlayerCodeBroker } from '@crowdedkingdoms/crowdyjs';
const half = await client.exec.modClientArtifactBytes(appId, modId);
const broker = new PlayerCodeBroker({
workerUrl,
grid,
onHostCall,
moduleName: half.name,
artifactHash: half.digest,
fuelPerDispatch: half.fuelPerDispatch,
consentedHostCalls: half.capabilitySummary.hostFunctions,
tickIntervalMs: half.tickIntervalMs, // omit for invoke-only
onLog: (line) => console.log(`[${line.moduleName}] ${line.level}: ${line.message}`),
});
await broker.start(half.bytes);Most games embed the ready-made shell rather than hand-rolling window chrome
around mountCrowdyStudio:
import { createCrowdyStudioEmbed } from '@crowdedkingdoms/crowdyjs/crowdy-studio';
// Self-starting glue worker for CLIENT mods (Vite shown; any bundler that
// packages module workers works):
import workerUrl from '@crowdedkingdoms/crowdyjs/player-glue-worker?worker&url';
const studio = createCrowdyStudioEmbed({
client: game, // CrowdyClient: crowdyStudio, exec, playerWallet, crowdyStudioGitHub
appId,
gameName: 'My Game',
suppressGameplayInput: () => pauseInput(),
onLayoutChange: () => resizeCanvas(),
});
// Per open (for example after the player claims a grid):
studio.toggle({
gridId,
targetPermissions: {
SERVER: { canWrite: true, canRun: true },
CLIENT: { canWrite: false, canRun: false }, // SERVER-only embeds omit workerUrl
},
});The embed renders a resizable right dock on desktop and a focus-trapped
fullscreen modal on narrow screens. For custom chrome, call
mountCrowdyStudio(host, options) directly; for a headless integration, use
new CrowdyStudioController(options). New games should start SERVER-only.
Untrusted HUD payloads always render as text, never HTML.
The SERVER target runs as a ck-exec mod. A new project's SERVER target starts from
the platform's mod starter (client.exec.modStarter(appId), a ckx-sdk crate), Test draft
and Deploy live build it with modBuild and deploy it to the grid as the mod
mod:<server module name>, Invoke calls one of its endpoints (state by default) over an
exec connection, and Logs shows its ctx.log lines.
The CLIENT target is that mod's CLIENT half (17.14.0). A new CLIENT target starts from a
crowdy-client-sdk crate; Test draft and Deploy live build it with modClientBuild, attach
it to the project's mod with modClientDeploy, consent to it as its author (the API serves a
CLIENT half only to players who consented, its author too) and preview the served module in
the HUD layer; the preview's crowdy::log lines show in Logs beside the mod's own. A
CLIENT-only project's CLIENT half rides the mod named for its CLIENT module:
when the player has no mod of that name on the grid, Studio deploys the mod starter's server
half under it first and says so in the build log, and Stop switches that mod off. The
preview loads only while the player stands in the grid with run_client_code, and saving a
CLIENT project needs ck-api v2.25.1 or later. A CLIENT crate still on the legacy
crowdy-compute-sdk is refused with what to change. The embed takes exec from the client;
mountCrowdyStudio and the controller take mods: client.exec. Crowdy Studio runs nothing
on legacy player compute since 18.0.0.
See CLIENT halves, mods and Embed Crowdy Studio in your game.
The agent pane docks beside the editor and runs the
DeepSeek Harness entirely
in the player's browser: the stock harness web UI in a same-origin iframe, the
harness plugin tree in a Web Worker, and a filesystem whose files are the open
Crowdy Studio project (the bound GitHub repository when the project has one).
The model is reached through the tier's metered endpoint
(POST /v1/model/chat/completions) with the player's own app token, so usage
is priced per request at the app's rate card and billed to the player's wallet
by default (or the app's org wallet when its billing admin chose that). The
harness worker holds that token in memory to call the API as the player; it is
sent over the page/worker channel, never written to a seed file, the worker's
virtual filesystem or OPFS, and no tool exposes it to the model. The model has
no shell and no network of its own; what it can do in the game runs through
this SDK on the page, and a live deploy additionally waits for the player to
confirm in the pane.
A game enables the pane with the dsh option and ships the packed harness from
the published @crowdedkingdoms/crowdy-dsh npm package (dist/dsh-web/,
stamped with BUILD.json) under a same-origin path, usually by copying it into
public/dsh/ at build time:
const studio = createCrowdyStudioEmbed({
client: game,
appId,
dsh: {
graphql: game.graphql,
webBase: '/dsh/', // where dist/dsh-web is served
graphqlUrl: `${apiOrigin}/graphql`,
apiOrigin,
getToken: () => game.getToken(),
persistScope: `${appId}/${userId}`, // browser-side session persistence key
studioOrigin: 'https://studio.crowdedkingdoms.com',
},
});
// Per open: what the model may see.
studio.toggle({
gridId,
targetPermissions,
playerHost, // PlayerHostAdapterV1 → game_observe
dshHost: {
captureFrame: () => renderer.captureFrame(), // screenshot tool + auto-capture after draft tests
describeView: () => hud.summary(),
clientLogs: () => modLogs.tail(200),
},
});The pane shows a provider-data notice once per app (recorded with
crowdyStudioSetProviderConsent), a Screenshot button, and today's spend
against the policy ceiling. "Fix with AI" on any problem queues a prompt into
the agent. @crowdedkingdoms/crowdyjs/crowdy-dsh exports the pieces
(CrowdyStudioDshPane, StudioDshBridge, CrowdyStudioDshTransport, the
bridge protocol) for custom chrome; @crowdedkingdoms/crowdyjs/player-host
keeps the PlayerHostAdapterV1 observation contract and its schemas.
The host document must allow the iframe (frame-src 'self') and serve the
harness path with script-src 'self' 'unsafe-eval' 'unsafe-inline' blob:,
connect-src 'self' blob:, worker-src 'self' blob: and
frame-ancestors 'self'; the game page's own policy stays strict. The iframe
is same-origin by design (BroadcastChannel and OPFS are origin-scoped), so
its sandbox="allow-scripts allow-same-origin" does not isolate it from the
page; that CSP is the control. See the
@crowdedkingdoms/crowdy-dsh README on npm.
When the open project is bound to a game generated from the Construct
template, the API reports it as such (crowdyStudioGitHubLayout.kind === 'CONSTRUCT_GAME') and Studio edits the game itself instead of mod crates,
provided the host gives the controller a draft store:
import { GitHubDraftStore, IndexedDbDraftOverlayStorage } from '@crowdedkingdoms/crowdyjs/crowdy-studio';
const storage = new IndexedDbDraftOverlayStorage();
const studio = createCrowdyStudioEmbed({
// ...
draftStore: ({ appId, projectId, githubSha }) =>
new GitHubDraftStore({ transport: game.crowdyStudioGitHub, appId, projectId, baseCommitSha: githubSha, storage }),
});
// A Live code link names the project; open it first.
studio.toggle({ gridId, targetPermissions, projectId });The draft is the game's working copy until the player commits. Everything
reads it: the Files pane (dirty files marked, discard per file), the editor,
the agent (in game mode), and whatever the game hot-reloads from it. Versions
are git blob ids, so an untouched file carries its GitHub blob id. The hosted
store keeps edits in IndexedDB on the game's own origin and reads the bound
branch through crowdyStudioGitHub.tree and getFiles (100 paths a call);
Commit (or the agent's commit_game_files, which the player confirms in
the pane) publishes the draft as ONE commit through commitFiles; an agent's
commit carries exactly the files the player approved, and is refused as stale
if one of them changed while they decided. When the
branch moved meanwhile, the store rebases every edit that does not collide and
lists the rest as conflicts the player settles (keep mine / take theirs). A
game that runs a local dev server can implement DraftStore over its checkout
instead. The page answers the agent's draft requests and its preview_status
(through the host's dshHost.previewStatus), and boots the harness in game
mode, rebooting it when the open project changes editor.
Transport and protocol failures throw structured error classes:
CrowdyHttpError— non-2xx response from a GraphQL endpoint.CrowdyGraphQLError— preserves every GraphQL error includingpathandextensions.code.CrowdyNetworkError— network-level failure (DNS, TLS, connection refused).CrowdyTimeoutError— request orAndWaittimed out.CrowdyRealtimeError— realtime subscription couldn't be established or was dropped.CrowdyProtocolError— server response failed schema validation.
GraphQL errors carry a stable extensions.code (e.g. UNAUTHENTICATED,
SCOPE_MISSING, FORBIDDEN, IDEMPOTENCY_CONFLICT, RATE_LIMITED) plus,
where applicable, extensions.remediation and extensions.requiredPermission.
Branch on error.extensions?.code rather than parsing messages.
Readers for the refusals a player should be told about, each null for any other error:
accessRefusalOf(err) (ACCESS_REVOKED, ACCESS_SUSPENDED with suspendedUntil,
ACCESS_NOT_GRANTED), appPausedOf(err) (APP_PAUSED, with reason) and actorExistsOf(err)
(ACTOR_EXISTS; ownedByCaller: true means a retried create of your own actor). A paused app
still mints tokens: check isAppPaused(token.runtimeGate) (or the bootstrap's runtimeGate)
before entering the world. For org-managed players: assertionRejectedOf(err)
(ASSERTION_REJECTED, with the failed check as reason) and managedPlayerNotAllowedOf(err)
(MANAGED_PLAYER_NOT_ALLOWED: no wallet, or mods the organization has not switched on).
For an organization's game servers: orgTokenRequiredOf(err) (ORG_TOKEN_REQUIRED),
fleetSessionLimitOf(err) (FLEET_SESSION_LIMIT), fleetSessionNotFoundOf(err) (NOT_FOUND
on a fleet session's refresh), and platformBusyOf(err) (PLATFORM_BUSY, with retryAfterMs).
The platform's retryAfterMs runs from 200 ms to 10 seconds. retryWaitMs(retryAfterMs)
(18.41.0) is the wait to make on it: 0 for a hint of 0 or below, and 30 seconds
(MAX_RETRY_AFTER_WAIT_MS) at most. The SDK's own waits on a server's hint go through it.
serverStatus.serverWithLeastClients() asks once: after PLATFORM_BUSY the SDK does not
ask again, so wait retryWaitMs(retryAfterMs) before your next call, and make that call
from one place.
The player gate and player safety (18.24.0): legalAcceptanceRequiredOf(err)
(LEGAL_ACCEPTANCE_REQUIRED, with the missingDocuments), ageRequiredOf(err) (AGE_REQUIRED),
ageRequirementNotMetOf(err) (AGE_REQUIREMENT_NOT_MET; a boolean on purpose, since no refusal
names an age), territoryNotSupportedOf(err) (TERRITORY_NOT_SUPPORTED, with country),
safetyLogRequiredOf(err) (SAFETY_LOG_REQUIRED), safetyModeratorRequiredOf(err)
(SAFETY_MODERATOR_REQUIRED, 18.25.0), parentalConsentUnavailableOf(err)
(PARENTAL_CONSENT_UNAVAILABLE, with reason since 18.25.0), socialLimitReachedOf(err) (SOCIAL_LIMIT_REACHED), and for
Minecraft sign-in minecraftVerificationFailedOf(err) (with reason) and
minecraftVerificationUnavailableOf(err) (retry shortly). Each has its *_CODE constant.
Destructive game-client mutations accept an optional idempotency key. Pass
a stable key (e.g. crypto.randomUUID()) and a network retry replays the
first result instead of applying the side effect twice. Reusing a key with
different arguments throws a CrowdyGraphQLError with
extensions.code === 'IDEMPOTENCY_CONFLICT'. Keys expire server-side after 24h.
const key = crypto.randomUUID();
await client.actors.delete(uuid, key); // first call deletes
await client.actors.delete(uuid, key); // retry → replays the first result
await client.teams.remove(groupId, key); // deleteTeam
await client.teams.leave(groupId, key); // leaveTeam
await client.voxels.rollback({ ...input, idempotencyKey: key }); // input fieldThe key parameter is optional and trailing, so it's safe to omit.
portal.refresh() needs no key. From Application API v2.95.0 a refresh sent again with the
old token within a minute answers the same new token, and the SDK sends a refresh again
itself when no answer came (see
Token refresh during gameplay). It is the one mutation
the SDK sends again. voxels.delete is safe to repeat as well: the same input removes
whatever still matches.
Typed sub-client methods are first-class, but generated operation documents
are also available through a transport escape hatch, client.graphql:
import { VersionInfoDocument } from '@crowdedkingdoms/crowdyjs/generated';
const data = await client.graphql.request(VersionInfoDocument);For any brand-new server field not yet wrapped, client.graphql.request(...)
always works. (client.management was removed in v14 along with the second
endpoint; client.graphql reaches every surface.)
npm run test:e2e drives a real deployed stack, and the suites self-skip when
the environment is not configured, so they are safe to leave in npm test.
CROWDY_HTTP_URL='https://ck.<tier>.crowdedkingdoms.com' \
CROWDY_WS_URL='wss://ck.<tier>.crowdedkingdoms.com/graphql' \
CROWDY_OWNER_EMAIL='owner@example.com' \
CROWDY_TEST_APP_ID='78221653114368' \
npm run test:e2eCROWDY_HTTP_URL is the ENTRY origin, not the gameplay origin. Point it at
the shared multivalue name (ck.<tier>…), the same one a cold client resolves.
The harness then does what the SDK is built to do: sign in and mint against the
entry origin, and build every gameplay client on the applicationApiUrl /
applicationApiWsUrl the mint returns, threading discoveryUrl into realtime so
instance loss is recoverable.
Do not point it at a single datacenter to "make the tests pass". That was the old behaviour and it hid two things. A suite pinned to one datacenter never exercises residency at all, so a placement regression cannot fail it. And a suite that ran gameplay against the shared origin was testing a configuration no client is ever in: the origin resolves to every datacenter's load balancer, so consecutive requests from one client can be answered by different instances, and because the UDP proxy connection is per-instance a subscription opened on one and a mutation sent to the other never meet. That produced failures in tests as simple as self-echo, which has a single client and cannot have a placement problem.
test/e2e/app-residency.test.mjs is the suite that asserts the contract every
other suite now depends on — that discovery.apps() and mintAppToken name the
same datacenter, and that gameplay works against it. On a single-datacenter
environment its cross-datacenter assertions self-skip and say so, rather than
passing quietly.
Two endpoint shapes are both correct and are not interchangeable:
appDiscovery answers with the datacenter's load balancer (ck-<dc>.<zone>),
while mintAppToken under direct connect hands back one instance
(ck-api-<dc>-<n>.<zone>). They agree on the datacenter, not on the host, which
is why the mint also returns discoveryUrl.
test/e2e/open-grid-and-exec-gateway.test.mjs needs no account at all: with
CROWDY_HTTP_URL and CROWDY_E2E_THROWAWAY_OWNER=1 it registers a throwaway org admin (its own
org and app) and a player, opens and closes a grid, and checks the tier's ck-exec gateway. It
leaves the org behind and archives the app, so it runs only when asked to.
test/e2e/game-kit.test.mjs does the same for the Game Kit: the throwaway owner composes the
starter hubs with kit.topology, builds and deploys them, and two players play them (on dev and
test it also needs CROWDY_PROVISIONING_TOKEN, which their staff-only sign-up asks for).
test/e2e/teen-safety.test.mjs runs the teen safety calls (18.24.0, 18.25.0). With
CROWDY_SAFETY_APP_ID (an app whose default tier admits any player) and
CROWDY_PROVISIONING_TOKEN on dev and test, two new players sign up with a birth date and a
country, read me, change their voice and video settings, ask, accept and remove a contact,
block and unblock, and delete their accounts; a sign-up declaring a blocked country is refused
before any account exists. That test registers two accounts, and a tier's sign-ups are limited
and shared, so run it deliberately (--test-name-pattern selects the others). With
CROWDY_OWNER_EMAIL / _PASSWORD (an admin of that app's org) one player also reports the
other and the admin lists and resolves the report; without them no report is filed. With those
and CROWDY_PLAYER_EMAIL / _PASSWORD (an existing player outside that org), existing accounts
read hasSafetyModerator, the player's own input-log sessions and the territory regions, with no
sign-up. With CROWDY_ORG_TOKEN (players:mint and players:manage) and
CROWDY_MANAGED_APP_ID, an organization's server signs a managed player in with ageYears and
country, a blocked country, a blocked region, a missing region and an age under 13 are
refused, and the players are deleted. CROWDY_E2E_UNDER13_SIGNUP=1 also signs up under 13; since
ck-api v2.61.0 that blocks every sign-up from the machine's address and user agent for 24 hours,
so do not set it on a shared builder.
test/e2e/fleet-sessions.test.mjs plays an organization's two game servers against a tier's
realtime servers. It runs only with CROWDY_FLEET_API_URL (the GraphQL endpoint),
CROWDY_FLEET_APP_ID, and CROWDY_FLEET_ORG_TOKEN (scopes players:mint and fleet:session)
all set. It opens two fleet sessions, signs in four managed players
(crowdyjs-fleet-e2e-0 to -3), carries them, sends and receives state and text, moves one
player from one server to the other, refreshes a session, refreshes one player's token and
carries the player again while they send, and closes everything. It also opens a third
session, closes it through the Application API, and waits for that session to see that a
refresh is due.
CROWDY_FLEET_HUB_APP_ID adds the hub server connection, and CROWDY_FLEET_IDLE_SECONDS (the
app's idle timeout) adds a wait for one player's idle release. The suite leaves the four
players, which every run reuses, and their sign-ins, which last 10 minutes. It prints no token.
Its last step fails when the realtime server sent a session anything that is not its own
(another app's state, or an unsigned notification), which the SDK drops and counts.
CrowdyJS is a standalone public package: a clean clone builds with
npm install && npm run build using the artifacts committed to this repo —
no other repositories and no network access required:
schema.gql— the unified API SDL (management and game surfaces).src/generated/graphql.ts— generated TypeScript operation types; it re-exportssrc/generated/graphql-schema.ts, the generated schema types.
Schema refresh is explicit, from the published SDL:
npm run schema:sync:prod
npm run codegen(npm run schema:sync:paths -- --schema <file-or-url> accepts an explicit
source, and npm run schema:sync:local reads ../cks-game-api/schema.gql.) Commit schema.gql, src/generated/graphql.ts and
src/generated/graphql-schema.ts together whenever the public GraphQL surface changes; npm run check:schema
detects drift in CI/release work.
Two more committed fixtures follow the same boundary — the build validates them locally and never reads a sibling checkout; coordinated maintainers refresh them from an explicitly supplied source:
- The browser Rust authoring index:
npm run authoring-index:drift -- --source <exporter-json> [--write], thennpm run authoring-index:generate. - The agent tool-descriptor fixture:
npm run agent-descriptors:drift -- --source <application-api-fixture>; every build re-checks the digests. - The ck-exec client frames,
test/unit/fixtures/exec-client-frames.json: a copy of ck-exec's golden frames, which hold the call-as frame (0x05) and the vouch frame (0x06). - The fleet session's golden vectors, in
test/unit/fleet-wire.test.mjs: the test builds each one withnode:cryptofrom the inputs in its header, which the other SDKs use too.
See MIGRATION.md for breaking changes between SDK majors.
MIT