gthinking 1.1.0 → 1.2.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 (90) hide show
  1. package/GEMINI.md +68 -0
  2. package/README.md +39 -1
  3. package/analysis.ts +78 -1
  4. package/creativity.ts +62 -9
  5. package/dist/analysis.d.ts +2 -0
  6. package/dist/analysis.d.ts.map +1 -1
  7. package/dist/analysis.js +75 -1
  8. package/dist/analysis.js.map +1 -1
  9. package/dist/creativity.d.ts +2 -1
  10. package/dist/creativity.d.ts.map +1 -1
  11. package/dist/creativity.js +57 -7
  12. package/dist/creativity.js.map +1 -1
  13. package/dist/engine.d.ts +15 -1
  14. package/dist/engine.d.ts.map +1 -1
  15. package/dist/engine.js +23 -21
  16. package/dist/engine.js.map +1 -1
  17. package/dist/examples.js +1 -1
  18. package/dist/examples.js.map +1 -1
  19. package/dist/llm-service.d.ts +21 -0
  20. package/dist/llm-service.d.ts.map +1 -0
  21. package/dist/llm-service.js +100 -0
  22. package/dist/llm-service.js.map +1 -0
  23. package/dist/reasoning.d.ts +1 -0
  24. package/dist/reasoning.d.ts.map +1 -1
  25. package/dist/reasoning.js +80 -27
  26. package/dist/reasoning.js.map +1 -1
  27. package/dist/search-discovery.d.ts.map +1 -1
  28. package/dist/search-discovery.js +43 -0
  29. package/dist/search-discovery.js.map +1 -1
  30. package/dist/types/analysis.d.ts +54 -0
  31. package/dist/types/analysis.d.ts.map +1 -0
  32. package/dist/types/analysis.js +3 -0
  33. package/dist/types/analysis.js.map +1 -0
  34. package/dist/types/core.d.ts +66 -0
  35. package/dist/types/core.d.ts.map +1 -0
  36. package/dist/types/core.js +61 -0
  37. package/dist/types/core.js.map +1 -0
  38. package/dist/types/creativity.d.ts +58 -0
  39. package/dist/types/creativity.d.ts.map +1 -0
  40. package/dist/types/creativity.js +3 -0
  41. package/dist/types/creativity.js.map +1 -0
  42. package/dist/types/engine.d.ts +55 -0
  43. package/dist/types/engine.d.ts.map +1 -0
  44. package/dist/types/engine.js +3 -0
  45. package/dist/types/engine.js.map +1 -0
  46. package/dist/types/index.d.ts +10 -0
  47. package/dist/types/index.d.ts.map +1 -0
  48. package/dist/types/index.js +26 -0
  49. package/dist/types/index.js.map +1 -0
  50. package/dist/types/learning.d.ts +62 -0
  51. package/dist/types/learning.d.ts.map +1 -0
  52. package/dist/types/learning.js +3 -0
  53. package/dist/types/learning.js.map +1 -0
  54. package/dist/types/planning.d.ts +78 -0
  55. package/dist/types/planning.d.ts.map +1 -0
  56. package/dist/types/planning.js +3 -0
  57. package/dist/types/planning.js.map +1 -0
  58. package/dist/types/reasoning.d.ts +83 -0
  59. package/dist/types/reasoning.d.ts.map +1 -0
  60. package/dist/types/reasoning.js +13 -0
  61. package/dist/types/reasoning.js.map +1 -0
  62. package/dist/types/search.d.ts +56 -0
  63. package/dist/types/search.d.ts.map +1 -0
  64. package/dist/types/search.js +3 -0
  65. package/dist/types/search.js.map +1 -0
  66. package/dist/types/synthesis.d.ts +39 -0
  67. package/dist/types/synthesis.d.ts.map +1 -0
  68. package/dist/types/synthesis.js +3 -0
  69. package/dist/types/synthesis.js.map +1 -0
  70. package/dist/types.d.ts +1 -530
  71. package/dist/types.d.ts.map +1 -1
  72. package/dist/types.js +15 -70
  73. package/dist/types.js.map +1 -1
  74. package/engine.ts +42 -23
  75. package/examples.ts +1 -1
  76. package/llm-service.ts +120 -0
  77. package/package.json +1 -1
  78. package/reasoning.ts +88 -28
  79. package/search-discovery.ts +46 -0
  80. package/types/analysis.ts +69 -0
  81. package/types/core.ts +90 -0
  82. package/types/creativity.ts +72 -0
  83. package/types/engine.ts +60 -0
  84. package/types/index.ts +9 -0
  85. package/types/learning.ts +69 -0
  86. package/types/planning.ts +85 -0
  87. package/types/reasoning.ts +92 -0
  88. package/types/search.ts +58 -0
  89. package/types/synthesis.ts +42 -0
  90. package/types.ts +1 -669
package/dist/types.js CHANGED
@@ -3,75 +3,20 @@
3
3
  * Sequential Thinking System - Core Types and Interfaces
4
4
  * A comprehensive intelligent thinking framework for complex problem solving
5
5
  */
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.ThinkingError = exports.ReasoningType = exports.SourceType = exports.TaskStatus = exports.Priority = exports.ConfidenceLevel = exports.ThinkingStage = void 0;
8
- // ============================================================================
9
- // CORE ENUMS
10
- // ============================================================================
11
- var ThinkingStage;
12
- (function (ThinkingStage) {
13
- ThinkingStage["SEARCH"] = "search";
14
- ThinkingStage["ANALYSIS"] = "analysis";
15
- ThinkingStage["REASONING"] = "reasoning";
16
- ThinkingStage["LEARNING"] = "learning";
17
- ThinkingStage["PLANNING"] = "planning";
18
- ThinkingStage["CREATIVITY"] = "creativity";
19
- ThinkingStage["SYNTHESIS"] = "synthesis";
20
- ThinkingStage["EVALUATION"] = "evaluation";
21
- })(ThinkingStage || (exports.ThinkingStage = ThinkingStage = {}));
22
- var ConfidenceLevel;
23
- (function (ConfidenceLevel) {
24
- ConfidenceLevel[ConfidenceLevel["VERY_LOW"] = 0.1] = "VERY_LOW";
25
- ConfidenceLevel[ConfidenceLevel["LOW"] = 0.3] = "LOW";
26
- ConfidenceLevel[ConfidenceLevel["MEDIUM"] = 0.5] = "MEDIUM";
27
- ConfidenceLevel[ConfidenceLevel["HIGH"] = 0.7] = "HIGH";
28
- ConfidenceLevel[ConfidenceLevel["VERY_HIGH"] = 0.9] = "VERY_HIGH";
29
- })(ConfidenceLevel || (exports.ConfidenceLevel = ConfidenceLevel = {}));
30
- var Priority;
31
- (function (Priority) {
32
- Priority[Priority["CRITICAL"] = 1] = "CRITICAL";
33
- Priority[Priority["HIGH"] = 2] = "HIGH";
34
- Priority[Priority["MEDIUM"] = 3] = "MEDIUM";
35
- Priority[Priority["LOW"] = 4] = "LOW";
36
- Priority[Priority["MINIMAL"] = 5] = "MINIMAL";
37
- })(Priority || (exports.Priority = Priority = {}));
38
- var TaskStatus;
39
- (function (TaskStatus) {
40
- TaskStatus["PENDING"] = "pending";
41
- TaskStatus["IN_PROGRESS"] = "in_progress";
42
- TaskStatus["COMPLETED"] = "completed";
43
- TaskStatus["FAILED"] = "failed";
44
- TaskStatus["CANCELLED"] = "cancelled";
45
- })(TaskStatus || (exports.TaskStatus = TaskStatus = {}));
46
- var SourceType;
47
- (function (SourceType) {
48
- SourceType["WEB"] = "web";
49
- SourceType["DATABASE"] = "database";
50
- SourceType["API"] = "api";
51
- SourceType["CACHE"] = "cache";
52
- SourceType["KNOWLEDGE_BASE"] = "knowledge_base";
53
- SourceType["USER_INPUT"] = "user_input";
54
- })(SourceType || (exports.SourceType = SourceType = {}));
55
- var ReasoningType;
56
- (function (ReasoningType) {
57
- ReasoningType["DEDUCTIVE"] = "deductive";
58
- ReasoningType["INDUCTIVE"] = "inductive";
59
- ReasoningType["ABDUCTIVE"] = "abductive";
60
- ReasoningType["ANALOGICAL"] = "analogical";
61
- ReasoningType["CAUSAL"] = "causal";
62
- ReasoningType["COUNTERFACTUAL"] = "counterfactual";
63
- })(ReasoningType || (exports.ReasoningType = ReasoningType = {}));
64
- // ============================================================================
65
- // ERROR TYPES
66
- // ============================================================================
67
- class ThinkingError extends Error {
68
- constructor(message, stage, recoverable, originalError) {
69
- super(message);
70
- this.stage = stage;
71
- this.recoverable = recoverable;
72
- this.originalError = originalError;
73
- this.name = 'ThinkingError';
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
74
11
  }
75
- }
76
- exports.ThinkingError = ThinkingError;
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
18
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ __exportStar(require("./types/index"), exports);
77
22
  //# sourceMappingURL=types.js.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../types.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,+EAA+E;AAC/E,aAAa;AACb,+EAA+E;AAE/E,IAAY,aASX;AATD,WAAY,aAAa;IACvB,kCAAiB,CAAA;IACjB,sCAAqB,CAAA;IACrB,wCAAuB,CAAA;IACvB,sCAAqB,CAAA;IACrB,sCAAqB,CAAA;IACrB,0CAAyB,CAAA;IACzB,wCAAuB,CAAA;IACvB,0CAAyB,CAAA;AAC3B,CAAC,EATW,aAAa,6BAAb,aAAa,QASxB;AAED,IAAY,eAMX;AAND,WAAY,eAAe;IACzB,+DAAc,CAAA;IACd,qDAAS,CAAA;IACT,2DAAY,CAAA;IACZ,uDAAU,CAAA;IACV,iEAAe,CAAA;AACjB,CAAC,EANW,eAAe,+BAAf,eAAe,QAM1B;AAED,IAAY,QAMX;AAND,WAAY,QAAQ;IAClB,+CAAY,CAAA;IACZ,uCAAQ,CAAA;IACR,2CAAU,CAAA;IACV,qCAAO,CAAA;IACP,6CAAW,CAAA;AACb,CAAC,EANW,QAAQ,wBAAR,QAAQ,QAMnB;AAED,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,iCAAmB,CAAA;IACnB,yCAA2B,CAAA;IAC3B,qCAAuB,CAAA;IACvB,+BAAiB,CAAA;IACjB,qCAAuB,CAAA;AACzB,CAAC,EANW,UAAU,0BAAV,UAAU,QAMrB;AAED,IAAY,UAOX;AAPD,WAAY,UAAU;IACpB,yBAAW,CAAA;IACX,mCAAqB,CAAA;IACrB,yBAAW,CAAA;IACX,6BAAe,CAAA;IACf,+CAAiC,CAAA;IACjC,uCAAyB,CAAA;AAC3B,CAAC,EAPW,UAAU,0BAAV,UAAU,QAOrB;AAED,IAAY,aAOX;AAPD,WAAY,aAAa;IACvB,wCAAuB,CAAA;IACvB,wCAAuB,CAAA;IACvB,wCAAuB,CAAA;IACvB,0CAAyB,CAAA;IACzB,kCAAiB,CAAA;IACjB,kDAAiC,CAAA;AACnC,CAAC,EAPW,aAAa,6BAAb,aAAa,QAOxB;AAilBD,+EAA+E;AAC/E,cAAc;AACd,+EAA+E;AAE/E,MAAa,aAAc,SAAQ,KAAK;IACtC,YACE,OAAe,EACR,KAAoB,EACpB,WAAoB,EACpB,aAAqB;QAE5B,KAAK,CAAC,OAAO,CAAC,CAAC;QAJR,UAAK,GAAL,KAAK,CAAe;QACpB,gBAAW,GAAX,WAAW,CAAS;QACpB,kBAAa,GAAb,aAAa,CAAQ;QAG5B,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AAVD,sCAUC"}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../types.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;AAEH,gDAA8B"}
package/engine.ts CHANGED
@@ -70,7 +70,7 @@ class SynthesisEngine {
70
70
  query: string,
71
71
  searchResults: SearchResult[],
72
72
  analysisResults: AnalysisResult[],
73
- reasoningSession: ReasoningSession,
73
+ reasoningSession?: ReasoningSession,
74
74
  creativeSession?: CreativeSession
75
75
  ): SynthesisResult {
76
76
  // Extract key insights from each component
@@ -106,7 +106,7 @@ class SynthesisEngine {
106
106
  id: `synthesis_${Date.now()}`,
107
107
  sources: [
108
108
  ...searchResults.map(r => r.url),
109
- `reasoning_${reasoningSession.id}`
109
+ reasoningSession ? `reasoning_${reasoningSession.id}` : 'reasoning_skipped'
110
110
  ],
111
111
  summary,
112
112
  keyInsights: insights,
@@ -120,7 +120,7 @@ class SynthesisEngine {
120
120
  private extractInsights(
121
121
  searchResults: SearchResult[],
122
122
  analysisResults: AnalysisResult[],
123
- reasoningSession: ReasoningSession,
123
+ reasoningSession?: ReasoningSession,
124
124
  creativeSession?: CreativeSession
125
125
  ): string[] {
126
126
  const insights: string[] = [];
@@ -141,7 +141,7 @@ class SynthesisEngine {
141
141
  });
142
142
 
143
143
  // From reasoning
144
- if (reasoningSession.steps.length > 0) {
144
+ if (reasoningSession && reasoningSession.steps.length > 0) {
145
145
  const lastStep = reasoningSession.steps[reasoningSession.steps.length - 1];
146
146
  insights.push(`Reasoning conclusion: ${lastStep.inference}`);
147
147
  }
@@ -169,12 +169,12 @@ class SynthesisEngine {
169
169
  private generateRecommendations(
170
170
  query: string,
171
171
  insights: string[],
172
- reasoningSession: ReasoningSession
172
+ reasoningSession?: ReasoningSession
173
173
  ): Recommendation[] {
174
174
  const recommendations: Recommendation[] = [];
175
175
 
176
176
  // Based on reasoning
177
- if (reasoningSession.conclusion) {
177
+ if (reasoningSession && reasoningSession.conclusion) {
178
178
  recommendations.push({
179
179
  id: `rec_${Date.now()}_1`,
180
180
  action: `Proceed with approach suggested by ${reasoningSession.type} reasoning`,
@@ -218,14 +218,16 @@ class SynthesisEngine {
218
218
  return gaps;
219
219
  }
220
220
 
221
- private identifyUncertainties(reasoningSession: ReasoningSession): string[] {
221
+ private identifyUncertainties(reasoningSession?: ReasoningSession): string[] {
222
222
  const uncertainties: string[] = [];
223
223
 
224
- reasoningSession.steps.forEach(step => {
225
- if (step.confidence < 0.7) {
226
- uncertainties.push(`Step ${step.stepNumber}: ${step.inference}`);
227
- }
228
- });
224
+ if (reasoningSession) {
225
+ reasoningSession.steps.forEach(step => {
226
+ if (step.confidence < 0.7) {
227
+ uncertainties.push(`Step ${step.stepNumber}: ${step.inference}`);
228
+ }
229
+ });
230
+ }
229
231
 
230
232
  return uncertainties;
231
233
  }
@@ -233,14 +235,17 @@ class SynthesisEngine {
233
235
  private calculateSynthesisConfidence(
234
236
  searchResults: SearchResult[],
235
237
  analysisResults: AnalysisResult[],
236
- reasoningSession: ReasoningSession
238
+ reasoningSession?: ReasoningSession
237
239
  ): number {
238
240
  const factors = [
239
241
  searchResults.length > 0 ? searchResults[0].credibility : 0,
240
242
  analysisResults.length > 0 ?
241
243
  analysisResults.reduce((sum, r) => sum + r.confidence, 0) / analysisResults.length : 0,
242
- reasoningSession.confidence
243
244
  ];
245
+
246
+ if (reasoningSession) {
247
+ factors.push(reasoningSession.confidence);
248
+ }
244
249
 
245
250
  return factors.reduce((sum, f) => sum + f, 0) / factors.length;
246
251
  }
@@ -250,6 +255,15 @@ class SynthesisEngine {
250
255
  // MAIN SEQUENTIAL THINKING ENGINE
251
256
  // ============================================================================
252
257
 
258
+ export interface SequentialThinkingEngineDeps {
259
+ searchEngine?: SearchDiscoveryEngine;
260
+ analysisEngine?: AnalysisEngine;
261
+ reasoningEngine?: ReasoningEngine;
262
+ learningEngine?: LearningEngine;
263
+ planningEngine?: PlanningEngine;
264
+ creativityEngine?: CreativityEngine;
265
+ }
266
+
253
267
  export class SequentialThinkingEngine extends EventEmitter {
254
268
  private searchEngine: SearchDiscoveryEngine;
255
269
  private analysisEngine: AnalysisEngine;
@@ -262,7 +276,10 @@ export class SequentialThinkingEngine extends EventEmitter {
262
276
  private config: SequentialThinkingConfig;
263
277
  private sessions: Map<string, ThinkingSession> = new Map();
264
278
 
265
- constructor(config: Partial<SequentialThinkingConfig> = {}) {
279
+ constructor(
280
+ config: Partial<SequentialThinkingConfig> = {},
281
+ deps: SequentialThinkingEngineDeps = {}
282
+ ) {
266
283
  super();
267
284
 
268
285
  this.config = {
@@ -277,13 +294,15 @@ export class SequentialThinkingEngine extends EventEmitter {
277
294
  ...config
278
295
  };
279
296
 
280
- // Initialize all engines
281
- this.searchEngine = new SearchDiscoveryEngine();
282
- this.analysisEngine = new AnalysisEngine();
283
- this.reasoningEngine = new ReasoningEngine();
284
- this.learningEngine = new LearningEngine();
285
- this.planningEngine = new PlanningEngine();
286
- this.creativityEngine = new CreativityEngine();
297
+ // Initialize all engines (inject or default)
298
+ this.searchEngine = deps.searchEngine || new SearchDiscoveryEngine();
299
+ this.analysisEngine = deps.analysisEngine || new AnalysisEngine();
300
+ this.reasoningEngine = deps.reasoningEngine || new ReasoningEngine();
301
+ this.learningEngine = deps.learningEngine || new LearningEngine();
302
+ this.planningEngine = deps.planningEngine || new PlanningEngine();
303
+ this.creativityEngine = deps.creativityEngine || new CreativityEngine();
304
+
305
+ // Synthesis engine is internal for now, but could be injected too
287
306
  this.synthesisEngine = new SynthesisEngine();
288
307
 
289
308
  // Set up event forwarding
@@ -569,7 +588,7 @@ export class SequentialThinkingEngine extends EventEmitter {
569
588
  ['brainstorming'] :
570
589
  ['brainstorming', 'scamper', 'analogy'];
571
590
 
572
- const creativeSession = this.creativityEngine.startSession(request.query, {
591
+ const creativeSession = await this.creativityEngine.startSession(request.query, {
573
592
  techniques,
574
593
  ideaCount: 15
575
594
  });
package/examples.ts CHANGED
@@ -438,7 +438,7 @@ async function creativityModuleExample() {
438
438
  console.log('=== Example 10: Creativity Module ===\n');
439
439
 
440
440
  // Start creative session
441
- const session = creativityEngine.startSession(
441
+ const session = await creativityEngine.startSession(
442
442
  'How can we improve remote team collaboration?',
443
443
  {
444
444
  techniques: [
package/llm-service.ts ADDED
@@ -0,0 +1,120 @@
1
+
2
+ import { spawn } from 'child_process';
3
+
4
+ export type LLMProvider = 'gemini' | 'claude' | 'kimi' | 'opencode' | 'openai';
5
+
6
+ export interface LLMRequest {
7
+ prompt: string;
8
+ provider?: LLMProvider;
9
+ systemPrompt?: string;
10
+ model?: string;
11
+ }
12
+
13
+ export class LLMService {
14
+ private defaultProvider: LLMProvider = 'gemini';
15
+
16
+ constructor() {
17
+ this.detectProvider();
18
+ }
19
+
20
+ private async spawnCommand(command: string, args: string[]): Promise<string> {
21
+ return new Promise((resolve, reject) => {
22
+ const child = spawn(command, args);
23
+ let stdout = '';
24
+ let stderr = '';
25
+
26
+ child.stdout.on('data', (data) => {
27
+ stdout += data.toString();
28
+ });
29
+
30
+ child.stderr.on('data', (data) => {
31
+ stderr += data.toString();
32
+ });
33
+
34
+ child.on('close', (code) => {
35
+ if (code === 0) {
36
+ resolve(stdout.trim());
37
+ } else {
38
+ // Check if it's just a command not found check (checking 'which')
39
+ if (command === 'which' && code === 1) {
40
+ reject(new Error('Command not found'));
41
+ return;
42
+ }
43
+ reject(new Error(`Command '${command}' failed with code ${code}: ${stderr}`));
44
+ }
45
+ });
46
+
47
+ child.on('error', (err) => {
48
+ reject(err);
49
+ });
50
+ });
51
+ }
52
+
53
+ private async detectProvider() {
54
+ if (process.env.LLM_PROVIDER) {
55
+ this.defaultProvider = process.env.LLM_PROVIDER as LLMProvider;
56
+ return;
57
+ }
58
+
59
+ // Simple detection based on available commands
60
+ const providers: LLMProvider[] = ['gemini', 'claude', 'kimi', 'opencode'];
61
+
62
+ for (const p of providers) {
63
+ try {
64
+ await this.spawnCommand('which', [p]);
65
+ this.defaultProvider = p;
66
+ break;
67
+ } catch (e) {
68
+ // Command not found, continue
69
+ }
70
+ }
71
+ }
72
+
73
+ async generateText(request: LLMRequest): Promise<string> {
74
+ const provider = request.provider || this.defaultProvider;
75
+ const prompt = this.constructPrompt(request);
76
+
77
+ try {
78
+ switch (provider) {
79
+ case 'gemini':
80
+ return await this.callGemini(prompt);
81
+ case 'claude':
82
+ return await this.callClaude(prompt);
83
+ case 'kimi':
84
+ return await this.callKimi(prompt);
85
+ case 'opencode':
86
+ return await this.callOpenCode(prompt);
87
+ default:
88
+ return await this.callGemini(prompt); // Fallback
89
+ }
90
+ } catch (error) {
91
+ console.error(`LLM call failed (${provider}):`, error);
92
+ throw new Error(`Failed to generate text using ${provider}: ${error instanceof Error ? error.message : String(error)}`);
93
+ }
94
+ }
95
+
96
+ private constructPrompt(request: LLMRequest): string {
97
+ if (request.systemPrompt) {
98
+ return `System: ${request.systemPrompt}\n\nUser: ${request.prompt}`;
99
+ }
100
+ return request.prompt;
101
+ }
102
+
103
+ private async callGemini(prompt: string): Promise<string> {
104
+ return this.spawnCommand('gemini', [prompt]);
105
+ }
106
+
107
+ private async callClaude(prompt: string): Promise<string> {
108
+ return this.spawnCommand('claude', [prompt]);
109
+ }
110
+
111
+ private async callKimi(prompt: string): Promise<string> {
112
+ return this.spawnCommand('kimi', [prompt]);
113
+ }
114
+
115
+ private async callOpenCode(prompt: string): Promise<string> {
116
+ return this.spawnCommand('opencode', [prompt]);
117
+ }
118
+ }
119
+
120
+ export const llmService = new LLMService();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gthinking",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "A comprehensive intelligent sequential thinking framework for complex problem solving",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
package/reasoning.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  ThinkingStage
22
22
  } from './types';
23
23
  import { EventEmitter } from 'events';
24
+ import { llmService } from './llm-service';
24
25
 
25
26
  // ============================================================================
26
27
  // LOGICAL RULES ENGINE
@@ -541,37 +542,44 @@ export class ReasoningEngine extends EventEmitter {
541
542
  } as ThinkingEvent);
542
543
 
543
544
  try {
544
- // Generate Chain of Thought if enabled
545
+ // Generate Chain of Thought if enabled (via LLM implicitly or explicitly)
545
546
  let cot: ChainOfThought | undefined;
546
- if (generateCOT) {
547
- cot = this.cotGenerator.generate(problem, maxSteps);
548
- }
547
+
548
+ // Try LLM-based reasoning first
549
+ await this.executeReasoningWithLLM(session, maxSteps);
549
550
 
550
- // Execute reasoning based on type
551
- switch (type) {
552
- case ReasoningType.DEDUCTIVE:
553
- await this.executeDeductiveReasoning(session, maxSteps);
554
- break;
555
- case ReasoningType.INDUCTIVE:
556
- await this.executeInductiveReasoning(session, maxSteps);
557
- break;
558
- case ReasoningType.ABDUCTIVE:
559
- await this.executeAbductiveReasoning(session, maxSteps);
560
- break;
561
- case ReasoningType.ANALOGICAL:
562
- await this.executeAnalogicalReasoning(session, maxSteps);
563
- break;
564
- case ReasoningType.CAUSAL:
565
- await this.executeCausalReasoning(session, maxSteps);
566
- break;
567
- case ReasoningType.COUNTERFACTUAL:
568
- await this.executeCounterfactualReasoning(session, maxSteps);
569
- break;
570
- }
551
+ // If LLM failed (empty steps), fallback to internal engines
552
+ if (session.steps.length === 0) {
553
+ if (generateCOT) {
554
+ cot = this.cotGenerator.generate(problem, maxSteps);
555
+ }
571
556
 
572
- // Generate conclusion
573
- session.conclusion = this.generateConclusion(session, cot);
574
- session.confidence = this.calculateSessionConfidence(session);
557
+ switch (type) {
558
+ case ReasoningType.DEDUCTIVE:
559
+ await this.executeDeductiveReasoning(session, maxSteps);
560
+ break;
561
+ case ReasoningType.INDUCTIVE:
562
+ await this.executeInductiveReasoning(session, maxSteps);
563
+ break;
564
+ case ReasoningType.ABDUCTIVE:
565
+ await this.executeAbductiveReasoning(session, maxSteps);
566
+ break;
567
+ case ReasoningType.ANALOGICAL:
568
+ await this.executeAnalogicalReasoning(session, maxSteps);
569
+ break;
570
+ case ReasoningType.CAUSAL:
571
+ await this.executeCausalReasoning(session, maxSteps);
572
+ break;
573
+ case ReasoningType.COUNTERFACTUAL:
574
+ await this.executeCounterfactualReasoning(session, maxSteps);
575
+ break;
576
+ }
577
+
578
+ // Generate conclusion for fallback
579
+ session.conclusion = this.generateConclusion(session, cot);
580
+ session.confidence = this.calculateSessionConfidence(session);
581
+ }
582
+
575
583
  session.endTime = new Date();
576
584
 
577
585
  this.emit('reasoning_complete', {
@@ -604,6 +612,58 @@ export class ReasoningEngine extends EventEmitter {
604
612
  }
605
613
  }
606
614
 
615
+ private async executeReasoningWithLLM(session: ReasoningSession, maxSteps: number): Promise<void> {
616
+ const prompt = `
617
+ You are an expert reasoning engine.
618
+ Problem: "${session.problem}"
619
+ Task: Perform ${session.type} reasoning with approximately ${maxSteps} steps.
620
+
621
+ Return a JSON object with this exact structure (no markdown, just JSON):
622
+ {
623
+ "steps": [
624
+ {
625
+ "stepNumber": number,
626
+ "premise": "string (the basis for this step)",
627
+ "inference": "string (the logical deduction)",
628
+ "confidence": number (0.0 to 1.0)
629
+ }
630
+ ],
631
+ "conclusion": "string (final conclusion)",
632
+ "overallConfidence": number (0.0 to 1.0)
633
+ }
634
+ `;
635
+
636
+ try {
637
+ const response = await llmService.generateText({ prompt });
638
+ const jsonMatch = response.match(/\{[\s\S]*\}/);
639
+
640
+ if (jsonMatch) {
641
+ const result = JSON.parse(jsonMatch[0]);
642
+
643
+ if (Array.isArray(result.steps)) {
644
+ result.steps.forEach((s: any, i: number) => {
645
+ session.steps.push({
646
+ id: `step_${i}`,
647
+ stepNumber: s.stepNumber || i + 1,
648
+ premise: s.premise || '',
649
+ inference: s.inference || '',
650
+ evidence: [],
651
+ assumptions: [],
652
+ confidence: s.confidence || 0.8,
653
+ nextSteps: []
654
+ });
655
+ });
656
+ }
657
+
658
+ session.conclusion = result.conclusion;
659
+ session.confidence = result.overallConfidence || 0.8;
660
+ }
661
+ } catch (error) {
662
+ console.warn('LLM reasoning failed, falling back to internal engine', error);
663
+ // Fallback handled in caller
664
+ }
665
+ }
666
+
607
667
  private async executeDeductiveReasoning(session: ReasoningSession, maxSteps: number): Promise<void> {
608
668
  const facts = this.extractFacts(session.problem);
609
669
 
@@ -17,6 +17,7 @@ import {
17
17
  ThinkingStage
18
18
  } from './types';
19
19
  import { EventEmitter } from 'events';
20
+ import { llmService } from './llm-service';
20
21
 
21
22
  // ============================================================================
22
23
  // SEARCH PROVIDER INTERFACES
@@ -40,6 +41,15 @@ class WebSearchProvider implements SearchProvider {
40
41
  filters: SearchFilters,
41
42
  maxResults: number
42
43
  ): Promise<SearchResult[]> {
44
+ try {
45
+ const results = await this.searchWithLLM(query, maxResults);
46
+ if (results.length > 0) {
47
+ return this.applyFilters(results, filters);
48
+ }
49
+ } catch (error) {
50
+ console.warn('LLM search failed, falling back to simulation', error);
51
+ }
52
+
43
53
  // In real implementation, this would call actual search APIs
44
54
  // For demonstration, we simulate search results
45
55
  const simulatedResults: SearchResult[] = [];
@@ -66,6 +76,42 @@ class WebSearchProvider implements SearchProvider {
66
76
  return this.applyFilters(simulatedResults, filters);
67
77
  }
68
78
 
79
+ private async searchWithLLM(query: string, maxResults: number): Promise<SearchResult[]> {
80
+ const prompt = `
81
+ Act as a search engine. Query: "${query}"
82
+ Generate ${maxResults} relevant search results based on your knowledge.
83
+
84
+ Return strictly JSON with an array of objects:
85
+ [
86
+ {
87
+ "title": "string",
88
+ "url": "https://... (invent a plausible URL)",
89
+ "snippet": "string (1-2 sentences summarizing the content)",
90
+ "credibility": number (0-1)
91
+ }
92
+ ]
93
+ `;
94
+
95
+ const response = await llmService.generateText({ prompt });
96
+ const jsonMatch = response.match(/\[[\s\S]*\]/); // Match array
97
+
98
+ if (jsonMatch) {
99
+ const data = JSON.parse(jsonMatch[0]);
100
+ return data.map((item: any, i: number) => ({
101
+ id: `web_llm_${Date.now()}_${i}`,
102
+ title: item.title,
103
+ url: item.url,
104
+ snippet: item.snippet,
105
+ source: SourceType.WEB,
106
+ credibility: item.credibility || 0.7,
107
+ relevance: 0.9, // Assumed relevant
108
+ timestamp: new Date(),
109
+ metadata: { wordCount: 1000, citations: 10 }
110
+ }));
111
+ }
112
+ return [];
113
+ }
114
+
69
115
  getCredibilityScore(url: string): number {
70
116
  const credibleDomains = [
71
117
  'edu', 'gov', 'ac.uk', 'ac.jp', 'arxiv.org',
@@ -0,0 +1,69 @@
1
+ import { SearchResult } from './search';
2
+
3
+ export interface AnalysisRequest {
4
+ id: string;
5
+ content: string;
6
+ analysisTypes: AnalysisType[];
7
+ context?: string;
8
+ depth: 'surface' | 'moderate' | 'deep';
9
+ }
10
+
11
+ export type AnalysisType =
12
+ | 'sentiment'
13
+ | 'entity'
14
+ | 'topic'
15
+ | 'keyword'
16
+ | 'summary'
17
+ | 'fact_check'
18
+ | 'comparison'
19
+ | 'trend';
20
+
21
+ export interface AnalysisResult {
22
+ id: string;
23
+ requestId: string;
24
+ type: AnalysisType;
25
+ findings: Finding[];
26
+ confidence: number;
27
+ processingTime: number;
28
+ timestamp: Date;
29
+ }
30
+
31
+ export interface Finding {
32
+ id: string;
33
+ type: string;
34
+ value: unknown;
35
+ confidence: number;
36
+ evidence: Evidence[];
37
+ relatedFindings: string[];
38
+ }
39
+
40
+ export interface Evidence {
41
+ source: string;
42
+ excerpt: string;
43
+ location: string;
44
+ strength: number;
45
+ }
46
+
47
+ export interface ComparisonResult {
48
+ id: string;
49
+ subjects: string[];
50
+ similarities: ComparisonPoint[];
51
+ differences: ComparisonPoint[];
52
+ conclusion: string;
53
+ confidence: number;
54
+ }
55
+
56
+ export interface ComparisonPoint {
57
+ aspect: string;
58
+ values: Record<string, unknown>;
59
+ significance: number;
60
+ }
61
+
62
+ export interface FactCheckResult {
63
+ claim: string;
64
+ verdict: 'true' | 'false' | 'partially_true' | 'unverifiable';
65
+ confidence: number;
66
+ sources: SearchResult[];
67
+ explanation: string;
68
+ corrections?: string[];
69
+ }