web-agent-bridge 3.2.0 → 3.4.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 (256) hide show
  1. package/LICENSE +84 -72
  2. package/README.ar.md +1304 -1152
  3. package/README.md +298 -1635
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -138
  6. package/bin/wab-init.js +223 -0
  7. package/bin/wab.js +80 -80
  8. package/examples/azure-dns-wab.js +83 -0
  9. package/examples/bidi-agent.js +119 -119
  10. package/examples/cloudflare-wab-dns.js +121 -0
  11. package/examples/cpanel-wab-dns.js +114 -0
  12. package/examples/cross-site-agent.js +91 -91
  13. package/examples/dns-discovery-agent.js +166 -0
  14. package/examples/gcp-dns-wab.js +76 -0
  15. package/examples/governance-agent.js +169 -0
  16. package/examples/mcp-agent.js +94 -94
  17. package/examples/next-app-router/README.md +44 -44
  18. package/examples/plesk-wab-dns.js +103 -0
  19. package/examples/puppeteer-agent.js +108 -108
  20. package/examples/route53-wab-dns.js +144 -0
  21. package/examples/saas-dashboard/README.md +55 -55
  22. package/examples/safe-mode-agent.js +96 -0
  23. package/examples/shopify-hydrogen/README.md +74 -74
  24. package/examples/vision-agent.js +171 -171
  25. package/examples/wab-sign.js +74 -0
  26. package/examples/wab-verify.js +60 -0
  27. package/examples/wordpress-elementor/README.md +77 -77
  28. package/package.json +19 -6
  29. package/public/.well-known/agent-tools.json +180 -180
  30. package/public/.well-known/ai-assets.json +59 -59
  31. package/public/.well-known/security.txt +8 -0
  32. package/public/.well-known/wab.json +28 -0
  33. package/public/activate.html +368 -0
  34. package/public/adoption-metrics.html +188 -0
  35. package/public/agent-workspace.html +349 -349
  36. package/public/ai.html +198 -198
  37. package/public/api.html +413 -412
  38. package/public/azure-dns-integration.html +289 -0
  39. package/public/browser.html +486 -486
  40. package/public/cloudflare-integration.html +380 -0
  41. package/public/commander-dashboard.html +243 -243
  42. package/public/cookies.html +210 -210
  43. package/public/cpanel-integration.html +398 -0
  44. package/public/css/agent-workspace.css +1713 -1713
  45. package/public/css/premium.css +317 -317
  46. package/public/css/styles.css +1263 -1235
  47. package/public/dashboard.html +707 -706
  48. package/public/dns.html +436 -0
  49. package/public/docs.html +588 -587
  50. package/public/feed.xml +89 -89
  51. package/public/gcp-dns-integration.html +318 -0
  52. package/public/growth.html +465 -463
  53. package/public/index.html +1266 -982
  54. package/public/integrations.html +556 -0
  55. package/public/js/activate.js +145 -0
  56. package/public/js/agent-workspace.js +1740 -1740
  57. package/public/js/auth-nav.js +65 -31
  58. package/public/js/auth-redirect.js +12 -12
  59. package/public/js/cookie-consent.js +56 -56
  60. package/public/js/dns.js +438 -0
  61. package/public/js/wab-demo-page.js +721 -721
  62. package/public/js/ws-client.js +74 -74
  63. package/public/llms-full.txt +360 -360
  64. package/public/llms.txt +125 -125
  65. package/public/login.html +85 -85
  66. package/public/mesh-dashboard.html +328 -328
  67. package/public/openapi.json +669 -580
  68. package/public/phone-shield.html +281 -0
  69. package/public/plesk-integration.html +375 -0
  70. package/public/premium-dashboard.html +2489 -2489
  71. package/public/premium.html +793 -793
  72. package/public/privacy.html +297 -297
  73. package/public/provider-onboarding.html +172 -0
  74. package/public/provider-sandbox.html +134 -0
  75. package/public/providers.html +359 -0
  76. package/public/register.html +105 -105
  77. package/public/registrar-integrations.html +141 -0
  78. package/public/robots.txt +99 -87
  79. package/public/route53-integration.html +531 -0
  80. package/public/script/wab-consent.d.ts +36 -36
  81. package/public/script/wab-consent.js +104 -104
  82. package/public/script/wab-schema.js +131 -131
  83. package/public/script/wab.d.ts +108 -108
  84. package/public/script/wab.min.js +580 -580
  85. package/public/security.txt +8 -0
  86. package/public/shieldqr.html +231 -0
  87. package/public/sitemap.xml +6 -0
  88. package/public/terms.html +256 -256
  89. package/public/wab-trust.html +200 -0
  90. package/public/wab-vs-protocols.html +210 -0
  91. package/public/whitepaper.html +449 -0
  92. package/script/ai-agent-bridge.js +1754 -1754
  93. package/sdk/README.md +99 -99
  94. package/sdk/agent-mesh.js +449 -449
  95. package/sdk/auto-discovery.js +288 -0
  96. package/sdk/commander.js +262 -262
  97. package/sdk/governance.js +262 -0
  98. package/sdk/index.d.ts +464 -464
  99. package/sdk/index.js +25 -1
  100. package/sdk/multi-agent.js +318 -318
  101. package/sdk/package.json +2 -2
  102. package/sdk/safe-mode.js +221 -0
  103. package/sdk/safety-shield.js +219 -0
  104. package/sdk/schema-discovery.js +83 -83
  105. package/server/adapters/index.js +520 -520
  106. package/server/config/plans.js +367 -367
  107. package/server/config/secrets.js +102 -102
  108. package/server/control-plane/index.js +301 -301
  109. package/server/data-plane/index.js +354 -354
  110. package/server/index.js +670 -427
  111. package/server/llm/index.js +404 -404
  112. package/server/middleware/adminAuth.js +35 -35
  113. package/server/middleware/auth.js +50 -50
  114. package/server/middleware/featureGate.js +88 -88
  115. package/server/middleware/rateLimits.js +100 -100
  116. package/server/middleware/sensitiveAction.js +157 -0
  117. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  118. package/server/migrations/002_premium_features.sql +418 -418
  119. package/server/migrations/003_ads_integer_cents.sql +33 -33
  120. package/server/migrations/004_agent_os.sql +158 -158
  121. package/server/migrations/005_marketplace_metering.sql +126 -126
  122. package/server/migrations/007_governance.sql +106 -0
  123. package/server/migrations/008_plans.sql +144 -0
  124. package/server/migrations/009_shieldqr.sql +30 -0
  125. package/server/migrations/010_extended_trust.sql +33 -0
  126. package/server/models/adapters/index.js +33 -33
  127. package/server/models/adapters/mysql.js +183 -183
  128. package/server/models/adapters/postgresql.js +172 -172
  129. package/server/models/adapters/sqlite.js +7 -7
  130. package/server/models/db.js +740 -681
  131. package/server/observability/failure-analysis.js +337 -337
  132. package/server/observability/index.js +394 -394
  133. package/server/protocol/capabilities.js +223 -223
  134. package/server/protocol/index.js +243 -243
  135. package/server/protocol/schema.js +584 -584
  136. package/server/registry/certification.js +271 -271
  137. package/server/registry/index.js +326 -326
  138. package/server/routes/admin-plans.js +76 -0
  139. package/server/routes/admin-premium.js +673 -671
  140. package/server/routes/admin-shieldqr.js +90 -0
  141. package/server/routes/admin-trust-monitor.js +83 -0
  142. package/server/routes/admin.js +549 -261
  143. package/server/routes/ads.js +130 -130
  144. package/server/routes/agent-workspace.js +540 -540
  145. package/server/routes/api.js +150 -150
  146. package/server/routes/auth.js +71 -71
  147. package/server/routes/billing.js +57 -45
  148. package/server/routes/commander.js +316 -316
  149. package/server/routes/demo-showcase.js +332 -332
  150. package/server/routes/demo-store.js +154 -0
  151. package/server/routes/discovery.js +2348 -417
  152. package/server/routes/gateway.js +173 -157
  153. package/server/routes/governance.js +208 -0
  154. package/server/routes/license.js +251 -240
  155. package/server/routes/mesh.js +469 -469
  156. package/server/routes/noscript.js +543 -543
  157. package/server/routes/plans.js +33 -0
  158. package/server/routes/premium-v2.js +686 -686
  159. package/server/routes/premium.js +724 -724
  160. package/server/routes/providers.js +650 -0
  161. package/server/routes/runtime.js +2148 -2147
  162. package/server/routes/shieldqr.js +88 -0
  163. package/server/routes/sovereign.js +465 -385
  164. package/server/routes/universal.js +200 -185
  165. package/server/routes/wab-api.js +850 -501
  166. package/server/runtime/container-worker.js +111 -111
  167. package/server/runtime/container.js +448 -448
  168. package/server/runtime/distributed-worker.js +362 -362
  169. package/server/runtime/event-bus.js +210 -210
  170. package/server/runtime/index.js +253 -253
  171. package/server/runtime/queue.js +599 -599
  172. package/server/runtime/replay.js +666 -666
  173. package/server/runtime/sandbox.js +266 -266
  174. package/server/runtime/scheduler.js +534 -534
  175. package/server/runtime/session-engine.js +293 -293
  176. package/server/runtime/state-manager.js +188 -188
  177. package/server/security/cross-site-redactor.js +196 -0
  178. package/server/security/dry-run.js +180 -0
  179. package/server/security/human-gate-rate-limit.js +147 -0
  180. package/server/security/human-gate-transports.js +178 -0
  181. package/server/security/human-gate.js +281 -0
  182. package/server/security/index.js +368 -368
  183. package/server/security/intent-engine.js +245 -0
  184. package/server/security/reward-guard.js +171 -0
  185. package/server/security/rollback-store.js +239 -0
  186. package/server/security/token-scope.js +404 -0
  187. package/server/security/url-policy.js +139 -0
  188. package/server/services/agent-chat.js +506 -506
  189. package/server/services/agent-learning.js +601 -575
  190. package/server/services/agent-memory.js +625 -625
  191. package/server/services/agent-mesh.js +555 -539
  192. package/server/services/agent-symphony.js +717 -717
  193. package/server/services/agent-tasks.js +1807 -1807
  194. package/server/services/api-key-engine.js +292 -261
  195. package/server/services/cluster.js +894 -894
  196. package/server/services/commander.js +738 -738
  197. package/server/services/edge-compute.js +440 -440
  198. package/server/services/email.js +233 -204
  199. package/server/services/governance.js +466 -0
  200. package/server/services/hosted-runtime.js +205 -205
  201. package/server/services/lfd.js +635 -635
  202. package/server/services/local-ai.js +389 -389
  203. package/server/services/marketplace.js +270 -270
  204. package/server/services/metering.js +182 -182
  205. package/server/services/modules/affiliate-intelligence.js +93 -93
  206. package/server/services/modules/agent-firewall.js +90 -90
  207. package/server/services/modules/bounty.js +89 -89
  208. package/server/services/modules/collective-bargaining.js +92 -92
  209. package/server/services/modules/dark-pattern.js +66 -66
  210. package/server/services/modules/gov-intelligence.js +45 -45
  211. package/server/services/modules/neural.js +55 -55
  212. package/server/services/modules/notary.js +49 -49
  213. package/server/services/modules/price-time-machine.js +86 -86
  214. package/server/services/modules/protocol.js +104 -104
  215. package/server/services/negotiation.js +439 -439
  216. package/server/services/plans.js +214 -0
  217. package/server/services/plugins.js +771 -771
  218. package/server/services/premium.js +1 -1
  219. package/server/services/price-intelligence.js +566 -566
  220. package/server/services/price-shield.js +1137 -1137
  221. package/server/services/provider-clients.js +740 -0
  222. package/server/services/reputation.js +465 -465
  223. package/server/services/search-engine.js +357 -357
  224. package/server/services/security.js +513 -513
  225. package/server/services/self-healing.js +843 -843
  226. package/server/services/shieldqr.js +322 -0
  227. package/server/services/sovereign-shield.js +542 -0
  228. package/server/services/ssl-inspector.js +42 -0
  229. package/server/services/ssl-monitor.js +167 -0
  230. package/server/services/stripe.js +205 -192
  231. package/server/services/swarm.js +788 -788
  232. package/server/services/universal-scraper.js +662 -661
  233. package/server/services/verification.js +481 -481
  234. package/server/services/vision.js +1163 -1163
  235. package/server/services/wab-crypto.js +178 -0
  236. package/server/utils/cache.js +125 -125
  237. package/server/utils/migrate.js +81 -81
  238. package/server/utils/safe-fetch.js +228 -0
  239. package/server/utils/secureFields.js +50 -50
  240. package/server/ws.js +161 -161
  241. package/templates/artisan-marketplace.yaml +104 -104
  242. package/templates/book-price-scout.yaml +98 -98
  243. package/templates/electronics-price-tracker.yaml +108 -108
  244. package/templates/flight-deal-hunter.yaml +113 -113
  245. package/templates/freelancer-direct.yaml +116 -116
  246. package/templates/grocery-price-compare.yaml +93 -93
  247. package/templates/hotel-direct-booking.yaml +113 -113
  248. package/templates/local-services.yaml +98 -98
  249. package/templates/olive-oil-tunisia.yaml +88 -88
  250. package/templates/organic-farm-fresh.yaml +101 -101
  251. package/templates/restaurant-direct.yaml +97 -97
  252. package/public/score.html +0 -263
  253. package/server/migrations/006_growth_suite.sql +0 -138
  254. package/server/routes/growth.js +0 -962
  255. package/server/services/fairness-engine.js +0 -409
  256. 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
+ };