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/reasoning.js DELETED
@@ -1,845 +0,0 @@
1
- "use strict";
2
- /**
3
- * Reasoning Module
4
- * Advanced logical reasoning with Chain of Thought, hypothesis testing, and multi-step problem solving
5
- */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.reasoningEngine = exports.ReasoningEngine = void 0;
8
- const types_1 = require("./types");
9
- const events_1 = require("events");
10
- const llm_service_1 = require("./llm-service");
11
- class LogicalRulesEngine {
12
- constructor() {
13
- this.rules = new Map();
14
- }
15
- addRule(rule) {
16
- this.rules.set(rule.id, rule);
17
- }
18
- infer(facts) {
19
- const inferences = [];
20
- this.rules.forEach(rule => {
21
- const premisesMet = rule.premises.every(premise => facts.some(fact => this.match(fact, premise)));
22
- if (premisesMet) {
23
- inferences.push({
24
- conclusion: rule.conclusion,
25
- confidence: rule.confidence,
26
- rule
27
- });
28
- }
29
- });
30
- return inferences.sort((a, b) => b.confidence - a.confidence);
31
- }
32
- match(fact, premise) {
33
- // Simple pattern matching - in real implementation use NLP
34
- const factWords = fact.toLowerCase().split(/\s+/);
35
- const premiseWords = premise.toLowerCase().split(/\s+/);
36
- const matchCount = premiseWords.filter(pw => factWords.some(fw => fw.includes(pw) || pw.includes(fw))).length;
37
- return matchCount / premiseWords.length > 0.7;
38
- }
39
- getRulesByDomain(domain) {
40
- return Array.from(this.rules.values()).filter(r => r.domain === domain);
41
- }
42
- }
43
- // ============================================================================
44
- // CHAIN OF THOUGHT GENERATOR
45
- // ============================================================================
46
- class ChainOfThoughtGenerator {
47
- constructor() {
48
- this.thoughtId = 0;
49
- }
50
- generate(question, maxDepth = 5) {
51
- const thoughts = [];
52
- const rootThought = {
53
- id: this.nextThoughtId(),
54
- content: question,
55
- children: [],
56
- depth: 0,
57
- confidence: 1.0,
58
- type: 'question'
59
- };
60
- thoughts.push(rootThought);
61
- // Generate thought chain
62
- this.expandThought(rootThought, thoughts, maxDepth, 0);
63
- // Generate final answer based on thought chain
64
- const finalAnswer = this.synthesizeAnswer(thoughts);
65
- return {
66
- id: `cot_${Date.now()}`,
67
- initialQuestion: question,
68
- thoughts,
69
- finalAnswer,
70
- completeness: this.calculateCompleteness(thoughts)
71
- };
72
- }
73
- expandThought(parent, thoughts, maxDepth, currentDepth) {
74
- if (currentDepth >= maxDepth)
75
- return;
76
- const expansions = this.generateExpansions(parent, currentDepth);
77
- expansions.forEach(expansion => {
78
- const child = {
79
- id: this.nextThoughtId(),
80
- content: expansion.content,
81
- parentId: parent.id,
82
- children: [],
83
- depth: currentDepth + 1,
84
- confidence: expansion.confidence * parent.confidence,
85
- type: expansion.type
86
- };
87
- parent.children.push(child.id);
88
- thoughts.push(child);
89
- // Recursively expand if it's an observation or inference
90
- if (expansion.type === 'observation' || expansion.type === 'inference') {
91
- this.expandThought(child, thoughts, maxDepth, currentDepth + 1);
92
- }
93
- });
94
- }
95
- generateExpansions(thought, depth) {
96
- const expansions = [];
97
- const content = thought.content.toLowerCase();
98
- // Generate contextual expansions based on thought type
99
- if (thought.type === 'question') {
100
- expansions.push({ content: `Let me break down this question into parts.`, type: 'observation', confidence: 0.9 }, { content: `What are the key elements involved?`, type: 'observation', confidence: 0.85 }, { content: `What do I already know about this?`, type: 'observation', confidence: 0.8 });
101
- }
102
- else if (thought.type === 'observation') {
103
- expansions.push({ content: `This suggests that...`, type: 'inference', confidence: 0.75 }, { content: `One implication is...`, type: 'inference', confidence: 0.7 }, { content: `However, we must also consider...`, type: 'observation', confidence: 0.65 });
104
- }
105
- else if (thought.type === 'inference') {
106
- if (depth < 3) {
107
- expansions.push({ content: `Building on this inference...`, type: 'inference', confidence: 0.7 }, { content: `This leads to the conclusion that...`, type: 'conclusion', confidence: 0.8 });
108
- }
109
- else {
110
- expansions.push({ content: `Therefore, we can conclude...`, type: 'conclusion', confidence: 0.85 });
111
- }
112
- }
113
- return expansions;
114
- }
115
- synthesizeAnswer(thoughts) {
116
- const conclusions = thoughts.filter(t => t.type === 'conclusion');
117
- const inferences = thoughts.filter(t => t.type === 'inference');
118
- if (conclusions.length > 0) {
119
- const topConclusion = conclusions.sort((a, b) => b.confidence - a.confidence)[0];
120
- return topConclusion.content + ' Based on the analysis: ' +
121
- inferences.slice(0, 3).map(i => i.content).join('; ') + '.';
122
- }
123
- return 'Based on the analysis: ' + inferences.slice(0, 3).map(i => i.content).join('; ') + '.';
124
- }
125
- calculateCompleteness(thoughts) {
126
- const hasQuestion = thoughts.some(t => t.type === 'question');
127
- const hasObservations = thoughts.some(t => t.type === 'observation');
128
- const hasInferences = thoughts.some(t => t.type === 'inference');
129
- const hasConclusions = thoughts.some(t => t.type === 'conclusion');
130
- const elements = [hasQuestion, hasObservations, hasInferences, hasConclusions];
131
- return elements.filter(Boolean).length / elements.length;
132
- }
133
- nextThoughtId() {
134
- return `thought_${++this.thoughtId}`;
135
- }
136
- }
137
- // ============================================================================
138
- // HYPOTHESIS MANAGER
139
- // ============================================================================
140
- class HypothesisManager {
141
- constructor() {
142
- this.hypotheses = new Map();
143
- }
144
- createHypothesis(statement) {
145
- const hypothesis = {
146
- id: `hypothesis_${Date.now()}`,
147
- statement,
148
- supportingEvidence: [],
149
- contradictingEvidence: [],
150
- tests: [],
151
- status: 'proposed',
152
- confidence: 0.5
153
- };
154
- this.hypotheses.set(hypothesis.id, hypothesis);
155
- return hypothesis;
156
- }
157
- addEvidence(hypothesisId, evidence, supporting) {
158
- const hypothesis = this.hypotheses.get(hypothesisId);
159
- if (!hypothesis)
160
- throw new Error(`Hypothesis ${hypothesisId} not found`);
161
- if (supporting) {
162
- hypothesis.supportingEvidence.push(evidence);
163
- }
164
- else {
165
- hypothesis.contradictingEvidence.push(evidence);
166
- }
167
- this.updateConfidence(hypothesis);
168
- }
169
- addTest(hypothesisId, test) {
170
- const hypothesis = this.hypotheses.get(hypothesisId);
171
- if (!hypothesis)
172
- throw new Error(`Hypothesis ${hypothesisId} not found`);
173
- hypothesis.tests.push(test);
174
- }
175
- runTest(hypothesisId, testId, outcome) {
176
- const hypothesis = this.hypotheses.get(hypothesisId);
177
- if (!hypothesis)
178
- throw new Error(`Hypothesis ${hypothesisId} not found`);
179
- const test = hypothesis.tests.find(t => t.id === testId);
180
- if (!test)
181
- throw new Error(`Test ${testId} not found`);
182
- test.actualOutcome = outcome;
183
- test.passed = outcome === test.expectedOutcome;
184
- this.updateStatus(hypothesis);
185
- }
186
- updateConfidence(hypothesis) {
187
- const supportWeight = hypothesis.supportingEvidence.reduce((sum, e) => sum + e.strength, 0);
188
- const contradictWeight = hypothesis.contradictingEvidence.reduce((sum, e) => sum + e.strength, 0);
189
- const totalWeight = supportWeight + contradictWeight;
190
- if (totalWeight === 0) {
191
- hypothesis.confidence = 0.5;
192
- }
193
- else {
194
- hypothesis.confidence = supportWeight / totalWeight;
195
- }
196
- }
197
- updateStatus(hypothesis) {
198
- const completedTests = hypothesis.tests.filter(t => t.passed !== undefined);
199
- const passedTests = completedTests.filter(t => t.passed);
200
- if (completedTests.length === 0) {
201
- hypothesis.status = 'testing';
202
- }
203
- else if (passedTests.length === completedTests.length && hypothesis.confidence > 0.8) {
204
- hypothesis.status = 'confirmed';
205
- }
206
- else if (passedTests.length === 0 && completedTests.length > 2) {
207
- hypothesis.status = 'rejected';
208
- }
209
- else {
210
- hypothesis.status = 'testing';
211
- }
212
- }
213
- getHypothesis(id) {
214
- return this.hypotheses.get(id);
215
- }
216
- getAllHypotheses() {
217
- return Array.from(this.hypotheses.values());
218
- }
219
- getHypothesesByStatus(status) {
220
- return this.getAllHypotheses().filter(h => h.status === status);
221
- }
222
- }
223
- // ============================================================================
224
- // PROBLEM DECOMPOSITION ENGINE
225
- // ============================================================================
226
- class ProblemDecompositionEngine {
227
- decompose(problem) {
228
- const subProblems = [];
229
- const dependencies = [];
230
- // Analyze problem structure
231
- const problemParts = this.identifyProblemParts(problem);
232
- // Create sub-problems
233
- problemParts.forEach((part, index) => {
234
- const subProblem = {
235
- id: `sub_${index}`,
236
- description: part.description,
237
- difficulty: part.difficulty,
238
- estimatedTime: part.estimatedTime,
239
- prerequisites: [],
240
- status: types_1.TaskStatus.PENDING
241
- };
242
- subProblems.push(subProblem);
243
- });
244
- // Identify dependencies
245
- subProblems.forEach((sub, i) => {
246
- subProblems.forEach((other, j) => {
247
- if (i !== j && this.hasDependency(sub, other)) {
248
- dependencies.push({
249
- from: sub.id,
250
- to: other.id,
251
- type: 'requires'
252
- });
253
- sub.prerequisites.push(other.id);
254
- }
255
- });
256
- });
257
- // Determine solution strategy
258
- const solutionStrategy = this.determineStrategy(subProblems, dependencies);
259
- return {
260
- id: `decomp_${Date.now()}`,
261
- originalProblem: problem,
262
- subProblems,
263
- dependencies,
264
- solutionStrategy
265
- };
266
- }
267
- identifyProblemParts(problem) {
268
- const parts = [];
269
- // Simple decomposition based on keywords
270
- const keywords = {
271
- research: { difficulty: 0.7, time: 120 },
272
- analyze: { difficulty: 0.6, time: 90 },
273
- design: { difficulty: 0.8, time: 180 },
274
- implement: { difficulty: 0.75, time: 240 },
275
- test: { difficulty: 0.5, time: 60 },
276
- optimize: { difficulty: 0.85, time: 150 },
277
- evaluate: { difficulty: 0.55, time: 45 },
278
- plan: { difficulty: 0.4, time: 30 }
279
- };
280
- const problemLower = problem.toLowerCase();
281
- Object.entries(keywords).forEach(([keyword, config]) => {
282
- if (problemLower.includes(keyword)) {
283
- parts.push({
284
- description: `${keyword.charAt(0).toUpperCase() + keyword.slice(1)} phase of the problem`,
285
- difficulty: config.difficulty,
286
- estimatedTime: config.time
287
- });
288
- }
289
- });
290
- // If no specific parts identified, create generic ones
291
- if (parts.length === 0) {
292
- parts.push({ description: 'Understand the problem', difficulty: 0.4, estimatedTime: 30 }, { description: 'Research and gather information', difficulty: 0.6, estimatedTime: 60 }, { description: 'Develop solution approach', difficulty: 0.7, estimatedTime: 90 }, { description: 'Implement the solution', difficulty: 0.75, estimatedTime: 120 }, { description: 'Verify and validate', difficulty: 0.5, estimatedTime: 45 });
293
- }
294
- return parts;
295
- }
296
- hasDependency(sub1, sub2) {
297
- // Check if sub1 requires sub2 based on description
298
- const orderIndicators = {
299
- 'understand': [],
300
- 'research': ['understand'],
301
- 'design': ['research', 'understand'],
302
- 'implement': ['design', 'research'],
303
- 'test': ['implement'],
304
- 'optimize': ['test', 'implement'],
305
- 'evaluate': ['test', 'implement', 'optimize'],
306
- 'plan': ['understand', 'research']
307
- };
308
- const sub1Keywords = Object.keys(orderIndicators).filter(k => sub1.description.toLowerCase().includes(k));
309
- const sub2Keywords = Object.keys(orderIndicators).filter(k => sub2.description.toLowerCase().includes(k));
310
- return sub1Keywords.some(k1 => sub2Keywords.some(k2 => orderIndicators[k1]?.includes(k2)));
311
- }
312
- determineStrategy(subProblems, dependencies) {
313
- const criticalPath = this.findCriticalPath(subProblems, dependencies);
314
- const totalTime = subProblems.reduce((sum, sp) => sum + sp.estimatedTime, 0);
315
- const avgDifficulty = subProblems.reduce((sum, sp) => sum + sp.difficulty, 0) / subProblems.length;
316
- if (avgDifficulty > 0.7) {
317
- return `Divide-and-conquer approach recommended. Tackle critical path first: ${criticalPath.join(' → ')}. Estimated total time: ${totalTime} minutes.`;
318
- }
319
- else if (dependencies.length > subProblems.length) {
320
- return `Sequential approach with careful dependency management. Start with: ${criticalPath[0]}.`;
321
- }
322
- else {
323
- return `Parallel processing possible. Focus on: ${criticalPath.join(', ')}.`;
324
- }
325
- }
326
- findCriticalPath(subProblems, dependencies) {
327
- // Simplified critical path - in real implementation use topological sort
328
- const visited = new Set();
329
- const path = [];
330
- const visit = (subId) => {
331
- if (visited.has(subId))
332
- return;
333
- visited.add(subId);
334
- const prereqs = dependencies
335
- .filter(d => d.to === subId && d.type === 'requires')
336
- .map(d => d.from);
337
- prereqs.forEach(visit);
338
- const sub = subProblems.find(s => s.id === subId);
339
- if (sub)
340
- path.push(sub.description);
341
- };
342
- subProblems.forEach(sp => visit(sp.id));
343
- return path.length > 0 ? path : subProblems.map(s => s.description);
344
- }
345
- }
346
- // ============================================================================
347
- // REASONING ENGINE
348
- // ============================================================================
349
- class ReasoningEngine extends events_1.EventEmitter {
350
- constructor() {
351
- super();
352
- this.sessions = new Map();
353
- this.rulesEngine = new LogicalRulesEngine();
354
- this.cotGenerator = new ChainOfThoughtGenerator();
355
- this.hypothesisManager = new HypothesisManager();
356
- this.decompositionEngine = new ProblemDecompositionEngine();
357
- this.initializeDefaultRules();
358
- }
359
- initializeDefaultRules() {
360
- // Add some default logical rules
361
- this.rulesEngine.addRule({
362
- id: 'rule_cause_effect',
363
- premises: ['A causes B', 'A occurred'],
364
- conclusion: 'B will occur',
365
- confidence: 0.8,
366
- domain: 'causality'
367
- });
368
- this.rulesEngine.addRule({
369
- id: 'rule_generalization',
370
- premises: ['All X are Y', 'Z is X'],
371
- conclusion: 'Z is Y',
372
- confidence: 0.95,
373
- domain: 'logic'
374
- });
375
- this.rulesEngine.addRule({
376
- id: 'rule_analogy',
377
- premises: ['A is similar to B', 'A has property P'],
378
- conclusion: 'B likely has property P',
379
- confidence: 0.7,
380
- domain: 'analogy'
381
- });
382
- }
383
- /**
384
- * Perform reasoning on a problem
385
- */
386
- async reason(problem, options = {}) {
387
- const { type = types_1.ReasoningType.DEDUCTIVE, maxSteps = 5, generateCOT = true } = options;
388
- const sessionId = this.generateId();
389
- const startTime = Date.now();
390
- const session = {
391
- id: sessionId,
392
- problem,
393
- type,
394
- steps: [],
395
- confidence: 0,
396
- startTime: new Date()
397
- };
398
- this.sessions.set(sessionId, session);
399
- this.emit('reasoning_start', {
400
- id: sessionId,
401
- stage: types_1.ThinkingStage.REASONING,
402
- timestamp: new Date(),
403
- data: { problem, type }
404
- });
405
- try {
406
- // Generate Chain of Thought if enabled (via LLM implicitly or explicitly)
407
- let cot;
408
- // Try LLM-based reasoning first
409
- await this.executeReasoningWithLLM(session, maxSteps);
410
- // If LLM failed (empty steps), fallback to internal engines
411
- if (session.steps.length === 0) {
412
- if (generateCOT) {
413
- cot = this.cotGenerator.generate(problem, maxSteps);
414
- }
415
- switch (type) {
416
- case types_1.ReasoningType.DEDUCTIVE:
417
- await this.executeDeductiveReasoning(session, maxSteps);
418
- break;
419
- case types_1.ReasoningType.INDUCTIVE:
420
- await this.executeInductiveReasoning(session, maxSteps);
421
- break;
422
- case types_1.ReasoningType.ABDUCTIVE:
423
- await this.executeAbductiveReasoning(session, maxSteps);
424
- break;
425
- case types_1.ReasoningType.ANALOGICAL:
426
- await this.executeAnalogicalReasoning(session, maxSteps);
427
- break;
428
- case types_1.ReasoningType.CAUSAL:
429
- await this.executeCausalReasoning(session, maxSteps);
430
- break;
431
- case types_1.ReasoningType.COUNTERFACTUAL:
432
- await this.executeCounterfactualReasoning(session, maxSteps);
433
- break;
434
- }
435
- // Generate conclusion for fallback
436
- session.conclusion = this.generateConclusion(session, cot);
437
- session.confidence = this.calculateSessionConfidence(session);
438
- }
439
- session.endTime = new Date();
440
- this.emit('reasoning_complete', {
441
- id: sessionId,
442
- stage: types_1.ThinkingStage.REASONING,
443
- timestamp: new Date(),
444
- data: {
445
- session,
446
- steps: session.steps.length,
447
- confidence: session.confidence
448
- }
449
- });
450
- return session;
451
- }
452
- catch (error) {
453
- this.emit('reasoning_error', {
454
- id: sessionId,
455
- stage: types_1.ThinkingStage.REASONING,
456
- timestamp: new Date(),
457
- data: { error }
458
- });
459
- throw new types_1.ThinkingError(`Reasoning failed: ${error instanceof Error ? error.message : 'Unknown error'}`, types_1.ThinkingStage.REASONING, true, error instanceof Error ? error : undefined);
460
- }
461
- }
462
- async executeReasoningWithLLM(session, maxSteps) {
463
- const prompt = `
464
- You are an expert reasoning engine.
465
- Problem: "${session.problem}"
466
- Task: Perform ${session.type} reasoning with approximately ${maxSteps} steps.
467
-
468
- Return a JSON object with this exact structure (no markdown, just JSON):
469
- {
470
- "steps": [
471
- {
472
- "stepNumber": number,
473
- "premise": "string (the basis for this step)",
474
- "inference": "string (the logical deduction)",
475
- "confidence": number (0.0 to 1.0)
476
- }
477
- ],
478
- "conclusion": "string (final conclusion)",
479
- "overallConfidence": number (0.0 to 1.0)
480
- }
481
- `;
482
- try {
483
- const response = await llm_service_1.llmService.generateText({ prompt });
484
- const jsonMatch = response.match(/\{[\s\S]*\}/);
485
- if (jsonMatch) {
486
- const result = JSON.parse(jsonMatch[0]);
487
- if (Array.isArray(result.steps)) {
488
- result.steps.forEach((s, i) => {
489
- session.steps.push({
490
- id: `step_${i}`,
491
- stepNumber: s.stepNumber || i + 1,
492
- premise: s.premise || '',
493
- inference: s.inference || '',
494
- evidence: [],
495
- assumptions: [],
496
- confidence: s.confidence || 0.8,
497
- nextSteps: []
498
- });
499
- });
500
- }
501
- session.conclusion = result.conclusion;
502
- session.confidence = result.overallConfidence || 0.8;
503
- }
504
- }
505
- catch (error) {
506
- console.warn('LLM reasoning failed, falling back to internal engine', error);
507
- // Fallback handled in caller
508
- }
509
- }
510
- async executeDeductiveReasoning(session, maxSteps) {
511
- const facts = this.extractFacts(session.problem);
512
- for (let i = 0; i < maxSteps; i++) {
513
- const inferences = this.rulesEngine.infer(facts);
514
- if (inferences.length === 0)
515
- break;
516
- const topInference = inferences[0];
517
- const step = {
518
- id: `step_${i}`,
519
- stepNumber: i + 1,
520
- premise: facts.join(', '),
521
- inference: topInference.conclusion,
522
- evidence: [{
523
- source: 'logical_rules',
524
- excerpt: `Rule: ${topInference.rule.premises.join(' AND ')} => ${topInference.rule.conclusion}`,
525
- location: 'rules_engine',
526
- strength: topInference.confidence
527
- }],
528
- assumptions: topInference.rule.premises,
529
- confidence: topInference.confidence,
530
- nextSteps: inferences.slice(1).map(inf => inf.conclusion)
531
- };
532
- session.steps.push(step);
533
- facts.push(topInference.conclusion);
534
- }
535
- }
536
- async executeInductiveReasoning(session, maxSteps) {
537
- // Pattern-based reasoning from specific to general
538
- const observations = this.extractObservations(session.problem);
539
- for (let i = 0; i < maxSteps && i < observations.length; i++) {
540
- const pattern = this.identifyPattern(observations.slice(0, i + 1));
541
- const step = {
542
- id: `step_${i}`,
543
- stepNumber: i + 1,
544
- premise: observations.slice(0, i + 1).join('; '),
545
- inference: `Pattern identified: ${pattern.description}`,
546
- evidence: observations.map(obs => ({
547
- source: 'observation',
548
- excerpt: obs,
549
- location: 'problem_statement',
550
- strength: 0.7
551
- })),
552
- assumptions: ['Observations are representative', 'Pattern will continue'],
553
- confidence: pattern.confidence,
554
- nextSteps: ['Test pattern with new data', 'Formulate general rule']
555
- };
556
- session.steps.push(step);
557
- }
558
- }
559
- async executeAbductiveReasoning(session, maxSteps) {
560
- // Inference to the best explanation
561
- const observations = this.extractObservations(session.problem);
562
- const possibleExplanations = this.generateExplanations(observations);
563
- for (let i = 0; i < maxSteps && i < possibleExplanations.length; i++) {
564
- const explanation = possibleExplanations[i];
565
- const step = {
566
- id: `step_${i}`,
567
- stepNumber: i + 1,
568
- premise: observations.join('; '),
569
- inference: `Best explanation: ${explanation.description}`,
570
- evidence: [{
571
- source: 'abductive_inference',
572
- excerpt: explanation.supportingEvidence,
573
- location: 'generated_explanation',
574
- strength: explanation.plausibility
575
- }],
576
- assumptions: explanation.assumptions,
577
- confidence: explanation.plausibility,
578
- nextSteps: possibleExplanations.slice(i + 1).map(e => `Alternative: ${e.description}`)
579
- };
580
- session.steps.push(step);
581
- }
582
- }
583
- async executeAnalogicalReasoning(session, maxSteps) {
584
- // Reasoning by analogy
585
- const sourceDomain = this.extractDomain(session.problem);
586
- const analogies = this.findAnalogies(sourceDomain);
587
- for (let i = 0; i < maxSteps && i < analogies.length; i++) {
588
- const analogy = analogies[i];
589
- const step = {
590
- id: `step_${i}`,
591
- stepNumber: i + 1,
592
- premise: `Source domain: ${sourceDomain}`,
593
- inference: `Analogous to: ${analogy.targetDomain}. Therefore: ${analogy.inferredProperty}`,
594
- evidence: [{
595
- source: 'analogy',
596
- excerpt: `Similarity: ${analogy.similarityDescription}`,
597
- location: 'analogy_mapping',
598
- strength: analogy.similarityScore
599
- }],
600
- assumptions: ['Analogous domains share relevant properties'],
601
- confidence: analogy.similarityScore,
602
- nextSteps: analogies.slice(i + 1).map(a => `Alternative analogy: ${a.targetDomain}`)
603
- };
604
- session.steps.push(step);
605
- }
606
- }
607
- async executeCausalReasoning(session, maxSteps) {
608
- // Cause-effect reasoning
609
- const causalChain = this.identifyCausalChain(session.problem);
610
- for (let i = 0; i < maxSteps && i < causalChain.length; i++) {
611
- const causalLink = causalChain[i];
612
- const step = {
613
- id: `step_${i}`,
614
- stepNumber: i + 1,
615
- premise: `Cause: ${causalLink.cause}`,
616
- inference: `Effect: ${causalLink.effect}`,
617
- evidence: [{
618
- source: 'causal_analysis',
619
- excerpt: causalLink.mechanism,
620
- location: 'causal_chain',
621
- strength: causalLink.confidence
622
- }],
623
- assumptions: ['Causal relationship is consistent', 'No confounding factors'],
624
- confidence: causalLink.confidence,
625
- nextSteps: causalChain.slice(i + 1).map(c => `Next effect: ${c.effect}`)
626
- };
627
- session.steps.push(step);
628
- }
629
- }
630
- async executeCounterfactualReasoning(session, maxSteps) {
631
- // What-if reasoning
632
- const counterfactuals = this.generateCounterfactuals(session.problem);
633
- for (let i = 0; i < maxSteps && i < counterfactuals.length; i++) {
634
- const cf = counterfactuals[i];
635
- const step = {
636
- id: `step_${i}`,
637
- stepNumber: i + 1,
638
- premise: `Actual: ${cf.actual}`,
639
- inference: `If ${cf.condition}, then ${cf.outcome}`,
640
- evidence: [{
641
- source: 'counterfactual',
642
- excerpt: cf.reasoning,
643
- location: 'counterfactual_analysis',
644
- strength: cf.plausibility
645
- }],
646
- assumptions: cf.assumptions,
647
- confidence: cf.plausibility,
648
- nextSteps: counterfactuals.slice(i + 1).map(c => `Alternative: If ${c.condition}`)
649
- };
650
- session.steps.push(step);
651
- }
652
- }
653
- /**
654
- * Create and test a hypothesis
655
- */
656
- createHypothesis(statement) {
657
- return this.hypothesisManager.createHypothesis(statement);
658
- }
659
- addEvidenceToHypothesis(hypothesisId, evidence, supporting) {
660
- this.hypothesisManager.addEvidence(hypothesisId, evidence, supporting);
661
- }
662
- /**
663
- * Decompose a complex problem
664
- */
665
- decomposeProblem(problem) {
666
- return this.decompositionEngine.decompose(problem);
667
- }
668
- /**
669
- * Generate Chain of Thought for a question
670
- */
671
- generateChainOfThought(question, maxDepth) {
672
- return this.cotGenerator.generate(question, maxDepth);
673
- }
674
- // Helper methods
675
- generateId() {
676
- return `reasoning_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
677
- }
678
- extractFacts(problem) {
679
- // Simplified fact extraction
680
- return problem
681
- .split(/[.!?]+/)
682
- .map(s => s.trim())
683
- .filter(s => s.length > 10);
684
- }
685
- extractObservations(problem) {
686
- return this.extractFacts(problem);
687
- }
688
- identifyPattern(observations) {
689
- // Simplified pattern identification
690
- const commonWords = this.findCommonElements(observations);
691
- return {
692
- description: `Common elements: ${commonWords.join(', ')}`,
693
- confidence: Math.min(0.9, observations.length * 0.2)
694
- };
695
- }
696
- findCommonElements(strings) {
697
- if (strings.length === 0)
698
- return [];
699
- const wordSets = strings.map(s => new Set(s.toLowerCase().split(/\s+/)));
700
- const common = Array.from(wordSets[0]).filter(word => wordSets.every(set => set.has(word)) && word.length > 4);
701
- return common.slice(0, 5);
702
- }
703
- generateExplanations(observations) {
704
- return [
705
- {
706
- description: `Explanation based on ${observations.length} observations`,
707
- plausibility: 0.7,
708
- supportingEvidence: observations.join('; '),
709
- assumptions: ['Observations are accurate', 'No hidden factors']
710
- }
711
- ];
712
- }
713
- extractDomain(problem) {
714
- const domains = ['business', 'technology', 'science', 'health', 'education', 'finance'];
715
- const problemLower = problem.toLowerCase();
716
- return domains.find(d => problemLower.includes(d)) || 'general';
717
- }
718
- findAnalogies(sourceDomain) {
719
- const analogies = {
720
- business: [
721
- { target: 'ecosystem', property: 'interconnected components', similarity: 'both have interdependent parts' },
722
- { target: 'organism', property: 'growth and adaptation', similarity: 'both evolve over time' }
723
- ],
724
- technology: [
725
- { target: 'biology', property: 'modular components', similarity: 'both use building blocks' },
726
- { target: 'language', property: 'syntax and structure', similarity: 'both have rules and patterns' }
727
- ]
728
- };
729
- return (analogies[sourceDomain] || []).map(a => ({
730
- targetDomain: a.target,
731
- inferredProperty: a.property,
732
- similarityDescription: a.similarity,
733
- similarityScore: 0.7
734
- }));
735
- }
736
- identifyCausalChain(problem) {
737
- const causalIndicators = ['causes', 'leads to', 'results in', 'because', 'due to', 'therefore'];
738
- const chain = [];
739
- causalIndicators.forEach(indicator => {
740
- const regex = new RegExp(`(.+?)\\s+${indicator}\\s+(.+?)[.!?]`, 'gi');
741
- let match;
742
- while ((match = regex.exec(problem)) !== null) {
743
- chain.push({
744
- cause: match[1].trim(),
745
- effect: match[2].trim(),
746
- mechanism: `${match[1].trim()} ${indicator} ${match[2].trim()}`,
747
- confidence: 0.75
748
- });
749
- }
750
- });
751
- return chain.length > 0 ? chain : [{
752
- cause: 'Initial condition',
753
- effect: 'Observed outcome',
754
- mechanism: 'Causal relationship inferred from context',
755
- confidence: 0.5
756
- }];
757
- }
758
- generateCounterfactuals(problem) {
759
- return [
760
- {
761
- actual: problem,
762
- condition: 'conditions were different',
763
- outcome: 'outcome would change',
764
- reasoning: 'Counterfactual analysis based on problem context',
765
- plausibility: 0.6,
766
- assumptions: ['Minimal change principle', 'Ceteris paribus']
767
- }
768
- ];
769
- }
770
- generateConclusion(session, cot) {
771
- const stepConclusions = session.steps.map(s => s.inference);
772
- if (cot?.finalAnswer) {
773
- return `${cot.finalAnswer} Based on ${session.steps.length} reasoning steps.`;
774
- }
775
- return `After ${session.steps.length} steps of ${session.type} reasoning: ${stepConclusions.slice(-2).join('; ')}.`;
776
- }
777
- calculateSessionConfidence(session) {
778
- if (session.steps.length === 0)
779
- return 0;
780
- const avgConfidence = session.steps.reduce((sum, s) => sum + s.confidence, 0) / session.steps.length;
781
- return Math.min(0.95, avgConfidence);
782
- }
783
- /**
784
- * Get reasoning session
785
- */
786
- getSession(sessionId) {
787
- return this.sessions.get(sessionId);
788
- }
789
- /**
790
- * Add custom logical rule
791
- */
792
- addRule(rule) {
793
- this.rulesEngine.addRule(rule);
794
- }
795
- }
796
- exports.ReasoningEngine = ReasoningEngine;
797
- // ============================================================================
798
- // EXPORT SINGLETON INSTANCE
799
- // ============================================================================
800
- exports.reasoningEngine = new ReasoningEngine();
801
- // ============================================================================
802
- // EXAMPLE USAGE
803
- // ============================================================================
804
- /*
805
- // Deductive reasoning
806
- const deductiveResult = await reasoningEngine.reason(
807
- "All software requires maintenance. This application is software. Therefore...",
808
- { type: ReasoningType.DEDUCTIVE }
809
- );
810
-
811
- // Inductive reasoning
812
- const inductiveResult = await reasoningEngine.reason(
813
- "Every software project I've seen with good documentation succeeded. " +
814
- "Projects with poor documentation often failed. Therefore...",
815
- { type: ReasoningType.INDUCTIVE }
816
- );
817
-
818
- // Hypothesis testing
819
- const hypothesis = reasoningEngine.createHypothesis(
820
- "Using TypeScript reduces bug count by 30%"
821
- );
822
-
823
- reasoningEngine.addEvidenceToHypothesis(
824
- hypothesis.id,
825
- {
826
- source: 'study',
827
- excerpt: 'TypeScript projects had 15% fewer bugs',
828
- location: 'research_paper',
829
- strength: 0.8
830
- },
831
- true
832
- );
833
-
834
- // Problem decomposition
835
- const decomposition = reasoningEngine.decomposeProblem(
836
- "Build a scalable e-commerce platform with AI recommendations"
837
- );
838
-
839
- // Chain of Thought
840
- const cot = reasoningEngine.generateChainOfThought(
841
- "How can we improve software development productivity?",
842
- 5
843
- );
844
- */
845
- //# sourceMappingURL=reasoning.js.map