@juspay/neurolink 9.82.0 → 9.84.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.
Files changed (127) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/agent/agent.d.ts +104 -0
  3. package/dist/agent/agent.js +401 -0
  4. package/dist/agent/agentNetwork.d.ts +87 -0
  5. package/dist/agent/agentNetwork.js +458 -0
  6. package/dist/agent/communication/index.d.ts +9 -0
  7. package/dist/agent/communication/index.js +9 -0
  8. package/dist/agent/communication/message-bus.d.ts +113 -0
  9. package/dist/agent/communication/message-bus.js +406 -0
  10. package/dist/agent/coordination/coordinator.d.ts +83 -0
  11. package/dist/agent/coordination/coordinator.js +598 -0
  12. package/dist/agent/coordination/index.d.ts +10 -0
  13. package/dist/agent/coordination/index.js +10 -0
  14. package/dist/agent/coordination/task-distributor.d.ts +113 -0
  15. package/dist/agent/coordination/task-distributor.js +585 -0
  16. package/dist/agent/index.d.ts +38 -0
  17. package/dist/agent/index.js +44 -0
  18. package/dist/agent/orchestration/index.d.ts +10 -0
  19. package/dist/agent/orchestration/index.js +10 -0
  20. package/dist/agent/orchestration/orchestrator.d.ts +114 -0
  21. package/dist/agent/orchestration/orchestrator.js +476 -0
  22. package/dist/agent/orchestration/topology.d.ts +164 -0
  23. package/dist/agent/orchestration/topology.js +520 -0
  24. package/dist/agent/prompts/routingPrompts.d.ts +63 -0
  25. package/dist/agent/prompts/routingPrompts.js +201 -0
  26. package/dist/browser/neurolink.min.js +377 -358
  27. package/dist/cli/commands/agent.d.ts +37 -0
  28. package/dist/cli/commands/agent.js +718 -0
  29. package/dist/cli/factories/commandFactory.d.ts +8 -0
  30. package/dist/cli/factories/commandFactory.js +116 -0
  31. package/dist/cli/loop/optionsSchema.d.ts +1 -1
  32. package/dist/cli/parser.js +4 -0
  33. package/dist/index.d.ts +6 -0
  34. package/dist/index.js +19 -0
  35. package/dist/lib/agent/agent.d.ts +104 -0
  36. package/dist/lib/agent/agent.js +402 -0
  37. package/dist/lib/agent/agentNetwork.d.ts +87 -0
  38. package/dist/lib/agent/agentNetwork.js +459 -0
  39. package/dist/lib/agent/communication/index.d.ts +9 -0
  40. package/dist/lib/agent/communication/index.js +10 -0
  41. package/dist/lib/agent/communication/message-bus.d.ts +113 -0
  42. package/dist/lib/agent/communication/message-bus.js +407 -0
  43. package/dist/lib/agent/coordination/coordinator.d.ts +83 -0
  44. package/dist/lib/agent/coordination/coordinator.js +599 -0
  45. package/dist/lib/agent/coordination/index.d.ts +10 -0
  46. package/dist/lib/agent/coordination/index.js +11 -0
  47. package/dist/lib/agent/coordination/task-distributor.d.ts +113 -0
  48. package/dist/lib/agent/coordination/task-distributor.js +586 -0
  49. package/dist/lib/agent/index.d.ts +38 -0
  50. package/dist/lib/agent/index.js +45 -0
  51. package/dist/lib/agent/orchestration/index.d.ts +10 -0
  52. package/dist/lib/agent/orchestration/index.js +11 -0
  53. package/dist/lib/agent/orchestration/orchestrator.d.ts +114 -0
  54. package/dist/lib/agent/orchestration/orchestrator.js +477 -0
  55. package/dist/lib/agent/orchestration/topology.d.ts +164 -0
  56. package/dist/lib/agent/orchestration/topology.js +521 -0
  57. package/dist/lib/agent/prompts/routingPrompts.d.ts +63 -0
  58. package/dist/lib/agent/prompts/routingPrompts.js +202 -0
  59. package/dist/lib/index.d.ts +6 -0
  60. package/dist/lib/index.js +19 -0
  61. package/dist/lib/neurolink.d.ts +129 -0
  62. package/dist/lib/neurolink.js +276 -0
  63. package/dist/lib/processors/config/{fileTypes.js → fileExtensions.js} +1 -1
  64. package/dist/lib/processors/config/index.d.ts +2 -2
  65. package/dist/lib/processors/config/index.js +2 -2
  66. package/dist/lib/processors/config/{mimeTypes.js → mimeConstants.js} +1 -1
  67. package/dist/lib/processors/index.js +8 -0
  68. package/dist/lib/providers/googleAiStudio.js +28 -7
  69. package/dist/lib/providers/googleNativeGemini3.d.ts +18 -0
  70. package/dist/lib/providers/googleNativeGemini3.js +69 -3
  71. package/dist/lib/providers/googleVertex.js +33 -9
  72. package/dist/lib/types/agentNetwork.d.ts +1184 -0
  73. package/dist/lib/types/agentNetwork.js +8 -0
  74. package/dist/lib/types/cli.d.ts +66 -0
  75. package/dist/lib/types/common.d.ts +3 -0
  76. package/dist/lib/types/generate.d.ts +53 -0
  77. package/dist/lib/types/index.d.ts +2 -0
  78. package/dist/lib/types/index.js +3 -0
  79. package/dist/lib/types/ioProcessor.d.ts +119 -0
  80. package/dist/lib/types/ioProcessor.js +10 -0
  81. package/dist/lib/types/providers.d.ts +8 -0
  82. package/dist/lib/types/stream.d.ts +36 -0
  83. package/dist/lib/utils/piiDetector.d.ts +24 -0
  84. package/dist/lib/utils/piiDetector.js +221 -0
  85. package/dist/lib/utils/pricing.js +144 -26
  86. package/dist/lib/utils/responseValidator.d.ts +21 -0
  87. package/dist/lib/utils/responseValidator.js +354 -0
  88. package/dist/lib/utils/tokenUtils.d.ts +11 -0
  89. package/dist/lib/utils/tokenUtils.js +33 -2
  90. package/dist/lib/utils/tripwireEvaluator.d.ts +73 -0
  91. package/dist/lib/utils/tripwireEvaluator.js +285 -0
  92. package/dist/neurolink.d.ts +129 -0
  93. package/dist/neurolink.js +276 -0
  94. package/dist/processors/config/index.d.ts +2 -2
  95. package/dist/processors/config/index.js +2 -2
  96. package/dist/processors/index.js +8 -0
  97. package/dist/providers/googleAiStudio.js +28 -7
  98. package/dist/providers/googleNativeGemini3.d.ts +18 -0
  99. package/dist/providers/googleNativeGemini3.js +69 -3
  100. package/dist/providers/googleVertex.js +33 -9
  101. package/dist/types/agentNetwork.d.ts +1184 -0
  102. package/dist/types/agentNetwork.js +7 -0
  103. package/dist/types/cli.d.ts +66 -0
  104. package/dist/types/common.d.ts +3 -0
  105. package/dist/types/generate.d.ts +53 -0
  106. package/dist/types/index.d.ts +2 -0
  107. package/dist/types/index.js +3 -0
  108. package/dist/types/ioProcessor.d.ts +119 -0
  109. package/dist/types/ioProcessor.js +9 -0
  110. package/dist/types/providers.d.ts +8 -0
  111. package/dist/types/stream.d.ts +36 -0
  112. package/dist/utils/piiDetector.d.ts +24 -0
  113. package/dist/utils/piiDetector.js +220 -0
  114. package/dist/utils/pricing.js +144 -26
  115. package/dist/utils/responseValidator.d.ts +21 -0
  116. package/dist/utils/responseValidator.js +353 -0
  117. package/dist/utils/tokenUtils.d.ts +11 -0
  118. package/dist/utils/tokenUtils.js +33 -2
  119. package/dist/utils/tripwireEvaluator.d.ts +73 -0
  120. package/dist/utils/tripwireEvaluator.js +284 -0
  121. package/package.json +1 -1
  122. /package/dist/lib/processors/config/{fileTypes.d.ts → fileExtensions.d.ts} +0 -0
  123. /package/dist/lib/processors/config/{mimeTypes.d.ts → mimeConstants.d.ts} +0 -0
  124. /package/dist/processors/config/{fileTypes.d.ts → fileExtensions.d.ts} +0 -0
  125. /package/dist/processors/config/{fileTypes.js → fileExtensions.js} +0 -0
  126. /package/dist/processors/config/{mimeTypes.d.ts → mimeConstants.d.ts} +0 -0
  127. /package/dist/processors/config/{mimeTypes.js → mimeConstants.js} +0 -0
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Agent Module - Multi-Agent Networks for NeuroLink
3
+ *
4
+ * This module provides multi-agent orchestration capabilities:
5
+ * - Agent: Individual agent with specialized instructions and tools
6
+ * - AgentNetwork: Multi-agent orchestration using agents-as-tools pattern
7
+ *
8
+ * Types for this module live in src/lib/types/agentNetwork.ts and are
9
+ * re-exported via the central barrel at src/lib/types/index.ts.
10
+ *
11
+ * @example Basic Usage
12
+ * ```typescript
13
+ * import { Agent, AgentNetwork } from '@juspay/neurolink';
14
+ *
15
+ * const neurolink = new NeuroLink();
16
+ *
17
+ * // Create a network with multiple agents
18
+ * const network = neurolink.createNetwork({
19
+ * name: 'Content Team',
20
+ * agents: [
21
+ * { id: 'researcher', name: 'Researcher', description: '...', instructions: '...' },
22
+ * { id: 'writer', name: 'Writer', description: '...', instructions: '...' }
23
+ * ]
24
+ * });
25
+ *
26
+ * // Execute the network
27
+ * const result = await network.execute({
28
+ * message: 'Write an article about AI trends'
29
+ * });
30
+ * ```
31
+ */
32
+ export { Agent } from "./agent.js";
33
+ export { AgentNetwork } from "./agentNetwork.js";
34
+ export { directAgentTools, getAvailableToolNames, getToolsForCategory, } from "./directTools.js";
35
+ export { buildConfidencePrompt, buildMultiStepPlanningPrompt, buildRoutingPrompt, parseRoutingResponse, ROUTING_PROMPTS, } from "./prompts/routingPrompts.js";
36
+ export { AgentCoordinator, TaskDistributor } from "./coordination/index.js";
37
+ export { MessageBus } from "./communication/index.js";
38
+ export { NetworkOrchestrator, NetworkTopology, TopologyBuilder, } from "./orchestration/index.js";
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Agent Module - Multi-Agent Networks for NeuroLink
3
+ *
4
+ * This module provides multi-agent orchestration capabilities:
5
+ * - Agent: Individual agent with specialized instructions and tools
6
+ * - AgentNetwork: Multi-agent orchestration using agents-as-tools pattern
7
+ *
8
+ * Types for this module live in src/lib/types/agentNetwork.ts and are
9
+ * re-exported via the central barrel at src/lib/types/index.ts.
10
+ *
11
+ * @example Basic Usage
12
+ * ```typescript
13
+ * import { Agent, AgentNetwork } from '@juspay/neurolink';
14
+ *
15
+ * const neurolink = new NeuroLink();
16
+ *
17
+ * // Create a network with multiple agents
18
+ * const network = neurolink.createNetwork({
19
+ * name: 'Content Team',
20
+ * agents: [
21
+ * { id: 'researcher', name: 'Researcher', description: '...', instructions: '...' },
22
+ * { id: 'writer', name: 'Writer', description: '...', instructions: '...' }
23
+ * ]
24
+ * });
25
+ *
26
+ * // Execute the network
27
+ * const result = await network.execute({
28
+ * message: 'Write an article about AI trends'
29
+ * });
30
+ * ```
31
+ */
32
+ // Core agent classes
33
+ export { Agent } from "./agent.js";
34
+ export { AgentNetwork } from "./agentNetwork.js";
35
+ // Direct tools (existing)
36
+ export { directAgentTools, getAvailableToolNames, getToolsForCategory, } from "./directTools.js";
37
+ // Routing prompts and utilities
38
+ export { buildConfidencePrompt, buildMultiStepPlanningPrompt, buildRoutingPrompt, parseRoutingResponse, ROUTING_PROMPTS, } from "./prompts/routingPrompts.js";
39
+ // Coordination module
40
+ export { AgentCoordinator, TaskDistributor } from "./coordination/index.js";
41
+ // Communication module
42
+ export { MessageBus } from "./communication/index.js";
43
+ // Orchestration module
44
+ export { NetworkOrchestrator, NetworkTopology, TopologyBuilder, } from "./orchestration/index.js";
45
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Network Orchestration Module
3
+ *
4
+ * Provides high-level orchestration capabilities for agent networks.
5
+ *
6
+ * Types for this module live in src/lib/types/agentNetwork.ts and are
7
+ * re-exported via the central barrel at src/lib/types/index.ts.
8
+ */
9
+ export { NetworkOrchestrator } from "./orchestrator.js";
10
+ export { NetworkTopology, TopologyBuilder } from "./topology.js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Network Orchestration Module
3
+ *
4
+ * Provides high-level orchestration capabilities for agent networks.
5
+ *
6
+ * Types for this module live in src/lib/types/agentNetwork.ts and are
7
+ * re-exported via the central barrel at src/lib/types/index.ts.
8
+ */
9
+ export { NetworkOrchestrator } from "./orchestrator.js";
10
+ export { NetworkTopology, TopologyBuilder } from "./topology.js";
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Network Orchestrator - High-level orchestration of agent networks
3
+ *
4
+ * The Orchestrator manages:
5
+ * - Network lifecycle (creation, execution, shutdown)
6
+ * - Multi-network coordination
7
+ * - Network-level policies and constraints
8
+ * - Resource management and scaling
9
+ */
10
+ import type { NeuroLink } from "../../neurolink.js";
11
+ import type { AgentNetwork } from "../agentNetwork.js";
12
+ import { MessageBus } from "../communication/message-bus.js";
13
+ import type { AgentNetworkConfig, HierarchicalNetworkConfig, NetworkExecutionInput, NetworkExecutionOptions, NetworkExecutionResult, NetworkStreamChunk, HierarchicalExecutionTrace, CoordinationStrategy, OrchestrationMode, NetworkState, NetworkInfo, OrchestratorConfig } from "../../types/index.js";
14
+ /**
15
+ * Network Orchestrator - Central controller for agent networks
16
+ */
17
+ export declare class NetworkOrchestrator {
18
+ private neurolink;
19
+ private networks;
20
+ private networkInfo;
21
+ private coordinators;
22
+ private messageBus;
23
+ private config;
24
+ private emitter;
25
+ private executionQueue;
26
+ private activeExecutions;
27
+ constructor(neurolink: NeuroLink, config?: OrchestratorConfig);
28
+ /**
29
+ * Create a new agent network
30
+ */
31
+ createNetwork(config: AgentNetworkConfig, mode?: OrchestrationMode): Promise<AgentNetwork>;
32
+ /**
33
+ * Create a hierarchical network
34
+ */
35
+ createHierarchicalNetwork(config: HierarchicalNetworkConfig, parentNetworkId?: string): Promise<AgentNetwork>;
36
+ /**
37
+ * Get a network by ID
38
+ */
39
+ getNetwork(networkId: string): AgentNetwork | undefined;
40
+ /**
41
+ * Get network info
42
+ */
43
+ getNetworkInfo(networkId: string): NetworkInfo | undefined;
44
+ /**
45
+ * Get all networks
46
+ */
47
+ getAllNetworks(): NetworkInfo[];
48
+ /**
49
+ * Execute a network
50
+ */
51
+ executeNetwork(networkId: string, input: NetworkExecutionInput, options?: NetworkExecutionOptions): Promise<NetworkExecutionResult>;
52
+ /**
53
+ * Internal network execution
54
+ */
55
+ private executeNetworkInternal;
56
+ /**
57
+ * Queue an execution request
58
+ */
59
+ private queueExecution;
60
+ /**
61
+ * Process queued executions
62
+ */
63
+ private processExecutionQueue;
64
+ /**
65
+ * Stream network execution
66
+ */
67
+ streamNetwork(networkId: string, input: NetworkExecutionInput, options?: NetworkExecutionOptions): AsyncIterable<NetworkStreamChunk>;
68
+ /**
69
+ * Execute hierarchical network with delegation
70
+ */
71
+ executeHierarchical(networkId: string, input: NetworkExecutionInput, options?: NetworkExecutionOptions): Promise<HierarchicalExecutionTrace>;
72
+ /**
73
+ * Pause a network
74
+ */
75
+ pauseNetwork(networkId: string): void;
76
+ /**
77
+ * Resume a network
78
+ */
79
+ resumeNetwork(networkId: string): void;
80
+ /**
81
+ * Shutdown a network
82
+ */
83
+ shutdownNetwork(networkId: string): Promise<void>;
84
+ /**
85
+ * Coordinate multiple networks
86
+ */
87
+ coordinateNetworks(networkIds: string[], task: string, strategy?: CoordinationStrategy): Promise<Map<string, NetworkExecutionResult>>;
88
+ /**
89
+ * Get orchestrator statistics
90
+ */
91
+ getStats(): {
92
+ totalNetworks: number;
93
+ activeExecutions: number;
94
+ queuedExecutions: number;
95
+ totalExecutions: number;
96
+ networksByState: Record<NetworkState, number>;
97
+ };
98
+ /**
99
+ * Get the shared message bus
100
+ */
101
+ getMessageBus(): MessageBus;
102
+ /**
103
+ * Subscribe to orchestrator events
104
+ */
105
+ on(event: string, handler: (...args: unknown[]) => void): void;
106
+ /**
107
+ * Unsubscribe from orchestrator events
108
+ */
109
+ off(event: string, handler: (...args: unknown[]) => void): void;
110
+ /**
111
+ * Shutdown the orchestrator
112
+ */
113
+ shutdown(): Promise<void>;
114
+ }
@@ -0,0 +1,477 @@
1
+ /**
2
+ * Network Orchestrator - High-level orchestration of agent networks
3
+ *
4
+ * The Orchestrator manages:
5
+ * - Network lifecycle (creation, execution, shutdown)
6
+ * - Multi-network coordination
7
+ * - Network-level policies and constraints
8
+ * - Resource management and scaling
9
+ */
10
+ import { EventEmitter } from "events";
11
+ import { randomUUID } from "crypto";
12
+ import { AgentCoordinator } from "../coordination/coordinator.js";
13
+ import { MessageBus } from "../communication/message-bus.js";
14
+ import { logger } from "../../utils/logger.js";
15
+ /**
16
+ * Network Orchestrator - Central controller for agent networks
17
+ */
18
+ export class NetworkOrchestrator {
19
+ neurolink;
20
+ networks = new Map();
21
+ networkInfo = new Map();
22
+ coordinators = new Map();
23
+ messageBus;
24
+ config;
25
+ emitter;
26
+ executionQueue = [];
27
+ activeExecutions = new Map();
28
+ constructor(neurolink, config) {
29
+ this.neurolink = neurolink;
30
+ this.config = {
31
+ defaultMode: "autonomous",
32
+ maxConcurrentExecutions: 5,
33
+ defaultTimeout: 120000,
34
+ enableHierarchy: true,
35
+ maxHierarchyDepth: 3,
36
+ enableSharedMessageBus: true,
37
+ resourceLimits: {
38
+ maxNetworks: 10,
39
+ maxAgentsPerNetwork: 20,
40
+ maxTotalAgents: 100,
41
+ },
42
+ ...config,
43
+ };
44
+ this.emitter = new EventEmitter();
45
+ this.messageBus = new MessageBus();
46
+ logger.info("[NetworkOrchestrator] Initialized", {
47
+ maxConcurrentExecutions: this.config.maxConcurrentExecutions,
48
+ enableHierarchy: this.config.enableHierarchy,
49
+ });
50
+ }
51
+ /**
52
+ * Create a new agent network
53
+ */
54
+ async createNetwork(config, mode) {
55
+ // Check resource limits
56
+ if (this.config.resourceLimits?.maxNetworks &&
57
+ this.networks.size >= this.config.resourceLimits.maxNetworks) {
58
+ throw new Error("Maximum number of networks reached");
59
+ }
60
+ if (this.config.resourceLimits?.maxAgentsPerNetwork &&
61
+ config.agents.length > this.config.resourceLimits.maxAgentsPerNetwork) {
62
+ throw new Error(`Maximum agents per network (${this.config.resourceLimits.maxAgentsPerNetwork}) exceeded`);
63
+ }
64
+ if (this.config.resourceLimits?.maxTotalAgents) {
65
+ const currentTotalAgents = Array.from(this.networkInfo.values()).reduce((sum, info) => sum + info.agentCount, 0);
66
+ if (currentTotalAgents + config.agents.length >
67
+ this.config.resourceLimits.maxTotalAgents) {
68
+ throw new Error(`Maximum total agents (${this.config.resourceLimits.maxTotalAgents}) exceeded`);
69
+ }
70
+ }
71
+ // Create the network via NeuroLink
72
+ const network = await this.neurolink.createNetwork(config);
73
+ // Track network info
74
+ const info = {
75
+ id: network.id,
76
+ name: network.name,
77
+ state: "ready",
78
+ agentCount: config.agents.length,
79
+ mode: mode ?? this.config.defaultMode,
80
+ createdAt: Date.now(),
81
+ executionCount: 0,
82
+ childNetworkIds: [],
83
+ };
84
+ this.networkInfo.set(network.id, info);
85
+ this.networks.set(network.id, network);
86
+ // Create coordinator for the network
87
+ const coordinator = new AgentCoordinator({
88
+ strategy: "sequential",
89
+ maxConcurrency: 3,
90
+ });
91
+ for (const agent of network.getAllAgents()) {
92
+ coordinator.registerAgent(agent);
93
+ }
94
+ this.coordinators.set(network.id, coordinator);
95
+ this.emitter.emit("network:created", {
96
+ networkId: network.id,
97
+ name: network.name,
98
+ });
99
+ logger.info(`[NetworkOrchestrator] Network created: ${network.name}`, {
100
+ networkId: network.id,
101
+ agentCount: config.agents.length,
102
+ });
103
+ return network;
104
+ }
105
+ /**
106
+ * Create a hierarchical network
107
+ */
108
+ async createHierarchicalNetwork(config, parentNetworkId) {
109
+ if (!this.config.enableHierarchy) {
110
+ throw new Error("Hierarchical networks are disabled");
111
+ }
112
+ // Check hierarchy constraints
113
+ if (parentNetworkId) {
114
+ const parentInfo = this.networkInfo.get(parentNetworkId);
115
+ if (!parentInfo) {
116
+ throw new Error(`Parent network not found: ${parentNetworkId}`);
117
+ }
118
+ // Check depth
119
+ let depth = 0;
120
+ let currentParent = parentInfo;
121
+ while (currentParent.parentNetworkId) {
122
+ depth++;
123
+ currentParent = this.networkInfo.get(currentParent.parentNetworkId);
124
+ if (depth >= this.config.maxHierarchyDepth) {
125
+ throw new Error(`Maximum hierarchy depth (${this.config.maxHierarchyDepth}) exceeded`);
126
+ }
127
+ }
128
+ }
129
+ const network = await this.createNetwork(config, config.supervisionMode ?? "hierarchical");
130
+ // Set up hierarchy relationships
131
+ if (parentNetworkId) {
132
+ const info = this.networkInfo.get(network.id);
133
+ info.parentNetworkId = parentNetworkId;
134
+ const parentInfo = this.networkInfo.get(parentNetworkId);
135
+ parentInfo.childNetworkIds.push(network.id);
136
+ }
137
+ return network;
138
+ }
139
+ /**
140
+ * Get a network by ID
141
+ */
142
+ getNetwork(networkId) {
143
+ return this.networks.get(networkId);
144
+ }
145
+ /**
146
+ * Get network info
147
+ */
148
+ getNetworkInfo(networkId) {
149
+ return this.networkInfo.get(networkId);
150
+ }
151
+ /**
152
+ * Get all networks
153
+ */
154
+ getAllNetworks() {
155
+ return Array.from(this.networkInfo.values());
156
+ }
157
+ /**
158
+ * Execute a network
159
+ */
160
+ async executeNetwork(networkId, input, options) {
161
+ const network = this.networks.get(networkId);
162
+ if (!network) {
163
+ throw new Error(`Network not found: ${networkId}`);
164
+ }
165
+ const info = this.networkInfo.get(networkId);
166
+ if (info.state === "paused") {
167
+ throw new Error(`Network is paused: ${networkId}`);
168
+ }
169
+ if (info.state === "shutdown") {
170
+ throw new Error(`Network is shut down: ${networkId}`);
171
+ }
172
+ if (info.state === "executing") {
173
+ // Queue the execution
174
+ return this.queueExecution({ networkId, input, options });
175
+ }
176
+ // Check concurrent execution limit
177
+ if (this.activeExecutions.size >= this.config.maxConcurrentExecutions) {
178
+ return this.queueExecution({ networkId, input, options });
179
+ }
180
+ return this.executeNetworkInternal(network, info, input, options);
181
+ }
182
+ /**
183
+ * Internal network execution
184
+ */
185
+ async executeNetworkInternal(network, info, input, options) {
186
+ info.state = "executing";
187
+ info.executionCount++;
188
+ const executionPromise = (async () => {
189
+ try {
190
+ this.emitter.emit("network:execution:start", {
191
+ networkId: network.id,
192
+ input,
193
+ });
194
+ const result = await network.execute(input, {
195
+ ...options,
196
+ timeout: options?.timeout ?? this.config.defaultTimeout,
197
+ });
198
+ info.lastExecutionAt = Date.now();
199
+ info.state = "ready";
200
+ this.emitter.emit("network:execution:complete", {
201
+ networkId: network.id,
202
+ result,
203
+ });
204
+ return result;
205
+ }
206
+ catch (error) {
207
+ info.state = "error";
208
+ this.emitter.emit("network:execution:error", {
209
+ networkId: network.id,
210
+ error: error instanceof Error ? error.message : String(error),
211
+ });
212
+ throw error;
213
+ }
214
+ finally {
215
+ this.activeExecutions.delete(network.id);
216
+ this.processExecutionQueue();
217
+ }
218
+ })();
219
+ this.activeExecutions.set(network.id, executionPromise);
220
+ return executionPromise;
221
+ }
222
+ /**
223
+ * Queue an execution request
224
+ */
225
+ async queueExecution(request) {
226
+ return new Promise((resolve, reject) => {
227
+ const _queuedRequest = {
228
+ ...request,
229
+ resolve,
230
+ reject,
231
+ };
232
+ this.executionQueue.push(_queuedRequest);
233
+ this.executionQueue.sort((a, b) => {
234
+ const priorityOrder = { high: 0, normal: 1, low: 2 };
235
+ return ((priorityOrder[a.priority ?? "normal"] ?? 1) -
236
+ (priorityOrder[b.priority ?? "normal"] ?? 1));
237
+ });
238
+ this.emitter.emit("execution:queued", { networkId: request.networkId });
239
+ });
240
+ }
241
+ /**
242
+ * Process queued executions
243
+ */
244
+ async processExecutionQueue() {
245
+ while (this.executionQueue.length > 0 &&
246
+ this.activeExecutions.size < this.config.maxConcurrentExecutions) {
247
+ const request = this.executionQueue.shift();
248
+ const network = this.networks.get(request.networkId);
249
+ const info = this.networkInfo.get(request.networkId);
250
+ if (network && info && info.state !== "executing") {
251
+ // Fire-and-forget: executeNetworkInternal is NOT awaited so the while
252
+ // loop drains the entire queue synchronously before any launched
253
+ // execution sets info.state = "executing" (that happens at the first
254
+ // await inside executeNetworkInternal). This is intentional — it lets
255
+ // one queue-drain pass start multiple networks in parallel up to
256
+ // maxConcurrentExecutions.
257
+ this.executeNetworkInternal(network, info, request.input, request.options)
258
+ .then((result) => request.resolve?.(result))
259
+ .catch((err) => request.reject?.(err));
260
+ }
261
+ else if (request.reject) {
262
+ request.reject(new Error(`Network unavailable for execution: ${request.networkId}`));
263
+ }
264
+ }
265
+ }
266
+ /**
267
+ * Stream network execution
268
+ */
269
+ async *streamNetwork(networkId, input, options) {
270
+ const network = this.networks.get(networkId);
271
+ if (!network) {
272
+ throw new Error(`Network not found: ${networkId}`);
273
+ }
274
+ const info = this.networkInfo.get(networkId);
275
+ if (info.state === "paused") {
276
+ throw new Error(`Network is paused: ${networkId}`);
277
+ }
278
+ if (info.state === "shutdown") {
279
+ throw new Error(`Network is shut down: ${networkId}`);
280
+ }
281
+ if (info.state === "executing") {
282
+ throw new Error(`Network is already executing: ${networkId}. Streaming does not support queuing.`);
283
+ }
284
+ if (this.activeExecutions.size >= this.config.maxConcurrentExecutions) {
285
+ throw new Error(`Maximum concurrent executions (${this.config.maxConcurrentExecutions}) reached. Streaming does not support queuing.`);
286
+ }
287
+ info.state = "executing";
288
+ info.executionCount++;
289
+ const streamPromise = Promise.resolve(); // placeholder to track in activeExecutions
290
+ this.activeExecutions.set(networkId, streamPromise);
291
+ try {
292
+ yield* network.stream(input, options);
293
+ info.lastExecutionAt = Date.now();
294
+ }
295
+ finally {
296
+ info.state = "ready";
297
+ this.activeExecutions.delete(networkId);
298
+ this.processExecutionQueue();
299
+ }
300
+ }
301
+ /**
302
+ * Execute hierarchical network with delegation
303
+ */
304
+ async executeHierarchical(networkId, input, options) {
305
+ const network = this.networks.get(networkId);
306
+ const info = this.networkInfo.get(networkId);
307
+ if (!network || !info) {
308
+ throw new Error(`Network not found: ${networkId}`);
309
+ }
310
+ const traceId = randomUUID();
311
+ const trace = {
312
+ traceId,
313
+ steps: [],
314
+ routingDecisions: [],
315
+ startTime: Date.now(),
316
+ hierarchyLevel: 0,
317
+ childTraces: [],
318
+ };
319
+ // Calculate hierarchy level
320
+ let currentInfo = info;
321
+ while (currentInfo.parentNetworkId) {
322
+ trace.hierarchyLevel++;
323
+ trace.parentTraceId = currentInfo.parentNetworkId;
324
+ currentInfo = this.networkInfo.get(currentInfo.parentNetworkId);
325
+ }
326
+ // Execute main network
327
+ const result = await this.executeNetwork(networkId, input, options);
328
+ trace.steps = result.trace.steps;
329
+ trace.routingDecisions = result.trace.routingDecisions;
330
+ trace.endTime = Date.now();
331
+ // Execute child networks if needed based on delegation rules
332
+ for (const childId of info.childNetworkIds) {
333
+ const childNetwork = this.networks.get(childId);
334
+ if (childNetwork) {
335
+ const childTrace = await this.executeHierarchical(childId, { message: result.content, context: input.context }, options);
336
+ trace.childTraces?.push(childTrace);
337
+ }
338
+ }
339
+ return trace;
340
+ }
341
+ /**
342
+ * Pause a network
343
+ */
344
+ pauseNetwork(networkId) {
345
+ const info = this.networkInfo.get(networkId);
346
+ if (info && info.state === "ready") {
347
+ info.state = "paused";
348
+ this.emitter.emit("network:paused", { networkId });
349
+ }
350
+ }
351
+ /**
352
+ * Resume a network
353
+ */
354
+ resumeNetwork(networkId) {
355
+ const info = this.networkInfo.get(networkId);
356
+ if (info && info.state === "paused") {
357
+ info.state = "ready";
358
+ this.emitter.emit("network:resumed", { networkId });
359
+ }
360
+ }
361
+ /**
362
+ * Shutdown a network
363
+ */
364
+ async shutdownNetwork(networkId) {
365
+ const info = this.networkInfo.get(networkId);
366
+ if (!info) {
367
+ return;
368
+ }
369
+ // Shutdown child networks first
370
+ for (const childId of info.childNetworkIds) {
371
+ await this.shutdownNetwork(childId);
372
+ }
373
+ // Remove from parent's child list
374
+ if (info.parentNetworkId) {
375
+ const parentInfo = this.networkInfo.get(info.parentNetworkId);
376
+ if (parentInfo) {
377
+ parentInfo.childNetworkIds = parentInfo.childNetworkIds.filter((id) => id !== networkId);
378
+ }
379
+ }
380
+ info.state = "shutdown";
381
+ this.networks.delete(networkId);
382
+ this.networkInfo.delete(networkId);
383
+ this.coordinators.delete(networkId);
384
+ this.emitter.emit("network:shutdown", { networkId });
385
+ logger.info(`[NetworkOrchestrator] Network shutdown: ${networkId}`);
386
+ }
387
+ /**
388
+ * Coordinate multiple networks
389
+ */
390
+ async coordinateNetworks(networkIds, task, strategy = "parallel") {
391
+ const results = new Map();
392
+ switch (strategy) {
393
+ case "sequential":
394
+ case "pipeline": {
395
+ // Each network receives the previous network's output as its input
396
+ let currentInput = task;
397
+ for (const networkId of networkIds) {
398
+ const result = await this.executeNetwork(networkId, {
399
+ message: currentInput,
400
+ });
401
+ results.set(networkId, result);
402
+ currentInput = result.content;
403
+ }
404
+ break;
405
+ }
406
+ case "parallel": {
407
+ await Promise.all(networkIds.map(async (networkId) => {
408
+ const result = await this.executeNetwork(networkId, {
409
+ message: task,
410
+ });
411
+ results.set(networkId, result);
412
+ }));
413
+ break;
414
+ }
415
+ default:
416
+ throw new Error(`Unsupported coordination strategy: ${strategy}`);
417
+ }
418
+ return results;
419
+ }
420
+ /**
421
+ * Get orchestrator statistics
422
+ */
423
+ getStats() {
424
+ const networksByState = {
425
+ idle: 0,
426
+ initializing: 0,
427
+ ready: 0,
428
+ executing: 0,
429
+ paused: 0,
430
+ error: 0,
431
+ shutdown: 0,
432
+ };
433
+ let totalExecutions = 0;
434
+ for (const info of this.networkInfo.values()) {
435
+ networksByState[info.state]++;
436
+ totalExecutions += info.executionCount;
437
+ }
438
+ return {
439
+ totalNetworks: this.networks.size,
440
+ activeExecutions: this.activeExecutions.size,
441
+ queuedExecutions: this.executionQueue.length,
442
+ totalExecutions,
443
+ networksByState,
444
+ };
445
+ }
446
+ /**
447
+ * Get the shared message bus
448
+ */
449
+ getMessageBus() {
450
+ return this.messageBus;
451
+ }
452
+ /**
453
+ * Subscribe to orchestrator events
454
+ */
455
+ on(event, handler) {
456
+ this.emitter.on(event, handler);
457
+ }
458
+ /**
459
+ * Unsubscribe from orchestrator events
460
+ */
461
+ off(event, handler) {
462
+ this.emitter.off(event, handler);
463
+ }
464
+ /**
465
+ * Shutdown the orchestrator
466
+ */
467
+ async shutdown() {
468
+ // Shutdown all networks
469
+ for (const networkId of this.networks.keys()) {
470
+ await this.shutdownNetwork(networkId);
471
+ }
472
+ // Shutdown message bus
473
+ this.messageBus.shutdown();
474
+ logger.info("[NetworkOrchestrator] Shutdown complete");
475
+ }
476
+ }
477
+ //# sourceMappingURL=orchestrator.js.map