@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:

bash
npm install -D @b4run/cli
npx b4 dev

Install it as a runtime dependency when production code or a generated server imports it:

bash
npm install @b4run/cli
ts
import { serveRuntime } from "@b4run/cli"
import { createRuntimeFetchHandler } from "@b4run/cli/fetch"

Compatibility and audienceCopy link to section: Compatibility and audience

SurfaceRuntimePurityAudienceStability
@b4run/clinode-onlynot-claimedapplicationsupported
@b4run/cli/fetchedge-safenot-claimedintegrationsupported
@b4run/cli/runtimenode-onlynot-claimedtoolinglow-level
@b4run/cli/testingnode-onlynot-claimedtestingsupported
@b4run/cli/workspacenode-onlynot-claimedtoolinglow-level
bin:b4node-onlyn/atoolingsupported

Public exportsCopy link to section: Public exports

@b4run/cliCopy link to section: @b4run/cli

ExportResponsibility
B4ConfigRe-export the @b4run/core configuration type, so an app that depends only on @b4run/cli can name it.
B4StaticModulesMap generated route modules for runtime boot.
ServeFallbackHandle requests the runtime does not own.
ServeGuardAnswer or pass every request before routing.
ServeHandleControl a composed server.
ServeOptionsConfigure a composed server.
ServeRuntimeHandleControl an embedded server.
ServeRuntimeOptionsConfigure an embedded Node server.
StaticRouteModuleDescribe one generated route module.
configRe-export @b4run/core configuration typing.
createProgramConstruct the command program for custom I/O.
isExecutedAsMainDetect direct executable invocation.
loadStaticModulesLoad generated static route modules.
renderErrorFormat a CLI-facing error.
runRun the command program with explicit arguments.
serveServe the runtime's routes beside an application handler.
serveRuntimeStart the production Node runtime server.
cleanupWorkspacesRemove managed workspaces from an inactive, dedicated app installation with exclusive ownership and retryable deletion.
withWorkspaceRun host-authored work in a fresh managed workspace with durable cleanup.
WithWorkspaceOptionsSelect source, provider, policy, and a private durable state directory.

@b4run/cli/fetchCopy link to section: @b4run/cli/fetch

ExportResponsibility
BootResolvedInstancesHold stores resolved before request handling.
B4StaticModulesMap generated route modules.
RequestStoresSupply request-scoped durable stores.
RuntimeBootFallbacksDefine optional runtime boot fallbacks.
RuntimeEnvRe-export the @b4run/core runtime environment type.
RuntimeFetchHandlerHandle a web-standard runtime request.
SerializedErrorDescribe one serialized error and its cause chain.
StartRuntimeServerOptionsShare runtime assembly inputs.
StaticRouteModuleDescribe one materialized route module.
StaticRouteModuleInputDescribe a generated route-module input.
StaticToolModuleInputDescribe a generated tool-module input.
StreamChunkRepresent one runtime stream chunk.
buildStaticRouteModuleBuild one route module without filesystem discovery.
createRuntimeFetchHandlerAssemble a web-standard request handler.
describeConnectionTargetReduce a connection string to its scheme, host, port and database for logging.
errorStackOfFind the first stack trace in a thrown value's cause chain.
formatErrorChainRender a thrown value and its cause chain as operator-readable log lines.
normalizeMiddlewareModuleNormalize generated middleware exports.
normalizeThreadAccessModuleNormalize generated thread-access policy exports.
normalizeWsProxyNormalize a B4_PG_WS_PROXY value (host:port, ws://, or wss://) into the address and TLS flag the neon driver needs.
PostgresDriverName the Postgres driver a generated store factory opens (neon or pg).
PostgresDriverSelectionDescribe the driver decision and optional proxy target for one request.
readRuntimeEnvRe-export @b4run/core environment lookup.
seedB4ConfigRe-export @b4run/core static configuration seeding.
seedModelImporterRe-export the @b4run/langchain static importer seam; its deep reference is deferred.
seedRuntimeEnvRe-export @b4run/core environment seeding.
selectPostgresDriverDecide per request which driver talks to DATABASE_URL on the hono or vercel target; see Edge and Hono.
SelectPostgresDriverInputSupply DATABASE_URL, B4_PG_DRIVER, B4_PG_WS_PROXY, and the target to selectPostgresDriver.
serializeErrorRead the message, code and nested cause off any thrown value, including an ErrorEvent.
WsProxyTargetCarry a normalized proxy address and whether the WebSocket stays secure.

@b4run/cli/runtimeCopy link to section: @b4run/cli/runtime

ExportResponsibility
B4ResumeEntryDescribe one submitted interrupt decision.
normalizeThreadAccessResultCoerce a policy's return value into a decision the runtime can act on.
B4StaticModulesMap generated route modules.
MaterializeResolvedRouteGraphOptionsConfigure route graph materialization.
PendingInterruptDescribe a pending human decision.
PendingInterruptSnapshotSnapshot pending decisions for a thread.
PermissionDecisionRepresent a human permission decision.
PreparedRouteModulesHold prepared modules for a route.
ReadResponseFormatResultRepresent a parsed or rejected client response schema.
ResumeResolutionRepresent resolved resume input.
RuntimeFetchHandlerHandle runtime fetch requests.
RuntimeRegistryResolve materialized routes.
RuntimeRequestListenerHandle Node HTTP requests.
SandboxManagerManage runtime sandboxes.
ServeFallbackHandle requests the runtime does not own.
ServeGuardAnswer or pass every request before routing.
ServeHandleControl a composed dev server.
ServeOptionsConfigure a composed dev server.
ServeRuntimeHandleControl a running server.
ServeRuntimeOptionsConfigure production server boot.
StartRuntimeServerOptionsConfigure low-level server assembly.
StaticRouteModuleDescribe a generated route module.
StaticRouteModuleInputDescribe a route-module input.
StaticToolModuleInputDescribe a tool-module input.
StreamChunkRepresent one stream chunk.
__resetMaterializedAgentsForTestsReset LangChain materialization caches in tests.
__resetRouteLoadCachesForTestsReset route-loader caches in tests.
buildStaticRouteModuleBuild a static route module.
createRuntimeFetchHandlerAssemble the Node fetch handler.
createRuntimeRegistryConstruct a runtime route registry.
createRuntimeRequestListenerConstruct a Node request listener.
executeResolvedRouteExecute a resolved route.
invokeResolvedRouteInvoke a resolved route graph.
loadStaticModulesLoad generated route modules.
materializeResolvedRouteGraphMaterialize a resolved graph.
normalizeMiddlewareModuleNormalize middleware exports.
normalizeThreadAccessModuleNormalize thread-access policy exports.
readPendingInterruptsRead pending human decisions.
readResponseFormatParse a run body's hashbrown.responseSchema into a bound response format.
resolveCheckpointerResolve the configured checkpointer.
resolvePendingResumeResolve submitted interrupt decisions.
resolveSandboxManagerResolve the server sandbox manager.
resolveThreadsStoreResolve the configured thread store.
runMemoryCommandRun the low-level memory command implementation.
runTypegenGenerate application route declarations.
seedPreparedRouteModulesSeed prepared route modules.
serveServe the runtime's routes beside an application handler.
serveRuntimeStart the production runtime server.
startRuntimeServerAssemble and start the Node server.
streamResolvedRouteStream 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

ExportResponsibility
expectErrorDeprecated alias of @b4run/sdk/testing expectError.
expectMetaDeprecated alias of @b4run/sdk/testing expectMeta.
expectOutputDeprecated 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

ExportResponsibility
WithWorkspaceOptionsSelect source, provider, policy, and a private durable state directory.
cleanupWorkspacesRemove managed workspaces from an inactive, dedicated app installation with exclusive ownership and retryable deletion.
withWorkspaceRun host-authored work in a fresh managed workspace with durable cleanup.
ManagedWorkspaceReadOptionsName the worker app root, its provider, the thread to read, cancellation, and the reader identity.
openManagedWorkspaceReaderResolve a thread to its published managed workspace through the worker's installation store and open it read-only.
withManagedWorkspaceReaderOpen a managed workspace reader for a thread, hand it to an operation, and always close it.
readThreadWorkspaceRead a thread's workspace over a worker's Agent Protocol port (sandbox.workspaceRead: "http") and verify the answer.
ReadThreadWorkspaceOptionsName the root, omitted directories, required links, ignored prefixes, and limits of an HTTP workspace read.
ReadThreadWorkspaceInitCarry the request headers, cancellation, the expected source digest, the response-size cap, and an optional fetch.
ThreadWorkspaceReadReturn the thread id, its recorded source and intent digests, the root, and the inspection.
ThreadWorkspaceReadErrorReport 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.

ts
export declare function serveRuntime(opts: ServeRuntimeOptions): Promise<ServeRuntimeHandle>
ts
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

FieldTypeRequiredDescription
readonly appRootstringyesSelect the B4.run application root.
readonly hoststringnoOverride the listen host.
readonly portnumbernoOverride the listen port.
readonly installSignalHandlersbooleannoOpt into SIGTERM and SIGINT shutdown handlers.
readonly modulesB4StaticModulesnoSupply build-time generated route modules.
readonly configB4ConfignoSupply an already-constructed application configuration.
readonly checkpointerBaseCheckpointSavernoSupply the boot-resolved checkpointer.
readonly threadsStoreThreadsStorenoSupply the boot-resolved thread store.
readonly permissionsStorePermissionsStore | (() => Promise<PermissionsStore>)noSupply a permissions store or its async factory.
readonly memoryStore() => Promise<MemoryStore>noSupply the lazy memory-store factory.
readonly middlewareB4MiddlewarenoSupply preloaded middleware.
readonly threadAccessExpectedbooleannoRecord 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.

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