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<D>, options: RunOptions<D>): 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
memorySearchToolsmemorySearchTools(memoryAgentId: string): Promise<Tool[]>search_memory, open_turns and list_entities over the runtime's memory, see Agent Memory Tools. Throws VALIDATION_ERROR without memory
consolidateMemoryconsolidateMemory(agent: Agent, run?: { userId?: string; threadId?: string; since?: Date }): Promise<MemoryConsolidationReport>A pass over the agent's memory now, with memory.consolidation or memory.observations, see Consolidation. since: report.dedupe.through goes on where a capped pass stopped
forgetforget(target: { entryIds: readonly string[] } | { threadId: string } | { userId: string }, options?: MemoryCascadeCall): Promise<MemoryCascadeReport>Deletes entries, a thread or everything kept for a user, with all memory derived from them and the paused runs of the threads it touches, see Forgetting, Redacting and Rewinding
redactEntriesredactEntries(entryIds: readonly string[], options?: MemoryCascadeCall & { reason?: string }): Promise<MemoryCascadeReport>What the entries said becomes [redacted], their place stays, what was derived from them goes, an event entry among them or their replies is deleted. Also throws VALIDATION_ERROR when the adapter cannot redact
rewindrewind(threadId: string, toEntryId: string, options?: RewindOptions): Promise<RewindReport>Rewinds the thread, the memory items that stood only on the turns after toEntryId become stale, its paused and durable runs are dropped, and with files the workspace is restored from the checkpoint at that point. Also throws VALIDATION_ERROR when the adapter has no branches, THREAD_BUSY while a run goes on, see File Checkpoints and Rewind
forkThreadforkThread(threadId: string, atEntryId: string, options?: ForkThreadOptions): Promise<ForkThreadResult> (ForkThreadPlan with dryRun: true)Copies the branch up to atEntryId into a new thread, with files the fork's workspace restored to that point, see Forking With Files
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)
pricerreadonly pricer: CallPricerPrices calls by llm.pricing, then the model registry (pricing(model), cost(model, usage))
pricedModelpricedModel(modelString: string, explicitProvider?: string): stringThe provider/model string a call is priced by, the provider by the name it is registered under
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
experimental_triggersget experimental_triggers(): experimental_TriggerManager | undefinedRoutines, their triggers and the inbox of experimental_triggers (experimental), see Triggers
closeclose(): Promise<void>Disconnect memory, stop sandboxes, release resources

D is the agent's deps type (new Agent<D>(...), unknown by default): when it is set, run() and resume() require deps, which reach the tools as context.deps and never the model or a checkpoint (RunDeps<D>).

RunOptions.branch: { fromEntryId: string | null; activate?: boolean } runs on a branch of the thread's memory, and RunResult.memory (RunMemoryPlace: threadId, branchPoint, leafId?) says where a run wrote. A branch needs an adapter with getPath and an entry of the thread, otherwise the run fails with VALIDATION_ERROR. See Runs on Branches.

MemoryCascadeCall is { agents?: readonly (Agent | string)[]; graph?: GraphAdapter; keepReplies?: boolean }, the options of forget and redactEntries: the agents (or memory ids) whose items, files, facts and graph to go through besides those the threads name in metadata.memoryAgentIds, a knowledge graph of your own (the graph is reached only with it), and whether to leave the replies to a user message alone. rewind takes RewindOptions (agents, memory, files, workspace, dryRun, force). All three throw CogitatorError (VALIDATION_ERROR) when no memory is configured or the agents to go through are not known (a thread that names none and no agents, or a user without threads). A store that fails part of the way throws its own error, and the call can be made again. MemoryCascadeReport comes from @cogitator-ai/memory.

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
memoryAgentIdmemoryAgentId(agent: { config: { id?: string }; name: string }): stringThe id an agent's memory items are kept under: its configured id, else its name, the same for every instance of the agent
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 with the skills defined in code
SkillRegistrynew SkillRegistry(config?: SkillRegistryConfig)Finds SKILL.md skills in dirs, the run's workspace, a project and the user folder, discover() and reload() (Skills)
parseSkillFile, splitSkillFileparseSkillFile(text, origin): ParsedSkillFileRead a SKILL.md leniently into a manifest and diagnostics
mergeSkillCatalogsmergeSkillCatalogs(catalogs: SkillCatalog[]): SkillCatalogOne catalog of several, the first winning a name
availableSkillsSection, skillToolsskillTools(options: SkillToolsOptions): Tool[]The <available_skills> prompt section, and use_skill with read_skill_file, as a run builds them
writeTodosTool, todosIn, parseTodos, renderTodostodosIn(messages: Message[]): TodoItem[] | undefinedThe write_todos tool and its list, see Todo Lists
toolSearchTool, rankTools, toolsFoundInrankTools(tools: Tool[], query: string, limit: number): Tool[]The tool_search tool, its BM25 ranking and the tools a conversation loaded, see Tool Search

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, throws a TypeError for a name providers refuse (Tool Names)
toolsettoolset<T extends Tool[]>(...tools: T): TReturn several tools as a typed tuple
toolToSchematoolToSchema(tool: Tool): ToolSchemaJSON Schema sent to the LLM
withParsedArgumentswithParsedArguments<TParams, TResult>(tool: Tool<TParams, TResult>): Tool<TParams, TResult>The tool with a pass-through schema, for invokeTool calls whose arguments were already parsed with its schema (Approvals)
toToolParameterstoToolParameters(schema: Record<string, unknown>): ToolParametersSchemaA JSON Schema made self-contained: recursive definitions in $defs, other refs inlined
toolContenttoolContent(...parts: ToolContentPart[]): ToolContentResultA tool result of text, JSON, resource, image and file parts: images reach the model as images, files and binary resources only as a description
isToolContentResult, toolResultParts, toolPartsToTexttoolResultParts(result: unknown): ToolContentPart[] | undefined, toolPartsToText(parts): stringThe media parts of a tool result (toolContent results and objects with a base64 image), and their text with images and files described (also in @cogitator-ai/types)
truncateToolResultText, DEFAULT_TOOL_RESULT_MAX_LENGTHtruncateToolResultText(text: string, maxLength: number): string, 100_000Cut a result to what the model reads, keeping start and end (Result Size)
isProviderSafeToolName, normalizeToolName, normalizeToolNames, TOOL_NAME_MAX_LENGTH(name: string) => boolean, (name: string) => string, (names: readonly string[]) => string[], 64Check a tool name against provider rules, or make one that fits
ToolRegistrynew ToolRegistry() - register(tool, { replace? }), registerMany(tools, { replace? }), get, has, getAll, getSchemas, getNames, clearTools by name, warns when a different tool takes a registered name unless replace: true
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, and memory items when given items. With memory (the thread store), remember keeps a fact as the user's only when its quote is in one of the run user's own messages on the thread's active branch
createMemorySearchTools, MEMORY_SEARCH_TOOLScreateMemorySearchTools(config: MemorySearchToolsConfig), ['search_memory', 'open_turns', 'list_entities']Tools an agent searches the turns of its thread and memory items with, ranked by the MemoryRetriever of hybrid recall. MemorySearchToolsConfig is { memory; agentId; items?; embedding?; messageIndex?; timeZone?; placeOf? }
memoryFileTool, MEMORY_FILE_TOOLmemoryFileTool(config: MemoryFileToolConfig): Tool<MemoryFileToolParams, ToolContentResult>, 'memory'The memory tool over a store that keeps memory files, native memory_20250818 on Claude 4 and later. MemoryFileToolConfig is { memory; agentId; scope?; readOnly?; placeOf?; files? }, see Memory Files
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
tripwire, isTripwire, TripwireDetailstripwire(reason: string, info?: unknown): neverStop a run from a middleware hook with GUARDRAIL_TRIPPED
piiMiddleware, promptInjectionMiddleware, guardrailsMiddleware, compactionMiddlewarepiiMiddleware(config: PiiConfig): RunMiddlewareThe built-in run middleware, to give a feature to one agent (Run Middleware)
memoryCompactionMiddleware, MemoryCompactionDeps, CompactionRunmemoryCompactionMiddleware(config: MemoryCompactionConfig, deps: { memory: () => MemoryAdapter | undefined; summarizer: (model: string, run: CompactionRun) => SummarizeFn; windowOf: (model: string) => number }): RunMiddlewareThe afterRun middleware behind memory.compaction (Compaction After a Run), CompactionRun being { runId, agentId, threadId, signal? }, the run a summarizer's calls are counted against
memoryExtractionMiddleware, MemoryExtractionDeps, EXTRACTION_CURSORmemoryExtractionMiddleware(config: MemoryExtractionConfig, deps: { memory: () => MemoryAdapter | undefined; summarizer: (model: string, run: CompactionRun) => SummarizeFn }): RunMiddleware, 'memoryExtraction'The afterRun middleware behind memory.extraction, and the thread metadata key of its cursor (Extraction After a Run)
memoryBriefMiddleware, MemoryBriefDeps, BriefPlacememoryBriefMiddleware(config: MemoryBriefConfig, deps: { memory: () => MemoryAdapter | undefined; summarizer: (model: string, run: CompactionRun) => SummarizeFn; placeOf: (runId: string) => BriefPlace | undefined }): RunMiddlewareThe beforeModel middleware behind memory.brief, BriefPlace being { threadId, leafId?, ownAfter? }, where a run keeps its conversation (Pre-Turn Brief)
memoryUpkeepMiddleware, MemoryUpkeep, MemoryUpkeepConfig, MemoryUpkeepDeps, upkeepScope, CONSOLIDATION_STATEmemoryUpkeepMiddleware(config: { observations?; consolidation?; scope? }, deps: { memory; summarizer }): MemoryUpkeep, 'memoryConsolidation'The afterRun middleware behind memory.observations and memory.consolidation, with noteCompaction(threadId), consolidate({ scope, model, run }) and close(), the scope memory items of a run belong to, and the thread metadata key that counts runs (Between Runs)
memoryCitations, MemoryCitationsOptionsmemoryCitations(options?: { tools?: readonly string[]; onUncited?: (references: string[], context: RunMiddlewareContext) => void }): RunMiddlewareCitation lock: takes out of a final answer each [turn:<id>] or [item:<id>] the run's memory search tools never handed out, see Citation Lock
anthropicCompactionSummarizer, ANTHROPIC_COMPACTION_BETA, AnthropicCompactionOptionsanthropicCompactionSummarizer(options: { model: string; client?: Anthropic; apiKey?: string; maxTokens?: number }): SummarizeFn, 'compact-2026-09-04'A SummarizeFn that has Anthropic's compaction on request write the summary (Hierarchical Compaction)
LLMError, createLLMError, wrapSDKError, llmUnavailable, llmInvalidResponse, llmTimeout, llmConfigError, llmNotImplemented, providerErrorIn, retryAfterFromHeaderserror helpersErrors backends throw (CogitatorError subclasses), LLMError.kind says why
classifyProviderErrorclassifyProviderError(provider: string, status: number | undefined, body: string | undefined): LLMErrorKindThe kind of a provider error, from its own codes, then the status
abortReasonabortReason(signal: AbortSignal | undefined): Error | undefinedThe error an aborted call fails with
OPENAI_COMPATIBLE_PROFILES, resolveOpenAICompatibleProfile, reasoningEffortForpresets, (fallback, profile?) => ResolvedOpenAICompatibleProfile, (profile, effort) => ReasoningEffort | undefinedServer profiles of OpenAI-compatible servers
CallPricernew CallPricer(overrides?: PricingOverrides)The class of cog.pricer

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, compare, live replays and forks on branches of the original threadTime 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
Triggers (experimental)experimental_TriggerManager, experimental_Inbox, experimental_Scheduler, the routine and inbox stores, experimental_webhookSinkcog.experimental_triggers: start, fire, handle, respond, inboxTriggers

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