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<D>, options: RunOptions<D>): 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 |
memorySearchTools | memorySearchTools(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 |
consolidateMemory | consolidateMemory(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 |
forget | forget(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 |
redactEntries | redactEntries(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 |
rewind | rewind(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 |
forkThread | forkThread(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 |
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) |
pricer | readonly pricer: CallPricer | Prices calls by llm.pricing, then the model registry (pricing(model), cost(model, usage)) |
pricedModel | pricedModel(modelString: string, explicitProvider?: string): string | The provider/model string a call is priced by, the provider by the name it is registered under |
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 |
experimental_triggers | get experimental_triggers(): experimental_TriggerManager | undefined | Routines, their triggers and the inbox of experimental_triggers (experimental), see Triggers |
close | close(): 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
| 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 |
memoryAgentId | memoryAgentId(agent: { config: { id?: string }; name: string }): string | The id an agent's memory items are kept under: its configured id, else its name, the same for every instance of the agent |
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 with the skills defined in code |
SkillRegistry | new SkillRegistry(config?: SkillRegistryConfig) | Finds SKILL.md skills in dirs, the run's workspace, a project and the user folder, discover() and reload() (Skills) |
parseSkillFile, splitSkillFile | parseSkillFile(text, origin): ParsedSkillFile | Read a SKILL.md leniently into a manifest and diagnostics |
mergeSkillCatalogs | mergeSkillCatalogs(catalogs: SkillCatalog[]): SkillCatalog | One catalog of several, the first winning a name |
availableSkillsSection, skillTools | skillTools(options: SkillToolsOptions): Tool[] | The <available_skills> prompt section, and use_skill with read_skill_file, as a run builds them |
writeTodosTool, todosIn, parseTodos, renderTodos | todosIn(messages: Message[]): TodoItem[] | undefined | The write_todos tool and its list, see Todo Lists |
toolSearchTool, rankTools, toolsFoundIn | rankTools(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
| Export | Signature | Purpose |
|---|---|---|
tool | tool<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) |
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 |
withParsedArguments | withParsedArguments<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) |
toToolParameters | toToolParameters(schema: Record<string, unknown>): ToolParametersSchema | A JSON Schema made self-contained: recursive definitions in $defs, other refs inlined |
toolContent | toolContent(...parts: ToolContentPart[]): ToolContentResult | A 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, toolPartsToText | toolResultParts(result: unknown): ToolContentPart[] | undefined, toolPartsToText(parts): string | The 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_LENGTH | truncateToolResultText(text: string, maxLength: number): string, 100_000 | Cut 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[], 64 | Check a tool name against provider rules, or make one that fits |
ToolRegistry | new ToolRegistry() - register(tool, { replace? }), registerMany(tools, { replace? }), get, has, getAll, getSchemas, getNames, clear | Tools by name, warns when a different tool takes a registered name unless replace: true |
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, 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_TOOLS | createMemorySearchTools(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_TOOL | memoryFileTool(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 |
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 |
tripwire, isTripwire, TripwireDetails | tripwire(reason: string, info?: unknown): never | Stop a run from a middleware hook with GUARDRAIL_TRIPPED |
piiMiddleware, promptInjectionMiddleware, guardrailsMiddleware, compactionMiddleware | piiMiddleware(config: PiiConfig): RunMiddleware | The built-in run middleware, to give a feature to one agent (Run Middleware) |
memoryCompactionMiddleware, MemoryCompactionDeps, CompactionRun | memoryCompactionMiddleware(config: MemoryCompactionConfig, deps: { memory: () => MemoryAdapter | undefined; summarizer: (model: string, run: CompactionRun) => SummarizeFn; windowOf: (model: string) => number }): RunMiddleware | The 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_CURSOR | memoryExtractionMiddleware(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, BriefPlace | memoryBriefMiddleware(config: MemoryBriefConfig, deps: { memory: () => MemoryAdapter | undefined; summarizer: (model: string, run: CompactionRun) => SummarizeFn; placeOf: (runId: string) => BriefPlace | undefined }): RunMiddleware | The 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_STATE | memoryUpkeepMiddleware(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, MemoryCitationsOptions | memoryCitations(options?: { tools?: readonly string[]; onUncited?: (references: string[], context: RunMiddlewareContext) => void }): RunMiddleware | Citation 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, AnthropicCompactionOptions | anthropicCompactionSummarizer(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, retryAfterFromHeaders | error helpers | Errors backends throw (CogitatorError subclasses), LLMError.kind says why |
classifyProviderError | classifyProviderError(provider: string, status: number | undefined, body: string | undefined): LLMErrorKind | The kind of a provider error, from its own codes, then the status |
abortReason | abortReason(signal: AbortSignal | undefined): Error | undefined | The error an aborted call fails with |
OPENAI_COMPATIBLE_PROFILES, resolveOpenAICompatibleProfile, reasoningEffortFor | presets, (fallback, profile?) => ResolvedOpenAICompatibleProfile, (profile, effort) => ReasoningEffort | undefined | Server profiles of OpenAI-compatible servers |
CallPricer | new 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
| 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, live replays and forks on branches of the original thread | 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 |
| Triggers (experimental) | experimental_TriggerManager, experimental_Inbox, experimental_Scheduler, the routine and inbox stores, experimental_webhookSink | cog.experimental_triggers: start, fire, handle, respond, inbox | Triggers |
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.
Backend Conformance
Hold an LLM backend of your own to the contract every built-in backend meets, against a fake provider that speaks the real wire format.
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.