Cogitator
API Reference

Swarms API

Public exports of @cogitator-ai/swarms — the Swarm class and builder, strategies, communication, distributed execution, swarm tools, workflow nodes and the assessor — with their signatures.

Swarm

import { Cogitator, Agent } from '@cogitator-ai/core';
import { Swarm, swarm } from '@cogitator-ai/swarms';

const team = new Swarm(cog, {
  name: 'dev-team',
  strategy: 'hierarchical',
  supervisor: lead,
  workers: [developer, reviewer],
  hierarchical: { maxDelegationDepth: 2 },
});

const sameTeam = swarm('dev-team')
  .strategy('hierarchical')
  .supervisor(lead)
  .workers([developer, reviewer])
  .hierarchical({ maxDelegationDepth: 2 })
  .build(cog);

const result = await team.run({ input: 'Build a landing page' });
console.log(result.output, result.agentResults.get('developer')?.output);
MemberSignaturePurpose
constructornew Swarm(cogitator: Cogitator, config: SwarmConfig, assessorConfig?: AssessorConfig)With assessorConfig, the first run() assigns models first
runrun(options: SwarmRunOptions): Promise<StrategyResult>Run the swarm on an input
dryRundryRun(options: { input: string }): Promise<AssessmentResult>Assess models without running (throws without an assessor)
getLastAssessmentgetLastAssessment(): AssessmentResult | undefinedThe assessment the last run used
on / onceon(event: SwarmEventType | '*', handler: SwarmEventHandler): () => voidSubscribe to events; returns an unsubscribe function
getAgents, getAgentgetAgents(): SwarmAgent[], getAgent(name: string): SwarmAgent | undefinedAgents with their metadata, state and usage
getResourceUsagegetResourceUsage(): SwarmResourceUsageTokens, cost, elapsed time, per-agent usage
pause, resume, abort(): voidControl a running swarm
isPaused, isAborted(): booleanState
respondToApprovalrespondToApproval(requestId: string, response: NegotiationApprovalResponse): voidAnswer a negotiation approval gate (request.id from negotiation:approval-required); throws for other strategies
resetreset(): Promise<void>Clear messages, blackboard, usage and agent state
closeclose(): Promise<void>Release resources (Redis connections when distributed)
name, id, strategyType, isDistributedgettersThe swarm's identity
messageBusReadTrackingMessageBusMessageBus plus markAsRead(agentName, ids), resetTurnCounts(agentName?), onMessage(listener)
blackboardObservableBlackboardBlackboard plus onWrite(listener)
eventsQueryableSwarmEventEmitterSwarmEventEmitter plus getEventsByType(type), getEventsByAgent(name), clearEvents()
ExportSignaturePurpose
swarmswarm(name: string): SwarmBuilderFluent builder
SwarmBuilderstrategy, supervisor, workers, agents, moderator, router, agentMetadata, observability, hierarchical, roundRobin, consensus, auction, pipeline, debate, negotiation, messaging, blackboardConfig, agentTools, resources, errorHandling, distributed, withAssessor(config?), build(cogitator): SwarmOne method per SwarmConfig field
SwarmTimeoutErrorclass extends Error { swarmName; timeoutMs }Thrown by run() when its timeout elapses

SwarmConfig

FieldTypeUsed by
namestringall
strategySwarmStrategyall
supervisor, workersAgent, Agent[]hierarchical (supervisor required)
agentsAgent[]round-robin, consensus, auction, debate, negotiation
moderator, routerAgentdebate moderator, specialist routing
stagesPipelineStage[]pipeline stages (alternative to pipeline.stages; different stages in both throw)
agentMetadataRecord<string, SwarmAgentMetadata>role, expertise, priority, weight, locked per agent name
hierarchical, roundRobin, consensus, auction, pipeline, debate, negotiationstrategy configsthe matching strategy; consensus, auction, pipeline and debate are required for theirs
messaging, blackboardMessageBusConfig, BlackboardConfigcommunication (messaging.protocol and blackboard.locking are deprecated, no effect)
agentToolsSwarmAgentToolsConfig ({ messaging?: boolean; blackboard?: boolean })built-in messaging / blackboard tools for every agent; local swarms only
resourcesSwarmResourceConfigmaxConcurrency (default 4), tokenBudget, costLimit, timeout, perAgent
errorHandlingSwarmErrorConfigretry / skip / failover / abort on agent failure
distributedDistributedSwarmConfigrun agents as Redis jobs
observability{ tracing?; messageLogging?; blackboardLogging? }logging; tracing logs each agent run's trace (spans)

SwarmRunOptions and Results

interface SwarmRunOptions {
  input: string;
  context?: Record<string, unknown>; // passed to all agents
  threadId?: string;
  userId?: string; // every agent run acts for this user
  timeout?: number;
  saveHistory?: boolean; // default: true
  onAgentStart?: (agentName: string) => void;
  onAgentComplete?: (agentName: string, result: RunResult) => void;
  onAgentError?: (agentName: string, error: Error) => void;
  onMessage?: (message: SwarmMessage) => void;
  onEvent?: (event: SwarmEvent) => void;
}

interface StrategyResult {
  output: unknown;
  structured?: unknown;
  agentResults: Map<string, RunResult>;
  votes?: Map<string, unknown>; // consensus
  bids?: Map<string, number>; // auction
  auctionWinner?: string;
  debateTranscript?: SwarmMessage[];
  pipelineOutputs?: Map<string, unknown>;
  negotiationResult?: NegotiationResult;
}

Strategies

strategyClassConfig (SwarmConfig field)Needs
'hierarchical'HierarchicalStrategyhierarchical?: { maxDelegationDepth? (3), workerCommunication?, routeThrough?, visibility? }supervisor
'round-robin'RoundRobinStrategyroundRobin?: { sticky?, stickyKey?, rotation?: 'sequential' | 'random' }1+ agents
'consensus'ConsensusStrategyconsensus: { threshold, maxRounds, resolution: 'majority' | 'unanimous' | 'weighted', onNoConsensus, weights? }2+ agents
'auction'AuctionStrategyauction: { bidding: 'capability-match' | 'custom', bidFunction?, selection, minBid? }1+ agents
'pipeline'PipelineStrategypipeline: { stages: PipelineStage[], stageInput?, gates? } (or top-level stages)1+ stages
'debate'DebateStrategydebate: { rounds, maxTokensPerTurn?, reasoningTokensPerTurn?, format?, synthesisPrompt? }2+ agents, rounds ≥ 1
'negotiation'NegotiationStrategynegotiation?: Partial<NegotiationConfig>2+ agents
ExportSignaturePurpose
createStrategycreateStrategy(coordinator: SwarmCoordinatorInterface, config: SwarmConfig): IStrategyThe strategy for a config
getDefaultStrategyConfiggetDefaultStrategyConfig(strategy: SwarmStrategy)Default config of a strategy
BaseStrategyabstract class BaseStrategy implements IStrategy (new (coordinator))Base for your own strategy
TurnManager, ConvergenceCalculator, ApprovalIntegrationclassesBuilding blocks of the negotiation strategy

Every strategy class takes (coordinator, config). See Strategies.

Coordinators

ExportSignaturePurpose
SwarmCoordinatornew SwarmCoordinator(cogitator: Cogitator, config: SwarmConfig)In-process coordinator Swarm uses
DistributedSwarmCoordinatornew DistributedSwarmCoordinator(options: { config; distributed: DistributedSwarmConfig; resolveModel? }) — initialize(), reset(), close()Runs agent turns as jobs on a Redis queue for @cogitator-ai/worker
BaseSwarmCoordinatorabstract class — runInScope(scope: SwarmRunScope, work) binds a strategy run to its run's threadId, userId and signalShared coordinator logic
swarmJobQueueKeyswarmJobQueueKey(keyPrefix?: string, queue?: string): stringRedis key of the agent job queue
ResourceTrackernew ResourceTracker(config?: SwarmResourceConfig) — trackAgentRun, isWithinBudget, checkLimit, getUsage, getAgentUsage, getRemainingBudget, resetBudgets
CircuitBreakernew CircuitBreaker(config: { threshold; resetTimeout; successThreshold? }) — canExecute, recordSuccess, recordFailure, getState, onStateChange, resetPer-agent failure breaker

DistributedSwarmConfig: { enabled, queue? ('swarm-agent-jobs'), timeout? (300000), redis?: { host?, port?, password?, keyPrefix?, db? }, retry?, cleanupAfter? (3600000), workerConcurrency? }. retry: { maxRetries? (3), backoff? ('exponential'), initialDelay? (1000), maxDelay? (30000) } re-dispatches jobs that fail on a worker or time out (no retries without it). cleanupAfter is how long the swarm's Redis state is kept after close() (0 deletes it at once). workerConcurrency is deprecated and has no effect; set concurrency on DistributedSwarmWorker. The job payload and result types are SwarmAgentJobPayload, SwarmAgentJobResult and SerializedSwarmAgentConfig. See Distributed Swarms.

Communication

ExportSignaturePurpose
InMemoryMessageBusnew InMemoryMessageBus(config: MessageBusConfig)MessageBus in process memory
RedisMessageBusnew RedisMessageBus(config: MessageBusConfig, options: { redis; swarmId; keyPrefix? })MessageBus over Redis
InMemoryBlackboardnew InMemoryBlackboard(config: BlackboardConfig)Blackboard in process memory
RedisBlackboardnew RedisBlackboard(config: BlackboardConfig, options: { redis; swarmId; keyPrefix? })Blackboard over Redis
SwarmEventEmitterImplnew SwarmEventEmitterImpl(maxEvents?: number)QueryableSwarmEventEmitter in process memory
RedisSwarmEventEmitternew RedisSwarmEventEmitter(options: { redis; swarmId; keyPrefix?; maxEvents? })QueryableSwarmEventEmitter over Redis pub/sub
isReadTrackingMessageBus, isObservableBlackboardtype guardsOptional capabilities of a bus / blackboard
ReadTrackingMessageBus, ObservableBlackboard, QueryableSwarmEventEmittertypesThe extended interfaces swarm.messageBus, swarm.blackboard and swarm.events return

MessageBus: send(message), broadcast(from, content, channel?), subscribe(agentName, handler), getMessages(agentName, limit?), getConversation(a, b), getAllMessages(), getUnreadMessages(agentName), clear().

Blackboard: read(section), write(section, data, agentName), append(section, item, agentName), has, delete, subscribe(section, handler), getSections(), getSection(section), getHistory(section), clear(). See Communication.

Swarm Tools

Inside a swarm, the hierarchical supervisor gets the delegation tools, consensus voters the voting tools and negotiating agents the negotiation tools automatically; agentTools adds the messaging and blackboard tools to every agent. The factories build the same tools for custom strategies:

ExportSignatureTools
createSwarmToolscreateSwarmTools(context: SwarmToolContext): Tool[]all of the tools below
createStrategyToolscreateStrategyTools(strategy, context: SwarmToolContext): Tool[]the set for a strategy
createMessagingToolscreateMessagingTools(messageBus, currentAgent, swarmId?, options?)send_message, read_messages, broadcast_message, reply_to_message
createBlackboardToolscreateBlackboardTools(blackboard, currentAgent)read_blackboard, write_blackboard, append_blackboard, list_blackboard_sections, get_blackboard_history
createDelegationToolscreateDelegationTools(coordinator, blackboard, currentAgent)delegate_task, check_progress, request_revision, list_workers
createVotingToolscreateVotingTools(blackboard, events, currentAgent, agentWeight?)cast_vote, get_votes, change_vote, get_consensus_status
createNegotiationToolscreateNegotiationTools(blackboard, events, currentAgent, agentWeight?)make_offer, counter_offer, accept_offer, reject_offer, get_negotiation_status, get_current_offers, propose_coalition, join_coalition, declare_interests

SwarmToolContext: { coordinator, blackboard, messageBus, events, agentName, agentWeight?, swarmId? }.

Workflow Nodes

ExportSignaturePurpose
swarmNodeswarmNode<S>(swarmOrConfig: Swarm | SwarmConfig, options?: SwarmNodeOptions<S>): WorkflowNode<S>Run a swarm as a workflow node
conditionalSwarmNodeconditionalSwarmNode<S>(swarmOrConfig, condition: (state: S, ctx) => boolean, options?)Run only when condition holds
parallelSwarmsNodeparallelSwarmsNode<S>(swarms: { swarm; key; options? }[], mergeResults?: (results: Record<string, StrategyResult>) => Partial<S>)Several swarms at once

SwarmNodeOptions: { inputMapper?: (state, input?) => string; stateMapper?: (result: StrategyResult) => Partial<S>; runOptions?: Partial<SwarmRunOptions> }. With a SwarmConfig, the node builds the swarm from the cogitator in the node context.

Assessor

ExportSignaturePurpose
SwarmAssessornew SwarmAssessor(config?: AssessorConfig, runtime?: AssessorRuntime)Pick models per agent for a task; with runtime (a Cogitator) 'ai' / 'hybrid' analysis runs and cloud models are limited to routable providers
assessor.analyzeanalyze(task: string, swarmConfig: SwarmConfig, resolveModel?): Promise<AssessmentResult>Requirements, candidates and assignments
assessor.assignModelsassignModels(config: SwarmConfig, result: AssessmentResult): SwarmConfigApply an assessment
assessor.suggestModelssuggestModels(requirements: TaskRequirements): Promise<ModelCandidate[]>Ranked models for requirements
createAssessorcreateAssessor(config?: AssessorConfig, runtime?: AssessorRuntime): SwarmAssessorFactory
TaskAnalyzernew TaskAnalyzer() — analyze(task: string): TaskRequirementsRule-based task analysis
AiTaskAnalyzernew AiTaskAnalyzer(runtime: Pick<Cogitator, 'run'>, model?: string) — analyze(task: string): Promise<TaskRequirements>Model-based task analysis ('ai' / 'hybrid' modes)
AssessorRuntimePick<Cogitator, 'run' | 'route'>What the assessor needs from a Cogitator
ModelDiscoverynew ModelDiscovery(config: AssessorConfig, canRunModel?: (model: DiscoveredModel) => boolean) — discoverAll, discoverOllama, getCloudModels, checkOllamaAvailabilityAvailable models
ModelScorernew ModelScorer() — score(model, requirements), scoreAll(models, requirements)Score models (ScoredModel)
RoleMatchernew RoleMatcher() — analyzeRole(agent, taskReqs), extractAgentsFromConfig(config)Requirements per role

See Assessment.

Events

SwarmEventType covers the swarm lifecycle (swarm:start, swarm:complete, swarm:error, swarm:paused, swarm:resumed, swarm:aborted, swarm:reset), agents (agent:start, agent:complete, agent:error), messaging (message:sent, message:received, blackboard:write), each strategy (consensus:*, auction:*, debate:*, pipeline:*, round-robin:assigned, negotiation:*) and assessor:complete. A SwarmEvent is { type, timestamp, agentName?, data? }; subscribe to '*' for all of them.

Types

Re-exported from @cogitator-ai/types: SwarmStrategy, SwarmConfig, SwarmRunOptions, SwarmAgent, SwarmAgentMetadata, SwarmAgentState, SwarmMessage, SwarmMessageType, MessageBus, MessageBusConfig, Blackboard, BlackboardConfig, BlackboardEntry, SwarmEventEmitter, SwarmEventType, SwarmEvent, SwarmEventHandler, the strategy configs (HierarchicalConfig, RoundRobinConfig, ConsensusConfig, AuctionConfig, PipelineConfig, PipelineStage, PipelineContext, PipelineGateConfig, DebateConfig, NegotiationConfig, …), the negotiation types (NegotiationOffer, NegotiationAgreement, NegotiationResult, Coalition, …), StrategyResult, IStrategy, SwarmCoordinatorInterface, SwarmResourceConfig, SwarmErrorConfig, SwarmAgentToolsConfig and the assessor types (TaskRequirements, RoleRequirements, ModelCandidate, ModelAssignment, AssessmentResult, AssessorConfig, DiscoveredModel, …).

On this page