@iqai/adk 0.0.5 → 0.0.7
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/CHANGELOG.md +2 -2
- package/README.md +177 -0
- package/dist/index.d.mts +76 -144
- package/dist/index.d.ts +76 -144
- package/dist/index.js +706 -552
- package/dist/index.mjs +516 -362
- package/package.json +3 -2
package/dist/index.mjs
CHANGED
|
@@ -19,10 +19,47 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
19
19
|
};
|
|
20
20
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
21
|
|
|
22
|
+
// src/helpers/logger.ts
|
|
23
|
+
function isDebugEnabled() {
|
|
24
|
+
return process.env.NODE_ENV === "development" || process.env.DEBUG === "true";
|
|
25
|
+
}
|
|
26
|
+
var Logger;
|
|
27
|
+
var init_logger = __esm({
|
|
28
|
+
"src/helpers/logger.ts"() {
|
|
29
|
+
Logger = class {
|
|
30
|
+
name;
|
|
31
|
+
isDebugEnabled = isDebugEnabled();
|
|
32
|
+
constructor({ name }) {
|
|
33
|
+
this.name = name;
|
|
34
|
+
}
|
|
35
|
+
debug(message, ...args) {
|
|
36
|
+
const time = (/* @__PURE__ */ new Date()).toISOString();
|
|
37
|
+
if (this.isDebugEnabled) {
|
|
38
|
+
console.log(`[${time}] \u{1F41B} [DEBUG] \u2728 [${this.name}] ${message}`, ...args);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
info(message, ...args) {
|
|
42
|
+
const time = (/* @__PURE__ */ new Date()).toISOString();
|
|
43
|
+
console.info(`[${time}] \u2139\uFE0F [INFO] \u2728 [${this.name}] ${message}`, ...args);
|
|
44
|
+
}
|
|
45
|
+
warn(message, ...args) {
|
|
46
|
+
const time = (/* @__PURE__ */ new Date()).toISOString();
|
|
47
|
+
console.warn(`[${time}] \u{1F6A7} [WARN] \u2728 [${this.name}] ${message}`, ...args);
|
|
48
|
+
}
|
|
49
|
+
error(message, ...args) {
|
|
50
|
+
const time = (/* @__PURE__ */ new Date()).toISOString();
|
|
51
|
+
console.error(`[${time}] \u274C [ERROR] \u2728 [${this.name}] ${message}`, ...args);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
|
|
22
57
|
// src/tools/base/base-tool.ts
|
|
23
|
-
var BaseTool;
|
|
58
|
+
var logger2, BaseTool;
|
|
24
59
|
var init_base_tool = __esm({
|
|
25
60
|
"src/tools/base/base-tool.ts"() {
|
|
61
|
+
init_logger();
|
|
62
|
+
logger2 = new Logger({ name: "BaseTool" });
|
|
26
63
|
BaseTool = class {
|
|
27
64
|
/**
|
|
28
65
|
* Name of the tool
|
|
@@ -112,11 +149,9 @@ var init_base_tool = __esm({
|
|
|
112
149
|
while (attempts <= (this.shouldRetryOnFailure ? this.maxRetryAttempts : 0)) {
|
|
113
150
|
try {
|
|
114
151
|
if (attempts > 0) {
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
);
|
|
119
|
-
}
|
|
152
|
+
logger2.debug(
|
|
153
|
+
`Retrying tool ${this.name} (attempt ${attempts} of ${this.maxRetryAttempts})...`
|
|
154
|
+
);
|
|
120
155
|
const delay = Math.min(
|
|
121
156
|
this.baseRetryDelay * 2 ** (attempts - 1) + Math.random() * 1e3,
|
|
122
157
|
this.maxRetryDelay
|
|
@@ -459,7 +494,12 @@ var BaseAgent = class {
|
|
|
459
494
|
}
|
|
460
495
|
};
|
|
461
496
|
|
|
497
|
+
// src/agents/llm-agent.ts
|
|
498
|
+
init_logger();
|
|
499
|
+
|
|
462
500
|
// src/models/llm-registry.ts
|
|
501
|
+
init_logger();
|
|
502
|
+
var logger = new Logger({ name: "LLMRegistry" });
|
|
463
503
|
var LLMRegistry = class _LLMRegistry {
|
|
464
504
|
/**
|
|
465
505
|
* Map of model name regex to LLM class
|
|
@@ -516,12 +556,10 @@ var LLMRegistry = class _LLMRegistry {
|
|
|
516
556
|
* Logs all registered models for debugging
|
|
517
557
|
*/
|
|
518
558
|
static logRegisteredModels() {
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
}
|
|
524
|
-
}
|
|
559
|
+
logger.debug(
|
|
560
|
+
"Registered LLM models:",
|
|
561
|
+
[..._LLMRegistry.llmRegistry.entries()].map(([regex]) => regex.toString())
|
|
562
|
+
);
|
|
525
563
|
}
|
|
526
564
|
};
|
|
527
565
|
|
|
@@ -887,6 +925,7 @@ var Agent = class extends BaseAgent {
|
|
|
887
925
|
* The minimum relevance score for memory augmentation (0-1)
|
|
888
926
|
*/
|
|
889
927
|
memoryRelevanceThreshold;
|
|
928
|
+
logger = new Logger({ name: "LlmAgent" });
|
|
890
929
|
/**
|
|
891
930
|
* Constructor for Agent
|
|
892
931
|
*/
|
|
@@ -919,9 +958,7 @@ var Agent = class extends BaseAgent {
|
|
|
919
958
|
*/
|
|
920
959
|
async executeTool(toolCall, context) {
|
|
921
960
|
const { name, arguments: argsString } = toolCall.function;
|
|
922
|
-
|
|
923
|
-
console.log(`Executing tool: ${name}`);
|
|
924
|
-
}
|
|
961
|
+
this.logger.debug(`Executing tool: ${name}`);
|
|
925
962
|
const tool = this.findTool(name);
|
|
926
963
|
if (!tool) {
|
|
927
964
|
console.warn(`Tool '${name}' not found`);
|
|
@@ -939,9 +976,7 @@ var Agent = class extends BaseAgent {
|
|
|
939
976
|
toolContext.toolName = name;
|
|
940
977
|
toolContext.toolId = toolCall.id;
|
|
941
978
|
const result = await tool.runAsync(args, toolContext);
|
|
942
|
-
|
|
943
|
-
console.log(`Tool ${name} execution complete`);
|
|
944
|
-
}
|
|
979
|
+
this.logger.debug(`Tool ${name} execution complete`);
|
|
945
980
|
return {
|
|
946
981
|
name,
|
|
947
982
|
result: typeof result === "string" ? result : JSON.stringify(result)
|
|
@@ -1110,10 +1145,7 @@ ${relevantInfo.join("\n\n")}`
|
|
|
1110
1145
|
let stepCount = 0;
|
|
1111
1146
|
while (stepCount < this.maxToolExecutionSteps) {
|
|
1112
1147
|
stepCount++;
|
|
1113
|
-
|
|
1114
|
-
console.log(`
|
|
1115
|
-
[Agent] Step ${stepCount}: Thinking...`);
|
|
1116
|
-
}
|
|
1148
|
+
this.logger.debug(`Step ${stepCount}: Thinking...`);
|
|
1117
1149
|
const llmRequest = new LLMRequest({
|
|
1118
1150
|
messages: context.messages,
|
|
1119
1151
|
config: {
|
|
@@ -1130,9 +1162,9 @@ ${relevantInfo.join("\n\n")}`
|
|
|
1130
1162
|
throw new Error("No response from LLM");
|
|
1131
1163
|
}
|
|
1132
1164
|
if (currentResponse.tool_calls && currentResponse.tool_calls.length > 0) {
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1165
|
+
this.logger.debug(
|
|
1166
|
+
`Tool calls: ${JSON.stringify(currentResponse.tool_calls)}`
|
|
1167
|
+
);
|
|
1136
1168
|
context.addMessage({
|
|
1137
1169
|
role: "assistant",
|
|
1138
1170
|
content: currentResponse.content || "",
|
|
@@ -1151,9 +1183,7 @@ ${relevantInfo.join("\n\n")}`
|
|
|
1151
1183
|
});
|
|
1152
1184
|
}
|
|
1153
1185
|
} else {
|
|
1154
|
-
|
|
1155
|
-
console.log("[Agent] No tool calls, finishing...");
|
|
1156
|
-
}
|
|
1186
|
+
this.logger.debug("No tool calls, finishing...");
|
|
1157
1187
|
context.addMessage({
|
|
1158
1188
|
role: "assistant",
|
|
1159
1189
|
content: currentResponse.content || ""
|
|
@@ -1191,10 +1221,7 @@ ${relevantInfo.join("\n\n")}`
|
|
|
1191
1221
|
let stepCount = 0;
|
|
1192
1222
|
let hadToolCalls = false;
|
|
1193
1223
|
while (stepCount < this.maxToolExecutionSteps) {
|
|
1194
|
-
|
|
1195
|
-
console.log(`
|
|
1196
|
-
[Agent] Step ${stepCount + 1}: Thinking...`);
|
|
1197
|
-
}
|
|
1224
|
+
this.logger.debug(`Step ${stepCount}: Thinking...`);
|
|
1198
1225
|
const toolDeclarations = this.tools.map((tool) => tool.getDeclaration()).filter((declaration) => declaration !== null);
|
|
1199
1226
|
const request = {
|
|
1200
1227
|
messages: context.messages,
|
|
@@ -1223,14 +1250,10 @@ ${relevantInfo.join("\n\n")}`
|
|
|
1223
1250
|
function_call: finalResponse.function_call
|
|
1224
1251
|
});
|
|
1225
1252
|
if (!hadToolCalls) {
|
|
1226
|
-
|
|
1227
|
-
console.log("[Agent] No tool calls, finishing...");
|
|
1228
|
-
}
|
|
1253
|
+
this.logger.debug("No tool calls, finishing...");
|
|
1229
1254
|
break;
|
|
1230
1255
|
}
|
|
1231
|
-
|
|
1232
|
-
console.log("[Agent] Executing tools...");
|
|
1233
|
-
}
|
|
1256
|
+
this.logger.debug(`Step ${stepCount + 1}: Executing tools...`);
|
|
1234
1257
|
stepCount++;
|
|
1235
1258
|
if (finalResponse.function_call) {
|
|
1236
1259
|
const toolCall = {
|
|
@@ -1247,11 +1270,9 @@ ${relevantInfo.join("\n\n")}`
|
|
|
1247
1270
|
content: JSON.stringify(result.result)
|
|
1248
1271
|
});
|
|
1249
1272
|
} else if (finalResponse.tool_calls && finalResponse.tool_calls.length > 0) {
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
);
|
|
1254
|
-
}
|
|
1273
|
+
this.logger.debug(
|
|
1274
|
+
`Step ${stepCount + 1}: Executing ${finalResponse.tool_calls.length} tool(s)...`
|
|
1275
|
+
);
|
|
1255
1276
|
context.messages.pop();
|
|
1256
1277
|
context.addMessage({
|
|
1257
1278
|
role: "assistant",
|
|
@@ -1276,7 +1297,9 @@ ${relevantInfo.join("\n\n")}`
|
|
|
1276
1297
|
};
|
|
1277
1298
|
|
|
1278
1299
|
// src/agents/sequential-agent.ts
|
|
1300
|
+
init_logger();
|
|
1279
1301
|
var SequentialAgent = class extends BaseAgent {
|
|
1302
|
+
logger = new Logger({ name: "SequentialAgent" });
|
|
1280
1303
|
/**
|
|
1281
1304
|
* Constructor for SequentialAgent
|
|
1282
1305
|
*/
|
|
@@ -1296,11 +1319,9 @@ var SequentialAgent = class extends BaseAgent {
|
|
|
1296
1319
|
* Executes sub-agents sequentially, passing output from one to the next
|
|
1297
1320
|
*/
|
|
1298
1321
|
async run(options) {
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
);
|
|
1303
|
-
}
|
|
1322
|
+
this.logger.debug(
|
|
1323
|
+
`Running ${this.subAgents.length} sub-agents in sequence`
|
|
1324
|
+
);
|
|
1304
1325
|
if (this.subAgents.length === 0) {
|
|
1305
1326
|
return {
|
|
1306
1327
|
content: "No sub-agents defined for sequential execution.",
|
|
@@ -1316,11 +1337,9 @@ var SequentialAgent = class extends BaseAgent {
|
|
|
1316
1337
|
let finalResponse = null;
|
|
1317
1338
|
for (let i = 0; i < this.subAgents.length; i++) {
|
|
1318
1339
|
const agent = this.subAgents[i];
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
);
|
|
1323
|
-
}
|
|
1340
|
+
this.logger.debug(
|
|
1341
|
+
`Running sub-agent ${i + 1}/${this.subAgents.length}: ${agent.name}`
|
|
1342
|
+
);
|
|
1324
1343
|
try {
|
|
1325
1344
|
const response = await agent.run({
|
|
1326
1345
|
messages: currentMessages,
|
|
@@ -1335,10 +1354,7 @@ var SequentialAgent = class extends BaseAgent {
|
|
|
1335
1354
|
});
|
|
1336
1355
|
}
|
|
1337
1356
|
} catch (error) {
|
|
1338
|
-
console.error(
|
|
1339
|
-
`[SequentialAgent] Error in sub-agent ${agent.name}:`,
|
|
1340
|
-
error
|
|
1341
|
-
);
|
|
1357
|
+
console.error(`Error in sub-agent ${agent.name}:`, error);
|
|
1342
1358
|
return {
|
|
1343
1359
|
content: `Error in sub-agent ${agent.name}: ${error instanceof Error ? error.message : String(error)}`,
|
|
1344
1360
|
role: "assistant",
|
|
@@ -1376,11 +1392,9 @@ var SequentialAgent = class extends BaseAgent {
|
|
|
1376
1392
|
* Streams responses from each sub-agent in sequence
|
|
1377
1393
|
*/
|
|
1378
1394
|
async *runStreaming(options) {
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
);
|
|
1383
|
-
}
|
|
1395
|
+
this.logger.debug(
|
|
1396
|
+
`Streaming ${this.subAgents.length} sub-agents in sequence`
|
|
1397
|
+
);
|
|
1384
1398
|
if (this.subAgents.length === 0) {
|
|
1385
1399
|
yield {
|
|
1386
1400
|
content: "No sub-agents defined for sequential execution.",
|
|
@@ -1396,11 +1410,9 @@ var SequentialAgent = class extends BaseAgent {
|
|
|
1396
1410
|
const currentMessages = [...options.messages];
|
|
1397
1411
|
for (let i = 0; i < this.subAgents.length; i++) {
|
|
1398
1412
|
const agent = this.subAgents[i];
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
);
|
|
1403
|
-
}
|
|
1413
|
+
this.logger.debug(
|
|
1414
|
+
`Streaming sub-agent ${i + 1}/${this.subAgents.length}: ${agent.name}`
|
|
1415
|
+
);
|
|
1404
1416
|
try {
|
|
1405
1417
|
const streamGenerator = agent.runStreaming({
|
|
1406
1418
|
messages: currentMessages,
|
|
@@ -1432,10 +1444,7 @@ var SequentialAgent = class extends BaseAgent {
|
|
|
1432
1444
|
});
|
|
1433
1445
|
}
|
|
1434
1446
|
} catch (error) {
|
|
1435
|
-
console.error(
|
|
1436
|
-
`[SequentialAgent] Error in streaming sub-agent ${agent.name}:`,
|
|
1437
|
-
error
|
|
1438
|
-
);
|
|
1447
|
+
console.error(`Error in streaming sub-agent ${agent.name}:`, error);
|
|
1439
1448
|
yield {
|
|
1440
1449
|
content: `Error in sub-agent ${agent.name}: ${error instanceof Error ? error.message : String(error)}`,
|
|
1441
1450
|
role: "assistant",
|
|
@@ -1453,7 +1462,9 @@ var SequentialAgent = class extends BaseAgent {
|
|
|
1453
1462
|
};
|
|
1454
1463
|
|
|
1455
1464
|
// src/agents/parallel-agent.ts
|
|
1465
|
+
init_logger();
|
|
1456
1466
|
var ParallelAgent = class extends BaseAgent {
|
|
1467
|
+
logger = new Logger({ name: "ParallelAgent" });
|
|
1457
1468
|
/**
|
|
1458
1469
|
* Constructor for ParallelAgent
|
|
1459
1470
|
*/
|
|
@@ -1473,11 +1484,9 @@ var ParallelAgent = class extends BaseAgent {
|
|
|
1473
1484
|
* Executes all sub-agents in parallel
|
|
1474
1485
|
*/
|
|
1475
1486
|
async run(options) {
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
);
|
|
1480
|
-
}
|
|
1487
|
+
this.logger.debug(
|
|
1488
|
+
`Running ${this.subAgents.length} sub-agents in parallel`
|
|
1489
|
+
);
|
|
1481
1490
|
if (this.subAgents.length === 0) {
|
|
1482
1491
|
return {
|
|
1483
1492
|
content: "No sub-agents defined for parallel execution.",
|
|
@@ -1489,10 +1498,7 @@ var ParallelAgent = class extends BaseAgent {
|
|
|
1489
1498
|
messages: options.messages,
|
|
1490
1499
|
config: options.config
|
|
1491
1500
|
}).catch((error) => {
|
|
1492
|
-
console.error(
|
|
1493
|
-
`[ParallelAgent] Error in sub-agent ${agent.name}:`,
|
|
1494
|
-
error
|
|
1495
|
-
);
|
|
1501
|
+
console.error(`Error in sub-agent ${agent.name}:`, error);
|
|
1496
1502
|
return {
|
|
1497
1503
|
content: `Error in sub-agent ${agent.name}: ${error instanceof Error ? error.message : String(error)}`,
|
|
1498
1504
|
role: "assistant"
|
|
@@ -1520,11 +1526,9 @@ ${result.content || "No content"}
|
|
|
1520
1526
|
* Collects streaming responses from all sub-agents
|
|
1521
1527
|
*/
|
|
1522
1528
|
async *runStreaming(options) {
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
);
|
|
1527
|
-
}
|
|
1529
|
+
this.logger.debug(
|
|
1530
|
+
`Streaming ${this.subAgents.length} sub-agents in parallel`
|
|
1531
|
+
);
|
|
1528
1532
|
if (this.subAgents.length === 0) {
|
|
1529
1533
|
yield {
|
|
1530
1534
|
content: "No sub-agents defined for parallel execution.",
|
|
@@ -1537,10 +1541,7 @@ ${result.content || "No content"}
|
|
|
1537
1541
|
messages: options.messages,
|
|
1538
1542
|
config: options.config
|
|
1539
1543
|
}).catch((error) => {
|
|
1540
|
-
console.error(
|
|
1541
|
-
`[ParallelAgent] Error in sub-agent ${agent.name}:`,
|
|
1542
|
-
error
|
|
1543
|
-
);
|
|
1544
|
+
console.error(`Error in sub-agent ${agent.name}:`, error);
|
|
1544
1545
|
return {
|
|
1545
1546
|
content: `Error in sub-agent ${agent.name}: ${error instanceof Error ? error.message : String(error)}`,
|
|
1546
1547
|
role: "assistant"
|
|
@@ -1590,6 +1591,7 @@ ${response.content || "No content"}
|
|
|
1590
1591
|
};
|
|
1591
1592
|
|
|
1592
1593
|
// src/agents/loop-agent.ts
|
|
1594
|
+
init_logger();
|
|
1593
1595
|
var LoopAgent = class extends BaseAgent {
|
|
1594
1596
|
/**
|
|
1595
1597
|
* Maximum number of iterations to prevent infinite loops
|
|
@@ -1603,6 +1605,7 @@ var LoopAgent = class extends BaseAgent {
|
|
|
1603
1605
|
* Custom condition check function
|
|
1604
1606
|
*/
|
|
1605
1607
|
conditionCheck;
|
|
1608
|
+
logger = new Logger({ name: "LoopAgent" });
|
|
1606
1609
|
/**
|
|
1607
1610
|
* Constructor for LoopAgent
|
|
1608
1611
|
*/
|
|
@@ -1630,28 +1633,20 @@ var LoopAgent = class extends BaseAgent {
|
|
|
1630
1633
|
*/
|
|
1631
1634
|
async shouldContinue(response, iterationCount, messages, config) {
|
|
1632
1635
|
if (iterationCount >= this.maxIterations) {
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
);
|
|
1637
|
-
}
|
|
1636
|
+
this.logger.debug(
|
|
1637
|
+
`Maximum iterations (${this.maxIterations}) reached. Stopping loop.`
|
|
1638
|
+
);
|
|
1638
1639
|
return false;
|
|
1639
1640
|
}
|
|
1640
1641
|
if (this.conditionCheck) {
|
|
1641
1642
|
const shouldContinue = await this.conditionCheck(response);
|
|
1642
|
-
|
|
1643
|
-
console.log(
|
|
1644
|
-
`[LoopAgent] Custom condition check result: ${shouldContinue}`
|
|
1645
|
-
);
|
|
1646
|
-
}
|
|
1643
|
+
this.logger.debug(`Custom condition check result: ${shouldContinue}`);
|
|
1647
1644
|
return shouldContinue;
|
|
1648
1645
|
}
|
|
1649
1646
|
if (this.conditionAgent) {
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
);
|
|
1654
|
-
}
|
|
1647
|
+
this.logger.debug(
|
|
1648
|
+
`Using condition agent ${this.conditionAgent.name} to check loop condition`
|
|
1649
|
+
);
|
|
1655
1650
|
const conditionMessages = [
|
|
1656
1651
|
...messages,
|
|
1657
1652
|
{
|
|
@@ -1670,14 +1665,12 @@ var LoopAgent = class extends BaseAgent {
|
|
|
1670
1665
|
});
|
|
1671
1666
|
const content = conditionResponse.content?.toLowerCase() || "";
|
|
1672
1667
|
const shouldContinue = content.includes("yes") && !content.includes("no");
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
);
|
|
1677
|
-
}
|
|
1668
|
+
this.logger.debug(
|
|
1669
|
+
`Condition agent result: ${shouldContinue ? "Continue loop" : "Stop loop"}`
|
|
1670
|
+
);
|
|
1678
1671
|
return shouldContinue;
|
|
1679
1672
|
} catch (error) {
|
|
1680
|
-
console.error("
|
|
1673
|
+
console.error("Error in condition agent:", error);
|
|
1681
1674
|
return false;
|
|
1682
1675
|
}
|
|
1683
1676
|
}
|
|
@@ -1688,11 +1681,9 @@ var LoopAgent = class extends BaseAgent {
|
|
|
1688
1681
|
* Executes the sub-agent in a loop until the condition is met
|
|
1689
1682
|
*/
|
|
1690
1683
|
async run(options) {
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
);
|
|
1695
|
-
}
|
|
1684
|
+
this.logger.debug(
|
|
1685
|
+
`Starting loop with max ${this.maxIterations} iterations`
|
|
1686
|
+
);
|
|
1696
1687
|
if (this.subAgents.length === 0) {
|
|
1697
1688
|
return {
|
|
1698
1689
|
content: "No sub-agent defined for loop execution.",
|
|
@@ -1706,11 +1697,9 @@ var LoopAgent = class extends BaseAgent {
|
|
|
1706
1697
|
let shouldContinueLoop = true;
|
|
1707
1698
|
while (shouldContinueLoop && iterationCount < this.maxIterations) {
|
|
1708
1699
|
iterationCount++;
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
);
|
|
1713
|
-
}
|
|
1700
|
+
this.logger.debug(
|
|
1701
|
+
`Running iteration ${iterationCount}/${this.maxIterations}`
|
|
1702
|
+
);
|
|
1714
1703
|
try {
|
|
1715
1704
|
const response = await subAgent.run({
|
|
1716
1705
|
messages: currentMessages,
|
|
@@ -1734,10 +1723,7 @@ var LoopAgent = class extends BaseAgent {
|
|
|
1734
1723
|
});
|
|
1735
1724
|
}
|
|
1736
1725
|
} catch (error) {
|
|
1737
|
-
console.error(
|
|
1738
|
-
`[LoopAgent] Error in loop iteration ${iterationCount}:`,
|
|
1739
|
-
error
|
|
1740
|
-
);
|
|
1726
|
+
console.error(`Error in loop iteration ${iterationCount}:`, error);
|
|
1741
1727
|
break;
|
|
1742
1728
|
}
|
|
1743
1729
|
}
|
|
@@ -1758,11 +1744,9 @@ ${lastResponse.content || ""}`,
|
|
|
1758
1744
|
* Runs the agent with streaming support
|
|
1759
1745
|
*/
|
|
1760
1746
|
async *runStreaming(options) {
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
);
|
|
1765
|
-
}
|
|
1747
|
+
this.logger.debug(
|
|
1748
|
+
`Starting loop with max ${this.maxIterations} iterations (streaming)`
|
|
1749
|
+
);
|
|
1766
1750
|
if (this.subAgents.length === 0) {
|
|
1767
1751
|
yield {
|
|
1768
1752
|
content: "No sub-agent defined for loop execution.",
|
|
@@ -1781,11 +1765,9 @@ ${lastResponse.content || ""}`,
|
|
|
1781
1765
|
};
|
|
1782
1766
|
while (shouldContinueLoop && iterationCount < this.maxIterations) {
|
|
1783
1767
|
iterationCount++;
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
);
|
|
1788
|
-
}
|
|
1768
|
+
this.logger.debug(
|
|
1769
|
+
`Running iteration ${iterationCount}/${this.maxIterations} (streaming)`
|
|
1770
|
+
);
|
|
1789
1771
|
yield {
|
|
1790
1772
|
content: `Running iteration ${iterationCount}/${this.maxIterations}...`,
|
|
1791
1773
|
role: "assistant",
|
|
@@ -1809,11 +1791,9 @@ ${lastResponse.content || ""}`,
|
|
|
1809
1791
|
}
|
|
1810
1792
|
}
|
|
1811
1793
|
if (!lastChunk) {
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
);
|
|
1816
|
-
}
|
|
1794
|
+
this.logger.debug(
|
|
1795
|
+
`No complete chunk received from iteration ${iterationCount}`
|
|
1796
|
+
);
|
|
1817
1797
|
shouldContinueLoop = false;
|
|
1818
1798
|
continue;
|
|
1819
1799
|
}
|
|
@@ -1839,9 +1819,8 @@ ${lastResponse.content || ""}`,
|
|
|
1839
1819
|
};
|
|
1840
1820
|
}
|
|
1841
1821
|
} catch (error) {
|
|
1842
|
-
|
|
1843
|
-
`
|
|
1844
|
-
error
|
|
1822
|
+
this.logger.debug(
|
|
1823
|
+
`Error in loop iteration ${iterationCount}: ${error instanceof Error ? error.message : String(error)}`
|
|
1845
1824
|
);
|
|
1846
1825
|
yield {
|
|
1847
1826
|
content: `Error in loop iteration ${iterationCount}: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -1858,6 +1837,7 @@ ${lastResponse.content || ""}`,
|
|
|
1858
1837
|
};
|
|
1859
1838
|
|
|
1860
1839
|
// src/agents/lang-graph-agent.ts
|
|
1840
|
+
init_logger();
|
|
1861
1841
|
var LangGraphAgent = class extends BaseAgent {
|
|
1862
1842
|
/**
|
|
1863
1843
|
* Graph nodes (agents and their connections)
|
|
@@ -1875,6 +1855,7 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
1875
1855
|
* Results from node executions
|
|
1876
1856
|
*/
|
|
1877
1857
|
results = [];
|
|
1858
|
+
logger = new Logger({ name: "LangGraphAgent" });
|
|
1878
1859
|
/**
|
|
1879
1860
|
* Constructor for LangGraphAgent
|
|
1880
1861
|
*/
|
|
@@ -1949,17 +1930,13 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
1949
1930
|
for (const targetName of currentNode.targets) {
|
|
1950
1931
|
const targetNode = this.nodes.get(targetName);
|
|
1951
1932
|
if (!targetNode) {
|
|
1952
|
-
console.error(`
|
|
1933
|
+
console.error(`Target node "${targetName}" not found`);
|
|
1953
1934
|
continue;
|
|
1954
1935
|
}
|
|
1955
1936
|
if (targetNode.condition) {
|
|
1956
1937
|
const shouldExecute = await targetNode.condition(result, context);
|
|
1957
1938
|
if (!shouldExecute) {
|
|
1958
|
-
|
|
1959
|
-
console.log(
|
|
1960
|
-
`[LangGraphAgent] Skipping node "${targetName}" due to condition`
|
|
1961
|
-
);
|
|
1962
|
-
}
|
|
1939
|
+
this.logger.debug(`Skipping node "${targetName}" due to condition`);
|
|
1963
1940
|
continue;
|
|
1964
1941
|
}
|
|
1965
1942
|
}
|
|
@@ -1984,11 +1961,7 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
1984
1961
|
};
|
|
1985
1962
|
const shouldExecute = await node.condition(mockResponse, mockContext);
|
|
1986
1963
|
if (!shouldExecute) {
|
|
1987
|
-
|
|
1988
|
-
console.log(
|
|
1989
|
-
`[LangGraphAgent] Skipping node "${targetName}" due to condition`
|
|
1990
|
-
);
|
|
1991
|
-
}
|
|
1964
|
+
this.logger.debug(`Skipping node "${targetName}" due to condition`);
|
|
1992
1965
|
}
|
|
1993
1966
|
return { shouldExecute };
|
|
1994
1967
|
}
|
|
@@ -2001,11 +1974,9 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
2001
1974
|
messages: options.messages,
|
|
2002
1975
|
config: options.config
|
|
2003
1976
|
});
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
);
|
|
2008
|
-
}
|
|
1977
|
+
this.logger.debug(
|
|
1978
|
+
`Starting graph execution from root node "${this.rootNode}"`
|
|
1979
|
+
);
|
|
2009
1980
|
if (this.nodes.size === 0) {
|
|
2010
1981
|
return {
|
|
2011
1982
|
content: "No nodes defined in the graph.",
|
|
@@ -2025,11 +1996,7 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
2025
1996
|
while (nodesToExecute.length > 0 && stepCount < this.maxSteps) {
|
|
2026
1997
|
stepCount++;
|
|
2027
1998
|
const { node, messages } = nodesToExecute.shift();
|
|
2028
|
-
|
|
2029
|
-
console.log(
|
|
2030
|
-
`[LangGraphAgent] Step ${stepCount}: Executing node "${node.name}"`
|
|
2031
|
-
);
|
|
2032
|
-
}
|
|
1999
|
+
this.logger.debug(`Step ${stepCount}: Executing node "${node.name}"`);
|
|
2033
2000
|
executedNodes.push(node.name);
|
|
2034
2001
|
try {
|
|
2035
2002
|
const result = await node.agent.run({
|
|
@@ -2077,7 +2044,7 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
2077
2044
|
});
|
|
2078
2045
|
}
|
|
2079
2046
|
} catch (error) {
|
|
2080
|
-
console.error(`
|
|
2047
|
+
console.error(`Error in node "${node.name}":`, error);
|
|
2081
2048
|
return {
|
|
2082
2049
|
content: `Error in node "${node.name}": ${error instanceof Error ? error.message : String(error)}`,
|
|
2083
2050
|
role: "assistant"
|
|
@@ -2101,11 +2068,9 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
2101
2068
|
messages: options.messages,
|
|
2102
2069
|
config: options.config
|
|
2103
2070
|
});
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
);
|
|
2108
|
-
}
|
|
2071
|
+
this.logger.debug(
|
|
2072
|
+
`Starting graph execution from root node "${this.rootNode}" (streaming)`
|
|
2073
|
+
);
|
|
2109
2074
|
if (this.nodes.size === 0) {
|
|
2110
2075
|
yield {
|
|
2111
2076
|
content: "No nodes defined in the graph.",
|
|
@@ -2132,11 +2097,9 @@ var LangGraphAgent = class extends BaseAgent {
|
|
|
2132
2097
|
while (nodesToExecute.length > 0 && stepCount < this.maxSteps) {
|
|
2133
2098
|
stepCount++;
|
|
2134
2099
|
const { node, messages } = nodesToExecute.shift();
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
);
|
|
2139
|
-
}
|
|
2100
|
+
this.logger.debug(
|
|
2101
|
+
`Step ${stepCount}: Executing node "${node.name}" (streaming)`
|
|
2102
|
+
);
|
|
2140
2103
|
executedNodes.push(node.name);
|
|
2141
2104
|
try {
|
|
2142
2105
|
const result = await node.agent.run({
|
|
@@ -2190,7 +2153,7 @@ Node output: ${this.extractTextContent(result.content)}` : ""}`,
|
|
|
2190
2153
|
});
|
|
2191
2154
|
}
|
|
2192
2155
|
} catch (error) {
|
|
2193
|
-
console.error(`
|
|
2156
|
+
console.error(`Error in node "${node.name}":`, error);
|
|
2194
2157
|
yield {
|
|
2195
2158
|
content: `Error in node "${node.name}": ${error instanceof Error ? error.message : String(error)}`,
|
|
2196
2159
|
role: "assistant"
|
|
@@ -2250,8 +2213,10 @@ function createFunctionTool(func, options) {
|
|
|
2250
2213
|
init_function_utils();
|
|
2251
2214
|
|
|
2252
2215
|
// src/tools/common/google-search.ts
|
|
2216
|
+
init_logger();
|
|
2253
2217
|
init_base_tool();
|
|
2254
2218
|
var GoogleSearch = class extends BaseTool {
|
|
2219
|
+
logger = new Logger({ name: "GoogleSearch" });
|
|
2255
2220
|
/**
|
|
2256
2221
|
* Constructor for GoogleSearch
|
|
2257
2222
|
*/
|
|
@@ -2290,9 +2255,9 @@ var GoogleSearch = class extends BaseTool {
|
|
|
2290
2255
|
* This is a simplified implementation that doesn't actually search, just returns mock results
|
|
2291
2256
|
*/
|
|
2292
2257
|
async runAsync(args, _context) {
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2258
|
+
this.logger.debug(
|
|
2259
|
+
`[GoogleSearch] Executing Google search for: ${args.query}`
|
|
2260
|
+
);
|
|
2296
2261
|
return {
|
|
2297
2262
|
results: [
|
|
2298
2263
|
{
|
|
@@ -2755,8 +2720,10 @@ var UserInteractionTool = class extends BaseTool {
|
|
|
2755
2720
|
};
|
|
2756
2721
|
|
|
2757
2722
|
// src/tools/common/exit-loop-tool.ts
|
|
2723
|
+
init_logger();
|
|
2758
2724
|
init_base_tool();
|
|
2759
2725
|
var ExitLoopTool = class extends BaseTool {
|
|
2726
|
+
logger = new Logger({ name: "ExitLoopTool" });
|
|
2760
2727
|
/**
|
|
2761
2728
|
* Constructor for ExitLoopTool
|
|
2762
2729
|
*/
|
|
@@ -2784,9 +2751,7 @@ var ExitLoopTool = class extends BaseTool {
|
|
|
2784
2751
|
* Execute the exit loop action
|
|
2785
2752
|
*/
|
|
2786
2753
|
async runAsync(_args, context) {
|
|
2787
|
-
|
|
2788
|
-
console.log("Executing exit loop tool");
|
|
2789
|
-
}
|
|
2754
|
+
this.logger.debug("Executing exit loop tool");
|
|
2790
2755
|
if (context.actions) {
|
|
2791
2756
|
context.actions.escalate = true;
|
|
2792
2757
|
} else {
|
|
@@ -2801,8 +2766,10 @@ var ExitLoopTool = class extends BaseTool {
|
|
|
2801
2766
|
};
|
|
2802
2767
|
|
|
2803
2768
|
// src/tools/common/get-user-choice-tool.ts
|
|
2769
|
+
init_logger();
|
|
2804
2770
|
init_base_tool();
|
|
2805
2771
|
var GetUserChoiceTool = class extends BaseTool {
|
|
2772
|
+
logger = new Logger({ name: "GetUserChoiceTool" });
|
|
2806
2773
|
/**
|
|
2807
2774
|
* Constructor for GetUserChoiceTool
|
|
2808
2775
|
*/
|
|
@@ -2845,13 +2812,11 @@ var GetUserChoiceTool = class extends BaseTool {
|
|
|
2845
2812
|
* and the actual choice will be provided asynchronously
|
|
2846
2813
|
*/
|
|
2847
2814
|
async runAsync(args, context) {
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
console.log(`Question: ${args.question}`);
|
|
2854
|
-
}
|
|
2815
|
+
this.logger.debug(
|
|
2816
|
+
`Executing get_user_choice with options: ${args.options.join(", ")}`
|
|
2817
|
+
);
|
|
2818
|
+
if (args.question) {
|
|
2819
|
+
this.logger.debug(`Question: ${args.question}`);
|
|
2855
2820
|
}
|
|
2856
2821
|
if (context.actions) {
|
|
2857
2822
|
context.actions.skip_summarization = true;
|
|
@@ -2865,8 +2830,10 @@ var GetUserChoiceTool = class extends BaseTool {
|
|
|
2865
2830
|
};
|
|
2866
2831
|
|
|
2867
2832
|
// src/tools/common/transfer-to-agent-tool.ts
|
|
2833
|
+
init_logger();
|
|
2868
2834
|
init_base_tool();
|
|
2869
2835
|
var TransferToAgentTool = class extends BaseTool {
|
|
2836
|
+
logger = new Logger({ name: "TransferToAgentTool" });
|
|
2870
2837
|
/**
|
|
2871
2838
|
* Constructor for TransferToAgentTool
|
|
2872
2839
|
*/
|
|
@@ -2899,9 +2866,7 @@ var TransferToAgentTool = class extends BaseTool {
|
|
|
2899
2866
|
* Execute the transfer to agent action
|
|
2900
2867
|
*/
|
|
2901
2868
|
async runAsync(args, context) {
|
|
2902
|
-
|
|
2903
|
-
console.log(`Executing transfer to agent: ${args.agent_name}`);
|
|
2904
|
-
}
|
|
2869
|
+
this.logger.debug(`Executing transfer to agent: ${args.agent_name}`);
|
|
2905
2870
|
if (context.actions) {
|
|
2906
2871
|
context.actions.transfer_to_agent = args.agent_name;
|
|
2907
2872
|
} else {
|
|
@@ -2916,8 +2881,10 @@ var TransferToAgentTool = class extends BaseTool {
|
|
|
2916
2881
|
};
|
|
2917
2882
|
|
|
2918
2883
|
// src/tools/common/load-memory-tool.ts
|
|
2884
|
+
init_logger();
|
|
2919
2885
|
init_base_tool();
|
|
2920
2886
|
var LoadMemoryTool = class extends BaseTool {
|
|
2887
|
+
logger = new Logger({ name: "LoadMemoryTool" });
|
|
2921
2888
|
/**
|
|
2922
2889
|
* Constructor for LoadMemoryTool
|
|
2923
2890
|
*/
|
|
@@ -2950,9 +2917,7 @@ var LoadMemoryTool = class extends BaseTool {
|
|
|
2950
2917
|
* Execute the memory loading action
|
|
2951
2918
|
*/
|
|
2952
2919
|
async runAsync(args, context) {
|
|
2953
|
-
|
|
2954
|
-
console.log(`Executing load_memory with query: ${args.query}`);
|
|
2955
|
-
}
|
|
2920
|
+
this.logger.debug(`Executing load_memory with query: ${args.query}`);
|
|
2956
2921
|
if (!context.memoryService) {
|
|
2957
2922
|
return {
|
|
2958
2923
|
error: "Memory service is not available",
|
|
@@ -2976,9 +2941,11 @@ var LoadMemoryTool = class extends BaseTool {
|
|
|
2976
2941
|
};
|
|
2977
2942
|
|
|
2978
2943
|
// src/tools/mcp/client.ts
|
|
2944
|
+
init_logger();
|
|
2979
2945
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
2980
2946
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
2981
2947
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
2948
|
+
import { CreateMessageRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2982
2949
|
|
|
2983
2950
|
// src/tools/mcp/types.ts
|
|
2984
2951
|
var McpErrorType = /* @__PURE__ */ ((McpErrorType2) => {
|
|
@@ -2987,6 +2954,8 @@ var McpErrorType = /* @__PURE__ */ ((McpErrorType2) => {
|
|
|
2987
2954
|
McpErrorType2["RESOURCE_CLOSED_ERROR"] = "resource_closed_error";
|
|
2988
2955
|
McpErrorType2["TIMEOUT_ERROR"] = "timeout_error";
|
|
2989
2956
|
McpErrorType2["INVALID_SCHEMA_ERROR"] = "invalid_schema_error";
|
|
2957
|
+
McpErrorType2["SAMPLING_ERROR"] = "SAMPLING_ERROR";
|
|
2958
|
+
McpErrorType2["INVALID_REQUEST_ERROR"] = "INVALID_REQUEST_ERROR";
|
|
2990
2959
|
return McpErrorType2;
|
|
2991
2960
|
})(McpErrorType || {});
|
|
2992
2961
|
var McpError = class extends Error {
|
|
@@ -3034,8 +3003,11 @@ var McpClientService = class {
|
|
|
3034
3003
|
client = null;
|
|
3035
3004
|
transport = null;
|
|
3036
3005
|
isClosing = false;
|
|
3006
|
+
samplingHandler = null;
|
|
3007
|
+
logger = new Logger({ name: "McpClientService" });
|
|
3037
3008
|
constructor(config) {
|
|
3038
3009
|
this.config = config;
|
|
3010
|
+
this.samplingHandler = config.samplingHandler || null;
|
|
3039
3011
|
}
|
|
3040
3012
|
/**
|
|
3041
3013
|
* Initializes and returns an MCP client based on configuration.
|
|
@@ -3084,6 +3056,7 @@ var McpClientService = class {
|
|
|
3084
3056
|
} else {
|
|
3085
3057
|
await connectPromise;
|
|
3086
3058
|
}
|
|
3059
|
+
await this.setupSamplingHandler(client);
|
|
3087
3060
|
if (this.config.debug) {
|
|
3088
3061
|
console.log("\u2705 MCP client connected successfully");
|
|
3089
3062
|
}
|
|
@@ -3235,9 +3208,77 @@ var McpClientService = class {
|
|
|
3235
3208
|
isConnected() {
|
|
3236
3209
|
return !!this.client && !this.isClosing;
|
|
3237
3210
|
}
|
|
3211
|
+
async setupSamplingHandler(client) {
|
|
3212
|
+
if (!this.samplingHandler) {
|
|
3213
|
+
if (this.config.debug) {
|
|
3214
|
+
console.log(
|
|
3215
|
+
"\u26A0\uFE0F No sampling handler provided - sampling requests will be rejected"
|
|
3216
|
+
);
|
|
3217
|
+
}
|
|
3218
|
+
return;
|
|
3219
|
+
}
|
|
3220
|
+
client.setRequestHandler(CreateMessageRequestSchema, async (request) => {
|
|
3221
|
+
try {
|
|
3222
|
+
this.logger.debug("Received sampling request:", request);
|
|
3223
|
+
const samplingRequest = request.params;
|
|
3224
|
+
if (!samplingRequest.messages || !Array.isArray(samplingRequest.messages)) {
|
|
3225
|
+
throw new McpError(
|
|
3226
|
+
"Invalid sampling request: messages array is required",
|
|
3227
|
+
"INVALID_REQUEST_ERROR" /* INVALID_REQUEST_ERROR */
|
|
3228
|
+
);
|
|
3229
|
+
}
|
|
3230
|
+
if (!samplingRequest.maxTokens || samplingRequest.maxTokens <= 0) {
|
|
3231
|
+
throw new McpError(
|
|
3232
|
+
"Invalid sampling request: maxTokens must be a positive number",
|
|
3233
|
+
"INVALID_REQUEST_ERROR" /* INVALID_REQUEST_ERROR */
|
|
3234
|
+
);
|
|
3235
|
+
}
|
|
3236
|
+
const response = await this.samplingHandler({
|
|
3237
|
+
method: request.method,
|
|
3238
|
+
params: request.params
|
|
3239
|
+
});
|
|
3240
|
+
if (this.config.debug) {
|
|
3241
|
+
console.log("\u2705 Sampling request completed successfully");
|
|
3242
|
+
}
|
|
3243
|
+
return response;
|
|
3244
|
+
} catch (error) {
|
|
3245
|
+
console.error("\u274C Error handling sampling request:", error);
|
|
3246
|
+
if (error instanceof McpError) {
|
|
3247
|
+
throw error;
|
|
3248
|
+
}
|
|
3249
|
+
throw new McpError(
|
|
3250
|
+
`Sampling request failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
3251
|
+
"SAMPLING_ERROR" /* SAMPLING_ERROR */,
|
|
3252
|
+
error instanceof Error ? error : void 0
|
|
3253
|
+
);
|
|
3254
|
+
}
|
|
3255
|
+
});
|
|
3256
|
+
if (this.config.debug) {
|
|
3257
|
+
console.log("\u{1F3AF} Sampling handler registered successfully");
|
|
3258
|
+
}
|
|
3259
|
+
}
|
|
3260
|
+
setSamplingHandler(handler) {
|
|
3261
|
+
this.samplingHandler = handler;
|
|
3262
|
+
if (this.client) {
|
|
3263
|
+
this.setupSamplingHandler(this.client).catch((error) => {
|
|
3264
|
+
console.error("Failed to update sampling handler:", error);
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
removeSamplingHandler() {
|
|
3269
|
+
this.samplingHandler = null;
|
|
3270
|
+
if (this.client) {
|
|
3271
|
+
try {
|
|
3272
|
+
this.client.removeRequestHandler?.("sampling/createMessage");
|
|
3273
|
+
} catch (error) {
|
|
3274
|
+
console.error("Failed to remove sampling handler:", error);
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
}
|
|
3238
3278
|
};
|
|
3239
3279
|
|
|
3240
3280
|
// src/tools/mcp/create-tool.ts
|
|
3281
|
+
init_logger();
|
|
3241
3282
|
init_base_tool();
|
|
3242
3283
|
|
|
3243
3284
|
// src/tools/mcp/schema-conversion.ts
|
|
@@ -3440,6 +3481,7 @@ var McpToolAdapter = class extends BaseTool {
|
|
|
3440
3481
|
mcpTool;
|
|
3441
3482
|
client;
|
|
3442
3483
|
clientService = null;
|
|
3484
|
+
logger = new Logger({ name: "McpToolAdapter" });
|
|
3443
3485
|
constructor(mcpTool, client) {
|
|
3444
3486
|
const metadata = mcpTool.metadata || {};
|
|
3445
3487
|
super({
|
|
@@ -3472,9 +3514,7 @@ var McpToolAdapter = class extends BaseTool {
|
|
|
3472
3514
|
}
|
|
3473
3515
|
}
|
|
3474
3516
|
async runAsync(args, _context) {
|
|
3475
|
-
|
|
3476
|
-
console.log(`Executing MCP tool ${this.name} with args:`, args);
|
|
3477
|
-
}
|
|
3517
|
+
this.logger.debug(`Executing MCP tool ${this.name} with args:`, args);
|
|
3478
3518
|
try {
|
|
3479
3519
|
if (typeof this.mcpTool.execute === "function") {
|
|
3480
3520
|
return await this.mcpTool.execute(args);
|
|
@@ -3794,9 +3834,11 @@ var BaseLLMConnection = class {
|
|
|
3794
3834
|
};
|
|
3795
3835
|
|
|
3796
3836
|
// src/models/anthropic-llm.ts
|
|
3837
|
+
init_logger();
|
|
3797
3838
|
import axios from "axios";
|
|
3798
3839
|
|
|
3799
3840
|
// src/models/anthropic-llm-connection.ts
|
|
3841
|
+
init_logger();
|
|
3800
3842
|
var AnthropicLLMConnection = class extends BaseLLMConnection {
|
|
3801
3843
|
/**
|
|
3802
3844
|
* Axios instance for API calls
|
|
@@ -3824,6 +3866,7 @@ var AnthropicLLMConnection = class extends BaseLLMConnection {
|
|
|
3824
3866
|
responseCallback;
|
|
3825
3867
|
errorCallback;
|
|
3826
3868
|
endCallback;
|
|
3869
|
+
logger = new Logger({ name: "AnthropicLlmConnection" });
|
|
3827
3870
|
/**
|
|
3828
3871
|
* Constructor
|
|
3829
3872
|
*/
|
|
@@ -3926,19 +3969,12 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
3926
3969
|
if (!content?.length) return [];
|
|
3927
3970
|
const toolUses = [];
|
|
3928
3971
|
for (const block of content) {
|
|
3929
|
-
|
|
3930
|
-
console.log(
|
|
3931
|
-
"Connection - Processing content block of type:",
|
|
3932
|
-
block.type
|
|
3933
|
-
);
|
|
3934
|
-
}
|
|
3972
|
+
this.logger.debug(`Processing content block of type: ${block.type}`);
|
|
3935
3973
|
if (block.type === "tool_use") {
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
);
|
|
3941
|
-
}
|
|
3974
|
+
this.logger.debug(
|
|
3975
|
+
"Found tool_use block:",
|
|
3976
|
+
JSON.stringify(block, null, 2)
|
|
3977
|
+
);
|
|
3942
3978
|
toolUses.push({
|
|
3943
3979
|
id: block.id || "unknown-id",
|
|
3944
3980
|
name: block.name || "unknown-name",
|
|
@@ -3946,14 +3982,12 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
3946
3982
|
});
|
|
3947
3983
|
}
|
|
3948
3984
|
}
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
);
|
|
3956
|
-
}
|
|
3985
|
+
this.logger.debug(`Found ${toolUses.length} tool uses in content`);
|
|
3986
|
+
if (toolUses.length > 0) {
|
|
3987
|
+
this.logger.debug(
|
|
3988
|
+
"Extracted tool uses:",
|
|
3989
|
+
JSON.stringify(toolUses, null, 2)
|
|
3990
|
+
);
|
|
3957
3991
|
}
|
|
3958
3992
|
return toolUses;
|
|
3959
3993
|
}
|
|
@@ -4047,43 +4081,27 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
4047
4081
|
}
|
|
4048
4082
|
const toolUses = this.extractToolUses(apiResponse.content);
|
|
4049
4083
|
const toolCalls = this.convertToolCalls(toolUses);
|
|
4050
|
-
|
|
4051
|
-
|
|
4052
|
-
|
|
4053
|
-
"Connection - Extracted Tool Uses:",
|
|
4054
|
-
JSON.stringify(toolUses, null, 2)
|
|
4055
|
-
);
|
|
4056
|
-
console.log(
|
|
4057
|
-
"Connection - Converted Tool Calls:",
|
|
4058
|
-
JSON.stringify(toolCalls, null, 2)
|
|
4059
|
-
);
|
|
4060
|
-
}
|
|
4061
|
-
}
|
|
4084
|
+
this.logger.debug(
|
|
4085
|
+
`- Extracted ${toolUses.length} tool uses in content and converted ${toolCalls?.length || 0} tool calls`
|
|
4086
|
+
);
|
|
4062
4087
|
const llmResponse = new LLMResponse({
|
|
4063
4088
|
role: "assistant",
|
|
4064
4089
|
content,
|
|
4065
4090
|
tool_calls: toolCalls?.length ? toolCalls : void 0,
|
|
4066
4091
|
raw_response: apiResponse
|
|
4067
4092
|
});
|
|
4068
|
-
|
|
4069
|
-
|
|
4070
|
-
|
|
4071
|
-
|
|
4072
|
-
|
|
4073
|
-
|
|
4074
|
-
|
|
4075
|
-
|
|
4076
|
-
|
|
4077
|
-
null,
|
|
4078
|
-
2
|
|
4079
|
-
)
|
|
4080
|
-
);
|
|
4081
|
-
}
|
|
4093
|
+
const logObject = {
|
|
4094
|
+
role: llmResponse.role,
|
|
4095
|
+
content: llmResponse.content?.substring(0, 50) + (llmResponse.content && llmResponse.content.length > 50 ? "..." : ""),
|
|
4096
|
+
tool_calls: llmResponse.tool_calls ? `[${llmResponse.tool_calls.length} calls]` : "undefined"
|
|
4097
|
+
};
|
|
4098
|
+
this.logger.debug(
|
|
4099
|
+
"Final LLMResponse object:",
|
|
4100
|
+
JSON.stringify(logObject, null, 2)
|
|
4101
|
+
);
|
|
4082
4102
|
return llmResponse;
|
|
4083
4103
|
} catch (error) {
|
|
4084
|
-
|
|
4085
|
-
console.error("Error sending message to Anthropic:", error);
|
|
4086
|
-
}
|
|
4104
|
+
this.logger.debug("Error sending message to Anthropic:", error);
|
|
4087
4105
|
throw error;
|
|
4088
4106
|
}
|
|
4089
4107
|
}
|
|
@@ -4103,6 +4121,7 @@ var AnthropicLLM = class extends BaseLLM {
|
|
|
4103
4121
|
* Default parameters for requests
|
|
4104
4122
|
*/
|
|
4105
4123
|
defaultParams;
|
|
4124
|
+
logger = new Logger({ name: "AnthropicLLM" });
|
|
4106
4125
|
/**
|
|
4107
4126
|
* Constructor for AnthropicLLM
|
|
4108
4127
|
*/
|
|
@@ -4235,13 +4254,11 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
4235
4254
|
if (!content?.length) return [];
|
|
4236
4255
|
const toolUses = [];
|
|
4237
4256
|
for (const block of content) {
|
|
4238
|
-
|
|
4239
|
-
console.log("Processing content block of type:", block.type);
|
|
4240
|
-
}
|
|
4257
|
+
this.logger.debug(`Processing content block of type: ${block.type}`);
|
|
4241
4258
|
if (block.type === "tool_use") {
|
|
4242
|
-
|
|
4243
|
-
|
|
4244
|
-
|
|
4259
|
+
this.logger.debug(
|
|
4260
|
+
`Found tool_use block: ${JSON.stringify(block, null, 2)}`
|
|
4261
|
+
);
|
|
4245
4262
|
toolUses.push({
|
|
4246
4263
|
id: block.id || "unknown-id",
|
|
4247
4264
|
name: block.name || "unknown-name",
|
|
@@ -4249,12 +4266,10 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
4249
4266
|
});
|
|
4250
4267
|
}
|
|
4251
4268
|
}
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
}
|
|
4257
|
-
}
|
|
4269
|
+
this.logger.debug(
|
|
4270
|
+
`Found ${toolUses.length} tool uses in content`,
|
|
4271
|
+
toolUses
|
|
4272
|
+
);
|
|
4258
4273
|
return toolUses;
|
|
4259
4274
|
}
|
|
4260
4275
|
/**
|
|
@@ -4276,16 +4291,14 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
4276
4291
|
},
|
|
4277
4292
|
responseType: stream ? "stream" : "json"
|
|
4278
4293
|
});
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
|
|
4282
|
-
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
}
|
|
4288
|
-
}
|
|
4294
|
+
this.logger.debug(
|
|
4295
|
+
`API Response done with ${response.status}:`,
|
|
4296
|
+
response.data
|
|
4297
|
+
);
|
|
4298
|
+
this.logger.debug(
|
|
4299
|
+
"API Response content:",
|
|
4300
|
+
response.data.content.map((block) => ({ type: block.type }))
|
|
4301
|
+
);
|
|
4289
4302
|
return response.data;
|
|
4290
4303
|
} catch (error) {
|
|
4291
4304
|
console.error("Error calling Anthropic API:", error);
|
|
@@ -4311,24 +4324,17 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
4311
4324
|
top_p: llmRequest.config.top_p ?? this.defaultParams.top_p,
|
|
4312
4325
|
tools: tools?.length ? tools : void 0
|
|
4313
4326
|
};
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
});
|
|
4321
|
-
}
|
|
4327
|
+
this.logger.debug("API Request:", {
|
|
4328
|
+
model: params.model,
|
|
4329
|
+
messageCount: params.messages.length,
|
|
4330
|
+
systemMessage: params.system ? "present" : "none",
|
|
4331
|
+
tools: params.tools ? params.tools.map((t) => t.name) : "none"
|
|
4332
|
+
});
|
|
4322
4333
|
if (stream) {
|
|
4323
4334
|
throw new Error("Streaming is not supported in this implementation");
|
|
4324
4335
|
}
|
|
4325
4336
|
const response = await this.callAnthropicAPI(params);
|
|
4326
|
-
|
|
4327
|
-
console.log(
|
|
4328
|
-
"Full Response Content:",
|
|
4329
|
-
JSON.stringify(response.content, null, 2)
|
|
4330
|
-
);
|
|
4331
|
-
}
|
|
4337
|
+
this.logger.debug("Full Response Content:", response.content);
|
|
4332
4338
|
let content = "";
|
|
4333
4339
|
for (const block of response.content) {
|
|
4334
4340
|
if (block.type === "text") {
|
|
@@ -4337,43 +4343,26 @@ ${typeof message.content === "string" ? message.content : JSON.stringify(message
|
|
|
4337
4343
|
}
|
|
4338
4344
|
const toolUses = this.extractToolUses(response.content);
|
|
4339
4345
|
const toolCalls = this.convertToolUses(toolUses);
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
console.log(
|
|
4343
|
-
"Extracted Tool Uses:",
|
|
4344
|
-
JSON.stringify(toolUses, null, 2)
|
|
4345
|
-
);
|
|
4346
|
-
console.log(
|
|
4347
|
-
"Converted Tool Calls:",
|
|
4348
|
-
JSON.stringify(toolCalls, null, 2)
|
|
4349
|
-
);
|
|
4350
|
-
}
|
|
4351
|
-
}
|
|
4346
|
+
this.logger.debug("Extracted Tool Uses:", toolUses);
|
|
4347
|
+
this.logger.debug("Converted Tool Calls:", toolCalls);
|
|
4352
4348
|
const llmResponse = new LLMResponse({
|
|
4353
4349
|
role: "assistant",
|
|
4354
4350
|
content,
|
|
4355
4351
|
tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
|
|
4356
4352
|
raw_response: response
|
|
4357
4353
|
});
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
null,
|
|
4368
|
-
2
|
|
4369
|
-
)
|
|
4370
|
-
);
|
|
4371
|
-
}
|
|
4354
|
+
const logObject = {
|
|
4355
|
+
role: llmResponse.role,
|
|
4356
|
+
content: llmResponse.content?.substring(0, 50) + (llmResponse.content && llmResponse.content.length > 50 ? "..." : ""),
|
|
4357
|
+
tool_calls: llmResponse.tool_calls ? `[${llmResponse.tool_calls.length} calls]` : "undefined"
|
|
4358
|
+
};
|
|
4359
|
+
this.logger.debug(
|
|
4360
|
+
"Final LLMResponse object:",
|
|
4361
|
+
JSON.stringify(logObject, null, 2)
|
|
4362
|
+
);
|
|
4372
4363
|
yield llmResponse;
|
|
4373
4364
|
} catch (error) {
|
|
4374
|
-
|
|
4375
|
-
console.error("Error calling Anthropic:", error);
|
|
4376
|
-
}
|
|
4365
|
+
this.logger.debug("Error:", error);
|
|
4377
4366
|
throw error;
|
|
4378
4367
|
}
|
|
4379
4368
|
}
|
|
@@ -4768,6 +4757,7 @@ var GoogleLLM = class extends BaseLLM {
|
|
|
4768
4757
|
};
|
|
4769
4758
|
|
|
4770
4759
|
// src/models/openai-llm.ts
|
|
4760
|
+
init_logger();
|
|
4771
4761
|
import OpenAI from "openai";
|
|
4772
4762
|
|
|
4773
4763
|
// src/models/openai-llm-connection.ts
|
|
@@ -5027,6 +5017,7 @@ var OpenAILLM = class extends BaseLLM {
|
|
|
5027
5017
|
* Default parameters for requests
|
|
5028
5018
|
*/
|
|
5029
5019
|
defaultParams;
|
|
5020
|
+
logger = new Logger({ name: "OpenAILLM" });
|
|
5030
5021
|
/**
|
|
5031
5022
|
* Constructor for OpenAILLM
|
|
5032
5023
|
*/
|
|
@@ -5176,11 +5167,9 @@ var OpenAILLM = class extends BaseLLM {
|
|
|
5176
5167
|
* Convert OpenAI streaming chunk to LLMResponse
|
|
5177
5168
|
*/
|
|
5178
5169
|
convertChunk(chunk) {
|
|
5179
|
-
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
);
|
|
5183
|
-
}
|
|
5170
|
+
this.logger.debug(
|
|
5171
|
+
`Converting chunk - delta: ${JSON.stringify(chunk.delta || {})}`
|
|
5172
|
+
);
|
|
5184
5173
|
const content = chunk.delta?.content;
|
|
5185
5174
|
const result = new LLMResponse({
|
|
5186
5175
|
content: content !== void 0 ? content : null,
|
|
@@ -5221,32 +5210,24 @@ var OpenAILLM = class extends BaseLLM {
|
|
|
5221
5210
|
presence_penalty: llmRequest.config.presence_penalty ?? this.defaultParams.presence_penalty,
|
|
5222
5211
|
stream: shouldStream
|
|
5223
5212
|
};
|
|
5224
|
-
|
|
5225
|
-
|
|
5226
|
-
|
|
5227
|
-
);
|
|
5228
|
-
}
|
|
5213
|
+
this.logger.debug(
|
|
5214
|
+
`Request parameters - model: ${params.model}, messages: ${params.messages.length}, functions: ${params.tools ? params.tools.length : 0}, streaming: ${shouldStream}`
|
|
5215
|
+
);
|
|
5229
5216
|
if (tools && tools.length > 0) {
|
|
5230
5217
|
params.tools = tools;
|
|
5231
5218
|
}
|
|
5232
5219
|
try {
|
|
5233
5220
|
if (shouldStream) {
|
|
5234
|
-
|
|
5235
|
-
console.log("OpenAI: Starting streaming request");
|
|
5236
|
-
}
|
|
5221
|
+
this.logger.debug("Starting streaming request");
|
|
5237
5222
|
const streamResponse = await this.client.chat.completions.create(params);
|
|
5238
5223
|
let partialFunctionCall;
|
|
5239
5224
|
const partialToolCalls = /* @__PURE__ */ new Map();
|
|
5240
5225
|
let accumulatedContent = "";
|
|
5241
5226
|
const asyncIterable = streamResponse;
|
|
5242
|
-
|
|
5243
|
-
console.log("OpenAI: Stream response received, processing chunks");
|
|
5244
|
-
}
|
|
5227
|
+
this.logger.debug("Stream response received, processing chunks");
|
|
5245
5228
|
for await (const chunk of asyncIterable) {
|
|
5246
5229
|
if (!chunk.choices || chunk.choices.length === 0) {
|
|
5247
|
-
|
|
5248
|
-
console.log("OpenAI: Empty chunk received, skipping");
|
|
5249
|
-
}
|
|
5230
|
+
this.logger.debug("Empty chunk received, skipping");
|
|
5250
5231
|
continue;
|
|
5251
5232
|
}
|
|
5252
5233
|
const choice = chunk.choices[0];
|
|
@@ -5254,14 +5235,12 @@ var OpenAILLM = class extends BaseLLM {
|
|
|
5254
5235
|
if (responseChunk.content !== null) {
|
|
5255
5236
|
accumulatedContent += responseChunk.content;
|
|
5256
5237
|
}
|
|
5257
|
-
|
|
5258
|
-
|
|
5259
|
-
|
|
5260
|
-
|
|
5261
|
-
|
|
5262
|
-
|
|
5263
|
-
);
|
|
5264
|
-
}
|
|
5238
|
+
this.logger.debug(
|
|
5239
|
+
`Chunk received - delta: "${choice.delta?.content || ""}"`,
|
|
5240
|
+
`responseChunk content: "${responseChunk.content || ""}"`,
|
|
5241
|
+
`is_partial: ${responseChunk.is_partial}`,
|
|
5242
|
+
`accumulated: "${accumulatedContent.substring(0, 30)}${accumulatedContent.length > 30 ? "..." : ""}"`
|
|
5243
|
+
);
|
|
5265
5244
|
if (responseChunk.function_call) {
|
|
5266
5245
|
if (!partialFunctionCall) {
|
|
5267
5246
|
partialFunctionCall = {
|
|
@@ -5286,37 +5265,27 @@ var OpenAILLM = class extends BaseLLM {
|
|
|
5286
5265
|
}
|
|
5287
5266
|
responseChunk.tool_calls = Array.from(partialToolCalls.values());
|
|
5288
5267
|
}
|
|
5289
|
-
|
|
5290
|
-
console.log("OpenAI: Yielding chunk to caller");
|
|
5291
|
-
}
|
|
5268
|
+
this.logger.debug("Yielding chunk to caller");
|
|
5292
5269
|
yield responseChunk;
|
|
5293
5270
|
}
|
|
5294
5271
|
if (accumulatedContent.length > 0) {
|
|
5295
|
-
|
|
5296
|
-
|
|
5297
|
-
|
|
5298
|
-
);
|
|
5299
|
-
}
|
|
5272
|
+
this.logger.debug(
|
|
5273
|
+
`Yielding final accumulated content: "${accumulatedContent.substring(0, 30)}${accumulatedContent.length > 30 ? "..." : ""}"`
|
|
5274
|
+
);
|
|
5300
5275
|
yield new LLMResponse({
|
|
5301
5276
|
content: accumulatedContent,
|
|
5302
5277
|
role: "assistant",
|
|
5303
5278
|
is_partial: false
|
|
5304
5279
|
});
|
|
5305
5280
|
}
|
|
5306
|
-
|
|
5307
|
-
console.log("OpenAI: Finished processing all stream chunks");
|
|
5308
|
-
}
|
|
5281
|
+
this.logger.debug("Finished processing all stream chunks");
|
|
5309
5282
|
} else {
|
|
5310
|
-
|
|
5311
|
-
console.log("OpenAI: Making non-streaming request");
|
|
5312
|
-
}
|
|
5283
|
+
this.logger.debug("Making non-streaming request");
|
|
5313
5284
|
const response = await this.client.chat.completions.create(params);
|
|
5314
5285
|
if (!response.choices || response.choices.length === 0) {
|
|
5315
5286
|
throw new Error("No response from OpenAI");
|
|
5316
5287
|
}
|
|
5317
|
-
|
|
5318
|
-
console.log("OpenAI: Non-streaming response received");
|
|
5319
|
-
}
|
|
5288
|
+
this.logger.debug("Non-streaming response received");
|
|
5320
5289
|
yield this.convertResponse(response.choices[0]);
|
|
5321
5290
|
}
|
|
5322
5291
|
} catch (error) {
|
|
@@ -5903,6 +5872,7 @@ var InMemoryMemoryService = class {
|
|
|
5903
5872
|
};
|
|
5904
5873
|
|
|
5905
5874
|
// src/memory/persistent-memory-service.ts
|
|
5875
|
+
init_logger();
|
|
5906
5876
|
import fs2 from "fs";
|
|
5907
5877
|
import path2 from "path";
|
|
5908
5878
|
var PersistentMemoryService = class {
|
|
@@ -5918,6 +5888,7 @@ var PersistentMemoryService = class {
|
|
|
5918
5888
|
* File prefix for memory files
|
|
5919
5889
|
*/
|
|
5920
5890
|
filePrefix;
|
|
5891
|
+
logger = new Logger({ name: "PersistentMemoryService" });
|
|
5921
5892
|
/**
|
|
5922
5893
|
* Constructor for PersistentMemoryService
|
|
5923
5894
|
*/
|
|
@@ -6006,11 +5977,9 @@ var PersistentMemoryService = class {
|
|
|
6006
5977
|
}
|
|
6007
5978
|
}
|
|
6008
5979
|
}
|
|
6009
|
-
|
|
6010
|
-
|
|
6011
|
-
|
|
6012
|
-
);
|
|
6013
|
-
}
|
|
5980
|
+
this.logger.debug(
|
|
5981
|
+
`Loaded ${this.inMemoryService.getAllSessions().length} sessions from persistent storage`
|
|
5982
|
+
);
|
|
6014
5983
|
} catch (error) {
|
|
6015
5984
|
console.error("Error loading memory files:", error);
|
|
6016
5985
|
}
|
|
@@ -6074,9 +6043,9 @@ __export(sessions_exports, {
|
|
|
6074
6043
|
PgLiteSessionService: () => PgLiteSessionService,
|
|
6075
6044
|
PostgresSessionService: () => PostgresSessionService,
|
|
6076
6045
|
SessionState: () => SessionState,
|
|
6046
|
+
SqliteSessionService: () => SqliteSessionService,
|
|
6077
6047
|
cloneSession: () => cloneSession,
|
|
6078
6048
|
generateSessionId: () => generateSessionId,
|
|
6079
|
-
sessionsSchema: () => sessionsSchema2,
|
|
6080
6049
|
validateSession: () => validateSession
|
|
6081
6050
|
});
|
|
6082
6051
|
|
|
@@ -6519,6 +6488,191 @@ var PgLiteSessionService = class {
|
|
|
6519
6488
|
}
|
|
6520
6489
|
};
|
|
6521
6490
|
|
|
6491
|
+
// src/sessions/sqlite-session-service.ts
|
|
6492
|
+
import * as fs3 from "fs";
|
|
6493
|
+
import * as path3 from "path";
|
|
6494
|
+
import { eq as eq3 } from "drizzle-orm";
|
|
6495
|
+
import {
|
|
6496
|
+
drizzle as drizzle2
|
|
6497
|
+
} from "drizzle-orm/better-sqlite3";
|
|
6498
|
+
import { integer, text } from "drizzle-orm/sqlite-core";
|
|
6499
|
+
import { sqliteTable } from "drizzle-orm/sqlite-core";
|
|
6500
|
+
var sessionsSchema3 = sqliteTable("sessions", {
|
|
6501
|
+
id: text("id").primaryKey(),
|
|
6502
|
+
userId: text("user_id").notNull(),
|
|
6503
|
+
messages: text("messages", { mode: "json" }).default("[]").$type(),
|
|
6504
|
+
metadata: text("metadata", { mode: "json" }).default("{}").$type(),
|
|
6505
|
+
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
|
|
6506
|
+
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
|
|
6507
|
+
state: text("state", { mode: "json" }).default("{}").$type()
|
|
6508
|
+
});
|
|
6509
|
+
var SqliteSessionService = class {
|
|
6510
|
+
db;
|
|
6511
|
+
sessionsTable;
|
|
6512
|
+
initialized = false;
|
|
6513
|
+
sqliteInstance;
|
|
6514
|
+
constructor(config) {
|
|
6515
|
+
this.sqliteInstance = config.sqlite;
|
|
6516
|
+
const dbPath = this.sqliteInstance.name;
|
|
6517
|
+
if (dbPath && dbPath !== ":memory:") {
|
|
6518
|
+
const dbDir = path3.dirname(dbPath);
|
|
6519
|
+
if (!fs3.existsSync(dbDir)) {
|
|
6520
|
+
fs3.mkdirSync(dbDir, { recursive: true });
|
|
6521
|
+
}
|
|
6522
|
+
}
|
|
6523
|
+
this.db = drizzle2(config.sqlite, {
|
|
6524
|
+
schema: { sessions: sessionsSchema3 }
|
|
6525
|
+
});
|
|
6526
|
+
this.sessionsTable = sessionsSchema3;
|
|
6527
|
+
if (!config.skipTableCreation) {
|
|
6528
|
+
this.initializeDatabase().catch((error) => {
|
|
6529
|
+
console.error("Failed to initialize SQLite database:", error);
|
|
6530
|
+
});
|
|
6531
|
+
}
|
|
6532
|
+
}
|
|
6533
|
+
/**
|
|
6534
|
+
* Initialize the database by creating required tables if they don't exist
|
|
6535
|
+
*/
|
|
6536
|
+
async initializeDatabase() {
|
|
6537
|
+
if (this.initialized) {
|
|
6538
|
+
return;
|
|
6539
|
+
}
|
|
6540
|
+
try {
|
|
6541
|
+
this.sqliteInstance.pragma("journal_mode = WAL");
|
|
6542
|
+
this.sqliteInstance.exec(`
|
|
6543
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
6544
|
+
id TEXT PRIMARY KEY,
|
|
6545
|
+
user_id TEXT NOT NULL,
|
|
6546
|
+
messages TEXT DEFAULT '[]',
|
|
6547
|
+
metadata TEXT DEFAULT '{}',
|
|
6548
|
+
created_at INTEGER NOT NULL,
|
|
6549
|
+
updated_at INTEGER NOT NULL,
|
|
6550
|
+
state TEXT DEFAULT '{}'
|
|
6551
|
+
);
|
|
6552
|
+
`);
|
|
6553
|
+
this.sqliteInstance.exec(`
|
|
6554
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
|
|
6555
|
+
`);
|
|
6556
|
+
this.initialized = true;
|
|
6557
|
+
} catch (error) {
|
|
6558
|
+
console.error("Error initializing SQLite database:", error);
|
|
6559
|
+
throw error;
|
|
6560
|
+
}
|
|
6561
|
+
}
|
|
6562
|
+
/**
|
|
6563
|
+
* Ensure database is initialized before any operation
|
|
6564
|
+
*/
|
|
6565
|
+
async ensureInitialized() {
|
|
6566
|
+
if (!this.initialized) {
|
|
6567
|
+
await this.initializeDatabase();
|
|
6568
|
+
}
|
|
6569
|
+
}
|
|
6570
|
+
generateSessionId() {
|
|
6571
|
+
return `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
6572
|
+
}
|
|
6573
|
+
async createSession(userId, metadata = {}) {
|
|
6574
|
+
await this.ensureInitialized();
|
|
6575
|
+
const sessionId = this.generateSessionId();
|
|
6576
|
+
const now = /* @__PURE__ */ new Date();
|
|
6577
|
+
const sessionState = new SessionState();
|
|
6578
|
+
const newSessionData = {
|
|
6579
|
+
id: sessionId,
|
|
6580
|
+
userId,
|
|
6581
|
+
messages: [],
|
|
6582
|
+
metadata,
|
|
6583
|
+
createdAt: now,
|
|
6584
|
+
updatedAt: now,
|
|
6585
|
+
state: sessionState.toObject()
|
|
6586
|
+
};
|
|
6587
|
+
const results = await this.db.insert(this.sessionsTable).values(newSessionData).returning();
|
|
6588
|
+
const result = results[0];
|
|
6589
|
+
if (!result) {
|
|
6590
|
+
throw new Error(
|
|
6591
|
+
"Failed to create session, no data returned from insert."
|
|
6592
|
+
);
|
|
6593
|
+
}
|
|
6594
|
+
return {
|
|
6595
|
+
id: result.id,
|
|
6596
|
+
userId: result.userId,
|
|
6597
|
+
messages: Array.isArray(result.messages) ? result.messages : [],
|
|
6598
|
+
metadata: result.metadata || {},
|
|
6599
|
+
state: SessionState.fromObject(result.state || {}),
|
|
6600
|
+
createdAt: result.createdAt,
|
|
6601
|
+
updatedAt: result.updatedAt
|
|
6602
|
+
};
|
|
6603
|
+
}
|
|
6604
|
+
async getSession(sessionId) {
|
|
6605
|
+
await this.ensureInitialized();
|
|
6606
|
+
const results = await this.db.select().from(this.sessionsTable).where(eq3(this.sessionsTable.id, sessionId)).limit(1);
|
|
6607
|
+
const sessionData = results[0];
|
|
6608
|
+
if (!sessionData) {
|
|
6609
|
+
return void 0;
|
|
6610
|
+
}
|
|
6611
|
+
return {
|
|
6612
|
+
id: sessionData.id,
|
|
6613
|
+
userId: sessionData.userId,
|
|
6614
|
+
messages: Array.isArray(sessionData.messages) ? sessionData.messages : [],
|
|
6615
|
+
metadata: sessionData.metadata || {},
|
|
6616
|
+
state: SessionState.fromObject(sessionData.state || {}),
|
|
6617
|
+
createdAt: sessionData.createdAt,
|
|
6618
|
+
updatedAt: sessionData.updatedAt
|
|
6619
|
+
};
|
|
6620
|
+
}
|
|
6621
|
+
async updateSession(session) {
|
|
6622
|
+
await this.ensureInitialized();
|
|
6623
|
+
const updateData = {
|
|
6624
|
+
userId: session.userId,
|
|
6625
|
+
messages: session.messages,
|
|
6626
|
+
metadata: session.metadata,
|
|
6627
|
+
updatedAt: /* @__PURE__ */ new Date(),
|
|
6628
|
+
state: session.state.toObject()
|
|
6629
|
+
};
|
|
6630
|
+
await this.db.update(this.sessionsTable).set(updateData).where(eq3(this.sessionsTable.id, session.id));
|
|
6631
|
+
}
|
|
6632
|
+
async listSessions(userId, options) {
|
|
6633
|
+
await this.ensureInitialized();
|
|
6634
|
+
let query = this.db.select().from(this.sessionsTable).where(eq3(this.sessionsTable.userId, userId));
|
|
6635
|
+
if (options?.limit !== void 0 && options.limit > 0) {
|
|
6636
|
+
query = query.limit(options.limit);
|
|
6637
|
+
}
|
|
6638
|
+
const results = await query;
|
|
6639
|
+
return results.map((sessionData) => ({
|
|
6640
|
+
id: sessionData.id,
|
|
6641
|
+
userId: sessionData.userId,
|
|
6642
|
+
messages: Array.isArray(sessionData.messages) ? sessionData.messages : [],
|
|
6643
|
+
metadata: sessionData.metadata || {},
|
|
6644
|
+
state: SessionState.fromObject(sessionData.state || {}),
|
|
6645
|
+
createdAt: sessionData.createdAt,
|
|
6646
|
+
updatedAt: sessionData.updatedAt
|
|
6647
|
+
}));
|
|
6648
|
+
}
|
|
6649
|
+
async deleteSession(sessionId) {
|
|
6650
|
+
await this.ensureInitialized();
|
|
6651
|
+
await this.db.delete(this.sessionsTable).where(eq3(this.sessionsTable.id, sessionId));
|
|
6652
|
+
}
|
|
6653
|
+
async appendEvent(session, event) {
|
|
6654
|
+
await this.ensureInitialized();
|
|
6655
|
+
if (event.is_partial) {
|
|
6656
|
+
return event;
|
|
6657
|
+
}
|
|
6658
|
+
if (event.actions?.stateDelta) {
|
|
6659
|
+
for (const [key, value] of Object.entries(event.actions.stateDelta)) {
|
|
6660
|
+
if (key.startsWith("_temp_")) {
|
|
6661
|
+
continue;
|
|
6662
|
+
}
|
|
6663
|
+
session.state?.set(key, value);
|
|
6664
|
+
}
|
|
6665
|
+
}
|
|
6666
|
+
if (!session.events) {
|
|
6667
|
+
session.events = [];
|
|
6668
|
+
}
|
|
6669
|
+
session.events.push(event);
|
|
6670
|
+
session.updatedAt = /* @__PURE__ */ new Date();
|
|
6671
|
+
await this.updateSession(session);
|
|
6672
|
+
return event;
|
|
6673
|
+
}
|
|
6674
|
+
};
|
|
6675
|
+
|
|
6522
6676
|
// src/sessions/session-util.ts
|
|
6523
6677
|
function generateSessionId() {
|
|
6524
6678
|
return `session-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
|
|
@@ -6886,6 +7040,7 @@ export {
|
|
|
6886
7040
|
SequentialAgent,
|
|
6887
7041
|
SessionState,
|
|
6888
7042
|
sessions_exports as Sessions,
|
|
7043
|
+
SqliteSessionService,
|
|
6889
7044
|
StreamingMode,
|
|
6890
7045
|
ToolContext,
|
|
6891
7046
|
tools_exports as Tools,
|
|
@@ -6902,6 +7057,5 @@ export {
|
|
|
6902
7057
|
mcpSchemaToParameters,
|
|
6903
7058
|
normalizeJsonSchema,
|
|
6904
7059
|
registerProviders,
|
|
6905
|
-
sessionsSchema2 as sessionsSchema,
|
|
6906
7060
|
validateSession
|
|
6907
7061
|
};
|