@b4run/cli
Use this whenCopy link to section: Use this when
Most apps only need the b4 command to develop, test, build, and serve. Import the package root to embed the Node server. Use /fetch when an edge adapter supplies the generated modules and the durable stores its routes need. The adapter may also pass a constructed configuration. Without one, runtime defaults apply. /runtime is low-level tooling. /workspace is the managed-workspace lifecycle without the command program, for a host process that owns its own executions. /testing is a deprecated compatibility alias.
Install and importCopy link to section: Install and import
For command-only use, install the CLI as a dev dependency:
npm install -D @b4run/cli
npx b4 devInstall it as a runtime dependency when production code or a generated server imports it:
npm install @b4run/cliimport { serveRuntime } from "@b4run/cli"
import { createRuntimeFetchHandler } from "@b4run/cli/fetch"Compatibility and audienceCopy link to section: Compatibility and audience
| Surface | Runtime | Purity | Audience | Stability |
|---|---|---|---|---|
@b4run/cli | node-only | not-claimed | application | supported |
@b4run/cli/fetch | edge-safe | not-claimed | integration | supported |
@b4run/cli/runtime | node-only | not-claimed | tooling | low-level |
@b4run/cli/testing | node-only | not-claimed | testing | supported |
@b4run/cli/workspace | node-only | not-claimed | tooling | low-level |
bin:b4 | node-only | n/a | tooling | supported |
Public exportsCopy link to section: Public exports
@b4run/cliCopy link to section: @b4run/cli
| Export | Responsibility |
|---|---|
B4Config | Re-export the @b4run/core configuration type, so an app that depends only on @b4run/cli can name it. |
B4StaticModules | Map generated route modules for runtime boot. |
ServeFallback | Handle requests the runtime does not own. |
ServeGuard | Answer or pass every request before routing. |
ServeHandle | Control a composed server. |
ServeOptions | Configure a composed server. |
ServeRuntimeHandle | Control an embedded server. |
ServeRuntimeOptions | Configure an embedded Node server. |
StaticRouteModule | Describe one generated route module. |
config | Re-export @b4run/core configuration typing. |
createProgram | Construct the command program for custom I/O. |
isExecutedAsMain | Detect direct executable invocation. |
loadStaticModules | Load generated static route modules. |
renderError | Format a CLI-facing error. |
run | Run the command program with explicit arguments. |
serve | Serve the runtime's routes beside an application handler. |
serveRuntime | Start the production Node runtime server. |
cleanupWorkspaces | Remove managed workspaces from an inactive, dedicated app installation with exclusive ownership and retryable deletion. |
withWorkspace | Run host-authored work in a fresh managed workspace with durable cleanup. |
WithWorkspaceOptions | Select source, provider, policy, and a private durable state directory. |
@b4run/cli/fetchCopy link to section: @b4run/cli/fetch
| Export | Responsibility |
|---|---|
BootResolvedInstances | Hold stores resolved before request handling. |
B4StaticModules | Map generated route modules. |
RequestStores | Supply request-scoped durable stores. |
RuntimeBootFallbacks | Define optional runtime boot fallbacks. |
RuntimeEnv | Re-export the @b4run/core runtime environment type. |
RuntimeFetchHandler | Handle a web-standard runtime request. |
SerializedError | Describe one serialized error and its cause chain. |
StartRuntimeServerOptions | Share runtime assembly inputs. |
StaticRouteModule | Describe one materialized route module. |
StaticRouteModuleInput | Describe a generated route-module input. |
StaticToolModuleInput | Describe a generated tool-module input. |
StreamChunk | Represent one runtime stream chunk. |
buildStaticRouteModule | Build one route module without filesystem discovery. |
createRuntimeFetchHandler | Assemble a web-standard request handler. |
describeConnectionTarget | Reduce a connection string to its scheme, host, port and database for logging. |
errorStackOf | Find the first stack trace in a thrown value's cause chain. |
formatErrorChain | Render a thrown value and its cause chain as operator-readable log lines. |
normalizeMiddlewareModule | Normalize generated middleware exports. |
normalizeThreadAccessModule | Normalize generated thread-access policy exports. |
normalizeWsProxy | Normalize a B4_PG_WS_PROXY value (host:port, ws://, or wss://) into the address and TLS flag the neon driver needs. |
PostgresDriver | Name the Postgres driver a generated store factory opens (neon or pg). |
PostgresDriverSelection | Describe the driver decision and optional proxy target for one request. |
readRuntimeEnv | Re-export @b4run/core environment lookup. |
seedB4Config | Re-export @b4run/core static configuration seeding. |
seedModelImporter | Re-export the @b4run/langchain static importer seam; its deep reference is deferred. |
seedRuntimeEnv | Re-export @b4run/core environment seeding. |
selectPostgresDriver | Decide per request which driver talks to DATABASE_URL on the hono or vercel target; see Edge and Hono. |
SelectPostgresDriverInput | Supply DATABASE_URL, B4_PG_DRIVER, B4_PG_WS_PROXY, and the target to selectPostgresDriver. |
serializeError | Read the message, code and nested cause off any thrown value, including an ErrorEvent. |
WsProxyTarget | Carry a normalized proxy address and whether the WebSocket stays secure. |
@b4run/cli/runtimeCopy link to section: @b4run/cli/runtime
| Export | Responsibility |
|---|---|
B4ResumeEntry | Describe one submitted interrupt decision. |
normalizeThreadAccessResult | Coerce a policy's return value into a decision the runtime can act on. |
B4StaticModules | Map generated route modules. |
MaterializeResolvedRouteGraphOptions | Configure route graph materialization. |
PendingInterrupt | Describe a pending human decision. |
PendingInterruptSnapshot | Snapshot pending decisions for a thread. |
PermissionDecision | Represent a human permission decision. |
PreparedRouteModules | Hold prepared modules for a route. |
ReadResponseFormatResult | Represent a parsed or rejected client response schema. |
ResumeResolution | Represent resolved resume input. |
RuntimeFetchHandler | Handle runtime fetch requests. |
RuntimeRegistry | Resolve materialized routes. |
RuntimeRequestListener | Handle Node HTTP requests. |
SandboxManager | Manage runtime sandboxes. |
ServeFallback | Handle requests the runtime does not own. |
ServeGuard | Answer or pass every request before routing. |
ServeHandle | Control a composed dev server. |
ServeOptions | Configure a composed dev server. |
ServeRuntimeHandle | Control a running server. |
ServeRuntimeOptions | Configure production server boot. |
StartRuntimeServerOptions | Configure low-level server assembly. |
StaticRouteModule | Describe a generated route module. |
StaticRouteModuleInput | Describe a route-module input. |
StaticToolModuleInput | Describe a tool-module input. |
StreamChunk | Represent one stream chunk. |
__resetMaterializedAgentsForTests | Reset LangChain materialization caches in tests. |
__resetRouteLoadCachesForTests | Reset route-loader caches in tests. |
buildStaticRouteModule | Build a static route module. |
createRuntimeFetchHandler | Assemble the Node fetch handler. |
createRuntimeRegistry | Construct a runtime route registry. |
createRuntimeRequestListener | Construct a Node request listener. |
executeResolvedRoute | Execute a resolved route. |
invokeResolvedRoute | Invoke a resolved route graph. |
loadStaticModules | Load generated route modules. |
materializeResolvedRouteGraph | Materialize a resolved graph. |
normalizeMiddlewareModule | Normalize middleware exports. |
normalizeThreadAccessModule | Normalize thread-access policy exports. |
readPendingInterrupts | Read pending human decisions. |
readResponseFormat | Parse a run body's hashbrown.responseSchema into a bound response format. |
resolveCheckpointer | Resolve the configured checkpointer. |
resolvePendingResume | Resolve submitted interrupt decisions. |
resolveSandboxManager | Resolve the server sandbox manager. |
resolveThreadsStore | Resolve the configured thread store. |
runMemoryCommand | Run the low-level memory command implementation. |
runTypegen | Generate application route declarations. |
seedPreparedRouteModules | Seed prepared route modules. |
serve | Serve the runtime's routes beside an application handler. |
serveRuntime | Start the production runtime server. |
startRuntimeServer | Assemble and start the Node server. |
streamResolvedRoute | Stream a resolved route. |
These exports are for framework tooling and test harnesses. Application code should use root serveRuntime or the edge-safe /fetch entry.
@b4run/cli/testingCopy link to section: @b4run/cli/testing
| Export | Responsibility |
|---|---|
expectError | Deprecated alias of @b4run/sdk/testing expectError. |
expectMeta | Deprecated alias of @b4run/sdk/testing expectMeta. |
expectOutput | Deprecated alias of @b4run/sdk/testing expectOutput. |
New scenario files should import these aliases from @b4run/sdk/testing.
@b4run/cli/workspaceCopy link to section: @b4run/cli/workspace
| Export | Responsibility |
|---|---|
WithWorkspaceOptions | Select source, provider, policy, and a private durable state directory. |
cleanupWorkspaces | Remove managed workspaces from an inactive, dedicated app installation with exclusive ownership and retryable deletion. |
withWorkspace | Run host-authored work in a fresh managed workspace with durable cleanup. |
ManagedWorkspaceReadOptions | Name the worker app root, its provider, the thread to read, cancellation, and the reader identity. |
openManagedWorkspaceReader | Resolve a thread to its published managed workspace through the worker's installation store and open it read-only. |
withManagedWorkspaceReader | Open a managed workspace reader for a thread, hand it to an operation, and always close it. |
readThreadWorkspace | Read a thread's workspace over a worker's Agent Protocol port (sandbox.workspaceRead: "http") and verify the answer. |
ReadThreadWorkspaceOptions | Name the root, omitted directories, required links, ignored prefixes, and limits of an HTTP workspace read. |
ReadThreadWorkspaceInit | Carry the request headers, cancellation, the expected source digest, the response-size cap, and an optional fetch. |
ThreadWorkspaceRead | Return the thread id, its recorded source and intent digests, the root, and the inspection. |
ThreadWorkspaceReadError | Report a refused or unverifiable read with the worker's status, code, and details. |
The package root exports the first three. This subpath lets a host process own the workspace lifecycle without importing the command program at the root.
bin:b4Copy link to section: bin:b4
bin:b4 is the executable, not a TypeScript subpath. It runs the add, build, check, dev, docs, eval, inspect, memory, routes, run, start, test, typegen, and verify commands. See the CLI Reference for command syntax.
Key contractsCopy link to section: Key contracts
serveRuntime()Copy link to section: serveRuntime()
Embeds B4.run's production Node server. It starts once, returns a close handle, and does not watch the filesystem.
export declare function serveRuntime(opts: ServeRuntimeOptions): Promise<ServeRuntimeHandle>export interface ServeRuntimeOptions {
readonly appRoot: string
readonly host?: string
readonly port?: number
readonly installSignalHandlers?: boolean
readonly modules?: B4StaticModules
readonly config?: B4Config
readonly checkpointer?: BaseCheckpointSaver
readonly threadsStore?: ThreadsStore
readonly permissionsStore?: PermissionsStore | (() => Promise<PermissionsStore>)
readonly memoryStore?: () => Promise<MemoryStore>
readonly middleware?: B4Middleware
readonly threadAccessExpected?: boolean
}Fields: @b4run/cli#.:ServeRuntimeOptions
| Field | Type | Required | Description |
|---|---|---|---|
readonly appRoot | string | yes | Select the B4.run application root. |
readonly host | string | no | Override the listen host. |
readonly port | number | no | Override the listen port. |
readonly installSignalHandlers | boolean | no | Opt into SIGTERM and SIGINT shutdown handlers. |
readonly modules | B4StaticModules | no | Supply build-time generated route modules. |
readonly config | B4Config | no | Supply an already-constructed application configuration. |
readonly checkpointer | BaseCheckpointSaver | no | Supply the boot-resolved checkpointer. |
readonly threadsStore | ThreadsStore | no | Supply the boot-resolved thread store. |
readonly permissionsStore | PermissionsStore | (() => Promise<PermissionsStore>) | no | Supply a permissions store or its async factory. |
readonly memoryStore | () => Promise<MemoryStore> | no | Supply the lazy memory-store factory. |
readonly middleware | B4Middleware | no | Supply preloaded middleware. |
readonly threadAccessExpected | boolean | no | Record that the build saw a thread access policy, so a modules manifest without one fails the boot instead of serving thread endpoints open. The node target's generated server.mjs sets it. |
Behavior contract cli.serve.production-boot
serveRuntime starts without running type generation or writing .b4 artifacts.
Behavior contract cli.serve-runtime.port-precedence
serveRuntime uses an explicit port first, then a numeric PORT value, then 8000. Empty or non-numeric PORT values also fall back to 8000; an explicit 0 still requests a random port.
Runtime ownershipCopy link to section: Runtime ownership
The /fetch handler has no filesystem fallback for its module map or its required stores, so an edge host must inject them. The host may also pass a constructed configuration. Without one, runtime defaults apply.
Behavior contract cli.fetch.request-store-lifecycle
A requestStores factory creates and disposes stores per request. Disposal waits for an SSE body to finish. close() waits for in-flight disposal while its bounded shutdown drain remains open; after the 30-second default deadline it warns and proceeds.
Disposable managed executionCopy link to section: Disposable managed execution
withWorkspace(options, callback) captures options.workspace relative to
appRoot, uses provider.workspaces, and invokes the callback with ordinary
sandbox filesystem/command backends. Its private stateRoot retains unfinished
cleanup across process restarts. One invocation may own each state directory;
use separate directories for concurrent jobs. Prior unfinished work is destroyed
before a fresh callback starts. Cleanup is part of completion: failures propagate
and retained deletion records support retry. An independent verifier can use this
instead of duplicating provider lifecycle code.
Reading a managed workspaceCopy link to section: Reading a managed workspace
withManagedWorkspaceReader({ appRoot, provider, threadId, signal }, operation)
reads the workspace of a thread whose app declares sandbox.workspace. Those
threads never reach SandboxProvider.acquire, so withWorkspaceReader can't
address them by thread id.
The helper opens the worker's installation store under appRoot read-only,
without taking the worker's owner lock. It resolves the thread's published
ReadyWorkspace and passes it to provider.workspaces.openWorkspaceReader.
It refuses, with the reason, when:
- the provider has no managed or read capability,
- the installation or the thread's association is missing, or
- the workspace isn't published yet (
retryable), is deleted (lost), or is past its retention deadline (expired).
It never falls back to provider storage. openManagedWorkspaceReader does the
same resolution without the scoped close. Both only address a workspace, so
gate access in the calling process.
readThreadWorkspace(url, threadId, options, { headers, signal, expectedSourceDigest })
reads the same inventory over a worker's Agent Protocol port when the worker
sets sandbox.workspaceRead: "http", for a caller that cannot reach the
worker's app root. It verifies the answer's shape, thread and (when given)
source digest, and throws ThreadWorkspaceReadError with the worker's status
and code otherwise.
Examples and related guidesCopy link to section: Examples and related guides
import { serveRuntime } from "@b4run/cli"
const server = await serveRuntime({ appRoot: process.cwd(), port: 8000 })
console.log(server.url)Continue with CLI Reference, Embed the Runtime, Edge and Hono, and Deployment Options.