/** * Strategy Agent — AI Meta-Orchestrator for Network-AI * * The StrategyAgent sits above SwarmOrchestrator and makes high-level decisions * about agent allocation, workload distribution, budget partitioning, and * adaptive scaling. It is designed for scenarios where a single AI controls * thousands to millions of agents. * * Architecture: * - **AgentPool**: Elastic pool of agents from a template — spawn/recycle on demand * - **WorkloadPartitioner**: Splits large tasks into chunks and routes to pools * - **StrategyPlanner**: Evaluates current state and produces a StrategyPlan * - **StrategyAgent**: Facade that composes all of the above * * Design principles: * - Zero external dependencies (Node.js builtins only) * - Pluggable strategy functions (bring your own AI decision-making) * - Non-destructive: all actions go through existing orchestrator APIs * - Observable: every decision is logged and emittable * * @module StrategyAgent * @version 1.0.0 */ import { EventEmitter } from 'events'; /** Template for spawning agents in a pool */ export interface AgentTemplate { /** Unique template identifier */ id: string; /** Adapter name to route through */ adapter: string; /** Default action/payload for spawned agents */ defaultAction: string; /** Default params merged into every spawn */ defaultParams: Record; /** Max concurrent agents from this template */ maxConcurrent: number; /** Budget allocation per agent (tokens) */ budgetPerAgent: number; /** Tags for routing and filtering */ tags: string[]; } /** Current status of a managed agent */ export interface ManagedAgent { id: string; templateId: string; status: 'spawning' | 'running' | 'completed' | 'failed' | 'recycled'; spawnedAt: number; completedAt?: number; taskId?: string; tokensUsed: number; } /** A chunk of work to be distributed */ export interface WorkChunk { id: string; input: unknown; priority: number; assignedPool?: string; assignedAgent?: string; status: 'pending' | 'assigned' | 'running' | 'completed' | 'failed'; result?: unknown; error?: string; createdAt: number; completedAt?: number; } /** Strategy plan produced by the planner */ export interface StrategyPlan { /** Human-readable description of the plan */ description: string; /** Pools to scale up (templateId → target count) */ scaleUp: Map; /** Pools to scale down (templateId → target count) */ scaleDown: Map; /** Budget reallocation (templateId → new per-agent budget) */ budgetReallocation: Map; /** FSM transition to trigger (if any) */ fsmTransition?: string; /** Work chunks to create */ newChunks: Array<{ input: unknown; priority: number; targetPool: string; }>; /** Confidence score 0-1 */ confidence: number; /** Timestamp */ createdAt: number; } /** Snapshot of the current system state for the planner */ export interface SystemSnapshot { pools: Map; totalBudgetSpent: number; totalBudgetCeiling: number; fsmState: string; pendingChunks: number; runningAgents: number; completedTasks: number; failedTasks: number; averageTaskDuration: number; timestamp: number; } /** Status of a single agent pool */ export interface PoolStatus { templateId: string; active: number; maxConcurrent: number; completed: number; failed: number; totalTokensUsed: number; budgetPerAgent: number; pendingChunks: number; } /** Pluggable strategy function — given state, produce a plan */ export type StrategyFunction = (snapshot: SystemSnapshot) => StrategyPlan | Promise; /** Events emitted by the StrategyAgent */ export interface StrategyEvents { 'plan:created': (plan: StrategyPlan) => void; 'plan:executed': (plan: StrategyPlan) => void; 'pool:created': (templateId: string) => void; 'pool:scaled': (templateId: string, from: number, to: number) => void; 'agent:spawned': (agent: ManagedAgent) => void; 'agent:completed': (agent: ManagedAgent) => void; 'agent:failed': (agent: ManagedAgent, error: string) => void; 'chunk:created': (chunk: WorkChunk) => void; 'chunk:assigned': (chunk: WorkChunk) => void; 'chunk:completed': (chunk: WorkChunk) => void; 'chunk:failed': (chunk: WorkChunk) => void; 'cycle:start': (cycleNumber: number) => void; 'cycle:end': (cycleNumber: number, plan: StrategyPlan) => void; } /** Options for creating a StrategyAgent */ export interface StrategyAgentOptions { /** Custom strategy function (default: built-in adaptive strategy) */ strategy?: StrategyFunction; /** How often to re-evaluate strategy (ms, default: 5000) */ evaluationInterval?: number; /** Maximum total agents across all pools (default: 10000) */ globalAgentLimit?: number; /** Maximum total budget across all pools (default: Infinity) */ globalBudgetLimit?: number; /** Auto-start evaluation loop (default: false) */ autoStart?: boolean; } /** * Elastic pool of agents from a template. Manages spawn/complete/recycle * lifecycle without knowing about specific adapter implementations. */ export declare class AgentPool { readonly template: AgentTemplate; private agents; private _completedCount; private _failedCount; private _totalTokens; private _events; private _dispatchPaused; private _dispatchAllowedPercent; constructor(template: AgentTemplate, events: EventEmitter); /** Number of currently active (spawning or running) agents */ get active(): number; /** Total completed agents */ get completed(): number; /** Total failed agents */ get failed(): number; /** Total tokens consumed by this pool */ get totalTokensUsed(): number; /** Whether the pool can accept more agents */ get canSpawn(): boolean; /** How many more agents can be spawned */ get availableSlots(): number; /** Whether dispatch is currently paused for this pool. */ get isDispatchPaused(): boolean; /** Current allowed spawn percentage (0–100). */ get dispatchAllowedPercent(): number; /** * Pause or partially resume dispatch for this pool. * Used by TransportAgent to drain the fleet before an environment promotion. * @param paused - true to fully pause; false to resume (optionally at a partial rate) * @param options.percent - 1–100 fraction of maxConcurrent slots to allow (ignored when paused=true) */ setDispatchPause(paused: boolean, options?: { percent?: number; }): void; /** * Reserve a slot and create a ManagedAgent record. * Returns null if pool is at capacity. */ spawn(taskId?: string): ManagedAgent | null; /** Mark an agent as running */ markRunning(agentId: string): void; /** Mark an agent as completed and record token usage */ markCompleted(agentId: string, tokensUsed?: number): void; /** Mark an agent as failed */ markFailed(agentId: string, error: string): void; /** Recycle completed/failed agents to free slots */ recycle(): number; /** Get a snapshot of pool status */ getStatus(pendingChunks?: number): PoolStatus; /** Get all agents (for inspection) */ getAgents(): ReadonlyArray; } /** * Splits large tasks into work chunks and manages the chunk lifecycle. */ export declare class WorkloadPartitioner { private chunks; private _chunkCounter; private _events; constructor(events: EventEmitter); /** * Create work chunks from an array of inputs. * @param inputs - Array of task inputs * @param targetPool - Pool template ID to route chunks to * @param priority - Priority level (higher = more urgent) */ partition(inputs: unknown[], targetPool: string, priority?: number): WorkChunk[]; /** Get all pending chunks for a pool, sorted by priority (descending) */ getPendingForPool(poolId: string): WorkChunk[]; /** Assign a chunk to an agent */ assign(chunkId: string, agentId: string): boolean; /** Mark a chunk as running */ markRunning(chunkId: string): void; /** Mark a chunk as completed */ markCompleted(chunkId: string, result?: unknown): void; /** Mark a chunk as failed */ markFailed(chunkId: string, error: string): void; /** Get counts by status */ getCounts(): { pending: number; assigned: number; running: number; completed: number; failed: number; total: number; }; /** Get all chunks for a pool */ getChunksForPool(poolId: string): WorkChunk[]; /** Get a chunk by ID */ getChunk(chunkId: string): WorkChunk | undefined; } /** * Default adaptive strategy that: * - Scales up pools with pending work * - Scales down idle pools * - Reallocates budget from idle to busy pools */ export declare function adaptiveStrategy(snapshot: SystemSnapshot): StrategyPlan; /** * AI Meta-Orchestrator that manages agent pools, work distribution, and * adaptive strategy. Designed for controlling thousands to millions of agents. * * @example * ```typescript * const strategy = new StrategyAgent({ * globalAgentLimit: 10000, * globalBudgetLimit: 1_000_000, * evaluationInterval: 5000, * }); * * // Define agent templates * strategy.createPool({ * id: 'researchers', * adapter: 'langchain', * defaultAction: 'research', * defaultParams: { depth: 'thorough' }, * maxConcurrent: 500, * budgetPerAgent: 1000, * tags: ['research', 'data'], * }); * * // Distribute work * const urls = [...thousandUrls]; * strategy.distributeWork(urls, 'researchers', 2); * * // Start auto-evaluation loop * strategy.start(); * * // Or manually evaluate + execute * const plan = await strategy.evaluate(); * await strategy.executePlan(plan); * ``` */ export declare class StrategyAgent extends EventEmitter { private pools; private partitioner; private strategyFn; private evaluationInterval; private globalAgentLimit; private globalBudgetLimit; private intervalHandle; private _cycleCount; private _plans; constructor(options?: StrategyAgentOptions); /** Create an agent pool from a template */ createPool(template: AgentTemplate): AgentPool; /** Get a pool by template ID */ getPool(templateId: string): AgentPool | undefined; /** List all pools */ listPools(): Array; /** Remove a pool (recycles all agents first) */ removePool(templateId: string): boolean; /** Total active agents across all pools */ get totalActiveAgents(): number; /** Whether the global agent limit has been reached */ get atCapacity(): boolean; /** * Distribute work items across a pool. * Each input becomes a work chunk assigned to the pool. */ distributeWork(inputs: unknown[], targetPool: string, priority?: number): WorkChunk[]; /** Get work distribution status */ getWorkStatus(): ReturnType; /** Access the partitioner directly */ get workload(): WorkloadPartitioner; /** Take a snapshot of the current system state */ snapshot(budgetSpent?: number, budgetCeiling?: number, fsmState?: string): SystemSnapshot; /** Evaluate the current state and produce a strategy plan */ evaluate(budgetSpent?: number, budgetCeiling?: number, fsmState?: string): Promise; /** * Execute a strategy plan: scale pools, reallocate budgets, create chunks. * Returns the number of actions taken. */ executePlan(plan: StrategyPlan): number; /** Start the automatic evaluation loop */ start(): void; /** Stop the evaluation loop */ stop(): void; /** Whether the evaluation loop is running */ get isRunning(): boolean; /** Number of evaluation cycles completed */ get cycleCount(): number; /** All plans produced so far */ get planHistory(): ReadonlyArray; /** Get a summary string of the current state */ summary(): string; } //# sourceMappingURL=strategy-agent.d.ts.map