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