@causyne/agent 1.20.60 → 1.20.62

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/acp/agentCatalog.js +1 -1
  3. package/src/acp/agentCatalog.ts +1 -1
  4. package/src/acp/peerProfiles.js +3 -3
  5. package/src/acp/peerProfiles.ts +3 -3
  6. package/src/agentLoop.js +58 -22
  7. package/src/agentLoop.ts +64 -25
  8. package/src/checkpoints.js +23 -5
  9. package/src/cliMode.js +4 -2
  10. package/src/commands.js +503 -78
  11. package/src/contextManager.d.ts +3 -0
  12. package/src/contextManager.js +78 -5
  13. package/src/cortex/autoCondenser.js +105 -145
  14. package/src/cortex/autoCondenser.ts +185 -0
  15. package/src/cortex/cortexEngine.js +179 -0
  16. package/src/cortex/cortexEngine.ts +209 -0
  17. package/src/cortex/provisioner.js +12 -14
  18. package/src/cortex/provisioner.ts +29 -0
  19. package/src/cortex/vectorDb.js +307 -386
  20. package/src/cortex/vectorDb.ts +473 -0
  21. package/src/reporting.js +30 -7
  22. package/src/sessionJournal.js +13 -0
  23. package/src/sessionJournal.ts +13 -0
  24. package/src/tokenTracker.js +22 -0
  25. package/src/tokenTracker.ts +28 -0
  26. package/src/tui/chatRenderer.js +6 -2
  27. package/src/tui/completion.js +34 -15
  28. package/src/tui/composerControls.js +5 -0
  29. package/src/tui/composerControls.ts +5 -0
  30. package/src/tui/layout.js +1 -1
  31. package/src/tui/layout.ts +1 -1
  32. package/src/tui/observerPicker.js +323 -0
  33. package/src/tui/observerPicker.ts +386 -0
  34. package/src/tui/prompt.js +184 -22
  35. package/src/tui/stageSurface.js +18 -8
  36. package/src/tui/usageCard.js +178 -0
  37. package/src/tui/usageCard.ts +240 -0
  38. package/src/utils/paths.js +30 -1
  39. package/src/utils/paths.ts +32 -1
  40. package/src/cortex/autoCondenser.d.ts +0 -2
  41. package/src/cortex/vectorDb.d.ts +0 -1
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Sovereign Cortex Engine — Native Zero-Dependency SQLite & Semantic Vectors.
3
+ *
4
+ * Provides instant, production-grade memory persistence and semantic vector retrieval
5
+ * across all development environments and platforms with zero required npm packages,
6
+ * using Node.js built-in SQLite and deterministic semantic feature hashing.
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { causyneHome } from '../utils/paths.js';
11
+ /**
12
+ * Open or create the SQLite database for Cortex using native Node SQLite or better-sqlite3.
13
+ */
14
+ export async function openCortexDatabase(dbPath) {
15
+ const dir = path.dirname(dbPath);
16
+ if (!fs.existsSync(dir)) {
17
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
18
+ }
19
+ // 1. Prefer Node.js native `node:sqlite` (Node 22+)
20
+ try {
21
+ const sqliteModule = await import('node:sqlite');
22
+ if (sqliteModule && typeof sqliteModule.DatabaseSync === 'function') {
23
+ const dbInstance = new sqliteModule.DatabaseSync(dbPath);
24
+ // Ensure transaction helper is available
25
+ if (typeof dbInstance.transaction !== 'function') {
26
+ dbInstance.transaction = function (fn) {
27
+ return function (...args) {
28
+ dbInstance.exec('BEGIN IMMEDIATE');
29
+ try {
30
+ const res = fn(...args);
31
+ dbInstance.exec('COMMIT');
32
+ return res;
33
+ }
34
+ catch (err) {
35
+ try {
36
+ dbInstance.exec('ROLLBACK');
37
+ }
38
+ catch (_) { }
39
+ throw err;
40
+ }
41
+ };
42
+ };
43
+ }
44
+ return dbInstance;
45
+ }
46
+ }
47
+ catch (_e) {
48
+ // Native node:sqlite unavailable or disabled; fall through to optional provider
49
+ }
50
+ // 2. Check for optional better-sqlite3 in cortex package
51
+ try {
52
+ const { requireCortexModule } = await import('./provisioner.js');
53
+ const DatabaseConstructor = await requireCortexModule('better-sqlite3');
54
+ if (DatabaseConstructor) {
55
+ return new DatabaseConstructor(dbPath);
56
+ }
57
+ }
58
+ catch (_e) {
59
+ // better-sqlite3 not provisioned
60
+ }
61
+ throw new Error('SQLite engine unavailable. Node 22+ with node:sqlite or better-sqlite3 is required for Cortex.');
62
+ }
63
+ /**
64
+ * Deterministic string hash (FNV-1a 32-bit).
65
+ */
66
+ function fnv1a32(str) {
67
+ let h = 2166136261 >>> 0;
68
+ for (let i = 0; i < str.length; i++) {
69
+ h ^= str.charCodeAt(i);
70
+ h = Math.imul(h, 16777619) >>> 0;
71
+ }
72
+ return h;
73
+ }
74
+ /**
75
+ * Native, zero-dependency 128-dimensional semantic feature hashing embedding.
76
+ * Captures word tokens, character trigrams, and morphology with unit L2 normalization.
77
+ */
78
+ export function computeNativeEmbedding(text, dims = 128) {
79
+ const vec = new Float64Array(dims);
80
+ const words = String(text || '').toLowerCase().match(/[a-z0-9_#.-]+/g) || [];
81
+ for (const word of words) {
82
+ const h = fnv1a32(word);
83
+ const idx = h % dims;
84
+ const sign = (fnv1a32(word + '_s') & 1) ? 1 : -1;
85
+ vec[idx] = (vec[idx] ?? 0) + sign * 2.0;
86
+ if (word.length >= 3) {
87
+ for (let i = 0; i <= word.length - 3; i++) {
88
+ const tri = word.slice(i, i + 3);
89
+ const th = fnv1a32(tri);
90
+ const tidx = th % dims;
91
+ const tsign = (fnv1a32(tri + '_s') & 1) ? 1 : -1;
92
+ vec[tidx] = (vec[tidx] ?? 0) + tsign * 0.5;
93
+ }
94
+ }
95
+ }
96
+ let norm = 0;
97
+ for (let i = 0; i < dims; i++) {
98
+ const v = vec[i] ?? 0;
99
+ norm += v * v;
100
+ }
101
+ norm = Math.sqrt(norm);
102
+ if (norm > 0) {
103
+ for (let i = 0; i < dims; i++) {
104
+ vec[i] = (vec[i] ?? 0) / norm;
105
+ }
106
+ }
107
+ return Array.from(vec);
108
+ }
109
+ /**
110
+ * Exact cosine similarity between two float vectors.
111
+ */
112
+ export function cosineSimilarity(vecA, vecB) {
113
+ let dotProduct = 0;
114
+ let normA = 0;
115
+ let normB = 0;
116
+ const len = Math.min(vecA.length, vecB.length);
117
+ for (let i = 0; i < len; i++) {
118
+ const a = vecA[i] ?? 0;
119
+ const b = vecB[i] ?? 0;
120
+ dotProduct += a * b;
121
+ normA += a * a;
122
+ normB += b * b;
123
+ }
124
+ if (normA === 0 || normB === 0)
125
+ return 0;
126
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
127
+ }
128
+ /**
129
+ * Compute hybrid similarity between query and stored memory.
130
+ */
131
+ export function computeSimilarityScore(queryEmbedding, memoryEmbedding, queryText, memoryText, isNeural) {
132
+ const cosine = Math.max(0, cosineSimilarity(queryEmbedding, memoryEmbedding));
133
+ if (isNeural)
134
+ return cosine;
135
+ // For native semantic vectors: incorporate token and subword stem overlap
136
+ const qWords = String(queryText || '').toLowerCase().match(/[a-z0-9_-]+/g) || [];
137
+ const mWords = new Set(String(memoryText || '').toLowerCase().match(/[a-z0-9_-]+/g) || []);
138
+ let matches = 0;
139
+ for (const w of qWords) {
140
+ if (mWords.has(w)) {
141
+ matches++;
142
+ }
143
+ else if (w.length >= 4) {
144
+ for (const mw of mWords) {
145
+ if (mw.length >= 4 && (mw.includes(w) || w.includes(mw))) {
146
+ matches += 0.8;
147
+ break;
148
+ }
149
+ }
150
+ }
151
+ }
152
+ const overlapRatio = qWords.length > 0 ? (matches / qWords.length) : 0;
153
+ return (cosine * 0.4) + (overlapRatio * 0.6);
154
+ }
155
+ /**
156
+ * Read memory stats from episodic and long-term facts stores.
157
+ */
158
+ export function readExtendedMemoryStats() {
159
+ let episodicCount = 0;
160
+ let factsCount = 0;
161
+ const home = causyneHome();
162
+ try {
163
+ const episodicFile = path.join(home, 'episodic-memory.json');
164
+ if (fs.existsSync(episodicFile)) {
165
+ const data = JSON.parse(fs.readFileSync(episodicFile, 'utf8'));
166
+ episodicCount = Array.isArray(data.observations) ? data.observations.length : 0;
167
+ }
168
+ }
169
+ catch (_) { }
170
+ try {
171
+ const factsFile = path.join(home, 'memory.json');
172
+ if (fs.existsSync(factsFile)) {
173
+ const data = JSON.parse(fs.readFileSync(factsFile, 'utf8'));
174
+ factsCount = Array.isArray(data.facts) ? data.facts.length : 0;
175
+ }
176
+ }
177
+ catch (_) { }
178
+ return { episodicCount, factsCount };
179
+ }
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Sovereign Cortex Engine — Native Zero-Dependency SQLite & Semantic Vectors.
3
+ *
4
+ * Provides instant, production-grade memory persistence and semantic vector retrieval
5
+ * across all development environments and platforms with zero required npm packages,
6
+ * using Node.js built-in SQLite and deterministic semantic feature hashing.
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { causyneHome } from '../utils/paths.js';
12
+
13
+ export interface CortexDbStatement {
14
+ run(...params: unknown[]): { changes: number; lastInsertRowid: number | bigint };
15
+ get(...params: unknown[]): any;
16
+ all(...params: unknown[]): any[];
17
+ }
18
+
19
+ export interface CortexDatabase {
20
+ exec(sql: string): void;
21
+ prepare(sql: string): CortexDbStatement;
22
+ transaction(fn: (...args: any[]) => any): (...args: any[]) => any;
23
+ close?(): void;
24
+ }
25
+
26
+ /**
27
+ * Open or create the SQLite database for Cortex using native Node SQLite or better-sqlite3.
28
+ */
29
+ export async function openCortexDatabase(dbPath: string): Promise<CortexDatabase> {
30
+ const dir = path.dirname(dbPath);
31
+ if (!fs.existsSync(dir)) {
32
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
33
+ }
34
+
35
+ // 1. Prefer Node.js native `node:sqlite` (Node 22+)
36
+ try {
37
+ const sqliteModule = await import('node:sqlite');
38
+ if (sqliteModule && typeof sqliteModule.DatabaseSync === 'function') {
39
+ const dbInstance = new sqliteModule.DatabaseSync(dbPath);
40
+ // Ensure transaction helper is available
41
+ if (typeof (dbInstance as any).transaction !== 'function') {
42
+ (dbInstance as any).transaction = function (fn: (...args: any[]) => any) {
43
+ return function (...args: any[]) {
44
+ dbInstance.exec('BEGIN IMMEDIATE');
45
+ try {
46
+ const res = fn(...args);
47
+ dbInstance.exec('COMMIT');
48
+ return res;
49
+ } catch (err) {
50
+ try {
51
+ dbInstance.exec('ROLLBACK');
52
+ } catch (_) {}
53
+ throw err;
54
+ }
55
+ };
56
+ };
57
+ }
58
+ return dbInstance as unknown as CortexDatabase;
59
+ }
60
+ } catch (_e) {
61
+ // Native node:sqlite unavailable or disabled; fall through to optional provider
62
+ }
63
+
64
+ // 2. Check for optional better-sqlite3 in cortex package
65
+ try {
66
+ const { requireCortexModule } = await import('./provisioner.js');
67
+ const DatabaseConstructor = await requireCortexModule('better-sqlite3');
68
+ if (DatabaseConstructor) {
69
+ return new DatabaseConstructor(dbPath) as CortexDatabase;
70
+ }
71
+ } catch (_e) {
72
+ // better-sqlite3 not provisioned
73
+ }
74
+
75
+ throw new Error('SQLite engine unavailable. Node 22+ with node:sqlite or better-sqlite3 is required for Cortex.');
76
+ }
77
+
78
+ /**
79
+ * Deterministic string hash (FNV-1a 32-bit).
80
+ */
81
+ function fnv1a32(str: string): number {
82
+ let h = 2166136261 >>> 0;
83
+ for (let i = 0; i < str.length; i++) {
84
+ h ^= str.charCodeAt(i);
85
+ h = Math.imul(h, 16777619) >>> 0;
86
+ }
87
+ return h;
88
+ }
89
+
90
+ /**
91
+ * Native, zero-dependency 128-dimensional semantic feature hashing embedding.
92
+ * Captures word tokens, character trigrams, and morphology with unit L2 normalization.
93
+ */
94
+ export function computeNativeEmbedding(text: string, dims = 128): number[] {
95
+ const vec = new Float64Array(dims);
96
+ const words = String(text || '').toLowerCase().match(/[a-z0-9_#.-]+/g) || [];
97
+
98
+ for (const word of words) {
99
+ const h = fnv1a32(word);
100
+ const idx = h % dims;
101
+ const sign = (fnv1a32(word + '_s') & 1) ? 1 : -1;
102
+ vec[idx] = (vec[idx] ?? 0) + sign * 2.0;
103
+
104
+ if (word.length >= 3) {
105
+ for (let i = 0; i <= word.length - 3; i++) {
106
+ const tri = word.slice(i, i + 3);
107
+ const th = fnv1a32(tri);
108
+ const tidx = th % dims;
109
+ const tsign = (fnv1a32(tri + '_s') & 1) ? 1 : -1;
110
+ vec[tidx] = (vec[tidx] ?? 0) + tsign * 0.5;
111
+ }
112
+ }
113
+ }
114
+
115
+ let norm = 0;
116
+ for (let i = 0; i < dims; i++) {
117
+ const v = vec[i] ?? 0;
118
+ norm += v * v;
119
+ }
120
+ norm = Math.sqrt(norm);
121
+ if (norm > 0) {
122
+ for (let i = 0; i < dims; i++) {
123
+ vec[i] = (vec[i] ?? 0) / norm;
124
+ }
125
+ }
126
+ return Array.from(vec);
127
+ }
128
+
129
+ /**
130
+ * Exact cosine similarity between two float vectors.
131
+ */
132
+ export function cosineSimilarity(vecA: number[], vecB: number[]): number {
133
+ let dotProduct = 0;
134
+ let normA = 0;
135
+ let normB = 0;
136
+ const len = Math.min(vecA.length, vecB.length);
137
+ for (let i = 0; i < len; i++) {
138
+ const a = vecA[i] ?? 0;
139
+ const b = vecB[i] ?? 0;
140
+ dotProduct += a * b;
141
+ normA += a * a;
142
+ normB += b * b;
143
+ }
144
+ if (normA === 0 || normB === 0) return 0;
145
+ return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
146
+ }
147
+
148
+ /**
149
+ * Compute hybrid similarity between query and stored memory.
150
+ */
151
+ export function computeSimilarityScore(
152
+ queryEmbedding: number[],
153
+ memoryEmbedding: number[],
154
+ queryText: string,
155
+ memoryText: string,
156
+ isNeural: boolean
157
+ ): number {
158
+ const cosine = Math.max(0, cosineSimilarity(queryEmbedding, memoryEmbedding));
159
+ if (isNeural) return cosine;
160
+
161
+ // For native semantic vectors: incorporate token and subword stem overlap
162
+ const qWords = String(queryText || '').toLowerCase().match(/[a-z0-9_-]+/g) || [];
163
+ const mWords = new Set(String(memoryText || '').toLowerCase().match(/[a-z0-9_-]+/g) || []);
164
+
165
+ let matches = 0;
166
+ for (const w of qWords) {
167
+ if (mWords.has(w)) {
168
+ matches++;
169
+ } else if (w.length >= 4) {
170
+ for (const mw of mWords) {
171
+ if (mw.length >= 4 && (mw.includes(w) || w.includes(mw))) {
172
+ matches += 0.8;
173
+ break;
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ const overlapRatio = qWords.length > 0 ? (matches / qWords.length) : 0;
180
+ return (cosine * 0.4) + (overlapRatio * 0.6);
181
+ }
182
+
183
+ /**
184
+ * Read memory stats from episodic and long-term facts stores.
185
+ */
186
+ export function readExtendedMemoryStats(): { episodicCount: number; factsCount: number } {
187
+ let episodicCount = 0;
188
+ let factsCount = 0;
189
+ const home = causyneHome();
190
+
191
+ try {
192
+ const episodicFile = path.join(home, 'episodic-memory.json');
193
+ if (fs.existsSync(episodicFile)) {
194
+ const data = JSON.parse(fs.readFileSync(episodicFile, 'utf8'));
195
+ episodicCount = Array.isArray(data.observations) ? data.observations.length : 0;
196
+ }
197
+ } catch (_) {}
198
+
199
+ try {
200
+ const factsFile = path.join(home, 'memory.json');
201
+ if (fs.existsSync(factsFile)) {
202
+ const data = JSON.parse(fs.readFileSync(factsFile, 'utf8'));
203
+ factsCount = Array.isArray(data.facts) ? data.facts.length : 0;
204
+ }
205
+ } catch (_) {}
206
+
207
+ return { episodicCount, factsCount };
208
+ }
209
+
@@ -3,25 +3,23 @@ import path from 'node:path';
3
3
  import { createRequire } from 'node:module';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { causyneHome } from '../utils/paths.js';
6
-
7
6
  const CORTEX_DIR = path.join(causyneHome(), 'cortex');
8
-
9
7
  // Read-only check. The legacy implementation silently ran npm during memory
10
8
  // initialization. Optional native packages now require explicit manual setup.
11
9
  export async function provisionCortexDependencies() {
12
- for (const name of ['better-sqlite3', '@xenova/transformers']) {
13
- if (!fs.existsSync(path.join(CORTEX_DIR, 'node_modules', name))) {
14
- throw new Error('Optional Cortex dependencies are not installed. Automatic installation is disabled; see docs/OPTIONAL_CAPABILITIES.md. Standard local session memory remains available.');
10
+ const allowed = ['better-sqlite3'];
11
+ for (const name of allowed) {
12
+ if (!fs.existsSync(path.join(CORTEX_DIR, 'node_modules', name))) {
13
+ throw new Error('Optional Cortex dependencies are not installed. Automatic installation is disabled; see docs/OPTIONAL_CAPABILITIES.md. Standard local session memory remains available.');
14
+ }
15
15
  }
16
- }
17
16
  }
18
-
19
17
  export async function requireCortexModule(moduleName) {
20
- if (!['better-sqlite3', '@xenova/transformers'].includes(moduleName)) {
21
- throw new Error(`Unsupported Cortex module: ${moduleName}`);
22
- }
23
- const require = createRequire(path.join(CORTEX_DIR, 'package.json'));
24
- const resolved = require.resolve(moduleName);
25
- const mod = await import(pathToFileURL(resolved).href);
26
- return mod.default || mod;
18
+ if (moduleName !== 'better-sqlite3') {
19
+ throw new Error(`Unsupported Cortex module: ${moduleName}`);
20
+ }
21
+ const req = createRequire(path.join(CORTEX_DIR, 'package.json'));
22
+ const resolved = req.resolve(moduleName);
23
+ const mod = await import(pathToFileURL(resolved).href);
24
+ return mod.default || mod;
27
25
  }
@@ -0,0 +1,29 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { causyneHome } from '../utils/paths.js';
6
+
7
+ const CORTEX_DIR = path.join(causyneHome(), 'cortex');
8
+
9
+ // Read-only check. The legacy implementation silently ran npm during memory
10
+ // initialization. Optional native packages now require explicit manual setup.
11
+ export async function provisionCortexDependencies(): Promise<void> {
12
+ const allowed = ['better-sqlite3'];
13
+ for (const name of allowed) {
14
+ if (!fs.existsSync(path.join(CORTEX_DIR, 'node_modules', name))) {
15
+ throw new Error('Optional Cortex dependencies are not installed. Automatic installation is disabled; see docs/OPTIONAL_CAPABILITIES.md. Standard local session memory remains available.');
16
+ }
17
+ }
18
+ }
19
+
20
+ export async function requireCortexModule(moduleName: string): Promise<any> {
21
+ if (moduleName !== 'better-sqlite3') {
22
+ throw new Error(`Unsupported Cortex module: ${moduleName}`);
23
+ }
24
+ const req = createRequire(path.join(CORTEX_DIR, 'package.json'));
25
+ const resolved = req.resolve(moduleName);
26
+ const mod = await import(pathToFileURL(resolved).href);
27
+ return mod.default || mod;
28
+ }
29
+