@cpajs/cpa
v0.1.0
Published
Run the official CLIProxyAPI from JavaScript and talk to its v8 management API with a typed client
Readme
@cpajs/cpa
Run the official CLIProxyAPI (CPA) from Node.js or Bun, and manage any CPA instance with a hand-written, typed client for its native v8 management API.
@cpajs/cpa/serverlocates the bundled binary, writes the config, starts the process, waits until it is ready, streams logs and stops it.@cpajs/cpa/clientis afetch-based client for/v8/management, with types derived from the CPA source. It can connect to local or remote instances.- Prebuilt CPA binaries for 23 platforms come through
optionalDependencies, sonpm installis all that is needed.
Bundled CLIProxyAPI: v8.1.8.
- Upgrading: CHANGELOG.md and docs/migration.md.
- Platforms, versions and the versioning policy: docs/compatibility.md.
- Every management API route: docs/api-coverage.md.
- What cpajs does and does not do: docs/scope.md.
npm install @cpajs/cpaStart a server
import { startServer } from '@cpajs/cpa/server';
const server = await startServer({
stateDir: './.cpa', // omit for a temporary directory that is removed on stop
config: { // native v8 config, typed as CpaConfig
access: { 'api-keys': ['sk-my-model-key'] },
routing: { strategy: 'fill-first' },
},
onLog: ({ stream, line }) => console.log(`[cpa ${stream}] ${line}`),
});
console.log(server.origin); // http://127.0.0.1:40123 (a free port is picked by default)
console.log(server.baseUrl); // http://127.0.0.1:40123/v1 for OpenAI-compatible SDKs
// Management API client, already bound to this server and a key generated for this start.
const client = server.client();
await client.credentials.list();
await server.stop();configandconfigPathare mutually exclusive.configis either a native config object or a function that returns one.- An object is written as YAML to
<stateDir>/config.yamlonly when that file does not exist yet. On later starts the existing file is reused, so changes made through the management API (or by CPA itself) survivestop()andstartServer(). PassoverwriteConfig: trueto replace it; when a file is kept,config,hostandportare not applied and aconfigReusedwarning is emitted. Credentials go to<stateDir>/authsunlessoauth.auth-diris set. The server binds127.0.0.1unless you passhostor setserver.host. - A function is called before the first start and again before every manual
restart(). It receives{ existing, reason }: the parsed current<stateDir>/config.yaml(orundefined) and'start'or'restart'. Its result replaces the file each time, likeoverwriteConfig: true, while cpajs still fills in the listener, management secret and panel fields. It cannot be combined withoverwriteConfig, and aconfigReusedwarning is never emitted. The management key is resolved before the function runs, somanagement['secret-key']in its result does not choose the key behindserver.client(); passmanagementfor that (or keep the generated key).
- An object is written as YAML to
configPathhands an existing file to CPA unchanged. CPA may rewrite it on startup: it hashes a plaintextmanagement.secret-key, removes legacy keys that conflict with their v8 equivalents, and normalizes the layout (internal/config/config_load.goandNormalizeConfigLayout).
Both modes require the file to set a fixed positive port: CPA does not default the port, and a missing or non-positive one becomes 0, which makes CPA bind a random port it does not report. Like upstream,
server.host/server.port/server.tls.enablewin by presence over the legacy top-levelhost/port/tls.enable. When cpajs writes the file and no port is given, it picks a free port first; a reused file keeps the port it already has.startServerresolves only once/healthzanswers. It rejects withCpaStartErroron early exit, port conflict, timeout (startupTimeoutMs, default 30 s),signalabort, or an invalid config function. In every failure case the process is stopped and the temporary directory removed.stop()is idempotent: on POSIX it sends SIGTERM and then SIGKILL afterstopTimeoutMs(default 10 s). On Windows Node cannot deliver a graceful shutdown signal, sostop()terminates the process forcefully (equivalent to SIGKILL),stopTimeoutMshas no effect, and CPA gets no chance to flush state or update auth files. The same applies to the stop half ofrestart().server.exitedsettles on the final stop or an unexpected exit.restart({ timeoutMs, signal })stops the old process with the same SIGTERM → SIGKILL sequence (timeoutMsdefaults tostopTimeoutMs) and starts it again with the original options. The handle keepsorigin,baseUrl,host,port,stateDirandconfigPath;pid,processandrecentLogspoint at the new process. With an objectconfig, the existingconfig.yamlis reused and never rewritten, so changes made through the management API survive. A functionconfigis evaluated again before the restart and its result replaces the file. The original port is reused; if another process took it meanwhile, restart fails withCpaStartErrorcodeport-in-useinstead of changingorigin. Concurrentrestart()calls share one operation,stop()during a restart aborts it, andrestart()after the handle stopped (including after an unexpected exit) rejects with codestopped. A failed restart leaves the handle stopped and cleans up a temporary state directory likestartServerdoes.There is no automatic restart. Use
server.exitedto observe an unexpected exit and callstartServer()again, or callrestart()from your own supervisor.Lifecycle events:
server.on('exit', listener)returns an unsubscribe function. Anexitpayload hascode,signal,recentLogs,willRestartandreason:'stop'whenstop()stopped the process,'restart'when a manualrestart()replaced it, and'unexpected'when the process exited by itself. A listener that throws is reported throughprocess.emitWarningand never disturbs the server.Shutdown: CPA does not outlive your process, even if it is killed with SIGKILL, crashes, or is restarted by
tsx watch/nodemon. Each platform package ships a smallcpa-launcher(pure Go, inlauncher/) that relies only on operating-system facilities:- Linux: it sets
PR_SET_PDEATHSIGand execs CPA, so there is no extra process. The kernel sends CPA SIGTERM when your process dies. - macOS / BSD: it stays as CPA's parent and stops CPA when the pipe to your process closes.
server.pidis then the launcher's pid; signals sent to it reach CPA. - Windows: no launcher is needed, because Node already kills child processes with their parent.
Pass
launcher: falseto start CPA directly. With a custombinaryPath, the launcher is looked up next to that binary and then in the installed platform package; if none is found, CPA starts directly. A graceful stop is still nicer than a kill, andstopAllServers()stops every server this process started:import { stopAllServers } from '@cpajs/cpa/server'; for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { await stopAllServers(); process.exit(0); }); }Lines longer than 64 KiB in CPA's output are truncated, with a marker saying how much was dropped.
- Linux: it sets
Logs:
onLogreceives every line withstreamand the redactedline. When the line uses CPA's log format, it also haslevel(debug,info,warn,errororfatal), the short 8-characterrequestId(omitted for CPA's--------placeholder) andmessage(the text after CPA's timestamp, request-id, level and caller prefixes). Output that does not match the format still arrives, with onlystreamandline.onLogreceives every redacted line. Filter onlevelyourself when you only want some severities;recentLogsalways keeps everything.Management key: you usually don't need one. Without
management, cpajs generates a random key for each start, writes only its bcrypt hash into the managed config (remote management off), keeps the plaintext in memory, and gives youserver.client(): a management client bound to this server. The key is never exposed, and because nobody types it, it can never be wrong and trigger CPA's 30-minute IP ban.restart()keeps the key, so existing clients keep working; a newstartServer()generates a new one. Since no one could log in to the web control panel with that key, the panel defaults to off (disable-control-panel: true).management: falseturns the management API off.Pass a key yourself when a person or something else needs it, for example the web control panel, a remote admin tool or another process:
management: { key }. The default mode writes a bcrypt hash intomanagement.secret-keyof the managed config and setsmanagement.allow-remotefromallowRemote(defaultfalse), so the plaintext never reaches disk and remote management stays off.server.client()works there too.The three steps build on each other: no key (only this process),
management: { key }(people on this machine, with the control panel),allowRemote: true(people elsewhere too). The rest of the table below is for setups that need more control.Control panel:
@cpajs/cpaships a pinned copy of the web control panel (management.html, see compatibility), checked against its sha256 when the package is built. In a config cpajs manages, CPA serves that copy at/management.htmland never downloads one: cpajs copies it to<stateDir>/static/, pointsMANAGEMENT_STATIC_PATHat it and defaultsdisable-auto-update-paneltotrue. Upstream would otherwise fetch the latest panel from GitHub on start and every 3 hours, falling back to an unverified mirror. To get that behaviour back, setdisable-auto-update-panel: falseorpanel-github-repositoryinconfig.management, or setMANAGEMENT_STATIC_PATHinenv. WithconfigPath, cpajs leaves the panel to your file.Redaction: the key, secrets found in the config when the server starts, and
redactvalues are replaced with[REDACTED]inonLog,recentLogsand startup errors. This is best-effort, with known limits:- Values shorter than 4 characters are not redacted.
- Credentials added while the server runs (management API, OAuth logins,
restart()) are not added to the redaction list. - A line longer than 64 KiB is truncated before redaction, which can leave the start of a secret at the cut.
Do not treat CPA's output as safe to publish.
| Mode | How CPA compares the key | Remote access |
server.client()| Control panel | | --- | --- | --- | --- | --- | | omitted (default) | bcrypt hash of a key generated per start | Off | Yes | Off (nobody knows the key) | |management: false| — (management API disabled) | — | No | — | |management: { key }| bcrypt hash inmanagement.secret-key| Written fromallowRemote, defaultfalse| Yes | Pinned copy | |management: { key, allowRemote: true }| bcrypt hash inmanagement.secret-key| Non-loopback clients allowed | Yes | Pinned copy | |management: { key, viaEnvironment: true }| PlaintextMANAGEMENT_PASSWORD| Always allowed: upstream treats the variable asallow-remote: true| Yes | Pinned copy | |config.management['secret-key']| What you write; CPA hashes plaintext on startup |config.management['allow-remote']| No: the key is yours | Pinned copy | |configPath|secret-keyin the file |allow-remotein the file | Only withmanagement: { key, viaEnvironment: true }| Your file decides | |managementKey(deprecated) | bcrypt hash, same asmanagement: { key }| Off unless the file allows it | Yes | Pinned copy |management.keyis rejected together withconfig.management['secret-key'], or with asecret-keyalready present inconfigPath. InconfigPathmode it also requiresviaEnvironment: true, because cpajs must not edit your file.MANAGEMENT_PASSWORDreaches CPA only throughviaEnvironment: true. One inherited from the parent environment is always removed, and setting it inenvis rejected. Otherwise it would quietly add a plaintext key and turn remote management on.viaEnvironment: truealways emits themanagementViaEnvironmentwarning, because the key is compared in plaintext and remote management cannot be turned off.allowRemote: trueemitsremoteManagementExposedwhen the bind host is not loopback. These are warnings, not errors, because both are explicit choices.The server handle never exposes the key;
server.client()exposes the capability instead. To connect from elsewhere, pass your own key tocreateClient.Warnings: cpajs reports things worth knowing as coded warnings, separate from CPA's output (
onLog). By default they go throughprocess.emitWarningasCpaWarning, so they appear on stderr and work with Node's usual handling (--no-warnings,process.on('warning')). PassonWarningto route them yourself. PasssuppressWarningsto silence individual ones; every message names the field that silences it.await startServer({ config, suppressWarnings: { noManagementKey: true } });| Code | Emitted when | | --- | --- | |
noManagementKey| Nomanagementwas given, so a key was generated for this start (useserver.client()) | |managementViaEnvironment|management.viaEnvironmentis used: plaintext comparison, remote management forced on | |remoteManagementExposed|allowRemoteis on and the server binds a non-loopback host | |configReused| An existing managed config was kept; this start'sconfig,hostandportwere not applied | |managementKeyUpdated| A reused config's management key was replaced for a newmanagement.key|CLI flags are typed options:
localModel: true→-local-model, which uses the embedded model catalogs.home: { jwt, disableClusterDiscovery }→ Home mode. The JWT is passed throughHOME_JWT, so it never appears in argv.
argsis only for flags that plugins register. One-shot commands (-*-login,-discover,-tui, …) and flags that have a typed option are rejected.binaryPathoverrides the bundled binary.variant: 'lite'runs the installed lite platform package instead of the full one (see Lite build).
Manage a server
import { createClient, CpaHttpError } from '@cpajs/cpa/client';
const client = createClient({
baseUrl: 'http://127.0.0.1:8317', // a path prefix behind a reverse proxy is kept
managementKey: process.env.CPA_MANAGEMENT_KEY!,
timeoutMs: 15_000,
});
const { data: config, etag } = await client.config.get();
await client.config.patch({ routing: { strategy: 'round-robin' } }, { ifMatch: etag });
await client.config.set('routing/retry/request-retry', 2); // value typed by path: number
// Read one node with its ETag, then write it back conditionally.
const read = await client.config.getPath('routing/strategy');
await client.config.set('routing/strategy', 'fill-first', { ifMatch: read.etag });
const { files } = await client.credentials.list();
// Upload a credential file. CPA returns the credential list, models and downloads as-is.
await client.credentials.upload({ name: 'codex-me.json', content: credentialJson });
const login = await client.oauth.start({ provider: 'claude' });
console.log('open', login.url);
await client.oauth.waitForCompletion(login.state);
try {
await client.config.getPath('does/not/exist');
} catch (error) {
if (error instanceof CpaHttpError) console.log(error.status, error.errorCode); // 404 'not_found'
}credentials.list, upload, uploadMany, download, delete, setStatus and the other methods pass
through the matching upstream routes. setStatus and delete take file names (and arrays of names) only; config
api-keys entries are managed through client.config like any other config node.
| Group | Routes |
| --- | --- |
| config | /config, /config.yaml, /config/*path, with ETag / If-Match |
| credentials | list, models, upload (raw or multipart), delete, status, download, fields, refresh, SIWC status |
| oauth | auth URL, status / wait, cancel, callback, Vertex import, SIWC bind |
| logs | main log with cursor, clear, error logs, request logs |
| usage | API-key counters, usage queue (destructive pop) |
| routing | cooldown reset, model definitions |
| requests | server-side api-call (apiCall) |
| plugins | list, delete, store, install, quota |
| server | /healthz, version headers, latest release |
Every method takes { signal, timeoutMs, headers }. Errors:
CpaHttpErrorfor a non-2xx response. It carriesstatus, the rawbody, parseddata, anderrorCode/errorMessage.CpaNetworkErrorwhen the request fails.CpaTimeoutErrorwhen the request times out.CpaAbortErrorwhen yoursignalaborts the request.CpaResponseErrorwhen a 2xx response has a malformed body.
A 207 partial result resolves normally. Use client.request() for anything without a typed method.
Management-key bans
The fifth consecutive wrong management key from one IP address bans that IP for 30 minutes. While banned, CPA
answers 403 {"error":"IP banned due to too many failed attempts. Try again in <duration>"} before it even checks
the supplied key. Loopback clients are included, and 127.0.0.1 and ::1 are separate counters. The failed-attempt
map is in process memory and upstream has no unban route.
For a server you started with startServer, call server.restart() to clear the ban. For a remote instance you
can only wait for it to expire. Do not retry a 401 invalid management key or missing management key in a loop.
Model API
The management key and model API keys are different things. Model requests go to server.baseUrl or
client.modelBaseUrl with a key from access.api-keys:
import OpenAI from 'openai';
const openai = new OpenAI({ baseURL: server.baseUrl, apiKey: 'sk-my-model-key' });Lite build
@cpajs/cpa-lite is this package with the lite CLIProxyAPI build: the same code and API, published under another
name, whose optional dependencies are the @cpajs/lite-<target> platform packages. Import from
@cpajs/cpa-lite/server, @cpajs/cpa-lite/client and @cpajs/cpa-lite/binary.
npm install @cpajs/cpa-liteThe lite binary is the same CLIProxyAPI release, about 43% smaller (linux-x64: 45.8 MB instead of 80.6 MB). It does not include:
| Removed | Using it anyway |
| --- | --- |
| Terminal UI (-tui) and clipboard | -tui exits with the terminal UI (-tui) is not available in the lite build. cpajs rejects -tui in args in both builds. |
| mDNS discovery | discover / -discover exit with mDNS discovery is not available in the lite build; discovery.enabled: true logs that as a warning and the server keeps serving HTTP. |
| Codex live WebRTC media relay | With oauth.providers.codex.live-media-relay.enabled, POST /v1/realtime/calls answers 503 with the lite error. Disabled (the default), Codex live calls work as in the full build. |
| Postgres, object storage (S3) and git token stores | PGSTORE_DSN, OBJECTSTORE_ENDPOINT or GITSTORE_GIT_URL in CPA's environment makes it exit at startup with the lite error. |
| cl100k_base, p50k and r50k tokenizer vocabularies | Token counts (/v1/messages/count_tokens and the other count routes) use o200k_base for every model: identical for models upstream counts with o200k_base, different for gpt-4, gpt-3.5* and Codex model names matching no known prefix (including gpt-6.x), which upstream counts with cl100k_base. |
Everything else, including Redis / Home mode, plugins (on the plugin targets), kv.db and uTLS, is the same.
Lite packages exist for linux-x64-gnu, linux-arm64-gnu, linux-x64-musl, linux-arm64-musl, darwin-x64,
darwin-arm64, win32-x64 and win32-arm64; elsewhere resolveBinary fails with unsupported-platform.
@cpajs/cpa can also run a lite binary: add @cpajs/lite-<target> to your dependencies and pass
variant: 'lite' to startServer() (or resolveBinary()). The full platform package is still installed through
@cpajs/cpa's optional dependencies, so this saves nothing on disk unless you install with --omit=optional.
DEFAULT_VARIANT tells which variant a package uses by default ('full' here, 'lite' in @cpajs/cpa-lite).
For bundling, @cpajs/cpa-lite/binary works like @cpajs/cpa/binary below; its table also lists the lite
packages (LITE_PACKAGES, resolveLitePackage).
Bundling and deploying
The platform package is an optional dependency picked at runtime, so a bundler cannot see it in a normal
import. @cpajs/cpa/binary is a small entry that contains a literal require.resolve() for every target;
importing it for its side effect puts the installed platform packages in the module graph:
import '@cpajs/cpa/binary';Trace on the deployment platform (including glibc vs musl). A file tracer such as @vercel/nft then copies
the package that matches the build machine. Keep @cpajs/cpa and @cpajs/<target> external rather than
bundling them. nft reports a warning for every platform package that is not installed; those are expected
and non-fatal.
Nitro uses nft. Import the entry from the server code, and full-trace the platform package so its bin/
directory is copied too (pkg* copies every file, not only the traced ones):
import { resolveBinary } from '@cpajs/cpa/server';
export default defineNitroConfig({
// The platform package installed on the build machine, e.g. @cpajs/linux-x64-gnu.
// Build on the platform you deploy to, or write the package name out instead.
traceDeps: ['@cpajs/cpa', `${resolveBinary().packageName}*`],
});Vite SSR leaves packages in node_modules external; make that explicit and run nft over the server output (or
over @cpajs/cpa/binary) as part of the deploy step:
export default defineConfig({
ssr: { external: ['@cpajs/cpa'] },
});Next.js: keep cpajs outside the server bundle and let output file tracing include it:
module.exports = {
serverExternalPackages: ['@cpajs/cpa'],
};In all three setups the side-effect import is what makes the table visible; if a trace still misses the
binary, copy node_modules/@cpajs/<target>/ into the deployment or pass binaryPath to startServer.
Bun ignores libc, so bun install on Linux installs both @cpajs/linux-*-gnu and @cpajs/linux-*-musl
(about 72 MB extra). Install with npm or pnpm, or delete the packages for the other libc before packaging;
cpajs still picks the right target at runtime. binaryPath also lets you ship a single binary yourself.
Development
pnpm install
pnpm lint # Biome
pnpm typecheck && pnpm test # unit tests (mocked fetch + a fake CPA process)
pnpm test:coverage # line coverage for client resources and src/server
node scripts/build-binary.ts --target linux-x64-musl
CPA_BINARY=dist-bin/linux-x64-musl/cli-proxy-api pnpm test:e2e # contract tests against real CPABiome formatting is configured to match the existing style. The current tree predates it, so enforcing
formatting across the whole repository is left to a dedicated change; pnpm format:check currently covers
new examples only.
Release tooling, all in scripts/ and run directly with Node's type stripping:
| Script | Purpose |
| --- | --- |
| fetch-source.ts | Clone the pinned CPA tag and verify the commit. |
| generate-binary-table.ts | Regenerate src/binary-packages.cjs and its types from TARGETS; --check fails on drift. |
| build-binary.ts | Build one or more targets, with the same CGO/plugin split as upstream. |
| verify-binary.ts | Check format, CPU, static linking and the glibc baseline; --smoke starts the binary. |
| assemble-packages.ts | Create the @cpajs/* platform packages. |
| pack.ts | Produce the tarballs. |
| install-test.ts | Install the tarballs through a local registry with npm, pnpm or bun, and run them. |
| wait-for-packages.ts | Poll the npm registry until every platform package resolves at a version; run it before publishing the main package. |
| trust-publishers.ts | Configure npm trusted publishing for all packages (run locally after the first publish). |
.github/workflows/release.yml runs these steps across the whole platform matrix and publishes on v* tags through npm trusted publishing (OIDC). Prerelease versions such as 0.0.1-alpha-1 go to a matching dist-tag (alpha). There is no npm token; trust-publishers.ts configures the trusted publisher for every package. A newly added platform package has to exist on npm before it can be trusted. The publish job runs wait-for-packages.ts --version <version> after publishing the platform packages and before the main package, so @cpajs/cpa is not published while one of its optional dependencies is still missing from the install packument that npm, pnpm and bun read (registry metadata is CDN-cached). It can be run locally against an already published release, e.g. node scripts/wait-for-packages.ts --version 0.1.0-rc.5; --timeout and --interval take seconds.
License
MIT. The bundled CLIProxyAPI binaries are MIT licensed by their authors; each platform package ships their LICENSE.
