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