@axiom-lattice/core 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/base/BaseLatticeManager.ts","../src/model_lattice/ModelLattice.ts","../src/model_lattice/ModelLatticeManager.ts","../src/tool_lattice/get_current_date_time/index.ts","../src/tool_lattice/ToolLatticeManager.ts","../src/util/genUIMarkdown.ts","../src/tool_lattice/createToolApproveWrapper.ts","../src/tool_lattice/internet_search/index.ts","../src/util/genUICard.ts","../src/tool_lattice/write_todos/index.ts","../src/tool_lattice/read_file/index.ts","../src/tool_lattice/write_file/index.ts","../src/tool_lattice/edit_file/index.ts","../src/tool_lattice/ls/index.ts","../src/agent_lattice/types.ts","../src/agent_lattice/builders/ReActAgentGraphBuilder.ts","../src/memory_lattice/DefaultMemorySaver.ts","../src/memory_lattice/MemoryLatticeManager.ts","../src/agent_lattice/builders/state.ts","../src/deep_agent/subAgent.ts","../src/deep_agent/prompts.ts","../src/deep_agent/tools.ts","../src/deep_agent/state.ts","../src/deep_agent/graph.ts","../src/agent_lattice/builders/DeepAgentGraphBuilder.ts","../src/createPlanExecuteAgent.ts","../src/logger/Logger.ts","../src/util/returnToolResponse.ts","../src/util/returnAIResponse.ts","../src/util/getLastHumanMessageData.ts","../src/util/PGMemory.ts","../src/agent_lattice/builders/PlanExecuteAgentGraphBuilder.ts","../src/agent_lattice/builders/AgentGraphBuilderFactory.ts","../src/agent_lattice/builders/AgentParamsBuilder.ts","../src/agent_lattice/AgentLatticeManager.ts","../src/chunk_buffer_lattice/ChunkBuffer.ts","../src/chunk_buffer_lattice/types.ts","../src/chunk_buffer_lattice/InMemoryChunkBuffer.ts","../src/chunk_buffer_lattice/ChunkBufferLatticeManager.ts"],"sourcesContent":["// 导出核心模块\nexport * from \"./model_lattice\";\nexport * from \"./tool_lattice\";\nexport * from \"./agent_lattice\";\nexport * from \"./memory_lattice\";\nexport * from \"./chunk_buffer_lattice\";\n\n// 重新导出协议接口 - 使用命名导出避免冲突\nimport * as Protocols from \"@axiom-lattice/protocols\";\nexport { Protocols };\n","/**\n * BaseLatticeManager - 抽象基类,为各种Lattice管理器提供通用功能\n * 使用统一的Lattice注册表,不同类型的Lattice通过前缀区分\n * @template TItem - 管理的项目类型\n */\nexport abstract class BaseLatticeManager<TItem = any> {\n // 全局统一的Lattice注册表\n protected static registry: Map<string, any> = new Map();\n\n /**\n * 受保护的构造函数,防止外部直接实例化\n */\n protected constructor() {\n // 空实现\n }\n\n /**\n * 获取管理器实例(由子类实现)\n */\n public static getInstance(): BaseLatticeManager<any> {\n throw new Error(\"必须由子类实现\");\n }\n\n /**\n * 获取Lattice类型,用于构造键前缀\n * 子类必须重写此方法以提供唯一的类型标识符\n */\n protected abstract getLatticeType(): string;\n\n /**\n * 构造完整的键名,包含类型前缀\n * @param key 原始键名\n */\n protected getFullKey(key: string): string {\n return `${this.getLatticeType()}.${key}`;\n }\n\n /**\n * 注册项目\n * @param key 项目键名(不含前缀)\n * @param item 项目实例\n */\n public register(key: string, item: TItem): void {\n const fullKey = this.getFullKey(key);\n if (BaseLatticeManager.registry.has(fullKey)) {\n throw new Error(`项目 \"${fullKey}\" 已经存在,无法重复注册`);\n }\n\n BaseLatticeManager.registry.set(fullKey, item);\n }\n\n /**\n * 获取指定项目\n * @param key 项目键名(不含前缀)\n */\n public get(key: string): TItem | undefined {\n const fullKey = this.getFullKey(key);\n return BaseLatticeManager.registry.get(fullKey) as TItem | undefined;\n }\n\n /**\n * 获取所有当前类型的项目\n */\n public getAll(): TItem[] {\n const prefix = `${this.getLatticeType()}.`;\n const result: TItem[] = [];\n\n for (const [key, value] of BaseLatticeManager.registry.entries()) {\n if (key.startsWith(prefix)) {\n result.push(value as TItem);\n }\n }\n\n return result;\n }\n\n /**\n * 检查项目是否存在\n * @param key 项目键名(不含前缀)\n */\n public has(key: string): boolean {\n const fullKey = this.getFullKey(key);\n return BaseLatticeManager.registry.has(fullKey);\n }\n\n /**\n * 移除项目\n * @param key 项目键名(不含前缀)\n */\n public remove(key: string): boolean {\n const fullKey = this.getFullKey(key);\n return BaseLatticeManager.registry.delete(fullKey);\n }\n\n /**\n * 清空当前类型的所有项目\n */\n public clear(): void {\n const prefix = `${this.getLatticeType()}.`;\n const keysToDelete: string[] = [];\n\n for (const key of BaseLatticeManager.registry.keys()) {\n if (key.startsWith(prefix)) {\n keysToDelete.push(key);\n }\n }\n\n for (const key of keysToDelete) {\n BaseLatticeManager.registry.delete(key);\n }\n }\n\n /**\n * 获取当前类型的项目数量\n */\n public count(): number {\n const prefix = `${this.getLatticeType()}.`;\n let count = 0;\n\n for (const key of BaseLatticeManager.registry.keys()) {\n if (key.startsWith(prefix)) {\n count++;\n }\n }\n\n return count;\n }\n\n /**\n * 获取当前类型的项目键名列表(不含前缀)\n */\n public keys(): string[] {\n const prefix = `${this.getLatticeType()}.`;\n const prefixLength = prefix.length;\n const result: string[] = [];\n\n for (const key of BaseLatticeManager.registry.keys()) {\n if (key.startsWith(prefix)) {\n result.push(key.substring(prefixLength));\n }\n }\n\n return result;\n }\n}\n","import {\n AIMessage,\n BaseMessage,\n BaseMessageLike,\n HumanMessage,\n} from \"@langchain/core/messages\";\nimport { ChatDeepSeek } from \"@langchain/deepseek\";\nimport { AzureChatOpenAI, ChatOpenAI } from \"@langchain/openai\";\nimport { z } from \"zod\";\nimport { ZodType as ZodTypeV3 } from \"zod/v3\";\nimport { $ZodType as ZodTypeV4 } from \"zod/v4/core\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n BaseLanguageModel,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n CallbackManagerForLLMRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nBaseLanguageModel;\nimport { LLMConfig } from \"@axiom-lattice/protocols\";\n\n/**\n * ModelLattice类,继承自BaseChatModel\n * 简化版本,只保留通过LLMConfig创建LLM实例的功能\n */\nexport class ModelLattice extends BaseChatModel {\n private config: LLMConfig;\n private llm: BaseChatModel;\n\n lc_namespace: string[] = [\"langchain\", \"model_lattice\"];\n\n /**\n * 构造函数\n * @param config LLM配置\n */\n constructor(config: LLMConfig) {\n super({});\n this.config = config;\n this.llm = this.initChatModel(config);\n }\n\n /**\n * 返回模型类型\n */\n _llmType(): string {\n return \"model_lattice\";\n }\n\n /**\n * 返回模型类型\n */\n _modelType(): string {\n return this.llm._modelType();\n }\n\n /**\n * 实现BaseChatModel的_generate方法\n * @param messages 消息数组\n * @param options 调用选项\n * @param runManager 回调管理器\n * @returns 聊天结果\n */\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n return this.llm._generate(messages, options as any, runManager);\n }\n\n /**\n * 将工具绑定到模型\n * @param tools 工具列表\n * @param tool_choice 工具选择选项\n * @returns 绑定工具后的模型\n */\n bindTools(\n tools: any[],\n {\n tool_choice = \"auto\",\n ...kwargs\n }: {\n tool_choice?: \"auto\" | \"none\" | \"required\" | any;\n [key: string]: any;\n } = {}\n ): any {\n // 如果底层LLM实现了bindTools方法,则使用它的实现\n if (typeof this.llm.bindTools === \"function\") {\n return this.llm.bindTools(tools, {\n tool_choice,\n ...kwargs,\n });\n }\n\n // 如果底层LLM没有实现bindTools方法,抛出错误\n throw new Error(\"llm not support bindTools\");\n }\n\n /**\n * 使用结构化输出调用LLM\n * @param input 输入\n * @param schema 结构化输出的schema\n * @param options 调用选项\n * @returns 结构化输出\n */\n async invokeWithStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n input: BaseLanguageModelInput,\n schema: ZodTypeV3<RunOutput> | ZodTypeV4<RunOutput> | Record<string, any>,\n options?: BaseChatModelCallOptions & {\n includeRaw?: boolean;\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\";\n }\n ): Promise<RunOutput | { raw: BaseMessage; parsed: RunOutput }> {\n // 使用LLM的withStructuredOutput方法\n if (this.llm.withStructuredOutput) {\n // 使用类型断言解决类型兼容性问题\n const structuredLLM = this.llm.withStructuredOutput(schema, {\n includeRaw: options?.includeRaw ?? false,\n name: options?.name,\n method: options?.method,\n } as any);\n\n return structuredLLM.invoke(input, options);\n }\n\n // 如果LLM没有withStructuredOutput方法,抛出错误\n throw new Error(\"当前LLM不支持结构化输出\");\n }\n\n /**\n * 创建LLM实例\n * @param config LLM配置\n * @returns LLM实例\n */\n private initChatModel(config: LLMConfig): BaseChatModel {\n if (config.provider === \"azure\") {\n return new AzureChatOpenAI({\n azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,\n azureOpenAIApiInstanceName: \"convertlab-westus\",\n azureOpenAIApiDeploymentName: config.model,\n azureOpenAIApiVersion: \"2024-02-01\",\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n streaming: config.streaming,\n });\n } else if (config.provider === \"deepseek\") {\n return new ChatDeepSeek({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n apiKey: process.env[config.apiKeyEnvName || \"DEEPSEEK_API_KEY\"],\n streaming: config.streaming,\n });\n } else if (config.provider === \"siliconcloud\") {\n return new ChatOpenAI({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n apiKey: process.env[config.apiKeyEnvName || \"SILICONCLOUD_API_KEY\"],\n configuration: {\n baseURL: \"https://api.siliconflow.cn/v1\",\n },\n streaming: config.streaming,\n });\n } else if (config.provider === \"volcengine\") {\n return new ChatOpenAI({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n apiKey: process.env[config.apiKeyEnvName || \"VOLCENGINE_API_KEY\"],\n configuration: {\n baseURL: \"https://ark.cn-beijing.volces.com/api/v3\",\n },\n streaming: config.streaming,\n });\n } else {\n return new ChatOpenAI({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n streaming: config.streaming,\n apiKey: process.env[config.apiKeyEnvName || \"OPENAI_API_KEY\"],\n configuration: {\n baseURL: config.baseURL,\n },\n });\n }\n }\n}\n","import { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { ModelLattice as LLMModelLattice } from \"./ModelLattice\";\nimport { LLMConfig } from \"@axiom-lattice/protocols\";\n\n// 模型配置接口,直接使用 LLMConfig\nexport type ModelConfig = LLMConfig;\n\n// 模型客户端类型,使用 LLMManager\ntype ModelClient = LLMModelLattice;\n\n// 定义接口\nexport interface ModelLatticeInterface {\n key: string;\n client: ModelClient;\n}\n\n/**\n * ModelLatticeManager - 单例模型Lattice管理器\n * 负责注册、管理各种语言模型Lattice\n */\nexport class ModelLatticeManager extends BaseLatticeManager<ModelLatticeInterface> {\n private static _instance: ModelLatticeManager;\n\n /**\n * 获取ModelLatticeManager单例实例\n */\n public static getInstance(): ModelLatticeManager {\n if (!ModelLatticeManager._instance) {\n ModelLatticeManager._instance = new ModelLatticeManager();\n }\n return ModelLatticeManager._instance;\n }\n\n /**\n * 获取Lattice类型前缀\n */\n protected getLatticeType(): string {\n return \"models\";\n }\n\n /**\n * 注册模型Lattice\n * @param key Lattice键名\n * @param config 模型配置\n */\n public registerLattice(key: string, config: ModelConfig): void {\n // 使用 LLMManager 创建客户端\n const client = new LLMModelLattice(config);\n\n // 创建模型Lattice对象\n const modelLattice: ModelLatticeInterface = {\n key,\n client,\n };\n\n // 调用基类的register方法\n this.register(key, modelLattice);\n }\n\n /**\n * 获取ModelLattice\n * @param key Lattice键名\n */\n public getModelLattice(key: string): ModelLatticeInterface {\n const modelLattice = this.get(key);\n if (!modelLattice) {\n throw new Error(`ModelLattice ${key} not found`);\n }\n return modelLattice;\n }\n\n /**\n * 获取所有Lattice\n */\n public getAllLattices(): ModelLatticeInterface[] {\n return this.getAll();\n }\n\n /**\n * 检查Lattice是否存在\n * @param key Lattice键名\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * 移除Lattice\n * @param key Lattice键名\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * 清空所有Lattice\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * 获取Lattice数量\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * 获取Lattice键名列表\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// 导出单例实例\nexport const modelLatticeManager = ModelLatticeManager.getInstance();\n\n// 导出便捷方法\nexport const registerModelLattice = (key: string, config: ModelConfig) =>\n modelLatticeManager.registerLattice(key, config);\n\nexport const getModelLattice = (key: string) =>\n modelLatticeManager.getModelLattice(key);\n","import z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\n\nregisterToolLattice(\n \"get_current_date_time\",\n {\n name: \"get_current_date_time\",\n description: \"获取当前日期时间\",\n schema: z.object({}),\n },\n async () => {\n return \"当前日期时间:\" + new Date().toLocaleString();\n }\n);\n","import { StructuredTool, tool } from \"@langchain/core/tools\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { ToolConfig, ToolExecutor } from \"@axiom-lattice/protocols\";\nimport { createToolApproveWrapper } from \"./createToolApproveWrapper\";\n\n// 工具定义接口 - 使用协议中的ToolConfig\nexport type ToolDefinition = ToolConfig;\n\n// Lattice 接口定义\nexport interface ToolLattice {\n key: string;\n config: ToolConfig;\n client: StructuredTool;\n}\n\n/**\n * ToolLatticeManager - 单例工具Lattice管理器\n * 负责注册、管理各种工具Lattice\n */\nexport class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {\n private static _instance: ToolLatticeManager;\n\n /**\n * 获取ToolLatticeManager单例实例\n */\n public static getInstance(): ToolLatticeManager {\n if (!ToolLatticeManager._instance) {\n ToolLatticeManager._instance = new ToolLatticeManager();\n }\n return ToolLatticeManager._instance;\n }\n\n /**\n * 获取Lattice类型前缀\n */\n protected getLatticeType(): string {\n return \"tools\";\n }\n\n /**\n * 注册工具Lattice\n * @param key Lattice键名\n * @param config 工具配置(定义)\n * @param executor 工具执行函数\n */\n public registerLattice<TInput = any, TOutput = any>(\n key: string,\n config: ToolConfig,\n executor: ToolExecutor<TInput, TOutput>\n ): void {\n // 创建工具Lattice对象\n let toolExecutor;\n\n if (config.needUserApprove) {\n toolExecutor = createToolApproveWrapper<TInput, TOutput>(\n config,\n executor\n );\n } else {\n toolExecutor = async (input: TInput, exe_config: any) => {\n const result = await executor(input, exe_config);\n return result;\n };\n }\n\n const toolLattice: ToolLattice = {\n key,\n config,\n client: tool(toolExecutor as ToolExecutor, config),\n };\n\n // 调用基类的register方法\n this.register(key, toolLattice);\n }\n\n /**\n * 获取ToolLattice\n * @param key Lattice键名\n */\n public getToolLattice(key: string): ToolLattice | undefined {\n return this.get(key);\n }\n\n /**\n * 获取所有Lattice\n */\n public getAllLattices(): ToolLattice[] {\n return this.getAll();\n }\n\n /**\n * 检查Lattice是否存在\n * @param key Lattice键名\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * 移除Lattice\n * @param key Lattice键名\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * 清空所有Lattice\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * 获取Lattice数量\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * 获取Lattice键名列表\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * 获取工具定义\n * @param key Lattice键名\n */\n public getToolDefinition(key: string): ToolDefinition {\n const toolLattice = this.getToolLattice(key);\n if (!toolLattice) {\n throw new Error(`ToolLattice ${key} not found`);\n }\n return toolLattice.config;\n }\n\n /**\n * 获取工具客户端\n * @param key Lattice键名\n */\n public getToolClient(key: string): StructuredTool {\n const toolLattice = this.getToolLattice(key);\n if (!toolLattice) {\n throw new Error(`ToolLattice ${key} not found`);\n }\n return toolLattice.client;\n }\n\n /**\n * 获取所有工具定义\n */\n public getAllToolDefinitions(): ToolDefinition[] {\n return this.getAllLattices().map((lattice) => lattice.config);\n }\n\n /**\n * 验证工具输入参数\n * @param key Lattice键名\n * @param input 输入参数\n */\n public validateToolInput(key: string, input: any): boolean {\n const toolLattice = this.getToolLattice(key);\n if (!toolLattice) {\n return false;\n }\n\n try {\n if (toolLattice.config.schema) {\n toolLattice.config.schema.parse(input);\n }\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// 导出单例实例\nexport const toolLatticeManager = ToolLatticeManager.getInstance();\n\n// 导出便捷方法\nexport const registerToolLattice = (\n key: string,\n config: ToolConfig,\n executor: ToolExecutor\n) => toolLatticeManager.registerLattice(key, config, executor);\n\nexport const getToolLattice = (key: string) =>\n toolLatticeManager.getToolLattice(key);\n\nexport const getToolDefinition = (key: string) =>\n toolLatticeManager.getToolDefinition(key);\n\nexport const getToolClient = (key: string) =>\n toolLatticeManager.getToolClient(key);\n\nexport const getAllToolDefinitions = () =>\n toolLatticeManager.getAllToolDefinitions();\n\nexport const validateToolInput = (key: string, input: any) =>\n toolLatticeManager.validateToolInput(key, input);\n","export const genUIMarkdown = (type: string, data: any) => {\n return [\"```\" + type, JSON.stringify(data), \"```\"].join(\"\\n\");\n};\n","import { AIMessage, isAIMessage } from \"@langchain/core/messages\";\nimport { ToolLatticeManager } from \"./ToolLatticeManager\";\nimport { ToolLattice } from \"./ToolLatticeManager\";\nimport { genUIMarkdown } from \"../util/genUIMarkdown\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport { UserFeedbackResponse } from \"../types\";\nimport { END, interrupt } from \"@langchain/langgraph\";\nimport { ToolConfig, ToolExecutor } from \"@axiom-lattice/protocols\";\nexport function createToolApproveWrapper<TInput = any, TOutput = any>(\n tool_config: ToolConfig,\n toolExecutor: ToolExecutor<TInput, TOutput>\n) {\n return async (input: TInput, exe_config: any) => {\n const messagePrefix = \"Tool execution requires approval\";\n const description = `${messagePrefix}\\n\\nTool: ${tool_config.name}\\nArgs: ${JSON.stringify(input, null, 2)}`;\n\n const md = genUIMarkdown(\"confirm\", {\n message: description,\n tool_call: {\n tool_call_id: exe_config.id,\n tool_name: tool_config.name,\n tool_args: input,\n tool_config: tool_config,\n },\n });\n\n const feedback: UserFeedbackResponse = await interrupt(md);\n\n if (feedback.data.action === \"yes\") {\n return await toolExecutor(input, exe_config);\n } else {\n return {\n goto: END,\n };\n }\n };\n}\n","import z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { TavilySearch } from \"@langchain/tavily\";\nimport \"dotenv/config\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { genUICard } from \"@util/genUICard\";\n\ntype Topic = \"general\" | \"news\" | \"finance\";\n\nregisterToolLattice(\n \"internet_search\",\n {\n name: \"internet_search\",\n description: \"Run a web search\",\n needUserApprove: false,\n schema: z.object({\n query: z.string().describe(\"The search query\"),\n maxResults: z\n .number()\n .optional()\n .default(5)\n .describe(\"Maximum number of results to return\"),\n topic: z\n .enum([\"general\", \"news\", \"finance\"])\n .optional()\n .default(\"general\")\n .describe(\"Search topic category\"),\n includeRawContent: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to include raw content\"),\n }),\n },\n async (\n {\n query,\n maxResults = 5,\n topic = \"general\" as Topic,\n includeRawContent = false,\n }: {\n query: string;\n maxResults?: number;\n topic?: Topic;\n includeRawContent?: boolean;\n },\n config: LangGraphRunnableConfig\n ) => {\n /**\n * Run a web search\n */\n console.log(\"[DEBUG][internet_search] Starting search with params:\", {\n query,\n maxResults,\n topic,\n includeRawContent,\n });\n\n // Note: You'll need to install and import tavily-js or similar package\n console.log(\"[DEBUG][internet_search] Creating TavilySearch instance...\");\n const tavilySearch = new TavilySearch({\n maxResults,\n tavilyApiKey: process.env.TAVILY_API_KEY,\n includeRawContent,\n topic,\n });\n\n console.log(\"[DEBUG][internet_search] Invoking search for query:\", query);\n const tavilyResponse = await tavilySearch.invoke({ query });\n console.log(\n \"[DEBUG][internet_search] Search completed. Results count:\",\n tavilyResponse.results?.length ?? 0\n );\n\n const result = genUICard(\"Internet Search:\" + query, \"generic_data_table\", {\n dataSource: tavilyResponse.results,\n });\n console.log(\"[DEBUG][internet_search] Returning UI card result\");\n\n return result;\n }\n);\n","export const genUICard = (title: string, type: string, data: any) => {\n return [title, \"```\" + type, JSON.stringify(data), \"```\"].join(\"\\n\");\n};\n","/**\n * Write Todos Tool\n *\n * Manages todo list with Command return for deep agents.\n * Uses getCurrentTaskInput() instead of Python's InjectedState.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { Command } from \"@langchain/langgraph\";\nimport { genUIMarkdown } from \"@util/genUIMarkdown\";\n\nconst 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.\n\nWhen to Use This Tool\nUse this tool proactively in these scenarios:\n\nComplex multi-step tasks - When a task requires 3 or more distinct steps or actions\nNon-trivial and complex tasks - Tasks that require careful planning or multiple operations\nUser explicitly requests todo list - When the user directly asks you to use the todo list\nUser provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\nAfter receiving new instructions - Immediately capture user requirements as todos\nWhen 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\nAfter completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation\n\nWhen NOT to Use This Tool\nSkip using this tool when:\n\nThere is only a single, straightforward task\nThe task is trivial and tracking it provides no organizational benefit\nThe task can be completed in less than 3 trivial steps\nThe task is purely conversational or informational\n\nNOTE 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.`;\n\nregisterToolLattice(\n \"write_todos\",\n {\n name: \"write_todos\",\n description: WRITE_TODOS_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n todos: z\n .array(\n z.object({\n content: z.string().describe(\"Content of the todo item\"),\n status: z\n .enum([\"pending\", \"in_progress\", \"completed\"])\n .describe(\"Status of the todo\"),\n })\n )\n .describe(\"List of todo items to update\"),\n }),\n },\n ((\n input: {\n todos: Array<{\n content: string;\n status: \"pending\" | \"in_progress\" | \"completed\";\n }>;\n },\n config: ToolRunnableConfig\n ) => {\n return new Command({\n update: {\n todos: input.todos,\n messages: [\n new ToolMessage({\n content: genUIMarkdown(\"todo_list\", input.todos),\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }) as any\n);\n","/**\n * Read File Tool\n *\n * Reads from mock filesystem in state.files.\n * Matches Python read_file function behavior exactly.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nconst READ_FILE_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.\nUsage:\n\nThe file_path parameter must be an absolute path, not a relative path\nBy default, it reads up to 2000 lines starting from the beginning of the file\nYou 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\nAny lines longer than 2000 characters will be truncated\nResults are returned using cat -n format, with line numbers starting at 1\nYou 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.\nIf you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;\n\nregisterToolLattice(\n \"read_file\",\n {\n name: \"read_file\",\n description: READ_FILE_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to read\"),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from\"),\n limit: z\n .number()\n .optional()\n .default(2000)\n .describe(\"Maximum number of lines to read\"),\n }),\n },\n ((input: { file_path: string; offset?: number; limit?: number }) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = state.files || {};\n const { file_path, offset = 0, limit = 2000 } = input;\n\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get file content\n const content = mockFilesystem[file_path];\n\n // Handle empty file\n if (!content || content.trim() === \"\") {\n return \"System reminder: File exists but has empty contents\";\n }\n\n // Split content into lines\n const lines = content.split(\"\\n\");\n\n // Apply line offset and limit\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n // Handle case where offset is beyond file length\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n // Format output with line numbers (cat -n format)\n const resultLines: string[] = [];\n for (let i = startIdx; i < endIdx; i++) {\n let lineContent = lines[i];\n\n // Truncate lines longer than 2000 characters\n if (lineContent.length > 2000) {\n lineContent = lineContent.substring(0, 2000);\n }\n\n // Line numbers start at 1, so add 1 to the index\n const lineNumber = i + 1;\n resultLines.push(`${lineNumber.toString().padStart(6)}\\t${lineContent}`);\n }\n\n return resultLines.join(\"\\n\");\n }) as any\n);\n","/**\n * Write File Tool\n *\n * Writes to mock filesystem with Command return.\n * Matches Python write_file function behavior exactly.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nregisterToolLattice(\n \"write_file\",\n {\n name: \"write_file\",\n description: \"Write content to a file in the mock filesystem\",\n needUserApprove: false,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to write\"),\n content: z.string().describe(\"Content to write to the file\"),\n }),\n },\n ((\n input: { file_path: string; content: string },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = { ...(state.files || {}) };\n files[input.file_path] = input.content;\n\n return new Command({\n update: {\n files: files,\n messages: [\n new ToolMessage({\n content: `Updated file ${input.file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }) as any\n);\n\n","/**\n * Edit File Tool\n *\n * Edits files in mock filesystem with Command return.\n * Matches Python edit_file function behavior exactly.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nconst EDIT_FILE_DESCRIPTION = `Performs exact string replacements in files.\nUsage:\n\nYou 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.\nWhen 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.\nALWAYS prefer editing existing files. NEVER write new files unless explicitly required.\nOnly use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\nThe 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.\nUse replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;\n\nregisterToolLattice(\n \"edit_file\",\n {\n name: \"edit_file\",\n description: EDIT_FILE_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to edit\"),\n old_string: z\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z.string().describe(\"String to replace with\"),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n },\n ((\n input: {\n file_path: string;\n old_string: string;\n new_string: string;\n replace_all?: boolean;\n },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = { ...(state.files || {}) };\n const { file_path, old_string, new_string, replace_all = false } = input;\n\n // Check if file exists in mock filesystem\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get current file content\n const content = mockFilesystem[file_path];\n\n // Check if old_string exists in the file\n if (!content.includes(old_string)) {\n return `Error: String not found in file: '${old_string}'`;\n }\n\n // If not replace_all, check for uniqueness\n if (!replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n const occurrences = (\n content.match(new RegExp(escapedOldString, \"g\")) || []\n ).length;\n if (occurrences > 1) {\n 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.`;\n } else if (occurrences === 0) {\n return `Error: String not found in file: '${old_string}'`;\n }\n }\n\n // Perform the replacement\n let newContent: string;\n\n if (replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n newContent = content.replace(\n new RegExp(escapedOldString, \"g\"),\n new_string\n );\n } else {\n newContent = content.replace(old_string, new_string);\n }\n\n // Update the mock filesystem\n mockFilesystem[file_path] = newContent;\n\n return new Command({\n update: {\n files: mockFilesystem,\n messages: [\n new ToolMessage({\n content: `Updated file ${file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }) as any\n);\n\n","/**\n * List Files Tool\n *\n * Returns list of files from state.files.\n * Equivalent to Python's ls function.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nregisterToolLattice(\n \"ls\",\n {\n name: \"ls\",\n description: \"List all files in the mock filesystem\",\n needUserApprove: false,\n schema: z.object({}),\n },\n (() => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = state.files || {};\n return Object.keys(files);\n }) as any\n);\n\n","/**\n * Agent Lattice 类型定义\n *\n * 包含Agent Lattice相关的所有类型定义,供其他模块共享使用\n */\n\nimport { z } from \"zod\";\nimport { ModelLattice } from \"@model_lattice/ModelLattice\";\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport {\n AgentType,\n AgentConfig,\n ReactAgentConfig,\n DeepAgentConfig,\n PlanExecuteAgentConfig,\n SequentialAgentConfig,\n AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n} from \"@axiom-lattice/protocols\";\n\n// Re-export types from protocols\nexport {\n AgentType,\n AgentConfig,\n ReactAgentConfig,\n DeepAgentConfig,\n PlanExecuteAgentConfig,\n SequentialAgentConfig,\n AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n};\n\n// Agent客户端类型 - CompiledStateGraph\nexport type AgentClient = CompiledStateGraph<any, any, any, any, any>;\n\n// AgentLattice接口定义\nexport interface AgentLattice {\n config: AgentConfig;\n client?: AgentClient | undefined;\n}\n\n// Agent构建参数接口\nexport interface AgentBuildParams {\n tools: Array<{\n key: string;\n definition: any;\n executor: any;\n }>;\n model: ModelLattice;\n subAgents: Array<{\n key: string;\n config: AgentConfig;\n client: AgentClient | undefined;\n }>;\n prompt: string;\n stateSchema?: z.ZodObject<any, any, any, any, any>;\n}\n","/**\n * ReAct Agent Graph Builder\n *\n * 实现 ReAct 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph, MessagesZodState } from \"@langchain/langgraph\";\nimport { DynamicTool } from \"@langchain/core/tools\";\nimport { AgentLattice, AgentBuildParams } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { getCheckpointSaver } from \"@memory_lattice\";\nimport { createReactAgentSchema, ReActAgentState } from \"./state\";\n\nexport class ReActAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 构建ReAct Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(\n agentLattice: AgentLattice,\n params: AgentBuildParams\n ): CompiledStateGraph<any, any, any, any, any> {\n // 创建符合 DynamicTool 接口的工具对象\n const tools = params.tools\n .map((t) => {\n // 使用 DynamicTool 构造工具对象\n const tool = getToolClient(t.key);\n return tool;\n })\n .filter((tool) => tool !== undefined);\n\n const stateSchema = createReactAgentSchema(params.stateSchema);\n\n return createReactAgent({\n llm: params.model,\n tools: tools,\n prompt: params.prompt,\n name: agentLattice.config.name,\n checkpointer: getCheckpointSaver(\"default\"),\n stateSchema: stateSchema,\n });\n }\n}\n","import { MemorySaver } from \"@langchain/langgraph\";\nimport { registerCheckpointSaver } from \"./MemoryLatticeManager\";\nconst memory = new MemorySaver();\nregisterCheckpointSaver(\"default\", memory);\n","/**\n * MemoryLatticeManager\n *\n * 记忆Lattice管理器,负责管理和注册检查点保存器\n */\n\nimport { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { MemoryLatticeProtocol, MemoryType } from \"@axiom-lattice/protocols\";\n\n// Re-export types from protocols\nexport { MemoryType };\n\n/**\n * 记忆Lattice管理器类\n */\nexport class MemoryLatticeManager extends BaseLatticeManager {\n private static instance: MemoryLatticeManager;\n\n // 检查点保存器注册表\n private static checkpointSavers: Map<string, BaseCheckpointSaver> = new Map();\n\n /**\n * 私有构造函数,防止外部直接实例化\n */\n private constructor() {\n super();\n }\n\n /**\n * 获取单例实例\n */\n public static getInstance(): MemoryLatticeManager {\n if (!MemoryLatticeManager.instance) {\n MemoryLatticeManager.instance = new MemoryLatticeManager();\n }\n return MemoryLatticeManager.instance;\n }\n\n /**\n * 获取Lattice类型\n */\n protected getLatticeType(): string {\n return \"memory\";\n }\n\n /**\n * 注册检查点保存器\n * @param key 保存器键名\n * @param saver 检查点保存器实例\n */\n public registerCheckpointSaver(\n key: string,\n saver: BaseCheckpointSaver\n ): void {\n if (MemoryLatticeManager.checkpointSavers.has(key)) {\n console.warn(`检查点保存器 \"${key}\" 已经存在,将会覆盖旧的检查点保存器`);\n }\n\n MemoryLatticeManager.checkpointSavers.set(key, saver);\n }\n\n /**\n * 获取检查点保存器\n * @param key 保存器键名\n */\n public getCheckpointSaver(key: string): BaseCheckpointSaver {\n const saver = MemoryLatticeManager.checkpointSavers.get(key);\n if (!saver) {\n throw new Error(`检查点保存器 \"${key}\" 不存在`);\n }\n return saver;\n }\n\n /**\n * 获取所有已注册的检查点保存器键名\n */\n public getCheckpointSaverKeys(): string[] {\n return Array.from(MemoryLatticeManager.checkpointSavers.keys());\n }\n\n /**\n * 检查检查点保存器是否存在\n * @param key 保存器键名\n */\n public hasCheckpointSaver(key: string): boolean {\n return MemoryLatticeManager.checkpointSavers.has(key);\n }\n\n /**\n * 移除检查点保存器\n * @param key 保存器键名\n */\n public removeCheckpointSaver(key: string): boolean {\n return MemoryLatticeManager.checkpointSavers.delete(key);\n }\n}\n\nexport const getCheckpointSaver = (key: string) =>\n MemoryLatticeManager.getInstance().getCheckpointSaver(key);\n\nexport const registerCheckpointSaver = (\n key: string,\n saver: BaseCheckpointSaver\n) => MemoryLatticeManager.getInstance().registerCheckpointSaver(key, saver);\n","/**\n * State definitions for Deep Agents\n *\n * TypeScript equivalents of the Python state classes using LangGraph's Annotation.Root() pattern.\n * Defines Todo interface and DeepAgentState using MessagesAnnotation as base with proper reducer functions.\n */\n\nimport \"@langchain/langgraph/zod\";\nimport { MessagesZodState } from \"@langchain/langgraph\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\nimport { z } from \"zod\";\n\n/**\n * File reducer function that merges file dictionaries\n * Matches the Python file_reducer function behavior exactly\n */\nexport function fileReducer(\n left: Record<string, string> | null | undefined,\n right: Record<string, string> | null | undefined\n): Record<string, string> {\n if (left == null) {\n return right || {};\n } else if (right == null) {\n return left;\n } else {\n return { ...left, ...right };\n }\n}\n\nexport const ReActAgentState = MessagesZodState.extend({\n files: z.object({\n final_output: z.record(z.any()),\n }),\n});\n\nexport const createReactAgentSchema = (\n schema?: z.ZodObject<any, any, any, any, any>\n) => {\n return schema ? MessagesZodState.extend(schema.shape) : undefined;\n};\n","/**\n * SubAgent implementation for Deep Agents\n *\n * Task tool creation and sub-agent management.\n * Creates SubAgent interface matching Python's TypedDict structure and implements\n * createTaskTool() function that creates agents map, handles tool resolution by name,\n * and returns a tool function that uses createReactAgent for sub-agents.\n */\n\nimport { tool, StructuredTool } from \"@langchain/core/tools\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport {\n Command,\n getCurrentTaskInput,\n GraphInterrupt,\n} from \"@langchain/langgraph\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { z } from \"zod\";\nimport type { LanguageModelLike, PostModelHook, SubAgent } from \"./types\";\nimport { TASK_DESCRIPTION_PREFIX, TASK_DESCRIPTION_SUFFIX } from \"./prompts\";\nimport { ModelLattice } from \"../model_lattice/ModelLattice\";\nimport { getModelLattice } from \"../model_lattice/ModelLatticeManager\";\nimport { getCheckpointSaver } from \"@memory_lattice/MemoryLatticeManager\";\nimport {\n createAgentClientFromAgentLattice,\n getAgentClient,\n getAgentLattice,\n} from \"@agent_lattice/AgentLatticeManager\";\nimport {\n AgentConfig,\n getToolsFromConfig,\n hasTools,\n} from \"@axiom-lattice/protocols\";\nimport { getToolClient } from \"@tool_lattice\";\n\n/**\n * Built-in tool names for tool resolution\n */\nconst BUILTIN_TOOL_NAMES = [\n \"write_todos\",\n \"read_file\",\n \"write_file\",\n \"edit_file\",\n \"ls\",\n];\n\n/**\n * Get built-in tools map from ToolLatticeManager\n */\nfunction getBuiltinTools(): Record<string, StructuredTool> {\n const tools: Record<string, StructuredTool> = {};\n for (const name of BUILTIN_TOOL_NAMES) {\n try {\n tools[name] = getToolClient(name);\n } catch {\n // Tool may not be registered yet, skip\n }\n }\n return tools;\n}\n\n/**\n * Create task tool function that creates agents map, handles tool resolution by name,\n * and returns a tool function that uses createReactAgent for sub-agents.\n * Uses Command for state updates and navigation between agents.\n */\nexport function createTaskTool<\n StateSchema extends z.ZodObject<any, any, any, any, any>\n>(inputs: {\n subagents: AgentConfig[];\n tools: Record<string, StructuredTool>;\n model: ModelLattice;\n stateSchema: StateSchema;\n postModelHook?: PostModelHook;\n}) {\n const {\n subagents,\n tools = {},\n model = getModelLattice(\"default\")?.client,\n stateSchema,\n postModelHook,\n } = inputs;\n\n if (!model) {\n throw new Error(\"Model not found\");\n }\n\n // Combine built-in tools with provided tools for tool resolution\n const allTools = { ...getBuiltinTools(), ...tools };\n\n const agentsMap = new Map<string, any>();\n for (const subagent of subagents) {\n let reactAgent;\n const agentLattice = getAgentLattice(subagent.key); // get agent lattice from lattice registry\n if (agentLattice) {\n //use agent lattice client directly\n reactAgent = agentLattice.client;\n } else {\n // Resolve tools by name for this subagent\n const subagentTools: StructuredTool[] = [];\n if (hasTools(subagent)) {\n for (const toolName of getToolsFromConfig(subagent)) {\n const resolvedTool = allTools[toolName];\n if (resolvedTool) {\n subagentTools.push(resolvedTool);\n } else {\n // eslint-disable-next-line no-console\n console.warn(\n `Warning: Tool '${toolName}' not found for agent '${subagent.name}'`\n );\n }\n }\n } else {\n // If no tools specified, use all tools\n subagentTools.push(...Object.values(allTools));\n }\n\n // Create react agent for the subagent\n\n reactAgent = createAgentClientFromAgentLattice({ config: subagent });\n\n // reactAgent = createReactAgent({\n // llm: model,\n // tools: subagentTools,\n // stateSchema: stateSchema as any,\n // messageModifier: subagent.prompt,\n // // checkpointer: false,\n // checkpointer: getCheckpointSaver(\"default\"),\n\n // postModelHook: postModelHook,\n // });\n }\n\n agentsMap.set(subagent.name, reactAgent);\n }\n\n return tool(\n async (\n input: { description: string; subagent_type: string },\n config: ToolRunnableConfig\n ) => {\n const { description, subagent_type } = input;\n\n // Get the pre-created agent\n const reactAgent = agentsMap.get(subagent_type);\n if (!reactAgent) {\n return `Error: Agent '${subagent_type}' not found. Available agents: ${Array.from(\n agentsMap.keys()\n ).join(\", \")}`;\n }\n\n try {\n // Get current state for context\n const currentState = getCurrentTaskInput<z.infer<typeof stateSchema>>();\n\n // Modify state messages like Python does\n const modifiedState = {\n ...currentState,\n messages: [\n {\n role: \"user\",\n content: description,\n },\n ],\n };\n\n // Execute the subagent with the task\n const result = await reactAgent.invoke(modifiedState, config);\n\n // Use Command for state updates and navigation between agents\n // Return the result using Command to properly handle subgraph state\n return new Command({\n update: {\n files: result.files || {},\n messages: [\n new ToolMessage({\n content:\n result.messages?.slice(-1)[0]?.content || \"Task completed\",\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n } catch (error) {\n if (error instanceof GraphInterrupt) {\n throw error;\n }\n // Handle errors gracefully\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return new Command({\n update: {\n messages: [\n new ToolMessage({\n content: `Error executing task '${description}' with agent '${subagent_type}': ${errorMessage}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }\n },\n {\n name: \"task\",\n description:\n TASK_DESCRIPTION_PREFIX.replace(\n \"{other_agents}\",\n subagents.map((a) => `- ${a.name}: ${a.description}`).join(\"\\n\")\n ) + TASK_DESCRIPTION_SUFFIX,\n schema: z.object({\n description: z\n .string()\n .describe(\"The task to execute with the selected agent\"),\n subagent_type: z\n .string()\n .describe(\n `Name of the agent to use. Available: ${subagents\n .map((a) => a.name)\n .join(\", \")}`\n ),\n }),\n }\n );\n}\n","/**\n * Prompt constants for Deep Agents\n *\n * All prompt strings ported from Python implementation with exact string content and formatting\n * to ensure 1:1 compatibility with the Python version.\n */\n\n/**\n * Description for the write_todos tool\n * Ported exactly from Python WRITE_TODOS_DESCRIPTION\n */\nexport const 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.\n\nWhen to Use This Tool\nUse this tool proactively in these scenarios:\n\nComplex multi-step tasks - When a task requires 3 or more distinct steps or actions\nNon-trivial and complex tasks - Tasks that require careful planning or multiple operations\nUser explicitly requests todo list - When the user directly asks you to use the todo list\nUser provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\nAfter receiving new instructions - Immediately capture user requirements as todos\nWhen 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\nAfter completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation\nWhen NOT to Use This Tool\nSkip using this tool when:\n\nThere is only a single, straightforward task\nThe task is trivial and tracking it provides no organizational benefit\nThe task can be completed in less than 3 trivial steps\nThe task is purely conversational or informational\nNOTE 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.\n\nExamples of When to Use the Todo List\n<example>\nUser: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!\nAssistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.\n*Creates todo list with the following items:*\n1. Create dark mode toggle component in Settings page\n2. Add dark mode state management (context/store)\n3. Implement CSS-in-JS styles for dark theme\n4. Update existing components to support theme switching\n5. Run tests and build process, addressing any failures or errors that occur\n*Begins working on the first task*\n<reasoning>\nThe assistant used the todo list because:\n1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes\n2. The user explicitly requested tests and build be run afterward\n3. The assistant inferred that tests and build need to pass by adding \"Ensure tests and build succeed\" as the final task\n</reasoning>\n</example>\n<example>\nUser: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.\nAssistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.\n*Creates todo list with the following items:*\n1. Define target audience and key messaging\n2. Create social media content calendar and posting schedule\n3. Design email marketing sequence and automation flows\n4. Draft press release and identify media contacts\n5. Set up tracking and analytics for campaign performance\n6. Create visual assets and brand materials\n7. Coordinate launch timeline and deliverables\n*Begins working on the first task*\n<reasoning>\nThe assistant used the todo list because:\n1. Marketing campaign planning involves multiple distinct channels and activities\n2. Each component requires careful coordination and planning\n3. The systematic approach ensures all aspects of the launch are covered\n4. Progress tracking helps maintain timeline and deliverables\n</reasoning>\n</example>\n<example>\nUser: Help me rename the function getCwd to getCurrentWorkingDirectory across my project\nAssistant: Let me first search through your codebase to find all occurrences of 'getCwd'.\n*Uses search tools to locate all instances of getCwd in the codebase*\nAssistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.\n*Creates todo list with specific items for each file that needs updating*\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant searched to understand the scope of the task\n2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps\n3. The todo list helps ensure every instance is tracked and updated systematically\n4. This approach prevents missing any occurrences and maintains consistency\n</reasoning>\n</example>\n<example>\nUser: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.\nAssistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.\n*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*\nLet's start with decluttering your desk space to create a clean foundation for the other organizational systems.\n<reasoning>\nThe assistant used the todo list because:\n1. The user provided multiple distinct organizational tasks\n2. Each area requires different approaches and careful planning\n3. Home organization benefits from systematic, step-by-step completion\n4. Progress tracking ensures all areas are addressed thoroughly\n</reasoning>\n</example>\nExamples of When NOT to Use the Todo List\n<example>\nUser: How do I print 'Hello World' in Python?\nAssistant: In Python, you can print \"Hello World\" with this simple code:\n\n\\`\\`\\`python\nprint(\"Hello World\")\n\\`\\`\\`\n\nThis will output the text \"Hello World\" to the console when executed.\n<reasoning>\nThe 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.\n</reasoning>\n</example>\n<example>\nUser: What's the best way to water houseplants?\nAssistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:\n\nCheck soil moisture by inserting your finger about 1-2 inches into the soil\nWater thoroughly when the top inch feels dry, allowing water to drain from the bottom\nUse room temperature water and water in the morning when possible\nAvoid overwatering, which is more harmful than underwatering for most plants\n\nDifferent plants have different needs, so it's important to research your specific varieties for optimal care.\n\n<reasoning>\nThe 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.\n</reasoning>\n</example>\n<example>\nUser: Can you add a comment to the calculateTotal function to explain what it does?\nAssistant: Sure, let me add a comment to the calculateTotal function to explain what it does.\n* Uses the Edit tool to add a comment to the calculateTotal function *\n<reasoning>\nThe 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.\n</reasoning>\n</example>\n<example>\nUser: What time is it in Tokyo right now?\nAssistant: I'll check the current time in Tokyo for you.\n\n*Searches for current time in Tokyo*\n\nThe current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.\n\n<reasoning>\nThe 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.\n</reasoning>\n</example>\nTask States and Management\nTask States: Use these states to track progress:\n\npending: Task not yet started\nin_progress: Currently working on (limit to ONE task at a time)\ncompleted: Task finished successfully\nTask Management:\n\nUpdate task status in real-time as you work\nMark tasks complete IMMEDIATELY after finishing (don't batch completions)\nOnly have ONE task in_progress at any time\nComplete current tasks before starting new ones\nRemove tasks that are no longer relevant from the list entirely\nTask Completion Requirements:\n\nONLY mark a task as completed when you have FULLY accomplished it\nIf you encounter errors, blockers, or cannot finish, keep the task as in_progress\nWhen blocked, create a new task describing what needs to be resolved\nNever mark a task as completed if:\nThere are unresolved issues or errors\nWork is partial or incomplete\nYou encountered blockers that prevent completion\nYou couldn't find necessary resources or dependencies\nQuality standards haven't been met\nTask Breakdown:\n\nCreate specific, actionable items\nBreak complex tasks into smaller, manageable steps\nUse clear, descriptive task names\nWhen in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`;\n\n/**\n * Prefix for task tool description\n * Ported exactly from Python TASK_DESCRIPTION_PREFIX\n */\nexport const TASK_DESCRIPTION_PREFIX = `Launch a new agent to handle complex, multi-step tasks autonomously.\n\nAvailable agent types and the tools they have access to:\n\ngeneral-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: *)\n{other_agents}\n`;\n\n/**\n * Suffix for task tool description\n * Ported exactly from Python TASK_DESCRIPTION_SUFFIX\n */\nexport const TASK_DESCRIPTION_SUFFIX = `When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\nWhen to use the Agent tool:\n\nWhen 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\")\nWhen NOT to use the Agent tool:\n\nIf 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\nIf you are searching for a specific term or definition within a known location, use the Glob tool instead, to find the match more quickly\nIf 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\nOther tasks that are not related to the agent descriptions above\nUsage notes:\n\nLaunch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\nWhen 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.\nEach 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.\nThe agent's outputs should generally be trusted\nClearly 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\nIf 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.\nExample usage:\n\n<example_agent_descriptions>\n\"content-reviewer\": use this agent after you are done creating significant content or documents\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n\"research-analyst\": use this agent to conduct thorough research on complex topics\n</example_agent_description>\n\n<example>\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the Write tool to write a function that checks if a number is prime\nassistant: I'm going to use the Write tool to write the following code:\n<code>\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n</code>\n<commentary>\nSince significant content was created and the task was completed, now use the content-reviewer agent to review the work\n</commentary>\nassistant: Now let me use the content-reviewer agent to review the code\nassistant: Uses the Task tool to launch with the content-reviewer agent\n</example>\n<example>\nuser: \"Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?\"\n<commentary>\nThis is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis\n</commentary>\nassistant: 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.\nassistant: 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\n</example>\n<example>\nuser: \"Hello\"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: \"I'm going to use the Task tool to launch with the greeting-responder agent\"\n</example>`;\n\n/**\n * Description for the edit_file tool\n * Ported exactly from Python EDIT_DESCRIPTION\n */\nexport const EDIT_DESCRIPTION = `Performs exact string replacements in files.\nUsage:\n\nYou 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.\nWhen 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.\nALWAYS prefer editing existing files. NEVER write new files unless explicitly required.\nOnly use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\nThe 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.\nUse replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;\n\n/**\n * Description for the read_file tool\n * Ported exactly from Python TOOL_DESCRIPTION\n */\nexport const 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.\nUsage:\n\nThe file_path parameter must be an absolute path, not a relative path\nBy default, it reads up to 2000 lines starting from the beginning of the file\nYou 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\nAny lines longer than 2000 characters will be truncated\nResults are returned using cat -n format, with line numbers starting at 1\nYou 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.\nIf you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;\n","/**\n * Tool functions for Deep Agents\n *\n * TypeScript versions of all tools using @langchain/core/tools tool() function.\n * Uses getCurrentTaskInput() for state access and returns Command objects for state updates.\n * Implements mock filesystem operations using state.files similar to Python version.\n */\n\nimport { tool, ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport { z } from \"zod\";\nimport {\n WRITE_TODOS_DESCRIPTION,\n EDIT_DESCRIPTION,\n TOOL_DESCRIPTION,\n} from \"./prompts\";\nimport { DeepAgentStateType } from \"./types\";\nimport { genUIMarkdown } from \"@util/genUIMarkdown\";\n\n/**\n * Write todos tool - manages todo list with Command return\n * Uses getCurrentTaskInput() instead of Python's InjectedState\n */\nexport const writeTodos = tool(\n (input, config: ToolRunnableConfig) => {\n return new Command({\n update: {\n todos: input.todos,\n messages: [\n new ToolMessage({\n content: genUIMarkdown(\"todo_list\", input.todos),\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n },\n\n {\n name: \"write_todos\",\n description: WRITE_TODOS_DESCRIPTION,\n schema: z.object({\n todos: z\n .array(\n z.object({\n content: z.string().describe(\"Content of the todo item\"),\n status: z\n .enum([\"pending\", \"in_progress\", \"completed\"])\n .describe(\"Status of the todo\"),\n })\n )\n .describe(\"List of todo items to update\"),\n }),\n }\n);\n\n/**\n * List files tool - returns list of files from state.files\n * Equivalent to Python's ls function\n */\nexport const ls = tool(\n () => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = state.files || {};\n return Object.keys(files);\n },\n {\n name: \"ls\",\n description: \"List all files in the mock filesystem\",\n schema: z.object({}),\n }\n);\n\n/**\n * Read file tool - reads from mock filesystem in state.files\n * Matches Python read_file function behavior exactly\n */\nexport const readFile = tool(\n (input: { file_path: string; offset?: number; limit?: number }) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = state.files || {};\n const { file_path, offset = 0, limit = 2000 } = input;\n\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get file content\n const content = mockFilesystem[file_path];\n\n // Handle empty file\n if (!content || content.trim() === \"\") {\n return \"System reminder: File exists but has empty contents\";\n }\n\n // Split content into lines\n const lines = content.split(\"\\n\");\n\n // Apply line offset and limit\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n // Handle case where offset is beyond file length\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n // Format output with line numbers (cat -n format)\n const resultLines: string[] = [];\n for (let i = startIdx; i < endIdx; i++) {\n let lineContent = lines[i];\n\n // Truncate lines longer than 2000 characters\n if (lineContent.length > 2000) {\n lineContent = lineContent.substring(0, 2000);\n }\n\n // Line numbers start at 1, so add 1 to the index\n const lineNumber = i + 1;\n resultLines.push(`${lineNumber.toString().padStart(6)}\t${lineContent}`);\n }\n\n return resultLines.join(\"\\n\");\n },\n {\n name: \"read_file\",\n description: TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to read\"),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from\"),\n limit: z\n .number()\n .optional()\n .default(2000)\n .describe(\"Maximum number of lines to read\"),\n }),\n }\n);\n\n/**\n * Write file tool - writes to mock filesystem with Command return\n * Matches Python write_file function behavior exactly\n */\nexport const writeFile = tool(\n (\n input: { file_path: string; content: string },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = { ...(state.files || {}) };\n files[input.file_path] = input.content;\n\n return new Command({\n update: {\n files: files,\n messages: [\n new ToolMessage({\n content: `Updated file ${input.file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n },\n {\n name: \"write_file\",\n description: \"Write content to a file in the mock filesystem\",\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to write\"),\n content: z.string().describe(\"Content to write to the file\"),\n }),\n }\n);\n\n/**\n * Edit file tool - edits files in mock filesystem with Command return\n * Matches Python edit_file function behavior exactly\n */\nexport const editFile = tool(\n (\n input: {\n file_path: string;\n old_string: string;\n new_string: string;\n replace_all?: boolean;\n },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = { ...(state.files || {}) };\n const { file_path, old_string, new_string, replace_all = false } = input;\n\n // Check if file exists in mock filesystem\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get current file content\n const content = mockFilesystem[file_path];\n\n // Check if old_string exists in the file\n if (!content.includes(old_string)) {\n return `Error: String not found in file: '${old_string}'`;\n }\n\n // If not replace_all, check for uniqueness\n if (!replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n const occurrences = (\n content.match(new RegExp(escapedOldString, \"g\")) || []\n ).length;\n if (occurrences > 1) {\n 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.`;\n } else if (occurrences === 0) {\n return `Error: String not found in file: '${old_string}'`;\n }\n }\n\n // Perform the replacement\n let newContent: string;\n\n if (replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n newContent = content.replace(\n new RegExp(escapedOldString, \"g\"),\n new_string\n );\n } else {\n newContent = content.replace(old_string, new_string);\n }\n\n // Update the mock filesystem\n mockFilesystem[file_path] = newContent;\n\n return new Command({\n update: {\n files: mockFilesystem,\n messages: [\n new ToolMessage({\n content: `Updated file ${file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n },\n {\n name: \"edit_file\",\n description: EDIT_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to edit\"),\n old_string: z\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z.string().describe(\"String to replace with\"),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n }\n);\n","/**\n * State definitions for Deep Agents\n *\n * TypeScript equivalents of the Python state classes using LangGraph's Annotation.Root() pattern.\n * Defines Todo interface and DeepAgentState using MessagesAnnotation as base with proper reducer functions.\n */\n\nimport \"@langchain/langgraph/zod\";\nimport { MessagesZodState } from \"@langchain/langgraph\";\nimport type { Todo } from \"./types\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\nimport { z } from \"zod\";\n\n/**\n * File reducer function that merges file dictionaries\n * Matches the Python file_reducer function behavior exactly\n */\nexport function fileReducer(\n left: Record<string, string> | null | undefined,\n right: Record<string, string> | null | undefined\n): Record<string, string> {\n if (left == null) {\n return right || {};\n } else if (right == null) {\n return left;\n } else {\n return { ...left, ...right };\n }\n}\n\n/**\n * Todo reducer function that replaces the entire todo list\n * This matches the Python behavior where todos are completely replaced\n */\nexport function todoReducer(\n left: Todo[] | null | undefined,\n right: Todo[] | null | undefined\n): Todo[] {\n if (right != null) {\n return right;\n }\n return left || [];\n}\n\n/**\n * DeepAgentState using LangGraph's Annotation.Root() pattern\n * Extends MessagesAnnotation (equivalent to Python's AgentState) with todos and files channels\n */\nexport const DeepAgentState = MessagesZodState.extend({\n todos: withLangGraph(z.custom<Todo[]>(), {\n reducer: {\n schema: z.custom<Todo[]>(),\n fn: todoReducer,\n },\n }),\n\n files: withLangGraph(z.custom<Record<string, string>>(), {\n reducer: {\n schema: z.custom<Record<string, string>>(),\n fn: fileReducer,\n },\n }),\n});\n","/**\n * Main createDeepAgent function for Deep Agents\n *\n * Main entry point for creating deep agents with TypeScript types for all parameters:\n * tools, instructions, model, subagents, and stateSchema. Combines built-in tools with\n * provided tools, creates task tool using createTaskTool(), and returns createReactAgent\n * with proper configuration. Ensures exact parameter matching and behavior with Python version.\n */\n\n// import \"@langchain/anthropic/zod\";\nimport { createTaskTool } from \"./subAgent\";\nimport { writeTodos, readFile, writeFile, editFile, ls } from \"./tools\";\nimport type { CreateDeepAgentParams, PostModelHook } from \"./types\";\nimport type { StructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { DeepAgentState } from \"./state\";\nimport { getModelLattice } from \"../model_lattice/ModelLatticeManager\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { getCheckpointSaver } from \"@memory_lattice/MemoryLatticeManager\";\nimport { createInterruptHook } from \"./createInterruptHook\";\n/**\n * Base prompt that provides instructions about available tools\n * Ported from Python implementation to ensure consistent behavior\n */\nconst BASE_PROMPT = `You have access to a number of standard tools\n\n## \\`write_todos\\`\n\nYou 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.\nThese 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.\n\nIt 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.\n## \\`task\\`\n\n- When doing web search, prefer to use the \\`task\\` tool in order to reduce context usage.`;\n\n/**\n * Built-in tools that are always available in Deep Agents\n */\nconst BUILTIN_TOOLS: StructuredTool[] = [\n writeTodos,\n readFile,\n writeFile,\n editFile,\n ls,\n];\n\n/**\n * Create a Deep Agent with TypeScript types for all parameters.\n * Combines built-in tools with provided tools, creates task tool using createTaskTool(),\n * and returns createReactAgent with proper configuration.\n * Ensures exact parameter matching and behavior with Python version.\n */\nexport function createDeepAgent<\n StateSchema extends z.ZodObject<any, any, any, any, any>\n>(params: CreateDeepAgentParams<StateSchema> = {}) {\n const {\n tools = [],\n instructions,\n model = getModelLattice(\"default\")?.client,\n subagents = [],\n } = params;\n\n if (!model) {\n throw new Error(\"Model not found\");\n }\n\n const stateSchema = params.stateSchema\n ? DeepAgentState.extend(params.stateSchema.shape)\n : DeepAgentState;\n\n // Combine built-in tools with provided tools\n const allTools: StructuredTool[] = [...BUILTIN_TOOLS, ...tools];\n\n // Create task tool using createTaskTool() if subagents are provided\n\n if (subagents.length > 0) {\n // Create tools map for task tool creation\n const toolsMap: Record<string, StructuredTool> = {};\n for (const tool of allTools) {\n if (tool.name) {\n toolsMap[tool.name] = tool;\n }\n }\n\n const taskTool = createTaskTool({\n subagents,\n tools: toolsMap,\n model,\n stateSchema,\n });\n allTools.push(taskTool);\n }\n\n // Combine instructions with base prompt like Python implementation\n const finalInstructions = instructions\n ? instructions + BASE_PROMPT\n : BASE_PROMPT;\n\n // Return createReactAgent with proper configuration\n return createReactAgent<typeof stateSchema, Record<string, any>>({\n llm: model,\n tools: allTools,\n stateSchema: stateSchema,\n prompt: finalInstructions,\n checkpointer: getCheckpointSaver(\"default\"),\n });\n}\n","/**\n * Deep Agent Graph Builder\n *\n * 实现 Deep Agent 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { DynamicTool } from \"@langchain/core/tools\";\nimport { createDeepAgent } from \"../../deep_agent\";\nimport { AgentLattice, AgentBuildParams } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { getToolsFromConfig } from \"@axiom-lattice/protocols\";\n\nexport class DeepAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 构建Deep Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(\n agentLattice: AgentLattice,\n params: AgentBuildParams\n ): CompiledStateGraph<any, any, any, any, any> {\n const tools = params.tools\n .map((t) => {\n const toolClient = getToolClient(t.key);\n\n return toolClient;\n })\n .filter((tool) => tool !== undefined);\n\n return createDeepAgent({\n tools: tools,\n model: params.model,\n stateSchema: params.stateSchema,\n instructions: params.prompt,\n subagents: params.subAgents.map((sa) => sa.config),\n });\n }\n}\n","import {\n Annotation,\n BaseCheckpointSaver,\n END,\n GraphInterrupt,\n LangGraphRunnableConfig,\n START,\n StateGraph,\n messagesStateReducer,\n} from \"@langchain/langgraph\";\nimport {\n BaseMessage,\n HumanMessage,\n mergeMessageRuns,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod\";\nimport { ModelLattice } from \"./model_lattice/ModelLattice\";\nimport { Logger } from \"@logger/Logger\";\nimport { StateBaseType } from \"./types\";\nimport { returnToolResponse } from \"./util/returnToolResponse\";\nimport { returnAIResponse } from \"./util/returnAIResponse\";\nimport { getLastHumanMessageData } from \"./util/getLastHumanMessageData\";\nimport { tool } from \"@langchain/core/tools\";\nimport { MemoryManager } from \"./util/PGMemory\";\nimport { getModelLattice } from \"./model_lattice/ModelLatticeManager\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n/**\n * Plan-and-Execute Agent 状态定义\n */\nexport const PlanExecuteState = Annotation.Root({\n // 输入\n input: Annotation<string>({\n reducer: (x, y) => y ?? x ?? \"\",\n }),\n // 计划步骤列表\n plan: Annotation<string[]>({\n reducer: (x, y) => y ?? x ?? [],\n }),\n // 已执行的步骤 [步骤名称, 执行结果]\n pastSteps: Annotation<[string, string][]>({\n reducer: (x, y) => x.concat(y),\n default: () => [],\n }),\n // 最终响应\n response: Annotation<string | undefined>({\n reducer: (x, y) => y ?? x,\n }),\n // 错误信息\n error: Annotation<string | undefined>({\n reducer: (x, y) => y ?? x,\n }),\n // 继承基础状态\n \"x-tenant-id\": Annotation<number>(),\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n});\n\n/**\n * 计划工具的结构化输出模式\n */\nconst planSchema = z.object({\n steps: z.array(z.string()).describe(\"需要执行的步骤列表,应按照执行顺序排序\"),\n});\n\n/**\n * 响应工具的结构化输出模式\n */\nconst responseSchema = z.object({\n response: z\n .string()\n .describe(\"给用户的最终响应,如果不需要执行步骤,则返回这个字段\"),\n});\n\n/**\n * Plan-and-Execute Agent 配置接口\n */\nexport interface PlanExecuteAgentConfig {\n name: string;\n description: string;\n tools?: any[]; // 执行器可使用的工具\n checkpointer?: false | BaseCheckpointSaver<number>;\n llmManager?: ModelLattice;\n logger?: Logger;\n maxSteps?: number; // 最大步骤数限制\n prompt?: string;\n}\n\n/**\n * 创建 Plan-and-Execute Agent\n *\n * 这是一个规划-执行风格的代理,首先制定多步骤计划,然后逐一执行。\n * 在完成每个任务后,会重新评估计划并根据需要进行修改。\n *\n * 相比传统的ReAct风格代理的优势:\n * 1. 明确的长期规划能力\n * 2. 可以在执行步骤使用较小的模型,只在规划步骤使用大模型\n * 3. 更好的任务分解和执行追踪\n */\nexport function createPlanExecuteAgent(config: PlanExecuteAgentConfig) {\n const {\n name,\n description,\n tools: executorTools = [],\n checkpointer,\n llmManager,\n logger,\n maxSteps = 10,\n prompt,\n } = config;\n\n const agentLogger =\n logger || new Logger({ name: `PlanExecuteAgent:${name}` });\n const llm = llmManager || getModelLattice(\"default\")?.client;\n\n if (!llm) {\n throw new Error(\"LLM not found\");\n }\n\n agentLogger.info(`初始化Plan-Execute代理: ${name}`, {\n description,\n maxSteps,\n toolsCount: executorTools.length,\n });\n\n const agentExecutor = createReactAgent({\n tools: executorTools,\n llm: llm,\n });\n\n /**\n * 规划步骤:创建初始计划\n */\n async function planStep(\n state: typeof PlanExecuteState.State,\n config: LangGraphRunnableConfig\n ): Promise<Partial<typeof PlanExecuteState.State>> {\n const input =\n state.input || getLastHumanMessageData(state.messages)?.content;\n\n const plannerPrompt = `${\n prompt || \"\"\n }\\n针对给定的目标,制定一个简单的分步计划。\n这个计划应该包含独立的任务,如果正确执行将会得到正确的答案。不要添加多余的步骤。\n最后一步的结果应该是最终答案。确保每一步都有所需的所有信息 - 不要跳过步骤。\n\n可以使用的工具如下:\n${executorTools.map((tool) => tool.name).join(\"\\n\")}\n\n目标: ${input}`;\n\n try {\n const planResult = (await llm.invokeWithStructuredOutput(\n [new HumanMessage(plannerPrompt)],\n planSchema\n )) as { steps: string[] };\n\n const { messages } = await returnToolResponse(config, {\n title: \"我的计划\",\n content: planResult.steps.map((step: string) => step).join(\"\\n\\n\"),\n status: \"success\",\n });\n\n agentLogger.info(\"计划制定完成\", { plan: planResult.steps });\n\n return {\n input: input as string,\n plan: planResult.steps,\n error: undefined,\n messages,\n };\n } catch (error) {\n const errorMsg = `计划制定失败: ${\n error instanceof Error ? error.message : \"未知错误\"\n }`;\n agentLogger.error(errorMsg, { error });\n return {\n error: errorMsg,\n };\n }\n }\n\n /**\n * 执行步骤:执行计划中的第一个任务\n */\n async function executeStep(\n state: typeof PlanExecuteState.State,\n config: LangGraphRunnableConfig\n ): Promise<Partial<typeof PlanExecuteState.State>> {\n if (!state.plan || state.plan.length === 0) {\n agentLogger.warn(\"没有可执行的任务\");\n return { error: \"没有可执行的任务\" };\n }\n\n const currentTask = state.plan[0];\n agentLogger.info(\"开始执行任务\", { task: currentTask });\n\n try {\n // 这里可以集成真实的工具执行器\n // 目前使用LLM来模拟执行\n const executorPrompt = `执行以下任务并提供结果:\n\n任务: ${currentTask}\n\n上下文信息:\n- 原始目标: ${state.input}\n- 已完成的步骤: ${state.pastSteps\n .map(([step, result]) => `${step}: ${result}`)\n .join(\"\\n\")}\n\n请提供执行此任务的详细结果。`;\n\n const executionResult = await agentExecutor.invoke({\n messages: [new HumanMessage(executorPrompt)],\n });\n\n const resultContent =\n executionResult.messages[executionResult.messages.length - 1].content;\n\n // 生成工具响应消息\n // const { messages } = await returnToolResponse(config, {\n // title: `执行任务: ${currentTask}`,\n // content: resultContent as string,\n // status: \"success\",\n // });\n\n return {\n pastSteps: [[currentTask, resultContent]] as [string, string][],\n plan: state.plan.slice(1), // 移除已执行的任务\n //messages,\n error: undefined,\n };\n } catch (error) {\n if (error instanceof GraphInterrupt) {\n throw error;\n }\n const errorMsg = `任务执行失败: ${\n error instanceof Error ? error.message : \"未知错误\"\n }`;\n agentLogger.error(errorMsg, { task: currentTask, error });\n\n // const { messages } = await returnToolResponse(config, {\n // title: `执行任务失败: ${currentTask}`,\n // content: errorMsg,\n // status: \"error\",\n // });\n\n return {\n error: errorMsg,\n //messages,\n };\n }\n }\n\n const responseTool = tool(\n ({ response }: { response: string }) => {\n return response;\n },\n {\n name: \"response\",\n description: \"Respond to the user.\",\n schema: responseSchema,\n returnDirect: true,\n }\n );\n\n const planTool = tool(\n ({ steps }: { steps: string[] }) => {\n return steps.join(\"\\n\\n\");\n },\n {\n name: \"plan\",\n description: \"This tool is used to plan the steps to follow.\",\n schema: planSchema,\n returnDirect: true,\n }\n );\n\n const replanAgent = createReactAgent({\n tools: [responseTool, planTool],\n llm: llm,\n });\n /**\n * 重新规划步骤:根据执行结果调整计划\n */\n async function replanStep(\n state: typeof PlanExecuteState.State,\n config: LangGraphRunnableConfig\n ): Promise<Partial<typeof PlanExecuteState.State>> {\n agentLogger.info(\"开始重新规划\");\n\n const replannerPrompt = `${\n prompt || \"\"\n }\\n针对给定的目标,根据已执行的步骤来更新计划。\n这个计划应该包含独立的任务,如果正确执行将会得到正确的答案。不要添加多余的步骤。\n最后一步的结果应该是最终答案。确保每一步都有所需的所有信息 - 不要跳过步骤。\n\n你的目标是:\n${state.input}\n\n你的原始计划是:\n${state.plan.join(\"\\n\")}\n\n你目前已经完成了以下步骤:\n${state.pastSteps.map(([step, result]) => `${step}: ${result}`).join(\"\\n\")}\n\nUpdate 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.\nOtherwise, fill out the plan.\nOnly add steps to the plan that still NEED to be done. Do not return previously done steps as part of the plan.`;\n\n try {\n // 首先尝试获取最终响应\n const responseResult = await replanAgent.invoke({\n messages: [new HumanMessage(replannerPrompt)],\n });\n\n const toolCall =\n responseResult.messages[responseResult.messages.length - 1];\n\n if (toolCall?.name == \"response\") {\n agentLogger.info(\"任务完成,提供最终响应\");\n\n const { messages } = await returnAIResponse(\n config,\n toolCall.content as string\n );\n\n return {\n response: toolCall.content as string,\n messages,\n error: undefined,\n };\n } else if (toolCall?.name == \"plan\") {\n let messages: any[] = [];\n if (toolCall.content?.length > 0) {\n messages = await returnToolResponse(config, {\n title: \"新的计划\",\n content: toolCall.content as string,\n status: \"success\",\n }).messages;\n }\n agentLogger.info(\"计划更新完成\", { newPlan: toolCall.content });\n return {\n messages,\n plan: (toolCall.content as string).split(\"\\n\\n\"),\n error: undefined,\n };\n } else {\n return {\n error: \"重新规划失败\",\n };\n }\n } catch (error) {\n if (error instanceof GraphInterrupt) {\n throw error;\n }\n const errorMsg = `重新规划失败: ${\n error instanceof Error ? error.message : \"未知错误\"\n }`;\n agentLogger.error(errorMsg, { error });\n return {\n error: errorMsg,\n };\n }\n }\n\n /**\n * 判断是否应该结束执行\n */\n function shouldEnd(state: typeof PlanExecuteState.State): \"end\" | \"continue\" {\n if (state.error) {\n agentLogger.warn(\"因错误结束执行\", { error: state.error });\n return \"end\";\n }\n\n if (state.response) {\n agentLogger.info(\"任务完成,结束执行\");\n return \"end\";\n }\n\n if (state.pastSteps.length >= maxSteps) {\n agentLogger.warn(\"达到最大步骤数限制,结束执行\", {\n maxSteps,\n currentSteps: state.pastSteps.length,\n });\n return \"end\";\n }\n\n if (!state.plan || state.plan.length === 0) {\n agentLogger.info(\"计划为空,结束执行\");\n return \"end\";\n }\n\n return \"continue\";\n }\n\n // 构建状态图\n const workflow = new StateGraph(PlanExecuteState)\n .addNode(\"planner\", planStep)\n .addNode(\"executor\", executeStep)\n .addNode(\"replanner\", replanStep)\n .addEdge(START, \"planner\")\n .addEdge(\"planner\", \"executor\")\n .addEdge(\"executor\", \"replanner\")\n .addConditionalEdges(\"replanner\", shouldEnd, {\n end: END,\n continue: \"executor\",\n });\n\n // 编译图\n //const memory = MemoryManager.getInstance();\n const compiledGraph = workflow.compile({\n checkpointer: checkpointer || MemoryManager.getInstance(),\n name: `PlanExecuteAgent:${name}`,\n });\n\n agentLogger.info(`Plan-Execute代理编译完成: ${name}`);\n\n return {\n /**\n * 执行代理\n */\n invoke: async (\n input: { input: string; \"x-tenant-id\": number },\n config?: LangGraphRunnableConfig\n ) => {\n agentLogger.info(`开始执行Plan-Execute代理: ${name}`, {\n input: input.input,\n });\n\n try {\n const result = await compiledGraph.invoke(input, config);\n agentLogger.info(`代理执行完成: ${name}`);\n return result;\n } catch (error) {\n agentLogger.error(\n `代理执行失败: ${name}`,\n error instanceof Error ? error : { error }\n );\n throw error;\n }\n },\n\n /**\n * 流式执行代理\n */\n stream: async (\n input: { input: string; \"x-tenant-id\": number },\n config?: LangGraphRunnableConfig\n ) => {\n agentLogger.info(`开始流式执行Plan-Execute代理: ${name}`, {\n input: input.input,\n });\n return compiledGraph.stream(input, config);\n },\n\n /**\n * 获取代理信息\n */\n getInfo: () => ({\n name,\n description,\n type: \"PlanExecuteAgent\",\n toolsCount: executorTools.length,\n maxSteps,\n }),\n\n /**\n * 获取编译后的图\n */\n getCompiledGraph: () => compiledGraph,\n };\n}\n","import pino from \"pino\";\nimport \"pino-pretty\";\nimport \"pino-roll\";\nimport { AsyncLocalStorage } from \"async_hooks\";\n\nexport interface LoggerContext {\n \"x-user-id\"?: string;\n \"x-tenant-id\"?: string;\n \"x-request-id\"?: string;\n \"x-task-id\"?: string;\n \"x-thread-id\"?: string;\n}\n\nexport interface LoggerOptions {\n name?: string;\n serviceName?: string;\n context?: LoggerContext;\n}\n\n/**\n * 单例的Pino日志工厂类,管理底层pino实例\n */\nclass PinoLoggerFactory {\n private static instance: PinoLoggerFactory;\n private pinoLogger: pino.Logger;\n\n private constructor() {\n const isProd = process.env.NODE_ENV === \"production\";\n\n const loggerConfig: pino.LoggerOptions = {\n // 自定义时间戳格式\n timestamp: () => `,\"@timestamp\":\"${new Date().toISOString()}\"`,\n\n // 关闭默认的时间戳键\n base: {\n \"@version\": \"1\",\n app_name: \"lattice\",\n service_name: \"lattice/graph-server\",\n thread_name: \"main\",\n logger_name: \"lattice-graph-logger\",\n },\n\n formatters: {\n level: (label, number) => {\n return {\n level: label.toUpperCase(),\n level_value: number * 1000,\n };\n },\n },\n };\n\n // 生产环境使用文件日志\n if (isProd) {\n try {\n this.pinoLogger = pino(\n loggerConfig,\n pino.transport({\n target: \"pino-roll\",\n options: {\n file: \"./logs/fin_ai_graph_server\",\n frequency: \"daily\",\n mkdir: true,\n },\n })\n );\n } catch (error) {\n console.error(\n \"无法初始化 pino-roll 日志记录器,回退到控制台日志\",\n error\n );\n // 回退到开发环境的配置\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n } else {\n // 开发环境使用格式化输出\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n }\n\n public static getInstance(): PinoLoggerFactory {\n if (!PinoLoggerFactory.instance) {\n PinoLoggerFactory.instance = new PinoLoggerFactory();\n }\n return PinoLoggerFactory.instance;\n }\n\n public getPinoLogger(): pino.Logger {\n return this.pinoLogger;\n }\n}\n\n/**\n * Logger类,可以创建多个实例,每个实例有自己的上下文\n */\nexport class Logger {\n private context: LoggerContext;\n private name: string;\n private serviceName: string;\n\n constructor(options?: LoggerOptions) {\n this.context = options?.context || {};\n this.name = options?.name || \"lattice-graph-logger\";\n this.serviceName = options?.serviceName || \"lattice/graph-server\";\n }\n\n /**\n * 获取合并了上下文的日志对象\n * @param additionalContext 额外的上下文数据\n * @returns 带有上下文的pino日志对象\n */\n private getContextualLogger(additionalContext?: object): pino.Logger {\n const pinoLogger = PinoLoggerFactory.getInstance().getPinoLogger();\n\n // 合并Logger实例的上下文和额外上下文\n const contextObj = {\n \"x-user-id\": this.context[\"x-user-id\"] || \"\",\n \"x-tenant-id\": this.context[\"x-tenant-id\"] || \"\",\n \"x-request-id\": this.context[\"x-request-id\"] || \"\",\n \"x-task-id\": this.context[\"x-task-id\"] || \"\",\n \"x-thread-id\": this.context[\"x-thread-id\"] || \"\",\n service_name: this.serviceName,\n logger_name: this.name,\n ...additionalContext,\n };\n\n // 创建带有上下文的子日志记录器\n return pinoLogger.child(contextObj);\n }\n\n info(msg: string, obj?: object): void {\n this.getContextualLogger(obj).info(msg);\n }\n\n error(msg: string, obj?: object | Error): void {\n this.getContextualLogger(obj).error(msg);\n }\n\n warn(msg: string, obj?: object): void {\n this.getContextualLogger(obj).warn(msg);\n }\n\n debug(msg: string, obj?: object): void {\n this.getContextualLogger(obj).debug(msg);\n }\n\n /**\n * 更新Logger实例的上下文\n */\n updateContext(context: Partial<LoggerContext>): void {\n this.context = {\n ...this.context,\n ...context,\n };\n }\n\n /**\n * 创建一个新的Logger实例,继承当前Logger的上下文\n */\n child(options: Partial<LoggerOptions>): Logger {\n return new Logger({\n name: options.name || this.name,\n serviceName: options.serviceName || this.serviceName,\n context: {\n ...this.context,\n ...options.context,\n },\n });\n }\n}\n","import { ToolMessage } from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { v4 } from \"uuid\";\nimport { genUIMarkdown } from \"./genUIMarkdown\";\n\nexport const returnToolResponse = (\n config: LangGraphRunnableConfig,\n think: {\n think_id?: string; // 思考的id,为了解决思考过程分组的问题\n title?: string;\n content: string;\n status?: \"success\" | \"error\";\n type?: string;\n data?: Record<string, any>;\n }\n) => {\n const { think_id = v4(), content, title, status, type, data } = think;\n const contents = type\n ? [title, content, genUIMarkdown(type, data)]\n : [title, content];\n const message = {\n messages: [\n new ToolMessage({\n content: contents.filter((item) => item).join(\"\\n\\n\"),\n tool_call_id: config.configurable?.run_id + \"_tool_\" + think_id,\n status: status || \"success\",\n }),\n ],\n };\n\n return message;\n};\n","import { AIMessage } from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { v4 } from \"uuid\";\nimport { genUIMarkdown } from \"./genUIMarkdown\";\n\nexport const returnAIResponse = (\n config: LangGraphRunnableConfig,\n content: string,\n type?: string,\n data?: Record<string, any>\n) => {\n const contents = type\n ? [content, genUIMarkdown(type, data)].join(\"\\n\")\n : content;\n const message = {\n messages: [\n new AIMessage({\n content: contents,\n }),\n // {\n // id: v4(),\n // role: \"ai\",\n // content: contents,\n // type: \"message\",\n // }, // 旧的message\n ],\n };\n // config.writer?.(message);\n return message;\n};\n","import {\n BaseMessage,\n HumanMessage,\n isHumanMessage,\n} from \"@langchain/core/messages\";\nexport type UserFile = {\n id: number;\n name: string;\n type?: string;\n path?: string;\n};\nexport type UserFileZip = {\n id: number;\n name: string;\n files: UserFile[];\n type?: \"application/zip\" | \"application/rar\";\n totalFiles?: number;\n processedFiles?: number;\n skippedFiles?: number;\n};\n\nexport const isCompressedFile = (fileType: string): boolean => {\n return fileType === \"application/zip\" || fileType === \"application/rar\";\n};\n\nexport const getLastHumanMessageData = (messages: BaseMessage[]) => {\n // 从最后一条消息开始向前查找第一个人类消息\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isHumanMessage(message)) {\n const files = message?.additional_kwargs?.files as UserFile[];\n return {\n files,\n content: message?.content,\n };\n }\n }\n\n // 如果没有找到任何人类消息,返回 null\n return null;\n};\n","import { MemorySaver } from \"@langchain/langgraph\";\nimport { PostgresSaver } from \"@langchain/langgraph-checkpoint-postgres\";\nimport dotenv from \"dotenv\";\n\nconst globalMemory = PostgresSaver.fromConnString(process.env.DATABASE_URL!);\n\nconst memory = new MemorySaver();\n// 创建一个管理器来访问这个实例\nexport class MemoryManager {\n private static instance: MemorySaver = memory;\n\n static getInstance(): MemorySaver {\n return MemoryManager.instance;\n }\n}\n//MemoryManager.getInstance().setup();\n","/**\n * Plan Execute Agent Graph Builder\n *\n * 实现 Plan Execute 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { DynamicTool } from \"@langchain/core/tools\";\nimport { AgentLattice, AgentBuildParams } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { createPlanExecuteAgent } from \"@createPlanExecuteAgent\";\n\nexport class PlanExecuteAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 构建Plan Execute Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(\n agentLattice: AgentLattice,\n params: AgentBuildParams\n ): CompiledStateGraph<any, any, any, any, any> {\n // 创建符合 DynamicTool 接口的工具对象\n const tools = params.tools\n .map((t) => {\n // 使用 DynamicTool 构造工具对象\n const tool = getToolClient(t.key);\n return tool;\n })\n .filter((tool) => tool !== undefined);\n\n // 由于createPlanExecuteAgent的返回类型与CompiledStateGraph不兼容\n // 这里我们使用createAgentExecutor作为替代方案\n const agent = createPlanExecuteAgent({\n llmManager: params.model,\n tools: tools,\n prompt: params.prompt,\n name: agentLattice.config.name,\n description: agentLattice.config.description,\n });\n return agent.getCompiledGraph();\n }\n}\n","/**\n * Agent Graph Builder Factory\n *\n * 工厂类,根据Agent类型创建对应的Builder\n */\n\nimport { AgentType } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { ReActAgentGraphBuilder } from \"./ReActAgentGraphBuilder\";\nimport { DeepAgentGraphBuilder } from \"./DeepAgentGraphBuilder\";\nimport { PlanExecuteAgentGraphBuilder } from \"./PlanExecuteAgentGraphBuilder\";\n\nexport class AgentGraphBuilderFactory {\n // 单例模式\n private static instance: AgentGraphBuilderFactory;\n\n // Builder缓存\n private builders: Map<AgentType, AgentGraphBuilder>;\n\n private constructor() {\n this.builders = new Map();\n this.registerDefaultBuilders();\n }\n\n /**\n * 获取单例实例\n */\n public static getInstance(): AgentGraphBuilderFactory {\n if (!AgentGraphBuilderFactory.instance) {\n AgentGraphBuilderFactory.instance = new AgentGraphBuilderFactory();\n }\n return AgentGraphBuilderFactory.instance;\n }\n\n /**\n * 注册默认的Builder\n */\n private registerDefaultBuilders(): void {\n this.builders.set(AgentType.REACT, new ReActAgentGraphBuilder());\n this.builders.set(AgentType.DEEP_AGENT, new DeepAgentGraphBuilder());\n this.builders.set(\n AgentType.PLAN_EXECUTE,\n new PlanExecuteAgentGraphBuilder()\n );\n }\n\n /**\n * 注册自定义Builder\n *\n * @param type Agent类型\n * @param builder Builder实例\n */\n public registerBuilder(type: AgentType, builder: AgentGraphBuilder): void {\n this.builders.set(type, builder);\n }\n\n /**\n * 获取Builder\n *\n * @param type Agent类型\n * @returns 返回对应的Builder\n */\n public getBuilder(type: AgentType): AgentGraphBuilder {\n const builder = this.builders.get(type);\n if (!builder) {\n throw new Error(`不支持的Agent类型: ${type}`);\n }\n return builder;\n }\n}\n","/**\n * Agent parameters builder\n *\n * responsible for preparing the parameters required for building the Agent\n */\n\nimport { toolLatticeManager } from \"../../tool_lattice/ToolLatticeManager\";\nimport { modelLatticeManager } from \"../../model_lattice/ModelLatticeManager\";\nimport { AgentLattice, AgentBuildParams, GraphBuildOptions } from \"../types\";\nimport {\n getToolsFromConfig,\n getSubAgentsFromConfig,\n isDeepAgentConfig,\n AgentConfig,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * Get Agent Lattice function type\n */\nexport type GetAgentLatticeFunction = (key: string) => AgentLattice | undefined;\n\n/**\n * Agent parameters builder\n */\nexport class AgentParamsBuilder {\n private getAgentLatticeFunc: GetAgentLatticeFunction;\n\n /**\n * constructor\n *\n * @param getAgentLatticeFunc get Agent Lattice function\n */\n constructor(getAgentLatticeFunc: GetAgentLatticeFunction) {\n this.getAgentLatticeFunc = getAgentLatticeFunc;\n }\n\n /**\n * build Agent parameters\n *\n * @param agentLattice Agent Lattice object\n * @param options build options\n * @returns Agent build parameters\n */\n public buildParams(\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n ): AgentBuildParams {\n // get tools (use type-safe helper)\n const toolKeys =\n options?.overrideTools || getToolsFromConfig(agentLattice.config);\n const tools = toolKeys.map((toolKey: string) => {\n const toolLattice = toolLatticeManager.getToolLattice(toolKey);\n if (!toolLattice) {\n throw new Error(`Tool \"${toolKey}\" does not exist`);\n }\n return {\n key: toolKey,\n definition: toolLattice.config,\n executor: toolLattice.client,\n };\n });\n\n // get model\n const modelKey = options?.overrideModel || agentLattice.config.modelKey;\n const model = modelKey\n ? modelLatticeManager.getModelLattice(modelKey).client\n : modelLatticeManager.getModelLattice(\"default\").client;\n if (!model) {\n throw new Error(`Model \"${modelKey}\" does not exist`);\n }\n\n // get subAgents (use type-safe helper - only DeepAgentConfig has subAgents)\n const subAgentKeys = getSubAgentsFromConfig(agentLattice.config);\n const subAgents = subAgentKeys.map((agentKey: string) => {\n const subAgentLattice = this.getAgentLatticeFunc(agentKey);\n if (!subAgentLattice) {\n throw new Error(`SubAgent \"${agentKey}\" does not exist`);\n }\n return {\n key: agentKey,\n config: subAgentLattice.config,\n client: subAgentLattice.client,\n };\n });\n let internalSubAgents: any[] = [];\n if (isDeepAgentConfig(agentLattice.config)) {\n internalSubAgents =\n agentLattice.config.internalSubAgents?.map((i) => ({\n key: i.key,\n config: i,\n })) || [];\n }\n\n return {\n tools,\n model,\n subAgents: [...subAgents, ...internalSubAgents],\n prompt: agentLattice.config.prompt,\n stateSchema: agentLattice.config.schema,\n };\n }\n}\n","import { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n AgentConfig,\n AgentClient,\n AgentLattice,\n GraphBuildOptions,\n AgentBuildParams,\n} from \"./types\";\nimport { AgentGraphBuilderFactory } from \"./builders/AgentGraphBuilderFactory\";\nimport { AgentParamsBuilder } from \"./builders/AgentParamsBuilder\";\nimport \"../tool_lattice\";\n// 类型定义已移至 ./types.ts\n\n/**\n * AgentLatticeManager - 单例Agent Lattice管理器\n * 负责注册、管理各种Agent Lattice\n */\nexport class AgentLatticeManager extends BaseLatticeManager<AgentLattice> {\n private static _instance: AgentLatticeManager;\n\n /**\n * 获取AgentLatticeManager单例实例\n */\n public static getInstance(): AgentLatticeManager {\n if (!AgentLatticeManager._instance) {\n AgentLatticeManager._instance = new AgentLatticeManager();\n }\n return AgentLatticeManager._instance;\n }\n\n /**\n * 获取Lattice类型前缀\n */\n protected getLatticeType(): string {\n return \"agents\";\n }\n\n /**\n * 注册Agent Lattice\n * @param config Agent配置\n */\n public registerLattice(config: AgentConfig): void {\n // 创建Agent Lattice对象\n const agentLattice: AgentLattice = {\n config,\n client: undefined, // 客户端将在需要时由initializeClient创建\n };\n\n // 调用基类的register方法\n this.register(config.key, agentLattice);\n }\n\n /**\n * 获取AgentLattice\n * @param key Lattice键名\n */\n public getAgentLattice(key: string): AgentLattice | undefined {\n return this.get(key);\n }\n\n /**\n * 获取所有Lattice\n */\n public getAllLattices(): AgentLattice[] {\n return this.getAll();\n }\n\n /**\n * 检查Lattice是否存在\n * @param key Lattice键名\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * 移除Lattice\n * @param key Lattice键名\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * 获取Agent配置\n * @param key Lattice键名\n */\n public getAgentConfig(key: string): AgentConfig | undefined {\n return this.getAgentLattice(key)?.config;\n }\n\n /**\n * 获取所有Agent配置\n */\n public getAllAgentConfigs(): AgentConfig[] {\n return this.getAllLattices().map((lattice) => lattice.config);\n }\n\n /**\n * 验证Agent输入参数\n * @param key Lattice键名\n * @param input 输入参数\n */\n public validateAgentInput(key: string, input: any): boolean {\n const agentLattice = this.getAgentLattice(key);\n if (!agentLattice) {\n return false;\n }\n\n try {\n if (agentLattice.config.schema) {\n agentLattice.config.schema.parse(input);\n }\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * 构建Agent参数\n *\n * @param agentLattice Agent Lattice对象\n * @param options 构建选项\n * @returns 返回Agent构建参数\n */\n private buildAgentParams(\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n ): AgentBuildParams {\n // 创建参数构建器\n const paramsBuilder = new AgentParamsBuilder((key: string) => {\n this.initializeClient(key);\n return this.getAgentLattice(key);\n });\n\n // 构建参数\n return paramsBuilder.buildParams(agentLattice, options);\n }\n\n /**\n * Create an AgentClient from AgentLattice config\n *\n * @param agentLattice Agent Lattice object\n * @param options Build options\n * @returns AgentClient instance\n */\n public createAgentClientFromConfig(\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n ): AgentClient {\n // Get factory instance\n const factory = AgentGraphBuilderFactory.getInstance();\n\n // Get the builder for the agent type\n const builder = factory.getBuilder(agentLattice.config.type);\n\n // Build params\n const params = this.buildAgentParams(agentLattice, options);\n\n // Use builder to build the graph\n return builder.build(agentLattice, params);\n }\n\n /**\n * 初始化Agent客户端\n *\n * 使用AgentGraphBuilderFactory构建Graph并设置为客户端\n *\n * @param key Lattice键名\n * @param options 构建选项\n * @returns 返回CompiledGraph对象\n */\n public initializeClient(\n key: string,\n options?: GraphBuildOptions\n ): AgentClient {\n const agentLattice = this.getAgentLattice(key);\n if (!agentLattice) {\n throw new Error(`Agent Lattice \"${key}\" 不存在`);\n }\n\n // If client already exists, return it directly\n if (agentLattice.client) {\n return agentLattice.client;\n }\n\n // Create agent client from config\n const graph = this.createAgentClientFromConfig(agentLattice, options);\n\n // Set as client\n agentLattice.client = graph;\n\n return graph;\n }\n}\n\n// 导出单例实例\nexport const agentLatticeManager = AgentLatticeManager.getInstance();\n\n// 导出便捷方法\nexport const registerAgentLattice = (config: AgentConfig) => {\n agentLatticeManager.registerLattice(config);\n};\n\nexport const registerAgentLattices = (configs: AgentConfig[]) => {\n configs.forEach((config) => {\n agentLatticeManager.registerLattice(config);\n });\n};\n\nexport const getAgentLattice = (key: string) =>\n agentLatticeManager.getAgentLattice(key);\n\nexport const getAgentConfig = (key: string) =>\n agentLatticeManager.getAgentConfig(key);\n\nexport const getAllAgentConfigs = () =>\n agentLatticeManager.getAllAgentConfigs();\n\nexport const validateAgentInput = (key: string, input: any) =>\n agentLatticeManager.validateAgentInput(key, input);\n\n/**\n * 获取或初始化Agent客户端\n *\n * @param key Agent Lattice键名\n * @param options 构建选项\n * @returns 返回CompiledGraph对象\n */\nexport const getAgentClient = (key: string, options?: GraphBuildOptions) =>\n agentLatticeManager.initializeClient(key, options);\n\nexport const createAgentClientFromAgentLattice = (\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n) => agentLatticeManager.createAgentClientFromConfig(agentLattice, options);\n","/**\n * ChunkBuffer Abstract Base Class\n *\n * Defines the interface for chunk buffer implementations\n */\n\nimport { MessageChunk } from \"@axiom-lattice/protocols\";\nimport { ThreadStatus, ThreadBuffer } from \"./types\";\n\nexport abstract class ChunkBuffer {\n /**\n * Add a chunk to a thread (creates thread if not exists)\n * Chunks are appended in order\n */\n abstract addChunk(threadId: string, content: MessageChunk): Promise<void>;\n\n /**\n * Mark thread as completed (explicit call)\n */\n abstract completeThread(threadId: string): Promise<void>;\n\n /**\n * Mark thread as aborted (explicit call)\n */\n abstract abortThread(threadId: string): Promise<void>;\n\n /**\n * Check if thread is still active\n */\n abstract isThreadActive(threadId: string): Promise<boolean>;\n\n /**\n * Get thread status (returns undefined if thread doesn't exist)\n */\n abstract getThreadStatus(threadId: string): Promise<ThreadStatus | undefined>;\n\n /**\n * Get thread buffer info including metadata\n */\n abstract getThreadBuffer(threadId: string): Promise<ThreadBuffer | undefined>;\n\n /**\n * Clear specific thread buffer\n */\n abstract clearThread(threadId: string): Promise<void>;\n\n /**\n * Get all active thread IDs\n */\n abstract getActiveThreads(): Promise<string[]>;\n\n /**\n * Get all thread IDs (regardless of status)\n */\n abstract getAllThreads(): Promise<string[]>;\n\n /**\n * Manually trigger cleanup of expired threads\n * Returns number of threads cleaned up\n */\n abstract cleanupExpiredThreads(): Promise<number>;\n\n /**\n * Extend thread TTL (reset expiration time)\n */\n abstract extendThreadTTL(\n threadId: string,\n additionalMs?: number\n ): Promise<void>;\n\n /**\n * Check if a thread exists (valid or expired)\n */\n abstract hasThread(threadId: string): Promise<boolean>;\n\n abstract getNewChunksSinceContentIterator(\n threadId: string,\n messageId: string,\n knownContent: string\n ): AsyncIterable<MessageChunk>;\n}\n","/**\n * ChunkBuffer Types\n *\n * Defines types for managing streaming chunks organized by thread\n */\n\nimport { MessageChunk } from \"@axiom-lattice/protocols\";\nimport { ReplaySubject } from \"rxjs\";\n\n/**\n * Represents a single chunk of data\n * Chunks are identified by their position in the sequence (no unique ID)\n */\nexport interface Chunk {\n messageId: string; // Message this chunk belongs to\n content: MessageChunk; // Chunk content\n}\n\n/**\n * Thread status - requires explicit state transitions\n */\nexport enum ThreadStatus {\n ACTIVE = \"active\",\n COMPLETED = \"completed\",\n ABORTED = \"aborted\",\n}\n\n/**\n * Thread buffer configuration\n */\nexport interface ThreadBufferConfig {\n ttl?: number; // Time-to-live in milliseconds (default: 1 hour)\n cleanupInterval?: number; // Optional: periodic cleanup interval in ms\n}\n\n/**\n * Thread buffer state\n */\nexport interface ThreadBuffer {\n threadId: string;\n chunks$: ReplaySubject<MessageChunk>; // Ordered list of chunks\n status: ThreadStatus;\n createdAt: number;\n updatedAt: number;\n expiresAt: number; // TTL expiration timestamp\n}\n\n/**\n * Buffer statistics\n */\nexport interface BufferStats {\n totalThreads: number;\n activeThreads: number;\n completedThreads: number;\n abortedThreads: number;\n config: Required<ThreadBufferConfig>;\n}\n","/**\n * InMemoryChunkBuffer\n *\n * In-memory implementation of ChunkBuffer with hybrid cleanup strategy:\n * - Lazy cleanup: expired threads are removed on access\n * - Optional periodic cleanup: background timer to clean expired threads\n */\n\nimport { MessageChunk } from \"@axiom-lattice/protocols\";\nimport { EventEmitter, once } from \"events\";\nimport { ChunkBuffer } from \"./ChunkBuffer\";\nimport {\n BufferStats,\n ThreadBuffer,\n ThreadBufferConfig,\n ThreadStatus,\n} from \"./types\";\nimport { ReplaySubject, Observable, Subscription } from \"rxjs\";\n\nexport class InMemoryChunkBuffer extends ChunkBuffer {\n private buffers: Map<string, ThreadBuffer>;\n private config: Required<ThreadBufferConfig> & { maxChunks?: number };\n private cleanupTimer?: NodeJS.Timeout;\n\n constructor(config?: ThreadBufferConfig & { maxChunks?: number }) {\n super();\n this.buffers = new Map();\n\n // Default: 1 hour TTL, no periodic cleanup (lazy only)\n this.config = {\n ttl: config?.ttl ?? 60 * 60 * 1000,\n cleanupInterval: config?.cleanupInterval ?? 0,\n maxChunks: config?.maxChunks ?? 1000, // Default max chunks per thread\n };\n\n // Start periodic cleanup only if cleanupInterval is specified\n if (this.config.cleanupInterval > 0) {\n this.startCleanupTimer();\n }\n }\n\n /**\n * Start automatic periodic cleanup timer\n */\n private startCleanupTimer(): void {\n if (this.config.cleanupInterval <= 0) return;\n\n this.cleanupTimer = setInterval(() => {\n this.cleanupExpiredThreads().catch(console.error);\n }, this.config.cleanupInterval);\n\n // Don't prevent process from exiting\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref();\n }\n }\n\n /**\n * Stop cleanup timer (for cleanup/shutdown)\n */\n public stopCleanupTimer(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n }\n\n /**\n * Check if a buffer is expired (lazy cleanup helper)\n */\n private isExpired(buffer: ThreadBuffer): boolean {\n return buffer.expiresAt <= Date.now();\n }\n\n /**\n * Get buffer if valid, perform lazy cleanup if expired\n */\n private getBufferIfValid(threadId: string): ThreadBuffer | undefined {\n const buffer = this.buffers.get(threadId);\n\n if (buffer && this.isExpired(buffer)) {\n // Lazy cleanup: remove expired buffer on access\n this.buffers.delete(threadId);\n return undefined;\n }\n\n return buffer;\n }\n\n /**\n * Create or get thread buffer\n */\n private getOrCreateBuffer(threadId: string): ThreadBuffer {\n // First check with lazy cleanup\n let buffer = this.getBufferIfValid(threadId);\n 4;\n if (!buffer) {\n const now = Date.now();\n buffer = {\n threadId,\n chunks$: new ReplaySubject<MessageChunk>(\n this.config.maxChunks ?? 10000\n ),\n status: ThreadStatus.ACTIVE,\n createdAt: now,\n updatedAt: now,\n expiresAt: now + this.config.ttl,\n };\n this.buffers.set(threadId, buffer);\n }\n\n if (buffer.status !== ThreadStatus.ACTIVE) {\n buffer.status = ThreadStatus.ACTIVE;\n buffer.chunks$ = new ReplaySubject<MessageChunk>(\n this.config.maxChunks ?? 10000\n );\n buffer.updatedAt = Date.now();\n buffer.expiresAt = Date.now() + this.config.ttl;\n }\n\n return buffer;\n }\n\n async addChunk(threadId: string, content: MessageChunk): Promise<void> {\n const buffer = this.getOrCreateBuffer(threadId);\n\n const chunk: MessageChunk = content;\n\n buffer.chunks$.next(chunk);\n buffer.updatedAt = Date.now();\n\n // Auto-extend TTL on activity\n buffer.expiresAt = Date.now() + this.config.ttl;\n buffer.status = ThreadStatus.ACTIVE;\n\n // Notify listeners\n }\n\n async completeThread(threadId: string): Promise<void> {\n const buffer = this.getBufferIfValid(threadId);\n if (buffer) {\n buffer.status = ThreadStatus.COMPLETED;\n buffer.updatedAt = Date.now();\n buffer.chunks$.complete();\n }\n }\n\n async abortThread(threadId: string): Promise<void> {\n const buffer = this.getBufferIfValid(threadId);\n if (buffer) {\n buffer.status = ThreadStatus.ABORTED;\n buffer.updatedAt = Date.now();\n buffer.chunks$.error(new Error(\"Thread aborted\"));\n }\n }\n\n async isThreadActive(threadId: string): Promise<boolean> {\n const buffer = this.getBufferIfValid(threadId);\n return buffer?.status === ThreadStatus.ACTIVE;\n }\n\n async getThreadStatus(threadId: string): Promise<ThreadStatus | undefined> {\n return this.getBufferIfValid(threadId)?.status;\n }\n\n async getThreadBuffer(threadId: string): Promise<ThreadBuffer | undefined> {\n const buffer = this.getBufferIfValid(threadId);\n if (!buffer) return undefined;\n return buffer;\n }\n\n async clearThread(threadId: string): Promise<void> {\n this.buffers.delete(threadId);\n }\n\n async getActiveThreads(): Promise<string[]> {\n const activeThreads: string[] = [];\n\n for (const [threadId, buffer] of this.buffers.entries()) {\n // Apply lazy cleanup\n if (this.isExpired(buffer)) {\n this.buffers.delete(threadId);\n continue;\n }\n\n if (buffer.status === ThreadStatus.ACTIVE) {\n activeThreads.push(threadId);\n }\n }\n\n return activeThreads;\n }\n\n async getAllThreads(): Promise<string[]> {\n const validThreads: string[] = [];\n\n for (const [threadId, buffer] of this.buffers.entries()) {\n // Apply lazy cleanup\n if (this.isExpired(buffer)) {\n this.buffers.delete(threadId);\n } else {\n validThreads.push(threadId);\n }\n }\n\n return validThreads;\n }\n\n async hasThread(threadId: string): Promise<boolean> {\n return this.getBufferIfValid(threadId) !== undefined;\n }\n\n /**\n * Cleanup expired threads based on TTL\n * Returns number of threads cleaned up\n */\n async cleanupExpiredThreads(): Promise<number> {\n const now = Date.now();\n let cleanedCount = 0;\n\n for (const [threadId, buffer] of this.buffers.entries()) {\n if (buffer.expiresAt <= now) {\n this.buffers.delete(threadId);\n cleanedCount++;\n }\n }\n\n return cleanedCount;\n }\n\n async extendThreadTTL(\n threadId: string,\n additionalMs?: number\n ): Promise<void> {\n const buffer = this.getBufferIfValid(threadId);\n if (buffer) {\n const extension = additionalMs ?? this.config.ttl;\n buffer.expiresAt = Date.now() + extension;\n buffer.updatedAt = Date.now();\n }\n }\n\n async *getNewChunksSinceContentIterator(\n threadId: string,\n messageId: string,\n knownContent: string\n ): AsyncIterable<MessageChunk> {\n const buffer = this.getBufferIfValid(threadId);\n if (!buffer) return;\n\n let accumulatedContent = \"\";\n const queue: MessageChunk[] = [];\n let resolveNext: (() => void) | null = null;\n let errorNext: ((err: any) => void) | null = null;\n let isCompleted = false;\n\n const subscription = buffer.chunks$.subscribe({\n next: (chunk) => {\n queue.push(chunk);\n if (resolveNext) {\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n error: (err) => {\n if (errorNext) {\n const reject = errorNext;\n errorNext = null;\n reject(err);\n }\n },\n complete: () => {\n isCompleted = true;\n if (resolveNext) {\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n });\n\n try {\n while (true) {\n if (queue.length === 0) {\n if (isCompleted) break;\n await new Promise<void>((resolve, reject) => {\n resolveNext = resolve;\n errorNext = reject;\n });\n }\n\n while (queue.length > 0) {\n const chunk = queue.shift();\n if (!chunk) continue;\n\n if (chunk.data?.id === messageId) {\n accumulatedContent += chunk.data?.content || \"\";\n }\n\n if (accumulatedContent.length > knownContent.length) {\n if (accumulatedContent.startsWith(knownContent)) {\n yield chunk;\n }\n }\n }\n }\n } finally {\n subscription.unsubscribe();\n }\n }\n\n public getStats(): BufferStats {\n let activeCount = 0;\n let completedCount = 0;\n let abortedCount = 0;\n\n const validBuffers: ThreadBuffer[] = [];\n for (const [threadId, buffer] of this.buffers.entries()) {\n if (this.isExpired(buffer)) {\n this.buffers.delete(threadId);\n } else {\n validBuffers.push(buffer);\n }\n }\n\n for (const buffer of validBuffers) {\n switch (buffer.status) {\n case ThreadStatus.ACTIVE:\n activeCount++;\n break;\n case ThreadStatus.COMPLETED:\n completedCount++;\n break;\n case ThreadStatus.ABORTED:\n abortedCount++;\n break;\n }\n }\n\n return {\n totalThreads: validBuffers.length,\n activeThreads: activeCount,\n completedThreads: completedCount,\n abortedThreads: abortedCount,\n\n config: this.config,\n };\n }\n\n public dispose(): void {\n this.stopCleanupTimer();\n this.buffers.clear();\n }\n}\n","/**\n * ChunkBufferLatticeManager\n * \n * Manages ChunkBuffer instances following the Lattice pattern\n */\n\nimport { BaseLatticeManager } from '../base/BaseLatticeManager';\nimport { ChunkBuffer } from './ChunkBuffer';\n\n/**\n * ChunkBuffer Lattice Manager\n */\nexport class ChunkBufferLatticeManager extends BaseLatticeManager<ChunkBuffer> {\n private static instance: ChunkBufferLatticeManager;\n \n /**\n * Private constructor for singleton pattern\n */\n private constructor() {\n super();\n }\n \n /**\n * Get singleton instance\n */\n public static getInstance(): ChunkBufferLatticeManager {\n if (!ChunkBufferLatticeManager.instance) {\n ChunkBufferLatticeManager.instance = new ChunkBufferLatticeManager();\n }\n return ChunkBufferLatticeManager.instance;\n }\n \n /**\n * Get Lattice type identifier\n */\n protected getLatticeType(): string {\n return 'chunk_buffer';\n }\n}\n\n// Convenience functions\nexport const getChunkBuffer = (key: string): ChunkBuffer | undefined =>\n ChunkBufferLatticeManager.getInstance().get(key);\n\nexport const registerChunkBuffer = (key: string, buffer: ChunkBuffer): void =>\n ChunkBufferLatticeManager.getInstance().register(key, buffer);\n\nexport const hasChunkBuffer = (key: string): boolean =>\n ChunkBufferLatticeManager.getInstance().has(key);\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAe,sBAAf,MAAe,oBAAgC;AAAA;AAAA;AAAA;AAAA,EAO1C,cAAc;AAAA,EAExB;AAAA;AAAA;AAAA;AAAA,EAKA,OAAc,cAAuC;AACnD,UAAM,IAAI,MAAM,4CAAS;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA;AAAA,EAYU,WAAW,KAAqB;AACxC,WAAO,GAAG,KAAK,eA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AAAA,EACT;AACF;AAGO,IAAM,iBAAiB,CAAC,QAC7B,0BAA0B,YAAY,EAAE,IAAI,GAAG;AAE1C,IAAM,sBAAsB,CAAC,KAAa,WAC/C,0BAA0B,YAAY,EAAE,SAAS,KAAK,MAAM;AAEvD,IAAM,iBAAiB,CAAC,QAC7B,0BAA0B,YAAY,EAAE,IAAI,GAAG;;;AvCxCjD,gBAA2B;","names":["getAgentClient","z","import_zod","z","import_zod","import_langgraph","z","import_zod","import_langgraph","z","import_zod","import_messages","import_langgraph","z","import_zod","import_messages","import_langgraph","z","import_zod","import_langgraph","z","import_langgraph","import_protocols","import_zod","import_langgraph","tool","import_tools","import_messages","import_langgraph","import_zod","WRITE_TODOS_DESCRIPTION","import_protocols","import_tools","import_messages","import_langgraph","import_zod","WRITE_TODOS_DESCRIPTION","import_zod","import_langgraph","import_prebuilt","tool","tool","import_langgraph","import_messages","import_zod","pino","import_messages","import_messages","import_messages","import_tools","import_langgraph","memory","import_prebuilt","config","tool","tool","import_protocols","getAgentClient","ThreadStatus"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/base/BaseLatticeManager.ts","../src/model_lattice/ModelLattice.ts","../src/model_lattice/ModelLatticeManager.ts","../src/tool_lattice/get_current_date_time/index.ts","../src/tool_lattice/ToolLatticeManager.ts","../src/util/genUIMarkdown.ts","../src/tool_lattice/createToolApproveWrapper.ts","../src/tool_lattice/internet_search/index.ts","../src/util/genUICard.ts","../src/tool_lattice/write_todos/index.ts","../src/tool_lattice/read_file/index.ts","../src/tool_lattice/write_file/index.ts","../src/tool_lattice/edit_file/index.ts","../src/tool_lattice/ls/index.ts","../src/agent_lattice/types.ts","../src/agent_lattice/builders/ReActAgentGraphBuilder.ts","../src/memory_lattice/DefaultMemorySaver.ts","../src/memory_lattice/MemoryLatticeManager.ts","../src/agent_lattice/builders/state.ts","../src/deep_agent/subAgent.ts","../src/deep_agent/prompts.ts","../src/deep_agent/tools.ts","../src/deep_agent/state.ts","../src/deep_agent/graph.ts","../src/agent_lattice/builders/DeepAgentGraphBuilder.ts","../src/createPlanExecuteAgent.ts","../src/logger/Logger.ts","../src/util/returnToolResponse.ts","../src/util/returnAIResponse.ts","../src/util/getLastHumanMessageData.ts","../src/util/PGMemory.ts","../src/agent_lattice/builders/PlanExecuteAgentGraphBuilder.ts","../src/agent_lattice/builders/AgentGraphBuilderFactory.ts","../src/agent_lattice/builders/AgentParamsBuilder.ts","../src/agent_lattice/AgentLatticeManager.ts","../src/chunk_buffer_lattice/ChunkBuffer.ts","../src/chunk_buffer_lattice/types.ts","../src/chunk_buffer_lattice/InMemoryChunkBuffer.ts","../src/chunk_buffer_lattice/ChunkBufferLatticeManager.ts"],"sourcesContent":["// 导出核心模块\nexport * from \"./model_lattice\";\nexport * from \"./tool_lattice\";\nexport * from \"./agent_lattice\";\nexport * from \"./memory_lattice\";\nexport * from \"./chunk_buffer_lattice\";\n\n// 重新导出协议接口 - 使用命名导出避免冲突\nimport * as Protocols from \"@axiom-lattice/protocols\";\nexport { Protocols };\n","/**\n * BaseLatticeManager - 抽象基类,为各种Lattice管理器提供通用功能\n * 使用统一的Lattice注册表,不同类型的Lattice通过前缀区分\n * @template TItem - 管理的项目类型\n */\nexport abstract class BaseLatticeManager<TItem = any> {\n // 全局统一的Lattice注册表\n protected static registry: Map<string, any> = new Map();\n\n /**\n * 受保护的构造函数,防止外部直接实例化\n */\n protected constructor() {\n // 空实现\n }\n\n /**\n * 获取管理器实例(由子类实现)\n */\n public static getInstance(): BaseLatticeManager<any> {\n throw new Error(\"必须由子类实现\");\n }\n\n /**\n * 获取Lattice类型,用于构造键前缀\n * 子类必须重写此方法以提供唯一的类型标识符\n */\n protected abstract getLatticeType(): string;\n\n /**\n * 构造完整的键名,包含类型前缀\n * @param key 原始键名\n */\n protected getFullKey(key: string): string {\n return `${this.getLatticeType()}.${key}`;\n }\n\n /**\n * 注册项目\n * @param key 项目键名(不含前缀)\n * @param item 项目实例\n */\n public register(key: string, item: TItem): void {\n const fullKey = this.getFullKey(key);\n if (BaseLatticeManager.registry.has(fullKey)) {\n throw new Error(`项目 \"${fullKey}\" 已经存在,无法重复注册`);\n }\n\n BaseLatticeManager.registry.set(fullKey, item);\n }\n\n /**\n * 获取指定项目\n * @param key 项目键名(不含前缀)\n */\n public get(key: string): TItem | undefined {\n const fullKey = this.getFullKey(key);\n return BaseLatticeManager.registry.get(fullKey) as TItem | undefined;\n }\n\n /**\n * 获取所有当前类型的项目\n */\n public getAll(): TItem[] {\n const prefix = `${this.getLatticeType()}.`;\n const result: TItem[] = [];\n\n for (const [key, value] of BaseLatticeManager.registry.entries()) {\n if (key.startsWith(prefix)) {\n result.push(value as TItem);\n }\n }\n\n return result;\n }\n\n /**\n * 检查项目是否存在\n * @param key 项目键名(不含前缀)\n */\n public has(key: string): boolean {\n const fullKey = this.getFullKey(key);\n return BaseLatticeManager.registry.has(fullKey);\n }\n\n /**\n * 移除项目\n * @param key 项目键名(不含前缀)\n */\n public remove(key: string): boolean {\n const fullKey = this.getFullKey(key);\n return BaseLatticeManager.registry.delete(fullKey);\n }\n\n /**\n * 清空当前类型的所有项目\n */\n public clear(): void {\n const prefix = `${this.getLatticeType()}.`;\n const keysToDelete: string[] = [];\n\n for (const key of BaseLatticeManager.registry.keys()) {\n if (key.startsWith(prefix)) {\n keysToDelete.push(key);\n }\n }\n\n for (const key of keysToDelete) {\n BaseLatticeManager.registry.delete(key);\n }\n }\n\n /**\n * 获取当前类型的项目数量\n */\n public count(): number {\n const prefix = `${this.getLatticeType()}.`;\n let count = 0;\n\n for (const key of BaseLatticeManager.registry.keys()) {\n if (key.startsWith(prefix)) {\n count++;\n }\n }\n\n return count;\n }\n\n /**\n * 获取当前类型的项目键名列表(不含前缀)\n */\n public keys(): string[] {\n const prefix = `${this.getLatticeType()}.`;\n const prefixLength = prefix.length;\n const result: string[] = [];\n\n for (const key of BaseLatticeManager.registry.keys()) {\n if (key.startsWith(prefix)) {\n result.push(key.substring(prefixLength));\n }\n }\n\n return result;\n }\n}\n","import {\n AIMessage,\n BaseMessage,\n BaseMessageLike,\n HumanMessage,\n} from \"@langchain/core/messages\";\nimport { ChatDeepSeek } from \"@langchain/deepseek\";\nimport { AzureChatOpenAI, ChatOpenAI } from \"@langchain/openai\";\nimport { z } from \"zod\";\nimport { ZodType as ZodTypeV3 } from \"zod/v3\";\nimport { $ZodType as ZodTypeV4 } from \"zod/v4/core\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n BaseLanguageModel,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n CallbackManagerForLLMRun,\n Callbacks,\n} from \"@langchain/core/callbacks/manager\";\nimport { ChatResult } from \"@langchain/core/outputs\";\nBaseLanguageModel;\nimport { LLMConfig } from \"@axiom-lattice/protocols\";\n\n/**\n * ModelLattice类,继承自BaseChatModel\n * 简化版本,只保留通过LLMConfig创建LLM实例的功能\n */\nexport class ModelLattice extends BaseChatModel {\n private config: LLMConfig;\n private llm: BaseChatModel;\n\n lc_namespace: string[] = [\"langchain\", \"model_lattice\"];\n\n /**\n * 构造函数\n * @param config LLM配置\n */\n constructor(config: LLMConfig) {\n super({});\n this.config = config;\n this.llm = this.initChatModel(config);\n }\n\n /**\n * 返回模型类型\n */\n _llmType(): string {\n return \"model_lattice\";\n }\n\n /**\n * 返回模型类型\n */\n _modelType(): string {\n return this.llm._modelType();\n }\n\n /**\n * 实现BaseChatModel的_generate方法\n * @param messages 消息数组\n * @param options 调用选项\n * @param runManager 回调管理器\n * @returns 聊天结果\n */\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n return this.llm._generate(messages, options as any, runManager);\n }\n\n /**\n * 将工具绑定到模型\n * @param tools 工具列表\n * @param tool_choice 工具选择选项\n * @returns 绑定工具后的模型\n */\n bindTools(\n tools: any[],\n {\n tool_choice = \"auto\",\n ...kwargs\n }: {\n tool_choice?: \"auto\" | \"none\" | \"required\" | any;\n [key: string]: any;\n } = {}\n ): any {\n // 如果底层LLM实现了bindTools方法,则使用它的实现\n if (typeof this.llm.bindTools === \"function\") {\n return this.llm.bindTools(tools, {\n tool_choice,\n ...kwargs,\n });\n }\n\n // 如果底层LLM没有实现bindTools方法,抛出错误\n throw new Error(\"llm not support bindTools\");\n }\n\n /**\n * 使用结构化输出调用LLM\n * @param input 输入\n * @param schema 结构化输出的schema\n * @param options 调用选项\n * @returns 结构化输出\n */\n async invokeWithStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n input: BaseLanguageModelInput,\n schema: ZodTypeV3<RunOutput> | ZodTypeV4<RunOutput> | Record<string, any>,\n options?: BaseChatModelCallOptions & {\n includeRaw?: boolean;\n name?: string;\n method?: \"functionCalling\" | \"jsonMode\";\n }\n ): Promise<RunOutput | { raw: BaseMessage; parsed: RunOutput }> {\n // 使用LLM的withStructuredOutput方法\n if (this.llm.withStructuredOutput) {\n // 使用类型断言解决类型兼容性问题\n const structuredLLM = this.llm.withStructuredOutput(schema, {\n includeRaw: options?.includeRaw ?? false,\n name: options?.name,\n method: options?.method,\n } as any);\n\n return structuredLLM.invoke(input, options);\n }\n\n // 如果LLM没有withStructuredOutput方法,抛出错误\n throw new Error(\"当前LLM不支持结构化输出\");\n }\n\n /**\n * 创建LLM实例\n * @param config LLM配置\n * @returns LLM实例\n */\n private initChatModel(config: LLMConfig): BaseChatModel {\n if (config.provider === \"azure\") {\n return new AzureChatOpenAI({\n azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,\n azureOpenAIApiInstanceName: \"convertlab-westus\",\n azureOpenAIApiDeploymentName: config.model,\n azureOpenAIApiVersion: \"2024-02-01\",\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n streaming: config.streaming,\n });\n } else if (config.provider === \"deepseek\") {\n return new ChatDeepSeek({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n apiKey: process.env[config.apiKeyEnvName || \"DEEPSEEK_API_KEY\"],\n streaming: config.streaming,\n });\n } else if (config.provider === \"siliconcloud\") {\n return new ChatOpenAI({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n apiKey: process.env[config.apiKeyEnvName || \"SILICONCLOUD_API_KEY\"],\n configuration: {\n baseURL: \"https://api.siliconflow.cn/v1\",\n },\n streaming: config.streaming,\n });\n } else if (config.provider === \"volcengine\") {\n return new ChatOpenAI({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n apiKey: process.env[config.apiKeyEnvName || \"VOLCENGINE_API_KEY\"],\n configuration: {\n baseURL: \"https://ark.cn-beijing.volces.com/api/v3\",\n },\n streaming: config.streaming,\n });\n } else {\n return new ChatOpenAI({\n model: config.model,\n temperature: config.temperature || 0,\n maxTokens: config.maxTokens,\n timeout: config.timeout,\n maxRetries: config.maxRetries || 2,\n streaming: config.streaming,\n apiKey: process.env[config.apiKeyEnvName || \"OPENAI_API_KEY\"],\n configuration: {\n baseURL: config.baseURL,\n },\n });\n }\n }\n}\n","import { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { ModelLattice as LLMModelLattice } from \"./ModelLattice\";\nimport { LLMConfig } from \"@axiom-lattice/protocols\";\n\n// 模型配置接口,直接使用 LLMConfig\nexport type ModelConfig = LLMConfig;\n\n// 模型客户端类型,使用 LLMManager\ntype ModelClient = LLMModelLattice;\n\n// 定义接口\nexport interface ModelLatticeInterface {\n key: string;\n client: ModelClient;\n}\n\n/**\n * ModelLatticeManager - 单例模型Lattice管理器\n * 负责注册、管理各种语言模型Lattice\n */\nexport class ModelLatticeManager extends BaseLatticeManager<ModelLatticeInterface> {\n private static _instance: ModelLatticeManager;\n\n /**\n * 获取ModelLatticeManager单例实例\n */\n public static getInstance(): ModelLatticeManager {\n if (!ModelLatticeManager._instance) {\n ModelLatticeManager._instance = new ModelLatticeManager();\n }\n return ModelLatticeManager._instance;\n }\n\n /**\n * 获取Lattice类型前缀\n */\n protected getLatticeType(): string {\n return \"models\";\n }\n\n /**\n * 注册模型Lattice\n * @param key Lattice键名\n * @param config 模型配置\n */\n public registerLattice(key: string, config: ModelConfig): void {\n // 使用 LLMManager 创建客户端\n const client = new LLMModelLattice(config);\n\n // 创建模型Lattice对象\n const modelLattice: ModelLatticeInterface = {\n key,\n client,\n };\n\n // 调用基类的register方法\n this.register(key, modelLattice);\n }\n\n /**\n * 获取ModelLattice\n * @param key Lattice键名\n */\n public getModelLattice(key: string): ModelLatticeInterface {\n const modelLattice = this.get(key);\n if (!modelLattice) {\n throw new Error(`ModelLattice ${key} not found`);\n }\n return modelLattice;\n }\n\n /**\n * 获取所有Lattice\n */\n public getAllLattices(): ModelLatticeInterface[] {\n return this.getAll();\n }\n\n /**\n * 检查Lattice是否存在\n * @param key Lattice键名\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * 移除Lattice\n * @param key Lattice键名\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * 清空所有Lattice\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * 获取Lattice数量\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * 获取Lattice键名列表\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// 导出单例实例\nexport const modelLatticeManager = ModelLatticeManager.getInstance();\n\n// 导出便捷方法\nexport const registerModelLattice = (key: string, config: ModelConfig) =>\n modelLatticeManager.registerLattice(key, config);\n\nexport const getModelLattice = (key: string) =>\n modelLatticeManager.getModelLattice(key);\n","import z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\n\nregisterToolLattice(\n \"get_current_date_time\",\n {\n name: \"get_current_date_time\",\n description: \"获取当前日期时间\",\n schema: z.object({}),\n },\n async () => {\n return \"当前日期时间:\" + new Date().toLocaleString();\n }\n);\n","import { StructuredTool, tool } from \"@langchain/core/tools\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { ToolConfig, ToolExecutor } from \"@axiom-lattice/protocols\";\nimport { createToolApproveWrapper } from \"./createToolApproveWrapper\";\n\n// 工具定义接口 - 使用协议中的ToolConfig\nexport type ToolDefinition = ToolConfig;\n\n// Lattice 接口定义\nexport interface ToolLattice {\n key: string;\n config: ToolConfig;\n client: StructuredTool;\n}\n\n/**\n * ToolLatticeManager - 单例工具Lattice管理器\n * 负责注册、管理各种工具Lattice\n */\nexport class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {\n private static _instance: ToolLatticeManager;\n\n /**\n * 获取ToolLatticeManager单例实例\n */\n public static getInstance(): ToolLatticeManager {\n if (!ToolLatticeManager._instance) {\n ToolLatticeManager._instance = new ToolLatticeManager();\n }\n return ToolLatticeManager._instance;\n }\n\n /**\n * 获取Lattice类型前缀\n */\n protected getLatticeType(): string {\n return \"tools\";\n }\n\n /**\n * 注册工具Lattice\n * @param key Lattice键名\n * @param config 工具配置(定义)\n * @param executor 工具执行函数\n */\n public registerLattice<TInput = any, TOutput = any>(\n key: string,\n config: ToolConfig,\n executor: ToolExecutor<TInput, TOutput>\n ): void {\n // 创建工具Lattice对象\n let toolExecutor;\n\n if (config.needUserApprove) {\n toolExecutor = createToolApproveWrapper<TInput, TOutput>(\n config,\n executor\n );\n } else {\n toolExecutor = async (input: TInput, exe_config: any) => {\n const result = await executor(input, exe_config);\n return result;\n };\n }\n\n const toolLattice: ToolLattice = {\n key,\n config,\n client: tool(toolExecutor as ToolExecutor, config),\n };\n\n // 调用基类的register方法\n this.register(key, toolLattice);\n }\n\n /**\n * 获取ToolLattice\n * @param key Lattice键名\n */\n public getToolLattice(key: string): ToolLattice | undefined {\n return this.get(key);\n }\n\n /**\n * 获取所有Lattice\n */\n public getAllLattices(): ToolLattice[] {\n return this.getAll();\n }\n\n /**\n * 检查Lattice是否存在\n * @param key Lattice键名\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * 移除Lattice\n * @param key Lattice键名\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * 清空所有Lattice\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * 获取Lattice数量\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * 获取Lattice键名列表\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * 获取工具定义\n * @param key Lattice键名\n */\n public getToolDefinition(key: string): ToolDefinition {\n const toolLattice = this.getToolLattice(key);\n if (!toolLattice) {\n throw new Error(`ToolLattice ${key} not found`);\n }\n return toolLattice.config;\n }\n\n /**\n * 获取工具客户端\n * @param key Lattice键名\n */\n public getToolClient(key: string): StructuredTool {\n const toolLattice = this.getToolLattice(key);\n if (!toolLattice) {\n throw new Error(`ToolLattice ${key} not found`);\n }\n return toolLattice.client;\n }\n\n /**\n * 获取所有工具定义\n */\n public getAllToolDefinitions(): ToolDefinition[] {\n return this.getAllLattices().map((lattice) => lattice.config);\n }\n\n /**\n * 验证工具输入参数\n * @param key Lattice键名\n * @param input 输入参数\n */\n public validateToolInput(key: string, input: any): boolean {\n const toolLattice = this.getToolLattice(key);\n if (!toolLattice) {\n return false;\n }\n\n try {\n if (toolLattice.config.schema) {\n toolLattice.config.schema.parse(input);\n }\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// 导出单例实例\nexport const toolLatticeManager = ToolLatticeManager.getInstance();\n\n// 导出便捷方法\nexport const registerToolLattice = (\n key: string,\n config: ToolConfig,\n executor: ToolExecutor\n) => toolLatticeManager.registerLattice(key, config, executor);\n\nexport const getToolLattice = (key: string) =>\n toolLatticeManager.getToolLattice(key);\n\nexport const getToolDefinition = (key: string) =>\n toolLatticeManager.getToolDefinition(key);\n\nexport const getToolClient = (key: string) =>\n toolLatticeManager.getToolClient(key);\n\nexport const getAllToolDefinitions = () =>\n toolLatticeManager.getAllToolDefinitions();\n\nexport const validateToolInput = (key: string, input: any) =>\n toolLatticeManager.validateToolInput(key, input);\n","export const genUIMarkdown = (type: string, data: any) => {\n return [\"```\" + type, JSON.stringify(data), \"```\"].join(\"\\n\");\n};\n","import { AIMessage, isAIMessage } from \"@langchain/core/messages\";\nimport { ToolLatticeManager } from \"./ToolLatticeManager\";\nimport { ToolLattice } from \"./ToolLatticeManager\";\nimport { genUIMarkdown } from \"../util/genUIMarkdown\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport { UserFeedbackResponse } from \"../types\";\nimport { END, interrupt } from \"@langchain/langgraph\";\nimport { ToolConfig, ToolExecutor } from \"@axiom-lattice/protocols\";\nexport function createToolApproveWrapper<TInput = any, TOutput = any>(\n tool_config: ToolConfig,\n toolExecutor: ToolExecutor<TInput, TOutput>\n) {\n return async (input: TInput, exe_config: any) => {\n const messagePrefix = \"Tool execution requires approval\";\n const description = `${messagePrefix}\\n\\nTool: ${tool_config.name}\\nArgs: ${JSON.stringify(input, null, 2)}`;\n\n const md = genUIMarkdown(\"confirm\", {\n message: description,\n tool_call: {\n tool_call_id: exe_config.id,\n tool_name: tool_config.name,\n tool_args: input,\n tool_config: tool_config,\n },\n });\n\n const feedback: UserFeedbackResponse = await interrupt(md);\n\n if (feedback.data.action === \"yes\") {\n return await toolExecutor(input, exe_config);\n } else {\n return {\n goto: END,\n };\n }\n };\n}\n","import z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { TavilySearch } from \"@langchain/tavily\";\nimport \"dotenv/config\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { genUICard } from \"@util/genUICard\";\n\ntype Topic = \"general\" | \"news\" | \"finance\";\n\nregisterToolLattice(\n \"internet_search\",\n {\n name: \"internet_search\",\n description: \"Run a web search\",\n needUserApprove: false,\n schema: z.object({\n query: z.string().describe(\"The search query\"),\n maxResults: z\n .number()\n .optional()\n .default(5)\n .describe(\"Maximum number of results to return\"),\n topic: z\n .enum([\"general\", \"news\", \"finance\"])\n .optional()\n .default(\"general\")\n .describe(\"Search topic category\"),\n includeRawContent: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to include raw content\"),\n }),\n },\n async (\n {\n query,\n maxResults = 5,\n topic = \"general\" as Topic,\n includeRawContent = false,\n }: {\n query: string;\n maxResults?: number;\n topic?: Topic;\n includeRawContent?: boolean;\n },\n config: LangGraphRunnableConfig\n ) => {\n /**\n * Run a web search\n */\n console.log(\"[DEBUG][internet_search] Starting search with params:\", {\n query,\n maxResults,\n topic,\n includeRawContent,\n });\n\n // Note: You'll need to install and import tavily-js or similar package\n console.log(\"[DEBUG][internet_search] Creating TavilySearch instance...\");\n const tavilySearch = new TavilySearch({\n maxResults,\n tavilyApiKey: process.env.TAVILY_API_KEY,\n includeRawContent,\n topic,\n });\n\n console.log(\"[DEBUG][internet_search] Invoking search for query:\", query);\n const tavilyResponse = await tavilySearch.invoke({ query });\n console.log(\n \"[DEBUG][internet_search] Search completed. Results count:\",\n tavilyResponse.results?.length ?? 0\n );\n\n const result = genUICard(\"Internet Search:\" + query, \"generic_data_table\", {\n dataSource: tavilyResponse.results,\n });\n console.log(\"[DEBUG][internet_search] Returning UI card result\");\n\n return result;\n }\n);\n","export const genUICard = (title: string, type: string, data: any) => {\n return [title, \"```\" + type, JSON.stringify(data), \"```\"].join(\"\\n\");\n};\n","/**\n * Write Todos Tool\n *\n * Manages todo list with Command return for deep agents.\n * Uses getCurrentTaskInput() instead of Python's InjectedState.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { Command } from \"@langchain/langgraph\";\nimport { genUIMarkdown } from \"@util/genUIMarkdown\";\n\nconst 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.\n\nWhen to Use This Tool\nUse this tool proactively in these scenarios:\n\nComplex multi-step tasks - When a task requires 3 or more distinct steps or actions\nNon-trivial and complex tasks - Tasks that require careful planning or multiple operations\nUser explicitly requests todo list - When the user directly asks you to use the todo list\nUser provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\nAfter receiving new instructions - Immediately capture user requirements as todos\nWhen 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\nAfter completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation\n\nWhen NOT to Use This Tool\nSkip using this tool when:\n\nThere is only a single, straightforward task\nThe task is trivial and tracking it provides no organizational benefit\nThe task can be completed in less than 3 trivial steps\nThe task is purely conversational or informational\n\nNOTE 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.`;\n\nregisterToolLattice(\n \"write_todos\",\n {\n name: \"write_todos\",\n description: WRITE_TODOS_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n todos: z\n .array(\n z.object({\n content: z.string().describe(\"Content of the todo item\"),\n status: z\n .enum([\"pending\", \"in_progress\", \"completed\"])\n .describe(\"Status of the todo\"),\n })\n )\n .describe(\"List of todo items to update\"),\n }),\n },\n ((\n input: {\n todos: Array<{\n content: string;\n status: \"pending\" | \"in_progress\" | \"completed\";\n }>;\n },\n config: ToolRunnableConfig\n ) => {\n return new Command({\n update: {\n todos: input.todos,\n messages: [\n new ToolMessage({\n content: genUIMarkdown(\"todo_list\", input.todos),\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }) as any\n);\n","/**\n * Read File Tool\n *\n * Reads from mock filesystem in state.files.\n * Matches Python read_file function behavior exactly.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nconst READ_FILE_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.\nUsage:\n\nThe file_path parameter must be an absolute path, not a relative path\nBy default, it reads up to 2000 lines starting from the beginning of the file\nYou 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\nAny lines longer than 2000 characters will be truncated\nResults are returned using cat -n format, with line numbers starting at 1\nYou 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.\nIf you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;\n\nregisterToolLattice(\n \"read_file\",\n {\n name: \"read_file\",\n description: READ_FILE_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to read\"),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from\"),\n limit: z\n .number()\n .optional()\n .default(2000)\n .describe(\"Maximum number of lines to read\"),\n }),\n },\n ((input: { file_path: string; offset?: number; limit?: number }) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = state.files || {};\n const { file_path, offset = 0, limit = 2000 } = input;\n\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get file content\n const content = mockFilesystem[file_path];\n\n // Handle empty file\n if (!content || content.trim() === \"\") {\n return \"System reminder: File exists but has empty contents\";\n }\n\n // Split content into lines\n const lines = content.split(\"\\n\");\n\n // Apply line offset and limit\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n // Handle case where offset is beyond file length\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n // Format output with line numbers (cat -n format)\n const resultLines: string[] = [];\n for (let i = startIdx; i < endIdx; i++) {\n let lineContent = lines[i];\n\n // Truncate lines longer than 2000 characters\n if (lineContent.length > 2000) {\n lineContent = lineContent.substring(0, 2000);\n }\n\n // Line numbers start at 1, so add 1 to the index\n const lineNumber = i + 1;\n resultLines.push(`${lineNumber.toString().padStart(6)}\\t${lineContent}`);\n }\n\n return resultLines.join(\"\\n\");\n }) as any\n);\n","/**\n * Write File Tool\n *\n * Writes to mock filesystem with Command return.\n * Matches Python write_file function behavior exactly.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nregisterToolLattice(\n \"write_file\",\n {\n name: \"write_file\",\n description: \"Write content to a file in the mock filesystem\",\n needUserApprove: false,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to write\"),\n content: z.string().describe(\"Content to write to the file\"),\n }),\n },\n ((\n input: { file_path: string; content: string },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = { ...(state.files || {}) };\n files[input.file_path] = input.content;\n\n return new Command({\n update: {\n files: files,\n messages: [\n new ToolMessage({\n content: `Updated file ${input.file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }) as any\n);\n","/**\n * Edit File Tool\n *\n * Edits files in mock filesystem with Command return.\n * Matches Python edit_file function behavior exactly.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nconst EDIT_FILE_DESCRIPTION = `Performs exact string replacements in files.\nUsage:\n\nYou 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.\nWhen 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.\nALWAYS prefer editing existing files. NEVER write new files unless explicitly required.\nOnly use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\nThe 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.\nUse replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;\n\nregisterToolLattice(\n \"edit_file\",\n {\n name: \"edit_file\",\n description: EDIT_FILE_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to edit\"),\n old_string: z\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z.string().describe(\"String to replace with\"),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n },\n ((\n input: {\n file_path: string;\n old_string: string;\n new_string: string;\n replace_all?: boolean;\n },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = { ...(state.files || {}) };\n const { file_path, old_string, new_string, replace_all = false } = input;\n\n // Check if file exists in mock filesystem\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get current file content\n const content = mockFilesystem[file_path];\n\n // Check if old_string exists in the file\n if (!content.includes(old_string)) {\n return `Error: String not found in file: '${old_string}'`;\n }\n\n // If not replace_all, check for uniqueness\n if (!replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n const occurrences = (\n content.match(new RegExp(escapedOldString, \"g\")) || []\n ).length;\n if (occurrences > 1) {\n 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.`;\n } else if (occurrences === 0) {\n return `Error: String not found in file: '${old_string}'`;\n }\n }\n\n // Perform the replacement\n let newContent: string;\n\n if (replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n newContent = content.replace(\n new RegExp(escapedOldString, \"g\"),\n new_string\n );\n } else {\n newContent = content.replace(old_string, new_string);\n }\n\n // Update the mock filesystem\n mockFilesystem[file_path] = newContent;\n\n return new Command({\n update: {\n files: mockFilesystem,\n messages: [\n new ToolMessage({\n content: `Updated file ${file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }) as any\n);\n","/**\n * List Files Tool\n *\n * Returns list of files from state.files.\n * Equivalent to Python's ls function.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { getCurrentTaskInput } from \"@langchain/langgraph\";\n\ninterface DeepAgentStateType {\n files?: Record<string, string>;\n}\n\nregisterToolLattice(\n \"ls\",\n {\n name: \"ls\",\n description: \"List all files in the mock filesystem\",\n needUserApprove: false,\n schema: z.object({}),\n },\n (() => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = state.files || {};\n return Object.keys(files);\n }) as any\n);\n","/**\n * Agent Lattice 类型定义\n *\n * 包含Agent Lattice相关的所有类型定义,供其他模块共享使用\n */\n\nimport { z } from \"zod\";\nimport { ModelLattice } from \"@model_lattice/ModelLattice\";\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport {\n AgentType,\n AgentConfig,\n ReactAgentConfig,\n DeepAgentConfig,\n PlanExecuteAgentConfig,\n SequentialAgentConfig,\n AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n} from \"@axiom-lattice/protocols\";\n\n// Re-export types from protocols\nexport {\n AgentType,\n AgentConfig,\n ReactAgentConfig,\n DeepAgentConfig,\n PlanExecuteAgentConfig,\n SequentialAgentConfig,\n AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n};\n\n// Agent客户端类型 - CompiledStateGraph\nexport type AgentClient = CompiledStateGraph<any, any, any, any, any>;\n\n// AgentLattice接口定义\nexport interface AgentLattice {\n config: AgentConfig;\n client?: AgentClient | undefined;\n}\n\n// Agent构建参数接口\nexport interface AgentBuildParams {\n tools: Array<{\n key: string;\n definition: any;\n executor: any;\n }>;\n model: ModelLattice;\n subAgents: Array<{\n key: string;\n config: AgentConfig;\n client: AgentClient | undefined;\n }>;\n prompt: string;\n stateSchema?: z.ZodObject<any, any, any, any, any>;\n}\n","/**\n * ReAct Agent Graph Builder\n *\n * 实现 ReAct 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph, MessagesZodState } from \"@langchain/langgraph\";\nimport { DynamicTool } from \"@langchain/core/tools\";\nimport { AgentLattice, AgentBuildParams } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { getCheckpointSaver } from \"@memory_lattice\";\nimport { createReactAgentSchema, ReActAgentState } from \"./state\";\n\nexport class ReActAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 构建ReAct Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(\n agentLattice: AgentLattice,\n params: AgentBuildParams\n ): CompiledStateGraph<any, any, any, any, any> {\n // 创建符合 DynamicTool 接口的工具对象\n const tools = params.tools\n .map((t) => {\n // 使用 DynamicTool 构造工具对象\n const tool = getToolClient(t.key);\n return tool;\n })\n .filter((tool) => tool !== undefined);\n\n const stateSchema = createReactAgentSchema(params.stateSchema);\n\n return createReactAgent({\n llm: params.model,\n tools: tools,\n prompt: params.prompt,\n name: agentLattice.config.name,\n checkpointer: getCheckpointSaver(\"default\"),\n stateSchema: stateSchema,\n });\n }\n}\n","import { MemorySaver } from \"@langchain/langgraph\";\nimport { registerCheckpointSaver } from \"./MemoryLatticeManager\";\nconst memory = new MemorySaver();\nregisterCheckpointSaver(\"default\", memory);\n","/**\n * MemoryLatticeManager\n *\n * 记忆Lattice管理器,负责管理和注册检查点保存器\n */\n\nimport { BaseCheckpointSaver } from \"@langchain/langgraph-checkpoint\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { MemoryLatticeProtocol, MemoryType } from \"@axiom-lattice/protocols\";\n\n// Re-export types from protocols\nexport { MemoryType };\n\n/**\n * 记忆Lattice管理器类\n */\nexport class MemoryLatticeManager extends BaseLatticeManager {\n private static instance: MemoryLatticeManager;\n\n // 检查点保存器注册表\n private static checkpointSavers: Map<string, BaseCheckpointSaver> = new Map();\n\n /**\n * 私有构造函数,防止外部直接实例化\n */\n private constructor() {\n super();\n }\n\n /**\n * 获取单例实例\n */\n public static getInstance(): MemoryLatticeManager {\n if (!MemoryLatticeManager.instance) {\n MemoryLatticeManager.instance = new MemoryLatticeManager();\n }\n return MemoryLatticeManager.instance;\n }\n\n /**\n * 获取Lattice类型\n */\n protected getLatticeType(): string {\n return \"memory\";\n }\n\n /**\n * 注册检查点保存器\n * @param key 保存器键名\n * @param saver 检查点保存器实例\n */\n public registerCheckpointSaver(\n key: string,\n saver: BaseCheckpointSaver\n ): void {\n if (MemoryLatticeManager.checkpointSavers.has(key)) {\n console.warn(`检查点保存器 \"${key}\" 已经存在,将会覆盖旧的检查点保存器`);\n }\n\n MemoryLatticeManager.checkpointSavers.set(key, saver);\n }\n\n /**\n * 获取检查点保存器\n * @param key 保存器键名\n */\n public getCheckpointSaver(key: string): BaseCheckpointSaver {\n const saver = MemoryLatticeManager.checkpointSavers.get(key);\n if (!saver) {\n throw new Error(`检查点保存器 \"${key}\" 不存在`);\n }\n return saver;\n }\n\n /**\n * 获取所有已注册的检查点保存器键名\n */\n public getCheckpointSaverKeys(): string[] {\n return Array.from(MemoryLatticeManager.checkpointSavers.keys());\n }\n\n /**\n * 检查检查点保存器是否存在\n * @param key 保存器键名\n */\n public hasCheckpointSaver(key: string): boolean {\n return MemoryLatticeManager.checkpointSavers.has(key);\n }\n\n /**\n * 移除检查点保存器\n * @param key 保存器键名\n */\n public removeCheckpointSaver(key: string): boolean {\n return MemoryLatticeManager.checkpointSavers.delete(key);\n }\n}\n\nexport const getCheckpointSaver = (key: string) =>\n MemoryLatticeManager.getInstance().getCheckpointSaver(key);\n\nexport const registerCheckpointSaver = (\n key: string,\n saver: BaseCheckpointSaver\n) => MemoryLatticeManager.getInstance().registerCheckpointSaver(key, saver);\n","/**\n * State definitions for Deep Agents\n *\n * TypeScript equivalents of the Python state classes using LangGraph's Annotation.Root() pattern.\n * Defines Todo interface and DeepAgentState using MessagesAnnotation as base with proper reducer functions.\n */\n\nimport \"@langchain/langgraph/zod\";\nimport { MessagesZodState } from \"@langchain/langgraph\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\nimport { z } from \"zod\";\n\n/**\n * File reducer function that merges file dictionaries\n * Matches the Python file_reducer function behavior exactly\n */\nexport function fileReducer(\n left: Record<string, string> | null | undefined,\n right: Record<string, string> | null | undefined\n): Record<string, string> {\n if (left == null) {\n return right || {};\n } else if (right == null) {\n return left;\n } else {\n return { ...left, ...right };\n }\n}\n\nexport const ReActAgentState = MessagesZodState.extend({\n files: z.object({\n final_output: z.record(z.any()),\n }),\n});\n\nexport const createReactAgentSchema = (\n schema?: z.ZodObject<any, any, any, any, any>\n) => {\n return schema ? MessagesZodState.extend(schema.shape) : undefined;\n};\n","/**\n * SubAgent implementation for Deep Agents\n *\n * Task tool creation and sub-agent management.\n * Creates SubAgent interface matching Python's TypedDict structure and implements\n * createTaskTool() function that creates agents map, handles tool resolution by name,\n * and returns a tool function that uses createReactAgent for sub-agents.\n */\n\nimport { tool, StructuredTool } from \"@langchain/core/tools\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport {\n Command,\n getCurrentTaskInput,\n GraphInterrupt,\n} from \"@langchain/langgraph\";\nimport { ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { z } from \"zod\";\nimport type { LanguageModelLike, PostModelHook, SubAgent } from \"./types\";\nimport { TASK_DESCRIPTION_PREFIX, TASK_DESCRIPTION_SUFFIX } from \"./prompts\";\nimport { ModelLattice } from \"../model_lattice/ModelLattice\";\nimport { getModelLattice } from \"../model_lattice/ModelLatticeManager\";\nimport { getCheckpointSaver } from \"@memory_lattice/MemoryLatticeManager\";\nimport {\n createAgentClientFromAgentLattice,\n getAgentClient,\n getAgentLattice,\n} from \"@agent_lattice/AgentLatticeManager\";\nimport {\n AgentConfig,\n getToolsFromConfig,\n hasTools,\n} from \"@axiom-lattice/protocols\";\nimport { getToolClient } from \"@tool_lattice\";\n\n/**\n * Built-in tool names for tool resolution\n */\nconst BUILTIN_TOOL_NAMES = [\n \"write_todos\",\n \"read_file\",\n \"write_file\",\n \"edit_file\",\n \"ls\",\n];\n\n/**\n * Get built-in tools map from ToolLatticeManager\n */\nfunction getBuiltinTools(): Record<string, StructuredTool> {\n const tools: Record<string, StructuredTool> = {};\n for (const name of BUILTIN_TOOL_NAMES) {\n try {\n tools[name] = getToolClient(name);\n } catch {\n // Tool may not be registered yet, skip\n }\n }\n return tools;\n}\n\n/**\n * Create task tool function that creates agents map, handles tool resolution by name,\n * and returns a tool function that uses createReactAgent for sub-agents.\n * Uses Command for state updates and navigation between agents.\n */\nexport function createTaskTool<\n StateSchema extends z.ZodObject<any, any, any, any, any>\n>(inputs: {\n subagents: AgentConfig[];\n tools: Record<string, StructuredTool>;\n model: ModelLattice;\n stateSchema: StateSchema;\n postModelHook?: PostModelHook;\n}) {\n const {\n subagents,\n tools = {},\n model = getModelLattice(\"default\")?.client,\n stateSchema,\n postModelHook,\n } = inputs;\n\n if (!model) {\n throw new Error(\"Model not found\");\n }\n\n // Combine built-in tools with provided tools for tool resolution\n const allTools = { ...getBuiltinTools(), ...tools };\n\n const agentsMap = new Map<string, any>();\n for (const subagent of subagents) {\n let reactAgent;\n const agentLattice = getAgentLattice(subagent.key); // get agent lattice from lattice registry\n if (agentLattice) {\n //use agent lattice client directly\n reactAgent = agentLattice.client;\n } else {\n // Resolve tools by name for this subagent\n const subagentTools: StructuredTool[] = [];\n if (hasTools(subagent)) {\n for (const toolName of getToolsFromConfig(subagent)) {\n const resolvedTool = allTools[toolName];\n if (resolvedTool) {\n subagentTools.push(resolvedTool);\n } else {\n // eslint-disable-next-line no-console\n console.warn(\n `Warning: Tool '${toolName}' not found for agent '${subagent.name}'`\n );\n }\n }\n } else {\n // If no tools specified, use all tools\n subagentTools.push(...Object.values(allTools));\n }\n\n // Create react agent for the subagent\n\n reactAgent = createAgentClientFromAgentLattice({ config: subagent });\n\n // reactAgent = createReactAgent({\n // llm: model,\n // tools: subagentTools,\n // stateSchema: stateSchema as any,\n // messageModifier: subagent.prompt,\n // // checkpointer: false,\n // checkpointer: getCheckpointSaver(\"default\"),\n\n // postModelHook: postModelHook,\n // });\n }\n\n agentsMap.set(subagent.name, reactAgent);\n }\n\n return tool(\n async (\n input: { description: string; subagent_type: string },\n config: ToolRunnableConfig\n ) => {\n const { description, subagent_type } = input;\n\n // Get the pre-created agent\n const reactAgent = agentsMap.get(subagent_type);\n if (!reactAgent) {\n return `Error: Agent '${subagent_type}' not found. Available agents: ${Array.from(\n agentsMap.keys()\n ).join(\", \")}`;\n }\n\n try {\n // Get current state for context\n const currentState = getCurrentTaskInput<z.infer<typeof stateSchema>>();\n\n // Modify state messages like Python does\n const modifiedState = {\n ...currentState,\n messages: [\n {\n role: \"user\",\n content: description,\n },\n ],\n };\n\n // Execute the subagent with the task\n const result = await reactAgent.invoke(modifiedState, config);\n\n // Use Command for state updates and navigation between agents\n // Return the result using Command to properly handle subgraph state\n return new Command({\n update: {\n files: result.files || {},\n messages: [\n new ToolMessage({\n content:\n result.messages?.slice(-1)[0]?.content || \"Task completed\",\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n } catch (error) {\n if (error instanceof GraphInterrupt) {\n throw error;\n }\n // Handle errors gracefully\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return new Command({\n update: {\n messages: [\n new ToolMessage({\n content: `Error executing task '${description}' with agent '${subagent_type}': ${errorMessage}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n }\n },\n {\n name: \"task\",\n description:\n TASK_DESCRIPTION_PREFIX.replace(\n \"{other_agents}\",\n subagents.map((a) => `- ${a.name}: ${a.description}`).join(\"\\n\")\n ) + TASK_DESCRIPTION_SUFFIX,\n schema: z.object({\n description: z\n .string()\n .describe(\"The task to execute with the selected agent\"),\n subagent_type: z\n .string()\n .describe(\n `Name of the agent to use. Available: ${subagents\n .map((a) => a.name)\n .join(\", \")}`\n ),\n }),\n }\n );\n}\n","/**\n * Prompt constants for Deep Agents\n *\n * All prompt strings ported from Python implementation with exact string content and formatting\n * to ensure 1:1 compatibility with the Python version.\n */\n\n/**\n * Description for the write_todos tool\n * Ported exactly from Python WRITE_TODOS_DESCRIPTION\n */\nexport const 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.\n\nWhen to Use This Tool\nUse this tool proactively in these scenarios:\n\nComplex multi-step tasks - When a task requires 3 or more distinct steps or actions\nNon-trivial and complex tasks - Tasks that require careful planning or multiple operations\nUser explicitly requests todo list - When the user directly asks you to use the todo list\nUser provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\nAfter receiving new instructions - Immediately capture user requirements as todos\nWhen 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\nAfter completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation\nWhen NOT to Use This Tool\nSkip using this tool when:\n\nThere is only a single, straightforward task\nThe task is trivial and tracking it provides no organizational benefit\nThe task can be completed in less than 3 trivial steps\nThe task is purely conversational or informational\nNOTE 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.\n\nExamples of When to Use the Todo List\n<example>\nUser: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!\nAssistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.\n*Creates todo list with the following items:*\n1. Create dark mode toggle component in Settings page\n2. Add dark mode state management (context/store)\n3. Implement CSS-in-JS styles for dark theme\n4. Update existing components to support theme switching\n5. Run tests and build process, addressing any failures or errors that occur\n*Begins working on the first task*\n<reasoning>\nThe assistant used the todo list because:\n1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes\n2. The user explicitly requested tests and build be run afterward\n3. The assistant inferred that tests and build need to pass by adding \"Ensure tests and build succeed\" as the final task\n</reasoning>\n</example>\n<example>\nUser: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.\nAssistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.\n*Creates todo list with the following items:*\n1. Define target audience and key messaging\n2. Create social media content calendar and posting schedule\n3. Design email marketing sequence and automation flows\n4. Draft press release and identify media contacts\n5. Set up tracking and analytics for campaign performance\n6. Create visual assets and brand materials\n7. Coordinate launch timeline and deliverables\n*Begins working on the first task*\n<reasoning>\nThe assistant used the todo list because:\n1. Marketing campaign planning involves multiple distinct channels and activities\n2. Each component requires careful coordination and planning\n3. The systematic approach ensures all aspects of the launch are covered\n4. Progress tracking helps maintain timeline and deliverables\n</reasoning>\n</example>\n<example>\nUser: Help me rename the function getCwd to getCurrentWorkingDirectory across my project\nAssistant: Let me first search through your codebase to find all occurrences of 'getCwd'.\n*Uses search tools to locate all instances of getCwd in the codebase*\nAssistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.\n*Creates todo list with specific items for each file that needs updating*\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant searched to understand the scope of the task\n2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps\n3. The todo list helps ensure every instance is tracked and updated systematically\n4. This approach prevents missing any occurrences and maintains consistency\n</reasoning>\n</example>\n<example>\nUser: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.\nAssistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.\n*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*\nLet's start with decluttering your desk space to create a clean foundation for the other organizational systems.\n<reasoning>\nThe assistant used the todo list because:\n1. The user provided multiple distinct organizational tasks\n2. Each area requires different approaches and careful planning\n3. Home organization benefits from systematic, step-by-step completion\n4. Progress tracking ensures all areas are addressed thoroughly\n</reasoning>\n</example>\nExamples of When NOT to Use the Todo List\n<example>\nUser: How do I print 'Hello World' in Python?\nAssistant: In Python, you can print \"Hello World\" with this simple code:\n\n\\`\\`\\`python\nprint(\"Hello World\")\n\\`\\`\\`\n\nThis will output the text \"Hello World\" to the console when executed.\n<reasoning>\nThe 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.\n</reasoning>\n</example>\n<example>\nUser: What's the best way to water houseplants?\nAssistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:\n\nCheck soil moisture by inserting your finger about 1-2 inches into the soil\nWater thoroughly when the top inch feels dry, allowing water to drain from the bottom\nUse room temperature water and water in the morning when possible\nAvoid overwatering, which is more harmful than underwatering for most plants\n\nDifferent plants have different needs, so it's important to research your specific varieties for optimal care.\n\n<reasoning>\nThe 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.\n</reasoning>\n</example>\n<example>\nUser: Can you add a comment to the calculateTotal function to explain what it does?\nAssistant: Sure, let me add a comment to the calculateTotal function to explain what it does.\n* Uses the Edit tool to add a comment to the calculateTotal function *\n<reasoning>\nThe 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.\n</reasoning>\n</example>\n<example>\nUser: What time is it in Tokyo right now?\nAssistant: I'll check the current time in Tokyo for you.\n\n*Searches for current time in Tokyo*\n\nThe current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.\n\n<reasoning>\nThe 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.\n</reasoning>\n</example>\nTask States and Management\nTask States: Use these states to track progress:\n\npending: Task not yet started\nin_progress: Currently working on (limit to ONE task at a time)\ncompleted: Task finished successfully\nTask Management:\n\nUpdate task status in real-time as you work\nMark tasks complete IMMEDIATELY after finishing (don't batch completions)\nOnly have ONE task in_progress at any time\nComplete current tasks before starting new ones\nRemove tasks that are no longer relevant from the list entirely\nTask Completion Requirements:\n\nONLY mark a task as completed when you have FULLY accomplished it\nIf you encounter errors, blockers, or cannot finish, keep the task as in_progress\nWhen blocked, create a new task describing what needs to be resolved\nNever mark a task as completed if:\nThere are unresolved issues or errors\nWork is partial or incomplete\nYou encountered blockers that prevent completion\nYou couldn't find necessary resources or dependencies\nQuality standards haven't been met\nTask Breakdown:\n\nCreate specific, actionable items\nBreak complex tasks into smaller, manageable steps\nUse clear, descriptive task names\nWhen in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`;\n\n/**\n * Prefix for task tool description\n * Ported exactly from Python TASK_DESCRIPTION_PREFIX\n */\nexport const TASK_DESCRIPTION_PREFIX = `Launch a new agent to handle complex, multi-step tasks autonomously.\n\nAvailable agent types and the tools they have access to:\n\ngeneral-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: *)\n{other_agents}\n`;\n\n/**\n * Suffix for task tool description\n * Ported exactly from Python TASK_DESCRIPTION_SUFFIX\n */\nexport const TASK_DESCRIPTION_SUFFIX = `When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\nWhen to use the Agent tool:\n\nWhen 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\")\nWhen NOT to use the Agent tool:\n\nIf 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\nIf you are searching for a specific term or definition within a known location, use the Glob tool instead, to find the match more quickly\nIf 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\nOther tasks that are not related to the agent descriptions above\nUsage notes:\n\nLaunch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\nWhen 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.\nEach 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.\nThe agent's outputs should generally be trusted\nClearly 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\nIf 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.\nExample usage:\n\n<example_agent_descriptions>\n\"content-reviewer\": use this agent after you are done creating significant content or documents\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n\"research-analyst\": use this agent to conduct thorough research on complex topics\n</example_agent_description>\n\n<example>\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the Write tool to write a function that checks if a number is prime\nassistant: I'm going to use the Write tool to write the following code:\n<code>\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n</code>\n<commentary>\nSince significant content was created and the task was completed, now use the content-reviewer agent to review the work\n</commentary>\nassistant: Now let me use the content-reviewer agent to review the code\nassistant: Uses the Task tool to launch with the content-reviewer agent\n</example>\n<example>\nuser: \"Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?\"\n<commentary>\nThis is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis\n</commentary>\nassistant: 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.\nassistant: 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\n</example>\n<example>\nuser: \"Hello\"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: \"I'm going to use the Task tool to launch with the greeting-responder agent\"\n</example>`;\n\n/**\n * Description for the edit_file tool\n * Ported exactly from Python EDIT_DESCRIPTION\n */\nexport const EDIT_DESCRIPTION = `Performs exact string replacements in files.\nUsage:\n\nYou 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.\nWhen 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.\nALWAYS prefer editing existing files. NEVER write new files unless explicitly required.\nOnly use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\nThe 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.\nUse replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;\n\n/**\n * Description for the read_file tool\n * Ported exactly from Python TOOL_DESCRIPTION\n */\nexport const 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.\nUsage:\n\nThe file_path parameter must be an absolute path, not a relative path\nBy default, it reads up to 2000 lines starting from the beginning of the file\nYou 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\nAny lines longer than 2000 characters will be truncated\nResults are returned using cat -n format, with line numbers starting at 1\nYou 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.\nIf you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;\n","/**\n * Tool functions for Deep Agents\n *\n * TypeScript versions of all tools using @langchain/core/tools tool() function.\n * Uses getCurrentTaskInput() for state access and returns Command objects for state updates.\n * Implements mock filesystem operations using state.files similar to Python version.\n */\n\nimport { tool, ToolRunnableConfig } from \"@langchain/core/tools\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport { z } from \"zod\";\nimport {\n WRITE_TODOS_DESCRIPTION,\n EDIT_DESCRIPTION,\n TOOL_DESCRIPTION,\n} from \"./prompts\";\nimport { DeepAgentStateType } from \"./types\";\nimport { genUIMarkdown } from \"@util/genUIMarkdown\";\n\n/**\n * Write todos tool - manages todo list with Command return\n * Uses getCurrentTaskInput() instead of Python's InjectedState\n */\nexport const writeTodos = tool(\n (input, config: ToolRunnableConfig) => {\n return new Command({\n update: {\n todos: input.todos,\n messages: [\n new ToolMessage({\n content: genUIMarkdown(\"todo_list\", input.todos),\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n },\n\n {\n name: \"write_todos\",\n description: WRITE_TODOS_DESCRIPTION,\n schema: z.object({\n todos: z\n .array(\n z.object({\n content: z.string().describe(\"Content of the todo item\"),\n status: z\n .enum([\"pending\", \"in_progress\", \"completed\"])\n .describe(\"Status of the todo\"),\n })\n )\n .describe(\"List of todo items to update\"),\n }),\n }\n);\n\n/**\n * List files tool - returns list of files from state.files\n * Equivalent to Python's ls function\n */\nexport const ls = tool(\n () => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = state.files || {};\n return Object.keys(files);\n },\n {\n name: \"ls\",\n description: \"List all files in the mock filesystem\",\n schema: z.object({}),\n }\n);\n\n/**\n * Read file tool - reads from mock filesystem in state.files\n * Matches Python read_file function behavior exactly\n */\nexport const readFile = tool(\n (input: { file_path: string; offset?: number; limit?: number }) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = state.files || {};\n const { file_path, offset = 0, limit = 2000 } = input;\n\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get file content\n const content = mockFilesystem[file_path];\n\n // Handle empty file\n if (!content || content.trim() === \"\") {\n return \"System reminder: File exists but has empty contents\";\n }\n\n // Split content into lines\n const lines = content.split(\"\\n\");\n\n // Apply line offset and limit\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n // Handle case where offset is beyond file length\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n // Format output with line numbers (cat -n format)\n const resultLines: string[] = [];\n for (let i = startIdx; i < endIdx; i++) {\n let lineContent = lines[i];\n\n // Truncate lines longer than 2000 characters\n if (lineContent.length > 2000) {\n lineContent = lineContent.substring(0, 2000);\n }\n\n // Line numbers start at 1, so add 1 to the index\n const lineNumber = i + 1;\n resultLines.push(`${lineNumber.toString().padStart(6)}\t${lineContent}`);\n }\n\n return resultLines.join(\"\\n\");\n },\n {\n name: \"read_file\",\n description: TOOL_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to read\"),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from\"),\n limit: z\n .number()\n .optional()\n .default(2000)\n .describe(\"Maximum number of lines to read\"),\n }),\n }\n);\n\n/**\n * Write file tool - writes to mock filesystem with Command return\n * Matches Python write_file function behavior exactly\n */\nexport const writeFile = tool(\n (\n input: { file_path: string; content: string },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const files = { ...(state.files || {}) };\n files[input.file_path] = input.content;\n\n return new Command({\n update: {\n files: files,\n messages: [\n new ToolMessage({\n content: `Updated file ${input.file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n },\n {\n name: \"write_file\",\n description: \"Write content to a file in the mock filesystem\",\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to write\"),\n content: z.string().describe(\"Content to write to the file\"),\n }),\n }\n);\n\n/**\n * Edit file tool - edits files in mock filesystem with Command return\n * Matches Python edit_file function behavior exactly\n */\nexport const editFile = tool(\n (\n input: {\n file_path: string;\n old_string: string;\n new_string: string;\n replace_all?: boolean;\n },\n config: ToolRunnableConfig\n ) => {\n const state = getCurrentTaskInput<DeepAgentStateType>();\n const mockFilesystem = { ...(state.files || {}) };\n const { file_path, old_string, new_string, replace_all = false } = input;\n\n // Check if file exists in mock filesystem\n if (!(file_path in mockFilesystem)) {\n return `Error: File '${file_path}' not found`;\n }\n\n // Get current file content\n const content = mockFilesystem[file_path];\n\n // Check if old_string exists in the file\n if (!content.includes(old_string)) {\n return `Error: String not found in file: '${old_string}'`;\n }\n\n // If not replace_all, check for uniqueness\n if (!replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n const occurrences = (\n content.match(new RegExp(escapedOldString, \"g\")) || []\n ).length;\n if (occurrences > 1) {\n 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.`;\n } else if (occurrences === 0) {\n return `Error: String not found in file: '${old_string}'`;\n }\n }\n\n // Perform the replacement\n let newContent: string;\n\n if (replace_all) {\n const escapedOldString = old_string.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n \"\\\\$&\"\n );\n newContent = content.replace(\n new RegExp(escapedOldString, \"g\"),\n new_string\n );\n } else {\n newContent = content.replace(old_string, new_string);\n }\n\n // Update the mock filesystem\n mockFilesystem[file_path] = newContent;\n\n return new Command({\n update: {\n files: mockFilesystem,\n messages: [\n new ToolMessage({\n content: `Updated file ${file_path}`,\n tool_call_id: config.toolCall?.id as string,\n }),\n ],\n },\n });\n },\n {\n name: \"edit_file\",\n description: EDIT_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Absolute path to the file to edit\"),\n old_string: z\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z.string().describe(\"String to replace with\"),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n }\n);\n","/**\n * State definitions for Deep Agents\n *\n * TypeScript equivalents of the Python state classes using LangGraph's Annotation.Root() pattern.\n * Defines Todo interface and DeepAgentState using MessagesAnnotation as base with proper reducer functions.\n */\n\nimport \"@langchain/langgraph/zod\";\nimport { MessagesZodState } from \"@langchain/langgraph\";\nimport type { Todo } from \"./types\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\nimport { z } from \"zod\";\n\n/**\n * File reducer function that merges file dictionaries\n * Matches the Python file_reducer function behavior exactly\n */\nexport function fileReducer(\n left: Record<string, string> | null | undefined,\n right: Record<string, string> | null | undefined\n): Record<string, string> {\n if (left == null) {\n return right || {};\n } else if (right == null) {\n return left;\n } else {\n return { ...left, ...right };\n }\n}\n\n/**\n * Todo reducer function that replaces the entire todo list\n * This matches the Python behavior where todos are completely replaced\n */\nexport function todoReducer(\n left: Todo[] | null | undefined,\n right: Todo[] | null | undefined\n): Todo[] {\n if (right != null) {\n return right;\n }\n return left || [];\n}\n\n/**\n * DeepAgentState using LangGraph's Annotation.Root() pattern\n * Extends MessagesAnnotation (equivalent to Python's AgentState) with todos and files channels\n */\nexport const DeepAgentState = MessagesZodState.extend({\n todos: withLangGraph(z.custom<Todo[]>(), {\n reducer: {\n schema: z.custom<Todo[]>(),\n fn: todoReducer,\n },\n }),\n\n files: withLangGraph(z.custom<Record<string, string>>(), {\n reducer: {\n schema: z.custom<Record<string, string>>(),\n fn: fileReducer,\n },\n }),\n});\n","/**\n * Main createDeepAgent function for Deep Agents\n *\n * Main entry point for creating deep agents with TypeScript types for all parameters:\n * tools, instructions, model, subagents, and stateSchema. Combines built-in tools with\n * provided tools, creates task tool using createTaskTool(), and returns createReactAgent\n * with proper configuration. Ensures exact parameter matching and behavior with Python version.\n */\n\n// import \"@langchain/anthropic/zod\";\nimport { createTaskTool } from \"./subAgent\";\nimport { writeTodos, readFile, writeFile, editFile, ls } from \"./tools\";\nimport type { CreateDeepAgentParams, PostModelHook } from \"./types\";\nimport type { StructuredTool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\nimport { DeepAgentState } from \"./state\";\nimport { getModelLattice } from \"../model_lattice/ModelLatticeManager\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\nimport { getCheckpointSaver } from \"@memory_lattice/MemoryLatticeManager\";\nimport { createInterruptHook } from \"./createInterruptHook\";\n/**\n * Base prompt that provides instructions about available tools\n * Ported from Python implementation to ensure consistent behavior\n */\nconst BASE_PROMPT = `You have access to a number of standard tools\n\n## \\`write_todos\\`\n\nYou 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.\nThese 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.\n\nIt 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.\n## \\`task\\`\n\n- When doing web search, prefer to use the \\`task\\` tool in order to reduce context usage.`;\n\n/**\n * Built-in tools that are always available in Deep Agents\n */\nconst BUILTIN_TOOLS: StructuredTool[] = [\n writeTodos,\n readFile,\n writeFile,\n editFile,\n ls,\n];\n\n/**\n * Create a Deep Agent with TypeScript types for all parameters.\n * Combines built-in tools with provided tools, creates task tool using createTaskTool(),\n * and returns createReactAgent with proper configuration.\n * Ensures exact parameter matching and behavior with Python version.\n */\nexport function createDeepAgent<\n StateSchema extends z.ZodObject<any, any, any, any, any>\n>(params: CreateDeepAgentParams<StateSchema> = {}) {\n const {\n tools = [],\n instructions,\n model = getModelLattice(\"default\")?.client,\n subagents = [],\n } = params;\n\n if (!model) {\n throw new Error(\"Model not found\");\n }\n\n const stateSchema = params.stateSchema\n ? DeepAgentState.extend(params.stateSchema.shape)\n : DeepAgentState;\n\n // Combine built-in tools with provided tools\n const allTools: StructuredTool[] = [...BUILTIN_TOOLS, ...tools];\n\n // Create task tool using createTaskTool() if subagents are provided\n\n if (subagents.length > 0) {\n // Create tools map for task tool creation\n const toolsMap: Record<string, StructuredTool> = {};\n for (const tool of allTools) {\n if (tool.name) {\n toolsMap[tool.name] = tool;\n }\n }\n\n const taskTool = createTaskTool({\n subagents,\n tools: toolsMap,\n model,\n stateSchema,\n });\n allTools.push(taskTool);\n }\n\n // Combine instructions with base prompt like Python implementation\n const finalInstructions = instructions\n ? instructions + BASE_PROMPT\n : BASE_PROMPT;\n\n // Return createReactAgent with proper configuration\n return createReactAgent<typeof stateSchema, Record<string, any>>({\n llm: model,\n tools: allTools,\n stateSchema: stateSchema,\n prompt: finalInstructions,\n checkpointer: getCheckpointSaver(\"default\"),\n });\n}\n","/**\n * Deep Agent Graph Builder\n *\n * 实现 Deep Agent 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { DynamicTool } from \"@langchain/core/tools\";\nimport { createDeepAgent } from \"../../deep_agent\";\nimport { AgentLattice, AgentBuildParams } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { getToolsFromConfig } from \"@axiom-lattice/protocols\";\n\nexport class DeepAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 构建Deep Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(\n agentLattice: AgentLattice,\n params: AgentBuildParams\n ): CompiledStateGraph<any, any, any, any, any> {\n const tools = params.tools\n .map((t) => {\n const toolClient = getToolClient(t.key);\n\n return toolClient;\n })\n .filter((tool) => tool !== undefined);\n\n return createDeepAgent({\n tools: tools,\n model: params.model,\n stateSchema: params.stateSchema,\n instructions: params.prompt,\n subagents: params.subAgents.map((sa) => sa.config),\n });\n }\n}\n","import {\n Annotation,\n BaseCheckpointSaver,\n END,\n GraphInterrupt,\n LangGraphRunnableConfig,\n START,\n StateGraph,\n messagesStateReducer,\n} from \"@langchain/langgraph\";\nimport {\n BaseMessage,\n HumanMessage,\n mergeMessageRuns,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod\";\nimport { ModelLattice } from \"./model_lattice/ModelLattice\";\nimport { Logger } from \"@logger/Logger\";\nimport { StateBaseType } from \"./types\";\nimport { returnToolResponse } from \"./util/returnToolResponse\";\nimport { returnAIResponse } from \"./util/returnAIResponse\";\nimport { getLastHumanMessageData } from \"./util/getLastHumanMessageData\";\nimport { tool } from \"@langchain/core/tools\";\nimport { MemoryManager } from \"./util/PGMemory\";\nimport { getModelLattice } from \"./model_lattice/ModelLatticeManager\";\nimport { createReactAgent } from \"@langchain/langgraph/prebuilt\";\n\n/**\n * Plan-and-Execute Agent 状态定义\n */\nexport const PlanExecuteState = Annotation.Root({\n // 输入\n input: Annotation<string>({\n reducer: (x, y) => y ?? x ?? \"\",\n }),\n // 计划步骤列表\n plan: Annotation<string[]>({\n reducer: (x, y) => y ?? x ?? [],\n }),\n // 已执行的步骤 [步骤名称, 执行结果]\n pastSteps: Annotation<[string, string][]>({\n reducer: (x, y) => x.concat(y),\n default: () => [],\n }),\n // 最终响应\n response: Annotation<string | undefined>({\n reducer: (x, y) => y ?? x,\n }),\n // 错误信息\n error: Annotation<string | undefined>({\n reducer: (x, y) => y ?? x,\n }),\n // 继承基础状态\n \"x-tenant-id\": Annotation<number>(),\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n});\n\n/**\n * 计划工具的结构化输出模式\n */\nconst planSchema = z.object({\n steps: z.array(z.string()).describe(\"需要执行的步骤列表,应按照执行顺序排序\"),\n});\n\n/**\n * 响应工具的结构化输出模式\n */\nconst responseSchema = z.object({\n response: z\n .string()\n .describe(\"给用户的最终响应,如果不需要执行步骤,则返回这个字段\"),\n});\n\n/**\n * Plan-and-Execute Agent 配置接口\n */\nexport interface PlanExecuteAgentConfig {\n name: string;\n description: string;\n tools?: any[]; // 执行器可使用的工具\n checkpointer?: false | BaseCheckpointSaver<number>;\n llmManager?: ModelLattice;\n logger?: Logger;\n maxSteps?: number; // 最大步骤数限制\n prompt?: string;\n}\n\n/**\n * 创建 Plan-and-Execute Agent\n *\n * 这是一个规划-执行风格的代理,首先制定多步骤计划,然后逐一执行。\n * 在完成每个任务后,会重新评估计划并根据需要进行修改。\n *\n * 相比传统的ReAct风格代理的优势:\n * 1. 明确的长期规划能力\n * 2. 可以在执行步骤使用较小的模型,只在规划步骤使用大模型\n * 3. 更好的任务分解和执行追踪\n */\nexport function createPlanExecuteAgent(config: PlanExecuteAgentConfig) {\n const {\n name,\n description,\n tools: executorTools = [],\n checkpointer,\n llmManager,\n logger,\n maxSteps = 10,\n prompt,\n } = config;\n\n const agentLogger =\n logger || new Logger({ name: `PlanExecuteAgent:${name}` });\n const llm = llmManager || getModelLattice(\"default\")?.client;\n\n if (!llm) {\n throw new Error(\"LLM not found\");\n }\n\n agentLogger.info(`初始化Plan-Execute代理: ${name}`, {\n description,\n maxSteps,\n toolsCount: executorTools.length,\n });\n\n const agentExecutor = createReactAgent({\n tools: executorTools,\n llm: llm,\n });\n\n /**\n * 规划步骤:创建初始计划\n */\n async function planStep(\n state: typeof PlanExecuteState.State,\n config: LangGraphRunnableConfig\n ): Promise<Partial<typeof PlanExecuteState.State>> {\n const input =\n state.input || getLastHumanMessageData(state.messages)?.content;\n\n const plannerPrompt = `${\n prompt || \"\"\n }\\n针对给定的目标,制定一个简单的分步计划。\n这个计划应该包含独立的任务,如果正确执行将会得到正确的答案。不要添加多余的步骤。\n最后一步的结果应该是最终答案。确保每一步都有所需的所有信息 - 不要跳过步骤。\n\n可以使用的工具如下:\n${executorTools.map((tool) => tool.name).join(\"\\n\")}\n\n目标: ${input}`;\n\n try {\n const planResult = (await llm.invokeWithStructuredOutput(\n [new HumanMessage(plannerPrompt)],\n planSchema\n )) as { steps: string[] };\n\n const { messages } = await returnToolResponse(config, {\n title: \"我的计划\",\n content: planResult.steps.map((step: string) => step).join(\"\\n\\n\"),\n status: \"success\",\n });\n\n agentLogger.info(\"计划制定完成\", { plan: planResult.steps });\n\n return {\n input: input as string,\n plan: planResult.steps,\n error: undefined,\n messages,\n };\n } catch (error) {\n const errorMsg = `计划制定失败: ${\n error instanceof Error ? error.message : \"未知错误\"\n }`;\n agentLogger.error(errorMsg, { error });\n return {\n error: errorMsg,\n };\n }\n }\n\n /**\n * 执行步骤:执行计划中的第一个任务\n */\n async function executeStep(\n state: typeof PlanExecuteState.State,\n config: LangGraphRunnableConfig\n ): Promise<Partial<typeof PlanExecuteState.State>> {\n if (!state.plan || state.plan.length === 0) {\n agentLogger.warn(\"没有可执行的任务\");\n return { error: \"没有可执行的任务\" };\n }\n\n const currentTask = state.plan[0];\n agentLogger.info(\"开始执行任务\", { task: currentTask });\n\n try {\n // 这里可以集成真实的工具执行器\n // 目前使用LLM来模拟执行\n const executorPrompt = `执行以下任务并提供结果:\n\n任务: ${currentTask}\n\n上下文信息:\n- 原始目标: ${state.input}\n- 已完成的步骤: ${state.pastSteps\n .map(([step, result]) => `${step}: ${result}`)\n .join(\"\\n\")}\n\n请提供执行此任务的详细结果。`;\n\n const executionResult = await agentExecutor.invoke({\n messages: [new HumanMessage(executorPrompt)],\n });\n\n const resultContent =\n executionResult.messages[executionResult.messages.length - 1].content;\n\n // 生成工具响应消息\n // const { messages } = await returnToolResponse(config, {\n // title: `执行任务: ${currentTask}`,\n // content: resultContent as string,\n // status: \"success\",\n // });\n\n return {\n pastSteps: [[currentTask, resultContent]] as [string, string][],\n plan: state.plan.slice(1), // 移除已执行的任务\n //messages,\n error: undefined,\n };\n } catch (error) {\n if (error instanceof GraphInterrupt) {\n throw error;\n }\n const errorMsg = `任务执行失败: ${\n error instanceof Error ? error.message : \"未知错误\"\n }`;\n agentLogger.error(errorMsg, { task: currentTask, error });\n\n // const { messages } = await returnToolResponse(config, {\n // title: `执行任务失败: ${currentTask}`,\n // content: errorMsg,\n // status: \"error\",\n // });\n\n return {\n error: errorMsg,\n //messages,\n };\n }\n }\n\n const responseTool = tool(\n ({ response }: { response: string }) => {\n return response;\n },\n {\n name: \"response\",\n description: \"Respond to the user.\",\n schema: responseSchema,\n returnDirect: true,\n }\n );\n\n const planTool = tool(\n ({ steps }: { steps: string[] }) => {\n return steps.join(\"\\n\\n\");\n },\n {\n name: \"plan\",\n description: \"This tool is used to plan the steps to follow.\",\n schema: planSchema,\n returnDirect: true,\n }\n );\n\n const replanAgent = createReactAgent({\n tools: [responseTool, planTool],\n llm: llm,\n });\n /**\n * 重新规划步骤:根据执行结果调整计划\n */\n async function replanStep(\n state: typeof PlanExecuteState.State,\n config: LangGraphRunnableConfig\n ): Promise<Partial<typeof PlanExecuteState.State>> {\n agentLogger.info(\"开始重新规划\");\n\n const replannerPrompt = `${\n prompt || \"\"\n }\\n针对给定的目标,根据已执行的步骤来更新计划。\n这个计划应该包含独立的任务,如果正确执行将会得到正确的答案。不要添加多余的步骤。\n最后一步的结果应该是最终答案。确保每一步都有所需的所有信息 - 不要跳过步骤。\n\n你的目标是:\n${state.input}\n\n你的原始计划是:\n${state.plan.join(\"\\n\")}\n\n你目前已经完成了以下步骤:\n${state.pastSteps.map(([step, result]) => `${step}: ${result}`).join(\"\\n\")}\n\nUpdate 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.\nOtherwise, fill out the plan.\nOnly add steps to the plan that still NEED to be done. Do not return previously done steps as part of the plan.`;\n\n try {\n // 首先尝试获取最终响应\n const responseResult = await replanAgent.invoke({\n messages: [new HumanMessage(replannerPrompt)],\n });\n\n const toolCall =\n responseResult.messages[responseResult.messages.length - 1];\n\n if (toolCall?.name == \"response\") {\n agentLogger.info(\"任务完成,提供最终响应\");\n\n const { messages } = await returnAIResponse(\n config,\n toolCall.content as string\n );\n\n return {\n response: toolCall.content as string,\n messages,\n error: undefined,\n };\n } else if (toolCall?.name == \"plan\") {\n let messages: any[] = [];\n if (toolCall.content?.length > 0) {\n messages = await returnToolResponse(config, {\n title: \"新的计划\",\n content: toolCall.content as string,\n status: \"success\",\n }).messages;\n }\n agentLogger.info(\"计划更新完成\", { newPlan: toolCall.content });\n return {\n messages,\n plan: (toolCall.content as string).split(\"\\n\\n\"),\n error: undefined,\n };\n } else {\n return {\n error: \"重新规划失败\",\n };\n }\n } catch (error) {\n if (error instanceof GraphInterrupt) {\n throw error;\n }\n const errorMsg = `重新规划失败: ${\n error instanceof Error ? error.message : \"未知错误\"\n }`;\n agentLogger.error(errorMsg, { error });\n return {\n error: errorMsg,\n };\n }\n }\n\n /**\n * 判断是否应该结束执行\n */\n function shouldEnd(state: typeof PlanExecuteState.State): \"end\" | \"continue\" {\n if (state.error) {\n agentLogger.warn(\"因错误结束执行\", { error: state.error });\n return \"end\";\n }\n\n if (state.response) {\n agentLogger.info(\"任务完成,结束执行\");\n return \"end\";\n }\n\n if (state.pastSteps.length >= maxSteps) {\n agentLogger.warn(\"达到最大步骤数限制,结束执行\", {\n maxSteps,\n currentSteps: state.pastSteps.length,\n });\n return \"end\";\n }\n\n if (!state.plan || state.plan.length === 0) {\n agentLogger.info(\"计划为空,结束执行\");\n return \"end\";\n }\n\n return \"continue\";\n }\n\n // 构建状态图\n const workflow = new StateGraph(PlanExecuteState)\n .addNode(\"planner\", planStep)\n .addNode(\"executor\", executeStep)\n .addNode(\"replanner\", replanStep)\n .addEdge(START, \"planner\")\n .addEdge(\"planner\", \"executor\")\n .addEdge(\"executor\", \"replanner\")\n .addConditionalEdges(\"replanner\", shouldEnd, {\n end: END,\n continue: \"executor\",\n });\n\n // 编译图\n //const memory = MemoryManager.getInstance();\n const compiledGraph = workflow.compile({\n checkpointer: checkpointer || MemoryManager.getInstance(),\n name: `PlanExecuteAgent:${name}`,\n });\n\n agentLogger.info(`Plan-Execute代理编译完成: ${name}`);\n\n return {\n /**\n * 执行代理\n */\n invoke: async (\n input: { input: string; \"x-tenant-id\": number },\n config?: LangGraphRunnableConfig\n ) => {\n agentLogger.info(`开始执行Plan-Execute代理: ${name}`, {\n input: input.input,\n });\n\n try {\n const result = await compiledGraph.invoke(input, config);\n agentLogger.info(`代理执行完成: ${name}`);\n return result;\n } catch (error) {\n agentLogger.error(\n `代理执行失败: ${name}`,\n error instanceof Error ? error : { error }\n );\n throw error;\n }\n },\n\n /**\n * 流式执行代理\n */\n stream: async (\n input: { input: string; \"x-tenant-id\": number },\n config?: LangGraphRunnableConfig\n ) => {\n agentLogger.info(`开始流式执行Plan-Execute代理: ${name}`, {\n input: input.input,\n });\n return compiledGraph.stream(input, config);\n },\n\n /**\n * 获取代理信息\n */\n getInfo: () => ({\n name,\n description,\n type: \"PlanExecuteAgent\",\n toolsCount: executorTools.length,\n maxSteps,\n }),\n\n /**\n * 获取编译后的图\n */\n getCompiledGraph: () => compiledGraph,\n };\n}\n","import pino from \"pino\";\nimport \"pino-pretty\";\nimport \"pino-roll\";\nimport { AsyncLocalStorage } from \"async_hooks\";\n\nexport interface LoggerContext {\n \"x-user-id\"?: string;\n \"x-tenant-id\"?: string;\n \"x-request-id\"?: string;\n \"x-task-id\"?: string;\n \"x-thread-id\"?: string;\n}\n\nexport interface LoggerOptions {\n name?: string;\n serviceName?: string;\n context?: LoggerContext;\n}\n\n/**\n * 单例的Pino日志工厂类,管理底层pino实例\n */\nclass PinoLoggerFactory {\n private static instance: PinoLoggerFactory;\n private pinoLogger: pino.Logger;\n\n private constructor() {\n const isProd = process.env.NODE_ENV === \"production\";\n\n const loggerConfig: pino.LoggerOptions = {\n // 自定义时间戳格式\n timestamp: () => `,\"@timestamp\":\"${new Date().toISOString()}\"`,\n\n // 关闭默认的时间戳键\n base: {\n \"@version\": \"1\",\n app_name: \"lattice\",\n service_name: \"lattice/graph-server\",\n thread_name: \"main\",\n logger_name: \"lattice-graph-logger\",\n },\n\n formatters: {\n level: (label, number) => {\n return {\n level: label.toUpperCase(),\n level_value: number * 1000,\n };\n },\n },\n };\n\n // 生产环境使用文件日志\n if (isProd) {\n try {\n this.pinoLogger = pino(\n loggerConfig,\n pino.transport({\n target: \"pino-roll\",\n options: {\n file: \"./logs/fin_ai_graph_server\",\n frequency: \"daily\",\n mkdir: true,\n },\n })\n );\n } catch (error) {\n console.error(\n \"无法初始化 pino-roll 日志记录器,回退到控制台日志\",\n error\n );\n // 回退到开发环境的配置\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n } else {\n // 开发环境使用格式化输出\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n }\n\n public static getInstance(): PinoLoggerFactory {\n if (!PinoLoggerFactory.instance) {\n PinoLoggerFactory.instance = new PinoLoggerFactory();\n }\n return PinoLoggerFactory.instance;\n }\n\n public getPinoLogger(): pino.Logger {\n return this.pinoLogger;\n }\n}\n\n/**\n * Logger类,可以创建多个实例,每个实例有自己的上下文\n */\nexport class Logger {\n private context: LoggerContext;\n private name: string;\n private serviceName: string;\n\n constructor(options?: LoggerOptions) {\n this.context = options?.context || {};\n this.name = options?.name || \"lattice-graph-logger\";\n this.serviceName = options?.serviceName || \"lattice/graph-server\";\n }\n\n /**\n * 获取合并了上下文的日志对象\n * @param additionalContext 额外的上下文数据\n * @returns 带有上下文的pino日志对象\n */\n private getContextualLogger(additionalContext?: object): pino.Logger {\n const pinoLogger = PinoLoggerFactory.getInstance().getPinoLogger();\n\n // 合并Logger实例的上下文和额外上下文\n const contextObj = {\n \"x-user-id\": this.context[\"x-user-id\"] || \"\",\n \"x-tenant-id\": this.context[\"x-tenant-id\"] || \"\",\n \"x-request-id\": this.context[\"x-request-id\"] || \"\",\n \"x-task-id\": this.context[\"x-task-id\"] || \"\",\n \"x-thread-id\": this.context[\"x-thread-id\"] || \"\",\n service_name: this.serviceName,\n logger_name: this.name,\n ...additionalContext,\n };\n\n // 创建带有上下文的子日志记录器\n return pinoLogger.child(contextObj);\n }\n\n info(msg: string, obj?: object): void {\n this.getContextualLogger(obj).info(msg);\n }\n\n error(msg: string, obj?: object | Error): void {\n this.getContextualLogger(obj).error(msg);\n }\n\n warn(msg: string, obj?: object): void {\n this.getContextualLogger(obj).warn(msg);\n }\n\n debug(msg: string, obj?: object): void {\n this.getContextualLogger(obj).debug(msg);\n }\n\n /**\n * 更新Logger实例的上下文\n */\n updateContext(context: Partial<LoggerContext>): void {\n this.context = {\n ...this.context,\n ...context,\n };\n }\n\n /**\n * 创建一个新的Logger实例,继承当前Logger的上下文\n */\n child(options: Partial<LoggerOptions>): Logger {\n return new Logger({\n name: options.name || this.name,\n serviceName: options.serviceName || this.serviceName,\n context: {\n ...this.context,\n ...options.context,\n },\n });\n }\n}\n","import { ToolMessage } from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { v4 } from \"uuid\";\nimport { genUIMarkdown } from \"./genUIMarkdown\";\n\nexport const returnToolResponse = (\n config: LangGraphRunnableConfig,\n think: {\n think_id?: string; // 思考的id,为了解决思考过程分组的问题\n title?: string;\n content: string;\n status?: \"success\" | \"error\";\n type?: string;\n data?: Record<string, any>;\n }\n) => {\n const { think_id = v4(), content, title, status, type, data } = think;\n const contents = type\n ? [title, content, genUIMarkdown(type, data)]\n : [title, content];\n const message = {\n messages: [\n new ToolMessage({\n content: contents.filter((item) => item).join(\"\\n\\n\"),\n tool_call_id: config.configurable?.run_id + \"_tool_\" + think_id,\n status: status || \"success\",\n }),\n ],\n };\n\n return message;\n};\n","import { AIMessage } from \"@langchain/core/messages\";\nimport { LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { v4 } from \"uuid\";\nimport { genUIMarkdown } from \"./genUIMarkdown\";\n\nexport const returnAIResponse = (\n config: LangGraphRunnableConfig,\n content: string,\n type?: string,\n data?: Record<string, any>\n) => {\n const contents = type\n ? [content, genUIMarkdown(type, data)].join(\"\\n\")\n : content;\n const message = {\n messages: [\n new AIMessage({\n content: contents,\n }),\n // {\n // id: v4(),\n // role: \"ai\",\n // content: contents,\n // type: \"message\",\n // }, // 旧的message\n ],\n };\n // config.writer?.(message);\n return message;\n};\n","import {\n BaseMessage,\n HumanMessage,\n isHumanMessage,\n} from \"@langchain/core/messages\";\nexport type UserFile = {\n id: number;\n name: string;\n type?: string;\n path?: string;\n};\nexport type UserFileZip = {\n id: number;\n name: string;\n files: UserFile[];\n type?: \"application/zip\" | \"application/rar\";\n totalFiles?: number;\n processedFiles?: number;\n skippedFiles?: number;\n};\n\nexport const isCompressedFile = (fileType: string): boolean => {\n return fileType === \"application/zip\" || fileType === \"application/rar\";\n};\n\nexport const getLastHumanMessageData = (messages: BaseMessage[]) => {\n // 从最后一条消息开始向前查找第一个人类消息\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isHumanMessage(message)) {\n const files = message?.additional_kwargs?.files as UserFile[];\n return {\n files,\n content: message?.content,\n };\n }\n }\n\n // 如果没有找到任何人类消息,返回 null\n return null;\n};\n","import { MemorySaver } from \"@langchain/langgraph\";\nimport { PostgresSaver } from \"@langchain/langgraph-checkpoint-postgres\";\nimport dotenv from \"dotenv\";\n\nconst globalMemory = PostgresSaver.fromConnString(process.env.DATABASE_URL!);\n\nconst memory = new MemorySaver();\n// 创建一个管理器来访问这个实例\nexport class MemoryManager {\n private static instance: MemorySaver = memory;\n\n static getInstance(): MemorySaver {\n return MemoryManager.instance;\n }\n}\n//MemoryManager.getInstance().setup();\n","/**\n * Plan Execute Agent Graph Builder\n *\n * 实现 Plan Execute 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { DynamicTool } from \"@langchain/core/tools\";\nimport { AgentLattice, AgentBuildParams } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { createPlanExecuteAgent } from \"@createPlanExecuteAgent\";\n\nexport class PlanExecuteAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 构建Plan Execute Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(\n agentLattice: AgentLattice,\n params: AgentBuildParams\n ): CompiledStateGraph<any, any, any, any, any> {\n // 创建符合 DynamicTool 接口的工具对象\n const tools = params.tools\n .map((t) => {\n // 使用 DynamicTool 构造工具对象\n const tool = getToolClient(t.key);\n return tool;\n })\n .filter((tool) => tool !== undefined);\n\n // 由于createPlanExecuteAgent的返回类型与CompiledStateGraph不兼容\n // 这里我们使用createAgentExecutor作为替代方案\n const agent = createPlanExecuteAgent({\n llmManager: params.model,\n tools: tools,\n prompt: params.prompt,\n name: agentLattice.config.name,\n description: agentLattice.config.description,\n });\n return agent.getCompiledGraph();\n }\n}\n","/**\n * Agent Graph Builder Factory\n *\n * 工厂类,根据Agent类型创建对应的Builder\n */\n\nimport { AgentType } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { ReActAgentGraphBuilder } from \"./ReActAgentGraphBuilder\";\nimport { DeepAgentGraphBuilder } from \"./DeepAgentGraphBuilder\";\nimport { PlanExecuteAgentGraphBuilder } from \"./PlanExecuteAgentGraphBuilder\";\n\nexport class AgentGraphBuilderFactory {\n // 单例模式\n private static instance: AgentGraphBuilderFactory;\n\n // Builder缓存\n private builders: Map<AgentType, AgentGraphBuilder>;\n\n private constructor() {\n this.builders = new Map();\n this.registerDefaultBuilders();\n }\n\n /**\n * 获取单例实例\n */\n public static getInstance(): AgentGraphBuilderFactory {\n if (!AgentGraphBuilderFactory.instance) {\n AgentGraphBuilderFactory.instance = new AgentGraphBuilderFactory();\n }\n return AgentGraphBuilderFactory.instance;\n }\n\n /**\n * 注册默认的Builder\n */\n private registerDefaultBuilders(): void {\n this.builders.set(AgentType.REACT, new ReActAgentGraphBuilder());\n this.builders.set(AgentType.DEEP_AGENT, new DeepAgentGraphBuilder());\n this.builders.set(\n AgentType.PLAN_EXECUTE,\n new PlanExecuteAgentGraphBuilder()\n );\n }\n\n /**\n * 注册自定义Builder\n *\n * @param type Agent类型\n * @param builder Builder实例\n */\n public registerBuilder(type: AgentType, builder: AgentGraphBuilder): void {\n this.builders.set(type, builder);\n }\n\n /**\n * 获取Builder\n *\n * @param type Agent类型\n * @returns 返回对应的Builder\n */\n public getBuilder(type: AgentType): AgentGraphBuilder {\n const builder = this.builders.get(type);\n if (!builder) {\n throw new Error(`不支持的Agent类型: ${type}`);\n }\n return builder;\n }\n}\n","/**\n * Agent parameters builder\n *\n * responsible for preparing the parameters required for building the Agent\n */\n\nimport { toolLatticeManager } from \"../../tool_lattice/ToolLatticeManager\";\nimport { modelLatticeManager } from \"../../model_lattice/ModelLatticeManager\";\nimport { AgentLattice, AgentBuildParams, GraphBuildOptions } from \"../types\";\nimport {\n getToolsFromConfig,\n getSubAgentsFromConfig,\n isDeepAgentConfig,\n AgentConfig,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * Get Agent Lattice function type\n */\nexport type GetAgentLatticeFunction = (key: string) => AgentLattice | undefined;\n\n/**\n * Agent parameters builder\n */\nexport class AgentParamsBuilder {\n private getAgentLatticeFunc: GetAgentLatticeFunction;\n\n /**\n * constructor\n *\n * @param getAgentLatticeFunc get Agent Lattice function\n */\n constructor(getAgentLatticeFunc: GetAgentLatticeFunction) {\n this.getAgentLatticeFunc = getAgentLatticeFunc;\n }\n\n /**\n * build Agent parameters\n *\n * @param agentLattice Agent Lattice object\n * @param options build options\n * @returns Agent build parameters\n */\n public buildParams(\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n ): AgentBuildParams {\n // get tools (use type-safe helper)\n const toolKeys =\n options?.overrideTools || getToolsFromConfig(agentLattice.config);\n const tools = toolKeys.map((toolKey: string) => {\n const toolLattice = toolLatticeManager.getToolLattice(toolKey);\n if (!toolLattice) {\n throw new Error(`Tool \"${toolKey}\" does not exist`);\n }\n return {\n key: toolKey,\n definition: toolLattice.config,\n executor: toolLattice.client,\n };\n });\n\n // get model\n const modelKey = options?.overrideModel || agentLattice.config.modelKey;\n const model = modelKey\n ? modelLatticeManager.getModelLattice(modelKey).client\n : modelLatticeManager.getModelLattice(\"default\").client;\n if (!model) {\n throw new Error(`Model \"${modelKey}\" does not exist`);\n }\n\n // get subAgents (use type-safe helper - only DeepAgentConfig has subAgents)\n const subAgentKeys = getSubAgentsFromConfig(agentLattice.config);\n const subAgents = subAgentKeys.map((agentKey: string) => {\n const subAgentLattice = this.getAgentLatticeFunc(agentKey);\n if (!subAgentLattice) {\n throw new Error(`SubAgent \"${agentKey}\" does not exist`);\n }\n return {\n key: agentKey,\n config: subAgentLattice.config,\n client: subAgentLattice.client,\n };\n });\n let internalSubAgents: any[] = [];\n if (isDeepAgentConfig(agentLattice.config)) {\n internalSubAgents =\n agentLattice.config.internalSubAgents?.map((i) => ({\n key: i.key,\n config: i,\n })) || [];\n }\n\n return {\n tools,\n model,\n subAgents: [...subAgents, ...internalSubAgents],\n prompt: agentLattice.config.prompt,\n stateSchema: agentLattice.config.schema,\n };\n }\n}\n","import { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n AgentConfig,\n AgentClient,\n AgentLattice,\n GraphBuildOptions,\n AgentBuildParams,\n} from \"./types\";\nimport { AgentGraphBuilderFactory } from \"./builders/AgentGraphBuilderFactory\";\nimport { AgentParamsBuilder } from \"./builders/AgentParamsBuilder\";\nimport \"../tool_lattice\";\n// 类型定义已移至 ./types.ts\n\n/**\n * AgentLatticeManager - 单例Agent Lattice管理器\n * 负责注册、管理各种Agent Lattice\n */\nexport class AgentLatticeManager extends BaseLatticeManager<AgentLattice> {\n private static _instance: AgentLatticeManager;\n\n /**\n * 获取AgentLatticeManager单例实例\n */\n public static getInstance(): AgentLatticeManager {\n if (!AgentLatticeManager._instance) {\n AgentLatticeManager._instance = new AgentLatticeManager();\n }\n return AgentLatticeManager._instance;\n }\n\n /**\n * 获取Lattice类型前缀\n */\n protected getLatticeType(): string {\n return \"agents\";\n }\n\n /**\n * 注册Agent Lattice\n * @param config Agent配置\n */\n public registerLattice(config: AgentConfig): void {\n // 创建Agent Lattice对象\n const agentLattice: AgentLattice = {\n config,\n client: undefined, // 客户端将在需要时由initializeClient创建\n };\n\n // 调用基类的register方法\n this.register(config.key, agentLattice);\n }\n\n /**\n * 获取AgentLattice\n * @param key Lattice键名\n */\n public getAgentLattice(key: string): AgentLattice | undefined {\n return this.get(key);\n }\n\n /**\n * 获取所有Lattice\n */\n public getAllLattices(): AgentLattice[] {\n return this.getAll();\n }\n\n /**\n * 检查Lattice是否存在\n * @param key Lattice键名\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * 移除Lattice\n * @param key Lattice键名\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * 获取Agent配置\n * @param key Lattice键名\n */\n public getAgentConfig(key: string): AgentConfig | undefined {\n return this.getAgentLattice(key)?.config;\n }\n\n /**\n * 获取所有Agent配置\n */\n public getAllAgentConfigs(): AgentConfig[] {\n return this.getAllLattices().map((lattice) => lattice.config);\n }\n\n /**\n * 验证Agent输入参数\n * @param key Lattice键名\n * @param input 输入参数\n */\n public validateAgentInput(key: string, input: any): boolean {\n const agentLattice = this.getAgentLattice(key);\n if (!agentLattice) {\n return false;\n }\n\n try {\n if (agentLattice.config.schema) {\n agentLattice.config.schema.parse(input);\n }\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * 构建Agent参数\n *\n * @param agentLattice Agent Lattice对象\n * @param options 构建选项\n * @returns 返回Agent构建参数\n */\n private buildAgentParams(\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n ): AgentBuildParams {\n // 创建参数构建器\n const paramsBuilder = new AgentParamsBuilder((key: string) => {\n this.initializeClient(key);\n return this.getAgentLattice(key);\n });\n\n // 构建参数\n return paramsBuilder.buildParams(agentLattice, options);\n }\n\n /**\n * Create an AgentClient from AgentLattice config\n *\n * @param agentLattice Agent Lattice object\n * @param options Build options\n * @returns AgentClient instance\n */\n public createAgentClientFromConfig(\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n ): AgentClient {\n // Get factory instance\n const factory = AgentGraphBuilderFactory.getInstance();\n\n // Get the builder for the agent type\n const builder = factory.getBuilder(agentLattice.config.type);\n\n // Build params\n const params = this.buildAgentParams(agentLattice, options);\n\n // Use builder to build the graph\n return builder.build(agentLattice, params);\n }\n\n /**\n * 初始化Agent客户端\n *\n * 使用AgentGraphBuilderFactory构建Graph并设置为客户端\n *\n * @param key Lattice键名\n * @param options 构建选项\n * @returns 返回CompiledGraph对象\n */\n public initializeClient(\n key: string,\n options?: GraphBuildOptions\n ): AgentClient {\n const agentLattice = this.getAgentLattice(key);\n if (!agentLattice) {\n throw new Error(`Agent Lattice \"${key}\" 不存在`);\n }\n\n // If client already exists, return it directly\n if (agentLattice.client) {\n return agentLattice.client;\n }\n\n // Create agent client from config\n const graph = this.createAgentClientFromConfig(agentLattice, options);\n\n // Set as client\n agentLattice.client = graph;\n\n return graph;\n }\n}\n\n// 导出单例实例\nexport const agentLatticeManager = AgentLatticeManager.getInstance();\n\n// 导出便捷方法\nexport const registerAgentLattice = (config: AgentConfig) => {\n agentLatticeManager.registerLattice(config);\n};\n\nexport const registerAgentLattices = (configs: AgentConfig[]) => {\n configs.forEach((config) => {\n agentLatticeManager.registerLattice(config);\n });\n};\n\nexport const getAgentLattice = (key: string) =>\n agentLatticeManager.getAgentLattice(key);\n\nexport const getAgentConfig = (key: string) =>\n agentLatticeManager.getAgentConfig(key);\n\nexport const getAllAgentConfigs = () =>\n agentLatticeManager.getAllAgentConfigs();\n\nexport const validateAgentInput = (key: string, input: any) =>\n agentLatticeManager.validateAgentInput(key, input);\n\n/**\n * 获取或初始化Agent客户端\n *\n * @param key Agent Lattice键名\n * @param options 构建选项\n * @returns 返回CompiledGraph对象\n */\nexport const getAgentClient = (key: string, options?: GraphBuildOptions) =>\n agentLatticeManager.initializeClient(key, options);\n\nexport const createAgentClientFromAgentLattice = (\n agentLattice: AgentLattice,\n options?: GraphBuildOptions\n) => agentLatticeManager.createAgentClientFromConfig(agentLattice, options);\n","/**\n * ChunkBuffer Abstract Base Class\n *\n * Defines the interface for chunk buffer implementations\n */\n\nimport { MessageChunk } from \"@axiom-lattice/protocols\";\nimport { ThreadStatus, ThreadBuffer } from \"./types\";\n\nexport abstract class ChunkBuffer {\n /**\n * Add a chunk to a thread (creates thread if not exists)\n * Chunks are appended in order\n */\n abstract addChunk(threadId: string, content: MessageChunk): Promise<void>;\n\n /**\n * Mark thread as completed (explicit call)\n */\n abstract completeThread(threadId: string): Promise<void>;\n\n /**\n * Mark thread as aborted (explicit call)\n */\n abstract abortThread(threadId: string): Promise<void>;\n\n /**\n * Check if thread is still active\n */\n abstract isThreadActive(threadId: string): Promise<boolean>;\n\n /**\n * Get thread status (returns undefined if thread doesn't exist)\n */\n abstract getThreadStatus(threadId: string): Promise<ThreadStatus | undefined>;\n\n /**\n * Get thread buffer info including metadata\n */\n abstract getThreadBuffer(threadId: string): Promise<ThreadBuffer | undefined>;\n\n /**\n * Clear specific thread buffer\n */\n abstract clearThread(threadId: string): Promise<void>;\n\n /**\n * Get all active thread IDs\n */\n abstract getActiveThreads(): Promise<string[]>;\n\n /**\n * Get all thread IDs (regardless of status)\n */\n abstract getAllThreads(): Promise<string[]>;\n\n /**\n * Manually trigger cleanup of expired threads\n * Returns number of threads cleaned up\n */\n abstract cleanupExpiredThreads(): Promise<number>;\n\n /**\n * Extend thread TTL (reset expiration time)\n */\n abstract extendThreadTTL(\n threadId: string,\n additionalMs?: number\n ): Promise<void>;\n\n /**\n * Check if a thread exists (valid or expired)\n */\n abstract hasThread(threadId: string): Promise<boolean>;\n\n abstract getNewChunksSinceContentIterator(\n threadId: string,\n messageId: string,\n knownContent: string\n ): AsyncIterable<MessageChunk>;\n}\n","/**\n * ChunkBuffer Types\n *\n * Defines types for managing streaming chunks organized by thread\n */\n\nimport { MessageChunk } from \"@axiom-lattice/protocols\";\nimport { ReplaySubject } from \"rxjs\";\n\n/**\n * Represents a single chunk of data\n * Chunks are identified by their position in the sequence (no unique ID)\n */\nexport interface Chunk {\n messageId: string; // Message this chunk belongs to\n content: MessageChunk; // Chunk content\n}\n\n/**\n * Thread status - requires explicit state transitions\n */\nexport enum ThreadStatus {\n ACTIVE = \"active\",\n COMPLETED = \"completed\",\n ABORTED = \"aborted\",\n}\n\n/**\n * Thread buffer configuration\n */\nexport interface ThreadBufferConfig {\n ttl?: number; // Time-to-live in milliseconds (default: 1 hour)\n cleanupInterval?: number; // Optional: periodic cleanup interval in ms\n}\n\n/**\n * Thread buffer state\n */\nexport interface ThreadBuffer {\n threadId: string;\n chunks$: ReplaySubject<MessageChunk>; // Ordered list of chunks\n status: ThreadStatus;\n createdAt: number;\n updatedAt: number;\n expiresAt: number; // TTL expiration timestamp\n}\n\n/**\n * Buffer statistics\n */\nexport interface BufferStats {\n totalThreads: number;\n activeThreads: number;\n completedThreads: number;\n abortedThreads: number;\n config: Required<ThreadBufferConfig>;\n}\n","/**\n * InMemoryChunkBuffer\n *\n * In-memory implementation of ChunkBuffer with hybrid cleanup strategy:\n * - Lazy cleanup: expired threads are removed on access\n * - Optional periodic cleanup: background timer to clean expired threads\n */\n\nimport { MessageChunk } from \"@axiom-lattice/protocols\";\nimport { EventEmitter, once } from \"events\";\nimport { ChunkBuffer } from \"./ChunkBuffer\";\nimport {\n BufferStats,\n ThreadBuffer,\n ThreadBufferConfig,\n ThreadStatus,\n} from \"./types\";\nimport { ReplaySubject, Observable, Subscription } from \"rxjs\";\n\nexport class InMemoryChunkBuffer extends ChunkBuffer {\n private buffers: Map<string, ThreadBuffer>;\n private config: Required<ThreadBufferConfig> & { maxChunks?: number };\n private cleanupTimer?: NodeJS.Timeout;\n\n constructor(config?: ThreadBufferConfig & { maxChunks?: number }) {\n super();\n this.buffers = new Map();\n\n // Default: 1 hour TTL, no periodic cleanup (lazy only)\n this.config = {\n ttl: config?.ttl ?? 60 * 60 * 1000,\n cleanupInterval: config?.cleanupInterval ?? 0,\n maxChunks: config?.maxChunks ?? 1000, // Default max chunks per thread\n };\n\n // Start periodic cleanup only if cleanupInterval is specified\n if (this.config.cleanupInterval > 0) {\n this.startCleanupTimer();\n }\n }\n\n /**\n * Start automatic periodic cleanup timer\n */\n private startCleanupTimer(): void {\n if (this.config.cleanupInterval <= 0) return;\n\n this.cleanupTimer = setInterval(() => {\n this.cleanupExpiredThreads().catch(console.error);\n }, this.config.cleanupInterval);\n\n // Don't prevent process from exiting\n if (this.cleanupTimer.unref) {\n this.cleanupTimer.unref();\n }\n }\n\n /**\n * Stop cleanup timer (for cleanup/shutdown)\n */\n public stopCleanupTimer(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n }\n\n /**\n * Check if a buffer is expired (lazy cleanup helper)\n */\n private isExpired(buffer: ThreadBuffer): boolean {\n return buffer.expiresAt <= Date.now();\n }\n\n /**\n * Get buffer if valid, perform lazy cleanup if expired\n */\n private getBufferIfValid(threadId: string): ThreadBuffer | undefined {\n const buffer = this.buffers.get(threadId);\n\n if (buffer && this.isExpired(buffer)) {\n // Lazy cleanup: remove expired buffer on access\n this.buffers.delete(threadId);\n return undefined;\n }\n\n return buffer;\n }\n\n /**\n * Create or get thread buffer\n */\n private getOrCreateBuffer(threadId: string): ThreadBuffer {\n // First check with lazy cleanup\n let buffer = this.getBufferIfValid(threadId);\n 4;\n if (!buffer) {\n const now = Date.now();\n buffer = {\n threadId,\n chunks$: new ReplaySubject<MessageChunk>(\n this.config.maxChunks ?? 10000\n ),\n status: ThreadStatus.ACTIVE,\n createdAt: now,\n updatedAt: now,\n expiresAt: now + this.config.ttl,\n };\n this.buffers.set(threadId, buffer);\n }\n\n if (buffer.status !== ThreadStatus.ACTIVE) {\n buffer.status = ThreadStatus.ACTIVE;\n buffer.chunks$ = new ReplaySubject<MessageChunk>(\n this.config.maxChunks ?? 10000\n );\n buffer.updatedAt = Date.now();\n buffer.expiresAt = Date.now() + this.config.ttl;\n }\n\n return buffer;\n }\n\n async addChunk(threadId: string, content: MessageChunk): Promise<void> {\n const buffer = this.getOrCreateBuffer(threadId);\n\n const chunk: MessageChunk = content;\n\n buffer.chunks$.next(chunk);\n buffer.updatedAt = Date.now();\n\n // Auto-extend TTL on activity\n buffer.expiresAt = Date.now() + this.config.ttl;\n buffer.status = ThreadStatus.ACTIVE;\n\n // Notify listeners\n }\n\n async completeThread(threadId: string): Promise<void> {\n const buffer = this.getBufferIfValid(threadId);\n if (buffer) {\n buffer.status = ThreadStatus.COMPLETED;\n buffer.updatedAt = Date.now();\n buffer.chunks$.complete();\n }\n }\n\n async abortThread(threadId: string): Promise<void> {\n const buffer = this.getBufferIfValid(threadId);\n if (buffer) {\n buffer.status = ThreadStatus.ABORTED;\n buffer.updatedAt = Date.now();\n buffer.chunks$.error(new Error(\"Thread aborted\"));\n }\n }\n\n async isThreadActive(threadId: string): Promise<boolean> {\n const buffer = this.getBufferIfValid(threadId);\n return buffer?.status === ThreadStatus.ACTIVE;\n }\n\n async getThreadStatus(threadId: string): Promise<ThreadStatus | undefined> {\n return this.getBufferIfValid(threadId)?.status;\n }\n\n async getThreadBuffer(threadId: string): Promise<ThreadBuffer | undefined> {\n const buffer = this.getBufferIfValid(threadId);\n if (!buffer) return undefined;\n return buffer;\n }\n\n async clearThread(threadId: string): Promise<void> {\n this.buffers.delete(threadId);\n }\n\n async getActiveThreads(): Promise<string[]> {\n const activeThreads: string[] = [];\n\n for (const [threadId, buffer] of this.buffers.entries()) {\n // Apply lazy cleanup\n if (this.isExpired(buffer)) {\n this.buffers.delete(threadId);\n continue;\n }\n\n if (buffer.status === ThreadStatus.ACTIVE) {\n activeThreads.push(threadId);\n }\n }\n\n return activeThreads;\n }\n\n async getAllThreads(): Promise<string[]> {\n const validThreads: string[] = [];\n\n for (const [threadId, buffer] of this.buffers.entries()) {\n // Apply lazy cleanup\n if (this.isExpired(buffer)) {\n this.buffers.delete(threadId);\n } else {\n validThreads.push(threadId);\n }\n }\n\n return validThreads;\n }\n\n async hasThread(threadId: string): Promise<boolean> {\n return this.getBufferIfValid(threadId) !== undefined;\n }\n\n /**\n * Cleanup expired threads based on TTL\n * Returns number of threads cleaned up\n */\n async cleanupExpiredThreads(): Promise<number> {\n const now = Date.now();\n let cleanedCount = 0;\n\n for (const [threadId, buffer] of this.buffers.entries()) {\n if (buffer.expiresAt <= now) {\n this.buffers.delete(threadId);\n cleanedCount++;\n }\n }\n\n return cleanedCount;\n }\n\n async extendThreadTTL(\n threadId: string,\n additionalMs?: number\n ): Promise<void> {\n const buffer = this.getBufferIfValid(threadId);\n if (buffer) {\n const extension = additionalMs ?? this.config.ttl;\n buffer.expiresAt = Date.now() + extension;\n buffer.updatedAt = Date.now();\n }\n }\n\n async *getNewChunksSinceContentIterator(\n threadId: string,\n messageId: string,\n knownContent: string\n ): AsyncIterable<MessageChunk> {\n const buffer = this.getBufferIfValid(threadId);\n if (!buffer) return;\n\n let accumulatedContent = \"\";\n const queue: MessageChunk[] = [];\n let resolveNext: (() => void) | null = null;\n let errorNext: ((err: any) => void) | null = null;\n let isCompleted = false;\n\n const subscription = buffer.chunks$.subscribe({\n next: (chunk) => {\n queue.push(chunk);\n if (resolveNext) {\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n error: (err) => {\n if (errorNext) {\n const reject = errorNext;\n errorNext = null;\n reject(err);\n }\n },\n complete: () => {\n isCompleted = true;\n if (resolveNext) {\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n });\n\n try {\n while (true) {\n if (queue.length === 0) {\n if (isCompleted) break;\n await new Promise<void>((resolve, reject) => {\n resolveNext = resolve;\n errorNext = reject;\n });\n }\n\n while (queue.length > 0) {\n const chunk = queue.shift();\n if (!chunk) continue;\n\n if (chunk.data?.id === messageId) {\n accumulatedContent += chunk.data?.content || \"\";\n }\n\n if (accumulatedContent.length > knownContent.length) {\n if (accumulatedContent.startsWith(knownContent)) {\n yield chunk;\n }\n }\n }\n }\n } finally {\n subscription.unsubscribe();\n }\n }\n\n public getStats(): BufferStats {\n let activeCount = 0;\n let completedCount = 0;\n let abortedCount = 0;\n\n const validBuffers: ThreadBuffer[] = [];\n for (const [threadId, buffer] of this.buffers.entries()) {\n if (this.isExpired(buffer)) {\n this.buffers.delete(threadId);\n } else {\n validBuffers.push(buffer);\n }\n }\n\n for (const buffer of validBuffers) {\n switch (buffer.status) {\n case ThreadStatus.ACTIVE:\n activeCount++;\n break;\n case ThreadStatus.COMPLETED:\n completedCount++;\n break;\n case ThreadStatus.ABORTED:\n abortedCount++;\n break;\n }\n }\n\n return {\n totalThreads: validBuffers.length,\n activeThreads: activeCount,\n completedThreads: completedCount,\n abortedThreads: abortedCount,\n\n config: this.config,\n };\n }\n\n public dispose(): void {\n this.stopCleanupTimer();\n this.buffers.clear();\n }\n}\n","/**\n * ChunkBufferLatticeManager\n * \n * Manages ChunkBuffer instances following the Lattice pattern\n */\n\nimport { BaseLatticeManager } from '../base/BaseLatticeManager';\nimport { ChunkBuffer } from './ChunkBuffer';\n\n/**\n * ChunkBuffer Lattice Manager\n */\nexport class ChunkBufferLatticeManager extends BaseLatticeManager<ChunkBuffer> {\n private static instance: ChunkBufferLatticeManager;\n \n /**\n * Private constructor for singleton pattern\n */\n private constructor() {\n super();\n }\n \n /**\n * Get singleton instance\n */\n public static getInstance(): ChunkBufferLatticeManager {\n if (!ChunkBufferLatticeManager.instance) {\n ChunkBufferLatticeManager.instance = new ChunkBufferLatticeManager();\n }\n return ChunkBufferLatticeManager.instance;\n }\n \n /**\n * Get Lattice type identifier\n */\n protected getLatticeType(): string {\n return 'chunk_buffer';\n }\n}\n\n// Convenience functions\nexport const getChunkBuffer = (key: string): ChunkBuffer | undefined =>\n ChunkBufferLatticeManager.getInstance().get(key);\n\nexport const registerChunkBuffer = (key: string, buffer: ChunkBuffer): void =>\n ChunkBufferLatticeManager.getInstance().register(key, buffer);\n\nexport const hasChunkBuffer = (key: string): boolean =>\n ChunkBufferLatticeManager.getInstance().has(key);\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AA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A,MAC3B,eAAe;AAAA,MACf,kBAAkB;AAAA,MAClB,gBAAgB;AAAA,MAEhB,QAAQ,KAAK;AAAA,IACf;AAAA,EACF;AAAA,EAEO,UAAgB;AACrB,SAAK,iBAAiB;AACtB,SAAK,QAAQ,MAAM;AAAA,EACrB;AACF;;;ACtVO,IAAM,4BAAN,MAAM,mCAAkC,mBAAgC;AAAA;AAAA;AAAA;AAAA,EAMrE,cAAc;AACpB,UAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA,EAKA,OAAc,cAAyC;AACrD,QAAI,CAAC,2BAA0B,UAAU;AACvC,iCAA0B,WAAW,IAAI,2BAA0B;AAAA,IACrE;AACA,WAAO,2BAA0B;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKU,iBAAyB;AACjC,WAAO;AAAA,EACT;AACF;AAGO,IAAM,iBAAiB,CAAC,QAC7B,0BAA0B,YAAY,EAAE,IAAI,GAAG;AAE1C,IAAM,sBAAsB,CAAC,KAAa,WAC/C,0BAA0B,YAAY,EAAE,SAAS,KAAK,MAAM;AAEvD,IAAM,iBAAiB,CAAC,QAC7B,0BAA0B,YAAY,EAAE,IAAI,GAAG;;;AvCxCjD,gBAA2B;","names":["getAgentClient","z","import_zod","z","import_zod","import_langgraph","z","import_zod","import_langgraph","z","import_zod","import_messages","import_langgraph","z","import_zod","import_messages","import_langgraph","z","import_zod","import_langgraph","z","import_langgraph","import_protocols","import_zod","import_langgraph","tool","import_tools","import_messages","import_langgraph","import_zod","WRITE_TODOS_DESCRIPTION","import_protocols","import_tools","import_messages","import_langgraph","import_zod","WRITE_TODOS_DESCRIPTION","import_zod","import_langgraph","import_prebuilt","tool","tool","import_langgraph","import_messages","import_zod","pino","import_messages","import_messages","import_messages","import_tools","import_langgraph","memory","import_prebuilt","config","tool","tool","import_protocols","getAgentClient","ThreadStatus"]}