@civitai/sdk
The Civitai SDK: one client for the public API, the orchestrator and, inside a
civitai.com page, the host. The same code serves a block app and an app of your
own. New block apps start here. @civitai/app-sdk/blocks remains the contract
underneath (the workflow body types, the manifest types, the host message
shapes) and @civitai/blocks-react the React hook binding over it; both are
still supported and release from this repo as separate codebases.
import { initialize } from '@civitai/sdk';
const app = await initialize();
const picked = await app.host.openResourcePicker({ resourceType: 'Checkpoint' });
if (picked && (await app.requestGrants(['ai:write:budgeted']))) {
const { air } = await app.site.get<{ air: string }>(`model-versions/mini/${picked.versionId}`);
const submitted = await app.orchestration.submitWorkflow({
steps: [
{
$type: 'textToImage',
input: { model: air, prompt: 'A lighthouse at dusk', cfgScale: 7, seed: 1234 },
},
],
});
const workflow = await app.orchestration.waitForWorkflow(submitted.id!);
render(workflow);
}
🔴 If you are a BLOCK, do not copy the app.orchestration call above. That
reaches the orchestrator directly and carries none of the controls the block
path applies — the per-call Buzz budget, the per-viewer and per-app daily caps,
the maturity clamp, and the app-block:<appId> attribution tag. Generate with
app.workflows instead: estimate, submit and wait go through the
host's /api/v1/blocks/workflows/* routes, which apply all of them — see
Multi-step workflows. The substitution type-checks and
passes tests, which is why it is worth saying here: the snippet above is written
for an app that is its own principal, not for a block. BREAKING.md §What a
direct orchestrator call loses has the detail.
An app calls the Civitai API and the orchestrator as the viewer, with a token.
Reading images, creating posts, running a workflow — all of it is an API call.
A block additionally asks its host page to show the host's own UI.
initialize()
| Call |
Where |
Resolves |
initialize() |
A block on civitai.com |
Once the host hands over the viewer, the slot and a token. Rejects with BridgeError unavailable if no host answers within timeoutMs (10s) |
initialize({ token, refresh?, requestGrants? }) |
Anywhere else, typically your server |
At once, with the OAuth access token you hold |
initialize(await createSignIn(...)) |
A web app outside civitai.com |
At once, as the viewer who signed in; see below |
Both give you:
| Member |
What it is |
app.site |
The public REST API at /api/v1: get, post, request |
app.workflows |
Generation for a block, through the host's blocks/workflows/* routes: estimate, submit, get, watch, wait, cancel, list. Needs the block token: an OAuth access token is answered 401, and a block holding one generates through app.orchestration. See Multi-step workflows |
app.orchestration |
The orchestrator itself, for an app holding an OAuth access token: submitWorkflow, estimateWorkflow, getWorkflow, watchWorkflow, waitForWorkflow, cancelWorkflow, queryWorkflows |
app.storage |
Document storage: collection(name) and info() over the collections the manifest declares. Needs the block token. See Document storage. The legacy get/set/delete/list/getQuota were removed in 0.33 |
app.moderation |
report({ collection, key, from? }): report one shared document to civitai.com's moderators. Needs the block token and a signed-in viewer. See Reporting a document |
app.subListings |
The viewer's own App Store items for this app: upsert, withdraw, mine. Needs the block token and apps:store:items:write. See Store sub-listings |
app.requestGrants(scopes) |
Asks for more scopes; resolves false when they cannot be granted |
app.getToken() |
For a call this client does not make |
The AppClient interface in src/app/index.ts (and the published types) is the
authority for this list.
A block's app also has host, viewer, context, settings, theme and
onChange(listener). Outside a block they do not exist, and the types say so.
context and theme are LIVE, not mount-time snapshots: the host pushes
THEME_CHANGE when the viewer toggles dark mode and ROUTE_CHANGED when a page
block's sub-path moves, and both are folded into the same snapshot — so
app.context.subPath tracks app.host.navigate(path) (and the viewer's own back
button) and onChange tells you when. Read them on each render rather than
copying them once; there is deliberately no onRouteChange, because one value
observed two ways is two values that can disagree.
A block opts in by declaring auth: "oauth" in its block.manifest.json. The
host then hands it a real OAuth access token that /api/v1, the orchestrator
and the MCP accept, and consent — including requestGrants — goes through the
host's consent dialog. The manifest must also declare user:read:self, which
every OAuth token carries: on civitai.com the host never mints one without it
and hands back the block token. The dev tunnel mints one regardless, so a
missing user:read:self only shows up after approval. And auth: "oauth" cannot be declared alongside any
apps:storage:* scope: such a manifest is refused at submit.
When the token is the block-scoped one
initialize() starts either way. A block-scoped token for a signed-in viewer is
not an error in itself: the host's OAuth mint is flag-gated, so an opted-in
block can legitimately receive the block token, and that token serves the
/api/v1/blocks/* routes it was minted for, GET /api/v1/models/{id}, and
app.storage — which an OAuth token cannot reach at all.
What it does not reach is the rest of /api/v1, the orchestrator or the MCP. So
the refusal sits at the surface, not at startup:
| You call |
Holding a block token, signed in |
app.storage.* |
Works (app.storage.collection(name), app.storage.info()). This is the token app storage requires |
app.subListings.* |
Works for a signed-in viewer when the token carries apps:store:items:write — never in a dev-token, dev-tunnel or review session |
app.site on blocks/… |
Works. These are the routes the token was minted for |
app.site.get('me') and the rest of /api/v1 |
The API's own 401/403, with auth: "oauth" named in the message. status and body are untouched, so a caller can still branch on them |
app.workflows.* |
Works. Generation for a block goes here, with the ai:write:budgeted scope |
app.orchestration.* |
Rejects before the request with a CivitaiError naming auth: "oauth" — the orchestrator accepts no block token on any route, so there is nothing to learn from making the call |
app.requestGrants(...) |
Works. Goes to the host's consent dialog, so a consent_required fallback can still prompt |
Anonymous viewers are untouched: no OAuth token is minted for one whatever the
manifest says, so the manifest is not their fix — host.requestSignIn() is. A
host that predates the kind field sends none, and behaves as it always did.
⚠ Two limits on that middle row, and neither is a bug to be tuned away.
The SDK does not know which /api/v1 routes accept the token, so its
message does not say. The route is a string this client never interprets, and
which routes are dual-auth is the server's to change without a release here —
so the message names blocks/* (the token's own mint namespace) and states
plainly that the rest is not known from here, leaving the advice conditional:
if this path needs an OAuth token, declare it. GET /api/v1/models/{id} is
in fact accepted — it is the one dual-auth route today — so a refusal there
gets the same conditional annotation; BREAKING.md records the route map as it
stood when this version was published, and the models:read:self binding that
route applies.
"Does not reach" is not always "refuses." A public route such as
/api/v1/images ignores an unusable token and answers anonymously instead
of erroring. Nothing at the client seam tells that apart from a successful
authenticated read, so prefer the blocks/* twin.
Signing in outside civitai.com
A browser app signs the viewer in with Civitai itself: PKCE against
auth.civitai.com, no server and no client secret. Register the app as a
public OAuth client with its origins and redirect URL.
import { createSignIn, initialize } from '@civitai/sdk';
const auth = await createSignIn({ clientId, scopes: ['user:read:self', 'ai:write:budgeted'] });
if (!auth.signedIn) {
button.onclick = () => auth.signIn();
if (auth.returning) auth.signIn();
} else {
const app = await initialize(auth);
}
createSignIn finishes the return from Civitai when the page has just come
back from it, and takes code and state out of the address bar. Tokens live
in memory only and refresh themselves; storage holds only the sign-in in flight
and a flag that the viewer signed in before (returning). Signing in again is
a quick round trip, since Civitai remembers the consent. requestGrants goes
back to Civitai for anything not yet granted.
Without leaving the page
A page that must not be navigated away from, such as one with a chat or an
editor embedded in it, signs in in a popup instead:
import { createSignIn, initialize } from '@civitai/sdk';
const auth = await createSignIn({ clientId, scopes: ['ai:write:budgeted'] });
button.onclick = async () => {
await auth.signInWithPopup(); // from the click itself: browsers only open a popup there
const app = await initialize(auth);
};
Civitai returns the popup to redirectUri, the same page by default. That page
calls createSignIn() as on any visit; in the popup it hands the result back to
the page that opened it and closes. The result travels over a same-origin
BroadcastChannel, not window.opener, because signing in through Google cuts
the opener. A blocked popup rejects with SignInError code: 'popup-blocked';
pass a signal to give up, which rejects with code: 'canceled'.
requestGrants still leaves the page.
Only scopes with an OAuth equivalent can be asked for: user:read:self,
models:read:self, ai:write:budgeted, buzz:read:self, posts:write:self
and social:tip:self. The storage and collection scopes belong to blocks.
/api/v1 and the orchestrator both accept these tokens from any origin.
The API
Routes are addressed by path, so a route /api/v1 gains needs no release here:
const images = await app.site.get('images', { query: { limit: 20, username: 'civitai' } });
A 401 is retried once with a fresh token — except one whose body's code is
sign_in_required, which is about the viewer, not the token. Any failure the server answered is an
ApiError carrying status, the parsed body, and the server's own message —
while a request the browser never delivered (CORS, DNS, offline) surfaces as a
fetch TypeError with no status, so test error instanceof ApiError before
reading one.
Document storage
An app declares its collections in its manifest, and app.storage.collection(name)
reads and writes their JSON documents. private collections hold one key space per
viewer; shared ones one key space every viewer reads, written under the policy the
collection declares (own: viewers create, only the author edits or deletes). A vote,
a like or any per-viewer entry is the viewer's own document in a
viewer-keyed collection, counted by listing.
"scopes": ["apps:storage", "apps:storage:publish"],
"storage": { "collections": {
"prefs": { "visibility": "private" },
"requests": { "visibility": "shared", "write": "own",
"indexes": { "status": "string" }, "showAuthor": true },
"votes": { "visibility": "shared", "write": "own", "keyedBy": "parent+viewer" }
}}