@kernel.chat/kbot 2.21.0 → 2.22.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/dist/autopoiesis.d.ts +93 -0
- package/dist/autopoiesis.d.ts.map +1 -0
- package/dist/autopoiesis.js +222 -0
- package/dist/autopoiesis.js.map +1 -0
- package/dist/free-energy.d.ts +95 -0
- package/dist/free-energy.d.ts.map +1 -0
- package/dist/free-energy.js +180 -0
- package/dist/free-energy.js.map +1 -0
- package/dist/integrated-information.d.ts +56 -0
- package/dist/integrated-information.d.ts.map +1 -0
- package/dist/integrated-information.js +165 -0
- package/dist/integrated-information.js.map +1 -0
- package/dist/predictive-processing.d.ts +79 -0
- package/dist/predictive-processing.d.ts.map +1 -0
- package/dist/predictive-processing.js +250 -0
- package/dist/predictive-processing.js.map +1 -0
- package/dist/strange-loops.d.ts +89 -0
- package/dist/strange-loops.d.ts.map +1 -0
- package/dist/strange-loops.js +199 -0
- package/dist/strange-loops.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export interface SystemComponent {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
type: 'provider' | 'tool' | 'memory' | 'model' | 'connection';
|
|
5
|
+
status: 'healthy' | 'degraded' | 'failed' | 'unknown';
|
|
6
|
+
lastChecked: number;
|
|
7
|
+
failureCount: number;
|
|
8
|
+
/** How critical is this component? 0-1 */
|
|
9
|
+
criticality: number;
|
|
10
|
+
/** Can the system compensate if this fails? */
|
|
11
|
+
compensable: boolean;
|
|
12
|
+
/** What compensates for this component */
|
|
13
|
+
fallback?: string;
|
|
14
|
+
}
|
|
15
|
+
export interface HealthReport {
|
|
16
|
+
/** Overall system viability (0-1) */
|
|
17
|
+
viability: number;
|
|
18
|
+
/** Components by status */
|
|
19
|
+
healthy: string[];
|
|
20
|
+
degraded: string[];
|
|
21
|
+
failed: string[];
|
|
22
|
+
/** Self-healing actions taken */
|
|
23
|
+
healingActions: string[];
|
|
24
|
+
/** Is the system in a viable state? */
|
|
25
|
+
isViable: boolean;
|
|
26
|
+
/** Boundary integrity: are internal/external correctly distinguished? */
|
|
27
|
+
boundaryIntact: boolean;
|
|
28
|
+
}
|
|
29
|
+
export interface AdaptiveResponse {
|
|
30
|
+
/** Action taken to maintain viability */
|
|
31
|
+
action: string;
|
|
32
|
+
/** Component affected */
|
|
33
|
+
component: string;
|
|
34
|
+
/** Was the action successful? */
|
|
35
|
+
success: boolean;
|
|
36
|
+
/** New state after action */
|
|
37
|
+
newStatus: SystemComponent['status'];
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Autopoietic System — self-maintaining operational integrity.
|
|
41
|
+
*
|
|
42
|
+
* The system continuously:
|
|
43
|
+
* 1. Monitors its own components (providers, tools, memory, models)
|
|
44
|
+
* 2. Detects degradation before failure
|
|
45
|
+
* 3. Self-heals by activating fallbacks
|
|
46
|
+
* 4. Maintains its operational boundary
|
|
47
|
+
*
|
|
48
|
+
* If viability drops below threshold, it signals for external help
|
|
49
|
+
* rather than continuing in a degraded state.
|
|
50
|
+
*/
|
|
51
|
+
export declare class AutopoieticSystem {
|
|
52
|
+
private components;
|
|
53
|
+
private healingLog;
|
|
54
|
+
private readonly viabilityThreshold;
|
|
55
|
+
constructor();
|
|
56
|
+
/** Register the core components that constitute kbot */
|
|
57
|
+
private initializeComponents;
|
|
58
|
+
/**
|
|
59
|
+
* Report a component's health status.
|
|
60
|
+
* Called by the agent loop after each operation.
|
|
61
|
+
*/
|
|
62
|
+
reportHealth(componentId: string, healthy: boolean): void;
|
|
63
|
+
/**
|
|
64
|
+
* Attempt self-healing for a degraded or failed component.
|
|
65
|
+
* Returns the adaptive response taken.
|
|
66
|
+
*/
|
|
67
|
+
selfHeal(componentId: string): AdaptiveResponse | null;
|
|
68
|
+
/**
|
|
69
|
+
* Compute overall system viability.
|
|
70
|
+
* Weighted average of component health, weighted by criticality.
|
|
71
|
+
*/
|
|
72
|
+
computeViability(): number;
|
|
73
|
+
/**
|
|
74
|
+
* Full health check — assess all components, self-heal if needed.
|
|
75
|
+
*/
|
|
76
|
+
healthCheck(): HealthReport;
|
|
77
|
+
/**
|
|
78
|
+
* Should the agent continue operating, or signal for help?
|
|
79
|
+
*/
|
|
80
|
+
shouldContinue(): {
|
|
81
|
+
continue: boolean;
|
|
82
|
+
reason?: string;
|
|
83
|
+
};
|
|
84
|
+
/** Get the healing log */
|
|
85
|
+
getHealingLog(): AdaptiveResponse[];
|
|
86
|
+
/** Get a specific component's status */
|
|
87
|
+
getComponent(id: string): SystemComponent | undefined;
|
|
88
|
+
/** Register a new component (e.g., when an MCP server connects) */
|
|
89
|
+
registerComponent(component: Omit<SystemComponent, 'status' | 'lastChecked' | 'failureCount'>): void;
|
|
90
|
+
/** Reset for new session */
|
|
91
|
+
reset(): void;
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=autopoiesis.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"autopoiesis.d.ts","sourceRoot":"","sources":["../src/autopoiesis.ts"],"names":[],"mappings":"AAiBA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,GAAG,YAAY,CAAA;IAC7D,MAAM,EAAE,SAAS,GAAG,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAA;IACrD,WAAW,EAAE,MAAM,CAAA;IACnB,YAAY,EAAE,MAAM,CAAA;IACpB,0CAA0C;IAC1C,WAAW,EAAE,MAAM,CAAA;IACnB,+CAA+C;IAC/C,WAAW,EAAE,OAAO,CAAA;IACpB,0CAA0C;IAC1C,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,qCAAqC;IACrC,SAAS,EAAE,MAAM,CAAA;IACjB,2BAA2B;IAC3B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AQ,GAAG,aAAa,GAAG,cAAc,CAAC,GAAG,IAAI;IASpG,4BAA4B;IAC5B,KAAK,IAAI,IAAI;CAQd"}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// K:BOT Autopoiesis — Self-Maintaining System
|
|
2
|
+
//
|
|
3
|
+
// Based on Maturana & Varela's Autopoiesis theory (1972):
|
|
4
|
+
// Living systems are "self-making" — they continuously produce and
|
|
5
|
+
// maintain the components that constitute them. An autopoietic system
|
|
6
|
+
// is organizationally closed but structurally coupled to its environment.
|
|
7
|
+
//
|
|
8
|
+
// For kbot: the agent monitors its own health, detects degradation,
|
|
9
|
+
// self-heals broken components, and maintains its operational boundary.
|
|
10
|
+
// kbot doesn't just run — it actively maintains its ability to run.
|
|
11
|
+
//
|
|
12
|
+
// References:
|
|
13
|
+
// - Maturana, H.R. & Varela, F.J. (1980). Autopoiesis and Cognition.
|
|
14
|
+
// - Varela, F.J. (1979). Principles of Biological Autonomy.
|
|
15
|
+
// - Thompson, E. (2007). Mind in Life: Biology, Phenomenology, and the Sciences of Mind.
|
|
16
|
+
// - Di Paolo, E.A. (2005). Autopoiesis, adaptivity, teleology, agency.
|
|
17
|
+
/**
|
|
18
|
+
* Autopoietic System — self-maintaining operational integrity.
|
|
19
|
+
*
|
|
20
|
+
* The system continuously:
|
|
21
|
+
* 1. Monitors its own components (providers, tools, memory, models)
|
|
22
|
+
* 2. Detects degradation before failure
|
|
23
|
+
* 3. Self-heals by activating fallbacks
|
|
24
|
+
* 4. Maintains its operational boundary
|
|
25
|
+
*
|
|
26
|
+
* If viability drops below threshold, it signals for external help
|
|
27
|
+
* rather than continuing in a degraded state.
|
|
28
|
+
*/
|
|
29
|
+
export class AutopoieticSystem {
|
|
30
|
+
components = new Map();
|
|
31
|
+
healingLog = [];
|
|
32
|
+
viabilityThreshold = 0.4;
|
|
33
|
+
constructor() {
|
|
34
|
+
this.initializeComponents();
|
|
35
|
+
}
|
|
36
|
+
/** Register the core components that constitute kbot */
|
|
37
|
+
initializeComponents() {
|
|
38
|
+
const defaults = [
|
|
39
|
+
// Providers
|
|
40
|
+
{ id: 'anthropic', name: 'Anthropic API', type: 'provider', criticality: 0.9, compensable: true, fallback: 'openai' },
|
|
41
|
+
{ id: 'openai', name: 'OpenAI API', type: 'provider', criticality: 0.7, compensable: true, fallback: 'ollama' },
|
|
42
|
+
{ id: 'ollama', name: 'Ollama (local)', type: 'provider', criticality: 0.5, compensable: true, fallback: 'embedded' },
|
|
43
|
+
{ id: 'embedded', name: 'Embedded llama.cpp', type: 'model', criticality: 0.4, compensable: false },
|
|
44
|
+
// Core tools
|
|
45
|
+
{ id: 'filesystem', name: 'File System Access', type: 'tool', criticality: 1.0, compensable: false },
|
|
46
|
+
{ id: 'bash', name: 'Shell Execution', type: 'tool', criticality: 0.9, compensable: false },
|
|
47
|
+
{ id: 'git', name: 'Git Operations', type: 'tool', criticality: 0.7, compensable: false },
|
|
48
|
+
// Memory
|
|
49
|
+
{ id: 'local-memory', name: 'Local Memory (~/.kbot/memory/)', type: 'memory', criticality: 0.6, compensable: true, fallback: 'session-context' },
|
|
50
|
+
{ id: 'session-context', name: 'Session Context', type: 'memory', criticality: 0.8, compensable: false },
|
|
51
|
+
// External connections
|
|
52
|
+
{ id: 'internet', name: 'Internet Connectivity', type: 'connection', criticality: 0.5, compensable: true, fallback: 'ollama' },
|
|
53
|
+
{ id: 'mcp-servers', name: 'MCP Server Connections', type: 'connection', criticality: 0.3, compensable: true },
|
|
54
|
+
];
|
|
55
|
+
for (const d of defaults) {
|
|
56
|
+
this.components.set(d.id, {
|
|
57
|
+
...d,
|
|
58
|
+
status: 'unknown',
|
|
59
|
+
lastChecked: 0,
|
|
60
|
+
failureCount: 0,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Report a component's health status.
|
|
66
|
+
* Called by the agent loop after each operation.
|
|
67
|
+
*/
|
|
68
|
+
reportHealth(componentId, healthy) {
|
|
69
|
+
const comp = this.components.get(componentId);
|
|
70
|
+
if (!comp)
|
|
71
|
+
return;
|
|
72
|
+
comp.lastChecked = Date.now();
|
|
73
|
+
if (healthy) {
|
|
74
|
+
comp.status = 'healthy';
|
|
75
|
+
// Gradually reduce failure count on success
|
|
76
|
+
comp.failureCount = Math.max(0, comp.failureCount - 1);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
comp.failureCount++;
|
|
80
|
+
comp.status = comp.failureCount >= 3 ? 'failed' : 'degraded';
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Attempt self-healing for a degraded or failed component.
|
|
85
|
+
* Returns the adaptive response taken.
|
|
86
|
+
*/
|
|
87
|
+
selfHeal(componentId) {
|
|
88
|
+
const comp = this.components.get(componentId);
|
|
89
|
+
if (!comp || comp.status === 'healthy')
|
|
90
|
+
return null;
|
|
91
|
+
// If compensable, activate fallback
|
|
92
|
+
if (comp.compensable && comp.fallback) {
|
|
93
|
+
const fallback = this.components.get(comp.fallback);
|
|
94
|
+
if (fallback && fallback.status !== 'failed') {
|
|
95
|
+
const response = {
|
|
96
|
+
action: `Activated fallback: ${comp.name} → ${fallback.name}`,
|
|
97
|
+
component: componentId,
|
|
98
|
+
success: true,
|
|
99
|
+
newStatus: 'degraded',
|
|
100
|
+
};
|
|
101
|
+
comp.status = 'degraded';
|
|
102
|
+
this.healingLog.push(response);
|
|
103
|
+
return response;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
// If not compensable, report inability to self-heal
|
|
107
|
+
const response = {
|
|
108
|
+
action: `Cannot self-heal: ${comp.name} has no viable fallback`,
|
|
109
|
+
component: componentId,
|
|
110
|
+
success: false,
|
|
111
|
+
newStatus: comp.status,
|
|
112
|
+
};
|
|
113
|
+
this.healingLog.push(response);
|
|
114
|
+
return response;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Compute overall system viability.
|
|
118
|
+
* Weighted average of component health, weighted by criticality.
|
|
119
|
+
*/
|
|
120
|
+
computeViability() {
|
|
121
|
+
let weightedHealth = 0;
|
|
122
|
+
let totalWeight = 0;
|
|
123
|
+
for (const comp of this.components.values()) {
|
|
124
|
+
const healthScore = comp.status === 'healthy' ? 1.0 :
|
|
125
|
+
comp.status === 'degraded' ? 0.5 :
|
|
126
|
+
comp.status === 'failed' ? 0.0 : 0.3; // unknown
|
|
127
|
+
weightedHealth += healthScore * comp.criticality;
|
|
128
|
+
totalWeight += comp.criticality;
|
|
129
|
+
}
|
|
130
|
+
return totalWeight > 0 ? weightedHealth / totalWeight : 0;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Full health check — assess all components, self-heal if needed.
|
|
134
|
+
*/
|
|
135
|
+
healthCheck() {
|
|
136
|
+
const healthy = [];
|
|
137
|
+
const degraded = [];
|
|
138
|
+
const failed = [];
|
|
139
|
+
const healingActions = [];
|
|
140
|
+
for (const [id, comp] of this.components) {
|
|
141
|
+
switch (comp.status) {
|
|
142
|
+
case 'healthy':
|
|
143
|
+
healthy.push(comp.name);
|
|
144
|
+
break;
|
|
145
|
+
case 'degraded':
|
|
146
|
+
degraded.push(comp.name);
|
|
147
|
+
// Attempt self-healing for degraded components
|
|
148
|
+
const healResult = this.selfHeal(id);
|
|
149
|
+
if (healResult)
|
|
150
|
+
healingActions.push(healResult.action);
|
|
151
|
+
break;
|
|
152
|
+
case 'failed':
|
|
153
|
+
failed.push(comp.name);
|
|
154
|
+
// Attempt self-healing for failed components
|
|
155
|
+
const failHeal = this.selfHeal(id);
|
|
156
|
+
if (failHeal)
|
|
157
|
+
healingActions.push(failHeal.action);
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const viability = this.computeViability();
|
|
162
|
+
// Boundary check: are we correctly distinguishing internal from external?
|
|
163
|
+
const internalOk = ['filesystem', 'session-context'].every(id => {
|
|
164
|
+
const c = this.components.get(id);
|
|
165
|
+
return c && c.status !== 'failed';
|
|
166
|
+
});
|
|
167
|
+
return {
|
|
168
|
+
viability,
|
|
169
|
+
healthy,
|
|
170
|
+
degraded,
|
|
171
|
+
failed,
|
|
172
|
+
healingActions,
|
|
173
|
+
isViable: viability >= this.viabilityThreshold,
|
|
174
|
+
boundaryIntact: internalOk,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Should the agent continue operating, or signal for help?
|
|
179
|
+
*/
|
|
180
|
+
shouldContinue() {
|
|
181
|
+
const viability = this.computeViability();
|
|
182
|
+
if (viability < this.viabilityThreshold) {
|
|
183
|
+
return {
|
|
184
|
+
continue: false,
|
|
185
|
+
reason: `System viability critically low (${(viability * 100).toFixed(0)}%). Core components degraded.`,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
// Check if filesystem is available (absolute requirement)
|
|
189
|
+
const fs = this.components.get('filesystem');
|
|
190
|
+
if (fs && fs.status === 'failed') {
|
|
191
|
+
return { continue: false, reason: 'File system access lost — cannot operate.' };
|
|
192
|
+
}
|
|
193
|
+
return { continue: true };
|
|
194
|
+
}
|
|
195
|
+
/** Get the healing log */
|
|
196
|
+
getHealingLog() {
|
|
197
|
+
return [...this.healingLog];
|
|
198
|
+
}
|
|
199
|
+
/** Get a specific component's status */
|
|
200
|
+
getComponent(id) {
|
|
201
|
+
return this.components.get(id);
|
|
202
|
+
}
|
|
203
|
+
/** Register a new component (e.g., when an MCP server connects) */
|
|
204
|
+
registerComponent(component) {
|
|
205
|
+
this.components.set(component.id, {
|
|
206
|
+
...component,
|
|
207
|
+
status: 'unknown',
|
|
208
|
+
lastChecked: 0,
|
|
209
|
+
failureCount: 0,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/** Reset for new session */
|
|
213
|
+
reset() {
|
|
214
|
+
for (const comp of this.components.values()) {
|
|
215
|
+
comp.status = 'unknown';
|
|
216
|
+
comp.failureCount = 0;
|
|
217
|
+
comp.lastChecked = 0;
|
|
218
|
+
}
|
|
219
|
+
this.healingLog = [];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AC;YACd,YAAY,EAAE,CAAC;SAChB,CAAC,CAAA;IACJ,CAAC;IAED,4BAA4B;IAC5B,KAAK;QACH,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,EAAE,CAAC;YAC5C,IAAI,CAAC,MAAM,GAAG,SAAS,CAAA;YACvB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAA;YACrB,IAAI,CAAC,WAAW,GAAG,CAAC,CAAA;QACtB,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,EAAE,CAAA;IACtB,CAAC;CACF"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
export interface BeliefState {
|
|
2
|
+
/** What the agent expects the user wants */
|
|
3
|
+
predictedIntent: string;
|
|
4
|
+
/** Confidence in the prediction (0-1) */
|
|
5
|
+
confidence: number;
|
|
6
|
+
/** Expected tool outcomes */
|
|
7
|
+
expectedOutcomes: Map<string, number>;
|
|
8
|
+
/** Entropy of the belief distribution (bits) */
|
|
9
|
+
entropy: number;
|
|
10
|
+
}
|
|
11
|
+
export interface Surprise {
|
|
12
|
+
/** How surprising the observation was (bits) */
|
|
13
|
+
informationContent: number;
|
|
14
|
+
/** Which prediction was violated */
|
|
15
|
+
violatedExpectation: string | null;
|
|
16
|
+
/** Magnitude of prediction error (0-1) */
|
|
17
|
+
predictionError: number;
|
|
18
|
+
}
|
|
19
|
+
export interface FreeEnergyState {
|
|
20
|
+
/** Current variational free energy (lower = better model) */
|
|
21
|
+
freeEnergy: number;
|
|
22
|
+
/** Accumulated surprise across the session */
|
|
23
|
+
totalSurprise: number;
|
|
24
|
+
/** Number of belief updates (perceptual inference) */
|
|
25
|
+
beliefUpdates: number;
|
|
26
|
+
/** Number of actions taken (active inference) */
|
|
27
|
+
actionsTaken: number;
|
|
28
|
+
/** Running average prediction error */
|
|
29
|
+
avgPredictionError: number;
|
|
30
|
+
/** Recommended policy: explore (reduce uncertainty) or exploit (act on beliefs) */
|
|
31
|
+
policy: 'explore' | 'exploit' | 'balanced';
|
|
32
|
+
}
|
|
33
|
+
export type InferenceMode = 'perceptual' | 'active';
|
|
34
|
+
/**
|
|
35
|
+
* Active Inference Engine — minimizes free energy by balancing
|
|
36
|
+
* belief updates (learning) with actions (tool use).
|
|
37
|
+
*
|
|
38
|
+
* When prediction errors are high → explore (research, read, search)
|
|
39
|
+
* When prediction errors are low → exploit (write, execute, commit)
|
|
40
|
+
*/
|
|
41
|
+
export declare class ActiveInferenceEngine {
|
|
42
|
+
private beliefs;
|
|
43
|
+
private surpriseHistory;
|
|
44
|
+
private toolOutcomeHistory;
|
|
45
|
+
private beliefUpdates;
|
|
46
|
+
private actionsTaken;
|
|
47
|
+
private readonly explorationThreshold;
|
|
48
|
+
private readonly exploitationThreshold;
|
|
49
|
+
private readonly learningRate;
|
|
50
|
+
private readonly decayRate;
|
|
51
|
+
constructor();
|
|
52
|
+
/**
|
|
53
|
+
* Observe a user message and compute surprise.
|
|
54
|
+
* High surprise = our model of the user is wrong → update beliefs.
|
|
55
|
+
*/
|
|
56
|
+
observeMessage(message: string, previousPrediction?: string): Surprise;
|
|
57
|
+
/**
|
|
58
|
+
* Observe a tool execution result and update expected outcomes.
|
|
59
|
+
*/
|
|
60
|
+
observeToolResult(toolName: string, success: boolean, relevance: number): void;
|
|
61
|
+
/**
|
|
62
|
+
* Compute current variational free energy.
|
|
63
|
+
* F = E[log q(s) - log p(o,s)] ≈ prediction_error + entropy
|
|
64
|
+
*
|
|
65
|
+
* Lower free energy = better internal model.
|
|
66
|
+
*/
|
|
67
|
+
computeFreeEnergy(): number;
|
|
68
|
+
/**
|
|
69
|
+
* Decide inference mode: should the agent explore or exploit?
|
|
70
|
+
*
|
|
71
|
+
* High free energy → explore (search, read, research — reduce uncertainty)
|
|
72
|
+
* Low free energy → exploit (write, execute, commit — act on beliefs)
|
|
73
|
+
*/
|
|
74
|
+
recommendPolicy(): 'explore' | 'exploit' | 'balanced';
|
|
75
|
+
/**
|
|
76
|
+
* Get tools recommended for the current policy.
|
|
77
|
+
* Explore → information-gathering tools
|
|
78
|
+
* Exploit → action-taking tools
|
|
79
|
+
*/
|
|
80
|
+
recommendToolBias(): {
|
|
81
|
+
preferred: string[];
|
|
82
|
+
discouraged: string[];
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Update the predicted intent (what the agent thinks the user wants next).
|
|
86
|
+
*/
|
|
87
|
+
updatePrediction(intent: string): void;
|
|
88
|
+
/** Get running average prediction error */
|
|
89
|
+
getAveragePredictionError(): number;
|
|
90
|
+
/** Get the full free energy state for diagnostics */
|
|
91
|
+
getState(): FreeEnergyState;
|
|
92
|
+
/** Reset for new conversation */
|
|
93
|
+
reset(): void;
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=free-energy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"free-energy.d.ts","sourceRoot":"","sources":["../src/free-energy.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,WAAW;IAC1B,4CAA4C;IAC5C,eAAe,EAAE,MAAM,CAAA;IACvB,yCAAyC;IACzC,UAAU,EAAE,MAAM,CAAA;IAClB,6BAA6B;IAC7B,gBAAgB,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IACrC,gDAAgD;IAChD,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,QAAQ;IACvB,gDAAgD;IAChD,kBAAkB,EAAE,MAAM,CAAA;IAC1B,oCAAoC;IACpC,mBAAmB,EAAE,MAAM,GAAG,IAAI,CAAA;IAClC,0CAA0C;IAC1C,eAAe,EAAE,MAAM,CAAA;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,6DAA6D;IAC7D,UAAU,EAAE,MAAM,CAAA;IAClB,8CAA8C;IAC9C,aAAa,EAAE,MAAM,CAAA;IACrB,sDAAsD;IACtD,aAAa,EAAE,MAAM,CAAA;IACrB,iDAAiD;IACjD,YAAY,EAAE,MAAM,CAAA;IACpB,uCAAu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active Inference Engine
|
|
2
|
+
//
|
|
3
|
+
// Based on Karl Friston's Free Energy Principle (2006-2024):
|
|
4
|
+
// All adaptive systems minimize variational free energy — the difference
|
|
5
|
+
// between their internal model of the world and actual sensory input.
|
|
6
|
+
//
|
|
7
|
+
// An agent can minimize surprise in two ways:
|
|
8
|
+
// 1. Perceptual inference — update beliefs to match observations
|
|
9
|
+
// 2. Active inference — act on the world to match predictions
|
|
10
|
+
//
|
|
11
|
+
// This module makes kbot's decision loop information-theoretically grounded:
|
|
12
|
+
// should I learn more (reduce uncertainty) or act (change the world)?
|
|
13
|
+
//
|
|
14
|
+
// References:
|
|
15
|
+
// - Friston, K. (2010). The free-energy principle: a unified brain theory?
|
|
16
|
+
// - Parr, T., Pezzulo, G., & Friston, K.J. (2022). Active Inference.
|
|
17
|
+
// - Da Costa, L. et al. (2020). Active inference on discrete state-spaces.
|
|
18
|
+
/**
|
|
19
|
+
* Active Inference Engine — minimizes free energy by balancing
|
|
20
|
+
* belief updates (learning) with actions (tool use).
|
|
21
|
+
*
|
|
22
|
+
* When prediction errors are high → explore (research, read, search)
|
|
23
|
+
* When prediction errors are low → exploit (write, execute, commit)
|
|
24
|
+
*/
|
|
25
|
+
export class ActiveInferenceEngine {
|
|
26
|
+
beliefs;
|
|
27
|
+
surpriseHistory = [];
|
|
28
|
+
toolOutcomeHistory = [];
|
|
29
|
+
beliefUpdates = 0;
|
|
30
|
+
actionsTaken = 0;
|
|
31
|
+
// Hyperparameters
|
|
32
|
+
explorationThreshold = 0.6; // Above this → explore
|
|
33
|
+
exploitationThreshold = 0.3; // Below this → exploit
|
|
34
|
+
learningRate = 0.15; // Belief update step size
|
|
35
|
+
decayRate = 0.95; // Surprise memory decay
|
|
36
|
+
constructor() {
|
|
37
|
+
this.beliefs = {
|
|
38
|
+
predictedIntent: '',
|
|
39
|
+
confidence: 0.5,
|
|
40
|
+
expectedOutcomes: new Map(),
|
|
41
|
+
entropy: 1.0,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Observe a user message and compute surprise.
|
|
46
|
+
* High surprise = our model of the user is wrong → update beliefs.
|
|
47
|
+
*/
|
|
48
|
+
observeMessage(message, previousPrediction) {
|
|
49
|
+
const words = new Set(message.toLowerCase().split(/\s+/).filter(w => w.length > 3));
|
|
50
|
+
const predWords = previousPrediction
|
|
51
|
+
? new Set(previousPrediction.toLowerCase().split(/\s+/).filter(w => w.length > 3))
|
|
52
|
+
: new Set();
|
|
53
|
+
// Prediction error via Jaccard distance
|
|
54
|
+
let predictionError = 1.0;
|
|
55
|
+
if (predWords.size > 0 && words.size > 0) {
|
|
56
|
+
const intersection = new Set([...words].filter(w => predWords.has(w)));
|
|
57
|
+
const union = new Set([...words, ...predWords]);
|
|
58
|
+
predictionError = 1 - (intersection.size / union.size);
|
|
59
|
+
}
|
|
60
|
+
// Information content (surprise in bits) = -log2(1 - predictionError)
|
|
61
|
+
// Clamped to avoid infinity
|
|
62
|
+
const p = Math.max(0.01, Math.min(0.99, 1 - predictionError));
|
|
63
|
+
const informationContent = -Math.log2(p);
|
|
64
|
+
const surprise = {
|
|
65
|
+
informationContent,
|
|
66
|
+
violatedExpectation: predictionError > 0.7 ? this.beliefs.predictedIntent : null,
|
|
67
|
+
predictionError,
|
|
68
|
+
};
|
|
69
|
+
this.surpriseHistory.push(surprise);
|
|
70
|
+
// Update beliefs via perceptual inference
|
|
71
|
+
if (predictionError > this.explorationThreshold) {
|
|
72
|
+
this.beliefs.confidence *= (1 - this.learningRate);
|
|
73
|
+
this.beliefs.entropy = Math.min(2.0, this.beliefs.entropy + predictionError * 0.3);
|
|
74
|
+
this.beliefUpdates++;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
this.beliefs.confidence = Math.min(1.0, this.beliefs.confidence + this.learningRate * (1 - predictionError));
|
|
78
|
+
this.beliefs.entropy = Math.max(0.1, this.beliefs.entropy - (1 - predictionError) * 0.2);
|
|
79
|
+
}
|
|
80
|
+
return surprise;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Observe a tool execution result and update expected outcomes.
|
|
84
|
+
*/
|
|
85
|
+
observeToolResult(toolName, success, relevance) {
|
|
86
|
+
const predicted = this.beliefs.expectedOutcomes.get(toolName) ?? 0.5;
|
|
87
|
+
const actual = success ? relevance : 0;
|
|
88
|
+
this.toolOutcomeHistory.push({ tool: toolName, predicted, actual });
|
|
89
|
+
// Update expected outcome for this tool (exponential moving average)
|
|
90
|
+
const updated = predicted + this.learningRate * (actual - predicted);
|
|
91
|
+
this.beliefs.expectedOutcomes.set(toolName, Math.max(0, Math.min(1, updated)));
|
|
92
|
+
this.actionsTaken++;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Compute current variational free energy.
|
|
96
|
+
* F = E[log q(s) - log p(o,s)] ≈ prediction_error + entropy
|
|
97
|
+
*
|
|
98
|
+
* Lower free energy = better internal model.
|
|
99
|
+
*/
|
|
100
|
+
computeFreeEnergy() {
|
|
101
|
+
const recentSurprises = this.surpriseHistory.slice(-10);
|
|
102
|
+
const avgSurprise = recentSurprises.length > 0
|
|
103
|
+
? recentSurprises.reduce((sum, s) => sum + s.informationContent, 0) / recentSurprises.length
|
|
104
|
+
: 1.0;
|
|
105
|
+
// Free energy ≈ expected surprise + model complexity (entropy)
|
|
106
|
+
const freeEnergy = avgSurprise * 0.7 + this.beliefs.entropy * 0.3;
|
|
107
|
+
return freeEnergy;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Decide inference mode: should the agent explore or exploit?
|
|
111
|
+
*
|
|
112
|
+
* High free energy → explore (search, read, research — reduce uncertainty)
|
|
113
|
+
* Low free energy → exploit (write, execute, commit — act on beliefs)
|
|
114
|
+
*/
|
|
115
|
+
recommendPolicy() {
|
|
116
|
+
const fe = this.computeFreeEnergy();
|
|
117
|
+
const avgPredError = this.getAveragePredictionError();
|
|
118
|
+
if (avgPredError > this.explorationThreshold || fe > 1.5) {
|
|
119
|
+
return 'explore';
|
|
120
|
+
}
|
|
121
|
+
if (avgPredError < this.exploitationThreshold && fe < 0.8) {
|
|
122
|
+
return 'exploit';
|
|
123
|
+
}
|
|
124
|
+
return 'balanced';
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Get tools recommended for the current policy.
|
|
128
|
+
* Explore → information-gathering tools
|
|
129
|
+
* Exploit → action-taking tools
|
|
130
|
+
*/
|
|
131
|
+
recommendToolBias() {
|
|
132
|
+
const policy = this.recommendPolicy();
|
|
133
|
+
if (policy === 'explore') {
|
|
134
|
+
return {
|
|
135
|
+
preferred: ['web_search', 'read_file', 'grep', 'glob', 'git_log', 'arxiv_search', 'url_fetch'],
|
|
136
|
+
discouraged: ['write_file', 'bash', 'git_commit', 'git_push'],
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
if (policy === 'exploit') {
|
|
140
|
+
return {
|
|
141
|
+
preferred: ['write_file', 'edit_file', 'bash', 'git_commit', 'multi_file_write'],
|
|
142
|
+
discouraged: [],
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
return { preferred: [], discouraged: [] };
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Update the predicted intent (what the agent thinks the user wants next).
|
|
149
|
+
*/
|
|
150
|
+
updatePrediction(intent) {
|
|
151
|
+
this.beliefs.predictedIntent = intent;
|
|
152
|
+
}
|
|
153
|
+
/** Get running average prediction error */
|
|
154
|
+
getAveragePredictionError() {
|
|
155
|
+
const recent = this.surpriseHistory.slice(-10);
|
|
156
|
+
if (recent.length === 0)
|
|
157
|
+
return 0.5;
|
|
158
|
+
return recent.reduce((sum, s) => sum + s.predictionError, 0) / recent.length;
|
|
159
|
+
}
|
|
160
|
+
/** Get the full free energy state for diagnostics */
|
|
161
|
+
getState() {
|
|
162
|
+
return {
|
|
163
|
+
freeEnergy: this.computeFreeEnergy(),
|
|
164
|
+
totalSurprise: this.surpriseHistory.reduce((sum, s) => sum + s.informationContent, 0),
|
|
165
|
+
beliefUpdates: this.beliefUpdates,
|
|
166
|
+
actionsTaken: this.actionsTaken,
|
|
167
|
+
avgPredictionError: this.getAveragePredictionError(),
|
|
168
|
+
policy: this.recommendPolicy(),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
/** Reset for new conversation */
|
|
172
|
+
reset() {
|
|
173
|
+
this.beliefs = { predictedIntent: '', confidence: 0.5, expectedOutcomes: new Map(), entropy: 1.0 };
|
|
174
|
+
this.surpriseHistory = [];
|
|
175
|
+
this.toolOutcomeHistory = [];
|
|
176
|
+
this.beliefUpdates = 0;
|
|
177
|
+
this.actionsTaken = 0;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
//# sourceMappingURL=free-energy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"free-energy.js","sourceRoot":"","sources":["../src/free-energy.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,EAAE;AACF,6DAA6D;AAC7D,yEAAyE;AACzE,sEAAsE;AACtE,EAAE;AACF,8CAA8C;AAC9C,mEAAmE;AACnE,gEAAgE;AAChE,EAAE;AACF,6EAA6E;AAC7E,sEAAsE;AACtE,EAAE;AACF,cAAc;AACd,6EAA6E;AAC7E,uEAAuE;AACvE,6EAA6E;AAuC7E;;;;;;GAMG;AACH,MAAM,OAAO,qBAAqB;IACxB,OAAO,CAAa;IACpB,eAAe,GAAe,EAAE,CAAA;IAChC,kBAAkB,GAA+D,EAAE,CAAA;IACnF,aAAa,GAAG,CAAC,CAAA;IACjB,YAAY,GAAG,CAAC,CAAA;IAExB,kBAAkB;IACD,oBAAoB,GAAG,GAAG,CAAA,CAAE,uBAAuB;IACnD,qBAAqB,GAAG,GAAG,CAAA,CAAC,uBAAuB;IACnD,YAAY,GAAG,IAAI,CAAA,CAAU,0BAA0B;IACvD,SAAS,GAAG,IAAI,CAAA,CAAa,wBAAwB;IAEtE;QACE,IAAI,CAAC,OAAO,GAAG;YACb,eAAe,EAAE,EAAE;YACnB,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