gthinking 1.2.1 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +34 -0
- package/ANALYSIS_SUMMARY.md +363 -0
- package/README.md +230 -245
- package/dist/analysis/analysis-engine.d.ts +63 -0
- package/dist/analysis/analysis-engine.d.ts.map +1 -0
- package/dist/analysis/analysis-engine.js +322 -0
- package/dist/analysis/analysis-engine.js.map +1 -0
- package/dist/core/config.d.ts +1419 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +361 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/engine.d.ts +176 -0
- package/dist/core/engine.d.ts.map +1 -0
- package/dist/core/engine.js +604 -0
- package/dist/core/engine.js.map +1 -0
- package/dist/core/errors.d.ts +153 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +287 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/index.d.ts +7 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/{types.js → core/index.js} +8 -4
- package/dist/core/index.js.map +1 -0
- package/dist/core/pipeline.d.ts +121 -0
- package/dist/core/pipeline.d.ts.map +1 -0
- package/dist/core/pipeline.js +289 -0
- package/dist/core/pipeline.js.map +1 -0
- package/dist/core/rate-limiter.d.ts +58 -0
- package/dist/core/rate-limiter.d.ts.map +1 -0
- package/dist/core/rate-limiter.js +133 -0
- package/dist/core/rate-limiter.js.map +1 -0
- package/dist/core/session-manager.d.ts +96 -0
- package/dist/core/session-manager.d.ts.map +1 -0
- package/dist/core/session-manager.js +223 -0
- package/dist/core/session-manager.js.map +1 -0
- package/dist/creativity/creativity-engine.d.ts +6 -0
- package/dist/creativity/creativity-engine.d.ts.map +1 -0
- package/dist/creativity/creativity-engine.js +17 -0
- package/dist/creativity/creativity-engine.js.map +1 -0
- package/dist/index.d.ts +24 -32
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +130 -104
- package/dist/index.js.map +1 -1
- package/dist/learning/learning-engine.d.ts +6 -0
- package/dist/learning/learning-engine.d.ts.map +1 -0
- package/dist/learning/learning-engine.js +17 -0
- package/dist/learning/learning-engine.js.map +1 -0
- package/dist/llm/index.d.ts +10 -0
- package/dist/llm/index.d.ts.map +1 -0
- package/dist/llm/index.js +26 -0
- package/dist/llm/index.js.map +1 -0
- package/dist/llm/llm-service.d.ts +109 -0
- package/dist/llm/llm-service.d.ts.map +1 -0
- package/dist/llm/llm-service.js +224 -0
- package/dist/llm/llm-service.js.map +1 -0
- package/dist/llm/providers/base.d.ts +85 -0
- package/dist/llm/providers/base.d.ts.map +1 -0
- package/dist/llm/providers/base.js +57 -0
- package/dist/llm/providers/base.js.map +1 -0
- package/dist/llm/providers/cli.d.ts +23 -0
- package/dist/llm/providers/cli.d.ts.map +1 -0
- package/dist/llm/providers/cli.js +158 -0
- package/dist/llm/providers/cli.js.map +1 -0
- package/dist/llm/providers/gemini.d.ts +30 -0
- package/dist/llm/providers/gemini.d.ts.map +1 -0
- package/dist/llm/providers/gemini.js +168 -0
- package/dist/llm/providers/gemini.js.map +1 -0
- package/dist/llm/sanitization.d.ts +50 -0
- package/dist/llm/sanitization.d.ts.map +1 -0
- package/dist/llm/sanitization.js +149 -0
- package/dist/llm/sanitization.js.map +1 -0
- package/dist/{server.d.ts.map → mcp/server.d.ts.map} +1 -1
- package/dist/mcp/server.js +108 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/planning/planning-engine.d.ts +6 -0
- package/dist/planning/planning-engine.d.ts.map +1 -0
- package/dist/planning/planning-engine.js +17 -0
- package/dist/planning/planning-engine.js.map +1 -0
- package/dist/reasoning/reasoning-engine.d.ts +6 -0
- package/dist/reasoning/reasoning-engine.d.ts.map +1 -0
- package/dist/reasoning/reasoning-engine.js +17 -0
- package/dist/reasoning/reasoning-engine.js.map +1 -0
- package/dist/search/search-engine.d.ts +99 -0
- package/dist/search/search-engine.d.ts.map +1 -0
- package/dist/search/search-engine.js +271 -0
- package/dist/search/search-engine.js.map +1 -0
- package/dist/synthesis/synthesis-engine.d.ts +6 -0
- package/dist/synthesis/synthesis-engine.d.ts.map +1 -0
- package/dist/synthesis/synthesis-engine.js +17 -0
- package/dist/synthesis/synthesis-engine.js.map +1 -0
- package/dist/types/analysis.d.ts +1534 -49
- package/dist/types/analysis.d.ts.map +1 -1
- package/dist/types/analysis.js +250 -0
- package/dist/types/analysis.js.map +1 -1
- package/dist/types/core.d.ts +257 -30
- package/dist/types/core.d.ts.map +1 -1
- package/dist/types/core.js +148 -18
- package/dist/types/core.js.map +1 -1
- package/dist/types/creativity.d.ts +2871 -56
- package/dist/types/creativity.d.ts.map +1 -1
- package/dist/types/creativity.js +195 -0
- package/dist/types/creativity.js.map +1 -1
- package/dist/types/index.d.ts +6 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +17 -2
- package/dist/types/index.js.map +1 -1
- package/dist/types/learning.d.ts +851 -61
- package/dist/types/learning.d.ts.map +1 -1
- package/dist/types/learning.js +155 -0
- package/dist/types/learning.js.map +1 -1
- package/dist/types/planning.d.ts +2223 -71
- package/dist/types/planning.d.ts.map +1 -1
- package/dist/types/planning.js +190 -0
- package/dist/types/planning.js.map +1 -1
- package/dist/types/reasoning.d.ts +2209 -72
- package/dist/types/reasoning.d.ts.map +1 -1
- package/dist/types/reasoning.js +200 -1
- package/dist/types/reasoning.js.map +1 -1
- package/dist/types/search.d.ts +981 -53
- package/dist/types/search.d.ts.map +1 -1
- package/dist/types/search.js +137 -0
- package/dist/types/search.js.map +1 -1
- package/dist/types/synthesis.d.ts +583 -37
- package/dist/types/synthesis.d.ts.map +1 -1
- package/dist/types/synthesis.js +138 -0
- package/dist/types/synthesis.js.map +1 -1
- package/dist/utils/cache.d.ts +144 -0
- package/dist/utils/cache.d.ts.map +1 -0
- package/dist/utils/cache.js +288 -0
- package/dist/utils/cache.js.map +1 -0
- package/dist/utils/id-generator.d.ts +89 -0
- package/dist/utils/id-generator.d.ts.map +1 -0
- package/dist/utils/id-generator.js +132 -0
- package/dist/utils/id-generator.js.map +1 -0
- package/dist/utils/index.d.ts +11 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +33 -0
- package/dist/utils/index.js.map +1 -0
- package/dist/utils/logger.d.ts +142 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +248 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/metrics.d.ts +149 -0
- package/dist/utils/metrics.d.ts.map +1 -0
- package/dist/utils/metrics.js +296 -0
- package/dist/utils/metrics.js.map +1 -0
- package/dist/utils/timer.d.ts +7 -0
- package/dist/utils/timer.d.ts.map +1 -0
- package/dist/utils/timer.js +17 -0
- package/dist/utils/timer.js.map +1 -0
- package/dist/utils/validation.d.ts +147 -0
- package/dist/utils/validation.d.ts.map +1 -0
- package/dist/utils/validation.js +275 -0
- package/dist/utils/validation.js.map +1 -0
- package/docs/API.md +411 -0
- package/docs/ARCHITECTURE.md +271 -0
- package/docs/CHANGELOG.md +283 -0
- package/jest.config.js +28 -0
- package/package.json +43 -30
- package/src/analysis/analysis-engine.ts +383 -0
- package/src/core/config.ts +406 -0
- package/src/core/engine.ts +785 -0
- package/src/core/errors.ts +349 -0
- package/src/core/index.ts +12 -0
- package/src/core/pipeline.ts +424 -0
- package/src/core/rate-limiter.ts +155 -0
- package/src/core/session-manager.ts +269 -0
- package/src/creativity/creativity-engine.ts +14 -0
- package/src/index.ts +178 -0
- package/src/learning/learning-engine.ts +14 -0
- package/src/llm/index.ts +10 -0
- package/src/llm/llm-service.ts +285 -0
- package/src/llm/providers/base.ts +146 -0
- package/src/llm/providers/cli.ts +186 -0
- package/src/llm/providers/gemini.ts +201 -0
- package/src/llm/sanitization.ts +178 -0
- package/src/mcp/server.ts +117 -0
- package/src/planning/planning-engine.ts +14 -0
- package/src/reasoning/reasoning-engine.ts +14 -0
- package/src/search/search-engine.ts +333 -0
- package/src/synthesis/synthesis-engine.ts +14 -0
- package/src/types/analysis.ts +337 -0
- package/src/types/core.ts +342 -0
- package/src/types/creativity.ts +268 -0
- package/src/types/index.ts +31 -0
- package/src/types/learning.ts +215 -0
- package/src/types/planning.ts +251 -0
- package/src/types/reasoning.ts +288 -0
- package/src/types/search.ts +192 -0
- package/src/types/synthesis.ts +187 -0
- package/src/utils/cache.ts +363 -0
- package/src/utils/id-generator.ts +135 -0
- package/src/utils/index.ts +22 -0
- package/src/utils/logger.ts +290 -0
- package/src/utils/metrics.ts +380 -0
- package/src/utils/timer.ts +15 -0
- package/src/utils/validation.ts +297 -0
- package/tests/setup.ts +22 -0
- package/tests/unit/cache.test.ts +189 -0
- package/tests/unit/engine.test.ts +179 -0
- package/tests/unit/validation.test.ts +218 -0
- package/tsconfig.json +17 -12
- package/GEMINI.md +0 -68
- package/analysis.ts +0 -1063
- package/creativity.ts +0 -1055
- package/dist/analysis.d.ts +0 -54
- package/dist/analysis.d.ts.map +0 -1
- package/dist/analysis.js +0 -866
- package/dist/analysis.js.map +0 -1
- package/dist/creativity.d.ts +0 -81
- package/dist/creativity.d.ts.map +0 -1
- package/dist/creativity.js +0 -828
- package/dist/creativity.js.map +0 -1
- package/dist/engine.d.ts +0 -90
- package/dist/engine.d.ts.map +0 -1
- package/dist/engine.js +0 -677
- package/dist/engine.js.map +0 -1
- package/dist/examples.d.ts +0 -7
- package/dist/examples.d.ts.map +0 -1
- package/dist/examples.js +0 -506
- package/dist/examples.js.map +0 -1
- package/dist/learning.d.ts +0 -72
- package/dist/learning.d.ts.map +0 -1
- package/dist/learning.js +0 -615
- package/dist/learning.js.map +0 -1
- package/dist/llm-service.d.ts +0 -21
- package/dist/llm-service.d.ts.map +0 -1
- package/dist/llm-service.js +0 -100
- package/dist/llm-service.js.map +0 -1
- package/dist/planning.d.ts +0 -58
- package/dist/planning.d.ts.map +0 -1
- package/dist/planning.js +0 -824
- package/dist/planning.js.map +0 -1
- package/dist/reasoning.d.ts +0 -73
- package/dist/reasoning.d.ts.map +0 -1
- package/dist/reasoning.js +0 -845
- package/dist/reasoning.js.map +0 -1
- package/dist/search-discovery.d.ts +0 -73
- package/dist/search-discovery.d.ts.map +0 -1
- package/dist/search-discovery.js +0 -548
- package/dist/search-discovery.js.map +0 -1
- package/dist/server.js +0 -113
- package/dist/server.js.map +0 -1
- package/dist/types/engine.d.ts +0 -55
- package/dist/types/engine.d.ts.map +0 -1
- package/dist/types/engine.js +0 -3
- package/dist/types/engine.js.map +0 -1
- package/dist/types.d.ts +0 -6
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js.map +0 -1
- package/engine.ts +0 -947
- package/examples.ts +0 -717
- package/index.ts +0 -106
- package/learning.ts +0 -779
- package/llm-service.ts +0 -120
- package/planning.ts +0 -1028
- package/reasoning.ts +0 -1079
- package/search-discovery.ts +0 -700
- package/server.ts +0 -115
- package/types/analysis.ts +0 -69
- package/types/core.ts +0 -90
- package/types/creativity.ts +0 -72
- package/types/engine.ts +0 -60
- package/types/index.ts +0 -9
- package/types/learning.ts +0 -69
- package/types/planning.ts +0 -85
- package/types/reasoning.ts +0 -92
- package/types/search.ts +0 -58
- package/types/synthesis.ts +0 -42
- package/types.ts +0 -6
- /package/dist/{server.d.ts → mcp/server.d.ts} +0 -0
|
@@ -0,0 +1,785 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sequential Thinking Engine - Core Engine for gthinking v2.0.0
|
|
3
|
+
* Main orchestrator that coordinates all thinking stages
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { EventEmitter } from 'events';
|
|
7
|
+
import {
|
|
8
|
+
ThinkingStage,
|
|
9
|
+
ThinkingRequest,
|
|
10
|
+
ThinkingResponse,
|
|
11
|
+
StageResult,
|
|
12
|
+
SynthesisResult,
|
|
13
|
+
CreativeResult,
|
|
14
|
+
Plan,
|
|
15
|
+
BaseConfig,
|
|
16
|
+
AnalysisType,
|
|
17
|
+
EngineConfig,
|
|
18
|
+
} from '../types';
|
|
19
|
+
import { GThinkingError, TimeoutError, StageError, withRetry } from './errors';
|
|
20
|
+
import { ConfigManager, defaultConfig, GThinkingConfig } from './config';
|
|
21
|
+
import { Logger, PerformanceLogger } from '../utils/logger';
|
|
22
|
+
import { Cache } from '../utils/cache';
|
|
23
|
+
import { metricsCollector, trackOperation } from '../utils/metrics';
|
|
24
|
+
import { generateUUID } from '../utils/id-generator';
|
|
25
|
+
import { validateSchema } from '../utils/validation';
|
|
26
|
+
import { z } from 'zod';
|
|
27
|
+
|
|
28
|
+
// Import engines
|
|
29
|
+
import { LLMService, createLLMService } from '../llm/llm-service';
|
|
30
|
+
import { AnalysisEngine, createAnalysisEngine } from '../analysis/analysis-engine';
|
|
31
|
+
// import { SearchDiscoveryEngine } from '../search/search-engine';
|
|
32
|
+
// import { ReasoningEngine } from '../reasoning/reasoning-engine';
|
|
33
|
+
// import { LearningEngine } from '../learning/learning-engine';
|
|
34
|
+
// import { PlanningEngine } from '../planning/planning-engine';
|
|
35
|
+
// import { CreativityEngine } from '../creativity/creativity-engine';
|
|
36
|
+
// import { SynthesisEngine } from '../synthesis/synthesis-engine';
|
|
37
|
+
|
|
38
|
+
const logger = new Logger('SequentialThinkingEngine');
|
|
39
|
+
const perfLogger = new PerformanceLogger();
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Thinking Request Schema
|
|
43
|
+
*/
|
|
44
|
+
const ThinkingRequestSchema = z.object({
|
|
45
|
+
id: z.string().uuid().optional(),
|
|
46
|
+
query: z.string().min(1).max(10000),
|
|
47
|
+
context: z.array(z.string()).default([]),
|
|
48
|
+
preferredStages: z.array(z.nativeEnum(ThinkingStage)).optional(),
|
|
49
|
+
options: z.object({
|
|
50
|
+
depth: z.enum(['shallow', 'medium', 'deep']).default('medium'),
|
|
51
|
+
complexity: z.enum(['simple', 'moderate', 'complex']).default('moderate'),
|
|
52
|
+
timeout: z.number().positive().optional(),
|
|
53
|
+
maxStages: z.number().positive().optional(),
|
|
54
|
+
stream: z.boolean().default(false),
|
|
55
|
+
}).default({}),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Stage Executor Interface
|
|
60
|
+
*/
|
|
61
|
+
interface StageExecutor {
|
|
62
|
+
execute(request: ThinkingRequest, context: StageContext): Promise<StageResult>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Stage Context Interface
|
|
67
|
+
*/
|
|
68
|
+
interface StageContext {
|
|
69
|
+
sessionId: string;
|
|
70
|
+
stageResults: Map<ThinkingStage, StageResult>;
|
|
71
|
+
config: GThinkingConfig;
|
|
72
|
+
cache: Cache<unknown>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Sequential Thinking Engine - Main orchestrator
|
|
77
|
+
*/
|
|
78
|
+
export class SequentialThinkingEngine extends EventEmitter {
|
|
79
|
+
private config: GThinkingConfig;
|
|
80
|
+
private configManager: ConfigManager;
|
|
81
|
+
private cache: Cache<unknown>;
|
|
82
|
+
private sessions: Map<string, Session> = new Map();
|
|
83
|
+
private stageExecutors: Map<ThinkingStage, StageExecutor> = new Map();
|
|
84
|
+
private initialized = false;
|
|
85
|
+
|
|
86
|
+
// Engines
|
|
87
|
+
private llmService: LLMService | undefined;
|
|
88
|
+
private analysisEngine: AnalysisEngine | undefined;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Create a new SequentialThinkingEngine
|
|
92
|
+
* @param config - Optional configuration
|
|
93
|
+
*/
|
|
94
|
+
constructor(config?: Partial<GThinkingConfig>) {
|
|
95
|
+
super();
|
|
96
|
+
this.configManager = new ConfigManager(config);
|
|
97
|
+
this.config = this.configManager.getConfig();
|
|
98
|
+
this.cache = new Cache({
|
|
99
|
+
maxSize: this.config.cache.maxSize,
|
|
100
|
+
defaultTTL: this.config.cache.defaultTTL,
|
|
101
|
+
checkInterval: this.config.cache.checkInterval,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
this.initializeEngines();
|
|
105
|
+
this.startSessionCleanup();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Initialize all stage engines
|
|
110
|
+
*/
|
|
111
|
+
private initializeEngines(): void {
|
|
112
|
+
logger.info('Initializing Sequential Thinking Engine v2.0.0');
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
// Map configuration to EngineConfig
|
|
116
|
+
const engineConfig: EngineConfig = {
|
|
117
|
+
llmProvider: this.config.llm.provider,
|
|
118
|
+
llmApiKey: this.config.llm.apiKey,
|
|
119
|
+
llmModel: this.config.llm.model,
|
|
120
|
+
llmCliCommand: this.config.llm.cliCommand,
|
|
121
|
+
llmCliArgs: this.config.llm.cliArgs,
|
|
122
|
+
llmCliPromptPassingMethod: this.config.llm.cliPromptPassingMethod,
|
|
123
|
+
llmCliPromptFlag: this.config.llm.cliPromptFlag,
|
|
124
|
+
llmTimeoutMs: this.config.llm.timeout,
|
|
125
|
+
llmMaxRetries: this.config.llm.maxRetries,
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// Initialize LLM Service
|
|
129
|
+
this.llmService = createLLMService(engineConfig);
|
|
130
|
+
|
|
131
|
+
// Initialize Analysis Engine
|
|
132
|
+
this.analysisEngine = createAnalysisEngine(this.llmService);
|
|
133
|
+
|
|
134
|
+
// Register Analysis Executor
|
|
135
|
+
this.stageExecutors.set(ThinkingStage.ANALYSIS, {
|
|
136
|
+
execute: async (request: ThinkingRequest, context: StageContext) => {
|
|
137
|
+
if (!this.analysisEngine) throw new Error('Analysis Engine not initialized');
|
|
138
|
+
|
|
139
|
+
// Map ThinkingRequest to AnalysisRequest
|
|
140
|
+
const analysisRequest = {
|
|
141
|
+
content: request.query, // Using query as content for now
|
|
142
|
+
types: [
|
|
143
|
+
AnalysisType.SENTIMENT,
|
|
144
|
+
AnalysisType.TOPIC,
|
|
145
|
+
AnalysisType.KEYWORD,
|
|
146
|
+
AnalysisType.SUMMARY
|
|
147
|
+
],
|
|
148
|
+
options: {
|
|
149
|
+
depth: request.options?.depth || 'medium',
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const result = await this.analysisEngine.analyze(analysisRequest);
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
stage: ThinkingStage.ANALYSIS,
|
|
157
|
+
status: 'completed',
|
|
158
|
+
success: result.success,
|
|
159
|
+
confidence: result.confidence,
|
|
160
|
+
data: result,
|
|
161
|
+
timestamp: result.timestamp,
|
|
162
|
+
duration: result.duration,
|
|
163
|
+
errors: result.errors,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// Register placeholders for other stages
|
|
169
|
+
const placeholderExecutor: StageExecutor = {
|
|
170
|
+
execute: async (request, context) => ({
|
|
171
|
+
stage: ThinkingStage.SYNTHESIS, // Will be overwritten
|
|
172
|
+
status: 'completed',
|
|
173
|
+
success: true,
|
|
174
|
+
confidence: 0.8,
|
|
175
|
+
timestamp: new Date(),
|
|
176
|
+
duration: 100,
|
|
177
|
+
data: { placeholder: true },
|
|
178
|
+
errors: []
|
|
179
|
+
})
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// Register other stages
|
|
183
|
+
Object.values(ThinkingStage).forEach(stage => {
|
|
184
|
+
if (stage !== ThinkingStage.ANALYSIS && !this.stageExecutors.has(stage)) {
|
|
185
|
+
this.stageExecutors.set(stage, {
|
|
186
|
+
execute: async (req, ctx) => {
|
|
187
|
+
const result = await placeholderExecutor.execute(req, ctx);
|
|
188
|
+
return { ...result, stage };
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
this.initialized = true;
|
|
195
|
+
logger.info('Sequential Thinking Engine initialized successfully');
|
|
196
|
+
} catch (error) {
|
|
197
|
+
logger.error('Failed to initialize engines', { error });
|
|
198
|
+
// Don't throw here to allow partial initialization, but log error
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Execute the full thinking pipeline
|
|
204
|
+
* @param request - The thinking request
|
|
205
|
+
* @returns The synthesis result
|
|
206
|
+
*/
|
|
207
|
+
public async think(request: unknown): Promise<SynthesisResult> {
|
|
208
|
+
const startTime = Date.now();
|
|
209
|
+
const sessionId = generateUUID();
|
|
210
|
+
let session: Session | undefined;
|
|
211
|
+
|
|
212
|
+
try {
|
|
213
|
+
// Validate request
|
|
214
|
+
const validatedRequest = validateSchema(ThinkingRequestSchema, request);
|
|
215
|
+
const thinkingRequest: ThinkingRequest = {
|
|
216
|
+
...validatedRequest,
|
|
217
|
+
id: validatedRequest.id || sessionId,
|
|
218
|
+
} as ThinkingRequest;
|
|
219
|
+
|
|
220
|
+
logger.info(`Starting thinking session: ${sessionId}`, {
|
|
221
|
+
query: thinkingRequest.query,
|
|
222
|
+
stages: thinkingRequest.preferredStages,
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
this.emit('thinking:start', { sessionId, request: thinkingRequest });
|
|
226
|
+
|
|
227
|
+
// Check cache
|
|
228
|
+
const cacheKey = this.generateCacheKey(thinkingRequest);
|
|
229
|
+
if (this.config.cache.enabled) {
|
|
230
|
+
const cached = this.cache.get(cacheKey) as SynthesisResult | undefined;
|
|
231
|
+
if (cached) {
|
|
232
|
+
logger.info(`Cache hit for session: ${sessionId}`);
|
|
233
|
+
metricsCollector.counter('cache_hit', 1, { type: 'think' });
|
|
234
|
+
return cached;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Create session
|
|
239
|
+
session = {
|
|
240
|
+
id: sessionId,
|
|
241
|
+
request: thinkingRequest,
|
|
242
|
+
stageResults: new Map(),
|
|
243
|
+
startTime,
|
|
244
|
+
status: 'running',
|
|
245
|
+
metadata: {}
|
|
246
|
+
};
|
|
247
|
+
this.sessions.set(sessionId, session);
|
|
248
|
+
|
|
249
|
+
// Determine stages to execute
|
|
250
|
+
const stages = this.determineStages(thinkingRequest);
|
|
251
|
+
logger.info(`Executing stages: ${stages.join(', ')}`);
|
|
252
|
+
|
|
253
|
+
// Execute stages
|
|
254
|
+
const stageResults = await this.executeStages(stages, thinkingRequest, session);
|
|
255
|
+
|
|
256
|
+
// Synthesize results
|
|
257
|
+
const synthesisResult = await this.synthesizeResults(
|
|
258
|
+
thinkingRequest,
|
|
259
|
+
stageResults,
|
|
260
|
+
sessionId
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
// Cache result
|
|
264
|
+
if (this.config.cache.enabled) {
|
|
265
|
+
this.cache.set(cacheKey, synthesisResult);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Update session
|
|
269
|
+
session.status = 'completed';
|
|
270
|
+
session.endTime = Date.now();
|
|
271
|
+
session.result = synthesisResult;
|
|
272
|
+
|
|
273
|
+
this.emit('thinking:complete', { sessionId, result: synthesisResult });
|
|
274
|
+
|
|
275
|
+
logger.info(`Thinking session completed: ${sessionId}`, {
|
|
276
|
+
duration: Date.now() - startTime,
|
|
277
|
+
confidence: synthesisResult.confidence,
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
return synthesisResult;
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (session) {
|
|
283
|
+
session.status = 'failed';
|
|
284
|
+
session.error = error as Error;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
logger.error(`Thinking session failed: ${sessionId}`, {
|
|
288
|
+
error: (error as Error).message,
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
this.emit('thinking:error', { sessionId, error });
|
|
292
|
+
|
|
293
|
+
if (error instanceof GThinkingError) {
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
throw new GThinkingError(
|
|
298
|
+
`Thinking process failed: ${(error as Error).message}`,
|
|
299
|
+
'THINKING_ERROR',
|
|
300
|
+
{ originalError: error }
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Quick search with minimal stages
|
|
307
|
+
* @param query - The search query
|
|
308
|
+
* @returns Synthesis result
|
|
309
|
+
*/
|
|
310
|
+
public async quickSearch(query: string): Promise<SynthesisResult> {
|
|
311
|
+
return this.think({
|
|
312
|
+
query,
|
|
313
|
+
preferredStages: [ThinkingStage.SEARCH, ThinkingStage.ANALYSIS, ThinkingStage.SYNTHESIS],
|
|
314
|
+
options: { depth: 'shallow', complexity: 'simple' },
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Deep analysis with all stages
|
|
320
|
+
* @param query - The analysis query
|
|
321
|
+
* @returns Synthesis result
|
|
322
|
+
*/
|
|
323
|
+
public async deepAnalysis(query: string): Promise<SynthesisResult> {
|
|
324
|
+
return this.think({
|
|
325
|
+
query,
|
|
326
|
+
preferredStages: [
|
|
327
|
+
ThinkingStage.SEARCH,
|
|
328
|
+
ThinkingStage.ANALYSIS,
|
|
329
|
+
ThinkingStage.REASONING,
|
|
330
|
+
ThinkingStage.LEARNING,
|
|
331
|
+
ThinkingStage.PLANNING,
|
|
332
|
+
ThinkingStage.CREATIVITY,
|
|
333
|
+
ThinkingStage.SYNTHESIS,
|
|
334
|
+
ThinkingStage.EVALUATION,
|
|
335
|
+
],
|
|
336
|
+
options: { depth: 'deep', complexity: 'complex' },
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Creative problem solving
|
|
342
|
+
* @param challenge - The creative challenge
|
|
343
|
+
* @returns Creative result
|
|
344
|
+
*/
|
|
345
|
+
public async creativeSolve(challenge: string): Promise<CreativeResult> {
|
|
346
|
+
// This will be implemented when CreativityEngine is ready
|
|
347
|
+
throw new GThinkingError(
|
|
348
|
+
'Creative solve not yet implemented in v2.0.0',
|
|
349
|
+
'NOT_IMPLEMENTED'
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Create an execution plan
|
|
355
|
+
* @param goal - The planning goal
|
|
356
|
+
* @returns Execution plan
|
|
357
|
+
*/
|
|
358
|
+
public async createPlan(goal: string): Promise<Plan> {
|
|
359
|
+
// This will be implemented when PlanningEngine is ready
|
|
360
|
+
throw new GThinkingError(
|
|
361
|
+
'Create plan not yet implemented in v2.0.0',
|
|
362
|
+
'NOT_IMPLEMENTED'
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Determine which stages to execute based on the request
|
|
368
|
+
* @param request - The thinking request
|
|
369
|
+
* @returns Array of stages to execute
|
|
370
|
+
*/
|
|
371
|
+
private determineStages(request: ThinkingRequest): ThinkingStage[] {
|
|
372
|
+
// If preferred stages are specified, use them
|
|
373
|
+
if (request.preferredStages && request.preferredStages.length > 0) {
|
|
374
|
+
return request.preferredStages.filter(stage =>
|
|
375
|
+
this.config.pipeline.stages[stage]?.enabled
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Dynamic stage selection based on query analysis
|
|
380
|
+
if (this.config.pipeline.enableDynamicPipeline) {
|
|
381
|
+
return this.analyzeQueryAndSelectStages(request.query);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// Default stages
|
|
385
|
+
return [
|
|
386
|
+
ThinkingStage.SEARCH,
|
|
387
|
+
ThinkingStage.ANALYSIS,
|
|
388
|
+
ThinkingStage.REASONING,
|
|
389
|
+
ThinkingStage.SYNTHESIS,
|
|
390
|
+
];
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Analyze query and select appropriate stages
|
|
395
|
+
* @param query - The query to analyze
|
|
396
|
+
* @returns Array of selected stages
|
|
397
|
+
*/
|
|
398
|
+
private analyzeQueryAndSelectStages(query: string): ThinkingStage[] {
|
|
399
|
+
const lowerQuery = query.toLowerCase();
|
|
400
|
+
const stages: ThinkingStage[] = [];
|
|
401
|
+
|
|
402
|
+
// Always include search for information gathering
|
|
403
|
+
stages.push(ThinkingStage.SEARCH);
|
|
404
|
+
|
|
405
|
+
// Check for planning keywords
|
|
406
|
+
if (/\b(plan|schedule|timeline|project|roadmap|strategy)\b/.test(lowerQuery)) {
|
|
407
|
+
stages.push(ThinkingStage.PLANNING);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Check for creative keywords
|
|
411
|
+
if (/\b(idea|creative|brainstorm|innovation|design|solution)\b/.test(lowerQuery)) {
|
|
412
|
+
stages.push(ThinkingStage.CREATIVITY);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Check for reasoning keywords
|
|
416
|
+
if (/\b(why|how|because|reason|analyze|compare|evaluate)\b/.test(lowerQuery)) {
|
|
417
|
+
stages.push(ThinkingStage.ANALYSIS);
|
|
418
|
+
stages.push(ThinkingStage.REASONING);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Always include synthesis
|
|
422
|
+
stages.push(ThinkingStage.SYNTHESIS);
|
|
423
|
+
|
|
424
|
+
// Include evaluation for complex queries
|
|
425
|
+
if (lowerQuery.length > 100 || stages.length > 4) {
|
|
426
|
+
stages.push(ThinkingStage.EVALUATION);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
return stages.filter(stage => this.config.pipeline.stages[stage]?.enabled);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Execute thinking stages
|
|
434
|
+
* @param stages - Stages to execute
|
|
435
|
+
* @param request - The thinking request
|
|
436
|
+
* @param session - The session
|
|
437
|
+
* @returns Map of stage results
|
|
438
|
+
*/
|
|
439
|
+
private async executeStages(
|
|
440
|
+
stages: ThinkingStage[],
|
|
441
|
+
request: ThinkingRequest,
|
|
442
|
+
session: Session
|
|
443
|
+
): Promise<Map<ThinkingStage, StageResult>> {
|
|
444
|
+
const stageResults = new Map<ThinkingStage, StageResult>();
|
|
445
|
+
const context: StageContext = {
|
|
446
|
+
sessionId: session.id,
|
|
447
|
+
stageResults,
|
|
448
|
+
config: this.config,
|
|
449
|
+
cache: this.cache,
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
// Execute stages sequentially or in parallel based on configuration
|
|
453
|
+
const parallelStages = stages.filter(stage =>
|
|
454
|
+
this.config.pipeline.stages[stage]?.parallel
|
|
455
|
+
);
|
|
456
|
+
const sequentialStages = stages.filter(stage =>
|
|
457
|
+
!this.config.pipeline.stages[stage]?.parallel
|
|
458
|
+
);
|
|
459
|
+
|
|
460
|
+
// Execute parallel stages
|
|
461
|
+
if (parallelStages.length > 0) {
|
|
462
|
+
const parallelResults = await Promise.all(
|
|
463
|
+
parallelStages.map(stage => this.executeStage(stage, request, context))
|
|
464
|
+
);
|
|
465
|
+
parallelStages.forEach((stage, index) => {
|
|
466
|
+
stageResults.set(stage, parallelResults[index]);
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// Execute sequential stages
|
|
471
|
+
for (const stage of sequentialStages) {
|
|
472
|
+
const result = await this.executeStage(stage, request, context);
|
|
473
|
+
stageResults.set(stage, result);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
return stageResults;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Execute a single stage
|
|
481
|
+
* @param stage - The stage to execute
|
|
482
|
+
* @param request - The thinking request
|
|
483
|
+
* @param context - The stage context
|
|
484
|
+
* @returns Stage result
|
|
485
|
+
*/
|
|
486
|
+
private async executeStage(
|
|
487
|
+
stage: ThinkingStage,
|
|
488
|
+
request: ThinkingRequest,
|
|
489
|
+
context: StageContext
|
|
490
|
+
): Promise<StageResult> {
|
|
491
|
+
const stageStartTime = Date.now();
|
|
492
|
+
const stageConfig = this.config.pipeline.stages[stage];
|
|
493
|
+
|
|
494
|
+
logger.info(`Executing stage: ${stage}`, { sessionId: context.sessionId });
|
|
495
|
+
this.emit('thinking:stage:start', { sessionId: context.sessionId, stage });
|
|
496
|
+
|
|
497
|
+
try {
|
|
498
|
+
const timeout = request.options?.timeout || stageConfig?.timeout || 60000;
|
|
499
|
+
|
|
500
|
+
const result = await withRetry(
|
|
501
|
+
async () => this.executeStageWithTimeout(stage, request, context, timeout),
|
|
502
|
+
{ maxRetries: stageConfig?.maxRetries || 2 }
|
|
503
|
+
);
|
|
504
|
+
|
|
505
|
+
const duration = Date.now() - stageStartTime;
|
|
506
|
+
|
|
507
|
+
logger.info(`Stage completed: ${stage}`, {
|
|
508
|
+
sessionId: context.sessionId,
|
|
509
|
+
duration,
|
|
510
|
+
confidence: result.confidence,
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
this.emit('thinking:stage:complete', {
|
|
514
|
+
sessionId: context.sessionId,
|
|
515
|
+
stage,
|
|
516
|
+
result,
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
metricsCollector.counter('stage_completed', 1, { stage });
|
|
520
|
+
metricsCollector.histogram('stage_duration', duration, { stage });
|
|
521
|
+
|
|
522
|
+
return result;
|
|
523
|
+
} catch (error) {
|
|
524
|
+
logger.error(`Stage failed: ${stage}`, {
|
|
525
|
+
sessionId: context.sessionId,
|
|
526
|
+
error: (error as Error).message,
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
this.emit('thinking:stage:error', {
|
|
530
|
+
sessionId: context.sessionId,
|
|
531
|
+
stage,
|
|
532
|
+
error,
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
metricsCollector.counter('stage_error', 1, { stage });
|
|
536
|
+
|
|
537
|
+
// If stage is required, throw error
|
|
538
|
+
if (stageConfig?.required) {
|
|
539
|
+
throw new StageError(
|
|
540
|
+
`Required stage ${stage} failed: ${(error as Error).message}`,
|
|
541
|
+
stage,
|
|
542
|
+
false
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Return error result for non-required stages
|
|
547
|
+
return {
|
|
548
|
+
stage,
|
|
549
|
+
success: false,
|
|
550
|
+
status: 'failed',
|
|
551
|
+
data: null,
|
|
552
|
+
confidence: 0,
|
|
553
|
+
timestamp: new Date(),
|
|
554
|
+
duration: Date.now() - stageStartTime,
|
|
555
|
+
errors: [(error as Error).message],
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Execute stage with timeout
|
|
562
|
+
* @param stage - The stage to execute
|
|
563
|
+
* @param request - The thinking request
|
|
564
|
+
* @param context - The stage context
|
|
565
|
+
* @param timeout - Timeout in milliseconds
|
|
566
|
+
* @returns Stage result
|
|
567
|
+
*/
|
|
568
|
+
private async executeStageWithTimeout(
|
|
569
|
+
stage: ThinkingStage,
|
|
570
|
+
request: ThinkingRequest,
|
|
571
|
+
context: StageContext,
|
|
572
|
+
timeout: number
|
|
573
|
+
): Promise<StageResult> {
|
|
574
|
+
return Promise.race([
|
|
575
|
+
this.executeStageLogic(stage, request, context),
|
|
576
|
+
new Promise<never>((_, reject) =>
|
|
577
|
+
setTimeout(() => reject(new TimeoutError(`Stage ${stage} timed out`, stage)), timeout)
|
|
578
|
+
),
|
|
579
|
+
]);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Execute stage logic
|
|
584
|
+
* @param stage - The stage to execute
|
|
585
|
+
* @param request - The thinking request
|
|
586
|
+
* @param context - The stage context
|
|
587
|
+
* @returns Stage result
|
|
588
|
+
*/
|
|
589
|
+
private async executeStageLogic(
|
|
590
|
+
stage: ThinkingStage,
|
|
591
|
+
request: ThinkingRequest,
|
|
592
|
+
context: StageContext
|
|
593
|
+
): Promise<StageResult> {
|
|
594
|
+
const executor = this.stageExecutors.get(stage);
|
|
595
|
+
|
|
596
|
+
if (executor) {
|
|
597
|
+
return executor.execute(request, context);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// Fallback if no executor found (should not happen if initialized)
|
|
601
|
+
logger.warn(`No executor found for stage: ${stage}, using fallback`);
|
|
602
|
+
|
|
603
|
+
return {
|
|
604
|
+
stage,
|
|
605
|
+
success: true,
|
|
606
|
+
status: 'completed',
|
|
607
|
+
confidence: 0.8,
|
|
608
|
+
timestamp: new Date(),
|
|
609
|
+
duration: 1000,
|
|
610
|
+
data: { placeholder: true },
|
|
611
|
+
errors: [],
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Synthesize stage results into final output
|
|
617
|
+
* @param request - The thinking request
|
|
618
|
+
* @param stageResults - Map of stage results
|
|
619
|
+
* @param sessionId - The session ID
|
|
620
|
+
* @returns Synthesis result
|
|
621
|
+
*/
|
|
622
|
+
private async synthesizeResults(
|
|
623
|
+
request: ThinkingRequest,
|
|
624
|
+
stageResults: Map<ThinkingStage, StageResult>,
|
|
625
|
+
sessionId: string
|
|
626
|
+
): Promise<SynthesisResult> {
|
|
627
|
+
// This will be implemented when SynthesisEngine is ready
|
|
628
|
+
// For now, return a placeholder result
|
|
629
|
+
|
|
630
|
+
const results = Array.from(stageResults.entries()).map(([stage, result]) => ({
|
|
631
|
+
stage,
|
|
632
|
+
result: result.data || {},
|
|
633
|
+
confidence: result.confidence,
|
|
634
|
+
}));
|
|
635
|
+
|
|
636
|
+
return {
|
|
637
|
+
success: true,
|
|
638
|
+
confidence: 0.8,
|
|
639
|
+
timestamp: new Date(),
|
|
640
|
+
duration: 1000,
|
|
641
|
+
errors: [],
|
|
642
|
+
query: request.query,
|
|
643
|
+
summary: `Analysis of: ${request.query}`,
|
|
644
|
+
keyFindings: results.map(r => `${r.stage}: ${r.confidence}`),
|
|
645
|
+
recommendations: [],
|
|
646
|
+
evaluation: [],
|
|
647
|
+
devilsAdvocate: [],
|
|
648
|
+
confidenceBreakdown: {
|
|
649
|
+
overall: 0.8,
|
|
650
|
+
byStage: Object.fromEntries(
|
|
651
|
+
Array.from(stageResults.entries()).map(([stage, result]) => [stage, result.confidence])
|
|
652
|
+
),
|
|
653
|
+
bySource: {},
|
|
654
|
+
factors: [],
|
|
655
|
+
},
|
|
656
|
+
nextSteps: [],
|
|
657
|
+
additionalConsiderations: [],
|
|
658
|
+
sources: [],
|
|
659
|
+
metadata: { sessionId },
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Generate cache key for a request
|
|
665
|
+
* @param request - The thinking request
|
|
666
|
+
* @returns Cache key
|
|
667
|
+
*/
|
|
668
|
+
private generateCacheKey(request: ThinkingRequest): string {
|
|
669
|
+
const keyData = {
|
|
670
|
+
query: request.query,
|
|
671
|
+
stages: request.preferredStages,
|
|
672
|
+
depth: request.options?.depth,
|
|
673
|
+
complexity: request.options?.complexity,
|
|
674
|
+
};
|
|
675
|
+
return `think:${JSON.stringify(keyData)}`;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Start session cleanup interval
|
|
680
|
+
*/
|
|
681
|
+
private startSessionCleanup(): void {
|
|
682
|
+
setInterval(() => {
|
|
683
|
+
const now = Date.now();
|
|
684
|
+
const ttl = this.config.session.sessionTTL;
|
|
685
|
+
|
|
686
|
+
for (const [sessionId, session] of this.sessions.entries()) {
|
|
687
|
+
if (session.status === 'completed' || session.status === 'failed') {
|
|
688
|
+
const endTime = session.endTime || now;
|
|
689
|
+
if (now - endTime > ttl) {
|
|
690
|
+
this.sessions.delete(sessionId);
|
|
691
|
+
logger.debug(`Cleaned up session: ${sessionId}`);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}, 60000); // Clean up every minute
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* Get session by ID
|
|
700
|
+
* @param sessionId - The session ID
|
|
701
|
+
* @returns The session or undefined
|
|
702
|
+
*/
|
|
703
|
+
public getSession(sessionId: string): Session | undefined {
|
|
704
|
+
return this.sessions.get(sessionId);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Get all active sessions
|
|
709
|
+
* @returns Array of active sessions
|
|
710
|
+
*/
|
|
711
|
+
public getActiveSessions(): Session[] {
|
|
712
|
+
return Array.from(this.sessions.values()).filter(
|
|
713
|
+
s => s.status === 'running'
|
|
714
|
+
);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Cancel a running session
|
|
719
|
+
* @param sessionId - The session ID
|
|
720
|
+
* @returns True if cancelled
|
|
721
|
+
*/
|
|
722
|
+
public cancelSession(sessionId: string): boolean {
|
|
723
|
+
const session = this.sessions.get(sessionId);
|
|
724
|
+
if (session && session.status === 'running') {
|
|
725
|
+
session.status = 'cancelled';
|
|
726
|
+
session.endTime = Date.now();
|
|
727
|
+
this.emit('thinking:cancelled', { sessionId });
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Get engine statistics
|
|
735
|
+
* @returns Engine statistics
|
|
736
|
+
*/
|
|
737
|
+
public getStats(): {
|
|
738
|
+
sessions: number;
|
|
739
|
+
activeSessions: number;
|
|
740
|
+
cacheStats: ReturnType<Cache<unknown>['getStats']>;
|
|
741
|
+
} {
|
|
742
|
+
return {
|
|
743
|
+
sessions: this.sessions.size,
|
|
744
|
+
activeSessions: this.getActiveSessions().length,
|
|
745
|
+
cacheStats: this.cache.getStats(),
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Dispose of the engine
|
|
751
|
+
*/
|
|
752
|
+
public dispose(): void {
|
|
753
|
+
this.cache.dispose();
|
|
754
|
+
this.sessions.clear();
|
|
755
|
+
this.removeAllListeners();
|
|
756
|
+
logger.info('Sequential Thinking Engine disposed');
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* Session interface
|
|
762
|
+
*/
|
|
763
|
+
interface Session {
|
|
764
|
+
id: string;
|
|
765
|
+
request: ThinkingRequest;
|
|
766
|
+
stageResults: Map<ThinkingStage, StageResult>;
|
|
767
|
+
startTime: number;
|
|
768
|
+
endTime?: number;
|
|
769
|
+
status: 'running' | 'completed' | 'failed' | 'cancelled';
|
|
770
|
+
result?: SynthesisResult;
|
|
771
|
+
error?: Error;
|
|
772
|
+
metadata: Record<string, unknown>;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Create a new SequentialThinkingEngine instance
|
|
777
|
+
* @param config - Optional configuration
|
|
778
|
+
* @returns New engine instance
|
|
779
|
+
*/
|
|
780
|
+
export function createEngine(config?: Partial<GThinkingConfig>): SequentialThinkingEngine {
|
|
781
|
+
return new SequentialThinkingEngine(config);
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// Export singleton instance
|
|
785
|
+
export const thinkingEngine = new SequentialThinkingEngine();
|