Skip to main content

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.

backend.ts
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.

backend.ts
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.

backend.ts
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.

sign-in.ts
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.

read-state.ts
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.

write-state.ts
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​

MethodWhat it does
getHealthAnswers whether the service is up. No session.
loginStarts signing in a person by email, and answers with a session to validate. No session.
validateSessionActivates a session from login with the code the person was sent. No session.
getAccountThe account the session belongs to.
updateAccountChanges the account's details.
getAccountSessionsEvery session of the account, without their session IDs.
logoutEnds the session.
logoutAllEnds every human session of the account. Its tokens keep theirs.
createBotMakes a personal access token that can act in the organizations named, with its session.
getBotsEvery token of the account, and what each can do in each organization.
removeBotRemoves a token from every organization and ends its session.
createBotSessionGives a token a new session. Its old session stops working.
createBotSessionRequestAsks for a token's session, which a person approves by its code. No session.
approveBotSessionRequestApproves a request with one of the account's tokens, replacing that token's session.
claimBotSessionRequestClaims the session an approved request holds, once. No session.
updateBotOrganizationReplaces what a token may do in one organization.
removeBotOrganizationRemoves a token from one organization. It keeps its access elsewhere.
createOrganizationCreates an organization, with the session's account as its owner.
getMemberOrganizationsA page of the organizations the session is a member of or invited to.
getOrganizationOne organization.
updateOrganizationChanges an organization's details.
getOrganizationCreditUsagesA page of the credits an organization spent and was given over a period.
getMembersA page of an organization's members.
inviteMemberInvites a person to an organization with a role.
joinAsMemberAccepts the invitation the session holds.
declineMemberInvitationDeclines the invitation the session holds.
updateMemberRoleMoves a member to another role.
removeMemberRemoves a member from an organization.
removeMemberBotRemoves a member's token from an organization. It keeps its access elsewhere.
getRoleResourcesThe resources a role's scope can name.
getRolesA page of an organization's roles, without the owner role.
createRoleCreates a role.
updateRoleReplaces a role's scope, and with it what every member holding the role may do.
createOrganizationAppCreates an app in an organization.
getOrganizationAppsA page of an organization's apps.
getOrganizationAppOne app.
updateOrganizationAppChanges an app's name.

State management service methods​

MethodWhat it does
getHealthAnswers whether the service is up. No session.
createAppLockTakes a lock over members of an app for a commit, and answers with its lockId.
getAppLocksThe locks an app holds.
unlockAppLockSeals the state the lock's run wrote and releases the lock.
getStatesA page of an app's states, newest first, optionally only those in one phase.
getStateThe state of one commit, without its files.
getStateByLockThe state a held lock's run is writing.
getStateFilesThe state of one commit, whatever its phase, with a URL for each file.
getStateLatestFilesThe newest sealed state, with a URL for each file. An app with nothing sealed answers 404.
getStateFileOne file of a state, with a URL for its bytes.
getStateUsageWhat an app's states weigh, and what they may come to before a lock is refused.
createStateUploadAsks for an upload through a lock, and answers with a URL for each file to send.
claimStateUploadMakes an upload the state, once every file it carried is in place.
downloadLatestStateFilesThe newest sealed state, with a stream of each file.
downloadStateFilesThe state of one commit, whatever its phase, with a stream of each file.
downloadStateFileA stream of one file of a state.
downloadStateFileRangePart of one file, read through the URL a read answered with. Calls no endpoint.
uploadStateUploads 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.