@gotza02/seq-thinking 1.1.2 → 1.1.3

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 (69) hide show
  1. package/README.md +42 -4
  2. package/data/agents/1770106504306-dljh9ef.json +68 -0
  3. package/data/agents/1770106504310-4oarrst.json +58 -0
  4. package/data/agents/1770106540588-pvitt55.json +68 -0
  5. package/data/agents/1770106540595-z2ya871.json +58 -0
  6. package/data/agents/1770106710890-0e2naq1.json +68 -0
  7. package/data/agents/1770106710893-r076yxx.json +58 -0
  8. package/data/agents/1770109212161-4ybd0i7.json +68 -0
  9. package/data/agents/1770109212166-gkhya8h.json +58 -0
  10. package/data/sessions/1770100622009-5afiuyv.json +499 -0
  11. package/data/sessions/1770106504312-75zk750.json +107 -0
  12. package/data/sessions/1770106540597-z8e8soo.json +150 -0
  13. package/data/sessions/1770106710894-0kxgy5x.json +150 -0
  14. package/data/sessions/1770109212169-zpddeb9.json +150 -0
  15. package/dist/__tests__/sequential-thinking.test.js +21 -21
  16. package/dist/__tests__/sequential-thinking.test.js.map +1 -1
  17. package/dist/agents/base-agent.d.ts +1 -0
  18. package/dist/agents/base-agent.d.ts.map +1 -1
  19. package/dist/agents/base-agent.js +5 -3
  20. package/dist/agents/base-agent.js.map +1 -1
  21. package/dist/agents/meta-reasoning-agent.d.ts +3 -54
  22. package/dist/agents/meta-reasoning-agent.d.ts.map +1 -1
  23. package/dist/agents/meta-reasoning-agent.js +35 -328
  24. package/dist/agents/meta-reasoning-agent.js.map +1 -1
  25. package/dist/agents/synthesizer-agent.d.ts +3 -17
  26. package/dist/agents/synthesizer-agent.d.ts.map +1 -1
  27. package/dist/agents/synthesizer-agent.js +41 -139
  28. package/dist/agents/synthesizer-agent.js.map +1 -1
  29. package/dist/mcp-server.d.ts.map +1 -1
  30. package/dist/mcp-server.js +9 -6
  31. package/dist/mcp-server.js.map +1 -1
  32. package/dist/real_world_test.d.ts +2 -0
  33. package/dist/real_world_test.d.ts.map +1 -0
  34. package/dist/real_world_test.js +78 -0
  35. package/dist/real_world_test.js.map +1 -0
  36. package/dist/sequential-thinking.d.ts +5 -5
  37. package/dist/sequential-thinking.d.ts.map +1 -1
  38. package/dist/sequential-thinking.js +68 -32
  39. package/dist/sequential-thinking.js.map +1 -1
  40. package/dist/swarm-coordinator.d.ts +1 -1
  41. package/dist/swarm-coordinator.d.ts.map +1 -1
  42. package/dist/swarm-coordinator.js +39 -13
  43. package/dist/swarm-coordinator.js.map +1 -1
  44. package/dist/utils/llm-adapter.d.ts +2 -2
  45. package/dist/utils/llm-adapter.d.ts.map +1 -1
  46. package/dist/utils/llm-adapter.js +57 -33
  47. package/dist/utils/llm-adapter.js.map +1 -1
  48. package/dist/utils/logger.d.ts +20 -0
  49. package/dist/utils/logger.d.ts.map +1 -0
  50. package/dist/utils/logger.js +49 -0
  51. package/dist/utils/logger.js.map +1 -0
  52. package/dist/utils/persistence.d.ts.map +1 -1
  53. package/dist/utils/persistence.js +4 -3
  54. package/dist/utils/persistence.js.map +1 -1
  55. package/package.json +1 -1
  56. package/real_world_test.log +200 -0
  57. package/real_world_test_dynamic.log +184 -0
  58. package/real_world_test_real.log +184 -0
  59. package/src/__tests__/sequential-thinking.test.ts +21 -21
  60. package/src/agents/base-agent.ts +6 -3
  61. package/src/agents/meta-reasoning-agent.ts +38 -397
  62. package/src/agents/synthesizer-agent.ts +48 -165
  63. package/src/mcp-server.ts +9 -6
  64. package/src/real_world_test.ts +89 -0
  65. package/src/sequential-thinking.ts +87 -33
  66. package/src/swarm-coordinator.ts +41 -13
  67. package/src/utils/llm-adapter.ts +66 -32
  68. package/src/utils/logger.ts +56 -0
  69. package/src/utils/persistence.ts +4 -3
@@ -12,6 +12,7 @@ import {
12
12
  type TaskResult,
13
13
  type AgentCapability
14
14
  } from '../types/index.js';
15
+ import { LLMAdapter } from '../utils/llm-adapter.js';
15
16
 
16
17
  /**
17
18
  * Synthesis input
@@ -57,25 +58,25 @@ export class SynthesizerAgent extends BaseAgent {
57
58
  {
58
59
  name: 'consensus_building',
59
60
  description: 'Build consensus from multiple outputs',
60
- confidence: 0.85,
61
+ confidence: 0.9,
61
62
  performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
62
63
  },
63
64
  {
64
65
  name: 'conflict_resolution',
65
66
  description: 'Resolve conflicts between outputs',
66
- confidence: 0.8,
67
+ confidence: 0.85,
67
68
  performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
68
69
  },
69
70
  {
70
71
  name: 'creative_synthesis',
71
72
  description: 'Create creative combinations',
72
- confidence: 0.75,
73
+ confidence: 0.8,
73
74
  performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
74
75
  },
75
76
  {
76
77
  name: 'integration',
77
78
  description: 'Integrate multiple perspectives',
78
- confidence: 0.85,
79
+ confidence: 0.9,
79
80
  performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
80
81
  }
81
82
  ];
@@ -109,7 +110,7 @@ export class SynthesizerAgent extends BaseAgent {
109
110
  }
110
111
 
111
112
  /**
112
- * Process a task - synthesize inputs
113
+ * Process a task - synthesize inputs using LLM
113
114
  * @param task - Task to process
114
115
  * @returns Task result
115
116
  */
@@ -117,196 +118,78 @@ export class SynthesizerAgent extends BaseAgent {
117
118
  const startTime = Date.now();
118
119
  const input = task.input as SynthesisInput;
119
120
 
120
- let result: Synthesis;
121
+ if (!input.outputs || input.outputs.length === 0) {
122
+ return this.createTaskResult(task.id, { error: 'No outputs to synthesize' }, 0, Date.now() - startTime);
123
+ }
124
+
125
+ const contextStr = input.context ? `Context: ${JSON.stringify(input.context)}\n` : '';
126
+ const outputsStr = input.outputs.map((o, i) => `Agent ${o.agentId} (Confidence: ${o.confidence}):\n${JSON.stringify(o.output)}`).join('\n\n');
127
+
128
+ const provider = (task.context as any)?.modelProvider;
129
+
130
+ let prompt = '';
131
+ let systemPrompt = 'You are an expert synthesizer agent in a swarm intelligence system. Your goal is to combine multiple agent outputs into a coherent, high-quality result.';
121
132
 
122
133
  switch (this.synthesizerType) {
123
134
  case SynthesizerType.CONSENSUS:
124
- result = await this.buildConsensus(input);
135
+ prompt = `Build a consensus from the following agent outputs. Identify common points, resolve minor discrepancies, and provide a unified conclusion.\n\n${contextStr}\n${outputsStr}`;
125
136
  break;
126
137
  case SynthesizerType.CREATIVE:
127
- result = await this.creativeSynthesis(input);
138
+ prompt = `Perform a creative synthesis of these agent outputs. Look for unexpected connections, combine ideas in novel ways, and provide a unique integrated insight.\n\n${contextStr}\n${outputsStr}`;
139
+ systemPrompt = 'You are a creative synthesizer agent. You excel at finding novel connections and unique perspectives by combining diverse ideas.';
128
140
  break;
129
141
  case SynthesizerType.CONFLICT_RESOLUTION:
130
- result = await this.resolveConflicts(input);
142
+ prompt = `Resolve the conflicts between these agent outputs. Analyze the reasoning behind each conflicting point and determine the most logically sound resolution based on the evidence and confidence levels.\n\n${contextStr}\n${outputsStr}`;
143
+ systemPrompt = 'You are a conflict resolution specialist agent. You excel at analyzing differing perspectives and finding the most accurate resolution based on logic and evidence.';
131
144
  break;
132
145
  default:
133
- result = await this.buildConsensus(input);
146
+ prompt = `Integrate the following agent outputs into a comprehensive final result.\n\n${contextStr}\n${outputsStr}`;
147
+ }
148
+
149
+ const response = await LLMAdapter.call(prompt, systemPrompt, provider);
150
+
151
+ if (response.error) {
152
+ // Fallback to heuristic if LLM fails
153
+ const heuristicResult = await this.heuristicSynthesis(input);
154
+ return this.createTaskResult(task.id, heuristicResult, heuristicResult.confidence, Date.now() - startTime, { error: response.error });
134
155
  }
135
156
 
157
+ const synthesizedOutput = response.content;
158
+ const avgConfidence = input.outputs.reduce((sum, o) => sum + o.confidence, 0) / input.outputs.length;
159
+
160
+ const result: Synthesis = {
161
+ synthesizedOutput,
162
+ confidence: Math.min(0.95, avgConfidence + 0.1), // Boost confidence for successful synthesis
163
+ contributingAgents: input.outputs.map(o => o.agentId),
164
+ synthesisMethod: `llm_${this.synthesizerType.toLowerCase()}`
165
+ };
166
+
136
167
  return this.createTaskResult(
137
168
  task.id,
138
169
  result,
139
170
  result.confidence,
140
171
  Date.now() - startTime,
141
172
  {
142
- reasoningSteps: input.outputs.length,
173
+ reasoningSteps: input.outputs.length + 1,
143
174
  intermediateResults: input.outputs.map(o => o.output)
144
175
  }
145
176
  );
146
177
  }
147
178
 
148
179
  /**
149
- * Build consensus from multiple outputs
150
- * @param input - Synthesis input
151
- * @returns Synthesis result
152
- */
153
- private async buildConsensus(input: SynthesisInput): Promise<Synthesis> {
154
- const { outputs } = input;
155
-
156
- if (outputs.length === 0) {
157
- return {
158
- synthesizedOutput: null,
159
- confidence: 0,
160
- contributingAgents: [],
161
- synthesisMethod: 'consensus'
162
- };
163
- }
164
-
165
- if (outputs.length === 1) {
166
- return {
167
- synthesizedOutput: outputs[0].output,
168
- confidence: outputs[0].confidence,
169
- contributingAgents: [outputs[0].agentId],
170
- synthesisMethod: 'consensus'
171
- };
172
- }
173
-
174
- // Extract key points from each output
175
- const keyPoints = outputs.map(o => this.extractKeyPoints(o.output));
176
-
177
- // Find consensus points (common across multiple outputs)
178
- const consensusPoints = this.findConsensusPoints(keyPoints);
179
-
180
- // Find points of divergence
181
- const divergencePoints = this.findDivergencePoints(keyPoints);
182
-
183
- // Weight by confidence
184
- const weightedConsensus = this.applyConfidenceWeights(consensusPoints, outputs);
185
-
186
- // Calculate consensus level
187
- const consensusLevel = consensusPoints.length / Math.max(...keyPoints.map(kp => kp.length));
188
-
189
- // Generate unified output
190
- const unified = this.generateUnifiedOutput(weightedConsensus, divergencePoints);
191
-
192
- // Calculate overall confidence
193
- const avgConfidence = outputs.reduce((sum, o) => sum + o.confidence, 0) / outputs.length;
194
- const consensusBoost = consensusLevel * 0.1;
195
-
196
- return {
197
- synthesizedOutput: unified,
198
- confidence: Math.min(1, avgConfidence + consensusBoost),
199
- contributingAgents: outputs.map(o => o.agentId),
200
- synthesisMethod: 'consensus',
201
- consensusLevel,
202
- dissentPoints: divergencePoints
203
- };
204
- }
205
-
206
- /**
207
- * Creative synthesis
208
- * @param input - Synthesis input
209
- * @returns Synthesis result
180
+ * Fallback heuristic synthesis
210
181
  */
211
- private async creativeSynthesis(input: SynthesisInput): Promise<Synthesis> {
182
+ private async heuristicSynthesis(input: SynthesisInput): Promise<Synthesis> {
212
183
  const { outputs } = input;
213
-
214
- if (outputs.length === 0) {
215
- return {
216
- synthesizedOutput: null,
217
- confidence: 0,
218
- contributingAgents: [],
219
- synthesisMethod: 'creative_combination'
220
- };
221
- }
222
-
223
- // Extract creative elements
224
- const creativeElements = outputs.map(o => this.extractCreativeElements(o.output));
225
-
226
- // Find unexpected connections
227
- const connections = this.findUnexpectedConnections(creativeElements);
228
-
229
- // Generate novel combinations
230
- const combinations = this.generateNovelCombinations(creativeElements, connections);
231
-
232
- // Create creative output
233
- const creativeOutput = {
234
- combinations,
235
- connections,
236
- originalElements: creativeElements,
237
- novelInsights: this.generateNovelInsights(combinations)
238
- };
239
-
240
- // Calculate confidence based on diversity and novelty
241
- const diversityScore = this.calculateDiversity(creativeElements);
242
- const noveltyScore = connections.length > 0 ? 0.8 : 0.5;
243
- const confidence = (diversityScore + noveltyScore) / 2;
244
-
184
+ // Simplified version of the previous heuristic logic
245
185
  return {
246
- synthesizedOutput: creativeOutput,
247
- confidence,
186
+ synthesizedOutput: outputs.map(o => JSON.stringify(o.output)).join('\n---\n'),
187
+ confidence: outputs.reduce((sum, o) => sum + o.confidence, 0) / outputs.length,
248
188
  contributingAgents: outputs.map(o => o.agentId),
249
- synthesisMethod: 'creative_combination'
189
+ synthesisMethod: 'heuristic_fallback'
250
190
  };
251
191
  }
252
192
 
253
- /**
254
- * Resolve conflicts between outputs
255
- * @param input - Synthesis input
256
- * @returns Synthesis result
257
- */
258
- private async resolveConflicts(input: SynthesisInput): Promise<Synthesis> {
259
- const { outputs } = input;
260
-
261
- if (outputs.length === 0) {
262
- return {
263
- synthesizedOutput: null,
264
- confidence: 0,
265
- contributingAgents: [],
266
- synthesisMethod: 'conflict_resolution'
267
- };
268
- }
269
-
270
- if (outputs.length === 1) {
271
- return {
272
- synthesizedOutput: outputs[0].output,
273
- confidence: outputs[0].confidence,
274
- contributingAgents: [outputs[0].agentId],
275
- synthesisMethod: 'conflict_resolution'
276
- };
277
- }
278
-
279
- // Identify conflicts
280
- const conflicts = this.identifyConflicts(outputs);
281
-
282
- if (conflicts.length === 0) {
283
- // No conflicts, use consensus
284
- return this.buildConsensus(input);
285
- }
286
-
287
- // Resolve each conflict
288
- const resolutions = conflicts.map(conflict => ({
289
- conflict,
290
- resolution: this.resolveConflict(conflict, outputs)
291
- }));
292
-
293
- // Merge resolved conflicts with non-conflicting content
294
- const finalOutput = this.mergeResolutions(outputs, resolutions);
295
-
296
- // Calculate confidence
297
- const avgConfidence = outputs.reduce((sum, o) => sum + o.confidence, 0) / outputs.length;
298
- const resolutionQuality = resolutions.length > 0
299
- ? resolutions.reduce((sum, r) => sum + r.resolution.confidence, 0) / resolutions.length
300
- : 1;
301
-
302
- return {
303
- synthesizedOutput: finalOutput,
304
- confidence: (avgConfidence + resolutionQuality) / 2,
305
- contributingAgents: outputs.map(o => o.agentId),
306
- synthesisMethod: 'conflict_resolution',
307
- dissentPoints: conflicts.map(c => c.description)
308
- };
309
- }
310
193
 
311
194
  // ============================================================================
312
195
  // Helper Methods
package/src/mcp-server.ts CHANGED
@@ -9,6 +9,7 @@ import { SessionManager, SelfCorrectionEngine, AdaptiveGranularityEngine } from
9
9
  import { SwarmCoordinator } from './swarm-coordinator.js';
10
10
  import { ThoughtType, AgentType, ReasoningStrategy, CriticType, SynthesizerType, ConsensusAlgorithm, ConflictResolutionStrategy } from './types/index.js';
11
11
  import { ReasonerAgent, CriticAgent, SynthesizerAgent, MetaReasoningAgent } from './agents/index.js';
12
+ import { Logger } from './utils/logger.js';
12
13
  const SEQUENTIAL_THINKING_TOOL = {
13
14
  name: 'advanced_sequential_thinking',
14
15
  description: 'Advanced sequential thinking with self-correction, parallel hypotheses, meta-reasoning',
@@ -39,7 +40,8 @@ const SEQUENTIAL_THINKING_TOOL = {
39
40
  tags: { type: 'array', items: { type: 'string' } },
40
41
  assumptions: { type: 'array', items: { type: 'string' } },
41
42
  dependencies: { type: 'array', items: { type: 'string' } },
42
- settings: { type: 'object' }
43
+ settings: { type: 'object' },
44
+ modelProvider: { type: 'string', description: 'Optional LLM provider (gemini, claude, kimi)' }
43
45
  },
44
46
  required: ['operation']
45
47
  }
@@ -183,7 +185,7 @@ export class MCPServer {
183
185
  if (!thought)
184
186
  throw new Error(`Thought not found: ${args.thoughtId}`);
185
187
  const correctionEngine = new SelfCorrectionEngine();
186
- const issues = correctionEngine.detectIssues(thought, graph);
188
+ const issues = await correctionEngine.detectIssues(thought, graph);
187
189
  return { success: true, issuesDetected: issues, recommendations: issues.map((i: any) => i.suggestion) };
188
190
  }
189
191
  case 'add_meta_thought': {
@@ -215,7 +217,7 @@ export class MCPServer {
215
217
  if (!session)
216
218
  throw new Error(`Session not found: ${args.sessionId}`);
217
219
  const engine = new AdaptiveGranularityEngine();
218
- const granularity = engine.calculateGranularity(session.topic, session.context, session.thoughts.size);
220
+ const granularity = await engine.calculateGranularity(session.topic, session.context, session.thoughts.size);
219
221
  return { success: true, recommendedDetail: granularity.detail, reasoning: granularity.reasoning };
220
222
  }
221
223
  case 'get_session_state': {
@@ -246,7 +248,7 @@ export class MCPServer {
246
248
  const { task, assignedAgent } = this.swarmCoordinator.submitTask(
247
249
  taskType,
248
250
  `Analyze and expand on this thought: ${thought.content}`,
249
- { thought: thought.content, context: session.context },
251
+ { thought: thought.content, context: session.context, modelProvider: args.modelProvider },
250
252
  { requiredCapabilities: args.requiredCapabilities || [], minConfidence: 0.6, maxTimeMs: 30000 }
251
253
  );
252
254
 
@@ -375,14 +377,15 @@ export class MCPServer {
375
377
  }
376
378
  }
377
379
  async start() {
380
+ await this.initialize();
378
381
  const transport = new StdioServerTransport();
379
382
  await this.server.connect(transport);
380
- console.error('MCP Sequential Thinking Server running on stdio');
383
+ Logger.error('MCP Sequential Thinking Server running on stdio');
381
384
  }
382
385
  }
383
386
  const isMainModule = import.meta.url === `file://${process.argv[1]}`;
384
387
  if (isMainModule) {
385
388
  const server = new MCPServer();
386
- server.start().catch(console.error);
389
+ server.start().catch((error) => Logger.error('Server error', { error }));
387
390
  }
388
391
  //# sourceMappingURL=mcp-server.js.map
@@ -0,0 +1,89 @@
1
+ import { MCPServer } from './mcp-server.js';
2
+ import { Logger, LogLevel } from './utils/logger.js';
3
+
4
+ async function runTest() {
5
+ Logger.setLevel(LogLevel.INFO);
6
+ console.log('--- Starting Real World Scenario Test ---');
7
+
8
+ const server = new MCPServer();
9
+ await server.initialize();
10
+ console.log('[System] Server Initialized');
11
+
12
+ // 1. Register Agents
13
+ console.log('\n[Step 1] Registering Agents...');
14
+ const reasoner = await server.handleSwarmCoordination({
15
+ operation: 'register_agent',
16
+ name: 'LogicMaster',
17
+ agentType: 'reasoner',
18
+ subtype: 'chain_of_thought'
19
+ });
20
+ console.log('Registered Reasoner:', JSON.stringify(reasoner, null, 2));
21
+
22
+ const critic = await server.handleSwarmCoordination({
23
+ operation: 'register_agent',
24
+ name: 'SafetyCheck',
25
+ agentType: 'critic',
26
+ subtype: 'safety'
27
+ });
28
+ console.log('Registered Critic:', JSON.stringify(critic, null, 2));
29
+
30
+ // 2. Start Thinking Session
31
+ console.log('\n[Step 2] Initializing Thinking Session...');
32
+ const session = await server.handleSequentialThinking({
33
+ operation: 'initialize',
34
+ topic: 'Architecting a scalable microservices system'
35
+ });
36
+ console.log('Session Created:', JSON.stringify(session, null, 2));
37
+ const sessionId = session.sessionId;
38
+
39
+ // 3. Add Initial Thought
40
+ console.log('\n[Step 3] Adding Initial Thought...');
41
+ const thought1 = await server.handleSequentialThinking({
42
+ operation: 'add_thought',
43
+ sessionId: sessionId,
44
+ content: 'We need to break down the monolithic application into smaller services.',
45
+ thoughtType: 'analysis',
46
+ confidence: 0.8
47
+ });
48
+ console.log('Thought Added:', JSON.stringify(thought1, null, 2));
49
+
50
+ if (!thought1.thought) {
51
+ throw new Error('Failed to create thought');
52
+ }
53
+ const thoughtId = thought1.thought.id;
54
+
55
+ // 4. Delegate to Swarm (Reasoner)
56
+ console.log('\n[Step 4] Delegating to Swarm (Reasoner)...');
57
+ const swarmResult = await server.handleSequentialThinking({
58
+ operation: 'delegate_to_swarm',
59
+ sessionId: sessionId,
60
+ thoughtId: thoughtId,
61
+ taskType: 'reasoning',
62
+ requiredCapabilities: ['problem_solving']
63
+ });
64
+ console.log('Swarm Delegation Result:', JSON.stringify(swarmResult, null, 2));
65
+
66
+ // 5. Self Correction (Simulation)
67
+ console.log('\n[Step 5] Triggering Self-Correction...');
68
+ const correction = await server.handleSequentialThinking({
69
+ operation: 'self_correct',
70
+ sessionId: sessionId,
71
+ thoughtId: thoughtId
72
+ });
73
+ console.log('Self Correction Result:', JSON.stringify(correction, null, 2));
74
+
75
+ // 6. Complete Session
76
+ console.log('\n[Step 6] Completing Session...');
77
+ const completion = await server.handleSequentialThinking({
78
+ operation: 'complete_session',
79
+ sessionId: sessionId
80
+ });
81
+ console.log('Completion Result:', JSON.stringify(completion, null, 2));
82
+
83
+ console.log('\n--- Test Finished Successfully ---');
84
+ }
85
+
86
+ runTest().catch(error => {
87
+ console.error('Test Failed:', error);
88
+ process.exit(1);
89
+ });
@@ -3,6 +3,8 @@
3
3
  */
4
4
  import { ThoughtType, Thought, ThoughtBranch, ConfidenceScore, MetaNote, ThinkingSession, SessionStatus, BranchStatus } from './types/index.js';
5
5
  import { calculateSimilarity } from './utils/index.js';
6
+ import { LLMAdapter } from './utils/llm-adapter.js';
7
+ import { Logger } from './utils/logger.js';
6
8
 
7
9
  export class ConfidenceCalibrator {
8
10
  createInitialConfidence(): ConfidenceScore {
@@ -226,25 +228,43 @@ export class ThoughtGraph {
226
228
 
227
229
  export class MetaReasoningEngine {
228
230
  metaNotes = new Map<string, MetaNote>();
229
- reflect(session: ThinkingSession) {
231
+
232
+ async reflect(session: ThinkingSession) {
230
233
  const thoughts = Array.from(session.thoughts.values());
234
+
235
+ // Basic analysis
231
236
  const insights: string[] = [];
232
237
  const recommendations: string[] = [];
233
- // Analyze thinking patterns
234
- const analysisCount = thoughts.filter(t => (t as any).thoughtType === 'analysis').length;
235
- const hypothesisCount = thoughts.filter(t => (t as any).thoughtType === 'hypothesis').length;
238
+
239
+ const analysisCount = thoughts.filter(t => t.thoughtType === ThoughtType.ANALYSIS).length;
240
+ const hypothesisCount = thoughts.filter(t => t.thoughtType === ThoughtType.HYPOTHESIS).length;
241
+
236
242
  if (analysisCount > hypothesisCount * 2) {
237
243
  insights.push('Heavy focus on analysis with limited hypothesis generation');
238
244
  recommendations.push('Consider exploring more alternative hypotheses');
239
245
  }
240
- // Check confidence trends
246
+
241
247
  const avgConfidence = thoughts.length > 0
242
- ? thoughts.reduce((sum, t) => sum + (t as any).confidence.overall, 0) / thoughts.length
248
+ ? thoughts.reduce((sum, t) => sum + t.confidence.overall, 0) / thoughts.length
243
249
  : 0;
250
+
244
251
  if (avgConfidence < 0.5) {
245
252
  insights.push('Overall confidence is low');
246
253
  recommendations.push('Review assumptions and gather more evidence');
247
254
  }
255
+
256
+ // Advanced LLM-powered reflection
257
+ try {
258
+ const prompt = `Reflect on the following thinking session and provide 3 key insights and 3 specific recommendations for improvement.\nTopic: ${session.topic}\nThoughts:\n${thoughts.map(t => `- [${t.thoughtType}] ${t.content.substring(0, 100)}...`).join('\n')}`;
259
+ const response = await LLMAdapter.call(prompt, "You are a meta-reasoning engine that analyzes thinking processes.");
260
+
261
+ if (!response.error) {
262
+ insights.push(`LLM Insight: ${response.content}`);
263
+ }
264
+ } catch (e) {
265
+ Logger.warn('LLM Reflection failed', { error: String(e) });
266
+ }
267
+
248
268
  return {
249
269
  reflectionType: 'session_review',
250
270
  content: `Analyzed ${thoughts.length} thoughts across ${session.branches.size} branches`,
@@ -252,6 +272,7 @@ export class MetaReasoningEngine {
252
272
  recommendations
253
273
  };
254
274
  }
275
+
255
276
  generateMetaObservation(thoughtId: string, thoughtGraph: ThoughtGraph) {
256
277
  const thought = thoughtGraph.getThoughts().get(thoughtId);
257
278
  if (!thought)
@@ -281,8 +302,10 @@ export class MetaReasoningEngine {
281
302
  }
282
303
 
283
304
  export class SelfCorrectionEngine {
284
- detectIssues(thought: Thought, graph: ThoughtGraph) {
305
+ async detectIssues(thought: Thought, graph: ThoughtGraph) {
285
306
  const issues: any[] = [];
307
+
308
+ // Fast heuristics
286
309
  if (thought.confidence.overall < 0.3) {
287
310
  issues.push({
288
311
  type: 'calibration',
@@ -299,6 +322,26 @@ export class SelfCorrectionEngine {
299
322
  suggestion: 'Document assumptions'
300
323
  });
301
324
  }
325
+
326
+ // Deeper LLM analysis for potential fallacies
327
+ if (thought.content.length > 100) {
328
+ try {
329
+ const prompt = `Analyze this thought for logical fallacies or inconsistencies. If any are found, describe them briefly and suggest a correction.\nThought: ${thought.content}`;
330
+ const response = await LLMAdapter.call(prompt, "You are a critical thinking assistant. Be concise.");
331
+
332
+ if (!response.error && response.content.toLowerCase().includes('fallacy') || response.content.toLowerCase().includes('inconsistency')) {
333
+ issues.push({
334
+ type: 'logic',
335
+ severity: 'medium',
336
+ description: `Potential logical issue: ${response.content.substring(0, 100)}...`,
337
+ suggestion: 'Review the reasoning for potential fallacies.'
338
+ });
339
+ }
340
+ } catch (e) {
341
+ Logger.warn('LLM Self-Correction analysis failed', { error: String(e) });
342
+ }
343
+ }
344
+
302
345
  return issues;
303
346
  }
304
347
  checkSessionHealth(session: ThinkingSession) {
@@ -333,34 +376,44 @@ export class SelfCorrectionEngine {
333
376
  }
334
377
 
335
378
  export class AdaptiveGranularityEngine {
336
- calculateGranularity(topic: string, context: any, currentDepth: number) {
337
- const hasComplexTerms = /\b(system|architecture|framework)\b/i.test(topic);
338
- const detail = hasComplexTerms ? 0.8 : 0.5;
339
- return { detail, reasoning: hasComplexTerms ? 'Complex topic detected' : 'Standard granularity' };
340
- }
341
- getRecommendation(session: ThinkingSession) {
342
- const thoughts = Array.from(session.thoughts.values());
343
- const avgConfidence = thoughts.length > 0
344
- ? thoughts.reduce((sum, t) => sum + (t as any).confidence.overall, 0) / thoughts.length
345
- : 0.5;
346
- if (avgConfidence < 0.4) {
347
- return {
348
- suggestedAction: 'increase_detail',
349
- detail: 0.9,
350
- reasoning: 'Low confidence detected - need more detailed analysis'
351
- };
379
+ async calculateGranularity(topic: string, context: any, currentDepth: number) {
380
+ // Basic heuristic
381
+ let detail = 0.5;
382
+ let reasoning = 'Standard granularity';
383
+
384
+ const hasComplexTerms = /\b(system|architecture|framework|optimization|deep learning|quantum)\b/i.test(topic);
385
+ if (hasComplexTerms) {
386
+ detail = 0.8;
387
+ reasoning = 'Complex topic keywords detected';
352
388
  }
353
- if (thoughts.length > 10 && avgConfidence > 0.8) {
354
- return {
355
- suggestedAction: 'decrease_detail',
356
- detail: 0.4,
357
- reasoning: 'High confidence with many thoughts - can summarize'
358
- };
389
+
390
+ // LLM evaluation of complexity
391
+ try {
392
+ const prompt = `On a scale of 0.1 to 1.0, how complex is this topic? Provide only the number and a short reason.\nTopic: ${topic}`;
393
+ const response = await LLMAdapter.call(prompt, "You are an expert at assessing problem complexity.");
394
+
395
+ if (!response.error) {
396
+ const match = response.content.match(/0?\.\d+|1\.0/);
397
+ if (match) {
398
+ detail = parseFloat(match[0]);
399
+ reasoning = `LLM Complexity Assessment: ${response.content}`;
400
+ }
401
+ }
402
+ } catch (e) {
403
+ Logger.warn('LLM Granularity calculation failed', { error: String(e) });
359
404
  }
405
+
406
+ return { detail, reasoning };
407
+ }
408
+
409
+ getRecommendation(session: ThinkingSession) {
410
+ const hasComplexTerms = /\b(system|architecture|framework|optimization|deep learning|quantum)\b/i.test(session.topic);
411
+ const detail = hasComplexTerms ? 0.8 : 0.5;
412
+
360
413
  return {
361
- suggestedAction: 'maintain',
362
- detail: 0.6,
363
- reasoning: 'Current granularity is appropriate'
414
+ suggestedAction: detail > 0.7 ? 'increase_granularity' : 'maintain_granularity',
415
+ detail,
416
+ reasoning: hasComplexTerms ? 'Complex topic detected' : 'Standard complexity'
364
417
  };
365
418
  }
366
419
  }
@@ -504,7 +557,7 @@ export class SessionManager {
504
557
  }
505
558
  }
506
559
  if (session.settings.enableSelfCorrection) {
507
- issues = this.correctionEngine.detectIssues(thought, this.graph);
560
+ issues = await this.correctionEngine.detectIssues(thought, this.graph);
508
561
  }
509
562
 
510
563
  if (this.persistence) {
@@ -557,4 +610,5 @@ export class SessionManager {
557
610
  };
558
611
  }
559
612
  }
613
+
560
614
  //# sourceMappingURL=sequential-thinking.js.map