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