tachibot-mcp 2.0.2

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 (214) hide show
  1. package/.env.example +260 -0
  2. package/CHANGELOG.md +54 -0
  3. package/CODE_OF_CONDUCT.md +56 -0
  4. package/CONTRIBUTING.md +54 -0
  5. package/Dockerfile +36 -0
  6. package/LICENSE +644 -0
  7. package/README.md +201 -0
  8. package/SECURITY.md +95 -0
  9. package/dist/personality/komaai-expressions.js +12 -0
  10. package/dist/profiles/balanced.json +33 -0
  11. package/dist/profiles/code_focus.json +33 -0
  12. package/dist/profiles/full.json +33 -0
  13. package/dist/profiles/minimal.json +33 -0
  14. package/dist/profiles/research_power.json +33 -0
  15. package/dist/scripts/build-profiles.js +46 -0
  16. package/dist/src/application/services/focus/FocusModeRegistry.js +46 -0
  17. package/dist/src/application/services/focus/FocusTool.service.js +109 -0
  18. package/dist/src/application/services/focus/ModeRegistry.js +46 -0
  19. package/dist/src/application/services/focus/modes/focus-deep.mode.js +27 -0
  20. package/dist/src/application/services/focus/modes/status.mode.js +50 -0
  21. package/dist/src/application/services/focus/modes/tachibot-status.mode.js +50 -0
  22. package/dist/src/collaborative-orchestrator.js +391 -0
  23. package/dist/src/config/model-constants.js +188 -0
  24. package/dist/src/config/model-defaults.js +57 -0
  25. package/dist/src/config/model-preferences.js +382 -0
  26. package/dist/src/config/timeout-config.js +130 -0
  27. package/dist/src/config.js +173 -0
  28. package/dist/src/domain/interfaces/IFocusMode.js +5 -0
  29. package/dist/src/domain/interfaces/IProvider.js +6 -0
  30. package/dist/src/domain/interfaces/ITool.js +5 -0
  31. package/dist/src/focus-deep.js +245 -0
  32. package/dist/src/infrastructure/ascii/art/robots.ascii.js +16 -0
  33. package/dist/src/mcp-client.js +90 -0
  34. package/dist/src/memory/index.js +17 -0
  35. package/dist/src/memory/memory-config.js +135 -0
  36. package/dist/src/memory/memory-interface.js +174 -0
  37. package/dist/src/memory/memory-manager.js +383 -0
  38. package/dist/src/memory/providers/devlog-provider.js +385 -0
  39. package/dist/src/memory/providers/hybrid-provider.js +399 -0
  40. package/dist/src/memory/providers/local-provider.js +388 -0
  41. package/dist/src/memory/providers/mem0-provider.js +337 -0
  42. package/dist/src/modes/architect.js +477 -0
  43. package/dist/src/modes/auditor.js +362 -0
  44. package/dist/src/modes/challenger.js +841 -0
  45. package/dist/src/modes/code-reviewer.js +382 -0
  46. package/dist/src/modes/commit-guardian.js +424 -0
  47. package/dist/src/modes/documentation-writer.js +572 -0
  48. package/dist/src/modes/scout.js +587 -0
  49. package/dist/src/modes/shared/helpers/challenger-helpers.js +454 -0
  50. package/dist/src/modes/shared/helpers/index.js +17 -0
  51. package/dist/src/modes/shared/helpers/scout-helpers.js +270 -0
  52. package/dist/src/modes/shared/helpers/verifier-helpers.js +332 -0
  53. package/dist/src/modes/test-architect.js +767 -0
  54. package/dist/src/modes/verifier.js +378 -0
  55. package/dist/src/monitoring/performance-monitor.js +435 -0
  56. package/dist/src/optimization/batch-executor.js +121 -0
  57. package/dist/src/optimization/context-pruner.js +196 -0
  58. package/dist/src/optimization/cost-monitor.js +338 -0
  59. package/dist/src/optimization/index.js +65 -0
  60. package/dist/src/optimization/model-router.js +264 -0
  61. package/dist/src/optimization/result-cache.js +114 -0
  62. package/dist/src/optimization/token-optimizer.js +257 -0
  63. package/dist/src/optimization/token-tracker.js +118 -0
  64. package/dist/src/orchestrator-instructions.js +128 -0
  65. package/dist/src/orchestrator-lite.js +139 -0
  66. package/dist/src/orchestrator.js +191 -0
  67. package/dist/src/orchestrators/collaborative/interfaces/IToolExecutionEngine.js +1 -0
  68. package/dist/src/orchestrators/collaborative/interfaces/IToolExecutionStrategy.js +5 -0
  69. package/dist/src/orchestrators/collaborative/interfaces/IVisualizationRenderer.js +1 -0
  70. package/dist/src/orchestrators/collaborative/registries/ModelProviderRegistry.js +95 -0
  71. package/dist/src/orchestrators/collaborative/registries/ToolAdapterRegistry.js +64 -0
  72. package/dist/src/orchestrators/collaborative/services/tool-execution/ToolExecutionService.js +502 -0
  73. package/dist/src/orchestrators/collaborative/services/visualization/VisualizationService.js +206 -0
  74. package/dist/src/orchestrators/collaborative/types/session-types.js +5 -0
  75. package/dist/src/profiles/balanced.js +37 -0
  76. package/dist/src/profiles/code_focus.js +37 -0
  77. package/dist/src/profiles/debug_intensive.js +59 -0
  78. package/dist/src/profiles/full.js +37 -0
  79. package/dist/src/profiles/minimal.js +37 -0
  80. package/dist/src/profiles/research_code.js +59 -0
  81. package/dist/src/profiles/research_power.js +37 -0
  82. package/dist/src/profiles/types.js +5 -0
  83. package/dist/src/profiles/workflow_builder.js +53 -0
  84. package/dist/src/prompt-engineer-lite.js +78 -0
  85. package/dist/src/prompt-engineer.js +399 -0
  86. package/dist/src/reasoning-chain.js +508 -0
  87. package/dist/src/sequential-thinking.js +291 -0
  88. package/dist/src/server-diagnostic.js +74 -0
  89. package/dist/src/server-raw.js +158 -0
  90. package/dist/src/server-simple.js +58 -0
  91. package/dist/src/server.js +514 -0
  92. package/dist/src/session/session-logger.js +617 -0
  93. package/dist/src/session/session-manager.js +571 -0
  94. package/dist/src/session/session-tools.js +400 -0
  95. package/dist/src/tools/advanced-modes.js +200 -0
  96. package/dist/src/tools/claude-integration.js +356 -0
  97. package/dist/src/tools/consolidated/ai-router.js +174 -0
  98. package/dist/src/tools/consolidated/ai-tool.js +48 -0
  99. package/dist/src/tools/consolidated/brainstorm-tool.js +87 -0
  100. package/dist/src/tools/consolidated/environment-detector.js +80 -0
  101. package/dist/src/tools/consolidated/index.js +50 -0
  102. package/dist/src/tools/consolidated/search-tool.js +110 -0
  103. package/dist/src/tools/consolidated/workflow-tool.js +238 -0
  104. package/dist/src/tools/gemini-tools.js +329 -0
  105. package/dist/src/tools/grok-enhanced.js +376 -0
  106. package/dist/src/tools/grok-tools.js +299 -0
  107. package/dist/src/tools/lmstudio-tools.js +223 -0
  108. package/dist/src/tools/openai-tools.js +498 -0
  109. package/dist/src/tools/openrouter-tools.js +317 -0
  110. package/dist/src/tools/optimized-wrapper.js +204 -0
  111. package/dist/src/tools/perplexity-tools.js +294 -0
  112. package/dist/src/tools/pingpong-tool.js +343 -0
  113. package/dist/src/tools/qwen-wrapper.js +74 -0
  114. package/dist/src/tools/tool-router.js +444 -0
  115. package/dist/src/tools/unified-ai-provider.js +260 -0
  116. package/dist/src/tools/workflow-runner.js +425 -0
  117. package/dist/src/tools/workflow-validator-tool.js +107 -0
  118. package/dist/src/types.js +23 -0
  119. package/dist/src/utils/input-validator.js +130 -0
  120. package/dist/src/utils/model-router.js +91 -0
  121. package/dist/src/utils/progress-stream.js +255 -0
  122. package/dist/src/utils/provider-router.js +88 -0
  123. package/dist/src/utils/smart-api-client.js +146 -0
  124. package/dist/src/utils/table-builder.js +218 -0
  125. package/dist/src/utils/timestamp-formatter.js +134 -0
  126. package/dist/src/utils/tool-compressor.js +257 -0
  127. package/dist/src/utils/tool-config.js +201 -0
  128. package/dist/src/validators/dependency-graph-validator.js +147 -0
  129. package/dist/src/validators/interpolation-validator.js +222 -0
  130. package/dist/src/validators/output-usage-validator.js +151 -0
  131. package/dist/src/validators/syntax-validator.js +102 -0
  132. package/dist/src/validators/tool-registry-validator.js +123 -0
  133. package/dist/src/validators/tool-types.js +97 -0
  134. package/dist/src/validators/types.js +8 -0
  135. package/dist/src/validators/workflow-validator.js +134 -0
  136. package/dist/src/visualizer-lite.js +42 -0
  137. package/dist/src/visualizer.js +179 -0
  138. package/dist/src/workflows/circuit-breaker.js +199 -0
  139. package/dist/src/workflows/custom-workflows.js +451 -0
  140. package/dist/src/workflows/engine/AutoSynthesizer.js +97 -0
  141. package/dist/src/workflows/engine/StepParameterResolver.js +74 -0
  142. package/dist/src/workflows/engine/VariableInterpolator.js +123 -0
  143. package/dist/src/workflows/engine/WorkflowDiscovery.js +125 -0
  144. package/dist/src/workflows/engine/WorkflowExecutionEngine.js +485 -0
  145. package/dist/src/workflows/engine/WorkflowExecutor.js +113 -0
  146. package/dist/src/workflows/engine/WorkflowFileManager.js +244 -0
  147. package/dist/src/workflows/engine/WorkflowHelpers.js +114 -0
  148. package/dist/src/workflows/engine/WorkflowOutputFormatter.js +83 -0
  149. package/dist/src/workflows/engine/events/WorkflowEventBus.js +132 -0
  150. package/dist/src/workflows/engine/events/interfaces/IEventBus.js +5 -0
  151. package/dist/src/workflows/engine/handlers/ErrorRecoveryHandler.js +162 -0
  152. package/dist/src/workflows/engine/handlers/PromptEnhancementHandler.js +115 -0
  153. package/dist/src/workflows/engine/handlers/SessionPersistenceHandler.js +167 -0
  154. package/dist/src/workflows/engine/handlers/StepExecutionHandler.js +231 -0
  155. package/dist/src/workflows/engine/handlers/ToolInvocationHandler.js +46 -0
  156. package/dist/src/workflows/engine/interfaces/IAutoSynthesizer.js +5 -0
  157. package/dist/src/workflows/engine/interfaces/IStepParameterResolver.js +5 -0
  158. package/dist/src/workflows/engine/interfaces/IVariableInterpolator.js +5 -0
  159. package/dist/src/workflows/engine/interfaces/IWorkflowDiscovery.js +4 -0
  160. package/dist/src/workflows/engine/interfaces/IWorkflowFileManager.js +5 -0
  161. package/dist/src/workflows/engine/interfaces/IWorkflowOutputFormatter.js +5 -0
  162. package/dist/src/workflows/engine/state/WorkflowStateMachine.js +194 -0
  163. package/dist/src/workflows/engine/state/interfaces/IStateMachine.js +17 -0
  164. package/dist/src/workflows/fallback-strategies.js +373 -0
  165. package/dist/src/workflows/message-queue.js +455 -0
  166. package/dist/src/workflows/model-router.js +189 -0
  167. package/dist/src/workflows/orchestrator-examples.js +174 -0
  168. package/dist/src/workflows/orchestrator-integration.js +200 -0
  169. package/dist/src/workflows/self-healing.js +524 -0
  170. package/dist/src/workflows/tool-mapper.js +407 -0
  171. package/dist/src/workflows/tool-orchestrator.js +796 -0
  172. package/dist/src/workflows/workflow-engine.js +573 -0
  173. package/dist/src/workflows/workflow-parser.js +283 -0
  174. package/dist/src/workflows/workflow-types.js +95 -0
  175. package/dist/src/workflows.js +568 -0
  176. package/dist/test-workflow-file-output.js +93 -0
  177. package/docs/API_KEYS.md +570 -0
  178. package/docs/CLAUDE_CODE_SETUP.md +181 -0
  179. package/docs/CLAUDE_DESKTOP_MANUAL.md +127 -0
  180. package/docs/CONFIGURATION.md +745 -0
  181. package/docs/FOCUS_MODES.md +240 -0
  182. package/docs/INSTALLATION_BOTH.md +145 -0
  183. package/docs/TERMS.md +352 -0
  184. package/docs/TOOLS_REFERENCE.md +1622 -0
  185. package/docs/TOOL_PARAMETERS.md +496 -0
  186. package/docs/TOOL_PROFILES.md +236 -0
  187. package/docs/WORKFLOWS.md +987 -0
  188. package/docs/WORKFLOW_OUTPUT.md +198 -0
  189. package/docs/WORKFLOW_PROGRESS_TRACKING.md +305 -0
  190. package/docs/workflows/design-brainstorm.md +335 -0
  191. package/package.json +97 -0
  192. package/profiles/balanced.json +37 -0
  193. package/profiles/code_focus.json +37 -0
  194. package/profiles/debug_intensive.json +34 -0
  195. package/profiles/full.json +37 -0
  196. package/profiles/minimal.json +37 -0
  197. package/profiles/research_power.json +37 -0
  198. package/profiles/workflow_builder.json +37 -0
  199. package/smithery.yaml +66 -0
  200. package/start.sh +8 -0
  201. package/tools.config.json +81 -0
  202. package/tsconfig.json +18 -0
  203. package/workflows/accessibility-code-audit.yaml +92 -0
  204. package/workflows/code-architecture-review.yaml +202 -0
  205. package/workflows/code-review.yaml +142 -0
  206. package/workflows/core/iterative-problem-solver.yaml +283 -0
  207. package/workflows/creative-brainstorm-yaml.yaml +215 -0
  208. package/workflows/pingpong.yaml +141 -0
  209. package/workflows/system/README.md +412 -0
  210. package/workflows/system/challenger.yaml +175 -0
  211. package/workflows/system/scout.yaml +164 -0
  212. package/workflows/system/verifier.yaml +133 -0
  213. package/workflows/ultra-creative-brainstorm.yaml +318 -0
  214. package/workflows/ux-research-flow.yaml +92 -0
@@ -0,0 +1,376 @@
1
+ /**
2
+ * Enhanced Grok Tools with Live Search and Heavy Mode Support
3
+ * Implements Grok-4 with proper model names and live search capability
4
+ */
5
+ import { z } from "zod";
6
+ import { config } from "dotenv";
7
+ import * as path from 'path';
8
+ import { fileURLToPath } from 'url';
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+ config({ path: path.resolve(__dirname, '../../../.env') });
12
+ // Grok API configuration
13
+ const GROK_API_KEY = process.env.GROK_API_KEY || process.env.XAI_API_KEY;
14
+ const GROK_API_URL = "https://api.x.ai/v1/chat/completions";
15
+ // Grok models - Updated 2025-11-07 with new fast models
16
+ export var GrokModel;
17
+ (function (GrokModel) {
18
+ // New fast models (2025) - PRIMARY USE
19
+ GrokModel["CODE_FAST"] = "grok-code-fast-1";
20
+ GrokModel["GROK_4_FAST_REASONING"] = "grok-4-fast-reasoning";
21
+ GrokModel["GROK_4_FAST"] = "grok-4-fast-non-reasoning";
22
+ // Expensive/specialized (use sparingly)
23
+ GrokModel["GROK_4_HEAVY"] = "grok-4-0709";
24
+ GrokModel["GROK_3"] = "grok-3";
25
+ // Beta/experimental (deprecated)
26
+ GrokModel["GROK_BETA"] = "grok-beta";
27
+ GrokModel["GROK_VISION_BETA"] = "grok-vision-beta";
28
+ })(GrokModel || (GrokModel = {}));
29
+ /**
30
+ * Enhanced Grok API call with live search support
31
+ */
32
+ export async function callGrokEnhanced(messages, options = {}) {
33
+ if (!GROK_API_KEY) {
34
+ return {
35
+ content: `[Grok API key not configured. Add GROK_API_KEY or XAI_API_KEY to .env file]`
36
+ };
37
+ }
38
+ const { model = GrokModel.GROK_4_FAST_REASONING, // Changed: Use cheap fast reasoning by default
39
+ temperature = 0.7, maxTokens = options.useHeavy ? 100000 : 4000, enableLiveSearch = false, searchSources = 100, // Default to 100 sources for cost control
40
+ searchDomains = [], structuredOutput = false } = options;
41
+ try {
42
+ const requestBody = {
43
+ model,
44
+ messages,
45
+ temperature,
46
+ max_tokens: maxTokens,
47
+ stream: false
48
+ };
49
+ // Add live search configuration if enabled (following official xAI docs exactly)
50
+ if (enableLiveSearch) {
51
+ // Only use search_parameters as documented - NO tools array
52
+ requestBody.search_parameters = {
53
+ mode: "on", // Force search on
54
+ max_search_results: searchSources || 20,
55
+ return_citations: true
56
+ };
57
+ // Add sources if specific domains requested
58
+ if (searchDomains && searchDomains.length > 0) {
59
+ requestBody.search_parameters.sources = [{
60
+ type: "web",
61
+ allowed_websites: searchDomains.slice(0, 5) // Max 5 websites
62
+ }];
63
+ }
64
+ // If no specific domains, sources will default to web, news, and x
65
+ }
66
+ // Enable structured output if requested
67
+ if (structuredOutput) {
68
+ requestBody.response_format = { type: "json_object" };
69
+ }
70
+ // Heavy mode would be handled by subscription/tier, not headers in body
71
+ // Removed incorrect header addition to request body
72
+ // Debug logging for search requests
73
+ if (enableLiveSearch) {
74
+ console.error('[Grok Search Debug] Model:', model);
75
+ console.error('[Grok Search Debug] Request body:', JSON.stringify(requestBody, null, 2));
76
+ console.error('[Grok Search Debug] API URL:', GROK_API_URL);
77
+ }
78
+ const response = await fetch(GROK_API_URL, {
79
+ method: "POST",
80
+ headers: {
81
+ "Authorization": `Bearer ${GROK_API_KEY}`,
82
+ "Content-Type": "application/json",
83
+ // Add heavy mode header here if needed
84
+ ...(options.useHeavy ? { 'X-Grok-Mode': 'heavy' } : {})
85
+ },
86
+ body: JSON.stringify(requestBody)
87
+ });
88
+ if (!response.ok) {
89
+ const error = await response.text();
90
+ throw new Error(`Grok API error: ${response.statusText} - ${error}`);
91
+ }
92
+ const data = await response.json();
93
+ const content = data.choices?.[0]?.message?.content || "No response from Grok";
94
+ // Extract sources if live search was used
95
+ const sources = data.choices?.[0]?.message?.sources || [];
96
+ return {
97
+ content,
98
+ sources,
99
+ usage: data.usage // Include token and cost information
100
+ };
101
+ }
102
+ catch (error) {
103
+ return {
104
+ content: `[Grok error: ${error instanceof Error ? error.message : String(error)}]`
105
+ };
106
+ }
107
+ }
108
+ /**
109
+ * Enhanced Scout Tool with Grok-4 Live Search
110
+ * Quick research with real-time web data
111
+ */
112
+ export const grokScoutTool = {
113
+ name: "grok_scout",
114
+ description: "Quick research",
115
+ parameters: z.object({
116
+ query: z.string(),
117
+ enableLiveSearch: z.boolean().optional(),
118
+ searchSources: z.number().optional(),
119
+ searchDomains: z.array(z.string()).optional(),
120
+ variant: z.enum(["quick", "deep", "technical", "academic"]).optional()
121
+ }),
122
+ execute: async (args, { log }) => {
123
+ const { query, enableLiveSearch = true, searchSources = 50, searchDomains, variant = "quick" } = args;
124
+ const variantPrompts = {
125
+ quick: "Provide a quick, concise overview with key facts",
126
+ deep: "Conduct thorough research with multiple perspectives",
127
+ technical: "Focus on technical details and implementation aspects",
128
+ academic: "Provide scholarly analysis with citations"
129
+ };
130
+ const messages = [
131
+ {
132
+ role: "system",
133
+ content: `You are Grok in research mode with live search capability.
134
+ ${variantPrompts[variant]}.
135
+ Use live search to find the most current and relevant information.
136
+ Cite your sources when using web data.`
137
+ },
138
+ {
139
+ role: "user",
140
+ content: query
141
+ }
142
+ ];
143
+ log?.info(`Grok Scout: ${variant} research with ${enableLiveSearch ? 'live search' : 'knowledge base'} (using ${enableLiveSearch ? 'grok-4-fast-reasoning with search' : 'grok-4-fast-reasoning'})`);
144
+ const result = await callGrokEnhanced(messages, {
145
+ model: GrokModel.GROK_4_FAST_REASONING, // Changed: Use fast reasoning (works with search)
146
+ enableLiveSearch,
147
+ searchSources,
148
+ searchDomains,
149
+ temperature: 0.5, // Lower temperature for factual research
150
+ maxTokens: 5000
151
+ });
152
+ // Format response with sources
153
+ if (result.sources && result.sources.length > 0) {
154
+ const sourcesText = result.sources
155
+ .slice(0, 5) // Limit to top 5 sources
156
+ .map((s, i) => `[${i + 1}] ${s.title || s.url}`)
157
+ .join('\n');
158
+ return `${result.content}\n\n**Sources:**\n${sourcesText}`;
159
+ }
160
+ return result.content;
161
+ }
162
+ };
163
+ /**
164
+ * Enhanced Reasoning Tool with configurable Heavy mode
165
+ */
166
+ export const grokReasonEnhanced = {
167
+ name: "grok_reason_v4",
168
+ description: "Deep reasoning",
169
+ parameters: z.object({
170
+ problem: z.string(),
171
+ approach: z.enum(["analytical", "creative", "systematic", "first-principles", "multi-agent"]).optional(),
172
+ context: z.string().optional(),
173
+ useHeavy: z.boolean().optional(),
174
+ enableLiveSearch: z.boolean().optional(),
175
+ maxSteps: z.number().optional()
176
+ }),
177
+ execute: async (args, { log }) => {
178
+ const { problem, approach = "first-principles", context, useHeavy = false, enableLiveSearch = false, maxSteps = 5 } = args;
179
+ const approachPrompts = {
180
+ analytical: "Break down the problem systematically and analyze each component",
181
+ creative: "Think outside the box and consider unconventional solutions",
182
+ systematic: "Follow a step-by-step logical process",
183
+ "first-principles": "Break down to fundamental truths and build up from there",
184
+ "multi-agent": "Consider multiple perspectives and synthesize them"
185
+ };
186
+ const messages = [
187
+ {
188
+ role: "system",
189
+ content: `You are Grok-4 in ${useHeavy ? 'Heavy' : 'Standard'} reasoning mode.
190
+ ${approachPrompts[approach]}.
191
+ ${context ? `Context: ${context}` : ''}
192
+ Maximum reasoning steps: ${maxSteps}
193
+ ${enableLiveSearch ? 'Use live search for current information when needed.' : ''}`
194
+ },
195
+ {
196
+ role: "user",
197
+ content: problem
198
+ }
199
+ ];
200
+ const modelName = useHeavy ? 'Grok-4-Heavy' : 'Grok-4-Fast-Reasoning';
201
+ const costInfo = useHeavy ? '$3/$15 (expensive!)' : '$0.20/$0.50 (cheap!)';
202
+ log?.info(`Using ${modelName} (${approach}) with ${enableLiveSearch ? 'live search' : 'knowledge base'} - Cost: ${costInfo}`);
203
+ const result = await callGrokEnhanced(messages, {
204
+ model: useHeavy ? GrokModel.GROK_4_HEAVY : GrokModel.GROK_4_FAST_REASONING, // Changed: Use fast reasoning unless heavy requested
205
+ useHeavy,
206
+ enableLiveSearch,
207
+ searchSources: 50,
208
+ temperature: 0.7,
209
+ maxTokens: useHeavy ? 100000 : 10000
210
+ });
211
+ // Add usage info if Heavy mode
212
+ if (useHeavy && result.usage) {
213
+ const costEstimate = (result.usage.total_tokens / 1000) * 0.015; // Rough estimate
214
+ return `${result.content}\n\n---\n*Heavy mode used: ${result.usage.total_tokens} tokens (~$${costEstimate.toFixed(3)})*`;
215
+ }
216
+ return result.content;
217
+ }
218
+ };
219
+ /**
220
+ * Function Calling Tool - demonstrates Grok-4's function calling capability
221
+ */
222
+ export const grokFunctionTool = {
223
+ name: "grok_function",
224
+ description: "Use Grok-4's function calling to integrate with external tools",
225
+ parameters: z.object({
226
+ task: z.string(),
227
+ availableFunctions: z.array(z.object({
228
+ name: z.string(),
229
+ description: z.string(),
230
+ parameters: z.any()
231
+ })),
232
+ useHeavy: z.boolean().optional().default(false)
233
+ }),
234
+ execute: async (args, { log }) => {
235
+ // Convert to OpenAI-compatible tool format
236
+ const tools = args.availableFunctions.map((fn) => ({
237
+ type: "function",
238
+ function: {
239
+ name: fn.name,
240
+ description: fn.description,
241
+ parameters: fn.parameters
242
+ }
243
+ }));
244
+ const messages = [
245
+ {
246
+ role: "system",
247
+ content: "You are Grok-4 with function calling capability. Use the provided functions to complete the task."
248
+ },
249
+ {
250
+ role: "user",
251
+ content: args.task
252
+ }
253
+ ];
254
+ // Make request with tools
255
+ const requestBody = {
256
+ model: args.useHeavy ? GrokModel.GROK_4_HEAVY : GrokModel.GROK_4_FAST_REASONING, // Changed: Use fast reasoning unless heavy requested
257
+ messages,
258
+ tools,
259
+ tool_choice: "auto", // Let Grok decide when to call functions
260
+ max_tokens: args.useHeavy ? 50000 : 5000,
261
+ temperature: 0.3 // Lower for function calling
262
+ };
263
+ log?.info(`Function calling with ${args.useHeavy ? 'Grok-4-Heavy ($3/$15)' : 'Grok-4-Fast-Reasoning ($0.20/$0.50)'}`);
264
+ try {
265
+ const response = await fetch(GROK_API_URL, {
266
+ method: "POST",
267
+ headers: {
268
+ "Authorization": `Bearer ${GROK_API_KEY}`,
269
+ "Content-Type": "application/json"
270
+ },
271
+ body: JSON.stringify(requestBody)
272
+ });
273
+ const data = await response.json();
274
+ // Check if Grok made tool calls
275
+ const toolCalls = data.choices?.[0]?.message?.tool_calls || [];
276
+ if (toolCalls.length > 0) {
277
+ const callsDesc = toolCalls.map((tc) => `- ${tc.function.name}(${tc.function.arguments})`).join('\n');
278
+ return `Grok-4 would call these functions:\n${callsDesc}\n\n${data.choices?.[0]?.message?.content || ''}`;
279
+ }
280
+ return data.choices?.[0]?.message?.content || "No function calls made";
281
+ }
282
+ catch (error) {
283
+ return `Function calling error: ${error}`;
284
+ }
285
+ }
286
+ };
287
+ /**
288
+ * Cost-optimized Live Search Tool
289
+ */
290
+ export const grokSearchTool = {
291
+ name: "grok_search",
292
+ description: "Web search",
293
+ parameters: z.object({
294
+ query: z.string(),
295
+ sources: z.array(z.object({
296
+ type: z.enum(["web", "news", "x", "rss"]),
297
+ country: z.string().optional(),
298
+ allowed_websites: z.array(z.string()).optional()
299
+ })).optional(),
300
+ max_search_results: z.number().optional(),
301
+ recency: z.enum(["all", "day", "week", "month", "year"]).optional()
302
+ }),
303
+ execute: async (args, { log }) => {
304
+ const { query, sources = [{ type: "web" }], max_search_results = 20, recency = "all" } = args;
305
+ const recencyPrompt = recency !== "all"
306
+ ? `Focus on information from the last ${recency}.`
307
+ : "";
308
+ const messages = [
309
+ {
310
+ role: "system",
311
+ content: `You are Grok-3 with live search. Search for: "${query}".
312
+ ${recencyPrompt}
313
+ Provide concise, factual results with sources.
314
+ Limit search to ${max_search_results} sources for cost control.`
315
+ },
316
+ {
317
+ role: "user",
318
+ content: `Search for: ${query}`
319
+ }
320
+ ];
321
+ log?.info(`Grok Search: ${max_search_results} sources, recency: ${recency} (using grok-4-fast-reasoning with search)`);
322
+ // Extract domains from sources if specified
323
+ const domains = sources
324
+ ?.filter((s) => s.allowed_websites)
325
+ ?.flatMap((s) => s.allowed_websites) || [];
326
+ const result = await callGrokEnhanced(messages, {
327
+ model: GrokModel.GROK_4_FAST_REASONING, // Changed: Use fast reasoning with search
328
+ enableLiveSearch: true,
329
+ searchSources: max_search_results,
330
+ searchDomains: domains,
331
+ temperature: 0.3, // Low temperature for factual search
332
+ maxTokens: 3000
333
+ });
334
+ // Add cost warning
335
+ const estimatedCost = (max_search_results / 1000) * 0.025; // $25 per 1000 sources
336
+ return `${result.content}\n\n*Search used up to ${max_search_results} sources (~$${estimatedCost.toFixed(4)})*`;
337
+ }
338
+ };
339
+ /**
340
+ * Check if Grok is available
341
+ */
342
+ export function isGrokAvailable() {
343
+ return !!(GROK_API_KEY);
344
+ }
345
+ /**
346
+ * Get Grok configuration status
347
+ */
348
+ export function getGrokStatus() {
349
+ return {
350
+ available: isGrokAvailable(),
351
+ model: GrokModel.GROK_4_FAST_REASONING,
352
+ features: [
353
+ 'Fast reasoning (grok-4-fast-reasoning: $0.20/$0.50, 2M→4M context)',
354
+ 'Code specialist (grok-code-fast-1: 92 tok/sec)',
355
+ 'Heavy mode available (grok-4-0709: $3/$15, use sparingly)',
356
+ 'Live web search with citations',
357
+ 'Function calling',
358
+ 'Structured outputs',
359
+ 'Multi-modal (text, image)'
360
+ ]
361
+ };
362
+ }
363
+ /**
364
+ * Get all enhanced Grok tools
365
+ */
366
+ export function getEnhancedGrokTools() {
367
+ if (!isGrokAvailable()) {
368
+ return [];
369
+ }
370
+ return [
371
+ grokScoutTool,
372
+ grokReasonEnhanced,
373
+ grokFunctionTool,
374
+ grokSearchTool
375
+ ];
376
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Grok Tools Implementation
3
+ * Provides Grok 4 reasoning and code analysis capabilities
4
+ */
5
+ import { z } from "zod";
6
+ import { config } from "dotenv";
7
+ import * as path from 'path';
8
+ import { fileURLToPath } from 'url';
9
+ import { grokSearchTool } from './grok-enhanced.js';
10
+ import { validateToolInput } from "../utils/input-validator.js";
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = path.dirname(__filename);
13
+ config({ path: path.resolve(__dirname, '../../../.env') });
14
+ // Grok API configuration
15
+ const GROK_API_KEY = process.env.GROK_API_KEY;
16
+ const GROK_API_URL = "https://api.x.ai/v1/chat/completions";
17
+ // Available Grok models - Updated 2025-11-07 with new fast models
18
+ export var GrokModel;
19
+ (function (GrokModel) {
20
+ // New fast models (2025) - PRIMARY USE
21
+ GrokModel["CODE_FAST"] = "grok-code-fast-1";
22
+ GrokModel["GROK_4_FAST_REASONING"] = "grok-4-fast-reasoning";
23
+ GrokModel["GROK_4_FAST"] = "grok-4-fast-non-reasoning";
24
+ // Expensive/specialized (use sparingly)
25
+ GrokModel["GROK_4_HEAVY"] = "grok-4-0709";
26
+ GrokModel["GROK_3"] = "grok-3";
27
+ })(GrokModel || (GrokModel = {}));
28
+ /**
29
+ * Call Grok API
30
+ */
31
+ export async function callGrok(messages, model = GrokModel.GROK_4_FAST_REASONING, // Changed: Use cheap fast reasoning by default
32
+ temperature = 0.7, maxTokens = 16384, // Increased default for comprehensive responses
33
+ forceVisibleOutput = true) {
34
+ if (!GROK_API_KEY) {
35
+ return `[Grok API key not configured. Add GROK_API_KEY to .env file]`;
36
+ }
37
+ // Validate and sanitize message content
38
+ const validatedMessages = messages.map((msg) => {
39
+ const validation = validateToolInput(msg.content);
40
+ if (!validation.valid) {
41
+ throw new Error(validation.error || "Invalid message content");
42
+ }
43
+ return { ...msg, content: validation.sanitized };
44
+ });
45
+ try {
46
+ // For Grok 4 models, we need to handle reasoning tokens specially
47
+ const isGrok4 = model === GrokModel.GROK_4_FAST_REASONING ||
48
+ model === GrokModel.GROK_4_FAST ||
49
+ model === GrokModel.GROK_4_HEAVY;
50
+ // Adjust prompt for Grok 4 to ensure visible output
51
+ if (isGrok4 && forceVisibleOutput) {
52
+ const lastMessage = validatedMessages[validatedMessages.length - 1];
53
+ if (lastMessage.role === 'user') {
54
+ lastMessage.content += '\n\nProvide a detailed response with your reasoning and conclusion.';
55
+ }
56
+ }
57
+ const response = await fetch(GROK_API_URL, {
58
+ method: "POST",
59
+ headers: {
60
+ "Authorization": `Bearer ${GROK_API_KEY}`,
61
+ "Content-Type": "application/json"
62
+ },
63
+ body: JSON.stringify({
64
+ model,
65
+ messages: validatedMessages,
66
+ temperature,
67
+ max_tokens: maxTokens,
68
+ stream: false
69
+ })
70
+ });
71
+ if (!response.ok) {
72
+ const error = await response.text();
73
+ throw new Error(`Grok API error: ${response.statusText} - ${error}`);
74
+ }
75
+ const data = await response.json();
76
+ const content = data.choices?.[0]?.message?.content;
77
+ // Handle Grok 4's reasoning tokens
78
+ if (!content && data.usage?.completion_tokens_details?.reasoning_tokens > 0) {
79
+ // If Grok 4 returns no visible content, retry with Grok 3 for visible output
80
+ if (isGrok4 && forceVisibleOutput) {
81
+ console.error(`Grok 4 used ${data.usage.completion_tokens_details.reasoning_tokens} reasoning tokens with no output. Retrying with Grok 3...`);
82
+ return callGrok(validatedMessages, GrokModel.GROK_3, temperature, maxTokens, false);
83
+ }
84
+ return `[Grok ${model} performed deep reasoning with ${data.usage.completion_tokens_details.reasoning_tokens} tokens]`;
85
+ }
86
+ return content || "No response from Grok";
87
+ }
88
+ catch (error) {
89
+ return `[Grok error: ${error instanceof Error ? error.message : String(error)}]`;
90
+ }
91
+ }
92
+ /**
93
+ * Grok Reasoning Tool
94
+ * Deep logical reasoning with first principles thinking
95
+ */
96
+ export const grokReasonTool = {
97
+ name: "grok_reason",
98
+ description: "Deep reasoning",
99
+ parameters: z.object({
100
+ problem: z.string(),
101
+ approach: z.enum(["analytical", "creative", "systematic", "first-principles"]).optional(),
102
+ context: z.string().optional(),
103
+ useHeavy: z.boolean().optional()
104
+ }),
105
+ execute: async (args, { log }) => {
106
+ const { problem, approach = "first-principles", context, useHeavy } = args;
107
+ const approachPrompts = {
108
+ analytical: "Break down the problem systematically and analyze each component",
109
+ creative: "Think outside the box and consider unconventional solutions",
110
+ systematic: "Follow a step-by-step logical process",
111
+ "first-principles": "Break down to fundamental truths and build up from there"
112
+ };
113
+ const messages = [
114
+ {
115
+ role: "system",
116
+ content: `You are Grok, an expert at logical reasoning and problem-solving.
117
+ ${approachPrompts[approach]}.
118
+ ${context ? `Context: ${context}` : ''}`
119
+ },
120
+ {
121
+ role: "user",
122
+ content: problem
123
+ }
124
+ ];
125
+ // Use GROK_4_FAST_REASONING by default (3x cheaper!), GROK_4_HEAVY only if explicitly requested
126
+ const model = useHeavy ? GrokModel.GROK_4_HEAVY : GrokModel.GROK_4_FAST_REASONING;
127
+ const maxTokens = useHeavy ? 100000 : 16384; // 100k for heavy, 16k for normal reasoning
128
+ log?.info(`Using Grok model: ${model} for deep reasoning (max tokens: ${maxTokens}, cost: ${useHeavy ? 'expensive $3/$15' : 'cheap $0.20/$0.50'})`);
129
+ return await callGrok(messages, model, 0.7, maxTokens, true);
130
+ }
131
+ };
132
+ /**
133
+ * Grok Code Tool
134
+ * Code analysis, optimization, and debugging
135
+ */
136
+ export const grokCodeTool = {
137
+ name: "grok_code",
138
+ description: "Code analysis",
139
+ parameters: z.object({
140
+ task: z.enum(["analyze", "optimize", "debug", "review", "refactor"]),
141
+ code: z.string(),
142
+ language: z.string().optional(),
143
+ requirements: z.string().optional()
144
+ }),
145
+ execute: async (args, { log }) => {
146
+ const { task, code, language, requirements } = args;
147
+ const taskPrompts = {
148
+ analyze: "Analyze this code for logic, structure, and potential issues",
149
+ optimize: "Optimize this code for performance and efficiency",
150
+ debug: "Debug this code and identify issues or bugs",
151
+ review: "Review this code for best practices and improvements",
152
+ refactor: "Refactor this code for better maintainability and clarity"
153
+ };
154
+ const messages = [
155
+ {
156
+ role: "system",
157
+ content: `You are Grok Code Fast, an expert programmer and code analyst.
158
+ Task: ${taskPrompts[task]}
159
+ ${language ? `Language: ${language}` : ''}
160
+ ${requirements ? `Requirements: ${requirements}` : ''}`
161
+ },
162
+ {
163
+ role: "user",
164
+ content: `Code:\n\`\`\`${language || ''}\n${code}\n\`\`\``
165
+ }
166
+ ];
167
+ log?.info(`Using Grok Code Fast (92 tok/sec coding specialist)`);
168
+ return await callGrok(messages, GrokModel.CODE_FAST, 0.2, 4000, true);
169
+ }
170
+ };
171
+ /**
172
+ * Grok Debug Tool
173
+ * Specialized debugging assistance
174
+ */
175
+ export const grokDebugTool = {
176
+ name: "grok_debug",
177
+ description: "Debug assistance",
178
+ parameters: z.object({
179
+ issue: z.string(),
180
+ code: z.string().optional(),
181
+ error: z.string().optional(),
182
+ context: z.string().optional()
183
+ }),
184
+ execute: async (args, { log }) => {
185
+ const { issue, code, error, context } = args;
186
+ let prompt = `Debug this issue: ${issue}\n`;
187
+ if (error) {
188
+ prompt += `\nError:\n${error}\n`;
189
+ }
190
+ if (code) {
191
+ prompt += `\nRelevant code:\n\`\`\`\n${code}\n\`\`\`\n`;
192
+ }
193
+ if (context) {
194
+ prompt += `\nContext: ${context}\n`;
195
+ }
196
+ const messages = [
197
+ {
198
+ role: "system",
199
+ content: `You are Grok Code Fast, an expert debugger.
200
+ Analyze the issue systematically:
201
+ 1. Identify the root cause
202
+ 2. Explain why it's happening
203
+ 3. Provide a clear solution
204
+ 4. Suggest preventive measures`
205
+ },
206
+ {
207
+ role: "user",
208
+ content: prompt
209
+ }
210
+ ];
211
+ log?.info(`Using Grok Code Fast for debugging (specialized code model)`);
212
+ return await callGrok(messages, GrokModel.CODE_FAST, 0.3, 3000, true);
213
+ }
214
+ };
215
+ /**
216
+ * Grok Architect Tool
217
+ * System architecture and design
218
+ */
219
+ export const grokArchitectTool = {
220
+ name: "grok_architect",
221
+ description: "Architecture design",
222
+ parameters: z.object({
223
+ requirements: z.string(),
224
+ constraints: z.string().optional(),
225
+ scale: z.enum(["small", "medium", "large", "enterprise"]).optional()
226
+ }),
227
+ execute: async (args, { log }) => {
228
+ const { requirements, constraints, scale } = args;
229
+ const messages = [
230
+ {
231
+ role: "system",
232
+ content: `You are Grok, an expert system architect.
233
+ Design a robust, scalable architecture using first principles.
234
+ Consider: reliability, scalability, maintainability, security, and cost.
235
+ ${scale ? `Target scale: ${scale}` : ''}
236
+ ${constraints ? `Constraints: ${constraints}` : ''}`
237
+ },
238
+ {
239
+ role: "user",
240
+ content: requirements
241
+ }
242
+ ];
243
+ log?.info(`Using Grok 4 Fast Reasoning for architecture (cheap reasoning model)`);
244
+ return await callGrok(messages, GrokModel.GROK_4_FAST_REASONING, 0.6, 4000, true);
245
+ }
246
+ };
247
+ /**
248
+ * Grok Brainstorm Tool
249
+ * Creative brainstorming with Grok 4 Heavy
250
+ */
251
+ export const grokBrainstormTool = {
252
+ name: "grok_brainstorm",
253
+ description: "Creative brainstorming",
254
+ parameters: z.object({
255
+ topic: z.string(),
256
+ constraints: z.string().optional(),
257
+ numIdeas: z.number().optional(),
258
+ forceHeavy: z.boolean().optional()
259
+ }),
260
+ execute: async (args, { log }) => {
261
+ const { topic, constraints, numIdeas = 5, forceHeavy = false } = args; // Changed: Default to cheap model
262
+ const messages = [
263
+ {
264
+ role: "system",
265
+ content: `You are Grok in maximum creative mode. Generate ${numIdeas} innovative, unconventional ideas.
266
+ Think beyond normal boundaries. Challenge assumptions. Propose radical solutions.
267
+ ${constraints ? `Constraints: ${constraints}` : 'No constraints - think freely!'}`
268
+ },
269
+ {
270
+ role: "user",
271
+ content: `Brainstorm creative solutions for: ${topic}`
272
+ }
273
+ ];
274
+ // Use GROK_4_FAST for creative brainstorming (cheap, fast), GROK_4_HEAVY only if explicitly requested
275
+ const model = forceHeavy ? GrokModel.GROK_4_HEAVY : GrokModel.GROK_4_FAST;
276
+ log?.info(`Brainstorming with Grok model: ${model} (Heavy: ${forceHeavy}, cost: ${forceHeavy ? 'expensive $3/$15' : 'cheap $0.20/$0.50'})`);
277
+ return await callGrok(messages, model, 0.95, 4000); // High temperature for creativity
278
+ }
279
+ };
280
+ /**
281
+ * Check if Grok is available
282
+ */
283
+ export function isGrokAvailable() {
284
+ return !!GROK_API_KEY;
285
+ }
286
+ export function getAllGrokTools() {
287
+ if (!isGrokAvailable()) {
288
+ return [];
289
+ }
290
+ // Minimized tool set - keeping all essential Grok tools
291
+ return [
292
+ grokReasonTool, // Deep reasoning
293
+ grokCodeTool, // Code analysis
294
+ grokDebugTool, // Deep debugging
295
+ grokArchitectTool, // System architecture
296
+ grokBrainstormTool, // Creative brainstorming
297
+ grokSearchTool // Web search with Grok
298
+ ];
299
+ }