Cogitator
API Reference

Core API

Public exports of @cogitator-ai/core — runtime, agents, tools, LLM backends and the advanced subsystems — with their signatures.

Everything below is exported from @cogitator-ai/core. Types such as AgentConfig, RunOptions and RunResult live in @cogitator-ai/types and are re-exported from core.

Runtime

Cogitator

new Cogitator(config?: CogitatorConfig)
MemberSignaturePurpose
runrun(agent: Agent, options: RunOptions): Promise<RunResult>Run an agent: LLM calls, tools, memory, guardrails, tracing
resumeresume(agent: Agent, target: RunCheckpoint | string, options?: ResumeOptions): Promise<RunResult>Continue a run paused for approvals, by checkpoint or thread id
toolsreadonly tools: ToolRegistryTools offered to every agent this instance runs
promptsget prompts(): PromptRegistryVersioned instructions and A/B tests
getMemorygetMemory(): Promise<MemoryAdapter | undefined>The configured memory adapter, connected on first use
memoryget memory(): MemoryAdapter | undefined / set memory(adapter)The connected adapter (undefined before first use), or set your own
resolveModelresolveModel(agent: Agent): stringThe agent's model, else llm.defaultModel; throws CONFIGURATION_ERROR
routeroute(modelString: string, explicitProvider?: string): ModelRouteBackend and provider-side model name for a model string
getLLMBackendgetLLMBackend(modelString: string, explicitProvider?: string): LLMBackendThe backend a model string runs on
knowsProviderknowsProvider(name: string): booleanWhether a name/... model prefix routes to name (backend, built-in or plugin)
estimateCostestimateCost(params: { agent; input; options?: EstimateOptions; model? }): Promise<CostEstimate>Cost estimate before running
getCostSummarygetCostSummary(): CostSummary | undefinedTracked spend (with costRouting)
getCostRoutergetCostRouter(): CostAwareRouter | undefinedThe cost router (with costRouting)
getInsightsgetInsights(agentId: string): Promise<Insight[]>Reflection insights (with reflection)
getReflectionSummarygetReflectionSummary(agentId: string): Promise<ReflectionSummary | null>Reflection statistics
reflectionEngineget reflectionEngine(): ReflectionEngine | undefinedThe reflection engine
getGuardrailsgetGuardrails(): ConstitutionalAI | undefinedThe guardrails instance
setConstitutionsetConstitution(constitution: Constitution): voidReplace the guardrails constitution
closeclose(): Promise<void>Disconnect memory, stop sandboxes, release resources

See Cogitator for the configuration.

Run Checkpoints, Prompts, Threads

ExportSignaturePurpose
InMemoryRunCheckpointStorenew InMemoryRunCheckpointStore()RunCheckpointStore in process memory
ThreadRunCheckpointStorenew ThreadRunCheckpointStore(memory: MemoryAdapter)Keeps paused runs in thread metadata (the default with memory)
PromptRegistrynew PromptRegistry(config?: PromptsConfig)deploy, current, history, rollbackTo, startABTest, activeABTest, completeABTest, resolve, record
promptKeypromptKey(target: Agent | string): stringKey instructions are versioned under (agent id if set, else name)
InMemoryInstructionVersionStore, InMemoryABTestStorenew …()Default prompt stores
threadOwnerthreadOwner(thread: Thread): string | undefinedThe userId a thread belongs to
threadMetadatathreadMetadata(owner: { agentId: string; userId?: string }): Record<string, unknown>Metadata for a new thread owned by a user
assertThreadAccessassertThreadAccess(memory, threadId, userId): Promise<Thread | null>Throws THREAD_ACCESS_DENIED for another user's thread
ensureThreadAccessensureThreadAccess(memory, threadId, owner: { agentId; userId? }): Promise<Thread>Check access and create the thread when missing

Agents and Skills

ExportSignaturePurpose
Agentnew Agent(config: AgentConfig)An agent; defaults temperature: 0.7, maxIterations: 10
agent.cloneclone(overrides: Partial<AgentConfig>): AgentCopy with changes
agent.serializeserialize(): AgentSnapshotJSON snapshot (tools by name)
Agent.deserializeAgent.deserialize(snapshot: AgentSnapshot, options?: DeserializeOptions): AgentRestore from a snapshot (toolRegistry, tools, overrides)
Agent.validateSnapshotAgent.validateSnapshot(snapshot: unknown): snapshot is AgentSnapshotCheck a parsed snapshot
AgentDeserializationErrorclass extends ErrorThrown by deserialize for unknown tools or bad snapshots
defineSkilldefineSkill(config: SkillConfig): SkillBundle tools and instructions (name, version, description, tools, instructions?, env?, dependencies?)
validateSkillvalidateSkill(skill: Skill): SkillValidationResultCheck a skill
mergeSkillsIntoAgentmergeSkillsIntoAgent(tools, instructions, skills): { tools; instructions }What new Agent({ skills }) does

The instance getters id, name, model, instructions, tools and config read the configuration. See Agents.

Tools

ExportSignaturePurpose
tooltool<TParams, TResult>(config: ToolConfig<TParams, TResult>): Tool<TParams, TResult>Create a tool from a Zod schema and execute
toolsettoolset<T extends Tool[]>(...tools: T): TReturn several tools as a typed tuple
toolToSchematoolToSchema(tool: Tool): ToolSchemaJSON Schema sent to the LLM
ToolRegistrynew ToolRegistry() — register, registerMany, get, has, getAll, getSchemas, getNames, clearTools by name
agentAsToolagentAsTool(cogitator, agent, options: AgentAsToolOptions): Tool<{ task: string }, AgentToolResult>Delegate to another agent
builtinToolsTool[]The 26 built-in tools
calculator, datetime, uuid, randomNumber, randomString, hash, base64Encode, base64Decode, sleep, jsonParse, jsonStringify, regexMatch, regexReplace, fileRead, fileWrite, fileList, fileExists, fileDelete, httpRequest, exec, webSearch, webScrape, sqlQuery, vectorSearch, sendEmail, githubApiToolIndividual built-in tools
createAnalyzeImageTool, createGenerateImageTool(config: AnalyzeImageConfig) => Tool, (config?: GenerateImageConfig) => ToolImage tools
createTranscribeAudioTool, createGenerateSpeechTool(config?) => ToolAudio tools
createHttpRequestTool, createWebScrapeTool(options?) => Toolhttp_request and web_scrape with your options: allowPrivateNetwork, your own fetch, and for scraping a User-Agent and robots.txt check
fetchPublic, createPublicFetch, assertPublicUrl, assertPublicHost, isPrivateAddress, createGuardedLookup, PrivateNetworkErrornetwork guardA fetch that reaches only public hosts, checking redirects and the address a host resolves to when it connects
createMemoryToolscreateMemoryTools(config: MemoryToolsConfig)remember / recall / forget over a knowledge graph
createSchedulerToolscreateSchedulerTools(config: SchedulerToolsConfig)schedule_task / list_tasks / cancel_task
createCapabilitiesToolcreateCapabilitiesTool(capabilitiesDoc: string): Toollookup_capabilities
createDeviceToolscreateDeviceTools(): Tool[]Clipboard, system info, screenshot
createSelfToolscreateSelfTools(opts: { toolsDir: string; onToolsChanged?: () => void }): Tool[]Let an agent write its own tools
loadCustomToolsloadCustomTools(toolsDir: string): Promise<Tool[]>Load tools written by createSelfTools

Tool Caching

ExportSignaturePurpose
withCachewithCache(tool: Tool<P, R>, config: WithCacheOptions): CachedTool<P, R>Cache tool results
createToolCacheStoragecreateToolCacheStorage(type: 'memory' | 'redis', options?: { maxSize?; redisClient?; keyPrefix?; onEvict? }): ToolCacheStorageA storage instance
InMemoryToolCacheStoragenew InMemoryToolCacheStorage(maxSize = 1000, options?: { onEvict? })LRU storage in a Map
RedisToolCacheStoragenew RedisToolCacheStorage(config: { client: RedisClientLike; keyPrefix?; maxSize?; onEvict? })Redis storage
generateCacheKey, paramsToQueryString, cosineSimilarity, parseDurationfunctionsCache key and matching helpers

LLM Backends

ExportSignaturePurpose
OllamaBackendnew OllamaBackend(config: OllamaConfig)ollama/… models
OpenAIBackendnew OpenAIBackend(config: OpenAIConfig)openai/… (Responses API on api.openai.com)
AnthropicBackendnew AnthropicBackend(config: AnthropicConfig)anthropic/…
GoogleBackendnew GoogleBackend(config: GoogleConfig)google/… (Gemini)
AzureOpenAIBackendnew AzureOpenAIBackend(config: AzureOpenAIConfig)azure/…
BedrockBackendnew BedrockBackend(config: BedrockConfig)bedrock/… (Converse API)
BaseLLMBackend, OpenAICompatibleBackendabstract classesBases for your own backends
createLLMBackendcreateLLMBackend(provider: LLMProvider, config: CogitatorConfig['llm']): LLMBackendA built-in backend from llm config
parseModelparseModel(modelString: string): { provider: LLMProvider | null; model: string }Split provider/model
DEFAULT_OPENAI_MODEL, isOpenAIReasoningModelconstant, (model: string) => booleanOpenAI helpers
registerLLMBackendregisterLLMBackend<C>(plugin: LLMPlugin<C>): voidRegister a backend plugin under a provider name
defineBackenddefineBackend<C>(options: { metadata; provider; create; validateConfig? }): LLMPlugin<C>Build a plugin
unregisterLLMBackend, hasLLMPlugin, listLLMPlugins, createLLMBackendFromPlugin, llmPluginRegistryfunctions / registryManage plugins
withLLMRetrywithLLMRetry(backend: LLMBackend, config: LLMRetryConfig | false | undefined): LLMBackendThe retry policy runs use (llm.retry)
RetryingBackend, DEFAULT_LLM_RETRYnew RetryingBackend(inner, config?), constantRetry wrapper and its defaults (2 retries, 1 s base, 30 s cap, 60 s max Retry-After)
withDebug, LLMDebugWrapperwithDebug(backend: LLMBackend, options?: LLMDebugOptions): LLMBackendLog requests and responses
withPiiMasking, PiiMaskingBackendwithPiiMasking(backend: LLMBackend, config: PiiConfig | undefined): LLMBackendMask personal data before it reaches the provider
PiiMasker, PiiVault, PII_TYPESnew PiiMasker(config?), new PiiVault()PII detection and placeholder restore
LLMError, createLLMError, wrapSDKError, llmUnavailable, llmInvalidResponse, llmTimeout, llmConfigError, llmNotImplemented, providerErrorIn, retryAfterFromHeaderserror helpersErrors backends throw (CogitatorError subclasses)

Backends are normally created by the runtime from llm.providers; pass instances of your own through llm.backends. See LLM Backends.

Errors

ExportSignaturePurpose
CogitatorErrornew CogitatorError(options: CogitatorErrorOptions)Base error with code, statusCode, retryable
ErrorCodeenumAll error codes (list)
ERROR_STATUS_CODESRecord<ErrorCode, number>HTTP status per code
isRetryableErrorisRetryableError(error: unknown): booleanWhether an error is worth retrying
getRetryDelaygetRetryDelay(error: unknown, defaultDelay = 1000): numberretryAfter of a CogitatorError, else the default

Resilience and Logging

ExportSignaturePurpose
withRetrywithRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>Retry a function
retryableretryable(fn, options?): (...args) => Promise<R>Wrap a function with retries
CircuitBreakernew CircuitBreaker(options?: CircuitBreakerOptions) — execute, getState, getStats, open, close, resetCircuit breaker
CircuitBreakerRegistrynew CircuitBreakerRegistry(defaultOptions?) — get, getAllStats, resetAllBreakers by name
withFallbackwithFallback<T>(config: FallbackConfig<T>): Promise<T>Try alternatives in order
withGracefulDegradationwithGracefulDegradation<T>(fn, options): Promise<T>Return a fallback value on failure
createLLMFallbackExecutorcreateLLMFallbackExecutor(config: LLMFallbackConfig, breakers: CircuitBreakerRegistry)Provider/model fallback chain with breakers
Logger, createLogger, getLogger, setLoggernew Logger(options?: LoggerOptions, context?: LogContext)Structured logging used by the runtime
createLoggerFromConfigcreateLoggerFromConfig(config: LoggingConfig): LoggerThe logger new Cogitator({ logging }) installs process-wide
fetchImageAsBase64, fetchAudioAsBuffer, audioInputToBuffer, isValidAudioFormat, getAudioMimeTypefunctionsMedia input helpers

Observability

ExportSignaturePurpose
LangfuseExporter, createLangfuseExporternew LangfuseExporter(config: LangfuseConfig)Send traces to Langfuse; exports only with enabled: true
OTLPExporter, createOTLPExporternew OTLPExporter(config: OTLPExporterConfig)Send spans over OTLP; exports only with enabled: true

See Observability.

Advanced Subsystems

AreaMain exportsEntry pointGuide
ReflectionReflectionEngine, InMemoryInsightStorenew ReflectionEngine(options) — reflectOnToolCall, reflectOnError, reflectOnRun, getRelevantInsights, getSummaryReflection
Tree of ThoughtsThoughtTreeExecutor, BranchGenerator, BranchEvaluator, DEFAULT_TOT_CONFIGnew ThoughtTreeExecutor(cogitator, config?) — explore(agent, goal, options?): Promise<ToTResult>Reasoning
LearningAgentOptimizer, InMemoryTraceStore, PostgresTraceStore, MetricEvaluator, DemoSelector, InstructionOptimizer, createSuccessMetric, createExactMatchMetric, createContainsMetricnew AgentOptimizer(options) — run, compile, bootstrapDemos, captureTraceLearning
Prompt optimizationPromptLogger, wrapWithPromptLogger, ABTestingFramework, PromptMonitor, RollbackManager, AutoOptimizerwrapWithPromptLogger(backend, store, config?)Prompt Versions
Time travelTimeTravel, InMemoryCheckpointStore, ExecutionReplayer, ExecutionForker, TraceComparatornew TimeTravel(cogitator, options?) — checkpoint, replay, fork, compareTime Travel
Constitutional AIConstitutionalAI, InputFilter, OutputFilter, ToolGuard, CritiqueReviser, DEFAULT_CONSTITUTION, DEFAULT_PRINCIPLES, createConstitution, extendConstitution, …new ConstitutionalAI(options) — filterInput, filterOutput, guardTool, critiqueAndReviseConstitutional AI
Cost routingCostAwareRouter, TaskAnalyzer, ModelSelector, CostTracker, BudgetEnforcer, TokenEstimator, CostEstimatornew CostAwareRouter(options?) — recommendModel(input), checkBudget, getCostSummaryCost Routing
Causal reasoningCausalReasoner, CausalGraphBuilder, CausalInferenceEngine, CounterfactualReasoner, dSeparation, findBackdoorAdjustment, evaluateCounterfactual, …new CausalReasoner(options)Causal Reasoning
Prompt-injection defencePromptInjectionDetector, LocalInjectionClassifier, LLMInjectionClassifier, INJECTION_PATTERNS, detectEncodingThreats, detectUnicodeThreats, matchPatternsnew PromptInjectionDetector(options?) — analyze(input)Security
Context managementContextManager, TruncateStrategy, SlidingWindowStrategy, SummarizeStrategy, HybridStrategynew ContextManager(config, deps?) — checkState, compressContext Management

The configuration and result types of these subsystems (ToTConfig, GuardrailConfig, CostRoutingConfig, CausalGraph, …) and their defaults (DEFAULT_GUARDRAIL_CONFIG, DEFAULT_COST_ROUTING_CONFIG, DEFAULT_INJECTION_CONFIG, DEFAULT_CAUSAL_CONFIG, …) are re-exported from @cogitator-ai/types.

On this page