Skip to content
Cavemandocs
Apache-2.0

API reference

Every exported entrypoint, package, and command.

Every entrypoint @caveman-ai/agent publishes, the values each one exports, the sibling packages, and the caveman-agent commands. Signatures are from the 0.2.0 source; type-only exports are named in the group they belong to rather than listed one by one.

typescript
import { agent, auto, run, schema, tool } from "@caveman-ai/agent";
import { createAgentServer } from "@caveman-ai/agent/serve";
import { SqlDurableStore } from "@caveman-ai/agent/durable";

Entrypoints#

Import pathWhat is behind it
@caveman-ai/agentThe runtime: definitions, tools, runs, receipts, memory, compaction, context IR.
/builddefineBuild, compile, the lock parsers and the digest helpers.
/compilerThe profiled compiler and its capability lattice.
/profileWorkload profiles built from normalized trajectories.
/serveThe Node session server.
/serve-handlerThe same server as a web-standard fetch(Request) handler.
/durableJournals, stores and the replay validators.
/codeThe coding agent, its sessions, and its bill formatting.
/command-sessionThe command-session runtime behind interactive clients.
/execution-backendLocal and HTTP execution backends for tool code.
/pluginsSkill and plugin loading (agent-environment).
/compactionThe compaction primitives and the evaluation harness.
/memoryThe memory engine, adapters and the file store helpers.
/connectCaveman Connect: provider data through one tool.
/programmatic-toolsThe caveman_code runtime.
/adaptersObservability adapters for other harnesses.
/wirecreateCavemanTransport, a spend ceiling on your own fetch.
/model-boundaryMiddleware around the provider call.
/model-usageUsage parsing and accounting status.
/inputAgentInput parts, limits and encoders.
/run-receiptThe receipt schema id and its parser.
/catalogPublic price catalog lookups and digests.
/clauderunClaudeAgent, the Claude harness.
/testingfauxModel and scriptedStream.
/cache-engineThe cache planner's internals. Not part of the runtime's own exports.

Define an agent#

ExportSignature
agentagent(options): AgentDefinition
subagentsubagent(options): ToolDefinition
tooltool(options): ToolDefinition
schemaTypeBox builders: object, array, string, number, integer, boolean, literal, union, optional, null, any
autoauto(): Auto
AUTOThe symbol an Auto carries.
filefile(path: string): FileSource
contextcontext(options): ContextDefinition
memorymemory(options): MemoryDefinition
memoryTTLMillisecondsmemoryTTLMilliseconds(value: string): number
outputoutput(options): OutputDefinition
artifactartifact(options?): ArtifactDefinition
evalFixture, evalevalFixture(options): EvalDefinition, and the same function under eval
assertQualityGraderassertQualityGrader(grader: unknown): asserts grader is QualityGrader
applyAgentDefinitionTransformsapplyAgentDefinitionTransforms(definition, transforms): AgentDefinition
shellToolsshellTools(options: ShellToolsOptions): ToolDefinition[]
routineroutine(original, impl, opts?): ToolDefinition
routineOutcomesroutineOutcomes(): readonly RoutineOutcomeCount[]
loadAgentDirloadAgentDir(rootDir, options?): Promise<AgentDefinition>
composeAgentDircomposeAgentDir(input: AgentDirModules): AgentDefinition
AGENT_DIR_ENTRY".caveman/agent-dir-entry.mjs"

Types: AgentDefinition, AgentDefinitionTransform, AgentOutput, AgentDirConfig, AgentDirContextValue, AgentDirModules, AgentDirRunDefaults, ToolDefinition, ToolOptions, ToolEffect, ToolResultPolicy, ToolExecutionContext, ArtifactDefinition, OutputDefinition, ContextDefinition, ContextKind, ContextStability, CacheRegion, SafetyClass, PrivacyClass, RecoveryKind, MemoryDefinition, EvalDefinition, EvalSplit, EvalGuardrail, QualityGrader, FileSource, Auto, ShellToolName, ShellToolsOptions.

Run#

ExportSignature
runrun(definition, input, options?): Promise<RunResult<AgentOutput<D>>>
streamstream(definition, input, options?): AsyncGenerator<CavemanRunEvent>
runLockedrunLocked(definition, input, build, options?): Promise<RunResult>
createConversationcreateConversation(): Conversation
AgentRunControllerQueue, steering and interrupt handle for an active run.
CavemanRunErrorError with code and the partial receipt.
agentStaticContextDiagnosticsagentStaticContextDiagnostics(definition, rootDir?): Promise<AgentStaticContextDiagnostics>
verifySandboxConformanceverifySandboxConformance(): Promise<boolean>
decideToolCalldecideToolCall(policy, input): Promise<ToolCallDenial | undefined>
TOOL_POLICY_TIMEOUT_MSThe ceiling a tool policy has to answer within.
resolveEgressPolicyresolveEgressPolicy(policy: SandboxEgressPolicy): ResolvedEgressPolicy
egressAllowedegressAllowed(policy, host, port): boolean

Types: RunOptions, RunResult, CavemanRunEvent, ConversationState, RunBudget, RunStopReason, BudgetDenomination, BudgetController, BudgetTranche, BudgetExhaustionContext, BudgetExhaustionHandler, ModelCallRouter, ModelCallRouteInput, ModelCallRouteDecision, RunBreakers, BreakerEvent, ToolCallPolicy, ToolCallPolicyInput, ToolCallDecision, ToolCallDenial, SandboxEgress, SandboxEgressPolicy, ResolvedEgressPolicy.

Receipts and budget#

ExportSignature
renderReceiptrenderReceipt(receipt: ReceiptLike): string
AGENT_RUN_RECEIPT_SCHEMA"caveman.agent.run-receipt.v1"
defineRunReceiptdefineRunReceipt(value: unknown): RunReceipt
validateRunReceiptThe same parser under a name that reads better at a check.
createBudgetControllercreateBudgetController(): BudgetController
OUTPUT_CLAMP_FLOOR_TOKENS256

Types: RunReceipt, ReceiptCall, ReceiptTool, ReceiptCompaction, ReceiptResume, ReceiptLike, ReceiptPrintCall.

Memory#

ExportSignature
MemoryEngineThe engine class: remember, recall, search, searchSessions, forget, link, consolidate, beginTurn, endTurn, flush, endSession.
createMemoryEnginecreateMemoryEngine(options: CreateMemoryEngineOptions): MemoryEngine
createMemoryWorkflowcreateMemoryWorkflow(engine, sessionId)
createFileMemoryAdaptercreateFileMemoryAdapter(config?: { root?: string }): MemoryStorageAdapter
createInMemoryMemoryStoragecreateInMemoryMemoryStorage(): MemoryStorageAdapter
createSparseEmbeddingAdaptercreateSparseEmbeddingAdapter(dimensions?): MemoryEmbeddingAdapter
openAICompatibleMemoryEmbeddingopenAICompatibleMemoryEmbedding(options): MemoryEmbeddingAdapter
completionMemorySidecarcompletionMemorySidecar(options): MemorySidecarAdapter
emptyMemoryStateemptyMemoryState(): MemoryState
packVectorpackVector(adapter, input): MemoryVector
cosinecosine(first, second): number

@caveman-ai/agent/memory adds memoryFilePath, readMemoryState and the other file-store helpers. Types: MemoryRecord, MemoryState, MemoryScope, MemoryHit, MemoryRecall, MemoryStorageAdapter, MemoryEmbeddingAdapter, MemorySidecarAdapter, MemoryRuntimeConfig, MemoryStoreConfig, MemoryAmbientOptions.

Compaction#

ExportSignature
SUMMARY_SCHEMA_VERSION2
normalizeCompactionnormalizeCompaction(options?): NormalizedCompaction
summarizationInstructionsummarizationInstruction(previous, sources?): string
parseContextSummaryparseContextSummary(text): ContextSummary | undefined
renderSummaryrenderSummary(summary): Record<string, unknown>
validateContextSummaryTransitionvalidateContextSummaryTransition(summary, previous, sources): ContextSummaryValidation
latestContextSummarylatestContextSummary(messages): ContextSummary | undefined
contextSummarySourcescontextSummarySources(messages, indexes): readonly ContextSummarySource[]
evaluateContextSummaryGrades one capsule against its sources.
evaluateContextSummaryStabilityGrades a sequence of capsules for drift.
runContextCompactionHarnessRuns a fixture set through the compaction path.

@caveman-ai/agent/compaction adds the message-level primitives: planCompaction, evictMessage, evictionCitation, elidedDigest, newContextMessages, pinnedContentSurvives, messageText, messageTokens, messagesTokens, CONTEXT_SEED_MAX_CHARS.

Context, profiles and the compiler#

ExportSignature
lowerContextlowerContext(options): LoweredContext
contextBillcontextBill(ir): Record<string, number>
appendRuntimeContextSegmentappendRuntimeContextSegment(lowered, segment): ContextSegment
contextIRToWire, contextIRFromWireWire form of a Context IR, in both directions.
sha256, stableStringifyThe digest and the canonical serialization the locks use.
opaquePayloadopaquePayload(input: Uint8Array): boolean
normalizeTrajectory, parseNormalizedTrajectoryTrajectory IR in and out.
TRAJECTORY_IR_SCHEMA_VERSION1
createWorkloadProfile, createCompilerWorkloadProfile, parseWorkloadProfile, workloadSplitSHA256Workload profiles from trajectories.
WORKLOAD_PROFILE_SCHEMA_VERSION1
compileProfiled, compileProfiledNativePi, planNativePiCandidates, nativePiCompilerTarget, capabilityManifestFor, assertProfiledBuildTarget, executeCompiledPipelineThe profiled compiler.
PROFILED_COMPILER_VERSION, PROFILED_COMPILER_SHA256, TARGET_CAPABILITY_LATTICECompiler identity and what each harness can lower.

Input#

ExportValue
normalizeAgentInputnormalizeAgentInput(input): NormalizedAgentInput
defineAgentInputEncoder, encodeAgentInputEncode parts for a provider that wants its own shape.
AGENT_INPUT_MAX_PARTS64
AGENT_INPUT_MAX_TEXT_BYTES1048576
AGENT_INPUT_MAX_BASE64_BYTES_PER_PART33554432
AGENT_INPUT_MAX_BASE64_BYTES_TOTAL67108864
AGENT_INPUT_MAX_URL_LENGTH8192
AGENT_INPUT_MAX_MIME_LENGTH127
AGENT_INPUT_MAX_FILE_NAME_LENGTH255

Tool runtimes and transports#

ExportSignature
localExecutionBackendlocalExecutionBackend(): ExecutionBackend
httpExecutionBackendhttpExecutionBackend({ url, token }): ExecutionBackend
PROGRAMMATIC_TOOL_NAME"caveman_code"
createProgrammaticToolRuntimecreateProgrammaticToolRuntime(definition, options?)
programmaticToolInstructions, programmaticToolMetadata, createProgrammaticToolErrorWrapper, ProgrammaticSpeculationScopeThe rest of the programmatic surface.
createConnectcreateConnect(options: ConnectOptions): ConnectIntegration
ConnectRuntime, executeConnectTool, connectEnvironment, resolveConnectBinary, compareConnectEfficiencyThe Connect runtime and its helpers.
createModelBoundary, captureModelBoundaryMiddleware around the provider call.
MODEL_BOUNDARY_MAX_MIDDLEWARE, MODEL_BOUNDARY_MAX_ID_LENGTH, MODEL_BOUNDARY_MAX_CONTEXT_STRING_LENGTH64, 64, 512
defineModelUsage, modelUsageAccountingStatus, requireCompleteModelUsageParse and classify provider usage.

Durable stores at the root#

DiskDurableStore, HttpDurableStore, durableInputIsReplayable and durableRunSummary are re-exported from the root. Everything else durable lives at /durable.

@caveman-ai/agent/serve#

ExportSignature
createAgentServercreateAgentServer(options: AgentServerOptions): AgentServer

Types: AgentServerOptions, AgentServer, RecoveryReport.

@caveman-ai/agent/serve-handler#

ExportSignature
createAgentHandlercreateAgentHandler(options: AgentHandlerOptions): AgentHandler
INSTANCE_LOCK_RUN_ID"caveman.instance.lock"

Types: AgentHandlerOptions, AgentHandler, WebSocketLike, RecoveryReport, Principal.

@caveman-ai/agent/durable#

ExportWhat it is
DiskDurableStorenew DiskDurableStore(root). Journal on disk, 0o700 directories and 0o600 files.
SqlDurableStorenew SqlDurableStore({ sql, dialect }). One exec method is the whole database dependency.
ObjectDurableStoreThe same contract over S3, R2 or GCS.
HttpDurableStoreA journal behind an HTTP endpoint.
DurableJournalThe append-only journal itself.
DurableToolCoordinatorTool intent and settlement across attempts.
DURABLE_JOURNAL_VERSION2
validateDurableRunIdRejects a run id that cannot be a journal key.
durableToolIdempotencyKey, durableToolArgsSHA256The stable key an idempotent tool receives, and the digest behind it.
durableConversationCheckpoint, durableConversationMessagesSHA256Bind a conversation to a journal by digest.
durableInputIsReplayable, MULTIMODAL_DURABLE_INPUT_PREFIXWhether an input can be replayed, and the marker for encoded multimodal input.
durableRunSummary, analyzeJournalRead a journal back: attempts, spend and what was in flight.
validateReplayResult, validateReplayReceiptCheck a replayed outcome against the run it claims to be.
durableCancelRequest, requestDurableCancel, settleCancelledRun, DURABLE_CANCELLED_CODECancellation, recorded in the journal.
scheduleDurableWake, nextDurableWake, durableRunIsDue, MAX_DURABLE_SLEEP_MSDurable timers.

@caveman-ai/agent/code#

ExportWhat it is
createCodingAgentcreateCodingAgent(options?): CodingAgent. A workspace agent with the six shell tools.
startCodingSession, runCodingSession, runCodingTurn, streamCodingTurn, classifyTurnFailureThe session loop and one turn of it.
sessionBill, formatTurnBill, formatSessionBillPer-turn and per-session accounting, as text.
summarizeCodingTaskAttemptsEconomics across attempts at one task.
proveRecovery, formatRecoveryProof, RECOVERABLE_CODING_TRANSFORMSByte-exact recovery proof for the transforms a coding session may use.
defaultCodingPlan, codingModelsAtProviderBaseURLThe plan and the model list a session starts from.
CODING_TOOL_OUTPUT_CAPS, capOutputOutput caps for shell tools, and the function that applies one.
CODING_RUN_BREAKERSThe breaker set a coding run uses.
OBSERVE_ONLY_BANNERThe banner an observe-only session prints.
AgentRunController, createCommandSessionRuntime, createProgrammaticToolRuntime, programmaticToolInstructions, PROGRAMMATIC_TOOL_NAMERe-exported so a coding client needs one import.

CLI#

terminal
caveman-agent dev [entry] [prompt]
caveman-agent serve [dir] [--port N] [--host H] [--locked]
caveman-agent build [config] [--verbose] [--accept-prefix-shrink]
caveman-agent check [config]
caveman-agent doctor [--json]
caveman-agent register
caveman-agent connect [provider|providers|connections|status|doctor|...]
caveman-agent --version

Captured from caveman-agent help at 0.2.0. --accept-prefix-shrink resets the frozen-prefix baseline, and writes a new one only once a build completes.

Sibling packages#

PackageOn npmWhat it is
@caveman-ai/create-agent0.1.0The initializer. npm create @caveman-ai/agent@latest, bin create-caveman-agent.
@caveman-ai/evalscheckout onlyDeterministic and model-assisted graders. grade(grader, value, deps?). An unknown grader type, or an option of the wrong type, returns a failed verdict naming the problem rather than a pass.
@caveman-ai/reactcheckout onlyuseAgent and useSession, streaming a run or a session over Server-Sent Events.
@caveman-ai/adapter-kitcheckout onlyAdapter manifests and the registry other harnesses register through.
@caveman-ai/adapter-conformancecheckout onlyDeterministic conformance reports for those adapters.
@caveman-ai/coding-agentcheckout onlyThe interactive coding agent and the caveman-code CLI.
@pebble-agent/protocolcheckout onlyThe PEBBLE wire and storage contract: turn events, session entries, JSONL-RPC framing. Frozen at v1.

@caveman-ai/agent itself is 0.1.0 on npm; these pages document 0.2.0 from source. A checkout-only package reaches you as a dependency of the workspace @caveman-ai/agent you install from the checkout.

The cache planner under src/cache-planner/ is deliberately not re-exported from the runtime: it is reachable only through the /cache-engine subpath while its public shape is being decided.