@gotza02/mathinking 3.1.7 → 3.1.9
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/README.md +12 -1
- package/dist/schemas/brain.schema.d.ts +16 -0
- package/dist/schemas/brain.schema.d.ts.map +1 -1
- package/dist/schemas/brain.schema.js +14 -10
- package/dist/schemas/brain.schema.js.map +1 -1
- package/dist/sse-server.js +2 -1
- package/dist/sse-server.js.map +1 -1
- package/dist/test-new-features.d.ts +2 -0
- package/dist/test-new-features.d.ts.map +1 -0
- package/dist/test-new-features.js +62 -0
- package/dist/test-new-features.js.map +1 -0
- package/dist/tools/orchestrator.d.ts.map +1 -1
- package/dist/tools/orchestrator.js +93 -26
- package/dist/tools/orchestrator.js.map +1 -1
- package/dist/tools/sequential-thinking.d.ts +2 -0
- package/dist/tools/sequential-thinking.d.ts.map +1 -1
- package/dist/tools/sequential-thinking.js +265 -46
- package/dist/tools/sequential-thinking.js.map +1 -1
- package/dist/types/index.d.ts +17 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/dag.d.ts.map +1 -1
- package/dist/utils/dag.js +4 -7
- package/dist/utils/dag.js.map +1 -1
- package/dist/utils/fs-helper.d.ts +12 -0
- package/dist/utils/fs-helper.d.ts.map +1 -0
- package/dist/utils/fs-helper.js +45 -0
- package/dist/utils/fs-helper.js.map +1 -0
- package/dist/utils/memory.d.ts +2 -2
- package/dist/utils/memory.d.ts.map +1 -1
- package/dist/utils/memory.js +24 -11
- package/dist/utils/memory.js.map +1 -1
- package/dist/utils/mutex.d.ts.map +1 -1
- package/dist/utils/mutex.js +1 -1
- package/dist/utils/mutex.js.map +1 -1
- package/dist/utils/resilience.d.ts.map +1 -1
- package/dist/utils/resilience.js +5 -8
- package/dist/utils/resilience.js.map +1 -1
- package/dist/utils/tool-cache.d.ts +2 -2
- package/dist/utils/tool-cache.d.ts.map +1 -1
- package/dist/utils/tool-cache.js +2 -0
- package/dist/utils/tool-cache.js.map +1 -1
- package/dist/utils/vector-memory.d.ts +3 -2
- package/dist/utils/vector-memory.d.ts.map +1 -1
- package/dist/utils/vector-memory.js +34 -23
- package/dist/utils/vector-memory.js.map +1 -1
- package/package.json +1 -1
|
@@ -7,6 +7,7 @@ import { Mutex } from '../utils/mutex.js';
|
|
|
7
7
|
import { orchestratorManager } from './orchestrator.js';
|
|
8
8
|
import { vectorMemory } from '../utils/vector-memory.js';
|
|
9
9
|
import { BrainInputSchema } from '../schemas/brain.schema.js';
|
|
10
|
+
import { writeJsonAtomic, backupCorruptedFile } from '../utils/fs-helper.js';
|
|
10
11
|
export class SequentialThinkingManager {
|
|
11
12
|
sessions = new LRUCache({
|
|
12
13
|
max: 100,
|
|
@@ -67,7 +68,8 @@ export class SequentialThinkingManager {
|
|
|
67
68
|
// Force cleanup by calling purge (if available) or by checking entries
|
|
68
69
|
for (const [key, value] of this.sessions.entries()) {
|
|
69
70
|
const age = Date.now() - new Date(value.updatedAt).getTime();
|
|
70
|
-
if (age > 1000 * 60 * 60 * 24) {
|
|
71
|
+
if (age > 1000 * 60 * 60 * 24) {
|
|
72
|
+
// 24 hours
|
|
71
73
|
this.sessions.delete(key);
|
|
72
74
|
}
|
|
73
75
|
}
|
|
@@ -107,14 +109,14 @@ export class SequentialThinkingManager {
|
|
|
107
109
|
try {
|
|
108
110
|
data = await fs.readFile(this.storagePath, 'utf8');
|
|
109
111
|
}
|
|
110
|
-
catch
|
|
112
|
+
catch {
|
|
111
113
|
// Primary storage failed, try backup
|
|
112
114
|
try {
|
|
113
115
|
console.log('[Brain] Primary storage not found, trying backup...');
|
|
114
116
|
data = await fs.readFile(this.backupPath, 'utf8');
|
|
115
117
|
useBackup = true;
|
|
116
118
|
}
|
|
117
|
-
catch
|
|
119
|
+
catch {
|
|
118
120
|
// Backup also failed, start fresh
|
|
119
121
|
console.log('[Brain] No existing storage found, starting fresh');
|
|
120
122
|
this.initialized = true;
|
|
@@ -128,6 +130,13 @@ export class SequentialThinkingManager {
|
|
|
128
130
|
}
|
|
129
131
|
catch (parseError) {
|
|
130
132
|
console.error('[Brain] Failed to parse storage JSON:', parseError);
|
|
133
|
+
// 🔧 FIX: Handle corruption with backup instead of immediate crash
|
|
134
|
+
if (!useBackup) {
|
|
135
|
+
const backupFile = await backupCorruptedFile(this.storagePath);
|
|
136
|
+
if (backupFile) {
|
|
137
|
+
console.warn(`[Brain] Corrupted primary storage backed up to: ${backupFile}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
131
140
|
if (useBackup) {
|
|
132
141
|
throw new Error('Both primary and backup storage are corrupted');
|
|
133
142
|
}
|
|
@@ -176,12 +185,12 @@ export class SequentialThinkingManager {
|
|
|
176
185
|
for (const [key, value] of this.sessions.entries()) {
|
|
177
186
|
entries[key] = value;
|
|
178
187
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
await fs.writeFile(this.storagePath, data, 'utf8');
|
|
188
|
+
// 🔧 Save to primary storage with atomic write
|
|
189
|
+
await writeJsonAtomic(this.storagePath, entries);
|
|
182
190
|
// 🔧 Create backup after successful primary save
|
|
183
191
|
try {
|
|
184
|
-
|
|
192
|
+
// We can just reuse atomic write for backup too
|
|
193
|
+
await writeJsonAtomic(this.backupPath, entries);
|
|
185
194
|
}
|
|
186
195
|
catch (backupError) {
|
|
187
196
|
console.warn('[Brain] Backup save failed (primary is safe):', backupError);
|
|
@@ -234,10 +243,10 @@ export class SequentialThinkingManager {
|
|
|
234
243
|
innerResult = this.startSession(validatedInput);
|
|
235
244
|
break;
|
|
236
245
|
case 'add_thought':
|
|
237
|
-
innerResult = this.addThought(validatedInput);
|
|
246
|
+
innerResult = await this.addThought(validatedInput);
|
|
238
247
|
break;
|
|
239
248
|
case 'create_branch':
|
|
240
|
-
innerResult = this.createBranch(validatedInput);
|
|
249
|
+
innerResult = await this.createBranch(validatedInput);
|
|
241
250
|
break;
|
|
242
251
|
case 'generate_options':
|
|
243
252
|
innerResult = this.generateOptions(validatedInput);
|
|
@@ -249,16 +258,16 @@ export class SequentialThinkingManager {
|
|
|
249
258
|
innerResult = this.selectOption(validatedInput);
|
|
250
259
|
break;
|
|
251
260
|
case 'revise_thought':
|
|
252
|
-
innerResult = this.reviseThought(validatedInput);
|
|
261
|
+
innerResult = await this.reviseThought(validatedInput);
|
|
253
262
|
break;
|
|
254
263
|
case 'set_hypothesis':
|
|
255
|
-
innerResult = this.setHypothesis(validatedInput);
|
|
264
|
+
innerResult = await this.setHypothesis(validatedInput);
|
|
256
265
|
break;
|
|
257
266
|
case 'verify_hypothesis':
|
|
258
|
-
innerResult = this.verifyHypothesis(validatedInput);
|
|
267
|
+
innerResult = await this.verifyHypothesis(validatedInput);
|
|
259
268
|
break;
|
|
260
269
|
case 'conclude':
|
|
261
|
-
innerResult = this.conclude(validatedInput);
|
|
270
|
+
innerResult = await this.conclude(validatedInput);
|
|
262
271
|
break;
|
|
263
272
|
// execute_conclusion handled outside
|
|
264
273
|
case 'reflect':
|
|
@@ -276,7 +285,8 @@ export class SequentialThinkingManager {
|
|
|
276
285
|
case 'get_history':
|
|
277
286
|
innerResult = this.getHistory(validatedInput);
|
|
278
287
|
break;
|
|
279
|
-
default:
|
|
288
|
+
default:
|
|
289
|
+
innerResult = this.startSession(validatedInput);
|
|
280
290
|
}
|
|
281
291
|
if (innerResult.success)
|
|
282
292
|
await this._saveToStorage();
|
|
@@ -317,6 +327,7 @@ export class SequentialThinkingManager {
|
|
|
317
327
|
}
|
|
318
328
|
research(input) {
|
|
319
329
|
const session = this.getSession(input.sessionId);
|
|
330
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
320
331
|
if (!session)
|
|
321
332
|
return { success: false, message: 'Session not found' };
|
|
322
333
|
const topic = input.thought || session.problemStatement;
|
|
@@ -391,13 +402,15 @@ export class SequentialThinkingManager {
|
|
|
391
402
|
suggestedPlan = {
|
|
392
403
|
planId: 'recovery-' + uuidv4().substring(0, 8),
|
|
393
404
|
name: 'Network Recovery Plan',
|
|
394
|
-
tasks: [
|
|
405
|
+
tasks: [
|
|
406
|
+
{
|
|
395
407
|
id: 'fallback',
|
|
396
408
|
name: 'Fallback Echo',
|
|
397
409
|
toolName: 'echo',
|
|
398
410
|
toolInput: { msg: 'Recovered using fallback echo due to network failure.' },
|
|
399
411
|
dependencies: []
|
|
400
|
-
}
|
|
412
|
+
}
|
|
413
|
+
]
|
|
401
414
|
};
|
|
402
415
|
}
|
|
403
416
|
return {
|
|
@@ -420,6 +433,8 @@ export class SequentialThinkingManager {
|
|
|
420
433
|
thoughtHistory: [],
|
|
421
434
|
branches: [],
|
|
422
435
|
status: 'in_progress',
|
|
436
|
+
thinkingStyle: input.thinkingStyle || 'Analytical',
|
|
437
|
+
currentPhase: input.phase || 'Definition',
|
|
423
438
|
createdAt: new Date().toISOString(),
|
|
424
439
|
updatedAt: new Date().toISOString()
|
|
425
440
|
};
|
|
@@ -427,10 +442,12 @@ export class SequentialThinkingManager {
|
|
|
427
442
|
this.lastSessionId = sessionId;
|
|
428
443
|
// 🔧 NEW: Query past solutions for context
|
|
429
444
|
this.queryPastSolutions(session.problemStatement)
|
|
430
|
-
.then(solutions => {
|
|
445
|
+
.then((solutions) => {
|
|
431
446
|
if (solutions.length > 0) {
|
|
432
447
|
console.log(`[Brain] Found ${solutions.length} similar past problems`);
|
|
433
|
-
const context = solutions
|
|
448
|
+
const context = solutions
|
|
449
|
+
.map((s) => `- ${s.problem} (relevance: ${(s.relevance * 100).toFixed(0)}%)\n Patterns: ${s.patterns.join(', ')}`)
|
|
450
|
+
.join('\n');
|
|
434
451
|
// Add as a thought for AI to see
|
|
435
452
|
const thought = {
|
|
436
453
|
id: uuidv4(),
|
|
@@ -446,20 +463,25 @@ export class SequentialThinkingManager {
|
|
|
446
463
|
this._saveToStorage();
|
|
447
464
|
}
|
|
448
465
|
})
|
|
449
|
-
.catch(err => console.warn('[Brain] Failed to query past solutions:', err));
|
|
466
|
+
.catch((err) => console.warn('[Brain] Failed to query past solutions:', err));
|
|
450
467
|
return {
|
|
451
468
|
success: true,
|
|
452
469
|
sessionId,
|
|
453
470
|
currentStep: 0,
|
|
454
471
|
totalThoughts: session.totalThoughts,
|
|
455
472
|
status: 'in_progress',
|
|
456
|
-
message:
|
|
473
|
+
message: `Brain 2.0 Session Started. Style: ${session.thinkingStyle}, Phase: ${session.currentPhase}. Ready for Tree of Thoughts. Querying past solutions...`
|
|
457
474
|
};
|
|
458
475
|
}
|
|
459
|
-
addThought(input) {
|
|
476
|
+
async addThought(input) {
|
|
460
477
|
const session = this.getSession(input.sessionId);
|
|
478
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
461
479
|
if (!session)
|
|
462
480
|
return { success: false, message: 'Session not found' };
|
|
481
|
+
if (input.phase)
|
|
482
|
+
session.currentPhase = input.phase;
|
|
483
|
+
if (input.thinkingStyle)
|
|
484
|
+
session.thinkingStyle = input.thinkingStyle;
|
|
463
485
|
session.currentStep++;
|
|
464
486
|
const thought = {
|
|
465
487
|
id: uuidv4(),
|
|
@@ -469,9 +491,56 @@ export class SequentialThinkingManager {
|
|
|
469
491
|
timestamp: new Date().toISOString(),
|
|
470
492
|
confidence: input.confidence ?? 70, // Default confidence
|
|
471
493
|
parentId: input.branchFromThoughtId || this.getLastThoughtId(session),
|
|
472
|
-
branchLabel: input.branchLabel // Preserve label
|
|
494
|
+
branchLabel: input.branchLabel, // Preserve label
|
|
495
|
+
phase: session.currentPhase
|
|
473
496
|
};
|
|
474
497
|
session.thoughtHistory.push(thought);
|
|
498
|
+
// 🔧 Action 3: Complexity Routing (Simple Heuristic)
|
|
499
|
+
// If problem statement is short (< 50 chars), suggest simple execution.
|
|
500
|
+
// If long or contains "plan", "complex", "research", suggest full sequential thinking.
|
|
501
|
+
let complexityAnalysis;
|
|
502
|
+
if (session.currentStep === 0) {
|
|
503
|
+
const problemLength = session.problemStatement.length;
|
|
504
|
+
const keywords = ['complex', 'plan', 'research', 'analyze', 'strategy', 'architecture'];
|
|
505
|
+
const isComplex = problemLength > 100 ||
|
|
506
|
+
keywords.some((k) => session.problemStatement.toLowerCase().includes(k));
|
|
507
|
+
complexityAnalysis = isComplex
|
|
508
|
+
? 'Complexity: HIGH. Recommendation: Use full Sequential Thinking with multiple branches.'
|
|
509
|
+
: 'Complexity: LOW. Recommendation: You might be able to solve this directly with a single tool call or short sequence.';
|
|
510
|
+
// Auto-set style for complex problems
|
|
511
|
+
if (isComplex && session.thinkingStyle === 'Analytical') {
|
|
512
|
+
// Keep Analytical default
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// 🔧 Action 2: Intelligent Tool Recommendation
|
|
516
|
+
const recommendedTools = this.recommendTools(thought.thought, session.currentPhase);
|
|
517
|
+
// 🔧 Action 1+: Guidance based on Style/Phase
|
|
518
|
+
const guidance = this.getGuidance(session.thinkingStyle, session.currentPhase);
|
|
519
|
+
// 🔧 Action 5: Deeper Memory Integration (Async check for sub-problems)
|
|
520
|
+
let relatedMemories = [];
|
|
521
|
+
if (['decomposition', 'replan', 'hypothesis'].includes(thought.thoughtType)) {
|
|
522
|
+
// We await this one to provide immediate context, or we could fire-and-forget
|
|
523
|
+
// For better decision making, immediate is better.
|
|
524
|
+
try {
|
|
525
|
+
const past = await this.queryPastSolutions(thought.thought);
|
|
526
|
+
if (past.length > 0) {
|
|
527
|
+
relatedMemories = past.slice(0, 2); // Top 2 relevant memories
|
|
528
|
+
thought.metadata = { ...thought.metadata, relatedMemories };
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
catch (e) {
|
|
532
|
+
console.warn('[Brain] Failed to query memory in addThought:', e);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
// 🔧 Action 3: Suggest router tool if complexity is high
|
|
536
|
+
if (complexityAnalysis && complexityAnalysis.includes('HIGH')) {
|
|
537
|
+
recommendedTools.push({
|
|
538
|
+
toolName: 'decompose',
|
|
539
|
+
confidence: 0.95,
|
|
540
|
+
rationale: 'High complexity detected. Break down the problem first.',
|
|
541
|
+
suggestedInput: { thought: 'Break down the main problem into sub-components' }
|
|
542
|
+
});
|
|
543
|
+
}
|
|
475
544
|
return {
|
|
476
545
|
success: true,
|
|
477
546
|
sessionId: session.sessionId,
|
|
@@ -479,11 +548,125 @@ export class SequentialThinkingManager {
|
|
|
479
548
|
totalThoughts: session.totalThoughts,
|
|
480
549
|
status: session.status,
|
|
481
550
|
thought,
|
|
482
|
-
message: `Thought added (${thought.thoughtType})
|
|
551
|
+
message: `Thought added (${thought.thoughtType}) - Style: ${session.thinkingStyle}, Phase: ${session.currentPhase}`,
|
|
552
|
+
recommendedTools,
|
|
553
|
+
guidance: guidance + (complexityAnalysis ? ` [${complexityAnalysis}]` : ''),
|
|
554
|
+
metadata: { relatedMemories: relatedMemories.length > 0 ? relatedMemories : undefined }
|
|
483
555
|
};
|
|
484
556
|
}
|
|
557
|
+
getGuidance(style, phase) {
|
|
558
|
+
let guidance = '';
|
|
559
|
+
// Style-based guidance
|
|
560
|
+
switch (style) {
|
|
561
|
+
case 'Analytical':
|
|
562
|
+
guidance +=
|
|
563
|
+
'Focus on breaking down the problem into logical components and evaluating data objectively. ';
|
|
564
|
+
break;
|
|
565
|
+
case 'Creative':
|
|
566
|
+
guidance +=
|
|
567
|
+
'Brainstorm multiple alternative solutions, even those that seem unconventional. Use analogies. ';
|
|
568
|
+
break;
|
|
569
|
+
case 'Critical':
|
|
570
|
+
guidance +=
|
|
571
|
+
'Look for potential flaws, risks, and assumptions in the current line of reasoning. Challenge everything. ';
|
|
572
|
+
break;
|
|
573
|
+
case 'Emotional':
|
|
574
|
+
guidance +=
|
|
575
|
+
'Consider the human impact, user experience, and how stakeholders might feel about the solution. ';
|
|
576
|
+
break;
|
|
577
|
+
case 'Optimistic':
|
|
578
|
+
guidance +=
|
|
579
|
+
'Focus on the benefits, opportunities, and the "best-case" scenario. What makes this succeed? ';
|
|
580
|
+
break;
|
|
581
|
+
case 'Synthesis':
|
|
582
|
+
guidance +=
|
|
583
|
+
'Combine different perspectives and findings into a coherent and actionable conclusion. ';
|
|
584
|
+
break;
|
|
585
|
+
}
|
|
586
|
+
// Phase-based guidance
|
|
587
|
+
switch (phase) {
|
|
588
|
+
case 'Definition':
|
|
589
|
+
guidance += 'Ensure the problem is clearly defined and constraints are understood.';
|
|
590
|
+
break;
|
|
591
|
+
case 'Exploration':
|
|
592
|
+
guidance += 'Gather information and explore the solution space without committing yet.';
|
|
593
|
+
break;
|
|
594
|
+
case 'Analysis':
|
|
595
|
+
guidance += 'Deeply examine the gathered information and identify patterns or root causes.';
|
|
596
|
+
break;
|
|
597
|
+
case 'Evaluation':
|
|
598
|
+
guidance += 'Score and compare different options based on criteria like risk and impact.';
|
|
599
|
+
break;
|
|
600
|
+
case 'Synthesis':
|
|
601
|
+
guidance += 'Merge ideas and start forming the final solution plan.';
|
|
602
|
+
break;
|
|
603
|
+
case 'Conclusion':
|
|
604
|
+
guidance += 'Finalize the result and ensure it directly addresses the original problem.';
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
return guidance.trim();
|
|
608
|
+
}
|
|
609
|
+
recommendTools(thought, phase) {
|
|
610
|
+
const recommendations = [];
|
|
611
|
+
const text = thought.toLowerCase();
|
|
612
|
+
// Heuristics based on keywords and phase
|
|
613
|
+
if (text.includes('search') ||
|
|
614
|
+
text.includes('find') ||
|
|
615
|
+
text.includes('research') ||
|
|
616
|
+
phase === 'Exploration') {
|
|
617
|
+
recommendations.push({
|
|
618
|
+
toolName: 'web_search',
|
|
619
|
+
confidence: 0.9,
|
|
620
|
+
rationale: 'Thought involves searching for information or is in Exploration phase.',
|
|
621
|
+
suggestedInput: { query: thought }
|
|
622
|
+
});
|
|
623
|
+
recommendations.push({
|
|
624
|
+
toolName: 'vector_search',
|
|
625
|
+
confidence: 0.7,
|
|
626
|
+
rationale: 'Check local semantic memory for related concepts.',
|
|
627
|
+
suggestedInput: { query: thought }
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
if (text.includes('save') || text.includes('remember') || text.includes('note')) {
|
|
631
|
+
recommendations.push({
|
|
632
|
+
toolName: 'vector_save',
|
|
633
|
+
confidence: 0.8,
|
|
634
|
+
rationale: 'Thought suggests a need to persist information.',
|
|
635
|
+
suggestedInput: { content: thought }
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
if (text.includes('calculate') ||
|
|
639
|
+
text.includes('compute') ||
|
|
640
|
+
text.includes('math') ||
|
|
641
|
+
phase === 'Analysis') {
|
|
642
|
+
recommendations.push({
|
|
643
|
+
toolName: 'compute',
|
|
644
|
+
confidence: 0.8,
|
|
645
|
+
rationale: 'Analytical thoughts often benefit from precise computation.',
|
|
646
|
+
suggestedInput: { expression: '...' }
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
if (text.includes('file') || text.includes('write') || phase === 'Conclusion') {
|
|
650
|
+
recommendations.push({
|
|
651
|
+
toolName: 'write_file',
|
|
652
|
+
confidence: 0.7,
|
|
653
|
+
rationale: 'Thought mentions files or is in Conclusion phase, suggesting report generation.',
|
|
654
|
+
suggestedInput: { file_path: '...', content: '...' }
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
if (text.includes('list') || text.includes('directory')) {
|
|
658
|
+
recommendations.push({
|
|
659
|
+
toolName: 'list_directory',
|
|
660
|
+
confidence: 0.9,
|
|
661
|
+
rationale: 'Direct mention of directory/listing.',
|
|
662
|
+
suggestedInput: { dir_path: '.' }
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
return recommendations;
|
|
666
|
+
}
|
|
485
667
|
generateOptions(input) {
|
|
486
668
|
const session = this.getSession(input.sessionId);
|
|
669
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
487
670
|
if (!session)
|
|
488
671
|
return { success: false, message: 'Session not found' };
|
|
489
672
|
// 🔧 NEW: Generate 3-5 distinct options using templates
|
|
@@ -492,7 +675,9 @@ export class SequentialThinkingManager {
|
|
|
492
675
|
const thought = {
|
|
493
676
|
id: uuidv4(),
|
|
494
677
|
stepNumber: session.currentStep,
|
|
495
|
-
thought: `GENERATED OPTIONS:\n${options
|
|
678
|
+
thought: `GENERATED OPTIONS:\n${options
|
|
679
|
+
.map((o, i) => `${i + 1}. ${o.label}\n ${o.description}\n Effort: ${o.estimatedEffort}, Risk: ${o.riskLevel}`)
|
|
680
|
+
.join('\n')}`,
|
|
496
681
|
thoughtType: 'option_generation',
|
|
497
682
|
timestamp: new Date().toISOString(),
|
|
498
683
|
confidence: 75,
|
|
@@ -514,6 +699,7 @@ export class SequentialThinkingManager {
|
|
|
514
699
|
}
|
|
515
700
|
evaluateOptions(input) {
|
|
516
701
|
const session = this.getSession(input.sessionId);
|
|
702
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
517
703
|
if (!session)
|
|
518
704
|
return { success: false, message: 'Session not found' };
|
|
519
705
|
// 🔧 NEW: Evaluate last thought's options
|
|
@@ -526,9 +712,10 @@ export class SequentialThinkingManager {
|
|
|
526
712
|
totalThoughts: session.totalThoughts,
|
|
527
713
|
status: session.status,
|
|
528
714
|
message: 'No options found in last thought. Use generateOptions first.'
|
|
715
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
529
716
|
};
|
|
530
717
|
}
|
|
531
|
-
const options = lastThought.metadata.options;
|
|
718
|
+
const options = lastThought.metadata.options || [];
|
|
532
719
|
// 🔧 BUG FIX: Validate array before processing
|
|
533
720
|
if (!Array.isArray(options) || options.length === 0) {
|
|
534
721
|
return {
|
|
@@ -538,6 +725,7 @@ export class SequentialThinkingManager {
|
|
|
538
725
|
totalThoughts: session.totalThoughts,
|
|
539
726
|
status: session.status,
|
|
540
727
|
message: 'Invalid options in metadata. Use generateOptions first.'
|
|
728
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
541
729
|
};
|
|
542
730
|
}
|
|
543
731
|
const evaluatedOptions = options.map((opt) => {
|
|
@@ -547,7 +735,7 @@ export class SequentialThinkingManager {
|
|
|
547
735
|
return {
|
|
548
736
|
...opt,
|
|
549
737
|
scores: { feasibility, impact, risk },
|
|
550
|
-
totalScore:
|
|
738
|
+
totalScore: feasibility * 0.4 + impact * 0.4 + (1 - risk) * 0.2,
|
|
551
739
|
reasoning: `Feasibility: ${(feasibility * 100).toFixed(0)}%, Impact: ${(impact * 100).toFixed(0)}%, Risk: ${(risk * 100).toFixed(0)}%`,
|
|
552
740
|
confidence: 80,
|
|
553
741
|
uncertainty: 0.15
|
|
@@ -557,7 +745,9 @@ export class SequentialThinkingManager {
|
|
|
557
745
|
const thought = {
|
|
558
746
|
id: uuidv4(),
|
|
559
747
|
stepNumber: session.currentStep,
|
|
560
|
-
thought: `EVALUATED OPTIONS:\n${evaluatedOptions
|
|
748
|
+
thought: `EVALUATED OPTIONS:\n${evaluatedOptions
|
|
749
|
+
.map((o, i) => `${i + 1}. ${o.label}: ${o.totalScore.toFixed(2)}\n ${o.reasoning}`)
|
|
750
|
+
.join('\n')}`,
|
|
561
751
|
thoughtType: 'option_evaluation',
|
|
562
752
|
timestamp: new Date().toISOString(),
|
|
563
753
|
confidence: 80,
|
|
@@ -578,6 +768,8 @@ export class SequentialThinkingManager {
|
|
|
578
768
|
};
|
|
579
769
|
}
|
|
580
770
|
const best = [...evaluatedOptions].sort((a, b) => b.totalScore - a.totalScore)[0];
|
|
771
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
772
|
+
const bestOption = best;
|
|
581
773
|
return {
|
|
582
774
|
success: true,
|
|
583
775
|
sessionId: session.sessionId,
|
|
@@ -585,27 +777,30 @@ export class SequentialThinkingManager {
|
|
|
585
777
|
totalThoughts: session.totalThoughts,
|
|
586
778
|
status: session.status,
|
|
587
779
|
thought,
|
|
588
|
-
message: `Evaluated ${evaluatedOptions.length} options. Best: ${
|
|
780
|
+
message: `Evaluated ${evaluatedOptions.length} options. Best: ${bestOption.label} (${bestOption.totalScore.toFixed(2)})`,
|
|
589
781
|
nextSuggestedActions: ['select_option']
|
|
590
782
|
};
|
|
591
783
|
}
|
|
592
784
|
selectOption(input) {
|
|
593
785
|
const session = this.getSession(input.sessionId);
|
|
786
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
594
787
|
if (!session)
|
|
595
788
|
return { success: false, message: 'Session not found' };
|
|
789
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
596
790
|
if (!input.optionId)
|
|
597
791
|
return { success: false, message: 'optionId required' };
|
|
598
|
-
const selected = session.thoughtHistory.find(t => t.id === input.optionId);
|
|
792
|
+
const selected = session.thoughtHistory.find((t) => t.id === input.optionId);
|
|
793
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
599
794
|
if (!selected)
|
|
600
795
|
return { success: false, message: 'Option not found' };
|
|
601
796
|
// 🔧 NEW: Enhanced selection with evaluation data
|
|
602
797
|
const evalThought = session.thoughtHistory
|
|
603
|
-
.filter(t => t.thoughtType === 'option_evaluation')
|
|
798
|
+
.filter((t) => t.thoughtType === 'option_evaluation')
|
|
604
799
|
.slice(-1)[0];
|
|
605
800
|
let evalData = null;
|
|
606
801
|
if (evalThought?.metadata?.evaluatedOptions) {
|
|
607
802
|
const options = evalThought.metadata.evaluatedOptions;
|
|
608
|
-
evalData = options.find((o) => o.id === input.optionId);
|
|
803
|
+
evalData = options.find((o) => o.id === input.optionId) || null;
|
|
609
804
|
}
|
|
610
805
|
const confidence = evalData?.confidence || 85;
|
|
611
806
|
const uncertainty = evalData?.uncertainty || 0.15;
|
|
@@ -659,7 +854,9 @@ export class SequentialThinkingManager {
|
|
|
659
854
|
};
|
|
660
855
|
session.thoughtHistory.push(thought);
|
|
661
856
|
if (input.thought && input.thought.length > 50) {
|
|
662
|
-
vectorMemory.add(`Reflexion on ${session.problemStatement}: ${input.thought}`, {
|
|
857
|
+
vectorMemory.add(`Reflexion on ${session.problemStatement}: ${input.thought}`, {
|
|
858
|
+
sessionId: session.sessionId
|
|
859
|
+
});
|
|
663
860
|
}
|
|
664
861
|
return {
|
|
665
862
|
success: true,
|
|
@@ -707,16 +904,21 @@ export class SequentialThinkingManager {
|
|
|
707
904
|
plan = {
|
|
708
905
|
planId: 'auto-' + uuidv4(),
|
|
709
906
|
name: 'Auto Plan',
|
|
710
|
-
tasks: [
|
|
907
|
+
tasks: [
|
|
908
|
+
{
|
|
711
909
|
id: 't1',
|
|
712
910
|
name: 'Auto Echo',
|
|
713
911
|
toolName: 'echo',
|
|
714
912
|
toolInput: { text: 'Running fallback due to invalid plan format.' },
|
|
715
913
|
dependencies: []
|
|
716
|
-
}
|
|
914
|
+
}
|
|
915
|
+
]
|
|
717
916
|
};
|
|
718
917
|
}
|
|
719
|
-
const execResult = await orchestratorManager.process({
|
|
918
|
+
const execResult = await orchestratorManager.process({
|
|
919
|
+
action: 'execute_plan',
|
|
920
|
+
plan: plan
|
|
921
|
+
});
|
|
720
922
|
// 🔧 NEW: Learn from execution outcome
|
|
721
923
|
await this.analyzeExecutionOutcome(session, execResult);
|
|
722
924
|
await this.process({
|
|
@@ -733,7 +935,9 @@ export class SequentialThinkingManager {
|
|
|
733
935
|
currentStep: session.currentStep,
|
|
734
936
|
totalThoughts: session.totalThoughts,
|
|
735
937
|
status: session.status,
|
|
736
|
-
message: execResult.success
|
|
938
|
+
message: execResult.success
|
|
939
|
+
? `Execution Success. Reflexion triggered.`
|
|
940
|
+
: `Execution Failed: ${execResult.message}. Reflexion triggered.`,
|
|
737
941
|
executionResult: execResult.result,
|
|
738
942
|
metadata: { validationErrors: execResult.validationErrors }
|
|
739
943
|
};
|
|
@@ -754,7 +958,9 @@ export class SequentialThinkingManager {
|
|
|
754
958
|
return this.sessions.get(id);
|
|
755
959
|
}
|
|
756
960
|
getLastThoughtId(session) {
|
|
757
|
-
return session.thoughtHistory.length > 0
|
|
961
|
+
return session.thoughtHistory.length > 0
|
|
962
|
+
? session.thoughtHistory[session.thoughtHistory.length - 1].id
|
|
963
|
+
: undefined;
|
|
758
964
|
}
|
|
759
965
|
// 🔧 NEW: Helper methods for ToT implementation
|
|
760
966
|
generateThoughtOptions(session, context) {
|
|
@@ -792,22 +998,25 @@ export class SequentialThinkingManager {
|
|
|
792
998
|
// 🔧 BUG FIX: Add null safety
|
|
793
999
|
if (!opt || typeof opt !== 'object')
|
|
794
1000
|
return 0.5;
|
|
1001
|
+
const effort = opt.estimatedEffort;
|
|
795
1002
|
const effortMap = { low: 0.9, medium: 0.6, high: 0.3 };
|
|
796
|
-
return effortMap[
|
|
1003
|
+
return effortMap[effort] || 0.5;
|
|
797
1004
|
}
|
|
798
1005
|
estimateImpact(opt) {
|
|
799
1006
|
// 🔧 BUG FIX: Add null safety
|
|
800
1007
|
if (!opt || typeof opt !== 'object')
|
|
801
1008
|
return 0.5;
|
|
1009
|
+
const risk = opt.riskLevel;
|
|
802
1010
|
const riskMap = { low: 0.4, medium: 0.7, high: 0.9 };
|
|
803
|
-
return riskMap[
|
|
1011
|
+
return riskMap[risk] || 0.5;
|
|
804
1012
|
}
|
|
805
1013
|
estimateRisk(opt) {
|
|
806
1014
|
// 🔧 BUG FIX: Add null safety
|
|
807
1015
|
if (!opt || typeof opt !== 'object')
|
|
808
1016
|
return 0.5;
|
|
1017
|
+
const risk = opt.riskLevel;
|
|
809
1018
|
const riskMap = { low: 0.1, medium: 0.4, high: 0.7 };
|
|
810
|
-
return riskMap[
|
|
1019
|
+
return riskMap[risk] || 0.5;
|
|
811
1020
|
}
|
|
812
1021
|
// 🔧 NEW: Learning System methods
|
|
813
1022
|
async analyzeExecutionOutcome(session, result) {
|
|
@@ -846,7 +1055,9 @@ export class SequentialThinkingManager {
|
|
|
846
1055
|
}
|
|
847
1056
|
else {
|
|
848
1057
|
const errorMsg = result.message || result.result?.errors?.[0]?.error || '';
|
|
849
|
-
if (errorMsg.includes('fetch') ||
|
|
1058
|
+
if (errorMsg.includes('fetch') ||
|
|
1059
|
+
errorMsg.includes('network') ||
|
|
1060
|
+
errorMsg.includes('ECONNREFUSED')) {
|
|
850
1061
|
patterns.push('network-failure');
|
|
851
1062
|
}
|
|
852
1063
|
if (errorMsg.includes('timeout') || errorMsg.includes('timed out')) {
|
|
@@ -893,7 +1104,7 @@ export class SequentialThinkingManager {
|
|
|
893
1104
|
const query = `Similar problems to: ${problem}`;
|
|
894
1105
|
try {
|
|
895
1106
|
const results = await vectorMemory.search(query, 5);
|
|
896
|
-
return results.map(r => ({
|
|
1107
|
+
return results.map((r) => ({
|
|
897
1108
|
problem: r.item.content,
|
|
898
1109
|
solution: r.item.metadata,
|
|
899
1110
|
relevance: r.score || 0.5,
|
|
@@ -906,10 +1117,18 @@ export class SequentialThinkingManager {
|
|
|
906
1117
|
return [];
|
|
907
1118
|
}
|
|
908
1119
|
}
|
|
909
|
-
createBranch(input) {
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
1120
|
+
createBranch(input) {
|
|
1121
|
+
return this.addThought(input);
|
|
1122
|
+
}
|
|
1123
|
+
reviseThought(input) {
|
|
1124
|
+
return this.addThought({ ...input, thoughtType: 'revision' });
|
|
1125
|
+
}
|
|
1126
|
+
setHypothesis(input) {
|
|
1127
|
+
return this.addThought({ ...input, thoughtType: 'hypothesis' });
|
|
1128
|
+
}
|
|
1129
|
+
verifyHypothesis(input) {
|
|
1130
|
+
return this.addThought({ ...input, thoughtType: 'verification' });
|
|
1131
|
+
}
|
|
913
1132
|
conclude(input) {
|
|
914
1133
|
const session = this.getSession(input.sessionId);
|
|
915
1134
|
if (session) {
|