gthinking 1.3.0 → 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 -250
  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 -38
  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 -720
  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 -62
  231. package/dist/planning.d.ts.map +0 -1
  232. package/dist/planning.js +0 -886
  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 -1009
  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 -1101
  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 -43
  270. package/types.ts +0 -6
  271. /package/dist/{server.d.ts → mcp/server.d.ts} +0 -0
package/dist/engine.js DELETED
@@ -1,720 +0,0 @@
1
- "use strict";
2
- /**
3
- * Sequential Thinking Engine
4
- * Main orchestrator that integrates all thinking modules
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.thinkingEngine = exports.SequentialThinkingEngine = void 0;
8
- const types_1 = require("./types");
9
- const events_1 = require("events");
10
- // Import all engines
11
- const search_discovery_1 = require("./search-discovery");
12
- const analysis_1 = require("./analysis");
13
- const reasoning_1 = require("./reasoning");
14
- const learning_1 = require("./learning");
15
- const planning_1 = require("./planning");
16
- const creativity_1 = require("./creativity");
17
- // ============================================================================
18
- // SYNTHESIS ENGINE
19
- // ============================================================================
20
- class SynthesisEngine {
21
- synthesize(query, searchResults, analysisResults, reasoningSession, creativeSession) {
22
- // Extract key insights from each component
23
- const insights = this.extractInsights(searchResults, analysisResults, reasoningSession, creativeSession);
24
- // Generate summary
25
- const summary = this.generateSummary(query, insights);
26
- // Generate recommendations
27
- const recommendations = this.generateRecommendations(query, insights, reasoningSession);
28
- // Identify gaps and uncertainties
29
- const gaps = this.identifyGaps(searchResults, analysisResults);
30
- const uncertainties = this.identifyUncertainties(reasoningSession);
31
- // Generate Devil's Advocate critique
32
- const critique = this.generateCritique(query, insights, recommendations, uncertainties);
33
- // Calculate confidence
34
- const confidence = this.calculateSynthesisConfidence(searchResults, analysisResults, reasoningSession);
35
- return {
36
- id: `synthesis_${Date.now()}`,
37
- sources: [
38
- ...searchResults.map(r => r.url),
39
- reasoningSession ? `reasoning_${reasoningSession.id}` : 'reasoning_skipped'
40
- ],
41
- summary,
42
- keyInsights: insights,
43
- recommendations,
44
- confidence,
45
- gaps,
46
- uncertainties,
47
- critique
48
- };
49
- }
50
- generateCritique(query, insights, recommendations, uncertainties) {
51
- const parts = [];
52
- parts.push(`Devil's Advocate Review for: "${query}"`);
53
- if (uncertainties.length > 0) {
54
- parts.push('The proposed conclusion relies on uncertain premises:');
55
- uncertainties.slice(0, 3).forEach(u => parts.push(`- ${u}`));
56
- }
57
- else {
58
- parts.push('The reasoning appears consistent, but consider if key assumptions were inverted.');
59
- }
60
- if (recommendations.length > 0) {
61
- parts.push(`Counter-point to primary recommendation ("${recommendations[0].action}"):`);
62
- parts.push(`- Consider that ${recommendations[0].risks.join(' or ')} might be underestimated.`);
63
- parts.push('- What if the opposite approach was taken?');
64
- }
65
- if (insights.length < 3) {
66
- parts.push('Warning: limited insights generated. Conclusion may be premature.');
67
- }
68
- return parts.join('\n');
69
- }
70
- extractInsights(searchResults, analysisResults, reasoningSession, creativeSession) {
71
- const insights = [];
72
- // From search
73
- if (searchResults.length > 0) {
74
- const topResult = searchResults[0];
75
- insights.push(`Key finding from research: ${topResult.snippet.substring(0, 100)}...`);
76
- }
77
- // From analysis
78
- analysisResults.forEach(result => {
79
- result.findings.forEach(finding => {
80
- if (finding.confidence > 0.7) {
81
- insights.push(`${result.type}: ${JSON.stringify(finding.value).substring(0, 100)}`);
82
- }
83
- });
84
- });
85
- // From reasoning
86
- if (reasoningSession && reasoningSession.steps.length > 0) {
87
- const lastStep = reasoningSession.steps[reasoningSession.steps.length - 1];
88
- insights.push(`Reasoning conclusion: ${lastStep.inference}`);
89
- }
90
- // From creativity
91
- if (creativeSession) {
92
- const topIdeas = creativeSession.ideas
93
- .sort((a, b) => (b.novelty + b.feasibility + b.impact) - (a.novelty + a.feasibility + a.impact))
94
- .slice(0, 2);
95
- topIdeas.forEach(idea => {
96
- insights.push(`Creative insight: ${idea.content.substring(0, 80)}...`);
97
- });
98
- }
99
- return insights;
100
- }
101
- generateSummary(query, insights) {
102
- return `Analysis of "${query}" reveals ${insights.length} key insights. ` +
103
- `The synthesis combines research findings, logical reasoning, and creative exploration ` +
104
- `to provide a comprehensive understanding of the topic.`;
105
- }
106
- generateRecommendations(query, insights, reasoningSession) {
107
- const recommendations = [];
108
- // Based on reasoning
109
- if (reasoningSession && reasoningSession.conclusion) {
110
- recommendations.push({
111
- id: `rec_${Date.now()}_1`,
112
- action: `Proceed with approach suggested by ${reasoningSession.type} reasoning`,
113
- rationale: reasoningSession.conclusion,
114
- priority: reasoningSession.confidence > 0.7 ? 1 : 2,
115
- expectedOutcome: 'Resolution based on logical analysis',
116
- risks: ['Reasoning assumptions may not hold'],
117
- confidence: reasoningSession.confidence
118
- });
119
- }
120
- // General recommendations
121
- recommendations.push({
122
- id: `rec_${Date.now()}_2`,
123
- action: 'Gather additional data to validate findings',
124
- rationale: 'More information increases confidence',
125
- priority: 3,
126
- expectedOutcome: 'Improved decision quality',
127
- risks: ['Time delay'],
128
- confidence: 0.8
129
- });
130
- return recommendations;
131
- }
132
- identifyGaps(searchResults, analysisResults) {
133
- const gaps = [];
134
- if (searchResults.length < 5) {
135
- gaps.push('Limited research coverage');
136
- }
137
- const lowConfidenceAnalysis = analysisResults.filter(r => r.confidence < 0.5);
138
- if (lowConfidenceAnalysis.length > 0) {
139
- gaps.push('Some analyses have low confidence');
140
- }
141
- return gaps;
142
- }
143
- identifyUncertainties(reasoningSession) {
144
- const uncertainties = [];
145
- if (reasoningSession) {
146
- reasoningSession.steps.forEach(step => {
147
- if (step.confidence < 0.7) {
148
- uncertainties.push(`Step ${step.stepNumber}: ${step.inference}`);
149
- }
150
- });
151
- }
152
- return uncertainties;
153
- }
154
- calculateSynthesisConfidence(searchResults, analysisResults, reasoningSession) {
155
- const factors = [
156
- searchResults.length > 0 ? searchResults[0].credibility : 0,
157
- analysisResults.length > 0 ?
158
- analysisResults.reduce((sum, r) => sum + r.confidence, 0) / analysisResults.length : 0,
159
- ];
160
- if (reasoningSession) {
161
- factors.push(reasoningSession.confidence);
162
- }
163
- return factors.reduce((sum, f) => sum + f, 0) / factors.length;
164
- }
165
- }
166
- class SequentialThinkingEngine extends events_1.EventEmitter {
167
- constructor(config = {}, deps = {}) {
168
- super();
169
- this.sessions = new Map();
170
- this.config = {
171
- maxSearchResults: 10,
172
- analysisDepth: 'moderate',
173
- reasoningComplexity: 'moderate',
174
- learningEnabled: true,
175
- creativityLevel: 'balanced',
176
- planningDetail: 'detailed',
177
- timeout: 60000,
178
- retryAttempts: 3,
179
- ...config
180
- };
181
- // Initialize all engines (inject or default)
182
- this.searchEngine = deps.searchEngine || new search_discovery_1.SearchDiscoveryEngine();
183
- this.analysisEngine = deps.analysisEngine || new analysis_1.AnalysisEngine();
184
- this.reasoningEngine = deps.reasoningEngine || new reasoning_1.ReasoningEngine();
185
- this.learningEngine = deps.learningEngine || new learning_1.LearningEngine();
186
- this.planningEngine = deps.planningEngine || new planning_1.PlanningEngine();
187
- this.creativityEngine = deps.creativityEngine || new creativity_1.CreativityEngine();
188
- // Synthesis engine is internal for now, but could be injected too
189
- this.synthesisEngine = new SynthesisEngine();
190
- // Set up event forwarding
191
- this.setupEventForwarding();
192
- }
193
- setupEventForwarding() {
194
- // Forward events from all engines
195
- const engines = [
196
- this.searchEngine,
197
- this.analysisEngine,
198
- this.reasoningEngine,
199
- this.learningEngine,
200
- this.planningEngine,
201
- this.creativityEngine
202
- ];
203
- engines.forEach(engine => {
204
- engine.on('*', (event) => {
205
- this.emit(event.type, event);
206
- });
207
- });
208
- }
209
- /**
210
- * Process a thinking request through all stages
211
- */
212
- async think(request) {
213
- const startTime = Date.now();
214
- const stageResults = [];
215
- // Create or get session
216
- const session = this.getOrCreateSession(request);
217
- // Dynamic Pipeline: Determine stages if not explicitly provided
218
- if (!request.preferredStages || request.preferredStages.length === 0) {
219
- request.preferredStages = this.planningEngine.determineThinkingStages(request.query);
220
- this.emit('planning_dynamic', {
221
- id: request.id,
222
- stage: types_1.ThinkingStage.PLANNING,
223
- timestamp: new Date(),
224
- data: {
225
- message: 'Dynamic pipeline generated',
226
- stages: request.preferredStages
227
- }
228
- });
229
- }
230
- // Merge config
231
- const config = { ...this.config, ...request.config };
232
- this.emit('thinking_start', {
233
- id: request.id,
234
- stage: types_1.ThinkingStage.SEARCH,
235
- timestamp: new Date(),
236
- data: { query: request.query }
237
- });
238
- try {
239
- // Stage 1: Search & Discovery
240
- if (this.shouldExecuteStage(request, types_1.ThinkingStage.SEARCH)) {
241
- const searchResult = await this.executeSearch(request, config);
242
- stageResults.push(searchResult);
243
- }
244
- // Stage 2: Analysis
245
- if (this.shouldExecuteStage(request, types_1.ThinkingStage.ANALYSIS)) {
246
- const analysisResult = await this.executeAnalysis(request, stageResults, config);
247
- stageResults.push(analysisResult);
248
- }
249
- // Stage 3: Reasoning
250
- if (this.shouldExecuteStage(request, types_1.ThinkingStage.REASONING)) {
251
- const reasoningResult = await this.executeReasoning(request, stageResults, config);
252
- stageResults.push(reasoningResult);
253
- }
254
- // Stage 4: Learning (context enrichment)
255
- if (config.learningEnabled && this.shouldExecuteStage(request, types_1.ThinkingStage.LEARNING)) {
256
- const learningResult = await this.executeLearning(request, stageResults, config);
257
- stageResults.push(learningResult);
258
- }
259
- // Stage 5: Planning (if applicable)
260
- if (this.shouldExecuteStage(request, types_1.ThinkingStage.PLANNING) && this.isPlanningRequest(request)) {
261
- const planningResult = await this.executePlanning(request, stageResults, config);
262
- stageResults.push(planningResult);
263
- }
264
- // Stage 6: Creativity
265
- if (this.shouldExecuteStage(request, types_1.ThinkingStage.CREATIVITY)) {
266
- const creativityResult = await this.executeCreativity(request, stageResults, config);
267
- stageResults.push(creativityResult);
268
- }
269
- // Stage 7: Synthesis
270
- const synthesisResult = await this.executeSynthesis(request, stageResults, config);
271
- stageResults.push(synthesisResult);
272
- // Generate final response
273
- const response = this.generateResponse(request, stageResults, startTime);
274
- // Record interaction for learning
275
- if (config.learningEnabled) {
276
- this.learningEngine.recordInteraction(session.id, request.query, response.finalAnswer);
277
- }
278
- this.emit('thinking_complete', {
279
- id: request.id,
280
- stage: types_1.ThinkingStage.EVALUATION,
281
- timestamp: new Date(),
282
- data: {
283
- response,
284
- stagesExecuted: stageResults.length,
285
- processingTime: Date.now() - startTime
286
- }
287
- });
288
- return response;
289
- }
290
- catch (error) {
291
- this.emit('thinking_error', {
292
- id: request.id,
293
- stage: types_1.ThinkingStage.EVALUATION,
294
- timestamp: new Date(),
295
- data: { error }
296
- });
297
- throw new types_1.ThinkingError(`Thinking process failed: ${error instanceof Error ? error.message : 'Unknown error'}`, types_1.ThinkingStage.EVALUATION, false, error instanceof Error ? error : undefined);
298
- }
299
- }
300
- // ============================================================================
301
- // STAGE EXECUTORS
302
- // ============================================================================
303
- async executeSearch(request, config) {
304
- const startTime = Date.now();
305
- const searchResults = await this.searchEngine.search(request.query, {
306
- maxResults: config.maxSearchResults,
307
- sources: [types_1.SourceType.WEB, types_1.SourceType.KNOWLEDGE_BASE]
308
- });
309
- return {
310
- stage: types_1.ThinkingStage.SEARCH,
311
- status: types_1.TaskStatus.COMPLETED,
312
- input: { query: request.query },
313
- output: { results: searchResults, count: searchResults.length },
314
- processingTime: Date.now() - startTime,
315
- confidence: searchResults.length > 0 ? searchResults[0].credibility : 0
316
- };
317
- }
318
- async executeAnalysis(request, previousResults, config) {
319
- const startTime = Date.now();
320
- const searchResult = previousResults.find(r => r.stage === types_1.ThinkingStage.SEARCH);
321
- const content = searchResult ?
322
- searchResult.output.results.map((r) => r.snippet).join(' ') :
323
- request.query;
324
- const analysisTypes = config.analysisDepth === 'deep' ?
325
- ['sentiment', 'entity', 'topic', 'keyword', 'summary', 'fact_check'] :
326
- config.analysisDepth === 'surface' ?
327
- ['summary', 'keyword'] :
328
- ['sentiment', 'topic', 'summary'];
329
- const analysisResults = await this.analysisEngine.analyze(content, {
330
- types: analysisTypes,
331
- depth: config.analysisDepth,
332
- context: request.context
333
- });
334
- const avgConfidence = analysisResults.reduce((sum, r) => sum + r.confidence, 0) /
335
- analysisResults.length;
336
- return {
337
- stage: types_1.ThinkingStage.ANALYSIS,
338
- status: types_1.TaskStatus.COMPLETED,
339
- input: { content: content.substring(0, 200) },
340
- output: { results: analysisResults },
341
- processingTime: Date.now() - startTime,
342
- confidence: avgConfidence
343
- };
344
- }
345
- async executeReasoning(request, previousResults, config) {
346
- const startTime = Date.now();
347
- const reasoningType = this.inferReasoningType(request.query);
348
- const maxSteps = config.reasoningComplexity === 'complex' ? 7 :
349
- config.reasoningComplexity === 'simple' ? 3 : 5;
350
- const reasoningSession = await this.reasoningEngine.reason(request.query, {
351
- type: reasoningType,
352
- maxSteps,
353
- generateCOT: true
354
- });
355
- return {
356
- stage: types_1.ThinkingStage.REASONING,
357
- status: types_1.TaskStatus.COMPLETED,
358
- input: { problem: request.query },
359
- output: {
360
- session: reasoningSession,
361
- conclusion: reasoningSession.conclusion,
362
- steps: reasoningSession.steps.length
363
- },
364
- processingTime: Date.now() - startTime,
365
- confidence: reasoningSession.confidence
366
- };
367
- }
368
- async executeLearning(request, previousResults, config) {
369
- const startTime = Date.now();
370
- // Get relevant context
371
- const context = this.learningEngine.getOrCreateContext(request.id);
372
- const relevantContext = this.learningEngine.getRelevantContext(request.id, request.query);
373
- return {
374
- stage: types_1.ThinkingStage.LEARNING,
375
- status: types_1.TaskStatus.COMPLETED,
376
- input: { query: request.query },
377
- output: {
378
- context,
379
- relevantInteractions: relevantContext.interactions.length,
380
- relevantPatterns: relevantContext.patterns.length,
381
- relevantKnowledge: relevantContext.knowledge.length
382
- },
383
- processingTime: Date.now() - startTime,
384
- confidence: relevantContext.patterns.length > 0 ? 0.8 : 0.5
385
- };
386
- }
387
- async executePlanning(request, previousResults, config) {
388
- const startTime = Date.now();
389
- const plan = this.planningEngine.createPlan(request.query, {
390
- resources: [],
391
- deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days
392
- });
393
- return {
394
- stage: types_1.ThinkingStage.PLANNING,
395
- status: types_1.TaskStatus.COMPLETED,
396
- input: { goal: request.query },
397
- output: {
398
- plan,
399
- taskCount: plan.tasks.length,
400
- estimatedDuration: plan.tasks.reduce((sum, t) => sum + t.estimatedDuration, 0)
401
- },
402
- processingTime: Date.now() - startTime,
403
- confidence: 0.75
404
- };
405
- }
406
- async executeCreativity(request, previousResults, config) {
407
- const startTime = Date.now();
408
- const techniques = config.creativityLevel === 'adventurous' ?
409
- ['brainstorming', 'scamper', 'six_thinking_hats', 'lateral_thinking', 'analogy'] :
410
- config.creativityLevel === 'conservative' ?
411
- ['brainstorming'] :
412
- ['brainstorming', 'scamper', 'analogy'];
413
- const creativeSession = await this.creativityEngine.startSession(request.query, {
414
- techniques,
415
- ideaCount: 15
416
- });
417
- return {
418
- stage: types_1.ThinkingStage.CREATIVITY,
419
- status: types_1.TaskStatus.COMPLETED,
420
- input: { prompt: request.query },
421
- output: {
422
- session: creativeSession,
423
- ideaCount: creativeSession.ideas.length,
424
- connectionCount: creativeSession.connections.length,
425
- topIdeas: creativeSession.convergentPhase.selectedIdeas
426
- },
427
- processingTime: Date.now() - startTime,
428
- confidence: creativeSession.ideas.length > 5 ? 0.8 : 0.5
429
- };
430
- }
431
- async executeSynthesis(request, stageResults, config) {
432
- const startTime = Date.now();
433
- const searchResults = stageResults.find(r => r.stage === types_1.ThinkingStage.SEARCH)?.output?.results || [];
434
- const analysisResults = stageResults.find(r => r.stage === types_1.ThinkingStage.ANALYSIS)?.output?.results || [];
435
- const reasoningSession = stageResults.find(r => r.stage === types_1.ThinkingStage.REASONING)?.output?.session;
436
- const creativeSession = stageResults.find(r => r.stage === types_1.ThinkingStage.CREATIVITY)?.output?.session;
437
- const synthesis = this.synthesisEngine.synthesize(request.query, searchResults, analysisResults, reasoningSession, creativeSession);
438
- return {
439
- stage: types_1.ThinkingStage.SYNTHESIS,
440
- status: types_1.TaskStatus.COMPLETED,
441
- input: { query: request.query },
442
- output: { synthesis },
443
- processingTime: Date.now() - startTime,
444
- confidence: synthesis.confidence
445
- };
446
- }
447
- // ============================================================================
448
- // RESPONSE GENERATION
449
- // ============================================================================
450
- generateResponse(request, stageResults, startTime) {
451
- const synthesisResult = stageResults.find(r => r.stage === types_1.ThinkingStage.SYNTHESIS);
452
- const synthesis = synthesisResult?.output?.synthesis;
453
- const reasoningResult = stageResults.find(r => r.stage === types_1.ThinkingStage.REASONING);
454
- const reasoning = reasoningResult?.output?.session;
455
- const creativeResult = stageResults.find(r => r.stage === types_1.ThinkingStage.CREATIVITY);
456
- const creative = creativeResult?.output?.session;
457
- // Build final answer
458
- const parts = [];
459
- // Add synthesis summary
460
- if (synthesis) {
461
- parts.push(synthesis.summary);
462
- parts.push('');
463
- parts.push('Key Insights:');
464
- synthesis.keyInsights.forEach((insight, i) => {
465
- parts.push(`${i + 1}. ${insight}`);
466
- });
467
- }
468
- // Add reasoning conclusion
469
- if (reasoning?.conclusion) {
470
- parts.push('');
471
- parts.push('Reasoning:');
472
- parts.push(reasoning.conclusion);
473
- }
474
- // Add critique (Devil's Advocate)
475
- if (synthesis?.critique) {
476
- parts.push('');
477
- parts.push('---');
478
- parts.push(synthesis.critique);
479
- parts.push('---');
480
- }
481
- // Add creative insights
482
- if (creative) {
483
- parts.push('');
484
- parts.push('Creative Perspectives:');
485
- const topIdeas = creative.ideas
486
- .sort((a, b) => (b.novelty + b.feasibility + b.impact) - (a.novelty + a.feasibility + a.impact))
487
- .slice(0, 3);
488
- topIdeas.forEach((idea, i) => {
489
- parts.push(`${i + 1}. ${idea.content.substring(0, 100)}...`);
490
- });
491
- }
492
- // Add recommendations
493
- if (synthesis?.recommendations) {
494
- parts.push('');
495
- parts.push('Recommendations:');
496
- synthesis.recommendations.forEach((rec, i) => {
497
- parts.push(`${i + 1}. ${rec.action} (Confidence: ${Math.round(rec.confidence * 100)}%)`);
498
- });
499
- }
500
- const finalAnswer = parts.join('\n');
501
- // Calculate metadata
502
- const searchResult = stageResults.find(r => r.stage === types_1.ThinkingStage.SEARCH);
503
- const sourcesUsed = (searchResult?.output?.results || []).length;
504
- const reasoningSteps = reasoning?.steps.length || 0;
505
- const ideasGenerated = creative?.ideas.length || 0;
506
- const planningResult = stageResults.find(r => r.stage === types_1.ThinkingStage.PLANNING);
507
- const tasksCreated = planningResult?.output?.plan?.tasks.length || 0;
508
- const metadata = {
509
- sourcesUsed,
510
- reasoningSteps,
511
- ideasGenerated,
512
- tasksCreated,
513
- knowledgeNodesAccessed: 0
514
- };
515
- // Calculate overall confidence
516
- const confidenceScores = stageResults.map(r => r.confidence).filter(c => c > 0);
517
- const overallConfidence = confidenceScores.length > 0 ?
518
- confidenceScores.reduce((sum, c) => sum + c, 0) / confidenceScores.length :
519
- 0.5;
520
- return {
521
- id: `response_${Date.now()}`,
522
- requestId: request.id,
523
- stages: stageResults,
524
- finalAnswer,
525
- confidence: overallConfidence,
526
- processingTime: Date.now() - startTime,
527
- metadata,
528
- timestamp: new Date()
529
- };
530
- }
531
- // ============================================================================
532
- // UTILITY METHODS
533
- // ============================================================================
534
- getOrCreateSession(request) {
535
- if (this.sessions.has(request.id)) {
536
- return this.sessions.get(request.id);
537
- }
538
- const session = {
539
- id: request.id,
540
- requests: [request],
541
- responses: [],
542
- context: this.learningEngine.getOrCreateContext(request.id),
543
- startTime: new Date(),
544
- lastActivity: new Date()
545
- };
546
- this.sessions.set(request.id, session);
547
- return session;
548
- }
549
- shouldExecuteStage(request, stage) {
550
- if (!request.preferredStages)
551
- return true;
552
- return request.preferredStages.length === 0 || request.preferredStages.includes(stage);
553
- }
554
- isPlanningRequest(request) {
555
- const planningKeywords = ['plan', 'build', 'create', 'develop', 'implement', 'project', 'strategy'];
556
- return planningKeywords.some(kw => request.query.toLowerCase().includes(kw));
557
- }
558
- inferReasoningType(query) {
559
- const queryLower = query.toLowerCase();
560
- if (queryLower.includes('why') || queryLower.includes('because')) {
561
- return types_1.ReasoningType.CAUSAL;
562
- }
563
- if (queryLower.includes('what if') || queryLower.includes('suppose')) {
564
- return types_1.ReasoningType.COUNTERFACTUAL;
565
- }
566
- if (queryLower.includes('similar') || queryLower.includes('like')) {
567
- return types_1.ReasoningType.ANALOGICAL;
568
- }
569
- if (queryLower.includes('pattern') || queryLower.includes('trend')) {
570
- return types_1.ReasoningType.INDUCTIVE;
571
- }
572
- if (queryLower.includes('best explanation') || queryLower.includes('probably')) {
573
- return types_1.ReasoningType.ABDUCTIVE;
574
- }
575
- return types_1.ReasoningType.DEDUCTIVE;
576
- }
577
- // ============================================================================
578
- // PUBLIC API METHODS
579
- // ============================================================================
580
- /**
581
- * Quick search and answer
582
- */
583
- async quickSearch(query) {
584
- return this.think({
585
- id: `quick_${Date.now()}`,
586
- query,
587
- preferredStages: [types_1.ThinkingStage.SEARCH, types_1.ThinkingStage.ANALYSIS, types_1.ThinkingStage.SYNTHESIS],
588
- config: {
589
- analysisDepth: 'surface',
590
- reasoningComplexity: 'simple',
591
- learningEnabled: false,
592
- creativityLevel: 'conservative'
593
- }
594
- });
595
- }
596
- /**
597
- * Deep analysis with all stages
598
- */
599
- async deepAnalysis(query, context) {
600
- return this.think({
601
- id: `deep_${Date.now()}`,
602
- query,
603
- context,
604
- config: {
605
- analysisDepth: 'deep',
606
- reasoningComplexity: 'complex',
607
- learningEnabled: true,
608
- creativityLevel: 'adventurous',
609
- planningDetail: 'granular'
610
- }
611
- });
612
- }
613
- /**
614
- * Creative problem solving
615
- */
616
- async creativeSolve(problem) {
617
- return this.think({
618
- id: `creative_${Date.now()}`,
619
- query: problem,
620
- preferredStages: [
621
- types_1.ThinkingStage.SEARCH,
622
- types_1.ThinkingStage.ANALYSIS,
623
- types_1.ThinkingStage.REASONING,
624
- types_1.ThinkingStage.CREATIVITY,
625
- types_1.ThinkingStage.SYNTHESIS
626
- ],
627
- config: {
628
- creativityLevel: 'adventurous',
629
- analysisDepth: 'moderate'
630
- }
631
- });
632
- }
633
- /**
634
- * Create a plan for a goal
635
- */
636
- async createPlan(goal, options) {
637
- return this.planningEngine.createPlan(goal, options);
638
- }
639
- /**
640
- * Update config
641
- */
642
- updateConfig(config) {
643
- this.config = { ...this.config, ...config };
644
- }
645
- /**
646
- * Get session history
647
- */
648
- getSession(sessionId) {
649
- return this.sessions.get(sessionId);
650
- }
651
- /**
652
- * Get all sessions
653
- */
654
- getAllSessions() {
655
- return Array.from(this.sessions.values());
656
- }
657
- /**
658
- * Export knowledge graph
659
- */
660
- exportKnowledgeGraph() {
661
- return this.learningEngine.exportKnowledgeGraph();
662
- }
663
- /**
664
- * Import knowledge graph
665
- */
666
- importKnowledgeGraph(json) {
667
- this.learningEngine.importKnowledgeGraph(json);
668
- }
669
- }
670
- exports.SequentialThinkingEngine = SequentialThinkingEngine;
671
- // ============================================================================
672
- // EXPORT SINGLETON INSTANCE
673
- // ============================================================================
674
- exports.thinkingEngine = new SequentialThinkingEngine();
675
- // ============================================================================
676
- // EXAMPLE USAGE
677
- // ============================================================================
678
- /*
679
- // Basic usage
680
- const response = await thinkingEngine.think({
681
- id: 'request_1',
682
- query: 'What are the implications of quantum computing for cybersecurity?',
683
- config: {
684
- analysisDepth: 'deep',
685
- reasoningComplexity: 'complex'
686
- }
687
- });
688
-
689
- console.log(response.finalAnswer);
690
- console.log(`Confidence: ${response.confidence}`);
691
- console.log(`Processing time: ${response.processingTime}ms`);
692
-
693
- // Quick search
694
- const quick = await thinkingEngine.quickSearch('Latest AI trends 2024');
695
-
696
- // Deep analysis
697
- const deep = await thinkingEngine.deepAnalysis(
698
- 'How will climate change affect global food security?',
699
- 'Focus on agricultural impacts'
700
- );
701
-
702
- // Creative problem solving
703
- const creative = await thinkingEngine.creativeSolve(
704
- 'How can we make public transportation more appealing?'
705
- );
706
-
707
- // Create a plan
708
- const plan = await thinkingEngine.createPlan(
709
- 'Launch a sustainable fashion brand',
710
- {
711
- deadline: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000) // 6 months
712
- }
713
- );
714
-
715
- // Listen to events
716
- thinkingEngine.on('thinking_complete', (event) => {
717
- console.log(`Thinking completed: ${event.data.processingTime}ms`);
718
- });
719
- */
720
- //# sourceMappingURL=engine.js.map