gthinking 1.2.1 → 2.1.1

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 (271) hide show
  1. package/.eslintrc.js +34 -0
  2. package/ANALYSIS_SUMMARY.md +363 -0
  3. package/README.md +230 -245
  4. package/dist/analysis/analysis-engine.d.ts +63 -0
  5. package/dist/analysis/analysis-engine.d.ts.map +1 -0
  6. package/dist/analysis/analysis-engine.js +322 -0
  7. package/dist/analysis/analysis-engine.js.map +1 -0
  8. package/dist/core/config.d.ts +1419 -0
  9. package/dist/core/config.d.ts.map +1 -0
  10. package/dist/core/config.js +361 -0
  11. package/dist/core/config.js.map +1 -0
  12. package/dist/core/engine.d.ts +176 -0
  13. package/dist/core/engine.d.ts.map +1 -0
  14. package/dist/core/engine.js +604 -0
  15. package/dist/core/engine.js.map +1 -0
  16. package/dist/core/errors.d.ts +153 -0
  17. package/dist/core/errors.d.ts.map +1 -0
  18. package/dist/core/errors.js +287 -0
  19. package/dist/core/errors.js.map +1 -0
  20. package/dist/core/index.d.ts +7 -0
  21. package/dist/core/index.d.ts.map +1 -0
  22. package/dist/{types.js → core/index.js} +8 -4
  23. package/dist/core/index.js.map +1 -0
  24. package/dist/core/pipeline.d.ts +121 -0
  25. package/dist/core/pipeline.d.ts.map +1 -0
  26. package/dist/core/pipeline.js +289 -0
  27. package/dist/core/pipeline.js.map +1 -0
  28. package/dist/core/rate-limiter.d.ts +58 -0
  29. package/dist/core/rate-limiter.d.ts.map +1 -0
  30. package/dist/core/rate-limiter.js +133 -0
  31. package/dist/core/rate-limiter.js.map +1 -0
  32. package/dist/core/session-manager.d.ts +96 -0
  33. package/dist/core/session-manager.d.ts.map +1 -0
  34. package/dist/core/session-manager.js +223 -0
  35. package/dist/core/session-manager.js.map +1 -0
  36. package/dist/creativity/creativity-engine.d.ts +6 -0
  37. package/dist/creativity/creativity-engine.d.ts.map +1 -0
  38. package/dist/creativity/creativity-engine.js +17 -0
  39. package/dist/creativity/creativity-engine.js.map +1 -0
  40. package/dist/index.d.ts +24 -32
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +130 -104
  43. package/dist/index.js.map +1 -1
  44. package/dist/learning/learning-engine.d.ts +6 -0
  45. package/dist/learning/learning-engine.d.ts.map +1 -0
  46. package/dist/learning/learning-engine.js +17 -0
  47. package/dist/learning/learning-engine.js.map +1 -0
  48. package/dist/llm/index.d.ts +10 -0
  49. package/dist/llm/index.d.ts.map +1 -0
  50. package/dist/llm/index.js +26 -0
  51. package/dist/llm/index.js.map +1 -0
  52. package/dist/llm/llm-service.d.ts +109 -0
  53. package/dist/llm/llm-service.d.ts.map +1 -0
  54. package/dist/llm/llm-service.js +224 -0
  55. package/dist/llm/llm-service.js.map +1 -0
  56. package/dist/llm/providers/base.d.ts +85 -0
  57. package/dist/llm/providers/base.d.ts.map +1 -0
  58. package/dist/llm/providers/base.js +57 -0
  59. package/dist/llm/providers/base.js.map +1 -0
  60. package/dist/llm/providers/cli.d.ts +23 -0
  61. package/dist/llm/providers/cli.d.ts.map +1 -0
  62. package/dist/llm/providers/cli.js +158 -0
  63. package/dist/llm/providers/cli.js.map +1 -0
  64. package/dist/llm/providers/gemini.d.ts +30 -0
  65. package/dist/llm/providers/gemini.d.ts.map +1 -0
  66. package/dist/llm/providers/gemini.js +168 -0
  67. package/dist/llm/providers/gemini.js.map +1 -0
  68. package/dist/llm/sanitization.d.ts +50 -0
  69. package/dist/llm/sanitization.d.ts.map +1 -0
  70. package/dist/llm/sanitization.js +149 -0
  71. package/dist/llm/sanitization.js.map +1 -0
  72. package/dist/{server.d.ts.map → mcp/server.d.ts.map} +1 -1
  73. package/dist/mcp/server.js +108 -0
  74. package/dist/mcp/server.js.map +1 -0
  75. package/dist/planning/planning-engine.d.ts +6 -0
  76. package/dist/planning/planning-engine.d.ts.map +1 -0
  77. package/dist/planning/planning-engine.js +17 -0
  78. package/dist/planning/planning-engine.js.map +1 -0
  79. package/dist/reasoning/reasoning-engine.d.ts +6 -0
  80. package/dist/reasoning/reasoning-engine.d.ts.map +1 -0
  81. package/dist/reasoning/reasoning-engine.js +17 -0
  82. package/dist/reasoning/reasoning-engine.js.map +1 -0
  83. package/dist/search/search-engine.d.ts +99 -0
  84. package/dist/search/search-engine.d.ts.map +1 -0
  85. package/dist/search/search-engine.js +271 -0
  86. package/dist/search/search-engine.js.map +1 -0
  87. package/dist/synthesis/synthesis-engine.d.ts +6 -0
  88. package/dist/synthesis/synthesis-engine.d.ts.map +1 -0
  89. package/dist/synthesis/synthesis-engine.js +17 -0
  90. package/dist/synthesis/synthesis-engine.js.map +1 -0
  91. package/dist/types/analysis.d.ts +1534 -49
  92. package/dist/types/analysis.d.ts.map +1 -1
  93. package/dist/types/analysis.js +250 -0
  94. package/dist/types/analysis.js.map +1 -1
  95. package/dist/types/core.d.ts +257 -30
  96. package/dist/types/core.d.ts.map +1 -1
  97. package/dist/types/core.js +148 -18
  98. package/dist/types/core.js.map +1 -1
  99. package/dist/types/creativity.d.ts +2871 -56
  100. package/dist/types/creativity.d.ts.map +1 -1
  101. package/dist/types/creativity.js +195 -0
  102. package/dist/types/creativity.js.map +1 -1
  103. package/dist/types/index.d.ts +6 -2
  104. package/dist/types/index.d.ts.map +1 -1
  105. package/dist/types/index.js +17 -2
  106. package/dist/types/index.js.map +1 -1
  107. package/dist/types/learning.d.ts +851 -61
  108. package/dist/types/learning.d.ts.map +1 -1
  109. package/dist/types/learning.js +155 -0
  110. package/dist/types/learning.js.map +1 -1
  111. package/dist/types/planning.d.ts +2223 -71
  112. package/dist/types/planning.d.ts.map +1 -1
  113. package/dist/types/planning.js +190 -0
  114. package/dist/types/planning.js.map +1 -1
  115. package/dist/types/reasoning.d.ts +2209 -72
  116. package/dist/types/reasoning.d.ts.map +1 -1
  117. package/dist/types/reasoning.js +200 -1
  118. package/dist/types/reasoning.js.map +1 -1
  119. package/dist/types/search.d.ts +981 -53
  120. package/dist/types/search.d.ts.map +1 -1
  121. package/dist/types/search.js +137 -0
  122. package/dist/types/search.js.map +1 -1
  123. package/dist/types/synthesis.d.ts +583 -37
  124. package/dist/types/synthesis.d.ts.map +1 -1
  125. package/dist/types/synthesis.js +138 -0
  126. package/dist/types/synthesis.js.map +1 -1
  127. package/dist/utils/cache.d.ts +144 -0
  128. package/dist/utils/cache.d.ts.map +1 -0
  129. package/dist/utils/cache.js +288 -0
  130. package/dist/utils/cache.js.map +1 -0
  131. package/dist/utils/id-generator.d.ts +89 -0
  132. package/dist/utils/id-generator.d.ts.map +1 -0
  133. package/dist/utils/id-generator.js +132 -0
  134. package/dist/utils/id-generator.js.map +1 -0
  135. package/dist/utils/index.d.ts +11 -0
  136. package/dist/utils/index.d.ts.map +1 -0
  137. package/dist/utils/index.js +33 -0
  138. package/dist/utils/index.js.map +1 -0
  139. package/dist/utils/logger.d.ts +142 -0
  140. package/dist/utils/logger.d.ts.map +1 -0
  141. package/dist/utils/logger.js +248 -0
  142. package/dist/utils/logger.js.map +1 -0
  143. package/dist/utils/metrics.d.ts +149 -0
  144. package/dist/utils/metrics.d.ts.map +1 -0
  145. package/dist/utils/metrics.js +296 -0
  146. package/dist/utils/metrics.js.map +1 -0
  147. package/dist/utils/timer.d.ts +7 -0
  148. package/dist/utils/timer.d.ts.map +1 -0
  149. package/dist/utils/timer.js +17 -0
  150. package/dist/utils/timer.js.map +1 -0
  151. package/dist/utils/validation.d.ts +147 -0
  152. package/dist/utils/validation.d.ts.map +1 -0
  153. package/dist/utils/validation.js +275 -0
  154. package/dist/utils/validation.js.map +1 -0
  155. package/docs/API.md +411 -0
  156. package/docs/ARCHITECTURE.md +271 -0
  157. package/docs/CHANGELOG.md +283 -0
  158. package/jest.config.js +28 -0
  159. package/package.json +43 -30
  160. package/src/analysis/analysis-engine.ts +383 -0
  161. package/src/core/config.ts +406 -0
  162. package/src/core/engine.ts +785 -0
  163. package/src/core/errors.ts +349 -0
  164. package/src/core/index.ts +12 -0
  165. package/src/core/pipeline.ts +424 -0
  166. package/src/core/rate-limiter.ts +155 -0
  167. package/src/core/session-manager.ts +269 -0
  168. package/src/creativity/creativity-engine.ts +14 -0
  169. package/src/index.ts +178 -0
  170. package/src/learning/learning-engine.ts +14 -0
  171. package/src/llm/index.ts +10 -0
  172. package/src/llm/llm-service.ts +285 -0
  173. package/src/llm/providers/base.ts +146 -0
  174. package/src/llm/providers/cli.ts +186 -0
  175. package/src/llm/providers/gemini.ts +201 -0
  176. package/src/llm/sanitization.ts +178 -0
  177. package/src/mcp/server.ts +117 -0
  178. package/src/planning/planning-engine.ts +14 -0
  179. package/src/reasoning/reasoning-engine.ts +14 -0
  180. package/src/search/search-engine.ts +333 -0
  181. package/src/synthesis/synthesis-engine.ts +14 -0
  182. package/src/types/analysis.ts +337 -0
  183. package/src/types/core.ts +342 -0
  184. package/src/types/creativity.ts +268 -0
  185. package/src/types/index.ts +31 -0
  186. package/src/types/learning.ts +215 -0
  187. package/src/types/planning.ts +251 -0
  188. package/src/types/reasoning.ts +288 -0
  189. package/src/types/search.ts +192 -0
  190. package/src/types/synthesis.ts +187 -0
  191. package/src/utils/cache.ts +363 -0
  192. package/src/utils/id-generator.ts +135 -0
  193. package/src/utils/index.ts +22 -0
  194. package/src/utils/logger.ts +290 -0
  195. package/src/utils/metrics.ts +380 -0
  196. package/src/utils/timer.ts +15 -0
  197. package/src/utils/validation.ts +297 -0
  198. package/tests/setup.ts +22 -0
  199. package/tests/unit/cache.test.ts +189 -0
  200. package/tests/unit/engine.test.ts +179 -0
  201. package/tests/unit/validation.test.ts +218 -0
  202. package/tsconfig.json +17 -12
  203. package/GEMINI.md +0 -68
  204. package/analysis.ts +0 -1063
  205. package/creativity.ts +0 -1055
  206. package/dist/analysis.d.ts +0 -54
  207. package/dist/analysis.d.ts.map +0 -1
  208. package/dist/analysis.js +0 -866
  209. package/dist/analysis.js.map +0 -1
  210. package/dist/creativity.d.ts +0 -81
  211. package/dist/creativity.d.ts.map +0 -1
  212. package/dist/creativity.js +0 -828
  213. package/dist/creativity.js.map +0 -1
  214. package/dist/engine.d.ts +0 -90
  215. package/dist/engine.d.ts.map +0 -1
  216. package/dist/engine.js +0 -677
  217. package/dist/engine.js.map +0 -1
  218. package/dist/examples.d.ts +0 -7
  219. package/dist/examples.d.ts.map +0 -1
  220. package/dist/examples.js +0 -506
  221. package/dist/examples.js.map +0 -1
  222. package/dist/learning.d.ts +0 -72
  223. package/dist/learning.d.ts.map +0 -1
  224. package/dist/learning.js +0 -615
  225. package/dist/learning.js.map +0 -1
  226. package/dist/llm-service.d.ts +0 -21
  227. package/dist/llm-service.d.ts.map +0 -1
  228. package/dist/llm-service.js +0 -100
  229. package/dist/llm-service.js.map +0 -1
  230. package/dist/planning.d.ts +0 -58
  231. package/dist/planning.d.ts.map +0 -1
  232. package/dist/planning.js +0 -824
  233. package/dist/planning.js.map +0 -1
  234. package/dist/reasoning.d.ts +0 -73
  235. package/dist/reasoning.d.ts.map +0 -1
  236. package/dist/reasoning.js +0 -845
  237. package/dist/reasoning.js.map +0 -1
  238. package/dist/search-discovery.d.ts +0 -73
  239. package/dist/search-discovery.d.ts.map +0 -1
  240. package/dist/search-discovery.js +0 -548
  241. package/dist/search-discovery.js.map +0 -1
  242. package/dist/server.js +0 -113
  243. package/dist/server.js.map +0 -1
  244. package/dist/types/engine.d.ts +0 -55
  245. package/dist/types/engine.d.ts.map +0 -1
  246. package/dist/types/engine.js +0 -3
  247. package/dist/types/engine.js.map +0 -1
  248. package/dist/types.d.ts +0 -6
  249. package/dist/types.d.ts.map +0 -1
  250. package/dist/types.js.map +0 -1
  251. package/engine.ts +0 -947
  252. package/examples.ts +0 -717
  253. package/index.ts +0 -106
  254. package/learning.ts +0 -779
  255. package/llm-service.ts +0 -120
  256. package/planning.ts +0 -1028
  257. package/reasoning.ts +0 -1079
  258. package/search-discovery.ts +0 -700
  259. package/server.ts +0 -115
  260. package/types/analysis.ts +0 -69
  261. package/types/core.ts +0 -90
  262. package/types/creativity.ts +0 -72
  263. package/types/engine.ts +0 -60
  264. package/types/index.ts +0 -9
  265. package/types/learning.ts +0 -69
  266. package/types/planning.ts +0 -85
  267. package/types/reasoning.ts +0 -92
  268. package/types/search.ts +0 -58
  269. package/types/synthesis.ts +0 -42
  270. package/types.ts +0 -6
  271. /package/dist/{server.d.ts → mcp/server.d.ts} +0 -0
package/engine.ts DELETED
@@ -1,947 +0,0 @@
1
- /**
2
- * Sequential Thinking Engine
3
- * Main orchestrator that integrates all thinking modules
4
- */
5
-
6
- import {
7
- // Core types
8
- SequentialThinkingConfig,
9
- ThinkingRequest,
10
- ThinkingResponse,
11
- ThinkingSession,
12
- ThinkingStage,
13
- StageResult,
14
- ResponseMetadata,
15
- TaskStatus,
16
- ThinkingEvent,
17
- ThinkingError,
18
-
19
- // Search types
20
- SearchResult,
21
- AggregatedResult,
22
- SourceType,
23
-
24
- // Analysis types
25
- AnalysisResult,
26
- AnalysisType,
27
-
28
- // Reasoning types
29
- ReasoningSession,
30
- ReasoningType,
31
- ChainOfThought,
32
-
33
- // Learning types
34
- LearningContext,
35
- Interaction,
36
- KnowledgeNode,
37
-
38
- // Planning types
39
- Plan,
40
- Task,
41
- Resource,
42
- ProgressReport,
43
-
44
- // Creativity types
45
- CreativeSession,
46
- CreativityTechnique,
47
- OutOfBoxThinking,
48
-
49
- // Synthesis types
50
- SynthesisResult,
51
- Recommendation
52
- } from './types';
53
-
54
- import { EventEmitter } from 'events';
55
-
56
- // Import all engines
57
- import { SearchDiscoveryEngine } from './search-discovery';
58
- import { AnalysisEngine } from './analysis';
59
- import { ReasoningEngine } from './reasoning';
60
- import { LearningEngine } from './learning';
61
- import { PlanningEngine } from './planning';
62
- import { CreativityEngine } from './creativity';
63
-
64
- // ============================================================================
65
- // SYNTHESIS ENGINE
66
- // ============================================================================
67
-
68
- class SynthesisEngine {
69
- synthesize(
70
- query: string,
71
- searchResults: SearchResult[],
72
- analysisResults: AnalysisResult[],
73
- reasoningSession?: ReasoningSession,
74
- creativeSession?: CreativeSession
75
- ): SynthesisResult {
76
- // Extract key insights from each component
77
- const insights = this.extractInsights(
78
- searchResults,
79
- analysisResults,
80
- reasoningSession,
81
- creativeSession
82
- );
83
-
84
- // Generate summary
85
- const summary = this.generateSummary(query, insights);
86
-
87
- // Generate recommendations
88
- const recommendations = this.generateRecommendations(
89
- query,
90
- insights,
91
- reasoningSession
92
- );
93
-
94
- // Identify gaps and uncertainties
95
- const gaps = this.identifyGaps(searchResults, analysisResults);
96
- const uncertainties = this.identifyUncertainties(reasoningSession);
97
-
98
- // Calculate confidence
99
- const confidence = this.calculateSynthesisConfidence(
100
- searchResults,
101
- analysisResults,
102
- reasoningSession
103
- );
104
-
105
- return {
106
- id: `synthesis_${Date.now()}`,
107
- sources: [
108
- ...searchResults.map(r => r.url),
109
- reasoningSession ? `reasoning_${reasoningSession.id}` : 'reasoning_skipped'
110
- ],
111
- summary,
112
- keyInsights: insights,
113
- recommendations,
114
- confidence,
115
- gaps,
116
- uncertainties
117
- };
118
- }
119
-
120
- private extractInsights(
121
- searchResults: SearchResult[],
122
- analysisResults: AnalysisResult[],
123
- reasoningSession?: ReasoningSession,
124
- creativeSession?: CreativeSession
125
- ): string[] {
126
- const insights: string[] = [];
127
-
128
- // From search
129
- if (searchResults.length > 0) {
130
- const topResult = searchResults[0];
131
- insights.push(`Key finding from research: ${topResult.snippet.substring(0, 100)}...`);
132
- }
133
-
134
- // From analysis
135
- analysisResults.forEach(result => {
136
- result.findings.forEach(finding => {
137
- if (finding.confidence > 0.7) {
138
- insights.push(`${result.type}: ${JSON.stringify(finding.value).substring(0, 100)}`);
139
- }
140
- });
141
- });
142
-
143
- // From reasoning
144
- if (reasoningSession && reasoningSession.steps.length > 0) {
145
- const lastStep = reasoningSession.steps[reasoningSession.steps.length - 1];
146
- insights.push(`Reasoning conclusion: ${lastStep.inference}`);
147
- }
148
-
149
- // From creativity
150
- if (creativeSession) {
151
- const topIdeas = creativeSession.ideas
152
- .sort((a, b) => (b.novelty + b.feasibility + b.impact) - (a.novelty + a.feasibility + a.impact))
153
- .slice(0, 2);
154
-
155
- topIdeas.forEach(idea => {
156
- insights.push(`Creative insight: ${idea.content.substring(0, 80)}...`);
157
- });
158
- }
159
-
160
- return insights;
161
- }
162
-
163
- private generateSummary(query: string, insights: string[]): string {
164
- return `Analysis of "${query}" reveals ${insights.length} key insights. ` +
165
- `The synthesis combines research findings, logical reasoning, and creative exploration ` +
166
- `to provide a comprehensive understanding of the topic.`;
167
- }
168
-
169
- private generateRecommendations(
170
- query: string,
171
- insights: string[],
172
- reasoningSession?: ReasoningSession
173
- ): Recommendation[] {
174
- const recommendations: Recommendation[] = [];
175
-
176
- // Based on reasoning
177
- if (reasoningSession && reasoningSession.conclusion) {
178
- recommendations.push({
179
- id: `rec_${Date.now()}_1`,
180
- action: `Proceed with approach suggested by ${reasoningSession.type} reasoning`,
181
- rationale: reasoningSession.conclusion,
182
- priority: reasoningSession.confidence > 0.7 ? 1 : 2,
183
- expectedOutcome: 'Resolution based on logical analysis',
184
- risks: ['Reasoning assumptions may not hold'],
185
- confidence: reasoningSession.confidence
186
- });
187
- }
188
-
189
- // General recommendations
190
- recommendations.push({
191
- id: `rec_${Date.now()}_2`,
192
- action: 'Gather additional data to validate findings',
193
- rationale: 'More information increases confidence',
194
- priority: 3,
195
- expectedOutcome: 'Improved decision quality',
196
- risks: ['Time delay'],
197
- confidence: 0.8
198
- });
199
-
200
- return recommendations;
201
- }
202
-
203
- private identifyGaps(
204
- searchResults: SearchResult[],
205
- analysisResults: AnalysisResult[]
206
- ): string[] {
207
- const gaps: string[] = [];
208
-
209
- if (searchResults.length < 5) {
210
- gaps.push('Limited research coverage');
211
- }
212
-
213
- const lowConfidenceAnalysis = analysisResults.filter(r => r.confidence < 0.5);
214
- if (lowConfidenceAnalysis.length > 0) {
215
- gaps.push('Some analyses have low confidence');
216
- }
217
-
218
- return gaps;
219
- }
220
-
221
- private identifyUncertainties(reasoningSession?: ReasoningSession): string[] {
222
- const uncertainties: string[] = [];
223
-
224
- if (reasoningSession) {
225
- reasoningSession.steps.forEach(step => {
226
- if (step.confidence < 0.7) {
227
- uncertainties.push(`Step ${step.stepNumber}: ${step.inference}`);
228
- }
229
- });
230
- }
231
-
232
- return uncertainties;
233
- }
234
-
235
- private calculateSynthesisConfidence(
236
- searchResults: SearchResult[],
237
- analysisResults: AnalysisResult[],
238
- reasoningSession?: ReasoningSession
239
- ): number {
240
- const factors = [
241
- searchResults.length > 0 ? searchResults[0].credibility : 0,
242
- analysisResults.length > 0 ?
243
- analysisResults.reduce((sum, r) => sum + r.confidence, 0) / analysisResults.length : 0,
244
- ];
245
-
246
- if (reasoningSession) {
247
- factors.push(reasoningSession.confidence);
248
- }
249
-
250
- return factors.reduce((sum, f) => sum + f, 0) / factors.length;
251
- }
252
- }
253
-
254
- // ============================================================================
255
- // MAIN SEQUENTIAL THINKING ENGINE
256
- // ============================================================================
257
-
258
- export interface SequentialThinkingEngineDeps {
259
- searchEngine?: SearchDiscoveryEngine;
260
- analysisEngine?: AnalysisEngine;
261
- reasoningEngine?: ReasoningEngine;
262
- learningEngine?: LearningEngine;
263
- planningEngine?: PlanningEngine;
264
- creativityEngine?: CreativityEngine;
265
- }
266
-
267
- export class SequentialThinkingEngine extends EventEmitter {
268
- private searchEngine: SearchDiscoveryEngine;
269
- private analysisEngine: AnalysisEngine;
270
- private reasoningEngine: ReasoningEngine;
271
- private learningEngine: LearningEngine;
272
- private planningEngine: PlanningEngine;
273
- private creativityEngine: CreativityEngine;
274
- private synthesisEngine: SynthesisEngine;
275
-
276
- private config: SequentialThinkingConfig;
277
- private sessions: Map<string, ThinkingSession> = new Map();
278
-
279
- constructor(
280
- config: Partial<SequentialThinkingConfig> = {},
281
- deps: SequentialThinkingEngineDeps = {}
282
- ) {
283
- super();
284
-
285
- this.config = {
286
- maxSearchResults: 10,
287
- analysisDepth: 'moderate',
288
- reasoningComplexity: 'moderate',
289
- learningEnabled: true,
290
- creativityLevel: 'balanced',
291
- planningDetail: 'detailed',
292
- timeout: 60000,
293
- retryAttempts: 3,
294
- ...config
295
- };
296
-
297
- // Initialize all engines (inject or default)
298
- this.searchEngine = deps.searchEngine || new SearchDiscoveryEngine();
299
- this.analysisEngine = deps.analysisEngine || new AnalysisEngine();
300
- this.reasoningEngine = deps.reasoningEngine || new ReasoningEngine();
301
- this.learningEngine = deps.learningEngine || new LearningEngine();
302
- this.planningEngine = deps.planningEngine || new PlanningEngine();
303
- this.creativityEngine = deps.creativityEngine || new CreativityEngine();
304
-
305
- // Synthesis engine is internal for now, but could be injected too
306
- this.synthesisEngine = new SynthesisEngine();
307
-
308
- // Set up event forwarding
309
- this.setupEventForwarding();
310
- }
311
-
312
- private setupEventForwarding(): void {
313
- // Forward events from all engines
314
- const engines = [
315
- this.searchEngine,
316
- this.analysisEngine,
317
- this.reasoningEngine,
318
- this.learningEngine,
319
- this.planningEngine,
320
- this.creativityEngine
321
- ];
322
-
323
- engines.forEach(engine => {
324
- engine.on('*', (event: ThinkingEvent) => {
325
- this.emit(event.type, event);
326
- });
327
- });
328
- }
329
-
330
- /**
331
- * Process a thinking request through all stages
332
- */
333
- async think(request: ThinkingRequest): Promise<ThinkingResponse> {
334
- const startTime = Date.now();
335
- const stageResults: StageResult[] = [];
336
-
337
- // Create or get session
338
- const session = this.getOrCreateSession(request);
339
-
340
- // Merge config
341
- const config = { ...this.config, ...request.config };
342
-
343
- this.emit('thinking_start', {
344
- id: request.id,
345
- stage: ThinkingStage.SEARCH,
346
- timestamp: new Date(),
347
- data: { query: request.query }
348
- } as ThinkingEvent);
349
-
350
- try {
351
- // Stage 1: Search & Discovery
352
- if (this.shouldExecuteStage(request, ThinkingStage.SEARCH)) {
353
- const searchResult = await this.executeSearch(request, config);
354
- stageResults.push(searchResult);
355
- }
356
-
357
- // Stage 2: Analysis
358
- if (this.shouldExecuteStage(request, ThinkingStage.ANALYSIS)) {
359
- const analysisResult = await this.executeAnalysis(request, stageResults, config);
360
- stageResults.push(analysisResult);
361
- }
362
-
363
- // Stage 3: Reasoning
364
- if (this.shouldExecuteStage(request, ThinkingStage.REASONING)) {
365
- const reasoningResult = await this.executeReasoning(request, stageResults, config);
366
- stageResults.push(reasoningResult);
367
- }
368
-
369
- // Stage 4: Learning (context enrichment)
370
- if (config.learningEnabled && this.shouldExecuteStage(request, ThinkingStage.LEARNING)) {
371
- const learningResult = await this.executeLearning(request, stageResults, config);
372
- stageResults.push(learningResult);
373
- }
374
-
375
- // Stage 5: Planning (if applicable)
376
- if (this.shouldExecuteStage(request, ThinkingStage.PLANNING) && this.isPlanningRequest(request)) {
377
- const planningResult = await this.executePlanning(request, stageResults, config);
378
- stageResults.push(planningResult);
379
- }
380
-
381
- // Stage 6: Creativity
382
- if (this.shouldExecuteStage(request, ThinkingStage.CREATIVITY)) {
383
- const creativityResult = await this.executeCreativity(request, stageResults, config);
384
- stageResults.push(creativityResult);
385
- }
386
-
387
- // Stage 7: Synthesis
388
- const synthesisResult = await this.executeSynthesis(request, stageResults, config);
389
- stageResults.push(synthesisResult);
390
-
391
- // Generate final response
392
- const response = this.generateResponse(request, stageResults, startTime);
393
-
394
- // Record interaction for learning
395
- if (config.learningEnabled) {
396
- this.learningEngine.recordInteraction(
397
- session.id,
398
- request.query,
399
- response.finalAnswer
400
- );
401
- }
402
-
403
- this.emit('thinking_complete', {
404
- id: request.id,
405
- stage: ThinkingStage.EVALUATION,
406
- timestamp: new Date(),
407
- data: {
408
- response,
409
- stagesExecuted: stageResults.length,
410
- processingTime: Date.now() - startTime
411
- }
412
- } as ThinkingEvent);
413
-
414
- return response;
415
-
416
- } catch (error) {
417
- this.emit('thinking_error', {
418
- id: request.id,
419
- stage: ThinkingStage.EVALUATION,
420
- timestamp: new Date(),
421
- data: { error }
422
- } as ThinkingEvent);
423
-
424
- throw new ThinkingError(
425
- `Thinking process failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
426
- ThinkingStage.EVALUATION,
427
- false,
428
- error instanceof Error ? error : undefined
429
- );
430
- }
431
- }
432
-
433
- // ============================================================================
434
- // STAGE EXECUTORS
435
- // ============================================================================
436
-
437
- private async executeSearch(
438
- request: ThinkingRequest,
439
- config: SequentialThinkingConfig
440
- ): Promise<StageResult> {
441
- const startTime = Date.now();
442
-
443
- const searchResults = await this.searchEngine.search(request.query, {
444
- maxResults: config.maxSearchResults,
445
- sources: [SourceType.WEB, SourceType.KNOWLEDGE_BASE]
446
- });
447
-
448
- return {
449
- stage: ThinkingStage.SEARCH,
450
- status: TaskStatus.COMPLETED,
451
- input: { query: request.query },
452
- output: { results: searchResults, count: searchResults.length },
453
- processingTime: Date.now() - startTime,
454
- confidence: searchResults.length > 0 ? searchResults[0].credibility : 0
455
- };
456
- }
457
-
458
- private async executeAnalysis(
459
- request: ThinkingRequest,
460
- previousResults: StageResult[],
461
- config: SequentialThinkingConfig
462
- ): Promise<StageResult> {
463
- const startTime = Date.now();
464
-
465
- const searchResult = previousResults.find(r => r.stage === ThinkingStage.SEARCH);
466
- const content = searchResult ?
467
- (searchResult.output as any).results.map((r: SearchResult) => r.snippet).join(' ') :
468
- request.query;
469
-
470
- const analysisTypes: AnalysisType[] = config.analysisDepth === 'deep' ?
471
- ['sentiment', 'entity', 'topic', 'keyword', 'summary', 'fact_check'] :
472
- config.analysisDepth === 'surface' ?
473
- ['summary', 'keyword'] :
474
- ['sentiment', 'topic', 'summary'];
475
-
476
- const analysisResults = await this.analysisEngine.analyze(content, {
477
- types: analysisTypes,
478
- depth: config.analysisDepth,
479
- context: request.context
480
- });
481
-
482
- const avgConfidence = analysisResults.reduce((sum, r) => sum + r.confidence, 0) /
483
- analysisResults.length;
484
-
485
- return {
486
- stage: ThinkingStage.ANALYSIS,
487
- status: TaskStatus.COMPLETED,
488
- input: { content: content.substring(0, 200) },
489
- output: { results: analysisResults },
490
- processingTime: Date.now() - startTime,
491
- confidence: avgConfidence
492
- };
493
- }
494
-
495
- private async executeReasoning(
496
- request: ThinkingRequest,
497
- previousResults: StageResult[],
498
- config: SequentialThinkingConfig
499
- ): Promise<StageResult> {
500
- const startTime = Date.now();
501
-
502
- const reasoningType = this.inferReasoningType(request.query);
503
- const maxSteps = config.reasoningComplexity === 'complex' ? 7 :
504
- config.reasoningComplexity === 'simple' ? 3 : 5;
505
-
506
- const reasoningSession = await this.reasoningEngine.reason(request.query, {
507
- type: reasoningType,
508
- maxSteps,
509
- generateCOT: true
510
- });
511
-
512
- return {
513
- stage: ThinkingStage.REASONING,
514
- status: TaskStatus.COMPLETED,
515
- input: { problem: request.query },
516
- output: {
517
- session: reasoningSession,
518
- conclusion: reasoningSession.conclusion,
519
- steps: reasoningSession.steps.length
520
- },
521
- processingTime: Date.now() - startTime,
522
- confidence: reasoningSession.confidence
523
- };
524
- }
525
-
526
- private async executeLearning(
527
- request: ThinkingRequest,
528
- previousResults: StageResult[],
529
- config: SequentialThinkingConfig
530
- ): Promise<StageResult> {
531
- const startTime = Date.now();
532
-
533
- // Get relevant context
534
- const context = this.learningEngine.getOrCreateContext(request.id);
535
- const relevantContext = this.learningEngine.getRelevantContext(request.id, request.query);
536
-
537
- return {
538
- stage: ThinkingStage.LEARNING,
539
- status: TaskStatus.COMPLETED,
540
- input: { query: request.query },
541
- output: {
542
- context,
543
- relevantInteractions: relevantContext.interactions.length,
544
- relevantPatterns: relevantContext.patterns.length,
545
- relevantKnowledge: relevantContext.knowledge.length
546
- },
547
- processingTime: Date.now() - startTime,
548
- confidence: relevantContext.patterns.length > 0 ? 0.8 : 0.5
549
- };
550
- }
551
-
552
- private async executePlanning(
553
- request: ThinkingRequest,
554
- previousResults: StageResult[],
555
- config: SequentialThinkingConfig
556
- ): Promise<StageResult> {
557
- const startTime = Date.now();
558
-
559
- const plan = this.planningEngine.createPlan(request.query, {
560
- resources: [],
561
- deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days
562
- });
563
-
564
- return {
565
- stage: ThinkingStage.PLANNING,
566
- status: TaskStatus.COMPLETED,
567
- input: { goal: request.query },
568
- output: {
569
- plan,
570
- taskCount: plan.tasks.length,
571
- estimatedDuration: plan.tasks.reduce((sum, t) => sum + t.estimatedDuration, 0)
572
- },
573
- processingTime: Date.now() - startTime,
574
- confidence: 0.75
575
- };
576
- }
577
-
578
- private async executeCreativity(
579
- request: ThinkingRequest,
580
- previousResults: StageResult[],
581
- config: SequentialThinkingConfig
582
- ): Promise<StageResult> {
583
- const startTime = Date.now();
584
-
585
- const techniques: CreativityTechnique[] = config.creativityLevel === 'adventurous' ?
586
- ['brainstorming', 'scamper', 'six_thinking_hats', 'lateral_thinking', 'analogy'] :
587
- config.creativityLevel === 'conservative' ?
588
- ['brainstorming'] :
589
- ['brainstorming', 'scamper', 'analogy'];
590
-
591
- const creativeSession = await this.creativityEngine.startSession(request.query, {
592
- techniques,
593
- ideaCount: 15
594
- });
595
-
596
- return {
597
- stage: ThinkingStage.CREATIVITY,
598
- status: TaskStatus.COMPLETED,
599
- input: { prompt: request.query },
600
- output: {
601
- session: creativeSession,
602
- ideaCount: creativeSession.ideas.length,
603
- connectionCount: creativeSession.connections.length,
604
- topIdeas: creativeSession.convergentPhase.selectedIdeas
605
- },
606
- processingTime: Date.now() - startTime,
607
- confidence: creativeSession.ideas.length > 5 ? 0.8 : 0.5
608
- };
609
- }
610
-
611
- private async executeSynthesis(
612
- request: ThinkingRequest,
613
- stageResults: StageResult[],
614
- config: SequentialThinkingConfig
615
- ): Promise<StageResult> {
616
- const startTime = Date.now();
617
-
618
- const searchResults = (stageResults.find(r => r.stage === ThinkingStage.SEARCH)?.output as any)?.results || [];
619
- const analysisResults = (stageResults.find(r => r.stage === ThinkingStage.ANALYSIS)?.output as any)?.results || [];
620
- const reasoningSession = (stageResults.find(r => r.stage === ThinkingStage.REASONING)?.output as any)?.session;
621
- const creativeSession = (stageResults.find(r => r.stage === ThinkingStage.CREATIVITY)?.output as any)?.session;
622
-
623
- const synthesis = this.synthesisEngine.synthesize(
624
- request.query,
625
- searchResults,
626
- analysisResults,
627
- reasoningSession,
628
- creativeSession
629
- );
630
-
631
- return {
632
- stage: ThinkingStage.SYNTHESIS,
633
- status: TaskStatus.COMPLETED,
634
- input: { query: request.query },
635
- output: { synthesis },
636
- processingTime: Date.now() - startTime,
637
- confidence: synthesis.confidence
638
- };
639
- }
640
-
641
- // ============================================================================
642
- // RESPONSE GENERATION
643
- // ============================================================================
644
-
645
- private generateResponse(
646
- request: ThinkingRequest,
647
- stageResults: StageResult[],
648
- startTime: number
649
- ): ThinkingResponse {
650
- const synthesisResult = stageResults.find(r => r.stage === ThinkingStage.SYNTHESIS);
651
- const synthesis = (synthesisResult?.output as any)?.synthesis as SynthesisResult;
652
-
653
- const reasoningResult = stageResults.find(r => r.stage === ThinkingStage.REASONING);
654
- const reasoning = (reasoningResult?.output as any)?.session as ReasoningSession;
655
-
656
- const creativeResult = stageResults.find(r => r.stage === ThinkingStage.CREATIVITY);
657
- const creative = (creativeResult?.output as any)?.session as CreativeSession;
658
-
659
- // Build final answer
660
- const parts: string[] = [];
661
-
662
- // Add synthesis summary
663
- if (synthesis) {
664
- parts.push(synthesis.summary);
665
- parts.push('');
666
- parts.push('Key Insights:');
667
- synthesis.keyInsights.forEach((insight, i) => {
668
- parts.push(`${i + 1}. ${insight}`);
669
- });
670
- }
671
-
672
- // Add reasoning conclusion
673
- if (reasoning?.conclusion) {
674
- parts.push('');
675
- parts.push('Reasoning:');
676
- parts.push(reasoning.conclusion);
677
- }
678
-
679
- // Add creative insights
680
- if (creative) {
681
- parts.push('');
682
- parts.push('Creative Perspectives:');
683
- const topIdeas = creative.ideas
684
- .sort((a, b) => (b.novelty + b.feasibility + b.impact) - (a.novelty + a.feasibility + a.impact))
685
- .slice(0, 3);
686
-
687
- topIdeas.forEach((idea, i) => {
688
- parts.push(`${i + 1}. ${idea.content.substring(0, 100)}...`);
689
- });
690
- }
691
-
692
- // Add recommendations
693
- if (synthesis?.recommendations) {
694
- parts.push('');
695
- parts.push('Recommendations:');
696
- synthesis.recommendations.forEach((rec, i) => {
697
- parts.push(`${i + 1}. ${rec.action} (Confidence: ${Math.round(rec.confidence * 100)}%)`);
698
- });
699
- }
700
-
701
- const finalAnswer = parts.join('\n');
702
-
703
- // Calculate metadata
704
- const searchResult = stageResults.find(r => r.stage === ThinkingStage.SEARCH);
705
- const sourcesUsed = ((searchResult?.output as any)?.results as SearchResult[] || []).length;
706
-
707
- const reasoningSteps = reasoning?.steps.length || 0;
708
- const ideasGenerated = creative?.ideas.length || 0;
709
-
710
- const planningResult = stageResults.find(r => r.stage === ThinkingStage.PLANNING);
711
- const tasksCreated = ((planningResult?.output as any)?.plan as Plan)?.tasks.length || 0;
712
-
713
- const metadata: ResponseMetadata = {
714
- sourcesUsed,
715
- reasoningSteps,
716
- ideasGenerated,
717
- tasksCreated,
718
- knowledgeNodesAccessed: 0
719
- };
720
-
721
- // Calculate overall confidence
722
- const confidenceScores = stageResults.map(r => r.confidence).filter(c => c > 0);
723
- const overallConfidence = confidenceScores.length > 0 ?
724
- confidenceScores.reduce((sum, c) => sum + c, 0) / confidenceScores.length :
725
- 0.5;
726
-
727
- return {
728
- id: `response_${Date.now()}`,
729
- requestId: request.id,
730
- stages: stageResults,
731
- finalAnswer,
732
- confidence: overallConfidence,
733
- processingTime: Date.now() - startTime,
734
- metadata,
735
- timestamp: new Date()
736
- };
737
- }
738
-
739
- // ============================================================================
740
- // UTILITY METHODS
741
- // ============================================================================
742
-
743
- private getOrCreateSession(request: ThinkingRequest): ThinkingSession {
744
- if (this.sessions.has(request.id)) {
745
- return this.sessions.get(request.id)!;
746
- }
747
-
748
- const session: ThinkingSession = {
749
- id: request.id,
750
- requests: [request],
751
- responses: [],
752
- context: this.learningEngine.getOrCreateContext(request.id),
753
- startTime: new Date(),
754
- lastActivity: new Date()
755
- };
756
-
757
- this.sessions.set(request.id, session);
758
- return session;
759
- }
760
-
761
- private shouldExecuteStage(request: ThinkingRequest, stage: ThinkingStage): boolean {
762
- if (!request.preferredStages) return true;
763
- return request.preferredStages.length === 0 || request.preferredStages.includes(stage);
764
- }
765
-
766
- private isPlanningRequest(request: ThinkingRequest): boolean {
767
- const planningKeywords = ['plan', 'build', 'create', 'develop', 'implement', 'project', 'strategy'];
768
- return planningKeywords.some(kw => request.query.toLowerCase().includes(kw));
769
- }
770
-
771
- private inferReasoningType(query: string): ReasoningType {
772
- const queryLower = query.toLowerCase();
773
-
774
- if (queryLower.includes('why') || queryLower.includes('because')) {
775
- return ReasoningType.CAUSAL;
776
- }
777
- if (queryLower.includes('what if') || queryLower.includes('suppose')) {
778
- return ReasoningType.COUNTERFACTUAL;
779
- }
780
- if (queryLower.includes('similar') || queryLower.includes('like')) {
781
- return ReasoningType.ANALOGICAL;
782
- }
783
- if (queryLower.includes('pattern') || queryLower.includes('trend')) {
784
- return ReasoningType.INDUCTIVE;
785
- }
786
- if (queryLower.includes('best explanation') || queryLower.includes('probably')) {
787
- return ReasoningType.ABDUCTIVE;
788
- }
789
-
790
- return ReasoningType.DEDUCTIVE;
791
- }
792
-
793
- // ============================================================================
794
- // PUBLIC API METHODS
795
- // ============================================================================
796
-
797
- /**
798
- * Quick search and answer
799
- */
800
- async quickSearch(query: string): Promise<ThinkingResponse> {
801
- return this.think({
802
- id: `quick_${Date.now()}`,
803
- query,
804
- preferredStages: [ThinkingStage.SEARCH, ThinkingStage.ANALYSIS, ThinkingStage.SYNTHESIS],
805
- config: {
806
- analysisDepth: 'surface',
807
- reasoningComplexity: 'simple',
808
- learningEnabled: false,
809
- creativityLevel: 'conservative'
810
- }
811
- });
812
- }
813
-
814
- /**
815
- * Deep analysis with all stages
816
- */
817
- async deepAnalysis(query: string, context?: string): Promise<ThinkingResponse> {
818
- return this.think({
819
- id: `deep_${Date.now()}`,
820
- query,
821
- context,
822
- config: {
823
- analysisDepth: 'deep',
824
- reasoningComplexity: 'complex',
825
- learningEnabled: true,
826
- creativityLevel: 'adventurous',
827
- planningDetail: 'granular'
828
- }
829
- });
830
- }
831
-
832
- /**
833
- * Creative problem solving
834
- */
835
- async creativeSolve(problem: string): Promise<ThinkingResponse> {
836
- return this.think({
837
- id: `creative_${Date.now()}`,
838
- query: problem,
839
- preferredStages: [
840
- ThinkingStage.SEARCH,
841
- ThinkingStage.ANALYSIS,
842
- ThinkingStage.REASONING,
843
- ThinkingStage.CREATIVITY,
844
- ThinkingStage.SYNTHESIS
845
- ],
846
- config: {
847
- creativityLevel: 'adventurous',
848
- analysisDepth: 'moderate'
849
- }
850
- });
851
- }
852
-
853
- /**
854
- * Create a plan for a goal
855
- */
856
- async createPlan(goal: string, options?: { resources?: Resource[]; deadline?: Date }): Promise<Plan> {
857
- return this.planningEngine.createPlan(goal, options);
858
- }
859
-
860
- /**
861
- * Update config
862
- */
863
- updateConfig(config: Partial<SequentialThinkingConfig>): void {
864
- this.config = { ...this.config, ...config };
865
- }
866
-
867
- /**
868
- * Get session history
869
- */
870
- getSession(sessionId: string): ThinkingSession | undefined {
871
- return this.sessions.get(sessionId);
872
- }
873
-
874
- /**
875
- * Get all sessions
876
- */
877
- getAllSessions(): ThinkingSession[] {
878
- return Array.from(this.sessions.values());
879
- }
880
-
881
- /**
882
- * Export knowledge graph
883
- */
884
- exportKnowledgeGraph(): string {
885
- return this.learningEngine.exportKnowledgeGraph();
886
- }
887
-
888
- /**
889
- * Import knowledge graph
890
- */
891
- importKnowledgeGraph(json: string): void {
892
- this.learningEngine.importKnowledgeGraph(json);
893
- }
894
- }
895
-
896
- // ============================================================================
897
- // EXPORT SINGLETON INSTANCE
898
- // ============================================================================
899
-
900
- export const thinkingEngine = new SequentialThinkingEngine();
901
-
902
- // ============================================================================
903
- // EXAMPLE USAGE
904
- // ============================================================================
905
-
906
- /*
907
- // Basic usage
908
- const response = await thinkingEngine.think({
909
- id: 'request_1',
910
- query: 'What are the implications of quantum computing for cybersecurity?',
911
- config: {
912
- analysisDepth: 'deep',
913
- reasoningComplexity: 'complex'
914
- }
915
- });
916
-
917
- console.log(response.finalAnswer);
918
- console.log(`Confidence: ${response.confidence}`);
919
- console.log(`Processing time: ${response.processingTime}ms`);
920
-
921
- // Quick search
922
- const quick = await thinkingEngine.quickSearch('Latest AI trends 2024');
923
-
924
- // Deep analysis
925
- const deep = await thinkingEngine.deepAnalysis(
926
- 'How will climate change affect global food security?',
927
- 'Focus on agricultural impacts'
928
- );
929
-
930
- // Creative problem solving
931
- const creative = await thinkingEngine.creativeSolve(
932
- 'How can we make public transportation more appealing?'
933
- );
934
-
935
- // Create a plan
936
- const plan = await thinkingEngine.createPlan(
937
- 'Launch a sustainable fashion brand',
938
- {
939
- deadline: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000) // 6 months
940
- }
941
- );
942
-
943
- // Listen to events
944
- thinkingEngine.on('thinking_complete', (event) => {
945
- console.log(`Thinking completed: ${event.data.processingTime}ms`);
946
- });
947
- */