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