@axiom-lattice/core 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.eslintrc.json +22 -0
  2. package/.turbo/turbo-build.log +21 -0
  3. package/README.md +47 -0
  4. package/dist/index.d.mts +356 -0
  5. package/dist/index.d.ts +356 -0
  6. package/dist/index.js +2191 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/index.mjs +2159 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/jest.config.js +21 -0
  11. package/package.json +63 -0
  12. package/src/__tests__/AgentManager.test.ts +202 -0
  13. package/src/__tests__/setup.ts +5 -0
  14. package/src/agent_lattice/AgentLatticeManager.ts +216 -0
  15. package/src/agent_lattice/builders/AgentBuilder.ts +79 -0
  16. package/src/agent_lattice/builders/AgentGraphBuilder.ts +22 -0
  17. package/src/agent_lattice/builders/AgentGraphBuilderFactory.ts +70 -0
  18. package/src/agent_lattice/builders/AgentParamsBuilder.ts +86 -0
  19. package/src/agent_lattice/builders/DeepAgentGraphBuilder.ts +46 -0
  20. package/src/agent_lattice/builders/PlanExecuteAgentGraphBuilder.ts +46 -0
  21. package/src/agent_lattice/builders/ReActAgentGraphBuilder.ts +42 -0
  22. package/src/agent_lattice/builders/index.ts +14 -0
  23. package/src/agent_lattice/index.ts +27 -0
  24. package/src/agent_lattice/types.ts +42 -0
  25. package/src/base/BaseLatticeManager.ts +145 -0
  26. package/src/base/index.ts +1 -0
  27. package/src/createPlanExecuteAgent.ts +475 -0
  28. package/src/deep_agent/graph.ts +106 -0
  29. package/src/deep_agent/index.ts +25 -0
  30. package/src/deep_agent/prompts.ts +284 -0
  31. package/src/deep_agent/state.ts +63 -0
  32. package/src/deep_agent/subAgent.ts +185 -0
  33. package/src/deep_agent/tools.ts +273 -0
  34. package/src/deep_agent/types.ts +71 -0
  35. package/src/index.ts +9 -0
  36. package/src/logger/Logger.ts +186 -0
  37. package/src/memory_lattice/DefaultMemorySaver.ts +4 -0
  38. package/src/memory_lattice/MemoryLatticeManager.ts +105 -0
  39. package/src/memory_lattice/index.ts +9 -0
  40. package/src/model_lattice/ModelLattice.ts +208 -0
  41. package/src/model_lattice/ModelLatticeManager.ts +125 -0
  42. package/src/model_lattice/index.ts +1 -0
  43. package/src/tool_lattice/ToolLatticeManager.ts +221 -0
  44. package/src/tool_lattice/get_current_date_time/index.ts +14 -0
  45. package/src/tool_lattice/index.ts +2 -0
  46. package/src/tool_lattice/internet_search/index.ts +66 -0
  47. package/src/types.ts +28 -0
  48. package/src/util/PGMemory.ts +16 -0
  49. package/src/util/genUICard.ts +3 -0
  50. package/src/util/genUIMarkdown.ts +3 -0
  51. package/src/util/getLastHumanMessageData.ts +41 -0
  52. package/src/util/returnAIResponse.ts +30 -0
  53. package/src/util/returnErrorResponse.ts +26 -0
  54. package/src/util/returnFeedbackResponse.ts +25 -0
  55. package/src/util/returnToolResponse.ts +32 -0
  56. package/src/util/withAgentName.ts +220 -0
  57. package/src/util/zod-to-prompt.ts +50 -0
  58. package/tsconfig.json +26 -0
package/dist/index.js ADDED
@@ -0,0 +1,2191 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AgentConfig: () => import_protocols.AgentConfig,
34
+ AgentLatticeManager: () => AgentLatticeManager,
35
+ AgentType: () => import_protocols.AgentType,
36
+ GraphBuildOptions: () => import_protocols.GraphBuildOptions,
37
+ MemoryLatticeManager: () => MemoryLatticeManager,
38
+ MemoryType: () => import_protocols2.MemoryType,
39
+ ModelLatticeManager: () => ModelLatticeManager,
40
+ Protocols: () => Protocols,
41
+ agentLatticeManager: () => agentLatticeManager,
42
+ getAgentClient: () => getAgentClient,
43
+ getAgentConfig: () => getAgentConfig,
44
+ getAgentLattice: () => getAgentLattice,
45
+ getAllAgentConfigs: () => getAllAgentConfigs,
46
+ getCheckpointSaver: () => getCheckpointSaver,
47
+ getModelLattice: () => getModelLattice,
48
+ modelLatticeManager: () => modelLatticeManager,
49
+ registerAgentLattice: () => registerAgentLattice,
50
+ registerAgentLattices: () => registerAgentLattices,
51
+ registerCheckpointSaver: () => registerCheckpointSaver,
52
+ registerModelLattice: () => registerModelLattice,
53
+ validateAgentInput: () => validateAgentInput
54
+ });
55
+ module.exports = __toCommonJS(index_exports);
56
+
57
+ // src/base/BaseLatticeManager.ts
58
+ var _BaseLatticeManager = class _BaseLatticeManager {
59
+ /**
60
+ * 受保护的构造函数,防止外部直接实例化
61
+ */
62
+ constructor() {
63
+ }
64
+ /**
65
+ * 获取管理器实例(由子类实现)
66
+ */
67
+ static getInstance() {
68
+ throw new Error("\u5FC5\u987B\u7531\u5B50\u7C7B\u5B9E\u73B0");
69
+ }
70
+ /**
71
+ * 构造完整的键名,包含类型前缀
72
+ * @param key 原始键名
73
+ */
74
+ getFullKey(key) {
75
+ return `${this.getLatticeType()}.${key}`;
76
+ }
77
+ /**
78
+ * 注册项目
79
+ * @param key 项目键名(不含前缀)
80
+ * @param item 项目实例
81
+ */
82
+ register(key, item) {
83
+ const fullKey = this.getFullKey(key);
84
+ if (_BaseLatticeManager.registry.has(fullKey)) {
85
+ throw new Error(`\u9879\u76EE "${fullKey}" \u5DF2\u7ECF\u5B58\u5728\uFF0C\u65E0\u6CD5\u91CD\u590D\u6CE8\u518C`);
86
+ }
87
+ _BaseLatticeManager.registry.set(fullKey, item);
88
+ }
89
+ /**
90
+ * 获取指定项目
91
+ * @param key 项目键名(不含前缀)
92
+ */
93
+ get(key) {
94
+ const fullKey = this.getFullKey(key);
95
+ return _BaseLatticeManager.registry.get(fullKey);
96
+ }
97
+ /**
98
+ * 获取所有当前类型的项目
99
+ */
100
+ getAll() {
101
+ const prefix = `${this.getLatticeType()}.`;
102
+ const result = [];
103
+ for (const [key, value] of _BaseLatticeManager.registry.entries()) {
104
+ if (key.startsWith(prefix)) {
105
+ result.push(value);
106
+ }
107
+ }
108
+ return result;
109
+ }
110
+ /**
111
+ * 检查项目是否存在
112
+ * @param key 项目键名(不含前缀)
113
+ */
114
+ has(key) {
115
+ const fullKey = this.getFullKey(key);
116
+ return _BaseLatticeManager.registry.has(fullKey);
117
+ }
118
+ /**
119
+ * 移除项目
120
+ * @param key 项目键名(不含前缀)
121
+ */
122
+ remove(key) {
123
+ const fullKey = this.getFullKey(key);
124
+ return _BaseLatticeManager.registry.delete(fullKey);
125
+ }
126
+ /**
127
+ * 清空当前类型的所有项目
128
+ */
129
+ clear() {
130
+ const prefix = `${this.getLatticeType()}.`;
131
+ const keysToDelete = [];
132
+ for (const key of _BaseLatticeManager.registry.keys()) {
133
+ if (key.startsWith(prefix)) {
134
+ keysToDelete.push(key);
135
+ }
136
+ }
137
+ for (const key of keysToDelete) {
138
+ _BaseLatticeManager.registry.delete(key);
139
+ }
140
+ }
141
+ /**
142
+ * 获取当前类型的项目数量
143
+ */
144
+ count() {
145
+ const prefix = `${this.getLatticeType()}.`;
146
+ let count = 0;
147
+ for (const key of _BaseLatticeManager.registry.keys()) {
148
+ if (key.startsWith(prefix)) {
149
+ count++;
150
+ }
151
+ }
152
+ return count;
153
+ }
154
+ /**
155
+ * 获取当前类型的项目键名列表(不含前缀)
156
+ */
157
+ keys() {
158
+ const prefix = `${this.getLatticeType()}.`;
159
+ const prefixLength = prefix.length;
160
+ const result = [];
161
+ for (const key of _BaseLatticeManager.registry.keys()) {
162
+ if (key.startsWith(prefix)) {
163
+ result.push(key.substring(prefixLength));
164
+ }
165
+ }
166
+ return result;
167
+ }
168
+ };
169
+ // 全局统一的Lattice注册表
170
+ _BaseLatticeManager.registry = /* @__PURE__ */ new Map();
171
+ var BaseLatticeManager = _BaseLatticeManager;
172
+
173
+ // src/model_lattice/ModelLattice.ts
174
+ var import_deepseek = require("@langchain/deepseek");
175
+ var import_openai = require("@langchain/openai");
176
+ var import_chat_models = require("@langchain/core/language_models/chat_models");
177
+ var import_base = require("@langchain/core/language_models/base");
178
+ var ModelLattice = class extends import_chat_models.BaseChatModel {
179
+ /**
180
+ * 构造函数
181
+ * @param config LLM配置
182
+ */
183
+ constructor(config) {
184
+ super({});
185
+ this.lc_namespace = ["langchain", "model_lattice"];
186
+ this.config = config;
187
+ this.llm = this.initChatModel(config);
188
+ }
189
+ /**
190
+ * 返回模型类型
191
+ */
192
+ _llmType() {
193
+ return "model_lattice";
194
+ }
195
+ /**
196
+ * 返回模型类型
197
+ */
198
+ _modelType() {
199
+ return this.llm._modelType();
200
+ }
201
+ /**
202
+ * 实现BaseChatModel的_generate方法
203
+ * @param messages 消息数组
204
+ * @param options 调用选项
205
+ * @param runManager 回调管理器
206
+ * @returns 聊天结果
207
+ */
208
+ async _generate(messages, options, runManager) {
209
+ return this.llm._generate(messages, options, runManager);
210
+ }
211
+ /**
212
+ * 将工具绑定到模型
213
+ * @param tools 工具列表
214
+ * @param tool_choice 工具选择选项
215
+ * @returns 绑定工具后的模型
216
+ */
217
+ bindTools(tools, {
218
+ tool_choice = "auto",
219
+ ...kwargs
220
+ } = {}) {
221
+ if (typeof this.llm.bindTools === "function") {
222
+ return this.llm.bindTools(tools, {
223
+ tool_choice,
224
+ ...kwargs
225
+ });
226
+ }
227
+ throw new Error("llm not support bindTools");
228
+ }
229
+ /**
230
+ * 使用结构化输出调用LLM
231
+ * @param input 输入
232
+ * @param schema 结构化输出的schema
233
+ * @param options 调用选项
234
+ * @returns 结构化输出
235
+ */
236
+ async invokeWithStructuredOutput(input, schema, options) {
237
+ if (this.llm.withStructuredOutput) {
238
+ const structuredLLM = this.llm.withStructuredOutput(schema, {
239
+ includeRaw: options?.includeRaw ?? false,
240
+ name: options?.name,
241
+ method: options?.method
242
+ });
243
+ return structuredLLM.invoke(input, options);
244
+ }
245
+ throw new Error("\u5F53\u524DLLM\u4E0D\u652F\u6301\u7ED3\u6784\u5316\u8F93\u51FA");
246
+ }
247
+ /**
248
+ * 创建LLM实例
249
+ * @param config LLM配置
250
+ * @returns LLM实例
251
+ */
252
+ initChatModel(config) {
253
+ if (config.provider === "azure") {
254
+ return new import_openai.AzureChatOpenAI({
255
+ azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
256
+ azureOpenAIApiInstanceName: "convertlab-westus",
257
+ azureOpenAIApiDeploymentName: config.model,
258
+ azureOpenAIApiVersion: "2024-02-01",
259
+ temperature: config.temperature || 0,
260
+ maxTokens: config.maxTokens,
261
+ timeout: config.timeout,
262
+ maxRetries: config.maxRetries || 2,
263
+ streaming: config.streaming
264
+ });
265
+ } else if (config.provider === "deepseek") {
266
+ return new import_deepseek.ChatDeepSeek({
267
+ model: config.model,
268
+ temperature: config.temperature || 0,
269
+ maxTokens: config.maxTokens,
270
+ timeout: config.timeout,
271
+ maxRetries: config.maxRetries || 2,
272
+ apiKey: process.env[config.apiKeyEnvName || "DEEPSEEK_API_KEY"],
273
+ streaming: config.streaming
274
+ });
275
+ } else if (config.provider === "siliconcloud") {
276
+ return new import_openai.ChatOpenAI({
277
+ model: config.model,
278
+ temperature: config.temperature || 0,
279
+ maxTokens: config.maxTokens,
280
+ timeout: config.timeout,
281
+ maxRetries: config.maxRetries || 2,
282
+ apiKey: process.env[config.apiKeyEnvName || "SILICONCLOUD_API_KEY"],
283
+ configuration: {
284
+ baseURL: "https://api.siliconflow.cn/v1"
285
+ },
286
+ streaming: config.streaming
287
+ });
288
+ } else if (config.provider === "volcengine") {
289
+ return new import_openai.ChatOpenAI({
290
+ model: config.model,
291
+ temperature: config.temperature || 0,
292
+ maxTokens: config.maxTokens,
293
+ timeout: config.timeout,
294
+ maxRetries: config.maxRetries || 2,
295
+ apiKey: process.env[config.apiKeyEnvName || "VOLCENGINE_API_KEY"],
296
+ configuration: {
297
+ baseURL: "https://ark.cn-beijing.volces.com/api/v3"
298
+ },
299
+ streaming: config.streaming
300
+ });
301
+ } else {
302
+ return new import_openai.ChatOpenAI({
303
+ model: config.model,
304
+ temperature: config.temperature || 0,
305
+ maxTokens: config.maxTokens,
306
+ timeout: config.timeout,
307
+ maxRetries: config.maxRetries || 2,
308
+ streaming: config.streaming,
309
+ apiKey: process.env[config.apiKeyEnvName || "OPENAI_API_KEY"],
310
+ configuration: {
311
+ baseURL: config.baseURL
312
+ }
313
+ });
314
+ }
315
+ }
316
+ };
317
+
318
+ // src/model_lattice/ModelLatticeManager.ts
319
+ var ModelLatticeManager = class _ModelLatticeManager extends BaseLatticeManager {
320
+ /**
321
+ * 获取ModelLatticeManager单例实例
322
+ */
323
+ static getInstance() {
324
+ if (!_ModelLatticeManager._instance) {
325
+ _ModelLatticeManager._instance = new _ModelLatticeManager();
326
+ }
327
+ return _ModelLatticeManager._instance;
328
+ }
329
+ /**
330
+ * 获取Lattice类型前缀
331
+ */
332
+ getLatticeType() {
333
+ return "models";
334
+ }
335
+ /**
336
+ * 注册模型Lattice
337
+ * @param key Lattice键名
338
+ * @param config 模型配置
339
+ */
340
+ registerLattice(key, config) {
341
+ const client = new ModelLattice(config);
342
+ const modelLattice = {
343
+ key,
344
+ client
345
+ };
346
+ this.register(key, modelLattice);
347
+ }
348
+ /**
349
+ * 获取ModelLattice
350
+ * @param key Lattice键名
351
+ */
352
+ getModelLattice(key) {
353
+ const modelLattice = this.get(key);
354
+ if (!modelLattice) {
355
+ throw new Error(`ModelLattice ${key} not found`);
356
+ }
357
+ return modelLattice;
358
+ }
359
+ /**
360
+ * 获取所有Lattice
361
+ */
362
+ getAllLattices() {
363
+ return this.getAll();
364
+ }
365
+ /**
366
+ * 检查Lattice是否存在
367
+ * @param key Lattice键名
368
+ */
369
+ hasLattice(key) {
370
+ return this.has(key);
371
+ }
372
+ /**
373
+ * 移除Lattice
374
+ * @param key Lattice键名
375
+ */
376
+ removeLattice(key) {
377
+ return this.remove(key);
378
+ }
379
+ /**
380
+ * 清空所有Lattice
381
+ */
382
+ clearLattices() {
383
+ this.clear();
384
+ }
385
+ /**
386
+ * 获取Lattice数量
387
+ */
388
+ getLatticeCount() {
389
+ return this.count();
390
+ }
391
+ /**
392
+ * 获取Lattice键名列表
393
+ */
394
+ getLatticeKeys() {
395
+ return this.keys();
396
+ }
397
+ };
398
+ var modelLatticeManager = ModelLatticeManager.getInstance();
399
+ var registerModelLattice = (key, config) => modelLatticeManager.registerLattice(key, config);
400
+ var getModelLattice = (key) => modelLatticeManager.getModelLattice(key);
401
+
402
+ // src/tool_lattice/get_current_date_time/index.ts
403
+ var import_zod = __toESM(require("zod"));
404
+
405
+ // src/tool_lattice/ToolLatticeManager.ts
406
+ var import_tools = require("@langchain/core/tools");
407
+ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
408
+ /**
409
+ * 获取ToolLatticeManager单例实例
410
+ */
411
+ static getInstance() {
412
+ if (!_ToolLatticeManager._instance) {
413
+ _ToolLatticeManager._instance = new _ToolLatticeManager();
414
+ }
415
+ return _ToolLatticeManager._instance;
416
+ }
417
+ /**
418
+ * 获取Lattice类型前缀
419
+ */
420
+ getLatticeType() {
421
+ return "tools";
422
+ }
423
+ /**
424
+ * 注册工具Lattice
425
+ * @param key Lattice键名
426
+ * @param config 工具配置(定义)
427
+ * @param executor 工具执行函数
428
+ */
429
+ registerLattice(key, config, executor) {
430
+ let toolExecutor = async (input, exe_config) => {
431
+ const result = await executor(input, exe_config);
432
+ return result;
433
+ };
434
+ const toolLattice = {
435
+ key,
436
+ config,
437
+ client: (0, import_tools.tool)(toolExecutor, config)
438
+ };
439
+ this.register(key, toolLattice);
440
+ }
441
+ /**
442
+ * 获取ToolLattice
443
+ * @param key Lattice键名
444
+ */
445
+ getToolLattice(key) {
446
+ return this.get(key);
447
+ }
448
+ /**
449
+ * 获取所有Lattice
450
+ */
451
+ getAllLattices() {
452
+ return this.getAll();
453
+ }
454
+ /**
455
+ * 检查Lattice是否存在
456
+ * @param key Lattice键名
457
+ */
458
+ hasLattice(key) {
459
+ return this.has(key);
460
+ }
461
+ /**
462
+ * 移除Lattice
463
+ * @param key Lattice键名
464
+ */
465
+ removeLattice(key) {
466
+ return this.remove(key);
467
+ }
468
+ /**
469
+ * 清空所有Lattice
470
+ */
471
+ clearLattices() {
472
+ this.clear();
473
+ }
474
+ /**
475
+ * 获取Lattice数量
476
+ */
477
+ getLatticeCount() {
478
+ return this.count();
479
+ }
480
+ /**
481
+ * 获取Lattice键名列表
482
+ */
483
+ getLatticeKeys() {
484
+ return this.keys();
485
+ }
486
+ /**
487
+ * 获取工具定义
488
+ * @param key Lattice键名
489
+ */
490
+ getToolDefinition(key) {
491
+ const toolLattice = this.getToolLattice(key);
492
+ if (!toolLattice) {
493
+ throw new Error(`ToolLattice ${key} not found`);
494
+ }
495
+ return toolLattice.config;
496
+ }
497
+ /**
498
+ * 获取工具客户端
499
+ * @param key Lattice键名
500
+ */
501
+ getToolClient(key) {
502
+ const toolLattice = this.getToolLattice(key);
503
+ if (!toolLattice) {
504
+ throw new Error(`ToolLattice ${key} not found`);
505
+ }
506
+ return toolLattice.client;
507
+ }
508
+ /**
509
+ * 获取所有工具定义
510
+ */
511
+ getAllToolDefinitions() {
512
+ return this.getAllLattices().map((lattice) => lattice.config);
513
+ }
514
+ /**
515
+ * 验证工具输入参数
516
+ * @param key Lattice键名
517
+ * @param input 输入参数
518
+ */
519
+ validateToolInput(key, input) {
520
+ const toolLattice = this.getToolLattice(key);
521
+ if (!toolLattice) {
522
+ return false;
523
+ }
524
+ try {
525
+ if (toolLattice.config.schema) {
526
+ toolLattice.config.schema.parse(input);
527
+ }
528
+ return true;
529
+ } catch {
530
+ return false;
531
+ }
532
+ }
533
+ };
534
+ var toolLatticeManager = ToolLatticeManager.getInstance();
535
+ var registerToolLattice = (key, config, executor) => toolLatticeManager.registerLattice(key, config, executor);
536
+ var getToolClient = (key) => toolLatticeManager.getToolClient(key);
537
+
538
+ // src/tool_lattice/get_current_date_time/index.ts
539
+ registerToolLattice(
540
+ "get_current_date_time",
541
+ {
542
+ name: "\u83B7\u53D6\u5F53\u524D\u65E5\u671F\u65F6\u95F4",
543
+ description: "\u83B7\u53D6\u5F53\u524D\u65E5\u671F\u65F6\u95F4",
544
+ schema: import_zod.default.object({})
545
+ },
546
+ async () => {
547
+ return "\u5F53\u524D\u65E5\u671F\u65F6\u95F4\uFF1A" + (/* @__PURE__ */ new Date()).toLocaleString();
548
+ }
549
+ );
550
+
551
+ // src/tool_lattice/internet_search/index.ts
552
+ var import_zod2 = __toESM(require("zod"));
553
+ var import_tavily = require("@langchain/tavily");
554
+ var import_config = require("dotenv/config");
555
+
556
+ // src/util/genUICard.ts
557
+ var genUICard = (title, type, data) => {
558
+ return [title, "```" + type, JSON.stringify(data), "```"].join("\n");
559
+ };
560
+
561
+ // src/tool_lattice/internet_search/index.ts
562
+ registerToolLattice(
563
+ "internet_search",
564
+ {
565
+ name: "internet_search",
566
+ description: "Run a web search",
567
+ needUserApprove: true,
568
+ schema: import_zod2.default.object({
569
+ query: import_zod2.default.string().describe("The search query"),
570
+ maxResults: import_zod2.default.number().optional().default(5).describe("Maximum number of results to return"),
571
+ topic: import_zod2.default.enum(["general", "news", "finance"]).optional().default("general").describe("Search topic category"),
572
+ includeRawContent: import_zod2.default.boolean().optional().default(false).describe("Whether to include raw content")
573
+ })
574
+ },
575
+ async ({
576
+ query,
577
+ maxResults = 5,
578
+ topic = "general",
579
+ includeRawContent = false
580
+ }, config) => {
581
+ const tavilySearch = new import_tavily.TavilySearch({
582
+ maxResults,
583
+ tavilyApiKey: process.env.TAVILY_API_KEY,
584
+ includeRawContent,
585
+ topic
586
+ });
587
+ const tavilyResponse = await tavilySearch.invoke({ query });
588
+ return genUICard("Internet Search:" + query, "generic_data_table", {
589
+ dataSource: tavilyResponse.results
590
+ });
591
+ }
592
+ );
593
+
594
+ // src/agent_lattice/types.ts
595
+ var import_protocols = require("@axiom-lattice/protocols");
596
+
597
+ // src/agent_lattice/builders/ReActAgentGraphBuilder.ts
598
+ var import_prebuilt = require("@langchain/langgraph/prebuilt");
599
+ var ReActAgentGraphBuilder = class {
600
+ /**
601
+ * 构建ReAct Agent Graph
602
+ *
603
+ * @param agentLattice Agent Lattice对象
604
+ * @param params Agent构建参数
605
+ * @returns 返回CompiledGraph对象
606
+ */
607
+ build(agentLattice, params) {
608
+ const tools = params.tools.map((t) => {
609
+ const tool5 = getToolClient(t.key);
610
+ return tool5;
611
+ }).filter((tool5) => tool5 !== void 0);
612
+ return (0, import_prebuilt.createReactAgent)({
613
+ llm: params.model,
614
+ tools,
615
+ prompt: params.prompt,
616
+ name: agentLattice.config.name
617
+ });
618
+ }
619
+ };
620
+
621
+ // src/deep_agent/subAgent.ts
622
+ var import_tools3 = require("@langchain/core/tools");
623
+ var import_messages2 = require("@langchain/core/messages");
624
+ var import_langgraph2 = require("@langchain/langgraph");
625
+ var import_prebuilt2 = require("@langchain/langgraph/prebuilt");
626
+ var import_zod4 = require("zod");
627
+
628
+ // src/deep_agent/tools.ts
629
+ var import_tools2 = require("@langchain/core/tools");
630
+ var import_messages = require("@langchain/core/messages");
631
+ var import_langgraph = require("@langchain/langgraph");
632
+ var import_zod3 = require("zod");
633
+
634
+ // src/deep_agent/prompts.ts
635
+ var WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. It also helps the user understand the progress of the task and overall progress of their requests.
636
+
637
+ When to Use This Tool
638
+ Use this tool proactively in these scenarios:
639
+
640
+ Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
641
+ Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
642
+ User explicitly requests todo list - When the user directly asks you to use the todo list
643
+ User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
644
+ After receiving new instructions - Immediately capture user requirements as todos
645
+ When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
646
+ After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
647
+ When NOT to Use This Tool
648
+ Skip using this tool when:
649
+
650
+ There is only a single, straightforward task
651
+ The task is trivial and tracking it provides no organizational benefit
652
+ The task can be completed in less than 3 trivial steps
653
+ The task is purely conversational or informational
654
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
655
+
656
+ Examples of When to Use the Todo List
657
+ <example>
658
+ User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
659
+ Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
660
+ *Creates todo list with the following items:*
661
+ 1. Create dark mode toggle component in Settings page
662
+ 2. Add dark mode state management (context/store)
663
+ 3. Implement CSS-in-JS styles for dark theme
664
+ 4. Update existing components to support theme switching
665
+ 5. Run tests and build process, addressing any failures or errors that occur
666
+ *Begins working on the first task*
667
+ <reasoning>
668
+ The assistant used the todo list because:
669
+ 1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
670
+ 2. The user explicitly requested tests and build be run afterward
671
+ 3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
672
+ </reasoning>
673
+ </example>
674
+ <example>
675
+ User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
676
+ Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.
677
+ *Creates todo list with the following items:*
678
+ 1. Define target audience and key messaging
679
+ 2. Create social media content calendar and posting schedule
680
+ 3. Design email marketing sequence and automation flows
681
+ 4. Draft press release and identify media contacts
682
+ 5. Set up tracking and analytics for campaign performance
683
+ 6. Create visual assets and brand materials
684
+ 7. Coordinate launch timeline and deliverables
685
+ *Begins working on the first task*
686
+ <reasoning>
687
+ The assistant used the todo list because:
688
+ 1. Marketing campaign planning involves multiple distinct channels and activities
689
+ 2. Each component requires careful coordination and planning
690
+ 3. The systematic approach ensures all aspects of the launch are covered
691
+ 4. Progress tracking helps maintain timeline and deliverables
692
+ </reasoning>
693
+ </example>
694
+ <example>
695
+ User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
696
+ Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
697
+ *Uses search tools to locate all instances of getCwd in the codebase*
698
+ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
699
+ *Creates todo list with specific items for each file that needs updating*
700
+ <reasoning>
701
+ The assistant used the todo list because:
702
+ 1. First, the assistant searched to understand the scope of the task
703
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
704
+ 3. The todo list helps ensure every instance is tracked and updated systematically
705
+ 4. This approach prevents missing any occurrences and maintains consistency
706
+ </reasoning>
707
+ </example>
708
+ <example>
709
+ User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
710
+ Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
711
+ *Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines*
712
+ Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
713
+ <reasoning>
714
+ The assistant used the todo list because:
715
+ 1. The user provided multiple distinct organizational tasks
716
+ 2. Each area requires different approaches and careful planning
717
+ 3. Home organization benefits from systematic, step-by-step completion
718
+ 4. Progress tracking ensures all areas are addressed thoroughly
719
+ </reasoning>
720
+ </example>
721
+ Examples of When NOT to Use the Todo List
722
+ <example>
723
+ User: How do I print 'Hello World' in Python?
724
+ Assistant: In Python, you can print "Hello World" with this simple code:
725
+
726
+ \`\`\`python
727
+ print("Hello World")
728
+ \`\`\`
729
+
730
+ This will output the text "Hello World" to the console when executed.
731
+ <reasoning>
732
+ The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
733
+ </reasoning>
734
+ </example>
735
+ <example>
736
+ User: What's the best way to water houseplants?
737
+ Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
738
+
739
+ Check soil moisture by inserting your finger about 1-2 inches into the soil
740
+ Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
741
+ Use room temperature water and water in the morning when possible
742
+ Avoid overwatering, which is more harmful than underwatering for most plants
743
+
744
+ Different plants have different needs, so it's important to research your specific varieties for optimal care.
745
+
746
+ <reasoning>
747
+ The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities.
748
+ </reasoning>
749
+ </example>
750
+ <example>
751
+ User: Can you add a comment to the calculateTotal function to explain what it does?
752
+ Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
753
+ * Uses the Edit tool to add a comment to the calculateTotal function *
754
+ <reasoning>
755
+ The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization.
756
+ </reasoning>
757
+ </example>
758
+ <example>
759
+ User: What time is it in Tokyo right now?
760
+ Assistant: I'll check the current time in Tokyo for you.
761
+
762
+ *Searches for current time in Tokyo*
763
+
764
+ The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
765
+
766
+ <reasoning>
767
+ The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request.
768
+ </reasoning>
769
+ </example>
770
+ Task States and Management
771
+ Task States: Use these states to track progress:
772
+
773
+ pending: Task not yet started
774
+ in_progress: Currently working on (limit to ONE task at a time)
775
+ completed: Task finished successfully
776
+ Task Management:
777
+
778
+ Update task status in real-time as you work
779
+ Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
780
+ Only have ONE task in_progress at any time
781
+ Complete current tasks before starting new ones
782
+ Remove tasks that are no longer relevant from the list entirely
783
+ Task Completion Requirements:
784
+
785
+ ONLY mark a task as completed when you have FULLY accomplished it
786
+ If you encounter errors, blockers, or cannot finish, keep the task as in_progress
787
+ When blocked, create a new task describing what needs to be resolved
788
+ Never mark a task as completed if:
789
+ There are unresolved issues or errors
790
+ Work is partial or incomplete
791
+ You encountered blockers that prevent completion
792
+ You couldn't find necessary resources or dependencies
793
+ Quality standards haven't been met
794
+ Task Breakdown:
795
+
796
+ Create specific, actionable items
797
+ Break complex tasks into smaller, manageable steps
798
+ Use clear, descriptive task names
799
+ When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`;
800
+ var TASK_DESCRIPTION_PREFIX = `Launch a new agent to handle complex, multi-step tasks autonomously.
801
+
802
+ Available agent types and the tools they have access to:
803
+
804
+ general-purpose: General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. (Tools: *)
805
+ {other_agents}
806
+ `;
807
+ var TASK_DESCRIPTION_SUFFIX = `When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
808
+
809
+ When to use the Agent tool:
810
+
811
+ When you are instructed to execute custom slash commands. Use the Agent tool with the slash command invocation as the entire prompt. The slash command can take arguments. For example: Task(description="Check the file", prompt="/check-file path/to/file.py")
812
+ When NOT to use the Agent tool:
813
+
814
+ If you want to read a specific file path, use the Read or Glob tool instead of the Agent tool, to find the match more quickly
815
+ If you are searching for a specific term or definition within a known location, use the Glob tool instead, to find the match more quickly
816
+ If you are searching for content within a specific file or set of 2-3 files, use the Read tool instead of the Agent tool, to find the match more quickly
817
+ Other tasks that are not related to the agent descriptions above
818
+ Usage notes:
819
+
820
+ Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
821
+ When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
822
+ Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
823
+ The agent's outputs should generally be trusted
824
+ Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
825
+ If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
826
+ Example usage:
827
+
828
+ <example_agent_descriptions>
829
+ "content-reviewer": use this agent after you are done creating significant content or documents
830
+ "greeting-responder": use this agent when to respond to user greetings with a friendly joke
831
+ "research-analyst": use this agent to conduct thorough research on complex topics
832
+ </example_agent_description>
833
+
834
+ <example>
835
+ user: "Please write a function that checks if a number is prime"
836
+ assistant: Sure let me write a function that checks if a number is prime
837
+ assistant: First let me use the Write tool to write a function that checks if a number is prime
838
+ assistant: I'm going to use the Write tool to write the following code:
839
+ <code>
840
+ function isPrime(n) {
841
+ if (n <= 1) return false
842
+ for (let i = 2; i * i <= n; i++) {
843
+ if (n % i === 0) return false
844
+ }
845
+ return true
846
+ }
847
+ </code>
848
+ <commentary>
849
+ Since significant content was created and the task was completed, now use the content-reviewer agent to review the work
850
+ </commentary>
851
+ assistant: Now let me use the content-reviewer agent to review the code
852
+ assistant: Uses the Task tool to launch with the content-reviewer agent
853
+ </example>
854
+ <example>
855
+ user: "Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?"
856
+ <commentary>
857
+ This is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis
858
+ </commentary>
859
+ assistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic.
860
+ assistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take
861
+ </example>
862
+ <example>
863
+ user: "Hello"
864
+ <commentary>
865
+ Since the user is greeting, use the greeting-responder agent to respond with a friendly joke
866
+ </commentary>
867
+ assistant: "I'm going to use the Task tool to launch with the greeting-responder agent"
868
+ </example>`;
869
+ var EDIT_DESCRIPTION = `Performs exact string replacements in files.
870
+ Usage:
871
+
872
+ You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
873
+ When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
874
+ ALWAYS prefer editing existing files. NEVER write new files unless explicitly required.
875
+ Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
876
+ The edit will FAIL if old_string is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use replace_all to change every instance of old_string.
877
+ Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;
878
+ var TOOL_DESCRIPTION = `Reads a file from the local filesystem. You can access any file directly by using this tool. Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
879
+ Usage:
880
+
881
+ The file_path parameter must be an absolute path, not a relative path
882
+ By default, it reads up to 2000 lines starting from the beginning of the file
883
+ You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
884
+ Any lines longer than 2000 characters will be truncated
885
+ Results are returned using cat -n format, with line numbers starting at 1
886
+ You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
887
+ If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;
888
+
889
+ // src/deep_agent/tools.ts
890
+ var writeTodos = (0, import_tools2.tool)(
891
+ (input, config) => {
892
+ return new import_langgraph.Command({
893
+ update: {
894
+ todos: input.todos,
895
+ messages: [
896
+ new import_messages.ToolMessage({
897
+ content: `Updated todo list to ${JSON.stringify(input.todos)}`,
898
+ tool_call_id: config.toolCall?.id
899
+ })
900
+ ]
901
+ }
902
+ });
903
+ },
904
+ {
905
+ name: "write_todos",
906
+ description: WRITE_TODOS_DESCRIPTION,
907
+ schema: import_zod3.z.object({
908
+ todos: import_zod3.z.array(
909
+ import_zod3.z.object({
910
+ content: import_zod3.z.string().describe("Content of the todo item"),
911
+ status: import_zod3.z.enum(["pending", "in_progress", "completed"]).describe("Status of the todo")
912
+ })
913
+ ).describe("List of todo items to update")
914
+ })
915
+ }
916
+ );
917
+ var ls = (0, import_tools2.tool)(
918
+ () => {
919
+ const state = (0, import_langgraph.getCurrentTaskInput)();
920
+ const files = state.files || {};
921
+ return Object.keys(files);
922
+ },
923
+ {
924
+ name: "ls",
925
+ description: "List all files in the mock filesystem",
926
+ schema: import_zod3.z.object({})
927
+ }
928
+ );
929
+ var readFile = (0, import_tools2.tool)(
930
+ (input) => {
931
+ const state = (0, import_langgraph.getCurrentTaskInput)();
932
+ const mockFilesystem = state.files || {};
933
+ const { file_path, offset = 0, limit = 2e3 } = input;
934
+ if (!(file_path in mockFilesystem)) {
935
+ return `Error: File '${file_path}' not found`;
936
+ }
937
+ const content = mockFilesystem[file_path];
938
+ if (!content || content.trim() === "") {
939
+ return "System reminder: File exists but has empty contents";
940
+ }
941
+ const lines = content.split("\n");
942
+ const startIdx = offset;
943
+ const endIdx = Math.min(startIdx + limit, lines.length);
944
+ if (startIdx >= lines.length) {
945
+ return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;
946
+ }
947
+ const resultLines = [];
948
+ for (let i = startIdx; i < endIdx; i++) {
949
+ let lineContent = lines[i];
950
+ if (lineContent.length > 2e3) {
951
+ lineContent = lineContent.substring(0, 2e3);
952
+ }
953
+ const lineNumber = i + 1;
954
+ resultLines.push(`${lineNumber.toString().padStart(6)} ${lineContent}`);
955
+ }
956
+ return resultLines.join("\n");
957
+ },
958
+ {
959
+ name: "read_file",
960
+ description: TOOL_DESCRIPTION,
961
+ schema: import_zod3.z.object({
962
+ file_path: import_zod3.z.string().describe("Absolute path to the file to read"),
963
+ offset: import_zod3.z.number().optional().default(0).describe("Line offset to start reading from"),
964
+ limit: import_zod3.z.number().optional().default(2e3).describe("Maximum number of lines to read")
965
+ })
966
+ }
967
+ );
968
+ var writeFile = (0, import_tools2.tool)(
969
+ (input, config) => {
970
+ const state = (0, import_langgraph.getCurrentTaskInput)();
971
+ const files = { ...state.files || {} };
972
+ files[input.file_path] = input.content;
973
+ return new import_langgraph.Command({
974
+ update: {
975
+ files,
976
+ messages: [
977
+ new import_messages.ToolMessage({
978
+ content: `Updated file ${input.file_path}`,
979
+ tool_call_id: config.toolCall?.id
980
+ })
981
+ ]
982
+ }
983
+ });
984
+ },
985
+ {
986
+ name: "write_file",
987
+ description: "Write content to a file in the mock filesystem",
988
+ schema: import_zod3.z.object({
989
+ file_path: import_zod3.z.string().describe("Absolute path to the file to write"),
990
+ content: import_zod3.z.string().describe("Content to write to the file")
991
+ })
992
+ }
993
+ );
994
+ var editFile = (0, import_tools2.tool)(
995
+ (input, config) => {
996
+ const state = (0, import_langgraph.getCurrentTaskInput)();
997
+ const mockFilesystem = { ...state.files || {} };
998
+ const { file_path, old_string, new_string, replace_all = false } = input;
999
+ if (!(file_path in mockFilesystem)) {
1000
+ return `Error: File '${file_path}' not found`;
1001
+ }
1002
+ const content = mockFilesystem[file_path];
1003
+ if (!content.includes(old_string)) {
1004
+ return `Error: String not found in file: '${old_string}'`;
1005
+ }
1006
+ if (!replace_all) {
1007
+ const escapedOldString = old_string.replace(
1008
+ /[.*+?^${}()|[\]\\]/g,
1009
+ "\\$&"
1010
+ );
1011
+ const occurrences = (content.match(new RegExp(escapedOldString, "g")) || []).length;
1012
+ if (occurrences > 1) {
1013
+ return `Error: String '${old_string}' appears ${occurrences} times in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`;
1014
+ } else if (occurrences === 0) {
1015
+ return `Error: String not found in file: '${old_string}'`;
1016
+ }
1017
+ }
1018
+ let newContent;
1019
+ if (replace_all) {
1020
+ const escapedOldString = old_string.replace(
1021
+ /[.*+?^${}()|[\]\\]/g,
1022
+ "\\$&"
1023
+ );
1024
+ newContent = content.replace(
1025
+ new RegExp(escapedOldString, "g"),
1026
+ new_string
1027
+ );
1028
+ } else {
1029
+ newContent = content.replace(old_string, new_string);
1030
+ }
1031
+ mockFilesystem[file_path] = newContent;
1032
+ return new import_langgraph.Command({
1033
+ update: {
1034
+ files: mockFilesystem,
1035
+ messages: [
1036
+ new import_messages.ToolMessage({
1037
+ content: `Updated file ${file_path}`,
1038
+ tool_call_id: config.toolCall?.id
1039
+ })
1040
+ ]
1041
+ }
1042
+ });
1043
+ },
1044
+ {
1045
+ name: "edit_file",
1046
+ description: EDIT_DESCRIPTION,
1047
+ schema: import_zod3.z.object({
1048
+ file_path: import_zod3.z.string().describe("Absolute path to the file to edit"),
1049
+ old_string: import_zod3.z.string().describe("String to be replaced (must match exactly)"),
1050
+ new_string: import_zod3.z.string().describe("String to replace with"),
1051
+ replace_all: import_zod3.z.boolean().optional().default(false).describe("Whether to replace all occurrences")
1052
+ })
1053
+ }
1054
+ );
1055
+
1056
+ // src/deep_agent/subAgent.ts
1057
+ var BUILTIN_TOOLS = {
1058
+ write_todos: writeTodos,
1059
+ read_file: readFile,
1060
+ write_file: writeFile,
1061
+ edit_file: editFile,
1062
+ ls
1063
+ };
1064
+ function createTaskTool(inputs) {
1065
+ const {
1066
+ subagents,
1067
+ tools = {},
1068
+ model = getModelLattice("default")?.client,
1069
+ stateSchema
1070
+ } = inputs;
1071
+ if (!model) {
1072
+ throw new Error("Model not found");
1073
+ }
1074
+ const allTools = { ...BUILTIN_TOOLS, ...tools };
1075
+ const agentsMap = /* @__PURE__ */ new Map();
1076
+ for (const subagent of subagents) {
1077
+ const subagentTools = [];
1078
+ if (subagent.tools) {
1079
+ for (const toolName of subagent.tools) {
1080
+ const resolvedTool = allTools[toolName];
1081
+ if (resolvedTool) {
1082
+ subagentTools.push(resolvedTool);
1083
+ } else {
1084
+ console.warn(
1085
+ `Warning: Tool '${toolName}' not found for agent '${subagent.name}'`
1086
+ );
1087
+ }
1088
+ }
1089
+ } else {
1090
+ subagentTools.push(...Object.values(allTools));
1091
+ }
1092
+ const reactAgent = (0, import_prebuilt2.createReactAgent)({
1093
+ llm: model,
1094
+ tools: subagentTools,
1095
+ stateSchema,
1096
+ messageModifier: subagent.prompt,
1097
+ checkpointer: false
1098
+ });
1099
+ agentsMap.set(subagent.name, reactAgent);
1100
+ }
1101
+ return (0, import_tools3.tool)(
1102
+ async (input, config) => {
1103
+ const { description, subagent_type } = input;
1104
+ const reactAgent = agentsMap.get(subagent_type);
1105
+ if (!reactAgent) {
1106
+ return `Error: Agent '${subagent_type}' not found. Available agents: ${Array.from(
1107
+ agentsMap.keys()
1108
+ ).join(", ")}`;
1109
+ }
1110
+ try {
1111
+ const currentState = (0, import_langgraph2.getCurrentTaskInput)();
1112
+ const modifiedState = {
1113
+ ...currentState,
1114
+ messages: [
1115
+ {
1116
+ role: "user",
1117
+ content: description
1118
+ }
1119
+ ]
1120
+ };
1121
+ const result = await reactAgent.invoke(modifiedState, config);
1122
+ return new import_langgraph2.Command({
1123
+ update: {
1124
+ files: result.files || {},
1125
+ messages: [
1126
+ new import_messages2.ToolMessage({
1127
+ content: result.messages?.slice(-1)[0]?.content || "Task completed",
1128
+ tool_call_id: config.toolCall?.id
1129
+ })
1130
+ ]
1131
+ }
1132
+ });
1133
+ } catch (error) {
1134
+ if (error instanceof import_langgraph2.GraphInterrupt) {
1135
+ throw error;
1136
+ }
1137
+ const errorMessage = error instanceof Error ? error.message : String(error);
1138
+ return new import_langgraph2.Command({
1139
+ update: {
1140
+ messages: [
1141
+ new import_messages2.ToolMessage({
1142
+ content: `Error executing task '${description}' with agent '${subagent_type}': ${errorMessage}`,
1143
+ tool_call_id: config.toolCall?.id
1144
+ })
1145
+ ]
1146
+ }
1147
+ });
1148
+ }
1149
+ },
1150
+ {
1151
+ name: "task",
1152
+ description: TASK_DESCRIPTION_PREFIX.replace(
1153
+ "{other_agents}",
1154
+ subagents.map((a) => `- ${a.name}: ${a.description}`).join("\n")
1155
+ ) + TASK_DESCRIPTION_SUFFIX,
1156
+ schema: import_zod4.z.object({
1157
+ description: import_zod4.z.string().describe("The task to execute with the selected agent"),
1158
+ subagent_type: import_zod4.z.string().describe(
1159
+ `Name of the agent to use. Available: ${subagents.map((a) => a.name).join(", ")}`
1160
+ )
1161
+ })
1162
+ }
1163
+ );
1164
+ }
1165
+
1166
+ // src/deep_agent/state.ts
1167
+ var import_zod5 = require("@langchain/langgraph/zod");
1168
+ var import_langgraph3 = require("@langchain/langgraph");
1169
+ var import_zod6 = require("@langchain/langgraph/zod");
1170
+ var import_zod7 = require("zod");
1171
+ function fileReducer(left, right) {
1172
+ if (left == null) {
1173
+ return right || {};
1174
+ } else if (right == null) {
1175
+ return left;
1176
+ } else {
1177
+ return { ...left, ...right };
1178
+ }
1179
+ }
1180
+ function todoReducer(left, right) {
1181
+ if (right != null) {
1182
+ return right;
1183
+ }
1184
+ return left || [];
1185
+ }
1186
+ var DeepAgentState = import_langgraph3.MessagesZodState.extend({
1187
+ todos: (0, import_zod6.withLangGraph)(import_zod7.z.custom(), {
1188
+ reducer: {
1189
+ schema: import_zod7.z.custom(),
1190
+ fn: todoReducer
1191
+ }
1192
+ }),
1193
+ files: (0, import_zod6.withLangGraph)(import_zod7.z.custom(), {
1194
+ reducer: {
1195
+ schema: import_zod7.z.custom(),
1196
+ fn: fileReducer
1197
+ }
1198
+ })
1199
+ });
1200
+
1201
+ // src/deep_agent/graph.ts
1202
+ var import_prebuilt3 = require("@langchain/langgraph/prebuilt");
1203
+
1204
+ // src/memory_lattice/MemoryLatticeManager.ts
1205
+ var import_protocols2 = require("@axiom-lattice/protocols");
1206
+ var _MemoryLatticeManager = class _MemoryLatticeManager extends BaseLatticeManager {
1207
+ /**
1208
+ * 私有构造函数,防止外部直接实例化
1209
+ */
1210
+ constructor() {
1211
+ super();
1212
+ }
1213
+ /**
1214
+ * 获取单例实例
1215
+ */
1216
+ static getInstance() {
1217
+ if (!_MemoryLatticeManager.instance) {
1218
+ _MemoryLatticeManager.instance = new _MemoryLatticeManager();
1219
+ }
1220
+ return _MemoryLatticeManager.instance;
1221
+ }
1222
+ /**
1223
+ * 获取Lattice类型
1224
+ */
1225
+ getLatticeType() {
1226
+ return "memory";
1227
+ }
1228
+ /**
1229
+ * 注册检查点保存器
1230
+ * @param key 保存器键名
1231
+ * @param saver 检查点保存器实例
1232
+ */
1233
+ registerCheckpointSaver(key, saver) {
1234
+ if (_MemoryLatticeManager.checkpointSavers.has(key)) {
1235
+ throw new Error(`\u68C0\u67E5\u70B9\u4FDD\u5B58\u5668 "${key}" \u5DF2\u7ECF\u5B58\u5728\uFF0C\u65E0\u6CD5\u91CD\u590D\u6CE8\u518C`);
1236
+ }
1237
+ _MemoryLatticeManager.checkpointSavers.set(key, saver);
1238
+ }
1239
+ /**
1240
+ * 获取检查点保存器
1241
+ * @param key 保存器键名
1242
+ */
1243
+ getCheckpointSaver(key) {
1244
+ const saver = _MemoryLatticeManager.checkpointSavers.get(key);
1245
+ if (!saver) {
1246
+ throw new Error(`\u68C0\u67E5\u70B9\u4FDD\u5B58\u5668 "${key}" \u4E0D\u5B58\u5728`);
1247
+ }
1248
+ return saver;
1249
+ }
1250
+ /**
1251
+ * 获取所有已注册的检查点保存器键名
1252
+ */
1253
+ getCheckpointSaverKeys() {
1254
+ return Array.from(_MemoryLatticeManager.checkpointSavers.keys());
1255
+ }
1256
+ /**
1257
+ * 检查检查点保存器是否存在
1258
+ * @param key 保存器键名
1259
+ */
1260
+ hasCheckpointSaver(key) {
1261
+ return _MemoryLatticeManager.checkpointSavers.has(key);
1262
+ }
1263
+ /**
1264
+ * 移除检查点保存器
1265
+ * @param key 保存器键名
1266
+ */
1267
+ removeCheckpointSaver(key) {
1268
+ return _MemoryLatticeManager.checkpointSavers.delete(key);
1269
+ }
1270
+ };
1271
+ // 检查点保存器注册表
1272
+ _MemoryLatticeManager.checkpointSavers = /* @__PURE__ */ new Map();
1273
+ var MemoryLatticeManager = _MemoryLatticeManager;
1274
+ var getCheckpointSaver = (key) => MemoryLatticeManager.getInstance().getCheckpointSaver(key);
1275
+ var registerCheckpointSaver = (key, saver) => MemoryLatticeManager.getInstance().registerCheckpointSaver(key, saver);
1276
+
1277
+ // src/deep_agent/graph.ts
1278
+ var BASE_PROMPT = `You have access to a number of standard tools
1279
+
1280
+ ## \`write_todos\`
1281
+
1282
+ You have access to the \`write_todos\` tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
1283
+ These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
1284
+
1285
+ It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
1286
+ ## \`task\`
1287
+
1288
+ - When doing web search, prefer to use the \`task\` tool in order to reduce context usage.`;
1289
+ var BUILTIN_TOOLS2 = [
1290
+ writeTodos,
1291
+ readFile,
1292
+ writeFile,
1293
+ editFile,
1294
+ ls
1295
+ ];
1296
+ function createDeepAgent(params = {}) {
1297
+ const {
1298
+ tools = [],
1299
+ instructions,
1300
+ model = getModelLattice("default")?.client,
1301
+ subagents = []
1302
+ } = params;
1303
+ if (!model) {
1304
+ throw new Error("Model not found");
1305
+ }
1306
+ const stateSchema = params.stateSchema ? DeepAgentState.extend(params.stateSchema.shape) : DeepAgentState;
1307
+ const allTools = [...BUILTIN_TOOLS2, ...tools];
1308
+ if (subagents.length > 0) {
1309
+ const toolsMap = {};
1310
+ for (const tool5 of allTools) {
1311
+ if (tool5.name) {
1312
+ toolsMap[tool5.name] = tool5;
1313
+ }
1314
+ }
1315
+ const taskTool = createTaskTool({
1316
+ subagents,
1317
+ tools: toolsMap,
1318
+ model,
1319
+ stateSchema
1320
+ });
1321
+ allTools.push(taskTool);
1322
+ }
1323
+ const finalInstructions = instructions ? instructions + BASE_PROMPT : BASE_PROMPT;
1324
+ return (0, import_prebuilt3.createReactAgent)({
1325
+ llm: model,
1326
+ tools: allTools,
1327
+ stateSchema,
1328
+ prompt: finalInstructions,
1329
+ checkpointer: getCheckpointSaver("default")
1330
+ });
1331
+ }
1332
+
1333
+ // src/agent_lattice/builders/DeepAgentGraphBuilder.ts
1334
+ var DeepAgentGraphBuilder = class {
1335
+ /**
1336
+ * 构建Deep Agent Graph
1337
+ *
1338
+ * @param agentLattice Agent Lattice对象
1339
+ * @param params Agent构建参数
1340
+ * @returns 返回CompiledGraph对象
1341
+ */
1342
+ build(agentLattice, params) {
1343
+ const tools = params.tools.map((t) => {
1344
+ const toolClient = getToolClient(t.key);
1345
+ return toolClient;
1346
+ }).filter((tool5) => tool5 !== void 0);
1347
+ return createDeepAgent({
1348
+ tools,
1349
+ model: params.model,
1350
+ instructions: params.prompt,
1351
+ subagents: params.subAgents.map((sa) => ({
1352
+ name: sa.key,
1353
+ description: sa.config.description,
1354
+ prompt: sa.config.prompt,
1355
+ tools: sa.config.tools || []
1356
+ }))
1357
+ });
1358
+ }
1359
+ };
1360
+
1361
+ // src/createPlanExecuteAgent.ts
1362
+ var import_langgraph5 = require("@langchain/langgraph");
1363
+ var import_messages6 = require("@langchain/core/messages");
1364
+ var import_zod8 = require("zod");
1365
+
1366
+ // src/logger/Logger.ts
1367
+ var import_pino = __toESM(require("pino"));
1368
+ var import_pino_pretty = require("pino-pretty");
1369
+ var import_pino_roll = require("pino-roll");
1370
+ var PinoLoggerFactory = class _PinoLoggerFactory {
1371
+ constructor() {
1372
+ const isProd = process.env.NODE_ENV === "production";
1373
+ const loggerConfig = {
1374
+ // 自定义时间戳格式
1375
+ timestamp: () => `,"@timestamp":"${(/* @__PURE__ */ new Date()).toISOString()}"`,
1376
+ // 关闭默认的时间戳键
1377
+ base: {
1378
+ "@version": "1",
1379
+ app_name: "lattice",
1380
+ service_name: "lattice/graph-server",
1381
+ thread_name: "main",
1382
+ logger_name: "lattice-graph-logger"
1383
+ },
1384
+ formatters: {
1385
+ level: (label, number) => {
1386
+ return {
1387
+ level: label.toUpperCase(),
1388
+ level_value: number * 1e3
1389
+ };
1390
+ }
1391
+ }
1392
+ };
1393
+ if (isProd) {
1394
+ try {
1395
+ this.pinoLogger = (0, import_pino.default)(
1396
+ loggerConfig,
1397
+ import_pino.default.transport({
1398
+ target: "pino-roll",
1399
+ options: {
1400
+ file: "./logs/fin_ai_graph_server",
1401
+ frequency: "daily",
1402
+ mkdir: true
1403
+ }
1404
+ })
1405
+ );
1406
+ } catch (error) {
1407
+ console.error(
1408
+ "\u65E0\u6CD5\u521D\u59CB\u5316 pino-roll \u65E5\u5FD7\u8BB0\u5F55\u5668\uFF0C\u56DE\u9000\u5230\u63A7\u5236\u53F0\u65E5\u5FD7",
1409
+ error
1410
+ );
1411
+ this.pinoLogger = (0, import_pino.default)({
1412
+ ...loggerConfig,
1413
+ transport: {
1414
+ target: "pino-pretty",
1415
+ options: {
1416
+ colorize: true
1417
+ }
1418
+ }
1419
+ });
1420
+ }
1421
+ } else {
1422
+ this.pinoLogger = (0, import_pino.default)({
1423
+ ...loggerConfig,
1424
+ transport: {
1425
+ target: "pino-pretty",
1426
+ options: {
1427
+ colorize: true
1428
+ }
1429
+ }
1430
+ });
1431
+ }
1432
+ }
1433
+ static getInstance() {
1434
+ if (!_PinoLoggerFactory.instance) {
1435
+ _PinoLoggerFactory.instance = new _PinoLoggerFactory();
1436
+ }
1437
+ return _PinoLoggerFactory.instance;
1438
+ }
1439
+ getPinoLogger() {
1440
+ return this.pinoLogger;
1441
+ }
1442
+ };
1443
+ var Logger = class _Logger {
1444
+ constructor(options) {
1445
+ this.context = options?.context || {};
1446
+ this.name = options?.name || "lattice-graph-logger";
1447
+ this.serviceName = options?.serviceName || "lattice/graph-server";
1448
+ }
1449
+ /**
1450
+ * 获取合并了上下文的日志对象
1451
+ * @param additionalContext 额外的上下文数据
1452
+ * @returns 带有上下文的pino日志对象
1453
+ */
1454
+ getContextualLogger(additionalContext) {
1455
+ const pinoLogger = PinoLoggerFactory.getInstance().getPinoLogger();
1456
+ const contextObj = {
1457
+ "x-user-id": this.context["x-user-id"] || "",
1458
+ "x-tenant-id": this.context["x-tenant-id"] || "",
1459
+ "x-request-id": this.context["x-request-id"] || "",
1460
+ "x-task-id": this.context["x-task-id"] || "",
1461
+ "x-thread-id": this.context["x-thread-id"] || "",
1462
+ service_name: this.serviceName,
1463
+ logger_name: this.name,
1464
+ ...additionalContext
1465
+ };
1466
+ return pinoLogger.child(contextObj);
1467
+ }
1468
+ info(msg, obj) {
1469
+ this.getContextualLogger(obj).info(msg);
1470
+ }
1471
+ error(msg, obj) {
1472
+ this.getContextualLogger(obj).error(msg);
1473
+ }
1474
+ warn(msg, obj) {
1475
+ this.getContextualLogger(obj).warn(msg);
1476
+ }
1477
+ debug(msg, obj) {
1478
+ this.getContextualLogger(obj).debug(msg);
1479
+ }
1480
+ /**
1481
+ * 更新Logger实例的上下文
1482
+ */
1483
+ updateContext(context) {
1484
+ this.context = {
1485
+ ...this.context,
1486
+ ...context
1487
+ };
1488
+ }
1489
+ /**
1490
+ * 创建一个新的Logger实例,继承当前Logger的上下文
1491
+ */
1492
+ child(options) {
1493
+ return new _Logger({
1494
+ name: options.name || this.name,
1495
+ serviceName: options.serviceName || this.serviceName,
1496
+ context: {
1497
+ ...this.context,
1498
+ ...options.context
1499
+ }
1500
+ });
1501
+ }
1502
+ };
1503
+
1504
+ // src/util/returnToolResponse.ts
1505
+ var import_messages3 = require("@langchain/core/messages");
1506
+ var import_uuid = require("uuid");
1507
+
1508
+ // src/util/genUIMarkdown.ts
1509
+ var genUIMarkdown = (type, data) => {
1510
+ return ["```" + type, JSON.stringify(data), "```"].join("\n");
1511
+ };
1512
+
1513
+ // src/util/returnToolResponse.ts
1514
+ var returnToolResponse = (config, think) => {
1515
+ const { think_id = (0, import_uuid.v4)(), content, title, status, type, data } = think;
1516
+ const contents = type ? [title, content, genUIMarkdown(type, data)] : [title, content];
1517
+ const message = {
1518
+ messages: [
1519
+ new import_messages3.ToolMessage({
1520
+ content: contents.filter((item) => item).join("\n\n"),
1521
+ tool_call_id: config.configurable?.run_id + "_tool_" + think_id,
1522
+ status: status || "success"
1523
+ })
1524
+ ]
1525
+ };
1526
+ return message;
1527
+ };
1528
+
1529
+ // src/util/returnAIResponse.ts
1530
+ var import_messages4 = require("@langchain/core/messages");
1531
+ var returnAIResponse = (config, content, type, data) => {
1532
+ const contents = type ? [content, genUIMarkdown(type, data)].join("\n") : content;
1533
+ const message = {
1534
+ messages: [
1535
+ new import_messages4.AIMessage({
1536
+ content: contents
1537
+ })
1538
+ // {
1539
+ // id: v4(),
1540
+ // role: "ai",
1541
+ // content: contents,
1542
+ // type: "message",
1543
+ // }, // 旧的message
1544
+ ]
1545
+ };
1546
+ return message;
1547
+ };
1548
+
1549
+ // src/util/getLastHumanMessageData.ts
1550
+ var import_messages5 = require("@langchain/core/messages");
1551
+ var getLastHumanMessageData = (messages) => {
1552
+ for (let i = messages.length - 1; i >= 0; i--) {
1553
+ const message = messages[i];
1554
+ if ((0, import_messages5.isHumanMessage)(message)) {
1555
+ const files = message?.additional_kwargs?.files;
1556
+ return {
1557
+ files,
1558
+ content: message?.content
1559
+ };
1560
+ }
1561
+ }
1562
+ return null;
1563
+ };
1564
+
1565
+ // src/createPlanExecuteAgent.ts
1566
+ var import_tools7 = require("@langchain/core/tools");
1567
+
1568
+ // src/util/PGMemory.ts
1569
+ var import_langgraph4 = require("@langchain/langgraph");
1570
+ var import_langgraph_checkpoint_postgres = require("@langchain/langgraph-checkpoint-postgres");
1571
+ var globalMemory = import_langgraph_checkpoint_postgres.PostgresSaver.fromConnString(process.env.DATABASE_URL);
1572
+ var memory = new import_langgraph4.MemorySaver();
1573
+ var _MemoryManager = class _MemoryManager {
1574
+ static getInstance() {
1575
+ return _MemoryManager.instance;
1576
+ }
1577
+ };
1578
+ _MemoryManager.instance = memory;
1579
+ var MemoryManager = _MemoryManager;
1580
+
1581
+ // src/createPlanExecuteAgent.ts
1582
+ var import_prebuilt4 = require("@langchain/langgraph/prebuilt");
1583
+ var PlanExecuteState = import_langgraph5.Annotation.Root({
1584
+ // 输入
1585
+ input: (0, import_langgraph5.Annotation)({
1586
+ reducer: (x, y) => y ?? x ?? ""
1587
+ }),
1588
+ // 计划步骤列表
1589
+ plan: (0, import_langgraph5.Annotation)({
1590
+ reducer: (x, y) => y ?? x ?? []
1591
+ }),
1592
+ // 已执行的步骤 [步骤名称, 执行结果]
1593
+ pastSteps: (0, import_langgraph5.Annotation)({
1594
+ reducer: (x, y) => x.concat(y),
1595
+ default: () => []
1596
+ }),
1597
+ // 最终响应
1598
+ response: (0, import_langgraph5.Annotation)({
1599
+ reducer: (x, y) => y ?? x
1600
+ }),
1601
+ // 错误信息
1602
+ error: (0, import_langgraph5.Annotation)({
1603
+ reducer: (x, y) => y ?? x
1604
+ }),
1605
+ // 继承基础状态
1606
+ "x-tenant-id": (0, import_langgraph5.Annotation)(),
1607
+ messages: (0, import_langgraph5.Annotation)({
1608
+ reducer: import_langgraph5.messagesStateReducer,
1609
+ default: () => []
1610
+ })
1611
+ });
1612
+ var planSchema = import_zod8.z.object({
1613
+ steps: import_zod8.z.array(import_zod8.z.string()).describe("\u9700\u8981\u6267\u884C\u7684\u6B65\u9AA4\u5217\u8868\uFF0C\u5E94\u6309\u7167\u6267\u884C\u987A\u5E8F\u6392\u5E8F")
1614
+ });
1615
+ var responseSchema = import_zod8.z.object({
1616
+ response: import_zod8.z.string().describe("\u7ED9\u7528\u6237\u7684\u6700\u7EC8\u54CD\u5E94\uFF0C\u5982\u679C\u4E0D\u9700\u8981\u6267\u884C\u6B65\u9AA4\uFF0C\u5219\u8FD4\u56DE\u8FD9\u4E2A\u5B57\u6BB5")
1617
+ });
1618
+ function createPlanExecuteAgent(config) {
1619
+ const {
1620
+ name,
1621
+ description,
1622
+ tools: executorTools = [],
1623
+ checkpointer,
1624
+ llmManager,
1625
+ logger,
1626
+ maxSteps = 10,
1627
+ prompt
1628
+ } = config;
1629
+ const agentLogger = logger || new Logger({ name: `PlanExecuteAgent:${name}` });
1630
+ const llm = llmManager || getModelLattice("default")?.client;
1631
+ if (!llm) {
1632
+ throw new Error("LLM not found");
1633
+ }
1634
+ agentLogger.info(`\u521D\u59CB\u5316Plan-Execute\u4EE3\u7406: ${name}`, {
1635
+ description,
1636
+ maxSteps,
1637
+ toolsCount: executorTools.length
1638
+ });
1639
+ const agentExecutor = (0, import_prebuilt4.createReactAgent)({
1640
+ tools: executorTools,
1641
+ llm
1642
+ });
1643
+ async function planStep(state, config2) {
1644
+ const input = state.input || getLastHumanMessageData(state.messages)?.content;
1645
+ const plannerPrompt = `${prompt || ""}
1646
+ \u9488\u5BF9\u7ED9\u5B9A\u7684\u76EE\u6807\uFF0C\u5236\u5B9A\u4E00\u4E2A\u7B80\u5355\u7684\u5206\u6B65\u8BA1\u5212\u3002
1647
+ \u8FD9\u4E2A\u8BA1\u5212\u5E94\u8BE5\u5305\u542B\u72EC\u7ACB\u7684\u4EFB\u52A1\uFF0C\u5982\u679C\u6B63\u786E\u6267\u884C\u5C06\u4F1A\u5F97\u5230\u6B63\u786E\u7684\u7B54\u6848\u3002\u4E0D\u8981\u6DFB\u52A0\u591A\u4F59\u7684\u6B65\u9AA4\u3002
1648
+ \u6700\u540E\u4E00\u6B65\u7684\u7ED3\u679C\u5E94\u8BE5\u662F\u6700\u7EC8\u7B54\u6848\u3002\u786E\u4FDD\u6BCF\u4E00\u6B65\u90FD\u6709\u6240\u9700\u7684\u6240\u6709\u4FE1\u606F - \u4E0D\u8981\u8DF3\u8FC7\u6B65\u9AA4\u3002
1649
+
1650
+ \u53EF\u4EE5\u4F7F\u7528\u7684\u5DE5\u5177\u5982\u4E0B\uFF1A
1651
+ ${executorTools.map((tool5) => tool5.name).join("\n")}
1652
+
1653
+ \u76EE\u6807: ${input}`;
1654
+ try {
1655
+ const planResult = await llm.invokeWithStructuredOutput(
1656
+ [new import_messages6.HumanMessage(plannerPrompt)],
1657
+ planSchema
1658
+ );
1659
+ const { messages } = await returnToolResponse(config2, {
1660
+ title: "\u6211\u7684\u8BA1\u5212",
1661
+ content: planResult.steps.map((step) => step).join("\n\n"),
1662
+ status: "success"
1663
+ });
1664
+ agentLogger.info("\u8BA1\u5212\u5236\u5B9A\u5B8C\u6210", { plan: planResult.steps });
1665
+ return {
1666
+ input,
1667
+ plan: planResult.steps,
1668
+ error: void 0,
1669
+ messages
1670
+ };
1671
+ } catch (error) {
1672
+ const errorMsg = `\u8BA1\u5212\u5236\u5B9A\u5931\u8D25: ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`;
1673
+ agentLogger.error(errorMsg, { error });
1674
+ return {
1675
+ error: errorMsg
1676
+ };
1677
+ }
1678
+ }
1679
+ async function executeStep(state, config2) {
1680
+ if (!state.plan || state.plan.length === 0) {
1681
+ agentLogger.warn("\u6CA1\u6709\u53EF\u6267\u884C\u7684\u4EFB\u52A1");
1682
+ return { error: "\u6CA1\u6709\u53EF\u6267\u884C\u7684\u4EFB\u52A1" };
1683
+ }
1684
+ const currentTask = state.plan[0];
1685
+ agentLogger.info("\u5F00\u59CB\u6267\u884C\u4EFB\u52A1", { task: currentTask });
1686
+ try {
1687
+ const executorPrompt = `\u6267\u884C\u4EE5\u4E0B\u4EFB\u52A1\u5E76\u63D0\u4F9B\u7ED3\u679C\uFF1A
1688
+
1689
+ \u4EFB\u52A1: ${currentTask}
1690
+
1691
+ \u4E0A\u4E0B\u6587\u4FE1\u606F:
1692
+ - \u539F\u59CB\u76EE\u6807: ${state.input}
1693
+ - \u5DF2\u5B8C\u6210\u7684\u6B65\u9AA4: ${state.pastSteps.map(([step, result]) => `${step}: ${result}`).join("\n")}
1694
+
1695
+ \u8BF7\u63D0\u4F9B\u6267\u884C\u6B64\u4EFB\u52A1\u7684\u8BE6\u7EC6\u7ED3\u679C\u3002`;
1696
+ const executionResult = await agentExecutor.invoke({
1697
+ messages: [new import_messages6.HumanMessage(executorPrompt)]
1698
+ });
1699
+ const resultContent = executionResult.messages[executionResult.messages.length - 1].content;
1700
+ return {
1701
+ pastSteps: [[currentTask, resultContent]],
1702
+ plan: state.plan.slice(1),
1703
+ // 移除已执行的任务
1704
+ //messages,
1705
+ error: void 0
1706
+ };
1707
+ } catch (error) {
1708
+ if (error instanceof import_langgraph5.GraphInterrupt) {
1709
+ throw error;
1710
+ }
1711
+ const errorMsg = `\u4EFB\u52A1\u6267\u884C\u5931\u8D25: ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`;
1712
+ agentLogger.error(errorMsg, { task: currentTask, error });
1713
+ return {
1714
+ error: errorMsg
1715
+ //messages,
1716
+ };
1717
+ }
1718
+ }
1719
+ const responseTool = (0, import_tools7.tool)(
1720
+ ({ response }) => {
1721
+ return response;
1722
+ },
1723
+ {
1724
+ name: "response",
1725
+ description: "Respond to the user.",
1726
+ schema: responseSchema,
1727
+ returnDirect: true
1728
+ }
1729
+ );
1730
+ const planTool = (0, import_tools7.tool)(
1731
+ ({ steps }) => {
1732
+ return steps.join("\n\n");
1733
+ },
1734
+ {
1735
+ name: "plan",
1736
+ description: "This tool is used to plan the steps to follow.",
1737
+ schema: planSchema,
1738
+ returnDirect: true
1739
+ }
1740
+ );
1741
+ const replanAgent = (0, import_prebuilt4.createReactAgent)({
1742
+ tools: [responseTool, planTool],
1743
+ llm
1744
+ });
1745
+ async function replanStep(state, config2) {
1746
+ agentLogger.info("\u5F00\u59CB\u91CD\u65B0\u89C4\u5212");
1747
+ const replannerPrompt = `${prompt || ""}
1748
+ \u9488\u5BF9\u7ED9\u5B9A\u7684\u76EE\u6807\uFF0C\u6839\u636E\u5DF2\u6267\u884C\u7684\u6B65\u9AA4\u6765\u66F4\u65B0\u8BA1\u5212\u3002
1749
+ \u8FD9\u4E2A\u8BA1\u5212\u5E94\u8BE5\u5305\u542B\u72EC\u7ACB\u7684\u4EFB\u52A1\uFF0C\u5982\u679C\u6B63\u786E\u6267\u884C\u5C06\u4F1A\u5F97\u5230\u6B63\u786E\u7684\u7B54\u6848\u3002\u4E0D\u8981\u6DFB\u52A0\u591A\u4F59\u7684\u6B65\u9AA4\u3002
1750
+ \u6700\u540E\u4E00\u6B65\u7684\u7ED3\u679C\u5E94\u8BE5\u662F\u6700\u7EC8\u7B54\u6848\u3002\u786E\u4FDD\u6BCF\u4E00\u6B65\u90FD\u6709\u6240\u9700\u7684\u6240\u6709\u4FE1\u606F - \u4E0D\u8981\u8DF3\u8FC7\u6B65\u9AA4\u3002
1751
+
1752
+ \u4F60\u7684\u76EE\u6807\u662F\uFF1A
1753
+ ${state.input}
1754
+
1755
+ \u4F60\u7684\u539F\u59CB\u8BA1\u5212\u662F\uFF1A
1756
+ ${state.plan.join("\n")}
1757
+
1758
+ \u4F60\u76EE\u524D\u5DF2\u7ECF\u5B8C\u6210\u4E86\u4EE5\u4E0B\u6B65\u9AA4\uFF1A
1759
+ ${state.pastSteps.map(([step, result]) => `${step}: ${result}`).join("\n")}
1760
+
1761
+ Update your plan accordingly. If no more steps are needed and you can return to the user, then respond with that and use the 'response' function.
1762
+ Otherwise, fill out the plan.
1763
+ Only add steps to the plan that still NEED to be done. Do not return previously done steps as part of the plan.`;
1764
+ try {
1765
+ const responseResult = await replanAgent.invoke({
1766
+ messages: [new import_messages6.HumanMessage(replannerPrompt)]
1767
+ });
1768
+ const toolCall = responseResult.messages[responseResult.messages.length - 1];
1769
+ if (toolCall?.name == "response") {
1770
+ agentLogger.info("\u4EFB\u52A1\u5B8C\u6210\uFF0C\u63D0\u4F9B\u6700\u7EC8\u54CD\u5E94");
1771
+ const { messages } = await returnAIResponse(
1772
+ config2,
1773
+ toolCall.content
1774
+ );
1775
+ return {
1776
+ response: toolCall.content,
1777
+ messages,
1778
+ error: void 0
1779
+ };
1780
+ } else if (toolCall?.name == "plan") {
1781
+ let messages = [];
1782
+ if (toolCall.content?.length > 0) {
1783
+ messages = await returnToolResponse(config2, {
1784
+ title: "\u65B0\u7684\u8BA1\u5212",
1785
+ content: toolCall.content,
1786
+ status: "success"
1787
+ }).messages;
1788
+ }
1789
+ agentLogger.info("\u8BA1\u5212\u66F4\u65B0\u5B8C\u6210", { newPlan: toolCall.content });
1790
+ return {
1791
+ messages,
1792
+ plan: toolCall.content.split("\n\n"),
1793
+ error: void 0
1794
+ };
1795
+ } else {
1796
+ return {
1797
+ error: "\u91CD\u65B0\u89C4\u5212\u5931\u8D25"
1798
+ };
1799
+ }
1800
+ } catch (error) {
1801
+ if (error instanceof import_langgraph5.GraphInterrupt) {
1802
+ throw error;
1803
+ }
1804
+ const errorMsg = `\u91CD\u65B0\u89C4\u5212\u5931\u8D25: ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`;
1805
+ agentLogger.error(errorMsg, { error });
1806
+ return {
1807
+ error: errorMsg
1808
+ };
1809
+ }
1810
+ }
1811
+ function shouldEnd(state) {
1812
+ if (state.error) {
1813
+ agentLogger.warn("\u56E0\u9519\u8BEF\u7ED3\u675F\u6267\u884C", { error: state.error });
1814
+ return "end";
1815
+ }
1816
+ if (state.response) {
1817
+ agentLogger.info("\u4EFB\u52A1\u5B8C\u6210\uFF0C\u7ED3\u675F\u6267\u884C");
1818
+ return "end";
1819
+ }
1820
+ if (state.pastSteps.length >= maxSteps) {
1821
+ agentLogger.warn("\u8FBE\u5230\u6700\u5927\u6B65\u9AA4\u6570\u9650\u5236\uFF0C\u7ED3\u675F\u6267\u884C", {
1822
+ maxSteps,
1823
+ currentSteps: state.pastSteps.length
1824
+ });
1825
+ return "end";
1826
+ }
1827
+ if (!state.plan || state.plan.length === 0) {
1828
+ agentLogger.info("\u8BA1\u5212\u4E3A\u7A7A\uFF0C\u7ED3\u675F\u6267\u884C");
1829
+ return "end";
1830
+ }
1831
+ return "continue";
1832
+ }
1833
+ const workflow = new import_langgraph5.StateGraph(PlanExecuteState).addNode("planner", planStep).addNode("executor", executeStep).addNode("replanner", replanStep).addEdge(import_langgraph5.START, "planner").addEdge("planner", "executor").addEdge("executor", "replanner").addConditionalEdges("replanner", shouldEnd, {
1834
+ end: import_langgraph5.END,
1835
+ continue: "executor"
1836
+ });
1837
+ const compiledGraph = workflow.compile({
1838
+ checkpointer: checkpointer || MemoryManager.getInstance(),
1839
+ name: `PlanExecuteAgent:${name}`
1840
+ });
1841
+ agentLogger.info(`Plan-Execute\u4EE3\u7406\u7F16\u8BD1\u5B8C\u6210: ${name}`);
1842
+ return {
1843
+ /**
1844
+ * 执行代理
1845
+ */
1846
+ invoke: async (input, config2) => {
1847
+ agentLogger.info(`\u5F00\u59CB\u6267\u884CPlan-Execute\u4EE3\u7406: ${name}`, {
1848
+ input: input.input
1849
+ });
1850
+ try {
1851
+ const result = await compiledGraph.invoke(input, config2);
1852
+ agentLogger.info(`\u4EE3\u7406\u6267\u884C\u5B8C\u6210: ${name}`);
1853
+ return result;
1854
+ } catch (error) {
1855
+ agentLogger.error(
1856
+ `\u4EE3\u7406\u6267\u884C\u5931\u8D25: ${name}`,
1857
+ error instanceof Error ? error : { error }
1858
+ );
1859
+ throw error;
1860
+ }
1861
+ },
1862
+ /**
1863
+ * 流式执行代理
1864
+ */
1865
+ stream: async (input, config2) => {
1866
+ agentLogger.info(`\u5F00\u59CB\u6D41\u5F0F\u6267\u884CPlan-Execute\u4EE3\u7406: ${name}`, {
1867
+ input: input.input
1868
+ });
1869
+ return compiledGraph.stream(input, config2);
1870
+ },
1871
+ /**
1872
+ * 获取代理信息
1873
+ */
1874
+ getInfo: () => ({
1875
+ name,
1876
+ description,
1877
+ type: "PlanExecuteAgent",
1878
+ toolsCount: executorTools.length,
1879
+ maxSteps
1880
+ }),
1881
+ /**
1882
+ * 获取编译后的图
1883
+ */
1884
+ getCompiledGraph: () => compiledGraph
1885
+ };
1886
+ }
1887
+
1888
+ // src/agent_lattice/builders/PlanExecuteAgentGraphBuilder.ts
1889
+ var PlanExecuteAgentGraphBuilder = class {
1890
+ /**
1891
+ * 构建Plan Execute Agent Graph
1892
+ *
1893
+ * @param agentLattice Agent Lattice对象
1894
+ * @param params Agent构建参数
1895
+ * @returns 返回CompiledGraph对象
1896
+ */
1897
+ build(agentLattice, params) {
1898
+ const tools = params.tools.map((t) => {
1899
+ const tool5 = getToolClient(t.key);
1900
+ return tool5;
1901
+ }).filter((tool5) => tool5 !== void 0);
1902
+ const agent = createPlanExecuteAgent({
1903
+ llmManager: params.model,
1904
+ tools,
1905
+ prompt: params.prompt,
1906
+ name: agentLattice.config.name,
1907
+ description: agentLattice.config.description
1908
+ });
1909
+ return agent.getCompiledGraph();
1910
+ }
1911
+ };
1912
+
1913
+ // src/agent_lattice/builders/AgentGraphBuilderFactory.ts
1914
+ var AgentGraphBuilderFactory = class _AgentGraphBuilderFactory {
1915
+ constructor() {
1916
+ this.builders = /* @__PURE__ */ new Map();
1917
+ this.registerDefaultBuilders();
1918
+ }
1919
+ /**
1920
+ * 获取单例实例
1921
+ */
1922
+ static getInstance() {
1923
+ if (!_AgentGraphBuilderFactory.instance) {
1924
+ _AgentGraphBuilderFactory.instance = new _AgentGraphBuilderFactory();
1925
+ }
1926
+ return _AgentGraphBuilderFactory.instance;
1927
+ }
1928
+ /**
1929
+ * 注册默认的Builder
1930
+ */
1931
+ registerDefaultBuilders() {
1932
+ this.builders.set(import_protocols.AgentType.REACT, new ReActAgentGraphBuilder());
1933
+ this.builders.set(import_protocols.AgentType.DEEP_AGENT, new DeepAgentGraphBuilder());
1934
+ this.builders.set(
1935
+ import_protocols.AgentType.PLAN_EXECUTE,
1936
+ new PlanExecuteAgentGraphBuilder()
1937
+ );
1938
+ }
1939
+ /**
1940
+ * 注册自定义Builder
1941
+ *
1942
+ * @param type Agent类型
1943
+ * @param builder Builder实例
1944
+ */
1945
+ registerBuilder(type, builder) {
1946
+ this.builders.set(type, builder);
1947
+ }
1948
+ /**
1949
+ * 获取Builder
1950
+ *
1951
+ * @param type Agent类型
1952
+ * @returns 返回对应的Builder
1953
+ */
1954
+ getBuilder(type) {
1955
+ const builder = this.builders.get(type);
1956
+ if (!builder) {
1957
+ throw new Error(`\u4E0D\u652F\u6301\u7684Agent\u7C7B\u578B: ${type}`);
1958
+ }
1959
+ return builder;
1960
+ }
1961
+ };
1962
+
1963
+ // src/agent_lattice/builders/AgentParamsBuilder.ts
1964
+ var AgentParamsBuilder = class {
1965
+ /**
1966
+ * constructor
1967
+ *
1968
+ * @param getAgentLatticeFunc get Agent Lattice function
1969
+ */
1970
+ constructor(getAgentLatticeFunc) {
1971
+ this.getAgentLatticeFunc = getAgentLatticeFunc;
1972
+ }
1973
+ /**
1974
+ * build Agent parameters
1975
+ *
1976
+ * @param agentLattice Agent Lattice object
1977
+ * @param options build options
1978
+ * @returns Agent build parameters
1979
+ */
1980
+ buildParams(agentLattice, options) {
1981
+ const toolKeys = options?.overrideTools || agentLattice.config.tools || [];
1982
+ const tools = toolKeys.map((toolKey) => {
1983
+ const toolLattice = toolLatticeManager.getToolLattice(toolKey);
1984
+ if (!toolLattice) {
1985
+ throw new Error(`Tool "${toolKey}" does not exist`);
1986
+ }
1987
+ return {
1988
+ key: toolKey,
1989
+ definition: toolLattice.config,
1990
+ executor: toolLattice.client
1991
+ };
1992
+ });
1993
+ const modelKey = options?.overrideModel || agentLattice.config.modelKey;
1994
+ const model = modelKey ? modelLatticeManager.getModelLattice(modelKey).client : modelLatticeManager.getModelLattice("default").client;
1995
+ if (!model) {
1996
+ throw new Error(`Model "${modelKey}" does not exist`);
1997
+ }
1998
+ const subAgentKeys = agentLattice.config.subAgents || [];
1999
+ const subAgents = subAgentKeys.map((agentKey) => {
2000
+ const subAgentLattice = this.getAgentLatticeFunc(agentKey);
2001
+ if (!subAgentLattice) {
2002
+ throw new Error(`SubAgent "${agentKey}" does not exist`);
2003
+ }
2004
+ return {
2005
+ key: agentKey,
2006
+ config: subAgentLattice.config,
2007
+ client: subAgentLattice.client
2008
+ };
2009
+ });
2010
+ return {
2011
+ tools,
2012
+ model,
2013
+ subAgents,
2014
+ prompt: agentLattice.config.prompt
2015
+ };
2016
+ }
2017
+ };
2018
+
2019
+ // src/agent_lattice/AgentLatticeManager.ts
2020
+ var AgentLatticeManager = class _AgentLatticeManager extends BaseLatticeManager {
2021
+ /**
2022
+ * 获取AgentLatticeManager单例实例
2023
+ */
2024
+ static getInstance() {
2025
+ if (!_AgentLatticeManager._instance) {
2026
+ _AgentLatticeManager._instance = new _AgentLatticeManager();
2027
+ }
2028
+ return _AgentLatticeManager._instance;
2029
+ }
2030
+ /**
2031
+ * 获取Lattice类型前缀
2032
+ */
2033
+ getLatticeType() {
2034
+ return "agents";
2035
+ }
2036
+ /**
2037
+ * 注册Agent Lattice
2038
+ * @param config Agent配置
2039
+ */
2040
+ registerLattice(config) {
2041
+ const agentLattice = {
2042
+ config,
2043
+ client: void 0
2044
+ // 客户端将在需要时由initializeClient创建
2045
+ };
2046
+ this.register(config.key, agentLattice);
2047
+ }
2048
+ /**
2049
+ * 获取AgentLattice
2050
+ * @param key Lattice键名
2051
+ */
2052
+ getAgentLattice(key) {
2053
+ return this.get(key);
2054
+ }
2055
+ /**
2056
+ * 获取所有Lattice
2057
+ */
2058
+ getAllLattices() {
2059
+ return this.getAll();
2060
+ }
2061
+ /**
2062
+ * 检查Lattice是否存在
2063
+ * @param key Lattice键名
2064
+ */
2065
+ hasLattice(key) {
2066
+ return this.has(key);
2067
+ }
2068
+ /**
2069
+ * 移除Lattice
2070
+ * @param key Lattice键名
2071
+ */
2072
+ removeLattice(key) {
2073
+ return this.remove(key);
2074
+ }
2075
+ /**
2076
+ * 获取Agent配置
2077
+ * @param key Lattice键名
2078
+ */
2079
+ getAgentConfig(key) {
2080
+ return this.getAgentLattice(key)?.config;
2081
+ }
2082
+ /**
2083
+ * 获取所有Agent配置
2084
+ */
2085
+ getAllAgentConfigs() {
2086
+ return this.getAllLattices().map((lattice) => lattice.config);
2087
+ }
2088
+ /**
2089
+ * 验证Agent输入参数
2090
+ * @param key Lattice键名
2091
+ * @param input 输入参数
2092
+ */
2093
+ validateAgentInput(key, input) {
2094
+ const agentLattice = this.getAgentLattice(key);
2095
+ if (!agentLattice) {
2096
+ return false;
2097
+ }
2098
+ try {
2099
+ if (agentLattice.config.schema) {
2100
+ agentLattice.config.schema.parse(input);
2101
+ }
2102
+ return true;
2103
+ } catch {
2104
+ return false;
2105
+ }
2106
+ }
2107
+ /**
2108
+ * 构建Agent参数
2109
+ *
2110
+ * @param agentLattice Agent Lattice对象
2111
+ * @param options 构建选项
2112
+ * @returns 返回Agent构建参数
2113
+ */
2114
+ buildAgentParams(agentLattice, options) {
2115
+ const paramsBuilder = new AgentParamsBuilder(
2116
+ (key) => this.getAgentLattice(key)
2117
+ );
2118
+ return paramsBuilder.buildParams(agentLattice, options);
2119
+ }
2120
+ /**
2121
+ * 初始化Agent客户端
2122
+ *
2123
+ * 使用AgentGraphBuilderFactory构建Graph并设置为客户端
2124
+ *
2125
+ * @param key Lattice键名
2126
+ * @param options 构建选项
2127
+ * @returns 返回CompiledGraph对象
2128
+ */
2129
+ initializeClient(key, options) {
2130
+ const agentLattice = this.getAgentLattice(key);
2131
+ if (!agentLattice) {
2132
+ throw new Error(`Agent Lattice "${key}" \u4E0D\u5B58\u5728`);
2133
+ }
2134
+ if (agentLattice.client) {
2135
+ return agentLattice.client;
2136
+ }
2137
+ const factory = AgentGraphBuilderFactory.getInstance();
2138
+ const builder = factory.getBuilder(agentLattice.config.type);
2139
+ const params = this.buildAgentParams(agentLattice, options);
2140
+ const graph = builder.build(agentLattice, params);
2141
+ agentLattice.client = graph;
2142
+ return graph;
2143
+ }
2144
+ };
2145
+ var agentLatticeManager = AgentLatticeManager.getInstance();
2146
+ var registerAgentLattice = (config) => {
2147
+ agentLatticeManager.registerLattice(config);
2148
+ };
2149
+ var registerAgentLattices = (configs) => {
2150
+ configs.forEach((config) => {
2151
+ agentLatticeManager.registerLattice(config);
2152
+ });
2153
+ };
2154
+ var getAgentLattice = (key) => agentLatticeManager.getAgentLattice(key);
2155
+ var getAgentConfig = (key) => agentLatticeManager.getAgentConfig(key);
2156
+ var getAllAgentConfigs = () => agentLatticeManager.getAllAgentConfigs();
2157
+ var validateAgentInput = (key, input) => agentLatticeManager.validateAgentInput(key, input);
2158
+ var getAgentClient = (key, options) => agentLatticeManager.initializeClient(key, options);
2159
+
2160
+ // src/memory_lattice/DefaultMemorySaver.ts
2161
+ var import_langgraph6 = require("@langchain/langgraph");
2162
+ var memory2 = new import_langgraph6.MemorySaver();
2163
+ registerCheckpointSaver("default", memory2);
2164
+
2165
+ // src/index.ts
2166
+ var Protocols = __toESM(require("@axiom-lattice/protocols"));
2167
+ // Annotate the CommonJS export names for ESM import in node:
2168
+ 0 && (module.exports = {
2169
+ AgentConfig,
2170
+ AgentLatticeManager,
2171
+ AgentType,
2172
+ GraphBuildOptions,
2173
+ MemoryLatticeManager,
2174
+ MemoryType,
2175
+ ModelLatticeManager,
2176
+ Protocols,
2177
+ agentLatticeManager,
2178
+ getAgentClient,
2179
+ getAgentConfig,
2180
+ getAgentLattice,
2181
+ getAllAgentConfigs,
2182
+ getCheckpointSaver,
2183
+ getModelLattice,
2184
+ modelLatticeManager,
2185
+ registerAgentLattice,
2186
+ registerAgentLattices,
2187
+ registerCheckpointSaver,
2188
+ registerModelLattice,
2189
+ validateAgentInput
2190
+ });
2191
+ //# sourceMappingURL=index.js.map