@b4run/sdk
Use this whenCopy link to section: Use this when
Start here when you build a B4.run application. @b4run/sdk owns the route-authoring types and helpers most application code uses. Use /pure only when an integration needs dependency-free path or hash utilities, and /testing when you write route scenarios for b4 test.
Install and importCopy link to section: Install and import
npm install @b4run/sdkimport { agent, defineMiddleware, defineMemory } from "@b4run/sdk"
import { pureJoin } from "@b4run/sdk/pure"
import { scenarios } from "@b4run/sdk/testing"Compatibility and audienceCopy link to section: Compatibility and audience
| Surface | Runtime | Purity | Audience | Stability |
|---|---|---|---|---|
@b4run/sdk | edge-safe | not-claimed | application | supported |
@b4run/sdk/pure | edge-safe | dependency-free | integration | supported |
@b4run/sdk/testing | node-only | not-claimed | testing | supported |
@b4run/sdk/tool-step.schema.json | package metadata | n/a | integration | supported |
@b4run/sdk/answer.schema.json | package metadata | n/a | integration | supported |
@b4run/sdk/testing is the route-scoped scenario API used by b4 test. It's not the @b4run/testing package, which provides a programmatic agent harness.
Public exportsCopy link to section: Public exports
@b4run/sdkCopy link to section: @b4run/sdk
| Export | Responsibility |
|---|---|
AgentConfig | Configure an agent route. |
ConstraintContext | Describe the live context passed to a tool constraint. |
ConstraintPredicate | Validate one tool call before execution. |
ConstraintVerdict | Express a constraint decision. |
B4Agent | Represent an authored agent route. |
DelegationConfig | Configure subagent delegation policy. |
DelegationConstraintPredicate | Validate a delegated request. |
DelegationContext | Describe a delegated request's live context. |
DelegationRequest | Describe a delegated input. |
DelegationRule | Express one named delegation policy. |
DelegationRules | Map subagent names to delegation policy. |
DelegationVerdict | Express a delegation constraint decision. |
ReasoningConfig | Configure model reasoning per provider. |
OpenAIReasoningConfig | Configure OpenAI reasoning effort and streamed summary. |
AnthropicReasoningConfig | Configure Anthropic extended thinking. |
RetryConfig | Configure model-call retry attempts and delay. |
SubagentMap | Map local subagent names to agents. |
ToolScope | Select and gate route tools. |
ApproveEntry | Name one tools.approve tool, or { tool, allowAlways: false } to approve every call. |
NormalizedApproveEntry | Describe a tools.approve entry as { tool, allowAlways }. |
normalizeApproveEntries | Normalize tools.approve entries to { tool, allowAlways }. |
agent | Declare an agent route. |
isB4Agent | Test whether a value is an authored B4.run agent. |
BackendAdapter | Define a route backend adapter contract. |
B4ErrorCode | Name a registered B4.run error. |
B4ErrorDescriptor | Describe a registered B4.run error. |
B4_ERRORS | Read the error descriptor registry. |
describeError | Look up an error descriptor. |
errorDocsUrl | Build the documentation URL for an error code. |
AnthropicModelId | Name a curated Anthropic model. |
GoogleModelId | Name a curated Google model. |
KnownModelId | Offer curated model autocomplete while accepting custom string IDs. |
OpenAiModelId | Name a curated OpenAI model. |
XaiModelId | Name a curated xAI model. |
ANTHROPIC_MODEL_IDS | List curated Anthropic model IDs. |
CURATED_MODEL_IDS | Map curated providers to model IDs. |
GOOGLE_MODEL_IDS | List curated Google model IDs. |
OPENAI_MODEL_IDS | List curated OpenAI model IDs. |
XAI_MODEL_IDS | List curated xAI model IDs. |
DefinedMemory | Represent a typed memory declaration. |
MemoryScopeDimension | Define one typed memory namespace dimension. |
defineMemory | Declare a typed long-term memory schema. |
ContinueResult | Continue middleware execution with optional context. |
B4Middleware | Define the middleware export contract: a handler or a lifecycle definition. |
MiddlewareDefinition | Define middleware with setup, dispose, handle, and after. |
MiddlewareAfterHook | Validate or replace the final assistant message of an AG-UI run. |
MiddlewareAfterRun | Describe what after receives: the final message and the allowed context. |
MiddlewareAfterResult | Express an after decision: keep, replace, or reject. |
MiddlewareAfterMessage | Describe one message of the conversation an after run was started with. |
ReplaceFinalMessageResult | Replace the final assistant message from after. |
MiddlewareHandler | Define the per-request middleware function. |
MiddlewareRequest | Describe a middleware request. |
MiddlewareSetupContext | Describe what setup receives. |
MiddlewareResult | Express a middleware decision. |
RejectResult | Stop middleware execution with a response. |
allow | Continue middleware execution. |
defineMiddleware | Preserve types for a middleware function or lifecycle definition. |
reject | Stop middleware execution. |
AuthDefinition | Declare the app's authentication: authenticate, plus optional setup, dispose and canReviewMemory. |
AuthRequest | Describe the request authenticate resolves: headers, method and url. |
AuthResult | Express what authenticate returns: a principal, undefined for anonymous, or a rejection. |
AuthSetupContext | Describe what an auth setup hook receives. |
B4Principal | Name the app's principal type, as b4 typegen declares it from src/auth.ts. |
B4PrincipalShape | Describe the smallest principal: an object with a string id. |
B4Register | Declare app types the SDK reads; b4 typegen adds principal. |
defineAuth | Declare and brand the app's authentication for src/auth.ts. |
isAuthDefinition | Tell a defineAuth value from any other object. |
B4ThreadAccess | Define one thread-access action handler. |
ThreadAccessAllow | Express an allow decision, optionally stamping a thread on create. |
ThreadAccessDeny | Express a deny decision with an optional status and body. |
ThreadAccessPolicy | Declare per-action thread authorization handlers. |
ThreadAccessRequest | Describe the thread request being authorized. |
ThreadAccessRequestedWorkspace | Describe the workspace an upload stages or a create chooses: the source digest, and on a create its links, baseline and uploadedBy, the stamps its uploads were allowed with. |
ThreadAccessResult | Express a thread authorization decision. |
ThreadAction | Name the coarse thread action being authorized. |
ThreadOperation | Name the specific endpoint operation being authorized. |
ThreadSubject | Describe the thread a decision is made about. |
THREAD_ACCESS_METADATA_KEY | Name the reserved metadata key holding the server-issued access stamp. |
defineThreadAccess | Preserve types for a thread access policy. |
ownedThreads | Build the common thread policy as a value: each caller reaches only the threads it created, and adminsRead principals may also read the rest. |
OwnedThreadsOptions | Configure ownedThreads: owner (the id a thread is stamped with; default principal.id) and adminsRead. |
ownedThreadsOptions | Read back the options an ownedThreads policy was built from, or undefined for any other policy. |
deny | Refuse a thread request. |
permit | Allow a thread request, optionally stamping it on create. |
ApprovalGrantMode | Name the approval-grant strictness: off, optional, or required. |
ApprovalGrantMinter | Mint one single-use approval grant for one parked interrupt. |
InterruptGrantRecord | Describe a stored grant row, which holds the hash and never the grant. |
InterruptGrantStore | Define the durable record of which parked approvals have been answered. |
InterruptGrantConsumption | Express the outcome of a conditional consume. |
APPROVAL_GRANT_MODES | List every approval-grant mode. |
APPROVAL_GRANT_MINTER_KEY | Name the run-config key the per-run minter travels under. |
APPROVAL_GRANT_PREFIX | Expose the b4ag_ prefix that makes a grant recognizable. |
APPROVAL_GRANT_BYTES | Expose the randomness, in bytes, behind one grant. |
isApprovalGrantMode | Validate an approval-grant mode. |
isApprovalGrantShape | Check a grant arriving on the wire before it is hashed. |
createApprovalGrant | Mint one grant and return its plaintext and hash. |
hashApprovalGrant | Hash a grant for storage and comparison. |
timingSafeHexEqual | Compare two hex digests in constant time. |
createMemoryInterruptGrantStore | Create the in-process grant store used by tests and storeless runtimes. |
ClientToolCallRecord | Describe one row of the tool-call record: a client-provided call the server issued and is waiting on, or a server tool call recorded for identity — with the route that issued it and, inside a subagent, the launching task call. |
ToolCallOrigin | Say where a server tool call was issued from when inside a subagent: the child route's key and the launching task call id. |
ClientToolCallStore | Define the durable record of tool calls on AG-UI runs: which client calls are outstanding, answered, or voided, and which server calls were issued and settled. |
ToolCallRecordKind | Tell a client tool call row from a server tool call row. |
ClientToolCallSettle | Express the outcome of settling a server tool call row. |
ClientToolCallAnswer | Express the outcome of answering a client tool call. |
ClientToolRecorder | Record a tool call before it runs or its turn parks, and settle a server call afterward. |
CLIENT_TOOL_RECORDER_KEY | Name the run-config key the per-run client tool recorder travels under. |
createMemoryClientToolCallStore | Create the in-process client tool call store used by tests and embedders. |
encodeClientToolResult | Encode a client tool result for a store's text column: text as itself, a part list as a self-describing JSON envelope. |
decodeClientToolResult | Decode a stored client tool result: an envelope back to its parts, anything else as the text it is. |
B4ContentPart | Describe one AG-UI 1.0 content part: a B4TextPart or a B4MediaPart. |
B4TextPart | Describe a text content part. |
B4MediaPart | Describe an image, audio, video or document part and its source. |
B4MediaPartType | Name the four media part types. |
B4PartSource | Describe where a media part's bytes come from: inline data, a URL, or a provider file handle. |
B4DataSource | Describe inline base64 bytes with their mimeType. |
B4UrlSource | Describe a URL the provider fetches; B4.run never fetches it. |
B4FileSource | Describe a file handle issued by a model provider, optionally naming that provider. |
B4MessageContent | Describe what a user or tool message carries: a string or an ordered list of content parts. |
isContentPart | Check that an unvalidated value is a structurally valid content part. |
isContentPartArray | Check that an unvalidated value is an array of valid content parts. |
contentPartsText | Read a message's text: a string as is, or a part list's text parts in order. |
BuiltInModelProviderId | Name a built-in model provider. |
ModelProviderId | Name a built-in or custom model provider. |
inferProvider | Infer a provider from a model ID. |
SUPPORTED_AGENT_PROVIDERS | List providers built into agent materialization. |
RouteConfig | Describe route metadata. |
RouteKind | Name a supported route kind. |
RouteStateMap | Expose an open compatibility interface for route state. |
RouteToolMap | Expose an open compatibility interface for route tools. |
RuntimeContext | Provide request-scoped runtime data. |
RuntimeTool | Describe a runtime tool callable. |
ToolRegistry | Map runtime tool names to callables. |
Prettify | Flatten an object type for editor display. |
ModelIdValidation | Represent advisory model-ID validation. |
validateModelId | Check a model ID against curated suggestions. |
B4ToolContext | Provide context to a B4.run tool. |
WorkspaceFs | Define the workspace filesystem contract exposed to tools. |
WorkspaceContext | Supply trusted managed workspace identity, provenance, and permission-bound initial reads. |
ToolDisplay | Describe how a tool call reads to a person (icon, running/done/failed labels, sources). |
ToolDisplayIcon | Name one of the fixed step icons. |
ToolDisplaySource | Describe a file, URL or record a call drew on. |
TOOL_DISPLAY_ICONS | List the fixed step icon names. |
TOOL_DISPLAY_LABEL_MAX | Cap a step label's length. |
describeToolDisplayProblem | Name what is wrong with a display export, or nothing. |
isToolDisplayIcon | Narrow a string to a step icon name. |
ToolDenial | Describe a denied tool call's result: the reason the model receives, branded. |
TOOL_DENIAL | Name the symbol key that brands a denied tool call's result. |
toolDenial | Brand a denial reason as a tool result; the model still reads the reason as plain text. |
isToolDenial | Tell a denied tool call's result from a successful one. |
B4ToolStep | The versioned b4.step contract for one tool call: v: 1, kind, status, label, icon, queries, sources, start and settle times, error and gate decision. |
B4ToolStepStatus | Name a step status: running, completed, failed, denied or cancelled. |
B4ToolStepRead | A step read from the wire, whose status is absent when the producer sent one this reader does not know. |
B4ToolStepUpdate | A partial step for mergeToolStep; status and kind may be absent. |
B4StepSource | A file, URL, document or record a step or answer drew on, with a stable id. |
B4AnswerAnnotations | The b4.answer annotations on a final answer: citations, uncited sources, attribution. |
B4_STEP_METADATA_KEY | The message-metadata key a tool call's step travels under (b4.step). |
B4_ANSWER_METADATA_KEY | The message-metadata key a final answer's annotations travel under (b4.answer). |
B4_STEP_EVENT_NAME | The AG-UI CUSTOM event name a live step travels as (b4.step). |
B4_STEP_VERSION | The contract's major version (1). Additive changes never bump it. |
B4_TOOL_STEP_STATUSES | List every step status. |
B4_BUILTIN_TOOLS | List the recommended builtin values for provider tools; the field stays an open string. |
B4_TOOL_STEP_JSON_SCHEMA | The JSON Schema for a b4.step value. |
B4_ANSWER_JSON_SCHEMA | The JSON Schema for b4.answer annotations. |
readToolStep | Normalize a b4.step value (legacy shapes included) to a step; an unknown status is dropped, and an unusable value returns undefined. |
readToolStepUpdate | Like readToolStep, but kind stays absent when the source did not state it, so a merge keeps the stored kind. |
readAnswerAnnotations | Normalize b4.answer annotations. |
mergeToolStep | Merge a step from a call or a message into the stored step by the contract's rules. |
settleOpenSteps | Settle running steps at a run's end: failed after an error, cancelled after a cancel or interrupt, sparing the interrupt's open calls. |
B4_STEP_KEY | The additional_kwargs key under which every ToolMessage persists its v1 B4ToolStep (b4_step); read old and new values with readToolStep. |
B4_SUBAGENT_KEY | The additional_kwargs key under which a task ToolMessage persists the subagent it launched (b4_subagent). |
B4_TURN_METADATA_KEY | The checkpoint-metadata key under which the runtime stamps how a turn ended (b4:turn). |
GateDecision | How a permission gate was answered: once, always or deny. |
PersistedStep | Deprecated: use B4ToolStep. The step a ToolMessage persists: status (completed, failed or denied), icon, label, sources, start and settle times, and the gate decision. |
PersistedSubagent | The subagent a task call launched: name, route, description, depth, child checkpoint namespace, outcome and error. |
PersistedTurnEnd | How and when a turn ended, stamped on the head checkpoint's metadata. |
readPersistedStep | Deprecated: use readToolStep. Validate a b4_step value; invalid optional fields are dropped, a missing identity returns undefined. |
readPersistedSubagent | Validate a b4_subagent value. |
readPersistedTurnEnd | Validate a b4:turn value. |
@b4run/sdk/pureCopy link to section: @b4run/sdk/pure
| Export | Responsibility |
|---|---|
POSIX_SEP | Expose the portable path separator. |
pureBasename | Read the last path component. |
pureDirname | Read the parent path. |
pureJoin | Join path segments without Node dependencies. |
pureRelative | Compute one portable relative path. |
pureResolve | Resolve portable path segments. |
sha1Hex | Compute a SHA-1 hexadecimal digest. |
sha256Hex | Compute a SHA-256 hexadecimal digest. |
@b4run/sdk/testingCopy link to section: @b4run/sdk/testing
| Export | Responsibility |
|---|---|
TOOL_STEP_FIXTURES | List the b4.step fixture corpus: named event sequences with the steps and answers they must fold to. |
ToolStepFixture | Describe one fixture: its name, events and expected result. |
ToolStepFixtureEvent | Describe one AG-UI event in a fixture. |
ToolStepFolded | Describe the steps and answers a fold produces. |
foldToolStepEvents | Fold fixture events into steps and answers; a reference implementation for a client's own reducer. |
RouteScenarioMap | Receive generated route-to-tool augmentation. |
RuntimeErrorExpectation | Describe an expected scenario error. |
RuntimeExecutionBaseResult | Share fields across scenario execution results. |
RuntimeExecutionError | Describe a failed execution error. |
RuntimeExecutionErrorKind | Name a runtime failure kind. |
RuntimeExecutionFailureResult | Represent a failed execution. |
RuntimeExecutionMode | Name the materialized route mode. |
RuntimeExecutionResult | Represent either execution outcome. |
RuntimeExecutionSuccessResult | Represent a successful execution. |
RuntimeExecutionTiming | Describe execution timing. |
RuntimeMetaExpectation | Describe expected runtime metadata. |
ScenarioDescriptor | Represent one authored scenario. |
ScenarioSuiteBuilder | Build route-scoped scenarios fluently. |
ScenarioSuiteDescriptor | Represent a completed scenario suite. |
ScenarioToolCallExpectationDescriptor | Describe an expected tool call. |
ScenarioToolCallRecord | Record an observed tool call. |
ScenarioToolMockDescriptor | Describe a mocked tool response. |
expectError | Assert a failed runtime result. |
expectMeta | Assert selected runtime metadata. |
expectOutput | Assert a successful runtime output. |
isScenarioSuite | Test whether a value is a scenario suite. |
readScenarioSuite | Read a scenario suite descriptor. |
scenarios | Start a typed scenario suite for a route. |
@b4run/sdk/tool-step.schema.jsonCopy link to section: @b4run/sdk/tool-step.schema.json
The JSON Schema of a b4.step value, as data for tooling and for producers in other languages. It is the same schema as B4_TOOL_STEP_JSON_SCHEMA. It has no TypeScript exports, runtime classification, or purity claim. Don't execute it as application code.
@b4run/sdk/answer.schema.jsonCopy link to section: @b4run/sdk/answer.schema.json
The JSON Schema of b4.answer annotations, as data for tooling and for producers in other languages. It is the same schema as B4_ANSWER_JSON_SCHEMA. It has no TypeScript exports, runtime classification, or purity claim. Don't execute it as application code.
Key contractsCopy link to section: Key contracts
agent() and AgentConfigCopy link to section: agent() and AgentConfig
Use agent() as a route module's default export. model and systemPrompt are required. Optional policy, retry, reasoning, subagent, and tool fields are preserved on the branded descriptor.
export declare function agent<const Subagents extends SubagentMap = {}>(
config: AgentConfig<Subagents>,
): B4Agent<Subagents>export interface AgentConfig<Subagents extends SubagentMap = {}> {
readonly delegation?: DelegationConfig<NoInfer<Extract<keyof Subagents, string>>>
readonly description?: string
readonly model: KnownModelId
readonly provider?: ModelProviderId
readonly reasoning?: ReasoningConfig
readonly retry?: RetryConfig
readonly recursionLimit?: number
readonly subagents?: Subagents
readonly tools?: ToolScope
readonly systemPrompt: string
}Fields: @b4run/sdk#.:AgentConfig
| Field | Type | Required | Description |
|---|---|---|---|
readonly delegation | DelegationConfig<NoInfer<Extract<keyof Subagents, string>>> | no | Control dispatch to named subagents. |
readonly description | string | no | Describe the agent for selection. |
readonly model | KnownModelId | yes | Select the model. |
readonly provider | ModelProviderId | no | Override provider inference. |
readonly reasoning | ReasoningConfig | no | Tune reasoning per provider. |
readonly retry | RetryConfig | no | Tune transient retry behavior. |
readonly recursionLimit | number | no | Cap LangGraph super-steps. |
readonly subagents | Subagents | no | Register child agents by name. |
readonly tools | ToolScope | no | Scope and gate tools. |
readonly systemPrompt | string | yes | Set the agent's system instruction. |
Behavior contract sdk.agent.descriptor-shape
agent() returns a branded descriptor and includes optional tool scope only when supplied.
Agent configuration signatures
export interface ReasoningConfig {
readonly openai?: OpenAIReasoningConfig
readonly anthropic?: AnthropicReasoningConfig
}Fields: @b4run/sdk#.:ReasoningConfig
| Field | Type | Required | Description |
|---|---|---|---|
readonly openai | OpenAIReasoningConfig | no | Apply when the route resolves to OpenAI. |
readonly anthropic | AnthropicReasoningConfig | no | Apply when the route resolves to Anthropic. |
export interface OpenAIReasoningConfig {
readonly effort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh"
readonly summary?: "auto" | "concise" | "detailed"
}Fields: @b4run/sdk#.:OpenAIReasoningConfig
| Field | Type | Required | Description |
|---|---|---|---|
readonly effort | "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | no | Set the request's reasoning effort. |
readonly summary | "auto" | "concise" | "detailed" | no | Stream a reasoning summary on the Responses API. |
export interface AnthropicReasoningConfig {
readonly budgetTokens: number
}Fields: @b4run/sdk#.:AnthropicReasoningConfig
| Field | Type | Required | Description |
|---|---|---|---|
readonly budgetTokens | number | yes | Enable extended thinking with this token budget (at least 1024). |
export interface RetryConfig {
readonly maxAttempts?: number
readonly baseDelay?: number
}Fields: @b4run/sdk#.:RetryConfig
| Field | Type | Required | Description |
|---|---|---|---|
readonly maxAttempts | number | no | Set attempts per model call; defaults to 3. |
readonly baseDelay | number | no | Set the first capacity rate-limit backoff; defaults to 1000. |
export declare function isB4Agent(value: unknown): value is B4Agentallow() and reject()Copy link to section: allow() and reject()
Middleware returns an explicit continue or reject result. Use allow(context?) to continue and reject(status, body?) to stop the request.
defineMiddleware accepts either the handler function or a lifecycle
definition with optional setup(ctx) and dispose() hooks around handle.
setup runs once, lazily, before the first gated request and is retried on the
next request if it rejects. dispose runs from the Node runtimes' shutdown
path. See Lifecycle hooks. The definition
may also carry after(run), which receives an AG-UI run's final assistant
message with the allowed context and may keep, replace, or reject(...) it
before the client sees it. See
Validating the final assistant message.
export declare function defineMiddleware<T extends B4Middleware>(middleware: T): Texport declare function allow(context?: Record<string, unknown>): ContinueResultexport declare function reject(status: number, body?: unknown): RejectResultBehavior contract sdk.middleware.result-shapes
allow() and reject() return discriminated result objects; omitted context and body properties are absent.
defineAuth()Copy link to section: defineAuth()
src/auth.ts must default-export the result. authenticate runs once per
request, before middleware and the thread-access policy, and its principal
reaches middleware and the policy as req.principal and every tool as
ctx.principal. See Authentication.
export declare function defineAuth<P extends B4PrincipalShape>(definition: AuthDefinition<P>): AuthDefinition<P>
export declare function isAuthDefinition(value: unknown): value is AuthDefinitionvalidateModelId()Copy link to section: validateModelId()
Flags likely model-ID typos. It does not restrict custom model IDs.
export declare function validateModelId(opts: {
readonly model: string
readonly provider?: string
}): ModelIdValidationBehavior contract sdk.validate-model-id.advisory
Model validation is advisory: curated near-misses return provider-specific suggestions, while an uncurated or unresolved provider returns ok: true.
Application guidance
Treat ok: false as a warning for application feedback, not a runtime gate.
RouteConfigCopy link to section: RouteConfig
runtime, streaming, and tags are reserved metadata and don't change execution. Select deployment runtime with build.targets, select streaming through the endpoint or transport, and do not rely on tags for behavior.
export interface RouteConfig {
readonly runtime?: "node" | "edge"
readonly streaming?: boolean
readonly tags?: readonly string[]
}Fields: @b4run/sdk#.:RouteConfig
| Field | Type | Required | Description |
|---|---|---|---|
readonly runtime | "node" | "edge" | no | Reserved; has no effect. |
readonly streaming | boolean | no | Reserved; has no effect. |
readonly tags | readonly string[] | no | Reserved; has no effect. |
defineMemory()Copy link to section: defineMemory()
Declare the typed schema, kind, and namespace dimensions for a route's memory.ts module. identity is optional. Semantic memory defaults its reconciliation identity elsewhere.
export declare function defineMemory<S extends z.ZodTypeAny>(def: {
kind: DefinedMemory["kind"]
scope: readonly MemoryScopeDimension[]
schema: S
identity?: readonly string[]
}): DefinedMemory<S>Choosing a surfaceCopy link to section: Choosing a surface
Application routes normally import the root. Use /pure for infrastructure that must avoid runtime dependencies. Use /testing in *.scenario.ts files, and @b4run/testing when a test needs a programmatic harness.
Trusted initial sourceCopy link to section: Trusted initial source
An authored tool's optional ctx.workspace is present only for an admitted
managed workspace. It exposes id, sourceDigest, the pinned environment, an
optional baselineCommit, and readInitialFile(path): Promise<Uint8Array>.
Initial reads use the same read permission policy as ordinary file reads and
return independently owned bytes. The context has no provider handle or lifecycle
methods and cannot select another thread's source.
Use ctx.fs for current files. ctx.fs.stat(path) inspects entry kind,
size, executable mode, and a symlink's target without following the leaf link;
custom backends must supply lstat to support it.
Examples and related guidesCopy link to section: Examples and related guides
import { agent } from "@b4run/sdk"
export default agent({
model: "gpt-5-mini",
systemPrompt: "Answer concisely.",
})Continue with Agents, Middleware, Long-term Memory, Scenario Testing, and Agent Test Harness.