Backend SDK
The Octo backend keeps your accounts, organizations and apps, and the remote
state of every app. Two TypeScript SDKs call it.
@quadnix/octo-backend-account-service-sdk reaches the account service, which holds accounts,
organizations, members, roles, apps and tokens. @quadnix/octo-backend-state-management-service-sdk
reaches the state management service, which holds each app's states and locks. RemoteStateProvider
and the agent both call the backend through them, and a script of your own can too, such as a CI
step that reports who holds the shop's lock.
Installing
npm install @quadnix/octo-backend-account-service-sdk @quadnix/octo-backend-state-management-service-sdk axios
Install only the one you call. Each SDK sends its requests through axios, which you install beside it.
A client
Each SDK exports createClient, which takes the environment to reach and the axios instance to send
through.
import { createClient as createAccountServiceClient } from '@quadnix/octo-backend-account-service-sdk';
import { createClient as createStateManagementServiceClient } from '@quadnix/octo-backend-state-management-service-sdk';
import axios from 'axios';
const accountService = createAccountServiceClient({
axios: axios.create({ validateStatus: () => true }),
env: 'production',
});
const stateManagementService = createStateManagementServiceClient({
axios: axios.create({ validateStatus: () => true }),
env: 'production',
});
production is the backend at https://octo.quadnix.com. local is a backend served on your own
machine, which only somebody working on the backend runs.
validateStatus: () => true makes every method answer with the response whatever its status, so a
refusal is read from the response rather than caught. Without it axios throws on any status outside
2xx.
The session
Every method acts as a session, except the health checks, login, validateSession,
createBotSessionRequest and claimBotSessionRequest. The session is a personal access token, the
same one RemoteStateProvider takes as sessionId, and it travels in the x-session-id header of
the options every method takes last.
const options = { headers: { 'x-session-id': process.env.STATE_SESSION_ID! } };
const response = await stateManagementService.getAppLocks('shop-organization', 'shop', options);
A method takes its path's identifiers first, in the order the path names them, then its body where
it has one, then its query parameters, then the options. With StatePhase imported from the SDK,
getStates('shop-organization', 'shop', undefined, 10, StatePhase.COMMIT, options) reads the shop's
ten newest sealed states.
A refusal
A response with a status outside 2xx is a refusal, and its body carries a message: one string, or
a list of them when validation refused several fields. Read the refusal from the body before you
read its data, because the data of a refusal is not the shape the method declares.
if (response.status < 200 || response.status > 299) {
const { message } = response.data as unknown as { message?: string | string[] };
throw new Error(Array.isArray(message) ? message.join(', ') : (message ?? `${response.status}`));
}
const [lock] = response.data.locks;
console.log(lock ? `The shop is locked by "${lock.context}".` : 'The shop is not locked.');
A 401 means the session is missing or expired, a 402 that the organization has run out of
credits, and a 403 that the session may not do this in the organization.
Signing in
A program with no token signs in the way the agent signs in: it asks for a session, a person approves it in the web app, and the program claims it.
const { data: request } = await accountService.createBotSessionRequest();
console.log(`Open https://octo.quadnix.com/ui/agent?code=${request.requestCode} and approve the code.`);
// Once the person has approved it.
const claimed = await accountService.claimBotSessionRequest(request.requestCode, { claimSecret: request.claimSecret });
const session = claimed.data.session;
claimBotSessionRequest answers 409 until the code is approved, so call it again once the person
says they approved it. The claim answers with the session, the token it belongs to as botName, and
when it expires as expiresAt. Approving replaces the token's session, so anything else using that
token signs in again.
State files
The state management SDK adds five methods that move a state's bytes as well as calling the service.
These throw a StateFilesError, whose status is the status of the request that failed, instead of
answering with a refusal.
A read answers with the state and a stream of each file, and a file is downloaded only when its stream is read.
import { createWriteStream } from 'node:fs';
import { Writable } from 'node:stream';
const { stateFiles } = await stateManagementService.downloadLatestStateFiles('shop-organization', 'shop', options);
for (const stateFile of stateFiles) {
await stateFile.content.pipeTo(Writable.toWeb(createWriteStream(stateFile.filename)));
}
A write goes through a lock. createAppLock takes it, uploadState writes the whole state, as
often as the run needs, and unlockAppLock seals the state and releases the lock.
import { openAsBlob } from 'node:fs';
const { data: lock } = await stateManagementService.createAppLock(
'shop-organization',
'shop',
{ commitId: 'a1b2c3d', context: 'release script', scope: ['app'] },
options,
);
await stateManagementService.uploadState(
'shop-organization',
'shop',
lock.lockId,
[{ content: await openAsBlob('.octo/models.json'), filename: 'models.json' }],
options,
);
await stateManagementService.unlockAppLock('shop-organization', 'shop', lock.lockId, options);
uploadState names every file the state holds afterwards, so a file left out is removed. A file the
state already holds with the same bytes is not uploaded again. Either every file lands or the state
keeps what it held.
Account service methods
| Method | What it does |
|---|---|
getHealth | Answers whether the service is up. No session. |
login | Starts signing in a person by email, and answers with a session to validate. No session. |
validateSession | Activates a session from login with the code the person was sent. No session. |
getAccount | The account the session belongs to. |
updateAccount | Changes the account's details. |
getAccountSessions | Every session of the account, without their session IDs. |
logout | Ends the session. |
logoutAll | Ends every human session of the account. Its tokens keep theirs. |
createBot | Makes a personal access token that can act in the organizations named, with its session. |
getBots | Every token of the account, and what each can do in each organization. |
removeBot | Removes a token from every organization and ends its session. |
createBotSession | Gives a token a new session. Its old session stops working. |
createBotSessionRequest | Asks for a token's session, which a person approves by its code. No session. |
approveBotSessionRequest | Approves a request with one of the account's tokens, replacing that token's session. |
claimBotSessionRequest | Claims the session an approved request holds, once. No session. |
updateBotOrganization | Replaces what a token may do in one organization. |
removeBotOrganization | Removes a token from one organization. It keeps its access elsewhere. |
createOrganization | Creates an organization, with the session's account as its owner. |
getMemberOrganizations | A page of the organizations the session is a member of or invited to. |
getOrganization | One organization. |
updateOrganization | Changes an organization's details. |
getOrganizationCreditUsages | A page of the credits an organization spent and was given over a period. |
getMembers | A page of an organization's members. |
inviteMember | Invites a person to an organization with a role. |
joinAsMember | Accepts the invitation the session holds. |
declineMemberInvitation | Declines the invitation the session holds. |
updateMemberRole | Moves a member to another role. |
removeMember | Removes a member from an organization. |
removeMemberBot | Removes a member's token from an organization. It keeps its access elsewhere. |
getRoleResources | The resources a role's scope can name. |
getRoles | A page of an organization's roles, without the owner role. |
createRole | Creates a role. |
updateRole | Replaces a role's scope, and with it what every member holding the role may do. |
createOrganizationApp | Creates an app in an organization. |
getOrganizationApps | A page of an organization's apps. |
getOrganizationApp | One app. |
updateOrganizationApp | Changes an app's name. |
State management service methods
| Method | What it does |
|---|---|
getHealth | Answers whether the service is up. No session. |
createAppLock | Takes a lock over members of an app for a commit, and answers with its lockId. |
getAppLocks | The locks an app holds. |
unlockAppLock | Seals the state the lock's run wrote and releases the lock. |
getStates | A page of an app's states, newest first, optionally only those in one phase. |
getState | The state of one commit, without its files. |
getStateByLock | The state a held lock's run is writing. |
getStateFiles | The state of one commit, whatever its phase, with a URL for each file. |
getStateLatestFiles | The newest sealed state, with a URL for each file. An app with nothing sealed answers 404. |
getStateFile | One file of a state, with a URL for its bytes. |
getStateUsage | What an app's states weigh, and what they may come to before a lock is refused. |
createStateUpload | Asks for an upload through a lock, and answers with a URL for each file to send. |
claimStateUpload | Makes an upload the state, once every file it carried is in place. |
downloadLatestStateFiles | The newest sealed state, with a stream of each file. |
downloadStateFiles | The state of one commit, whatever its phase, with a stream of each file. |
downloadStateFile | A stream of one file of a state. |
downloadStateFileRange | Part of one file, read through the URL a read answered with. Calls no endpoint. |
uploadState | Uploads a whole state through a lock, by createStateUpload, the bytes and claimStateUpload. |
A URL a read answers with works for fifteen minutes. A stream checks the file's bytes against the
SHA-256 the service holds, and errors with a StateFilesError where they differ.