@b4run/core

Use this whenCopy link to section: Use this when

Route authors normally use @b4run/sdk, not Core. Use @b4run/core when you build a B4.run integration around configuration, capabilities, static type generation, or route metadata. Use /node for filesystem discovery and compiler-backed extraction. Do not build application code on /internal/compiler.

Install and importCopy link to section: Install and import

bash
npm install @b4run/core
ts
import { config, renderB4Types } from "@b4run/core"
import { discoverRoutes } from "@b4run/core/node"

Compatibility and audienceCopy link to section: Compatibility and audience

SurfaceRuntimePurityAudienceStability
@b4run/coreedge-safenot-claimedintegrationlow-level
@b4run/core/nodenode-onlynot-claimedintegrationlow-level
@b4run/core/internal/compilernode-onlynot-claimedinternalinternal

Importing /node registers the disk-backed b4.config.ts loader. The root stays free of that filesystem loader, so a static runtime can seed configuration instead.

Public exportsCopy link to section: Public exports

@b4run/coreCopy link to section: @b4run/core

ExportResponsibility
ThreadsStoreRe-export the @b4run/sqlite-storage thread-store contract; its deep reference is deferred.
createAgentsMdMarkerCreate the AGENTS.md capability marker.
createMemoryMarkerCreate the typed-memory capability marker.
createMemoryMdMarkerCreate the memory.md capability marker.
MAX_MEMORY_BYTESCap the size of a route memory.md.
RuntimeTodoDescribe one runtime plan item.
createPlanningMarkerCreate the planning capability marker.
MAX_PLAN_BYTESCap the size of a route plan.md.
createSkillsMarkerCreate the skills capability marker.
createSubagentsMarkerCreate the subagents capability marker.
createWorkspaceMarkerCreate the workspace capability marker.
BuildTargetNameName the known b4 build targets as a union (`"node"
BUILD_TARGET_NAMESList the known b4 build target names; the tuple BuildTargetName is derived from.
isBuildTargetNameNarrow an untyped string to a known b4 build target name.
BUILT_IN_TOOL_NAMESList built-in capability tool names.
ClientToolCallEnvelopeDescribe the interrupt envelope a parked client tool call leaves in the checkpoint.
ClientToolDefinitionDescribe a client-provided tool definition after envelope validation.
ClientToolResumeValueDescribe the value the internal resume delivers to a parked client tool call.
ClientToolStubOptionsOptions for createClientToolStub, such as a replay-only stub.
ABANDONED_CLIENT_TOOL_RESULTThe tool result recorded for a client tool call the client never answered.
CLIENT_TOOL_CALL_TYPEThe interrupt envelope type of a parked client tool call.
CLIENT_TOOL_PREFIXThe model-visible prefix of every client tool name (client_).
CLIENT_TOOL_UNAVAILABLE_RESULTThe tool result for a new call to a replay-only stub whose tool was not offered on this run.
clientToolInterruptIdDerive the stable interrupt id of a client tool call from its provider tool-call id.
createClientToolStubCreate the stub tool that gates, records and parks a client tool call.
gateClientToolOpGate a client tool call under the clientTool permission key.
isClientToolCallEnvelopeNarrow an interrupt value to a client tool call envelope.
MissingClientToolRecorderErrorThrown when a client tool call would park with no recorder to answer it.
MemorySupersedeDetailDescribe a gated memory supersede.
SubagentGateRequestDescribe a gated subagent operation.
gateMemorySupersedeGate a memory supersede operation.
gateSubagentOpGate a subagent operation.
gateToolOpGate a tool operation.
wrapToolWithApprovalWrap a tool with approval handling.
wrapToolWithConstraintWrap a tool with argument constraints.
AppliedContributionRecord an applied capability contribution.
ApplyResultReturn contributions and capability errors.
CapabilityErrorDescribe capability detection or load failure.
CapabilityRegistryHold capability markers.
applyCapabilitiesDetect and load registered capabilities.
createCapabilityRegistryConstruct a capability registry.
BrowseFilterLikeDefine a memory browse filter boundary.
BrowsePageLikeDefine a memory browse page boundary.
BrowseQueryLikeDefine a memory browse query boundary.
BrowseSortEntryLikeDefine a memory sort entry boundary.
BrowseSortFieldLikeName memory browse sort fields.
CapabilityContributionDescribe capability-provided runtime features.
CapabilityMarkerDefine capability detection and loading.
CapabilityMarkerContextProvide capability marker context.
B4ToolDefinitionDescribe a contributed B4.run tool.
EmbedderDefine the memory embedding seam.
MarkerFsDefine capability filesystem operations.
StaticMarkerFilesDescribe bundled marker file bodies.
staticMarkerFsServe bundled marker files without a filesystem.
MemoryContextProvide memory tool context.
MemoryKindLikeName memory kinds at the Core boundary.
MemoryRecordLikeDescribe a memory record at the Core boundary.
MemorySourceTypeLikeName memory source types.
MemoryStatusLikeName memory statuses.
MemoryStoreLikeDefine the runtime memory-store boundary.
MemoryWritesModeConfigure runtime memory writes.
PromptFragmentDescribe capability prompt text.
StreamTransformerTransform runtime stream chunks.
StreamTransformerInputDescribe a stream-transform input.
StreamTransformerOutputDescribe a stream-transform output.
CreateWorkspaceFsOptionsConfigure workspace filesystem creation.
createWorkspaceFsCreate a workspace filesystem facade.
B4ConfigLoaderDefine the configuration loader seam.
B4AppErrorDescribe an app-root or route-entry failure that carries a B4_Exxxx code.
NamespaceListingCheckpointerA checkpointer that enumerates a thread's checkpoint namespaces; B4's savers implement it, GET /threads/:id/turns requires it.
canListNamespacesWhether a checkpointer implements listNamespaces.
UnresolvedToolInputTypeErrorThrown by tool-schema extraction when a tool's declared input type resolves to any/unknown or depends on an import that does not resolve; the message names the tool file, the type, and the tsconfig used.
UnresolvedToolInputTypeDetailsThe structured details on UnresolvedToolInputTypeError: tool name, file, type text, what it resolved to, unresolved imports, and the tsconfig path.
UnresolvedImportOne unresolved module specifier or member from the compiler, with its diagnostic text.
__clearB4ConfigCacheForTestsClear the config memo in tests.
loadB4ConfigLoad or read a memoized app configuration.
registerConfigLoaderRegister a runtime-specific config loader.
seedB4ConfigSeed configuration for a static runtime.
configPreserve types for a B4.run config object.
isPrivateSegmentTest whether a route segment is private.
isRouteGroupSegmentTest whether a route segment is a group.
toRouteSegmentsParse filesystem route segments.
RuntimeEnvDescribe seeded runtime environment values.
__clearSeededRuntimeEnvForTestsClear seeded environment values in tests.
readRuntimeEnvRead process or seeded environment values.
seedRuntimeEnvSeed environment values for a static runtime.
ResolveStateFieldsOptionsConfigure state-field resolution.
resolveStateFieldsNormalize state defaults and reducers.
GuardedSubagentResultRepresent a gated subagent result.
ResolveGuardedSubagentArgsConfigure guarded subagent resolution.
resolveGuardedSubagentResolve a subagent under policy.
ResolveSubagentRegistryArgsConfigure subagent registry resolution.
dispatchableSubagentsList subagents eligible for dispatch.
resolveSubagentRegistryResolve local and conventional subagents.
DescriptorRouteIndexIndex route descriptors for subagents.
ResolvedDelegationRuleRepresent a resolved delegation rule.
ResolvedSubagentRepresent one resolved subagent.
ScopeInputConfigure route tool scoping.
ToolOriginIdentify where a tool came from.
impliedToolDenialsList tools a scope withholds through an implied deny.
resolveToolScopeApply route tool policy.
toolOriginRead a tool's origin.
renderB4TypesRender the complete generated route module.
renderRouteTypesRender route path and parameter types.
renderScenarioTypesRender scenario map augmentation.
SCENARIO_TYPES_FILEName the generated scenario declaration file.
RouteStateFieldsDescribe generated state fields for one route.
renderStateTypesRender route state types.
renderToolTypesRender route tool types.
CorsConfigConfigure cross-origin access to the runtime.
B4ConfigConfigure a B4.run application.
configureApprovalGrantsRaise the process-wide approval-grant mode.
approvalGrantModeRead the approval-grant mode in force in this process.
mintGrantForParkMint the grant for a park, or fail closed when one is required.
MissingApprovalGrantMinterErrorReport a required grant that no minter could issue.
__resetApprovalGrantsForTestsDrop the approval-grant latch so a suite can exercise every mode.
VercelBuildConfigDescribe the vercel target's static assets, extra functions, and routes (build.vercel).
VercelBuildRouteOne Build Output route with a required src.
DiscoveredB4AppDescribe a located B4.run application.
DiscoverRoutesOptionsConfigure route discovery.
ExtractedToolSchemaDescribe one extracted JSON tool schema.
ExtractedToolTypeDescribe one extracted tool type.
FindB4AppOptionsConfigure application-root discovery.
JsonSchemaPropertyDescribe a JSON Schema property.
LoadB4ConfigOptionsSelect the application whose config is loaded.
LoadedB4ConfigReturn config, root, and config path.
NormalizedRouteModuleDescribe a normalized route module.
ResolvedStateFieldDescribe a normalized state field.
RouteDefinitionDescribe one discovered route.
RouteKindRe-export the @b4run/sdk route-kind type.
RouteManifestDescribe all routes in an application.
RouteSegmentDescribe a static or dynamic route segment.
RouteToolSchemasGroup extracted schemas by route.
RouteToolTypesGroup extracted tool types by route.
StateFieldReducerName a built-in state reducer.

@b4run/core/nodeCopy link to section: @b4run/core/node

ExportResponsibility
loadB4ConfigUncachedLoad b4.config.ts directly from disk.
registerNodeConfigLoaderRegister the disk-backed config loader.
registerTsxLoaderRegister TypeScript module loading.
discoverRoutesDiscover filesystem routes.
assertB4RoutesDirValidate the routes directory.
findB4AppLocate a B4.run application root.
nodeMarkerFsProvide Node filesystem operations to capability markers.
ExtractToolSchemasOptionsConfigure compiler-backed schema extraction. Optional appRoot (where the nearest tsconfig.json search starts; defaults to routeDir) and tsconfig (an explicit config to compile with).
extractToolSchemasForRouteExtract tool schemas for a route. Throws UnresolvedToolInputTypeError when a declared input type resolves to any/unknown.
ExtractToolTypesOptionsConfigure compiler-backed type extraction; accepts the same appRoot and tsconfig options.
extractToolTypesForRouteExtract tool types for a route.

@b4run/core/internal/compilerCopy link to section: @b4run/core/internal/compiler

This subpath is internal and carries no compatibility promise. The CLI uses it during type generation.

Key contractsCopy link to section: Key contracts

loadB4Config()Copy link to section: loadB4Config()

Use this low-level seam when an integration owns configuration loading.

ts
export declare function loadB4Config(options: LoadB4ConfigOptions): Promise<LoadedB4Config>

Behavior contract core.load-config.failed-load-eviction

loadB4Config memoizes per app root. A failed in-flight load is evicted only while that same promise remains cached, so a seed written during the load survives its later rejection.

resolveStateFields()Copy link to section: resolveStateFields()

Turns state defaults and optional reducer overrides into the normalized fields that type generation and runtime state assembly consume.

ts
export declare function resolveStateFields(
  options: ResolveStateFieldsOptions,
): readonly ResolvedStateField[]

Behavior contract core.state.reducer-resolution

resolveStateFields infers append for array defaults and replace for scalar defaults, honors explicit reducer overrides, and sorts fields by name.

Configuration ownershipCopy link to section: Configuration ownership

See Configuration Reference for the full B4Config schema. The root loader is a runtime seam: Node callers import /node to register disk loading, and edge callers seed a constructed config.

ts
import { config } from "@b4run/core"
 
export default config({
  appDir: "src/app",
  build: { targets: ["node"] },
})

Continue with Configuration Reference, Routes, State, and b4:routes.