@bitclub.ai/opendesk-server-sdk
v0.0.4
Published
OpenDesk Server Node.js SDK - JavaScript client for OpenDesk API
Readme
@bitclub.ai/opendesk-server-sdk
OpenDesk Server Node.js SDK - JavaScript/TypeScript client for OpenDesk API.
Features
- Full API Coverage - 90+ endpoints across 9 modules (auth / namespaces / skills / review / labels / teams / admin / users / relay)
- Type Safe - Written in TypeScript with full type definitions
- JWT Auth - Login sets the JWT session token (auto-applied to every request)
- Timeout & Retry - Configurable request timeout, idempotent-request retry with exponential backoff
- Cancellation -
AbortSignalpassthrough for every request - Interceptors -
onRequest/onResponsehooks, customfetchinjection - Error Handling - Typed error classes; parses both FastAPI
{detail}and OpenAI-style{"error":{message,code}}bodies - Pagination - Built-in async generators for automatic page iteration
- Zero Dependencies - Uses native fetch API (Node.js >= 18) and works in browsers
- Download - Files as
Blob(browser and Node.js >= 18) or rawArrayBuffer
Installation
npm install @bitclub.ai/opendesk-server-sdkQuick Start
import { OpenDeskClient } from '@bitclub.ai/opendesk-server-sdk';
const client = new OpenDeskClient({
baseUrl: 'http://127.0.0.1:8000/api/v1',
});
// Discover the login methods the server allows
// (production defaults to third-party login only)
const methods = await client.auth.getAuthMethods();
// Third-party login (OpenDesk-direct): redirect the browser, then exchange the
// callback `code` + `state`. The returned token is applied automatically.
const { login_url } = await client.auth.getSocialLoginUrl(methods.providers[0].name);
window.location.href = login_url;
// ...on the callback page:
// await client.auth.socialCallback(code, state);
// Password login is only available when methods.password_login is true:
// await client.auth.login({ username: 'admin', password: 'admin' });
// Get current user
const me = await client.auth.getMe();
console.log('Hello,', me.username);
// List namespaces
const namespaces = await client.namespaces.list();
console.log('Namespaces:', namespaces.items);Authentication
Third-party Login (OpenDesk-direct)
// Ask the server which login methods are available
const methods = await client.auth.getAuthMethods();
// -> { password_login: boolean, registration: boolean, providers: [{ name, display_name }] }
// Render one button per provider and redirect straight to the IdP
const providers = await client.auth.getSocialProviders();
const { login_url } = await client.auth.getSocialLoginUrl(providers.items[0].name);
window.location.href = login_url;
// On the callback page, exchange code + state; the token is applied automatically
await client.auth.socialCallback(code, state);Casdoor is used only as the internal user/RBAC store. The legacy browser flow
(getCasdoorLoginUrl() / casdoorCallback()) is deprecated in favor of the
OpenDesk-direct social flow above.
Desktop / Native App Login
Apps that can open a browser but cannot receive a redirect (Windows GUI, CLI)
use the desktop polling flow. startDesktopLogin() wraps it end-to-end: it
fetches the URL, hands it to your openUrl, polls until the browser completes
and sets the token automatically.
import { shell } from 'electron'; // any platform opener
const token = await client.auth.startDesktopLogin({
provider: 'gitcode',
openUrl: (url) => shell.openExternal(url),
onPending: ({ elapsedSeconds, expiresAt }) => {
console.log(`Waiting for authorization… ${elapsedSeconds}s`, expiresAt);
},
// intervalSeconds: 5, // fallback when the server omits retry_after
// timeoutSeconds: 600, // signed-state TTL
// signal: controller.signal, // cancel when the user gives up
});
// token: { access_token, token_type, mode: 'desktop' }, already set on the clientOn failure it rejects with ServerError (provider denied), OpenDeskError(408)
(timeout) or AbortError (cancelled). The lower-level primitives
getSocialLoginUrl(provider, 'desktop') and getSocialSession(state) remain
available if you prefer to drive polling yourself.
Session Management
const client = new OpenDeskClient({ baseUrl: 'http://127.0.0.1:8000/api/v1' });
// Refresh returns a new token WITHOUT auto-applying it:
const token = await client.auth.refresh();
client.setToken(token.access_token); // rotate manually
// Logout - revokes the current JWT
await client.auth.logout();Password Login (may be disabled)
// Password login is disabled by default in production.
// When methods.password_login is false, POST /auth/login, /auth/register and
// /auth/local/change-password all return 403 - hide those entry points.
await client.auth.login({ username: 'your-user', password: 'your-pass' });
await client.auth.getMe(); // Authorization header sent automaticallyAccount Management
await client.auth.register({ username, email, password }); // only when methods.registration
await client.auth.updateMe({ display_name: 'New Name' }); // update profile
await client.auth.updateAvatar(formData); // upload avatar (<= 2MB)
const accounts = await client.auth.listOAuthAccounts(); // bound OAuth accounts
await client.auth.unlinkOAuthAccount('gitcode'); // unbind
await client.auth.changePassword({ old_password, new_password });API Modules
Namespaces (Teams)
// Create a namespace
const ns = await client.namespaces.create({
slug: 'my-team',
name: 'My Team',
is_public: false,
});
// Members
await client.namespaces.addMember('my-team', { user_id: 42, role: 'ADMIN' });
const members = await client.namespaces.listMembers('my-team');
// Invitations
const inv = await client.namespaces.createInvitation('my-team', { role: 'MEMBER', expires_in_days: 7 });
const invitations = await client.namespaces.listInvitations('my-team');
await client.namespaces.revokeInvitation('my-team', inv.id);
await client.namespaces.acceptInvitation(inv.token); // join as memberSkills
// Search skills
const results = await client.skills.search({ q: 'ai', page_size: 20 });
// Publish a skill (two-step: upload then publish)
const upload = await client.skills.upload(formData); // FormData with .zip file
const published = await client.skills.publish({
namespace: 'my-team',
slug: 'my-skill',
name: 'My Skill',
version: '1.0.0',
upload_token: upload.upload_token,
});
// Ownership transfer / copy
await client.skills.transfer('my-team', 'my-skill', { target_namespace: 'other', target_user_id: 42 });
await client.skills.copy('my-team', 'my-skill', { target_namespace: 'other' });
// Download a skill
const blob = await client.skills.download('my-team', 'my-skill', '1.0.0');Review (Governance)
// List pending reviews / my todos
const pending = await client.review.pending({ namespace: 'my-team' });
const todos = await client.review.myTodos();
// Approve / reject / promote
await client.review.approve('publish-id', { reason: 'Looks good!' });
await client.review.reject('publish-id', { reason: 'Needs fixes' });
await client.review.promoteGlobal('publish-id', { reason: 'Excellent' });
// Skill change requests
const requests = await client.review.changeRequests({ status: 'PENDING' });
await client.review.approveChangeRequest('request-id');
// Super admin: audit log & promotion candidates
await client.review.auditLog({ action: 'APPROVE' });
await client.review.promotionCandidates();Labels
const labels = await client.labels.list(); // all labels
await client.labels.create({ name: 'AI', category: 'tech' });Teams (Join Requests + Notifications)
await client.teams.applyJoin('my-namespace'); // apply to join
const requests = await client.teams.listJoinRequests('my-namespace');
await client.teams.approveJoin('my-namespace', 'request-id');
await client.teams.rejectJoin('my-namespace', 'request-id');
const notifs = await client.teams.listNotifications();
await client.teams.markRead('notification-id');
await client.teams.markAllRead();Admin (Super Admin Only)
// Operation logs
const logs = await client.admin.listLogs({ source: 'opendesk' });
const csvBlob = await client.admin.exportLogs({ action: 'approve' });
// Namespace quota
await client.admin.updateNamespaceQuota('my-team', { max_members: 50, max_skills: 100 });
// RBAC
const permissions = await client.admin.listPermissions();
const roles = await client.admin.listRoles();
await client.admin.createRole('admin', 'my-team'); // query params
await client.admin.deleteRole('admin');
await client.admin.listUserRoles(42); // by user id
await client.admin.assignRole({ username: 'alice', role: 'owner', namespace_slug: 'my-team' });
await client.admin.removeRole('alice', 'owner', 'my-team');
// Skill import (skillhub.cn)
const preview = await client.admin.previewImportSkills({ limit: 10 });
await client.admin.importSkills(preview.items);Users
const profile = await client.users.getProfile('username');
const followers = await client.users.getFollowers('username'); // { items: [...] }, non-paginated
const following = await client.users.getFollowing('username');
await client.users.follow('username');
await client.users.unfollow('username');
const dataBlob = await client.users.exportMyData(); // GDPR export (ZIP)
await client.users.deleteAccount(true);Relay (模型接入)
The relay is an OpenAI-compatible gateway backed by LiteLLM. Use it with the official OpenAI SDK - just swap the baseURL. First-party apps use the login JWT; third-party tools should use the per-user virtual key (sk-...) from getCredential() / createCredential() / rotateCredential(). The module covers channels (LiteLLM model deployments), credits, usage and credentials.
// Admin side (super_admin)
const { channels } = await client.relay.listChannels();
await client.relay.createChannel({
name: 'deepseek-chat', // exposed model name (no provider prefix)
model: 'deepseek-chat', // upstream model (defaults to name)
base_url: 'https://api.deepseek.com/v1',
api_key: 'sk-...',
ratio: 1, // billing multiplier (actual price = price x ratio)
input_cost_per_token: 1, // CNY per 1M tokens (see note below)
output_cost_per_token: 2,
});
await client.relay.testChannel(channelId);
await client.relay.fetchUpstreamModels({ base_url: 'https://api.deepseek.com/v1', api_key: 'sk-...' });
// Credits management (credit_enabled)
const credits = await client.relay.listCredits();
await client.relay.adjustCredit(userId, { amount: 10, reason: 'welcome', valid_months: 12 }); // delta
await client.relay.adjustCredit(userId, { amount: 0, mode: 'set' }); // absolute
// Credit policy (monthly gift / top-up validity / reset day)
await client.relay.updateCreditPolicy({ monthly_quota_points: 100, reset_day: 1 });
const usage = await client.relay.getUsage({ status: 'ok' });
const stats = await client.relay.getStats({ group_by: 'model' });
const trend = await client.relay.getTrend({ start: '2026-01-01' });
// User side
const myCredits = await client.relay.getCredits();
const lots = await client.relay.getMyCreditLots(); // per-lot expiry + balance
const myUsage = await client.relay.getMyUsage();
const { credential } = await client.relay.getCredential(); // sk-xxx, copyableCost fields keep the
*_per_tokennames for SDK compatibility, but their value is CNY per 1M tokens (the backend converts to LiteLLM per-token).
Calling the relay with the official OpenAI SDK
import OpenAI from 'openai';
// 1. Get the relay base URL (or hardcode the server's relay URL)
const info = await client.relay.getInfo(); // { base_url, models }
// 2a. First-party: use the login JWT
const relay = new OpenAI({
baseURL: info.base_url, // e.g. https://relay.example.com/v1
apiKey: client.token, // the OpenDesk JWT
});
// 2b. Third-party: use a per-user virtual key (scoped to the relay only)
const { credential } = await client.relay.createCredential();
const relay3p = new OpenAI({ baseURL: info.base_url, apiKey: credential });
const chat = await relay.chat.completions.create({
model: info.models[0],
messages: [{ role: 'user', content: 'Hello' }],
});
// Streaming works as usual:
const stream = await relay.chat.completions.create({
model: info.models[0],
messages: [{ role: 'user', content: 'Hi' }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}Client Options
const client = new OpenDeskClient({
baseUrl: 'https://your-server.com/api/v1', // API base URL
token: '<jwt>', // optional: pre-set JWT session token
headers: { 'X-Custom-Header': 'value' }, // optional: sent with every request
timeoutMs: 30_000, // default 30000 - request timeout
retries: 0, // default 0 - retries for idempotent requests (GET/DELETE), exponential backoff
retryDelayMs: 500, // default 500 - base backoff delay (multiplied by 2^n)
fetch: customFetch, // optional: inject a fetch implementation
onRequest(method, path, init) {}, // optional: per-attempt request hook
onResponse(method, path, response) {}, // optional: response hook
});Timeout, Retry & Cancellation
// A timeout raises OpenDeskError with status 408.
// Retries apply only to idempotent methods (GET/DELETE) and never to
// user-cancelled requests; backoff is retryDelayMs * 2^n.
// Cancel a long-running request with AbortSignal:
const controller = new AbortController();
const data = await client.request('GET', '/skills/search', undefined, {
params: { q: 'ai' },
signal: controller.signal,
});
controller.abort(); // aborts in-flight requestsDownloading Binary Data
// Default: Blob (browser) / Buffer (Node)
const blob = await client.download('/users/me/export');
// Raw bytes:
const buf: ArrayBuffer = await client.download('/files/data.bin', undefined, 'arraybuffer');Low-level requests
// Raw request with per-call overrides
const result = await client.request('POST', '/custom/endpoint', { payload: 1 }, {
params: { page: 1 },
headers: { 'X-Extra': 'yes' },
responseType: 'json', // 'json' | 'blob' | 'arraybuffer'
signal,
});
// Convenience methods: get / post / put / patch / delete / upload
await client.upload('/skills/upload', formData);Pagination
// Method 1: Manual
const page1 = await client.skills.catalog({ page: 1, page_size: 20 });
// Method 2: Async generator (memory-efficient)
for await (const items of client.skills.catalogPaginator({}, 10)) {
console.log('Batch:', items.length);
}
// Method 3: Fetch all
const all = await client.skills.catalogAll({}, 100);Error Handling
Errors are typed by status code, and carry status, detail and an optional OpenAI-style code.
import {
OpenDeskClient,
AuthenticationError, // 401
PermissionDeniedError, // 403
NotFoundError, // 404
ValidationError, // 422
QuotaExceededError, // 422 (quota message)
ServerError, // >= 500
} from '@bitclub.ai/opendesk-server-sdk';
try {
await client.auth.login({ username: 'wrong', password: 'wrong' });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Login failed:', error.detail);
} else if (error instanceof NotFoundError) {
console.error('Not found:', error.detail);
} else if (error instanceof OpenDeskError) {
console.error(`API error [${error.status}] code=${error.code}:`, error.detail);
}
}Both FastAPI {detail: "..."} and OpenAI-style {"error": {"message": "...", "code": "..."}}
error bodies are parsed automatically.
Environment Variables (SDK, Node.js only)
| Variable | Default | Description |
|----------|---------|-------------|
| OPENDESK_BASE_URL | http://127.0.0.1:8000/api/v1 | API base URL when baseUrl is not passed |
| OPENDESK_TOKEN | - | JWT token used when token is not passed |
Requirements
- Node.js >= 18 (for native fetch API)
- Or modern browsers with fetch support
License
项目采用 Mulan PSL v2(Mulan Permissive Software License, Version 2,SPDX: MulanPSL-2.0)开源协议。
