mark-improving-agent 2.2.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.
Files changed (79) hide show
  1. package/README.md +335 -0
  2. package/VERSION +1 -0
  3. package/bin/cli.js +12 -0
  4. package/dist/agent/context.js +78 -0
  5. package/dist/agent/index.js +6 -0
  6. package/dist/agent/runtime.js +195 -0
  7. package/dist/agent/task-graph.js +209 -0
  8. package/dist/agent/types.js +1 -0
  9. package/dist/cli/index.js +206 -0
  10. package/dist/core/cognition/active-inference.js +296 -0
  11. package/dist/core/cognition/cognitive-architecture.js +263 -0
  12. package/dist/core/cognition/dual-process.js +102 -0
  13. package/dist/core/cognition/index.js +13 -0
  14. package/dist/core/cognition/learning-from-failure.js +184 -0
  15. package/dist/core/cognition/meta-agent.js +407 -0
  16. package/dist/core/cognition/metacognition.js +322 -0
  17. package/dist/core/cognition/react.js +177 -0
  18. package/dist/core/cognition/retrieval-anchor.js +99 -0
  19. package/dist/core/cognition/self-evolution.js +294 -0
  20. package/dist/core/cognition/self-verification.js +190 -0
  21. package/dist/core/cognition/thought-graph.js +495 -0
  22. package/dist/core/cognition/tool-augmented-llm.js +188 -0
  23. package/dist/core/cognition/tool-execution-verifier.js +204 -0
  24. package/dist/core/collaboration/agentic-loop.js +165 -0
  25. package/dist/core/collaboration/index.js +3 -0
  26. package/dist/core/collaboration/multi-agent-system.js +186 -0
  27. package/dist/core/collaboration/multi-agent.js +110 -0
  28. package/dist/core/consciousness/emotion-engine.js +101 -0
  29. package/dist/core/consciousness/flow-machine.js +121 -0
  30. package/dist/core/consciousness/index.js +4 -0
  31. package/dist/core/consciousness/personality.js +103 -0
  32. package/dist/core/consciousness/types.js +1 -0
  33. package/dist/core/emotional-protocol.js +54 -0
  34. package/dist/core/evolution/engine.js +194 -0
  35. package/dist/core/evolution/goal-engine.js +153 -0
  36. package/dist/core/evolution/index.js +6 -0
  37. package/dist/core/evolution/meta-learning.js +172 -0
  38. package/dist/core/evolution/reflection.js +158 -0
  39. package/dist/core/evolution/self-healer.js +139 -0
  40. package/dist/core/evolution/types.js +1 -0
  41. package/dist/core/healing-rl.js +266 -0
  42. package/dist/core/heartbeat.js +408 -0
  43. package/dist/core/identity/index.js +3 -0
  44. package/dist/core/identity/reflexion.js +165 -0
  45. package/dist/core/identity/self-model.js +274 -0
  46. package/dist/core/identity/self-verifier.js +158 -0
  47. package/dist/core/identity/types.js +12 -0
  48. package/dist/core/lesson-bank.js +301 -0
  49. package/dist/core/memory/adaptive-rag.js +440 -0
  50. package/dist/core/memory/archive-store.js +187 -0
  51. package/dist/core/memory/dream-consolidation.js +366 -0
  52. package/dist/core/memory/embedder.js +130 -0
  53. package/dist/core/memory/hopfield-network.js +128 -0
  54. package/dist/core/memory/index.js +9 -0
  55. package/dist/core/memory/knowledge-graph.js +151 -0
  56. package/dist/core/memory/spaced-repetition.js +113 -0
  57. package/dist/core/memory/store.js +404 -0
  58. package/dist/core/memory/types.js +1 -0
  59. package/dist/core/psychology/analysis.js +456 -0
  60. package/dist/core/psychology/index.js +1 -0
  61. package/dist/core/rollback-manager.js +191 -0
  62. package/dist/core/security/index.js +1 -0
  63. package/dist/core/security/privacy.js +132 -0
  64. package/dist/core/truth-teller.js +253 -0
  65. package/dist/core/truthfulness.js +99 -0
  66. package/dist/core/types.js +2 -0
  67. package/dist/event/bus.js +47 -0
  68. package/dist/index.js +8 -0
  69. package/dist/skills/dag.js +181 -0
  70. package/dist/skills/index.js +5 -0
  71. package/dist/skills/registry.js +40 -0
  72. package/dist/skills/types.js +1 -0
  73. package/dist/storage/archive.js +77 -0
  74. package/dist/storage/checkpoint.js +119 -0
  75. package/dist/storage/types.js +1 -0
  76. package/dist/utils/config.js +81 -0
  77. package/dist/utils/logger.js +49 -0
  78. package/dist/version.js +1 -0
  79. package/package.json +37 -0
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Active Inference Engine
3
+ *
4
+ * Paper: "Active Inference in Multi-LLM Communication" (2024)
5
+ *
6
+ * Based on free energy principle:
7
+ * - Agents minimize free energy (surprise + complexity)
8
+ * - Active inference: choose actions that minimize expected surprise
9
+ * - Generative models: predict observations before they happen
10
+ * - Precision weighting: attention to salient information
11
+ *
12
+ * Key concepts:
13
+ * - Preference precision: How much an agent trusts its preferences
14
+ * - Policy selection: Choose actions that minimize expected free energy
15
+ * - Active inference loop: Infer → Act → Observe → Infer
16
+ */
17
+ import { randomUUID } from 'crypto';
18
+ const DEFAULT_CONFIG = {
19
+ explorationRate: 0.3,
20
+ precisionThreshold: 0.5,
21
+ surpriseThreshold: 2.0,
22
+ planningDepth: 3,
23
+ learningRate: 0.1,
24
+ };
25
+ const DEFAULT_PRIOR = {
26
+ active: 0.5,
27
+ expected: 0.5,
28
+ precision: 0.5,
29
+ entropy: 0.693, // ln(2)
30
+ };
31
+ export function createActiveInferenceEngine(config) {
32
+ const cfg = { ...DEFAULT_CONFIG, ...config };
33
+ let stats = {
34
+ totalInferences: 0,
35
+ successfulActions: 0,
36
+ failedActions: 0,
37
+ avgSurprise: 0,
38
+ avgComplexity: 0,
39
+ policiesGenerated: 0,
40
+ beliefsUpdated: 0,
41
+ };
42
+ // Policy history for learning
43
+ const policyHistory = [];
44
+ // Belief history
45
+ const beliefHistory = [];
46
+ function calculateSurprise(probability) {
47
+ if (probability <= 0)
48
+ return 100;
49
+ return -Math.log2(probability);
50
+ }
51
+ function calculateComplexity(prior, posterior) {
52
+ if (prior <= 0 || posterior <= 0)
53
+ return 0;
54
+ // KL divergence from prior to posterior
55
+ if (prior === 0 || posterior === 0)
56
+ return 0;
57
+ return posterior * Math.log2(posterior / prior);
58
+ }
59
+ function calculateAccuracy(observation, expectation) {
60
+ return 1 - Math.abs(observation - expectation);
61
+ }
62
+ function calculateFreeEnergy(observation, expectation, precision) {
63
+ // Convert observation to numeric value (simplified)
64
+ const obsValue = observation.length > 0 ? (observation.charCodeAt(0) % 100) / 100 : 0.5;
65
+ const probability = Math.max(0.01, Math.min(0.99, obsValue));
66
+ const surprise = calculateSurprise(probability);
67
+ const complexity = calculateComplexity(expectation, obsValue);
68
+ const accuracy = calculateAccuracy(obsValue, expectation);
69
+ const total = surprise + complexity * precision;
70
+ // Update running stats
71
+ stats.avgSurprise = (stats.avgSurprise * stats.totalInferences + surprise) / (stats.totalInferences + 1);
72
+ stats.avgComplexity = (stats.avgComplexity * stats.totalInferences + complexity) / (stats.totalInferences + 1);
73
+ return { surprise, complexity, accuracy, total };
74
+ }
75
+ function infer(observation, prior) {
76
+ stats.totalInferences++;
77
+ const belief = prior || { ...DEFAULT_PRIOR };
78
+ // Update belief based on observation
79
+ const obsValue = observation.length > 0 ? (observation.charCodeAt(0) % 100) / 100 : 0.5;
80
+ // Bayesian update: blend prior with observation
81
+ const newActive = belief.active * (1 - cfg.learningRate) + obsValue * cfg.learningRate;
82
+ const newPrecision = belief.precision * 0.95 + (1 - Math.abs(newActive - obsValue)) * 0.05;
83
+ const newBelief = {
84
+ active: newActive,
85
+ expected: belief.expected,
86
+ precision: Math.max(0.1, Math.min(1, newPrecision)),
87
+ entropy: getBeliefEntropy({ ...belief, active: newActive, precision: newPrecision }),
88
+ };
89
+ beliefHistory.push(newBelief);
90
+ if (beliefHistory.length > 50)
91
+ beliefHistory.shift();
92
+ return newBelief;
93
+ }
94
+ function generatePolicies(context, numPolicies = 5) {
95
+ const policies = [];
96
+ const contextLower = context.toLowerCase();
97
+ // Policy templates
98
+ const policyTemplates = [
99
+ { desc: 'explore', steps: ['search', 'analyze', 'plan'] },
100
+ { desc: 'exploit', steps: ['use_known', 'execute', 'verify'] },
101
+ { desc: 'replan', steps: ['observe', 'rethink', 'execute'] },
102
+ { desc: 'conservative', steps: ['validate', 'slow_execute', 'check'] },
103
+ { desc: 'adaptive', steps: ['observe', 'adapt', 'act'] },
104
+ ];
105
+ for (let i = 0; i < Math.min(numPolicies, policyTemplates.length); i++) {
106
+ const template = policyTemplates[i];
107
+ // Calculate expected free energy based on context
108
+ let expectedFE = 1.0;
109
+ if (contextLower.includes('uncertain') || contextLower.includes('unknown')) {
110
+ expectedFE += 0.5; // Higher FE for uncertain contexts
111
+ }
112
+ if (contextLower.includes('urgent') || contextLower.includes('quick')) {
113
+ expectedFE += 0.3; // Higher FE for urgent contexts
114
+ }
115
+ if (contextLower.includes('safe') || contextLower.includes('secure')) {
116
+ expectedFE -= 0.3; // Lower FE for safe contexts
117
+ }
118
+ // Add some randomness for diversity
119
+ const noise = (Math.random() - 0.5) * 0.4;
120
+ expectedFE = Math.max(0.1, expectedFE + noise);
121
+ // Calculate probability (softmax of negative FE)
122
+ const probability = Math.exp(-expectedFE) / (Math.exp(-0.5) + Math.exp(-expectedFE));
123
+ const policy = {
124
+ id: randomUUID(),
125
+ description: template.desc,
126
+ expectedFreeEnergy: expectedFE,
127
+ probability,
128
+ sequence: template.steps,
129
+ };
130
+ policies.push(policy);
131
+ }
132
+ // Normalize probabilities
133
+ const totalProb = policies.reduce((sum, p) => sum + p.probability, 0);
134
+ for (const policy of policies) {
135
+ policy.probability /= totalProb;
136
+ }
137
+ stats.policiesGenerated += policies.length;
138
+ return policies;
139
+ }
140
+ function selectPolicy(policies) {
141
+ if (policies.length === 0) {
142
+ return {
143
+ id: 'default',
144
+ description: 'default',
145
+ expectedFreeEnergy: 1.0,
146
+ probability: 1.0,
147
+ sequence: ['observe', 'act'],
148
+ };
149
+ }
150
+ // Exploration vs exploitation
151
+ const random = Math.random();
152
+ if (random < cfg.explorationRate) {
153
+ // Explore: select random policy with probability weighting
154
+ const cumsum = [];
155
+ let sum = 0;
156
+ for (const p of policies) {
157
+ sum += p.probability;
158
+ cumsum.push(sum);
159
+ }
160
+ const r = Math.random() * sum;
161
+ for (let i = 0; i < policies.length; i++) {
162
+ if (r <= cumsum[i]) {
163
+ return policies[i];
164
+ }
165
+ }
166
+ }
167
+ // Exploit: select best policy
168
+ return policies.reduce((best, p) => p.expectedFreeEnergy < best.expectedFreeEnergy ? p : best);
169
+ }
170
+ function updateBelief(current, observation, action) {
171
+ const obsValue = observation.length > 0 ? (observation.charCodeAt(0) % 100) / 100 : 0.5;
172
+ // Action effect on belief
173
+ let actionEffect = 0;
174
+ if (action.includes('explore'))
175
+ actionEffect = 0.1;
176
+ else if (action.includes('exploit'))
177
+ actionEffect = -0.05;
178
+ else if (action.includes('replan'))
179
+ actionEffect = 0.15;
180
+ const newActive = current.active + actionEffect * cfg.learningRate;
181
+ const newPrecision = updatePrecision(current, Math.abs(obsValue - current.active));
182
+ stats.beliefsUpdated++;
183
+ return {
184
+ active: Math.max(0, Math.min(1, newActive)),
185
+ expected: current.expected,
186
+ precision: Math.max(0.1, Math.min(1, newPrecision)),
187
+ entropy: getBeliefEntropy(current),
188
+ };
189
+ }
190
+ function updatePrecision(belief, surprise) {
191
+ // Precision increases when surprise is low, decreases when high
192
+ const targetPrecision = belief.precision - surprise * 0.1;
193
+ return Math.max(0.1, Math.min(1, targetPrecision));
194
+ }
195
+ function act(belief, context = '') {
196
+ const policies = generatePolicies(context);
197
+ const selectedPolicy = selectPolicy(policies);
198
+ // Get action from policy sequence
199
+ const action = selectedPolicy.sequence[0];
200
+ // Simulate observation
201
+ const newObservations = [`observed_${action}`, `context_${context.slice(0, 20)}`];
202
+ // Calculate free energy
203
+ const fe = calculateFreeEnergy(newObservations[0], belief.expected, belief.precision);
204
+ // Check if surprise exceeds threshold
205
+ if (fe.surprise > cfg.surpriseThreshold) {
206
+ // Replan needed - generate new policies
207
+ const replanPolicies = generatePolicies(context + '_replan', 3);
208
+ const replanPolicy = selectPolicy(replanPolicies);
209
+ return {
210
+ selectedPolicy: replanPolicy,
211
+ beliefState: belief,
212
+ freeEnergy: fe,
213
+ action: replanPolicy.sequence[0],
214
+ newObservations,
215
+ timestamp: Date.now(),
216
+ };
217
+ }
218
+ return {
219
+ selectedPolicy,
220
+ beliefState: belief,
221
+ freeEnergy: fe,
222
+ action,
223
+ newObservations,
224
+ timestamp: Date.now(),
225
+ };
226
+ }
227
+ function learnFromOutcome(policy, success) {
228
+ policyHistory.push({ policy, success, timestamp: Date.now() });
229
+ if (policyHistory.length > 100)
230
+ policyHistory.shift();
231
+ if (success) {
232
+ stats.successfulActions++;
233
+ // Increase probability of similar policies
234
+ cfg.explorationRate = Math.max(0.1, cfg.explorationRate - 0.02);
235
+ }
236
+ else {
237
+ stats.failedActions++;
238
+ // Decrease exploration rate when failing
239
+ cfg.explorationRate = Math.min(0.9, cfg.explorationRate + 0.05);
240
+ }
241
+ }
242
+ function getBeliefEntropy(belief) {
243
+ if (belief.precision <= 0)
244
+ return 1;
245
+ // Entropy decreases with higher precision
246
+ return Math.log2(1 / belief.precision) * 0.5;
247
+ }
248
+ function calculatePrecisionWeighting(surprise) {
249
+ // Precision weighting is inverse of surprise
250
+ return Math.exp(-surprise);
251
+ }
252
+ function getConfig() {
253
+ return { ...cfg };
254
+ }
255
+ function updateConfig(newConfig) {
256
+ Object.assign(cfg, newConfig);
257
+ }
258
+ function getStats() {
259
+ return { ...stats };
260
+ }
261
+ return {
262
+ infer,
263
+ act,
264
+ calculateFreeEnergy,
265
+ generatePolicies,
266
+ selectPolicy,
267
+ updateBelief,
268
+ updatePrecision,
269
+ learnFromOutcome,
270
+ getConfig,
271
+ updateConfig,
272
+ getStats,
273
+ getBeliefEntropy,
274
+ calculatePrecisionWeighting,
275
+ };
276
+ }
277
+ // Helper to format free energy metrics
278
+ export function formatFreeEnergyMetrics(fe) {
279
+ return `
280
+ Free Energy Analysis:
281
+ Surprise: ${fe.surprise.toFixed(3)}
282
+ Complexity: ${fe.complexity.toFixed(3)}
283
+ Accuracy: ${fe.accuracy.toFixed(3)}
284
+ Total: ${fe.total.toFixed(3)}
285
+ `.trim();
286
+ }
287
+ // Helper to format belief state
288
+ export function formatBeliefState(belief) {
289
+ return `
290
+ Belief State:
291
+ Active: ${(belief.active * 100).toFixed(1)}%
292
+ Expected: ${(belief.expected * 100).toFixed(1)}%
293
+ Precision: ${(belief.precision * 100).toFixed(1)}%
294
+ Entropy: ${belief.entropy.toFixed(3)}
295
+ `.trim();
296
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Cognitive Architecture for Language Agents (CoALA)
3
+ *
4
+ * Paper: "Cognitive Architectures for Language Agents" (Steeven
5
+ *
6
+ * Key components:
7
+ * - Memory (M): External storage + Working memory
8
+ * - Reasoning (R): In-Context learning, Plan execution, Chain-of-Thought
9
+ * - Action (A): Tool use, Generation
10
+ * - Perception (P): Input processing, Attention
11
+ *
12
+ * Plus:
13
+ * - Episodic Memory: Experience storage
14
+ * - Procedural Memory: Skills and policies
15
+ * - Long-term Memory: World knowledge
16
+ * - Metacognitive Monitoring: Self-awareness
17
+ */
18
+ import { randomUUID } from 'crypto';
19
+ // Re-export all cognitive components
20
+ export * from './index.js';
21
+ /**
22
+ * Create the full cognitive architecture based on CoALA
23
+ */
24
+ export function createCognitiveArchitecture(name = 'HeartFlow-CoALA') {
25
+ const architecture = {
26
+ id: randomUUID(),
27
+ name,
28
+ memory: new Map(),
29
+ reasoning: new Map(),
30
+ action: new Map(),
31
+ perception: {
32
+ type: 'perception',
33
+ description: 'Input processing and attention mechanism',
34
+ enabled: true,
35
+ stats: { inputsProcessed: 0, attentionShifts: 0 },
36
+ },
37
+ metacognitive: {
38
+ type: 'metacognitive',
39
+ description: 'Self-awareness and monitoring',
40
+ enabled: true,
41
+ stats: { reflections: 0, corrections: 0 },
42
+ },
43
+ };
44
+ // Initialize memory components
45
+ const memoryComponents = [
46
+ 'perception', 'working_memory', 'episodic', 'semantic', 'procedural'
47
+ ];
48
+ for (const comp of memoryComponents) {
49
+ architecture.memory.set(comp, {
50
+ type: comp,
51
+ description: `Memory component: ${comp}`,
52
+ enabled: true,
53
+ stats: { reads: 0, writes: 0 },
54
+ });
55
+ }
56
+ // Initialize reasoning components
57
+ const reasoningComponents = [
58
+ 'llm', 'cot', 'plan_execution', 'in_context'
59
+ ];
60
+ for (const comp of reasoningComponents) {
61
+ architecture.reasoning.set(comp, {
62
+ type: comp,
63
+ description: `Reasoning component: ${comp}`,
64
+ enabled: true,
65
+ stats: { invocations: 0, successes: 0 },
66
+ });
67
+ }
68
+ // Initialize action components
69
+ const actionComponents = ['tool_use', 'generation', 'world_interaction'];
70
+ for (const comp of actionComponents) {
71
+ architecture.action.set(comp, {
72
+ type: comp,
73
+ description: `Action component: ${comp}`,
74
+ enabled: true,
75
+ stats: { invocations: 0, successes: 0 },
76
+ });
77
+ }
78
+ // Working memory (simulated)
79
+ let workingMemory = [];
80
+ // Stats
81
+ let stats = {
82
+ totalCycles: 0,
83
+ memoryAccesses: 0,
84
+ reasoningSteps: 0,
85
+ actionsTaken: 0,
86
+ metacognitiveFlags: 0,
87
+ };
88
+ function perceive(input) {
89
+ stats.totalCycles++;
90
+ architecture.perception.stats.inputsProcessed++;
91
+ // Simple attention mechanism - focus on key terms
92
+ const attention = new Map();
93
+ const words = input.split(/\s+/);
94
+ for (const word of words) {
95
+ if (word.length > 4) {
96
+ attention.set(word, Math.random() * 0.5 + 0.5);
97
+ }
98
+ }
99
+ return {
100
+ processed: input.toLowerCase().trim(),
101
+ attention,
102
+ };
103
+ }
104
+ function readMemory(query) {
105
+ stats.memoryAccesses++;
106
+ architecture.memory.get('working_memory').stats.reads++;
107
+ // Search in working memory
108
+ const results = workingMemory.filter(item => item.toLowerCase().includes(query.toLowerCase()));
109
+ return results;
110
+ }
111
+ function writeMemory(content, type) {
112
+ stats.memoryAccesses++;
113
+ const component = architecture.memory.get(type);
114
+ if (component) {
115
+ component.stats.writes++;
116
+ }
117
+ if (type === 'working_memory') {
118
+ workingMemory.push(content);
119
+ if (workingMemory.length > 100) {
120
+ workingMemory = workingMemory.slice(-100);
121
+ }
122
+ }
123
+ }
124
+ function updateWorkingMemory(items) {
125
+ workingMemory = items.slice(-100);
126
+ architecture.memory.get('working_memory').stats.writes++;
127
+ }
128
+ function reason(input, mode) {
129
+ stats.reasoningSteps++;
130
+ const component = architecture.reasoning.get(mode);
131
+ if (component) {
132
+ component.stats.invocations++;
133
+ }
134
+ let result = '';
135
+ let confidence = 0.7;
136
+ switch (mode) {
137
+ case 'llm':
138
+ result = `LLM reasoning on: ${input.slice(0, 50)}...`;
139
+ confidence = 0.8;
140
+ break;
141
+ case 'cot':
142
+ result = `Chain-of-thought: ${input.split('.').slice(0, 3).join('. ')}...`;
143
+ confidence = 0.75;
144
+ break;
145
+ case 'plan_execution':
146
+ result = `Executing plan: ${input.slice(0, 30)}...`;
147
+ confidence = 0.7;
148
+ break;
149
+ case 'in_context':
150
+ result = `In-context: ${input.slice(0, 30)}...`;
151
+ confidence = 0.65;
152
+ break;
153
+ }
154
+ if (component) {
155
+ component.stats.successes++;
156
+ }
157
+ return { result, confidence };
158
+ }
159
+ function act(action, tools) {
160
+ stats.actionsTaken++;
161
+ const component = architecture.action.get('tool_use');
162
+ if (component) {
163
+ component.stats.invocations++;
164
+ }
165
+ let success = true;
166
+ let result = '';
167
+ if (tools && tools.length > 0) {
168
+ result = `Used tools [${tools.join(', ')}] for: ${action.slice(0, 30)}...`;
169
+ }
170
+ else {
171
+ result = `Action: ${action.slice(0, 30)}...`;
172
+ }
173
+ if (component) {
174
+ component.stats.successes++;
175
+ }
176
+ return { result, success };
177
+ }
178
+ function monitor() {
179
+ const alerts = [];
180
+ if (stats.totalCycles > 100 && stats.memoryAccesses / stats.totalCycles < 0.1) {
181
+ alerts.push('Low memory access rate relative to cycles');
182
+ }
183
+ if (stats.reasoningSteps > 50 && stats.reasoningSteps / stats.totalCycles > 0.5) {
184
+ alerts.push('High reasoning overhead');
185
+ }
186
+ return { metrics: { ...stats }, alerts };
187
+ }
188
+ function reflect() {
189
+ architecture.metacognitive.stats.reflections++;
190
+ stats.metacognitiveFlags++;
191
+ const insights = [];
192
+ const improvements = [];
193
+ // Analyze usage patterns
194
+ const memStats = Array.from(architecture.memory.values()).map(v => v.stats);
195
+ const totalMemAccess = memStats.reduce((sum, s) => sum + s.reads + s.writes, 0);
196
+ if (totalMemAccess > 10) {
197
+ insights.push(`Memory accessed ${totalMemAccess} times`);
198
+ }
199
+ const reasoningStats = Array.from(architecture.reasoning.values()).map(v => v.stats);
200
+ const totalReasoning = reasoningStats.reduce((sum, s) => sum + s.invocations, 0);
201
+ if (totalReasoning > 10) {
202
+ insights.push(`Reasoning invoked ${totalReasoning} times`);
203
+ }
204
+ // Generate improvements
205
+ if (totalMemAccess < stats.totalCycles * 0.1) {
206
+ improvements.push('Increase memory usage - consider storing intermediate results');
207
+ }
208
+ if (stats.metacognitiveFlags > 5) {
209
+ improvements.push('High metacognitive overhead - consider streamlining monitoring');
210
+ }
211
+ return { insights, improvements };
212
+ }
213
+ function getArchitecture() {
214
+ return architecture;
215
+ }
216
+ function getStats() {
217
+ return { ...stats };
218
+ }
219
+ function getComponent(type) {
220
+ if (architecture.perception.type === type)
221
+ return architecture.perception;
222
+ if (architecture.metacognitive.type === type)
223
+ return architecture.metacognitive;
224
+ for (const comp of architecture.memory.values()) {
225
+ if (comp.type === type)
226
+ return comp;
227
+ }
228
+ for (const comp of architecture.reasoning.values()) {
229
+ if (comp.type === type)
230
+ return comp;
231
+ }
232
+ for (const comp of architecture.action.values()) {
233
+ if (comp.type === type)
234
+ return comp;
235
+ }
236
+ return undefined;
237
+ }
238
+ function enableComponent(type) {
239
+ const comp = getComponent(type);
240
+ if (comp)
241
+ comp.enabled = true;
242
+ }
243
+ function disableComponent(type) {
244
+ const comp = getComponent(type);
245
+ if (comp)
246
+ comp.enabled = false;
247
+ }
248
+ return {
249
+ getArchitecture,
250
+ getStats,
251
+ getComponent,
252
+ enableComponent,
253
+ disableComponent,
254
+ perceive,
255
+ readMemory,
256
+ writeMemory,
257
+ updateWorkingMemory,
258
+ reason,
259
+ act,
260
+ monitor,
261
+ reflect,
262
+ };
263
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Dual Process Cognition - System 1 & System 2
3
+ *
4
+ * Based on paper: LLM Cognitive Architecture (2025)
5
+ * - System 1: Fast, intuitive, automatic thinking
6
+ * - System 2: Slow, deliberate, analytical reasoning
7
+ */
8
+ export function createDualProcessCognition() {
9
+ let currentMode = 'system1';
10
+ let system1Count = 0;
11
+ let system2Count = 0;
12
+ let switches = 0;
13
+ const startTime = Date.now();
14
+ /**
15
+ * Decide whether to use System 1 or System 2 based on context
16
+ */
17
+ function shouldUseSystem2(ctx) {
18
+ // High complexity favors System 2
19
+ if (ctx.complexity > 0.7)
20
+ return true;
21
+ // High stakes (important decisions) favor System 2
22
+ if (ctx.stakes > 0.8)
23
+ return true;
24
+ // Low urgency with high complexity favors System 2
25
+ if (ctx.complexity > 0.4 && ctx.urgency < 0.5)
26
+ return true;
27
+ // Default to System 1 for routine decisions
28
+ return false;
29
+ }
30
+ /**
31
+ * System 1: Fast, intuitive thinking
32
+ */
33
+ function system1Think(context) {
34
+ const start = Date.now();
35
+ system1Count++;
36
+ return {
37
+ mode: 'system1',
38
+ reasoning: '[System 1] Quick intuition-based response. Pattern matching activated.',
39
+ confidence: 0.7,
40
+ timeSpent: Date.now() - start,
41
+ reflectionCount: 0,
42
+ };
43
+ }
44
+ /**
45
+ * System 2: Slow, deliberate reasoning
46
+ */
47
+ function system2Think(context) {
48
+ const start = Date.now();
49
+ system2Count++;
50
+ let reflectionCount = 0;
51
+ // Simulate multi-step reflection
52
+ const reasoning = `[System 2] Deliberate analysis initiated.
53
+ Step 1: Decomposing problem into components
54
+ Step 2: Evaluating constraints and context
55
+ Step 3: Considering alternatives (${3 + Math.floor(Math.random() * 3)} options)
56
+ Step 4: Risk assessment
57
+ Step 5: Synthesis and conclusion`;
58
+ reflectionCount = 5;
59
+ return {
60
+ mode: 'system2',
61
+ reasoning,
62
+ confidence: 0.9,
63
+ timeSpent: Date.now() - start,
64
+ reflectionCount,
65
+ };
66
+ }
67
+ function analyze(context) {
68
+ const useSystem2 = shouldUseSystem2(context);
69
+ if (useSystem2 && currentMode === 'system1') {
70
+ switchMode('system1', 'system2');
71
+ }
72
+ else if (!useSystem2 && currentMode === 'system2') {
73
+ switchMode('system2', 'system1');
74
+ }
75
+ return useSystem2 ? system2Think(context) : system1Think(context);
76
+ }
77
+ function switchMode(from, to) {
78
+ if (from !== to) {
79
+ switches++;
80
+ currentMode = to;
81
+ }
82
+ }
83
+ function getCurrentMode() {
84
+ return currentMode;
85
+ }
86
+ function getStats() {
87
+ const total = system1Count + system2Count;
88
+ return {
89
+ system1Count,
90
+ system2Count,
91
+ switches,
92
+ system1Ratio: total > 0 ? system1Count / total : 0,
93
+ system2Ratio: total > 0 ? system2Count / total : 0,
94
+ };
95
+ }
96
+ return {
97
+ analyze,
98
+ switchMode,
99
+ getCurrentMode,
100
+ getStats,
101
+ };
102
+ }
@@ -0,0 +1,13 @@
1
+ export * from './dual-process.js';
2
+ export * from './retrieval-anchor.js';
3
+ export * from './react.js';
4
+ export * from './self-verification.js';
5
+ export * from './tool-augmented-llm.js';
6
+ export * from './tool-execution-verifier.js';
7
+ export * from './learning-from-failure.js';
8
+ export * from './metacognition.js';
9
+ export * from './thought-graph.js';
10
+ export * from './self-evolution.js';
11
+ export * from './cognitive-architecture.js';
12
+ export * from './meta-agent.js';
13
+ export * from './active-inference.js';