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)| Member | Signature | Purpose |
|---|---|---|
run | run(agent: Agent, options: RunOptions): Promise<RunResult> | Run an agent: LLM calls, tools, memory, guardrails, tracing |
resume | resume(agent: Agent, target: RunCheckpoint | string, options?: ResumeOptions): Promise<RunResult> | Continue a run paused for approvals, by checkpoint or thread id |
tools | readonly tools: ToolRegistry | Tools offered to every agent this instance runs |
prompts | get prompts(): PromptRegistry | Versioned instructions and A/B tests |
getMemory | getMemory(): Promise<MemoryAdapter | undefined> | The configured memory adapter, connected on first use |
memory | get memory(): MemoryAdapter | undefined / set memory(adapter) | The connected adapter (undefined before first use), or set your own |
resolveModel | resolveModel(agent: Agent): string | The agent's model, else llm.defaultModel; throws CONFIGURATION_ERROR |
route | route(modelString: string, explicitProvider?: string): ModelRoute | Backend and provider-side model name for a model string |
getLLMBackend | getLLMBackend(modelString: string, explicitProvider?: string): LLMBackend | The backend a model string runs on |
knowsProvider | knowsProvider(name: string): boolean | Whether a name/... model prefix routes to name (backend, built-in or plugin) |
estimateCost | estimateCost(params: { agent; input; options?: EstimateOptions; model? }): Promise<CostEstimate> | Cost estimate before running |
getCostSummary | getCostSummary(): CostSummary | undefined | Tracked spend (with costRouting) |
getCostRouter | getCostRouter(): CostAwareRouter | undefined | The cost router (with costRouting) |
getInsights | getInsights(agentId: string): Promise<Insight[]> | Reflection insights (with reflection) |
getReflectionSummary | getReflectionSummary(agentId: string): Promise<ReflectionSummary | null> | Reflection statistics |
reflectionEngine | get reflectionEngine(): ReflectionEngine | undefined | The reflection engine |
getGuardrails | getGuardrails(): ConstitutionalAI | undefined | The guardrails instance |
setConstitution | setConstitution(constitution: Constitution): void | Replace the guardrails constitution |
close | close(): Promise<void> | Disconnect memory, stop sandboxes, release resources |
See Cogitator for the configuration.
Run Checkpoints, Prompts, Threads
| Export | Signature | Purpose |
|---|---|---|
InMemoryRunCheckpointStore | new InMemoryRunCheckpointStore() | RunCheckpointStore in process memory |
ThreadRunCheckpointStore | new ThreadRunCheckpointStore(memory: MemoryAdapter) | Keeps paused runs in thread metadata (the default with memory) |
PromptRegistry | new PromptRegistry(config?: PromptsConfig) | deploy, current, history, rollbackTo, startABTest, activeABTest, completeABTest, resolve, record |
promptKey | promptKey(target: Agent | string): string | Key instructions are versioned under (agent id if set, else name) |
InMemoryInstructionVersionStore, InMemoryABTestStore | new …() | Default prompt stores |
threadOwner | threadOwner(thread: Thread): string | undefined | The userId a thread belongs to |
threadMetadata | threadMetadata(owner: { agentId: string; userId?: string }): Record<string, unknown> | Metadata for a new thread owned by a user |
assertThreadAccess | assertThreadAccess(memory, threadId, userId): Promise<Thread | null> | Throws THREAD_ACCESS_DENIED for another user's thread |
ensureThreadAccess | ensureThreadAccess(memory, threadId, owner: { agentId; userId? }): Promise<Thread> | Check access and create the thread when missing |
Agents and Skills
| Export | Signature | Purpose |
|---|---|---|
Agent | new Agent(config: AgentConfig) | An agent; defaults temperature: 0.7, maxIterations: 10 |
agent.clone | clone(overrides: Partial<AgentConfig>): Agent | Copy with changes |
agent.serialize | serialize(): AgentSnapshot | JSON snapshot (tools by name) |
Agent.deserialize | Agent.deserialize(snapshot: AgentSnapshot, options?: DeserializeOptions): Agent | Restore from a snapshot (toolRegistry, tools, overrides) |
Agent.validateSnapshot | Agent.validateSnapshot(snapshot: unknown): snapshot is AgentSnapshot | Check a parsed snapshot |
AgentDeserializationError | class extends Error | Thrown by deserialize for unknown tools or bad snapshots |
defineSkill | defineSkill(config: SkillConfig): Skill | Bundle tools and instructions (name, version, description, tools, instructions?, env?, dependencies?) |
validateSkill | validateSkill(skill: Skill): SkillValidationResult | Check a skill |
mergeSkillsIntoAgent | mergeSkillsIntoAgent(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
| Export | Signature | Purpose |
|---|---|---|
tool | tool<TParams, TResult>(config: ToolConfig<TParams, TResult>): Tool<TParams, TResult> | Create a tool from a Zod schema and execute |
toolset | toolset<T extends Tool[]>(...tools: T): T | Return several tools as a typed tuple |
toolToSchema | toolToSchema(tool: Tool): ToolSchema | JSON Schema sent to the LLM |
ToolRegistry | new ToolRegistry() — register, registerMany, get, has, getAll, getSchemas, getNames, clear | Tools by name |
agentAsTool | agentAsTool(cogitator, agent, options: AgentAsToolOptions): Tool<{ task: string }, AgentToolResult> | Delegate to another agent |
builtinTools | Tool[] | 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, githubApi | Tool | Individual built-in tools |
createAnalyzeImageTool, createGenerateImageTool | (config: AnalyzeImageConfig) => Tool, (config?: GenerateImageConfig) => Tool | Image tools |
createTranscribeAudioTool, createGenerateSpeechTool | (config?) => Tool | Audio tools |
createHttpRequestTool, createWebScrapeTool | (options?) => Tool | http_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, PrivateNetworkError | network guard | A fetch that reaches only public hosts, checking redirects and the address a host resolves to when it connects |
createMemoryTools | createMemoryTools(config: MemoryToolsConfig) | remember / recall / forget over a knowledge graph |
createSchedulerTools | createSchedulerTools(config: SchedulerToolsConfig) | schedule_task / list_tasks / cancel_task |
createCapabilitiesTool | createCapabilitiesTool(capabilitiesDoc: string): Tool | lookup_capabilities |
createDeviceTools | createDeviceTools(): Tool[] | Clipboard, system info, screenshot |
createSelfTools | createSelfTools(opts: { toolsDir: string; onToolsChanged?: () => void }): Tool[] | Let an agent write its own tools |
loadCustomTools | loadCustomTools(toolsDir: string): Promise<Tool[]> | Load tools written by createSelfTools |
Tool Caching
| Export | Signature | Purpose |
|---|---|---|
withCache | withCache(tool: Tool<P, R>, config: WithCacheOptions): CachedTool<P, R> | Cache tool results |
createToolCacheStorage | createToolCacheStorage(type: 'memory' | 'redis', options?: { maxSize?; redisClient?; keyPrefix?; onEvict? }): ToolCacheStorage | A storage instance |
InMemoryToolCacheStorage | new InMemoryToolCacheStorage(maxSize = 1000, options?: { onEvict? }) | LRU storage in a Map |
RedisToolCacheStorage | new RedisToolCacheStorage(config: { client: RedisClientLike; keyPrefix?; maxSize?; onEvict? }) | Redis storage |
generateCacheKey, paramsToQueryString, cosineSimilarity, parseDuration | functions | Cache key and matching helpers |
LLM Backends
| Export | Signature | Purpose |
|---|---|---|
OllamaBackend | new OllamaBackend(config: OllamaConfig) | ollama/… models |
OpenAIBackend | new OpenAIBackend(config: OpenAIConfig) | openai/… (Responses API on api.openai.com) |
AnthropicBackend | new AnthropicBackend(config: AnthropicConfig) | anthropic/… |
GoogleBackend | new GoogleBackend(config: GoogleConfig) | google/… (Gemini) |
AzureOpenAIBackend | new AzureOpenAIBackend(config: AzureOpenAIConfig) | azure/… |
BedrockBackend | new BedrockBackend(config: BedrockConfig) | bedrock/… (Converse API) |
BaseLLMBackend, OpenAICompatibleBackend | abstract classes | Bases for your own backends |
createLLMBackend | createLLMBackend(provider: LLMProvider, config: CogitatorConfig['llm']): LLMBackend | A built-in backend from llm config |
parseModel | parseModel(modelString: string): { provider: LLMProvider | null; model: string } | Split provider/model |
DEFAULT_OPENAI_MODEL, isOpenAIReasoningModel | constant, (model: string) => boolean | OpenAI helpers |
registerLLMBackend | registerLLMBackend<C>(plugin: LLMPlugin<C>): void | Register a backend plugin under a provider name |
defineBackend | defineBackend<C>(options: { metadata; provider; create; validateConfig? }): LLMPlugin<C> | Build a plugin |
unregisterLLMBackend, hasLLMPlugin, listLLMPlugins, createLLMBackendFromPlugin, llmPluginRegistry | functions / registry | Manage plugins |
withLLMRetry | withLLMRetry(backend: LLMBackend, config: LLMRetryConfig | false | undefined): LLMBackend | The retry policy runs use (llm.retry) |
RetryingBackend, DEFAULT_LLM_RETRY | new RetryingBackend(inner, config?), constant | Retry wrapper and its defaults (2 retries, 1 s base, 30 s cap, 60 s max Retry-After) |
withDebug, LLMDebugWrapper | withDebug(backend: LLMBackend, options?: LLMDebugOptions): LLMBackend | Log requests and responses |
withPiiMasking, PiiMaskingBackend | withPiiMasking(backend: LLMBackend, config: PiiConfig | undefined): LLMBackend | Mask personal data before it reaches the provider |
PiiMasker, PiiVault, PII_TYPES | new PiiMasker(config?), new PiiVault() | PII detection and placeholder restore |
LLMError, createLLMError, wrapSDKError, llmUnavailable, llmInvalidResponse, llmTimeout, llmConfigError, llmNotImplemented, providerErrorIn, retryAfterFromHeaders | error helpers | Errors 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
| Export | Signature | Purpose |
|---|---|---|
CogitatorError | new CogitatorError(options: CogitatorErrorOptions) | Base error with code, statusCode, retryable |
ErrorCode | enum | All error codes (list) |
ERROR_STATUS_CODES | Record<ErrorCode, number> | HTTP status per code |
isRetryableError | isRetryableError(error: unknown): boolean | Whether an error is worth retrying |
getRetryDelay | getRetryDelay(error: unknown, defaultDelay = 1000): number | retryAfter of a CogitatorError, else the default |
Resilience and Logging
| Export | Signature | Purpose |
|---|---|---|
withRetry | withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> | Retry a function |
retryable | retryable(fn, options?): (...args) => Promise<R> | Wrap a function with retries |
CircuitBreaker | new CircuitBreaker(options?: CircuitBreakerOptions) — execute, getState, getStats, open, close, reset | Circuit breaker |
CircuitBreakerRegistry | new CircuitBreakerRegistry(defaultOptions?) — get, getAllStats, resetAll | Breakers by name |
withFallback | withFallback<T>(config: FallbackConfig<T>): Promise<T> | Try alternatives in order |
withGracefulDegradation | withGracefulDegradation<T>(fn, options): Promise<T> | Return a fallback value on failure |
createLLMFallbackExecutor | createLLMFallbackExecutor(config: LLMFallbackConfig, breakers: CircuitBreakerRegistry) | Provider/model fallback chain with breakers |
Logger, createLogger, getLogger, setLogger | new Logger(options?: LoggerOptions, context?: LogContext) | Structured logging used by the runtime |
createLoggerFromConfig | createLoggerFromConfig(config: LoggingConfig): Logger | The logger new Cogitator({ logging }) installs process-wide |
fetchImageAsBase64, fetchAudioAsBuffer, audioInputToBuffer, isValidAudioFormat, getAudioMimeType | functions | Media input helpers |
Observability
| Export | Signature | Purpose |
|---|---|---|
LangfuseExporter, createLangfuseExporter | new LangfuseExporter(config: LangfuseConfig) | Send traces to Langfuse; exports only with enabled: true |
OTLPExporter, createOTLPExporter | new OTLPExporter(config: OTLPExporterConfig) | Send spans over OTLP; exports only with enabled: true |
See Observability.
Advanced Subsystems
| Area | Main exports | Entry point | Guide |
|---|---|---|---|
| Reflection | ReflectionEngine, InMemoryInsightStore | new ReflectionEngine(options) — reflectOnToolCall, reflectOnError, reflectOnRun, getRelevantInsights, getSummary | Reflection |
| Tree of Thoughts | ThoughtTreeExecutor, BranchGenerator, BranchEvaluator, DEFAULT_TOT_CONFIG | new ThoughtTreeExecutor(cogitator, config?) — explore(agent, goal, options?): Promise<ToTResult> | Reasoning |
| Learning | AgentOptimizer, InMemoryTraceStore, PostgresTraceStore, MetricEvaluator, DemoSelector, InstructionOptimizer, createSuccessMetric, createExactMatchMetric, createContainsMetric | new AgentOptimizer(options) — run, compile, bootstrapDemos, captureTrace | Learning |
| Prompt optimization | PromptLogger, wrapWithPromptLogger, ABTestingFramework, PromptMonitor, RollbackManager, AutoOptimizer | wrapWithPromptLogger(backend, store, config?) | Prompt Versions |
| Time travel | TimeTravel, InMemoryCheckpointStore, ExecutionReplayer, ExecutionForker, TraceComparator | new TimeTravel(cogitator, options?) — checkpoint, replay, fork, compare | Time Travel |
| Constitutional AI | ConstitutionalAI, InputFilter, OutputFilter, ToolGuard, CritiqueReviser, DEFAULT_CONSTITUTION, DEFAULT_PRINCIPLES, createConstitution, extendConstitution, … | new ConstitutionalAI(options) — filterInput, filterOutput, guardTool, critiqueAndRevise | Constitutional AI |
| Cost routing | CostAwareRouter, TaskAnalyzer, ModelSelector, CostTracker, BudgetEnforcer, TokenEstimator, CostEstimator | new CostAwareRouter(options?) — recommendModel(input), checkBudget, getCostSummary | Cost Routing |
| Causal reasoning | CausalReasoner, CausalGraphBuilder, CausalInferenceEngine, CounterfactualReasoner, dSeparation, findBackdoorAdjustment, evaluateCounterfactual, … | new CausalReasoner(options) | Causal Reasoning |
| Prompt-injection defence | PromptInjectionDetector, LocalInjectionClassifier, LLMInjectionClassifier, INJECTION_PATTERNS, detectEncodingThreats, detectUnicodeThreats, matchPatterns | new PromptInjectionDetector(options?) — analyze(input) | Security |
| Context management | ContextManager, TruncateStrategy, SlidingWindowStrategy, SummarizeStrategy, HybridStrategy | new ContextManager(config, deps?) — checkState, compress | Context 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.
Test Utilities
@cogitator-ai/test-utils — a scriptable mock LLM backend, a recording memory adapter, fixtures and async/stream helpers for testing Cogitator code.
Swarms API
Public exports of @cogitator-ai/swarms — the Swarm class and builder, strategies, communication, distributed execution, swarm tools, workflow nodes and the assessor — with their signatures.