Cogitator
API Reference

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 {
  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
  instructions: string;
  tools?: Tool[];
  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
}

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.

Run Types

interface RunOptions {
  input: string;
  images?: ImageInput[]; // URLs, base64 or { data, mimeType }
  audio?: AudioInput[]; // transcribed and added to the input
  context?: Record<string, unknown>;
  threadId?: string;
  timeout?: number;
  signal?: AbortSignal;
  stream?: boolean; // streams only together with onToken
  onToken?: (token: string) => void;
  onReasoning?: (delta: string) => void;
  onHandoff?: (handoff: HandoffEvent) => void;
  reasoning?: ReasoningConfig; // overrides the agent's
  onApproval?: (
    request: ToolApprovalRequest
  ) => ToolApprovalDecision | 'pause' | Promise<ToolApprovalDecision | 'pause'>;
  onToolCall?: (call: ToolCall) => void;
  onToolResult?: (result: ToolResult) => void;
  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) => void;
  onSpan?: (span: Span) => void;
  onMemoryError?: (error: Error, operation: 'save' | 'load') => void;
  parallelToolCalls?: boolean; // default: false
  userId?: string; // owns new threads, scopes facts, reaches tools as context.userId
  threadAccess?: 'owner' | 'shared'; // default: 'owner'
  channelType?: string;
  channelId?: string;
}

interface RunResult {
  readonly output: string;
  readonly structured?: unknown;
  readonly runId: string;
  readonly agentId: string;
  readonly threadId: string;
  readonly modelUsed?: string;
  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 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;
}

interface HandoffEvent {
  from: string;
  to: string;
  reason?: string;
}

Approvals

interface ToolApprovalRequest {
  toolCallId: string;
  toolName: string;
  arguments: Record<string, unknown>;
  description: string;
  sideEffects?: 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, …) that cogitator.resume() continues from.

Tool Types

interface Tool<TParams = unknown, TResult = unknown> {
  name: string;
  description: string;
  category?: ToolCategory;
  tags?: string[];
  parameters: ZodType<TParams>;
  execute(params: TParams, context: ToolContext): Promise<TResult>;
  sideEffects?: SideEffectType[];
  requiresApproval?: boolean | ApprovalCheck;
  timeout?: number;
  sandbox?: SandboxConfig;
  toJSON(): ToolSchema;
}

interface ToolConfig<TParams = unknown, TResult = unknown> {
  name: string;
  description: string;
  category?: ToolCategory;
  tags?: string[];
  parameters: ZodType<TParams>;
  execute: (params: TParams, context: ToolContext) => Promise<TResult>;
  sideEffects?: SideEffectType[];
  requiresApproval?: boolean | ((params: TParams) => boolean);
  timeout?: number;
  sandbox?: SandboxConfig;
}

type ApprovalCheck = (params: Record<string, unknown>) => boolean;

type ToolCategory =
  | 'math'
  | 'text'
  | 'file'
  | 'network'
  | 'system'
  | 'utility'
  | 'web'
  | 'database'
  | 'communication'
  | 'development';

type SideEffectType = 'filesystem' | 'network' | 'database' | 'process' | 'external';

interface ToolContext {
  agentId: string;
  runId: string;
  signal: AbortSignal;
  threadId?: string;
  userId?: string;
  channelType?: string;
  channelId?: string;
}

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;
  error?: string;
}

interface ToolSchema {
  name: string;
  description: string;
  parameters: {
    type: 'object';
    properties: Record<string, unknown>;
    required?: string[];
  };
}

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;
}

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.

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;
  signal?: AbortSignal;
}

interface ChatResponse {
  id: string;
  content: string;
  toolCalls?: ToolCall[];
  finishReason: 'stop' | 'tool_calls' | 'length' | 'error';
  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?: 'stop' | 'tool_calls' | 'length' | 'error';
  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
  onRetry?: (event: LLMRetryEvent) => void;
}

interface PromptCacheConfig {
  ttl?: '5m' | '1h'; // Anthropic cache lifetime, default 5m
}

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
}
type OpenAIWireApi = 'responses' | 'chat-completions';
interface AnthropicProviderConfig {
  apiKey: string;
}
interface GoogleProviderConfig {
  apiKey: string;
}
interface AzureProviderConfig {
  endpoint: string;
  apiKey: string;
  apiVersion?: string;
  deployment?: string;
}
interface BedrockProviderConfig {
  region?: string;
  accessKeyId?: string;
  secretAccessKey?: string;
}
interface VLLMProviderConfig {
  baseUrl: string;
}
// 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
  };
  runCheckpoints?: RunCheckpointStore; // where paused runs wait
  prompts?: PromptsConfig; // instruction versions and A/B tests
  limits?: {
    maxConcurrentRuns?: number;
    defaultTimeout?: number;
    maxTokensPerRun?: number;
  };
  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>;
}

type EmbeddingServiceConfig = OpenAIEmbeddingConfig | OllamaEmbeddingConfig | GoogleEmbeddingConfig;

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.

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',
  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',
  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',
  BUDGET_EXCEEDED = 'BUDGET_EXCEEDED',
  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',
  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), 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); 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).

Other Modules

The package also defines the types of the other packages, among them:

ModuleMain types
WorkflowsWorkflow, WorkflowState, WorkflowNode, NodeContext, NodeResult, WorkflowResult, CheckpointStore, ApprovalStore, TimerStore, RunStore — see Workflows API
SwarmsSwarmConfig, SwarmRunOptions, StrategyResult, MessageBus, Blackboard, SwarmEvent — see Swarms API
SandboxSandboxConfig, SandboxManagerConfig, SandboxExecutionRequest, SandboxExecutionResult
Reflection, learning, time travelReflectionConfig, Insight, ExecutionTrace, ToTConfig, ExecutionCheckpoint, TraceDiff
Guardrails, cost routing, securityGuardrailConfig, Constitution, CostRoutingConfig, BudgetConfig, PromptInjectionConfig, PiiType
Prompt optimizationInstructionVersion, InstructionVersionStore, ABTest, ABTestStore
Knowledge graphs, RAG, voice, channels, sessions, skills, deployGraphAdapter, RAGPipelineConfig, Channel, ChannelMessage, Session, Skill, DeployConfig, …

On this page