Types Reference
Key TypeScript type definitions from @cogitator-ai/types.
@cogitator-ai/types holds the shared interfaces of every package. Most of the types below are also re-exported from @cogitator-ai/core. Comments mark defaults and behaviour; the definitions are trimmed of doc comments, not of fields.
Agent Types
interface AgentConfig<TDeps = unknown> {
id?: string;
name: string;
description?: string;
provider?: string; // explicit provider, e.g. 'openai' for an OpenAI-compatible server
model?: string; // 'provider/model'; falls back to llm.defaultModel of the Cogitator
fallbackModels?: FallbackModel[]; // tried in order when model fails, see LLM Backends
instructions: string;
tools?: Tool<unknown, unknown, TDeps>[]; // with TDeps set, only tools whose deps it provides
skills?: Skill[];
temperature?: number; // Agent default: 0.7
topP?: number;
maxTokens?: number;
stopSequences?: string[];
responseFormat?: ResponseFormat;
reasoning?: ReasoningConfig;
handoffs?: Array<Agent | Handoff>; // each becomes a transfer_to_<name> tool
maxIterations?: number; // Agent default: 10
timeout?: number; // ms; run default: limits.defaultTimeout, else 120000
middleware?: RunMiddleware<TDeps>[]; // hooks around its model and tool calls
}
type FallbackModel = string | { model: string; provider?: string };
interface ModelFallbackEvent {
from: string; // 'provider/model' that failed
to: string; // 'provider/model' the turn goes on with
error: Error; // its error, or CIRCUIT_OPEN when it was skipped
}
interface ModelCircuitBreakerConfig {
failureThreshold?: number; // failures in a row before a model is skipped, default 5
resetTimeout?: number; // ms a failing model is skipped, default 30000
halfOpenRequests?: number; // successes needed afterwards, default 3
}
// deps as a run must pass them: required when the agent declares its deps type
type RunDeps<TDeps> = unknown extends TDeps ? { deps?: unknown } : { deps: TDeps };
interface Handoff {
agent: Agent;
toolName?: string; // instead of transfer_to_<agent name>
description?: string; // defaults to the agent's description
}
type ResponseFormat =
{ type: 'text' } | { type: 'json' } | { type: 'json_schema'; schema: ZodType };
interface Agent {
readonly id: string;
readonly name: string;
readonly config: AgentConfig;
readonly model: string | undefined;
readonly instructions: string;
readonly tools: Tool[];
clone(overrides: Partial<AgentConfig>): Agent;
serialize(): AgentSnapshot;
}
interface DeserializeOptions {
toolRegistry?: { get(name: string): Tool | undefined };
tools?: Tool[];
overrides?: Partial<AgentConfig>;
}AgentSnapshot ({ version, id, name, config: SerializedAgentConfig, metadata? }) is the JSON form agent.serialize() produces, tools are kept by name.
AgentWireConfig is how an agent travels to another process (toAgentWire / fromAgentWire in @cogitator-ai/core): every AgentConfig field, tools as ToolSchemas, the response schema as JSON Schema (AgentWireResponseFormat), handoffs as AgentWireHandoffs naming agents carried in handoffAgents. AgentWireRunResult is a run's outcome on the wire: output, structured, structuredError, reasoning, usage (AgentWireUsage: tokens, cost, duration, reasoning and cache tokens), toolCalls (AgentWireToolCall: name, input, output), truncated, blocked, iterationLimitReached, modelUsed, handoffs, finalAgent, runId and threadId.
Run Types
interface RunOptions<TDeps = unknown> {
input: string;
images?: ImageInput[]; // URLs, base64 or { data, mimeType }
audio?: AudioInput[]; // transcribed and added to the input
context?: Record<string, unknown>; // sent as data in the turn context, in front of the input
deps?: TDeps; // tools get them as context.deps; never sent to the model, memory or checkpoints
threadId?: string;
timeout?: number; // ms the whole run may take, RUN_TIMEOUT
timeouts?: RunTimeouts; // deadlines of the stages, over the agent's field by field
signal?: AbortSignal;
stream?: boolean; // streams only together with onToken, onReasoning or a tool input callback
onToken?: (token: string) => void;
onReasoning?: (delta: string) => void;
onHandoff?: (handoff: HandoffEvent) => void;
onModelFallback?: (event: ModelFallbackEvent) => void; // { from, to, error }
onModelTurn?: (turn: KeptModelTurn) => void; // { content, toolCalls, model } after afterModel
reasoning?: ReasoningConfig; // overrides the agent's
onApproval?: (
request: ToolApprovalRequest
) => ToolApprovalDecision | 'pause' | Promise<ToolApprovalDecision | 'pause'>;
onToolCall?: (call: ToolCall) => void;
onToolResult?: (result: ToolResult) => void;
onToolUpdate?: (update: ToolUpdate) => void; // each context.update() of a running tool
onToolInputStart?: (event: ToolInputStart) => void; // needs stream: true, as the next two
onToolInputDelta?: (event: ToolInputDelta) => void; // a piece of the JSON arguments
onToolInputAvailable?: (event: ToolInputAvailable) => void; // a call is complete, arguments read
onToolInputAbandoned?: (event: ToolInputAbandoned) => void; // a begun call will not run: 'incomplete' | 'discarded'
useMemory?: boolean; // default: true when an adapter is configured
loadHistory?: boolean; // default: true
saveHistory?: boolean; // default: true
onRunStart?: (data: { runId: string; agentId: string; input: string; threadId: string }) => void;
onRunComplete?: (result: RunResult) => void;
onRunError?: (error: Error, runId: string, usage?: RunUsage) => void;
onSpan?: (span: Span) => void;
onMemoryError?: (error: Error, operation: 'save' | 'load') => void;
onMemoryEntry?: (entry: MemoryEntry) => void | Promise<void>; // each saved entry, also of an aborted or failed run
branch?: { fromEntryId: string | null; activate?: boolean }; // run on a branch of the thread, activate default: true
brief?: string; // notes for this turn only, sent with the input and not saved
parallelToolCalls?: boolean; // run concurrency-safe calls of a step together, default: false
maxParallelToolCalls?: number; // most calls at once with parallelToolCalls, default: 10
middleware?: RunMiddleware<TDeps>[]; // after the Cogitator's and the agent's, pass again to resume()
userId?: string; // owns new threads, scopes facts, reaches tools as context.userId
threadAccess?: 'owner' | 'shared'; // default: 'owner'
channelType?: string;
channelId?: string;
}
interface RunTimeouts {
totalMs?: number; // the whole run, RUN_TIMEOUT, over timeout
stepMs?: number; // one model call, retries and fallback models included, RUN_STEP_TIMEOUT
chunkMs?: number; // a streamed model call without a chunk for this long, RUN_CHUNK_TIMEOUT
toolMs?: number; // a call of a tool without its own timeout, fails with errorCode TOOL_TIMEOUT
}
interface ToolUpdate extends ToolProgress {
callId: string;
name: string;
}
interface RunResult {
readonly output: string;
readonly structured?: unknown;
readonly runId: string;
readonly agentId: string;
readonly threadId: string;
readonly modelUsed?: string; // model of the final answer, set with cost routing or a fallback
readonly usage: {
readonly inputTokens: number;
readonly outputTokens: number;
readonly totalTokens: number;
readonly cost: number;
readonly duration: number;
readonly reasoningTokens?: number;
readonly cachedInputTokens?: number;
readonly cacheWriteTokens?: number;
};
readonly reasoning?: string;
readonly truncated?: boolean; // the last answer stopped at maxTokens
readonly blocked?: 'content_filter' | 'refusal'; // the last answer was filtered or refused
readonly prompt?: RunPrompt; // the instruction version or A/B variant used
readonly handoffs?: readonly HandoffEvent[];
readonly finalAgent?: string;
readonly status?: 'completed' | 'paused';
readonly pendingApprovals?: readonly ToolApprovalRequest[];
readonly checkpoint?: RunCheckpoint;
readonly toolCalls: readonly ToolCall[];
readonly messages: readonly Message[];
readonly trace: { readonly traceId: string; readonly spans: readonly Span[] };
readonly reflections?: readonly Reflection[];
readonly reflectionSummary?: ReflectionSummary;
readonly memory?: RunMemoryPlace; // where the run wrote in memory, when it wrote anything
readonly stopped?: { readonly reason: string; readonly middleware: string }; // a hook or middleware ended the run
readonly instructions?: readonly LoadedInstructionFile[]; // the project instruction files the run read
}
interface RunMemoryPlace {
readonly threadId: string;
readonly branchPoint: string | null; // the entry the run's first entry went after
readonly leafId?: string; // the run's last entry
}
interface HandoffEvent {
from: string;
to: string;
reason?: string;
}Approvals
interface ToolApprovalRequest {
toolCallId: string;
toolName: string;
arguments: Record<string, unknown>;
description: string;
sideEffects?: string[];
agentId?: string; // set for invokeTool() calls, as their options name them
threadId?: string;
userId?: string;
}
type ToolApprovalDecision = { approved: true } | { approved: false; reason?: string };
interface ResumeOptions extends Omit<
RunOptions,
'input' | 'images' | 'audio' | 'context' | 'threadId' | 'threadAccess'
> {
userId?: string;
decisions?: Record<string, ToolApprovalDecision>; // by tool call id
defaultDecision?: ToolApprovalDecision; // for every call decisions leaves out
}
interface RunCheckpointStore {
save(checkpoint: RunCheckpoint): Promise<void>;
load(threadId: string): Promise<RunCheckpoint | null>;
delete(threadId: string): Promise<void>;
}RunCheckpoint is the plain-JSON state of a paused run (version: 1, runId, threadId, model, messages, the paused turn with its decisions, usage so far, branch (where a run on a branch writes next), …) that cogitator.resume() continues from.
Middleware
interface RunMiddleware<TDeps = unknown> {
readonly name: string;
readonly holdsStream?: boolean; // a streamed turn's text waits until the turn is done
startRun?(
event: RunStartEvent,
context: RunMiddlewareContext<TDeps>
): void | RunContextUpdate | Promise<void | RunContextUpdate>;
beforeRun?(
event: RunInputEvent,
context: RunMiddlewareContext<TDeps>
): void | RunContextUpdate | Promise<void | RunContextUpdate>;
beforeModel?(
event: ModelTurnEvent,
context: RunMiddlewareContext<TDeps>
): void | ModelTurnUpdate | Promise<void | ModelTurnUpdate>;
wrapModelCall?(
call: ModelCallRequest,
next: (call: ModelCallRequest) => Promise<ChatResponse>,
context: RunMiddlewareContext<TDeps>
): Promise<ChatResponse>;
afterModel?(
event: ModelResponseEvent,
context: RunMiddlewareContext<TDeps>
): void | ModelResponseUpdate | Promise<void | ModelResponseUpdate>;
wrapToolCall?(
call: ToolCallRequest,
next: (call: ToolCallRequest) => Promise<ToolResult>,
context: RunMiddlewareContext<TDeps>
): Promise<ToolResult>;
beforeToolCall?(
event: ToolCallEvent,
context: RunMiddlewareContext<TDeps>
): void | ToolCallVerdict | Promise<void | ToolCallVerdict>;
decideApproval?(
event: ApprovalRequestEvent,
context: RunMiddlewareContext<TDeps>
): void | ToolApprovalDecision | Promise<void | ToolApprovalDecision>;
afterToolBatch?(
event: ToolBatchEvent,
context: RunMiddlewareContext<TDeps>
): void | Promise<void>;
beforeStop?(
event: RunStopEvent,
context: RunMiddlewareContext<TDeps>
): void | RunStopUpdate | Promise<void | RunStopUpdate>;
beforeCompaction?(
event: CompactionStartEvent,
context: RunMiddlewareContext<TDeps>
): void | CompactionDecision | Promise<void | CompactionDecision>;
afterCompaction?(
event: CompactionEndEvent,
context: RunMiddlewareContext<TDeps>
): void | Promise<void>;
beforeModelSwitch?(
event: ModelSwitchEvent,
context: RunMiddlewareContext<TDeps>
): void | ModelSwitchDecision | Promise<void | ModelSwitchDecision>;
onNotification?(
event: RunNotification,
context: RunMiddlewareContext<TDeps>
): void | Promise<void>;
afterRun?(event: RunEndEvent, context: RunMiddlewareContext<TDeps>): void | Promise<void>;
}
type RunEndEvent =
| { status: 'completed' | 'paused'; result: RunResult; model: string; memoryAgentId: string }
| { status: 'failed'; error: Error; model: string; memoryAgentId: string };
// model: the model the run ended on, as provider/model
// memoryAgentId: the id the agent's memory items are kept under: its configured id, else its name
interface ModelCallRequest {
request: ChatRequest;
model: string; // provider/model the call goes to
stream?: { onToken(token: string): void; onReasoning?(delta: string): void };
}
interface ToolCallRequest {
toolCall: ToolCall; // as the model made it
tool: Tool;
args: unknown; // as the tool's schema parsed them
approved: boolean; // a person approved the call (false once a middleware changed the arguments)
}afterRun is called once a run ended, before run() returns or throws: completed (its writes to memory settled), paused or failed. Check event.status before you read event.result. An error it throws is logged without changing the run's outcome.
RunMiddlewareContext carries runId, threadId, agentId, agentName, userId, channelType, channelId, iteration, signal, deps, a state map the run's middleware share, parentRunId, permissionMode, and in a run addContext(text), stop(reason) and logEvent(event, note). See Run Middleware.
Tool Types
interface Tool<TParams = unknown, TResult = unknown, TDeps = unknown> {
name: string;
title?: string; // name for people, such as an MCP client shows
description: string;
category?: ToolCategory;
tags?: string[];
parameters: ZodType<TParams>;
outputSchema?: ZodType<TResult>; // not checked in a run, MCPServer advertises it
annotations?: ToolAnnotations;
execute(params: TParams, context: BaseToolContext<TDeps>): Promise<TResult>;
sideEffects?: SideEffectType[];
requiresApproval?: boolean | ApprovalCheck;
timeout?: number;
sandbox?: SandboxConfig;
maxResultLength?: number; // characters of a result the model reads, over limits.maxToolResultLength
providerTypes?: ProviderToolTypes; // sent to that provider instead of the schema
isConcurrencySafe?: boolean | ToolCallCheck; // default: annotations.readOnlyHint
lockKeys?(
params: TParams,
context: BaseToolContext<TDeps>
): readonly string[] | Promise<readonly string[]>;
presentation?: ToolPresentation | ToolPresenter;
onInputStart?(event: ToolInputStart): void;
onInputDelta?(event: ToolInputDelta): void;
onInputAvailable?(event: ToolInputAvailable): void;
onInputAbandoned?(event: ToolInputAbandoned): void;
toJSON(): ToolSchema;
}
interface ToolConfig<TParams = unknown, TResult = unknown, TDeps = unknown> {
name: string;
title?: string;
description: string;
category?: ToolCategory;
tags?: string[];
parameters: ZodType<TParams>;
outputSchema?: ZodType<TResult>;
annotations?: ToolAnnotations;
execute: (params: TParams, context: ToolContext<TDeps>) => Promise<TResult>;
sideEffects?: SideEffectType[];
requiresApproval?: boolean | ((params: TParams) => boolean);
timeout?: number;
sandbox?: SandboxConfig;
maxResultLength?: number;
providerTypes?: ProviderToolTypes;
isConcurrencySafe?: boolean | ((params: TParams) => boolean); // may run beside other safe calls
lockKeys?: (
params: TParams,
context: ToolContext<TDeps>
) => readonly string[] | Promise<readonly string[]>;
presentation?: ToolPresentation | ((params: TParams) => ToolPresentation);
onInputStart?: (event: ToolInputStart) => void; // { toolCallId, toolName }
onInputDelta?: (event: ToolInputDelta) => void; // { toolCallId, toolName, delta }
onInputAvailable?: (event: ToolInputAvailable) => void; // { toolCallId, toolName, input }
onInputAbandoned?: (event: ToolInputAbandoned) => void; // { toolCallId, toolName, reason }
}
// How a client shows a tool call, saved in metadata.presentation of its tool_result entry
interface ToolPresentation {
label: string; // such as 'Edit file'
icon?: string; // an icon name, Lucide names by convention
detail?: string; // one line about the call, such as the path
}
// What toolOutput() builds: the model reads content, the application gets the rest too
interface ToolOutputResult<TContent = unknown, TDetails = unknown> {
type: 'tool-output';
content: TContent;
details?: TDetails;
presentation?: ToolPresentation;
}
// What context.update() reports
interface ToolProgress {
content?: unknown;
details?: unknown;
presentation?: ToolPresentation;
}
type ToolCallCheck = (params: Record<string, unknown>) => boolean;
type ToolPresenter = (params: Record<string, unknown>) => ToolPresentation;
// The tool's type in a provider's own catalog, such as { anthropic: 'memory_20250818' }
interface ProviderToolTypes {
anthropic?: string;
}
type ApprovalCheck = (params: Record<string, unknown>) => boolean;
// MCP tool annotations without the title, see Tool.title
interface ToolAnnotations {
readOnlyHint?: boolean; // does not change its environment
destructiveHint?: boolean; // may make destructive updates (when not read-only)
idempotentHint?: boolean; // a repeated call with the same arguments has no further effect
openWorldHint?: boolean; // reaches external entities, such as the web
}
type ToolCategory =
| 'math'
| 'text'
| 'file'
| 'network'
| 'system'
| 'utility'
| 'web'
| 'database'
| 'communication'
| 'development';
type SideEffectType = 'filesystem' | 'network' | 'database' | 'process' | 'external';
interface BaseToolContext<TDeps = unknown> {
agentId: string;
runId: string;
signal: AbortSignal;
toolCallId?: string;
threadId?: string;
userId?: string;
channelType?: string;
channelId?: string;
deps?: TDeps; // RunOptions.deps
update?: (progress: ToolProgress) => void; // what the tool has so far, see onToolUpdate
}
// ToolContext<AppDeps> has deps present and typed, for tools that read them
type ToolContext<TDeps = unknown> = unknown extends TDeps
? BaseToolContext
: BaseToolContext<TDeps> & { deps: TDeps };
interface ToolCall {
id: string;
name: string;
arguments: Record<string, unknown>;
thoughtSignature?: string; // provider reasoning signature, echoed back as-is (Gemini)
replay?: ToolCallReplayState; // opaque provider state replayed with the call (OpenAI Responses reasoning items)
}
interface ToolCallReplayState {
itemId?: string; // provider id of the output item that carried the call (e.g. `fc_...`)
precedingItems?: Record<string, unknown>[]; // e.g. reasoning items with encrypted_content, sent back verbatim
}
interface ToolResult {
callId: string;
name: string;
result: unknown; // what the model read, the content of a toolOutput() result
error?: string;
errorCode?: string; // TOOL_TIMEOUT for a call that ran out of time
details?: unknown; // toolOutput({ details }), never sent to the model
presentation?: ToolPresentation;
}
interface ToolSchema {
name: string;
description: string;
parameters: {
type: 'object';
properties: Record<string, unknown>;
required?: string[];
};
providerTypes?: ProviderToolTypes; // sent to that provider instead of parameters
outputSchema?: Record<string, unknown>; // JSON Schema of the result, Gemini's responseJsonSchema
}A tool that returns media or more than one value returns a ToolContentResult, built with toolContent() from @cogitator-ai/core (see Media Results):
interface ToolContentResult {
type: 'tool-content';
content: ToolContentPart[];
}
type ToolContentPart =
ToolTextPart | ToolImagePart | ToolFilePart | ToolJsonPart | ToolResourcePart;
interface ToolTextPart {
type: 'text';
text: string;
}
interface ToolImagePart {
type: 'image';
data: string; // base64, without a data: URL prefix
mediaType: string; // e.g. image/png
}
interface ToolFilePart {
type: 'file';
data: string; // base64, the model reads only a description
mediaType: string; // e.g. audio/mpeg
filename?: string;
}
interface ToolJsonPart {
type: 'json';
value: unknown; // the model reads it as JSON text
}
interface ToolResourcePart {
type: 'resource';
uri: string; // e.g. file:///repo/README.md
name?: string;
description?: string;
mediaType?: string;
text?: string; // the model reads it
data?: string; // base64, stays with the application, at most one of text and data
}The package also holds the helpers that read such results, with no dependencies, so packages without @cogitator-ai/core read them the same way a run does: isToolContentResult(value), toolResultParts(result) (the parts of a ToolContentResult or of an object with a base64 image or imageBase64), toolPartsToText(parts) (the text the model reads, images and files described), truncateToolResultText(text, maxLength) and DEFAULT_TOOL_RESULT_MAX_LENGTH (100 000). Core re-exports all of them.
The tool cache types (WithCacheOptions, CachedTool, CacheStats, ToolCacheStorage, RedisClientLike, DurationString) are described on Tool Caching.
Message Types
type MessageRole = 'system' | 'user' | 'assistant' | 'tool';
type MessageContent = string | ContentPart[];
type ContentPart =
| { type: 'text'; text: string }
| { type: 'image_url'; image_url: { url: string; detail?: 'auto' | 'low' | 'high' } }
| {
type: 'image_base64';
image_base64: {
data: string;
media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
};
};
interface Message {
role: MessageRole;
content: MessageContent;
name?: string;
toolCallId?: string;
cacheBreakpoint?: boolean; // ends a part of the prompt the next turns send again unchanged
}
interface ToolCallMessage extends Message {
role: 'assistant';
content: string;
toolCalls: ToolCall[];
}
interface ToolResultMessage extends Message {
role: 'tool';
content: string;
toolCallId: string;
name: string;
}The three content parts are exported as TextContentPart, ImageUrlContentPart and ImageBase64ContentPart.
cacheBreakpoint marks the end of a stable part of the prompt, such as the history a context was built from. Backends that mark Anthropic's prompt cache (Anthropic, and Claude through OpenRouter) put a cache breakpoint at the end of the last message that carries it, other backends ignore it.
LLM Types
type LLMProvider =
| 'ollama'
| 'openai'
| 'anthropic'
| 'google'
| 'azure'
| 'bedrock'
| 'vllm'
| 'mistral'
| 'groq'
| 'together'
| 'deepseek';
type LLMBackendProvider = LLMProvider | (string & {}); // or the name of your own backend / plugin
interface LLMBackend {
readonly provider: LLMBackendProvider;
chat(request: ChatRequest): Promise<ChatResponse>;
chatStream(request: ChatRequest): AsyncGenerator<ChatStreamChunk>;
complete?(request: Omit<ChatRequest, 'model'> & { model?: string }): Promise<ChatResponse>;
}
interface ChatRequest {
model: string;
messages: Message[];
tools?: ToolSchema[];
toolChoice?: ToolChoice; // 'auto' | 'none' | 'required' | { type: 'function'; function: { name } }
temperature?: number;
topP?: number;
maxTokens?: number;
stop?: string[];
stream?: boolean;
responseFormat?: LLMResponseFormat; // text | json_object | json_schema
reasoning?: ReasoningConfig;
cache?: PromptCacheConfig | false;
cachePrefix?: string; // the stable start of the system prompt, marked for the cache
signal?: AbortSignal;
}
type FinishReason = 'stop' | 'tool_calls' | 'length' | 'content_filter' | 'refusal' | 'error';
interface ChatResponse {
id: string;
content: string;
toolCalls?: ToolCall[];
finishReason: FinishReason; // only 'tool_calls' runs tools
finishMessage?: string; // the provider's explanation, e.g. of an 'error' turn
usage: ChatUsage;
reasoning?: string; // readable reasoning summary, when returned
}
interface ChatUsage {
inputTokens: number;
outputTokens: number;
totalTokens: number;
cachedInputTokens?: number; // served from the prompt cache; already counted in inputTokens
cacheWriteTokens?: number; // written to the prompt cache; already counted in inputTokens
reasoningTokens?: number; // hidden reasoning tokens; already counted in outputTokens
}
interface ChatStreamChunk {
id: string;
delta: {
content?: string;
reasoning?: string;
toolCalls?: Partial<ToolCall>[];
};
finishReason?: FinishReason; // on the chunk that ends the turn
finishMessage?: string;
usage?: ChatUsage; // typically only on the final chunk
}
interface ReasoningConfig {
effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
budgetTokens?: number; // Gemini 2.5 thinkingBudget, Claude before 4.6
summary?: boolean; // ask for a readable summary
}
interface LLMRetryConfig {
maxRetries?: number; // default 2
baseDelay?: number; // default 1000 ms, doubled per retry
maxDelay?: number; // default 30000 ms
maxRetryAfter?: number; // default 60000 ms
requestTimeout?: number; // ms one call may take before it is aborted and retried, off by default
onRetry?: (event: LLMRetryEvent) => void;
}
interface PromptCacheConfig {
ttl?: '5m' | '1h'; // Anthropic cache lifetime, default 5m
conversation?: boolean; // mark the conversation end too, default when tools or earlier turns
}
interface ModelRoute {
backend: LLMBackend;
model: string;
}
interface LLMConfig {
provider: LLMProvider;
model: string;
temperature?: number;
topP?: number;
maxTokens?: number;
stopSequences?: string[];
}Provider Configuration
type LLMProvidersConfig = { [K in LLMProvider]?: ProviderConfigMap[K] };
interface OllamaProviderConfig {
baseUrl: string;
apiKey?: string;
}
interface OpenAIProviderConfig {
apiKey: string;
baseUrl?: string;
api?: OpenAIWireApi; // default: 'responses' for api.openai.com, 'chat-completions' for other base URLs
profile?: OpenAICompatibleServer | OpenAICompatibleProfile; // default: 'openai' for api.openai.com, else 'generic'
headers?: Record<string, string>; // sent with every request
}
type OpenAIWireApi = 'responses' | 'chat-completions';
type OpenAICompatibleServer =
| 'openai'
| 'generic'
| 'vllm'
| 'ollama'
| 'lmstudio'
| 'llamacpp'
| 'groq'
| 'together'
| 'deepseek'
| 'mistral'
| 'openrouter';
interface OpenAICompatibleProfile {
server?: OpenAICompatibleServer; // the preset the other fields override
maxTokensField?: 'max_tokens' | 'max_completion_tokens';
streamUsage?: boolean; // send stream_options: { include_usage: true }
reasoningEffort?: boolean | readonly ReasoningEffort[]; // the efforts the server takes
}
interface AnthropicProviderConfig {
apiKey: string;
baseUrl?: string; // default 'https://api.anthropic.com'
headers?: Record<string, string>;
}
interface GoogleProviderConfig {
apiKey: string;
baseUrl?: string; // with the version, default 'https://generativelanguage.googleapis.com/v1beta'
headers?: Record<string, string>;
}
interface AzureProviderConfig {
endpoint: string;
apiKey: string;
apiVersion?: string; // default '2025-04-01-preview'
deployment?: string;
model?: string; // the model the deployments serve, e.g. 'gpt-5', when their names do not say
}
interface BedrockProviderConfig {
region?: string;
accessKeyId?: string;
secretAccessKey?: string;
sessionToken?: string;
profile?: string; // a named profile of the shared AWS config files
endpoint?: string; // a VPC endpoint or a proxy, default: the region's
}
interface VLLMProviderConfig {
baseUrl: string;
profile?: OpenAICompatibleServer | OpenAICompatibleProfile; // default 'vllm'
headers?: Record<string, string>;
}
interface OpenRouterProviderConfig {
apiKey: string;
baseUrl?: string; // default 'https://openrouter.ai/api/v1'
headers?: Record<string, string>; // e.g. HTTP-Referer and X-Title app attribution
}
// MistralProviderConfig, GroqProviderConfig, TogetherProviderConfig, DeepSeekProviderConfig: { apiKey: string }Configuration Types
interface CogitatorConfig {
llm?: {
defaultProvider?: LLMProvider; // for model strings without a known provider prefix; default 'ollama'
defaultModel?: string;
providers?: LLMProvidersConfig;
backends?: Record<string, LLMBackend>; // your own backends by name; a built-in name replaces it
plugins?: Record<string, unknown>; // config for registerLLMBackend plugins, by provider
retry?: LLMRetryConfig | false; // on by default
promptCache?: PromptCacheConfig | false; // on by default
toolOutputSchemas?: 'native' | 'description'; // default 'native'
modelCircuitBreaker?: ModelCircuitBreakerConfig; // when a failing fallbackModels model is skipped
pricing?: Record<string, ModelPriceConfig>; // USD per million tokens, by model string or its tail after any '/'
};
runCheckpoints?: RunCheckpointStore; // where paused runs wait
prompts?: PromptsConfig; // instruction versions and A/B tests
middleware?: RunMiddleware[]; // hooks around every run's model and tool calls, and invokeTool()
limits?: {
maxConcurrentRuns?: number;
defaultTimeout?: number;
maxTokensPerRun?: number;
maxToolResultLength?: number; // characters of a tool result the model reads (default 100000)
};
memory?: MemoryConfig;
sandbox?: SandboxManagerConfig;
reflection?: ReflectionConfig;
guardrails?: Partial<GuardrailConfig>; // on unless enabled: false
costRouting?: CostRoutingConfig;
security?: {
promptInjection?: Partial<PromptInjectionConfig>;
pii?: PiiConfig;
};
context?: ContextManagerConfig;
logging?: LoggingConfig;
deploy?: DeployConfig;
}
interface PromptsConfig {
versions?: InstructionVersionStore; // default: in process memory
abTests?: ABTestStore; // default: in process memory
score?: (result: RunResult) => number | Promise<number>; // default: 1
autoDeployWinner?: boolean;
}
interface PiiConfig {
mode?: 'mask' | 'redact' | 'block';
detect?: PiiType[]; // default: all built-in kinds
custom?: Array<{ type: string; pattern: RegExp }>;
onDetect?: (counts: Record<string, number>) => void;
}
interface LoggingConfig {
level?: 'debug' | 'info' | 'warn' | 'error' | 'silent'; // default: 'info'
format?: 'json' | 'pretty'; // default: 'pretty' ('json' for files)
destination?: 'console' | 'file'; // default: 'console'
filePath?: string; // required for 'file'
}logging configures the process-wide logger (getLogger() from @cogitator-ai/core), so the last Cogitator created with logging sets it for every runtime in the process. 'silent' outputs nothing; destination: 'file' appends one line per entry to filePath (JSON lines unless format is set) and falls back to the console, with a warning, when filePath is missing or the runtime has no file system.
Memory Types
type MemoryResult<T> = { success: true; data: T } | { success: false; error: string };
type MemoryProvider = 'memory' | 'redis' | 'postgres' | 'sqlite' | 'mongodb' | 'qdrant';
interface MemoryConfig {
adapter?: MemoryProvider;
inMemory?: Omit<InMemoryAdapterConfig, 'provider'>;
redis?: Omit<RedisAdapterConfig, 'provider'>;
postgres?: Omit<PostgresAdapterConfig, 'provider'>;
sqlite?: Omit<SQLiteAdapterConfig, 'provider'>;
mongodb?: Omit<MongoDBAdapterConfig, 'provider'>;
qdrant?: Omit<QdrantAdapterConfig, 'provider'>;
embedding?: EmbeddingServiceConfig;
contextBuilder?: Partial<ContextBuilderConfig>;
compaction?: MemoryCompactionConfig; // compaction of a run's thread after the run, off unless set
extraction?: MemoryExtractionConfig; // memory items extracted after each run, off unless set
files?: MemoryFilesConfig; // the memory tool and its files under /memories, off unless set
brief?: MemoryBriefConfig; // cards of what memory holds for a turn, off unless set
observations?: MemoryObservationsConfig; // what memory makes of each entity, off unless set
consolidation?: MemoryConsolidationConfig; // a pass over memory between runs, off unless set
}
interface MemoryFilesConfig {
scope?: 'user' | 'agent' | 'thread'; // default 'user', the thread for a run without a user
readOnly?: boolean; // the agent views the files and never changes them
indexChars?: number; // characters the list of files takes in the context (default 2000)
}
interface MemoryBriefConfig {
model?: string; // default: the run's model
maxCards?: number; // 1 to 4, default 4
timeoutMs?: number; // default 4000
maxTokens?: number; // default 600
prompt?: string;
}
// One card of a brief, quoting its source (`turn:<id>` or `item:<id>`) word for word
interface BriefCard {
kind: 'constraint' | 'knowledge' | 'consequence' | 'open_thread'; // BriefCardKind
text: string;
quote: string;
source: string;
}
interface MemoryObservationsConfig {
model?: string; // default: the model the run ended on, the agent's for a pass on demand
maxEntities?: number; // observations one refresh writes at most, default 3
minItems?: number; // facts that hold an entity needs, default 3
prompt?: string;
}
interface MemoryConsolidationConfig {
model?: string; // default: the model the run ended on, the agent's for a pass on demand
everyRuns?: number; // runs of a thread between passes, default 20
afterCompaction?: boolean; // pass after a compaction too, default true
maxChanges?: number; // items one pass marks as stale, default 10, 0 leaves items alone
maxSubjects?: number; // subjects one pass asks about, default 10, the next pass goes on
playbook?: 'apply' | 'shadow' | false; // default 'apply', false only stops new lessons
showPlaybook?: boolean; // the playbook in every run's context, default true, whatever playbook says
prompt?: string;
afterConsolidate?: (report: MemoryConsolidationReport) => void | Promise<void>;
}
interface MemoryConsolidationReport {
scope: MemoryItemScope;
observations: string[]; // paths written
observationsDeleted: string[];
stale: StaleMark[]; // { itemId, keptId, reason: 'duplicate' | 'contradiction' }
playbook?: { path: string; editCount: number; lessonIds: string[] };
dedupe?: { complete: boolean; through?: Date }; // through: the since of a pass that goes on
}
type EmbeddingServiceConfig = OpenAIEmbeddingConfig | OllamaEmbeddingConfig | GoogleEmbeddingConfig;
interface ModelPriceConfig {
input: number;
output: number;
inputCached?: number; // prompt-cache reads, default: the input price
inputCacheWrite?: number; // prompt-cache writes with the 5-minute TTL
inputCacheWrite1h?: number; // prompt-cache writes with the 1-hour TTL
}Every adapter method returns a MemoryResult; unwrap(result) from @cogitator-ai/memory returns data or throws. MemoryAdapter, Thread, MemoryEntry, Fact, Embedding and the search and graph types are listed on the Memory API page.
Threads are trees of entries (see Threads as Trees), described by these types:
type MemoryEntryType =
| 'message'
| 'tool_result'
| 'model_change'
| 'compaction'
| 'approval'
| 'interrupt'
| 'label'
| 'custom';
const CONVERSATION_ENTRY_TYPES: readonly MemoryEntryType[]; // ['message', 'tool_result'], what reads return by default
const MEMORY_ENTRY_FORMAT = 2; // layout of entries written now
type NewMemoryEntry = Omit<
MemoryEntry,
'id' | 'createdAt' | 'seq' | 'formatVersion' | 'parentId'
> & {
id?: string; // the id the entry gets instead of a new one, an id kept already fails the add
createdAt?: Date;
parentId?: string | null; // default: after the active leaf
activate?: boolean; // default: true, the entry becomes the active leaf
};
interface PathQueryOptions {
threadId: string;
leafId?: string;
limit?: number;
before?: string;
types?: readonly MemoryEntryType[] | 'all';
includeToolCalls?: boolean;
}
interface Evidence {
entryId?: string;
toolCallId?: string;
fileRange?: { path: string; start: number; end: number };
quote: string;
}
type EvidenceStatus = 'verified' | 'suggested';
interface EntryRedaction {
at: Date;
reason?: string; // why, such as a user's request
}
type MemoryChange =
| { type: 'entry-added'; entry: MemoryEntry }
| { type: 'entry-deleted'; entryId: string; threadId?: string }
| { type: 'entry-redacted'; entryId: string; threadId: string }
| { type: 'thread-cleared'; threadId: string }
| { type: 'thread-deleted'; threadId: string };MemoryAdapter.redactEntry?(entryId, redaction: EntryRedaction) replaces what a message or tool_result entry said with [redacted] in place (its text, the arguments, replay state and argument error of its tool calls, the results of its tools, and the sender name of a user message), keeps its parent, role and call ids, records the redaction in metadata.redacted ({ at, reason? }, at as an ISO string), and refuses an event entry. forkThread? lists the fork in the origin's metadata.memoryForks and does not copy its paused run. See Forgetting, Redacting and Rewinding. MemoryQueryOptions takes types as well, Thread has activeLeafId, MemoryEntry has type, parentId, seq, event and formatVersion, and Fact, GraphNode, GraphEdge and Insight take an optional evidence: Evidence[]. ExecutionCheckpoint keeps the run's memory: RunMemoryPlace, see Time Travel.
The context builder shares its budget among partitions and reports what it left out with these types:
type ContextPartition =
'system' | 'pinned' | 'index' | 'summaries' | 'facts' | 'recall' | 'brief' | 'recent' | 'final';
interface ContextPartitionBudget {
share?: number; // part of the context budget, 0 to 1
required?: boolean; // filled first, cut only when the budget cannot hold it
}
type DroppedReason = 'budget' | 'duplicate' | 'not-selected' | 'oversized';
interface DroppedBlock {
partition: ContextPartition;
reason: DroppedReason;
tokens: number;
sourceId?: string; // the history entry, fact or search result it came from
}ContextBuilderConfig takes partitions?: Partial<Record<ContextPartition, ContextPartitionBudget>>, merged over the defaults (system, pinned, index, summaries, brief and final required, facts 15%, recall 35%, recent the rest, shares of the partitions that are not required adding up to 1 at most), BuiltContext has memoryContext?: string (what changes every turn, sent with the input) and partitions (tokens per partition), and DroppedContext has blocks: DroppedBlock[].
Threads are compacted (see Sessions, Compaction and Core Facts) with these types:
type CompactionStrategy = 'hierarchical' | 'summary' | 'sliding-window' | 'hybrid';
interface CompactionConfig {
strategy: CompactionStrategy;
threshold?: number; // tokens of the thread that start a compaction
messageThreshold?: number; // entries of the thread that start a compaction
keepRecent: number; // newest entries kept verbatim
keepRecentTokens?: number; // hierarchical: newest tokens of whole turns kept verbatim, in place of keepRecent
chapterTokens?: number; // hierarchical: conversation one chapter covers (default 4000)
chapterConcurrency?: number; // hierarchical: chapters read at once (default 1)
chaptersPerArc?: number; // hierarchical: chapters kept before the oldest fold into an arc (default 4)
arcsPerSaga?: number; // hierarchical: arcs kept before the oldest fold into the saga (default 4)
summaryModel?: string;
summaryPrompt?: string;
}
interface CompactionEvent {
firstKeptEntryId: string | null;
lastCompactedEntryId?: string;
compacted: number;
summarized: boolean;
levels?: CompactionLevels; // the tree a hierarchical compaction keeps, its message is the handoff
}
type CompactionAtomKind = 'fact' | 'task' | 'decision' | 'constraint' | 'error' | 'file' | 'thread';
interface CompactionAtom {
kind: CompactionAtomKind;
status: 'open' | 'closed';
text: string;
evidence?: Evidence[]; // quotes of the entries it stands on
verified: boolean; // every quote was found in its entry
}
interface CompactionNode {
from: string; // the first entry it covers
to: string; // the last entry it covers
atoms: CompactionAtom[];
}
interface CompactionLevels {
saga?: CompactionNode;
arcs: CompactionNode[]; // oldest first
chapters: CompactionNode[]; // oldest first
}
interface MemoryCompactionConfig extends Partial<
Omit<CompactionConfig, 'strategy' | 'threshold' | 'messageThreshold'>
> {
at?: number; // share of the model's context window that starts a compaction (default 0.8)
beforeCompact?: (
event: BeforeCompactEvent
) => void | false | { instructions?: string } | Promise<void | false | { instructions?: string }>;
afterCompact?: (result: CompactionResult) => void | Promise<void>;
}
interface BeforeCompactEvent {
threadId: string;
tokens: number; // tokens of the thread's conversation
threshold: number; // tokens past which it is compacted
}MemoryCompactionConfig compacts a run's thread hierarchically after the run, keeping the newest keepRecentTokens (by default the less of 20000 and a quarter of the window). beforeCompact returns false to skip a compaction or { instructions } to add to the summarizer's prompt. See Compaction After a Run.
Memory items are what conversations established, kept with their quotes, their trust and when they held:
type MemoryItemKind = 'fact' | 'event' | 'preference' | 'instruction' | 'opinion' | 'lesson';
type MemoryItemStatus = 'suggested' | 'active' | 'stale' | 'superseded';
type MemoryItemTrust = 'user' | 'system' | 'model' | 'tool' | 'web';
type TimePrecision = 'instant' | 'day' | 'week' | 'month' | 'year' | 'approximate';
interface MemoryItemScope {
agentId: string;
userId?: string; // seen only by runs for this user
projectId?: string;
threadId?: string; // seen only in this thread
}
interface MemoryItemTime {
text?: string; // the words, such as 'last Friday'
start?: Date; // inclusive, absent when the words could not be resolved
end?: Date; // exclusive
precision: TimePrecision;
}
interface MemoryItem {
id: string;
kind: MemoryItemKind;
content: string; // one statement that reads on its own
subject?: string; // the entity it is about, as said
entityId?: string; // the entity subject was linked to
attribute?: string; // what about the subject it records, such as 'home city'
value?: string;
slot?: string; // the state it records: a newer active item of the slot supersedes it
status: MemoryItemStatus;
trust: MemoryItemTrust;
confidence: number; // 0 to 1
scope: MemoryItemScope;
evidence: Evidence[];
verified: boolean; // every quote was found in its entry
saidAt: Date;
sessionAt: Date; // the date relative dates are resolved against
about?: MemoryItemTime;
validFrom?: Date; // when it started to hold in the world, for an item of a slot
validTo?: Date; // when it stopped, once a newer item closed it
recordedAt: Date; // when memory took it in
expiredAt?: Date; // when memory let it go: kept, no longer found
supersedes?: string[];
supersededBy?: string;
metadata?: Record<string, unknown>;
}
type NewMemoryItem = Omit<
MemoryItem,
'id' | 'status' | 'recordedAt' | 'supersedes' | 'supersededBy' | 'expiredAt' | 'verified'
> & {
status?: MemoryItemStatus; // overrides the status memory would give it
verified?: boolean; // default false
recordedAt?: Date; // default now
};
interface MemoryEntity {
id: string;
scope: MemoryItemScope;
name: string;
aliases: string[];
type?: string; // such as 'person' or 'place'
firstSeenAt: Date;
lastSeenAt: Date;
}
interface MemoryItemQuery {
scope: MemoryItemScope;
kinds?: MemoryItemKind[];
statuses?: MemoryItemStatus[]; // default ['active', 'superseded'], which state holds read from the times
slots?: string[];
entityIds?: string[];
asOf?: Date; // the moment in the world: items of a slot that held then (default: knownAt)
knownAt?: Date; // the moment of memory: items memory had then (default: now)
includeClosed?: boolean; // keep items that no longer hold
text?: string; // words every found item holds, without case
limit?: number; // the newest recorded
}
interface MemoryItemFilter {
agentId: string;
ids?: string[];
slots?: string[];
entityIds?: string[];
kinds?: MemoryItemKind[];
statuses?: MemoryItemStatus[];
includeExpired?: boolean; // an item whose expiredAt is still to come is found either way
visibleTo?: MemoryItemScope; // items this scope sees: each of userId, projectId, threadId absent or the same (agentId not read)
scope?: MemoryItemScope; // items of exactly this scope (agentId not read)
}
interface MemoryEntityFilter {
agentId: string;
ids?: string[];
names?: string[]; // normalized names or aliases
}
interface MemoryItemAdapter {
putItem(item: MemoryItem): Promise<MemoryResult<MemoryItem>>;
getItem(itemId: string): Promise<MemoryResult<MemoryItem | null>>;
findItems(filter: MemoryItemFilter): Promise<MemoryResult<MemoryItem[]>>; // oldest recorded first
deleteItems(itemIds: string[]): Promise<MemoryResult<void>>;
putEntity(entity: MemoryEntity): Promise<MemoryResult<MemoryEntity>>;
findEntities(filter: MemoryEntityFilter): Promise<MemoryResult<MemoryEntity[]>>;
deleteEntities(entityIds: string[]): Promise<MemoryResult<void>>;
}
interface MemoryExtractionConfig {
model?: string; // default: the model the run ended on
prompt?: string; // added to the extraction prompt
windowTokens?: number; // conversation one call reads (default 4000)
activationConfidence?: number; // default 0.7
mode?: 'apply' | 'shadow'; // default 'apply', 'shadow' keeps every new item suggested
scope?: 'user' | 'agent' | 'thread'; // default 'user'
timeZone?: string; // IANA, when the thread names none in metadata.timeZone (default UTC)
afterExtract?: (items: MemoryItem[]) => void | Promise<void>;
}MemoryExtractionConfig extracts memory items from a run's conversation after the run, see Extraction After a Run.
Memory files are notes an agent keeps under /memories with the memory tool, every change a version of its own that only a redaction changes afterwards:
type MemoryFileAuthor = 'model' | 'user' | 'system';
interface MemoryFileVersion {
id: string;
scope: MemoryItemScope;
path: string; // starting with /memories/
sequence: number; // its place among the versions of its path in its scope, from 1
content: string | null; // null when this version deletes the file
sha256: string | null;
previousId: string | null; // the version this one replaces, null for a new file
place?: { threadId: string; entryId: string }; // seen in its thread only on branches holding the entry
renamedFrom?: string;
author: MemoryFileAuthor;
createdAt: Date;
redacted?: { at: Date; reason?: string };
}
interface MemoryFileFilter {
agentId: string;
ids?: string[];
paths?: string[];
prefix?: string; // versions of the paths under this one
visibleTo?: MemoryItemScope;
scope?: MemoryItemScope;
}
interface MemoryFileHeadFilter extends Omit<MemoryFileFilter, 'ids'> {
place?: { threadId: string; pathIds: readonly string[] }; // the branch a run stands on
}
const MEMORY_FILE_CONFLICT = 'memory-file-conflict'; // the error of a version whose place is taken
interface MemoryFileAdapter {
putFileVersions(versions: MemoryFileVersion[]): Promise<MemoryResult<MemoryFileVersion[]>>; // all or none
findFileVersions(filter: MemoryFileFilter): Promise<MemoryResult<MemoryFileVersion[]>>; // oldest first
redactFileVersions(
ids: string[],
redaction: { content: string; sha256: string; at: Date; reason?: string }
): Promise<MemoryResult<void>>;
deleteFileVersions(ids: string[]): Promise<MemoryResult<void>>;
withdrawFileVersions?(ids: string[], at: Date): Promise<MemoryResult<void>>; // optional
findFileHeads?(filter: MemoryFileHeadFilter): Promise<MemoryResult<MemoryFileVersion[]>>; // optional, oldest first
}Errors
class CogitatorError extends Error {
readonly code: ErrorCode;
readonly statusCode: number; // default: ERROR_STATUS_CODES[code]
readonly details?: ErrorDetails;
readonly retryable: boolean; // default: false
readonly retryAfter?: number; // ms
constructor(options: CogitatorErrorOptions); // { message, code, statusCode?, details?, cause?, retryable?, retryAfter? }
toJSON(): Record<string, unknown>;
static isCogitatorError(error: unknown): error is CogitatorError;
static wrap(error: unknown, code?: ErrorCode): CogitatorError; // default code: INTERNAL_ERROR
}
enum ErrorCode {
LLM_UNAVAILABLE = 'LLM_UNAVAILABLE',
LLM_RATE_LIMITED = 'LLM_RATE_LIMITED',
LLM_TIMEOUT = 'LLM_TIMEOUT',
LLM_INVALID_RESPONSE = 'LLM_INVALID_RESPONSE',
LLM_CONTEXT_LENGTH_EXCEEDED = 'LLM_CONTEXT_LENGTH_EXCEEDED',
LLM_CONTENT_FILTERED = 'LLM_CONTENT_FILTERED',
LLM_QUOTA_EXCEEDED = 'LLM_QUOTA_EXCEEDED', // out of credits or over a quota, never retried
SANDBOX_UNAVAILABLE = 'SANDBOX_UNAVAILABLE',
SANDBOX_TIMEOUT = 'SANDBOX_TIMEOUT',
SANDBOX_OOM = 'SANDBOX_OOM',
SANDBOX_EXECUTION_FAILED = 'SANDBOX_EXECUTION_FAILED',
SANDBOX_INVALID_MODULE = 'SANDBOX_INVALID_MODULE',
TOOL_NOT_FOUND = 'TOOL_NOT_FOUND',
TOOL_INVALID_ARGS = 'TOOL_INVALID_ARGS',
TOOL_EXECUTION_FAILED = 'TOOL_EXECUTION_FAILED',
TOOL_TIMEOUT = 'TOOL_TIMEOUT',
TOOL_LOCK_CYCLE = 'TOOL_LOCK_CYCLE',
MEMORY_UNAVAILABLE = 'MEMORY_UNAVAILABLE',
MEMORY_WRITE_FAILED = 'MEMORY_WRITE_FAILED',
MEMORY_READ_FAILED = 'MEMORY_READ_FAILED',
THREAD_ACCESS_DENIED = 'THREAD_ACCESS_DENIED',
AGENT_NOT_FOUND = 'AGENT_NOT_FOUND',
AGENT_ALREADY_RUNNING = 'AGENT_ALREADY_RUNNING',
AGENT_MAX_ITERATIONS = 'AGENT_MAX_ITERATIONS',
RUN_TOKEN_LIMIT_EXCEEDED = 'RUN_TOKEN_LIMIT_EXCEEDED',
RUN_NOT_PAUSED = 'RUN_NOT_PAUSED',
RUN_TIMEOUT = 'RUN_TIMEOUT',
RUN_STEP_TIMEOUT = 'RUN_STEP_TIMEOUT', // a model call outlasted timeouts.stepMs
RUN_CHUNK_TIMEOUT = 'RUN_CHUNK_TIMEOUT', // a streamed model call sent no chunk for timeouts.chunkMs
BUDGET_EXCEEDED = 'BUDGET_EXCEEDED',
TRIGGER_NOT_FOUND = 'TRIGGER_NOT_FOUND', // no routine, trigger or inbox item with that id (404)
INBOX_ITEM_ANSWERED = 'INBOX_ITEM_ANSWERED', // an inbox item answered or archived already (409)
WORKFLOW_NOT_FOUND = 'WORKFLOW_NOT_FOUND',
WORKFLOW_STEP_FAILED = 'WORKFLOW_STEP_FAILED',
WORKFLOW_CYCLE_DETECTED = 'WORKFLOW_CYCLE_DETECTED',
SWARM_NO_WORKERS = 'SWARM_NO_WORKERS',
SWARM_CONSENSUS_FAILED = 'SWARM_CONSENSUS_FAILED',
PROMPT_INJECTION_DETECTED = 'PROMPT_INJECTION_DETECTED',
PII_DETECTED = 'PII_DETECTED',
GUARDRAIL_TRIPPED = 'GUARDRAIL_TRIPPED', // a middleware tripwire() stopped the run
VALIDATION_ERROR = 'VALIDATION_ERROR',
CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',
INTERNAL_ERROR = 'INTERNAL_ERROR',
NOT_IMPLEMENTED = 'NOT_IMPLEMENTED',
CIRCUIT_OPEN = 'CIRCUIT_OPEN',
}cog.run() throws a CogitatorError when a run hits its timeout (Run timed out after <n>ms, RUN_TIMEOUT), a model call its timeouts.stepMs (RUN_STEP_TIMEOUT) or a stream its timeouts.chunkMs (RUN_CHUNK_TIMEOUT, both 504), when cost routing finds the budget exceeded (Budget exceeded: …, BUDGET_EXCEEDED), and when guardrails block the input or output (Input blocked: … / Output blocked: …, LLM_CONTENT_FILTERED, with details.harmScores), so server adapters answer with that status and message.
ERROR_STATUS_CODES maps each code to an HTTP status (for example RUN_TIMEOUT → 504, BUDGET_EXCEEDED → 429, LLM_CONTENT_FILTERED → 400, LLM_QUOTA_EXCEEDED → 402), isRetryableError(error) and getRetryDelay(error, defaultDelay = 1000) read retryable / retryAfter (and treat plain errors mentioning timeouts, connection resets, rate limits, 429 or 503 as retryable).
An LLMError (from @cogitator-ai/core) carries why the provider call failed as kind, also in details.kind:
type LLMErrorKind =
| 'rate_limit' // retrying after a wait helps
| 'quota' // out of credits or over a daily or billing quota
| 'authentication'
| 'permission'
| 'not_found'
| 'invalid_request'
| 'context_overflow'
| 'content_filter'
| 'overloaded'
| 'server_error'
| 'timeout'
| 'network'
| 'invalid_response';See Error Kinds for the code each kind maps to and how each provider is read.
Other Modules
The package also defines the types of the other packages, among them:
| Module | Main types |
|---|---|
| Workflows | Workflow, WorkflowState, WorkflowNode, NodeContext, NodeResult, WorkflowResult, CheckpointStore, ApprovalStore, TimerStore, RunStore — see Workflows API |
| Swarms | SwarmConfig, SwarmRunOptions, StrategyResult, MessageBus, Blackboard, SwarmEvent — see Swarms API |
| Sandbox | SandboxConfig, SandboxManagerConfig, SandboxExecutionRequest (with signal to stop it), SandboxExecutionResult - see Sandbox |
| Reflection, learning, time travel | ReflectionConfig, Insight, ExecutionTrace, ToTConfig, ExecutionCheckpoint, TraceDiff |
| Guardrails, cost routing, security | GuardrailConfig, Constitution, CostRoutingConfig, BudgetConfig, PromptInjectionConfig, PiiType |
| Prompt optimization | InstructionVersion, InstructionVersionStore, ABTest, ABTestStore |
| Triggers (experimental) | TriggersConfig, RoutineDefinition, TriggerSpec, TriggerEvent, TriggerFireResult, RoutineStore, InboxItem, InboxStore, NotificationSink, CronEngine, RoutineSchema, TriggerSpecSchema - see Triggers |
| Knowledge graphs, RAG, voice, channels, sessions, skills, deploy | GraphAdapter, RAGPipelineConfig, Channel, ChannelMessage, Session, Skill, DeployConfig, … |