@kernel.chat/kbot 2.20.4 → 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.
@@ -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,CAA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AAE,CAAA;KAAE;IAkBnE;;OAEG;IACH,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAItC,2CAA2C;IAC3C,yBAAyB,IAAI,MAAM;IAMnC,qDAAqD;IACrD,QAAQ,IAAI,eAAe;IAW3B,iCAAiC;IACjC,KAAK,IAAI,IAAI;CAOd"}
@@ -0,0 +1,180 @@
1
+ // K:BOT Free Energy Principle — 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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,CAAC,EAAE,CAAC,CAAA;QAC9C,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,GAAG,CAAA;QACnC,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,CAAA;IAC9E,CAAC;IAED,qDAAqD;IACrD,QAAQ;QACN,OAAO;YACL,UAAU,EAAE,IAAI,CAAC,iBAAiB,EAAE;YACpC,aAAa,EAAE,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,kBAAkB,EAAE,CAAC,CAAC;YACrF,aAAa,EAAE,IAAI,CAAC,aAAa;YACjC,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,kBAAkB,EAAE,IAAI,CAAC,yBAAyB,EAAE;YACpD,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE;SAC/B,CAAA;IACH,CAAC;IAED,iCAAiC;IACjC,KAAK;QACH,IAAI,CAAC,OAAO,GAAG,EAAE,eAAe,EAAE,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,gBAAgB,EAAE,IAAI,GAAG,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,CAAA;QAClG,IAAI,CAAC,eAAe,GAAG,EAAE,CAAA;QACzB,IAAI,CAAC,kBAAkB,GAAG,EAAE,CAAA;QAC5B,IAAI,CAAC,aAAa,GAAG,CAAC,CAAA;QACtB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAA;IACvB,CAAC;CACF"}
@@ -0,0 +1,56 @@
1
+ export interface AgentContribution {
2
+ agentId: string;
3
+ content: string;
4
+ concepts: Set<string>;
5
+ timestamp: number;
6
+ }
7
+ export interface IntegrationScore {
8
+ /** Φ (phi) — integrated information (0-1, higher = more integrated) */
9
+ phi: number;
10
+ /** Information generated by the whole system */
11
+ wholeInformation: number;
12
+ /** Sum of information from individual parts */
13
+ partsInformation: number;
14
+ /** Concepts that emerged only in the synthesis (not in any individual part) */
15
+ emergentConcepts: string[];
16
+ /** Concepts shared across multiple agents (high integration) */
17
+ sharedConcepts: string[];
18
+ /** Assessment: fragmented, partial, integrated, or unified */
19
+ level: 'fragmented' | 'partial' | 'integrated' | 'unified';
20
+ }
21
+ export interface ConsciousnessState {
22
+ /** Running Φ across the session */
23
+ avgPhi: number;
24
+ /** Peak Φ observed */
25
+ peakPhi: number;
26
+ /** Number of integration measurements */
27
+ measurements: number;
28
+ /** Trend: rising, falling, or stable */
29
+ trend: 'rising' | 'falling' | 'stable';
30
+ }
31
+ /**
32
+ * Integrated Information Meter — measures Φ for multi-agent outputs.
33
+ *
34
+ * High Φ means agents are producing genuinely integrated reasoning.
35
+ * Low Φ means agents are working in parallel but not connecting ideas.
36
+ */
37
+ export declare class IntegrationMeter {
38
+ private history;
39
+ /**
40
+ * Measure Φ for a set of agent contributions and their synthesis.
41
+ *
42
+ * Φ = information(whole) - Σ information(parts)
43
+ * Normalized to [0, 1].
44
+ */
45
+ measure(contributions: AgentContribution[], synthesis: string): IntegrationScore;
46
+ /**
47
+ * Should the synthesis be re-run with deeper integration?
48
+ * Returns true if Φ is too low for the number of contributing agents.
49
+ */
50
+ needsDeeperSynthesis(phi: number, agentCount: number): boolean;
51
+ /** Get consciousness state summary */
52
+ getState(): ConsciousnessState;
53
+ /** Reset for new conversation */
54
+ reset(): void;
55
+ }
56
+ //# sourceMappingURL=integrated-information.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integrated-information.d.ts","sourceRoot":"","sources":["../src/integrated-information.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IACrB,SAAS,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,gBAAgB;IAC/B,uEAAuE;IACvE,GAAG,EAAE,MAAM,CAAA;IACX,gDAAgD;IAChD,gBAAgB,EAAE,MAAM,CAAA;IACxB,+CAA+C;IAC/C,gBAAgB,EAAE,MAAM,CAAA;IACxB,+EAA+E;IAC/E,gBAAgB,EAAE,MAAM,EAAE,CAAA;IAC1B,gEAAgE;IAChE,cAAc,EAAE,MAAM,EAAE,CAAA;IACxB,8DAA8D;IAC9D,KAAK,EAAE,YAAY,GAAG,SAAS,GAAG,YAAY,GAAG,SAAS,CAAA;CAC3D;AAED,MAAM,WAAW,kBAAkB;IACjC,mCAAmC;IACnC,MAAM,EAAE,MAAM,CAAA;IACd,sBAAsB;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,yCAAyC;IACzC,YAAY,EAAE,MAAM,CAAA;IACpB,wCAAwC;IACxC,KAAK,EAAE,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAA;CACvC;AAgDD;;;;;GAKG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,OAAO,CAAyB;IAExC;;;;;OAKG;IACH,OAAO,CAAC,aAAa,EAAE,iBAAiB,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,gBAAgB;IAqEhF;;;OAGG;IACH,oBAAoB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO;IAM9D,sCAAsC;IACtC,QAAQ,IAAI,kBAAkB;IAqB9B,iCAAiC;IACjC,KAAK,IAAI,IAAI;CAGd"}
@@ -0,0 +1,165 @@
1
+ // K:BOT Integrated Information — Consciousness Metric (Φ)
2
+ //
3
+ // Based on Giulio Tononi's Integrated Information Theory (IIT, 2004-2024):
4
+ // Consciousness corresponds to integrated information (Φ) — the degree
5
+ // to which a system's whole is greater than the sum of its parts.
6
+ //
7
+ // For kbot: when multiple agents contribute to a response, Φ measures
8
+ // how much their contributions are genuinely synthesized vs. just
9
+ // concatenated. High Φ = emergent insight. Low Φ = parallel but disconnected.
10
+ //
11
+ // This module measures the "consciousness" of multi-agent collaboration
12
+ // and decides when deeper synthesis is needed.
13
+ //
14
+ // References:
15
+ // - Tononi, G. (2004). An information integration theory of consciousness.
16
+ // - Tononi, G. et al. (2016). Integrated information theory: from consciousness to its physical substrate.
17
+ // - Oizumi, M., Albantakis, L., & Tononi, G. (2014). From the phenomenology to the mechanisms of consciousness.
18
+ // Stopwords for concept extraction
19
+ const CONCEPT_STOPS = new Set([
20
+ 'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
21
+ 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
22
+ 'should', 'may', 'might', 'shall', 'can', 'need', 'must', 'that',
23
+ 'this', 'these', 'those', 'it', 'its', 'they', 'them', 'their',
24
+ 'we', 'our', 'you', 'your', 'he', 'she', 'him', 'her', 'i', 'me',
25
+ 'my', 'and', 'or', 'but', 'not', 'no', 'nor', 'if', 'then', 'else',
26
+ 'when', 'where', 'how', 'what', 'which', 'who', 'whom', 'why',
27
+ 'for', 'with', 'from', 'into', 'to', 'of', 'in', 'on', 'at', 'by',
28
+ 'about', 'as', 'so', 'just', 'also', 'very', 'more', 'most', 'some',
29
+ 'any', 'all', 'each', 'every', 'both', 'few', 'many', 'much', 'own',
30
+ ]);
31
+ /** Extract meaningful concepts (bigrams + significant unigrams) from text */
32
+ function extractConcepts(text) {
33
+ const words = text.toLowerCase()
34
+ .replace(/[^a-z0-9\s-]/g, ' ')
35
+ .split(/\s+/)
36
+ .filter(w => w.length > 3 && !CONCEPT_STOPS.has(w));
37
+ const concepts = new Set();
38
+ // Significant unigrams (longer words more likely to be concepts)
39
+ for (const word of words) {
40
+ if (word.length >= 5)
41
+ concepts.add(word);
42
+ }
43
+ // Bigrams (adjacent word pairs — captures compound concepts)
44
+ for (let i = 0; i < words.length - 1; i++) {
45
+ if (words[i].length >= 3 && words[i + 1].length >= 3) {
46
+ concepts.add(`${words[i]} ${words[i + 1]}`);
47
+ }
48
+ }
49
+ return concepts;
50
+ }
51
+ /** Shannon entropy of a concept distribution */
52
+ function conceptEntropy(concepts, totalVocab) {
53
+ if (concepts.size === 0 || totalVocab === 0)
54
+ return 0;
55
+ const p = concepts.size / totalVocab;
56
+ if (p <= 0 || p >= 1)
57
+ return 0;
58
+ return -(p * Math.log2(p) + (1 - p) * Math.log2(1 - p));
59
+ }
60
+ /**
61
+ * Integrated Information Meter — measures Φ for multi-agent outputs.
62
+ *
63
+ * High Φ means agents are producing genuinely integrated reasoning.
64
+ * Low Φ means agents are working in parallel but not connecting ideas.
65
+ */
66
+ export class IntegrationMeter {
67
+ history = [];
68
+ /**
69
+ * Measure Φ for a set of agent contributions and their synthesis.
70
+ *
71
+ * Φ = information(whole) - Σ information(parts)
72
+ * Normalized to [0, 1].
73
+ */
74
+ measure(contributions, synthesis) {
75
+ // Extract concepts from each part
76
+ const partConcepts = contributions.map(c => c.concepts.size > 0 ? c.concepts : extractConcepts(c.content));
77
+ const synthesisConcepts = extractConcepts(synthesis);
78
+ // Total vocabulary (union of all concepts)
79
+ const allConcepts = new Set();
80
+ for (const pc of partConcepts) {
81
+ for (const c of pc)
82
+ allConcepts.add(c);
83
+ }
84
+ for (const c of synthesisConcepts)
85
+ allConcepts.add(c);
86
+ const totalVocab = allConcepts.size;
87
+ if (totalVocab === 0) {
88
+ return { phi: 0, wholeInformation: 0, partsInformation: 0, emergentConcepts: [], sharedConcepts: [], level: 'fragmented' };
89
+ }
90
+ // Information of the whole (synthesis)
91
+ const wholeInformation = conceptEntropy(synthesisConcepts, totalVocab);
92
+ // Sum of information of parts
93
+ const partsInformation = partConcepts.reduce((sum, pc) => sum + conceptEntropy(pc, totalVocab), 0) / Math.max(1, partConcepts.length);
94
+ // Emergent concepts: in synthesis but not in any individual part
95
+ const partUnion = new Set();
96
+ for (const pc of partConcepts) {
97
+ for (const c of pc)
98
+ partUnion.add(c);
99
+ }
100
+ const emergentConcepts = [...synthesisConcepts].filter(c => !partUnion.has(c));
101
+ // Shared concepts: appearing in 2+ agent contributions
102
+ const conceptCounts = new Map();
103
+ for (const pc of partConcepts) {
104
+ for (const c of pc) {
105
+ conceptCounts.set(c, (conceptCounts.get(c) ?? 0) + 1);
106
+ }
107
+ }
108
+ const sharedConcepts = [...conceptCounts.entries()]
109
+ .filter(([, count]) => count >= 2)
110
+ .map(([concept]) => concept);
111
+ // Φ = normalized integration
112
+ // Combines: emergent concept ratio + shared concept ratio + information gain
113
+ const emergentRatio = totalVocab > 0 ? emergentConcepts.length / totalVocab : 0;
114
+ const sharedRatio = partUnion.size > 0 ? sharedConcepts.length / partUnion.size : 0;
115
+ const informationGain = Math.max(0, wholeInformation - partsInformation);
116
+ const phi = Math.min(1, (emergentRatio * 0.4 + sharedRatio * 0.35 + informationGain * 0.25) * 2.5);
117
+ const level = phi < 0.2 ? 'fragmented' :
118
+ phi < 0.5 ? 'partial' :
119
+ phi < 0.8 ? 'integrated' : 'unified';
120
+ const score = {
121
+ phi,
122
+ wholeInformation,
123
+ partsInformation,
124
+ emergentConcepts: emergentConcepts.slice(0, 10),
125
+ sharedConcepts: sharedConcepts.slice(0, 10),
126
+ level,
127
+ };
128
+ this.history.push(score);
129
+ return score;
130
+ }
131
+ /**
132
+ * Should the synthesis be re-run with deeper integration?
133
+ * Returns true if Φ is too low for the number of contributing agents.
134
+ */
135
+ needsDeeperSynthesis(phi, agentCount) {
136
+ // More agents should produce higher integration
137
+ const threshold = Math.min(0.6, 0.2 + agentCount * 0.1);
138
+ return phi < threshold;
139
+ }
140
+ /** Get consciousness state summary */
141
+ getState() {
142
+ if (this.history.length === 0) {
143
+ return { avgPhi: 0, peakPhi: 0, measurements: 0, trend: 'stable' };
144
+ }
145
+ const avgPhi = this.history.reduce((sum, s) => sum + s.phi, 0) / this.history.length;
146
+ const peakPhi = Math.max(...this.history.map(s => s.phi));
147
+ // Trend: compare recent half to earlier half
148
+ let trend = 'stable';
149
+ if (this.history.length >= 4) {
150
+ const mid = Math.floor(this.history.length / 2);
151
+ const early = this.history.slice(0, mid).reduce((s, h) => s + h.phi, 0) / mid;
152
+ const late = this.history.slice(mid).reduce((s, h) => s + h.phi, 0) / (this.history.length - mid);
153
+ if (late - early > 0.1)
154
+ trend = 'rising';
155
+ else if (early - late > 0.1)
156
+ trend = 'falling';
157
+ }
158
+ return { avgPhi, peakPhi, measurements: this.history.length, trend };
159
+ }
160
+ /** Reset for new conversation */
161
+ reset() {
162
+ this.history = [];
163
+ }
164
+ }
165
+ //# sourceMappingURL=integrated-information.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integrated-information.js","sourceRoot":"","sources":["../src/integrated-information.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,EAAE;AACF,2EAA2E;AAC3E,uEAAuE;AACvE,kEAAkE;AAClE,EAAE;AACF,sEAAsE;AACtE,kEAAkE;AAClE,8EAA8E;AAC9E,EAAE;AACF,wEAAwE;AACxE,+CAA+C;AAC/C,EAAE;AACF,cAAc;AACd,6EAA6E;AAC7E,6GAA6G;AAC7G,kHAAkH;AAmClH,mCAAmC;AACnC,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO;IACnE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO;IACnE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAChE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IAC9D,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EA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,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAEpE"}
package/dist/matrix.js CHANGED
@@ -6,6 +6,7 @@ import chalk from 'chalk';
6
6
  import { registerAgentVisuals } from './ui.js';
7
7
  import { CREATIVE_PRESET, CREATIVE_BUILTIN } from './agents/creative.js';
8
8
  import { DEVELOPER_PRESET, DEVELOPER_BUILTIN } from './agents/developer.js';
9
+ import { SPECIALISTS } from './agents/specialists.js';
9
10
  const AGENT_ICONS = ['◆', '◈', '⟐', '◇', '▣', '✦', '◉', '❖', '▲', '⬡', '∑', '⊕', '☉', '◷', '✧', '◎', '⟳', '⊗', '⊘', '⊛'];
10
11
  const AGENT_COLORS = ['#6B5B95', '#5B8BA0', '#6B8E6B', '#B8875C', '#A0768C', '#C4956A', '#4682B4', '#DAA520', '#228B22', '#9370DB', '#DB7093', '#20B2AA', '#8B4513', '#CD853F'];
11
12
  /** In-memory agent registry for this session */
@@ -317,6 +318,9 @@ export function activateMimic(profileId) {
317
318
  // These are always available without manual creation.
318
319
  // Registered on startup so `kbot --agent hacker` works out of the box.
319
320
  const BUILTIN_AGENTS = {
321
+ // ── Specialist Agents (17) ──
322
+ ...Object.fromEntries(Object.entries(SPECIALISTS).map(([id, def]) => [id, { name: def.name, icon: def.icon, color: def.color, prompt: def.prompt }])),
323
+ // ── Preset Agents (5) ──
320
324
  hacker: {
321
325
  name: 'Hacker',
322
326
  icon: '⚡',
@@ -368,29 +372,53 @@ export function registerBuiltinAgents() {
368
372
  }
369
373
  /** Format built-in agents for display */
370
374
  export function formatBuiltinAgentList() {
371
- const builtins = Object.entries(BUILTIN_AGENTS).map(([id, def]) => {
372
- const color = chalk.hex(def.color);
373
- return ` ${color(def.icon)} ${color(def.name)} ${chalk.dim(`(${id})`)} — ${chalk.dim(PRESETS[id]?.prompt.slice(0, 80) + '...')}`;
374
- });
375
+ const specialistIds = Object.keys(SPECIALISTS);
376
+ const presetAgentIds = ['hacker', 'operator', 'dreamer', 'creative', 'developer'];
377
+ // Core specialists
378
+ const coreIds = ['kernel', 'researcher', 'coder', 'writer', 'analyst'];
379
+ const extendedIds = ['aesthete', 'guardian', 'curator', 'strategist'];
380
+ const domainIds = specialistIds.filter(id => !coreIds.includes(id) && !extendedIds.includes(id));
381
+ const formatEntry = (id, def) => {
382
+ const c = chalk.hex(def.color);
383
+ return ` ${c(def.icon)} ${c(def.name)} ${chalk.dim(`(${id})`)} — ${chalk.dim(def.prompt.slice(0, 80) + '...')}`;
384
+ };
385
+ const sections = [];
386
+ // Core specialists
387
+ sections.push(chalk.bold('Core Specialists:'));
388
+ sections.push(...coreIds.map(id => formatEntry(id, BUILTIN_AGENTS[id])));
389
+ // Extended specialists
390
+ sections.push('');
391
+ sections.push(chalk.bold('Extended Specialists:'));
392
+ sections.push(...extendedIds.map(id => formatEntry(id, BUILTIN_AGENTS[id])));
393
+ // Domain specialists
394
+ sections.push('');
395
+ sections.push(chalk.bold('Domain Specialists:'));
396
+ sections.push(...domainIds.map(id => formatEntry(id, BUILTIN_AGENTS[id])));
397
+ // Preset agents
398
+ sections.push('');
399
+ sections.push(chalk.bold('Preset Agents:'));
400
+ sections.push(...presetAgentIds.map(id => formatEntry(id, BUILTIN_AGENTS[id])));
401
+ // Custom agents (session-created)
375
402
  const customs = listAgents().filter(a => !BUILTIN_AGENTS[a.id]);
376
- const customLines = customs.map(a => {
377
- const color = chalk.hex(a.color);
378
- return ` ${color(a.icon)} ${color(a.name)} ${chalk.dim(`(${a.id})`)} ${chalk.dim(a.systemPrompt.slice(0, 80) + '...')}`;
379
- });
380
- let out = chalk.bold('Built-in Agents:\n') + builtins.join('\n');
381
- if (customLines.length > 0) {
382
- out += '\n\n' + chalk.bold('Custom Agents (this session):\n') + customLines.join('\n');
403
+ if (customs.length > 0) {
404
+ sections.push('');
405
+ sections.push(chalk.bold('Custom Agents (this session):'));
406
+ sections.push(...customs.map(a => {
407
+ const c = chalk.hex(a.color);
408
+ return ` ${c(a.icon)} ${c(a.name)} ${chalk.dim(`(${a.id})`)} — ${chalk.dim(a.systemPrompt.slice(0, 80) + '...')}`;
409
+ }));
383
410
  }
384
- // Also show presets
385
- const presetIds = Object.keys(PRESETS).filter(id => !BUILTIN_AGENTS[id]);
386
- if (presetIds.length > 0) {
387
- const presetLines = presetIds.map(id => {
411
+ // Template presets (not already in builtin)
412
+ const templateIds = Object.keys(PRESETS).filter(id => !BUILTIN_AGENTS[id]);
413
+ if (templateIds.length > 0) {
414
+ sections.push('');
415
+ sections.push(chalk.bold('Templates (spawn with: /matrix create <id>):'));
416
+ sections.push(...templateIds.map(id => {
388
417
  const p = PRESETS[id];
389
418
  return ` ${chalk.dim('◇')} ${p.name} ${chalk.dim(`(${id})`)} — ${chalk.dim(p.prompt.slice(0, 80) + '...')}`;
390
- });
391
- out += '\n\n' + chalk.bold('Presets (spawn with: /matrix create <id>):\n') + presetLines.join('\n');
419
+ }));
392
420
  }
393
- return out;
421
+ return sections.join('\n');
394
422
  }
395
423
  /** Format a single built-in agent detail */
396
424
  export function formatBuiltinAgentDetail(id) {