@gotza02/seq-thinking 1.1.5 → 1.1.7
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 +4 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/mcp-server.js +1 -1
- package/package.json +9 -3
- package/agents_test.log +0 -15
- package/data/agents/1770106504306-dljh9ef.json +0 -68
- package/data/agents/1770106504310-4oarrst.json +0 -58
- package/data/agents/1770106540588-pvitt55.json +0 -68
- package/data/agents/1770106540595-z2ya871.json +0 -58
- package/data/agents/1770106710890-0e2naq1.json +0 -68
- package/data/agents/1770106710893-r076yxx.json +0 -58
- package/data/agents/1770109212161-4ybd0i7.json +0 -68
- package/data/agents/1770109212166-gkhya8h.json +0 -58
- package/data/agents/1770117726716-lrnm415.json +0 -68
- package/data/agents/1770117726719-w6hsf3v.json +0 -58
- package/data/sessions/1770100622009-5afiuyv.json +0 -499
- package/data/sessions/1770106504312-75zk750.json +0 -107
- package/data/sessions/1770106540597-z8e8soo.json +0 -150
- package/data/sessions/1770106710894-0kxgy5x.json +0 -150
- package/data/sessions/1770109212169-zpddeb9.json +0 -150
- package/data/sessions/1770117726720-frcwj99.json +0 -150
- package/real_world_test.log +0 -200
- package/real_world_test_dynamic.log +0 -184
- package/real_world_test_real.log +0 -184
- package/src/__tests__/agents.test.ts +0 -858
- package/src/__tests__/mcp-server.test.ts +0 -380
- package/src/__tests__/sequential-thinking.test.ts +0 -687
- package/src/__tests__/swarm-coordinator.test.ts +0 -903
- package/src/__tests__/types.test.ts +0 -839
- package/src/__tests__/utils.test.ts +0 -322
- package/src/agents/base-agent.ts +0 -288
- package/src/agents/critic-agent.ts +0 -582
- package/src/agents/index.ts +0 -11
- package/src/agents/meta-reasoning-agent.ts +0 -314
- package/src/agents/reasoner-agent.ts +0 -312
- package/src/agents/synthesizer-agent.ts +0 -641
- package/src/index.ts +0 -118
- package/src/mcp-server.ts +0 -391
- package/src/real_world_test.ts +0 -89
- package/src/sequential-thinking.ts +0 -614
- package/src/swarm-coordinator.ts +0 -772
- package/src/types/index.ts +0 -915
- package/src/utils/index.ts +0 -1004
- package/src/utils/llm-adapter.ts +0 -110
- package/src/utils/logger.ts +0 -56
- package/src/utils/persistence.ts +0 -109
- package/test_output.log +0 -0
- package/tsconfig.json +0 -21
|
@@ -1,614 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sequential Thinking Engine
|
|
3
|
-
*/
|
|
4
|
-
import { ThoughtType, Thought, ThoughtBranch, ConfidenceScore, MetaNote, ThinkingSession, SessionStatus, BranchStatus } from './types/index.js';
|
|
5
|
-
import { calculateSimilarity } from './utils/index.js';
|
|
6
|
-
import { LLMAdapter } from './utils/llm-adapter.js';
|
|
7
|
-
import { Logger } from './utils/logger.js';
|
|
8
|
-
|
|
9
|
-
export class ConfidenceCalibrator {
|
|
10
|
-
createInitialConfidence(): ConfidenceScore {
|
|
11
|
-
return {
|
|
12
|
-
overall: 0.5,
|
|
13
|
-
components: {
|
|
14
|
-
logicalConsistency: 0.5,
|
|
15
|
-
factualAccuracy: 0.5,
|
|
16
|
-
reasoningQuality: 0.5,
|
|
17
|
-
evidenceStrength: 0.5
|
|
18
|
-
},
|
|
19
|
-
uncertaintyBounds: [0.3, 0.7],
|
|
20
|
-
calibrationHistory: []
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
calculateOverall(components: any) {
|
|
24
|
-
const weights: Record<string, number> = {
|
|
25
|
-
logicalConsistency: 0.3,
|
|
26
|
-
factualAccuracy: 0.25,
|
|
27
|
-
reasoningQuality: 0.25,
|
|
28
|
-
evidenceStrength: 0.2
|
|
29
|
-
};
|
|
30
|
-
let weightedSum = 0;
|
|
31
|
-
for (const [key, value] of Object.entries(components)) {
|
|
32
|
-
weightedSum += (value as number) * weights[key];
|
|
33
|
-
}
|
|
34
|
-
return Math.min(1, Math.max(0, weightedSum));
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export class ThoughtGraph {
|
|
39
|
-
thoughts = new Map<string, Thought>();
|
|
40
|
-
branches = new Map<string, ThoughtBranch>();
|
|
41
|
-
calibrator: ConfidenceCalibrator;
|
|
42
|
-
constructor() {
|
|
43
|
-
this.calibrator = new ConfidenceCalibrator();
|
|
44
|
-
}
|
|
45
|
-
createThought(sessionId: string, content: string, options: any = {}): Thought {
|
|
46
|
-
const id = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
47
|
-
const now = new Date();
|
|
48
|
-
const branchId = options.branchId || 'main';
|
|
49
|
-
const thought: Thought = {
|
|
50
|
-
id,
|
|
51
|
-
sessionId,
|
|
52
|
-
content,
|
|
53
|
-
stepNumber: this.calculateStepNumber(sessionId, branchId, options.parentThoughtId),
|
|
54
|
-
thoughtType: options.thoughtType || ThoughtType.ANALYSIS,
|
|
55
|
-
confidence: this.createConfidence(options.confidence),
|
|
56
|
-
parentThoughtId: options.parentThoughtId || null,
|
|
57
|
-
childThoughtIds: [],
|
|
58
|
-
branchId,
|
|
59
|
-
revisionOf: null,
|
|
60
|
-
revisionHistory: [],
|
|
61
|
-
metadata: {
|
|
62
|
-
createdAt: now,
|
|
63
|
-
modifiedAt: now,
|
|
64
|
-
agentId: options.agentId,
|
|
65
|
-
processingTimeMs: 0,
|
|
66
|
-
tokensUsed: 0
|
|
67
|
-
},
|
|
68
|
-
tags: options.tags || [],
|
|
69
|
-
assumptions: options.assumptions || [],
|
|
70
|
-
dependencies: options.dependencies || []
|
|
71
|
-
};
|
|
72
|
-
this.thoughts.set(id, thought);
|
|
73
|
-
if (options.parentThoughtId) {
|
|
74
|
-
const parent = this.thoughts.get(options.parentThoughtId);
|
|
75
|
-
if (parent) {
|
|
76
|
-
parent.childThoughtIds.push(id);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return thought;
|
|
80
|
-
}
|
|
81
|
-
reviseThought(thoughtId: string, newContent: string, revisionReason: string): Thought {
|
|
82
|
-
const original = this.thoughts.get(thoughtId);
|
|
83
|
-
if (!original) {
|
|
84
|
-
throw new Error(`Thought not found: ${thoughtId}`);
|
|
85
|
-
}
|
|
86
|
-
const revisionId = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
87
|
-
const now = new Date();
|
|
88
|
-
const record = {
|
|
89
|
-
previousContent: original.content,
|
|
90
|
-
revisedAt: now,
|
|
91
|
-
revisionReason
|
|
92
|
-
};
|
|
93
|
-
original.revisionHistory.push(record);
|
|
94
|
-
original.metadata.modifiedAt = now;
|
|
95
|
-
|
|
96
|
-
const revision: Thought = {
|
|
97
|
-
...original,
|
|
98
|
-
id: revisionId,
|
|
99
|
-
content: newContent,
|
|
100
|
-
thoughtType: ThoughtType.REVISION,
|
|
101
|
-
revisionOf: thoughtId,
|
|
102
|
-
revisionHistory: [...original.revisionHistory],
|
|
103
|
-
metadata: {
|
|
104
|
-
...original.metadata,
|
|
105
|
-
createdAt: now,
|
|
106
|
-
modifiedAt: now
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
this.thoughts.set(revisionId, revision);
|
|
110
|
-
return revision;
|
|
111
|
-
}
|
|
112
|
-
createBranch(sessionId: string, parentThoughtId: string, name: string, description: string, initialContent: string) {
|
|
113
|
-
const branchId = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
114
|
-
const now = new Date();
|
|
115
|
-
const parentBranchId = this.getBranchIdForThought(parentThoughtId);
|
|
116
|
-
const branch: ThoughtBranch = {
|
|
117
|
-
id: branchId,
|
|
118
|
-
sessionId,
|
|
119
|
-
name,
|
|
120
|
-
description,
|
|
121
|
-
rootThoughtId: '',
|
|
122
|
-
thoughtIds: [],
|
|
123
|
-
parentBranchId: parentBranchId ?? null,
|
|
124
|
-
childBranchIds: [],
|
|
125
|
-
status: BranchStatus.ACTIVE,
|
|
126
|
-
confidence: 0.5,
|
|
127
|
-
metadata: { createdAt: now }
|
|
128
|
-
};
|
|
129
|
-
const thought = this.createThought(sessionId, initialContent, {
|
|
130
|
-
thoughtType: ThoughtType.BRANCH_POINT,
|
|
131
|
-
parentThoughtId,
|
|
132
|
-
branchId
|
|
133
|
-
});
|
|
134
|
-
branch.rootThoughtId = thought.id;
|
|
135
|
-
branch.thoughtIds.push(thought.id);
|
|
136
|
-
this.branches.set(branchId, branch);
|
|
137
|
-
const parentBranch = this.getBranchForThought(parentThoughtId);
|
|
138
|
-
if (parentBranch) {
|
|
139
|
-
parentBranch.childBranchIds.push(branchId);
|
|
140
|
-
}
|
|
141
|
-
return { branch, thought };
|
|
142
|
-
}
|
|
143
|
-
mergeBranches(targetBranchId: string, sourceBranchId: string, mergeContent: string) {
|
|
144
|
-
const target = this.branches.get(targetBranchId);
|
|
145
|
-
const source = this.branches.get(sourceBranchId);
|
|
146
|
-
if (!target || !source) {
|
|
147
|
-
throw new Error('Branch not found');
|
|
148
|
-
}
|
|
149
|
-
const mergeThought = this.createThought(target.sessionId, mergeContent, {
|
|
150
|
-
thoughtType: ThoughtType.MERGE_POINT,
|
|
151
|
-
branchId: targetBranchId
|
|
152
|
-
});
|
|
153
|
-
(source.status as any) = BranchStatus.MERGED;
|
|
154
|
-
source.metadata.completedAt = new Date();
|
|
155
|
-
return mergeThought;
|
|
156
|
-
}
|
|
157
|
-
pruneBranch(branchId: string, reason: string) {
|
|
158
|
-
const branch = this.branches.get(branchId);
|
|
159
|
-
if (!branch) {
|
|
160
|
-
throw new Error(`Branch not found: ${branchId}`);
|
|
161
|
-
}
|
|
162
|
-
(branch.status as any) = BranchStatus.PRUNED;
|
|
163
|
-
branch.metadata.prunedAt = new Date();
|
|
164
|
-
branch.metadata.pruneReason = reason;
|
|
165
|
-
}
|
|
166
|
-
getThinkingPath(thoughtId: string) {
|
|
167
|
-
const path: Thought[] = [];
|
|
168
|
-
let current = this.thoughts.get(thoughtId);
|
|
169
|
-
while (current) {
|
|
170
|
-
path.unshift(current);
|
|
171
|
-
current = current.parentThoughtId
|
|
172
|
-
? this.thoughts.get(current.parentThoughtId)
|
|
173
|
-
: undefined;
|
|
174
|
-
}
|
|
175
|
-
return path;
|
|
176
|
-
}
|
|
177
|
-
getBranchComparison(branchIds: string[]) {
|
|
178
|
-
return branchIds.map(id => {
|
|
179
|
-
const branch = this.branches.get(id);
|
|
180
|
-
if (!branch)
|
|
181
|
-
return null;
|
|
182
|
-
const thoughts = branch.thoughtIds
|
|
183
|
-
.map(tid => this.thoughts.get(tid))
|
|
184
|
-
.filter((t): t is Thought => t !== undefined);
|
|
185
|
-
const avgConfidence = thoughts.length > 0
|
|
186
|
-
? thoughts.reduce((sum, t) => sum + t.confidence.overall, 0) / thoughts.length
|
|
187
|
-
: 0;
|
|
188
|
-
const conclusion = thoughts.find(t => t.thoughtType === ThoughtType.CONCLUSION);
|
|
189
|
-
return {
|
|
190
|
-
branchId: id,
|
|
191
|
-
thoughtCount: thoughts.length,
|
|
192
|
-
averageConfidence: avgConfidence,
|
|
193
|
-
conclusion: conclusion?.content || null
|
|
194
|
-
};
|
|
195
|
-
}).filter((b): b is any => b !== null);
|
|
196
|
-
}
|
|
197
|
-
calculateStepNumber(sessionId: string, branchId: string, parentThoughtId: string | null | undefined): number {
|
|
198
|
-
if (!parentThoughtId) {
|
|
199
|
-
const branchThoughts = Array.from(this.thoughts.values())
|
|
200
|
-
.filter(t => t.sessionId === sessionId && t.branchId === branchId);
|
|
201
|
-
return branchThoughts.length + 1;
|
|
202
|
-
}
|
|
203
|
-
const parent = this.thoughts.get(parentThoughtId);
|
|
204
|
-
return parent ? parent.stepNumber + 1 : 1;
|
|
205
|
-
}
|
|
206
|
-
createConfidence(override: number | undefined): ConfidenceScore {
|
|
207
|
-
const confidence = this.calibrator.createInitialConfidence();
|
|
208
|
-
if (override !== undefined) {
|
|
209
|
-
confidence.overall = override;
|
|
210
|
-
}
|
|
211
|
-
return confidence;
|
|
212
|
-
}
|
|
213
|
-
getBranchIdForThought(thoughtId: string) {
|
|
214
|
-
const thought = this.thoughts.get(thoughtId);
|
|
215
|
-
return thought?.branchId;
|
|
216
|
-
}
|
|
217
|
-
getBranchForThought(thoughtId: string) {
|
|
218
|
-
const branchId = this.getBranchIdForThought(thoughtId);
|
|
219
|
-
return branchId ? this.branches.get(branchId) : undefined;
|
|
220
|
-
}
|
|
221
|
-
getThoughts() {
|
|
222
|
-
return this.thoughts;
|
|
223
|
-
}
|
|
224
|
-
getBranches() {
|
|
225
|
-
return this.branches;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
export class MetaReasoningEngine {
|
|
230
|
-
metaNotes = new Map<string, MetaNote>();
|
|
231
|
-
|
|
232
|
-
async reflect(session: ThinkingSession) {
|
|
233
|
-
const thoughts = Array.from(session.thoughts.values());
|
|
234
|
-
|
|
235
|
-
// Basic analysis
|
|
236
|
-
const insights: string[] = [];
|
|
237
|
-
const recommendations: string[] = [];
|
|
238
|
-
|
|
239
|
-
const analysisCount = thoughts.filter(t => t.thoughtType === ThoughtType.ANALYSIS).length;
|
|
240
|
-
const hypothesisCount = thoughts.filter(t => t.thoughtType === ThoughtType.HYPOTHESIS).length;
|
|
241
|
-
|
|
242
|
-
if (analysisCount > hypothesisCount * 2) {
|
|
243
|
-
insights.push('Heavy focus on analysis with limited hypothesis generation');
|
|
244
|
-
recommendations.push('Consider exploring more alternative hypotheses');
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
const avgConfidence = thoughts.length > 0
|
|
248
|
-
? thoughts.reduce((sum, t) => sum + t.confidence.overall, 0) / thoughts.length
|
|
249
|
-
: 0;
|
|
250
|
-
|
|
251
|
-
if (avgConfidence < 0.5) {
|
|
252
|
-
insights.push('Overall confidence is low');
|
|
253
|
-
recommendations.push('Review assumptions and gather more evidence');
|
|
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
|
-
|
|
268
|
-
return {
|
|
269
|
-
reflectionType: 'session_review',
|
|
270
|
-
content: `Analyzed ${thoughts.length} thoughts across ${session.branches.size} branches`,
|
|
271
|
-
insights,
|
|
272
|
-
recommendations
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
generateMetaObservation(thoughtId: string, thoughtGraph: ThoughtGraph) {
|
|
277
|
-
const thought = thoughtGraph.getThoughts().get(thoughtId);
|
|
278
|
-
if (!thought)
|
|
279
|
-
return null;
|
|
280
|
-
const observations: string[] = [];
|
|
281
|
-
if (thought.confidence.uncertaintyBounds[1] - thought.confidence.uncertaintyBounds[0] > 0.4) {
|
|
282
|
-
observations.push('High uncertainty detected');
|
|
283
|
-
}
|
|
284
|
-
const similarThoughts = Array.from(thoughtGraph.getThoughts().values())
|
|
285
|
-
.filter(t => t.id !== thought.id && calculateSimilarity(t.content, thought.content) > 0.7);
|
|
286
|
-
if (similarThoughts.length > 0) {
|
|
287
|
-
observations.push(`Similar to ${similarThoughts.length} previous thoughts`);
|
|
288
|
-
}
|
|
289
|
-
if (observations.length === 0)
|
|
290
|
-
return null;
|
|
291
|
-
const note: MetaNote = {
|
|
292
|
-
id: `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
|
|
293
|
-
thoughtId,
|
|
294
|
-
content: observations.join('\n'),
|
|
295
|
-
observationType: 'pattern',
|
|
296
|
-
timestamp: new Date(),
|
|
297
|
-
triggeredActions: []
|
|
298
|
-
};
|
|
299
|
-
this.metaNotes.set(note.id, note);
|
|
300
|
-
return note;
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
export class SelfCorrectionEngine {
|
|
305
|
-
async detectIssues(thought: Thought, graph: ThoughtGraph) {
|
|
306
|
-
const issues: any[] = [];
|
|
307
|
-
|
|
308
|
-
// Fast heuristics
|
|
309
|
-
if (thought.confidence.overall < 0.3) {
|
|
310
|
-
issues.push({
|
|
311
|
-
type: 'calibration',
|
|
312
|
-
severity: 'medium',
|
|
313
|
-
description: 'Very low confidence',
|
|
314
|
-
suggestion: 'Re-examine reasoning'
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
if (thought.assumptions.length === 0 && thought.thoughtType !== ThoughtType.CONCLUSION) {
|
|
318
|
-
issues.push({
|
|
319
|
-
type: 'assumption',
|
|
320
|
-
severity: 'low',
|
|
321
|
-
description: 'No explicit assumptions',
|
|
322
|
-
suggestion: 'Document assumptions'
|
|
323
|
-
});
|
|
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
|
-
|
|
345
|
-
return issues;
|
|
346
|
-
}
|
|
347
|
-
checkSessionHealth(session: ThinkingSession) {
|
|
348
|
-
const issues: string[] = [];
|
|
349
|
-
const suggestions: string[] = [];
|
|
350
|
-
const thoughts = Array.from(session.thoughts.values());
|
|
351
|
-
// Check for low confidence thoughts
|
|
352
|
-
const lowConfidenceCount = thoughts.filter(t => (t as any).confidence.overall < 0.4).length;
|
|
353
|
-
if (lowConfidenceCount > thoughts.length * 0.5) {
|
|
354
|
-
issues.push('More than 50% of thoughts have low confidence');
|
|
355
|
-
suggestions.push('Review and strengthen reasoning for low-confidence thoughts');
|
|
356
|
-
}
|
|
357
|
-
// Check for abandoned branches
|
|
358
|
-
const abandonedBranches = Array.from(session.branches.values())
|
|
359
|
-
.filter(b => (b as any).status === BranchStatus.ACTIVE && (b as any).thoughtIds.length === 0);
|
|
360
|
-
if (abandonedBranches.length > 0) {
|
|
361
|
-
issues.push(`${abandonedBranches.length} branches are empty`);
|
|
362
|
-
suggestions.push('Either develop abandoned branches or mark them as pruned`');
|
|
363
|
-
}
|
|
364
|
-
// Calculate overall confidence
|
|
365
|
-
const avgConfidence = thoughts.length > 0
|
|
366
|
-
? thoughts.reduce((sum, t) => sum + (t as any).confidence.overall, 0) / thoughts.length
|
|
367
|
-
: 0.5;
|
|
368
|
-
const isHealthy = issues.length === 0 && avgConfidence >= 0.5;
|
|
369
|
-
return {
|
|
370
|
-
isHealthy,
|
|
371
|
-
issues,
|
|
372
|
-
suggestions,
|
|
373
|
-
confidence: avgConfidence
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
export class AdaptiveGranularityEngine {
|
|
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';
|
|
388
|
-
}
|
|
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) });
|
|
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
|
-
|
|
413
|
-
return {
|
|
414
|
-
suggestedAction: detail > 0.7 ? 'increase_granularity' : 'maintain_granularity',
|
|
415
|
-
detail,
|
|
416
|
-
reasoning: hasComplexTerms ? 'Complex topic detected' : 'Standard complexity'
|
|
417
|
-
};
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
import { PersistenceManager } from './utils/persistence.js';
|
|
422
|
-
|
|
423
|
-
export class SessionManager {
|
|
424
|
-
sessions = new Map<string, ThinkingSession>();
|
|
425
|
-
graph: ThoughtGraph;
|
|
426
|
-
metaEngine: MetaReasoningEngine;
|
|
427
|
-
correctionEngine: SelfCorrectionEngine;
|
|
428
|
-
granularityEngine: AdaptiveGranularityEngine;
|
|
429
|
-
persistence: PersistenceManager | null = null;
|
|
430
|
-
|
|
431
|
-
constructor(persistenceDir?: string) {
|
|
432
|
-
this.graph = new ThoughtGraph();
|
|
433
|
-
this.metaEngine = new MetaReasoningEngine();
|
|
434
|
-
this.correctionEngine = new SelfCorrectionEngine();
|
|
435
|
-
this.granularityEngine = new AdaptiveGranularityEngine();
|
|
436
|
-
if (persistenceDir) {
|
|
437
|
-
this.persistence = new PersistenceManager(persistenceDir);
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
async initialize() {
|
|
442
|
-
if (this.persistence) {
|
|
443
|
-
await this.persistence.initialize(['sessions']);
|
|
444
|
-
await this.loadSessions();
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
async loadSessions() {
|
|
449
|
-
if (!this.persistence) return;
|
|
450
|
-
const ids = await this.persistence.list('sessions');
|
|
451
|
-
for (const id of ids) {
|
|
452
|
-
const session = await this.persistence.load<ThinkingSession>('sessions', id);
|
|
453
|
-
if (session) {
|
|
454
|
-
// Restore Maps from serialized format
|
|
455
|
-
if ((session.thoughts as any)._type === 'Map') {
|
|
456
|
-
session.thoughts = new Map((session.thoughts as any).data);
|
|
457
|
-
} else if (!(session.thoughts instanceof Map)) {
|
|
458
|
-
session.thoughts = new Map(Object.entries(session.thoughts));
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
if ((session.branches as any)._type === 'Map') {
|
|
462
|
-
session.branches = new Map((session.branches as any).data);
|
|
463
|
-
} else if (!(session.branches instanceof Map)) {
|
|
464
|
-
session.branches = new Map(Object.entries(session.branches));
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
if ((session.metaNotes as any)._type === 'Map') {
|
|
468
|
-
session.metaNotes = new Map((session.metaNotes as any).data);
|
|
469
|
-
} else if (!(session.metaNotes instanceof Map)) {
|
|
470
|
-
session.metaNotes = new Map(Object.entries(session.metaNotes));
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
this.sessions.set(id, session);
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
async createSession(topic: string, options: any = {}) {
|
|
479
|
-
const id = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
480
|
-
const now = new Date();
|
|
481
|
-
const session: ThinkingSession = {
|
|
482
|
-
id,
|
|
483
|
-
topic,
|
|
484
|
-
status: SessionStatus.INITIALIZING,
|
|
485
|
-
currentBranchId: 'main',
|
|
486
|
-
branches: new Map(),
|
|
487
|
-
thoughts: new Map(),
|
|
488
|
-
metaNotes: new Map(),
|
|
489
|
-
context: {
|
|
490
|
-
originalProblem: topic,
|
|
491
|
-
constraints: [],
|
|
492
|
-
relevantInformation: [],
|
|
493
|
-
workingMemory: new Map(),
|
|
494
|
-
longTermReferences: []
|
|
495
|
-
},
|
|
496
|
-
settings: {
|
|
497
|
-
maxBranches: 5,
|
|
498
|
-
maxDepth: 20,
|
|
499
|
-
confidenceThreshold: 0.6,
|
|
500
|
-
enableSelfCorrection: true,
|
|
501
|
-
enableMetaReasoning: true,
|
|
502
|
-
enableParallelHypotheses: true,
|
|
503
|
-
adaptiveGranularity: true,
|
|
504
|
-
granularitySettings: {
|
|
505
|
-
minStepDetail: 0.1,
|
|
506
|
-
maxStepDetail: 1.0,
|
|
507
|
-
complexityThreshold: 0.7
|
|
508
|
-
},
|
|
509
|
-
...options
|
|
510
|
-
},
|
|
511
|
-
metadata: {
|
|
512
|
-
createdAt: now,
|
|
513
|
-
lastActivityAt: now,
|
|
514
|
-
totalThoughts: 0,
|
|
515
|
-
totalBranches: 1
|
|
516
|
-
}
|
|
517
|
-
};
|
|
518
|
-
const mainBranch: ThoughtBranch = {
|
|
519
|
-
id: 'main',
|
|
520
|
-
sessionId: id,
|
|
521
|
-
name: 'Main',
|
|
522
|
-
description: 'Primary reasoning path',
|
|
523
|
-
rootThoughtId: '',
|
|
524
|
-
thoughtIds: [],
|
|
525
|
-
parentBranchId: null,
|
|
526
|
-
childBranchIds: [],
|
|
527
|
-
status: BranchStatus.ACTIVE,
|
|
528
|
-
confidence: 0.5,
|
|
529
|
-
metadata: { createdAt: now }
|
|
530
|
-
};
|
|
531
|
-
session.branches.set('main', mainBranch);
|
|
532
|
-
this.sessions.set(id, session);
|
|
533
|
-
|
|
534
|
-
if (this.persistence) {
|
|
535
|
-
await this.persistence.save('sessions', id, session);
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
return session;
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
async addThought(sessionId: string, content: string, options: any = {}) {
|
|
542
|
-
const session = this.sessions.get(sessionId);
|
|
543
|
-
if (!session) {
|
|
544
|
-
throw new Error(`Session not found: ${sessionId}`);
|
|
545
|
-
}
|
|
546
|
-
const thought = this.graph.createThought(sessionId, content, options);
|
|
547
|
-
session.thoughts.set(thought.id, thought);
|
|
548
|
-
session.metadata.totalThoughts++;
|
|
549
|
-
session.metadata.lastActivityAt = new Date();
|
|
550
|
-
let metaNote = undefined;
|
|
551
|
-
let issues = undefined;
|
|
552
|
-
if (session.settings.enableMetaReasoning) {
|
|
553
|
-
const generatedMetaNote = this.metaEngine.generateMetaObservation(thought.id, this.graph);
|
|
554
|
-
if (generatedMetaNote) {
|
|
555
|
-
metaNote = generatedMetaNote;
|
|
556
|
-
session.metaNotes.set(metaNote.id, metaNote);
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
if (session.settings.enableSelfCorrection) {
|
|
560
|
-
issues = await this.correctionEngine.detectIssues(thought, this.graph);
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
if (this.persistence) {
|
|
564
|
-
await this.persistence.save('sessions', sessionId, session);
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
return { thought, metaNote, issues };
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
getSession(sessionId: string) {
|
|
571
|
-
return this.sessions.get(sessionId);
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
getThoughtGraph() {
|
|
575
|
-
return this.graph;
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
getMetaEngine() {
|
|
579
|
-
return this.metaEngine;
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
async completeSession(sessionId: string) {
|
|
583
|
-
const session = this.sessions.get(sessionId);
|
|
584
|
-
if (!session) {
|
|
585
|
-
throw new Error(`Session not found: ${sessionId}`);
|
|
586
|
-
}
|
|
587
|
-
(session.status as any) = SessionStatus.COMPLETED;
|
|
588
|
-
session.metadata.completedAt = new Date();
|
|
589
|
-
|
|
590
|
-
if (this.persistence) {
|
|
591
|
-
await this.persistence.save('sessions', sessionId, session);
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
getSessionStatus(sessionId: string) {
|
|
595
|
-
const session = this.sessions.get(sessionId);
|
|
596
|
-
if (!session) {
|
|
597
|
-
throw new Error(`Session not found: ${sessionId}`);
|
|
598
|
-
}
|
|
599
|
-
const thoughts = Array.from(session.thoughts.values());
|
|
600
|
-
const avgConfidence = thoughts.length > 0
|
|
601
|
-
? thoughts.reduce((sum, t) => sum + (t as any).confidence.overall, 0) / thoughts.length
|
|
602
|
-
: 0;
|
|
603
|
-
return {
|
|
604
|
-
id: session.id,
|
|
605
|
-
status: session.status,
|
|
606
|
-
totalThoughts: session.metadata.totalThoughts,
|
|
607
|
-
branches: Array.from(session.branches.keys()),
|
|
608
|
-
averageConfidence: avgConfidence,
|
|
609
|
-
lastActivity: session.metadata.lastActivityAt
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
//# sourceMappingURL=sequential-thinking.js.map
|