@juspay/neurolink 5.1.0 → 5.3.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.
- package/CHANGELOG.md +21 -9
- package/README.md +123 -126
- package/dist/agent/direct-tools.d.ts +6 -6
- package/dist/cli/commands/config.d.ts +3 -3
- package/dist/cli/commands/mcp.js +8 -7
- package/dist/cli/factories/command-factory.d.ts +4 -0
- package/dist/cli/factories/command-factory.js +63 -8
- package/dist/cli/index.js +87 -140
- package/dist/core/base-provider.d.ts +423 -0
- package/dist/core/base-provider.js +376 -0
- package/dist/core/constants.d.ts +2 -1
- package/dist/core/constants.js +2 -1
- package/dist/core/dynamic-models.d.ts +6 -6
- package/dist/core/evaluation.d.ts +19 -80
- package/dist/core/evaluation.js +185 -484
- package/dist/core/factory.d.ts +3 -3
- package/dist/core/factory.js +31 -91
- package/dist/core/service-registry.d.ts +47 -0
- package/dist/core/service-registry.js +112 -0
- package/dist/core/types.d.ts +8 -1
- package/dist/factories/compatibility-factory.js +1 -1
- package/dist/factories/provider-factory.d.ts +72 -0
- package/dist/factories/provider-factory.js +144 -0
- package/dist/factories/provider-registry.d.ts +38 -0
- package/dist/factories/provider-registry.js +107 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -4
- package/dist/lib/agent/direct-tools.d.ts +6 -6
- package/dist/lib/core/base-provider.d.ts +423 -0
- package/dist/lib/core/base-provider.js +376 -0
- package/dist/lib/core/constants.d.ts +2 -1
- package/dist/lib/core/constants.js +2 -1
- package/dist/lib/core/dynamic-models.d.ts +6 -6
- package/dist/lib/core/evaluation.d.ts +19 -80
- package/dist/lib/core/evaluation.js +185 -484
- package/dist/lib/core/factory.d.ts +3 -3
- package/dist/lib/core/factory.js +30 -91
- package/dist/lib/core/service-registry.d.ts +47 -0
- package/dist/lib/core/service-registry.js +112 -0
- package/dist/lib/core/types.d.ts +8 -1
- package/dist/lib/factories/compatibility-factory.js +1 -1
- package/dist/lib/factories/provider-factory.d.ts +72 -0
- package/dist/lib/factories/provider-factory.js +144 -0
- package/dist/lib/factories/provider-registry.d.ts +38 -0
- package/dist/lib/factories/provider-registry.js +107 -0
- package/dist/lib/index.d.ts +4 -3
- package/dist/lib/index.js +2 -4
- package/dist/lib/mcp/client.d.ts +1 -0
- package/dist/lib/mcp/client.js +1 -0
- package/dist/lib/mcp/config.js +28 -3
- package/dist/lib/mcp/context-manager.d.ts +1 -0
- package/dist/lib/mcp/context-manager.js +8 -4
- package/dist/lib/mcp/function-calling.d.ts +13 -0
- package/dist/lib/mcp/function-calling.js +134 -35
- package/dist/lib/mcp/initialize-tools.d.ts +1 -1
- package/dist/lib/mcp/initialize-tools.js +45 -1
- package/dist/lib/mcp/initialize.js +16 -6
- package/dist/lib/mcp/neurolink-mcp-client.d.ts +1 -0
- package/dist/lib/mcp/neurolink-mcp-client.js +21 -5
- package/dist/lib/mcp/servers/agent/direct-tools-server.d.ts +8 -0
- package/dist/lib/mcp/servers/agent/direct-tools-server.js +109 -0
- package/dist/lib/mcp/servers/ai-providers/ai-core-server.js +3 -1
- package/dist/lib/mcp/servers/ai-providers/ai-workflow-tools.d.ts +2 -2
- package/dist/lib/mcp/unified-registry.d.ts +4 -0
- package/dist/lib/mcp/unified-registry.js +42 -9
- package/dist/lib/neurolink.d.ts +156 -117
- package/dist/lib/neurolink.js +619 -404
- package/dist/lib/providers/amazon-bedrock.d.ts +32 -0
- package/dist/lib/providers/amazon-bedrock.js +143 -0
- package/dist/lib/providers/analytics-helper.js +7 -4
- package/dist/lib/providers/anthropic-baseprovider.d.ts +23 -0
- package/dist/lib/providers/anthropic-baseprovider.js +114 -0
- package/dist/lib/providers/anthropic.d.ts +19 -43
- package/dist/lib/providers/anthropic.js +82 -306
- package/dist/lib/providers/azure-openai.d.ts +20 -0
- package/dist/lib/providers/azure-openai.js +89 -0
- package/dist/lib/providers/function-calling-provider.d.ts +64 -2
- package/dist/lib/providers/function-calling-provider.js +208 -9
- package/dist/lib/providers/google-ai-studio.d.ts +23 -0
- package/dist/lib/providers/google-ai-studio.js +107 -0
- package/dist/lib/providers/google-vertex.d.ts +47 -0
- package/dist/lib/providers/google-vertex.js +205 -0
- package/dist/lib/providers/huggingFace.d.ts +32 -25
- package/dist/lib/providers/huggingFace.js +97 -431
- package/dist/lib/providers/index.d.ts +9 -9
- package/dist/lib/providers/index.js +9 -9
- package/dist/lib/providers/mcp-provider.js +24 -5
- package/dist/lib/providers/mistral.d.ts +42 -0
- package/dist/lib/providers/mistral.js +160 -0
- package/dist/lib/providers/ollama.d.ts +52 -36
- package/dist/lib/providers/ollama.js +297 -520
- package/dist/lib/providers/openAI.d.ts +19 -18
- package/dist/lib/providers/openAI.js +76 -275
- package/dist/lib/sdk/tool-extension.d.ts +181 -0
- package/dist/lib/sdk/tool-extension.js +283 -0
- package/dist/lib/sdk/tool-registration.d.ts +95 -0
- package/dist/lib/sdk/tool-registration.js +167 -0
- package/dist/lib/services/streaming/streaming-manager.js +11 -10
- package/dist/lib/services/websocket/websocket-server.js +12 -11
- package/dist/lib/telemetry/telemetry-service.js +8 -7
- package/dist/lib/types/generate-types.d.ts +1 -0
- package/dist/lib/types/mcp-types.d.ts +116 -0
- package/dist/lib/types/mcp-types.js +5 -0
- package/dist/lib/types/stream-types.d.ts +30 -18
- package/dist/lib/types/universal-provider-options.d.ts +87 -0
- package/dist/lib/types/universal-provider-options.js +53 -0
- package/dist/mcp/client.d.ts +1 -0
- package/dist/mcp/client.js +1 -0
- package/dist/mcp/config.js +28 -3
- package/dist/mcp/context-manager.d.ts +1 -0
- package/dist/mcp/context-manager.js +8 -4
- package/dist/mcp/function-calling.d.ts +13 -0
- package/dist/mcp/function-calling.js +134 -35
- package/dist/mcp/initialize-tools.d.ts +1 -1
- package/dist/mcp/initialize-tools.js +45 -1
- package/dist/mcp/initialize.js +16 -6
- package/dist/mcp/neurolink-mcp-client.d.ts +1 -0
- package/dist/mcp/neurolink-mcp-client.js +21 -5
- package/dist/mcp/servers/agent/direct-tools-server.d.ts +8 -0
- package/dist/mcp/servers/agent/direct-tools-server.js +109 -0
- package/dist/mcp/servers/ai-providers/ai-core-server.js +3 -1
- package/dist/mcp/servers/ai-providers/ai-workflow-tools.d.ts +2 -2
- package/dist/mcp/unified-registry.d.ts +4 -0
- package/dist/mcp/unified-registry.js +42 -9
- package/dist/neurolink.d.ts +156 -117
- package/dist/neurolink.js +619 -404
- package/dist/providers/amazon-bedrock.d.ts +32 -0
- package/dist/providers/amazon-bedrock.js +143 -0
- package/dist/providers/analytics-helper.js +7 -4
- package/dist/providers/anthropic-baseprovider.d.ts +23 -0
- package/dist/providers/anthropic-baseprovider.js +114 -0
- package/dist/providers/anthropic.d.ts +19 -43
- package/dist/providers/anthropic.js +81 -305
- package/dist/providers/azure-openai.d.ts +20 -0
- package/dist/providers/azure-openai.js +89 -0
- package/dist/providers/function-calling-provider.d.ts +64 -2
- package/dist/providers/function-calling-provider.js +208 -9
- package/dist/providers/google-ai-studio.d.ts +23 -0
- package/dist/providers/google-ai-studio.js +108 -0
- package/dist/providers/google-vertex.d.ts +47 -0
- package/dist/providers/google-vertex.js +205 -0
- package/dist/providers/huggingFace.d.ts +32 -25
- package/dist/providers/huggingFace.js +96 -430
- package/dist/providers/index.d.ts +9 -9
- package/dist/providers/index.js +9 -9
- package/dist/providers/mcp-provider.js +24 -5
- package/dist/providers/mistral.d.ts +42 -0
- package/dist/providers/mistral.js +160 -0
- package/dist/providers/ollama.d.ts +52 -36
- package/dist/providers/ollama.js +297 -519
- package/dist/providers/openAI.d.ts +19 -18
- package/dist/providers/openAI.js +76 -276
- package/dist/sdk/tool-extension.d.ts +181 -0
- package/dist/sdk/tool-extension.js +283 -0
- package/dist/sdk/tool-registration.d.ts +95 -0
- package/dist/sdk/tool-registration.js +168 -0
- package/dist/services/streaming/streaming-manager.js +11 -10
- package/dist/services/websocket/websocket-server.js +12 -11
- package/dist/telemetry/telemetry-service.js +8 -7
- package/dist/types/generate-types.d.ts +1 -0
- package/dist/types/mcp-types.d.ts +116 -0
- package/dist/types/mcp-types.js +5 -0
- package/dist/types/stream-types.d.ts +30 -18
- package/dist/types/universal-provider-options.d.ts +87 -0
- package/dist/types/universal-provider-options.js +53 -0
- package/package.json +12 -5
- package/dist/lib/providers/agent-enhanced-provider.d.ts +0 -93
- package/dist/lib/providers/agent-enhanced-provider.js +0 -605
- package/dist/lib/providers/amazonBedrock.d.ts +0 -28
- package/dist/lib/providers/amazonBedrock.js +0 -364
- package/dist/lib/providers/azureOpenAI.d.ts +0 -42
- package/dist/lib/providers/azureOpenAI.js +0 -347
- package/dist/lib/providers/googleAIStudio.d.ts +0 -42
- package/dist/lib/providers/googleAIStudio.js +0 -364
- package/dist/lib/providers/googleVertexAI.d.ts +0 -34
- package/dist/lib/providers/googleVertexAI.js +0 -547
- package/dist/lib/providers/mistralAI.d.ts +0 -37
- package/dist/lib/providers/mistralAI.js +0 -325
- package/dist/providers/agent-enhanced-provider.d.ts +0 -93
- package/dist/providers/agent-enhanced-provider.js +0 -606
- package/dist/providers/amazonBedrock.d.ts +0 -28
- package/dist/providers/amazonBedrock.js +0 -364
- package/dist/providers/azureOpenAI.d.ts +0 -42
- package/dist/providers/azureOpenAI.js +0 -348
- package/dist/providers/googleAIStudio.d.ts +0 -42
- package/dist/providers/googleAIStudio.js +0 -364
- package/dist/providers/googleVertexAI.d.ts +0 -34
- package/dist/providers/googleVertexAI.js +0 -547
- package/dist/providers/mistralAI.d.ts +0 -37
- package/dist/providers/mistralAI.js +0 -325
|
@@ -1,606 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Agent-Enhanced Provider for NeuroLink CLI
|
|
3
|
-
* Integrates direct tools with AI providers for true agent functionality
|
|
4
|
-
*/
|
|
5
|
-
import { streamText, tool, generateText as aiGenerate } from "ai";
|
|
6
|
-
import { google } from "@ai-sdk/google";
|
|
7
|
-
import { openai } from "@ai-sdk/openai";
|
|
8
|
-
import { anthropic } from "@ai-sdk/anthropic";
|
|
9
|
-
import { directAgentTools, getToolsForCategory, } from "../agent/direct-tools.js";
|
|
10
|
-
import { StreamingEnhancer, StreamingMonitor, } from "../utils/streaming-utils.js";
|
|
11
|
-
import { UnifiedMCPSystem } from "../mcp/unified-mcp.js";
|
|
12
|
-
import { mcpLogger } from "../mcp/logging.js";
|
|
13
|
-
import { parseTimeout } from "../utils/timeout.js";
|
|
14
|
-
import { evaluateResponse } from "../core/evaluation.js";
|
|
15
|
-
import { createAnalytics } from "../core/analytics.js";
|
|
16
|
-
import { logger } from "../utils/logger.js";
|
|
17
|
-
/**
|
|
18
|
-
* Agent-Enhanced Provider Class
|
|
19
|
-
* Provides AI generation with tool calling capabilities
|
|
20
|
-
* Now includes MCP tool integration alongside direct tools
|
|
21
|
-
*/
|
|
22
|
-
export class AgentEnhancedProvider {
|
|
23
|
-
config;
|
|
24
|
-
model;
|
|
25
|
-
resolvedModelName = "default";
|
|
26
|
-
mcpSystem = null;
|
|
27
|
-
mcpInitialized = false;
|
|
28
|
-
mcpInitializing = false;
|
|
29
|
-
mcpInitFailed = false;
|
|
30
|
-
constructor(config) {
|
|
31
|
-
this.config = {
|
|
32
|
-
maxSteps: 5,
|
|
33
|
-
toolCategory: "all",
|
|
34
|
-
enableTools: true,
|
|
35
|
-
enableMCP: true,
|
|
36
|
-
mcpDiscoveryOptions: {
|
|
37
|
-
autoDiscover: true,
|
|
38
|
-
searchPaths: [process.cwd()],
|
|
39
|
-
configFiles: [".mcp-config.json", ".mcp-servers.json"],
|
|
40
|
-
},
|
|
41
|
-
...config,
|
|
42
|
-
};
|
|
43
|
-
// Initialize the AI model based on provider and store resolved model name
|
|
44
|
-
this.model = this.createModel();
|
|
45
|
-
// Initialize MCP registry if enabled
|
|
46
|
-
if (this.config.enableMCP) {
|
|
47
|
-
this.initializeMCP();
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
createModel() {
|
|
51
|
-
const { provider, model } = this.config;
|
|
52
|
-
switch (provider) {
|
|
53
|
-
case "google-ai":
|
|
54
|
-
this.resolvedModelName =
|
|
55
|
-
model || process.env.GOOGLE_AI_MODEL || "gemini-2.5-flash";
|
|
56
|
-
return google(this.resolvedModelName);
|
|
57
|
-
case "openai":
|
|
58
|
-
this.resolvedModelName = model || process.env.OPENAI_MODEL || "gpt-4o";
|
|
59
|
-
return openai(this.resolvedModelName);
|
|
60
|
-
case "anthropic":
|
|
61
|
-
this.resolvedModelName =
|
|
62
|
-
model || process.env.ANTHROPIC_MODEL || "claude-3-5-sonnet-20241022";
|
|
63
|
-
return anthropic(this.resolvedModelName);
|
|
64
|
-
default:
|
|
65
|
-
throw new Error(`Unsupported provider: ${provider}`);
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Initialize MCP registry with auto-discovery
|
|
70
|
-
*/
|
|
71
|
-
async initializeMCP() {
|
|
72
|
-
if (this.mcpInitializing || this.mcpInitFailed) {
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
this.mcpInitializing = true;
|
|
76
|
-
try {
|
|
77
|
-
mcpLogger.info("[AgentEnhancedProvider] Initializing MCP integration...");
|
|
78
|
-
this.mcpSystem = new UnifiedMCPSystem({
|
|
79
|
-
configPath: this.config.mcpDiscoveryOptions?.configFiles?.[0] ||
|
|
80
|
-
".mcp-config.json",
|
|
81
|
-
enableExternalServers: true,
|
|
82
|
-
enableInternalServers: true,
|
|
83
|
-
autoInitialize: false,
|
|
84
|
-
});
|
|
85
|
-
// ADD TIMEOUT to prevent hanging forever
|
|
86
|
-
const initPromise = this.mcpSystem.initialize();
|
|
87
|
-
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("MCP initialization timeout after 15 seconds")), this.config.mcpInitTimeoutMs || 15000));
|
|
88
|
-
await Promise.race([initPromise, timeoutPromise]);
|
|
89
|
-
this.mcpInitialized = true;
|
|
90
|
-
mcpLogger.info("[AgentEnhancedProvider] MCP integration initialized successfully");
|
|
91
|
-
}
|
|
92
|
-
catch (error) {
|
|
93
|
-
mcpLogger.error("[AgentEnhancedProvider] Failed to initialize MCP:", error);
|
|
94
|
-
this.mcpSystem = null;
|
|
95
|
-
this.mcpInitialized = false;
|
|
96
|
-
this.mcpInitFailed = true;
|
|
97
|
-
// Don't throw - continue with direct tools only
|
|
98
|
-
}
|
|
99
|
-
finally {
|
|
100
|
-
this.mcpInitializing = false;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Get combined tools: direct tools + MCP tools
|
|
105
|
-
*/
|
|
106
|
-
async getCombinedTools() {
|
|
107
|
-
const directTools = this.config.enableTools
|
|
108
|
-
? getToolsForCategory(this.config.toolCategory)
|
|
109
|
-
: {};
|
|
110
|
-
// If MCP is disabled or failed to initialize, return only direct tools
|
|
111
|
-
if (!this.config.enableMCP || !this.mcpSystem) {
|
|
112
|
-
return directTools;
|
|
113
|
-
}
|
|
114
|
-
// Get MCP tools if available
|
|
115
|
-
const mcpTools = {};
|
|
116
|
-
try {
|
|
117
|
-
// Skip if MCP failed to initialize or is still initializing
|
|
118
|
-
if (this.mcpInitFailed ||
|
|
119
|
-
this.mcpInitializing ||
|
|
120
|
-
!this.mcpInitialized ||
|
|
121
|
-
!this.mcpSystem) {
|
|
122
|
-
return directTools;
|
|
123
|
-
}
|
|
124
|
-
const mcpToolInfos = await this.mcpSystem.listTools();
|
|
125
|
-
// Convert MCP tools to AI SDK format
|
|
126
|
-
for (const toolInfo of mcpToolInfos) {
|
|
127
|
-
const toolKey = `mcp_${toolInfo.name}`;
|
|
128
|
-
mcpTools[toolKey] = {
|
|
129
|
-
description: toolInfo.description || `MCP tool: ${toolInfo.name}`,
|
|
130
|
-
parameters: toolInfo.inputSchema || {},
|
|
131
|
-
execute: async (args) => {
|
|
132
|
-
let timeoutId;
|
|
133
|
-
try {
|
|
134
|
-
// Create timeout controller for tool execution if configured
|
|
135
|
-
const toolTimeout = this.config.toolExecutionTimeout;
|
|
136
|
-
const toolAbortController = toolTimeout
|
|
137
|
-
? new AbortController()
|
|
138
|
-
: undefined;
|
|
139
|
-
if (toolAbortController && toolTimeout) {
|
|
140
|
-
const timeoutMs = typeof toolTimeout === "string"
|
|
141
|
-
? parseTimeout(toolTimeout)
|
|
142
|
-
: toolTimeout;
|
|
143
|
-
timeoutId = setTimeout(() => {
|
|
144
|
-
toolAbortController.abort();
|
|
145
|
-
}, timeoutMs);
|
|
146
|
-
}
|
|
147
|
-
const context = {
|
|
148
|
-
sessionId: "cli-session",
|
|
149
|
-
userId: "cli-user",
|
|
150
|
-
secureFS: {
|
|
151
|
-
readFile: async (path, encoding) => {
|
|
152
|
-
const fs = await import("fs/promises");
|
|
153
|
-
return encoding
|
|
154
|
-
? fs.readFile(path, {
|
|
155
|
-
encoding: encoding,
|
|
156
|
-
})
|
|
157
|
-
: fs.readFile(path);
|
|
158
|
-
},
|
|
159
|
-
writeFile: async (path, content) => {
|
|
160
|
-
const fs = await import("fs/promises");
|
|
161
|
-
await fs.writeFile(path, content);
|
|
162
|
-
},
|
|
163
|
-
readdir: async (path) => {
|
|
164
|
-
const fs = await import("fs/promises");
|
|
165
|
-
return fs.readdir(path);
|
|
166
|
-
},
|
|
167
|
-
stat: async (path) => {
|
|
168
|
-
const fs = await import("fs/promises");
|
|
169
|
-
return fs.stat(path);
|
|
170
|
-
},
|
|
171
|
-
mkdir: async (path, options) => {
|
|
172
|
-
const fs = await import("fs/promises");
|
|
173
|
-
await fs.mkdir(path, options);
|
|
174
|
-
},
|
|
175
|
-
exists: async (path) => {
|
|
176
|
-
const fs = await import("fs/promises");
|
|
177
|
-
try {
|
|
178
|
-
await fs.access(path);
|
|
179
|
-
return true;
|
|
180
|
-
}
|
|
181
|
-
catch {
|
|
182
|
-
return false;
|
|
183
|
-
}
|
|
184
|
-
},
|
|
185
|
-
},
|
|
186
|
-
path: {
|
|
187
|
-
join: (...paths) => {
|
|
188
|
-
const path = require("path");
|
|
189
|
-
return path.join(...paths);
|
|
190
|
-
},
|
|
191
|
-
resolve: (...paths) => {
|
|
192
|
-
const path = require("path");
|
|
193
|
-
return path.resolve(...paths);
|
|
194
|
-
},
|
|
195
|
-
relative: (from, to) => {
|
|
196
|
-
const path = require("path");
|
|
197
|
-
return path.relative(from, to);
|
|
198
|
-
},
|
|
199
|
-
dirname: (path) => {
|
|
200
|
-
const pathLib = require("path");
|
|
201
|
-
return pathLib.dirname(path);
|
|
202
|
-
},
|
|
203
|
-
basename: (path, ext) => {
|
|
204
|
-
const pathLib = require("path");
|
|
205
|
-
return pathLib.basename(path, ext);
|
|
206
|
-
},
|
|
207
|
-
},
|
|
208
|
-
grantedPermissions: ["read", "write", "execute"],
|
|
209
|
-
log: (level, message, data) => {
|
|
210
|
-
const logFn = mcpLogger[level];
|
|
211
|
-
if (typeof logFn === "function") {
|
|
212
|
-
if (data) {
|
|
213
|
-
logFn(`${message} ${JSON.stringify(data)}`);
|
|
214
|
-
}
|
|
215
|
-
else {
|
|
216
|
-
logFn(message);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
},
|
|
220
|
-
};
|
|
221
|
-
const toolPromise = this.mcpSystem.executeTool(toolInfo.name, args, context);
|
|
222
|
-
let result;
|
|
223
|
-
if (toolAbortController) {
|
|
224
|
-
// Race between tool execution and timeout
|
|
225
|
-
result = await Promise.race([
|
|
226
|
-
toolPromise,
|
|
227
|
-
new Promise((_, reject) => {
|
|
228
|
-
toolAbortController.signal.addEventListener("abort", () => {
|
|
229
|
-
reject(new Error(`Tool ${toolInfo.name} timed out after ${this.config.toolExecutionTimeout}`));
|
|
230
|
-
});
|
|
231
|
-
}),
|
|
232
|
-
]);
|
|
233
|
-
}
|
|
234
|
-
else {
|
|
235
|
-
result = await toolPromise;
|
|
236
|
-
}
|
|
237
|
-
// Clear timeout if successful
|
|
238
|
-
if (timeoutId) {
|
|
239
|
-
clearTimeout(timeoutId);
|
|
240
|
-
}
|
|
241
|
-
return result.data || result;
|
|
242
|
-
}
|
|
243
|
-
catch (error) {
|
|
244
|
-
// Clear timeout on error
|
|
245
|
-
if (timeoutId) {
|
|
246
|
-
clearTimeout(timeoutId);
|
|
247
|
-
}
|
|
248
|
-
mcpLogger.error(`MCP tool ${toolInfo.name} execution failed:`, error);
|
|
249
|
-
throw error;
|
|
250
|
-
}
|
|
251
|
-
},
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
mcpLogger.info(`[AgentEnhancedProvider] Loaded ${Object.keys(mcpTools).length} MCP tools`);
|
|
255
|
-
}
|
|
256
|
-
catch (error) {
|
|
257
|
-
mcpLogger.error("[AgentEnhancedProvider] Failed to load MCP tools:", error);
|
|
258
|
-
}
|
|
259
|
-
return { ...directTools, ...mcpTools };
|
|
260
|
-
}
|
|
261
|
-
/**
|
|
262
|
-
* PRIMARY METHOD: Stream content using AI (recommended for new code)
|
|
263
|
-
* Future-ready for multi-modal capabilities with current text focus
|
|
264
|
-
*/
|
|
265
|
-
async stream(optionsOrPrompt, analysisSchema) {
|
|
266
|
-
const functionTag = "AgentEnhancedProvider.stream";
|
|
267
|
-
const startTime = Date.now();
|
|
268
|
-
// Parse parameters - support both string and options object
|
|
269
|
-
const options = typeof optionsOrPrompt === "string"
|
|
270
|
-
? { input: { text: optionsOrPrompt } }
|
|
271
|
-
: optionsOrPrompt;
|
|
272
|
-
// Validate input
|
|
273
|
-
if (!options?.input?.text ||
|
|
274
|
-
typeof options.input.text !== "string" ||
|
|
275
|
-
options.input.text.trim() === "") {
|
|
276
|
-
throw new Error("Stream options must include input.text as a non-empty string");
|
|
277
|
-
}
|
|
278
|
-
// Convert StreamOptions for internal use
|
|
279
|
-
const convertedOptions = {
|
|
280
|
-
prompt: options.input.text,
|
|
281
|
-
provider: options.provider,
|
|
282
|
-
model: options.model,
|
|
283
|
-
temperature: options.temperature,
|
|
284
|
-
maxTokens: options.maxTokens,
|
|
285
|
-
systemPrompt: options.systemPrompt,
|
|
286
|
-
timeout: options.timeout,
|
|
287
|
-
};
|
|
288
|
-
// Use stream method to get streaming result
|
|
289
|
-
return await this.stream(options);
|
|
290
|
-
}
|
|
291
|
-
async generate(optionsOrPrompt) {
|
|
292
|
-
const startTime = Date.now();
|
|
293
|
-
const options = typeof optionsOrPrompt === "string"
|
|
294
|
-
? { prompt: optionsOrPrompt }
|
|
295
|
-
: optionsOrPrompt;
|
|
296
|
-
const { prompt, temperature = 0.7, maxTokens = 1000, systemPrompt, schema, timeout, } = options;
|
|
297
|
-
// Get combined tools (direct + MCP) if enabled
|
|
298
|
-
const tools = this.config.enableTools ? await this.getCombinedTools() : {};
|
|
299
|
-
const log = (msg, data) => {
|
|
300
|
-
mcpLogger.info(`[AgentEnhancedProvider] ${msg}`, data ? JSON.stringify(data, null, 2) : "");
|
|
301
|
-
};
|
|
302
|
-
log("Starting text generation", {
|
|
303
|
-
prompt: prompt.substring(0, 100),
|
|
304
|
-
toolsCount: Object.keys(tools).length,
|
|
305
|
-
maxSteps: this.config.maxSteps,
|
|
306
|
-
});
|
|
307
|
-
try {
|
|
308
|
-
// Parse timeout if provided
|
|
309
|
-
let abortSignal;
|
|
310
|
-
if (timeout) {
|
|
311
|
-
const timeoutMs = typeof timeout === "string" ? parseTimeout(timeout) : timeout;
|
|
312
|
-
if (timeoutMs !== undefined) {
|
|
313
|
-
abortSignal = AbortSignal.timeout(timeoutMs);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
// The AI SDK with maxSteps automatically handles tool calling and result integration
|
|
317
|
-
const result = await aiGenerate({
|
|
318
|
-
model: this.model,
|
|
319
|
-
prompt: systemPrompt
|
|
320
|
-
? `System: ${systemPrompt}\n\nUser: ${prompt}`
|
|
321
|
-
: prompt,
|
|
322
|
-
tools,
|
|
323
|
-
maxSteps: this.config.maxSteps, // This enables automatic tool calling
|
|
324
|
-
temperature,
|
|
325
|
-
maxTokens,
|
|
326
|
-
toolChoice: this.shouldForceToolUsage(prompt) ? "required" : "auto",
|
|
327
|
-
abortSignal, // Pass abort signal for timeout support
|
|
328
|
-
});
|
|
329
|
-
log("Generation completed", {
|
|
330
|
-
text: result.text?.substring(0, 200),
|
|
331
|
-
finishReason: result.finishReason,
|
|
332
|
-
toolCallsCount: result.toolCalls?.length || 0,
|
|
333
|
-
toolResultsCount: result.toolResults?.length || 0,
|
|
334
|
-
stepsCount: result.steps?.length || 0,
|
|
335
|
-
});
|
|
336
|
-
// Check if tools were called but no final text was generated
|
|
337
|
-
if (result.finishReason === "tool-calls" &&
|
|
338
|
-
!result.text &&
|
|
339
|
-
result.toolResults?.length > 0) {
|
|
340
|
-
log("Tools called but no final text generated, creating summary response");
|
|
341
|
-
try {
|
|
342
|
-
// Extract tool results and create a summary prompt
|
|
343
|
-
let toolResultsSummary = "";
|
|
344
|
-
if (result.toolResults) {
|
|
345
|
-
for (const toolResult of result.toolResults) {
|
|
346
|
-
const resultData = toolResult.result || toolResult;
|
|
347
|
-
// Try to extract meaningful data from the result
|
|
348
|
-
if (typeof resultData === "object" && resultData !== null) {
|
|
349
|
-
if (resultData.success && resultData.items) {
|
|
350
|
-
// This looks like a filesystem listing
|
|
351
|
-
toolResultsSummary += `Directory listing for ${resultData.path}:\n`;
|
|
352
|
-
for (const item of resultData.items) {
|
|
353
|
-
toolResultsSummary += `- ${item.name} (${item.type})\n`;
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
else {
|
|
357
|
-
toolResultsSummary += JSON.stringify(resultData, null, 2);
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
else {
|
|
361
|
-
toolResultsSummary += String(resultData);
|
|
362
|
-
}
|
|
363
|
-
toolResultsSummary += "\n\n";
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
log("Tool results extracted", {
|
|
367
|
-
summaryLength: toolResultsSummary.length,
|
|
368
|
-
preview: toolResultsSummary.substring(0, 200),
|
|
369
|
-
});
|
|
370
|
-
// Create a simple, direct summary
|
|
371
|
-
const finalText = `Based on the user request "${prompt}", here's what I found:\n\n${toolResultsSummary}`;
|
|
372
|
-
log("Final text created", {
|
|
373
|
-
textLength: finalText.length,
|
|
374
|
-
preview: finalText.substring(0, 200),
|
|
375
|
-
});
|
|
376
|
-
// Return result with the formatted text
|
|
377
|
-
return {
|
|
378
|
-
content: finalText,
|
|
379
|
-
provider: this.getProviderName(),
|
|
380
|
-
model: this.getModelName(),
|
|
381
|
-
usage: result.usage
|
|
382
|
-
? {
|
|
383
|
-
inputTokens: result.usage.promptTokens,
|
|
384
|
-
outputTokens: result.usage.completionTokens,
|
|
385
|
-
totalTokens: result.usage.totalTokens,
|
|
386
|
-
}
|
|
387
|
-
: undefined,
|
|
388
|
-
responseTime: 0,
|
|
389
|
-
toolsUsed: [],
|
|
390
|
-
toolExecutions: [],
|
|
391
|
-
enhancedWithTools: false,
|
|
392
|
-
availableTools: [],
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
catch (error) {
|
|
396
|
-
log("Error in summary generation", {
|
|
397
|
-
error: error instanceof Error ? error.message : String(error),
|
|
398
|
-
});
|
|
399
|
-
// Fallback: return raw tool results
|
|
400
|
-
const fallbackText = `Tool execution completed. Raw results: ${JSON.stringify(result.toolResults, null, 2)}`;
|
|
401
|
-
return {
|
|
402
|
-
content: fallbackText,
|
|
403
|
-
provider: this.getProviderName(),
|
|
404
|
-
model: this.getModelName(),
|
|
405
|
-
usage: result.usage
|
|
406
|
-
? {
|
|
407
|
-
inputTokens: result.usage.promptTokens,
|
|
408
|
-
outputTokens: result.usage.completionTokens,
|
|
409
|
-
totalTokens: result.usage.totalTokens,
|
|
410
|
-
}
|
|
411
|
-
: undefined,
|
|
412
|
-
responseTime: 0,
|
|
413
|
-
toolsUsed: [],
|
|
414
|
-
toolExecutions: [],
|
|
415
|
-
enhancedWithTools: false,
|
|
416
|
-
availableTools: [],
|
|
417
|
-
};
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
// Add analytics if enabled
|
|
421
|
-
if (options.enableAnalytics) {
|
|
422
|
-
result.analytics = createAnalytics(this.config.provider, this.resolvedModelName, result, Date.now() - startTime, options.context);
|
|
423
|
-
}
|
|
424
|
-
// Add evaluation if enabled
|
|
425
|
-
if (options.enableEvaluation) {
|
|
426
|
-
result.evaluation = await evaluateResponse(prompt, result.text, options.context);
|
|
427
|
-
}
|
|
428
|
-
// Return the full result - the AI SDK has already handled tool execution and integration
|
|
429
|
-
return {
|
|
430
|
-
content: result.text,
|
|
431
|
-
provider: this.getProviderName(),
|
|
432
|
-
model: this.getModelName(),
|
|
433
|
-
usage: result.usage
|
|
434
|
-
? {
|
|
435
|
-
inputTokens: result.usage.promptTokens,
|
|
436
|
-
outputTokens: result.usage.completionTokens,
|
|
437
|
-
totalTokens: result.usage.totalTokens,
|
|
438
|
-
}
|
|
439
|
-
: undefined,
|
|
440
|
-
responseTime: 0,
|
|
441
|
-
toolsUsed: [],
|
|
442
|
-
toolExecutions: [],
|
|
443
|
-
enhancedWithTools: false,
|
|
444
|
-
availableTools: [],
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
catch (error) {
|
|
448
|
-
console.error("[AgentEnhancedProvider] generate error:", error);
|
|
449
|
-
throw error;
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
/**
|
|
453
|
-
* Determine if we should force tool usage based on prompt patterns
|
|
454
|
-
*/
|
|
455
|
-
shouldForceToolUsage(prompt) {
|
|
456
|
-
const forceToolPatterns = [
|
|
457
|
-
/what time is it/i,
|
|
458
|
-
/current time/i,
|
|
459
|
-
/list files/i,
|
|
460
|
-
/read file/i,
|
|
461
|
-
/directory/i,
|
|
462
|
-
/calculate/i,
|
|
463
|
-
/math/i,
|
|
464
|
-
/search for/i,
|
|
465
|
-
/find files/i,
|
|
466
|
-
];
|
|
467
|
-
return forceToolPatterns.some((pattern) => pattern.test(prompt));
|
|
468
|
-
}
|
|
469
|
-
getCapabilities() {
|
|
470
|
-
return [
|
|
471
|
-
"text-generation",
|
|
472
|
-
"streaming",
|
|
473
|
-
"tool-calling",
|
|
474
|
-
"agent-functionality",
|
|
475
|
-
];
|
|
476
|
-
}
|
|
477
|
-
getProviderName() {
|
|
478
|
-
return `agent-${this.config.provider}`;
|
|
479
|
-
}
|
|
480
|
-
getModelName() {
|
|
481
|
-
return this.config.model || `default-${this.config.provider}-model`;
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* Test agent functionality
|
|
485
|
-
*/
|
|
486
|
-
async testAgentCapabilities() {
|
|
487
|
-
const testPrompts = [
|
|
488
|
-
"What time is it right now?",
|
|
489
|
-
"List files in current directory",
|
|
490
|
-
"Calculate 15 * 7",
|
|
491
|
-
"What is the square root of 144?",
|
|
492
|
-
];
|
|
493
|
-
const results = [];
|
|
494
|
-
let successCount = 0;
|
|
495
|
-
for (const prompt of testPrompts) {
|
|
496
|
-
try {
|
|
497
|
-
logger.debug(`Testing: "${prompt}"`);
|
|
498
|
-
const result = await this.generate(prompt);
|
|
499
|
-
if (!result) {
|
|
500
|
-
results.push({
|
|
501
|
-
prompt,
|
|
502
|
-
success: false,
|
|
503
|
-
error: "No result returned from generate",
|
|
504
|
-
});
|
|
505
|
-
logger.warn(`❌ No result returned`);
|
|
506
|
-
continue;
|
|
507
|
-
}
|
|
508
|
-
const toolsCalled = result.toolCalls?.length || 0;
|
|
509
|
-
const success = toolsCalled > 0;
|
|
510
|
-
if (success) {
|
|
511
|
-
successCount++;
|
|
512
|
-
}
|
|
513
|
-
results.push({
|
|
514
|
-
prompt,
|
|
515
|
-
success,
|
|
516
|
-
toolsCalled,
|
|
517
|
-
response: result.content.substring(0, 100) + "...",
|
|
518
|
-
});
|
|
519
|
-
logger.debug(`✅ Tools called: ${toolsCalled}, Response: ${result.content.substring(0, 50)}...`);
|
|
520
|
-
}
|
|
521
|
-
catch (error) {
|
|
522
|
-
results.push({
|
|
523
|
-
prompt,
|
|
524
|
-
success: false,
|
|
525
|
-
error: error instanceof Error ? error.message : String(error),
|
|
526
|
-
});
|
|
527
|
-
logger.error(`❌ Error: ${error}`);
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
return {
|
|
531
|
-
success: successCount > 0,
|
|
532
|
-
results,
|
|
533
|
-
};
|
|
534
|
-
}
|
|
535
|
-
/**
|
|
536
|
-
* Create agent-enhanced provider factory
|
|
537
|
-
*/
|
|
538
|
-
static createAgent(config) {
|
|
539
|
-
return new AgentEnhancedProvider(config);
|
|
540
|
-
}
|
|
541
|
-
/**
|
|
542
|
-
* Create multiple agent providers for comparison
|
|
543
|
-
*/
|
|
544
|
-
static createMultiProviderAgents() {
|
|
545
|
-
const providers = {};
|
|
546
|
-
// Only create providers that have API keys configured
|
|
547
|
-
if (process.env.GOOGLE_AI_API_KEY) {
|
|
548
|
-
providers["google-ai"] = new AgentEnhancedProvider({
|
|
549
|
-
provider: "google-ai",
|
|
550
|
-
});
|
|
551
|
-
}
|
|
552
|
-
if (process.env.OPENAI_API_KEY) {
|
|
553
|
-
providers["openai"] = new AgentEnhancedProvider({ provider: "openai" });
|
|
554
|
-
}
|
|
555
|
-
if (process.env.ANTHROPIC_API_KEY) {
|
|
556
|
-
providers["anthropic"] = new AgentEnhancedProvider({
|
|
557
|
-
provider: "anthropic",
|
|
558
|
-
});
|
|
559
|
-
}
|
|
560
|
-
return providers;
|
|
561
|
-
}
|
|
562
|
-
/**
|
|
563
|
-
* Alias for generate() - CLI-SDK consistency
|
|
564
|
-
*/
|
|
565
|
-
/**
|
|
566
|
-
* Short alias for generate() - CLI-SDK consistency
|
|
567
|
-
*/
|
|
568
|
-
async gen(optionsOrPrompt, analysisSchema) {
|
|
569
|
-
return this.generate(optionsOrPrompt);
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
/**
|
|
573
|
-
* Helper function to create agent provider
|
|
574
|
-
*/
|
|
575
|
-
export function createAgentProvider(provider, options) {
|
|
576
|
-
return new AgentEnhancedProvider({
|
|
577
|
-
provider,
|
|
578
|
-
...options,
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
|
-
/**
|
|
582
|
-
* Test all available agent providers
|
|
583
|
-
*/
|
|
584
|
-
export async function testAllAgentProviders() {
|
|
585
|
-
logger.info("🧪 Testing All Agent Providers\n");
|
|
586
|
-
const providers = AgentEnhancedProvider.createMultiProviderAgents();
|
|
587
|
-
if (Object.keys(providers).length === 0) {
|
|
588
|
-
logger.warn("❌ No API keys found. Please configure at least one provider.");
|
|
589
|
-
return;
|
|
590
|
-
}
|
|
591
|
-
for (const [name, provider] of Object.entries(providers)) {
|
|
592
|
-
logger.info(`\n🔬 Testing ${name.toUpperCase()} Agent Provider:`);
|
|
593
|
-
try {
|
|
594
|
-
const testResult = await provider.testAgentCapabilities();
|
|
595
|
-
if (testResult.success) {
|
|
596
|
-
logger.info(`✅ ${name} agent provider working correctly`);
|
|
597
|
-
}
|
|
598
|
-
else {
|
|
599
|
-
logger.warn(`❌ ${name} agent provider failed tests`);
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
catch (error) {
|
|
603
|
-
logger.error(`❌ ${name} provider error:`, error);
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import type { ZodType, ZodTypeDef } from "zod";
|
|
2
|
-
import { type Schema } from "ai";
|
|
3
|
-
import type { GenerateResult } from "../types/generate-types.js";
|
|
4
|
-
import type { StreamOptions, StreamResult } from "../types/stream-types.js";
|
|
5
|
-
import type { AIProvider, TextGenerationOptions, EnhancedGenerateResult } from "../core/types.js";
|
|
6
|
-
export declare class AmazonBedrock implements AIProvider {
|
|
7
|
-
private modelName;
|
|
8
|
-
private model;
|
|
9
|
-
private bedrock;
|
|
10
|
-
constructor(modelName?: string | null);
|
|
11
|
-
/**
|
|
12
|
-
* LEGACY METHOD: Use stream() instead for new code
|
|
13
|
-
* @deprecated Use stream() method instead
|
|
14
|
-
*/
|
|
15
|
-
/**
|
|
16
|
-
* PRIMARY METHOD: Stream content using AI (recommended for new code)
|
|
17
|
-
* Future-ready for multi-modal capabilities with current text focus
|
|
18
|
-
*/
|
|
19
|
-
stream(optionsOrPrompt: StreamOptions | string, analysisSchema?: ZodType<unknown, ZodTypeDef, unknown> | Schema<unknown>): Promise<StreamResult>;
|
|
20
|
-
generate(optionsOrPrompt: TextGenerationOptions | string, analysisSchema?: ZodType<unknown, ZodTypeDef, unknown> | Schema<unknown>): Promise<GenerateResult>;
|
|
21
|
-
/**
|
|
22
|
-
* Alias for generate() - CLI-SDK consistency
|
|
23
|
-
*/
|
|
24
|
-
/**
|
|
25
|
-
* Short alias for generate() - CLI-SDK consistency
|
|
26
|
-
*/
|
|
27
|
-
gen(optionsOrPrompt: TextGenerationOptions | string, analysisSchema?: ZodType<unknown, ZodTypeDef, unknown> | Schema<unknown>): Promise<EnhancedGenerateResult | null>;
|
|
28
|
-
}
|