web-agent-bridge 3.2.0 → 3.3.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 (202) hide show
  1. package/LICENSE +72 -72
  2. package/README.ar.md +1286 -1152
  3. package/README.md +1764 -1635
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -138
  6. package/bin/wab.js +80 -80
  7. package/examples/bidi-agent.js +119 -119
  8. package/examples/cross-site-agent.js +91 -91
  9. package/examples/mcp-agent.js +94 -94
  10. package/examples/next-app-router/README.md +44 -44
  11. package/examples/puppeteer-agent.js +108 -108
  12. package/examples/saas-dashboard/README.md +55 -55
  13. package/examples/shopify-hydrogen/README.md +74 -74
  14. package/examples/vision-agent.js +171 -171
  15. package/examples/wordpress-elementor/README.md +77 -77
  16. package/package.json +16 -3
  17. package/public/.well-known/agent-tools.json +180 -180
  18. package/public/.well-known/ai-assets.json +59 -59
  19. package/public/.well-known/security.txt +8 -0
  20. package/public/agent-workspace.html +349 -349
  21. package/public/ai.html +198 -198
  22. package/public/api.html +413 -412
  23. package/public/browser.html +486 -486
  24. package/public/commander-dashboard.html +243 -243
  25. package/public/cookies.html +210 -210
  26. package/public/css/agent-workspace.css +1713 -1713
  27. package/public/css/premium.css +317 -317
  28. package/public/css/styles.css +1235 -1235
  29. package/public/dashboard.html +706 -706
  30. package/public/dns.html +507 -0
  31. package/public/docs.html +587 -587
  32. package/public/feed.xml +89 -89
  33. package/public/growth.html +463 -463
  34. package/public/index.html +1070 -982
  35. package/public/integrations.html +556 -0
  36. package/public/js/agent-workspace.js +1740 -1740
  37. package/public/js/auth-nav.js +31 -31
  38. package/public/js/auth-redirect.js +12 -12
  39. package/public/js/cookie-consent.js +56 -56
  40. package/public/js/wab-demo-page.js +721 -721
  41. package/public/js/ws-client.js +74 -74
  42. package/public/llms-full.txt +360 -360
  43. package/public/llms.txt +125 -125
  44. package/public/login.html +85 -85
  45. package/public/mesh-dashboard.html +328 -328
  46. package/public/openapi.json +580 -580
  47. package/public/phone-shield.html +281 -0
  48. package/public/premium-dashboard.html +2489 -2489
  49. package/public/premium.html +793 -793
  50. package/public/privacy.html +297 -297
  51. package/public/register.html +105 -105
  52. package/public/robots.txt +87 -87
  53. package/public/script/wab-consent.d.ts +36 -36
  54. package/public/script/wab-consent.js +104 -104
  55. package/public/script/wab-schema.js +131 -131
  56. package/public/script/wab.d.ts +108 -108
  57. package/public/script/wab.min.js +580 -580
  58. package/public/security.txt +8 -0
  59. package/public/terms.html +256 -256
  60. package/script/ai-agent-bridge.js +1754 -1754
  61. package/sdk/README.md +99 -99
  62. package/sdk/agent-mesh.js +449 -449
  63. package/sdk/commander.js +262 -262
  64. package/sdk/index.d.ts +464 -464
  65. package/sdk/index.js +12 -1
  66. package/sdk/multi-agent.js +318 -318
  67. package/sdk/package.json +1 -1
  68. package/sdk/safety-shield.js +219 -0
  69. package/sdk/schema-discovery.js +83 -83
  70. package/server/adapters/index.js +520 -520
  71. package/server/config/plans.js +367 -367
  72. package/server/config/secrets.js +102 -102
  73. package/server/control-plane/index.js +301 -301
  74. package/server/data-plane/index.js +354 -354
  75. package/server/index.js +531 -427
  76. package/server/llm/index.js +404 -404
  77. package/server/middleware/adminAuth.js +35 -35
  78. package/server/middleware/auth.js +50 -50
  79. package/server/middleware/featureGate.js +88 -88
  80. package/server/middleware/rateLimits.js +100 -100
  81. package/server/middleware/sensitiveAction.js +157 -0
  82. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  83. package/server/migrations/002_premium_features.sql +418 -418
  84. package/server/migrations/003_ads_integer_cents.sql +33 -33
  85. package/server/migrations/004_agent_os.sql +158 -158
  86. package/server/migrations/005_marketplace_metering.sql +126 -126
  87. package/server/models/adapters/index.js +33 -33
  88. package/server/models/adapters/mysql.js +183 -183
  89. package/server/models/adapters/postgresql.js +172 -172
  90. package/server/models/adapters/sqlite.js +7 -7
  91. package/server/models/db.js +681 -681
  92. package/server/observability/failure-analysis.js +337 -337
  93. package/server/observability/index.js +394 -394
  94. package/server/protocol/capabilities.js +223 -223
  95. package/server/protocol/index.js +243 -243
  96. package/server/protocol/schema.js +584 -584
  97. package/server/registry/certification.js +271 -271
  98. package/server/registry/index.js +326 -326
  99. package/server/routes/admin-premium.js +671 -671
  100. package/server/routes/admin.js +261 -261
  101. package/server/routes/ads.js +130 -130
  102. package/server/routes/agent-workspace.js +540 -540
  103. package/server/routes/api.js +150 -150
  104. package/server/routes/auth.js +71 -71
  105. package/server/routes/billing.js +45 -45
  106. package/server/routes/commander.js +316 -316
  107. package/server/routes/demo-showcase.js +332 -332
  108. package/server/routes/demo-store.js +154 -0
  109. package/server/routes/discovery.js +417 -417
  110. package/server/routes/gateway.js +173 -157
  111. package/server/routes/license.js +251 -240
  112. package/server/routes/mesh.js +469 -469
  113. package/server/routes/noscript.js +543 -543
  114. package/server/routes/premium-v2.js +686 -686
  115. package/server/routes/premium.js +724 -724
  116. package/server/routes/runtime.js +2148 -2147
  117. package/server/routes/sovereign.js +465 -385
  118. package/server/routes/universal.js +200 -185
  119. package/server/routes/wab-api.js +850 -501
  120. package/server/runtime/container-worker.js +111 -111
  121. package/server/runtime/container.js +448 -448
  122. package/server/runtime/distributed-worker.js +362 -362
  123. package/server/runtime/event-bus.js +210 -210
  124. package/server/runtime/index.js +253 -253
  125. package/server/runtime/queue.js +599 -599
  126. package/server/runtime/replay.js +666 -666
  127. package/server/runtime/sandbox.js +266 -266
  128. package/server/runtime/scheduler.js +534 -534
  129. package/server/runtime/session-engine.js +293 -293
  130. package/server/runtime/state-manager.js +188 -188
  131. package/server/security/cross-site-redactor.js +196 -0
  132. package/server/security/dry-run.js +180 -0
  133. package/server/security/human-gate-rate-limit.js +147 -0
  134. package/server/security/human-gate-transports.js +178 -0
  135. package/server/security/human-gate.js +281 -0
  136. package/server/security/index.js +368 -368
  137. package/server/security/intent-engine.js +245 -0
  138. package/server/security/reward-guard.js +171 -0
  139. package/server/security/rollback-store.js +239 -0
  140. package/server/security/token-scope.js +404 -0
  141. package/server/security/url-policy.js +139 -0
  142. package/server/services/agent-chat.js +506 -506
  143. package/server/services/agent-learning.js +601 -575
  144. package/server/services/agent-memory.js +625 -625
  145. package/server/services/agent-mesh.js +555 -539
  146. package/server/services/agent-symphony.js +717 -717
  147. package/server/services/agent-tasks.js +1807 -1807
  148. package/server/services/api-key-engine.js +292 -261
  149. package/server/services/cluster.js +894 -894
  150. package/server/services/commander.js +738 -738
  151. package/server/services/edge-compute.js +440 -440
  152. package/server/services/email.js +204 -204
  153. package/server/services/hosted-runtime.js +205 -205
  154. package/server/services/lfd.js +635 -635
  155. package/server/services/local-ai.js +389 -389
  156. package/server/services/marketplace.js +270 -270
  157. package/server/services/metering.js +182 -182
  158. package/server/services/modules/affiliate-intelligence.js +93 -93
  159. package/server/services/modules/agent-firewall.js +90 -90
  160. package/server/services/modules/bounty.js +89 -89
  161. package/server/services/modules/collective-bargaining.js +92 -92
  162. package/server/services/modules/dark-pattern.js +66 -66
  163. package/server/services/modules/gov-intelligence.js +45 -45
  164. package/server/services/modules/neural.js +55 -55
  165. package/server/services/modules/notary.js +49 -49
  166. package/server/services/modules/price-time-machine.js +86 -86
  167. package/server/services/modules/protocol.js +104 -104
  168. package/server/services/negotiation.js +439 -439
  169. package/server/services/plugins.js +771 -771
  170. package/server/services/price-intelligence.js +566 -566
  171. package/server/services/price-shield.js +1137 -1137
  172. package/server/services/reputation.js +465 -465
  173. package/server/services/search-engine.js +357 -357
  174. package/server/services/security.js +513 -513
  175. package/server/services/self-healing.js +843 -843
  176. package/server/services/sovereign-shield.js +542 -0
  177. package/server/services/stripe.js +192 -192
  178. package/server/services/swarm.js +788 -788
  179. package/server/services/universal-scraper.js +662 -661
  180. package/server/services/verification.js +481 -481
  181. package/server/services/vision.js +1163 -1163
  182. package/server/utils/cache.js +125 -125
  183. package/server/utils/migrate.js +81 -81
  184. package/server/utils/safe-fetch.js +228 -0
  185. package/server/utils/secureFields.js +50 -50
  186. package/server/ws.js +161 -161
  187. package/templates/artisan-marketplace.yaml +104 -104
  188. package/templates/book-price-scout.yaml +98 -98
  189. package/templates/electronics-price-tracker.yaml +108 -108
  190. package/templates/flight-deal-hunter.yaml +113 -113
  191. package/templates/freelancer-direct.yaml +116 -116
  192. package/templates/grocery-price-compare.yaml +93 -93
  193. package/templates/hotel-direct-booking.yaml +113 -113
  194. package/templates/local-services.yaml +98 -98
  195. package/templates/olive-oil-tunisia.yaml +88 -88
  196. package/templates/organic-farm-fresh.yaml +101 -101
  197. package/templates/restaurant-direct.yaml +97 -97
  198. package/public/score.html +0 -263
  199. package/server/migrations/006_growth_suite.sql +0 -138
  200. package/server/routes/growth.js +0 -962
  201. package/server/services/fairness-engine.js +0 -409
  202. package/server/services/fairness.js +0 -420
@@ -1,625 +1,625 @@
1
- 'use strict';
2
-
3
- const { db } = require('../models/db');
4
- const { randomUUID } = require('crypto');
5
-
6
- // ─── Schema ──────────────────────────────────────────────────────────────────
7
-
8
- db.exec(`
9
- CREATE TABLE IF NOT EXISTS agent_memories (
10
- id TEXT PRIMARY KEY,
11
- site_id TEXT NOT NULL,
12
- agent_id TEXT NOT NULL,
13
- memory_type TEXT CHECK(memory_type IN ('preference','interaction','correction','pattern')),
14
- category TEXT CHECK(category IN ('navigation','purchase','search','form','custom')),
15
- key TEXT NOT NULL,
16
- value TEXT NOT NULL,
17
- embedding TEXT,
18
- importance REAL DEFAULT 0.5,
19
- access_count INTEGER DEFAULT 0,
20
- last_accessed TEXT,
21
- expires_at TEXT,
22
- created_at TEXT DEFAULT (datetime('now')),
23
- updated_at TEXT DEFAULT (datetime('now')),
24
- FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
25
- );
26
-
27
- CREATE TABLE IF NOT EXISTS memory_sessions (
28
- id TEXT PRIMARY KEY,
29
- site_id TEXT,
30
- agent_id TEXT,
31
- context TEXT,
32
- started_at TEXT DEFAULT (datetime('now')),
33
- ended_at TEXT
34
- );
35
-
36
- CREATE TABLE IF NOT EXISTS memory_associations (
37
- id TEXT PRIMARY KEY,
38
- source_memory_id TEXT,
39
- target_memory_id TEXT,
40
- relationship TEXT CHECK(relationship IN ('leads_to','similar_to','replaces','depends_on')),
41
- strength REAL DEFAULT 0.5,
42
- created_at TEXT DEFAULT (datetime('now')),
43
- FOREIGN KEY (source_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE,
44
- FOREIGN KEY (target_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE
45
- );
46
-
47
- CREATE INDEX IF NOT EXISTS idx_mem_site ON agent_memories(site_id);
48
- CREATE INDEX IF NOT EXISTS idx_mem_agent ON agent_memories(agent_id);
49
- CREATE INDEX IF NOT EXISTS idx_mem_type ON agent_memories(memory_type);
50
- CREATE INDEX IF NOT EXISTS idx_mem_category ON agent_memories(category);
51
- CREATE INDEX IF NOT EXISTS idx_mem_importance ON agent_memories(importance);
52
- CREATE INDEX IF NOT EXISTS idx_mem_sessions_site ON memory_sessions(site_id);
53
- CREATE INDEX IF NOT EXISTS idx_mem_sessions_agent ON memory_sessions(agent_id);
54
- CREATE INDEX IF NOT EXISTS idx_mem_assoc_source ON memory_associations(source_memory_id);
55
- CREATE INDEX IF NOT EXISTS idx_mem_assoc_target ON memory_associations(target_memory_id);
56
- `);
57
-
58
- // ─── Prepared Statements ─────────────────────────────────────────────────────
59
-
60
- const stmts = {
61
- insertMemory: db.prepare(`
62
- INSERT INTO agent_memories (id, site_id, agent_id, memory_type, category, key, value, embedding, importance, expires_at)
63
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
- `),
65
- getMemory: db.prepare(`SELECT * FROM agent_memories WHERE id = ?`),
66
- queryMemories: db.prepare(`
67
- SELECT * FROM agent_memories
68
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
69
- ORDER BY importance DESC, updated_at DESC
70
- `),
71
- queryByCategory: db.prepare(`
72
- SELECT * FROM agent_memories
73
- WHERE site_id = ? AND agent_id = ? AND category = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
74
- ORDER BY importance DESC, updated_at DESC
75
- `),
76
- queryByType: db.prepare(`
77
- SELECT * FROM agent_memories
78
- WHERE site_id = ? AND agent_id = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
79
- ORDER BY importance DESC, updated_at DESC
80
- `),
81
- queryByCategoryAndType: db.prepare(`
82
- SELECT * FROM agent_memories
83
- WHERE site_id = ? AND agent_id = ? AND category = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
84
- ORDER BY importance DESC, updated_at DESC
85
- `),
86
- touchMemory: db.prepare(`
87
- UPDATE agent_memories SET access_count = access_count + 1, last_accessed = datetime('now') WHERE id = ?
88
- `),
89
- softDelete: db.prepare(`
90
- UPDATE agent_memories SET expires_at = datetime('now'), updated_at = datetime('now') WHERE id = ?
91
- `),
92
- updateImportance: db.prepare(`
93
- UPDATE agent_memories SET importance = ?, updated_at = datetime('now') WHERE id = ?
94
- `),
95
- deleteExpired: db.prepare(`
96
- DELETE FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')
97
- `),
98
- findDuplicates: db.prepare(`
99
- SELECT key, category, COUNT(*) as cnt, GROUP_CONCAT(id) as ids
100
- FROM agent_memories
101
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
102
- GROUP BY key, category HAVING cnt > 1
103
- `),
104
- deleteMemoryById: db.prepare(`DELETE FROM agent_memories WHERE id = ?`),
105
-
106
- insertAssociation: db.prepare(`
107
- INSERT INTO memory_associations (id, source_memory_id, target_memory_id, relationship, strength)
108
- VALUES (?, ?, ?, ?, ?)
109
- `),
110
- getAssociationsFrom: db.prepare(`
111
- SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
112
- FROM memory_associations ma
113
- JOIN agent_memories am ON am.id = ma.target_memory_id
114
- WHERE ma.source_memory_id = ?
115
- ORDER BY ma.strength DESC
116
- `),
117
- getAssociationsFromFiltered: db.prepare(`
118
- SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
119
- FROM memory_associations ma
120
- JOIN agent_memories am ON am.id = ma.target_memory_id
121
- WHERE ma.source_memory_id = ? AND ma.relationship = ?
122
- ORDER BY ma.strength DESC
123
- `),
124
-
125
- insertSession: db.prepare(`
126
- INSERT INTO memory_sessions (id, site_id, agent_id, context) VALUES (?, ?, ?, ?)
127
- `),
128
- endSession: db.prepare(`
129
- UPDATE memory_sessions SET ended_at = datetime('now'), context = json_patch(COALESCE(context, '{}'), ?) WHERE id = ?
130
- `),
131
- getSessionHistory: db.prepare(`
132
- SELECT * FROM memory_sessions WHERE site_id = ? AND agent_id = ? ORDER BY started_at DESC LIMIT ?
133
- `),
134
-
135
- countAll: db.prepare(`
136
- SELECT COUNT(*) as total FROM agent_memories WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
137
- `),
138
- countByType: db.prepare(`
139
- SELECT memory_type, COUNT(*) as count FROM agent_memories
140
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
141
- GROUP BY memory_type
142
- `),
143
- countByCategory: db.prepare(`
144
- SELECT category, COUNT(*) as count FROM agent_memories
145
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
146
- GROUP BY category
147
- `),
148
- avgImportance: db.prepare(`
149
- SELECT AVG(importance) as avg FROM agent_memories
150
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
151
- `),
152
- storageEstimate: db.prepare(`
153
- SELECT SUM(LENGTH(key) + LENGTH(value) + COALESCE(LENGTH(embedding), 0)) as bytes
154
- FROM agent_memories WHERE site_id = ? AND agent_id = ?
155
- `),
156
-
157
- allActiveMemories: db.prepare(`
158
- SELECT * FROM agent_memories
159
- WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
160
- ORDER BY created_at ASC
161
- `),
162
- getPreferences: db.prepare(`
163
- SELECT * FROM agent_memories
164
- WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND (expires_at IS NULL OR expires_at > datetime('now'))
165
- ORDER BY importance DESC
166
- `),
167
- findPreference: db.prepare(`
168
- SELECT * FROM agent_memories
169
- WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND key = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
170
- LIMIT 1
171
- `),
172
- updateMemoryValue: db.prepare(`
173
- UPDATE agent_memories SET value = ?, embedding = ?, importance = ?, updated_at = datetime('now') WHERE id = ?
174
- `),
175
- };
176
-
177
- // ─── Vector Utilities ────────────────────────────────────────────────────────
178
-
179
- const EMBED_DIM = 128;
180
-
181
- /**
182
- * Tokenizes text into lowercase alphanumeric tokens.
183
- * @param {string} text
184
- * @returns {string[]}
185
- */
186
- function tokenize(text) {
187
- return String(text).toLowerCase().match(/[a-z0-9]+/g) || [];
188
- }
189
-
190
- /**
191
- * Deterministic hash of a string to a 32-bit unsigned integer.
192
- * @param {string} str
193
- * @returns {number}
194
- */
195
- function hashStr(str) {
196
- let h = 0x811c9dc5;
197
- for (let i = 0; i < str.length; i++) {
198
- h ^= str.charCodeAt(i);
199
- h = Math.imul(h, 0x01000193);
200
- }
201
- return h >>> 0;
202
- }
203
-
204
- /**
205
- * Computes a TF-IDF-style embedding: hashes tokens into a fixed-size vector and L2-normalizes.
206
- * @param {string} text
207
- * @returns {number[]} 128-dimensional unit vector
208
- */
209
- function computeEmbedding(text) {
210
- const tokens = tokenize(text);
211
- const vec = new Float64Array(EMBED_DIM);
212
- if (tokens.length === 0) return Array.from(vec);
213
-
214
- const tf = {};
215
- for (const t of tokens) tf[t] = (tf[t] || 0) + 1;
216
-
217
- for (const [token, count] of Object.entries(tf)) {
218
- const idx = hashStr(token) % EMBED_DIM;
219
- const sign = (hashStr(token + '_sign') & 1) ? 1 : -1;
220
- const weight = (1 + Math.log(count)) * sign;
221
- vec[idx] += weight;
222
- }
223
-
224
- let norm = 0;
225
- for (let i = 0; i < EMBED_DIM; i++) norm += vec[i] * vec[i];
226
- norm = Math.sqrt(norm);
227
- if (norm > 0) for (let i = 0; i < EMBED_DIM; i++) vec[i] /= norm;
228
-
229
- return Array.from(vec);
230
- }
231
-
232
- /**
233
- * Standard cosine similarity between two equal-length vectors.
234
- * @param {number[]} a
235
- * @param {number[]} b
236
- * @returns {number} similarity in [-1, 1]
237
- */
238
- function cosineSimilarity(a, b) {
239
- if (!a || !b || a.length !== b.length) return 0;
240
- let dot = 0, normA = 0, normB = 0;
241
- for (let i = 0; i < a.length; i++) {
242
- dot += a[i] * b[i];
243
- normA += a[i] * a[i];
244
- normB += b[i] * b[i];
245
- }
246
- const denom = Math.sqrt(normA) * Math.sqrt(normB);
247
- return denom === 0 ? 0 : dot / denom;
248
- }
249
-
250
- // ─── Core Memory Operations ──────────────────────────────────────────────────
251
-
252
- /**
253
- * Stores a memory entry for an agent on a site.
254
- * @param {string} siteId
255
- * @param {string} agentId
256
- * @param {{ type?: string, category?: string, key: string, value: any, importance?: number, ttlSeconds?: number }} opts
257
- * @returns {object} the stored memory row
258
- */
259
- function storeMemory(siteId, agentId, { type, category, key, value, importance, ttlSeconds }) {
260
- const id = randomUUID();
261
- const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
262
- const embedding = computeEmbedding(`${key} ${typeof value === 'string' ? value : JSON.stringify(value)}`);
263
- const expiresAt = ttlSeconds
264
- ? new Date(Date.now() + ttlSeconds * 1000).toISOString().replace('T', ' ').slice(0, 19)
265
- : null;
266
-
267
- stmts.insertMemory.run(
268
- id, siteId, agentId,
269
- type || null, category || null,
270
- key, jsonValue,
271
- JSON.stringify(embedding),
272
- importance ?? 0.5,
273
- expiresAt
274
- );
275
-
276
- return stmts.getMemory.get(id);
277
- }
278
-
279
- /**
280
- * Recalls memories matching filters, optionally ranked by semantic similarity.
281
- * @param {string} siteId
282
- * @param {string} agentId
283
- * @param {{ query?: string, category?: string, type?: string, limit?: number, minImportance?: number }} opts
284
- * @returns {object[]}
285
- */
286
- function recallMemories(siteId, agentId, { query, category, type, limit, minImportance } = {}) {
287
- let rows;
288
- if (category && type) {
289
- rows = stmts.queryByCategoryAndType.all(siteId, agentId, category, type);
290
- } else if (category) {
291
- rows = stmts.queryByCategory.all(siteId, agentId, category);
292
- } else if (type) {
293
- rows = stmts.queryByType.all(siteId, agentId, type);
294
- } else {
295
- rows = stmts.queryMemories.all(siteId, agentId);
296
- }
297
-
298
- if (minImportance != null) {
299
- rows = rows.filter(r => r.importance >= minImportance);
300
- }
301
-
302
- if (query) {
303
- const queryEmbed = computeEmbedding(query);
304
- rows = rows.map(r => {
305
- const memEmbed = r.embedding ? JSON.parse(r.embedding) : null;
306
- const similarity = memEmbed ? cosineSimilarity(queryEmbed, memEmbed) : 0;
307
- return { ...r, similarity };
308
- });
309
- rows.sort((a, b) => b.similarity - a.similarity);
310
- }
311
-
312
- const maxRows = limit || 20;
313
- rows = rows.slice(0, maxRows);
314
-
315
- const touchTx = db.transaction((ids) => {
316
- for (const id of ids) stmts.touchMemory.run(id);
317
- });
318
- touchTx(rows.map(r => r.id));
319
-
320
- return rows;
321
- }
322
-
323
- // ─── Associations ────────────────────────────────────────────────────────────
324
-
325
- /**
326
- * Creates a directional link between two memories.
327
- * @param {string} sourceId
328
- * @param {string} targetId
329
- * @param {string} relationship - leads_to | similar_to | replaces | depends_on
330
- * @param {number} [strength=0.5]
331
- * @returns {object}
332
- */
333
- function associateMemories(sourceId, targetId, relationship, strength = 0.5) {
334
- const id = randomUUID();
335
- stmts.insertAssociation.run(id, sourceId, targetId, relationship, strength);
336
- return { id, sourceId, targetId, relationship, strength };
337
- }
338
-
339
- /**
340
- * Retrieves memories associated with a given memory.
341
- * @param {string} memoryId
342
- * @param {{ relationship?: string, minStrength?: number }} [opts]
343
- * @returns {object[]}
344
- */
345
- function getAssociatedMemories(memoryId, { relationship, minStrength } = {}) {
346
- let rows;
347
- if (relationship) {
348
- rows = stmts.getAssociationsFromFiltered.all(memoryId, relationship);
349
- } else {
350
- rows = stmts.getAssociationsFrom.all(memoryId);
351
- }
352
- if (minStrength != null) {
353
- rows = rows.filter(r => r.strength >= minStrength);
354
- }
355
- return rows;
356
- }
357
-
358
- // ─── Lifecycle ───────────────────────────────────────────────────────────────
359
-
360
- /**
361
- * Soft-deletes a memory by setting its expiration to now.
362
- * @param {string} memoryId
363
- * @returns {boolean}
364
- */
365
- function forgetMemory(memoryId) {
366
- const info = stmts.softDelete.run(memoryId);
367
- return info.changes > 0;
368
- }
369
-
370
- /**
371
- * Consolidates memories: merges duplicates, adjusts importance, purges expired.
372
- * @param {string} siteId
373
- * @param {string} agentId
374
- * @returns {{ merged: number, boosted: number, decayed: number, expired: number }}
375
- */
376
- function consolidateMemories(siteId, agentId) {
377
- const stats = { merged: 0, boosted: 0, decayed: 0, expired: 0 };
378
-
379
- const expiredInfo = stmts.deleteExpired.run();
380
- stats.expired = expiredInfo.changes;
381
-
382
- const dupes = stmts.findDuplicates.all(siteId, agentId);
383
- const mergeTx = db.transaction(() => {
384
- for (const group of dupes) {
385
- const ids = group.ids.split(',');
386
- const memories = ids.map(id => stmts.getMemory.get(id)).filter(Boolean);
387
- if (memories.length < 2) continue;
388
-
389
- memories.sort((a, b) => b.access_count - a.access_count || b.importance - a.importance);
390
- const keeper = memories[0];
391
-
392
- let mergedValues;
393
- try {
394
- const parsed = memories.map(m => JSON.parse(m.value));
395
- if (typeof parsed[0] === 'object' && parsed[0] !== null && !Array.isArray(parsed[0])) {
396
- mergedValues = JSON.stringify(Object.assign({}, ...parsed.reverse()));
397
- } else {
398
- mergedValues = keeper.value;
399
- }
400
- } catch {
401
- mergedValues = keeper.value;
402
- }
403
-
404
- const newImportance = Math.min(1, keeper.importance + 0.05 * (memories.length - 1));
405
- const newEmbedding = computeEmbedding(`${keeper.key} ${mergedValues}`);
406
- stmts.updateMemoryValue.run(mergedValues, JSON.stringify(newEmbedding), newImportance, keeper.id);
407
-
408
- for (let i = 1; i < memories.length; i++) {
409
- stmts.deleteMemoryById.run(memories[i].id);
410
- stats.merged++;
411
- }
412
- }
413
- });
414
- mergeTx();
415
-
416
- const active = stmts.allActiveMemories.all(siteId, agentId);
417
- const now = Date.now();
418
-
419
- const adjustTx = db.transaction(() => {
420
- for (const mem of active) {
421
- const ageMs = now - new Date(mem.created_at).getTime();
422
- const ageDays = ageMs / 86400000;
423
-
424
- if (mem.access_count >= 5) {
425
- const boost = Math.min(1, mem.importance + 0.02 * Math.log2(mem.access_count));
426
- if (boost > mem.importance) {
427
- stmts.updateImportance.run(Math.min(1, boost), mem.id);
428
- stats.boosted++;
429
- }
430
- }
431
-
432
- if (ageDays > 30 && mem.access_count < 3) {
433
- const decayFactor = Math.max(0.1, 1 - 0.01 * (ageDays - 30));
434
- const decayed = mem.importance * decayFactor;
435
- if (decayed < mem.importance) {
436
- stmts.updateImportance.run(Math.max(0, decayed), mem.id);
437
- stats.decayed++;
438
- }
439
- }
440
- }
441
- });
442
- adjustTx();
443
-
444
- return stats;
445
- }
446
-
447
- // ─── Stats ───────────────────────────────────────────────────────────────────
448
-
449
- /**
450
- * Returns aggregate statistics for an agent's memories on a site.
451
- * @param {string} siteId
452
- * @param {string} agentId
453
- * @returns {object}
454
- */
455
- function getMemoryStats(siteId, agentId) {
456
- const total = stmts.countAll.get(siteId, agentId).total;
457
- const byType = stmts.countByType.all(siteId, agentId);
458
- const byCategory = stmts.countByCategory.all(siteId, agentId);
459
- const avgImportance = stmts.avgImportance.get(siteId, agentId).avg || 0;
460
- const storageBytes = stmts.storageEstimate.get(siteId, agentId).bytes || 0;
461
-
462
- return {
463
- total,
464
- byType: Object.fromEntries(byType.map(r => [r.memory_type, r.count])),
465
- byCategory: Object.fromEntries(byCategory.map(r => [r.category, r.count])),
466
- avgImportance: Math.round(avgImportance * 1000) / 1000,
467
- storageEstimateBytes: storageBytes,
468
- };
469
- }
470
-
471
- // ─── Sessions ────────────────────────────────────────────────────────────────
472
-
473
- /**
474
- * Starts an agent memory session.
475
- * @param {string} siteId
476
- * @param {string} agentId
477
- * @param {object} [context]
478
- * @returns {{ id: string, siteId: string, agentId: string, startedAt: string }}
479
- */
480
- function startSession(siteId, agentId, context = {}) {
481
- const id = randomUUID();
482
- stmts.insertSession.run(id, siteId, agentId, JSON.stringify(context));
483
- return { id, siteId, agentId, startedAt: new Date().toISOString() };
484
- }
485
-
486
- /**
487
- * Ends a session, optionally attaching a summary to the context.
488
- * @param {string} sessionId
489
- * @param {string} [summary]
490
- * @returns {boolean}
491
- */
492
- function endSession(sessionId, summary) {
493
- const patch = summary ? JSON.stringify({ summary }) : '{}';
494
- const info = stmts.endSession.run(patch, sessionId);
495
- return info.changes > 0;
496
- }
497
-
498
- /**
499
- * Returns recent sessions for a site/agent pair.
500
- * @param {string} siteId
501
- * @param {string} agentId
502
- * @param {{ limit?: number }} [opts]
503
- * @returns {object[]}
504
- */
505
- function getSessionHistory(siteId, agentId, { limit } = {}) {
506
- return stmts.getSessionHistory.all(siteId, agentId, limit || 20);
507
- }
508
-
509
- // ─── Import / Export ─────────────────────────────────────────────────────────
510
-
511
- /**
512
- * Exports all active memories as JSON or CSV.
513
- * @param {string} siteId
514
- * @param {string} agentId
515
- * @param {{ format?: 'json'|'csv' }} [opts]
516
- * @returns {string}
517
- */
518
- function exportMemories(siteId, agentId, { format } = {}) {
519
- const rows = stmts.allActiveMemories.all(siteId, agentId);
520
-
521
- if (format === 'csv') {
522
- const cols = ['id', 'site_id', 'agent_id', 'memory_type', 'category', 'key', 'value', 'importance', 'access_count', 'created_at', 'updated_at'];
523
- const escape = (v) => `"${String(v == null ? '' : v).replace(/"/g, '""')}"`;
524
- const header = cols.join(',');
525
- const lines = rows.map(r => cols.map(c => escape(r[c])).join(','));
526
- return [header, ...lines].join('\n');
527
- }
528
-
529
- return JSON.stringify(rows, null, 2);
530
- }
531
-
532
- /**
533
- * Bulk-imports memories from an array of objects.
534
- * @param {string} siteId
535
- * @param {string} agentId
536
- * @param {object[]} data
537
- * @returns {{ imported: number }}
538
- */
539
- function importMemories(siteId, agentId, data) {
540
- let imported = 0;
541
- const tx = db.transaction(() => {
542
- for (const item of data) {
543
- const id = item.id || randomUUID();
544
- const jsonValue = typeof item.value === 'string' ? item.value : JSON.stringify(item.value);
545
- const embedding = item.embedding
546
- ? (typeof item.embedding === 'string' ? item.embedding : JSON.stringify(item.embedding))
547
- : JSON.stringify(computeEmbedding(`${item.key} ${jsonValue}`));
548
-
549
- stmts.insertMemory.run(
550
- id, siteId, agentId,
551
- item.type || item.memory_type || null,
552
- item.category || null,
553
- item.key,
554
- jsonValue,
555
- embedding,
556
- item.importance ?? 0.5,
557
- item.expires_at || null
558
- );
559
- imported++;
560
- }
561
- });
562
- tx();
563
- return { imported };
564
- }
565
-
566
- // ─── Preference Shortcuts ────────────────────────────────────────────────────
567
-
568
- /**
569
- * Returns all 'preference' type memories for a site/agent.
570
- * @param {string} siteId
571
- * @param {string} agentId
572
- * @returns {object[]}
573
- */
574
- function getPreferences(siteId, agentId) {
575
- return stmts.getPreferences.all(siteId, agentId);
576
- }
577
-
578
- /**
579
- * Stores or updates a preference memory. Upserts if the same key exists.
580
- * @param {string} siteId
581
- * @param {string} agentId
582
- * @param {string} key
583
- * @param {any} value
584
- * @returns {object}
585
- */
586
- function recordPreference(siteId, agentId, key, value) {
587
- const existing = stmts.findPreference.get(siteId, agentId, key);
588
- const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
589
- const embedding = computeEmbedding(`${key} ${jsonValue}`);
590
-
591
- if (existing) {
592
- const newImportance = Math.min(1, existing.importance + 0.05);
593
- stmts.updateMemoryValue.run(jsonValue, JSON.stringify(embedding), newImportance, existing.id);
594
- return stmts.getMemory.get(existing.id);
595
- }
596
-
597
- return storeMemory(siteId, agentId, {
598
- type: 'preference',
599
- category: 'custom',
600
- key,
601
- value: jsonValue,
602
- importance: 0.7,
603
- });
604
- }
605
-
606
- // ─── Exports ─────────────────────────────────────────────────────────────────
607
-
608
- module.exports = {
609
- storeMemory,
610
- recallMemories,
611
- computeEmbedding,
612
- cosineSimilarity,
613
- associateMemories,
614
- getAssociatedMemories,
615
- forgetMemory,
616
- consolidateMemories,
617
- getMemoryStats,
618
- startSession,
619
- endSession,
620
- getSessionHistory,
621
- exportMemories,
622
- importMemories,
623
- getPreferences,
624
- recordPreference,
625
- };
1
+ 'use strict';
2
+
3
+ const { db } = require('../models/db');
4
+ const { randomUUID } = require('crypto');
5
+
6
+ // ─── Schema ──────────────────────────────────────────────────────────────────
7
+
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS agent_memories (
10
+ id TEXT PRIMARY KEY,
11
+ site_id TEXT NOT NULL,
12
+ agent_id TEXT NOT NULL,
13
+ memory_type TEXT CHECK(memory_type IN ('preference','interaction','correction','pattern')),
14
+ category TEXT CHECK(category IN ('navigation','purchase','search','form','custom')),
15
+ key TEXT NOT NULL,
16
+ value TEXT NOT NULL,
17
+ embedding TEXT,
18
+ importance REAL DEFAULT 0.5,
19
+ access_count INTEGER DEFAULT 0,
20
+ last_accessed TEXT,
21
+ expires_at TEXT,
22
+ created_at TEXT DEFAULT (datetime('now')),
23
+ updated_at TEXT DEFAULT (datetime('now')),
24
+ FOREIGN KEY (site_id) REFERENCES sites(id) ON DELETE CASCADE
25
+ );
26
+
27
+ CREATE TABLE IF NOT EXISTS memory_sessions (
28
+ id TEXT PRIMARY KEY,
29
+ site_id TEXT,
30
+ agent_id TEXT,
31
+ context TEXT,
32
+ started_at TEXT DEFAULT (datetime('now')),
33
+ ended_at TEXT
34
+ );
35
+
36
+ CREATE TABLE IF NOT EXISTS memory_associations (
37
+ id TEXT PRIMARY KEY,
38
+ source_memory_id TEXT,
39
+ target_memory_id TEXT,
40
+ relationship TEXT CHECK(relationship IN ('leads_to','similar_to','replaces','depends_on')),
41
+ strength REAL DEFAULT 0.5,
42
+ created_at TEXT DEFAULT (datetime('now')),
43
+ FOREIGN KEY (source_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE,
44
+ FOREIGN KEY (target_memory_id) REFERENCES agent_memories(id) ON DELETE CASCADE
45
+ );
46
+
47
+ CREATE INDEX IF NOT EXISTS idx_mem_site ON agent_memories(site_id);
48
+ CREATE INDEX IF NOT EXISTS idx_mem_agent ON agent_memories(agent_id);
49
+ CREATE INDEX IF NOT EXISTS idx_mem_type ON agent_memories(memory_type);
50
+ CREATE INDEX IF NOT EXISTS idx_mem_category ON agent_memories(category);
51
+ CREATE INDEX IF NOT EXISTS idx_mem_importance ON agent_memories(importance);
52
+ CREATE INDEX IF NOT EXISTS idx_mem_sessions_site ON memory_sessions(site_id);
53
+ CREATE INDEX IF NOT EXISTS idx_mem_sessions_agent ON memory_sessions(agent_id);
54
+ CREATE INDEX IF NOT EXISTS idx_mem_assoc_source ON memory_associations(source_memory_id);
55
+ CREATE INDEX IF NOT EXISTS idx_mem_assoc_target ON memory_associations(target_memory_id);
56
+ `);
57
+
58
+ // ─── Prepared Statements ─────────────────────────────────────────────────────
59
+
60
+ const stmts = {
61
+ insertMemory: db.prepare(`
62
+ INSERT INTO agent_memories (id, site_id, agent_id, memory_type, category, key, value, embedding, importance, expires_at)
63
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
64
+ `),
65
+ getMemory: db.prepare(`SELECT * FROM agent_memories WHERE id = ?`),
66
+ queryMemories: db.prepare(`
67
+ SELECT * FROM agent_memories
68
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
69
+ ORDER BY importance DESC, updated_at DESC
70
+ `),
71
+ queryByCategory: db.prepare(`
72
+ SELECT * FROM agent_memories
73
+ WHERE site_id = ? AND agent_id = ? AND category = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
74
+ ORDER BY importance DESC, updated_at DESC
75
+ `),
76
+ queryByType: db.prepare(`
77
+ SELECT * FROM agent_memories
78
+ WHERE site_id = ? AND agent_id = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
79
+ ORDER BY importance DESC, updated_at DESC
80
+ `),
81
+ queryByCategoryAndType: db.prepare(`
82
+ SELECT * FROM agent_memories
83
+ WHERE site_id = ? AND agent_id = ? AND category = ? AND memory_type = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
84
+ ORDER BY importance DESC, updated_at DESC
85
+ `),
86
+ touchMemory: db.prepare(`
87
+ UPDATE agent_memories SET access_count = access_count + 1, last_accessed = datetime('now') WHERE id = ?
88
+ `),
89
+ softDelete: db.prepare(`
90
+ UPDATE agent_memories SET expires_at = datetime('now'), updated_at = datetime('now') WHERE id = ?
91
+ `),
92
+ updateImportance: db.prepare(`
93
+ UPDATE agent_memories SET importance = ?, updated_at = datetime('now') WHERE id = ?
94
+ `),
95
+ deleteExpired: db.prepare(`
96
+ DELETE FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')
97
+ `),
98
+ findDuplicates: db.prepare(`
99
+ SELECT key, category, COUNT(*) as cnt, GROUP_CONCAT(id) as ids
100
+ FROM agent_memories
101
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
102
+ GROUP BY key, category HAVING cnt > 1
103
+ `),
104
+ deleteMemoryById: db.prepare(`DELETE FROM agent_memories WHERE id = ?`),
105
+
106
+ insertAssociation: db.prepare(`
107
+ INSERT INTO memory_associations (id, source_memory_id, target_memory_id, relationship, strength)
108
+ VALUES (?, ?, ?, ?, ?)
109
+ `),
110
+ getAssociationsFrom: db.prepare(`
111
+ SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
112
+ FROM memory_associations ma
113
+ JOIN agent_memories am ON am.id = ma.target_memory_id
114
+ WHERE ma.source_memory_id = ?
115
+ ORDER BY ma.strength DESC
116
+ `),
117
+ getAssociationsFromFiltered: db.prepare(`
118
+ SELECT ma.*, am.key, am.value, am.memory_type, am.category, am.importance
119
+ FROM memory_associations ma
120
+ JOIN agent_memories am ON am.id = ma.target_memory_id
121
+ WHERE ma.source_memory_id = ? AND ma.relationship = ?
122
+ ORDER BY ma.strength DESC
123
+ `),
124
+
125
+ insertSession: db.prepare(`
126
+ INSERT INTO memory_sessions (id, site_id, agent_id, context) VALUES (?, ?, ?, ?)
127
+ `),
128
+ endSession: db.prepare(`
129
+ UPDATE memory_sessions SET ended_at = datetime('now'), context = json_patch(COALESCE(context, '{}'), ?) WHERE id = ?
130
+ `),
131
+ getSessionHistory: db.prepare(`
132
+ SELECT * FROM memory_sessions WHERE site_id = ? AND agent_id = ? ORDER BY started_at DESC LIMIT ?
133
+ `),
134
+
135
+ countAll: db.prepare(`
136
+ SELECT COUNT(*) as total FROM agent_memories WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
137
+ `),
138
+ countByType: db.prepare(`
139
+ SELECT memory_type, COUNT(*) as count FROM agent_memories
140
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
141
+ GROUP BY memory_type
142
+ `),
143
+ countByCategory: db.prepare(`
144
+ SELECT category, COUNT(*) as count FROM agent_memories
145
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
146
+ GROUP BY category
147
+ `),
148
+ avgImportance: db.prepare(`
149
+ SELECT AVG(importance) as avg FROM agent_memories
150
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
151
+ `),
152
+ storageEstimate: db.prepare(`
153
+ SELECT SUM(LENGTH(key) + LENGTH(value) + COALESCE(LENGTH(embedding), 0)) as bytes
154
+ FROM agent_memories WHERE site_id = ? AND agent_id = ?
155
+ `),
156
+
157
+ allActiveMemories: db.prepare(`
158
+ SELECT * FROM agent_memories
159
+ WHERE site_id = ? AND agent_id = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
160
+ ORDER BY created_at ASC
161
+ `),
162
+ getPreferences: db.prepare(`
163
+ SELECT * FROM agent_memories
164
+ WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND (expires_at IS NULL OR expires_at > datetime('now'))
165
+ ORDER BY importance DESC
166
+ `),
167
+ findPreference: db.prepare(`
168
+ SELECT * FROM agent_memories
169
+ WHERE site_id = ? AND agent_id = ? AND memory_type = 'preference' AND key = ? AND (expires_at IS NULL OR expires_at > datetime('now'))
170
+ LIMIT 1
171
+ `),
172
+ updateMemoryValue: db.prepare(`
173
+ UPDATE agent_memories SET value = ?, embedding = ?, importance = ?, updated_at = datetime('now') WHERE id = ?
174
+ `),
175
+ };
176
+
177
+ // ─── Vector Utilities ────────────────────────────────────────────────────────
178
+
179
+ const EMBED_DIM = 128;
180
+
181
+ /**
182
+ * Tokenizes text into lowercase alphanumeric tokens.
183
+ * @param {string} text
184
+ * @returns {string[]}
185
+ */
186
+ function tokenize(text) {
187
+ return String(text).toLowerCase().match(/[a-z0-9]+/g) || [];
188
+ }
189
+
190
+ /**
191
+ * Deterministic hash of a string to a 32-bit unsigned integer.
192
+ * @param {string} str
193
+ * @returns {number}
194
+ */
195
+ function hashStr(str) {
196
+ let h = 0x811c9dc5;
197
+ for (let i = 0; i < str.length; i++) {
198
+ h ^= str.charCodeAt(i);
199
+ h = Math.imul(h, 0x01000193);
200
+ }
201
+ return h >>> 0;
202
+ }
203
+
204
+ /**
205
+ * Computes a TF-IDF-style embedding: hashes tokens into a fixed-size vector and L2-normalizes.
206
+ * @param {string} text
207
+ * @returns {number[]} 128-dimensional unit vector
208
+ */
209
+ function computeEmbedding(text) {
210
+ const tokens = tokenize(text);
211
+ const vec = new Float64Array(EMBED_DIM);
212
+ if (tokens.length === 0) return Array.from(vec);
213
+
214
+ const tf = {};
215
+ for (const t of tokens) tf[t] = (tf[t] || 0) + 1;
216
+
217
+ for (const [token, count] of Object.entries(tf)) {
218
+ const idx = hashStr(token) % EMBED_DIM;
219
+ const sign = (hashStr(token + '_sign') & 1) ? 1 : -1;
220
+ const weight = (1 + Math.log(count)) * sign;
221
+ vec[idx] += weight;
222
+ }
223
+
224
+ let norm = 0;
225
+ for (let i = 0; i < EMBED_DIM; i++) norm += vec[i] * vec[i];
226
+ norm = Math.sqrt(norm);
227
+ if (norm > 0) for (let i = 0; i < EMBED_DIM; i++) vec[i] /= norm;
228
+
229
+ return Array.from(vec);
230
+ }
231
+
232
+ /**
233
+ * Standard cosine similarity between two equal-length vectors.
234
+ * @param {number[]} a
235
+ * @param {number[]} b
236
+ * @returns {number} similarity in [-1, 1]
237
+ */
238
+ function cosineSimilarity(a, b) {
239
+ if (!a || !b || a.length !== b.length) return 0;
240
+ let dot = 0, normA = 0, normB = 0;
241
+ for (let i = 0; i < a.length; i++) {
242
+ dot += a[i] * b[i];
243
+ normA += a[i] * a[i];
244
+ normB += b[i] * b[i];
245
+ }
246
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
247
+ return denom === 0 ? 0 : dot / denom;
248
+ }
249
+
250
+ // ─── Core Memory Operations ──────────────────────────────────────────────────
251
+
252
+ /**
253
+ * Stores a memory entry for an agent on a site.
254
+ * @param {string} siteId
255
+ * @param {string} agentId
256
+ * @param {{ type?: string, category?: string, key: string, value: any, importance?: number, ttlSeconds?: number }} opts
257
+ * @returns {object} the stored memory row
258
+ */
259
+ function storeMemory(siteId, agentId, { type, category, key, value, importance, ttlSeconds }) {
260
+ const id = randomUUID();
261
+ const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
262
+ const embedding = computeEmbedding(`${key} ${typeof value === 'string' ? value : JSON.stringify(value)}`);
263
+ const expiresAt = ttlSeconds
264
+ ? new Date(Date.now() + ttlSeconds * 1000).toISOString().replace('T', ' ').slice(0, 19)
265
+ : null;
266
+
267
+ stmts.insertMemory.run(
268
+ id, siteId, agentId,
269
+ type || null, category || null,
270
+ key, jsonValue,
271
+ JSON.stringify(embedding),
272
+ importance ?? 0.5,
273
+ expiresAt
274
+ );
275
+
276
+ return stmts.getMemory.get(id);
277
+ }
278
+
279
+ /**
280
+ * Recalls memories matching filters, optionally ranked by semantic similarity.
281
+ * @param {string} siteId
282
+ * @param {string} agentId
283
+ * @param {{ query?: string, category?: string, type?: string, limit?: number, minImportance?: number }} opts
284
+ * @returns {object[]}
285
+ */
286
+ function recallMemories(siteId, agentId, { query, category, type, limit, minImportance } = {}) {
287
+ let rows;
288
+ if (category && type) {
289
+ rows = stmts.queryByCategoryAndType.all(siteId, agentId, category, type);
290
+ } else if (category) {
291
+ rows = stmts.queryByCategory.all(siteId, agentId, category);
292
+ } else if (type) {
293
+ rows = stmts.queryByType.all(siteId, agentId, type);
294
+ } else {
295
+ rows = stmts.queryMemories.all(siteId, agentId);
296
+ }
297
+
298
+ if (minImportance != null) {
299
+ rows = rows.filter(r => r.importance >= minImportance);
300
+ }
301
+
302
+ if (query) {
303
+ const queryEmbed = computeEmbedding(query);
304
+ rows = rows.map(r => {
305
+ const memEmbed = r.embedding ? JSON.parse(r.embedding) : null;
306
+ const similarity = memEmbed ? cosineSimilarity(queryEmbed, memEmbed) : 0;
307
+ return { ...r, similarity };
308
+ });
309
+ rows.sort((a, b) => b.similarity - a.similarity);
310
+ }
311
+
312
+ const maxRows = limit || 20;
313
+ rows = rows.slice(0, maxRows);
314
+
315
+ const touchTx = db.transaction((ids) => {
316
+ for (const id of ids) stmts.touchMemory.run(id);
317
+ });
318
+ touchTx(rows.map(r => r.id));
319
+
320
+ return rows;
321
+ }
322
+
323
+ // ─── Associations ────────────────────────────────────────────────────────────
324
+
325
+ /**
326
+ * Creates a directional link between two memories.
327
+ * @param {string} sourceId
328
+ * @param {string} targetId
329
+ * @param {string} relationship - leads_to | similar_to | replaces | depends_on
330
+ * @param {number} [strength=0.5]
331
+ * @returns {object}
332
+ */
333
+ function associateMemories(sourceId, targetId, relationship, strength = 0.5) {
334
+ const id = randomUUID();
335
+ stmts.insertAssociation.run(id, sourceId, targetId, relationship, strength);
336
+ return { id, sourceId, targetId, relationship, strength };
337
+ }
338
+
339
+ /**
340
+ * Retrieves memories associated with a given memory.
341
+ * @param {string} memoryId
342
+ * @param {{ relationship?: string, minStrength?: number }} [opts]
343
+ * @returns {object[]}
344
+ */
345
+ function getAssociatedMemories(memoryId, { relationship, minStrength } = {}) {
346
+ let rows;
347
+ if (relationship) {
348
+ rows = stmts.getAssociationsFromFiltered.all(memoryId, relationship);
349
+ } else {
350
+ rows = stmts.getAssociationsFrom.all(memoryId);
351
+ }
352
+ if (minStrength != null) {
353
+ rows = rows.filter(r => r.strength >= minStrength);
354
+ }
355
+ return rows;
356
+ }
357
+
358
+ // ─── Lifecycle ───────────────────────────────────────────────────────────────
359
+
360
+ /**
361
+ * Soft-deletes a memory by setting its expiration to now.
362
+ * @param {string} memoryId
363
+ * @returns {boolean}
364
+ */
365
+ function forgetMemory(memoryId) {
366
+ const info = stmts.softDelete.run(memoryId);
367
+ return info.changes > 0;
368
+ }
369
+
370
+ /**
371
+ * Consolidates memories: merges duplicates, adjusts importance, purges expired.
372
+ * @param {string} siteId
373
+ * @param {string} agentId
374
+ * @returns {{ merged: number, boosted: number, decayed: number, expired: number }}
375
+ */
376
+ function consolidateMemories(siteId, agentId) {
377
+ const stats = { merged: 0, boosted: 0, decayed: 0, expired: 0 };
378
+
379
+ const expiredInfo = stmts.deleteExpired.run();
380
+ stats.expired = expiredInfo.changes;
381
+
382
+ const dupes = stmts.findDuplicates.all(siteId, agentId);
383
+ const mergeTx = db.transaction(() => {
384
+ for (const group of dupes) {
385
+ const ids = group.ids.split(',');
386
+ const memories = ids.map(id => stmts.getMemory.get(id)).filter(Boolean);
387
+ if (memories.length < 2) continue;
388
+
389
+ memories.sort((a, b) => b.access_count - a.access_count || b.importance - a.importance);
390
+ const keeper = memories[0];
391
+
392
+ let mergedValues;
393
+ try {
394
+ const parsed = memories.map(m => JSON.parse(m.value));
395
+ if (typeof parsed[0] === 'object' && parsed[0] !== null && !Array.isArray(parsed[0])) {
396
+ mergedValues = JSON.stringify(Object.assign({}, ...parsed.reverse()));
397
+ } else {
398
+ mergedValues = keeper.value;
399
+ }
400
+ } catch {
401
+ mergedValues = keeper.value;
402
+ }
403
+
404
+ const newImportance = Math.min(1, keeper.importance + 0.05 * (memories.length - 1));
405
+ const newEmbedding = computeEmbedding(`${keeper.key} ${mergedValues}`);
406
+ stmts.updateMemoryValue.run(mergedValues, JSON.stringify(newEmbedding), newImportance, keeper.id);
407
+
408
+ for (let i = 1; i < memories.length; i++) {
409
+ stmts.deleteMemoryById.run(memories[i].id);
410
+ stats.merged++;
411
+ }
412
+ }
413
+ });
414
+ mergeTx();
415
+
416
+ const active = stmts.allActiveMemories.all(siteId, agentId);
417
+ const now = Date.now();
418
+
419
+ const adjustTx = db.transaction(() => {
420
+ for (const mem of active) {
421
+ const ageMs = now - new Date(mem.created_at).getTime();
422
+ const ageDays = ageMs / 86400000;
423
+
424
+ if (mem.access_count >= 5) {
425
+ const boost = Math.min(1, mem.importance + 0.02 * Math.log2(mem.access_count));
426
+ if (boost > mem.importance) {
427
+ stmts.updateImportance.run(Math.min(1, boost), mem.id);
428
+ stats.boosted++;
429
+ }
430
+ }
431
+
432
+ if (ageDays > 30 && mem.access_count < 3) {
433
+ const decayFactor = Math.max(0.1, 1 - 0.01 * (ageDays - 30));
434
+ const decayed = mem.importance * decayFactor;
435
+ if (decayed < mem.importance) {
436
+ stmts.updateImportance.run(Math.max(0, decayed), mem.id);
437
+ stats.decayed++;
438
+ }
439
+ }
440
+ }
441
+ });
442
+ adjustTx();
443
+
444
+ return stats;
445
+ }
446
+
447
+ // ─── Stats ───────────────────────────────────────────────────────────────────
448
+
449
+ /**
450
+ * Returns aggregate statistics for an agent's memories on a site.
451
+ * @param {string} siteId
452
+ * @param {string} agentId
453
+ * @returns {object}
454
+ */
455
+ function getMemoryStats(siteId, agentId) {
456
+ const total = stmts.countAll.get(siteId, agentId).total;
457
+ const byType = stmts.countByType.all(siteId, agentId);
458
+ const byCategory = stmts.countByCategory.all(siteId, agentId);
459
+ const avgImportance = stmts.avgImportance.get(siteId, agentId).avg || 0;
460
+ const storageBytes = stmts.storageEstimate.get(siteId, agentId).bytes || 0;
461
+
462
+ return {
463
+ total,
464
+ byType: Object.fromEntries(byType.map(r => [r.memory_type, r.count])),
465
+ byCategory: Object.fromEntries(byCategory.map(r => [r.category, r.count])),
466
+ avgImportance: Math.round(avgImportance * 1000) / 1000,
467
+ storageEstimateBytes: storageBytes,
468
+ };
469
+ }
470
+
471
+ // ─── Sessions ────────────────────────────────────────────────────────────────
472
+
473
+ /**
474
+ * Starts an agent memory session.
475
+ * @param {string} siteId
476
+ * @param {string} agentId
477
+ * @param {object} [context]
478
+ * @returns {{ id: string, siteId: string, agentId: string, startedAt: string }}
479
+ */
480
+ function startSession(siteId, agentId, context = {}) {
481
+ const id = randomUUID();
482
+ stmts.insertSession.run(id, siteId, agentId, JSON.stringify(context));
483
+ return { id, siteId, agentId, startedAt: new Date().toISOString() };
484
+ }
485
+
486
+ /**
487
+ * Ends a session, optionally attaching a summary to the context.
488
+ * @param {string} sessionId
489
+ * @param {string} [summary]
490
+ * @returns {boolean}
491
+ */
492
+ function endSession(sessionId, summary) {
493
+ const patch = summary ? JSON.stringify({ summary }) : '{}';
494
+ const info = stmts.endSession.run(patch, sessionId);
495
+ return info.changes > 0;
496
+ }
497
+
498
+ /**
499
+ * Returns recent sessions for a site/agent pair.
500
+ * @param {string} siteId
501
+ * @param {string} agentId
502
+ * @param {{ limit?: number }} [opts]
503
+ * @returns {object[]}
504
+ */
505
+ function getSessionHistory(siteId, agentId, { limit } = {}) {
506
+ return stmts.getSessionHistory.all(siteId, agentId, limit || 20);
507
+ }
508
+
509
+ // ─── Import / Export ─────────────────────────────────────────────────────────
510
+
511
+ /**
512
+ * Exports all active memories as JSON or CSV.
513
+ * @param {string} siteId
514
+ * @param {string} agentId
515
+ * @param {{ format?: 'json'|'csv' }} [opts]
516
+ * @returns {string}
517
+ */
518
+ function exportMemories(siteId, agentId, { format } = {}) {
519
+ const rows = stmts.allActiveMemories.all(siteId, agentId);
520
+
521
+ if (format === 'csv') {
522
+ const cols = ['id', 'site_id', 'agent_id', 'memory_type', 'category', 'key', 'value', 'importance', 'access_count', 'created_at', 'updated_at'];
523
+ const escape = (v) => `"${String(v == null ? '' : v).replace(/"/g, '""')}"`;
524
+ const header = cols.join(',');
525
+ const lines = rows.map(r => cols.map(c => escape(r[c])).join(','));
526
+ return [header, ...lines].join('\n');
527
+ }
528
+
529
+ return JSON.stringify(rows, null, 2);
530
+ }
531
+
532
+ /**
533
+ * Bulk-imports memories from an array of objects.
534
+ * @param {string} siteId
535
+ * @param {string} agentId
536
+ * @param {object[]} data
537
+ * @returns {{ imported: number }}
538
+ */
539
+ function importMemories(siteId, agentId, data) {
540
+ let imported = 0;
541
+ const tx = db.transaction(() => {
542
+ for (const item of data) {
543
+ const id = item.id || randomUUID();
544
+ const jsonValue = typeof item.value === 'string' ? item.value : JSON.stringify(item.value);
545
+ const embedding = item.embedding
546
+ ? (typeof item.embedding === 'string' ? item.embedding : JSON.stringify(item.embedding))
547
+ : JSON.stringify(computeEmbedding(`${item.key} ${jsonValue}`));
548
+
549
+ stmts.insertMemory.run(
550
+ id, siteId, agentId,
551
+ item.type || item.memory_type || null,
552
+ item.category || null,
553
+ item.key,
554
+ jsonValue,
555
+ embedding,
556
+ item.importance ?? 0.5,
557
+ item.expires_at || null
558
+ );
559
+ imported++;
560
+ }
561
+ });
562
+ tx();
563
+ return { imported };
564
+ }
565
+
566
+ // ─── Preference Shortcuts ────────────────────────────────────────────────────
567
+
568
+ /**
569
+ * Returns all 'preference' type memories for a site/agent.
570
+ * @param {string} siteId
571
+ * @param {string} agentId
572
+ * @returns {object[]}
573
+ */
574
+ function getPreferences(siteId, agentId) {
575
+ return stmts.getPreferences.all(siteId, agentId);
576
+ }
577
+
578
+ /**
579
+ * Stores or updates a preference memory. Upserts if the same key exists.
580
+ * @param {string} siteId
581
+ * @param {string} agentId
582
+ * @param {string} key
583
+ * @param {any} value
584
+ * @returns {object}
585
+ */
586
+ function recordPreference(siteId, agentId, key, value) {
587
+ const existing = stmts.findPreference.get(siteId, agentId, key);
588
+ const jsonValue = typeof value === 'string' ? value : JSON.stringify(value);
589
+ const embedding = computeEmbedding(`${key} ${jsonValue}`);
590
+
591
+ if (existing) {
592
+ const newImportance = Math.min(1, existing.importance + 0.05);
593
+ stmts.updateMemoryValue.run(jsonValue, JSON.stringify(embedding), newImportance, existing.id);
594
+ return stmts.getMemory.get(existing.id);
595
+ }
596
+
597
+ return storeMemory(siteId, agentId, {
598
+ type: 'preference',
599
+ category: 'custom',
600
+ key,
601
+ value: jsonValue,
602
+ importance: 0.7,
603
+ });
604
+ }
605
+
606
+ // ─── Exports ─────────────────────────────────────────────────────────────────
607
+
608
+ module.exports = {
609
+ storeMemory,
610
+ recallMemories,
611
+ computeEmbedding,
612
+ cosineSimilarity,
613
+ associateMemories,
614
+ getAssociatedMemories,
615
+ forgetMemory,
616
+ consolidateMemories,
617
+ getMemoryStats,
618
+ startSession,
619
+ endSession,
620
+ getSessionHistory,
621
+ exportMemories,
622
+ importMemories,
623
+ getPreferences,
624
+ recordPreference,
625
+ };