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