@deepagents/agent 0.36.0 → 0.37.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.
package/dist/index.js CHANGED
@@ -176,11 +176,11 @@ function createRepairToolCall(model, abortSignal) {
176
176
  console.log(
177
177
  `Debug: ${chalk.yellow("RepairingToolCall")}: ${toolCall.toolName}`
178
178
  );
179
- const tool3 = tools[toolCall.toolName];
179
+ const tool2 = tools[toolCall.toolName];
180
180
  const { output } = await generateText({
181
181
  abortSignal,
182
182
  model,
183
- output: Output.object({ schema: tool3.inputSchema }),
183
+ output: Output.object({ schema: tool2.inputSchema }),
184
184
  prompt: [
185
185
  `The model tried to call the tool "${toolCall.toolName}" with the following inputs:`,
186
186
  JSON.stringify(toolCall.input),
@@ -983,925 +983,6 @@ function lastTransferResult(messages) {
983
983
  return void 0;
984
984
  }
985
985
 
986
- // packages/agent/src/lib/memory.ts
987
- import { tool as tool2 } from "ai";
988
- import Conf from "conf";
989
- import { z as z2 } from "zod";
990
- var MemoryStore = class {
991
- store;
992
- constructor(name = "agent-memory") {
993
- this.store = new Conf({
994
- projectName: name,
995
- schema: {
996
- memories: {
997
- type: "object",
998
- default: {}
999
- },
1000
- relationships: {
1001
- type: "object",
1002
- default: {}
1003
- },
1004
- metadata: {
1005
- type: "object",
1006
- default: {
1007
- lastConsolidation: Date.now(),
1008
- totalAccesses: 0
1009
- }
1010
- }
1011
- }
1012
- });
1013
- }
1014
- /**
1015
- * Generate a unique memory ID
1016
- */
1017
- generateId() {
1018
- return `mem_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1019
- }
1020
- /**
1021
- * Calculate memory decay based on time and access patterns
1022
- */
1023
- calculateDecay(memory) {
1024
- const now = Date.now();
1025
- const age = now - memory.timestamp;
1026
- const timeSinceAccess = now - memory.lastAccessed;
1027
- const daysSinceCreation = age / (1e3 * 60 * 60 * 24);
1028
- const daysSinceAccess = timeSinceAccess / (1e3 * 60 * 60 * 24);
1029
- const accessBonus = Math.log(memory.accessCount + 1) * 0.1;
1030
- const importanceBonus = memory.importance * 0.05;
1031
- const decay = Math.max(
1032
- 0.1,
1033
- 1 - (daysSinceCreation * 0.05 + daysSinceAccess * 0.08 - accessBonus - importanceBonus)
1034
- );
1035
- return Math.min(1, decay);
1036
- }
1037
- /**
1038
- * Store a new memory
1039
- */
1040
- write(entry) {
1041
- const id = this.generateId();
1042
- const now = Date.now();
1043
- const memory = {
1044
- ...entry,
1045
- id,
1046
- timestamp: now,
1047
- accessCount: 0,
1048
- lastAccessed: now,
1049
- decay: 1
1050
- };
1051
- const memories = this.store.get("memories");
1052
- memories[id] = memory;
1053
- this.store.set("memories", memories);
1054
- if (entry.relationships && entry.relationships.length > 0) {
1055
- const relationships = this.store.get("relationships");
1056
- for (const relatedId of entry.relationships) {
1057
- if (!relationships[relatedId]) {
1058
- relationships[relatedId] = [];
1059
- }
1060
- if (!relationships[relatedId].includes(id)) {
1061
- relationships[relatedId].push(id);
1062
- }
1063
- }
1064
- this.store.set("relationships", relationships);
1065
- }
1066
- return memory;
1067
- }
1068
- /**
1069
- * Retrieve a memory by ID
1070
- */
1071
- get(id) {
1072
- const memories = this.store.get("memories");
1073
- const memory = memories[id];
1074
- if (!memory) {
1075
- return null;
1076
- }
1077
- memory.accessCount++;
1078
- memory.lastAccessed = Date.now();
1079
- memory.decay = this.calculateDecay(memory);
1080
- memories[id] = memory;
1081
- this.store.set("memories", memories);
1082
- const metadata = this.store.get("metadata");
1083
- metadata.totalAccesses++;
1084
- this.store.set("metadata", metadata);
1085
- return memory;
1086
- }
1087
- /**
1088
- * Search memories based on query
1089
- */
1090
- lookup(query) {
1091
- const memories = Object.values(this.store.get("memories"));
1092
- let results = memories;
1093
- if (query.type) {
1094
- results = results.filter((m) => m.type === query.type);
1095
- }
1096
- if (query.minImportance !== void 0) {
1097
- results = results.filter((m) => m.importance >= query.minImportance);
1098
- }
1099
- if (query.tags && query.tags.length > 0) {
1100
- results = results.filter(
1101
- (m) => query.tags.some((tag) => m.tags.includes(tag))
1102
- );
1103
- }
1104
- if (query.timeRange) {
1105
- if (query.timeRange.start) {
1106
- results = results.filter((m) => m.timestamp >= query.timeRange.start);
1107
- }
1108
- if (query.timeRange.end) {
1109
- results = results.filter((m) => m.timestamp <= query.timeRange.end);
1110
- }
1111
- }
1112
- const searchTerms = query.query.toLowerCase().split(" ");
1113
- results = results.filter((m) => {
1114
- const content = m.content.toLowerCase();
1115
- const tags = m.tags.join(" ").toLowerCase();
1116
- return searchTerms.some(
1117
- (term) => content.includes(term) || tags.includes(term)
1118
- );
1119
- });
1120
- results = results.map((m) => ({
1121
- ...m,
1122
- decay: this.calculateDecay(m)
1123
- }));
1124
- results.sort((a, b) => {
1125
- const scoreA = (a.decay || 0) * a.importance * (1 + Math.log(a.accessCount + 1));
1126
- const scoreB = (b.decay || 0) * b.importance * (1 + Math.log(b.accessCount + 1));
1127
- return scoreB - scoreA;
1128
- });
1129
- const limit = query.limit || 10;
1130
- return results.slice(0, limit);
1131
- }
1132
- /**
1133
- * Update an existing memory
1134
- */
1135
- correct(id, updates) {
1136
- const memories = this.store.get("memories");
1137
- const memory = memories[id];
1138
- if (!memory) {
1139
- return null;
1140
- }
1141
- const updated = {
1142
- ...memory,
1143
- ...updates,
1144
- id: memory.id,
1145
- // Preserve ID
1146
- timestamp: memory.timestamp,
1147
- // Preserve original timestamp
1148
- lastAccessed: Date.now(),
1149
- accessCount: memory.accessCount + 1
1150
- };
1151
- updated.decay = this.calculateDecay(updated);
1152
- memories[id] = updated;
1153
- this.store.set("memories", memories);
1154
- return updated;
1155
- }
1156
- /**
1157
- * Delete a memory (forget)
1158
- */
1159
- forget(id) {
1160
- const memories = this.store.get("memories");
1161
- if (!memories[id]) {
1162
- return false;
1163
- }
1164
- delete memories[id];
1165
- this.store.set("memories", memories);
1166
- const relationships = this.store.get("relationships");
1167
- delete relationships[id];
1168
- for (const [key, refs] of Object.entries(relationships)) {
1169
- relationships[key] = refs.filter((ref) => ref !== id);
1170
- }
1171
- this.store.set("relationships", relationships);
1172
- return true;
1173
- }
1174
- /**
1175
- * Get related memories
1176
- */
1177
- getRelated(id, limit = 5) {
1178
- const relationships = this.store.get("relationships");
1179
- const relatedIds = relationships[id] || [];
1180
- const memories = this.store.get("memories");
1181
- const relatedMemories = relatedIds.map((relId) => memories[relId]).filter(Boolean).slice(0, limit);
1182
- return relatedMemories;
1183
- }
1184
- /**
1185
- * Get memory statistics
1186
- */
1187
- getStats() {
1188
- const memories = Object.values(this.store.get("memories"));
1189
- const byType = memories.reduce(
1190
- (acc, m) => {
1191
- acc[m.type] = (acc[m.type] || 0) + 1;
1192
- return acc;
1193
- },
1194
- {}
1195
- );
1196
- const mostAccessed = [...memories].sort((a, b) => b.accessCount - a.accessCount).slice(0, 10);
1197
- const recentMemories = [...memories].sort((a, b) => b.timestamp - a.timestamp).slice(0, 10);
1198
- const averageImportance = memories.length > 0 ? memories.reduce((sum, m) => sum + m.importance, 0) / memories.length : 0;
1199
- return {
1200
- totalMemories: memories.length,
1201
- byType,
1202
- mostAccessed,
1203
- recentMemories,
1204
- averageImportance
1205
- };
1206
- }
1207
- /**
1208
- * Consolidate memories (prune low-importance, rarely accessed memories)
1209
- */
1210
- consolidate(threshold = 0.2) {
1211
- const memories = this.store.get("memories");
1212
- const entries = Object.entries(memories);
1213
- let pruned = 0;
1214
- for (const [id, memory] of entries) {
1215
- const decay = this.calculateDecay(memory);
1216
- if (decay < threshold && memory.importance < 5) {
1217
- delete memories[id];
1218
- pruned++;
1219
- }
1220
- }
1221
- if (pruned > 0) {
1222
- this.store.set("memories", memories);
1223
- const metadata = this.store.get("metadata");
1224
- metadata.lastConsolidation = Date.now();
1225
- this.store.set("metadata", metadata);
1226
- }
1227
- return pruned;
1228
- }
1229
- /**
1230
- * Clear all memories
1231
- */
1232
- clear() {
1233
- this.store.clear();
1234
- }
1235
- /**
1236
- * Export all memories
1237
- */
1238
- export() {
1239
- return this.store.get("memories");
1240
- }
1241
- /**
1242
- * Import memories
1243
- */
1244
- import(memories) {
1245
- this.store.set("memories", memories);
1246
- }
1247
- // ============================================================================
1248
- // Specialized Write Functions - High-level convenience methods
1249
- // ============================================================================
1250
- /**
1251
- * Write a semantic memory (facts, concepts, general knowledge)
1252
- *
1253
- * @example
1254
- * store.writeSemantic("React is a JavaScript library for building UIs", {
1255
- * tags: ["react", "javascript"],
1256
- * importance: 8
1257
- * });
1258
- */
1259
- writeSemantic(content, options) {
1260
- return this.write({
1261
- content,
1262
- type: "semantic",
1263
- importance: options?.importance ?? 7,
1264
- // Default to 7 for facts
1265
- tags: options?.tags ?? [],
1266
- context: options?.context,
1267
- relationships: options?.relationships
1268
- });
1269
- }
1270
- /**
1271
- * Write an episodic memory (events, conversations, experiences)
1272
- *
1273
- * @example
1274
- * store.writeEpisodic("User completed onboarding", {
1275
- * tags: ["milestone", "user123"],
1276
- * context: { userId: "user123", timestamp: Date.now() }
1277
- * });
1278
- */
1279
- writeEpisodic(content, options) {
1280
- return this.write({
1281
- content,
1282
- type: "episodic",
1283
- importance: options?.importance ?? 6,
1284
- // Default to 6 for events
1285
- tags: options?.tags ?? [],
1286
- context: {
1287
- ...options?.context,
1288
- timestamp: options?.context?.timestamp ?? Date.now()
1289
- },
1290
- relationships: options?.relationships
1291
- });
1292
- }
1293
- /**
1294
- * Write a procedural memory (patterns, behaviors, methods)
1295
- *
1296
- * @example
1297
- * store.writeProcedural("When user asks for help, first check documentation", {
1298
- * tags: ["pattern", "help"],
1299
- * importance: 7
1300
- * });
1301
- */
1302
- writeProcedural(content, options) {
1303
- return this.write({
1304
- content,
1305
- type: "procedural",
1306
- importance: options?.importance ?? 7,
1307
- // Default to 7 for patterns
1308
- tags: options?.tags ?? [],
1309
- context: options?.context,
1310
- relationships: options?.relationships
1311
- });
1312
- }
1313
- /**
1314
- * Store a user preference (convenience wrapper for semantic memory)
1315
- *
1316
- * @example
1317
- * store.storePreference("user123", "theme", "dark");
1318
- */
1319
- storePreference(userId, preference, value, importance = 8) {
1320
- return this.writeSemantic(
1321
- `User ${userId} prefers ${preference}: ${typeof value === "object" ? JSON.stringify(value) : value}`,
1322
- {
1323
- importance,
1324
- tags: ["preference", userId, preference],
1325
- context: {
1326
- userId,
1327
- preference,
1328
- value,
1329
- category: "user-preference"
1330
- }
1331
- }
1332
- );
1333
- }
1334
- /**
1335
- * Record a conversation exchange (convenience wrapper for episodic memory)
1336
- *
1337
- * @example
1338
- * store.recordConversation("user123", "session456", "user", "How do I use React hooks?");
1339
- */
1340
- recordConversation(userId, sessionId, role, message, importance = 5) {
1341
- return this.writeEpisodic(`[${role}]: ${message}`, {
1342
- importance,
1343
- tags: ["conversation", userId, sessionId, role],
1344
- context: {
1345
- userId,
1346
- sessionId,
1347
- role,
1348
- timestamp: Date.now(),
1349
- category: "conversation"
1350
- }
1351
- });
1352
- }
1353
- /**
1354
- * Record a user action/event (convenience wrapper for episodic memory)
1355
- *
1356
- * @example
1357
- * store.recordAction("user123", "completed_tutorial", { tutorialId: "intro" });
1358
- */
1359
- recordAction(userId, action, details, importance = 6) {
1360
- return this.writeEpisodic(`User ${userId} performed action: ${action}`, {
1361
- importance,
1362
- tags: ["action", userId, action],
1363
- context: {
1364
- userId,
1365
- action,
1366
- details,
1367
- timestamp: Date.now(),
1368
- category: "user-action"
1369
- }
1370
- });
1371
- }
1372
- /**
1373
- * Learn a pattern from observations (convenience wrapper for procedural memory)
1374
- *
1375
- * @example
1376
- * store.learnPattern("optimization-workflow", "Profile before optimizing", {
1377
- * conditions: "Performance issues reported",
1378
- * relatedMemories: ["mem_123"]
1379
- * });
1380
- */
1381
- learnPattern(patternName, description, options) {
1382
- return this.writeProcedural(`Pattern [${patternName}]: ${description}`, {
1383
- importance: options?.importance ?? 7,
1384
- tags: ["pattern", "learned", patternName],
1385
- context: {
1386
- patternName,
1387
- conditions: options?.conditions,
1388
- category: "learned-pattern",
1389
- ...options?.context
1390
- },
1391
- relationships: options?.relatedMemories
1392
- });
1393
- }
1394
- /**
1395
- * Store a fact or knowledge (convenience wrapper for semantic memory)
1396
- *
1397
- * @example
1398
- * store.storeFact("JavaScript", "JavaScript is a programming language", {
1399
- * source: "documentation",
1400
- * relatedTo: ["mem_456"]
1401
- * });
1402
- */
1403
- storeFact(topic, fact, options) {
1404
- return this.writeSemantic(fact, {
1405
- importance: options?.importance ?? 7,
1406
- tags: ["fact", "knowledge", topic, ...options?.tags ?? []],
1407
- context: {
1408
- topic,
1409
- source: options?.source,
1410
- category: "fact"
1411
- },
1412
- relationships: options?.relatedTo
1413
- });
1414
- }
1415
- /**
1416
- * Record a milestone or achievement (convenience wrapper for episodic memory)
1417
- *
1418
- * @example
1419
- * store.recordMilestone("user123", "first-project-completed", "User completed their first project");
1420
- */
1421
- recordMilestone(userId, milestoneType, description, importance = 7) {
1422
- return this.writeEpisodic(description, {
1423
- importance,
1424
- tags: ["milestone", userId, milestoneType],
1425
- context: {
1426
- userId,
1427
- milestoneType,
1428
- timestamp: Date.now(),
1429
- category: "milestone"
1430
- }
1431
- });
1432
- }
1433
- /**
1434
- * Store contextual information about current session (working memory)
1435
- * Note: These should have lower importance as they're temporary
1436
- *
1437
- * @example
1438
- * store.storeSessionContext("session456", "user-preferences-loaded", { theme: "dark" });
1439
- */
1440
- storeSessionContext(sessionId, contextKey, data, importance = 4) {
1441
- return this.writeEpisodic(`Session context [${contextKey}]`, {
1442
- importance,
1443
- tags: ["session", "working-memory", sessionId, contextKey],
1444
- context: {
1445
- sessionId,
1446
- contextKey,
1447
- data,
1448
- category: "session-context",
1449
- timestamp: Date.now()
1450
- }
1451
- });
1452
- }
1453
- // ============================================================================
1454
- // Proactive Memory Loading - Auto-inject memories into system prompt
1455
- // ============================================================================
1456
- /**
1457
- * Get proactive memories that should always be present in system prompt
1458
- * These are high-importance memories that provide essential context
1459
- *
1460
- * @param options Configuration for proactive memory retrieval
1461
- * @returns Formatted string ready for system prompt injection
1462
- *
1463
- * @example
1464
- * const memoryContext = memoryStore.getProactiveMemories({
1465
- * userId: 'user123',
1466
- * minImportance: 7,
1467
- * categories: ['preference', 'core-knowledge']
1468
- * });
1469
- *
1470
- * // Use in agent:
1471
- * const systemPrompt = `${basePrompt}\n\n${memoryContext}`;
1472
- */
1473
- getProactiveMemories(options) {
1474
- const {
1475
- userId,
1476
- sessionId,
1477
- minImportance = 7,
1478
- // High importance by default
1479
- categories = [],
1480
- maxMemories = 10,
1481
- types,
1482
- includeRelationships = false
1483
- } = options;
1484
- const tags = [];
1485
- if (userId) tags.push(userId);
1486
- if (sessionId) tags.push(sessionId);
1487
- if (categories.length > 0) tags.push(...categories);
1488
- const memoriesByType = {
1489
- semantic: [],
1490
- procedural: [],
1491
- episodic: []
1492
- };
1493
- const typesToFetch = types || ["semantic", "procedural", "episodic"];
1494
- for (const type of typesToFetch) {
1495
- const memories = this.lookup({
1496
- query: "",
1497
- // Empty query to get all matching filters
1498
- type,
1499
- minImportance,
1500
- tags: tags.length > 0 ? tags : void 0,
1501
- limit: maxMemories
1502
- });
1503
- memoriesByType[type] = memories;
1504
- }
1505
- return this.formatProactiveMemories(memoriesByType, includeRelationships);
1506
- }
1507
- /**
1508
- * Format proactive memories into a structured system prompt section
1509
- */
1510
- formatProactiveMemories(memoriesByType, includeRelationships) {
1511
- const sections = [];
1512
- if (memoriesByType.semantic.length > 0) {
1513
- sections.push("## Core Knowledge & Preferences");
1514
- sections.push("");
1515
- memoriesByType.semantic.forEach((mem, idx) => {
1516
- sections.push(`${idx + 1}. ${mem.content}`);
1517
- if (mem.context?.preference) {
1518
- sections.push(` - Preference: ${mem.context.preference}`);
1519
- }
1520
- if (mem.context?.source) {
1521
- sections.push(` - Source: ${mem.context.source}`);
1522
- }
1523
- });
1524
- sections.push("");
1525
- }
1526
- if (memoriesByType.procedural.length > 0) {
1527
- sections.push("## Behavioral Patterns & Guidelines");
1528
- sections.push("");
1529
- memoriesByType.procedural.forEach((mem, idx) => {
1530
- sections.push(`${idx + 1}. ${mem.content}`);
1531
- if (mem.context?.conditions) {
1532
- sections.push(` - When: ${mem.context.conditions}`);
1533
- }
1534
- if (mem.context?.patternName) {
1535
- sections.push(` - Pattern: ${mem.context.patternName}`);
1536
- }
1537
- });
1538
- sections.push("");
1539
- }
1540
- if (memoriesByType.episodic.length > 0) {
1541
- sections.push("## Recent Context & History");
1542
- sections.push("");
1543
- memoriesByType.episodic.forEach((mem, idx) => {
1544
- const timeAgo = this.formatTimeAgo(Date.now() - mem.timestamp);
1545
- sections.push(`${idx + 1}. ${mem.content} (${timeAgo})`);
1546
- if (mem.context?.milestoneType) {
1547
- sections.push(` - Milestone: ${mem.context.milestoneType}`);
1548
- }
1549
- });
1550
- sections.push("");
1551
- }
1552
- if (sections.length === 0) {
1553
- return "";
1554
- }
1555
- return [
1556
- "",
1557
- "# Proactive Memory Context",
1558
- "The following information has been retrieved from memory to provide you with essential context:",
1559
- "",
1560
- ...sections
1561
- ].join("\n");
1562
- }
1563
- /**
1564
- * Helper to format time ago for human readability
1565
- */
1566
- formatTimeAgo(ms) {
1567
- const seconds = Math.floor(ms / 1e3);
1568
- const minutes = Math.floor(seconds / 60);
1569
- const hours = Math.floor(minutes / 60);
1570
- const days = Math.floor(hours / 24);
1571
- if (days > 0) return `${days}d ago`;
1572
- if (hours > 0) return `${hours}h ago`;
1573
- if (minutes > 0) return `${minutes}m ago`;
1574
- return `${seconds}s ago`;
1575
- }
1576
- /**
1577
- * Get user-specific proactive memories
1578
- * Convenience method that focuses on user preferences and patterns
1579
- *
1580
- * @example
1581
- * const proactiveUserMemories = memoryStore.getUserProactiveMemories('user123');
1582
- */
1583
- getUserProactiveMemories(userId, options) {
1584
- const {
1585
- includePreferences = true,
1586
- includePatterns = true,
1587
- includeRecentHistory = true,
1588
- maxPerCategory = 5
1589
- } = options || {};
1590
- const types = [];
1591
- const categories = [];
1592
- if (includePreferences) {
1593
- types.push("semantic");
1594
- categories.push("preference");
1595
- }
1596
- if (includePatterns) {
1597
- types.push("procedural");
1598
- categories.push("pattern");
1599
- }
1600
- if (includeRecentHistory) {
1601
- types.push("episodic");
1602
- categories.push("milestone", "action");
1603
- }
1604
- return this.getProactiveMemories({
1605
- userId,
1606
- minImportance: 7,
1607
- categories,
1608
- maxMemories: maxPerCategory * types.length,
1609
- types: types.length > 0 ? types : void 0
1610
- });
1611
- }
1612
- /**
1613
- * Get session-specific proactive memories
1614
- * Focuses on working memory and recent context
1615
- *
1616
- * @example
1617
- * const sessionContext = memoryStore.getSessionProactiveMemories('session456');
1618
- */
1619
- getSessionProactiveMemories(sessionId, options) {
1620
- const { includeWorkingMemory = true, maxMemories = 10 } = options || {};
1621
- const categories = includeWorkingMemory ? ["session", "working-memory", "conversation"] : ["session", "conversation"];
1622
- return this.getProactiveMemories({
1623
- sessionId,
1624
- minImportance: 4,
1625
- // Lower threshold for session context
1626
- categories,
1627
- maxMemories,
1628
- types: ["episodic"]
1629
- });
1630
- }
1631
- /**
1632
- * Get critical memories that should ALWAYS be present
1633
- * These are importance level 9-10 memories
1634
- *
1635
- * @example
1636
- * const criticalContext = memoryStore.getCriticalMemories();
1637
- */
1638
- getCriticalMemories(options) {
1639
- return this.getProactiveMemories({
1640
- userId: options?.userId,
1641
- minImportance: 9,
1642
- maxMemories: options?.maxMemories || 5,
1643
- types: ["semantic", "procedural"]
1644
- });
1645
- }
1646
- /**
1647
- * Build complete proactive context for an agent
1648
- * Combines critical, user-specific, and session-specific memories
1649
- *
1650
- * @example
1651
- * const fullContext = memoryStore.buildProactiveContext({
1652
- * userId: 'user123',
1653
- * sessionId: 'session456'
1654
- * });
1655
- *
1656
- * // Use in agent system prompt
1657
- * const systemPrompt = `${basePrompt}\n\n${fullContext}`;
1658
- */
1659
- buildProactiveContext(options) {
1660
- const {
1661
- userId,
1662
- sessionId,
1663
- includeCritical = true,
1664
- includeUser = true,
1665
- includeSession = true
1666
- } = options;
1667
- const sections = [];
1668
- if (includeCritical) {
1669
- const critical = this.getCriticalMemories({ userId });
1670
- if (critical) sections.push(critical);
1671
- }
1672
- if (includeUser && userId) {
1673
- const proactiveUserMemories = this.getUserProactiveMemories(userId);
1674
- if (proactiveUserMemories) sections.push(proactiveUserMemories);
1675
- }
1676
- if (includeSession && sessionId) {
1677
- const sessionContext = this.getSessionProactiveMemories(sessionId);
1678
- if (sessionContext) sections.push(sessionContext);
1679
- }
1680
- return sections.join("\n\n");
1681
- }
1682
- };
1683
- var memoryStore = new MemoryStore();
1684
- var memoryLookup = tool2({
1685
- description: `Search and retrieve memories from the memory store.
1686
- Use this to recall past conversations, learned facts, or previous interactions.
1687
- Memories decay over time but are reinforced through repeated access.`,
1688
- inputSchema: z2.object({
1689
- query: z2.string().describe("Search query to find relevant memories"),
1690
- type: z2.enum(["episodic", "semantic", "procedural"]).optional().describe("Type of memory to search"),
1691
- limit: z2.number().int().positive().max(50).default(10).describe("Maximum number of memories to retrieve"),
1692
- minImportance: z2.number().min(1).max(10).optional().describe("Minimum importance level (1-10)"),
1693
- tags: z2.array(z2.string()).optional().describe("Filter by tags")
1694
- }),
1695
- execute: async ({ query, type, limit, minImportance, tags }) => {
1696
- console.log("Memory lookup:", { query, type, limit, minImportance, tags });
1697
- const results = memoryStore.lookup({
1698
- query,
1699
- type,
1700
- limit,
1701
- minImportance,
1702
- tags
1703
- });
1704
- return {
1705
- count: results.length,
1706
- memories: results.map((m) => ({
1707
- id: m.id,
1708
- content: m.content,
1709
- type: m.type,
1710
- importance: m.importance,
1711
- tags: m.tags,
1712
- timestamp: new Date(m.timestamp).toISOString(),
1713
- accessCount: m.accessCount,
1714
- decay: m.decay?.toFixed(2),
1715
- context: m.context
1716
- }))
1717
- };
1718
- }
1719
- });
1720
- var memoryExplain = tool2({
1721
- description: `Get detailed information about a specific memory, including its relationships,
1722
- access history, and decay status. Use this to understand the context and relevance of a memory.`,
1723
- inputSchema: z2.object({
1724
- id: z2.string().describe("The unique identifier of the memory to explain"),
1725
- includeRelated: z2.boolean().default(true).describe("Include related memories in the explanation")
1726
- }),
1727
- execute: async ({ id, includeRelated }) => {
1728
- console.log("Memory explain:", { id, includeRelated });
1729
- const memory = memoryStore.get(id);
1730
- if (!memory) {
1731
- return {
1732
- found: false,
1733
- message: `No memory found with ID: ${id}`
1734
- };
1735
- }
1736
- const related = includeRelated ? memoryStore.getRelated(id) : [];
1737
- return {
1738
- found: true,
1739
- memory: {
1740
- id: memory.id,
1741
- content: memory.content,
1742
- type: memory.type,
1743
- importance: memory.importance,
1744
- tags: memory.tags,
1745
- timestamp: new Date(memory.timestamp).toISOString(),
1746
- lastAccessed: new Date(memory.lastAccessed).toISOString(),
1747
- accessCount: memory.accessCount,
1748
- decay: memory.decay?.toFixed(2),
1749
- context: memory.context,
1750
- age: {
1751
- days: Math.floor(
1752
- (Date.now() - memory.timestamp) / (1e3 * 60 * 60 * 24)
1753
- ),
1754
- hours: Math.floor((Date.now() - memory.timestamp) / (1e3 * 60 * 60))
1755
- },
1756
- timeSinceAccess: {
1757
- days: Math.floor(
1758
- (Date.now() - memory.lastAccessed) / (1e3 * 60 * 60 * 24)
1759
- ),
1760
- hours: Math.floor(
1761
- (Date.now() - memory.lastAccessed) / (1e3 * 60 * 60)
1762
- )
1763
- }
1764
- },
1765
- related: related.map((r) => ({
1766
- id: r.id,
1767
- content: r.content.substring(0, 100) + (r.content.length > 100 ? "..." : ""),
1768
- type: r.type,
1769
- importance: r.importance
1770
- }))
1771
- };
1772
- }
1773
- });
1774
- var memoryWrite = tool2({
1775
- description: `Store a new memory in the memory system. Use this to remember important facts,
1776
- events, or learnings. Choose the appropriate memory type:
1777
- - episodic: Events, conversations, experiences with temporal context
1778
- - semantic: Facts, concepts, general knowledge
1779
- - procedural: Patterns, methods, learned behaviors`,
1780
- inputSchema: z2.object({
1781
- content: z2.string().describe("The content of the memory to store"),
1782
- type: z2.enum(["episodic", "semantic", "procedural"]).describe("Type of memory"),
1783
- importance: z2.number().min(1).max(10).default(5).describe("Importance level (1-10), affects retention"),
1784
- tags: z2.array(z2.string()).default([]).describe("Tags for categorization and retrieval"),
1785
- context: z2.record(z2.any(), z2.any()).optional().describe("Additional context metadata"),
1786
- relationships: z2.array(z2.string()).optional().describe("IDs of related memories")
1787
- }),
1788
- execute: async ({
1789
- content,
1790
- type,
1791
- importance,
1792
- tags,
1793
- context,
1794
- relationships
1795
- }) => {
1796
- console.log("Memory write:", { content, type, importance, tags });
1797
- const memory = memoryStore.write({
1798
- content,
1799
- type,
1800
- importance,
1801
- tags,
1802
- context,
1803
- relationships
1804
- });
1805
- return {
1806
- success: true,
1807
- id: memory.id,
1808
- message: "Memory stored successfully",
1809
- memory: {
1810
- id: memory.id,
1811
- type: memory.type,
1812
- importance: memory.importance,
1813
- timestamp: new Date(memory.timestamp).toISOString()
1814
- }
1815
- };
1816
- }
1817
- });
1818
- var memoryForget = tool2({
1819
- description: `Delete a memory from the memory store. Use this to remove outdated,
1820
- incorrect, or irrelevant memories. This action is irreversible.`,
1821
- inputSchema: z2.object({
1822
- id: z2.string().describe("The unique identifier of the memory to forget"),
1823
- reason: z2.string().optional().describe("Optional reason for forgetting")
1824
- }),
1825
- execute: async ({ id, reason }) => {
1826
- console.log("Memory forget:", { id, reason });
1827
- const success = memoryStore.forget(id);
1828
- return {
1829
- success,
1830
- message: success ? `Memory ${id} has been forgotten${reason ? `: ${reason}` : ""}` : `No memory found with ID: ${id}`
1831
- };
1832
- }
1833
- });
1834
- var memoryCorrect = tool2({
1835
- description: `Update or correct an existing memory. Use this to fix errors,
1836
- add new information, or adjust importance levels. The original timestamp is preserved.`,
1837
- inputSchema: z2.object({
1838
- id: z2.string().describe("The unique identifier of the memory to correct"),
1839
- updates: z2.object({
1840
- content: z2.string().optional().describe("Updated content"),
1841
- importance: z2.number().min(1).max(10).optional().describe("Updated importance"),
1842
- tags: z2.array(z2.string()).optional().describe("Updated tags"),
1843
- context: z2.record(z2.any(), z2.any()).optional().describe("Updated context"),
1844
- relationships: z2.array(z2.string()).optional().describe("Updated relationships")
1845
- }),
1846
- correctionNote: z2.string().optional().describe("Note explaining the correction")
1847
- }),
1848
- execute: async ({ id, updates, correctionNote }) => {
1849
- console.log("Memory correct:", { id, updates, correctionNote });
1850
- const memory = memoryStore.correct(id, updates);
1851
- if (!memory) {
1852
- return {
1853
- success: false,
1854
- message: `No memory found with ID: ${id}`
1855
- };
1856
- }
1857
- return {
1858
- success: true,
1859
- message: `Memory ${id} has been updated${correctionNote ? `: ${correctionNote}` : ""}`,
1860
- memory: {
1861
- id: memory.id,
1862
- content: memory.content,
1863
- type: memory.type,
1864
- importance: memory.importance,
1865
- lastAccessed: new Date(memory.lastAccessed).toISOString()
1866
- }
1867
- };
1868
- }
1869
- });
1870
- var memoryStats = tool2({
1871
- description: `Get statistics about the memory system, including total memories,
1872
- distribution by type, most accessed memories, and recent memories.`,
1873
- inputSchema: z2.object({}),
1874
- execute: async () => {
1875
- console.log("Memory stats requested");
1876
- const stats = memoryStore.getStats();
1877
- return {
1878
- total: stats.totalMemories,
1879
- byType: stats.byType,
1880
- averageImportance: stats.averageImportance.toFixed(2),
1881
- mostAccessed: stats.mostAccessed.slice(0, 5).map((m) => ({
1882
- id: m.id,
1883
- content: m.content.substring(0, 50) + "...",
1884
- accessCount: m.accessCount,
1885
- type: m.type
1886
- })),
1887
- recent: stats.recentMemories.slice(0, 5).map((m) => ({
1888
- id: m.id,
1889
- content: m.content.substring(0, 50) + "...",
1890
- timestamp: new Date(m.timestamp).toISOString(),
1891
- type: m.type
1892
- }))
1893
- };
1894
- }
1895
- });
1896
- var memoryTools = {
1897
- memoryLookup,
1898
- memoryExplain,
1899
- memoryWrite,
1900
- memoryForget,
1901
- memoryCorrect,
1902
- memoryStats
1903
- };
1904
-
1905
986
  // packages/agent/src/lib/models.ts
1906
987
  import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
1907
988
  import { embedMany, extractReasoningMiddleware, wrapLanguageModel } from "ai";
@@ -2022,7 +1103,6 @@ export {
2022
1103
  Agent,
2023
1104
  GENERAL_STEP_BACK_EXAMPLES,
2024
1105
  KNOWLEDGE_QA_STEP_BACK_EXAMPLES,
2025
- MemoryStore,
2026
1106
  RECOMMENDED_PROMPT_PREFIX,
2027
1107
  STEM_STEP_BACK_EXAMPLES,
2028
1108
  SUPERVISOR_PROMPT_PREFIX,
@@ -2042,14 +1122,6 @@ export {
2042
1122
  last,
2043
1123
  lastTransferResult,
2044
1124
  lmstudio,
2045
- memoryCorrect,
2046
- memoryExplain,
2047
- memoryForget,
2048
- memoryLookup,
2049
- memoryStats,
2050
- memoryStore,
2051
- memoryTools,
2052
- memoryWrite,
2053
1125
  messageToUiMessage,
2054
1126
  minimax,
2055
1127
  nebius,