import { StateGraph } from "../graph.js"; import type { ONISkeletonV3 } from "../graph.js"; import { END } from "../types.js"; import type { ChannelSchema } from "../types.js"; import type { SwarmAgentDef, SupervisorConfig, AgentCapability } from "./types.js"; import { AgentRegistry } from "./registry.js"; import type { BaseSwarmState, HierarchicalConfig, FanOutConfig, PipelineConfig, PeerNetworkConfig, MapReduceConfig, DebateConfig, HierarchicalMeshConfig, SwarmCompileOpts, SwarmExtensions, CritiqueRefineConfig, StepwiseVerifyConfig, EnsembleVoteConfig, SpeculativeExecutionConfig, RedTeamConfig, SocraticElicitConfig, AutoResearchConfig, TreeOfThoughtConfig, AdversarialDevConfig } from "./config.js"; export declare class SwarmGraph { /** @internal */ inner: StateGraph; /** @internal */ registry: AgentRegistry; /** @internal */ channels: ChannelSchema; /** @internal */ agentIds: Set; /** @internal */ supervisorNodeName: string; /** @internal */ hasSupervisor: boolean; /** @internal */ onErrorPolicy: "fallback" | "throw"; private _broker?; private _pubsub?; private subGraphs; private get broker(); private get pubsub(); constructor(channels?: Partial>); /** * Create a complete supervisor-workers swarm from a config object. * Registers all agents, wires a supervisor node, and returns the * ready-to-compile SwarmGraph. */ static hierarchical(config: HierarchicalConfig): SwarmGraph; /** * Create a fan-out swarm that runs all agents in parallel via Send * and collects results through a reducer node. */ static fanOut(config: FanOutConfig): SwarmGraph; /** * Create a linear agent pipeline: stage1 → stage2 → … → END. * Optionally override any stage's outgoing edge with a conditional * transition (e.g. loop back for review cycles). */ static pipeline(config: PipelineConfig): SwarmGraph; /** * Create a decentralized peer network: agents route to each other * via conditional handoffs, with no supervisor. */ static peerNetwork(config: PeerNetworkConfig): SwarmGraph; /** * Distribute N inputs across poolSize copies of a mapper agent, * fan-out via Send, and collect results through a reducer node. */ static mapReduce(config: MapReduceConfig): SwarmGraph; /** * Create a multi-round parallel debate with judge termination. * All debaters argue in parallel each round; a judge evaluates * and decides whether consensus has been reached. */ static debate(config: DebateConfig): SwarmGraph; /** * Create a hierarchical mesh with a coordinator routing to team * sub-graphs. Each team is built using pipeline() or peerNetwork() * and compiled into a single node in the outer graph. */ static hierarchicalMesh(config: HierarchicalMeshConfig): SwarmGraph; /** * Race all agents in parallel — first acceptable result wins. * Optionally filter results with an `accept` predicate. */ static race(config: { agents: SwarmAgentDef[]; accept?: (result: unknown) => boolean; timeoutMs?: number; channels?: Partial>; }): SwarmGraph; /** * Execute agents in dependency order (directed acyclic graph). * Agents with no dependencies run in parallel. */ static dag(config: { agents: SwarmAgentDef[]; dependencies: Record; channels?: Partial>; }): SwarmGraph; /** * Distribute N input items across poolSize copies of a single agent, * then reduce all results. */ static pool(config: { agent: SwarmAgentDef; poolSize: number; inputField: keyof S; reducer: (results: Record) => Partial; channels?: Partial>; }): SwarmGraph; /** * Compose multiple sub-swarms as pipeline stages. * Each stage runs a compiled sub-swarm, passing state through. */ static compose(config: { stages: Array<{ id: string; swarm: SwarmGraph; }>; channels?: Partial>; }): SwarmGraph; /** * Create a generator/critic refinement loop. * Generator produces output, critic evaluates it, loop continues * until approval (freeform) or all rubric dimensions pass (rubric). */ static critiqueRefine(config: CritiqueRefineConfig): SwarmGraph; /** * Create a sequential multi-stage pipeline where each stage's output * is verified before proceeding. Supports halt or skip failure modes * and per-stage retry with optional delay. */ static stepwiseVerify(config: StepwiseVerifyConfig): SwarmGraph; /** * Run all agents in parallel and aggregate results via vote (judge picks best), * synthesize (a synthesizer agent merges all outputs), or a custom aggregator function. */ static ensembleVote(config: EnsembleVoteConfig): SwarmGraph; /** * Race multiple strategy agents — first valid result wins, all others are cancelled. * Supports per-strategy and global timeouts, an async validator, and an onCancel callback. */ static speculativeExecution(config: SpeculativeExecutionConfig): SwarmGraph; /** * Create an adversarial security loop. * An attacker agent finds vulnerabilities, a builder agent patches them. * Repeats until the attacker finds nothing significant or maxRounds is exhausted. * Optionally filter low-severity findings with severityThreshold. */ static redTeam(config: RedTeamConfig): SwarmGraph; /** * Create a Socratic elicitation loop. * An interviewer asks questions to a respondent (agent or human interrupt), * tracking coverage across defined dimensions. When enough dimensions are * covered or maxQuestions is reached, a synthesizer produces a final output. */ static socraticElicit(config: SocraticElicitConfig): SwarmGraph; /** * Create a recursive research loop. * A decomposer breaks the question into sub-questions, a researcher * investigates each in parallel, and a synthesizer merges findings, * scores confidence, and identifies gaps. The loop recurses on gaps * until confidence >= threshold, no gaps remain, or maxDepth is hit. */ static autoResearch(config: AutoResearchConfig): SwarmGraph; /** * Create a branching Tree-of-Thought topology. * At each depth, surviving branches are expanded by branchFactor, scored, * and pruned via a dual strategy (topK cap + pruneThreshold floor). * The highest-scoring surviving branch is selected as the final answer. */ static treeOfThought(config: TreeOfThoughtConfig): SwarmGraph; /** * Create an adversarial development topology with sprint contracts and retry budget. * A planner produces sprint scope, generator and evaluator negotiate acceptance criteria, * then generator builds and evaluator scores (0–10). Retries up to maxRetriesPerSprint * before declaring the sprint failed. Repeats for maxSprints or until planner sets done. */ static adversarialDev(config: AdversarialDevConfig): SwarmGraph; addAgent(def: SwarmAgentDef): this; addSupervisor(config: SupervisorConfig, nodeName?: string): this; /** * Wire two agents to hand off directly to each other. * The "from" agent's node will inspect its output for a Handoff * and route accordingly. */ addHandoffEdge(fromAgentId: string, toAgentId: string): this; /** * Add a conditional handoff: fromAgent routes to different agents * based on state. */ addConditionalHandoff(fromAgentId: string, condition: (state: S) => string | typeof END): this; addEdge(from: string, to: string): this; /** * Check the swarm topology for common issues like orphan agents. * Returns an array of issue strings (empty = valid). */ validateTopology(): string[]; /** * Wire agents as a linear pipeline: A → B → C → END */ pipeline(...agentIds: string[]): this; /** * Create a generator/evaluator loop (GAN-inspired). * Generator produces output → evaluator scores it → loop decides * refine, pivot, or accept. Returns a StateGraph that can be compiled. */ static ganLoop = Record>(config: GANLoopConfig): StateGraph>; /** * Dispose the swarm graph, cleaning up broker timeouts, pubsub * subscribers, and any tracked sub-graphs created by * hierarchicalMesh() or compose(). */ dispose(): void; compile(opts?: SwarmCompileOpts): ONISkeletonV3 & SwarmExtensions; } /** * Create a SwarmAgentDef from just an id and a handler function. * Builds a single-node StateGraph internally so the agent is fully * functional in any SwarmGraph topology. */ export declare function quickAgent(id: string, fn: (state: BaseSwarmState) => Promise> | Partial, opts?: { role?: string; capabilities?: AgentCapability[]; hooks?: SwarmAgentDef["hooks"]; maxRetries?: number; maxConcurrency?: number; systemPrompt?: string; timeout?: number; retryDelayMs?: number; }): SwarmAgentDef; export type { BaseSwarmState, SwarmCompileOpts, SwarmExtensions, PregelRunnerInternals } from "./config.js"; export { baseSwarmChannels } from "./config.js"; export type { HierarchicalConfig, FanOutConfig, PipelineConfig, PeerNetworkConfig, MapReduceConfig, DebateConfig, HierarchicalMeshConfig, CritiqueRefineConfig, EnsembleVoteConfig, EnsembleCustomAggregator, SpeculativeExecutionConfig, TreeOfThoughtConfig, AutoResearchConfig, AdversarialDevConfig, SocraticElicitConfig, RedTeamConfig, StepwiseVerifyConfig, StepwiseStage, } from "./config.js"; export interface AgentDefinition { /** Agent identifier, used as node name prefix */ id: string; /** The agent's execution function */ fn: (state: GANState) => Promise>> | Partial>; } export interface EvaluationCriterion { id: string; name: string; description: string; /** Weight 0-1, all weights must sum to 1.0 */ weight: number; /** If set, failing this criterion fails the entire evaluation */ hardThreshold?: number; } export interface CriterionScore { criterionId: string; score: number; rationale: string; passed: boolean; } export interface GANIterationResult { iteration: number; generatorOutput: TState; scores: CriterionScore[]; compositeScore: number; decision: "refine" | "pivot" | "accept"; evaluatorFeedback: string; } export interface GANLoopConfig { /** The agent that produces output */ generator: AgentDefinition; /** The agent that evaluates and critiques output */ evaluator: AgentDefinition; /** Scoring criteria passed to both agents */ criteria: EvaluationCriterion[]; /** Max iterations before forced termination. Default: 10 */ maxIterations?: number; /** Composite score threshold for acceptance. Default: 0.80 */ passingThreshold?: number; /** Called after each evaluation — return true to continue, false to stop */ onIteration?: (iteration: number, scores: CriterionScore[], decision: "refine" | "pivot" | "accept") => Promise; /** Score below this triggers a pivot (full approach change). Default: 0.40 */ pivotThreshold?: number; } export type GANState> = { iteration: number; decision: "refine" | "pivot" | "accept"; done: boolean; generatorOutput: TState; scores: CriterionScore[]; compositeScore: number; evaluatorFeedback: string; criteria: EvaluationCriterion[]; bestIteration: GANIterationResult | null; bestCompositeScore: number; maxIterations: number; passingThreshold: number; pivotThreshold: number; [key: string]: unknown; }; //# sourceMappingURL=graph.d.ts.map