@bike4mind/sdk

中文文档
2.2.0发布于 2026/11/16BUSL-1.1TypeScriptESM + CJS构建来源已验证近 30 天下载 32.8万

Typed client for the Bike4Mind HTTP API, generated from its OpenAPI spec

原始使用文档
文档目录11 节
  1. Install
  2. Create a client
  3. Call any operation
  4. Stream a completion
  5. Chat and image jobs
  6. Audio
  7. Bill the signed-in user
  8. Errors
  9. Types
  10. Regenerating the types (contributors)
  11. Publishing

@bike4mind/sdk

A small, typed client for the Bike4Mind HTTP API. Its types are generated from the API's OpenAPI spec, so every operation in the spec is callable with typed path params, query, body and response, with no hand-written code per endpoint.

  • Runs anywhere with a global fetch: Node 18+, Bun, Deno, browsers.
  • One runtime dependency (eventsource-parser, for streaming).
  • Responses are typed, not validated.

The full API reference, including scopes, rate limits and async jobs, is served by every deployment at /api/v1/docs (the raw spec is at /api/v1/openapi.json).

Install

npm install @bike4mind/sdk

Create a client

import { createClient } from '@bike4mind/sdk';

const b4m = createClient({
  baseUrl: 'https://app.example.com', // your deployment; there is no default
  apiKey: process.env.B4M_API_KEY, // sent as `Authorization: Bearer b4m_live_...`
});

Other options:

  • getAuthToken: () => string | undefined | Promise<...> runs before every request, and its token wins over apiKey. Use it for JWTs you refresh yourself.
  • fetch is a custom fetch for timeouts, retries, proxies or tests.
  • headers are sent on every request.

Call any operation

call(operationId, args) takes the spec's operationId. params (path), query and body are typed per operation, and params/body are required exactly when the operation requires them.

const me = await b4m.call('getMe');
const models = await b4m.call('listModels', { query: { limit: 20 } });
const project = await b4m.call('getProject', { params: { id: projectId } });
await b4m.call('deleteProject', { params: { id: projectId } }); // 204: resolves undefined

call returns the parsed JSON body. A non-JSON 2xx body (for example the default binary audio from synthesizeSpeech) throws; use raw, completions or the tts/music/soundEffects helpers. For a binary or streamed body, raw(operationId, args) returns the 2xx Response itself. operations maps each id to its { method, path }.

Stream a completion

for await (const event of b4m.completions({
  model: 'claude-sonnet-5-5',
  messages: [{ role: 'user', content: 'Hi' }],
})) {
  if (event.type === 'content') process.stdout.write(event.text);
  if (event.type === 'error') throw new Error(event.message);
}

The endpoint opens the stream before it validates, authenticates or rate-limits, so an invalid body, a rejected key or a rate limit arrives as a yielded { type: 'error' } event, not a thrown error. Only a response that never becomes a stream (a malformed JSON body, a wrong method, a proxy error) throws B4mApiError. Pass { signal } to cancel, or { url } to stream from a different endpoint; a relative url is joined under baseUrl. An absolute url receives the same Authorization header, so pass only an origin you trust. A stream that ends without [DONE] and without an error event throws.

Chat and image jobs

Chat turns and image generations and edits are queued. Each helper returns a handle whose poll() waits for the job to finish:

const turn = await b4m.chat({ message: 'Summarize my last notebook' });
const quest = await turn.poll({ timeoutMs: 120_000 });
console.log(quest.reply);

const image = await b4m.generateImage({ prompt: 'a red bicycle', model: 'gpt-image-1' });
const { images } = await image.poll();

poll backs off from intervalMs (default 1000 ms) up to maxIntervalMs (default 5000 ms). It throws B4mQuestError when the job ends with type: "error" (reason: 'error'), ends stopped ('stopped'), or outlives timeoutMs ('timeout'). error.quest holds the last state. To resume polling a known quest id, use pollQuest(id).

Other async jobs (agent executions, video generations, file uploads) are plain calls: start the job, then poll its get* operation.

Audio

tts, music and soundEffects always request encoding: 'base64', so a result too large for the response comes back as the delivery: 'url' variant instead of a redirect. A server that predates encoding streams raw bytes; the SDK rebuilds the same inline shape from those bytes and the X-B4M-Audio-* headers.

const result = await b4m.tts({ text: 'Hello', voice: 'alloy' });
if (result.kind === 'audio' && result.data.delivery === 'inline') {
  const bytes = Buffer.from(result.data.audio, 'base64');
}

tts also returns { kind: 'saved-too-large', data } when an older server rejects oversized audio with a 413 but kept a saved copy (data.fabFileId). To get binary audio directly, use raw('synthesizeSpeech', { body: { text, encoding: 'binary' } }).

Bill the signed-in user

exchangeIdToken trades a user's B4M ID token for a short-lived API key that bills that user's credits. It is server only: it sends your client secret.

import { createClient, exchangeIdToken } from '@bike4mind/sdk';

const baseUrl = 'https://your-b4m-host';
const { apiKey, expiresAt } = await exchangeIdToken({
  baseUrl,
  clientId,
  clientSecret,
  idToken,
  signal: AbortSignal.timeout(10_000),
});
const b4m = createClient({ baseUrl, apiKey });

A failure throws B4mApiError with errorCode set to the OAuth error (invalid_request, invalid_client, invalid_grant, access_denied, invalid_scope, subscription_required, temporarily_unavailable) and message set to its error_description. On a 429, wait retryAfterSeconds.

Caching is yours: there is one live key per user and app (each exchange revokes the previous one), so keep the key per user and re-mint shortly before expiresAt. See Bill the user, not yourself for the full contract.

Errors

Any non-2xx response throws B4mApiError. An OAuth-style body (a snake_case error code and error_description) maps error to errorCode and error_description to message:

import { B4mApiError } from '@bike4mind/sdk';

try {
  await b4m.call('getMe');
} catch (error) {
  if (error instanceof B4mApiError) {
    error.status; // HTTP status
    error.errorCode; // e.g. 'insufficient_credits'; branch on this, not on the message
    error.requestId; // body request_id or the X-Request-ID header
    error.retryAfterSeconds; // from Retry-After on a 429
    error.body; // the parsed body
  }
}

Types

Generated types are exported for your own code: paths, components, Operations, and the shortcut Schemas (for example Schemas['ErrorResponse']). Per-operation helpers are JsonBody<'createProject'>, JsonResponse<'getQuest'>, PathParams<...> and QueryParams<...>.

These names come straight from the spec (operationIds, schema names such as getQuestResponse200, status codes), so they are part of this package's public API: renaming one in the spec is a breaking change for code that imports it.

Regenerating the types (contributors)

src/generated/ is generated from apps/client/public/openapi.json and checked in. From the repo root:

pnpm turbo:openapi:generate   # regenerates the spec, then the SDK types

pnpm --filter @bike4mind/sdk generate regenerates only the SDK types from the current spec. CI fails when either is stale.

Publishing

Released to npm from CI through npm trusted publishing (OIDC); no npm token is stored.

版本与发布记录

@bike4mind/sdk 共发布 1,540 个版本,首次发布于 2026/10/20;过去 12 个月发布了 1540 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.2.0latest2026/11/16今天
0.0.0-snapshot-feat-bedrocknews-claim-page-202611031838132026/11/0412 天前
0.0.0-snapshot-feat-grant-packages-202611031759232026/11/0412 天前
0.0.0-snapshot-fix-release-notes-denylist-word-boundarie-202611031742552026/11/0412 天前
0.0.0-snapshot-feat-analytics-internal-users-202611031739312026/11/0412 天前
0.0.0-snapshot-feat-young-account-spend-shadow-detection-202611031729302026/11/0412 天前

其他发布通道:snapshot-feat-voice-hold-sweep-alarm → 1.1.0,snapshot-feat-5123-admin-org-storage-limit → 0.0.0-snapshot-feat-5123-admin-org-storage-limit-20261020084406,snapshot-gh-readonly-queue-main-pr-5038-b71e511989 → 0.0.0-snapshot-gh-readonly-queue-main-pr-5038-b71e511989-20261020085345,snapshot-gh-readonly-queue-main-pr-5088-be40ebd2d0 → 0.0.0-snapshot-gh-readonly-queue-main-pr-5088-be40ebd2d0-20261020090251,snapshot-feat-desktop-skill-market → 0.0.0-snapshot-feat-desktop-skill-market-20261020091438,snapshot-fix-model-price-catalog → 0.0.0-snapshot-fix-model-price-catalog-20261020091818。

关于 @bike4mind/sdk 的常见问题

@bike4mind/sdk 是什么?

Typed client for the Bike4Mind HTTP API, generated from its OpenAPI spec

如何安装 @bike4mind/sdk?

在项目目录运行 npm install @bike4mind/sdk,或使用 pnpm add / yarn add / bun add。

@bike4mind/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bike4mind/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@bike4mind/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@bike4mind/sdk 可以商用吗?

@bike4mind/sdk 使用 BUSL-1.1 许可。声明的许可为 BUSL-1.1,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@bike4mind/sdk 的下载量有多少?

根据 npm 官方下载统计,@bike4mind/sdk 在 2026/10/08 – 2026/11/06 这 30 天内被下载 327,503 次,日均约 10,917 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bike4mind/sdk 还在维护吗?

最新版本 2.2.0 发布于 2026/11/16(今天);至今共发布 1540 个版本,其中过去 12 个月发布了 1540 个;首次发布于 2026/10/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。