web-agent-bridge 3.3.0 → 3.8.1

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