network-ai 4.14.0 → 4.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Goal Decomposer — LLM-powered goal → task DAG → parallel execution
3
+ *
4
+ * Provides the `runTeam()` one-liner: describe a goal in plain English,
5
+ * specify which agents to use, and let an LLM plan the task graph.
6
+ * Execution respects all Network-AI guardrails (budgets, permissions, audit).
7
+ *
8
+ * Zero external dependencies — LLM calls go through the adapter system.
9
+ *
10
+ * @module GoalDecomposer
11
+ * @version 1.0.0
12
+ */
13
+ import { EventEmitter } from 'events';
14
+ import type { AgentPayload, AgentContext, AgentResult } from '../types/agent-adapter';
15
+ /** A single node in the task DAG */
16
+ export interface TaskNode {
17
+ /** Unique task identifier */
18
+ id: string;
19
+ /** Human-readable description of the task */
20
+ description: string;
21
+ /** Agent ID (or pool/template) to execute this task */
22
+ agent: string;
23
+ /** Action to invoke on the agent */
24
+ action: string;
25
+ /** Parameters for the action */
26
+ params: Record<string, unknown>;
27
+ /** IDs of tasks that must complete before this one starts */
28
+ dependencies: string[];
29
+ /** Priority (higher = more urgent) */
30
+ priority: number;
31
+ /** Execution status */
32
+ status: 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
33
+ /** Result after execution */
34
+ result?: AgentResult;
35
+ /** Error message if failed */
36
+ error?: string;
37
+ /** Timestamps */
38
+ startedAt?: number;
39
+ completedAt?: number;
40
+ }
41
+ /** Directed acyclic graph of tasks */
42
+ export interface TaskDAG {
43
+ /** The original goal */
44
+ goal: string;
45
+ /** All task nodes */
46
+ nodes: TaskNode[];
47
+ /** Adjacency list: taskId → downstream task IDs */
48
+ edges: Map<string, string[]>;
49
+ /** When the DAG was created */
50
+ createdAt: number;
51
+ }
52
+ /** Configuration for an agent available to the team */
53
+ export interface TeamAgent {
54
+ /** Agent ID (must match an adapter-registered agent or be resolvable by the executor) */
55
+ id: string;
56
+ /** What this agent can do (fed to LLM for planning) */
57
+ role: string;
58
+ /** Which adapter handles this agent */
59
+ adapter?: string;
60
+ /** Default action to invoke */
61
+ defaultAction?: string;
62
+ /** Default parameters */
63
+ defaultParams?: Record<string, unknown>;
64
+ }
65
+ /** Function that invokes an LLM to produce a decomposition plan */
66
+ export type PlannerFunction = (goal: string, agents: TeamAgent[], context?: Record<string, unknown>) => Promise<PlannedTask[]>;
67
+ /** Output from the planner (LLM-generated) */
68
+ export interface PlannedTask {
69
+ id: string;
70
+ description: string;
71
+ agent: string;
72
+ action: string;
73
+ params: Record<string, unknown>;
74
+ dependencies: string[];
75
+ priority?: number;
76
+ }
77
+ /** Function that executes a single task via the adapter system */
78
+ export type ExecutorFunction = (agentId: string, payload: AgentPayload, context: AgentContext) => Promise<AgentResult>;
79
+ /** Options for `runTeam` */
80
+ export interface RunTeamOptions {
81
+ /** Maximum number of tasks to run in parallel (default: 5) */
82
+ concurrency?: number;
83
+ /** Timeout per task in ms (default: 30000) */
84
+ taskTimeout?: number;
85
+ /** Timeout for the entire run in ms (default: 300000) */
86
+ totalTimeout?: number;
87
+ /** Whether to continue executing tasks after one fails (default: false) */
88
+ continueOnFailure?: boolean;
89
+ /** Session ID for context propagation */
90
+ sessionId?: string;
91
+ /** Arbitrary metadata passed to agent contexts */
92
+ metadata?: Record<string, unknown>;
93
+ /** Maximum LLM retries for planning (default: 1) */
94
+ plannerRetries?: number;
95
+ /** Callback for approval before execution starts */
96
+ approvalCallback?: (dag: TaskDAG) => Promise<boolean>;
97
+ }
98
+ /** Final result from a team run */
99
+ export interface TeamResult {
100
+ /** Whether the overall goal was achieved */
101
+ success: boolean;
102
+ /** The task graph that was executed */
103
+ dag: TaskDAG;
104
+ /** Aggregated results from all completed tasks */
105
+ results: Map<string, AgentResult>;
106
+ /** Summary of what happened */
107
+ summary: string;
108
+ /** Total execution time in ms */
109
+ durationMs: number;
110
+ /** Count of tasks by status */
111
+ stats: {
112
+ total: number;
113
+ completed: number;
114
+ failed: number;
115
+ skipped: number;
116
+ };
117
+ }
118
+ /** Events emitted during a team run */
119
+ export interface TeamRunnerEvents {
120
+ 'dag:created': (dag: TaskDAG) => void;
121
+ 'task:start': (node: TaskNode) => void;
122
+ 'task:complete': (node: TaskNode, result: AgentResult) => void;
123
+ 'task:fail': (node: TaskNode, error: string) => void;
124
+ 'task:skip': (node: TaskNode, reason: string) => void;
125
+ 'run:complete': (result: TeamResult) => void;
126
+ }
127
+ /**
128
+ * Validate that a set of planned tasks forms a valid DAG (no cycles, valid refs).
129
+ * @throws Error if the graph contains cycles or invalid dependency references
130
+ */
131
+ export declare function validateDAG(tasks: PlannedTask[]): void;
132
+ /**
133
+ * Compute topological layers — tasks in the same layer can execute in parallel.
134
+ * Returns arrays of task IDs grouped by execution layer.
135
+ */
136
+ export declare function topologicalLayers(tasks: PlannedTask[]): string[][];
137
+ /**
138
+ * Create a planner function that uses an LLM (via executor) to decompose goals.
139
+ *
140
+ * The planner sends a structured prompt to the specified agent and parses
141
+ * the JSON response into PlannedTask[]. Falls back gracefully on parse errors.
142
+ *
143
+ * @param executor - Function to call the LLM agent
144
+ * @param plannerAgent - Agent ID for the LLM that does planning
145
+ * @param plannerAdapter - Adapter name (optional, defaults to agent's adapter)
146
+ */
147
+ export declare function createLLMPlanner(executor: ExecutorFunction, plannerAgent: string): PlannerFunction;
148
+ /**
149
+ * Parse JSON from an LLM response string, handling markdown fences and preamble.
150
+ */
151
+ export declare function parsePlanJSON(text: string): PlannedTask[];
152
+ /**
153
+ * LLM-powered goal decomposition engine.
154
+ *
155
+ * Takes a natural language goal, creates a task DAG via an LLM planner,
156
+ * validates the graph, and returns a ready-to-execute TaskDAG.
157
+ */
158
+ export declare class GoalDecomposer {
159
+ private planner;
160
+ constructor(planner: PlannerFunction);
161
+ /**
162
+ * Decompose a goal into a validated TaskDAG.
163
+ * @param goal - Natural language description of the goal
164
+ * @param agents - Available team agents
165
+ * @param context - Optional context to feed to the planner
166
+ * @param retries - Number of retries on planning failure (default: 1)
167
+ */
168
+ decompose(goal: string, agents: TeamAgent[], context?: Record<string, unknown>, retries?: number): Promise<TaskDAG>;
169
+ }
170
+ /**
171
+ * Executes a TaskDAG by running tasks in parallel layers, respecting
172
+ * dependencies, concurrency limits, and timeouts.
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * const runner = new TeamRunner(executor);
177
+ * const result = await runner.run(dag, { concurrency: 3 });
178
+ * console.log(result.summary);
179
+ * ```
180
+ */
181
+ export declare class TeamRunner extends EventEmitter {
182
+ private executor;
183
+ constructor(executor: ExecutorFunction);
184
+ /**
185
+ * Execute a TaskDAG with parallel scheduling.
186
+ */
187
+ run(dag: TaskDAG, options?: RunTeamOptions): Promise<TeamResult>;
188
+ }
189
+ /**
190
+ * Decompose a goal into tasks and execute them with a team of agents.
191
+ *
192
+ * This is the main entry point — one line to go from goal to results:
193
+ *
194
+ * ```typescript
195
+ * const result = await runTeam(
196
+ * "Build a REST API for user management",
197
+ * [
198
+ * { id: "architect", role: "System design and API specification" },
199
+ * { id: "coder", role: "Write TypeScript code" },
200
+ * { id: "reviewer", role: "Code review and quality checks" },
201
+ * ],
202
+ * { planner, executor }
203
+ * );
204
+ * ```
205
+ *
206
+ * @param goal - Natural language description of what to achieve
207
+ * @param agents - Team of agents available for task execution
208
+ * @param config - Planner (LLM decomposition) and executor (agent invocation) functions
209
+ * @param options - Optional concurrency, timeout, and failure handling settings
210
+ * @returns Full result with DAG, individual results, and stats
211
+ */
212
+ export declare function runTeam(goal: string, agents: TeamAgent[], config: {
213
+ planner: PlannerFunction;
214
+ executor: ExecutorFunction;
215
+ }, options?: RunTeamOptions): Promise<TeamResult>;
216
+ //# sourceMappingURL=goal-decomposer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goal-decomposer.d.ts","sourceRoot":"","sources":["../../lib/goal-decomposer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,KA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