gthinking 1.0.0

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