@cogitator-ai/types

中文文档
0.89.0发布于 2026/10/29MITTypeScriptES Module近 30 天下载 2.4万

Shared TypeScript types for Cogitator

原始使用文档
文档目录26 节
  1. Installation
  2. Quick Start
  3. Type Categories
  4. Message Types
  5. Message Interfaces
  6. Tool Types
  7. Tool Interfaces
  8. Tool Options
  9. Reading Tool Results
  10. Agent Types
  11. LLM Types
  12. Runtime Types
  13. Approvals, Handoffs and Pauses
  14. Run Middleware
  15. RunResult
  16. Error Types
  17. Error Codes
  18. Reflection Types
  19. Reasoning Types
  20. Learning Types
  21. Time Travel Types
  22. Memory Types
  23. Knowledge Graph Types
  24. Prompt Optimization Types
  25. Other Modules
  26. License

@cogitator-ai/types

npm version License: MIT

Shared TypeScript types for the Cogitator AI agent runtime.

Installation

pnpm add @cogitator-ai/types

Types only, plus a few runtime values (CogitatorError, ErrorCode, DEFAULT_* configs). zod is a dependency because tool parameters and structured output schemas are Zod types. Most applications get these types re-exported from @cogitator-ai/core; install this package directly to implement adapters or stores without the runtime.

Reference on the website: Types API.

Quick Start

import type {
  Agent,
  AgentConfig,
  Tool,
  ToolConfig,
  Message,
  RunResult,
  CogitatorConfig,
} from '@cogitator-ai/types';

Type Categories

CategoryDescription
MessageChat messages, tool calls, tool results
ToolTool definitions with Zod schemas
AgentAgent configuration and interface
LLMLLM backend and provider types
RuntimeCogitator config, run options, results
ErrorsStructured error handling
ReflectionSelf-analyzing agent types
ReasoningTree-of-Thought reasoning
LearningDSPy-style optimization
Time TravelExecution debugging
Knowledge GraphEntity-relationship memory
Prompt OptimizationA/B testing, monitoring, rollback
Other ModulesWorkflows, swarms, security, RAG, voice…

Message Types

Types for LLM conversations and tool interactions.

import type {
  Message,
  MessageRole,
  ToolCall,
  ToolResult,
  ToolCallMessage,
  ToolResultMessage,
} from '@cogitator-ai/types';

// Basic message
const userMessage: Message = {
  role: 'user',
  content: 'What is 2 + 2?',
};

// Assistant message with tool calls
const assistantMessage: ToolCallMessage = {
  role: 'assistant',
  content: '',
  toolCalls: [
    {
      id: 'call_123',
      name: 'calculator',
      arguments: { expression: '2 + 2' },
    },
  ],
};

// Tool result message
const toolResult: ToolResultMessage = {
  role: 'tool',
  content: '4',
  toolCallId: 'call_123',
  name: 'calculator',
};

Message Interfaces

TypeDescription
MessageRole'system' | 'user' | 'assistant' | 'tool'
MessageBase message with role, content, optional name/toolCallId
MessageContentstring or ContentPart[] (text, image_url, image_base64)
ToolCallMessageAssistant message containing tool calls
ToolResultMessageTool execution result
ToolCallTool invocation with id, name, arguments, thoughtSignature, replay
ToolResultTool execution result with callId, name, result, error

Tool Types

Types for defining agent tools with Zod schemas.

import type { ToolConfig } from '@cogitator-ai/types';
import { z } from 'zod';

// Tool configuration
const calculatorConfig: ToolConfig<{ expression: string }, number> = {
  name: 'calculator',
  description: 'Evaluate mathematical expressions',
  category: 'math',
  parameters: z.object({
    expression: z.string().describe('Math expression to evaluate'),
  }),
  execute: async (params, context) => {
    console.log(`Run ${context.runId} executing calculator`);
    return Number(params.expression);
  },
  timeout: 5000,
  sideEffects: [],
};

// Tool context available during execution
interface BaseToolContext<TDeps = unknown> {
  agentId: string;
  runId: string;
  signal: AbortSignal; // aborted on run cancel or tool timeout
  toolCallId?: string;
  threadId?: string;
  userId?: string;
  channelType?: string;
  channelId?: string;
  deps?: TDeps; // RunOptions.deps, never sent to the model
  update?: (progress: ToolProgress) => void; // what the tool has so far, never sent to the model
}

// ToolContext<AppDeps> has deps present and typed
type ToolContext<TDeps = unknown> = unknown extends TDeps
  ? BaseToolContext
  : BaseToolContext<TDeps> & { deps: TDeps };

Tool Interfaces

TypeDescription
ToolConfig<TParams, TResult>Tool definition with execute function
Tool<TParams, TResult>Full tool with toJSON() method
ToolContextExecution context with agentId, runId, signal, threadId, userId, channel and the run's deps
SideEffectType'filesystem' | 'network' | 'database' | 'process' | 'external'
ApprovalCheck(params) => boolean form of requiresApproval
ToolSchemaJSON Schema representation for LLM
ToolCategory'math' | 'text' | 'file' | 'network' | 'system' | 'utility' | 'web' | 'database' | 'communication' | 'development'
ToolContentResultA result made of parts, built with toolContent() of @cogitator-ai/core
ToolContentPartToolTextPart | ToolImagePart | ToolFilePart | ToolJsonPart | ToolResourcePart
ToolOutputResultA result split by reader, built with toolOutput(): content for the model, details and presentation for the application
ToolPresentationHow a client shows a call: label, icon?, detail?
ToolProgress, ToolUpdateWhat context.update() reports, and what onToolUpdate gets (with callId and name)
ToolInputStart, ToolInputDelta, ToolInputAvailable, ToolInputAbandonedA tool call as the model writes it, or one that will not run, in a streamed run
ToolInputStreamPartA start, delta or end part of ChatStreamChunk.delta.toolInput, for backends that stream tool input
RunTimeoutstotalMs, stepMs, chunkMs, toolMs of RunOptions.timeouts and AgentConfig.timeouts

Tool Options

import type { ToolConfig } from '@cogitator-ai/types';
import { z } from 'zod';

const advancedTool: ToolConfig<{ path: string; content: string }, void> = {
  name: 'file_write',
  description: 'Write content to a file',
  parameters: z.object({
    path: z.string(),
    content: z.string(),
  }),
  execute: async ({ path, content }) => {
    console.log(`Writing ${content.length} chars to ${path}`);
  },

  // Optional configuration
  category: 'file',
  tags: ['io', 'filesystem'],
  sideEffects: ['filesystem'],
  requiresApproval: true, // or (params) => params.path.includes('/etc')
  timeout: 10000,
  sandbox: { type: 'docker', image: 'node:20' },
  maxResultLength: 20_000, // characters of the result the model reads
  isConcurrencySafe: false, // or (params) => boolean, default: annotations.readOnlyHint
  lockKeys: ({ path }) => [`file:${path}`], // calls whose keys meet never run at the same time
  presentation: ({ path }) => ({ label: 'Write file', icon: 'file-plus', detail: path }),
};

providerTypes (ProviderToolTypes) names the tool's type in a provider's own catalog, sent to that provider instead of the schema, such as { anthropic: 'memory_20250818' } for a tool Claude knows from its training, while every other provider gets the schema. ToolSchema carries it too.

Reading Tool Results

A few dependency-free helpers read tool results the way a run does, so packages that do not depend on @cogitator-ai/core (voice sessions, adapters) treat them the same. @cogitator-ai/core re-exports them.

FunctionDescription
isToolContentResult(value)Whether a result is a ToolContentResult
isToolOutputResult(value)Whether a result is a ToolOutputResult
toolOutputContent(value)What the model reads of a result: the content of a toolOutput() result, else the result
toolResultParts(value)The parts of a result with media (a toolContent() result or an object with a base64 image)
toolPartsToText(parts)The text of the parts, images, files and binary resources described, JSON as JSON text
truncateToolResultText(text, max)text cut to max characters, start and end kept, with a note of how much was left out
DEFAULT_TOOL_RESULT_MAX_LENGTH100_000, the characters of a result a model reads unless configured otherwise

Agent Types

Types for agent configuration.

import type { Agent, AgentConfig, ResponseFormat, Tool } from '@cogitator-ai/types';
import { z } from 'zod';

declare const calculatorTool: Tool;
declare const billingAgent: Agent;

const config: AgentConfig = {
  name: 'research-agent',
  model: 'openai/gpt-6.1-sol',
  instructions: 'You are a research assistant...',

  // Optional settings
  description: 'Helps with research tasks',
  tools: [calculatorTool],
  temperature: 0.7,
  topP: 0.9,
  maxTokens: 4096,
  stopSequences: ['END'],
  maxIterations: 10,
  timeout: 60000,

  // Response format
  responseFormat: { type: 'json' },

  // Reasoning effort for reasoning models, in one vocabulary for every provider
  reasoning: { effort: 'medium', summary: true },

  // Agents this one can hand the conversation to (transfer_to_<name> tools)
  handoffs: [
    billingAgent,
    { agent: billingAgent, toolName: 'to_billing', description: 'Invoices' },
  ],
};

// Response format options
const textFormat: ResponseFormat = { type: 'text' };
const jsonFormat: ResponseFormat = { type: 'json' };
const schemaFormat: ResponseFormat = {
  type: 'json_schema',
  schema: z.object({ answer: z.string() }),
};

AgentConfig also takes id, provider (an explicit backend name), skills (Skill bundles of tools and instructions) and fallbackModels (FallbackModel: models a turn moves to when model fails). AgentConfig<TDeps> with a deps type refuses tools whose deps type is unrelated to it, and RunOptions<TDeps>.deps carries them to the tools (RunDeps<TDeps> makes them required). AgentSnapshot / SerializedAgentConfig describe the JSON form of agent.serialize().


LLM Types

Types for LLM backends and providers.

import type {
  LLMProvider,
  LLMBackendProvider,
  LLMConfig,
  LLMBackend,
  ChatRequest,
  ChatResponse,
  ChatStreamChunk,
  ChatUsage,
  OpenAIProviderConfig,
  OpenAICompatibleProfile,
  OpenAICompatibleServer,
  ModelPriceConfig,
  ReasoningConfig,
  PromptCacheConfig,
} from '@cogitator-ai/types';

// Supported providers
type LLMProvider =
  | 'ollama'
  | 'openai'
  | 'anthropic'
  | 'google'
  | 'azure'
  | 'bedrock'
  | 'vllm'
  | 'mistral'
  | 'groq'
  | 'together'
  | 'deepseek';

// What LLMBackend.provider reports: a built-in provider, or the name of your
// own backend (llm.backends) or of a registered plugin
type LLMBackendProvider = LLMProvider | (string & {});

// LLM configuration
const llmConfig: LLMConfig = {
  provider: 'openai',
  model: 'gpt-6.1-sol',
  temperature: 0.7,
  maxTokens: 4096,
};

// Chat request
const request: ChatRequest = {
  model: 'gpt-6.1-sol',
  messages: [{ role: 'user', content: 'Hello' }],
  tools: [{ name: 'calc', description: '...', parameters: { type: 'object', properties: {} } }],
  stream: true,
};

// Chat response
const response: ChatResponse = {
  id: 'chatcmpl-123',
  content: 'Hello! How can I help?',
  finishReason: 'stop',
  usage: { inputTokens: 10, outputTokens: 20, totalTokens: 30 },
};

// Token usage; cached and reasoning tokens are already included in the totals
const usage: ChatUsage = {
  inputTokens: 1200,
  outputTokens: 300,
  totalTokens: 1500,
  cachedInputTokens: 1024,
  reasoningTokens: 120,
};

// OpenAI provider: Responses API for api.openai.com, Chat Completions for other base URLs
const openaiConfig: OpenAIProviderConfig = {
  apiKey: process.env.OPENAI_API_KEY!,
  api: 'chat-completions', // force a wire API: 'responses' | 'chat-completions'
};

// An OpenAI-compatible server: what it takes (OpenAICompatibleProfile over an OpenAICompatibleServer preset)
const lmStudio: OpenAIProviderConfig = {
  apiKey: 'lm-studio',
  baseUrl: 'http://localhost:1234/v1',
  profile: { server: 'lmstudio', reasoningEffort: ['low', 'medium', 'high'] },
  headers: { 'X-Team': 'search' }, // sent with every request
};

// A price of your own for CogitatorConfig.llm.pricing, USD per million tokens
const price: ModelPriceConfig = { input: 0.6, output: 0.6, inputCached: 0.06 };

// Reasoning effort, mapped per provider (Anthropic effort / thinking, OpenAI reasoning.effort, Gemini thinking, Ollama think)
const reasoning: ReasoningConfig = { effort: 'high', budgetTokens: 8000, summary: true };
// effort: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'

// Prompt caching for agent runs (CogitatorConfig.llm.promptCache)
const promptCache: PromptCacheConfig = { ttl: '1h' }; // '5m' (default) | '1h'

OllamaProviderConfig, AnthropicProviderConfig and GoogleProviderConfig take baseUrl and headers (Google's baseUrl includes the API version), VLLMProviderConfig takes profile and headers, OpenRouterProviderConfig takes headers, and BedrockProviderConfig takes endpoint for a VPC endpoint or a proxy. Ollama sends these headers with non-streaming and streaming chat requests to /api/chat, keeps the JSON content type and gives apiKey precedence over custom authorization headers regardless of casing.

LLMRetryConfig (maxRetries, baseDelay, maxDelay, maxRetryAfter, requestTimeout, onRetry) types CogitatorConfig.llm.retry; ModelRoute is what cog.route() resolves a model string to.

ToolCall.argumentsError says why the arguments of a call could not be read, such as JSON the provider broke: the call has empty arguments, never runs, and the model is told why.

ToolCall.replay (ToolCallReplayState) carries opaque provider output that must be sent back with the call on the next turn, such as OpenAI Responses reasoning items. It is JSON-serializable, so it survives memory persistence; backends that did not produce it ignore it.


Runtime Types

Types for Cogitator runtime configuration and execution.

import type { CogitatorConfig, RunOptions, RunResult, Span } from '@cogitator-ai/types';

// Cogitator configuration
const config: CogitatorConfig = {
  llm: {
    defaultProvider: 'openai',
    defaultModel: 'gpt-6.1-sol',
    providers: {
      openai: { apiKey: process.env.OPENAI_API_KEY! },
      ollama: { baseUrl: 'http://localhost:11434' },
      anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
    },
  },
  limits: {
    maxConcurrentRuns: 10,
    defaultTimeout: 30000,
    maxTokensPerRun: 100000,
  },
  memory: { adapter: 'redis', redis: { host: 'localhost' } },
  sandbox: { defaults: { type: 'docker', image: 'node:20-alpine' } },
  reflection: { enabled: true, reflectAfterError: true },
  security: {
    promptInjection: { action: 'block' },
    pii: { mode: 'mask', custom: [{ type: 'customer_id', pattern: /CUS-\d{6}/ }] },
  },
  prompts: { autoDeployWinner: true }, // versioned instructions and A/B tests
};

// Run options with callbacks
const runOptions: RunOptions = {
  input: 'Calculate 2 + 2',
  context: { plan: 'pro' },
  threadId: 'thread_abc',
  userId: 'user_123', // owns the thread; reaches tools as context.userId
  threadAccess: 'owner', // or 'shared'
  timeout: 30000,
  timeouts: { stepMs: 20_000, chunkMs: 10_000, toolMs: 5_000 }, // RunTimeouts, each off unless set
  stream: true,
  reasoning: { effort: 'low' },

  // Callbacks
  onToken: (token) => process.stdout.write(token),
  onToolCall: (call) => console.log('Tool called:', call.name),
  onToolResult: (result) => console.log('Tool result:', result.result, result.details),
  onToolUpdate: (update) => console.log('Progress:', update.callId, update.content),
  onToolInputDelta: ({ toolCallId, delta }) => console.log(toolCallId, delta), // needs stream: true
  onRunStart: ({ runId }) => console.log('Started:', runId),
  onRunComplete: (result) => console.log('Done:', result.output),
  onRunError: (error) => console.error('Error:', error),
  onSpan: (span) => console.log('Span:', span.name),
  onReasoning: (delta) => process.stdout.write(delta),
  onHandoff: (handoff) => console.log(`${handoff.from} -> ${handoff.to}`),
  onApproval: (request) => (request.toolName === 'refund' ? 'pause' : { approved: true }),

  // Memory options
  useMemory: true,
  loadHistory: true,
  saveHistory: true,
  parallelToolCalls: true, // concurrency-safe calls of a step run together (default: false)
  maxParallelToolCalls: 4, // default: 10
};

Approvals, Handoffs and Pauses

TypeDescription
ToolApprovalRequestA tool call waiting for a decision: toolCallId, toolName, arguments, description, sideEffects
ToolApprovalDecision{ approved: true } or { approved: false; reason? }
RunCheckpointJSON snapshot of a paused run, passed to cogitator.resume()
RunCheckpointStoresave / load(threadId) / delete for paused runs (CogitatorConfig.runCheckpoints)
ResumeOptionsRun options for resume() plus userId, decisions and defaultDecision
HandoffEvent{ from, to, reason? } for each handoff
PromptsConfigversions / abTests stores, score, autoDeployWinner
RunPromptThe instruction version or A/B variant a run used
PiiConfigmode (mask | redact | block), detect, custom, onDetect

Run Middleware

RunMiddleware hooks around a run's model and tool calls, given in middleware of CogitatorConfig, AgentConfig or RunOptions (see the core README).

TypeDescription
RunMiddlewarename, holdsStream? and the hooks beforeRun, beforeModel, wrapModelCall, afterModel, wrapToolCall
RunMiddlewareContextrunId, threadId, agentId, agentName, userId, channel, iteration, signal, deps and shared state
RunInputEventA new run's input and the messages its first turn starts from
ModelTurnEventThe messages and model of the next turn, ModelTurnUpdate returns new messages
ModelCallRequestThe ChatRequest, the provider/model it goes to and, when streaming, its ModelStreamSink
ModelResponseEventA turn's response, ModelResponseUpdate replaces its content or toolCalls
ToolCallRequestThe toolCall, the tool, the schema-parsed args and whether a person approved it

RunResult

import type { RunResult } from '@cogitator-ai/types';

const result: RunResult = {
  output: 'The answer is 4',
  structured: { answer: 4 }, // if responseFormat was json_schema
  runId: 'run_123',
  agentId: 'agent_456',
  threadId: 'thread_789',
  usage: {
    inputTokens: 100,
    outputTokens: 50,
    totalTokens: 150,
    cost: 0.0023,
    duration: 1500,
  },
  toolCalls: [{ id: 'call_1', name: 'calculator', arguments: { expression: '2+2' } }],
  messages: [],
  trace: {
    traceId: 'trace_abc',
    spans: [],
  },
  status: 'completed', // 'paused' when tool calls wait for approval
};

Optional fields: structured, modelUsed, usage.reasoningTokens / cachedInputTokens / cacheWriteTokens, reasoning, prompt, handoffs, finalAgent, status, pendingApprovals, checkpoint, reflections, reflectionSummary. All fields are readonly.


Error Types

Structured error handling with typed error codes.

import {
  CogitatorError,
  ErrorCode,
  ERROR_STATUS_CODES,
  isRetryableError,
  getRetryDelay,
} from '@cogitator-ai/types';

// Create a structured error
const error = new CogitatorError({
  message: 'LLM backend unavailable',
  code: ErrorCode.LLM_UNAVAILABLE,
  details: { provider: 'openai', endpoint: 'https://api.openai.com' },
  retryable: true,
  retryAfter: 5000,
});

// Check error type
if (CogitatorError.isCogitatorError(error)) {
  console.log(error.code); // 'LLM_UNAVAILABLE'
  console.log(error.statusCode); // 503
  console.log(error.retryable); // true
}

// Wrap any error
const wrapped = CogitatorError.wrap(new Error('timeout'), ErrorCode.LLM_TIMEOUT);

// Check if retryable
if (isRetryableError(error)) {
  const delay = getRetryDelay(error, 1000); // retryAfter, or the default
  await new Promise((resolve) => setTimeout(resolve, delay));
}

console.log(ERROR_STATUS_CODES[ErrorCode.LLM_RATE_LIMITED]); // 429

Error Codes

DomainCodes
LLMLLM_UNAVAILABLE, LLM_RATE_LIMITED, LLM_QUOTA_EXCEEDED, LLM_TIMEOUT, LLM_INVALID_RESPONSE, LLM_CONTEXT_LENGTH_EXCEEDED, LLM_CONTENT_FILTERED
SandboxSANDBOX_UNAVAILABLE, SANDBOX_TIMEOUT, SANDBOX_OOM, SANDBOX_EXECUTION_FAILED, SANDBOX_INVALID_MODULE
ToolTOOL_NOT_FOUND, TOOL_INVALID_ARGS, TOOL_EXECUTION_FAILED, TOOL_TIMEOUT, TOOL_LOCK_CYCLE
MemoryMEMORY_UNAVAILABLE, MEMORY_WRITE_FAILED, MEMORY_READ_FAILED, THREAD_ACCESS_DENIED
AgentAGENT_NOT_FOUND, AGENT_ALREADY_RUNNING, AGENT_MAX_ITERATIONS, RUN_TOKEN_LIMIT_EXCEEDED, RUN_NOT_PAUSED, RUN_TIMEOUT, RUN_STEP_TIMEOUT, RUN_CHUNK_TIMEOUT, BUDGET_EXCEEDED
WorkflowWORKFLOW_NOT_FOUND, WORKFLOW_STEP_FAILED, WORKFLOW_CYCLE_DETECTED
SwarmSWARM_NO_WORKERS, SWARM_CONSENSUS_FAILED
SecurityPROMPT_INJECTION_DETECTED, PII_DETECTED, GUARDRAIL_TRIPPED
GeneralVALIDATION_ERROR, CONFIGURATION_ERROR, INTERNAL_ERROR, NOT_IMPLEMENTED, CIRCUIT_OPEN

LLMErrorKind says why a model provider call failed, finer than the code: rate_limit, quota, authentication, permission, not_found, invalid_request, context_overflow, content_filter, overloaded, server_error, timeout, network or invalid_response. An LLMError of @cogitator-ai/core carries it as kind and details.kind. LLM_QUOTA_EXCEEDED (HTTP 402) is an account out of credits or over a quota that waiting a moment will not lift, and is never retried.

The runtime throws RUN_TIMEOUT (HTTP 504) for a run that hits its timeout (Run timed out after <n>ms), RUN_STEP_TIMEOUT and RUN_CHUNK_TIMEOUT (504) for a model call over timeouts.stepMs or a stream silent for timeouts.chunkMs, BUDGET_EXCEEDED (429) for a run over its cost-routing budget, and LLM_CONTENT_FILTERED (400) when guardrails block the input or output (Input blocked: … / Output blocked: …).


Reflection Types

Types for self-analyzing agents that learn from their actions.

import type {
  Reflection,
  ReflectionConfig,
  ReflectionAction,
  Insight,
  InsightStore,
  ReflectionSummary,
} from '@cogitator-ai/types';

// Reflection configuration
const reflectionConfig: ReflectionConfig = {
  enabled: true,
  reflectAfterToolCall: true,
  reflectAfterError: true,
  reflectAtEnd: true,
  storeInsights: true,
  maxInsightsPerAgent: 100,
  minConfidenceToStore: 0.7,
  useSmallModelForReflection: true,
  reflectionModel: 'gpt-6-luna',
};

// Insight types
type InsightType = 'pattern' | 'mistake' | 'success' | 'tip' | 'warning';

// Reflection result
const reflection: Reflection = {
  id: 'ref_123',
  runId: 'run_456',
  agentId: 'agent_789',
  timestamp: new Date(),
  action: {
    type: 'tool_call',
    toolName: 'search',
    input: { query: 'AI news' },
    output: { results: [] },
    duration: 500,
  },
  analysis: {
    wasSuccessful: false,
    confidence: 0.8,
    reasoning: 'Search returned no results, should try broader query',
    whatCouldImprove: 'Use more general search terms',
  },
  insights: [
    {
      id: 'ins_1',
      type: 'tip',
      content: 'Broaden search queries when results are empty',
      context: 'search operations',
      confidence: 0.85,
      usageCount: 0,
      createdAt: new Date(),
      lastUsedAt: new Date(),
      agentId: 'agent_789',
      source: { runId: 'run_456', reflectionId: 'ref_123' },
    },
  ],
  goal: 'Find recent AI news',
  iterationIndex: 2,
};

Reasoning Types

Tree-of-Thought (ToT) reasoning types for branching exploration.

import type {
  ToTConfig,
  ThoughtTree,
  ThoughtNode,
  ThoughtBranch,
  ToTResult,
  ExplorationStrategy,
} from '@cogitator-ai/types';

// ToT configuration
const totConfig: ToTConfig = {
  branchFactor: 3, // Generate 3 candidate thoughts per step
  beamWidth: 2, // Queue the best 2 candidates per expanded node
  maxDepth: 5, // Max reasoning depth
  explorationStrategy: 'beam', // 'beam' | 'best-first' | 'dfs'

  confidenceThreshold: 0.3,
  terminationConfidence: 0.8,
  maxTotalNodes: 50,
  maxIterationsPerBranch: 3, // Iteration cap for each branch run

  // Callbacks
  onBranchGenerated: (node, branches) => console.log('Generated:', branches.length),
  onBranchEvaluated: (branch, score) => console.log('Score:', score.composite),
  onNodeExplored: (node) => console.log('Explored:', node.id),
  onBacktrack: (from, to) => console.log('Backtracking...'),
};

// Thought branch with proposed action
const branch: ThoughtBranch = {
  id: 'branch_1',
  parentId: 'node_0',
  thought: 'I should search for the latest information first',
  proposedAction: { type: 'tool_call', toolName: 'search', arguments: { query: 'AI news 2024' } },
  score: { confidence: 0.8, progress: 0.3, novelty: 0.6, composite: 0.57, reasoning: '...' },
  messagesSnapshot: [/* ... */],
};

beam runs the tree level by level, best-first runs the node whose own branch scored highest, and dfs goes deep first; candidates beyond beamWidth wait as pending alternatives for backtracking. maxTotalNodes caps executed nodes, and maxIterationsPerBranch caps each branch run (never above the agent's own maxIterations).


Learning Types

DSPy-inspired agent optimization types.

import type {
  ExecutionTrace,
  TraceStore,
  Demo,
  OptimizerConfig,
  OptimizationResult,
  LearningConfig,
} from '@cogitator-ai/types';

// Learning configuration
const learningConfig: LearningConfig = {
  enabled: true,
  captureTraces: true,
  traceRetention: 1000,
  maxDemosPerAgent: 5,
  minScoreForDemo: 0.8,
  defaultMetrics: ['success', 'tool_accuracy', 'efficiency'],
  customMetrics: [
    { name: 'tool_accuracy', type: 'numeric', description: 'Tools worked', weight: 0.5 },
  ],
};
// autoOptimize, optimizeAfterRuns and traceStore are deprecated and not read

// Optimizer configuration
const optimizerConfig: OptimizerConfig = {
  type: 'full', // 'bootstrap-few-shot' | 'instruction' | 'full'
  maxBootstrappedDemos: 5,
  maxRounds: 3,
  instructionCandidates: 3,
  metricThreshold: 0.7,
  teacherModel: 'gpt-6.1-sol',
};

// Execution trace
const trace: ExecutionTrace = {
  id: 'trace_123',
  runId: 'run_456',
  agentId: 'agent_789',
  threadId: 'thread_abc',
  input: 'Calculate compound interest',
  output: 'The compound interest is $1,628.89',
  steps: [],
  toolCalls: [],
  reflections: [],
  metrics: {
    success: true,
    toolAccuracy: 0.95,
    efficiency: 0.8,
    completeness: 1.0,
    coherence: 0.9,
  },
  score: 0.92,
  model: 'gpt-6.1-sol',
  createdAt: new Date(),
  duration: 1500,
  usage: {
    inputTokens: 100,
    outputTokens: 50,
    cost: 0.0023,
  },
  isDemo: true,
};

Time Travel Types

Execution debugging with checkpoints, replay, and forking.

import type {
  ExecutionCheckpoint,
  TimeTravelCheckpointStore,
  ReplayOptions,
  ReplayResult,
  ForkOptions,
  TraceDiff,
} from '@cogitator-ai/types';

// Checkpoint
const checkpoint: ExecutionCheckpoint = {
  id: 'cp_123',
  traceId: 'trace_456',
  runId: 'run_789',
  agentId: 'agent_abc',
  stepIndex: 5,
  messages: [],
  toolResults: { call_1: 42, call_2: 'result' },
  pendingToolCalls: [],
  label: 'before-critical-decision',
  createdAt: new Date(),
};

// Replay options
const replayOptions: ReplayOptions = {
  fromCheckpoint: 'cp_123',
  mode: 'live', // 'deterministic' | 'live'
  modifiedToolResults: { web_search: { results: [] } }, // by tool name
  skipTools: ['expensive_api'], // removed from the replayed agent
};

// Fork options (branch execution with modifications)
const forkOptions: ForkOptions = {
  checkpointId: 'cp_123',
  input: 'Try a different approach',
  additionalContext: 'Focus on efficiency',
  mockToolResults: { api_call: { mocked: true } },
  label: 'efficiency-experiment',
};

// Compare two execution traces
const diff: TraceDiff = {
  trace1Id: 'trace_a',
  trace2Id: 'trace_b',
  stepDiffs: [
    { index: 0, status: 'identical' },
    { index: 1, status: 'similar', differences: ['different tool args'] },
    { index: 2, status: 'different' }, // step1 / step2 hold the ExecutionSteps
  ],
  commonSteps: 2,
  divergencePoint: 2,
  trace1OnlySteps: 1,
  trace2OnlySteps: 0,
  metricsDiff: {
    success: { trace1: true, trace2: false },
    score: { trace1: 0.9, trace2: 0.6, delta: -0.3 },
    tokens: { trace1: 1200, trace2: 1500, delta: 300 },
    duration: { trace1: 2100, trace2: 2600, delta: 500 },
  },
};

Memory Types

See @cogitator-ai/memory for detailed memory adapter types.

Memory files, notes an agent keeps under /memories with the memory tool, are kept as versions:

TypeDescription
MemoryFileVersionOne version of a file: scope, path, sequence (its place among the versions of its path in its scope), content (null for a deletion), sha256, previousId, place, renamedFrom, author, createdAt, redacted
MemoryFileHeadFilterMemoryFileFilter without ids, and place ({ threadId, pathIds }), the branch a run stands on
MemoryFileAdapterA store of versions: putFileVersions (all or none, MEMORY_FILE_CONFLICT when a place is taken), findFileVersions, redactFileVersions, deleteFileVersions, optional withdrawFileVersions (a withdrawn version, MemoryFileVersion.withdrawn, is never in front but keeps its place in the history), and optional findFileHeads (the newest version of each scope and path a filter and a branch see, MemoryFileHeadFilter). Every built-in memory adapter is one
MemoryFileFilteragentId, and ids, paths, prefix, visibleTo and scope to narrow it
MemoryFileAuthor'model' | 'user' | 'system'
MemoryFilesConfigMemoryConfig.files: scope (user, agent or thread), readOnly and indexChars, the memory tool a Cogitator gives every agent

Memory also works between runs. Its settings and what a pass reports:

TypeDescription
MemoryBriefConfigMemoryConfig.brief: model, maxCards (1 to 4), timeoutMs, maxTokens and prompt of the cards a cheap model writes before a turn
BriefCardOne card: kind (BriefCardKind: constraint, knowledge, consequence or open_thread), text, quote and source (turn:<id> or item:<id>)
MemoryObservationsConfigMemoryConfig.observations: model, maxEntities, minItems and prompt of the observations memory writes of each entity, shown to a turn only with contextBuilder set
MemoryConsolidationConfigMemoryConfig.consolidation: model, everyRuns, afterCompaction, maxChanges, maxSubjects, playbook (apply, shadow or false), showPlaybook, prompt and afterConsolidate
MemoryConsolidationReportWhat a pass changed: scope, observations and observationsDeleted (paths), stale, playbook (path, editCount, lessonIds) and dedupe (complete, through, where a later pass goes on)
StaleMarkAn item a pass marked as stale: itemId, keptId (the item it gave way to) and reason (duplicate or contradiction)

RunMiddlewareContext.memoryAgentId is the id the run's agent keeps memory under, its configured id, else its name, unset for a tool call made with invokeTool(). ContextBuildError.source may be observations too.

Entries can be redacted in place, which forgetting and redacting through a Cogitator build on:

TypeDescription
EntryRedactionWhat redacting an entry records in its metadata.redacted: at and an optional reason
MemoryAdapter.redactEntryOptional, in every built-in adapter: the text, tool call arguments and tool results of a message or tool_result entry become [redacted], its tool calls lose their replay state and argument error, a user message its sender name, its place, parent, role and call ids stay, null for a missing entry, an event entry refused
MemoryChangeWhat onChange listeners hear: entry-added, entry-deleted, entry-redacted (entryId, threadId), thread-cleared and thread-deleted. An exhaustive switch over it needs the entry-redacted case
MemoryAdapter.forkThreadAlso lists the fork in the origin's metadata.memoryForks, and does not copy the origin's paused run

Knowledge Graph Types

Entity-relationship memory with traversal and inference.

import type {
  GraphNode,
  GraphEdge,
  EntityType,
  RelationType,
  GraphAdapter,
  TraversalOptions,
  TraversalResult,
  GraphPath,
  ExtractionResult,
  InferredEdge,
} from '@cogitator-ai/types';

// EntityType: 'person' | 'organization' | 'location' | 'concept' | 'event' | 'object' | 'custom'
// RelationType: 'knows' | 'works_at' | 'located_in' | 'part_of' | 'related_to' | 'created_by'
//   | 'belongs_to' | 'associated_with' | 'causes' | 'precedes' | 'custom'

// Graph node
const node: GraphNode = {
  id: 'node_123',
  agentId: 'agent-1',
  type: 'person',
  name: 'Alice',
  aliases: ['alice_dev'],
  description: 'Software engineer',
  properties: { role: 'developer', team: 'platform' },
  embedding: [0.1, 0.2, 0.3],
  confidence: 1.0,
  source: 'extracted', // 'extracted' | 'user' | 'inferred'
  createdAt: new Date(),
  updatedAt: new Date(),
  lastAccessedAt: new Date(),
  accessCount: 0,
};

// Graph edge
const edge: GraphEdge = {
  id: 'edge_456',
  agentId: 'agent-1',
  sourceNodeId: 'node_123',
  targetNodeId: 'node_789',
  type: 'works_at',
  label: 'Senior Developer',
  weight: 1.0,
  bidirectional: false,
  confidence: 0.95,
  source: 'extracted',
  properties: { since: '2020' },
  createdAt: new Date(),
  updatedAt: new Date(),
};

// Traversal options
const traversalOptions: TraversalOptions = {
  agentId: 'agent-1',
  startNodeId: 'node_123',
  maxDepth: 3,
  direction: 'outgoing', // 'outgoing' | 'incoming' | 'both'
  edgeTypes: ['works_at', 'knows'],
  minEdgeWeight: 0.5,
  minConfidence: 0.7,
  limit: 100,
};

// Traversal result
const path: GraphPath = { nodes: [node], edges: [edge], totalWeight: 1.0, length: 1 };
const result: TraversalResult = {
  paths: [path],
  visitedNodes: [node],
  visitedEdges: [edge],
  depth: 1,
};

Prompt Optimization Types

A/B testing, monitoring, and version control for agent instructions.

import type {
  CapturedPrompt,
  PromptStore,
  ABTest,
  ABTestResults,
  ABTestOutcome,
  ABTestStore,
  InstructionVersion,
  InstructionVersionStore,
  PromptPerformanceMetrics,
  DegradationAlert,
  OptimizationRun,
} from '@cogitator-ai/types';

// Captured prompt
const prompt: CapturedPrompt = {
  id: 'prompt_123',
  runId: 'run_456',
  agentId: 'agent-1',
  threadId: 'thread_789',
  model: 'gpt-6.1-sol',
  provider: 'openai',
  timestamp: new Date(),
  systemPrompt: 'You are a helpful assistant.',
  messages: [{ role: 'user', content: 'Hello' }],
  tools: [
    {
      name: 'calculator',
      description: 'Evaluate math',
      parameters: { type: 'object', properties: {} },
    },
  ],
  promptTokens: 150,
  response: {
    content: 'Hi there!',
    completionTokens: 10,
    finishReason: 'stop',
    latencyMs: 450,
  },
};

// A/B test
const abTest: ABTest = {
  id: 'test_123',
  agentId: 'agent-1',
  name: 'Instruction Experiment',
  description: 'Testing concise vs verbose',
  status: 'running',
  controlInstructions: 'You are helpful.',
  treatmentInstructions: 'Be concise and direct.',
  treatmentAllocation: 0.5,
  minSampleSize: 100,
  maxDuration: 7 * 24 * 60 * 60 * 1000,
  confidenceLevel: 0.95,
  metricToOptimize: 'score',
  controlResults: {
    sampleSize: 50,
    successRate: 0.9,
    avgScore: 0.82,
    avgLatency: 900,
    totalCost: 0.4,
    scores: [],
  },
  treatmentResults: {
    sampleSize: 48,
    successRate: 0.94,
    avgScore: 0.87,
    avgLatency: 850,
    totalCost: 0.38,
    scores: [],
  },
  createdAt: new Date(),
  startedAt: new Date(),
};

// A/B test outcome
const outcome: ABTestOutcome = {
  winner: 'treatment',
  pValue: 0.023,
  confidenceInterval: [0.02, 0.08],
  effectSize: 0.45,
  isSignificant: true,
  recommendation: 'Treatment performs significantly better.',
};

// Instruction version
const version: InstructionVersion = {
  id: 'ver_123',
  agentId: 'agent-1',
  version: 3,
  instructions: 'Optimized instructions...',
  source: 'optimization',
  sourceId: 'opt-run-456',
  deployedAt: new Date(),
  metrics: { runCount: 100, avgScore: 0.88, successRate: 0.95, avgLatency: 1200, totalCost: 1.4 },
};

// Degradation alert
const alert: DegradationAlert = {
  id: 'alert_123',
  agentId: 'agent-1',
  type: 'score_drop',
  severity: 'warning',
  currentValue: 0.72,
  baselineValue: 0.85,
  threshold: 0.15,
  percentChange: 0.153,
  detectedAt: new Date(),
  autoAction: 'rollback',
  actionTaken: false,
};

Other Modules

Every module below is exported from the package root; the owning package documents how the types are used.

ModuleMain typesUsed by
MemoryMemoryAdapter, MemoryResult, Thread, MemoryEntry, Fact, Embedding, EmbeddingService, ContextBuilderConfig, BuiltContext, DroppedContext, ContextPartition, ContextPartitionBudget, DroppedReason, DroppedBlock, MemoryConfig@cogitator-ai/memory
SandboxSandboxConfig, SandboxManagerConfig (allowNativeFallback, default true: Docker-sandboxed commands run on the host when Docker is unavailable), SandboxPoolConfig (reuseContainers, default false: every execution gets a fresh container), SandboxWasmConfig (memoryPages caps the module's own memory), SandboxExecutionRequest@cogitator-ai/sandbox
WorkflowWorkflowState, Workflow, CheckpointStore, RunStore, ApprovalStore, TimerStore (optional claimTtl, renew, release), WorkflowRunStats@cogitator-ai/workflows
Swarm, negotiationSwarmConfig, SwarmStrategy, SwarmResult, negotiation types@cogitator-ai/swarms
Constitutional, securityGuardrailConfig, Constitution, PromptInjectionConfig, PiiConfig, PiiType@cogitator-ai/core
Cost routing, context, tool cacheCostRoutingConfig, BudgetConfig, ContextManagerConfig, ToolCacheConfig, RedisClientLike (an ioredis client fits)@cogitator-ai/core
CausalCausalGraph, StructuralEquation (custom type with a customFn expression), InterventionQuery, CounterfactualQuery, CausalReasoningConfig@cogitator-ai/core
Neuro-symbolicNeuroSymbolicConfig, ResolvedNeuroSymbolicConfig (every section present, returned by getConfig())@cogitator-ai/neuro-symbolic
Self-modifyingSelfModifyingConfig, generated tool and architecture types@cogitator-ai/self-modifying
Channel gatewayGatewayConfig, ChannelMessage, HookRegistry, HookPayloads (each hook name's payload: MessageReceivedEvent, AgentErrorEvent, ApprovalResolvedEvent, …)@cogitator-ai/channels
RAG, voice, browser, session, deployRAGPipelineConfig, voice/STT/TTS types, browser session types, session types, DeployConfigthe package of the same name
Skills, loggingSkill, SkillConfig, LoggingConfig (level up to 'silent', destination: 'file' with filePath)@cogitator-ai/core

HookPayloads types gateway hooks by name: HookRegistry.on('agent:error', ({ error, threadId }) => …) gets an AgentErrorEvent (error is always an Error), and HookName is keyof HookPayloads. A handler typed HookHandler (unknown payload) is accepted for any hook. GatewayConfig.owner is deprecated: owners are set on ownerCommands({ ownerIds }) and dmPolicy({ ownerIds }).


License

MIT

版本与发布记录

@cogitator-ai/types 共发布 97 个版本,首次发布于 2025/12/31;过去 12 个月发布了 97 个版本。

版本发布日期距今
0.89.0latest2026/10/2912 天前
0.88.02026/10/2912 天前
0.87.02026/10/2912 天前
0.86.02026/10/2912 天前
0.85.02026/10/2812 天前
0.84.02026/10/2813 天前

关于 @cogitator-ai/types 的常见问题

@cogitator-ai/types 是什么?

Shared TypeScript types for Cogitator

如何安装 @cogitator-ai/types?

在项目目录运行 npm install @cogitator-ai/types,或使用 pnpm add / yarn add / bun add。

@cogitator-ai/types 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cogitator-ai/types 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cogitator-ai/types 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cogitator-ai/types 可以商用吗?

@cogitator-ai/types 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cogitator-ai/types 的下载量有多少?

根据 npm 官方下载统计,@cogitator-ai/types 在 2026/10/11 – 2026/11/09 这 30 天内被下载 24,167 次,日均约 806 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cogitator-ai/types 还在维护吗?

最新版本 0.89.0 发布于 2026/10/29(12 天前);至今共发布 97 个版本,其中过去 12 个月发布了 97 个;首次发布于 2025/12/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。