@axiom-lattice/core 2.1.20 → 2.1.21

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/sql/SqlDatabaseManager.ts","../src/tool_lattice/sql/list_tables_sql.ts","../src/tool_lattice/sql/info_sql.ts","../src/tool_lattice/sql/query_checker_sql.ts","../src/tool_lattice/sql/query_sql.ts","../src/tool_lattice/code_eval/index.ts","../src/sandbox_lattice/SandboxLatticeManager.ts","../src/sandbox_lattice/utils.ts","../src/tool_lattice/code_execute_file/index.ts","../src/tool_lattice/convert_to_markdown/index.ts","../src/tool_lattice/browser/browser_navigate.ts","../src/tool_lattice/browser/browser_click.ts","../src/tool_lattice/browser/browser_get_text.ts","../src/tool_lattice/browser/browser_get_markdown.ts","../src/tool_lattice/browser/browser_evaluate.ts","../src/tool_lattice/browser/browser_screenshot.ts","../src/tool_lattice/browser/browser_scroll.ts","../src/tool_lattice/browser/browser_form_input_fill.ts","../src/tool_lattice/browser/browser_select.ts","../src/tool_lattice/browser/browser_hover.ts","../src/tool_lattice/browser/browser_go_back.ts","../src/tool_lattice/browser/browser_go_forward.ts","../src/tool_lattice/browser/browser_new_tab.ts","../src/tool_lattice/browser/browser_tab_list.ts","../src/tool_lattice/browser/browser_switch_tab.ts","../src/tool_lattice/browser/browser_close_tab.ts","../src/tool_lattice/browser/browser_close.ts","../src/tool_lattice/browser/browser_press_key.ts","../src/tool_lattice/browser/browser_read_links.ts","../src/tool_lattice/browser/browser_get_clickable_elements.ts","../src/tool_lattice/browser/browser_get_download_list.ts","../src/tool_lattice/browser/get_info.ts","../src/agent_lattice/types.ts","../src/memory_lattice/DefaultMemorySaver.ts","../src/memory_lattice/MemoryLatticeManager.ts","../src/agent_lattice/builders/state.ts","../src/agent_lattice/builders/ReActAgentGraphBuilder.ts","../src/deep_agent_new/backends/sandboxFiles.ts","../src/middlewares/codeEvalMiddleware.ts","../src/middlewares/browserMiddleware.ts","../src/middlewares/sqlMiddleware.ts","../src/middlewares/skillMiddleware.ts","../src/store_lattice/InMemoryThreadStore.ts","../src/store_lattice/InMemoryAssistantStore.ts","../src/store_lattice/FileSystemSkillStore.ts","../src/skill_lattice/skillNameValidator.ts","../src/store_lattice/StoreLatticeManager.ts","../src/tool_lattice/skill/load_skills.ts","../src/tool_lattice/skill/load_skill_content.ts","../src/deep_agent_new/middleware/fs.ts","../src/deep_agent_new/backends/utils.ts","../src/deep_agent_new/backends/state.ts","../src/agent_lattice/builders/commonMiddleware.ts","../src/deep_agent_new/agent.ts","../src/deep_agent_new/middleware/subagents.ts","../src/agent_worker/agent_worker_graph.ts","../src/constants/agent_task_types.ts","../src/services/event_bus.ts","../src/queue_lattice/QueueLatticeManager.ts","../src/queue_lattice/MemoryQueueClient.ts","../src/services/AgentManager.ts","../src/deep_agent_new/middleware/patch_tool_calls.ts","../src/deep_agent_new/backends/filesystem.ts","../src/deep_agent_new/middleware/todos.ts","../src/agent_lattice/builders/DeepAgentGraphBuilder.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","../src/schedule_lattice/ScheduleLatticeManager.ts","../src/schedule_lattice/DefaultScheduleClient.ts","../src/schedule_lattice/MemoryScheduleStorage.ts","../src/schedule_lattice/CronParser.ts","../src/embeddings_lattice/EmbeddingsLatticeManager.ts","../src/vectorstore_lattice/VectorStoreLatticeManager.ts","../src/logger_lattice/LoggerLatticeManager.ts","../src/logger_lattice/PinoLoggerClient.ts","../src/logger_lattice/ConsoleLoggerClient.ts","../src/skill_lattice/SkillLatticeManager.ts","../src/mcp_lattice/McpLatticeManager.ts"],"sourcesContent":["// Export core modules\nexport * from \"./model_lattice\";\nexport * from \"./tool_lattice\";\n// Direct export of SQL tools to ensure they are bundled\nexport * from \"./tool_lattice/sql\";\nexport * from \"./agent_lattice\";\nexport * from \"./memory_lattice\";\nexport * from \"./chunk_buffer_lattice\";\nexport * from \"./queue_lattice\";\nexport * from \"./schedule_lattice\";\nexport * from \"./store_lattice\";\nexport * from \"./embeddings_lattice\";\nexport * from \"./vectorstore_lattice\";\nexport * from \"./logger_lattice\";\nexport * from \"./skill_lattice\";\nexport * from \"./mcp_lattice\";\nexport * from \"./sandbox_lattice\";\n\n// Export service modules\nexport { eventBus, default as eventBusDefault } from \"./services/event_bus\";\nexport { AgentManager } from \"./services/AgentManager\";\n\n// Export constants\nexport * from \"./constants/agent_task_types\";\n\n// Re-export protocol interfaces - use named exports to avoid conflicts\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: config.apiKey || 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:\n config.apiKey ||\n 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:\n config.apiKey ||\n 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:\n config.apiKey ||\n 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:\n config.apiKey ||\n 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 /**\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 * 注册已有的StructuredTool到Lattice\n * @param key Lattice键名\n * @param tool 已有的StructuredTool实例\n */\n public registerExistingTool(key: string, tool: StructuredTool): void {\n // 从工具中提取配置信息\n const config: ToolConfig = {\n name: tool.name,\n description: tool.description,\n schema: tool.schema as any, // StructuredTool的schema已经是Zod兼容的\n needUserApprove: false, // MCP工具默认不需要用户批准\n };\n\n const toolLattice: ToolLattice = {\n key,\n config,\n client: tool,\n };\n\n this.register(key, toolLattice);\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 registerExistingTool = (key: string, tool: StructuredTool) =>\n toolLatticeManager.registerExistingTool(key, tool);\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 JSON.stringify(tavilyResponse.results);\n }\n);\n","export const genUICard = (title: string, type: string, data: any) => {\n return [title, \"```\" + type, JSON.stringify(data), \"```\"].join(\"\\n\");\n};\n","/**\n * SQL Database Manager\n * Singleton manager for SQL database connections\n */\n\nimport {\n DatabaseConfig,\n DatabaseType,\n ISqlDatabase,\n TableInfo,\n TableSchema,\n ColumnInfo,\n QueryResult,\n} from \"./types\";\n\n/**\n * PostgreSQL Database Implementation\n * Uses pg library for PostgreSQL connections\n */\nexport class PostgresDatabase implements ISqlDatabase {\n private config: DatabaseConfig;\n private pool: any; // pg.Pool\n private connected: boolean = false;\n\n constructor(config: DatabaseConfig) {\n this.config = config;\n }\n\n async connect(): Promise<void> {\n if (this.connected) return;\n\n try {\n // Dynamic import of pg to avoid bundling issues\n const { Pool } = await import(\"pg\");\n\n const poolConfig = this.config.connectionString\n ? { connectionString: this.config.connectionString }\n : {\n host: this.config.host || \"localhost\",\n port: this.config.port || 5432,\n database: this.config.database,\n user: this.config.user,\n password: this.config.password,\n ssl: this.config.ssl ? { rejectUnauthorized: false } : undefined,\n };\n\n this.pool = new Pool(poolConfig);\n // Test connection\n const client = await this.pool.connect();\n client.release();\n this.connected = true;\n } catch (error) {\n throw new Error(`Failed to connect to PostgreSQL: ${error}`);\n }\n }\n\n async disconnect(): Promise<void> {\n if (this.pool) {\n await this.pool.end();\n this.connected = false;\n }\n }\n\n async listTables(): Promise<TableInfo[]> {\n await this.ensureConnected();\n\n const query = `\n SELECT table_name, table_schema\n FROM information_schema.tables\n WHERE table_schema NOT IN ('pg_catalog', 'information_schema')\n AND table_type = 'BASE TABLE'\n ORDER BY table_schema, table_name;\n `;\n\n const result = await this.pool.query(query);\n return result.rows.map((row: any) => ({\n name: row.table_name,\n schema: row.table_schema,\n }));\n }\n\n async getTableInfo(tables: string[]): Promise<TableSchema[]> {\n await this.ensureConnected();\n\n const schemas: TableSchema[] = [];\n\n for (const tableName of tables) {\n // Get column information\n const columnQuery = `\n SELECT \n c.column_name,\n c.data_type,\n c.is_nullable,\n c.column_default,\n CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_primary_key,\n CASE WHEN fk.column_name IS NOT NULL THEN true ELSE false END as is_foreign_key,\n fk.foreign_table_name,\n fk.foreign_column_name\n FROM information_schema.columns c\n LEFT JOIN (\n SELECT ku.column_name, ku.table_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku\n ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'PRIMARY KEY'\n ) pk ON c.column_name = pk.column_name AND c.table_name = pk.table_name\n LEFT JOIN (\n SELECT \n kcu.column_name,\n kcu.table_name,\n ccu.table_name as foreign_table_name,\n ccu.column_name as foreign_column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n JOIN information_schema.constraint_column_usage ccu\n ON tc.constraint_name = ccu.constraint_name\n WHERE tc.constraint_type = 'FOREIGN KEY'\n ) fk ON c.column_name = fk.column_name AND c.table_name = fk.table_name\n WHERE c.table_name = $1\n ORDER BY c.ordinal_position;\n `;\n\n const columnResult = await this.pool.query(columnQuery, [tableName]);\n\n const columns: ColumnInfo[] = columnResult.rows.map((row: any) => ({\n name: row.column_name,\n type: row.data_type,\n nullable: row.is_nullable === \"YES\",\n default: row.column_default,\n isPrimaryKey: row.is_primary_key,\n isForeignKey: row.is_foreign_key,\n foreignKeyRef: row.is_foreign_key\n ? `${row.foreign_table_name}.${row.foreign_column_name}`\n : undefined,\n }));\n\n // Get sample rows (limit to 3)\n let sampleRows: Record<string, unknown>[] = [];\n try {\n const sampleQuery = `SELECT * FROM \"${tableName}\" LIMIT 3`;\n const sampleResult = await this.pool.query(sampleQuery);\n sampleRows = sampleResult.rows;\n } catch {\n // Ignore errors when getting sample rows\n }\n\n schemas.push({\n tableName,\n columns,\n sampleRows,\n });\n }\n\n return schemas;\n }\n\n async executeQuery(query: string): Promise<QueryResult> {\n await this.ensureConnected();\n\n const result = await this.pool.query(query);\n return {\n rows: result.rows,\n rowCount: result.rowCount || result.rows.length,\n fields: result.fields?.map((f: any) => f.name),\n };\n }\n\n getDatabaseType(): DatabaseType {\n return \"postgres\";\n }\n\n private async ensureConnected(): Promise<void> {\n if (!this.connected) {\n await this.connect();\n }\n }\n}\n\n/**\n * SQL Database Manager\n * Manages database connections and provides a unified interface\n */\nexport class SqlDatabaseManager {\n private static instance: SqlDatabaseManager;\n private databases: Map<string, ISqlDatabase> = new Map();\n private defaultDatabaseKey: string | null = null;\n\n private constructor() {}\n\n /**\n * Get the singleton instance\n */\n static getInstance(): SqlDatabaseManager {\n if (!SqlDatabaseManager.instance) {\n SqlDatabaseManager.instance = new SqlDatabaseManager();\n }\n return SqlDatabaseManager.instance;\n }\n\n /**\n * Register a database connection\n * @param key - Unique identifier for the database\n * @param config - Database configuration\n */\n registerDatabase(key: string, config: DatabaseConfig): void {\n let database: ISqlDatabase;\n\n switch (config.type) {\n case \"postgres\":\n database = new PostgresDatabase(config);\n break;\n case \"mysql\":\n throw new Error(\"MySQL support not yet implemented\");\n case \"sqlite\":\n throw new Error(\"SQLite support not yet implemented\");\n default:\n throw new Error(`Unsupported database type: ${config.type}`);\n }\n\n this.databases.set(key, database);\n\n // Set as default if it's the first database\n if (this.defaultDatabaseKey === null) {\n this.defaultDatabaseKey = key;\n }\n }\n\n /**\n * Set the default database\n * @param key - Database key to set as default\n */\n setDefaultDatabase(key: string): void {\n if (!this.databases.has(key)) {\n throw new Error(`Database '${key}' not found`);\n }\n this.defaultDatabaseKey = key;\n }\n\n /**\n * Get a database by key\n * @param key - Database key (optional, uses default if not provided)\n */\n getDatabase(key?: string): ISqlDatabase {\n const dbKey = key || this.defaultDatabaseKey;\n if (!dbKey) {\n throw new Error(\"No database registered\");\n }\n\n const database = this.databases.get(dbKey);\n if (!database) {\n throw new Error(`Database '${dbKey}' not found`);\n }\n\n return database;\n }\n\n /**\n * Check if a database is registered\n * @param key - Database key\n */\n hasDatabase(key: string): boolean {\n return this.databases.has(key);\n }\n\n /**\n * Get all registered database keys\n */\n getDatabaseKeys(): string[] {\n return Array.from(this.databases.keys());\n }\n\n /**\n * Remove a database connection\n * @param key - Database key\n */\n async removeDatabase(key: string): Promise<void> {\n const database = this.databases.get(key);\n if (database) {\n await database.disconnect();\n this.databases.delete(key);\n\n if (this.defaultDatabaseKey === key) {\n this.defaultDatabaseKey =\n this.databases.size > 0\n ? this.databases.keys().next().value || null\n : null;\n }\n }\n }\n\n /**\n * Disconnect all databases\n */\n async disconnectAll(): Promise<void> {\n for (const database of this.databases.values()) {\n await database.disconnect();\n }\n }\n}\n\nexport function parseConnectionString(connectionString: string): Omit<DatabaseConfig, \"type\"> {\n const url = new URL(connectionString);\n const protocol = url.protocol.replace(\":\", \"\");\n\n if (protocol !== \"postgres\" && protocol !== \"postgresql\") {\n throw new Error(`Unsupported protocol: ${protocol}. Only postgresql:// is supported.`);\n }\n\n return {\n host: url.hostname || \"localhost\",\n port: parseInt(url.port || \"5432\"),\n database: url.pathname.slice(1) || url.pathname,\n user: url.username,\n password: url.password,\n ssl: url.searchParams.get(\"sslmode\") === \"require\",\n };\n}\n\nexport function parseMysqlConnectionString(connectionString: string): Omit<DatabaseConfig, \"type\"> {\n const url = new URL(connectionString);\n const protocol = url.protocol.replace(\":\", \"\");\n\n if (protocol !== \"mysql\") {\n throw new Error(`Unsupported protocol: ${protocol}. Only mysql:// is supported.`);\n }\n\n return {\n host: url.hostname || \"localhost\",\n port: parseInt(url.port || \"3306\"),\n database: url.pathname.slice(1) || url.pathname,\n user: url.username,\n password: url.password,\n ssl: url.searchParams.get(\"sslmode\") === \"require\",\n };\n}\n\nexport function parseSqliteConnectionString(connectionString: string): Omit<DatabaseConfig, \"type\"> {\n if (connectionString.startsWith(\"sqlite:\")) {\n const path = connectionString.replace(\"sqlite:\", \"\");\n return { database: path };\n }\n return { database: connectionString };\n}\n\n// Export singleton instance\nexport const sqlDatabaseManager = SqlDatabaseManager.getInstance();\n","/**\n * List Tables SQL Tool\n * Tool for listing all tables in the connected database\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\n\nconst LIST_TABLES_SQL_DESCRIPTION = `List all tables in the connected SQL database. Returns a comma-separated list of table names. Use this tool first to understand what tables are available before querying the database.`;\n\nexport interface CreateSqlToolParams {\n databaseKey?: string;\n connectionString?: string;\n}\n\nexport const createListTablesSqlTool = ({ databaseKey, connectionString }: CreateSqlToolParams) => {\n return tool(\n async (_input: Record<string, never>, exe_config: any) => {\n try {\n let dbKey: string;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n } else {\n return \"Error: Must provide databaseKey or connectionString\";\n }\n\n const database = sqlDatabaseManager.getDatabase(dbKey);\n const tables = await database.listTables();\n\n if (tables.length === 0) {\n return \"No tables found in the database.\";\n }\n\n const tableNames = tables.map((t) =>\n t.schema && t.schema !== \"public\" ? `${t.schema}.${t.name}` : t.name\n );\n\n return tableNames.join(\", \");\n } catch (error) {\n return `Error listing tables: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"list_tables_sql\",\n description: LIST_TABLES_SQL_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Info SQL Tool\n * Tool for getting schema information about specified tables\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\nimport { TableSchema } from \"./types\";\n\nconst INFO_SQL_DESCRIPTION = `Get detailed schema information for specified tables, including column names, types, constraints (primary keys, foreign keys), and sample rows. Input should be a comma-separated list of table names.`;\n\nfunction formatTableSchema(schema: TableSchema): string {\n const lines: string[] = [];\n\n lines.push(`\\nTable: ${schema.tableName}`);\n lines.push(\"-\".repeat(40));\n lines.push(\"Columns:\");\n\n for (const col of schema.columns) {\n const constraints: string[] = [];\n if (col.isPrimaryKey) constraints.push(\"PRIMARY KEY\");\n if (col.isForeignKey && col.foreignKeyRef)\n constraints.push(`FK -> ${col.foreignKeyRef}`);\n if (!col.nullable) constraints.push(\"NOT NULL\");\n\n const constraintStr =\n constraints.length > 0 ? ` [${constraints.join(\", \")}]` : \"\";\n lines.push(` - ${col.name}: ${col.type}${constraintStr}`);\n }\n\n if (schema.sampleRows && schema.sampleRows.length > 0) {\n lines.push(\"\\nSample Rows (up to 3):\");\n for (const row of schema.sampleRows) {\n const rowStr = Object.entries(row)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(\", \");\n lines.push(` ${rowStr}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport const createInfoSqlTool = ({ databaseKey, connectionString }: { databaseKey?: string; connectionString?: string }) => {\n return tool(\n async (\n {\n tables,\n }: {\n tables: string;\n },\n exe_config: any\n ) => {\n try {\n let dbKey: string;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n } else {\n return \"Error: Must provide databaseKey or connectionString\";\n }\n\n const database = sqlDatabaseManager.getDatabase(dbKey);\n\n const tableNames = tables\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n\n if (tableNames.length === 0) {\n return \"Error: No table names provided. Please provide a comma-separated list of table names.\";\n }\n\n const schemas = await database.getTableInfo(tableNames);\n\n if (schemas.length === 0) {\n return `No schema information found for tables: ${tableNames.join(\", \")}`;\n }\n\n const output = schemas.map(formatTableSchema).join(\"\\n\");\n return output;\n } catch (error) {\n return `Error getting table info: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"info_sql\",\n description: INFO_SQL_DESCRIPTION,\n schema: z.object({\n tables: z\n .string()\n .describe(\n \"Comma-separated list of table names to get information for. Example: 'users, orders, products'\"\n ),\n }),\n }\n );\n};\n","/**\n * Query Checker SQL Tool\n * Tool for validating SQL queries before execution\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\n\nconst DANGEROUS_KEYWORDS = [\n \"DROP\",\n \"TRUNCATE\",\n \"DELETE\",\n \"ALTER\",\n \"CREATE\",\n \"GRANT\",\n \"REVOKE\",\n];\n\nfunction checkSyntax(query: string): string[] {\n const issues: string[] = [];\n const upperQuery = query.toUpperCase();\n\n let parenCount = 0;\n for (const char of query) {\n if (char === \"(\") parenCount++;\n if (char === \")\") parenCount--;\n if (parenCount < 0) {\n issues.push(\"Unbalanced parentheses: found closing ) without matching (\");\n break;\n }\n }\n if (parenCount > 0) {\n issues.push(\"Unbalanced parentheses: missing closing )\");\n }\n\n const singleQuotes = (query.match(/'/g) || []).length;\n if (singleQuotes % 2 !== 0) {\n issues.push(\"Unbalanced single quotes\");\n }\n\n if (upperQuery.includes(\"SELECT *\") && upperQuery.includes(\"JOIN\")) {\n issues.push(\n \"Warning: SELECT * with JOIN may return duplicate column names. Consider specifying columns explicitly.\"\n );\n }\n\n if (\n (upperQuery.includes(\"UPDATE \") || upperQuery.includes(\"DELETE FROM \")) &&\n !upperQuery.includes(\"WHERE \")\n ) {\n issues.push(\n \"Warning: UPDATE or DELETE without WHERE clause will affect all rows in the table.\"\n );\n }\n\n if (\n upperQuery.includes(\"GROUP BY\") &&\n !upperQuery.match(/\\b(COUNT|SUM|AVG|MAX|MIN|ARRAY_AGG|STRING_AGG)\\s*\\(/i)\n ) {\n issues.push(\n \"Warning: GROUP BY used but no aggregate functions found. Make sure all non-aggregated columns are in GROUP BY.\"\n );\n }\n\n return issues;\n}\n\nfunction checkDangerousOperations(query: string): string[] {\n const warnings: string[] = [];\n const upperQuery = query.toUpperCase();\n\n for (const keyword of DANGEROUS_KEYWORDS) {\n if (upperQuery.includes(keyword)) {\n warnings.push(\n `Warning: Query contains potentially dangerous operation: ${keyword}`\n );\n }\n }\n\n return warnings;\n}\n\nexport const createQueryCheckerSqlTool = ({ databaseKey, connectionString }: { databaseKey?: string; connectionString?: string }) => {\n return tool(\n async (\n {\n query,\n }: {\n query: string;\n },\n exe_config: any\n ) => {\n try {\n const trimmedQuery = query.trim();\n\n if (!trimmedQuery) {\n return \"Error: Empty query provided. Please provide a SQL query to check.\";\n }\n\n const results: string[] = [];\n results.push(\"SQL Query Check Results:\");\n results.push(\"=\".repeat(40));\n results.push(`\\nQuery:\\n${trimmedQuery}\\n`);\n\n const syntaxIssues = checkSyntax(trimmedQuery);\n if (syntaxIssues.length > 0) {\n results.push(\"Syntax Issues:\");\n for (const issue of syntaxIssues) {\n results.push(` - ${issue}`);\n }\n } else {\n results.push(\"Syntax: No obvious syntax issues found\");\n }\n\n const dangerWarnings = checkDangerousOperations(trimmedQuery);\n if (dangerWarnings.length > 0) {\n results.push(\"\\nSafety Warnings:\");\n for (const warning of dangerWarnings) {\n results.push(` - ${warning}`);\n }\n } else {\n results.push(\"Safety: No dangerous operations detected\");\n }\n\n try {\n let dbKey: string | undefined;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n }\n\n if (dbKey) {\n const database = sqlDatabaseManager.getDatabase(dbKey);\n const dbType = database.getDatabaseType();\n\n if (dbType === \"postgres\") {\n try {\n await database.executeQuery(`EXPLAIN ${trimmedQuery}`);\n results.push(\"Database Validation: Query is valid against database schema\");\n } catch (explainError) {\n results.push(\n `Database Validation: ${explainError instanceof Error ? explainError.message : String(explainError)}`\n );\n }\n }\n }\n } catch {\n results.push(\n \"Database Validation: Skipped (no database connection available)\"\n );\n }\n\n const hasErrors =\n syntaxIssues.some((i) => !i.startsWith(\"Warning:\")) ||\n dangerWarnings.length > 0;\n\n results.push(\"\\n\" + \"=\".repeat(40));\n if (hasErrors) {\n results.push(\n \"Overall: Query has potential issues. Review warnings before execution.\"\n );\n } else {\n results.push(\"Overall: Query appears to be safe to execute.\");\n }\n\n return results.join(\"\\n\");\n } catch (error) {\n return `Error checking query: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"query_checker_sql\",\n description:\n \"Check a SQL query for common issues before execution. This tool validates syntax, checks for dangerous operations, and provides suggestions for improvement. Use this before executing queries to ensure they are safe and correct.\",\n schema: z.object({\n query: z.string().describe(\"The SQL query to check and validate.\"),\n }),\n }\n );\n};\n","/**\n * Query SQL Tool\n * Tool for executing SQL queries against the database\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\n\nconst QUERY_SQL_DESCRIPTION = `Execute a SQL query against the database and return the results. Input should be a valid SQL query. Use this tool to retrieve data from the database. For complex queries, first use list_tables_sql and info_sql to understand the database schema.`;\n\nfunction formatQueryResult(\n rows: Record<string, unknown>[],\n fields?: string[]\n): string {\n if (rows.length === 0) {\n return \"Query executed successfully. No rows returned.\";\n }\n\n const lines: string[] = [];\n\n const columns = fields || Object.keys(rows[0]);\n\n lines.push(columns.join(\" | \"));\n lines.push(\"-\".repeat(columns.join(\" | \").length));\n\n const maxRows = 50;\n const displayRows = rows.slice(0, maxRows);\n\n for (const row of displayRows) {\n const values = columns.map((col) => {\n const val = row[col];\n if (val === null) return \"NULL\";\n if (typeof val === \"object\") return JSON.stringify(val);\n return String(val);\n });\n lines.push(values.join(\" | \"));\n }\n\n if (rows.length > maxRows) {\n lines.push(`\\n... (${rows.length - maxRows} more rows not shown)`);\n }\n\n lines.push(`\\nTotal rows: ${rows.length}`);\n\n return lines.join(\"\\n\");\n}\n\nexport const createQuerySqlTool = ({ databaseKey, connectionString }: { databaseKey?: string; connectionString?: string }) => {\n return tool(\n async (\n {\n query,\n }: {\n query: string;\n },\n exe_config: any\n ) => {\n try {\n let dbKey: string;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n } else {\n return \"Error: Must provide databaseKey or connectionString\";\n }\n\n const trimmedQuery = query.trim();\n if (!trimmedQuery) {\n return \"Error: Empty query provided. Please provide a valid SQL query.\";\n }\n\n const database = sqlDatabaseManager.getDatabase(dbKey);\n const result = await database.executeQuery(trimmedQuery);\n\n return formatQueryResult(result.rows, result.fields);\n } catch (error) {\n return `Error executing query: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n },\n {\n name: \"query_sql\",\n description: QUERY_SQL_DESCRIPTION,\n schema: z.object({\n query: z\n .string()\n .describe(\n \"The SQL query to execute. Should be a valid SELECT, INSERT, UPDATE, or DELETE statement.\"\n ),\n }),\n }\n );\n};\n","/**\n * Code Execution Tool (code_eval)\n *\n * Executes code in the sandbox for supported languages (Python, JavaScript).\n * Requires a sandbox to be connected (e.g. via params.connectedSandbox when\n * building the agent). Uses the sandbox's code.executeCode API to run the\n * code in isolation.\n */\n\nimport z from \"zod\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { tool } from \"langchain\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst CODE_EVAL_DESCRIPTION = `Execute code in Python or JavaScript runtime.\n\nArgs:\n code: Code to execute\n language: Programming language ('python', 'javascript')\n\nReturns:\n Dict containing output, errors, and execution details`;\n\n\n\n\n\nexport const createCodeEvalTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(async (\n input: { language: \"python\" | \"javascript\"; code: string; timeout_sec?: number },\n exe_config: any\n ) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel })\n\n const result = await sandbox.code.executeCode({\n language: input.language,\n code: input.code,\n timeout: 300,\n });\n\n if (!result.ok) {\n const err = result.error as { content?: { message?: string, errors?: string[] } };\n return `Error executing ${input.language} code: ${err?.content?.message + (err?.content?.errors ? `\\n${err?.content?.errors.join(\"\\n\")}` : \"\")}`;\n }\n\n const data = result.body?.data;\n if (!data) {\n return \"Error: No response data from sandbox code execution.\";\n }\n\n const { stdout = \"\", stderr = \"\", exit_code, traceback } = data;\n const parts: string[] = [];\n\n if (stdout) {\n parts.push(`stdout:\\n${stdout}`);\n }\n if (stderr) {\n parts.push(`stderr:\\n${stderr}`);\n }\n if (traceback && traceback.length > 0) {\n parts.push(`traceback:\\n${traceback.join(\"\\n\")}`);\n }\n parts.push(`exit_code: ${exit_code ?? \"—\"}`);\n\n return parts.length > 0 ? parts.join(\"\\n\\n\") : `exit_code: ${exit_code ?? 0}`;\n } catch (e) {\n return `Error: ${e instanceof Error ? e.message : String(e)}`;\n }\n }, {\n name: \"execute_code\",\n description: CODE_EVAL_DESCRIPTION,\n schema: z.object({\n language: z\n .enum([\"python\", \"javascript\"])\n .describe(\"Programming language: 'python' or 'javascript'\"),\n code: z.string().describe(\"Code to execute\"),\n\n }),\n },);\n\n}","/**\n * SandboxLatticeManager\n *\n * Sandbox Lattice manager for registering and managing sandbox services\n * Supports creating, deleting, and managing sandbox instances\n */\n\nimport { SandboxClient } from \"@agent-infra/sandbox\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { RunSandboxConfig, SandboxManagerProtocol } from \"./SandboxManagerProtocol\";\nimport { normalizeSandboxName } from \"./utils\";\n\n\n\n/**\n * Default implementation of SandboxManagerProtocol\n * Manages sandboxes using SandboxClient instances stored in memory\n */\nclass DefaultSandboxManager implements SandboxManagerProtocol {\n private sandboxes: Map<string, SandboxClient> = new Map();\n /**\n * Track in-flight sandbox creation promises by normalized sandbox name.\n * This ensures that concurrent calls with the same name share the same Promise\n * and we do not trigger multiple creations for the same sandbox.\n */\n private creatingSandboxes: Map<string, Promise<SandboxClient>> = new Map();\n private baseURL: string;\n\n constructor(baseURL: string = \"http://localhost:8080\") {\n this.baseURL = baseURL;\n }\n\n getBaseURL(): string {\n return this.baseURL;\n }\n\n async createSandbox(sandboxName: string): Promise<SandboxClient> {\n\n\n if (sandboxName === \"global\") {\n const client = new SandboxClient({ baseUrl: `${this.baseURL}/sandbox/global`, environment: \"\" });\n this.sandboxes.set(\"global\", client);\n return client;\n }\n\n\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n // If sandbox client already exists, return it directly.\n const existingClient = this.sandboxes.get(normalizedName);\n if (existingClient) {\n return existingClient;\n }\n\n // If a creation is already in progress for this sandbox, return the same Promise.\n const inFlight = this.creatingSandboxes.get(normalizedName);\n if (inFlight) {\n return inFlight;\n }\n\n // Start a new creation Promise and store it so concurrent callers share it.\n const creationPromise = (async (): Promise<SandboxClient> => {\n const response = await fetch(`${this.baseURL}/api/v1/sandbox`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: normalizedName,\n image: \"enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:latest\"\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to create sandbox: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // Create a new SandboxClient for the sandbox\n // The baseURL should point to the specific sandbox endpoint\n const sandboxURL = `${this.baseURL}/sandbox/${normalizedName}`;\n const client = new SandboxClient({ baseUrl: sandboxURL, environment: \"\" });\n this.sandboxes.set(normalizedName, client);\n return client;\n })();\n\n // Ensure we clean up the in-flight map when the Promise settles.\n this.creatingSandboxes.set(normalizedName, creationPromise);\n creationPromise\n .catch(() => {\n // On failure, remove the in-flight entry so future calls can retry.\n this.creatingSandboxes.delete(normalizedName);\n })\n .then(() => {\n // On success, also remove the in-flight entry; the client is now in sandboxes map.\n this.creatingSandboxes.delete(normalizedName);\n });\n\n return creationPromise;\n }\n\n async deleteSandbox(sandboxName: string): Promise<void> {\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n if (!this.sandboxes.has(normalizedName)) {\n throw new Error(`Sandbox ${sandboxName} (normalized: ${normalizedName}) not found`);\n }\n const response = await fetch(`${this.baseURL}/api/v1/sandbox/${normalizedName}`, {\n method: \"DELETE\",\n });\n if (!response.ok) {\n throw new Error(`Failed to delete sandbox: ${response.statusText}`);\n }\n this.sandboxes.delete(normalizedName);\n }\n\n async getSandbox(sandboxName: string): Promise<SandboxClient> {\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n const client = this.sandboxes.get(normalizedName);\n if (!client) {\n throw new Error(`Sandbox ${sandboxName} (normalized: ${normalizedName}) not found`);\n }\n return client;\n }\n\n async listSandboxes(): Promise<SandboxClient[]> {\n return Array.from(this.sandboxes.values());\n }\n\n async getSandboxStatus(sandboxName: string): Promise<string> {\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n if (!this.sandboxes.has(normalizedName)) {\n throw new Error(`Sandbox ${sandboxName} (normalized: ${normalizedName}) not found`);\n }\n // Try to get context to check if sandbox is active\n try {\n const client = this.sandboxes.get(normalizedName)!;\n const context = await client.sandbox.getContext();\n return context.ok ? \"active\" : \"inactive\";\n } catch {\n return \"unknown\";\n }\n }\n async getSandboxFromConfig(config: RunSandboxConfig): Promise<SandboxClient> {\n if (config.isolatedLevel === \"agent\") {\n return this.createSandbox(config.assistant_id);\n } else if (config.isolatedLevel === \"thread\") {\n return this.createSandbox(config.thread_id);\n } else {\n return this.createSandbox(\"global\");\n }\n }\n}\n\n/**\n * SandboxLatticeManager - Singleton sandbox Lattice manager\n * Responsible for registering and managing various sandbox service Lattices\n */\nexport class SandboxLatticeManager extends BaseLatticeManager<SandboxManagerProtocol> {\n private static _instance: SandboxLatticeManager;\n\n /**\n * Get SandboxLatticeManager singleton instance\n */\n public static getInstance(): SandboxLatticeManager {\n if (!SandboxLatticeManager._instance) {\n SandboxLatticeManager._instance = new SandboxLatticeManager();\n }\n return SandboxLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"sandbox_manager\";\n }\n\n /**\n * Register sandbox Lattice\n * @param key Lattice key name\n * @param manager Optional sandbox manager. If not provided, will create a default one.\n * @param baseURL Base URL for sandbox service (used when creating default manager)\n */\n public registerLattice(\n key: string,\n config: { manager?: SandboxManagerProtocol, baseURL?: string }\n ): void {\n const { manager, baseURL } = config;\n // Use provided manager or create default one\n const sandboxManager: SandboxManagerProtocol =\n manager || new DefaultSandboxManager(baseURL);\n\n\n // Call base class register method\n this.register(key, sandboxManager);\n }\n\n /**\n * Get SandboxLattice\n * @param key Lattice key name\n */\n public getSandboxLattice(key: string): SandboxManagerProtocol {\n const sandboxLattice = this.get(key);\n if (!sandboxLattice) {\n throw new Error(`SandboxLattice ${key} not found`);\n }\n return sandboxLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): SandboxManagerProtocol[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const sandboxLatticeManager =\n SandboxLatticeManager.getInstance();\n\nexport const getSandBoxManager = (key: string = \"default\") => {\n if (!sandboxLatticeManager.hasLattice(key)) {\n throw new Error(`Sandbox ${key} not configured. Ensure the sandbox manager is registered and the agent is built with connectedSandbox.`);\n }\n const sandboxManager = sandboxLatticeManager.getSandboxLattice(key);\n return sandboxManager;\n}","/**\n * Sandbox name normalization utility\n * \n * Normalizes sandbox names to comply with RFC 1123 subdomain naming requirements:\n * - Only lowercase alphanumeric characters, '-' or '.'\n * - Must start and end with an alphanumeric character\n * - No underscores or other special characters\n */\n\n/**\n * Normalize a sandbox name to be RFC 1123 compliant\n * \n * @param name - The sandbox name to normalize\n * @returns Normalized sandbox name that complies with RFC 1123 subdomain rules\n * \n * @example\n * normalizeSandboxName(\"sandbox_agent\") // returns \"sandbox-agent\"\n * normalizeSandboxName(\"My-Sandbox\") // returns \"my-sandbox\"\n * normalizeSandboxName(\"test.sandbox\") // returns \"test.sandbox\"\n * normalizeSandboxName(\"_invalid_\") // returns \"invalid\"\n */\nexport function normalizeSandboxName(name: string): string {\n if (!name || typeof name !== \"string\") {\n throw new Error(\"Sandbox name must be a non-empty string\");\n }\n\n // Convert to lowercase\n let normalized = name.toLowerCase();\n\n // Replace underscores with hyphens\n normalized = normalized.replace(/_/g, \"-\");\n\n // Remove any characters that are not alphanumeric, hyphen, or dot\n normalized = normalized.replace(/[^a-z0-9.-]/g, \"\");\n\n // Remove leading/trailing dots and hyphens (must start/end with alphanumeric)\n normalized = normalized.replace(/^[.-]+|[.-]+$/g, \"\");\n\n // Replace consecutive dots or hyphens with a single hyphen\n normalized = normalized.replace(/[.-]{2,}/g, \"-\");\n\n // Ensure it doesn't start or end with a dot or hyphen after cleanup\n normalized = normalized.replace(/^[.-]+|[.-]+$/g, \"\");\n\n // If the result is empty, throw an error\n if (!normalized) {\n throw new Error(\n `Sandbox name \"${name}\" cannot be normalized to a valid RFC 1123 subdomain name`\n );\n }\n\n // Ensure it starts and ends with alphanumeric\n // If it doesn't start with alphanumeric, prepend 'sandbox-'\n if (!/^[a-z0-9]/.test(normalized)) {\n normalized = `sandbox-${normalized}`;\n }\n\n // If it doesn't end with alphanumeric, append '-0'\n if (!/[a-z0-9]$/.test(normalized)) {\n normalized = `${normalized}-0`;\n }\n\n // Final validation: ensure it matches RFC 1123 pattern\n // Pattern: [a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\n const rfc1123Pattern = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;\n \n if (!rfc1123Pattern.test(normalized)) {\n // If still invalid, create a safe fallback\n normalized = normalized\n .replace(/[^a-z0-9-]/g, \"-\") // Replace any remaining invalid chars with hyphen\n .replace(/^-+|-+$/g, \"\") // Remove leading/trailing hyphens\n .replace(/-{2,}/g, \"-\"); // Replace consecutive hyphens\n \n // Ensure it starts and ends with alphanumeric\n if (!/^[a-z0-9]/.test(normalized)) {\n normalized = `sandbox-${normalized}`;\n }\n if (!/[a-z0-9]$/.test(normalized)) {\n normalized = `${normalized}0`;\n }\n }\n\n return normalized;\n}\n\n/**\n * Validate if a sandbox name is RFC 1123 compliant\n * \n * @param name - The sandbox name to validate\n * @returns true if the name is valid, false otherwise\n */\nexport function isValidSandboxName(name: string): boolean {\n if (!name || typeof name !== \"string\") {\n return false;\n }\n\n const rfc1123Pattern = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;\n return rfc1123Pattern.test(name.toLowerCase());\n}\n","/**\n * Code File Execution Tool (code_execute_file)\n *\n * Executes a code file from the sandbox filesystem. Only supports Python (.py) and JavaScript (.js, .mjs) files.\n * Other file types are not supported. The tool reads the file content from the sandbox and executes it\n * using the sandbox's code execution API. Language is automatically inferred from file extension.\n */\n\nimport z from \"zod\";\nimport { tool, type StructuredTool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\nimport * as path from \"path\";\n\nconst CODE_EXECUTE_FILE_DESCRIPTION = `Execute a code file from the sandbox filesystem. Only supports Python (.py) and JavaScript (.js, .mjs) files. Other file types are not supported. The tool reads the file content and executes it in an isolated sandbox environment. Language is automatically inferred from the file extension. Output is returned via stdout; errors appear in stderr and traceback.`;\n\nfunction inferLanguageFromPath(filePath: string): \"python\" | \"javascript\" | null {\n const ext = path.extname(filePath).toLowerCase();\n if (ext === \".py\") {\n return \"python\";\n } else if (ext === \".js\" || ext === \".mjs\") {\n return \"javascript\";\n }\n return null;\n}\n\nexport const createCodeExecuteFileTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }): StructuredTool => {\n return tool(\n async (input: { file_path: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const context = await sandbox.sandbox.getContext();\n if (!context.ok) {\n return `Error: ${context.error}`;\n }\n const homeDir = context.body?.home_dir;\n const resolvedFilePath = path.join(homeDir, input.file_path);\n\n const language = inferLanguageFromPath(input.file_path);\n if (!language) {\n return `Error: Unsupported file type. This tool only supports Python (.py) and JavaScript (.js, .mjs) files.`;\n }\n\n const readResult = await sandbox.file.readFile({\n file: resolvedFilePath,\n });\n\n if (!readResult.ok) {\n const err = readResult.error as { content?: { message?: string } };\n return `Error reading file '${input.file_path}': ${err?.content?.message ?? JSON.stringify(readResult.error)}`;\n }\n\n const fileContent = readResult.body?.data?.content;\n if (fileContent === undefined || fileContent === null) {\n return `Error: File '${input.file_path}' is empty or could not be read.`;\n }\n\n const result = await sandbox.code.executeCode({\n language: language,\n code: fileContent,\n timeout: 300,\n });\n\n if (!result.ok) {\n const err = result.error as { content?: { message?: string } };\n return `Error executing ${language} file '${input.file_path}': ${err?.content?.message ?? JSON.stringify(result.error)}`;\n }\n\n const data = result.body?.data;\n if (!data) {\n return \"Error: No response data from sandbox code execution.\";\n }\n\n const { stdout = \"\", stderr = \"\", exit_code, traceback } = data;\n const parts: string[] = [];\n\n if (stdout) {\n parts.push(`stdout:\\n${stdout}`);\n }\n if (stderr) {\n parts.push(`stderr:\\n${stderr}`);\n }\n if (traceback && traceback.length > 0) {\n parts.push(`traceback:\\n${traceback.join(\"\\n\")}`);\n }\n parts.push(`exit_code: ${exit_code ?? \"—\"}`);\n\n return parts.length > 0 ? parts.join(\"\\n\\n\") : `exit_code: ${exit_code ?? 0}`;\n } catch (e) {\n return `Error: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"execute_code_file\",\n description: CODE_EXECUTE_FILE_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Path to the code file to execute (absolute path in sandbox filesystem). Only supports .py (Python) and .js/.mjs (JavaScript) files.\"),\n }),\n }\n );\n};\n","/**\n * Convert to Markdown Tool (convert_to_markdown)\n *\n * Convert a resource described by an http:, https:, file: or data: URI to markdown.\n * This tool fetches or reads content from various URI schemes and converts it to markdown format.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { promises as fs } from \"fs\";\nimport path from \"path\";\nimport { getSandBoxManager } from \"@sandbox_lattice/SandboxLatticeManager\";\n\nconst CONVERT_TO_MARKDOWN_DESCRIPTION = `Convert a resource described by an http:, https:, file: or data: URI to markdown.\n\nArgs:\n uri (str): The URI to convert. Supported schemes:\n - http:// or https://: Fetch content from URL\n - file://: Read content from local file\n - data:: Decode data URI content\n\nReturns:\n str: The content converted to markdown format.`;\n\nregisterToolLattice(\n \"convert_to_markdown\",\n {\n name: \"convert_to_markdown\",\n description: CONVERT_TO_MARKDOWN_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n uri: z.string().describe(\"The URI to convert.\"),\n }),\n },\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig(runConfig);\n sandbox\n const result = await sandbox.util.convertToMarkdown({\n uri: input.uri,\n });\n if (!result.ok) {\n return `Error converting to markdown: ${result.error}`;\n }\n return result.body.data;\n } catch (e) {\n return `Error converting to markdown: ${e instanceof Error ? e.message : String(e)}`;\n }\n }\n);","/**\n * Browser Navigate Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_NAVIGATE_DESCRIPTION = `Navigate to a URL.\n\nArgs:\n url (str): The URL to navigate to.\n`;\n\nexport const createBrowserNavigateTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { url: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_navigate\", {\n url: input.url,\n });\n if (!result.ok) {\n return `Error navigating to URL: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Navigated to URL\";\n } catch (e) {\n return `Error navigating to URL: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_navigate\",\n description: BROWSER_NAVIGATE_DESCRIPTION,\n schema: z.object({\n url: z.string().describe(\"The URL to navigate to.\"),\n }),\n }\n );\n};\n","/**\n * Browser Click Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_CLICK_DESCRIPTION = `Click an element on the page, before using the tool, use \\`browser_get_clickable_elements\\` to get the index of the element, but not call \\`browser_get_clickable_elements\\` multiple times.\n\nArgs:\n index (int): Index of the element to click\n`;\n\nexport const createBrowserClickTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { index: number }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_click\", {\n index: input.index,\n });\n if (!result.ok) {\n return `Error clicking element: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Element clicked successfully\";\n } catch (e) {\n return `Error clicking element: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_click\",\n description: BROWSER_CLICK_DESCRIPTION,\n schema: z.object({\n index: z.number().describe(\"Index of the element to click\"),\n }),\n }\n );\n};\n","/**\n * Browser Get Text Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_TEXT_DESCRIPTION = `Get the text content of the current page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetTextTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_text\", {});\n if (!result.ok) {\n return `Error getting text content: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Text content retrieved\";\n } catch (e) {\n return `Error getting text content: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_text\",\n description: BROWSER_GET_TEXT_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Markdown Tool\n */\n\nimport z from \"zod\";\nimport { tool, type StructuredTool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_MARKDOWN_DESCRIPTION = `Get the markdown content of the current page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetMarkdownTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }): StructuredTool => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_markdown\", {});\n if (!result.ok) {\n return `Error getting markdown: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content ?? \"Markdown content retrieved\";\n } catch (e) {\n return `Error getting markdown: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_markdown\",\n description: BROWSER_GET_MARKDOWN_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Evaluate Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_EVALUATE_DESCRIPTION = `Execute JavaScript in the browser console.\n\nArgs:\n script (str): JavaScript code to execute, () => { /* code */ }\n`;\n\nexport const createBrowserEvaluateTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { script: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_evaluate\", {\n script: input.script,\n });\n if (!result.ok) {\n return `Error executing JavaScript: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"JavaScript executed successfully\";\n } catch (e) {\n return `Error executing JavaScript: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_evaluate\",\n description: BROWSER_EVALUATE_DESCRIPTION,\n schema: z.object({\n script: z.string().describe(\"JavaScript code to execute, () => { /* code */ }\"),\n }),\n }\n );\n};\n","/**\n * Browser Screenshot Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SCREENSHOT_DESCRIPTION = `Take a screenshot of the current page or a specific element.\n\nArgs:\n name (str): Name for the screenshot\n selector (str): CSS selector for element to screenshot\n index (int): index of the element to screenshot\n width (int): Width in pixels (default: viewport width)\n height (int): Height in pixels (default: viewport height)\n fullPage (bool): Full page screenshot (default: false)\n highlight (bool): Highlight the element\n`;\n\nexport const createBrowserScreenshotTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: {\n name?: string;\n selector?: string;\n index?: number;\n width?: number;\n height?: number;\n fullPage?: boolean;\n highlight?: boolean;\n }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_screenshot\", {\n name: input.name,\n selector: input.selector,\n index: input.index,\n width: input.width,\n height: input.height,\n fullPage: input.fullPage,\n highlight: input.highlight,\n });\n if (!result.ok) {\n return `Error taking screenshot: ${JSON.stringify(result.error.content)}`;\n }\n const lines = [];\n for (const item of result.body?.data?.content ?? []) {\n if (item.type === \"image\") {\n const base64Data = item.data;\n const buffer = Buffer.from(base64Data, \"base64\");\n const screenshotPath = `/home/gem/screenshots/screenshot_${input.name}.png`;\n const uploadResult = await sandbox.file.uploadFile({\n file: buffer,\n path: screenshotPath,\n });\n if (uploadResult.ok) {\n const screenshot_md = [\n \"\",\n \"Screenshot saved!\",\n \"```attachments\",\n JSON.stringify([{ id: screenshotPath, name: `screenshot_${input.name}.png` }]),\n \"```\",\n ].join(\"\\n\");\n lines.push(screenshot_md);\n } else {\n lines.push(`Failed to save screenshot: ${JSON.stringify(uploadResult.error)}`);\n }\n } else {\n lines.push(`${item.text}`);\n }\n }\n return lines.length > 0 ? lines.join(\"\\n\") : \"No Content\";\n } catch (e) {\n return `Error taking screenshot: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_screenshot\",\n description: BROWSER_SCREENSHOT_DESCRIPTION,\n schema: z.object({\n name: z.string().optional().describe(\"Name for the screenshot\"),\n selector: z.string().optional().describe(\"CSS selector for element to screenshot\"),\n index: z.number().optional().describe(\"index of the element to screenshot\"),\n width: z.number().optional().describe(\"Width in pixels (default: viewport width)\"),\n height: z.number().optional().describe(\"Height in pixels (default: viewport height)\"),\n fullPage: z.boolean().optional().describe(\"Full page screenshot (default: false)\"),\n highlight: z.boolean().default(false).describe(\"Highlight the element\"),\n }),\n }\n );\n};\n","/**\n * Browser Scroll Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SCROLL_DESCRIPTION = `Scroll the page.\n\nArgs:\n amount (int): Pixels to scroll (positive for down, negative for up), if the amount is not provided, scroll to the bottom of the page\n`;\n\nexport const createBrowserScrollTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { amount?: number }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_scroll\", {\n amount: input.amount,\n });\n if (!result.ok) {\n return `Error scrolling page: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Page scrolled successfully\";\n } catch (e) {\n return `Error scrolling page: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_scroll\",\n description: BROWSER_SCROLL_DESCRIPTION,\n schema: z.object({\n amount: z.number().optional().describe(\"Pixels to scroll (positive for down, negative for up)\"),\n }),\n }\n );\n};\n","/**\n * Browser Form Input Fill Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_FORM_INPUT_FILL_DESCRIPTION = `Fill out an input field, before using the tool, Either 'index' or 'selector' must be provided.\n\nArgs:\n selector (str): CSS selector for input field, priority use index, if index is not provided, use selector\n index (int): Index of the element to fill\n value (str): Value to fill\n clear (bool): Whether to clear existing text before filling\n`;\n\nexport const createBrowserFormInputFillTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: {\n selector?: string;\n index?: number;\n value: string;\n clear?: boolean;\n }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_form_input_fill\", {\n selector: input.selector,\n index: input.index,\n value: input.value,\n clear: input.clear,\n });\n if (!result.ok) {\n return `Error filling input field: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Input field filled successfully\";\n } catch (e) {\n return `Error filling input field: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_form_input_fill\",\n description: BROWSER_FORM_INPUT_FILL_DESCRIPTION,\n schema: z.object({\n selector: z.string().optional().describe(\"CSS selector for input field\"),\n index: z.number().optional().describe(\"Index of the element to fill\"),\n value: z.string().describe(\"Value to fill\"),\n clear: z.boolean().default(false).describe(\"Whether to clear existing text before filling\"),\n }),\n }\n );\n};\n","/**\n * Browser Select Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SELECT_DESCRIPTION = `Select an element on the page with index, Either 'index' or 'selector' must be provided.\n\nArgs:\n index (int): Index of the element to select\n selector (str): CSS selector for element to select\n value (str): Value to select\n`;\n\nexport const createBrowserSelectTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: {\n index?: number;\n selector?: string;\n value: string;\n }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_select\", {\n index: input.index,\n selector: input.selector,\n value: input.value,\n });\n if (!result.ok) {\n return `Error selecting element: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Element selected successfully\";\n } catch (e) {\n return `Error selecting element: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_select\",\n description: BROWSER_SELECT_DESCRIPTION,\n schema: z.object({\n index: z.number().optional().describe(\"Index of the element to select\"),\n selector: z.string().optional().describe(\"CSS selector for element to select\"),\n value: z.string().describe(\"Value to select\"),\n }),\n }\n );\n};\n","/**\n * Browser Hover Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_HOVER_DESCRIPTION = `Hover an element on the page, Either 'index' or 'selector' must be provided.\n\nArgs:\n index (int): Index of the element to hover\n selector (str): CSS selector for element to hover\n`;\n\nexport const createBrowserHoverTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { index?: number; selector?: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_hover\", {\n index: input.index,\n selector: input.selector,\n });\n if (!result.ok) {\n return `Error hovering element: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Element hovered successfully\";\n } catch (e) {\n return `Error hovering element: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_hover\",\n description: BROWSER_HOVER_DESCRIPTION,\n schema: z.object({\n index: z.number().optional().describe(\"Index of the element to hover\"),\n selector: z.string().optional().describe(\"CSS selector for element to hover\"),\n }),\n }\n );\n};\n","/**\n * Browser Go Back Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GO_BACK_DESCRIPTION = `Go back to the previous page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGoBackTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_go_back\", {});\n if (!result.ok) {\n return `Error going back: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Went back to previous page\";\n } catch (e) {\n return `Error going back: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_go_back\",\n description: BROWSER_GO_BACK_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Go Forward Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GO_FORWARD_DESCRIPTION = `Go forward to the next page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGoForwardTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_go_forward\", {});\n if (!result.ok) {\n return `Error going forward: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Went forward to next page\";\n } catch (e) {\n return `Error going forward: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_go_forward\",\n description: BROWSER_GO_FORWARD_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser New Tab Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_NEW_TAB_DESCRIPTION = `Open a new tab.\n\nArgs:\n url (str): URL to open in the new tab\n`;\n\nexport const createBrowserNewTabTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { url: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_new_tab\", {\n url: input.url,\n });\n if (!result.ok) {\n return `Error opening new tab: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"New tab opened successfully\";\n } catch (e) {\n return `Error opening new tab: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_new_tab\",\n description: BROWSER_NEW_TAB_DESCRIPTION,\n schema: z.object({\n url: z.string().describe(\"URL to open in the new tab\"),\n }),\n }\n );\n};\n","/**\n * Browser Tab List Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_TAB_LIST_DESCRIPTION = `Get the list of tabs.\n\nArgs:\n None\n`;\n\nexport const createBrowserTabListTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_tab_list\", {});\n if (!result.ok) {\n return `Error getting tab list: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Tab list retrieved successfully\";\n } catch (e) {\n return `Error getting tab list: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_tab_list\",\n description: BROWSER_TAB_LIST_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Switch Tab Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SWITCH_TAB_DESCRIPTION = `Switch to a specific tab.\n\nArgs:\n index (int): Tab index to switch to\n`;\n\nexport const createBrowserSwitchTabTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { index: number }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_switch_tab\", {\n index: input.index,\n });\n if (!result.ok) {\n return `Error switching tab: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Tab switched successfully\";\n } catch (e) {\n return `Error switching tab: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_switch_tab\",\n description: BROWSER_SWITCH_TAB_DESCRIPTION,\n schema: z.object({\n index: z.number().describe(\"Tab index to switch to\"),\n }),\n }\n );\n};\n","/**\n * Browser Close Tab Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_CLOSE_TAB_DESCRIPTION = `Close the current tab.\n\nArgs:\n None\n`;\n\nexport const createBrowserCloseTabTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_close_tab\", {});\n if (!result.ok) {\n return `Error closing tab: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Current tab closed successfully\";\n } catch (e) {\n return `Error closing tab: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_close_tab\",\n description: BROWSER_CLOSE_TAB_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Close Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_CLOSE_DESCRIPTION = `Close the browser when the task is done and the browser is not needed anymore.\n\nArgs:\n None\n`;\n\nexport const createBrowserCloseTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_close\", {});\n if (!result.ok) {\n return `Error closing browser: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Browser closed successfully\";\n } catch (e) {\n return `Error closing browser: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_close\",\n description: BROWSER_CLOSE_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Press Key Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_PRESS_KEY_DESCRIPTION = `Press a key on the keyboard.\n\nArgs:\n key (str): Name of the key to press or a character to generate, such as Enter, Tab, Escape, Backspace, Delete, Insert, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, PageUp, PageDown, Home, End, ShiftLeft, ShiftRight, ControlLeft, ControlRight, AltLeft, AltRight, MetaLeft, MetaRight, CapsLock, PrintScreen, ScrollLock, Pause, ContextMenu\n`;\n\nexport const createBrowserPressKeyTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { key: \"Enter\" | \"Tab\" | \"Escape\" | \"Backspace\" | \"Delete\" | \"Insert\" | \"F1\" | \"F2\" | \"F3\" | \"F4\" | \"F5\" | \"F6\" | \"F7\" | \"F8\" | \"F9\" | \"F10\" | \"F11\" | \"F12\" | \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"ArrowDown\" | \"PageUp\" | \"PageDown\" | \"Home\" | \"End\" | \"ShiftLeft\" | \"ShiftRight\" | \"ControlLeft\" | \"ControlRight\" | \"AltLeft\" | \"AltRight\" | \"MetaLeft\" | \"MetaRight\" | \"CapsLock\" | \"PrintScreen\" | \"ScrollLock\" | \"Pause\" | \"ContextMenu\" }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_press_key\", {\n key: input.key,\n });\n if (!result.ok) {\n return `Error pressing key: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? `Key ${input.key} pressed successfully`;\n } catch (e) {\n return `Error pressing key: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_press_key\",\n description: BROWSER_PRESS_KEY_DESCRIPTION,\n schema: z.object({\n key: z.enum([\n \"Enter\", \"Tab\", \"Escape\", \"Backspace\", \"Delete\", \"Insert\",\n \"F1\", \"F2\", \"F3\", \"F4\", \"F5\", \"F6\", \"F7\", \"F8\", \"F9\", \"F10\", \"F11\", \"F12\",\n \"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\",\n \"PageUp\", \"PageDown\", \"Home\", \"End\",\n \"ShiftLeft\", \"ShiftRight\", \"ControlLeft\", \"ControlRight\",\n \"AltLeft\", \"AltRight\", \"MetaLeft\", \"MetaRight\",\n \"CapsLock\", \"PrintScreen\", \"ScrollLock\", \"Pause\", \"ContextMenu\"\n ]).describe(\"Name of the key to press\"),\n }),\n }\n );\n};\n","/**\n * Browser Read Links Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_READ_LINKS_DESCRIPTION = `Get all links on the current page.\n\nArgs:\n None\n`;\n\nexport const createBrowserReadLinksTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_read_links\", {});\n if (!result.ok) {\n return `Error reading links: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Links retrieved successfully\";\n } catch (e) {\n return `Error reading links: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_read_links\",\n description: BROWSER_READ_LINKS_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Clickable Elements Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_CLICKABLE_ELEMENTS_DESCRIPTION = `Get the clickable or hoverable or selectable elements on the current page, don't call this tool multiple times.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetClickableElementsTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_clickable_elements\", {});\n if (!result.ok) {\n return `Error getting clickable elements: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Clickable elements retrieved successfully\";\n } catch (e) {\n return `Error getting clickable elements: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_clickable_elements\",\n description: BROWSER_GET_CLICKABLE_ELEMENTS_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Download List Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_DOWNLOAD_LIST_DESCRIPTION = `Get the list of downloaded files.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetDownloadListTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_download_list\", {});\n if (!result.ok) {\n return `Error getting download list: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Download list retrieved successfully\";\n } catch (e) {\n return `Error getting download list: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_download_list\",\n description: BROWSER_GET_DOWNLOAD_LIST_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Info Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_INFO_DESCRIPTION = `Get information about browser, like CDP URL, viewport size, etc.\n\nArgs:\n request (Dict): The incoming request context.\n\nReturns:\n Dict containing browser information including CDP URL, viewport dimensions, and other browser metadata.`;\n\nexport const createBrowserGetInfoTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.browser.getInfo();\n if (!result.ok) {\n return `Error getting browser info: ${result.error}`;\n }\n return JSON.stringify(result.body.data, undefined, 2);\n } catch (e) {\n return `Error getting browser info: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_info\",\n description: BROWSER_GET_INFO_DESCRIPTION,\n schema: z.object({}),\n }\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 AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n MiddlewareType,\n} from \"@axiom-lattice/protocols\";\nimport { ReactAgent } from \"langchain\";\n\n// Re-export types from protocols\nexport {\n AgentType,\n AgentConfig,\n ReactAgentConfig,\n DeepAgentConfig,\n AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n};\n\n// Agent客户端类型 - CompiledStateGraph\nexport type AgentClient =\n | CompiledStateGraph<any, any, any, any, any>\n | ReactAgent<any, any, any, any>;\n\n// AgentLattice接口定义\nexport interface AgentLattice {\n config: AgentConfig;\n client?: AgentClient | undefined;\n}\n\n// Middleware configuration\nexport interface MiddlewareConfig {\n id: string;\n type: MiddlewareType;\n name: string;\n description: string;\n enabled: boolean;\n config: Record<string, any>;\n}\n\n// Agent构建参数接口\nexport interface AgentBuildParams {\n middleware?: MiddlewareConfig[];\n skillCategories?: string[];\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","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 createReactAgentSchema = (\n schema?: z.ZodObject<any, any, any, any, any>\n) => {\n return schema ? MessagesZodState.extend(schema.shape) : undefined;\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, AgentClient, MiddlewareConfig } 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 } from \"./state\";\nimport { createAgent } from \"langchain\";\nimport { sandboxLatticeManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { SandboxFilesystem } from \"../../deep_agent_new/backends/sandboxFiles\";\nimport { createCommonMiddlewares } from \"./commonMiddleware\";\n\nexport class ReActAgentGraphBuilder implements AgentGraphBuilder {\n private createFilesystemBackendFactory(\n middlewareConfigs: MiddlewareConfig[]\n ): ((config: { state: unknown; store?: any }) => Promise<any>) | undefined {\n const filesystemConfig = middlewareConfigs.find(m => m.type === \"filesystem\");\n\n if (!filesystemConfig || !filesystemConfig.enabled) {\n return undefined;\n }\n\n const isolatedLevel = filesystemConfig.config?.isolatedLevel || \"global\";\n\n return async (config: { state: unknown }) => {\n let sandboxName = \"global\";\n\n if (isolatedLevel === \"agent\") {\n sandboxName = \"agent\";\n } else if (isolatedLevel === \"thread\") {\n sandboxName = \"thread\";\n }\n\n const sandboxManager = sandboxLatticeManager.getSandboxLattice(\"default\");\n if (!sandboxManager) {\n throw new Error(\"Sandbox manager not found\");\n }\n\n return new SandboxFilesystem({\n sandboxInstance: await sandboxManager.createSandbox(sandboxName),\n });\n };\n }\n\n private createMiddlewares(middlewareConfigs: MiddlewareConfig[]) {\n return createCommonMiddlewares(middlewareConfigs);\n }\n\n /**\n * 构建ReAct Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(agentLattice: AgentLattice, params: AgentBuildParams): AgentClient {\n const tools = params.tools\n .map((t) => {\n const tool = getToolClient(t.key);\n return tool;\n })\n .filter((tool) => tool !== undefined);\n\n const stateSchema = createReactAgentSchema(params.stateSchema);\n\n const middlewareConfigs = params.middleware || [];\n const filesystemBackend = this.createFilesystemBackendFactory(middlewareConfigs);\n const middlewares = createCommonMiddlewares(middlewareConfigs, filesystemBackend);\n\n return createAgent({\n model: params.model,\n tools: tools,\n systemPrompt: params.prompt,\n name: agentLattice.config.name,\n checkpointer: getCheckpointSaver(\"default\"),\n stateSchema: stateSchema as any,\n middleware: middlewares as any,\n });\n }\n}\n","/**\n * SandboxFilesystem: A sandboxed filesystem backend that connects to a remote sandbox via SDK.\n *\n * This backend provides a secure, isolated filesystem environment by connecting to a remote\n * sandbox service through the @agent-infra/sandbox SDK. It implements the BackendProtocol\n * interface and delegates all file operations to the remote sandbox.\n *\n * Features:\n * - Remote sandbox connection via HTTP API\n * - Virtual path support (all paths start with /)\n * - Path traversal prevention\n * - Full BackendProtocol implementation\n */\n\nimport { SandboxClient } from \"@agent-infra/sandbox\";\nimport * as path from \"path\";\nimport micromatch from \"micromatch\";\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileInfo,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n checkEmptyContent,\n formatContentWithLineNumbers,\n performStringReplacement,\n grepMatchesFromFiles,\n} from \"./utils.js\";\n\n/**\n * Sandboxed filesystem backend that connects to a remote sandbox service.\n *\n * All file operations are delegated to the remote sandbox via the SDK.\n * Paths are treated as virtual absolute paths (starting with /).\n */\nexport class SandboxFilesystem implements BackendProtocol {\n private sandbox: SandboxClient;\n private maxFileSizeBytes: number;\n private workingDirectory: string;\n private baseURL: string;\n private homeDir: string;\n\n /**\n * Create a new SandboxFilesystem instance.\n *\n * @param options - Configuration options\n * @param options.baseURL - Base URL of the sandbox service (default: 'http://localhost:8080')\n * @param options.maxFileSizeMb - Maximum file size in MB (default: 10)\n * @param options.sandboxInstance - Optional Sandbox instance (if provided, baseURL is ignored)\n */\n constructor(\n options: {\n baseURL?: string;\n workingDirectory?: string;\n maxFileSizeMb?: number;\n sandboxInstance?: SandboxClient;\n } = {}\n ) {\n const {\n baseURL = \"http://localhost:8080\",\n workingDirectory = \"/\",\n maxFileSizeMb = 10,\n sandboxInstance,\n } = options;\n\n this.sandbox = sandboxInstance || new SandboxClient({ baseUrl: baseURL, environment: \"\" });\n this.sandbox.mcp.listMcpServers().then((servers) => {\n\n });\n this.sandbox.mcp.listMcpTools(\"browser\").then((tools) => {\n console.log(tools);\n });\n\n // this.sandbox.sandbox.getContext().then((context) => {\n // if (!context.ok) {\n // console.error(context.error);\n // } else {\n // console.log(context?.body);\n // }\n // });\n this.baseURL = baseURL;\n this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024;\n this.workingDirectory = workingDirectory;\n this.homeDir = \"/home/gem\";\n }\n private resolvePath(virtualPath: string): string {\n return path.join(this.homeDir, this.workingDirectory, virtualPath);\n }\n\n /**\n * Convert a real filesystem path to a virtual path.\n *\n * @param realPath - Real filesystem path\n * @returns Virtual path starting with /\n */\n private toVirtualPath(realPath: string): string {\n const rootPath = path.join(this.homeDir, this.workingDirectory);\n const relative = path.relative(rootPath, realPath);\n const normalized = relative.split(path.sep).join(\"/\");\n return \"/\" + normalized;\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param dirPath - Virtual directory path (must start with /)\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(dirPath: string): Promise<FileInfo[]> {\n try {\n const resolvedPath = this.resolvePath(dirPath);\n\n const result = await this.sandbox.file.listPath({\n path: resolvedPath,\n recursive: false,\n show_hidden: false,\n max_depth: 0,\n include_size: false,\n include_permissions: false,\n sort_by: \"name\",\n sort_desc: false,\n });\n if (!result.ok) {\n throw result.error;\n }\n const files: FileInfo[] = result.body?.data?.files?.map((file) => ({\n path: this.toVirtualPath(file.path),\n is_dir: file.is_directory,\n size: file.size,\n modified_at: file.modified_time\n })) || [];\n return files;\n } catch (e: any) {\n console.error(`Error listing files in ${dirPath}:`, e);\n return [];\n }\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Virtual file path (must start with /)\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 10000\n ): Promise<string> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n const result = await this.sandbox.file.readFile({\n file: resolvedPath,\n start_line: offset,\n end_line: limit,\n });\n if (!result.ok) {\n throw result.error;\n }\n content = result.body?.data?.content || \"\";\n return content;\n\n } catch (e: any) {\n return `Error: File '${filePath}' not found`;\n }\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Virtual file path (must start with /)\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n try {\n const content = await this.read(filePath);\n return {\n content: content.split(\"\\n\"),\n created_at: new Date().toISOString(),\n modified_at: new Date().toISOString(),\n };\n\n } catch (e: any) {\n throw new Error(`Error reading file '${filePath}': ${e.message}`);\n }\n\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n *\n * @param filePath - Virtual file path (must start with /)\n * @param content - File content as string\n * @returns WriteResult with error populated on failure\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n try {\n\n const resolvedPath = this.resolvePath(filePath);\n // const mkdirResult = await this.sandbox.shell.execCommand({\n // command: `mkdir -p \"$(dirname \"${resolvedPath}\")\"`\n // })\n // if (!mkdirResult.ok) {\n // console.error(mkdirResult.error);\n // throw mkdirResult.error\n // }\n const result = await this.sandbox.file.writeFile({\n file: resolvedPath,\n content: content,\n \"encoding\": \"utf-8\",\n \"append\": false,\n // sudo: true\n });\n if (!result.ok) {\n console.error(result.error);\n throw result.error\n }\n\n return {\n path: filePath,\n filesUpdate: {\n [filePath]: {\n content: content.split(\"\\n\"),\n created_at: new Date().toISOString(),\n modified_at: new Date().toISOString(),\n }\n }\n }\n } catch (e: any) {\n throw new Error(`Error writing file '${filePath}': ${e.message}`);\n }\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n *\n * @param filePath - Virtual file path (must start with /)\n * @param oldString - String to find and replace\n * @param newString - Replacement string\n * @param replaceAll - If true, replace all occurrences (default: false)\n * @returns EditResult with error, path, filesUpdate, and occurrences\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false\n ): Promise<EditResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n const result = await this.sandbox.file.strReplaceEditor({\n command: \"str_replace\",\n path: resolvedPath,\n old_str: oldString,\n new_str: newString,\n replace_mode: replaceAll ? \"ALL\" : \"FIRST\",\n });\n if (!result.ok) {\n throw result.error;\n }\n return {\n path: filePath,\n filesUpdate: null,\n }\n }\n catch (e: any) {\n throw new Error(`Error editing file '${filePath}': ${e.message}`);\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n *\n * Searches file contents for a regex pattern within the sandbox.\n *\n * @param pattern - Regex pattern to search for\n * @param searchPath - Base path to search from (default: \"/\")\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @returns List of GrepMatch objects or error string for invalid regex\n */\n async grepRaw(\n pattern: string,\n searchPath: string | null = \"/\",\n glob: string | null = null\n ): Promise<GrepMatch[] | string> {\n // Resolve base path\n let baseFull: string;\n baseFull = this.resolvePath(searchPath || \"/\");\n\n // Use fast-glob to recursively find all files\n const result = await this.sandbox.file.findFiles({\n path: baseFull,\n glob: glob || \"**/*\"\n })\n\n if (!result.ok) {\n throw result.error;\n }\n const filePaths = result.body?.data?.files || [];\n\n const matches: GrepMatch[] = [];\n\n // Iterate through each file and search for matches\n for (const absolutePath of filePaths) {\n // Read file content as FileData\n const fileData = await this.sandbox.file.searchInFile({\n file: absolutePath,\n regex: pattern,\n });\n if (!fileData.ok) {\n continue;\n }\n\n const matchesData = fileData.body?.data?.matches || [];\n const matchLines = fileData.body?.data?.line_numbers || [];\n matchesData.forEach((match, index) => {\n matches.push({\n path: this.toVirtualPath(absolutePath),\n line: matchLines[index],\n text: match,\n });\n })\n }\n return matches;\n\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n *\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param searchPath - Base path to search from (default: \"/\")\n * @returns List of FileInfo objects matching the pattern\n */\n async globInfo(\n pattern: string,\n searchPath: string = \"/\"\n ): Promise<FileInfo[]> {\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.substring(1);\n }\n\n const resolvedSearchPath = this.resolvePath(searchPath);\n // Use fast-glob to recursively find all files\n const result = await this.sandbox.file.findFiles({\n path: resolvedSearchPath,\n glob: pattern || \"**/*\"\n })\n\n if (!result.ok) {\n throw result.error;\n }\n\n const results: FileInfo[] = [];\n for (const filePath of result.body?.data?.files || []) {\n const fileInfo = await this.sandbox.file.listPath({\n path: filePath,\n recursive: false,\n show_hidden: false,\n max_depth: 1,\n include_size: false,\n include_permissions: false,\n\n });\n if (!fileInfo.ok) {\n continue;\n }\n results.push({\n path: this.toVirtualPath(filePath),\n is_dir: false,\n size: fileInfo.body?.data?.files?.[0]?.size,\n modified_at: fileInfo.body?.data?.files?.[0]?.modified_time\n })\n }\n\n return results;\n\n\n }\n\n\n}\n","import { AIMessage, createMiddleware, tool, type AgentMiddleware } from \"langchain\";\n\nimport { sandboxLatticeManager } from \"../sandbox_lattice/SandboxLatticeManager\";\nimport { getToolClient } from \"../tool_lattice/ToolLatticeManager\";\nimport { createCodeEvalTool } from \"@tool_lattice/code_eval\";\nimport { createCodeExecuteFileTool } from \"@tool_lattice/code_execute_file\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n/**\n * Parameters for creating the Skill middleware.\n *\n * This is a TypeScript adaptation of the Python SkillMiddleware:\n *\n * - Injects a formatted list of skills into the system prompt.\n * - Registers a `load_skill`-like tool so the model can fetch\n * detailed information for specific skills when needed.\n */\nexport interface CreateCodeEvalMiddlewareParams {\n isolatedLevel: IsolatedLevel;\n}\n\n/**\n * Create middleware that injects sandbox descriptions into the system prompt.\n *\n * This mirrors the behavior of the Python SandboxMiddleware:\n *\n * - Injects a formatted list of sandboxes into the system prompt.\n * - Registers a `load_sandbox`-like tool so the model can fetch\n * detailed information for specific sandboxes when needed.\n */\nexport function createCodeEvalMiddleware(\n params: CreateCodeEvalMiddlewareParams = { isolatedLevel: \"global\" }\n): AgentMiddleware {\n\n const codeEvalTool = createCodeEvalTool({ isolatedLevel: params.isolatedLevel });\n const codeExecuteFileTool = createCodeExecuteFileTool({ isolatedLevel: params.isolatedLevel });\n return createMiddleware({\n name: \"codeEvalMiddleware\",\n tools: [codeEvalTool, codeExecuteFileTool, getToolClient(\"convert_to_markdown\")],\n\n });\n}\n\n\n","import { createMiddleware, type AgentMiddleware } from \"langchain\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\nimport {\n createBrowserNavigateTool,\n createBrowserClickTool,\n createBrowserGetTextTool,\n createBrowserGetMarkdownTool,\n createBrowserEvaluateTool,\n createBrowserScreenshotTool,\n createBrowserScrollTool,\n createBrowserFormInputFillTool,\n createBrowserSelectTool,\n createBrowserHoverTool,\n createBrowserGoBackTool,\n createBrowserGoForwardTool,\n createBrowserNewTabTool,\n createBrowserTabListTool,\n createBrowserSwitchTabTool,\n createBrowserCloseTabTool,\n createBrowserCloseTool,\n createBrowserPressKeyTool,\n createBrowserReadLinksTool,\n createBrowserGetClickableElementsTool,\n createBrowserGetDownloadListTool,\n createBrowserGetInfoTool,\n} from \"../tool_lattice/browser\";\n\nexport interface CreateBrowserMiddlewareParams {\n isolatedLevel?: IsolatedLevel;\n}\n\nexport function createBrowserMiddleware(\n params: CreateBrowserMiddlewareParams = { isolatedLevel: \"global\" }\n): AgentMiddleware {\n const isolatedLevel = params.isolatedLevel || \"global\";\n\n const tools = [\n createBrowserNavigateTool({ isolatedLevel }),\n createBrowserClickTool({ isolatedLevel }),\n createBrowserGetTextTool({ isolatedLevel }),\n createBrowserGetMarkdownTool({ isolatedLevel }),\n createBrowserEvaluateTool({ isolatedLevel }),\n createBrowserScreenshotTool({ isolatedLevel }),\n createBrowserScrollTool({ isolatedLevel }),\n createBrowserFormInputFillTool({ isolatedLevel }),\n createBrowserSelectTool({ isolatedLevel }),\n createBrowserHoverTool({ isolatedLevel }),\n createBrowserGoBackTool({ isolatedLevel }),\n createBrowserGoForwardTool({ isolatedLevel }),\n createBrowserNewTabTool({ isolatedLevel }),\n createBrowserTabListTool({ isolatedLevel }),\n createBrowserSwitchTabTool({ isolatedLevel }),\n createBrowserCloseTabTool({ isolatedLevel }),\n createBrowserCloseTool({ isolatedLevel }),\n createBrowserPressKeyTool({ isolatedLevel }),\n createBrowserReadLinksTool({ isolatedLevel }),\n createBrowserGetClickableElementsTool({ isolatedLevel }),\n createBrowserGetDownloadListTool({ isolatedLevel }),\n createBrowserGetInfoTool({ isolatedLevel }),\n ];\n\n return createMiddleware({\n name: \"browserMiddleware\",\n tools,\n });\n}\n","import { createMiddleware, type AgentMiddleware } from \"langchain\";\nimport {\n createListTablesSqlTool,\n createInfoSqlTool,\n createQueryCheckerSqlTool,\n createQuerySqlTool,\n} from \"../tool_lattice/sql\";\n\nexport interface CreateSqlMiddlewareParams {\n connectionMode?: \"databaseKey\" | \"connectionString\";\n databaseKey?: string;\n connectionString?: string;\n}\n\nexport function createSqlMiddleware(\n params: CreateSqlMiddlewareParams\n): AgentMiddleware {\n const { connectionMode, databaseKey, connectionString } = params;\n\n const toolParams: { databaseKey?: string; connectionString?: string } = {};\n\n if (connectionMode === \"databaseKey\" && databaseKey) {\n toolParams.databaseKey = databaseKey;\n } else if (connectionString) {\n toolParams.connectionString = connectionString;\n } else if (databaseKey) {\n toolParams.databaseKey = databaseKey;\n } else if (connectionString) {\n toolParams.connectionString = connectionString;\n }\n\n return createMiddleware({\n name: \"sqlMiddleware\",\n tools: [\n createListTablesSqlTool(toolParams),\n createInfoSqlTool(toolParams),\n createQueryCheckerSqlTool(toolParams),\n createQuerySqlTool(toolParams),\n ],\n });\n}\n","import { createMiddleware, type AgentMiddleware } from \"langchain\";\nimport type { Skill, SkillConfig } from \"@axiom-lattice/protocols\";\nimport { skillLatticeManager } from \"../skill_lattice\";\nimport { getStoreLattice } from \"@store_lattice\";\nimport { createLoadSkillsTool, createLoadSkillContentTool } from \"../tool_lattice/skill\";\n\n\n/**\n * Parameters for creating the Skill middleware.\n */\nexport interface CreateSkillMiddlewareParams {\n /**\n * List of skill IDs to use.\n * Only these skills will be available to the agent.\n */\n skills?: string[];\n /** Optional heading for the skills section */\n heading?: string;\n /** Optional extra explanatory note appended after the skills list */\n extraNote?: string;\n}\n\nconst DEFAULT_HEADING = \"## Available Skills\";\nconst DEFAULT_EXTRA_NOTE =\n \"Use the load_skill_content tool when you need detailed information about handling a specific type of request.\";\n\n/**\n * Create middleware that injects skill descriptions into the system prompt.\n */\nexport function createSkillMiddleware(\n params: CreateSkillMiddlewareParams = {}\n): AgentMiddleware {\n const {\n skills = [],\n heading = DEFAULT_HEADING,\n extraNote = DEFAULT_EXTRA_NOTE,\n } = params;\n\n let latestSkills: Skill[] = [];\n\n return createMiddleware({\n name: \"skillMiddleware\",\n tools: [\n createLoadSkillsTool({ skills }),\n createLoadSkillContentTool(),\n ],\n beforeAgent: async () => {\n try {\n if (skills && skills.length > 0) {\n const storeLattice = getStoreLattice(\"default\", \"skill\");\n const skillStore = storeLattice?.store;\n const skillLatticePromises = skills.map((skillId: string) =>\n skillStore.getSkillById(skillId)\n );\n const skillLattices = await Promise.all(skillLatticePromises);\n latestSkills = skillLattices.filter((skill): skill is Skill => skill !== undefined);\n }\n } catch (error) {\n console.error(\"Error fetching skills:\", error);\n }\n },\n wrapModelCall: (request, handler) => {\n const skillsPrompt = latestSkills\n .map((skill) => `- **${skill.name}**: ${skill.description}`)\n .join(\"\\n\");\n\n const skillsAddendum = `\\n\\n${heading}\\n\\n${skillsPrompt}\\n\\n${extraNote}`;\n\n const existingSystemPrompt = request.systemPrompt ?? \"\";\n const newSystemPrompt =\n existingSystemPrompt.length > 0\n ? `${existingSystemPrompt}${skillsAddendum}`\n : skillsAddendum.trimStart();\n\n return handler({\n ...request,\n systemPrompt: newSystemPrompt,\n });\n },\n });\n}\n\n","/**\n * InMemoryThreadStore\n *\n * In-memory implementation of ThreadStore\n * Provides CRUD operations for thread data stored in memory\n * Threads are organized by assistant ID\n */\n\nimport type {\n ThreadStore,\n Thread,\n CreateThreadRequest,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory implementation of ThreadStore\n */\nexport class InMemoryThreadStore implements ThreadStore {\n // Map<assistantId, Map<threadId, Thread>>\n private threads: Map<string, Map<string, Thread>> = new Map();\n\n /**\n * Get all threads for a specific assistant\n */\n async getThreadsByAssistantId(assistantId: string): Promise<Thread[]> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return [];\n }\n return Array.from(assistantThreads.values());\n }\n\n /**\n * Get a thread by ID for a specific assistant\n */\n async getThreadById(\n assistantId: string,\n threadId: string\n ): Promise<Thread | undefined> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return undefined;\n }\n return assistantThreads.get(threadId);\n }\n\n /**\n * Create a new thread for an assistant\n */\n async createThread(\n assistantId: string,\n threadId: string,\n data: CreateThreadRequest\n ): Promise<Thread> {\n const now = new Date();\n const thread: Thread = {\n id: threadId,\n assistantId,\n metadata: data.metadata || {},\n createdAt: now,\n updatedAt: now,\n };\n\n // Initialize assistant's thread map if it doesn't exist\n if (!this.threads.has(assistantId)) {\n this.threads.set(assistantId, new Map());\n }\n\n const assistantThreads = this.threads.get(assistantId)!;\n assistantThreads.set(threadId, thread);\n return thread;\n }\n\n /**\n * Update an existing thread\n */\n async updateThread(\n assistantId: string,\n threadId: string,\n updates: Partial<CreateThreadRequest>\n ): Promise<Thread | null> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return null;\n }\n\n const existing = assistantThreads.get(threadId);\n if (!existing) {\n return null;\n }\n\n const updated: Thread = {\n ...existing,\n metadata: {\n ...existing.metadata,\n ...(updates.metadata || {}),\n },\n updatedAt: new Date(),\n };\n assistantThreads.set(threadId, updated);\n return updated;\n }\n\n /**\n * Delete a thread by ID\n */\n async deleteThread(assistantId: string, threadId: string): Promise<boolean> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return false;\n }\n return assistantThreads.delete(threadId);\n }\n\n /**\n * Check if thread exists\n */\n async hasThread(assistantId: string, threadId: string): Promise<boolean> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return false;\n }\n return assistantThreads.has(threadId);\n }\n\n /**\n * Clear all threads (useful for testing)\n */\n clear(): void {\n this.threads.clear();\n }\n\n /**\n * Get all threads for all assistants (useful for debugging)\n */\n getAllThreads(): Thread[] {\n const allThreads: Thread[] = [];\n for (const assistantThreads of this.threads.values()) {\n allThreads.push(...Array.from(assistantThreads.values()));\n }\n return allThreads;\n }\n}\n","/**\n * InMemoryAssistantStore\n *\n * In-memory implementation of AssistantStore\n * Provides CRUD operations for assistant data stored in memory\n */\n\nimport type {\n AssistantStore,\n Assistant,\n CreateAssistantRequest,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory implementation of AssistantStore\n */\nexport class InMemoryAssistantStore implements AssistantStore {\n private assistants: Map<string, Assistant> = new Map();\n\n /**\n * Get all assistants\n */\n async getAllAssistants(): Promise<Assistant[]> {\n return Array.from(this.assistants.values());\n }\n\n /**\n * Get assistant by ID\n */\n async getAssistantById(id: string): Promise<Assistant | null> {\n return this.assistants.get(id) || null;\n }\n\n /**\n * Create a new assistant\n */\n async createAssistant(\n id: string,\n data: CreateAssistantRequest\n ): Promise<Assistant> {\n const now = new Date();\n const assistant: Assistant = {\n id,\n name: data.name,\n description: data.description,\n graphDefinition: data.graphDefinition,\n createdAt: now,\n updatedAt: now,\n };\n this.assistants.set(id, assistant);\n return assistant;\n }\n\n /**\n * Update an existing assistant\n */\n async updateAssistant(\n id: string,\n updates: Partial<CreateAssistantRequest>\n ): Promise<Assistant | null> {\n const existing = this.assistants.get(id);\n if (!existing) {\n return null;\n }\n\n const updated: Assistant = {\n ...existing,\n ...updates,\n updatedAt: new Date(),\n };\n this.assistants.set(id, updated);\n return updated;\n }\n\n /**\n * Delete an assistant by ID\n */\n async deleteAssistant(id: string): Promise<boolean> {\n return this.assistants.delete(id);\n }\n\n /**\n * Check if assistant exists\n */\n async hasAssistant(id: string): Promise<boolean> {\n return this.assistants.has(id);\n }\n\n /**\n * Clear all assistants (useful for testing)\n */\n clear(): void {\n this.assistants.clear();\n }\n}\n","/**\n * FileSystemSkillStore\n *\n * Filesystem-based implementation of SkillStore\n * Stores each skill as a Markdown file with YAML frontmatter\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport {\n SkillStore,\n Skill,\n CreateSkillRequest,\n} from \"@axiom-lattice/protocols\";\nimport { validateSkillName } from \"../skill_lattice/skillNameValidator\";\n\n/**\n * Parse YAML frontmatter from markdown content\n */\nfunction parseFrontmatter(content: string): {\n frontmatter: Record<string, any>;\n body: string;\n} {\n const frontmatterRegex = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n?([\\s\\S]*)$/;\n const match = content.match(frontmatterRegex);\n\n if (!match) {\n console.warn(\"[parseFrontmatter] No frontmatter match found in content\");\n return { frontmatter: {}, body: content };\n }\n\n const frontmatterText = match[1];\n const body = match[2] || \"\";\n\n // Simple YAML parser for basic key-value pairs and nested objects\n const frontmatter: Record<string, any> = {};\n const lines = frontmatterText.split(\"\\n\");\n let currentKey: string | null = null;\n let metadataIndent = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n \n if (!trimmed || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n // Check if this is a nested metadata entry\n const indentMatch = line.match(/^(\\s*)/);\n const indent = indentMatch ? indentMatch[1].length : 0;\n\n if (currentKey === \"metadata\" && indent > metadataIndent) {\n // This is a nested metadata entry\n const colonIndex = trimmed.indexOf(\":\");\n if (colonIndex !== -1) {\n const key = trimmed.substring(0, colonIndex).trim();\n let value = trimmed.substring(colonIndex + 1).trim();\n \n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n \n if (!frontmatter.metadata) {\n frontmatter.metadata = {};\n }\n frontmatter.metadata[key] = value;\n }\n continue;\n }\n\n if (currentKey === \"subSkills\" && indent > metadataIndent) {\n // This is a subSkills array item\n if (trimmed.startsWith(\"-\")) {\n let value = trimmed.substring(1).trim();\n \n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n \n if (!frontmatter.subSkills) {\n frontmatter.subSkills = [];\n }\n frontmatter.subSkills.push(value);\n }\n continue;\n }\n\n // Reset metadata/subSkills tracking\n if ((currentKey === \"metadata\" || currentKey === \"subSkills\") && indent <= metadataIndent) {\n currentKey = null;\n metadataIndent = 0;\n }\n\n const colonIndex = trimmed.indexOf(\":\");\n if (colonIndex === -1) {\n continue;\n }\n\n const key = trimmed.substring(0, colonIndex).trim();\n let value = trimmed.substring(colonIndex + 1).trim();\n\n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n // Handle metadata as nested object\n if (key === \"metadata\") {\n if (value === \"\" || value === \"{}\") {\n // Check if next line starts with indentation (nested metadata)\n if (i + 1 < lines.length) {\n const nextLine = lines[i + 1];\n const nextIndent = nextLine.match(/^(\\s*)/)?.[1].length || 0;\n if (nextIndent > indent) {\n currentKey = \"metadata\";\n metadataIndent = indent;\n frontmatter.metadata = {};\n continue;\n }\n }\n frontmatter[key] = {};\n } else if (value.startsWith(\"{\")) {\n try {\n frontmatter[key] = JSON.parse(value);\n } catch {\n frontmatter[key] = {};\n }\n } else {\n frontmatter[key] = {};\n }\n } else if (key === \"subSkills\") {\n // Handle subSkills as array\n if (value === \"\" || value === \"[]\") {\n // Check if next line starts with indentation (array items)\n if (i + 1 < lines.length) {\n const nextLine = lines[i + 1];\n const nextIndent = nextLine.match(/^(\\s*)/)?.[1].length || 0;\n if (nextIndent > indent && nextLine.trim().startsWith(\"-\")) {\n currentKey = \"subSkills\";\n metadataIndent = indent;\n frontmatter.subSkills = [];\n continue;\n }\n }\n frontmatter[key] = [];\n } else if (value.startsWith(\"[\")) {\n try {\n frontmatter[key] = JSON.parse(value);\n } catch {\n frontmatter[key] = [];\n }\n } else {\n frontmatter[key] = [];\n }\n } else {\n frontmatter[key] = value;\n }\n }\n\n return { frontmatter, body };\n}\n\n/**\n * Generate YAML frontmatter string\n */\nfunction generateFrontmatter(data: {\n name: string;\n description: string;\n license?: string;\n compatibility?: string;\n metadata?: Record<string, string>;\n subSkills?: string[];\n}): string {\n const lines: string[] = [\"---\"];\n\n lines.push(`name: ${data.name}`);\n lines.push(`description: ${data.description}`);\n\n if (data.license) {\n lines.push(`license: ${data.license}`);\n }\n\n if (data.compatibility) {\n lines.push(`compatibility: ${data.compatibility}`);\n }\n\n if (data.metadata && Object.keys(data.metadata).length > 0) {\n // Format metadata as YAML object\n lines.push(\"metadata:\");\n for (const [key, value] of Object.entries(data.metadata)) {\n lines.push(` ${key}: ${value}`);\n }\n }\n\n if (data.subSkills && data.subSkills.length > 0) {\n // Format subSkills as YAML array\n lines.push(\"subSkills:\");\n for (const subSkill of data.subSkills) {\n lines.push(` - ${subSkill}`);\n }\n }\n\n lines.push(\"---\");\n return lines.join(\"\\n\");\n}\n\n/**\n * FileSystemSkillStore options\n */\nexport interface FileSystemSkillStoreOptions {\n /**\n * Root directory path for storing skills\n * Can be absolute or relative path (relative to current working directory)\n * @default \"lattice_store/skills\"\n */\n rootDir?: string;\n}\n\n/**\n * Filesystem-based implementation of SkillStore\n */\nexport class FileSystemSkillStore implements SkillStore {\n private rootDir: string;\n\n constructor(options: FileSystemSkillStoreOptions = {}) {\n const defaultPath = \"lattice_store/skills\";\n const providedPath = options.rootDir || defaultPath;\n \n // Resolve path: if absolute, use as-is; if relative, resolve from cwd\n if (path.isAbsolute(providedPath)) {\n this.rootDir = providedPath;\n } else {\n this.rootDir = path.resolve(process.cwd(), providedPath);\n }\n \n // Ensure root directory exists\n this.ensureDirectoryExists().catch((error) => {\n console.error(\"Failed to initialize FileSystemSkillStore:\", error);\n });\n }\n\n /**\n * Ensure the root directory exists\n */\n private async ensureDirectoryExists(): Promise<void> {\n try {\n await fs.access(this.rootDir);\n } catch {\n // Directory doesn't exist, create it\n await fs.mkdir(this.rootDir, { recursive: true });\n }\n }\n\n /**\n * Get directory path for a skill name\n * Name is used as the directory name, and SKILL.md is the fixed filename\n */\n private getSkillDirectoryPath(name: string): string {\n // Name should already be validated, but add safety check\n if (name.includes(\"..\") || name.includes(\"/\") || name.includes(\"\\\\\")) {\n throw new Error(`Invalid skill name: ${name} (contains invalid characters)`);\n }\n return path.join(this.rootDir, name);\n }\n\n /**\n * Get file path for a skill name\n * File is always named SKILL.md inside the name directory\n */\n private getSkillFilePath(name: string): string {\n return path.join(this.getSkillDirectoryPath(name), \"SKILL.md\");\n }\n\n /**\n * Read skill from file\n * Uses name as the directory name and reads SKILL.md from it\n */\n private async readSkillFile(name: string): Promise<Skill | null> {\n await this.ensureDirectoryExists();\n const filePath = this.getSkillFilePath(name);\n\n try {\n const content = await fs.readFile(filePath, \"utf-8\");\n const { frontmatter, body } = parseFrontmatter(content);\n\n if (!frontmatter.name || !frontmatter.description) {\n console.warn(\n `Skill file ${name} parsed frontmatter:`,\n JSON.stringify(frontmatter, null, 2)\n );\n console.warn(`Raw frontmatter text (first 200 chars):`, content.substring(0, 200));\n }\n\n // Get file stats for timestamps\n const stats = await fs.stat(filePath);\n\n // Validate required fields\n if (!frontmatter.name || !frontmatter.description) {\n throw new Error(\n `Invalid skill file ${name}: missing required fields (name or description). Frontmatter: ${JSON.stringify(frontmatter)}`\n );\n }\n\n // Ensure name matches directory name\n if (frontmatter.name !== name) {\n throw new Error(\n `Skill name mismatch: directory name is \"${name}\" but frontmatter name is \"${frontmatter.name}\"`\n );\n }\n\n return {\n id: name, // id equals name (name is used for path addressing)\n name: frontmatter.name,\n description: frontmatter.description,\n license: frontmatter.license,\n compatibility: frontmatter.compatibility,\n metadata: frontmatter.metadata || {},\n content: body.trim() || undefined,\n subSkills: Array.isArray(frontmatter.subSkills) ? frontmatter.subSkills : undefined,\n createdAt: stats.birthtime,\n updatedAt: stats.mtime,\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(`Skill file not found: ${filePath}`);\n return null;\n }\n // Re-throw with more context\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read skill file ${filePath}: ${errorMessage}`);\n }\n }\n\n /**\n * Write skill to file\n * Creates directory with name and writes SKILL.md inside it\n */\n private async writeSkillFile(skill: Skill): Promise<void> {\n await this.ensureDirectoryExists();\n \n // Ensure id equals name (name is used for path addressing)\n const skillName = skill.name;\n const skillDir = this.getSkillDirectoryPath(skillName);\n const filePath = this.getSkillFilePath(skillName);\n\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(skillDir, { recursive: true });\n } catch (error) {\n // Directory might already exist, ignore\n }\n\n const frontmatter = generateFrontmatter({\n name: skillName,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n subSkills: skill.subSkills,\n });\n\n const body = skill.content || \"\";\n const content = body\n ? `${frontmatter}\\n${body}`\n : `${frontmatter}\\n`;\n\n await fs.writeFile(filePath, content, \"utf-8\");\n }\n\n /**\n * Get all skills\n */\n async getAllSkills(): Promise<Skill[]> {\n await this.ensureDirectoryExists();\n\n try {\n const entries = await fs.readdir(this.rootDir, { withFileTypes: true });\n\n const skills: Skill[] = [];\n for (const entry of entries) {\n // Only process directories\n if (entry.isDirectory()) {\n const skillName = entry.name;\n try {\n const skill = await this.readSkillFile(skillName);\n if (skill) {\n skills.push(skill);\n } else {\n console.warn(\n `Failed to load skill \"${skillName}\": readSkillFile returned null`\n );\n }\n } catch (error) {\n console.error(\n `Error loading skill \"${skillName}\" from ${this.getSkillFilePath(skillName)}:`,\n error instanceof Error ? error.message : String(error)\n );\n // Continue processing other skills instead of failing completely\n }\n }\n }\n\n return skills.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(\n `Skills directory not found: ${this.rootDir}`\n );\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Get skill by ID\n * ID should equal name (name is used for path addressing)\n */\n async getSkillById(id: string): Promise<Skill | null> {\n // Use id as name (they should be the same)\n return this.readSkillFile(id);\n }\n\n /**\n * Create a new skill\n * id should equal name (name is used for path addressing)\n */\n async createSkill(id: string, data: CreateSkillRequest): Promise<Skill> {\n await this.ensureDirectoryExists();\n\n // Validate name format\n validateSkillName(data.name);\n\n // Validate that id equals name\n if (id !== data.name) {\n throw new Error(\n `Skill id \"${id}\" must equal name \"${data.name}\" (name is used for path addressing)`\n );\n }\n\n // Check if skill already exists\n const existing = await this.getSkillById(id);\n if (existing) {\n // Update existing skill\n return this.updateSkill(id, data) as Promise<Skill>;\n }\n\n const now = new Date();\n const skill: Skill = {\n id: data.name, // id equals name\n name: data.name,\n description: data.description,\n license: data.license,\n compatibility: data.compatibility,\n metadata: data.metadata || {},\n content: data.content,\n subSkills: data.subSkills,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.writeSkillFile(skill);\n return skill;\n }\n\n /**\n * Update an existing skill\n */\n async updateSkill(\n id: string,\n updates: Partial<CreateSkillRequest>\n ): Promise<Skill | null> {\n const skill = await this.readSkillFile(id);\n if (!skill) {\n return null;\n }\n\n // If name is being updated, validate it\n if (updates.name !== undefined) {\n validateSkillName(updates.name);\n \n // If name changes, we need to move the directory\n if (updates.name !== skill.name) {\n const oldDir = this.getSkillDirectoryPath(skill.name);\n const newDir = this.getSkillDirectoryPath(updates.name);\n \n // Move directory\n try {\n await fs.rename(oldDir, newDir);\n } catch (error) {\n throw new Error(\n `Failed to rename skill directory from \"${skill.name}\" to \"${updates.name}\": ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n }\n\n const updatedSkill: Skill = {\n ...skill,\n name: updates.name ?? skill.name,\n id: updates.name ?? skill.id, // id equals name\n description: updates.description ?? skill.description,\n license: updates.license ?? skill.license,\n compatibility: updates.compatibility ?? skill.compatibility,\n metadata: updates.metadata ?? skill.metadata,\n content: updates.content !== undefined ? updates.content : skill.content,\n subSkills: updates.subSkills !== undefined ? updates.subSkills : skill.subSkills,\n updatedAt: new Date(),\n };\n\n await this.writeSkillFile(updatedSkill);\n return updatedSkill;\n }\n\n /**\n * Delete a skill by ID\n * Deletes the entire directory (name is the directory name)\n */\n async deleteSkill(id: string): Promise<boolean> {\n await this.ensureDirectoryExists();\n const skillDir = this.getSkillDirectoryPath(id);\n\n try {\n // Remove the entire directory\n await fs.rm(skillDir, { recursive: true, force: true });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Check if skill exists\n */\n async hasSkill(id: string): Promise<boolean> {\n const skill = await this.getSkillById(id);\n return skill !== null;\n }\n\n /**\n * Search skills by metadata\n */\n async searchByMetadata(\n metadataKey: string,\n metadataValue: string\n ): Promise<Skill[]> {\n const allSkills = await this.getAllSkills();\n return allSkills.filter((skill) => {\n return (\n skill.metadata &&\n skill.metadata[metadataKey] === metadataValue\n );\n });\n }\n\n /**\n * Filter skills by compatibility\n */\n async filterByCompatibility(compatibility: string): Promise<Skill[]> {\n const allSkills = await this.getAllSkills();\n return allSkills.filter((skill) => {\n return skill.compatibility === compatibility;\n });\n }\n\n /**\n * Filter skills by license\n */\n async filterByLicense(license: string): Promise<Skill[]> {\n const allSkills = await this.getAllSkills();\n return allSkills.filter((skill) => {\n return skill.license === license;\n });\n }\n\n /**\n * Get sub-skills of a parent skill\n */\n async getSubSkills(parentSkillName: string): Promise<Skill[]> {\n const parentSkill = await this.getSkillById(parentSkillName);\n if (!parentSkill || !parentSkill.subSkills || parentSkill.subSkills.length === 0) {\n return [];\n }\n\n const subSkills: Skill[] = [];\n for (const subSkillName of parentSkill.subSkills) {\n const subSkill = await this.getSkillById(subSkillName);\n if (subSkill) {\n subSkills.push(subSkill);\n }\n }\n\n return subSkills;\n }\n}\n","/**\n * Skill name validator\n * Validates skill names according to the specification:\n * - 1-64 characters\n * - Lowercase alphanumeric with single hyphen separators\n * - Not start or end with -\n * - Not contain consecutive --\n * - Match the directory name that contains SKILL.md\n * - Regex: ^[a-z0-9]+(-[a-z0-9]+)*$\n */\n\nconst SKILL_NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;\nconst MIN_LENGTH = 1;\nconst MAX_LENGTH = 64;\n\n/**\n * Validate skill name\n * @param name Skill name to validate\n * @returns true if valid, false otherwise\n */\nexport function isValidSkillName(name: string): boolean {\n if (!name || typeof name !== \"string\") {\n return false;\n }\n\n // Check length\n if (name.length < MIN_LENGTH || name.length > MAX_LENGTH) {\n return false;\n }\n\n // Check regex pattern\n return SKILL_NAME_REGEX.test(name);\n}\n\n/**\n * Validate skill name and throw error if invalid\n * @param name Skill name to validate\n * @throws Error if name is invalid\n */\nexport function validateSkillName(name: string): void {\n if (!name || typeof name !== \"string\") {\n throw new Error(\"Skill name is required and must be a string\");\n }\n\n if (name.length < MIN_LENGTH || name.length > MAX_LENGTH) {\n throw new Error(\n `Skill name must be between ${MIN_LENGTH} and ${MAX_LENGTH} characters`\n );\n }\n\n if (!SKILL_NAME_REGEX.test(name)) {\n throw new Error(\n \"Skill name must be lowercase alphanumeric with single hyphen separators, \" +\n \"not start or end with -, and not contain consecutive --. \" +\n \"Pattern: ^[a-z0-9]+(-[a-z0-9]+)*$\"\n );\n }\n}\n","/**\n * StoreLatticeManager\n *\n * Store Lattice manager for registering and managing store services\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport type {\n ThreadStore,\n AssistantStore,\n SkillStore,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * Store type to store interface mapping\n * Maps store type strings to their corresponding interface types\n */\nexport type StoreTypeMap = {\n thread: ThreadStore;\n assistant: AssistantStore;\n skill: SkillStore;\n // Future store types can be added here:\n // vector: VectorStore;\n};\n\n/**\n * Store type keys\n */\nexport type StoreType = keyof StoreTypeMap;\n\n/**\n * Store Lattice interface with type safety\n * @template TStoreType - The type of store (e.g., \"thread\")\n */\nexport interface StoreLattice<TStoreType extends StoreType = StoreType> {\n type: TStoreType;\n key: string;\n store: StoreTypeMap[TStoreType];\n}\n\n/**\n * StoreLatticeManager - Singleton store Lattice manager\n * Responsible for registering and managing various store service Lattices\n */\nexport class StoreLatticeManager extends BaseLatticeManager<\n StoreLattice<StoreType>\n> {\n private static _instance: StoreLatticeManager;\n\n /**\n * Get StoreLatticeManager singleton instance\n */\n public static getInstance(): StoreLatticeManager {\n if (!StoreLatticeManager._instance) {\n StoreLatticeManager._instance = new StoreLatticeManager();\n }\n return StoreLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"stores\";\n }\n\n /**\n * Generate composite key from key and type\n * @param key Lattice key name\n * @param type Store type\n * @returns Composite key string\n */\n private getCompositeKey(key: string, type: StoreType): string {\n return `${key}:${type}`;\n }\n\n /**\n * Register store Lattice with type safety\n * Uses composite key (key + type) as unique identifier\n * @param key Lattice key name\n * @param type Store type (e.g., \"thread\")\n * @param store Store implementation instance matching the type\n */\n public registerLattice<TStoreType extends StoreType>(\n key: string,\n type: TStoreType,\n store: StoreTypeMap[TStoreType]\n ): void {\n // Create store Lattice object\n const storeLattice: StoreLattice<TStoreType> = {\n key,\n type,\n store,\n };\n\n // Use composite key (key + type) for registration\n const compositeKey = this.getCompositeKey(key, type);\n this.register(compositeKey, storeLattice as StoreLattice<StoreType>);\n }\n\n /**\n * Get StoreLattice with type safety\n * Uses composite key (key + type) to retrieve the store\n * @param key Lattice key name\n * @param type Expected store type for type checking\n * @returns StoreLattice with typed store\n */\n public getStoreLattice<TStoreType extends StoreType>(\n key: string,\n type: TStoreType\n ): StoreLattice<TStoreType> {\n const compositeKey = this.getCompositeKey(key, type);\n const storeLattice = this.get(compositeKey);\n if (!storeLattice) {\n throw new Error(`StoreLattice ${key}:${type} not found`);\n }\n\n if (storeLattice.type !== type) {\n throw new Error(\n `StoreLattice ${key}:${type} has type \"${storeLattice.type}\", expected \"${type}\"`\n );\n }\n\n return storeLattice as StoreLattice<TStoreType>;\n }\n\n /**\n * Get StoreLattice without type checking (for backward compatibility)\n * @param key Lattice key name\n * @param type Store type\n * @returns StoreLattice (type may be unknown)\n */\n public getStoreLatticeUnsafe(\n key: string,\n type: StoreType\n ): StoreLattice<StoreType> {\n const compositeKey = this.getCompositeKey(key, type);\n const storeLattice = this.get(compositeKey);\n if (!storeLattice) {\n throw new Error(`StoreLattice ${key}:${type} not found`);\n }\n return storeLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): StoreLattice<StoreType>[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * Uses composite key (key + type) to check existence\n * @param key Lattice key name\n * @param type Store type\n */\n public hasLattice(key: string, type: StoreType): boolean {\n const compositeKey = this.getCompositeKey(key, type);\n return this.has(compositeKey);\n }\n\n /**\n * Remove Lattice\n * Uses composite key (key + type) to remove the store\n * @param key Lattice key name\n * @param type Store type\n */\n public removeLattice(key: string, type: StoreType): boolean {\n const compositeKey = this.getCompositeKey(key, type);\n return this.remove(compositeKey);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const storeLatticeManager = StoreLatticeManager.getInstance();\n\n// Export convenience methods with type safety\nexport const registerStoreLattice = <TStoreType extends StoreType>(\n key: string,\n type: TStoreType,\n store: StoreTypeMap[TStoreType]\n) => storeLatticeManager.registerLattice(key, type, store);\n\nexport const getStoreLattice = <TStoreType extends StoreType>(\n key: string,\n type: TStoreType\n) => storeLatticeManager.getStoreLattice(key, type);\n\n// Default registration of InMemory stores\nimport { InMemoryThreadStore } from \"./InMemoryThreadStore\";\nimport { InMemoryAssistantStore } from \"./InMemoryAssistantStore\";\nimport { FileSystemSkillStore } from \"./FileSystemSkillStore\";\n\n// Create default instances\nconst defaultThreadStore = new InMemoryThreadStore();\nconst defaultAssistantStore = new InMemoryAssistantStore();\nconst defaultSkillStore = new FileSystemSkillStore();\n\n// Register as default stores\nstoreLatticeManager.registerLattice(\"default\", \"thread\", defaultThreadStore);\nstoreLatticeManager.registerLattice(\n \"default\",\n \"assistant\",\n defaultAssistantStore\n);\nstoreLatticeManager.registerLattice(\"default\", \"skill\", defaultSkillStore);\n","/**\n * Load Skills Tool\n * Loads available skills and returns their metadata\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getStoreLattice } from \"../../store_lattice/StoreLatticeManager\";\n\nconst LOAD_SKILLS_DESCRIPTION = `Load all available skills and return their metadata (name, description, license, compatibility, metadata, and subSkills) without the content. This tool returns skill information including hierarchical relationships (subSkills). Use this to discover what skills are available and their structure.`;\n\nexport interface CreateLoadSkillsToolParams {\n skills?: string[];\n}\n\nexport const createLoadSkillsTool = ({ skills }: CreateLoadSkillsToolParams = {}) => {\n return tool(\n async (_input: Record<string, never>, _exe_config: any) => {\n try {\n const storeLattice = getStoreLattice(\"default\", \"skill\");\n const skillStore = storeLattice.store;\n const allSkills = await skillStore.getAllSkills();\n\n const filteredSkills = skills && skills.length > 0\n ? allSkills.filter((skill) => skills.includes(skill.id))\n : allSkills;\n\n const skillsMeta = filteredSkills.map((skill) => ({\n id: skill.id,\n name: skill.name,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n subSkills: skill.subSkills,\n }));\n\n return JSON.stringify(skillsMeta, null, 2);\n } catch (error) {\n return `Error loading skills: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"load_skills\",\n description: LOAD_SKILLS_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Load Skill Content Tool\n * Loads a specific skill's content by name and returns its full content\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getStoreLattice } from \"../../store_lattice/StoreLatticeManager\";\n\nconst LOAD_SKILL_CONTENT_DESCRIPTION = `Load a specific skill's content by name and return its full content including markdown body. This tool returns the complete skill content including frontmatter and markdown body. Use this tool to get the complete skill content for a skill that you want to use.`;\n\nexport const createLoadSkillContentTool = () => {\n return tool(\n async (input: { skill_name: string }, _exe_config: any) => {\n try {\n const storeLattice = getStoreLattice(\"default\", \"skill\");\n const skillStore = storeLattice.store;\n const skill = await skillStore.getSkillById(input.skill_name);\n\n if (!skill) {\n const allSkills = await skillStore.getAllSkills();\n const availableSkills = allSkills.map((s) => s.name).join(\", \");\n return `Skill \"${input.skill_name}\" not found. Available skills: ${availableSkills}`;\n }\n\n const frontmatter: string[] = [\"---\"];\n frontmatter.push(`name: ${skill.name}`);\n frontmatter.push(`description: ${skill.description}`);\n if (skill.license) {\n frontmatter.push(`license: ${skill.license}`);\n }\n if (skill.compatibility) {\n frontmatter.push(`compatibility: ${skill.compatibility}`);\n }\n if (skill.metadata && Object.keys(skill.metadata).length > 0) {\n frontmatter.push(\"metadata:\");\n for (const [key, value] of Object.entries(skill.metadata)) {\n frontmatter.push(` ${key}: ${value}`);\n }\n }\n if (skill.subSkills && skill.subSkills.length > 0) {\n frontmatter.push(\"subSkills:\");\n for (const subSkill of skill.subSkills) {\n frontmatter.push(` - ${subSkill}`);\n }\n }\n frontmatter.push(\"---\");\n\n const content = skill.content || \"\";\n return `${frontmatter.join(\"\\n\")}\\n${content}`;\n } catch (error) {\n return `Error loading skill content: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"load_skill_content\",\n description: LOAD_SKILL_CONTENT_DESCRIPTION,\n schema: z.object({\n skill_name: z.string().describe(\"The name of the skill to load\"),\n }),\n }\n );\n};\n","/**\n * Middleware for providing filesystem tools to an agent.\n *\n * Provides ls, read_file, write_file, edit_file, glob, and grep tools with support for:\n * - Pluggable backends (StateBackend, StoreBackend, FilesystemBackend, CompositeBackend)\n * - Tool result eviction for large outputs\n */\n\nimport { createMiddleware, tool, ToolMessage } from \"langchain\";\nimport { Command, isCommand, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport { z as z3 } from \"zod/v3\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\nimport type {\n BackendProtocol,\n BackendFactory,\n FileData,\n StateAndStore,\n} from \"../backends/protocol.js\";\nimport { StateBackend } from \"../backends/state.js\";\nimport { sanitizeToolCallId } from \"../backends/utils.js\";\n\n/**\n * Zod v3 schema for FileData (re-export from backends)\n */\nconst FileDataSchema = z3.object({\n content: z3.array(z3.string()),\n created_at: z3.string(),\n modified_at: z3.string(),\n});\n\nexport type { FileData };\n\n/**\n * Merge file updates with support for deletions.\n */\nfunction fileDataReducer(\n left: Record<string, FileData> | undefined,\n right: Record<string, FileData | null>\n): Record<string, FileData> {\n if (left === undefined) {\n const result: Record<string, FileData> = {};\n for (const [key, value] of Object.entries(right)) {\n if (value !== null) {\n result[key] = value;\n }\n }\n return result;\n }\n\n const result = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (value === null) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Shared filesystem state schema.\n * Defined at module level to ensure the same object identity is used across all agents,\n * preventing \"Channel already exists with different type\" errors when multiple agents\n * use createFilesystemMiddleware.\n */\nconst FilesystemStateSchema = z3.object({\n files: withLangGraph(\n z3.record(z3.string(), FileDataSchema).default({}) as any,\n {\n reducer: {\n fn: fileDataReducer,\n schema: z3.record(z3.string(), FileDataSchema.nullable()),\n },\n }\n ),\n});\n\n/**\n * Resolve backend from factory or instance.\n *\n * @param backend - Backend instance or factory function\n * @param stateAndStore - State and store container for backend initialization\n */\nasync function getBackend(\n backend: BackendProtocol | BackendFactory,\n stateAndStore: StateAndStore\n): Promise<BackendProtocol> {\n if (typeof backend === \"function\") {\n return await backend(stateAndStore);\n }\n return backend;\n}\n\n// System prompts\nconst FILESYSTEM_SYSTEM_PROMPT = `You have access to a virtual filesystem. All file paths must start with a /.\n\n- ls: list files in a directory (requires absolute path)\n- read_file: read a file from the filesystem\n- write_file: write to a file in the filesystem\n- edit_file: edit a file in the filesystem\n- glob: find files matching a pattern (e.g., \"**/*.py\")\n- grep: search for text within files`;\n\n// Tool descriptions\nexport const LS_TOOL_DESCRIPTION = \"List files and directories in a directory\";\nexport const READ_FILE_TOOL_DESCRIPTION = \"Read the contents of a file\";\nexport const WRITE_FILE_TOOL_DESCRIPTION =\n \"Write content to a new file. Returns an error if the file already exists\";\nexport const EDIT_FILE_TOOL_DESCRIPTION =\n \"Edit a file by replacing a specific string with a new string\";\nexport const GLOB_TOOL_DESCRIPTION =\n \"Find files matching a glob pattern (e.g., '**/*.py' for all Python files)\";\nexport const GREP_TOOL_DESCRIPTION =\n \"Search for a regex pattern in files. Returns matching files and line numbers\";\n\n/**\n * Create ls tool using backend.\n */\nfunction createLsTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const path = input.path || \"/\";\n const infos = await resolvedBackend.lsInfo(path);\n\n if (infos.length === 0) {\n return `No files found in ${path}`;\n }\n\n // Format output\n const lines: string[] = [];\n for (const info of infos) {\n if (info.is_dir) {\n lines.push(`<file>${info.path}</file> (directory)`);\n } else {\n const size = info.size ? ` (${info.size} bytes)` : \"\";\n lines.push(`<file>${info.path}</file>${size}`);\n }\n }\n return lines.join(\"\\n\");\n },\n {\n name: \"ls\",\n description: customDescription || LS_TOOL_DESCRIPTION,\n schema: z3.object({\n path: z3\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Directory path to list (default: /)\"),\n }),\n }\n );\n}\n\n/**\n * Create read_file tool using backend.\n */\nfunction createReadFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { file_path, offset = 0, limit = 2000 } = input;\n return await resolvedBackend.read(file_path, offset, limit);\n },\n {\n name: \"read_file\",\n description: customDescription || READ_FILE_TOOL_DESCRIPTION,\n schema: z3.object({\n file_path: z3.string().describe(\"Absolute path to the file to read\"),\n offset: z3\n .number({ coerce: true })\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from (0-indexed)\"),\n limit: z3\n .number({ coerce: true })\n .optional()\n .default(2000)\n .describe(\"Maximum number of lines to read\"),\n }),\n }\n );\n}\n\n/**\n * Create write_file tool using backend.\n */\nfunction createWriteFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { file_path, content } = input;\n const result = await resolvedBackend.write(file_path, content);\n\n if (result.error) {\n return result.error;\n }\n\n // If filesUpdate is present, return Command to update state\n const message = new ToolMessage({\n content: `Successfully wrote to '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"write_file\",\n metadata: result.metadata,\n });\n\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n return message;\n },\n {\n name: \"write_file\",\n description: customDescription || WRITE_FILE_TOOL_DESCRIPTION,\n schema: z3.object({\n file_path: z3.string().describe(\"Absolute path to the file to write\"),\n content: z3.string().describe(\"Content to write to the file\"),\n }),\n }\n );\n}\n\n/**\n * Create edit_file tool using backend.\n */\nfunction createEditFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { file_path, old_string, new_string, replace_all = false } = input;\n const result = await resolvedBackend.edit(\n file_path,\n old_string,\n new_string,\n replace_all\n );\n\n if (result.error) {\n return result.error;\n }\n\n const message = new ToolMessage({\n content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"edit_file\",\n metadata: result.metadata,\n });\n\n // If filesUpdate is present, return Command to update state\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n // External storage (filesUpdate is null)\n return message;\n },\n {\n name: \"edit_file\",\n description: customDescription || EDIT_FILE_TOOL_DESCRIPTION,\n schema: z3.object({\n file_path: z3.string().describe(\"Absolute path to the file to edit\"),\n old_string: z3\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z3.string().describe(\"String to replace with\"),\n replace_all: z3\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n }\n );\n}\n\n/**\n * Create glob tool using backend.\n */\nfunction createGlobTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { pattern, path = \"/\" } = input;\n const infos = await resolvedBackend.globInfo(pattern, path);\n\n if (infos.length === 0) {\n return `No files found matching pattern '${pattern}'`;\n }\n\n return infos.map((info) => info.path).join(\"\\n\");\n },\n {\n name: \"glob\",\n description: customDescription || GLOB_TOOL_DESCRIPTION,\n schema: z3.object({\n pattern: z3.string().describe(\"Glob pattern (e.g., '*.py', '**/*.ts')\"),\n path: z3\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n }),\n }\n );\n}\n\n/**\n * Create grep tool using backend.\n */\nfunction createGrepTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { pattern, path = \"/\", glob = null } = input;\n const result = await resolvedBackend.grepRaw(pattern, path, glob);\n\n // If string, it's an error\n if (typeof result === \"string\") {\n return result;\n }\n\n if (result.length === 0) {\n return `No matches found for pattern '${pattern}'`;\n }\n\n // Format output: group by file\n const lines: string[] = [];\n let currentFile: string | null = null;\n for (const match of result) {\n if (match.path !== currentFile) {\n currentFile = match.path;\n lines.push(`\\n${currentFile}:`);\n }\n lines.push(` ${match.line}: ${match.text}`);\n }\n\n return lines.join(\"\\n\");\n },\n {\n name: \"grep\",\n description: customDescription || GREP_TOOL_DESCRIPTION,\n schema: z3.object({\n pattern: z3.string().describe(\"Regex pattern to search for\"),\n path: z3\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n glob: z3\n .string()\n .optional()\n .nullable()\n .describe(\"Optional glob pattern to filter files (e.g., '*.py')\"),\n }),\n }\n );\n}\n\n/**\n * Options for creating filesystem middleware.\n */\nexport interface FilesystemMiddlewareOptions {\n /** Backend instance or factory (default: StateBackend) */\n backend?: BackendProtocol | BackendFactory;\n /** Optional custom system prompt override */\n systemPrompt?: string | null;\n /** Optional custom tool descriptions override */\n customToolDescriptions?: Record<string, string> | null;\n /** Optional token limit before evicting a tool result to the filesystem (default: 20000 tokens, ~80KB) */\n toolTokenLimitBeforeEvict?: number | null;\n}\n\n/**\n * Create filesystem middleware with all tools and features.\n */\nexport function createFilesystemMiddleware(\n options: FilesystemMiddlewareOptions = {}\n) {\n const {\n backend = async (stateAndStore: StateAndStore) => new StateBackend(stateAndStore),\n systemPrompt: customSystemPrompt = null,\n customToolDescriptions = null,\n toolTokenLimitBeforeEvict = 20000,\n } = options;\n\n const systemPrompt = customSystemPrompt || FILESYSTEM_SYSTEM_PROMPT;\n\n const tools = [\n createLsTool(backend, {\n customDescription: customToolDescriptions?.ls,\n }),\n createReadFileTool(backend, {\n customDescription: customToolDescriptions?.read_file,\n }),\n createWriteFileTool(backend, {\n customDescription: customToolDescriptions?.write_file,\n }),\n createEditFileTool(backend, {\n customDescription: customToolDescriptions?.edit_file,\n }),\n createGlobTool(backend, {\n customDescription: customToolDescriptions?.glob,\n }),\n createGrepTool(backend, {\n customDescription: customToolDescriptions?.grep,\n }),\n ];\n\n return createMiddleware({\n name: \"FilesystemMiddleware\",\n stateSchema: FilesystemStateSchema as any,\n tools,\n wrapModelCall: systemPrompt\n ? async (request, handler: any) => {\n const currentSystemPrompt = request.systemPrompt || \"\";\n const newSystemPrompt = currentSystemPrompt\n ? `${currentSystemPrompt}\\n\\n${systemPrompt}`\n : systemPrompt;\n return handler({ ...request, systemPrompt: newSystemPrompt });\n }\n : undefined,\n wrapToolCall: toolTokenLimitBeforeEvict\n ? ((async (request: any, handler: any) => {\n const result = await handler(request);\n\n async function processToolMessage(msg: ToolMessage) {\n if (\n typeof msg.content === \"string\" &&\n msg.content.length > toolTokenLimitBeforeEvict! * 4\n ) {\n // Build StateAndStore from request\n const stateAndStore: StateAndStore = {\n state: request.state || {},\n store: request.config?.store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const sanitizedId = sanitizeToolCallId(\n request.toolCall?.id || msg.tool_call_id\n );\n const evictPath = `/large_tool_results/${sanitizedId}`;\n\n const writeResult = await resolvedBackend.write(\n evictPath,\n msg.content\n );\n\n if (writeResult.error) {\n return { message: msg, filesUpdate: null };\n }\n\n const truncatedMessage = new ToolMessage({\n content: `Tool result too large (${Math.round(\n msg.content.length / 4\n )} tokens). Content saved to ${evictPath}`,\n tool_call_id: msg.tool_call_id,\n name: msg.name,\n });\n\n return {\n message: truncatedMessage,\n filesUpdate: writeResult.filesUpdate,\n };\n }\n return { message: msg, filesUpdate: null };\n }\n\n if (result instanceof ToolMessage) {\n const processed = await processToolMessage(result);\n\n if (processed.filesUpdate) {\n return new Command({\n update: {\n files: processed.filesUpdate,\n messages: [processed.message],\n },\n });\n }\n\n return processed.message;\n }\n\n if (isCommand(result)) {\n const update = result.update as any;\n if (!update?.messages) {\n return result;\n }\n\n let hasLargeResults = false;\n const accumulatedFiles: Record<string, FileData> = {\n ...(update.files || {}),\n };\n const processedMessages: ToolMessage[] = [];\n\n for (const msg of update.messages) {\n if (msg instanceof ToolMessage) {\n const processed = await processToolMessage(msg);\n processedMessages.push(processed.message);\n\n if (processed.filesUpdate) {\n hasLargeResults = true;\n Object.assign(accumulatedFiles, processed.filesUpdate);\n }\n } else {\n processedMessages.push(msg);\n }\n }\n\n if (hasLargeResults) {\n return new Command({\n update: {\n ...update,\n messages: processedMessages,\n files: accumulatedFiles,\n },\n });\n }\n }\n\n return result;\n }) as any)\n : undefined,\n });\n}\n","/**\n * Shared utility functions for memory backend implementations.\n *\n * This module contains both user-facing string formatters and structured\n * helpers used by backends and the composite router. Structured helpers\n * enable composition without fragile string parsing.\n */\n\nimport micromatch from \"micromatch\";\nimport { basename } from \"path\";\nimport type { FileData, GrepMatch } from \"./protocol.js\";\n\n// Constants\nexport const EMPTY_CONTENT_WARNING =\n \"System reminder: File exists but has empty contents\";\nexport const MAX_LINE_LENGTH = 10000;\nexport const LINE_NUMBER_WIDTH = 6;\nexport const TOOL_RESULT_TOKEN_LIMIT = 20000; // Same threshold as eviction\nexport const TRUNCATION_GUIDANCE =\n \"... [results truncated, try being more specific with your parameters]\";\n\n/**\n * Sanitize tool_call_id to prevent path traversal and separator issues.\n *\n * Replaces dangerous characters (., /, \\) with underscores.\n */\nexport function sanitizeToolCallId(toolCallId: string): string {\n return toolCallId.replace(/\\./g, \"_\").replace(/\\//g, \"_\").replace(/\\\\/g, \"_\");\n}\n\n/**\n * Format file content with line numbers (cat -n style).\n *\n * Chunks lines longer than MAX_LINE_LENGTH with continuation markers (e.g., 5.1, 5.2).\n *\n * @param content - File content as string or list of lines\n * @param startLine - Starting line number (default: 1)\n * @returns Formatted content with line numbers and continuation markers\n */\nexport function formatContentWithLineNumbers(\n content: string | string[],\n startLine: number = 1,\n): string {\n let lines: string[];\n if (typeof content === \"string\") {\n lines = content.split(\"\\n\");\n if (lines.length > 0 && lines[lines.length - 1] === \"\") {\n lines = lines.slice(0, -1);\n }\n } else {\n lines = content;\n }\n\n const resultLines: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNum = i + startLine;\n\n if (line.length <= MAX_LINE_LENGTH) {\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${line}`,\n );\n } else {\n // Split long line into chunks with continuation markers\n const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH);\n for (let chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) {\n const start = chunkIdx * MAX_LINE_LENGTH;\n const end = Math.min(start + MAX_LINE_LENGTH, line.length);\n const chunk = line.substring(start, end);\n if (chunkIdx === 0) {\n // First chunk: use normal line number\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n } else {\n // Continuation chunks: use decimal notation (e.g., 5.1, 5.2)\n const continuationMarker = `${lineNum}.${chunkIdx}`;\n resultLines.push(\n `${continuationMarker.padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n }\n }\n }\n }\n\n return resultLines.join(\"\\n\");\n}\n\n/**\n * Check if content is empty and return warning message.\n *\n * @param content - Content to check\n * @returns Warning message if empty, null otherwise\n */\nexport function checkEmptyContent(content: string): string | null {\n if (!content || content.trim() === \"\") {\n return EMPTY_CONTENT_WARNING;\n }\n return null;\n}\n\n/**\n * Convert FileData to plain string content.\n *\n * @param fileData - FileData object with 'content' key\n * @returns Content as string with lines joined by newlines\n */\nexport function fileDataToString(fileData: FileData): string {\n return fileData.content.join(\"\\n\");\n}\n\n/**\n * Create a FileData object with timestamps.\n *\n * @param content - File content as string\n * @param createdAt - Optional creation timestamp (ISO format)\n * @returns FileData object with content and timestamps\n */\nexport function createFileData(content: string, createdAt?: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: createdAt || now,\n modified_at: now,\n };\n}\n\n/**\n * Update FileData with new content, preserving creation timestamp.\n *\n * @param fileData - Existing FileData object\n * @param content - New content as string\n * @returns Updated FileData object\n */\nexport function updateFileData(fileData: FileData, content: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: fileData.created_at,\n modified_at: now,\n };\n}\n\n/**\n * Format file data for read response with line numbers.\n *\n * @param fileData - FileData object\n * @param offset - Line offset (0-indexed)\n * @param limit - Maximum number of lines\n * @returns Formatted content or error message\n */\nexport function formatReadResponse(\n fileData: FileData,\n offset: number,\n limit: number,\n): string {\n const content = fileDataToString(fileData);\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n}\n\n/**\n * Perform string replacement with occurrence validation.\n *\n * @param content - Original content\n * @param oldString - String to replace\n * @param newString - Replacement string\n * @param replaceAll - Whether to replace all occurrences\n * @returns Tuple of [new_content, occurrences] on success, or error message string\n */\nexport function performStringReplacement(\n content: string,\n oldString: string,\n newString: string,\n replaceAll: boolean,\n): [string, number] | string {\n // Use split to count occurrences (simpler than regex)\n const occurrences = content.split(oldString).length - 1;\n\n if (occurrences === 0) {\n return `Error: String not found in file: '${oldString}'`;\n }\n\n if (occurrences > 1 && !replaceAll) {\n return `Error: String '${oldString}' appears ${occurrences} times in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`;\n }\n\n // Python's str.replace() replaces ALL occurrences\n // Use split/join for consistent behavior\n const newContent = content.split(oldString).join(newString);\n\n return [newContent, occurrences];\n}\n\n/**\n * Truncate list or string result if it exceeds token limit (rough estimate: 4 chars/token).\n */\nexport function truncateIfTooLong(\n result: string[] | string,\n): string[] | string {\n if (Array.isArray(result)) {\n const totalChars = result.reduce((sum, item) => sum + item.length, 0);\n if (totalChars > TOOL_RESULT_TOKEN_LIMIT * 4) {\n const truncateAt = Math.floor(\n (result.length * TOOL_RESULT_TOKEN_LIMIT * 4) / totalChars,\n );\n return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE];\n }\n return result;\n }\n // string\n if (result.length > TOOL_RESULT_TOKEN_LIMIT * 4) {\n return (\n result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4) +\n \"\\n\" +\n TRUNCATION_GUIDANCE\n );\n }\n return result;\n}\n\n/**\n * Validate and normalize a path.\n *\n * @param path - Path to validate\n * @returns Normalized path starting with / and ending with /\n * @throws Error if path is invalid\n */\nexport function validatePath(path: string | null | undefined): string {\n const pathStr = path || \"/\";\n if (!pathStr || pathStr.trim() === \"\") {\n throw new Error(\"Path cannot be empty\");\n }\n\n let normalized = pathStr.startsWith(\"/\") ? pathStr : \"/\" + pathStr;\n\n if (!normalized.endsWith(\"/\")) {\n normalized += \"/\";\n }\n\n return normalized;\n}\n\n/**\n * Search files dict for paths matching glob pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param path - Base path to search from\n * @returns Newline-separated file paths, sorted by modification time (most recent first).\n * Returns \"No files found\" if no matches.\n *\n * @example\n * ```typescript\n * const files = {\"/src/main.py\": FileData(...), \"/test.py\": FileData(...)};\n * globSearchFiles(files, \"*.py\", \"/\");\n * // Returns: \"/test.py\\n/src/main.py\" (sorted by modified_at)\n * ```\n */\nexport function globSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string = \"/\",\n): string {\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No files found\";\n }\n\n const filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n // Respect standard glob semantics:\n // - Patterns without path separators (e.g., \"*.py\") match only in the current\n // directory (non-recursive) relative to `path`.\n // - Use \"**\" explicitly for recursive matching.\n const effectivePattern = pattern;\n\n const matches: Array<[string, string]> = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n let relative = filePath.substring(normalizedPath.length);\n if (relative.startsWith(\"/\")) {\n relative = relative.substring(1);\n }\n if (!relative) {\n const parts = filePath.split(\"/\");\n relative = parts[parts.length - 1] || \"\";\n }\n\n if (\n micromatch.isMatch(relative, effectivePattern, {\n dot: true,\n nobrace: false,\n })\n ) {\n matches.push([filePath, fileData.modified_at]);\n }\n }\n\n matches.sort((a, b) => b[1].localeCompare(a[1])); // Sort by modified_at descending\n\n if (matches.length === 0) {\n return \"No files found\";\n }\n\n return matches.map(([fp]) => fp).join(\"\\n\");\n}\n\n/**\n * Format grep search results based on output mode.\n *\n * @param results - Dictionary mapping file paths to list of [line_num, line_content] tuples\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted string output\n */\nexport function formatGrepResults(\n results: Record<string, Array<[number, string]>>,\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (outputMode === \"files_with_matches\") {\n return Object.keys(results).sort().join(\"\\n\");\n }\n if (outputMode === \"count\") {\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n const count = results[filePath].length;\n lines.push(`${filePath}: ${count}`);\n }\n return lines.join(\"\\n\");\n }\n // content mode\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n lines.push(`${filePath}:`);\n for (const [lineNum, line] of results[filePath]) {\n lines.push(` ${lineNum}: ${line}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Search file contents for regex pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Regex pattern to search for\n * @param path - Base path to search from\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted search results. Returns \"No matches found\" if no results.\n *\n * @example\n * ```typescript\n * const files = {\"/file.py\": FileData({content: [\"import os\", \"print('hi')\"], ...})};\n * grepSearchFiles(files, \"import\", \"/\");\n * // Returns: \"/file.py\" (with output_mode=\"files_with_matches\")\n * ```\n */\nexport function grepSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n outputMode: \"files_with_matches\" | \"content\" | \"count\" = \"files_with_matches\",\n): string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No matches found\";\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n if (!results[filePath]) {\n results[filePath] = [];\n }\n results[filePath].push([lineNum, line]);\n }\n }\n }\n\n if (Object.keys(results).length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(results, outputMode);\n}\n\n// -------- Structured helpers for composition --------\n\n/**\n * Return structured grep matches from an in-memory files mapping.\n *\n * Returns a list of GrepMatch on success, or a string for invalid inputs\n * (e.g., invalid regex). We deliberately do not raise here to keep backends\n * non-throwing in tool contexts and preserve user-facing error messages.\n */\nexport function grepMatchesFromFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n): GrepMatch[] | string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return [];\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const matches: GrepMatch[] = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n matches.push({ path: filePath, line: lineNum, text: line });\n }\n }\n }\n\n return matches;\n}\n\n/**\n * Group structured matches into the legacy dict form used by formatters.\n */\nexport function buildGrepResultsDict(\n matches: GrepMatch[],\n): Record<string, Array<[number, string]>> {\n const grouped: Record<string, Array<[number, string]>> = {};\n for (const m of matches) {\n if (!grouped[m.path]) {\n grouped[m.path] = [];\n }\n grouped[m.path].push([m.line, m.text]);\n }\n return grouped;\n}\n\n/**\n * Format structured grep matches using existing formatting logic.\n */\nexport function formatGrepMatches(\n matches: GrepMatch[],\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (matches.length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(buildGrepResultsDict(matches), outputMode);\n}\n","/**\n * StateBackend: Store files in LangGraph agent state (ephemeral).\n */\n\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileInfo,\n GrepMatch,\n StateAndStore,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n createFileData,\n fileDataToString,\n formatReadResponse,\n globSearchFiles,\n grepMatchesFromFiles,\n performStringReplacement,\n updateFileData,\n} from \"./utils.js\";\n\n/**\n * Backend that stores files in agent state (ephemeral).\n *\n * Uses LangGraph's state management and checkpointing. Files persist within\n * a conversation thread but not across threads. State is automatically\n * checkpointed after each agent step.\n *\n * Special handling: Since LangGraph state must be updated via Command objects\n * (not direct mutation), operations return filesUpdate in WriteResult/EditResult\n * for the middleware to apply via Command.\n */\nexport class StateBackend implements BackendProtocol {\n private stateAndStore: StateAndStore;\n\n constructor(stateAndStore: StateAndStore) {\n this.stateAndStore = stateAndStore;\n }\n\n /**\n * Get files from current state.\n */\n private getFiles(): Record<string, FileData> {\n return (\n ((this.stateAndStore.state as any).files as Record<string, FileData>) ||\n {}\n );\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n lsInfo(path: string): FileInfo[] {\n const files = this.getFiles();\n const infos: FileInfo[] = [];\n const subdirs = new Set<string>();\n\n // Normalize path to have trailing slash for proper prefix matching\n const normalizedPath = path.endsWith(\"/\") ? path : path + \"/\";\n\n for (const [k, fd] of Object.entries(files)) {\n // Check if file is in the specified directory or a subdirectory\n if (!k.startsWith(normalizedPath)) {\n continue;\n }\n\n // Get the relative path after the directory\n const relative = k.substring(normalizedPath.length);\n\n // If relative path contains '/', it's in a subdirectory\n if (relative.includes(\"/\")) {\n // Extract the immediate subdirectory name\n const subdirName = relative.split(\"/\")[0];\n subdirs.add(normalizedPath + subdirName + \"/\");\n continue;\n }\n\n // This is a file directly in the current directory\n const size = fd.content.join(\"\\n\").length;\n infos.push({\n path: k,\n is_dir: false,\n size: size,\n modified_at: fd.modified_at,\n });\n }\n\n // Add directories to the results\n for (const subdir of Array.from(subdirs).sort()) {\n infos.push({\n path: subdir,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n infos.sort((a, b) => a.path.localeCompare(b.path));\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n read(filePath: string, offset: number = 0, limit: number = 2000): string {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return `Error: File '${filePath}' not found`;\n }\n\n return formatReadResponse(fileData, offset, limit);\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n readRaw(filePath: string): FileData {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) throw new Error(`File '${filePath}' not found`);\n return fileData;\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult with filesUpdate to update LangGraph state.\n */\n write(filePath: string, content: string): WriteResult {\n const files = this.getFiles();\n\n if (filePath in files) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n const newFileData = createFileData(content);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult with filesUpdate and occurrences.\n */\n edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): EditResult {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const content = fileDataToString(fileData);\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n const newFileData = updateFileData(fileData, newContent);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n occurrences: occurrences,\n };\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): GrepMatch[] | string {\n const files = this.getFiles();\n return grepMatchesFromFiles(files, pattern, path, glob);\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n globInfo(pattern: string, path: string = \"/\"): FileInfo[] {\n const files = this.getFiles();\n const result = globSearchFiles(files, pattern, path);\n\n if (result === \"No files found\") {\n return [];\n }\n\n const paths = result.split(\"\\n\");\n const infos: FileInfo[] = [];\n for (const p of paths) {\n const fd = files[p];\n const size = fd ? fd.content.join(\"\\n\").length : 0;\n infos.push({\n path: p,\n is_dir: false,\n size: size,\n modified_at: fd?.modified_at || \"\",\n });\n }\n return infos;\n }\n}\n","import { createCodeEvalMiddleware, CreateCodeEvalMiddlewareParams } from \"../../middlewares/codeEvalMiddleware\";\nimport { createBrowserMiddleware, CreateBrowserMiddlewareParams } from \"../../middlewares/browserMiddleware\";\nimport { createSqlMiddleware, CreateSqlMiddlewareParams } from \"../../middlewares/sqlMiddleware\";\nimport { createSkillMiddleware, CreateSkillMiddlewareParams as CreateSkillMiddlewareParamsType } from \"../../middlewares/skillMiddleware\";\nimport { createFilesystemMiddleware, FilesystemMiddlewareOptions } from \"../../deep_agent_new/middleware/fs\";\nimport { MiddlewareConfig } from \"../types\";\nimport { BackendFactory } from \"../../deep_agent_new/backends/protocol.js\";\n\nexport function createCommonMiddlewares(\n middlewareConfigs: MiddlewareConfig[],\n filesystemBackend?: BackendFactory\n): any[] {\n const middlewares: any[] = [];\n const filesystemConfig = middlewareConfigs.find(m => m.type === \"filesystem\");\n\n if (filesystemConfig?.enabled && filesystemBackend) {\n const options: FilesystemMiddlewareOptions = { backend: filesystemBackend };\n middlewares.push(createFilesystemMiddleware(options));\n }\n\n for (const config of middlewareConfigs) {\n if (!config.enabled || config.type === \"filesystem\") continue;\n\n switch (config.type) {\n case \"code_eval\":\n middlewares.push(createCodeEvalMiddleware(config.config as CreateCodeEvalMiddlewareParams));\n break;\n case \"browser\":\n middlewares.push(createBrowserMiddleware(config.config as CreateBrowserMiddlewareParams));\n break;\n case \"sql\":\n middlewares.push(createSqlMiddleware(config.config as CreateSqlMiddlewareParams));\n break;\n case \"skill\":\n middlewares.push(createSkillMiddleware(config.config as CreateSkillMiddlewareParamsType));\n break;\n }\n }\n\n return middlewares;\n}\n","import {\n createAgent,\n humanInTheLoopMiddleware,\n anthropicPromptCachingMiddleware,\n summarizationMiddleware,\n type AgentMiddleware,\n type ReactAgent,\n type InterruptOnConfig,\n} from \"langchain\";\nimport type { StructuredTool } from \"@langchain/core/tools\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type {\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\n\nimport {\n createFilesystemMiddleware,\n createSubAgentMiddleware,\n createPatchToolCallsMiddleware,\n type SubAgent,\n} from \"./middleware/index.js\";\nimport { StateBackend, type BackendProtocol } from \"./backends/index.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { AnnotationRoot } from \"@langchain/langgraph\";\nimport { CompiledSubAgent } from \"./middleware/subagents.js\";\nimport { todoListMiddleware } from \"./middleware/todos.js\";\nimport { createSkillMiddleware } from \"../middlewares/skillMiddleware.js\";\n\n/**\n * Configuration parameters for creating a Deep Agent\n * Matches Python's create_deep_agent parameters\n */\nexport interface CreateDeepAgentParams<\n ContextSchema extends\n | AnnotationRoot<any>\n | InteropZodObject = AnnotationRoot<any>\n> {\n /** The model to use (model name string or LanguageModelLike instance). Defaults to claude-sonnet-4-5-20250929 */\n model?: BaseLanguageModel | string;\n /** Tools the agent should have access to */\n tools?: StructuredTool[];\n /** Custom system prompt for the agent. This will be combined with the base agent prompt */\n systemPrompt?: string;\n /** Custom middleware to apply after standard middleware */\n middleware?: AgentMiddleware[];\n /** List of subagent specifications for task delegation */\n subagents?: (SubAgent | CompiledSubAgent)[];\n /** Structured output response format for the agent */\n responseFormat?: any; // ResponseFormat type is complex, using any for now\n /** Optional schema for context (not persisted between invocations) */\n contextSchema?: ContextSchema;\n /** Optional checkpointer for persisting agent state between runs */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** Optional store for persisting longterm memories */\n store?: BaseStore;\n /**\n * Optional backend for filesystem operations.\n * Can be either a backend instance or a factory function that creates one.\n * The factory receives a config object with state and store.\n */\n backend?:\n | BackendProtocol\n | ((config: { state: unknown; store?: BaseStore }) => Promise<BackendProtocol>);\n /** Optional interrupt configuration mapping tool names to interrupt configs */\n interruptOn?: Record<string, boolean | InterruptOnConfig>;\n /** The name of the agent */\n name?: string;\n\n skills?: string[];\n\n}\n\nconst BASE_PROMPT = `In order to complete the objective that the user asks of you, you have access to a number of standard tools.`;\n\n/**\n * Create a Deep Agent with middleware-based architecture.\n *\n * Matches Python's create_deep_agent function, using middleware for all features:\n * - Todo management (todoListMiddleware)\n * - Filesystem tools (createFilesystemMiddleware)\n * - Subagent delegation (createSubAgentMiddleware)\n * - Conversation summarization (summarizationMiddleware)\n * - Prompt caching (anthropicPromptCachingMiddleware)\n * - Tool call patching (createPatchToolCallsMiddleware)\n * - Human-in-the-loop (humanInTheLoopMiddleware) - optional\n *\n * @param params Configuration parameters for the agent\n * @returns ReactAgent instance ready for invocation\n */\nexport function createDeepAgent<\n ContextSchema extends\n | AnnotationRoot<any>\n | InteropZodObject = AnnotationRoot<any>\n>(\n params: CreateDeepAgentParams<ContextSchema> = {}\n): ReactAgent<any, any, ContextSchema, any> {\n const {\n model = \"claude-sonnet-4-5-20250929\",\n tools = [],\n systemPrompt,\n middleware: customMiddleware = [],\n subagents = [],\n responseFormat,\n contextSchema,\n checkpointer,\n store,\n backend,\n interruptOn,\n name,\n skills,\n } = params;\n\n // Combine system prompt with base prompt like Python implementation\n const finalSystemPrompt = systemPrompt\n ? `${systemPrompt}\\n\\n${BASE_PROMPT}`\n : BASE_PROMPT;\n\n // Create backend configuration for filesystem middleware\n // If no backend is provided, use a factory that creates a StateBackend\n const filesystemBackend = backend\n ? backend\n : async (config: { state: unknown; store?: BaseStore }) =>\n new StateBackend(config);\n\n const middleware: AgentMiddleware[] = [\n // Provides todo list management capabilities for tracking tasks\n todoListMiddleware(),\n // Enables filesystem operations and optional long-term memory storage\n createFilesystemMiddleware({ backend: filesystemBackend }),\n // Enables delegation to specialized subagents for complex tasks\n createSubAgentMiddleware({\n defaultModel: model,\n defaultTools: tools,\n defaultMiddleware: [\n // Subagent middleware: Todo list management\n todoListMiddleware(),\n // Subagent middleware: Filesystem operations\n createFilesystemMiddleware({\n backend: filesystemBackend,\n }),\n // Subagent middleware: Automatic conversation summarization when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Subagent middleware: Anthropic prompt caching for improved performance\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Subagent middleware: Patches tool calls for compatibility\n createPatchToolCallsMiddleware(),\n ],\n defaultInterruptOn: interruptOn,\n subagents,\n generalPurposeAgent: false,\n }),\n // Automatically summarizes conversation history when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Enables Anthropic prompt caching for improved performance and reduced costs\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Patches tool calls to ensure compatibility across different model providers\n createPatchToolCallsMiddleware()\n\n ];\n\n // Add human-in-the-loop middleware if interrupt config provided\n if (interruptOn) {\n middleware.push(humanInTheLoopMiddleware({ interruptOn }));\n }\n\n // Add custom middleware last (after all built-in middleware)\n middleware.push(...customMiddleware);\n\n return createAgent({\n model,\n systemPrompt: finalSystemPrompt,\n tools,\n middleware,\n responseFormat,\n contextSchema,\n checkpointer,\n store,\n name,\n });\n}\n","import { z } from \"zod/v3\";\nimport {\n createMiddleware,\n createAgent,\n AgentMiddleware,\n tool,\n ToolMessage,\n humanInTheLoopMiddleware,\n type InterruptOnConfig,\n type ReactAgent,\n StructuredTool,\n} from \"langchain\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport { HumanMessage } from \"@langchain/core/messages\";\nimport { AgentClient } from \"@agent_lattice\";\nimport { agentWorkerGraph } from \"../../agent_worker/agent_worker_graph\";\nexport type { AgentMiddleware };\n\n// Constants\nconst DEFAULT_SUBAGENT_PROMPT =\n \"In order to complete the objective that the user asks of you, you have access to a number of standard tools.\";\n\n// State keys that should be excluded when passing state to subagents\nconst EXCLUDED_STATE_KEYS = [\"messages\", \"todos\", \"jumpTo\"] as const;\n\nconst DEFAULT_GENERAL_PURPOSE_DESCRIPTION =\n \"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. This agent has access to all tools as the main agent.\";\n\n// Comprehensive task tool description from Python\nfunction getTaskToolDescription(subagentDescriptions: string[]): string {\n return `\nLaunch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.\n\nAvailable agent types and the tools they have access to:\n${subagentDescriptions.join(\"\\n\")}\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n## Usage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent.\n\n### Example usage of the general-purpose agent:\n\n<example_agent_descriptions>\n\"general-purpose\": use this agent for general purpose tasks, it has access to all tools as the main agent.\n</example_agent_descriptions>\n\n<example>\nUser: \"I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them.\"\nAssistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*\nAssistant: *Synthesizes the results of the three isolated research tasks and responds to the User*\n<commentary>\nResearch is a complex, multi-step task in it of itself.\nThe research of each individual player is not dependent on the research of the other players.\nThe assistant uses the task tool to break down the complex objective into three isolated tasks.\nEach research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result.\nThis means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other.\n</commentary>\n</example>\n\n<example>\nUser: \"Analyze a single large code repository for security vulnerabilities and generate a report.\"\nAssistant: *Launches a single \\`task\\` subagent for the repository analysis*\nAssistant: *Receives report and integrates results into final summary*\n<commentary>\nSubagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details.\nIf the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money.\n</commentary>\n</example>\n\n<example>\nUser: \"Schedule two meetings for me and prepare agendas for each.\"\nAssistant: *Calls the task tool in parallel to launch two \\`task\\` subagents (one per meeting) to prepare agendas*\nAssistant: *Returns final schedules and agendas*\n<commentary>\nTasks are simple individually, but subagents help silo agenda preparation.\nEach subagent only needs to worry about the agenda for one meeting.\n</commentary>\n</example>\n\n<example>\nUser: \"I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\"\nAssistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway*\n<commentary>\nThe assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.\nIt is better to just complete the task directly and NOT use the \\`task\\`tool.\n</commentary>\n</example>\n\n### Example usage with custom agents:\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\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\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 `.trim();\n}\n\nconst TASK_SYSTEM_PROMPT = `## \\`task\\` (subagent spawner)\n\nYou have access to a \\`task\\` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result.\n\nWhen to use the task tool:\n- When a task is complex and multi-step, and can be fully delegated in isolation\n- When a task is independent of other tasks and can run in parallel\n- When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread\n- When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)\n- When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.)\n\nSubagent lifecycle:\n1. **Spawn** → Provide clear role, instructions, and expected output\n2. **Run** → The subagent completes the task autonomously\n3. **Return** → The subagent provides a single structured result\n4. **Reconcile** → Incorporate or synthesize the result into the main thread\n\nWhen NOT to use the task tool:\n- If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)\n- If the task is trivial (a few tool calls or simple lookup)\n- If delegating does not reduce token usage, complexity, or context switching\n- If splitting would add latency without benefit\n\n## Important Task Tool Usage Notes to Remember\n- Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important.\n- Remember to use the \\`task\\` tool to silo independent tasks within a multi-part objective.\n- You should use the \\`task\\` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient.`;\n\n/**\n * Type definitions for pre-compiled agents.\n */\nexport interface CompiledSubAgent {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The agent instance */\n runnable: AgentClient | Runnable;\n}\n\n/**\n * Type definitions for subagents\n */\nexport interface SubAgent {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The system prompt to use for the agent */\n systemPrompt: string;\n /** The tools to use for the agent (tool instances, not names). Defaults to defaultTools */\n tools?: StructuredTool[];\n /** The model for the agent. Defaults to default_model */\n model?: LanguageModelLike | string;\n /** Additional middleware to append after default_middleware */\n middleware?: AgentMiddleware[];\n /** The tool configs to use for the agent */\n interruptOn?: Record<string, boolean | InterruptOnConfig>;\n}\n\n/**\n * Filter state to exclude certain keys when passing to subagents\n */\nfunction filterStateForSubagent(\n state: Record<string, unknown>\n): Record<string, unknown> {\n const filtered: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(state)) {\n if (!EXCLUDED_STATE_KEYS.includes(key as never)) {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n\n/**\n * Create Command with filtered state update from subagent result\n */\nfunction returnCommandWithStateUpdate(\n result: Record<string, unknown>,\n toolCallId: string\n): Command {\n const stateUpdate = filterStateForSubagent(result);\n const messages = result.messages as Array<{ content: string }>;\n const lastMessage = messages?.[messages.length - 1];\n\n return new Command({\n update: {\n ...stateUpdate,\n messages: [\n new ToolMessage({\n content: lastMessage?.content || \"Task completed\",\n tool_call_id: toolCallId,\n name: \"task\",\n }),\n ],\n },\n });\n}\n\n/**\n * Create subagent instances from specifications\n */\nfunction getSubagents(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n}): {\n agents: Record<string, ReactAgent<any, any, any, any> | Runnable>;\n descriptions: string[];\n} {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n } = options;\n\n const defaultSubagentMiddleware = defaultMiddleware || [];\n const agents: Record<string, ReactAgent<any, any, any, any> | Runnable> = {};\n const subagentDescriptions: string[] = [];\n\n // Create general-purpose agent if enabled\n if (generalPurposeAgent) {\n const generalPurposeMiddleware = [...defaultSubagentMiddleware];\n if (defaultInterruptOn) {\n generalPurposeMiddleware.push(\n humanInTheLoopMiddleware({ interruptOn: defaultInterruptOn })\n );\n }\n\n const generalPurposeSubagent = createAgent({\n model: defaultModel,\n systemPrompt: DEFAULT_SUBAGENT_PROMPT,\n tools: defaultTools as any,\n middleware: generalPurposeMiddleware,\n });\n\n agents[\"general-purpose\"] = generalPurposeSubagent;\n subagentDescriptions.push(\n `- general-purpose: ${DEFAULT_GENERAL_PURPOSE_DESCRIPTION}`\n );\n }\n\n // Process custom subagents\n for (const agentParams of subagents) {\n subagentDescriptions.push(\n `- ${agentParams.name}: ${agentParams.description}`\n );\n\n if (\"runnable\" in agentParams) {\n agents[agentParams.name] = agentParams.runnable;\n } else {\n const middleware = agentParams.middleware\n ? [...defaultSubagentMiddleware, ...agentParams.middleware]\n : [...defaultSubagentMiddleware];\n\n const interruptOn = agentParams.interruptOn || defaultInterruptOn;\n if (interruptOn)\n middleware.push(humanInTheLoopMiddleware({ interruptOn }));\n\n agents[agentParams.name] = createAgent({\n model: agentParams.model ?? defaultModel,\n systemPrompt: agentParams.systemPrompt,\n tools: agentParams.tools ?? defaultTools,\n middleware,\n });\n }\n }\n\n return { agents, descriptions: subagentDescriptions };\n}\n\n/**\n * Create the task tool for invoking subagents\n */\nfunction createTaskTool(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n taskDescription: string | null;\n}) {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n } = options;\n\n const { agents: subagentGraphs, descriptions: subagentDescriptions } =\n getSubagents({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n });\n\n const finalTaskDescription = taskDescription\n ? taskDescription\n : getTaskToolDescription(subagentDescriptions);\n\n return tool(\n async (\n input: { description: string; subagent_type: string },\n config\n ): Promise<Command | string> => {\n const { description, subagent_type } = input;\n\n // Validate subagent type\n if (!(subagent_type in subagentGraphs)) {\n const allowedTypes = Object.keys(subagentGraphs)\n .map((k) => `\\`${k}\\``)\n .join(\", \");\n throw new Error(\n `Error: invoked agent of type ${subagent_type}, the only allowed types are ${allowedTypes}`\n );\n }\n\n const subagent = subagentGraphs[subagent_type];\n\n // Get current state and filter it for subagent\n const currentState = getCurrentTaskInput<Record<string, unknown>>();\n const subagentState = filterStateForSubagent(currentState);\n subagentState.messages = [new HumanMessage({ content: description })];\n\n const subagent_thread_id =\n config.configurable?.thread_id +\n \"____\" +\n subagent_type +\n \"_\" +\n config.toolCall.id;\n console.log(subagent_thread_id);\n // Invoke the subagent\n // const result = (await subagent.invoke(subagentState, {\n // configurable: { thread_id: subagent_thread_id },\n // })) as Record<string, unknown>;\n\n const workerResult = await agentWorkerGraph.invoke({\n assistant_id: subagent_type,\n thread_id: subagent_thread_id,\n input: { ...subagentState, message: description },\n });\n\n const result = workerResult.finalState?.values as Record<string, unknown>;\n\n // console.log(\"workerResult\", workerResult);\n\n // const result = (await AgentManager.getInstance().callAgentInQueue(\n // {\n // assistant_id: subagent_type,\n // thread_id: subagent_type + \"_\" + config.toolCall.id,\n // input: { ...subagentState, message: description },\n // },\n // true\n // )) as any;\n\n // Return command with filtered state update\n if (!config.toolCall?.id) {\n throw new Error(\"Tool call ID is required for subagent invocation\");\n }\n\n return returnCommandWithStateUpdate(result, config.toolCall.id);\n },\n {\n name: \"task\",\n description: finalTaskDescription,\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: ${Object.keys(\n subagentGraphs\n ).join(\", \")}`\n ),\n }),\n }\n );\n}\n\n/**\n * Options for creating subagent middleware\n */\nexport interface SubAgentMiddlewareOptions {\n /** The model to use for subagents */\n defaultModel: LanguageModelLike | string;\n /** The tools to use for the default general-purpose subagent */\n defaultTools?: StructuredTool[];\n /** Default middleware to apply to all subagents */\n defaultMiddleware?: AgentMiddleware[] | null;\n /** The tool configs for the default general-purpose subagent */\n defaultInterruptOn?: Record<string, boolean | InterruptOnConfig> | null;\n /** A list of additional subagents to provide to the agent */\n subagents?: (SubAgent | CompiledSubAgent)[];\n /** Full system prompt override */\n systemPrompt?: string | null;\n /** Whether to include the general-purpose agent */\n generalPurposeAgent?: boolean;\n /** Custom description for the task tool */\n taskDescription?: string | null;\n}\n\n/**\n * Create subagent middleware with task tool\n */\nexport function createSubAgentMiddleware(\n options: SubAgentMiddlewareOptions\n): AgentMiddleware {\n const {\n defaultModel,\n defaultTools = [],\n defaultMiddleware = null,\n defaultInterruptOn = null,\n subagents = [],\n systemPrompt = TASK_SYSTEM_PROMPT,\n generalPurposeAgent = true,\n taskDescription = null,\n } = options;\n\n const taskTool = createTaskTool({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n });\n\n return createMiddleware({\n name: \"subAgentMiddleware\",\n tools: [taskTool],\n wrapModelCall: async (request, handler) => {\n if (systemPrompt !== null) {\n const currentPrompt = request.systemPrompt || \"\";\n const newPrompt = currentPrompt\n ? `${currentPrompt}\\n\\n${systemPrompt}`\n : systemPrompt;\n\n return handler({\n ...request,\n systemPrompt: newPrompt,\n });\n }\n return handler(request);\n },\n });\n}\n","import {\n StateGraph,\n END,\n START,\n interrupt,\n Annotation,\n} from \"@langchain/langgraph\";\nimport { AgentManager } from \"../services/AgentManager\";\n\n/**\n * State schema for the agent worker graph\n */\nconst AgentWorkerState = Annotation.Root({\n // Input parameters\n assistant_id: Annotation<string>({\n reducer: (x: string, y: string) => y ?? x,\n default: () => \"\",\n }),\n thread_id: Annotation<string>({\n reducer: (x: string, y: string) => y ?? x,\n default: () => \"\",\n }),\n input: Annotation<Record<string, unknown>>({\n reducer: (x: Record<string, unknown>, y: Record<string, unknown>) => y ?? x,\n default: () => ({}),\n }),\n command2: Annotation<any>({\n reducer: (x: any, y: any) => y ?? x,\n default: () => undefined,\n }),\n\n // Execution result\n result: Annotation<any>({\n reducer: (x: any, y: any) => y ?? x,\n default: () => undefined,\n }),\n // Interrupt data\n interruptValue: Annotation<any>({\n reducer: (x: any, y: any) => y ?? x,\n default: () => undefined,\n }),\n // Final state to return\n finalState: Annotation<Record<string, unknown> | undefined>({\n reducer: (\n x: Record<string, unknown> | undefined,\n y: Record<string, unknown> | undefined\n ) => y ?? x,\n default: () => undefined,\n }),\n});\n\ntype AgentWorkerStateType = typeof AgentWorkerState.State;\n\n/**\n * Execute node: Calls AgentManager.callAgentInQueue\n * Uses command parameter if available (after interrupt response), otherwise uses input\n */\nasync function executeNode(\n state: AgentWorkerStateType\n): Promise<Partial<AgentWorkerStateType>> {\n const { assistant_id, thread_id, input, command2 } = state;\n\n // If command exists (after interrupt response), use command; otherwise use input\n const callParams: {\n assistant_id: string;\n thread_id: string;\n input?: any;\n command?: any;\n } = {\n assistant_id,\n thread_id,\n input,\n command: command2,\n };\n\n const result = (await AgentManager.getInstance().callAgentInQueue(\n callParams,\n true\n )) as any;\n\n return {\n result,\n };\n}\n\n/**\n * Interrupt node: Throws interrupt and waits for response\n */\nasync function interruptNode(\n state: AgentWorkerStateType\n): Promise<Partial<AgentWorkerStateType>> {\n const { result } = state;\n\n // Extract interrupt value from result.tasks[0].interrupts[0].value\n const interruptValue = result?.tasks?.[0]?.interrupts?.[0]?.value;\n\n if (!interruptValue) {\n throw new Error(\n \"Interrupt node called but no interrupt value found in result\"\n );\n }\n\n // Throw interrupt and wait for response\n const response = await interrupt(interruptValue);\n\n // After response, save the response as command for the next executeNode call\n return {\n command2: {\n resume: response,\n },\n };\n}\n\n/**\n * Conditional routing function\n * Routes to interrupt node if result.tasks has values, otherwise ends\n */\nfunction shouldInterrupt(state: AgentWorkerStateType): \"interrupt\" | \"end\" {\n const { result } = state;\n\n // Check if result.tasks exists and has values\n if (result?.tasks && Array.isArray(result.tasks) && result.tasks.length > 0) {\n // Check if there are interrupts\n if (result.tasks[0]?.interrupts && result.tasks[0].interrupts.length > 0) {\n return \"interrupt\";\n }\n }\n\n return \"end\";\n}\n\n/**\n * End node: Returns the final state and clears intermediate process states\n */\nfunction endNode(state: AgentWorkerStateType): Partial<AgentWorkerStateType> {\n // Save final state from result or input\n const finalState = state.result;\n\n // Clear intermediate process states\n return {\n finalState,\n // Clear intermediate states\n result: undefined,\n interruptValue: undefined,\n command2: undefined,\n };\n}\n\n/**\n * Create the agent worker graph\n */\nexport function createAgentWorkerGraph() {\n const workflow = new StateGraph(AgentWorkerState);\n\n // Add nodes\n workflow.addNode(\"execute\", executeNode);\n workflow.addNode(\"interrupt\", interruptNode);\n workflow.addNode(\"end\", endNode);\n\n // Set entry point: connect START to execute node\n (workflow as any).setEntryPoint(\"execute\");\n\n // Add conditional edge from execute node\n (workflow as any).addConditionalEdges(\"execute\", shouldInterrupt, {\n interrupt: \"interrupt\",\n end: \"end\",\n });\n\n // After interrupt, return to execute node\n (workflow as any).addEdge(\"interrupt\", \"execute\");\n\n // End node leads to END\n (workflow as any).addEdge(\"end\", END);\n\n return workflow.compile();\n}\nexport const agentWorkerGraph = createAgentWorkerGraph();\n","// Agent task event names\nexport const AGENT_TASK_EVENT = \"agent:execute\";\n\n\n\n","import { EventEmitter } from \"events\";\nimport { queueLatticeManager } from \"../queue_lattice\";\n\n/**\n * Event bus service\n * Used for event publishing and subscription between internal system components\n */\nclass EventBus {\n private emitter: EventEmitter;\n private defaultQueueKey: string = \"default\";\n\n constructor() {\n this.emitter = new EventEmitter();\n // Set maximum listener count to avoid memory leak warnings\n this.emitter.setMaxListeners(100);\n }\n\n /**\n * Set the default queue key for queue operations\n * @param queueKey Queue key name\n */\n setDefaultQueueKey(queueKey: string): void {\n this.defaultQueueKey = queueKey;\n }\n\n /**\n * Publish event\n * @param eventName Event name\n * @param data Event data\n * @param useQueue Whether to use queue for publishing\n */\n publish(eventName: string, data: any, useQueue: boolean = false): void {\n if (useQueue) {\n // Push to queue if queue service is available\n if (queueLatticeManager.hasLattice(this.defaultQueueKey)) {\n const queue = queueLatticeManager.getQueueLattice(this.defaultQueueKey);\n queue.push(data).catch((error) => {\n console.error(\"Failed to push event to queue:\", error);\n });\n } else {\n console.warn(\n `Queue \"${this.defaultQueueKey}\" not found. Event will not be queued.`\n );\n }\n } else {\n this.emitter.emit(eventName, data);\n }\n }\n\n /**\n * Subscribe to event\n * @param eventName Event name\n * @param callback Callback function\n */\n subscribe(eventName: string, callback: (data: any) => void): void {\n this.emitter.on(eventName, callback);\n }\n\n /**\n * Unsubscribe from event\n * @param eventName Event name\n * @param callback Callback function\n */\n unsubscribe(eventName: string, callback: (data: any) => void): void {\n this.emitter.off(eventName, callback);\n }\n\n /**\n * Subscribe to event once\n * @param eventName Event name\n * @param callback Callback function\n */\n subscribeOnce(eventName: string, callback: (data: any) => void): void {\n this.emitter.once(eventName, callback);\n }\n}\n\n// Create singleton instance\nconst eventBus = new EventBus();\n\nexport default eventBus;\nexport { eventBus };\n","/**\n * QueueLatticeManager\n *\n * Queue Lattice manager for registering and managing queue services\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n QueueLatticeProtocol,\n QueueConfig,\n QueueType,\n QueueClient,\n} from \"@axiom-lattice/protocols\";\nimport { MemoryQueueClient } from \"./MemoryQueueClient\";\n\n/**\n * Queue Lattice interface\n */\nexport interface QueueLattice extends QueueLatticeProtocol {\n key: string;\n config: QueueConfig;\n client: QueueLatticeProtocol[\"client\"];\n}\n\n/**\n * QueueLatticeManager - Singleton queue Lattice manager\n * Responsible for registering and managing various queue service Lattices\n */\nexport class QueueLatticeManager extends BaseLatticeManager<QueueLattice> {\n private static _instance: QueueLatticeManager;\n\n /**\n * Get QueueLatticeManager singleton instance\n */\n public static getInstance(): QueueLatticeManager {\n if (!QueueLatticeManager._instance) {\n QueueLatticeManager._instance = new QueueLatticeManager();\n }\n return QueueLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"queues\";\n }\n\n /**\n * Register queue Lattice\n * @param key Lattice key name\n * @param config Queue configuration\n * @param client Optional queue client. If not provided, will create based on config type.\n * For REDIS type, client must be provided (use @axiom-lattice/queue-redis).\n */\n public registerLattice(\n key: string,\n config: QueueConfig,\n client?: QueueClient\n ): void {\n // Create client based on queue type if not provided\n let queueClient: QueueLatticeProtocol[\"client\"];\n\n if (client) {\n // Use provided client\n queueClient = client;\n } else {\n const queueName = config.queueName || process.env.QUEUE_NAME || \"tasks\";\n\n if (config.type === QueueType.REDIS) {\n throw new Error(\n `Redis queue client must be provided. Please install @axiom-lattice/queue-redis and pass the client to registerLattice. Example: registerLattice(key, config, new RedisQueueClient(queueName, options))`\n );\n } else {\n // Default to memory\n queueClient = new MemoryQueueClient(queueName);\n }\n }\n\n // Create queue Lattice object\n const queueLattice: QueueLattice = {\n key,\n config,\n client: queueClient,\n push: async (item: any) => {\n return queueClient.push(item);\n },\n pop: async () => {\n return queueClient.pop();\n },\n createQueue: queueClient.createQueue\n ? async () => {\n return queueClient.createQueue!();\n }\n : undefined,\n };\n\n // Call base class register method\n this.register(key, queueLattice);\n }\n\n /**\n * Get QueueLattice\n * @param key Lattice key name\n */\n public getQueueLattice(key: string): QueueLattice {\n const queueLattice = this.get(key);\n if (!queueLattice) {\n throw new Error(`QueueLattice ${key} not found`);\n }\n return queueLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): QueueLattice[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const queueLatticeManager = QueueLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerQueueLattice = (\n key: string,\n config: QueueConfig,\n client?: QueueClient\n) => queueLatticeManager.registerLattice(key, config, client);\n\nexport const getQueueLattice = (key: string) =>\n queueLatticeManager.getQueueLattice(key);\n\n","/**\n * MemoryQueueClient\n *\n * In-memory queue service implementation\n */\n\nimport { QueueClient, QueueResult } from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory storage for queues: Map<queue_name, message[]>\n * Using Map to support multiple queues (e.g., per tenant)\n */\nconst queues = new Map<string, any[]>();\n\n/**\n * Initialize queue if it doesn't exist\n */\nconst ensureQueue = (queueName: string): void => {\n if (!queues.has(queueName)) {\n queues.set(queueName, []);\n }\n};\n\n/**\n * Memory-based queue client implementation\n */\nexport class MemoryQueueClient implements QueueClient {\n private queueName: string;\n\n constructor(queueName: string = \"tasks\") {\n this.queueName = queueName;\n ensureQueue(this.queueName);\n }\n\n /**\n * Enqueue message (equivalent to lPush - push to left/beginning)\n */\n async push(item: any): Promise<QueueResult<number>> {\n try {\n ensureQueue(this.queueName);\n const queue = queues.get(this.queueName)!;\n\n // lPush behavior: add to the beginning of the array\n queue.unshift(item);\n\n const result = queue.length;\n console.log(\"lPush (memory)\", result);\n return { data: result, error: null };\n } catch (error) {\n console.error(error);\n return { data: null, error };\n }\n }\n\n /**\n * Dequeue message (equivalent to rPop - pop from right/end)\n */\n async pop(): Promise<QueueResult<any>> {\n try {\n ensureQueue(this.queueName);\n const queue = queues.get(this.queueName)!;\n\n // rPop behavior: remove from the end of the array\n // This creates FIFO behavior when combined with lPush (unshift + pop = FIFO)\n const message = queue.pop();\n\n if (message) {\n return { data: message, error: null };\n }\n return { data: null, error: null };\n } catch (error) {\n console.error(error);\n return { data: null, error };\n }\n }\n\n /**\n * Create queue (initialize in memory)\n */\n async createQueue(): Promise<{\n success: boolean;\n queue_name?: string;\n error?: any;\n }> {\n try {\n ensureQueue(this.queueName);\n const queue = queues.get(this.queueName)!;\n const exists = queue !== undefined;\n return { success: true, queue_name: this.queueName };\n } catch (error) {\n console.error(error);\n return { success: false, error };\n }\n }\n}\n\n\n\n","import { AGENT_TASK_EVENT } from \"../constants/agent_task_types\";\nimport eventBus from \"./event_bus\";\n\nexport class AgentManager {\n private static instance: AgentManager;\n private constructor() {}\n private agents: { name: string; agent: any }[] = [];\n\n public static getInstance(): AgentManager {\n if (!AgentManager.instance) {\n AgentManager.instance = new AgentManager();\n }\n return AgentManager.instance;\n }\n\n callAgentInQueue(\n queue: {\n assistant_id: string;\n input?: any;\n thread_id: string;\n command?: any;\n \"x-tenant-id\"?: string;\n },\n return_agent_state?: boolean\n ) {\n return new Promise((resolve, reject) => {\n const callback_event = `${queue.assistant_id}::${queue.thread_id}`;\n if (return_agent_state) {\n eventBus.subscribeOnce(callback_event, (data) => {\n if (data.success) {\n // console.log(\"AgentManager callAgentInQueue success\", data);\n resolve(data.state);\n } else {\n // console.log(\"AgentManager callAgentInQueue error\", data);\n reject(data.error);\n }\n });\n }\n\n try {\n eventBus.publish(\n AGENT_TASK_EVENT,\n {\n ...queue,\n callback_event,\n },\n true\n );\n // without return_agent_state, resolve the promise\n !return_agent_state &&\n resolve({ callback_event_id: callback_event, success: true });\n } catch (error) {\n // without return_agent_state, reject the promise\n !return_agent_state &&\n reject({\n callback_event_id: callback_event,\n success: false,\n error: error,\n });\n }\n });\n }\n}\n","import {\n createMiddleware,\n AgentMiddleware,\n ToolMessage,\n AIMessage,\n} from \"langchain\";\nimport { RemoveMessage } from \"@langchain/core/messages\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\n\n/**\n * Create middleware that patches dangling tool calls in the messages history.\n *\n * When an AI message contains tool_calls but subsequent messages don't include\n * the corresponding ToolMessage responses, this middleware adds synthetic\n * ToolMessages saying the tool call was cancelled.\n *\n * @returns AgentMiddleware that patches dangling tool calls\n *\n * @example\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { createPatchToolCallsMiddleware } from \"./middleware/patch_tool_calls\";\n *\n * const agent = createAgent({\n * model: \"claude-sonnet-4-5-20250929\",\n * middleware: [createPatchToolCallsMiddleware()],\n * });\n * ```\n */\nexport function createPatchToolCallsMiddleware(): AgentMiddleware {\n return createMiddleware({\n name: \"patchToolCallsMiddleware\",\n beforeAgent: async (state) => {\n const messages = state.messages;\n\n if (!messages || messages.length === 0) {\n return;\n }\n\n const patchedMessages: any[] = [];\n\n // Iterate over the messages and add any dangling tool calls\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n patchedMessages.push(msg);\n\n // Check if this is an AI message with tool calls\n if (AIMessage.isInstance(msg) && msg.tool_calls != null) {\n for (const toolCall of msg.tool_calls) {\n // Look for a corresponding ToolMessage in the messages after this one\n const correspondingToolMsg = messages\n .slice(i)\n .find(\n (m: any) =>\n ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id\n );\n\n if (!correspondingToolMsg) {\n // We have a dangling tool call which needs a ToolMessage\n const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`;\n patchedMessages.push(\n new ToolMessage({\n content: toolMsg,\n name: toolCall.name,\n tool_call_id: toolCall.id!,\n })\n );\n }\n }\n }\n }\n\n // Return state update with RemoveMessage followed by patched messages\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n ...patchedMessages,\n ],\n };\n },\n });\n}\n","/**\n * FilesystemBackend: Read and write files directly from the filesystem.\n *\n * Security and search upgrades:\n * - Secure path resolution with root containment when in virtual_mode (sandboxed to cwd)\n * - Prevent symlink-following on file I/O using O_NOFOLLOW when available\n * - Ripgrep-powered grep with JSON parsing, plus regex fallback\n * and optional glob include filtering, while preserving virtual path behavior\n */\n\nimport * as fs from \"fs/promises\";\nimport * as fsSync from \"fs\";\nimport * as path from \"path\";\nimport { spawn } from \"child_process\";\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileInfo,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n checkEmptyContent,\n formatContentWithLineNumbers,\n performStringReplacement,\n} from \"./utils.js\";\n\nconst SUPPORTS_NOFOLLOW = fsSync.constants.O_NOFOLLOW !== undefined;\n\n/**\n * Backend that reads and writes files directly from the filesystem.\n *\n * Files are accessed using their actual filesystem paths. Relative paths are\n * resolved relative to the current working directory. Content is read/written\n * as plain text, and metadata (timestamps) are derived from filesystem stats.\n */\nexport class FilesystemBackend implements BackendProtocol {\n private cwd: string;\n private virtualMode: boolean;\n private maxFileSizeBytes: number;\n\n constructor(\n options: {\n rootDir?: string;\n virtualMode?: boolean;\n maxFileSizeMb?: number;\n } = {}\n ) {\n const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options;\n this.cwd = rootDir ? path.resolve(rootDir) : process.cwd();\n this.virtualMode = virtualMode;\n this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024;\n }\n\n /**\n * Resolve a file path with security checks.\n *\n * When virtualMode=true, treat incoming paths as virtual absolute paths under\n * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root.\n * When virtualMode=false, preserve legacy behavior: absolute paths are allowed\n * as-is; relative paths resolve under cwd.\n *\n * @param key - File path (absolute, relative, or virtual when virtualMode=true)\n * @returns Resolved absolute path string\n * @throws Error if path traversal detected or path outside root\n */\n private resolvePath(key: string): string {\n if (this.virtualMode) {\n const vpath = key.startsWith(\"/\") ? key : \"/\" + key;\n if (vpath.includes(\"..\") || vpath.startsWith(\"~\")) {\n throw new Error(\"Path traversal not allowed\");\n }\n const full = path.resolve(this.cwd, vpath.substring(1));\n const relative = path.relative(this.cwd, full);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Path: ${full} outside root directory: ${this.cwd}`);\n }\n return full;\n }\n\n if (path.isAbsolute(key)) {\n return key;\n }\n return path.resolve(this.cwd, key);\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param dirPath - Absolute directory path to list files from\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(dirPath: string): Promise<FileInfo[]> {\n try {\n const resolvedPath = this.resolvePath(dirPath);\n const stat = await fs.stat(resolvedPath);\n\n if (!stat.isDirectory()) {\n return [];\n }\n\n const entries = await fs.readdir(resolvedPath, { withFileTypes: true });\n const results: FileInfo[] = [];\n\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n\n for (const entry of entries) {\n const fullPath = path.join(resolvedPath, entry.name);\n\n try {\n const entryStat = await fs.stat(fullPath);\n const isFile = entryStat.isFile();\n const isDir = entryStat.isDirectory();\n\n if (!this.virtualMode) {\n // Non-virtual mode: use absolute paths\n if (isFile) {\n results.push({\n path: fullPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: fullPath + path.sep,\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n } else {\n let relativePath: string;\n if (fullPath.startsWith(cwdStr)) {\n relativePath = fullPath.substring(cwdStr.length);\n } else if (fullPath.startsWith(this.cwd)) {\n relativePath = fullPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = fullPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virtPath = \"/\" + relativePath;\n\n if (isFile) {\n results.push({\n path: virtPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: virtPath + \"/\",\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n }\n } catch {\n // Skip entries we can't stat\n continue;\n }\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n } catch (e: any) {\n console.error(`Error listing files in ${dirPath}:`, e);\n return [];\n }\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute or relative file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 2000\n ): Promise<string> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return `Error: Symlinks are not allowed: ${filePath}`;\n }\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n } catch (e: any) {\n return `Error reading file '${filePath}': ${e.message}`;\n }\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n let stat: fsSync.Stats;\n\n if (SUPPORTS_NOFOLLOW) {\n stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) throw new Error(`File '${filePath}' not found`);\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n throw new Error(`Symlinks are not allowed: ${filePath}`);\n }\n if (!stat.isFile()) throw new Error(`File '${filePath}' not found`);\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n return {\n content: content.split(\"\\n\"),\n created_at: stat.ctime.toISOString(),\n modified_at: stat.mtime.toISOString(),\n };\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n try {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return {\n error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.`,\n };\n }\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n } catch {\n // File doesn't exist, good to proceed\n }\n\n await fs.mkdir(path.dirname(resolvedPath), { recursive: true });\n\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_CREAT |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags, 0o644);\n try {\n await fd.writeFile(content, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, content, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null };\n } catch (e: any) {\n return { error: `Error writing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false\n ): Promise<EditResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return { error: `Error: Symlinks are not allowed: ${filePath}` };\n }\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n\n // Write securely\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags);\n try {\n await fd.writeFile(newContent, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, newContent, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null, occurrences: occurrences };\n } catch (e: any) {\n return { error: `Error editing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n dirPath: string = \"/\",\n glob: string | null = null\n ): Promise<GrepMatch[] | string> {\n // Validate regex\n try {\n new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n // Resolve base path\n let baseFull: string;\n try {\n baseFull = this.resolvePath(dirPath || \".\");\n } catch {\n return [];\n }\n\n try {\n await fs.stat(baseFull);\n } catch {\n return [];\n }\n\n // Try ripgrep first, fallback to regex search\n let results = await this.ripgrepSearch(pattern, baseFull, glob);\n if (results === null) {\n results = await this.pythonSearch(pattern, baseFull, glob);\n }\n\n const matches: GrepMatch[] = [];\n for (const [fpath, items] of Object.entries(results)) {\n for (const [lineNum, lineText] of items) {\n matches.push({ path: fpath, line: lineNum, text: lineText });\n }\n }\n return matches;\n }\n\n /**\n * Try to use ripgrep for fast searching.\n * Returns null if ripgrep is not available or fails.\n */\n private async ripgrepSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null\n ): Promise<Record<string, Array<[number, string]>> | null> {\n return new Promise((resolve) => {\n const args = [\"--json\"];\n if (includeGlob) {\n args.push(\"--glob\", includeGlob);\n }\n args.push(\"--\", pattern, baseFull);\n\n const proc = spawn(\"rg\", args, { timeout: 30000 });\n const results: Record<string, Array<[number, string]>> = {};\n let output = \"\";\n\n proc.stdout.on(\"data\", (data) => {\n output += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n if (code !== 0 && code !== 1) {\n // Error (code 1 means no matches, which is ok)\n resolve(null);\n return;\n }\n\n for (const line of output.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const data = JSON.parse(line);\n if (data.type !== \"match\") continue;\n\n const pdata = data.data || {};\n const ftext = pdata.path?.text;\n if (!ftext) continue;\n\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const resolved = path.resolve(ftext);\n const relative = path.relative(this.cwd, resolved);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = ftext;\n }\n\n const ln = pdata.line_number;\n const lt = pdata.lines?.text?.replace(/\\n$/, \"\") || \"\";\n if (ln === undefined) continue;\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([ln, lt]);\n } catch {\n // Skip invalid JSON\n continue;\n }\n }\n\n resolve(results);\n });\n\n proc.on(\"error\", () => {\n resolve(null);\n });\n });\n }\n\n /**\n * Fallback regex search implementation.\n */\n private async pythonSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null\n ): Promise<Record<string, Array<[number, string]>>> {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch {\n return {};\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n const stat = await fs.stat(baseFull);\n const root = stat.isDirectory() ? baseFull : path.dirname(baseFull);\n\n // Use fast-glob to recursively find all files\n const files = await fg(\"**/*\", {\n cwd: root,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const fp of files) {\n try {\n // Filter by glob if provided\n if (\n includeGlob &&\n !micromatch.isMatch(path.basename(fp), includeGlob)\n ) {\n continue;\n }\n\n // Check file size\n const stat = await fs.stat(fp);\n if (stat.size > this.maxFileSizeBytes) {\n continue;\n }\n\n // Read and search\n const content = await fs.readFile(fp, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (regex.test(line)) {\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const relative = path.relative(this.cwd, fp);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = fp;\n }\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([i + 1, line]);\n }\n }\n } catch {\n // Skip files we can't read\n continue;\n }\n }\n\n return results;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(\n pattern: string,\n searchPath: string = \"/\"\n ): Promise<FileInfo[]> {\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.substring(1);\n }\n\n const resolvedSearchPath =\n searchPath === \"/\" ? this.cwd : this.resolvePath(searchPath);\n\n try {\n const stat = await fs.stat(resolvedSearchPath);\n if (!stat.isDirectory()) {\n return [];\n }\n } catch {\n return [];\n }\n\n const results: FileInfo[] = [];\n\n try {\n // Use fast-glob for pattern matching\n const matches = await fg(pattern, {\n cwd: resolvedSearchPath,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const matchedPath of matches) {\n try {\n const stat = await fs.stat(matchedPath);\n if (!stat.isFile()) continue;\n\n // Normalize fast-glob paths to platform separators\n // fast-glob returns forward slashes on all platforms, but we need\n // platform-native separators for path comparisons on Windows\n const normalizedPath = matchedPath.split(\"/\").join(path.sep);\n\n if (!this.virtualMode) {\n results.push({\n path: normalizedPath,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n } else {\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n let relativePath: string;\n\n if (normalizedPath.startsWith(cwdStr)) {\n relativePath = normalizedPath.substring(cwdStr.length);\n } else if (normalizedPath.startsWith(this.cwd)) {\n relativePath = normalizedPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = normalizedPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virt = \"/\" + relativePath;\n results.push({\n path: virt,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n }\n } catch {\n // Skip files we can't stat\n continue;\n }\n }\n } catch {\n // Ignore glob errors\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n}\n","import { Command } from \"@langchain/langgraph\";\nimport { z } from \"zod\";\nimport { createMiddleware, tool, ToolMessage } from \"langchain\";\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.\nIt also helps the user understand the progress of the task and overall progress of their requests.\nOnly use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.\n\n## When to Use This Tool\nUse this tool in these scenarios:\n\n1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions\n2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations\n3. User explicitly requests todo list - When the user directly asks you to use the todo list\n4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\n5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful.\n\n## How to Use This Tool\n1. When you start working on a task - Mark it as in_progress BEFORE beginning work.\n2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.\n3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.\n4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.\n\n## When NOT to Use This Tool\nIt is important to skip using this tool when:\n1. There is only a single, straightforward task\n2. The task is trivial and tracking it provides no benefit\n3. The task can be completed in less than 3 trivial steps\n4. The task is purely conversational or informational\n\n## Examples of When to Use the Todo List\n\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\n<reasoning>\nThe assistant used the todo list because:\n1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes\n2. The assistant inferred that tests and build need to pass by adding \"Ensure tests and build succeed\" as the final task\n3. Both of the user's requests are complex and require multiple steps to complete.\n</reasoning>\n</example>\n\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\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\n</reasoning>\n</example>\n\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\n<reasoning>\nThe assistant used the todo list because:\n1. 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 (>3)\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\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\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>\n\n## Examples of When NOT to Use the Todo List\n\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.</assistant>\n\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\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\n- Check soil moisture by inserting your finger about 1-2 inches into the soil\n- Water thoroughly when the top inch feels dry, allowing water to drain from the bottom\n- Use room temperature water and water in the morning when possible\n- Avoid 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\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\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\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>\n\n<example>\nUser: I need to write a function that checks if a number is prime and then test it out.\nAssistant: I'll help you write a function that checks if a number is prime and then test it out.\n*Writes function that checks if a number is prime*\n*Tests the function*\n\n<reasoning>\nEven though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens.\n</reasoning>\n</example>\n\n<example>\nUser: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\nAssistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\n*Orders a pizza from Dominos*\n*Orders a burger from McDonald's*\n*Orders a salad from Subway*\n\n<reasoning>\nEven though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls. \nUsing the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.\n</reasoning>\n</example>\n\n\n## Task States and Management\n\n1. **Task States**: Use these states to track progress:\n - pending: Task not yet started\n - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)\n - completed: Task finished successfully\n\n2. **Task Management**:\n - Update task status in real-time as you work\n - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)\n - Complete current tasks before starting new ones\n - Remove tasks that are no longer relevant from the list entirely\n - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.\n - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something.\n\n3. **Task Completion Requirements**:\n - ONLY mark a task as completed when you have FULLY accomplished it\n - If you encounter errors, blockers, or cannot finish, keep the task as in_progress\n - When blocked, create a new task describing what needs to be resolved\n - Never mark a task as completed if:\n - There are unresolved issues or errors\n - Work is partial or incomplete\n - You encountered blockers that prevent completion\n - You couldn't find necessary resources or dependencies\n - Quality standards haven't been met\n\n4. **Task Breakdown**:\n - Create specific, actionable items\n - Break complex tasks into smaller, manageable steps\n - Use clear, descriptive task names\n\nBeing proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully\nRemember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`;\nconst TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = `## \\`write_todos\\`\n\nYou have access to the \\`write_todos\\` tool to help you manage and plan complex objectives. \nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\n\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\n\n## Important To-Do List Usage Notes to Remember\n- The \\`write_todos\\` tool should never be called multiple times in parallel.\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`;\nconst TodoStatus = z\n .enum([\"pending\", \"in_progress\", \"completed\"])\n .describe(\"Status of the todo\");\nconst TodoSchema = z.object({\n content: z.string().describe(\"Content of the todo item\"),\n status: TodoStatus,\n});\nconst stateSchema = z.object({ todos: z.array(TodoSchema).default([]) });\n\nexport function todoListMiddleware(options?: {\n systemPrompt?: string;\n toolDescription?: string;\n}) {\n /**\n * Write todos tool - manages todo list with Command return\n */\n const writeTodos = tool(\n ({ todos }, config) => {\n return new Command({\n update: {\n todos,\n messages: [\n new ToolMessage({\n content: genUIMarkdown(\"todo_list\", todos),\n tool_call_id: config.toolCall?.id,\n }),\n ],\n },\n });\n },\n {\n name: \"write_todos\",\n description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION,\n schema: z.object({\n todos: z.array(TodoSchema).describe(\"List of todo items to update\"),\n }),\n }\n );\n return createMiddleware({\n name: \"todoListMiddleware\",\n stateSchema,\n tools: [writeTodos],\n wrapModelCall: (request, handler) =>\n handler({\n ...request,\n systemPrompt:\n (request.systemPrompt ? `${request.systemPrompt}\\n\\n` : \"\") +\n (options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT),\n }),\n });\n}\n","/**\n * Deep Agent Graph Builder\n *\n * 实现 Deep Agent 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { createDeepAgent } from \"../../deep_agent_new/agent\";\nimport { AgentLattice, AgentBuildParams, AgentClient, MiddlewareConfig } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { AgentMiddleware } from \"langchain\";\nimport { createAgentClientFromAgentLattice } from \"@agent_lattice/AgentLatticeManager\";\nimport { getCheckpointSaver } from \"@memory_lattice/MemoryLatticeManager\";\nimport { sandboxLatticeManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { SandboxFilesystem } from \"../../deep_agent_new/backends/sandboxFiles\";\nimport { createCommonMiddlewares } from \"./commonMiddleware\";\n\nexport class DeepAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 根据 middleware 配置创建 backend factory\n */\n private createFilesystemBackendFactory(\n middlewareConfigs: MiddlewareConfig[]\n ): ((config: { state: unknown; store?: any }) => Promise<any>) | undefined {\n const filesystemConfig = middlewareConfigs.find(m => m.type === \"filesystem\");\n\n if (!filesystemConfig || !filesystemConfig.enabled) {\n return undefined;\n }\n\n const isolatedLevel = filesystemConfig.config?.isolatedLevel || \"global\";\n\n return async (config: { state: unknown }) => {\n let sandboxName = \"global\";\n\n if (isolatedLevel === \"agent\") {\n sandboxName = \"agent\";\n } else if (isolatedLevel === \"thread\") {\n sandboxName = \"thread\";\n }\n\n const sandboxManager = sandboxLatticeManager.getSandboxLattice(\"default\");\n if (!sandboxManager) {\n throw new Error(\"Sandbox manager not found\");\n }\n\n return new SandboxFilesystem({\n sandboxInstance: await sandboxManager.createSandbox(sandboxName),\n });\n };\n }\n\n /**\n * 根据 middleware 配置创建 middlewares\n */\n private createMiddlewares(middlewareConfigs: MiddlewareConfig[]) {\n const filesystemBackend = this.createFilesystemBackendFactory(middlewareConfigs);\n return createCommonMiddlewares(middlewareConfigs, filesystemBackend);\n }\n\n /**\n * 构建Deep Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(agentLattice: AgentLattice, params: AgentBuildParams): AgentClient {\n const tools = params.tools\n .map((t) => {\n const toolClient = getToolClient(t.key);\n return toolClient;\n })\n .filter((tool) => tool !== undefined);\n\n const subagents = params.subAgents.map((sa) => {\n if (sa.client) {\n return {\n name: sa.config.name,\n description: sa.config.description,\n runnable: sa.client,\n };\n } else {\n const subagentClient = createAgentClientFromAgentLattice({\n config: sa.config,\n });\n return {\n name: sa.config.name,\n description: sa.config.description,\n runnable: subagentClient,\n };\n }\n });\n\n const middlewareConfigs = params.middleware || [];\n const filesystemBackend = this.createFilesystemBackendFactory(middlewareConfigs);\n const middlewares = this.createMiddlewares(middlewareConfigs);\n\n const deepAgent = createDeepAgent({\n tools: tools,\n model: params.model,\n contextSchema: params.stateSchema,\n systemPrompt: params.prompt,\n subagents,\n checkpointer: getCheckpointSaver(\"default\"),\n skills: params.skillCategories,\n backend: filesystemBackend,\n middleware: middlewares,\n });\n\n return deepAgent as AgentClient;\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\";\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 }\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 skills = isDeepAgentConfig(agentLattice.config) ? agentLattice.config.skillCategories : undefined;\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 skillCategories: skills,\n middleware: agentLattice.config.middleware,\n };\n }\n}\n","import { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n AgentConfig,\n AgentClient,\n AgentLattice,\n GraphBuildOptions,\n AgentBuildParams,\n AgentType,\n} from \"./types\";\nimport { AgentGraphBuilderFactory } from \"./builders/AgentGraphBuilderFactory\";\nimport { AgentParamsBuilder } from \"./builders/AgentParamsBuilder\";\nimport \"../tool_lattice\";\nimport eventBus from \"../services/event_bus\";\nimport type { Assistant } from \"@axiom-lattice/protocols\";\nimport { getStoreLattice } from \"../store_lattice\";\n\nfunction assistantToConfig(assistant: Assistant): AgentConfig {\n const graphDef = typeof assistant.graphDefinition === \"object\" && assistant.graphDefinition !== null\n ? assistant.graphDefinition\n : {};\n\n const config: AgentConfig = {\n key: assistant.id,\n name: assistant.name ?? (graphDef as any).name ?? assistant.id,\n description: assistant.description ?? (graphDef as any).description ?? \"\",\n type: AgentType.REACT,\n prompt: typeof assistant.graphDefinition === \"string\"\n ? assistant.graphDefinition\n : JSON.stringify(assistant.graphDefinition),\n };\n\n if (graphDef) {\n Object.assign(config, graphDef);\n }\n return config;\n}\n\n/**\n * AgentLatticeManager - 单例Agent Lattice管理器\n * 负责注册、管理各种Agent Lattice\n */\nexport class AgentLatticeManager extends BaseLatticeManager<AgentLattice> {\n private static _instance: AgentLatticeManager;\n private initialized: boolean = false;\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 private constructor() {\n super();\n this.subscribeToAssistantEvents();\n }\n\n private async initializeStoredAssistants(): Promise<void> {\n if (this.initialized) return;\n\n try {\n const storeLattice = getStoreLattice(\"default\", \"assistant\");\n const assistants = await storeLattice.store.getAllAssistants();\n\n for (const assistant of assistants) {\n if (this.has(assistant.id)) continue;\n const config = assistantToConfig(assistant);\n this.registerLattice(config);\n }\n\n this.initialized = true;\n } catch (error) {\n console.error(\"Failed to initialize stored assistants:\", error);\n }\n }\n\n private subscribeToAssistantEvents(): void {\n eventBus.subscribe(\"assistant:created\", (data: { id: string }) => {\n this.handleAssistantChange(data.id);\n });\n eventBus.subscribe(\"assistant:updated\", (data: { id: string }) => {\n this.handleAssistantChange(data.id);\n });\n eventBus.subscribe(\"assistant:deleted\", (data: { id: string }) => {\n this.handleAssistantDelete(data.id);\n });\n }\n\n private async handleAssistantChange(assistantId: string): Promise<void> {\n try {\n const storeLattice = getStoreLattice(\"default\", \"assistant\");\n const assistant = await storeLattice.store.getAssistantById(assistantId);\n\n if (assistant) {\n if (this.has(assistantId)) {\n this.remove(assistantId);\n }\n const config = assistantToConfig(assistant);\n this.registerLattice(config);\n }\n } catch (error) {\n console.error(`Failed to handle assistant change for ${assistantId}:`, error);\n }\n }\n\n private handleAssistantDelete(assistantId: string): void {\n if (this.has(assistantId)) {\n this.remove(assistantId);\n }\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 * code-configured 和 stored assistants 都已注册到 registry\n */\n public async getAllAgentConfigs(): Promise<AgentConfig[]> {\n await this.initializeStoredAssistants();\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 {\n ReplaySubject,\n Observable,\n Subscription,\n observeOn,\n asyncScheduler,\n} 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 ?? 100000, // 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 if (!buffer) {\n const now = Date.now();\n buffer = {\n threadId,\n chunks$: new ReplaySubject<MessageChunk>(this.config.maxChunks),\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>(this.config.maxChunks);\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 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 let pendingError: Error | null = null; // Track errors that occur when not waiting\n\n const subscription = buffer.chunks$\n .pipe(observeOn(asyncScheduler))\n .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 pendingError = err; // Always store the error\n\n if (errorNext) {\n const reject = errorNext;\n errorNext = null;\n reject(err);\n } else if (resolveNext) {\n // If waiting on resolveNext, wake it up to check pendingError\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n complete: () => {\n isCompleted = true;\n if (resolveNext) {\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n });\n let startYieldChunk = false;\n\n try {\n while (true) {\n if (pendingError) {\n throw pendingError;\n }\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 // Check error again after waking up\n if (pendingError) {\n throw pendingError;\n }\n while (queue.length > 0) {\n const chunk = queue.shift();\n if (!chunk) continue;\n\n if (chunk.data?.id === messageId) {\n startYieldChunk = true;\n accumulatedContent += chunk.data?.content || \"\";\n }\n // if (accumulatedContent.length > knownContent.length) {\n // startYieldChunk = true;\n // }\n if (startYieldChunk) {\n yield chunk;\n }\n\n // if (accumulatedContent.length > knownContent.length) {\n // if (accumulatedContent.startsWith(knownContent)) {\n // yield chunk;\n // } else {\n // console.log(\n // \"accumulatedContent not starts with knownContent\",\n // accumulatedContent,\n // knownContent\n // );\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","/**\n * ScheduleLatticeManager\n *\n * Schedule Lattice manager for registering and managing schedule services\n * Supports both one-time and cron-style recurring tasks\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n ScheduleLatticeProtocol,\n ScheduleConfig,\n ScheduleType,\n ScheduleClient,\n ScheduleStorage,\n ScheduledTaskDefinition,\n TaskHandler,\n ScheduleOnceOptions,\n ScheduleCronOptions,\n} from \"@axiom-lattice/protocols\";\nimport { DefaultScheduleClient } from \"./DefaultScheduleClient\";\nimport { MemoryScheduleStorage } from \"./MemoryScheduleStorage\";\n\n/**\n * Schedule Lattice interface\n */\nexport interface ScheduleLattice extends ScheduleLatticeProtocol {\n key: string;\n config: ScheduleConfig;\n client: ScheduleLatticeProtocol[\"client\"];\n}\n\n/**\n * ScheduleLatticeManager - Singleton schedule Lattice manager\n * Responsible for registering and managing various schedule service Lattices\n */\nexport class ScheduleLatticeManager extends BaseLatticeManager<ScheduleLattice> {\n private static _instance: ScheduleLatticeManager;\n\n /**\n * Get ScheduleLatticeManager singleton instance\n */\n public static getInstance(): ScheduleLatticeManager {\n if (!ScheduleLatticeManager._instance) {\n ScheduleLatticeManager._instance = new ScheduleLatticeManager();\n }\n return ScheduleLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"schedules\";\n }\n\n /**\n * Register schedule Lattice\n * @param key Lattice key name\n * @param config Schedule configuration\n * @param client Optional schedule client. If not provided, will create based on config type.\n */\n public registerLattice(\n key: string,\n config: ScheduleConfig,\n client?: ScheduleClient\n ): void {\n // Create client based on schedule type if not provided\n let scheduleClient: ScheduleLatticeProtocol[\"client\"];\n\n if (client) {\n // Use provided client\n scheduleClient = client;\n // If storage is provided in config, set it on the client\n if (config.storage) {\n scheduleClient.setStorage(config.storage);\n }\n } else {\n // Create storage based on config\n let storage: ScheduleStorage;\n if (config.storage) {\n storage = config.storage;\n } else {\n // Default to memory storage\n storage = new MemoryScheduleStorage();\n }\n\n if (config.type === ScheduleType.MEMORY) {\n scheduleClient = new DefaultScheduleClient(storage);\n } else if (config.type === ScheduleType.POSTGRES) {\n // For Postgres, storage must be provided\n if (!config.storage) {\n throw new Error(\n `PostgreSQL schedule storage must be provided. Please install @axiom-lattice/pg-stores and pass the storage in config.storage.`\n );\n }\n scheduleClient = new DefaultScheduleClient(storage);\n } else {\n // Default to memory with memory storage\n scheduleClient = new DefaultScheduleClient(storage);\n }\n }\n\n // Create schedule Lattice object\n const scheduleLattice: ScheduleLattice = {\n key,\n config,\n client: scheduleClient,\n\n // Handler registration\n registerHandler: (taskType: string, handler: TaskHandler) => {\n scheduleClient.registerHandler(taskType, handler);\n },\n unregisterHandler: (taskType: string) => {\n return scheduleClient.unregisterHandler(taskType);\n },\n hasHandler: (taskType: string) => {\n return scheduleClient.hasHandler(taskType);\n },\n getHandlerTypes: () => {\n return scheduleClient.getHandlerTypes();\n },\n\n // One-time task scheduling\n scheduleOnce: async (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ) => {\n return scheduleClient.scheduleOnce(taskId, taskType, payload, options);\n },\n\n // Cron task scheduling\n scheduleCron: async (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ) => {\n return scheduleClient.scheduleCron(taskId, taskType, payload, options);\n },\n\n // Task management\n cancel: async (taskId: string) => {\n return scheduleClient.cancel(taskId);\n },\n pause: async (taskId: string) => {\n return scheduleClient.pause(taskId);\n },\n resume: async (taskId: string) => {\n return scheduleClient.resume(taskId);\n },\n has: async (taskId: string) => {\n return scheduleClient.has(taskId);\n },\n getTask: async (\n taskId: string\n ): Promise<ScheduledTaskDefinition | null> => {\n return scheduleClient.getTask(taskId);\n },\n getRemainingTime: async (taskId: string) => {\n return scheduleClient.getRemainingTime(taskId);\n },\n getActiveTaskCount: async () => {\n return scheduleClient.getActiveTaskCount();\n },\n getActiveTaskIds: async () => {\n return scheduleClient.getActiveTaskIds();\n },\n cancelAll: async () => {\n return scheduleClient.cancelAll();\n },\n\n // Recovery\n restore: async () => {\n return scheduleClient.restore();\n },\n };\n\n // Call base class register method\n this.register(key, scheduleLattice);\n }\n\n /**\n * Get ScheduleLattice\n * @param key Lattice key name\n */\n public getScheduleLattice(key: string): ScheduleLattice {\n const scheduleLattice = this.get(key);\n if (!scheduleLattice) {\n throw new Error(`ScheduleLattice ${key} not found`);\n }\n return scheduleLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): ScheduleLattice[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const scheduleLatticeManager = ScheduleLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerScheduleLattice = (\n key: string,\n config: ScheduleConfig,\n client?: ScheduleClient\n) => scheduleLatticeManager.registerLattice(key, config, client);\n\nexport const getScheduleLattice = (key: string) =>\n scheduleLatticeManager.getScheduleLattice(key);\n","/**\n * DefaultScheduleClient\n *\n * Default schedule client implementation with full protocol support\n * Core scheduling engine that handles timer management, cron parsing, and task execution\n * Supports both one-time and cron-style recurring tasks\n * Storage backend is pluggable - uses MemoryScheduleStorage by default\n */\n\nimport {\n ScheduleClient,\n ScheduleStorage,\n ScheduledTaskDefinition,\n ScheduledTaskStatus,\n ScheduleExecutionType,\n TaskHandler,\n ScheduleOnceOptions,\n ScheduleCronOptions,\n} from \"@axiom-lattice/protocols\";\nimport { MemoryScheduleStorage } from \"./MemoryScheduleStorage\";\nimport { getNextCronTime, isValidCronExpression } from \"./CronParser\";\n\n/**\n * Active timer info for in-memory scheduling\n */\ninterface ActiveTimer {\n timerId: NodeJS.Timeout;\n taskId: string;\n}\n\n/**\n * Default schedule client implementation\n * Core scheduling engine with pluggable storage backend\n */\nexport class DefaultScheduleClient implements ScheduleClient {\n private static instance: DefaultScheduleClient | null = null;\n\n private handlers: Map<string, TaskHandler> = new Map();\n private timers: Map<string, ActiveTimer> = new Map();\n private storage: ScheduleStorage;\n\n constructor(storage?: ScheduleStorage) {\n this.storage = storage || new MemoryScheduleStorage();\n }\n\n /**\n * Get the singleton instance of DefaultScheduleClient\n */\n public static getInstance(storage?: ScheduleStorage): DefaultScheduleClient {\n if (!DefaultScheduleClient.instance) {\n DefaultScheduleClient.instance = new DefaultScheduleClient(storage);\n }\n return DefaultScheduleClient.instance;\n }\n\n /**\n * Reset the singleton instance (useful for testing)\n */\n public static resetInstance(): void {\n if (DefaultScheduleClient.instance) {\n DefaultScheduleClient.instance.cancelAll();\n DefaultScheduleClient.instance = null;\n }\n }\n\n // ===== Handler Registration =====\n\n registerHandler(taskType: string, handler: TaskHandler): void {\n this.handlers.set(taskType, handler);\n console.log(`[Scheduler] Handler registered for task type: ${taskType}`);\n }\n\n unregisterHandler(taskType: string): boolean {\n const result = this.handlers.delete(taskType);\n if (result) {\n console.log(\n `[Scheduler] Handler unregistered for task type: ${taskType}`\n );\n }\n return result;\n }\n\n hasHandler(taskType: string): boolean {\n return this.handlers.has(taskType);\n }\n\n getHandlerTypes(): string[] {\n return Array.from(this.handlers.keys());\n }\n\n // ===== One-time Task Scheduling =====\n\n async scheduleOnce(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ): Promise<boolean> {\n // Validate handler exists\n if (!this.handlers.has(taskType)) {\n console.error(\n `[Scheduler] No handler registered for task type: ${taskType}`\n );\n return false;\n }\n\n // Calculate execute time\n let executeAt: number;\n if (options.executeAt !== undefined) {\n executeAt = options.executeAt;\n } else if (options.delayMs !== undefined) {\n executeAt = Date.now() + options.delayMs;\n } else {\n console.error(\"[Scheduler] Either executeAt or delayMs must be provided\");\n return false;\n }\n\n // Cancel existing task with same ID\n if (await this.has(taskId)) {\n await this.cancel(taskId);\n }\n\n const now = Date.now();\n const task: ScheduledTaskDefinition = {\n taskId,\n taskType,\n payload,\n assistantId: options.assistantId,\n threadId: options.threadId,\n executionType: ScheduleExecutionType.ONCE,\n executeAt,\n delayMs: options.delayMs,\n status: ScheduledTaskStatus.PENDING,\n runCount: 0,\n retryCount: 0,\n maxRetries: options.maxRetries ?? 0,\n createdAt: now,\n updatedAt: now,\n metadata: options.metadata,\n };\n\n // Save to storage\n await this.storage.save(task);\n\n // Schedule timer\n this.scheduleTimer(task);\n\n console.log(\n `[Scheduler] One-time task scheduled: ${taskId}, executes at ${new Date(\n executeAt\n ).toISOString()}`\n );\n return true;\n }\n\n // ===== Cron Task Scheduling =====\n\n async scheduleCron(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ): Promise<boolean> {\n // Validate handler exists\n if (!this.handlers.has(taskType)) {\n console.error(\n `[Scheduler] No handler registered for task type: ${taskType}`\n );\n return false;\n }\n\n // Validate cron expression\n if (!isValidCronExpression(options.cronExpression)) {\n console.error(\n `[Scheduler] Invalid cron expression: ${options.cronExpression}`\n );\n return false;\n }\n\n // Cancel existing task with same ID\n if (await this.has(taskId)) {\n await this.cancel(taskId);\n }\n\n const now = Date.now();\n const nextRunAt = getNextCronTime(options.cronExpression, new Date(now));\n\n const task: ScheduledTaskDefinition = {\n taskId,\n taskType,\n payload,\n assistantId: options.assistantId,\n threadId: options.threadId,\n executionType: ScheduleExecutionType.CRON,\n cronExpression: options.cronExpression,\n timezone: options.timezone,\n nextRunAt: nextRunAt.getTime(),\n status: ScheduledTaskStatus.PENDING,\n runCount: 0,\n maxRuns: options.maxRuns,\n retryCount: 0,\n maxRetries: options.maxRetries ?? 0,\n createdAt: now,\n updatedAt: now,\n expiresAt: options.expiresAt,\n metadata: options.metadata,\n };\n\n // Save to storage\n await this.storage.save(task);\n\n // Schedule timer\n this.scheduleTimer(task);\n\n console.log(\n `[Scheduler] Cron task scheduled: ${taskId}, expression: ${\n options.cronExpression\n }, next run: ${nextRunAt.toISOString()}`\n );\n return true;\n }\n\n // ===== Task Management =====\n\n async cancel(taskId: string): Promise<boolean> {\n // Clear timer\n const timer = this.timers.get(taskId);\n if (timer) {\n clearTimeout(timer.timerId);\n this.timers.delete(taskId);\n }\n\n // Update storage\n const task = await this.storage.get(taskId);\n if (task) {\n await this.storage.update(taskId, {\n status: ScheduledTaskStatus.CANCELLED,\n });\n console.log(`[Scheduler] Task cancelled: ${taskId}`);\n return true;\n }\n\n return false;\n }\n\n async pause(taskId: string): Promise<boolean> {\n const task = await this.storage.get(taskId);\n if (!task || task.executionType !== ScheduleExecutionType.CRON) {\n console.error(`[Scheduler] Can only pause CRON tasks: ${taskId}`);\n return false;\n }\n\n if (task.status !== ScheduledTaskStatus.PENDING) {\n console.error(`[Scheduler] Can only pause PENDING tasks: ${taskId}`);\n return false;\n }\n\n // Clear timer\n const timer = this.timers.get(taskId);\n if (timer) {\n clearTimeout(timer.timerId);\n this.timers.delete(taskId);\n }\n\n await this.storage.update(taskId, {\n status: ScheduledTaskStatus.PAUSED,\n });\n\n console.log(`[Scheduler] Task paused: ${taskId}`);\n return true;\n }\n\n async resume(taskId: string): Promise<boolean> {\n const task = await this.storage.get(taskId);\n if (!task || task.executionType !== ScheduleExecutionType.CRON) {\n console.error(`[Scheduler] Can only resume CRON tasks: ${taskId}`);\n return false;\n }\n\n if (task.status !== ScheduledTaskStatus.PAUSED) {\n console.error(`[Scheduler] Can only resume PAUSED tasks: ${taskId}`);\n return false;\n }\n\n // Calculate next run time\n const nextRunAt = getNextCronTime(task.cronExpression!);\n\n await this.storage.update(taskId, {\n status: ScheduledTaskStatus.PENDING,\n nextRunAt: nextRunAt.getTime(),\n });\n\n // Re-fetch updated task and schedule\n const updatedTask = await this.storage.get(taskId);\n if (updatedTask) {\n this.scheduleTimer(updatedTask);\n }\n\n console.log(`[Scheduler] Task resumed: ${taskId}`);\n return true;\n }\n\n async has(taskId: string): Promise<boolean> {\n const task = await this.storage.get(taskId);\n return task !== null;\n }\n\n async getTask(taskId: string): Promise<ScheduledTaskDefinition | null> {\n return this.storage.get(taskId);\n }\n\n async getRemainingTime(taskId: string): Promise<number> {\n const task = await this.storage.get(taskId);\n if (!task) {\n return -1;\n }\n\n const targetTime =\n task.executionType === ScheduleExecutionType.CRON\n ? task.nextRunAt\n : task.executeAt;\n\n if (targetTime === undefined) {\n return -1;\n }\n\n return Math.max(0, targetTime - Date.now());\n }\n\n async getActiveTaskCount(): Promise<number> {\n const tasks = await this.storage.getActiveTasks();\n return tasks.length;\n }\n\n async getActiveTaskIds(): Promise<string[]> {\n const tasks = await this.storage.getActiveTasks();\n return tasks.map((t) => t.taskId);\n }\n\n async cancelAll(): Promise<void> {\n // Clear all timers\n for (const timer of this.timers.values()) {\n clearTimeout(timer.timerId);\n }\n this.timers.clear();\n\n // Update all active tasks to cancelled\n const activeTasks = await this.storage.getActiveTasks();\n for (const task of activeTasks) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.CANCELLED,\n });\n }\n\n console.log(`[Scheduler] All tasks cancelled`);\n }\n\n // ===== Recovery =====\n\n async restore(): Promise<number> {\n const activeTasks = await this.storage.getActiveTasks();\n let restored = 0;\n\n for (const task of activeTasks) {\n // Skip if no handler registered\n if (!this.handlers.has(task.taskType)) {\n console.warn(\n `[Scheduler] No handler for task type ${task.taskType}, skipping restore for task ${task.taskId}`\n );\n continue;\n }\n\n // Skip paused tasks (they'll be resumed manually)\n if (task.status === ScheduledTaskStatus.PAUSED) {\n continue;\n }\n\n if (task.executionType === ScheduleExecutionType.ONCE) {\n // For one-time tasks, check if execution time has passed\n if (task.executeAt && task.executeAt <= Date.now()) {\n // Execute immediately\n console.log(\n `[Scheduler] Executing overdue one-time task: ${task.taskId}`\n );\n this.executeTask(task);\n } else {\n // Schedule for remaining time\n this.scheduleTimer(task);\n }\n } else if (task.executionType === ScheduleExecutionType.CRON) {\n // For cron tasks, calculate next run time\n const nextRunAt = getNextCronTime(task.cronExpression!);\n await this.storage.update(task.taskId, {\n nextRunAt: nextRunAt.getTime(),\n });\n\n const updatedTask = await this.storage.get(task.taskId);\n if (updatedTask) {\n this.scheduleTimer(updatedTask);\n }\n }\n\n restored++;\n }\n\n console.log(`[Scheduler] Restored ${restored} tasks`);\n return restored;\n }\n\n // ===== Storage =====\n\n setStorage(storage: ScheduleStorage): void {\n this.storage = storage;\n }\n\n getStorage(): ScheduleStorage | null {\n return this.storage;\n }\n\n // ===== Private Methods =====\n\n private scheduleTimer(task: ScheduledTaskDefinition): void {\n const targetTime =\n task.executionType === ScheduleExecutionType.CRON\n ? task.nextRunAt\n : task.executeAt;\n\n if (targetTime === undefined) {\n console.error(`[Scheduler] No execution time for task: ${task.taskId}`);\n return;\n }\n\n const delay = Math.max(0, targetTime - Date.now());\n\n const timerId = setTimeout(() => {\n this.executeTask(task);\n }, delay);\n\n this.timers.set(task.taskId, {\n timerId,\n taskId: task.taskId,\n });\n }\n\n private async executeTask(task: ScheduledTaskDefinition): Promise<void> {\n const handler = this.handlers.get(task.taskType);\n if (!handler) {\n console.error(\n `[Scheduler] No handler for task type: ${task.taskType}, task: ${task.taskId}`\n );\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.FAILED,\n lastError: `No handler registered for task type: ${task.taskType}`,\n });\n return;\n }\n\n // Update status to running\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.RUNNING,\n });\n\n console.log(`[Scheduler] Executing task: ${task.taskId}`);\n\n try {\n // Get latest task state\n const latestTask = await this.storage.get(task.taskId);\n if (!latestTask) {\n console.error(`[Scheduler] Task not found: ${task.taskId}`);\n return;\n }\n\n await handler(latestTask.payload, latestTask);\n\n const newRunCount = latestTask.runCount + 1;\n console.log(`[Scheduler] Task completed: ${task.taskId}`);\n\n // Handle completion based on execution type\n if (task.executionType === ScheduleExecutionType.ONCE) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.COMPLETED,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n });\n this.timers.delete(task.taskId);\n } else if (task.executionType === ScheduleExecutionType.CRON) {\n // Check if max runs reached\n if (task.maxRuns !== undefined && newRunCount >= task.maxRuns) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.COMPLETED,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n });\n this.timers.delete(task.taskId);\n console.log(\n `[Scheduler] Cron task completed (max runs): ${task.taskId}`\n );\n return;\n }\n\n // Check if expired\n if (task.expiresAt !== undefined && Date.now() >= task.expiresAt) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.COMPLETED,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n });\n this.timers.delete(task.taskId);\n console.log(\n `[Scheduler] Cron task completed (expired): ${task.taskId}`\n );\n return;\n }\n\n // Schedule next run\n const nextRunAt = getNextCronTime(task.cronExpression!);\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.PENDING,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n nextRunAt: nextRunAt.getTime(),\n retryCount: 0, // Reset retry count on success\n });\n\n const updatedTask = await this.storage.get(task.taskId);\n if (updatedTask) {\n this.scheduleTimer(updatedTask);\n console.log(\n `[Scheduler] Next cron run scheduled: ${\n task.taskId\n } at ${nextRunAt.toISOString()}`\n );\n }\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n console.error(`[Scheduler] Task failed: ${task.taskId}`, error);\n\n const latestTask = await this.storage.get(task.taskId);\n if (!latestTask) return;\n\n const newRetryCount = latestTask.retryCount + 1;\n\n // Check if can retry\n if (newRetryCount <= latestTask.maxRetries) {\n console.log(\n `[Scheduler] Retrying task: ${task.taskId} (attempt ${newRetryCount}/${latestTask.maxRetries})`\n );\n\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.PENDING,\n retryCount: newRetryCount,\n lastError: errorMessage,\n });\n\n // Retry with exponential backoff\n const retryDelay = Math.min(\n 1000 * Math.pow(2, newRetryCount - 1),\n 60000\n );\n const retryTask = await this.storage.get(task.taskId);\n if (retryTask) {\n if (task.executionType === ScheduleExecutionType.ONCE) {\n retryTask.executeAt = Date.now() + retryDelay;\n } else {\n retryTask.nextRunAt = Date.now() + retryDelay;\n }\n await this.storage.update(task.taskId, {\n executeAt: retryTask.executeAt,\n nextRunAt: retryTask.nextRunAt,\n });\n this.scheduleTimer(retryTask);\n }\n } else {\n // Max retries exceeded\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.FAILED,\n retryCount: newRetryCount,\n lastError: errorMessage,\n });\n this.timers.delete(task.taskId);\n console.error(\n `[Scheduler] Task failed permanently: ${task.taskId} (max retries exceeded)`\n );\n }\n }\n }\n}\n","/**\n * MemoryScheduleStorage\n *\n * In-memory storage implementation for scheduled tasks\n * Useful for development and testing, not recommended for production\n * Data is lost on service restart\n */\n\nimport {\n ScheduleStorage,\n ScheduledTaskDefinition,\n ScheduledTaskStatus,\n ScheduleExecutionType,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory storage for scheduled tasks\n */\nexport class MemoryScheduleStorage implements ScheduleStorage {\n private tasks: Map<string, ScheduledTaskDefinition> = new Map();\n\n /**\n * Save a new task\n */\n async save(task: ScheduledTaskDefinition): Promise<void> {\n this.tasks.set(task.taskId, { ...task });\n }\n\n /**\n * Get task by ID\n */\n async get(taskId: string): Promise<ScheduledTaskDefinition | null> {\n const task = this.tasks.get(taskId);\n return task ? { ...task } : null;\n }\n\n /**\n * Update task\n */\n async update(\n taskId: string,\n updates: Partial<ScheduledTaskDefinition>\n ): Promise<void> {\n const task = this.tasks.get(taskId);\n if (task) {\n this.tasks.set(taskId, {\n ...task,\n ...updates,\n updatedAt: Date.now(),\n });\n }\n }\n\n /**\n * Delete task\n */\n async delete(taskId: string): Promise<void> {\n this.tasks.delete(taskId);\n }\n\n /**\n * Get all active tasks (pending or paused)\n */\n async getActiveTasks(): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (\n task.status === ScheduledTaskStatus.PENDING ||\n task.status === ScheduledTaskStatus.PAUSED\n ) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by type\n */\n async getTasksByType(taskType: string): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.taskType === taskType) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by status\n */\n async getTasksByStatus(\n status: ScheduledTaskStatus\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.status === status) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by execution type\n */\n async getTasksByExecutionType(\n executionType: ScheduleExecutionType\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.executionType === executionType) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by assistant ID\n */\n async getTasksByAssistantId(\n assistantId: string\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.assistantId === assistantId) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by thread ID\n */\n async getTasksByThreadId(\n threadId: string\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.threadId === threadId) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get all tasks with optional filters\n */\n async getAllTasks(filters?: {\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n limit?: number;\n offset?: number;\n }): Promise<ScheduledTaskDefinition[]> {\n let result: ScheduledTaskDefinition[] = [];\n\n for (const task of this.tasks.values()) {\n let match = true;\n\n if (filters?.status !== undefined && task.status !== filters.status) {\n match = false;\n }\n if (\n filters?.executionType !== undefined &&\n task.executionType !== filters.executionType\n ) {\n match = false;\n }\n if (\n filters?.taskType !== undefined &&\n task.taskType !== filters.taskType\n ) {\n match = false;\n }\n if (\n filters?.assistantId !== undefined &&\n task.assistantId !== filters.assistantId\n ) {\n match = false;\n }\n if (\n filters?.threadId !== undefined &&\n task.threadId !== filters.threadId\n ) {\n match = false;\n }\n\n if (match) {\n result.push({ ...task });\n }\n }\n\n // Sort by createdAt descending\n result.sort((a, b) => b.createdAt - a.createdAt);\n\n // Apply offset and limit\n const offset = filters?.offset || 0;\n const limit = filters?.limit;\n\n if (limit !== undefined) {\n result = result.slice(offset, offset + limit);\n } else if (offset > 0) {\n result = result.slice(offset);\n }\n\n return result;\n }\n\n /**\n * Count tasks with optional filters\n */\n async countTasks(filters?: {\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n }): Promise<number> {\n let count = 0;\n\n for (const task of this.tasks.values()) {\n let match = true;\n\n if (filters?.status !== undefined && task.status !== filters.status) {\n match = false;\n }\n if (\n filters?.executionType !== undefined &&\n task.executionType !== filters.executionType\n ) {\n match = false;\n }\n if (\n filters?.taskType !== undefined &&\n task.taskType !== filters.taskType\n ) {\n match = false;\n }\n if (\n filters?.assistantId !== undefined &&\n task.assistantId !== filters.assistantId\n ) {\n match = false;\n }\n if (\n filters?.threadId !== undefined &&\n task.threadId !== filters.threadId\n ) {\n match = false;\n }\n\n if (match) {\n count++;\n }\n }\n\n return count;\n }\n\n /**\n * Delete completed/cancelled tasks older than specified time\n */\n async deleteOldTasks(olderThanMs: number): Promise<number> {\n const cutoff = Date.now() - olderThanMs;\n let deleted = 0;\n\n for (const [taskId, task] of this.tasks.entries()) {\n if (\n (task.status === ScheduledTaskStatus.COMPLETED ||\n task.status === ScheduledTaskStatus.CANCELLED ||\n task.status === ScheduledTaskStatus.FAILED) &&\n task.updatedAt < cutoff\n ) {\n this.tasks.delete(taskId);\n deleted++;\n }\n }\n\n return deleted;\n }\n\n /**\n * Clear all tasks (useful for testing)\n */\n clear(): void {\n this.tasks.clear();\n }\n\n /**\n * Get total task count (useful for debugging)\n */\n size(): number {\n return this.tasks.size;\n }\n}\n","/**\n * CronParser\n *\n * Simple cron expression parser for calculating next execution time\n * Supports standard 5-field cron format: minute hour day-of-month month day-of-week\n *\n * Field values:\n * minute: 0-59\n * hour: 0-23\n * day-of-month: 1-31\n * month: 1-12\n * day-of-week: 0-7 (0 and 7 are Sunday)\n *\n * Special characters:\n * asterisk (*) : any value\n * comma (,) : value list separator (1,3,5)\n * dash (-) : range of values (1-5)\n * slash (/) : step values (asterisk/5 = every 5)\n */\n\nexport interface CronFields {\n minute: number[];\n hour: number[];\n dayOfMonth: number[];\n month: number[];\n dayOfWeek: number[];\n}\n\n/**\n * Parse a cron expression into field arrays\n */\nexport function parseCronExpression(expression: string): CronFields {\n const parts = expression.trim().split(/\\s+/);\n\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression: expected 5 fields, got ${parts.length}`\n );\n }\n\n return {\n minute: parseField(parts[0], 0, 59),\n hour: parseField(parts[1], 0, 23),\n dayOfMonth: parseField(parts[2], 1, 31),\n month: parseField(parts[3], 1, 12),\n dayOfWeek: parseField(parts[4], 0, 7).map((d) => (d === 7 ? 0 : d)), // Normalize Sunday\n };\n}\n\n/**\n * Parse a single cron field\n */\nfunction parseField(field: string, min: number, max: number): number[] {\n const values = new Set<number>();\n\n // Handle comma-separated values\n const segments = field.split(\",\");\n\n for (const segment of segments) {\n // Handle step values (*/5 or 1-10/2)\n const [range, stepStr] = segment.split(\"/\");\n const step = stepStr ? parseInt(stepStr, 10) : 1;\n\n if (isNaN(step) || step < 1) {\n throw new Error(`Invalid step value: ${stepStr}`);\n }\n\n let rangeStart: number;\n let rangeEnd: number;\n\n if (range === \"*\") {\n rangeStart = min;\n rangeEnd = max;\n } else if (range.includes(\"-\")) {\n // Handle range (1-5)\n const [startStr, endStr] = range.split(\"-\");\n rangeStart = parseInt(startStr, 10);\n rangeEnd = parseInt(endStr, 10);\n\n if (isNaN(rangeStart) || isNaN(rangeEnd)) {\n throw new Error(`Invalid range: ${range}`);\n }\n } else {\n // Single value\n const value = parseInt(range, 10);\n if (isNaN(value)) {\n throw new Error(`Invalid value: ${range}`);\n }\n rangeStart = value;\n rangeEnd = value;\n }\n\n // Validate range\n if (rangeStart < min || rangeEnd > max || rangeStart > rangeEnd) {\n throw new Error(`Value out of range: ${range} (expected ${min}-${max})`);\n }\n\n // Add values with step\n for (let i = rangeStart; i <= rangeEnd; i += step) {\n values.add(i);\n }\n }\n\n return Array.from(values).sort((a, b) => a - b);\n}\n\n/**\n * Get the next execution time after the given date\n */\nexport function getNextCronTime(\n expression: string,\n after: Date = new Date(),\n timezone?: string\n): Date {\n const fields = parseCronExpression(expression);\n\n // Start from the next minute\n const next = new Date(after.getTime());\n next.setSeconds(0, 0);\n next.setMinutes(next.getMinutes() + 1);\n\n // Maximum iterations to prevent infinite loop\n const maxIterations = 366 * 24 * 60; // 1 year in minutes\n let iterations = 0;\n\n while (iterations < maxIterations) {\n iterations++;\n\n // Check month\n const month = next.getMonth() + 1; // JS months are 0-based\n if (!fields.month.includes(month)) {\n // Move to next valid month\n const nextMonth = fields.month.find((m) => m > month);\n if (nextMonth !== undefined) {\n next.setMonth(nextMonth - 1, 1);\n } else {\n // Next year, first valid month\n next.setFullYear(next.getFullYear() + 1);\n next.setMonth(fields.month[0] - 1, 1);\n }\n next.setHours(fields.hour[0], fields.minute[0], 0, 0);\n continue;\n }\n\n // Check day of month\n const dayOfMonth = next.getDate();\n const maxDayOfMonth = new Date(\n next.getFullYear(),\n next.getMonth() + 1,\n 0\n ).getDate();\n\n // Check day of week\n const dayOfWeek = next.getDay();\n\n // Both dayOfMonth and dayOfWeek must match if not wildcard\n const dayOfMonthMatch = fields.dayOfMonth.includes(dayOfMonth);\n const dayOfWeekMatch = fields.dayOfWeek.includes(dayOfWeek);\n\n // If either field is not *, both must match; if one is *, only the other needs to match\n const dayOfMonthWildcard =\n fields.dayOfMonth.length === 31 &&\n fields.dayOfMonth[0] === 1 &&\n fields.dayOfMonth[30] === 31;\n const dayOfWeekWildcard =\n fields.dayOfWeek.length >= 7 ||\n (fields.dayOfWeek.length === 1 && fields.dayOfWeek.includes(0));\n\n let dayMatch: boolean;\n if (dayOfMonthWildcard && dayOfWeekWildcard) {\n dayMatch = true;\n } else if (dayOfMonthWildcard) {\n dayMatch = dayOfWeekMatch;\n } else if (dayOfWeekWildcard) {\n dayMatch = dayOfMonthMatch;\n } else {\n // Standard cron behavior: OR between dayOfMonth and dayOfWeek when both are specified\n dayMatch = dayOfMonthMatch || dayOfWeekMatch;\n }\n\n if (!dayMatch || dayOfMonth > maxDayOfMonth) {\n // Move to next day\n next.setDate(next.getDate() + 1);\n next.setHours(fields.hour[0], fields.minute[0], 0, 0);\n continue;\n }\n\n // Check hour\n const hour = next.getHours();\n if (!fields.hour.includes(hour)) {\n const nextHour = fields.hour.find((h) => h > hour);\n if (nextHour !== undefined) {\n next.setHours(nextHour, fields.minute[0], 0, 0);\n } else {\n // Next day, first valid hour\n next.setDate(next.getDate() + 1);\n next.setHours(fields.hour[0], fields.minute[0], 0, 0);\n }\n continue;\n }\n\n // Check minute\n const minute = next.getMinutes();\n if (!fields.minute.includes(minute)) {\n const nextMinute = fields.minute.find((m) => m > minute);\n if (nextMinute !== undefined) {\n next.setMinutes(nextMinute, 0, 0);\n } else {\n // Next hour\n next.setHours(next.getHours() + 1, fields.minute[0], 0, 0);\n }\n continue;\n }\n\n // All fields match!\n return next;\n }\n\n throw new Error(\"Could not find next cron time within 1 year\");\n}\n\n/**\n * Validate a cron expression\n */\nexport function isValidCronExpression(expression: string): boolean {\n try {\n parseCronExpression(expression);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get a human-readable description of a cron expression\n */\nexport function describeCronExpression(expression: string): string {\n const fields = parseCronExpression(expression);\n\n const parts: string[] = [];\n\n // Minute\n if (fields.minute.length === 60) {\n parts.push(\"every minute\");\n } else if (fields.minute.length === 1) {\n parts.push(`at minute ${fields.minute[0]}`);\n } else {\n parts.push(`at minutes ${fields.minute.join(\", \")}`);\n }\n\n // Hour\n if (fields.hour.length === 24) {\n parts.push(\"of every hour\");\n } else if (fields.hour.length === 1) {\n parts.push(`of hour ${fields.hour[0]}`);\n } else {\n parts.push(`of hours ${fields.hour.join(\", \")}`);\n }\n\n // Day of month\n if (fields.dayOfMonth.length < 31) {\n if (fields.dayOfMonth.length === 1) {\n parts.push(`on day ${fields.dayOfMonth[0]}`);\n } else {\n parts.push(`on days ${fields.dayOfMonth.join(\", \")}`);\n }\n }\n\n // Month\n const monthNames = [\n \"\",\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n ];\n if (fields.month.length < 12) {\n const months = fields.month.map((m) => monthNames[m]);\n parts.push(`in ${months.join(\", \")}`);\n }\n\n // Day of week\n const dayNames = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const uniqueDays = [...new Set(fields.dayOfWeek)];\n if (uniqueDays.length < 7) {\n const days = uniqueDays.map((d) => dayNames[d]);\n parts.push(`on ${days.join(\", \")}`);\n }\n\n return parts.join(\" \");\n}\n","import { Embeddings } from \"@langchain/core/embeddings\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\n\n/**\n * Embeddings Lattice Interface\n * Defines the structure of an embeddings lattice entry\n */\nexport interface EmbeddingsLatticeInterface {\n key: string;\n client: Embeddings;\n}\n\n/**\n * EmbeddingsLatticeManager - Singleton embeddings Lattice manager\n * Responsible for registering and managing various embeddings model Lattices\n */\nexport class EmbeddingsLatticeManager extends BaseLatticeManager<EmbeddingsLatticeInterface> {\n private static _instance: EmbeddingsLatticeManager;\n\n /**\n * Get EmbeddingsLatticeManager singleton instance\n */\n public static getInstance(): EmbeddingsLatticeManager {\n if (!EmbeddingsLatticeManager._instance) {\n EmbeddingsLatticeManager._instance = new EmbeddingsLatticeManager();\n }\n return EmbeddingsLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"embeddings\";\n }\n\n /**\n * Register embeddings Lattice\n * @param key Lattice key name\n * @param embeddings Embeddings instance\n */\n public registerLattice(key: string, embeddings: Embeddings): void {\n // Create embeddings Lattice object\n const embeddingsLattice: EmbeddingsLatticeInterface = {\n key,\n client: embeddings,\n };\n\n // Call base class register method\n this.register(key, embeddingsLattice);\n }\n\n /**\n * Get EmbeddingsLattice\n * @param key Lattice key name\n */\n public getEmbeddingsLattice(key: string): EmbeddingsLatticeInterface {\n const embeddingsLattice = this.get(key);\n if (!embeddingsLattice) {\n throw new Error(`EmbeddingsLattice ${key} not found`);\n }\n return embeddingsLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): EmbeddingsLatticeInterface[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * Get embeddings client\n * @param key Lattice key name\n */\n public getEmbeddingsClient(key: string): Embeddings {\n const embeddingsLattice = this.getEmbeddingsLattice(key);\n return embeddingsLattice.client;\n }\n}\n\n// Export singleton instance\nexport const embeddingsLatticeManager = EmbeddingsLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerEmbeddingsLattice = (\n key: string,\n embeddings: Embeddings\n) => embeddingsLatticeManager.registerLattice(key, embeddings);\n\nexport const getEmbeddingsLattice = (key: string) =>\n embeddingsLatticeManager.getEmbeddingsLattice(key);\n\nexport const getEmbeddingsClient = (key: string) =>\n embeddingsLatticeManager.getEmbeddingsClient(key);\n","import { VectorStore } from \"@langchain/core/vectorstores\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\n\n/**\n * VectorStore Lattice Interface\n * Defines the structure of a vector store lattice entry\n */\nexport interface VectorStoreLatticeInterface {\n key: string;\n client: VectorStore;\n}\n\n/**\n * VectorStoreLatticeManager - Singleton vector store Lattice manager\n * Responsible for registering and managing various vector store Lattices\n */\nexport class VectorStoreLatticeManager extends BaseLatticeManager<VectorStoreLatticeInterface> {\n private static _instance: VectorStoreLatticeManager;\n\n /**\n * Get VectorStoreLatticeManager singleton instance\n */\n public static getInstance(): VectorStoreLatticeManager {\n if (!VectorStoreLatticeManager._instance) {\n VectorStoreLatticeManager._instance = new VectorStoreLatticeManager();\n }\n return VectorStoreLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"vectorstores\";\n }\n\n /**\n * Register vector store Lattice\n * @param key Lattice key name\n * @param vectorStore VectorStore instance\n */\n public registerLattice(key: string, vectorStore: VectorStore): void {\n // Create vector store Lattice object\n const vectorStoreLattice: VectorStoreLatticeInterface = {\n key,\n client: vectorStore,\n };\n\n // Call base class register method\n this.register(key, vectorStoreLattice);\n }\n\n /**\n * Get VectorStoreLattice\n * @param key Lattice key name\n */\n public getVectorStoreLattice(key: string): VectorStoreLatticeInterface {\n const vectorStoreLattice = this.get(key);\n if (!vectorStoreLattice) {\n throw new Error(`VectorStoreLattice ${key} not found`);\n }\n return vectorStoreLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): VectorStoreLatticeInterface[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * Get vector store client\n * @param key Lattice key name\n */\n public getVectorStoreClient(key: string): VectorStore {\n const vectorStoreLattice = this.getVectorStoreLattice(key);\n return vectorStoreLattice.client;\n }\n}\n\n// Export singleton instance\nexport const vectorStoreLatticeManager = VectorStoreLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerVectorStoreLattice = (key: string, vectorStore: VectorStore) =>\n vectorStoreLatticeManager.registerLattice(key, vectorStore);\n\nexport const getVectorStoreLattice = (key: string) =>\n vectorStoreLatticeManager.getVectorStoreLattice(key);\n\nexport const getVectorStoreClient = (key: string) =>\n vectorStoreLatticeManager.getVectorStoreClient(key);\n\n","/**\n * LoggerLatticeManager\n *\n * Logger Lattice manager for registering and managing logger services\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n LoggerLatticeProtocol,\n LoggerConfig,\n LoggerType,\n LoggerClient,\n} from \"@axiom-lattice/protocols\";\nimport { PinoLoggerClient } from \"./PinoLoggerClient\";\nimport { ConsoleLoggerClient } from \"./ConsoleLoggerClient\";\n\n/**\n * Logger Lattice interface\n */\nexport interface LoggerLattice extends LoggerLatticeProtocol {\n key: string;\n config: LoggerConfig;\n client: LoggerLatticeProtocol[\"client\"];\n}\n\n/**\n * LoggerLatticeManager - Singleton logger Lattice manager\n * Responsible for registering and managing various logger service Lattices\n */\nexport class LoggerLatticeManager extends BaseLatticeManager<LoggerLattice> {\n private static _instance: LoggerLatticeManager;\n\n /**\n * Get LoggerLatticeManager singleton instance\n */\n public static getInstance(): LoggerLatticeManager {\n if (!LoggerLatticeManager._instance) {\n LoggerLatticeManager._instance = new LoggerLatticeManager();\n }\n return LoggerLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"loggers\";\n }\n\n /**\n * Register logger Lattice\n * @param key Lattice key name\n * @param config Logger configuration\n * @param client Optional logger client. If not provided, will create based on config type.\n */\n public registerLattice(\n key: string,\n config: LoggerConfig,\n client?: LoggerClient\n ): void {\n // Create client based on logger type if not provided\n let loggerClient: LoggerLatticeProtocol[\"client\"];\n\n if (client) {\n // Use provided client\n loggerClient = client;\n } else {\n if (config.type === LoggerType.PINO) {\n loggerClient = new PinoLoggerClient(config);\n } else if (config.type === LoggerType.CONSOLE) {\n loggerClient = new ConsoleLoggerClient(config);\n } else if (config.type === LoggerType.CUSTOM) {\n // For custom type, client must be provided\n throw new Error(\n `Custom logger client must be provided. Please pass the client to registerLattice.`\n );\n } else {\n // Default to pino\n loggerClient = new PinoLoggerClient(config);\n }\n }\n\n // Create logger Lattice object\n const loggerLattice: LoggerLattice = {\n key,\n config,\n client: loggerClient,\n\n // Logger operations\n info: (msg: string, obj?: object) => {\n loggerClient.info(msg, obj);\n },\n error: (msg: string, obj?: object | Error) => {\n loggerClient.error(msg, obj);\n },\n warn: (msg: string, obj?: object) => {\n loggerClient.warn(msg, obj);\n },\n debug: (msg: string, obj?: object) => {\n loggerClient.debug(msg, obj);\n },\n updateContext: loggerClient.updateContext\n ? (context) => {\n loggerClient.updateContext!(context);\n }\n : undefined,\n child: loggerClient.child\n ? (options) => {\n return loggerClient.child!(options);\n }\n : undefined,\n };\n\n // Call base class register method\n this.register(key, loggerLattice);\n }\n\n /**\n * Get LoggerLattice\n * @param key Lattice key name\n */\n public getLoggerLattice(key: string): LoggerLattice {\n const loggerLattice = this.get(key);\n if (!loggerLattice) {\n throw new Error(`LoggerLattice ${key} not found`);\n }\n return loggerLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): LoggerLattice[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const loggerLatticeManager = LoggerLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerLoggerLattice = (\n key: string,\n config: LoggerConfig,\n client?: LoggerClient\n) => loggerLatticeManager.registerLattice(key, config, client);\n\nexport const getLoggerLattice = (key: string) =>\n loggerLatticeManager.getLoggerLattice(key);\n","/**\n * PinoLoggerClient\n *\n * Pino-based logger client implementation\n */\n\nimport pino from \"pino\";\nimport \"pino-pretty\";\nimport \"pino-roll\";\nimport {\n LoggerClient,\n LoggerContext,\n LoggerConfig,\n PinoFileOptions,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * Pino-based logger client implementation\n * Supports custom file paths and pino configurations\n */\nexport class PinoLoggerClient implements LoggerClient {\n private pinoLogger: pino.Logger;\n private config: LoggerConfig;\n private context: LoggerContext;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n this.context = config.context || {};\n\n // Create pino logger with custom configuration\n const loggerConfig: pino.LoggerOptions = {\n // Custom timestamp format\n timestamp: () => `,\"@timestamp\":\"${new Date().toISOString()}\"`,\n\n // Base metadata\n base: {\n \"@version\": \"1\",\n app_name: \"lattice\",\n service_name: config.serviceName || \"lattice-service\",\n thread_name: \"main\",\n logger_name: config.loggerName || config.name || \"lattice-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 // Determine if we should use file logging\n const useFileLogging = this.shouldUseFileLogging(config);\n const fileOptions = this.getFileOptions(config);\n\n if (useFileLogging && fileOptions) {\n // Use file logging with pino-roll\n try {\n this.pinoLogger = pino(\n loggerConfig,\n pino.transport({\n target: \"pino-roll\",\n options: {\n file: fileOptions.file || \"./logs/app\",\n frequency: fileOptions.frequency || \"daily\",\n mkdir: fileOptions.mkdir !== false, // Default to true\n size: fileOptions.size,\n maxFiles: fileOptions.maxFiles,\n },\n })\n );\n } catch (error) {\n console.error(\n \"Failed to initialize pino-roll logger, falling back to console\",\n error\n );\n // Fallback to console logging\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n } else {\n // Use console logging with pretty output\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n }\n\n /**\n * Determine if file logging should be used\n */\n private shouldUseFileLogging(config: LoggerConfig): boolean {\n // Use file logging if:\n // 1. file option is provided, OR\n // 2. NODE_ENV is production (unless explicitly disabled)\n const hasFileConfig = config.file !== undefined;\n const isProduction = process.env.NODE_ENV === \"production\";\n return hasFileConfig || isProduction;\n }\n\n /**\n * Get file options from config\n */\n private getFileOptions(config: LoggerConfig): PinoFileOptions | null {\n if (!config.file) {\n // If no file config but in production, use default\n if (process.env.NODE_ENV === \"production\") {\n return {\n file: \"./logs/app\",\n frequency: \"daily\",\n mkdir: true,\n };\n }\n return null;\n }\n\n // If file is a string, convert to PinoFileOptions\n if (typeof config.file === \"string\") {\n return {\n file: config.file,\n frequency: \"daily\",\n mkdir: true,\n };\n }\n\n // Otherwise, it's already PinoFileOptions\n return config.file;\n }\n\n /**\n * Get contextual logger with merged context\n */\n private getContextualLogger(additionalContext?: object): pino.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-thread-id\": this.context[\"x-thread-id\"] || \"\",\n service_name: this.config.serviceName || \"lattice-service\",\n logger_name:\n this.config.loggerName || this.config.name || \"lattice-logger\",\n ...additionalContext,\n };\n\n return this.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 updateContext(context: Partial<LoggerContext>): void {\n this.context = {\n ...this.context,\n ...context,\n };\n }\n\n child(options: Partial<LoggerConfig>): LoggerClient {\n // Create a new PinoLoggerClient with merged config\n return new PinoLoggerClient({\n ...this.config,\n ...options,\n context: {\n ...this.context,\n ...options.context,\n },\n });\n }\n}\n","/**\n * ConsoleLoggerClient\n *\n * Simple console-based logger client implementation\n */\n\nimport { LoggerClient, LoggerContext, LoggerConfig } from \"@axiom-lattice/protocols\";\n\n/**\n * Console-based logger client implementation\n */\nexport class ConsoleLoggerClient implements LoggerClient {\n private config: LoggerConfig;\n private context: LoggerContext;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n this.context = config.context || {};\n }\n\n private formatMessage(level: string, msg: string, obj?: object): string {\n const timestamp = new Date().toISOString();\n const contextStr = Object.keys(this.context).length > 0\n ? ` [${JSON.stringify(this.context)}]`\n : \"\";\n const objStr = obj ? ` ${JSON.stringify(obj)}` : \"\";\n return `[${timestamp}] [${level}]${contextStr} ${msg}${objStr}`;\n }\n\n info(msg: string, obj?: object): void {\n console.log(this.formatMessage(\"INFO\", msg, obj));\n }\n\n error(msg: string, obj?: object | Error): void {\n console.error(this.formatMessage(\"ERROR\", msg, obj));\n }\n\n warn(msg: string, obj?: object): void {\n console.warn(this.formatMessage(\"WARN\", msg, obj));\n }\n\n debug(msg: string, obj?: object): void {\n console.debug(this.formatMessage(\"DEBUG\", msg, obj));\n }\n\n updateContext(context: Partial<LoggerContext>): void {\n this.context = {\n ...this.context,\n ...context,\n };\n }\n\n child(options: Partial<LoggerConfig>): LoggerClient {\n const childClient = new ConsoleLoggerClient({\n ...this.config,\n ...options,\n context: {\n ...this.context,\n ...options.context,\n },\n });\n return childClient;\n }\n}\n","/**\n * SkillLatticeManager\n *\n * Skill Lattice manager for registering and managing skill components\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n SkillConfig,\n SkillLatticeProtocol,\n SkillClient,\n SkillClientType,\n SkillStore,\n} from \"@axiom-lattice/protocols\";\nimport { storeLatticeManager } from \"../store_lattice/StoreLatticeManager\";\nimport { validateSkillName } from \"./skillNameValidator\";\n\n/**\n * Skill Lattice interface\n */\nexport interface SkillLattice {\n key: string;\n config: SkillConfig;\n client: SkillClient | null;\n}\n\n/**\n * SkillLatticeManager - Singleton skill Lattice manager\n * Responsible for registering and managing various skill Lattices\n */\nexport class SkillLatticeManager extends BaseLatticeManager<SkillLattice> {\n private static _instance: SkillLatticeManager;\n private storeKey?: string;\n\n /**\n * Get SkillLatticeManager singleton instance\n */\n public static getInstance(): SkillLatticeManager {\n if (!SkillLatticeManager._instance) {\n SkillLatticeManager._instance = new SkillLatticeManager();\n }\n return SkillLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"skills\";\n }\n\n /**\n * Configure store for persistence\n * @param storeKey Store key name registered in StoreLatticeManager\n */\n public configureStore(storeKey: string): void {\n this.storeKey = storeKey;\n }\n\n /**\n * Get configured store\n * @returns SkillStore instance if configured, null otherwise\n */\n private getStore(): SkillStore | null {\n if (!this.storeKey) {\n return null;\n }\n\n try {\n const storeLattice = storeLatticeManager.getStoreLattice(\n this.storeKey,\n \"skill\"\n );\n return storeLattice.store;\n } catch {\n return null;\n }\n }\n\n /**\n * Inject store into client if client supports it\n * @param client Skill client instance\n * @param store Store instance to inject\n */\n private injectStoreIntoClient(client: SkillClientType, store: SkillStore): void {\n if (!client || typeof client !== \"object\") {\n return;\n }\n\n // Try setStore method first\n if (typeof client.setStore === \"function\") {\n client.setStore(store);\n }\n\n // Also set store property directly\n client.store = store;\n }\n\n /**\n * Register a skill Lattice\n * @param key Lattice key name\n * @param config Skill configuration\n * @param client Optional skill client implementation\n */\n public async registerLattice(\n key: string,\n config: SkillConfig,\n client?: SkillClient\n ): Promise<void> {\n // Validate required fields\n if (!config.name) {\n throw new Error(\"Skill name is required\");\n }\n if (!config.description) {\n throw new Error(\"Skill description is required\");\n }\n\n // Validate name format\n validateSkillName(config.name);\n\n // Validate that key equals name (name is used for path addressing)\n if (key !== config.name) {\n throw new Error(\n `Skill key \"${key}\" must equal name \"${config.name}\" (name is used for path addressing)`\n );\n }\n\n // Get store instance\n const store = this.getStore();\n\n // Inject store into client if provided\n if (client && store) {\n this.injectStoreIntoClient(client, store);\n }\n\n // Create skill Lattice object\n const skillLattice: SkillLattice = {\n key,\n config,\n client: client ?? null,\n };\n\n // Call base class register method\n this.register(key, skillLattice);\n\n // Persist to store if configured\n if (store) {\n try {\n await store.createSkill(key, {\n name: config.name,\n description: config.description,\n license: config.license,\n compatibility: config.compatibility,\n metadata: config.metadata,\n content: config.content,\n subSkills: config.subSkills,\n });\n } catch (error) {\n // Log error but don't fail registration\n console.warn(\n `Failed to persist skill ${key} to store:`,\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n }\n\n /**\n * Get skill Lattice by key\n * @param key Lattice key name\n */\n public getSkillLattice(key: string): SkillLattice | undefined {\n return this.get(key);\n }\n\n /**\n * Get all skill Lattices from store\n * Always reads from the configured store and merges with in-memory clients\n */\n public async getAllLattices(): Promise<SkillLattice[]> {\n const store = this.getStore();\n if (!store) {\n // If no store configured, fall back to memory\n return this.getAll();\n }\n\n const skills = await store.getAllSkills();\n\n return skills.map((skill) => {\n // Check if there's an in-memory lattice with a client\n const memoryLattice = this.get(skill.id);\n const client = memoryLattice?.client || null;\n\n // Inject store into client if it exists\n if (client && store) {\n this.injectStoreIntoClient(client, store);\n }\n\n return {\n key: skill.id,\n config: {\n name: skill.name,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n content: skill.content,\n subSkills: skill.subSkills,\n },\n client,\n };\n });\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public async removeLattice(key: string): Promise<boolean> {\n const removed = this.remove(key);\n\n // Remove from store if configured\n if (removed) {\n const store = this.getStore();\n if (store) {\n try {\n await store.deleteSkill(key);\n } catch (error) {\n // Log error but don't fail removal\n console.warn(\n `Failed to remove skill ${key} from store:`,\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n }\n\n return removed;\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key name list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * Get skill configuration\n * @param key Lattice key name\n */\n public getSkillConfig(key: string): SkillConfig {\n const skillLattice = this.getSkillLattice(key);\n if (!skillLattice) {\n throw new Error(`SkillLattice ${key} not found`);\n }\n return skillLattice.config;\n }\n\n /**\n * Get skill client\n * Ensures client has store access if store is configured\n * @param key Lattice key name\n */\n public getSkillClient(key: string): SkillClient | null {\n const skillLattice = this.getSkillLattice(key);\n if (!skillLattice) {\n throw new Error(`SkillLattice ${key} not found`);\n }\n\n const client = skillLattice.client;\n if (!client) {\n return null;\n }\n\n // Ensure client has store access if store is configured\n const store = this.getStore();\n if (store && client) {\n this.injectStoreIntoClient(client, store);\n }\n\n return client;\n }\n\n /**\n * Get all skill configurations from store\n * Always reads from the configured store, not from memory\n */\n public async getAllSkillConfigs(): Promise<SkillConfig[]> {\n const lattices = await this.getAllLattices();\n return lattices.map((lattice) => lattice.config);\n }\n\n /**\n * Search skills by metadata\n * @param metadataKey Metadata key to search for\n * @param metadataValue Metadata value to match\n */\n public async searchByMetadata(\n metadataKey: string,\n metadataValue: string\n ): Promise<SkillLattice[]> {\n const lattices = await this.getAllLattices();\n return lattices.filter((lattice) => {\n return (\n lattice.config.metadata &&\n lattice.config.metadata[metadataKey] === metadataValue\n );\n });\n }\n\n /**\n * Filter skills by compatibility\n * @param compatibility Compatibility string to filter by\n */\n public async filterByCompatibility(compatibility: string): Promise<SkillLattice[]> {\n const lattices = await this.getAllLattices();\n return lattices.filter((lattice) => {\n return lattice.config.compatibility === compatibility;\n });\n }\n\n /**\n * Filter skills by license\n * @param license License string to filter by\n */\n public async filterByLicense(license: string): Promise<SkillLattice[]> {\n const lattices = await this.getAllLattices();\n return lattices.filter((lattice) => {\n return lattice.config.license === license;\n });\n }\n\n /**\n * Load skills from configured store\n * This method loads all skills from the store and registers them in memory\n */\n public async loadFromStore(): Promise<void> {\n const store = this.getStore();\n if (!store) {\n throw new Error(\"No store configured. Call configureStore() first.\");\n }\n\n const skills = await store.getAllSkills();\n for (const skill of skills) {\n // Register skill in memory without persisting back to store\n const skillLattice: SkillLattice = {\n key: skill.id,\n config: {\n name: skill.name,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n content: skill.content,\n subSkills: skill.subSkills,\n },\n client: null,\n };\n\n // Use base class register method directly to avoid double persistence\n this.register(skill.id, skillLattice);\n\n // Note: If a client is later added to this skill, it will receive store access\n // via getSkillClient() method\n }\n }\n\n /**\n * Update skill in store\n * @param key Skill key\n * @param updates Partial skill data to update\n */\n public async updateSkillInStore(\n key: string,\n updates: Partial<SkillConfig>\n ): Promise<void> {\n const store = this.getStore();\n if (!store) {\n throw new Error(\"No store configured. Call configureStore() first.\");\n }\n\n // Update in memory\n const skillLattice = this.getSkillLattice(key);\n if (!skillLattice) {\n throw new Error(`SkillLattice ${key} not found`);\n }\n\n const updatedConfig: SkillConfig = {\n ...skillLattice.config,\n ...updates,\n };\n\n skillLattice.config = updatedConfig;\n\n // Update in store\n await store.updateSkill(key, {\n name: updatedConfig.name,\n description: updatedConfig.description,\n license: updatedConfig.license,\n compatibility: updatedConfig.compatibility,\n metadata: updatedConfig.metadata,\n content: updatedConfig.content,\n subSkills: updatedConfig.subSkills,\n });\n }\n}\n\n// Export singleton instance\nexport const skillLatticeManager = SkillLatticeManager.getInstance();\n","/**\n * McpLatticeManager\n *\n * MCP Lattice Manager - Manages MCP client connections using MultiServerMCPClient\n * Follows the singleton pattern for global access\n */\n\nimport { MultiServerMCPClient } from \"@langchain/mcp-adapters\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport type { Connection } from \"@langchain/mcp-adapters\";\nimport { toolLatticeManager } from \"../tool_lattice\";\n\nexport interface McpServerInfo {\n name: string;\n connection: Connection;\n}\n\nexport interface McpLatticeInterface {\n client: MultiServerMCPClient;\n servers: Map<string, McpServerInfo>;\n}\n\nexport class McpLatticeManager extends BaseLatticeManager<McpLatticeInterface> {\n private static _instance: McpLatticeManager;\n private client: MultiServerMCPClient | null = null;\n private servers: Map<string, McpServerInfo> = new Map();\n\n public static getInstance(): McpLatticeManager {\n if (!McpLatticeManager._instance) {\n McpLatticeManager._instance = new McpLatticeManager();\n }\n return McpLatticeManager._instance;\n }\n\n protected getLatticeType(): string {\n return \"mcp\";\n }\n\n public registerServers(servers: McpServerInfo[]): void {\n for (const server of servers) {\n if (this.servers.has(server.name)) {\n console.warn(`[MCP] Server '${server.name}' already registered, skipping`);\n continue;\n }\n this.servers.set(server.name, server);\n console.log(`[MCP] Registered server: ${server.name}`);\n }\n }\n\n public addServer(name: string, connection: Connection): void {\n this.registerServers([{ name, connection }]);\n }\n\n public removeServer(name: string): boolean {\n const deleted = this.servers.delete(name);\n if (deleted) {\n console.log(`[MCP] Removed server: ${name}`);\n }\n return deleted;\n }\n\n public async connect(): Promise<void> {\n if (this.client) {\n console.warn(\"[MCP] Client already connected\");\n return;\n }\n\n const serverConfigs: Record<string, Connection> = {};\n for (const [name, info] of this.servers) {\n serverConfigs[name] = info.connection;\n }\n\n if (Object.keys(serverConfigs).length === 0) {\n console.warn(\"[MCP] No servers registered\");\n return;\n }\n\n this.client = new MultiServerMCPClient({\n mcpServers: serverConfigs,\n });\n\n console.log(`[MCP] Connecting to ${this.servers.size} servers...`);\n await this.client.initializeConnections();\n console.log(\"[MCP] All servers connected\");\n }\n\n public async disconnect(): Promise<void> {\n if (this.client) {\n await this.client.close();\n this.client = null;\n console.log(\"[MCP] Disconnected\");\n }\n }\n\n public isConnected(): boolean {\n return this.client !== null;\n }\n\n public async getAllTools(): Promise<any[]> {\n if (!this.client) {\n throw new Error(\"MCP client not connected\");\n }\n return this.client.getTools();\n }\n\n public getServerNames(): string[] {\n return Array.from(this.servers.keys());\n }\n\n public hasServer(name: string): boolean {\n return this.servers.has(name);\n }\n\n /**\n * 将 MCP 工具注册到 Tool Lattice\n * @param prefix 工具键名前缀,用于区分不同服务器的工具\n */\n public async registerToolsToToolLattice(prefix?: string): Promise<void> {\n if (!this.client) {\n throw new Error(\"MCP client not connected\");\n }\n\n const tools = await this.getAllTools();\n console.log(`[MCP] Registering ${tools.length} tools to Tool Lattice...`);\n\n for (const tool of tools) {\n const toolKey = prefix ? `${prefix}_${tool.name}` : tool.name;\n tool.name = toolKey;\n toolLatticeManager.registerExistingTool(toolKey, tool);\n console.log(`[MCP] Registered tool: ${toolKey}`);\n }\n\n console.log(`[MCP] Successfully registered ${tools.length} tools to Tool Lattice`);\n }\n}\n\nexport const mcpManager = McpLatticeManager.getInstance();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,eAAe,CAAC,IAAI,GAAG;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,E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;AAEA,YAAQ,IAAI,iCAAiC,MAAM,MAAM,wBAAwB;AAAA,EACnF;AACF;AAEO,IAAM,aAAa,kBAAkB,YAAY;;;A5F9GxD,gBAA2B;","names":["tool","z","import_zod","z","import_zod","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_langgraph","import_protocols","import_zod","import_langgraph","import_langchain","import_sandbox","path","relative","import_langchain","import_langchain","import_langchain","import_langchain","path","colonIndex","key","value","import_zod","import_langchain","z","import_zod","import_langchain","z","import_langchain","import_langgraph","import_zod","path","relative","micromatch","path","micromatch","path","relative","z3","result","path","tool","stateSchema","import_langchain","import_v3","import_langchain","import_langgraph","import_langgraph","import_protocols","resolve","import_langchain","import_messages","import_langgraph","import_micromatch","import_langgraph","import_zod","import_langchain","tool","import_protocols","ThreadStatus","resolve","import_protocols","import_protocols","import_protocols","import_protocols","pino","tool"]}
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/sql/SqlDatabaseManager.ts","../src/tool_lattice/sql/list_tables_sql.ts","../src/tool_lattice/sql/info_sql.ts","../src/tool_lattice/sql/query_checker_sql.ts","../src/tool_lattice/sql/query_sql.ts","../src/tool_lattice/code_eval/index.ts","../src/sandbox_lattice/SandboxLatticeManager.ts","../src/sandbox_lattice/utils.ts","../src/tool_lattice/code_execute_file/index.ts","../src/tool_lattice/convert_to_markdown/index.ts","../src/tool_lattice/browser/browser_navigate.ts","../src/tool_lattice/browser/browser_click.ts","../src/tool_lattice/browser/browser_get_text.ts","../src/tool_lattice/browser/browser_get_markdown.ts","../src/tool_lattice/browser/browser_evaluate.ts","../src/tool_lattice/browser/browser_screenshot.ts","../src/tool_lattice/browser/browser_scroll.ts","../src/tool_lattice/browser/browser_form_input_fill.ts","../src/tool_lattice/browser/browser_select.ts","../src/tool_lattice/browser/browser_hover.ts","../src/tool_lattice/browser/browser_go_back.ts","../src/tool_lattice/browser/browser_go_forward.ts","../src/tool_lattice/browser/browser_new_tab.ts","../src/tool_lattice/browser/browser_tab_list.ts","../src/tool_lattice/browser/browser_switch_tab.ts","../src/tool_lattice/browser/browser_close_tab.ts","../src/tool_lattice/browser/browser_close.ts","../src/tool_lattice/browser/browser_press_key.ts","../src/tool_lattice/browser/browser_read_links.ts","../src/tool_lattice/browser/browser_get_clickable_elements.ts","../src/tool_lattice/browser/browser_get_download_list.ts","../src/tool_lattice/browser/get_info.ts","../src/agent_lattice/types.ts","../src/memory_lattice/DefaultMemorySaver.ts","../src/memory_lattice/MemoryLatticeManager.ts","../src/agent_lattice/builders/state.ts","../src/agent_lattice/builders/ReActAgentGraphBuilder.ts","../src/deep_agent_new/backends/sandboxFiles.ts","../src/middlewares/codeEvalMiddleware.ts","../src/middlewares/browserMiddleware.ts","../src/middlewares/sqlMiddleware.ts","../src/middlewares/skillMiddleware.ts","../src/store_lattice/InMemoryThreadStore.ts","../src/store_lattice/InMemoryAssistantStore.ts","../src/store_lattice/FileSystemSkillStore.ts","../src/skill_lattice/skillNameValidator.ts","../src/store_lattice/StoreLatticeManager.ts","../src/tool_lattice/skill/load_skills.ts","../src/tool_lattice/skill/load_skill_content.ts","../src/deep_agent_new/middleware/fs.ts","../src/deep_agent_new/backends/utils.ts","../src/deep_agent_new/backends/state.ts","../src/agent_lattice/builders/commonMiddleware.ts","../src/deep_agent_new/agent.ts","../src/deep_agent_new/middleware/subagents.ts","../src/agent_worker/agent_worker_graph.ts","../src/constants/agent_task_types.ts","../src/services/event_bus.ts","../src/queue_lattice/QueueLatticeManager.ts","../src/queue_lattice/MemoryQueueClient.ts","../src/services/AgentManager.ts","../src/deep_agent_new/middleware/patch_tool_calls.ts","../src/deep_agent_new/backends/filesystem.ts","../src/deep_agent_new/middleware/todos.ts","../src/agent_lattice/builders/DeepAgentGraphBuilder.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","../src/schedule_lattice/ScheduleLatticeManager.ts","../src/schedule_lattice/DefaultScheduleClient.ts","../src/schedule_lattice/MemoryScheduleStorage.ts","../src/schedule_lattice/CronParser.ts","../src/embeddings_lattice/EmbeddingsLatticeManager.ts","../src/vectorstore_lattice/VectorStoreLatticeManager.ts","../src/logger_lattice/LoggerLatticeManager.ts","../src/logger_lattice/PinoLoggerClient.ts","../src/logger_lattice/ConsoleLoggerClient.ts","../src/skill_lattice/SkillLatticeManager.ts","../src/mcp_lattice/McpLatticeManager.ts"],"sourcesContent":["// Export core modules\nexport * from \"./model_lattice\";\nexport * from \"./tool_lattice\";\n// Direct export of SQL tools to ensure they are bundled\nexport * from \"./tool_lattice/sql\";\nexport * from \"./agent_lattice\";\nexport * from \"./memory_lattice\";\nexport * from \"./chunk_buffer_lattice\";\nexport * from \"./queue_lattice\";\nexport * from \"./schedule_lattice\";\nexport * from \"./store_lattice\";\nexport * from \"./embeddings_lattice\";\nexport * from \"./vectorstore_lattice\";\nexport * from \"./logger_lattice\";\nexport * from \"./skill_lattice\";\nexport * from \"./mcp_lattice\";\nexport * from \"./sandbox_lattice\";\n\n// Export service modules\nexport { eventBus, default as eventBusDefault } from \"./services/event_bus\";\nexport { AgentManager } from \"./services/AgentManager\";\n\n// Export constants\nexport * from \"./constants/agent_task_types\";\n\n// Re-export protocol interfaces - use named exports to avoid conflicts\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: config.apiKey || 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:\n config.apiKey ||\n 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:\n config.apiKey ||\n 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:\n config.apiKey ||\n 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:\n config.apiKey ||\n 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 /**\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 * 注册已有的StructuredTool到Lattice\n * @param key Lattice键名\n * @param tool 已有的StructuredTool实例\n */\n public registerExistingTool(key: string, tool: StructuredTool): void {\n // 从工具中提取配置信息\n const config: ToolConfig = {\n name: tool.name,\n description: tool.description,\n schema: tool.schema as any, // StructuredTool的schema已经是Zod兼容的\n needUserApprove: false, // MCP工具默认不需要用户批准\n };\n\n const toolLattice: ToolLattice = {\n key,\n config,\n client: tool,\n };\n\n this.register(key, toolLattice);\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 registerExistingTool = (key: string, tool: StructuredTool) =>\n toolLatticeManager.registerExistingTool(key, tool);\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 JSON.stringify(tavilyResponse.results);\n }\n);\n","export const genUICard = (title: string, type: string, data: any) => {\n return [title, \"```\" + type, JSON.stringify(data), \"```\"].join(\"\\n\");\n};\n","/**\n * SQL Database Manager\n * Singleton manager for SQL database connections\n */\n\nimport {\n DatabaseConfig,\n DatabaseType,\n ISqlDatabase,\n TableInfo,\n TableSchema,\n ColumnInfo,\n QueryResult,\n} from \"./types\";\n\n/**\n * PostgreSQL Database Implementation\n * Uses pg library for PostgreSQL connections\n */\nexport class PostgresDatabase implements ISqlDatabase {\n private config: DatabaseConfig;\n private pool: any; // pg.Pool\n private connected: boolean = false;\n\n constructor(config: DatabaseConfig) {\n this.config = config;\n }\n\n async connect(): Promise<void> {\n if (this.connected) return;\n\n try {\n // Dynamic import of pg to avoid bundling issues\n const { Pool } = await import(\"pg\");\n\n const poolConfig = this.config.connectionString\n ? { connectionString: this.config.connectionString }\n : {\n host: this.config.host || \"localhost\",\n port: this.config.port || 5432,\n database: this.config.database,\n user: this.config.user,\n password: this.config.password,\n ssl: this.config.ssl ? { rejectUnauthorized: false } : undefined,\n };\n\n this.pool = new Pool(poolConfig);\n // Test connection\n const client = await this.pool.connect();\n client.release();\n this.connected = true;\n } catch (error) {\n throw new Error(`Failed to connect to PostgreSQL: ${error}`);\n }\n }\n\n async disconnect(): Promise<void> {\n if (this.pool) {\n await this.pool.end();\n this.connected = false;\n }\n }\n\n async listTables(): Promise<TableInfo[]> {\n await this.ensureConnected();\n\n const query = `\n SELECT table_name, table_schema\n FROM information_schema.tables\n WHERE table_schema NOT IN ('pg_catalog', 'information_schema')\n AND table_type = 'BASE TABLE'\n ORDER BY table_schema, table_name;\n `;\n\n const result = await this.pool.query(query);\n return result.rows.map((row: any) => ({\n name: row.table_name,\n schema: row.table_schema,\n }));\n }\n\n async getTableInfo(tables: string[]): Promise<TableSchema[]> {\n await this.ensureConnected();\n\n const schemas: TableSchema[] = [];\n\n for (const tableName of tables) {\n // Get column information\n const columnQuery = `\n SELECT \n c.column_name,\n c.data_type,\n c.is_nullable,\n c.column_default,\n CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_primary_key,\n CASE WHEN fk.column_name IS NOT NULL THEN true ELSE false END as is_foreign_key,\n fk.foreign_table_name,\n fk.foreign_column_name\n FROM information_schema.columns c\n LEFT JOIN (\n SELECT ku.column_name, ku.table_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage ku\n ON tc.constraint_name = ku.constraint_name\n WHERE tc.constraint_type = 'PRIMARY KEY'\n ) pk ON c.column_name = pk.column_name AND c.table_name = pk.table_name\n LEFT JOIN (\n SELECT \n kcu.column_name,\n kcu.table_name,\n ccu.table_name as foreign_table_name,\n ccu.column_name as foreign_column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n JOIN information_schema.constraint_column_usage ccu\n ON tc.constraint_name = ccu.constraint_name\n WHERE tc.constraint_type = 'FOREIGN KEY'\n ) fk ON c.column_name = fk.column_name AND c.table_name = fk.table_name\n WHERE c.table_name = $1\n ORDER BY c.ordinal_position;\n `;\n\n const columnResult = await this.pool.query(columnQuery, [tableName]);\n\n const columns: ColumnInfo[] = columnResult.rows.map((row: any) => ({\n name: row.column_name,\n type: row.data_type,\n nullable: row.is_nullable === \"YES\",\n default: row.column_default,\n isPrimaryKey: row.is_primary_key,\n isForeignKey: row.is_foreign_key,\n foreignKeyRef: row.is_foreign_key\n ? `${row.foreign_table_name}.${row.foreign_column_name}`\n : undefined,\n }));\n\n // Get sample rows (limit to 3)\n let sampleRows: Record<string, unknown>[] = [];\n try {\n const sampleQuery = `SELECT * FROM \"${tableName}\" LIMIT 3`;\n const sampleResult = await this.pool.query(sampleQuery);\n sampleRows = sampleResult.rows;\n } catch {\n // Ignore errors when getting sample rows\n }\n\n schemas.push({\n tableName,\n columns,\n sampleRows,\n });\n }\n\n return schemas;\n }\n\n async executeQuery(query: string): Promise<QueryResult> {\n await this.ensureConnected();\n\n const result = await this.pool.query(query);\n return {\n rows: result.rows,\n rowCount: result.rowCount || result.rows.length,\n fields: result.fields?.map((f: any) => f.name),\n };\n }\n\n getDatabaseType(): DatabaseType {\n return \"postgres\";\n }\n\n private async ensureConnected(): Promise<void> {\n if (!this.connected) {\n await this.connect();\n }\n }\n}\n\n/**\n * SQL Database Manager\n * Manages database connections and provides a unified interface\n */\nexport class SqlDatabaseManager {\n private static instance: SqlDatabaseManager;\n private databases: Map<string, ISqlDatabase> = new Map();\n private defaultDatabaseKey: string | null = null;\n\n private constructor() {}\n\n /**\n * Get the singleton instance\n */\n static getInstance(): SqlDatabaseManager {\n if (!SqlDatabaseManager.instance) {\n SqlDatabaseManager.instance = new SqlDatabaseManager();\n }\n return SqlDatabaseManager.instance;\n }\n\n /**\n * Register a database connection\n * @param key - Unique identifier for the database\n * @param config - Database configuration\n */\n registerDatabase(key: string, config: DatabaseConfig): void {\n let database: ISqlDatabase;\n\n switch (config.type) {\n case \"postgres\":\n database = new PostgresDatabase(config);\n break;\n case \"mysql\":\n throw new Error(\"MySQL support not yet implemented\");\n case \"sqlite\":\n throw new Error(\"SQLite support not yet implemented\");\n default:\n throw new Error(`Unsupported database type: ${config.type}`);\n }\n\n this.databases.set(key, database);\n\n // Set as default if it's the first database\n if (this.defaultDatabaseKey === null) {\n this.defaultDatabaseKey = key;\n }\n }\n\n /**\n * Set the default database\n * @param key - Database key to set as default\n */\n setDefaultDatabase(key: string): void {\n if (!this.databases.has(key)) {\n throw new Error(`Database '${key}' not found`);\n }\n this.defaultDatabaseKey = key;\n }\n\n /**\n * Get a database by key\n * @param key - Database key (optional, uses default if not provided)\n */\n getDatabase(key?: string): ISqlDatabase {\n const dbKey = key || this.defaultDatabaseKey;\n if (!dbKey) {\n throw new Error(\"No database registered\");\n }\n\n const database = this.databases.get(dbKey);\n if (!database) {\n throw new Error(`Database '${dbKey}' not found`);\n }\n\n return database;\n }\n\n /**\n * Check if a database is registered\n * @param key - Database key\n */\n hasDatabase(key: string): boolean {\n return this.databases.has(key);\n }\n\n /**\n * Get all registered database keys\n */\n getDatabaseKeys(): string[] {\n return Array.from(this.databases.keys());\n }\n\n /**\n * Remove a database connection\n * @param key - Database key\n */\n async removeDatabase(key: string): Promise<void> {\n const database = this.databases.get(key);\n if (database) {\n await database.disconnect();\n this.databases.delete(key);\n\n if (this.defaultDatabaseKey === key) {\n this.defaultDatabaseKey =\n this.databases.size > 0\n ? this.databases.keys().next().value || null\n : null;\n }\n }\n }\n\n /**\n * Disconnect all databases\n */\n async disconnectAll(): Promise<void> {\n for (const database of this.databases.values()) {\n await database.disconnect();\n }\n }\n}\n\nexport function parseConnectionString(connectionString: string): Omit<DatabaseConfig, \"type\"> {\n const url = new URL(connectionString);\n const protocol = url.protocol.replace(\":\", \"\");\n\n if (protocol !== \"postgres\" && protocol !== \"postgresql\") {\n throw new Error(`Unsupported protocol: ${protocol}. Only postgresql:// is supported.`);\n }\n\n return {\n host: url.hostname || \"localhost\",\n port: parseInt(url.port || \"5432\"),\n database: url.pathname.slice(1) || url.pathname,\n user: url.username,\n password: url.password,\n ssl: url.searchParams.get(\"sslmode\") === \"require\",\n };\n}\n\nexport function parseMysqlConnectionString(connectionString: string): Omit<DatabaseConfig, \"type\"> {\n const url = new URL(connectionString);\n const protocol = url.protocol.replace(\":\", \"\");\n\n if (protocol !== \"mysql\") {\n throw new Error(`Unsupported protocol: ${protocol}. Only mysql:// is supported.`);\n }\n\n return {\n host: url.hostname || \"localhost\",\n port: parseInt(url.port || \"3306\"),\n database: url.pathname.slice(1) || url.pathname,\n user: url.username,\n password: url.password,\n ssl: url.searchParams.get(\"sslmode\") === \"require\",\n };\n}\n\nexport function parseSqliteConnectionString(connectionString: string): Omit<DatabaseConfig, \"type\"> {\n if (connectionString.startsWith(\"sqlite:\")) {\n const path = connectionString.replace(\"sqlite:\", \"\");\n return { database: path };\n }\n return { database: connectionString };\n}\n\n// Export singleton instance\nexport const sqlDatabaseManager = SqlDatabaseManager.getInstance();\n","/**\n * List Tables SQL Tool\n * Tool for listing all tables in the connected database\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\n\nconst LIST_TABLES_SQL_DESCRIPTION = `List all tables in the connected SQL database. Returns a comma-separated list of table names. Use this tool first to understand what tables are available before querying the database.`;\n\nexport interface CreateSqlToolParams {\n databaseKey?: string;\n connectionString?: string;\n}\n\nexport const createListTablesSqlTool = ({ databaseKey, connectionString }: CreateSqlToolParams) => {\n return tool(\n async (_input: Record<string, never>, exe_config: any) => {\n try {\n let dbKey: string;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n } else {\n return \"Error: Must provide databaseKey or connectionString\";\n }\n\n const database = sqlDatabaseManager.getDatabase(dbKey);\n const tables = await database.listTables();\n\n if (tables.length === 0) {\n return \"No tables found in the database.\";\n }\n\n const tableNames = tables.map((t) =>\n t.schema && t.schema !== \"public\" ? `${t.schema}.${t.name}` : t.name\n );\n\n return tableNames.join(\", \");\n } catch (error) {\n return `Error listing tables: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"list_tables_sql\",\n description: LIST_TABLES_SQL_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Info SQL Tool\n * Tool for getting schema information about specified tables\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\nimport { TableSchema } from \"./types\";\n\nconst INFO_SQL_DESCRIPTION = `Get detailed schema information for specified tables, including column names, types, constraints (primary keys, foreign keys), and sample rows. Input should be a comma-separated list of table names.`;\n\nfunction formatTableSchema(schema: TableSchema): string {\n const lines: string[] = [];\n\n lines.push(`\\nTable: ${schema.tableName}`);\n lines.push(\"-\".repeat(40));\n lines.push(\"Columns:\");\n\n for (const col of schema.columns) {\n const constraints: string[] = [];\n if (col.isPrimaryKey) constraints.push(\"PRIMARY KEY\");\n if (col.isForeignKey && col.foreignKeyRef)\n constraints.push(`FK -> ${col.foreignKeyRef}`);\n if (!col.nullable) constraints.push(\"NOT NULL\");\n\n const constraintStr =\n constraints.length > 0 ? ` [${constraints.join(\", \")}]` : \"\";\n lines.push(` - ${col.name}: ${col.type}${constraintStr}`);\n }\n\n if (schema.sampleRows && schema.sampleRows.length > 0) {\n lines.push(\"\\nSample Rows (up to 3):\");\n for (const row of schema.sampleRows) {\n const rowStr = Object.entries(row)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(\", \");\n lines.push(` ${rowStr}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport const createInfoSqlTool = ({ databaseKey, connectionString }: { databaseKey?: string; connectionString?: string }) => {\n return tool(\n async (\n {\n tables,\n }: {\n tables: string;\n },\n exe_config: any\n ) => {\n try {\n let dbKey: string;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n } else {\n return \"Error: Must provide databaseKey or connectionString\";\n }\n\n const database = sqlDatabaseManager.getDatabase(dbKey);\n\n const tableNames = tables\n .split(\",\")\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n\n if (tableNames.length === 0) {\n return \"Error: No table names provided. Please provide a comma-separated list of table names.\";\n }\n\n const schemas = await database.getTableInfo(tableNames);\n\n if (schemas.length === 0) {\n return `No schema information found for tables: ${tableNames.join(\", \")}`;\n }\n\n const output = schemas.map(formatTableSchema).join(\"\\n\");\n return output;\n } catch (error) {\n return `Error getting table info: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"info_sql\",\n description: INFO_SQL_DESCRIPTION,\n schema: z.object({\n tables: z\n .string()\n .describe(\n \"Comma-separated list of table names to get information for. Example: 'users, orders, products'\"\n ),\n }),\n }\n );\n};\n","/**\n * Query Checker SQL Tool\n * Tool for validating SQL queries before execution\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\n\nconst DANGEROUS_KEYWORDS = [\n \"DROP\",\n \"TRUNCATE\",\n \"DELETE\",\n \"ALTER\",\n \"CREATE\",\n \"GRANT\",\n \"REVOKE\",\n];\n\nfunction checkSyntax(query: string): string[] {\n const issues: string[] = [];\n const upperQuery = query.toUpperCase();\n\n let parenCount = 0;\n for (const char of query) {\n if (char === \"(\") parenCount++;\n if (char === \")\") parenCount--;\n if (parenCount < 0) {\n issues.push(\"Unbalanced parentheses: found closing ) without matching (\");\n break;\n }\n }\n if (parenCount > 0) {\n issues.push(\"Unbalanced parentheses: missing closing )\");\n }\n\n const singleQuotes = (query.match(/'/g) || []).length;\n if (singleQuotes % 2 !== 0) {\n issues.push(\"Unbalanced single quotes\");\n }\n\n if (upperQuery.includes(\"SELECT *\") && upperQuery.includes(\"JOIN\")) {\n issues.push(\n \"Warning: SELECT * with JOIN may return duplicate column names. Consider specifying columns explicitly.\"\n );\n }\n\n if (\n (upperQuery.includes(\"UPDATE \") || upperQuery.includes(\"DELETE FROM \")) &&\n !upperQuery.includes(\"WHERE \")\n ) {\n issues.push(\n \"Warning: UPDATE or DELETE without WHERE clause will affect all rows in the table.\"\n );\n }\n\n if (\n upperQuery.includes(\"GROUP BY\") &&\n !upperQuery.match(/\\b(COUNT|SUM|AVG|MAX|MIN|ARRAY_AGG|STRING_AGG)\\s*\\(/i)\n ) {\n issues.push(\n \"Warning: GROUP BY used but no aggregate functions found. Make sure all non-aggregated columns are in GROUP BY.\"\n );\n }\n\n return issues;\n}\n\nfunction checkDangerousOperations(query: string): string[] {\n const warnings: string[] = [];\n const upperQuery = query.toUpperCase();\n\n for (const keyword of DANGEROUS_KEYWORDS) {\n if (upperQuery.includes(keyword)) {\n warnings.push(\n `Warning: Query contains potentially dangerous operation: ${keyword}`\n );\n }\n }\n\n return warnings;\n}\n\nexport const createQueryCheckerSqlTool = ({ databaseKey, connectionString }: { databaseKey?: string; connectionString?: string }) => {\n return tool(\n async (\n {\n query,\n }: {\n query: string;\n },\n exe_config: any\n ) => {\n try {\n const trimmedQuery = query.trim();\n\n if (!trimmedQuery) {\n return \"Error: Empty query provided. Please provide a SQL query to check.\";\n }\n\n const results: string[] = [];\n results.push(\"SQL Query Check Results:\");\n results.push(\"=\".repeat(40));\n results.push(`\\nQuery:\\n${trimmedQuery}\\n`);\n\n const syntaxIssues = checkSyntax(trimmedQuery);\n if (syntaxIssues.length > 0) {\n results.push(\"Syntax Issues:\");\n for (const issue of syntaxIssues) {\n results.push(` - ${issue}`);\n }\n } else {\n results.push(\"Syntax: No obvious syntax issues found\");\n }\n\n const dangerWarnings = checkDangerousOperations(trimmedQuery);\n if (dangerWarnings.length > 0) {\n results.push(\"\\nSafety Warnings:\");\n for (const warning of dangerWarnings) {\n results.push(` - ${warning}`);\n }\n } else {\n results.push(\"Safety: No dangerous operations detected\");\n }\n\n try {\n let dbKey: string | undefined;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n }\n\n if (dbKey) {\n const database = sqlDatabaseManager.getDatabase(dbKey);\n const dbType = database.getDatabaseType();\n\n if (dbType === \"postgres\") {\n try {\n await database.executeQuery(`EXPLAIN ${trimmedQuery}`);\n results.push(\"Database Validation: Query is valid against database schema\");\n } catch (explainError) {\n results.push(\n `Database Validation: ${explainError instanceof Error ? explainError.message : String(explainError)}`\n );\n }\n }\n }\n } catch {\n results.push(\n \"Database Validation: Skipped (no database connection available)\"\n );\n }\n\n const hasErrors =\n syntaxIssues.some((i) => !i.startsWith(\"Warning:\")) ||\n dangerWarnings.length > 0;\n\n results.push(\"\\n\" + \"=\".repeat(40));\n if (hasErrors) {\n results.push(\n \"Overall: Query has potential issues. Review warnings before execution.\"\n );\n } else {\n results.push(\"Overall: Query appears to be safe to execute.\");\n }\n\n return results.join(\"\\n\");\n } catch (error) {\n return `Error checking query: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"query_checker_sql\",\n description:\n \"Check a SQL query for common issues before execution. This tool validates syntax, checks for dangerous operations, and provides suggestions for improvement. Use this before executing queries to ensure they are safe and correct.\",\n schema: z.object({\n query: z.string().describe(\"The SQL query to check and validate.\"),\n }),\n }\n );\n};\n","/**\n * Query SQL Tool\n * Tool for executing SQL queries against the database\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { sqlDatabaseManager, parseConnectionString } from \"./SqlDatabaseManager\";\n\nconst QUERY_SQL_DESCRIPTION = `Execute a SQL query against the database and return the results. Input should be a valid SQL query. Use this tool to retrieve data from the database. For complex queries, first use list_tables_sql and info_sql to understand the database schema.`;\n\nfunction formatQueryResult(\n rows: Record<string, unknown>[],\n fields?: string[]\n): string {\n if (rows.length === 0) {\n return \"Query executed successfully. No rows returned.\";\n }\n\n const lines: string[] = [];\n\n const columns = fields || Object.keys(rows[0]);\n\n lines.push(columns.join(\" | \"));\n lines.push(\"-\".repeat(columns.join(\" | \").length));\n\n const maxRows = 50;\n const displayRows = rows.slice(0, maxRows);\n\n for (const row of displayRows) {\n const values = columns.map((col) => {\n const val = row[col];\n if (val === null) return \"NULL\";\n if (typeof val === \"object\") return JSON.stringify(val);\n return String(val);\n });\n lines.push(values.join(\" | \"));\n }\n\n if (rows.length > maxRows) {\n lines.push(`\\n... (${rows.length - maxRows} more rows not shown)`);\n }\n\n lines.push(`\\nTotal rows: ${rows.length}`);\n\n return lines.join(\"\\n\");\n}\n\nexport const createQuerySqlTool = ({ databaseKey, connectionString }: { databaseKey?: string; connectionString?: string }) => {\n return tool(\n async (\n {\n query,\n }: {\n query: string;\n },\n exe_config: any\n ) => {\n try {\n let dbKey: string;\n\n if (databaseKey) {\n dbKey = databaseKey;\n } else if (connectionString) {\n dbKey = connectionString;\n if (!sqlDatabaseManager.hasDatabase(dbKey)) {\n const config = parseConnectionString(connectionString);\n sqlDatabaseManager.registerDatabase(dbKey, { ...config, type: \"postgres\" });\n }\n } else {\n return \"Error: Must provide databaseKey or connectionString\";\n }\n\n const trimmedQuery = query.trim();\n if (!trimmedQuery) {\n return \"Error: Empty query provided. Please provide a valid SQL query.\";\n }\n\n const database = sqlDatabaseManager.getDatabase(dbKey);\n const result = await database.executeQuery(trimmedQuery);\n\n return formatQueryResult(result.rows, result.fields);\n } catch (error) {\n return `Error executing query: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n },\n {\n name: \"query_sql\",\n description: QUERY_SQL_DESCRIPTION,\n schema: z.object({\n query: z\n .string()\n .describe(\n \"The SQL query to execute. Should be a valid SELECT, INSERT, UPDATE, or DELETE statement.\"\n ),\n }),\n }\n );\n};\n","/**\n * Code Execution Tool (code_eval)\n *\n * Executes code in the sandbox for supported languages (Python, JavaScript).\n * Requires a sandbox to be connected (e.g. via params.connectedSandbox when\n * building the agent). Uses the sandbox's code.executeCode API to run the\n * code in isolation.\n */\n\nimport z from \"zod\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { tool } from \"langchain\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst CODE_EVAL_DESCRIPTION = `Execute code in Python or JavaScript runtime.\n\nArgs:\n code: Code to execute\n language: Programming language ('python', 'javascript')\n\nReturns:\n Dict containing output, errors, and execution details`;\n\n\n\n\n\nexport const createCodeEvalTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(async (\n input: { language: \"python\" | \"javascript\"; code: string; timeout_sec?: number },\n exe_config: any\n ) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel })\n\n const result = await sandbox.code.executeCode({\n language: input.language,\n code: input.code,\n timeout: 300,\n });\n\n if (!result.ok) {\n const err = result.error as { content?: { message?: string, errors?: string[] } };\n return `Error executing ${input.language} code: ${err?.content?.message + (err?.content?.errors ? `\\n${err?.content?.errors.join(\"\\n\")}` : \"\")}`;\n }\n\n const data = result.body?.data;\n if (!data) {\n return \"Error: No response data from sandbox code execution.\";\n }\n\n const { stdout = \"\", stderr = \"\", exit_code, traceback } = data;\n const parts: string[] = [];\n\n if (stdout) {\n parts.push(`stdout:\\n${stdout}`);\n }\n if (stderr) {\n parts.push(`stderr:\\n${stderr}`);\n }\n if (traceback && traceback.length > 0) {\n parts.push(`traceback:\\n${traceback.join(\"\\n\")}`);\n }\n parts.push(`exit_code: ${exit_code ?? \"—\"}`);\n\n return parts.length > 0 ? parts.join(\"\\n\\n\") : `exit_code: ${exit_code ?? 0}`;\n } catch (e) {\n return `Error: ${e instanceof Error ? e.message : String(e)}`;\n }\n }, {\n name: \"execute_code\",\n description: CODE_EVAL_DESCRIPTION,\n schema: z.object({\n language: z\n .enum([\"python\", \"javascript\"])\n .describe(\"Programming language: 'python' or 'javascript'\"),\n code: z.string().describe(\"Code to execute\"),\n\n }),\n },);\n\n}","/**\n * SandboxLatticeManager\n *\n * Sandbox Lattice manager for registering and managing sandbox services\n * Supports creating, deleting, and managing sandbox instances\n */\n\nimport { SandboxClient } from \"@agent-infra/sandbox\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport { RunSandboxConfig, SandboxManagerProtocol } from \"./SandboxManagerProtocol\";\nimport { normalizeSandboxName } from \"./utils\";\n\n\n\n/**\n * Default implementation of SandboxManagerProtocol\n * Manages sandboxes using SandboxClient instances stored in memory\n */\nclass DefaultSandboxManager implements SandboxManagerProtocol {\n private sandboxes: Map<string, SandboxClient> = new Map();\n /**\n * Track in-flight sandbox creation promises by normalized sandbox name.\n * This ensures that concurrent calls with the same name share the same Promise\n * and we do not trigger multiple creations for the same sandbox.\n */\n private creatingSandboxes: Map<string, Promise<SandboxClient>> = new Map();\n private baseURL: string;\n\n constructor(baseURL: string = \"http://localhost:8080\") {\n this.baseURL = baseURL;\n }\n\n getBaseURL(): string {\n return this.baseURL;\n }\n\n async createSandbox(sandboxName: string): Promise<SandboxClient> {\n\n\n if (sandboxName === \"global\") {\n const client = new SandboxClient({ baseUrl: `${this.baseURL}/sandbox/global`, environment: \"\" });\n this.sandboxes.set(\"global\", client);\n return client;\n }\n\n\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n // If sandbox client already exists, return it directly.\n const existingClient = this.sandboxes.get(normalizedName);\n if (existingClient) {\n return existingClient;\n }\n\n // If a creation is already in progress for this sandbox, return the same Promise.\n const inFlight = this.creatingSandboxes.get(normalizedName);\n if (inFlight) {\n return inFlight;\n }\n\n // Start a new creation Promise and store it so concurrent callers share it.\n const creationPromise = (async (): Promise<SandboxClient> => {\n const response = await fetch(`${this.baseURL}/api/v1/sandbox`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n name: normalizedName,\n image: \"enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:latest\"\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to create sandbox: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // Create a new SandboxClient for the sandbox\n // The baseURL should point to the specific sandbox endpoint\n const sandboxURL = `${this.baseURL}/sandbox/${normalizedName}`;\n const client = new SandboxClient({ baseUrl: sandboxURL, environment: \"\" });\n this.sandboxes.set(normalizedName, client);\n return client;\n })();\n\n // Ensure we clean up the in-flight map when the Promise settles.\n this.creatingSandboxes.set(normalizedName, creationPromise);\n creationPromise\n .catch(() => {\n // On failure, remove the in-flight entry so future calls can retry.\n this.creatingSandboxes.delete(normalizedName);\n })\n .then(() => {\n // On success, also remove the in-flight entry; the client is now in sandboxes map.\n this.creatingSandboxes.delete(normalizedName);\n });\n\n return creationPromise;\n }\n\n async deleteSandbox(sandboxName: string): Promise<void> {\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n if (!this.sandboxes.has(normalizedName)) {\n throw new Error(`Sandbox ${sandboxName} (normalized: ${normalizedName}) not found`);\n }\n const response = await fetch(`${this.baseURL}/api/v1/sandbox/${normalizedName}`, {\n method: \"DELETE\",\n });\n if (!response.ok) {\n throw new Error(`Failed to delete sandbox: ${response.statusText}`);\n }\n this.sandboxes.delete(normalizedName);\n }\n\n async getSandbox(sandboxName: string): Promise<SandboxClient> {\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n const client = this.sandboxes.get(normalizedName);\n if (!client) {\n throw new Error(`Sandbox ${sandboxName} (normalized: ${normalizedName}) not found`);\n }\n return client;\n }\n\n async listSandboxes(): Promise<SandboxClient[]> {\n return Array.from(this.sandboxes.values());\n }\n\n async getSandboxStatus(sandboxName: string): Promise<string> {\n // Normalize sandbox name to be RFC 1123 compliant\n const normalizedName = normalizeSandboxName(sandboxName);\n\n if (!this.sandboxes.has(normalizedName)) {\n throw new Error(`Sandbox ${sandboxName} (normalized: ${normalizedName}) not found`);\n }\n // Try to get context to check if sandbox is active\n try {\n const client = this.sandboxes.get(normalizedName)!;\n const context = await client.sandbox.getContext();\n return context.ok ? \"active\" : \"inactive\";\n } catch {\n return \"unknown\";\n }\n }\n async getSandboxFromConfig(config: RunSandboxConfig): Promise<SandboxClient> {\n if (config.isolatedLevel === \"agent\") {\n return this.createSandbox(config.assistant_id);\n } else if (config.isolatedLevel === \"thread\") {\n return this.createSandbox(config.thread_id);\n } else {\n return this.createSandbox(\"global\");\n }\n }\n}\n\n/**\n * SandboxLatticeManager - Singleton sandbox Lattice manager\n * Responsible for registering and managing various sandbox service Lattices\n */\nexport class SandboxLatticeManager extends BaseLatticeManager<SandboxManagerProtocol> {\n private static _instance: SandboxLatticeManager;\n\n /**\n * Get SandboxLatticeManager singleton instance\n */\n public static getInstance(): SandboxLatticeManager {\n if (!SandboxLatticeManager._instance) {\n SandboxLatticeManager._instance = new SandboxLatticeManager();\n }\n return SandboxLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"sandbox_manager\";\n }\n\n /**\n * Register sandbox Lattice\n * @param key Lattice key name\n * @param manager Optional sandbox manager. If not provided, will create a default one.\n * @param baseURL Base URL for sandbox service (used when creating default manager)\n */\n public registerLattice(\n key: string,\n config: { manager?: SandboxManagerProtocol, baseURL?: string }\n ): void {\n const { manager, baseURL } = config;\n // Use provided manager or create default one\n const sandboxManager: SandboxManagerProtocol =\n manager || new DefaultSandboxManager(baseURL);\n\n\n // Call base class register method\n this.register(key, sandboxManager);\n }\n\n /**\n * Get SandboxLattice\n * @param key Lattice key name\n */\n public getSandboxLattice(key: string): SandboxManagerProtocol {\n const sandboxLattice = this.get(key);\n if (!sandboxLattice) {\n throw new Error(`SandboxLattice ${key} not found`);\n }\n return sandboxLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): SandboxManagerProtocol[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const sandboxLatticeManager =\n SandboxLatticeManager.getInstance();\n\nexport const getSandBoxManager = (key: string = \"default\") => {\n if (!sandboxLatticeManager.hasLattice(key)) {\n throw new Error(`Sandbox ${key} not configured. Ensure the sandbox manager is registered and the agent is built with connectedSandbox.`);\n }\n const sandboxManager = sandboxLatticeManager.getSandboxLattice(key);\n return sandboxManager;\n}","/**\n * Sandbox name normalization utility\n * \n * Normalizes sandbox names to comply with RFC 1123 subdomain naming requirements:\n * - Only lowercase alphanumeric characters, '-' or '.'\n * - Must start and end with an alphanumeric character\n * - No underscores or other special characters\n */\n\n/**\n * Normalize a sandbox name to be RFC 1123 compliant\n * \n * @param name - The sandbox name to normalize\n * @returns Normalized sandbox name that complies with RFC 1123 subdomain rules\n * \n * @example\n * normalizeSandboxName(\"sandbox_agent\") // returns \"sandbox-agent\"\n * normalizeSandboxName(\"My-Sandbox\") // returns \"my-sandbox\"\n * normalizeSandboxName(\"test.sandbox\") // returns \"test.sandbox\"\n * normalizeSandboxName(\"_invalid_\") // returns \"invalid\"\n */\nexport function normalizeSandboxName(name: string): string {\n if (!name || typeof name !== \"string\") {\n throw new Error(\"Sandbox name must be a non-empty string\");\n }\n\n // Convert to lowercase\n let normalized = name.toLowerCase();\n\n // Replace underscores with hyphens\n normalized = normalized.replace(/_/g, \"-\");\n\n // Remove any characters that are not alphanumeric, hyphen, or dot\n normalized = normalized.replace(/[^a-z0-9.-]/g, \"\");\n\n // Remove leading/trailing dots and hyphens (must start/end with alphanumeric)\n normalized = normalized.replace(/^[.-]+|[.-]+$/g, \"\");\n\n // Replace consecutive dots or hyphens with a single hyphen\n normalized = normalized.replace(/[.-]{2,}/g, \"-\");\n\n // Ensure it doesn't start or end with a dot or hyphen after cleanup\n normalized = normalized.replace(/^[.-]+|[.-]+$/g, \"\");\n\n // If the result is empty, throw an error\n if (!normalized) {\n throw new Error(\n `Sandbox name \"${name}\" cannot be normalized to a valid RFC 1123 subdomain name`\n );\n }\n\n // Ensure it starts and ends with alphanumeric\n // If it doesn't start with alphanumeric, prepend 'sandbox-'\n if (!/^[a-z0-9]/.test(normalized)) {\n normalized = `sandbox-${normalized}`;\n }\n\n // If it doesn't end with alphanumeric, append '-0'\n if (!/[a-z0-9]$/.test(normalized)) {\n normalized = `${normalized}-0`;\n }\n\n // Final validation: ensure it matches RFC 1123 pattern\n // Pattern: [a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\n const rfc1123Pattern = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;\n \n if (!rfc1123Pattern.test(normalized)) {\n // If still invalid, create a safe fallback\n normalized = normalized\n .replace(/[^a-z0-9-]/g, \"-\") // Replace any remaining invalid chars with hyphen\n .replace(/^-+|-+$/g, \"\") // Remove leading/trailing hyphens\n .replace(/-{2,}/g, \"-\"); // Replace consecutive hyphens\n \n // Ensure it starts and ends with alphanumeric\n if (!/^[a-z0-9]/.test(normalized)) {\n normalized = `sandbox-${normalized}`;\n }\n if (!/[a-z0-9]$/.test(normalized)) {\n normalized = `${normalized}0`;\n }\n }\n\n return normalized;\n}\n\n/**\n * Validate if a sandbox name is RFC 1123 compliant\n * \n * @param name - The sandbox name to validate\n * @returns true if the name is valid, false otherwise\n */\nexport function isValidSandboxName(name: string): boolean {\n if (!name || typeof name !== \"string\") {\n return false;\n }\n\n const rfc1123Pattern = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;\n return rfc1123Pattern.test(name.toLowerCase());\n}\n","/**\n * Code File Execution Tool (code_execute_file)\n *\n * Executes a code file from the sandbox filesystem. Only supports Python (.py) and JavaScript (.js, .mjs) files.\n * Other file types are not supported. The tool reads the file content from the sandbox and executes it\n * using the sandbox's code execution API. Language is automatically inferred from file extension.\n */\n\nimport z from \"zod\";\nimport { tool, type StructuredTool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\nimport * as path from \"path\";\n\nconst CODE_EXECUTE_FILE_DESCRIPTION = `Execute a code file from the sandbox filesystem. Only supports Python (.py) and JavaScript (.js, .mjs) files. Other file types are not supported. The tool reads the file content and executes it in an isolated sandbox environment. Language is automatically inferred from the file extension. Output is returned via stdout; errors appear in stderr and traceback.`;\n\nfunction inferLanguageFromPath(filePath: string): \"python\" | \"javascript\" | null {\n const ext = path.extname(filePath).toLowerCase();\n if (ext === \".py\") {\n return \"python\";\n } else if (ext === \".js\" || ext === \".mjs\") {\n return \"javascript\";\n }\n return null;\n}\n\nexport const createCodeExecuteFileTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }): StructuredTool => {\n return tool(\n async (input: { file_path: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const context = await sandbox.sandbox.getContext();\n if (!context.ok) {\n return `Error: ${context.error}`;\n }\n const homeDir = context.body?.home_dir;\n const resolvedFilePath = path.join(homeDir, input.file_path);\n\n const language = inferLanguageFromPath(input.file_path);\n if (!language) {\n return `Error: Unsupported file type. This tool only supports Python (.py) and JavaScript (.js, .mjs) files.`;\n }\n\n const readResult = await sandbox.file.readFile({\n file: resolvedFilePath,\n });\n\n if (!readResult.ok) {\n const err = readResult.error as { content?: { message?: string } };\n return `Error reading file '${input.file_path}': ${err?.content?.message ?? JSON.stringify(readResult.error)}`;\n }\n\n const fileContent = readResult.body?.data?.content;\n if (fileContent === undefined || fileContent === null) {\n return `Error: File '${input.file_path}' is empty or could not be read.`;\n }\n\n const result = await sandbox.code.executeCode({\n language: language,\n code: fileContent,\n timeout: 300,\n });\n\n if (!result.ok) {\n const err = result.error as { content?: { message?: string } };\n return `Error executing ${language} file '${input.file_path}': ${err?.content?.message ?? JSON.stringify(result.error)}`;\n }\n\n const data = result.body?.data;\n if (!data) {\n return \"Error: No response data from sandbox code execution.\";\n }\n\n const { stdout = \"\", stderr = \"\", exit_code, traceback } = data;\n const parts: string[] = [];\n\n if (stdout) {\n parts.push(`stdout:\\n${stdout}`);\n }\n if (stderr) {\n parts.push(`stderr:\\n${stderr}`);\n }\n if (traceback && traceback.length > 0) {\n parts.push(`traceback:\\n${traceback.join(\"\\n\")}`);\n }\n parts.push(`exit_code: ${exit_code ?? \"—\"}`);\n\n return parts.length > 0 ? parts.join(\"\\n\\n\") : `exit_code: ${exit_code ?? 0}`;\n } catch (e) {\n return `Error: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"execute_code_file\",\n description: CODE_EXECUTE_FILE_DESCRIPTION,\n schema: z.object({\n file_path: z.string().describe(\"Path to the code file to execute (absolute path in sandbox filesystem). Only supports .py (Python) and .js/.mjs (JavaScript) files.\"),\n }),\n }\n );\n};\n","/**\n * Convert to Markdown Tool (convert_to_markdown)\n *\n * Convert a resource described by an http:, https:, file: or data: URI to markdown.\n * This tool fetches or reads content from various URI schemes and converts it to markdown format.\n */\n\nimport z from \"zod\";\nimport { registerToolLattice } from \"../ToolLatticeManager\";\nimport { promises as fs } from \"fs\";\nimport path from \"path\";\nimport { getSandBoxManager } from \"@sandbox_lattice/SandboxLatticeManager\";\n\nconst CONVERT_TO_MARKDOWN_DESCRIPTION = `Convert a resource described by an http:, https:, file: or data: URI to markdown.\n\nArgs:\n uri (str): The URI to convert. Supported schemes:\n - http:// or https://: Fetch content from URL\n - file://: Read content from local file\n - data:: Decode data URI content\n\nReturns:\n str: The content converted to markdown format.`;\n\nregisterToolLattice(\n \"convert_to_markdown\",\n {\n name: \"convert_to_markdown\",\n description: CONVERT_TO_MARKDOWN_DESCRIPTION,\n needUserApprove: false,\n schema: z.object({\n uri: z.string().describe(\"The URI to convert.\"),\n }),\n },\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig(runConfig);\n sandbox\n const result = await sandbox.util.convertToMarkdown({\n uri: input.uri,\n });\n if (!result.ok) {\n return `Error converting to markdown: ${result.error}`;\n }\n return result.body.data;\n } catch (e) {\n return `Error converting to markdown: ${e instanceof Error ? e.message : String(e)}`;\n }\n }\n);","/**\n * Browser Navigate Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_NAVIGATE_DESCRIPTION = `Navigate to a URL.\n\nArgs:\n url (str): The URL to navigate to.\n`;\n\nexport const createBrowserNavigateTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { url: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_navigate\", {\n url: input.url,\n });\n if (!result.ok) {\n return `Error navigating to URL: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Navigated to URL\";\n } catch (e) {\n return `Error navigating to URL: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_navigate\",\n description: BROWSER_NAVIGATE_DESCRIPTION,\n schema: z.object({\n url: z.string().describe(\"The URL to navigate to.\"),\n }),\n }\n );\n};\n","/**\n * Browser Click Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_CLICK_DESCRIPTION = `Click an element on the page, before using the tool, use \\`browser_get_clickable_elements\\` to get the index of the element, but not call \\`browser_get_clickable_elements\\` multiple times.\n\nArgs:\n index (int): Index of the element to click\n`;\n\nexport const createBrowserClickTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { index: number }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_click\", {\n index: input.index,\n });\n if (!result.ok) {\n return `Error clicking element: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Element clicked successfully\";\n } catch (e) {\n return `Error clicking element: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_click\",\n description: BROWSER_CLICK_DESCRIPTION,\n schema: z.object({\n index: z.number().describe(\"Index of the element to click\"),\n }),\n }\n );\n};\n","/**\n * Browser Get Text Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_TEXT_DESCRIPTION = `Get the text content of the current page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetTextTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_text\", {});\n if (!result.ok) {\n return `Error getting text content: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Text content retrieved\";\n } catch (e) {\n return `Error getting text content: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_text\",\n description: BROWSER_GET_TEXT_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Markdown Tool\n */\n\nimport z from \"zod\";\nimport { tool, type StructuredTool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_MARKDOWN_DESCRIPTION = `Get the markdown content of the current page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetMarkdownTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }): StructuredTool => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_markdown\", {});\n if (!result.ok) {\n return `Error getting markdown: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content ?? \"Markdown content retrieved\";\n } catch (e) {\n return `Error getting markdown: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_markdown\",\n description: BROWSER_GET_MARKDOWN_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Evaluate Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_EVALUATE_DESCRIPTION = `Execute JavaScript in the browser console.\n\nArgs:\n script (str): JavaScript code to execute, () => { /* code */ }\n`;\n\nexport const createBrowserEvaluateTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { script: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_evaluate\", {\n script: input.script,\n });\n if (!result.ok) {\n return `Error executing JavaScript: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"JavaScript executed successfully\";\n } catch (e) {\n return `Error executing JavaScript: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_evaluate\",\n description: BROWSER_EVALUATE_DESCRIPTION,\n schema: z.object({\n script: z.string().describe(\"JavaScript code to execute, () => { /* code */ }\"),\n }),\n }\n );\n};\n","/**\n * Browser Screenshot Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SCREENSHOT_DESCRIPTION = `Take a screenshot of the current page or a specific element.\n\nArgs:\n name (str): Name for the screenshot\n selector (str): CSS selector for element to screenshot\n index (int): index of the element to screenshot\n width (int): Width in pixels (default: viewport width)\n height (int): Height in pixels (default: viewport height)\n fullPage (bool): Full page screenshot (default: false)\n highlight (bool): Highlight the element\n`;\n\nexport const createBrowserScreenshotTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: {\n name?: string;\n selector?: string;\n index?: number;\n width?: number;\n height?: number;\n fullPage?: boolean;\n highlight?: boolean;\n }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_screenshot\", {\n name: input.name,\n selector: input.selector,\n index: input.index,\n width: input.width,\n height: input.height,\n fullPage: input.fullPage,\n highlight: input.highlight,\n });\n if (!result.ok) {\n return `Error taking screenshot: ${JSON.stringify(result.error.content)}`;\n }\n const lines = [];\n for (const item of result.body?.data?.content ?? []) {\n if (item.type === \"image\") {\n const base64Data = item.data;\n const buffer = Buffer.from(base64Data, \"base64\");\n const screenshotPath = `/home/gem/screenshots/screenshot_${input.name}.png`;\n const uploadResult = await sandbox.file.uploadFile({\n file: buffer,\n path: screenshotPath,\n });\n if (uploadResult.ok) {\n const screenshot_md = [\n \"\",\n \"Screenshot saved!\",\n \"```attachments\",\n JSON.stringify([{ id: screenshotPath, name: `screenshot_${input.name}.png` }]),\n \"```\",\n ].join(\"\\n\");\n lines.push(screenshot_md);\n } else {\n lines.push(`Failed to save screenshot: ${JSON.stringify(uploadResult.error)}`);\n }\n } else {\n lines.push(`${item.text}`);\n }\n }\n return lines.length > 0 ? lines.join(\"\\n\") : \"No Content\";\n } catch (e) {\n return `Error taking screenshot: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_screenshot\",\n description: BROWSER_SCREENSHOT_DESCRIPTION,\n schema: z.object({\n name: z.string().optional().describe(\"Name for the screenshot\"),\n selector: z.string().optional().describe(\"CSS selector for element to screenshot\"),\n index: z.number().optional().describe(\"index of the element to screenshot\"),\n width: z.number().optional().describe(\"Width in pixels (default: viewport width)\"),\n height: z.number().optional().describe(\"Height in pixels (default: viewport height)\"),\n fullPage: z.boolean().optional().describe(\"Full page screenshot (default: false)\"),\n highlight: z.boolean().default(false).describe(\"Highlight the element\"),\n }),\n }\n );\n};\n","/**\n * Browser Scroll Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SCROLL_DESCRIPTION = `Scroll the page.\n\nArgs:\n amount (int): Pixels to scroll (positive for down, negative for up), if the amount is not provided, scroll to the bottom of the page\n`;\n\nexport const createBrowserScrollTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { amount?: number }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_scroll\", {\n amount: input.amount,\n });\n if (!result.ok) {\n return `Error scrolling page: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Page scrolled successfully\";\n } catch (e) {\n return `Error scrolling page: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_scroll\",\n description: BROWSER_SCROLL_DESCRIPTION,\n schema: z.object({\n amount: z.number().optional().describe(\"Pixels to scroll (positive for down, negative for up)\"),\n }),\n }\n );\n};\n","/**\n * Browser Form Input Fill Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_FORM_INPUT_FILL_DESCRIPTION = `Fill out an input field, before using the tool, Either 'index' or 'selector' must be provided.\n\nArgs:\n selector (str): CSS selector for input field, priority use index, if index is not provided, use selector\n index (int): Index of the element to fill\n value (str): Value to fill\n clear (bool): Whether to clear existing text before filling\n`;\n\nexport const createBrowserFormInputFillTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: {\n selector?: string;\n index?: number;\n value: string;\n clear?: boolean;\n }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_form_input_fill\", {\n selector: input.selector,\n index: input.index,\n value: input.value,\n clear: input.clear,\n });\n if (!result.ok) {\n return `Error filling input field: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Input field filled successfully\";\n } catch (e) {\n return `Error filling input field: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_form_input_fill\",\n description: BROWSER_FORM_INPUT_FILL_DESCRIPTION,\n schema: z.object({\n selector: z.string().optional().describe(\"CSS selector for input field\"),\n index: z.number().optional().describe(\"Index of the element to fill\"),\n value: z.string().describe(\"Value to fill\"),\n clear: z.boolean().default(false).describe(\"Whether to clear existing text before filling\"),\n }),\n }\n );\n};\n","/**\n * Browser Select Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SELECT_DESCRIPTION = `Select an element on the page with index, Either 'index' or 'selector' must be provided.\n\nArgs:\n index (int): Index of the element to select\n selector (str): CSS selector for element to select\n value (str): Value to select\n`;\n\nexport const createBrowserSelectTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: {\n index?: number;\n selector?: string;\n value: string;\n }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_select\", {\n index: input.index,\n selector: input.selector,\n value: input.value,\n });\n if (!result.ok) {\n return `Error selecting element: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Element selected successfully\";\n } catch (e) {\n return `Error selecting element: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_select\",\n description: BROWSER_SELECT_DESCRIPTION,\n schema: z.object({\n index: z.number().optional().describe(\"Index of the element to select\"),\n selector: z.string().optional().describe(\"CSS selector for element to select\"),\n value: z.string().describe(\"Value to select\"),\n }),\n }\n );\n};\n","/**\n * Browser Hover Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_HOVER_DESCRIPTION = `Hover an element on the page, Either 'index' or 'selector' must be provided.\n\nArgs:\n index (int): Index of the element to hover\n selector (str): CSS selector for element to hover\n`;\n\nexport const createBrowserHoverTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { index?: number; selector?: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_hover\", {\n index: input.index,\n selector: input.selector,\n });\n if (!result.ok) {\n return `Error hovering element: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Element hovered successfully\";\n } catch (e) {\n return `Error hovering element: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_hover\",\n description: BROWSER_HOVER_DESCRIPTION,\n schema: z.object({\n index: z.number().optional().describe(\"Index of the element to hover\"),\n selector: z.string().optional().describe(\"CSS selector for element to hover\"),\n }),\n }\n );\n};\n","/**\n * Browser Go Back Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GO_BACK_DESCRIPTION = `Go back to the previous page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGoBackTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_go_back\", {});\n if (!result.ok) {\n return `Error going back: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Went back to previous page\";\n } catch (e) {\n return `Error going back: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_go_back\",\n description: BROWSER_GO_BACK_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Go Forward Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GO_FORWARD_DESCRIPTION = `Go forward to the next page.\n\nArgs:\n None\n`;\n\nexport const createBrowserGoForwardTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_go_forward\", {});\n if (!result.ok) {\n return `Error going forward: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Went forward to next page\";\n } catch (e) {\n return `Error going forward: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_go_forward\",\n description: BROWSER_GO_FORWARD_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser New Tab Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_NEW_TAB_DESCRIPTION = `Open a new tab.\n\nArgs:\n url (str): URL to open in the new tab\n`;\n\nexport const createBrowserNewTabTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { url: string }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_new_tab\", {\n url: input.url,\n });\n if (!result.ok) {\n return `Error opening new tab: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"New tab opened successfully\";\n } catch (e) {\n return `Error opening new tab: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_new_tab\",\n description: BROWSER_NEW_TAB_DESCRIPTION,\n schema: z.object({\n url: z.string().describe(\"URL to open in the new tab\"),\n }),\n }\n );\n};\n","/**\n * Browser Tab List Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_TAB_LIST_DESCRIPTION = `Get the list of tabs.\n\nArgs:\n None\n`;\n\nexport const createBrowserTabListTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_tab_list\", {});\n if (!result.ok) {\n return `Error getting tab list: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Tab list retrieved successfully\";\n } catch (e) {\n return `Error getting tab list: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_tab_list\",\n description: BROWSER_TAB_LIST_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Switch Tab Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_SWITCH_TAB_DESCRIPTION = `Switch to a specific tab.\n\nArgs:\n index (int): Tab index to switch to\n`;\n\nexport const createBrowserSwitchTabTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { index: number }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_switch_tab\", {\n index: input.index,\n });\n if (!result.ok) {\n return `Error switching tab: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Tab switched successfully\";\n } catch (e) {\n return `Error switching tab: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_switch_tab\",\n description: BROWSER_SWITCH_TAB_DESCRIPTION,\n schema: z.object({\n index: z.number().describe(\"Tab index to switch to\"),\n }),\n }\n );\n};\n","/**\n * Browser Close Tab Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_CLOSE_TAB_DESCRIPTION = `Close the current tab.\n\nArgs:\n None\n`;\n\nexport const createBrowserCloseTabTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_close_tab\", {});\n if (!result.ok) {\n return `Error closing tab: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Current tab closed successfully\";\n } catch (e) {\n return `Error closing tab: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_close_tab\",\n description: BROWSER_CLOSE_TAB_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Close Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_CLOSE_DESCRIPTION = `Close the browser when the task is done and the browser is not needed anymore.\n\nArgs:\n None\n`;\n\nexport const createBrowserCloseTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_close\", {});\n if (!result.ok) {\n return `Error closing browser: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Browser closed successfully\";\n } catch (e) {\n return `Error closing browser: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_close\",\n description: BROWSER_CLOSE_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Press Key Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_PRESS_KEY_DESCRIPTION = `Press a key on the keyboard.\n\nArgs:\n key (str): Name of the key to press or a character to generate, such as Enter, Tab, Escape, Backspace, Delete, Insert, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, PageUp, PageDown, Home, End, ShiftLeft, ShiftRight, ControlLeft, ControlRight, AltLeft, AltRight, MetaLeft, MetaRight, CapsLock, PrintScreen, ScrollLock, Pause, ContextMenu\n`;\n\nexport const createBrowserPressKeyTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: { key: \"Enter\" | \"Tab\" | \"Escape\" | \"Backspace\" | \"Delete\" | \"Insert\" | \"F1\" | \"F2\" | \"F3\" | \"F4\" | \"F5\" | \"F6\" | \"F7\" | \"F8\" | \"F9\" | \"F10\" | \"F11\" | \"F12\" | \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"ArrowDown\" | \"PageUp\" | \"PageDown\" | \"Home\" | \"End\" | \"ShiftLeft\" | \"ShiftRight\" | \"ControlLeft\" | \"ControlRight\" | \"AltLeft\" | \"AltRight\" | \"MetaLeft\" | \"MetaRight\" | \"CapsLock\" | \"PrintScreen\" | \"ScrollLock\" | \"Pause\" | \"ContextMenu\" }, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_press_key\", {\n key: input.key,\n });\n if (!result.ok) {\n return `Error pressing key: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? `Key ${input.key} pressed successfully`;\n } catch (e) {\n return `Error pressing key: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_press_key\",\n description: BROWSER_PRESS_KEY_DESCRIPTION,\n schema: z.object({\n key: z.enum([\n \"Enter\", \"Tab\", \"Escape\", \"Backspace\", \"Delete\", \"Insert\",\n \"F1\", \"F2\", \"F3\", \"F4\", \"F5\", \"F6\", \"F7\", \"F8\", \"F9\", \"F10\", \"F11\", \"F12\",\n \"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\",\n \"PageUp\", \"PageDown\", \"Home\", \"End\",\n \"ShiftLeft\", \"ShiftRight\", \"ControlLeft\", \"ControlRight\",\n \"AltLeft\", \"AltRight\", \"MetaLeft\", \"MetaRight\",\n \"CapsLock\", \"PrintScreen\", \"ScrollLock\", \"Pause\", \"ContextMenu\"\n ]).describe(\"Name of the key to press\"),\n }),\n }\n );\n};\n","/**\n * Browser Read Links Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_READ_LINKS_DESCRIPTION = `Get all links on the current page.\n\nArgs:\n None\n`;\n\nexport const createBrowserReadLinksTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_read_links\", {});\n if (!result.ok) {\n return `Error reading links: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Links retrieved successfully\";\n } catch (e) {\n return `Error reading links: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_read_links\",\n description: BROWSER_READ_LINKS_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Clickable Elements Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_CLICKABLE_ELEMENTS_DESCRIPTION = `Get the clickable or hoverable or selectable elements on the current page, don't call this tool multiple times.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetClickableElementsTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_clickable_elements\", {});\n if (!result.ok) {\n return `Error getting clickable elements: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Clickable elements retrieved successfully\";\n } catch (e) {\n return `Error getting clickable elements: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_clickable_elements\",\n description: BROWSER_GET_CLICKABLE_ELEMENTS_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Download List Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_DOWNLOAD_LIST_DESCRIPTION = `Get the list of downloaded files.\n\nArgs:\n None\n`;\n\nexport const createBrowserGetDownloadListTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.mcp.executeMcpTool(\"browser\", \"browser_get_download_list\", {});\n if (!result.ok) {\n return `Error getting download list: ${JSON.stringify(result.error.content)}`;\n }\n return result.body?.data?.content?.map((item: any) => item.text).join(\"\\n\") ?? \"Download list retrieved successfully\";\n } catch (e) {\n return `Error getting download list: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_download_list\",\n description: BROWSER_GET_DOWNLOAD_LIST_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Browser Get Info Tool\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getSandBoxManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n\nconst BROWSER_GET_INFO_DESCRIPTION = `Get information about browser, like CDP URL, viewport size, etc.\n\nArgs:\n request (Dict): The incoming request context.\n\nReturns:\n Dict containing browser information including CDP URL, viewport dimensions, and other browser metadata.`;\n\nexport const createBrowserGetInfoTool = ({ isolatedLevel }: { isolatedLevel: IsolatedLevel }) => {\n return tool(\n async (input: any, exe_config: any) => {\n try {\n const runConfig = (exe_config.configurable as any)?.runConfig;\n const sandboxManager = getSandBoxManager();\n const sandbox = await sandboxManager.getSandboxFromConfig({ ...runConfig, isolatedLevel });\n const result = await sandbox.browser.getInfo();\n if (!result.ok) {\n return `Error getting browser info: ${result.error}`;\n }\n return JSON.stringify(result.body.data, undefined, 2);\n } catch (e) {\n return `Error getting browser info: ${e instanceof Error ? e.message : String(e)}`;\n }\n },\n {\n name: \"browser_get_info\",\n description: BROWSER_GET_INFO_DESCRIPTION,\n schema: z.object({}),\n }\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 AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n MiddlewareType,\n} from \"@axiom-lattice/protocols\";\nimport { ReactAgent } from \"langchain\";\n\n// Re-export types from protocols\nexport {\n AgentType,\n AgentConfig,\n ReactAgentConfig,\n DeepAgentConfig,\n AgentConfigWithTools,\n GraphBuildOptions,\n hasTools,\n isDeepAgentConfig,\n getToolsFromConfig,\n getSubAgentsFromConfig,\n};\n\n// Agent客户端类型 - CompiledStateGraph\nexport type AgentClient =\n | CompiledStateGraph<any, any, any, any, any>\n | ReactAgent<any, any, any, any>;\n\n// AgentLattice接口定义\nexport interface AgentLattice {\n config: AgentConfig;\n client?: AgentClient | undefined;\n}\n\n// Middleware configuration\nexport interface MiddlewareConfig {\n id: string;\n type: MiddlewareType;\n name: string;\n description: string;\n enabled: boolean;\n config: Record<string, any>;\n}\n\n// Agent构建参数接口\nexport interface AgentBuildParams {\n middleware?: MiddlewareConfig[];\n skillCategories?: string[];\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","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 createReactAgentSchema = (\n schema?: z.ZodObject<any, any, any, any, any>\n) => {\n return schema ? MessagesZodState.extend(schema.shape) : undefined;\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, AgentClient, MiddlewareConfig } 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 } from \"./state\";\nimport { createAgent } from \"langchain\";\nimport { sandboxLatticeManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { SandboxFilesystem } from \"../../deep_agent_new/backends/sandboxFiles\";\nimport { createCommonMiddlewares } from \"./commonMiddleware\";\n\nexport class ReActAgentGraphBuilder implements AgentGraphBuilder {\n private createFilesystemBackendFactory(\n middlewareConfigs: MiddlewareConfig[]\n ): ((config: { state: unknown; store?: any }) => Promise<any>) | undefined {\n const filesystemConfig = middlewareConfigs.find(m => m.type === \"filesystem\");\n\n if (!filesystemConfig || !filesystemConfig.enabled) {\n return undefined;\n }\n\n const isolatedLevel = filesystemConfig.config?.isolatedLevel || \"global\";\n\n return async (config: { state: unknown }) => {\n let sandboxName = \"global\";\n\n if (isolatedLevel === \"agent\") {\n sandboxName = \"agent\";\n } else if (isolatedLevel === \"thread\") {\n sandboxName = \"thread\";\n }\n\n const sandboxManager = sandboxLatticeManager.getSandboxLattice(\"default\");\n if (!sandboxManager) {\n throw new Error(\"Sandbox manager not found\");\n }\n\n return new SandboxFilesystem({\n sandboxInstance: await sandboxManager.createSandbox(sandboxName),\n });\n };\n }\n\n private createMiddlewares(middlewareConfigs: MiddlewareConfig[]) {\n return createCommonMiddlewares(middlewareConfigs);\n }\n\n /**\n * 构建ReAct Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(agentLattice: AgentLattice, params: AgentBuildParams): AgentClient {\n const tools = params.tools\n .map((t) => {\n const tool = getToolClient(t.key);\n return tool;\n })\n .filter((tool) => tool !== undefined);\n\n const stateSchema = createReactAgentSchema(params.stateSchema);\n\n const middlewareConfigs = params.middleware || [];\n const filesystemBackend = this.createFilesystemBackendFactory(middlewareConfigs);\n const middlewares = createCommonMiddlewares(middlewareConfigs, filesystemBackend);\n\n return createAgent({\n model: params.model,\n tools: tools,\n systemPrompt: params.prompt,\n name: agentLattice.config.name,\n checkpointer: getCheckpointSaver(\"default\"),\n stateSchema: stateSchema as any,\n middleware: middlewares as any,\n });\n }\n}\n","/**\n * SandboxFilesystem: A sandboxed filesystem backend that connects to a remote sandbox via SDK.\n *\n * This backend provides a secure, isolated filesystem environment by connecting to a remote\n * sandbox service through the @agent-infra/sandbox SDK. It implements the BackendProtocol\n * interface and delegates all file operations to the remote sandbox.\n *\n * Features:\n * - Remote sandbox connection via HTTP API\n * - Virtual path support (all paths start with /)\n * - Path traversal prevention\n * - Full BackendProtocol implementation\n */\n\nimport { SandboxClient } from \"@agent-infra/sandbox\";\nimport * as path from \"path\";\nimport micromatch from \"micromatch\";\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileInfo,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n checkEmptyContent,\n formatContentWithLineNumbers,\n performStringReplacement,\n grepMatchesFromFiles,\n} from \"./utils.js\";\n\n/**\n * Sandboxed filesystem backend that connects to a remote sandbox service.\n *\n * All file operations are delegated to the remote sandbox via the SDK.\n * Paths are treated as virtual absolute paths (starting with /).\n */\nexport class SandboxFilesystem implements BackendProtocol {\n private sandbox: SandboxClient;\n private maxFileSizeBytes: number;\n private workingDirectory: string;\n private baseURL: string;\n private homeDir: string;\n\n /**\n * Create a new SandboxFilesystem instance.\n *\n * @param options - Configuration options\n * @param options.baseURL - Base URL of the sandbox service (default: 'http://localhost:8080')\n * @param options.maxFileSizeMb - Maximum file size in MB (default: 10)\n * @param options.sandboxInstance - Optional Sandbox instance (if provided, baseURL is ignored)\n */\n constructor(\n options: {\n baseURL?: string;\n workingDirectory?: string;\n maxFileSizeMb?: number;\n sandboxInstance?: SandboxClient;\n } = {}\n ) {\n const {\n baseURL = \"http://localhost:8080\",\n workingDirectory = \"/\",\n maxFileSizeMb = 10,\n sandboxInstance,\n } = options;\n\n this.sandbox = sandboxInstance || new SandboxClient({ baseUrl: baseURL, environment: \"\" });\n this.sandbox.mcp.listMcpServers().then((servers) => {\n\n });\n this.sandbox.mcp.listMcpTools(\"browser\").then((tools) => {\n console.log(tools);\n });\n\n // this.sandbox.sandbox.getContext().then((context) => {\n // if (!context.ok) {\n // console.error(context.error);\n // } else {\n // console.log(context?.body);\n // }\n // });\n this.baseURL = baseURL;\n this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024;\n this.workingDirectory = workingDirectory;\n this.homeDir = \"/home/gem\";\n }\n private resolvePath(virtualPath: string): string {\n return path.join(this.homeDir, this.workingDirectory, virtualPath);\n }\n\n /**\n * Convert a real filesystem path to a virtual path.\n *\n * @param realPath - Real filesystem path\n * @returns Virtual path starting with /\n */\n private toVirtualPath(realPath: string): string {\n const rootPath = path.join(this.homeDir, this.workingDirectory);\n const relative = path.relative(rootPath, realPath);\n const normalized = relative.split(path.sep).join(\"/\");\n return \"/\" + normalized;\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param dirPath - Virtual directory path (must start with /)\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(dirPath: string): Promise<FileInfo[]> {\n try {\n const resolvedPath = this.resolvePath(dirPath);\n\n const result = await this.sandbox.file.listPath({\n path: resolvedPath,\n recursive: false,\n show_hidden: false,\n max_depth: 0,\n include_size: false,\n include_permissions: false,\n sort_by: \"name\",\n sort_desc: false,\n });\n if (!result.ok) {\n throw result.error;\n }\n const files: FileInfo[] = result.body?.data?.files?.map((file) => ({\n path: this.toVirtualPath(file.path),\n is_dir: file.is_directory,\n size: file.size,\n modified_at: file.modified_time\n })) || [];\n return files;\n } catch (e: any) {\n console.error(`Error listing files in ${dirPath}:`, e);\n return [];\n }\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Virtual file path (must start with /)\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 10000\n ): Promise<string> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n const result = await this.sandbox.file.readFile({\n file: resolvedPath,\n start_line: offset,\n end_line: limit,\n });\n if (!result.ok) {\n throw result.error;\n }\n content = result.body?.data?.content || \"\";\n return content;\n\n } catch (e: any) {\n return `Error: File '${filePath}' not found`;\n }\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Virtual file path (must start with /)\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n try {\n const content = await this.read(filePath);\n return {\n content: content.split(\"\\n\"),\n created_at: new Date().toISOString(),\n modified_at: new Date().toISOString(),\n };\n\n } catch (e: any) {\n throw new Error(`Error reading file '${filePath}': ${e.message}`);\n }\n\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n *\n * @param filePath - Virtual file path (must start with /)\n * @param content - File content as string\n * @returns WriteResult with error populated on failure\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n try {\n\n const resolvedPath = this.resolvePath(filePath);\n // const mkdirResult = await this.sandbox.shell.execCommand({\n // command: `mkdir -p \"$(dirname \"${resolvedPath}\")\"`\n // })\n // if (!mkdirResult.ok) {\n // console.error(mkdirResult.error);\n // throw mkdirResult.error\n // }\n const result = await this.sandbox.file.writeFile({\n file: resolvedPath,\n content: content,\n \"encoding\": \"utf-8\",\n \"append\": false,\n // sudo: true\n });\n if (!result.ok) {\n console.error(result.error);\n throw result.error\n }\n\n return {\n path: filePath,\n filesUpdate: {\n [filePath]: {\n content: content.split(\"\\n\"),\n created_at: new Date().toISOString(),\n modified_at: new Date().toISOString(),\n }\n }\n }\n } catch (e: any) {\n throw new Error(`Error writing file '${filePath}': ${e.message}`);\n }\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n *\n * @param filePath - Virtual file path (must start with /)\n * @param oldString - String to find and replace\n * @param newString - Replacement string\n * @param replaceAll - If true, replace all occurrences (default: false)\n * @returns EditResult with error, path, filesUpdate, and occurrences\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false\n ): Promise<EditResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n const result = await this.sandbox.file.strReplaceEditor({\n command: \"str_replace\",\n path: resolvedPath,\n old_str: oldString,\n new_str: newString,\n replace_mode: replaceAll ? \"ALL\" : \"FIRST\",\n });\n if (!result.ok) {\n throw result.error;\n }\n return {\n path: filePath,\n filesUpdate: null,\n }\n }\n catch (e: any) {\n throw new Error(`Error editing file '${filePath}': ${e.message}`);\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n *\n * Searches file contents for a regex pattern within the sandbox.\n *\n * @param pattern - Regex pattern to search for\n * @param searchPath - Base path to search from (default: \"/\")\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @returns List of GrepMatch objects or error string for invalid regex\n */\n async grepRaw(\n pattern: string,\n searchPath: string | null = \"/\",\n glob: string | null = null\n ): Promise<GrepMatch[] | string> {\n // Resolve base path\n let baseFull: string;\n baseFull = this.resolvePath(searchPath || \"/\");\n\n // Use fast-glob to recursively find all files\n const result = await this.sandbox.file.findFiles({\n path: baseFull,\n glob: glob || \"**/*\"\n })\n\n if (!result.ok) {\n throw result.error;\n }\n const filePaths = result.body?.data?.files || [];\n\n const matches: GrepMatch[] = [];\n\n // Iterate through each file and search for matches\n for (const absolutePath of filePaths) {\n // Read file content as FileData\n const fileData = await this.sandbox.file.searchInFile({\n file: absolutePath,\n regex: pattern,\n });\n if (!fileData.ok) {\n continue;\n }\n\n const matchesData = fileData.body?.data?.matches || [];\n const matchLines = fileData.body?.data?.line_numbers || [];\n matchesData.forEach((match, index) => {\n matches.push({\n path: this.toVirtualPath(absolutePath),\n line: matchLines[index],\n text: match,\n });\n })\n }\n return matches;\n\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n *\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param searchPath - Base path to search from (default: \"/\")\n * @returns List of FileInfo objects matching the pattern\n */\n async globInfo(\n pattern: string,\n searchPath: string = \"/\"\n ): Promise<FileInfo[]> {\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.substring(1);\n }\n\n const resolvedSearchPath = this.resolvePath(searchPath);\n // Use fast-glob to recursively find all files\n const result = await this.sandbox.file.findFiles({\n path: resolvedSearchPath,\n glob: pattern || \"**/*\"\n })\n\n if (!result.ok) {\n throw result.error;\n }\n\n const results: FileInfo[] = [];\n for (const filePath of result.body?.data?.files || []) {\n const fileInfo = await this.sandbox.file.listPath({\n path: filePath,\n recursive: false,\n show_hidden: false,\n max_depth: 1,\n include_size: false,\n include_permissions: false,\n\n });\n if (!fileInfo.ok) {\n continue;\n }\n results.push({\n path: this.toVirtualPath(filePath),\n is_dir: false,\n size: fileInfo.body?.data?.files?.[0]?.size,\n modified_at: fileInfo.body?.data?.files?.[0]?.modified_time\n })\n }\n\n return results;\n\n\n }\n\n\n}\n","import { AIMessage, createMiddleware, tool, type AgentMiddleware } from \"langchain\";\n\nimport { sandboxLatticeManager } from \"../sandbox_lattice/SandboxLatticeManager\";\nimport { getToolClient } from \"../tool_lattice/ToolLatticeManager\";\nimport { createCodeEvalTool } from \"@tool_lattice/code_eval\";\nimport { createCodeExecuteFileTool } from \"@tool_lattice/code_execute_file\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\n/**\n * Parameters for creating the Skill middleware.\n *\n * This is a TypeScript adaptation of the Python SkillMiddleware:\n *\n * - Injects a formatted list of skills into the system prompt.\n * - Registers a `load_skill`-like tool so the model can fetch\n * detailed information for specific skills when needed.\n */\nexport interface CreateCodeEvalMiddlewareParams {\n isolatedLevel: IsolatedLevel;\n}\n\n/**\n * Create middleware that injects sandbox descriptions into the system prompt.\n *\n * This mirrors the behavior of the Python SandboxMiddleware:\n *\n * - Injects a formatted list of sandboxes into the system prompt.\n * - Registers a `load_sandbox`-like tool so the model can fetch\n * detailed information for specific sandboxes when needed.\n */\nexport function createCodeEvalMiddleware(\n params: CreateCodeEvalMiddlewareParams = { isolatedLevel: \"global\" }\n): AgentMiddleware {\n\n const codeEvalTool = createCodeEvalTool({ isolatedLevel: params.isolatedLevel });\n const codeExecuteFileTool = createCodeExecuteFileTool({ isolatedLevel: params.isolatedLevel });\n return createMiddleware({\n name: \"codeEvalMiddleware\",\n tools: [codeEvalTool, codeExecuteFileTool, getToolClient(\"convert_to_markdown\")],\n\n });\n}\n\n\n","import { createMiddleware, type AgentMiddleware } from \"langchain\";\nimport { IsolatedLevel } from \"@sandbox_lattice/SandboxManagerProtocol\";\nimport {\n createBrowserNavigateTool,\n createBrowserClickTool,\n createBrowserGetTextTool,\n createBrowserGetMarkdownTool,\n createBrowserEvaluateTool,\n createBrowserScreenshotTool,\n createBrowserScrollTool,\n createBrowserFormInputFillTool,\n createBrowserSelectTool,\n createBrowserHoverTool,\n createBrowserGoBackTool,\n createBrowserGoForwardTool,\n createBrowserNewTabTool,\n createBrowserTabListTool,\n createBrowserSwitchTabTool,\n createBrowserCloseTabTool,\n createBrowserCloseTool,\n createBrowserPressKeyTool,\n createBrowserReadLinksTool,\n createBrowserGetClickableElementsTool,\n createBrowserGetDownloadListTool,\n createBrowserGetInfoTool,\n} from \"../tool_lattice/browser\";\n\nexport interface CreateBrowserMiddlewareParams {\n isolatedLevel?: IsolatedLevel;\n}\n\nexport function createBrowserMiddleware(\n params: CreateBrowserMiddlewareParams = { isolatedLevel: \"global\" }\n): AgentMiddleware {\n const isolatedLevel = params.isolatedLevel || \"global\";\n\n const tools = [\n createBrowserNavigateTool({ isolatedLevel }),\n createBrowserClickTool({ isolatedLevel }),\n createBrowserGetTextTool({ isolatedLevel }),\n createBrowserGetMarkdownTool({ isolatedLevel }),\n createBrowserEvaluateTool({ isolatedLevel }),\n createBrowserScreenshotTool({ isolatedLevel }),\n createBrowserScrollTool({ isolatedLevel }),\n createBrowserFormInputFillTool({ isolatedLevel }),\n createBrowserSelectTool({ isolatedLevel }),\n createBrowserHoverTool({ isolatedLevel }),\n createBrowserGoBackTool({ isolatedLevel }),\n createBrowserGoForwardTool({ isolatedLevel }),\n createBrowserNewTabTool({ isolatedLevel }),\n createBrowserTabListTool({ isolatedLevel }),\n createBrowserSwitchTabTool({ isolatedLevel }),\n createBrowserCloseTabTool({ isolatedLevel }),\n createBrowserCloseTool({ isolatedLevel }),\n createBrowserPressKeyTool({ isolatedLevel }),\n createBrowserReadLinksTool({ isolatedLevel }),\n createBrowserGetClickableElementsTool({ isolatedLevel }),\n createBrowserGetDownloadListTool({ isolatedLevel }),\n createBrowserGetInfoTool({ isolatedLevel }),\n ];\n\n return createMiddleware({\n name: \"browserMiddleware\",\n tools,\n });\n}\n","import { createMiddleware, type AgentMiddleware } from \"langchain\";\nimport {\n createListTablesSqlTool,\n createInfoSqlTool,\n createQueryCheckerSqlTool,\n createQuerySqlTool,\n} from \"../tool_lattice/sql\";\n\nexport interface CreateSqlMiddlewareParams {\n connectionMode?: \"databaseKey\" | \"connectionString\";\n databaseKey?: string;\n connectionString?: string;\n}\n\nexport function createSqlMiddleware(\n params: CreateSqlMiddlewareParams\n): AgentMiddleware {\n const { connectionMode, databaseKey, connectionString } = params;\n\n const toolParams: { databaseKey?: string; connectionString?: string } = {};\n\n if (connectionMode === \"databaseKey\" && databaseKey) {\n toolParams.databaseKey = databaseKey;\n } else if (connectionString) {\n toolParams.connectionString = connectionString;\n } else if (databaseKey) {\n toolParams.databaseKey = databaseKey;\n } else if (connectionString) {\n toolParams.connectionString = connectionString;\n }\n\n return createMiddleware({\n name: \"sqlMiddleware\",\n tools: [\n createListTablesSqlTool(toolParams),\n createInfoSqlTool(toolParams),\n createQueryCheckerSqlTool(toolParams),\n createQuerySqlTool(toolParams),\n ],\n });\n}\n","import { createMiddleware, type AgentMiddleware } from \"langchain\";\nimport type { Skill, SkillConfig } from \"@axiom-lattice/protocols\";\nimport { skillLatticeManager } from \"../skill_lattice\";\nimport { getStoreLattice } from \"@store_lattice\";\nimport { createLoadSkillsTool, createLoadSkillContentTool } from \"../tool_lattice/skill\";\n\n\n/**\n * Parameters for creating the Skill middleware.\n */\nexport interface CreateSkillMiddlewareParams {\n /**\n * List of skill IDs to use.\n * Only these skills will be available to the agent.\n */\n skills?: string[];\n /** Optional heading for the skills section */\n heading?: string;\n /** Optional extra explanatory note appended after the skills list */\n extraNote?: string;\n}\n\nconst DEFAULT_HEADING = \"## Available Skills\";\nconst DEFAULT_EXTRA_NOTE =\n \"Use the load_skill_content tool when you need detailed information about handling a specific type of request.\";\n\n/**\n * Create middleware that injects skill descriptions into the system prompt.\n */\nexport function createSkillMiddleware(\n params: CreateSkillMiddlewareParams = {}\n): AgentMiddleware {\n const {\n skills = [],\n heading = DEFAULT_HEADING,\n extraNote = DEFAULT_EXTRA_NOTE,\n } = params;\n\n let latestSkills: Skill[] = [];\n\n return createMiddleware({\n name: \"skillMiddleware\",\n tools: [\n createLoadSkillsTool({ skills }),\n createLoadSkillContentTool(),\n ],\n beforeAgent: async () => {\n try {\n if (skills && skills.length > 0) {\n const storeLattice = getStoreLattice(\"default\", \"skill\");\n const skillStore = storeLattice?.store;\n const skillLatticePromises = skills.map((skillId: string) =>\n skillStore.getSkillById(skillId)\n );\n const skillLattices = await Promise.all(skillLatticePromises);\n latestSkills = skillLattices.filter((skill): skill is Skill => skill !== undefined);\n }\n } catch (error) {\n console.error(\"Error fetching skills:\", error);\n }\n },\n wrapModelCall: (request, handler) => {\n const skillsPrompt = latestSkills\n .map((skill) => `- **${skill.name}**: ${skill.description}`)\n .join(\"\\n\");\n\n const skillsAddendum = `\\n\\n${heading}\\n\\n${skillsPrompt}\\n\\n${extraNote}`;\n\n const existingSystemPrompt = request.systemPrompt ?? \"\";\n const newSystemPrompt =\n existingSystemPrompt.length > 0\n ? `${existingSystemPrompt}${skillsAddendum}`\n : skillsAddendum.trimStart();\n\n return handler({\n ...request,\n systemPrompt: newSystemPrompt,\n });\n },\n });\n}\n\n","/**\n * InMemoryThreadStore\n *\n * In-memory implementation of ThreadStore\n * Provides CRUD operations for thread data stored in memory\n * Threads are organized by assistant ID\n */\n\nimport type {\n ThreadStore,\n Thread,\n CreateThreadRequest,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory implementation of ThreadStore\n */\nexport class InMemoryThreadStore implements ThreadStore {\n // Map<assistantId, Map<threadId, Thread>>\n private threads: Map<string, Map<string, Thread>> = new Map();\n\n /**\n * Get all threads for a specific assistant\n */\n async getThreadsByAssistantId(assistantId: string): Promise<Thread[]> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return [];\n }\n return Array.from(assistantThreads.values());\n }\n\n /**\n * Get a thread by ID for a specific assistant\n */\n async getThreadById(\n assistantId: string,\n threadId: string\n ): Promise<Thread | undefined> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return undefined;\n }\n return assistantThreads.get(threadId);\n }\n\n /**\n * Create a new thread for an assistant\n */\n async createThread(\n assistantId: string,\n threadId: string,\n data: CreateThreadRequest\n ): Promise<Thread> {\n const now = new Date();\n const thread: Thread = {\n id: threadId,\n assistantId,\n metadata: data.metadata || {},\n createdAt: now,\n updatedAt: now,\n };\n\n // Initialize assistant's thread map if it doesn't exist\n if (!this.threads.has(assistantId)) {\n this.threads.set(assistantId, new Map());\n }\n\n const assistantThreads = this.threads.get(assistantId)!;\n assistantThreads.set(threadId, thread);\n return thread;\n }\n\n /**\n * Update an existing thread\n */\n async updateThread(\n assistantId: string,\n threadId: string,\n updates: Partial<CreateThreadRequest>\n ): Promise<Thread | null> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return null;\n }\n\n const existing = assistantThreads.get(threadId);\n if (!existing) {\n return null;\n }\n\n const updated: Thread = {\n ...existing,\n metadata: {\n ...existing.metadata,\n ...(updates.metadata || {}),\n },\n updatedAt: new Date(),\n };\n assistantThreads.set(threadId, updated);\n return updated;\n }\n\n /**\n * Delete a thread by ID\n */\n async deleteThread(assistantId: string, threadId: string): Promise<boolean> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return false;\n }\n return assistantThreads.delete(threadId);\n }\n\n /**\n * Check if thread exists\n */\n async hasThread(assistantId: string, threadId: string): Promise<boolean> {\n const assistantThreads = this.threads.get(assistantId);\n if (!assistantThreads) {\n return false;\n }\n return assistantThreads.has(threadId);\n }\n\n /**\n * Clear all threads (useful for testing)\n */\n clear(): void {\n this.threads.clear();\n }\n\n /**\n * Get all threads for all assistants (useful for debugging)\n */\n getAllThreads(): Thread[] {\n const allThreads: Thread[] = [];\n for (const assistantThreads of this.threads.values()) {\n allThreads.push(...Array.from(assistantThreads.values()));\n }\n return allThreads;\n }\n}\n","/**\n * InMemoryAssistantStore\n *\n * In-memory implementation of AssistantStore\n * Provides CRUD operations for assistant data stored in memory\n */\n\nimport type {\n AssistantStore,\n Assistant,\n CreateAssistantRequest,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory implementation of AssistantStore\n */\nexport class InMemoryAssistantStore implements AssistantStore {\n private assistants: Map<string, Assistant> = new Map();\n\n /**\n * Get all assistants\n */\n async getAllAssistants(): Promise<Assistant[]> {\n return Array.from(this.assistants.values());\n }\n\n /**\n * Get assistant by ID\n */\n async getAssistantById(id: string): Promise<Assistant | null> {\n return this.assistants.get(id) || null;\n }\n\n /**\n * Create a new assistant\n */\n async createAssistant(\n id: string,\n data: CreateAssistantRequest\n ): Promise<Assistant> {\n const now = new Date();\n const assistant: Assistant = {\n id,\n name: data.name,\n description: data.description,\n graphDefinition: data.graphDefinition,\n createdAt: now,\n updatedAt: now,\n };\n this.assistants.set(id, assistant);\n return assistant;\n }\n\n /**\n * Update an existing assistant\n */\n async updateAssistant(\n id: string,\n updates: Partial<CreateAssistantRequest>\n ): Promise<Assistant | null> {\n const existing = this.assistants.get(id);\n if (!existing) {\n return null;\n }\n\n const updated: Assistant = {\n ...existing,\n ...updates,\n updatedAt: new Date(),\n };\n this.assistants.set(id, updated);\n return updated;\n }\n\n /**\n * Delete an assistant by ID\n */\n async deleteAssistant(id: string): Promise<boolean> {\n return this.assistants.delete(id);\n }\n\n /**\n * Check if assistant exists\n */\n async hasAssistant(id: string): Promise<boolean> {\n return this.assistants.has(id);\n }\n\n /**\n * Clear all assistants (useful for testing)\n */\n clear(): void {\n this.assistants.clear();\n }\n}\n","/**\n * FileSystemSkillStore\n *\n * Filesystem-based implementation of SkillStore\n * Stores each skill as a Markdown file with YAML frontmatter\n */\n\nimport * as fs from \"fs/promises\";\nimport * as path from \"path\";\nimport {\n SkillStore,\n Skill,\n CreateSkillRequest,\n} from \"@axiom-lattice/protocols\";\nimport { validateSkillName } from \"../skill_lattice/skillNameValidator\";\n\n/**\n * Parse YAML frontmatter from markdown content\n */\nfunction parseFrontmatter(content: string): {\n frontmatter: Record<string, any>;\n body: string;\n} {\n const frontmatterRegex = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n?([\\s\\S]*)$/;\n const match = content.match(frontmatterRegex);\n\n if (!match) {\n console.warn(\"[parseFrontmatter] No frontmatter match found in content\");\n return { frontmatter: {}, body: content };\n }\n\n const frontmatterText = match[1];\n const body = match[2] || \"\";\n\n // Simple YAML parser for basic key-value pairs and nested objects\n const frontmatter: Record<string, any> = {};\n const lines = frontmatterText.split(\"\\n\");\n let currentKey: string | null = null;\n let metadataIndent = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n \n if (!trimmed || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n // Check if this is a nested metadata entry\n const indentMatch = line.match(/^(\\s*)/);\n const indent = indentMatch ? indentMatch[1].length : 0;\n\n if (currentKey === \"metadata\" && indent > metadataIndent) {\n // This is a nested metadata entry\n const colonIndex = trimmed.indexOf(\":\");\n if (colonIndex !== -1) {\n const key = trimmed.substring(0, colonIndex).trim();\n let value = trimmed.substring(colonIndex + 1).trim();\n \n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n \n if (!frontmatter.metadata) {\n frontmatter.metadata = {};\n }\n frontmatter.metadata[key] = value;\n }\n continue;\n }\n\n if (currentKey === \"subSkills\" && indent > metadataIndent) {\n // This is a subSkills array item\n if (trimmed.startsWith(\"-\")) {\n let value = trimmed.substring(1).trim();\n \n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n \n if (!frontmatter.subSkills) {\n frontmatter.subSkills = [];\n }\n frontmatter.subSkills.push(value);\n }\n continue;\n }\n\n // Reset metadata/subSkills tracking\n if ((currentKey === \"metadata\" || currentKey === \"subSkills\") && indent <= metadataIndent) {\n currentKey = null;\n metadataIndent = 0;\n }\n\n const colonIndex = trimmed.indexOf(\":\");\n if (colonIndex === -1) {\n continue;\n }\n\n const key = trimmed.substring(0, colonIndex).trim();\n let value = trimmed.substring(colonIndex + 1).trim();\n\n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n // Handle metadata as nested object\n if (key === \"metadata\") {\n if (value === \"\" || value === \"{}\") {\n // Check if next line starts with indentation (nested metadata)\n if (i + 1 < lines.length) {\n const nextLine = lines[i + 1];\n const nextIndent = nextLine.match(/^(\\s*)/)?.[1].length || 0;\n if (nextIndent > indent) {\n currentKey = \"metadata\";\n metadataIndent = indent;\n frontmatter.metadata = {};\n continue;\n }\n }\n frontmatter[key] = {};\n } else if (value.startsWith(\"{\")) {\n try {\n frontmatter[key] = JSON.parse(value);\n } catch {\n frontmatter[key] = {};\n }\n } else {\n frontmatter[key] = {};\n }\n } else if (key === \"subSkills\") {\n // Handle subSkills as array\n if (value === \"\" || value === \"[]\") {\n // Check if next line starts with indentation (array items)\n if (i + 1 < lines.length) {\n const nextLine = lines[i + 1];\n const nextIndent = nextLine.match(/^(\\s*)/)?.[1].length || 0;\n if (nextIndent > indent && nextLine.trim().startsWith(\"-\")) {\n currentKey = \"subSkills\";\n metadataIndent = indent;\n frontmatter.subSkills = [];\n continue;\n }\n }\n frontmatter[key] = [];\n } else if (value.startsWith(\"[\")) {\n try {\n frontmatter[key] = JSON.parse(value);\n } catch {\n frontmatter[key] = [];\n }\n } else {\n frontmatter[key] = [];\n }\n } else {\n frontmatter[key] = value;\n }\n }\n\n return { frontmatter, body };\n}\n\n/**\n * Generate YAML frontmatter string\n */\nfunction generateFrontmatter(data: {\n name: string;\n description: string;\n license?: string;\n compatibility?: string;\n metadata?: Record<string, string>;\n subSkills?: string[];\n}): string {\n const lines: string[] = [\"---\"];\n\n lines.push(`name: ${data.name}`);\n lines.push(`description: ${data.description}`);\n\n if (data.license) {\n lines.push(`license: ${data.license}`);\n }\n\n if (data.compatibility) {\n lines.push(`compatibility: ${data.compatibility}`);\n }\n\n if (data.metadata && Object.keys(data.metadata).length > 0) {\n // Format metadata as YAML object\n lines.push(\"metadata:\");\n for (const [key, value] of Object.entries(data.metadata)) {\n lines.push(` ${key}: ${value}`);\n }\n }\n\n if (data.subSkills && data.subSkills.length > 0) {\n // Format subSkills as YAML array\n lines.push(\"subSkills:\");\n for (const subSkill of data.subSkills) {\n lines.push(` - ${subSkill}`);\n }\n }\n\n lines.push(\"---\");\n return lines.join(\"\\n\");\n}\n\n/**\n * FileSystemSkillStore options\n */\nexport interface FileSystemSkillStoreOptions {\n /**\n * Root directory path for storing skills\n * Can be absolute or relative path (relative to current working directory)\n * @default \"lattice_store/skills\"\n */\n rootDir?: string;\n}\n\n/**\n * Filesystem-based implementation of SkillStore\n */\nexport class FileSystemSkillStore implements SkillStore {\n private rootDir: string;\n\n constructor(options: FileSystemSkillStoreOptions = {}) {\n const defaultPath = \"lattice_store/skills\";\n const providedPath = options.rootDir || defaultPath;\n \n // Resolve path: if absolute, use as-is; if relative, resolve from cwd\n if (path.isAbsolute(providedPath)) {\n this.rootDir = providedPath;\n } else {\n this.rootDir = path.resolve(process.cwd(), providedPath);\n }\n \n // Ensure root directory exists\n this.ensureDirectoryExists().catch((error) => {\n console.error(\"Failed to initialize FileSystemSkillStore:\", error);\n });\n }\n\n /**\n * Ensure the root directory exists\n */\n private async ensureDirectoryExists(): Promise<void> {\n try {\n await fs.access(this.rootDir);\n } catch {\n // Directory doesn't exist, create it\n await fs.mkdir(this.rootDir, { recursive: true });\n }\n }\n\n /**\n * Get directory path for a skill name\n * Name is used as the directory name, and SKILL.md is the fixed filename\n */\n private getSkillDirectoryPath(name: string): string {\n // Name should already be validated, but add safety check\n if (name.includes(\"..\") || name.includes(\"/\") || name.includes(\"\\\\\")) {\n throw new Error(`Invalid skill name: ${name} (contains invalid characters)`);\n }\n return path.join(this.rootDir, name);\n }\n\n /**\n * Get file path for a skill name\n * File is always named SKILL.md inside the name directory\n */\n private getSkillFilePath(name: string): string {\n return path.join(this.getSkillDirectoryPath(name), \"SKILL.md\");\n }\n\n /**\n * Read skill from file\n * Uses name as the directory name and reads SKILL.md from it\n */\n private async readSkillFile(name: string): Promise<Skill | null> {\n await this.ensureDirectoryExists();\n const filePath = this.getSkillFilePath(name);\n\n try {\n const content = await fs.readFile(filePath, \"utf-8\");\n const { frontmatter, body } = parseFrontmatter(content);\n\n if (!frontmatter.name || !frontmatter.description) {\n console.warn(\n `Skill file ${name} parsed frontmatter:`,\n JSON.stringify(frontmatter, null, 2)\n );\n console.warn(`Raw frontmatter text (first 200 chars):`, content.substring(0, 200));\n }\n\n // Get file stats for timestamps\n const stats = await fs.stat(filePath);\n\n // Validate required fields\n if (!frontmatter.name || !frontmatter.description) {\n throw new Error(\n `Invalid skill file ${name}: missing required fields (name or description). Frontmatter: ${JSON.stringify(frontmatter)}`\n );\n }\n\n // Ensure name matches directory name\n if (frontmatter.name !== name) {\n throw new Error(\n `Skill name mismatch: directory name is \"${name}\" but frontmatter name is \"${frontmatter.name}\"`\n );\n }\n\n return {\n id: name, // id equals name (name is used for path addressing)\n name: frontmatter.name,\n description: frontmatter.description,\n license: frontmatter.license,\n compatibility: frontmatter.compatibility,\n metadata: frontmatter.metadata || {},\n content: body.trim() || undefined,\n subSkills: Array.isArray(frontmatter.subSkills) ? frontmatter.subSkills : undefined,\n createdAt: stats.birthtime,\n updatedAt: stats.mtime,\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(`Skill file not found: ${filePath}`);\n return null;\n }\n // Re-throw with more context\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read skill file ${filePath}: ${errorMessage}`);\n }\n }\n\n /**\n * Write skill to file\n * Creates directory with name and writes SKILL.md inside it\n */\n private async writeSkillFile(skill: Skill): Promise<void> {\n await this.ensureDirectoryExists();\n \n // Ensure id equals name (name is used for path addressing)\n const skillName = skill.name;\n const skillDir = this.getSkillDirectoryPath(skillName);\n const filePath = this.getSkillFilePath(skillName);\n\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(skillDir, { recursive: true });\n } catch (error) {\n // Directory might already exist, ignore\n }\n\n const frontmatter = generateFrontmatter({\n name: skillName,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n subSkills: skill.subSkills,\n });\n\n const body = skill.content || \"\";\n const content = body\n ? `${frontmatter}\\n${body}`\n : `${frontmatter}\\n`;\n\n await fs.writeFile(filePath, content, \"utf-8\");\n }\n\n /**\n * Get all skills\n */\n async getAllSkills(): Promise<Skill[]> {\n await this.ensureDirectoryExists();\n\n try {\n const entries = await fs.readdir(this.rootDir, { withFileTypes: true });\n\n const skills: Skill[] = [];\n for (const entry of entries) {\n // Only process directories\n if (entry.isDirectory()) {\n const skillName = entry.name;\n try {\n const skill = await this.readSkillFile(skillName);\n if (skill) {\n skills.push(skill);\n } else {\n console.warn(\n `Failed to load skill \"${skillName}\": readSkillFile returned null`\n );\n }\n } catch (error) {\n console.error(\n `Error loading skill \"${skillName}\" from ${this.getSkillFilePath(skillName)}:`,\n error instanceof Error ? error.message : String(error)\n );\n // Continue processing other skills instead of failing completely\n }\n }\n }\n\n return skills.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n console.warn(\n `Skills directory not found: ${this.rootDir}`\n );\n return [];\n }\n throw error;\n }\n }\n\n /**\n * Get skill by ID\n * ID should equal name (name is used for path addressing)\n */\n async getSkillById(id: string): Promise<Skill | null> {\n // Use id as name (they should be the same)\n return this.readSkillFile(id);\n }\n\n /**\n * Create a new skill\n * id should equal name (name is used for path addressing)\n */\n async createSkill(id: string, data: CreateSkillRequest): Promise<Skill> {\n await this.ensureDirectoryExists();\n\n // Validate name format\n validateSkillName(data.name);\n\n // Validate that id equals name\n if (id !== data.name) {\n throw new Error(\n `Skill id \"${id}\" must equal name \"${data.name}\" (name is used for path addressing)`\n );\n }\n\n // Check if skill already exists\n const existing = await this.getSkillById(id);\n if (existing) {\n // Update existing skill\n return this.updateSkill(id, data) as Promise<Skill>;\n }\n\n const now = new Date();\n const skill: Skill = {\n id: data.name, // id equals name\n name: data.name,\n description: data.description,\n license: data.license,\n compatibility: data.compatibility,\n metadata: data.metadata || {},\n content: data.content,\n subSkills: data.subSkills,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.writeSkillFile(skill);\n return skill;\n }\n\n /**\n * Update an existing skill\n */\n async updateSkill(\n id: string,\n updates: Partial<CreateSkillRequest>\n ): Promise<Skill | null> {\n const skill = await this.readSkillFile(id);\n if (!skill) {\n return null;\n }\n\n // If name is being updated, validate it\n if (updates.name !== undefined) {\n validateSkillName(updates.name);\n \n // If name changes, we need to move the directory\n if (updates.name !== skill.name) {\n const oldDir = this.getSkillDirectoryPath(skill.name);\n const newDir = this.getSkillDirectoryPath(updates.name);\n \n // Move directory\n try {\n await fs.rename(oldDir, newDir);\n } catch (error) {\n throw new Error(\n `Failed to rename skill directory from \"${skill.name}\" to \"${updates.name}\": ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n }\n\n const updatedSkill: Skill = {\n ...skill,\n name: updates.name ?? skill.name,\n id: updates.name ?? skill.id, // id equals name\n description: updates.description ?? skill.description,\n license: updates.license ?? skill.license,\n compatibility: updates.compatibility ?? skill.compatibility,\n metadata: updates.metadata ?? skill.metadata,\n content: updates.content !== undefined ? updates.content : skill.content,\n subSkills: updates.subSkills !== undefined ? updates.subSkills : skill.subSkills,\n updatedAt: new Date(),\n };\n\n await this.writeSkillFile(updatedSkill);\n return updatedSkill;\n }\n\n /**\n * Delete a skill by ID\n * Deletes the entire directory (name is the directory name)\n */\n async deleteSkill(id: string): Promise<boolean> {\n await this.ensureDirectoryExists();\n const skillDir = this.getSkillDirectoryPath(id);\n\n try {\n // Remove the entire directory\n await fs.rm(skillDir, { recursive: true, force: true });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n }\n\n /**\n * Check if skill exists\n */\n async hasSkill(id: string): Promise<boolean> {\n const skill = await this.getSkillById(id);\n return skill !== null;\n }\n\n /**\n * Search skills by metadata\n */\n async searchByMetadata(\n metadataKey: string,\n metadataValue: string\n ): Promise<Skill[]> {\n const allSkills = await this.getAllSkills();\n return allSkills.filter((skill) => {\n return (\n skill.metadata &&\n skill.metadata[metadataKey] === metadataValue\n );\n });\n }\n\n /**\n * Filter skills by compatibility\n */\n async filterByCompatibility(compatibility: string): Promise<Skill[]> {\n const allSkills = await this.getAllSkills();\n return allSkills.filter((skill) => {\n return skill.compatibility === compatibility;\n });\n }\n\n /**\n * Filter skills by license\n */\n async filterByLicense(license: string): Promise<Skill[]> {\n const allSkills = await this.getAllSkills();\n return allSkills.filter((skill) => {\n return skill.license === license;\n });\n }\n\n /**\n * Get sub-skills of a parent skill\n */\n async getSubSkills(parentSkillName: string): Promise<Skill[]> {\n const parentSkill = await this.getSkillById(parentSkillName);\n if (!parentSkill || !parentSkill.subSkills || parentSkill.subSkills.length === 0) {\n return [];\n }\n\n const subSkills: Skill[] = [];\n for (const subSkillName of parentSkill.subSkills) {\n const subSkill = await this.getSkillById(subSkillName);\n if (subSkill) {\n subSkills.push(subSkill);\n }\n }\n\n return subSkills;\n }\n}\n","/**\n * Skill name validator\n * Validates skill names according to the specification:\n * - 1-64 characters\n * - Lowercase alphanumeric with single hyphen separators\n * - Not start or end with -\n * - Not contain consecutive --\n * - Match the directory name that contains SKILL.md\n * - Regex: ^[a-z0-9]+(-[a-z0-9]+)*$\n */\n\nconst SKILL_NAME_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/;\nconst MIN_LENGTH = 1;\nconst MAX_LENGTH = 64;\n\n/**\n * Validate skill name\n * @param name Skill name to validate\n * @returns true if valid, false otherwise\n */\nexport function isValidSkillName(name: string): boolean {\n if (!name || typeof name !== \"string\") {\n return false;\n }\n\n // Check length\n if (name.length < MIN_LENGTH || name.length > MAX_LENGTH) {\n return false;\n }\n\n // Check regex pattern\n return SKILL_NAME_REGEX.test(name);\n}\n\n/**\n * Validate skill name and throw error if invalid\n * @param name Skill name to validate\n * @throws Error if name is invalid\n */\nexport function validateSkillName(name: string): void {\n if (!name || typeof name !== \"string\") {\n throw new Error(\"Skill name is required and must be a string\");\n }\n\n if (name.length < MIN_LENGTH || name.length > MAX_LENGTH) {\n throw new Error(\n `Skill name must be between ${MIN_LENGTH} and ${MAX_LENGTH} characters`\n );\n }\n\n if (!SKILL_NAME_REGEX.test(name)) {\n throw new Error(\n \"Skill name must be lowercase alphanumeric with single hyphen separators, \" +\n \"not start or end with -, and not contain consecutive --. \" +\n \"Pattern: ^[a-z0-9]+(-[a-z0-9]+)*$\"\n );\n }\n}\n","/**\n * StoreLatticeManager\n *\n * Store Lattice manager for registering and managing store services\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport type {\n ThreadStore,\n AssistantStore,\n SkillStore,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * Store type to store interface mapping\n * Maps store type strings to their corresponding interface types\n */\nexport type StoreTypeMap = {\n thread: ThreadStore;\n assistant: AssistantStore;\n skill: SkillStore;\n // Future store types can be added here:\n // vector: VectorStore;\n};\n\n/**\n * Store type keys\n */\nexport type StoreType = keyof StoreTypeMap;\n\n/**\n * Store Lattice interface with type safety\n * @template TStoreType - The type of store (e.g., \"thread\")\n */\nexport interface StoreLattice<TStoreType extends StoreType = StoreType> {\n type: TStoreType;\n key: string;\n store: StoreTypeMap[TStoreType];\n}\n\n/**\n * StoreLatticeManager - Singleton store Lattice manager\n * Responsible for registering and managing various store service Lattices\n */\nexport class StoreLatticeManager extends BaseLatticeManager<\n StoreLattice<StoreType>\n> {\n private static _instance: StoreLatticeManager;\n\n /**\n * Get StoreLatticeManager singleton instance\n */\n public static getInstance(): StoreLatticeManager {\n if (!StoreLatticeManager._instance) {\n StoreLatticeManager._instance = new StoreLatticeManager();\n }\n return StoreLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"stores\";\n }\n\n /**\n * Generate composite key from key and type\n * @param key Lattice key name\n * @param type Store type\n * @returns Composite key string\n */\n private getCompositeKey(key: string, type: StoreType): string {\n return `${key}:${type}`;\n }\n\n /**\n * Register store Lattice with type safety\n * Uses composite key (key + type) as unique identifier\n * @param key Lattice key name\n * @param type Store type (e.g., \"thread\")\n * @param store Store implementation instance matching the type\n */\n public registerLattice<TStoreType extends StoreType>(\n key: string,\n type: TStoreType,\n store: StoreTypeMap[TStoreType]\n ): void {\n // Create store Lattice object\n const storeLattice: StoreLattice<TStoreType> = {\n key,\n type,\n store,\n };\n\n // Use composite key (key + type) for registration\n const compositeKey = this.getCompositeKey(key, type);\n this.register(compositeKey, storeLattice as StoreLattice<StoreType>);\n }\n\n /**\n * Get StoreLattice with type safety\n * Uses composite key (key + type) to retrieve the store\n * @param key Lattice key name\n * @param type Expected store type for type checking\n * @returns StoreLattice with typed store\n */\n public getStoreLattice<TStoreType extends StoreType>(\n key: string,\n type: TStoreType\n ): StoreLattice<TStoreType> {\n const compositeKey = this.getCompositeKey(key, type);\n const storeLattice = this.get(compositeKey);\n if (!storeLattice) {\n throw new Error(`StoreLattice ${key}:${type} not found`);\n }\n\n if (storeLattice.type !== type) {\n throw new Error(\n `StoreLattice ${key}:${type} has type \"${storeLattice.type}\", expected \"${type}\"`\n );\n }\n\n return storeLattice as StoreLattice<TStoreType>;\n }\n\n /**\n * Get StoreLattice without type checking (for backward compatibility)\n * @param key Lattice key name\n * @param type Store type\n * @returns StoreLattice (type may be unknown)\n */\n public getStoreLatticeUnsafe(\n key: string,\n type: StoreType\n ): StoreLattice<StoreType> {\n const compositeKey = this.getCompositeKey(key, type);\n const storeLattice = this.get(compositeKey);\n if (!storeLattice) {\n throw new Error(`StoreLattice ${key}:${type} not found`);\n }\n return storeLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): StoreLattice<StoreType>[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * Uses composite key (key + type) to check existence\n * @param key Lattice key name\n * @param type Store type\n */\n public hasLattice(key: string, type: StoreType): boolean {\n const compositeKey = this.getCompositeKey(key, type);\n return this.has(compositeKey);\n }\n\n /**\n * Remove Lattice\n * Uses composite key (key + type) to remove the store\n * @param key Lattice key name\n * @param type Store type\n */\n public removeLattice(key: string, type: StoreType): boolean {\n const compositeKey = this.getCompositeKey(key, type);\n return this.remove(compositeKey);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const storeLatticeManager = StoreLatticeManager.getInstance();\n\n// Export convenience methods with type safety\nexport const registerStoreLattice = <TStoreType extends StoreType>(\n key: string,\n type: TStoreType,\n store: StoreTypeMap[TStoreType]\n) => storeLatticeManager.registerLattice(key, type, store);\n\nexport const getStoreLattice = <TStoreType extends StoreType>(\n key: string,\n type: TStoreType\n) => storeLatticeManager.getStoreLattice(key, type);\n\n// Default registration of InMemory stores\nimport { InMemoryThreadStore } from \"./InMemoryThreadStore\";\nimport { InMemoryAssistantStore } from \"./InMemoryAssistantStore\";\nimport { FileSystemSkillStore } from \"./FileSystemSkillStore\";\n\n// Create default instances\nconst defaultThreadStore = new InMemoryThreadStore();\nconst defaultAssistantStore = new InMemoryAssistantStore();\nconst defaultSkillStore = new FileSystemSkillStore();\n\n// Register as default stores\nstoreLatticeManager.registerLattice(\"default\", \"thread\", defaultThreadStore);\nstoreLatticeManager.registerLattice(\n \"default\",\n \"assistant\",\n defaultAssistantStore\n);\nstoreLatticeManager.registerLattice(\"default\", \"skill\", defaultSkillStore);\n","/**\n * Load Skills Tool\n * Loads available skills and returns their metadata\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getStoreLattice } from \"../../store_lattice/StoreLatticeManager\";\n\nconst LOAD_SKILLS_DESCRIPTION = `Load all available skills and return their metadata (name, description, license, compatibility, metadata, and subSkills) without the content. This tool returns skill information including hierarchical relationships (subSkills). Use this to discover what skills are available and their structure.`;\n\nexport interface CreateLoadSkillsToolParams {\n skills?: string[];\n}\n\nexport const createLoadSkillsTool = ({ skills }: CreateLoadSkillsToolParams = {}) => {\n return tool(\n async (_input: Record<string, never>, _exe_config: any) => {\n try {\n const storeLattice = getStoreLattice(\"default\", \"skill\");\n const skillStore = storeLattice.store;\n const allSkills = await skillStore.getAllSkills();\n\n const filteredSkills = skills && skills.length > 0\n ? allSkills.filter((skill) => skills.includes(skill.id))\n : allSkills;\n\n const skillsMeta = filteredSkills.map((skill) => ({\n id: skill.id,\n name: skill.name,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n subSkills: skill.subSkills,\n }));\n\n return JSON.stringify(skillsMeta, null, 2);\n } catch (error) {\n return `Error loading skills: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"load_skills\",\n description: LOAD_SKILLS_DESCRIPTION,\n schema: z.object({}),\n }\n );\n};\n","/**\n * Load Skill Content Tool\n * Loads a specific skill's content by name and returns its full content\n */\n\nimport z from \"zod\";\nimport { tool } from \"langchain\";\nimport { getStoreLattice } from \"../../store_lattice/StoreLatticeManager\";\n\nconst LOAD_SKILL_CONTENT_DESCRIPTION = `Load a specific skill's content by name and return its full content including markdown body. This tool returns the complete skill content including frontmatter and markdown body. Use this tool to get the complete skill content for a skill that you want to use.`;\n\nexport const createLoadSkillContentTool = () => {\n return tool(\n async (input: { skill_name: string }, _exe_config: any) => {\n try {\n const storeLattice = getStoreLattice(\"default\", \"skill\");\n const skillStore = storeLattice.store;\n const skill = await skillStore.getSkillById(input.skill_name);\n\n if (!skill) {\n const allSkills = await skillStore.getAllSkills();\n const availableSkills = allSkills.map((s) => s.name).join(\", \");\n return `Skill \"${input.skill_name}\" not found. Available skills: ${availableSkills}`;\n }\n\n const frontmatter: string[] = [\"---\"];\n frontmatter.push(`name: ${skill.name}`);\n frontmatter.push(`description: ${skill.description}`);\n if (skill.license) {\n frontmatter.push(`license: ${skill.license}`);\n }\n if (skill.compatibility) {\n frontmatter.push(`compatibility: ${skill.compatibility}`);\n }\n if (skill.metadata && Object.keys(skill.metadata).length > 0) {\n frontmatter.push(\"metadata:\");\n for (const [key, value] of Object.entries(skill.metadata)) {\n frontmatter.push(` ${key}: ${value}`);\n }\n }\n if (skill.subSkills && skill.subSkills.length > 0) {\n frontmatter.push(\"subSkills:\");\n for (const subSkill of skill.subSkills) {\n frontmatter.push(` - ${subSkill}`);\n }\n }\n frontmatter.push(\"---\");\n\n const content = skill.content || \"\";\n return `${frontmatter.join(\"\\n\")}\\n${content}`;\n } catch (error) {\n return `Error loading skill content: ${error instanceof Error ? error.message : String(error)}`;\n }\n },\n {\n name: \"load_skill_content\",\n description: LOAD_SKILL_CONTENT_DESCRIPTION,\n schema: z.object({\n skill_name: z.string().describe(\"The name of the skill to load\"),\n }),\n }\n );\n};\n","/**\n * Middleware for providing filesystem tools to an agent.\n *\n * Provides ls, read_file, write_file, edit_file, glob, and grep tools with support for:\n * - Pluggable backends (StateBackend, StoreBackend, FilesystemBackend, CompositeBackend)\n * - Tool result eviction for large outputs\n */\n\nimport { createMiddleware, tool, ToolMessage } from \"langchain\";\nimport { Command, isCommand, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport { z as z3 } from \"zod/v3\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\nimport type {\n BackendProtocol,\n BackendFactory,\n FileData,\n StateAndStore,\n} from \"../backends/protocol.js\";\nimport { StateBackend } from \"../backends/state.js\";\nimport { sanitizeToolCallId } from \"../backends/utils.js\";\n\n/**\n * Zod v3 schema for FileData (re-export from backends)\n */\nconst FileDataSchema = z3.object({\n content: z3.array(z3.string()),\n created_at: z3.string(),\n modified_at: z3.string(),\n});\n\nexport type { FileData };\n\n/**\n * Merge file updates with support for deletions.\n */\nfunction fileDataReducer(\n left: Record<string, FileData> | undefined,\n right: Record<string, FileData | null>\n): Record<string, FileData> {\n if (left === undefined) {\n const result: Record<string, FileData> = {};\n for (const [key, value] of Object.entries(right)) {\n if (value !== null) {\n result[key] = value;\n }\n }\n return result;\n }\n\n const result = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (value === null) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Shared filesystem state schema.\n * Defined at module level to ensure the same object identity is used across all agents,\n * preventing \"Channel already exists with different type\" errors when multiple agents\n * use createFilesystemMiddleware.\n */\nconst FilesystemStateSchema = z3.object({\n files: withLangGraph(\n z3.record(z3.string(), FileDataSchema).default({}) as any,\n {\n reducer: {\n fn: fileDataReducer,\n schema: z3.record(z3.string(), FileDataSchema.nullable()),\n },\n }\n ),\n});\n\n/**\n * Resolve backend from factory or instance.\n *\n * @param backend - Backend instance or factory function\n * @param stateAndStore - State and store container for backend initialization\n */\nasync function getBackend(\n backend: BackendProtocol | BackendFactory,\n stateAndStore: StateAndStore\n): Promise<BackendProtocol> {\n if (typeof backend === \"function\") {\n return await backend(stateAndStore);\n }\n return backend;\n}\n\n// System prompts\nconst FILESYSTEM_SYSTEM_PROMPT = `You have access to a virtual filesystem. All file paths must start with a /.\n\n- ls: list files in a directory (requires absolute path)\n- read_file: read a file from the filesystem\n- write_file: write to a file in the filesystem\n- edit_file: edit a file in the filesystem\n- glob: find files matching a pattern (e.g., \"**/*.py\")\n- grep: search for text within files`;\n\n// Tool descriptions\nexport const LS_TOOL_DESCRIPTION = \"List files and directories in a directory\";\nexport const READ_FILE_TOOL_DESCRIPTION = \"Read the contents of a file\";\nexport const WRITE_FILE_TOOL_DESCRIPTION =\n \"Write content to a new file. Returns an error if the file already exists\";\nexport const EDIT_FILE_TOOL_DESCRIPTION =\n \"Edit a file by replacing a specific string with a new string\";\nexport const GLOB_TOOL_DESCRIPTION =\n \"Find files matching a glob pattern (e.g., '**/*.py' for all Python files)\";\nexport const GREP_TOOL_DESCRIPTION =\n \"Search for a regex pattern in files. Returns matching files and line numbers\";\n\n/**\n * Create ls tool using backend.\n */\nfunction createLsTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const path = input.path || \"/\";\n const infos = await resolvedBackend.lsInfo(path);\n\n if (infos.length === 0) {\n return `No files found in ${path}`;\n }\n\n // Format output\n const lines: string[] = [];\n for (const info of infos) {\n if (info.is_dir) {\n lines.push(`<file>${info.path}</file> (directory)`);\n } else {\n const size = info.size ? ` (${info.size} bytes)` : \"\";\n lines.push(`<file>${info.path}</file>${size}`);\n }\n }\n return lines.join(\"\\n\");\n },\n {\n name: \"ls\",\n description: customDescription || LS_TOOL_DESCRIPTION,\n schema: z3.object({\n path: z3\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Directory path to list (default: /)\"),\n }),\n }\n );\n}\n\n/**\n * Create read_file tool using backend.\n */\nfunction createReadFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { file_path, offset = 0, limit = 2000 } = input;\n return await resolvedBackend.read(file_path, offset, limit);\n },\n {\n name: \"read_file\",\n description: customDescription || READ_FILE_TOOL_DESCRIPTION,\n schema: z3.object({\n file_path: z3.string().describe(\"Absolute path to the file to read\"),\n offset: z3\n .number({ coerce: true })\n .optional()\n .default(0)\n .describe(\"Line offset to start reading from (0-indexed)\"),\n limit: z3\n .number({ coerce: true })\n .optional()\n .default(2000)\n .describe(\"Maximum number of lines to read\"),\n }),\n }\n );\n}\n\n/**\n * Create write_file tool using backend.\n */\nfunction createWriteFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { file_path, content } = input;\n const result = await resolvedBackend.write(file_path, content);\n\n if (result.error) {\n return result.error;\n }\n\n // If filesUpdate is present, return Command to update state\n const message = new ToolMessage({\n content: `Successfully wrote to '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"write_file\",\n metadata: result.metadata,\n });\n\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n return message;\n },\n {\n name: \"write_file\",\n description: customDescription || WRITE_FILE_TOOL_DESCRIPTION,\n schema: z3.object({\n file_path: z3.string().describe(\"Absolute path to the file to write\"),\n content: z3.string().describe(\"Content to write to the file\"),\n }),\n }\n );\n}\n\n/**\n * Create edit_file tool using backend.\n */\nfunction createEditFileTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { file_path, old_string, new_string, replace_all = false } = input;\n const result = await resolvedBackend.edit(\n file_path,\n old_string,\n new_string,\n replace_all\n );\n\n if (result.error) {\n return result.error;\n }\n\n const message = new ToolMessage({\n content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`,\n tool_call_id: config.toolCall?.id as string,\n name: \"edit_file\",\n metadata: result.metadata,\n });\n\n // If filesUpdate is present, return Command to update state\n if (result.filesUpdate) {\n return new Command({\n update: { files: result.filesUpdate, messages: [message] },\n });\n }\n\n // External storage (filesUpdate is null)\n return message;\n },\n {\n name: \"edit_file\",\n description: customDescription || EDIT_FILE_TOOL_DESCRIPTION,\n schema: z3.object({\n file_path: z3.string().describe(\"Absolute path to the file to edit\"),\n old_string: z3\n .string()\n .describe(\"String to be replaced (must match exactly)\"),\n new_string: z3.string().describe(\"String to replace with\"),\n replace_all: z3\n .boolean()\n .optional()\n .default(false)\n .describe(\"Whether to replace all occurrences\"),\n }),\n }\n );\n}\n\n/**\n * Create glob tool using backend.\n */\nfunction createGlobTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { pattern, path = \"/\" } = input;\n const infos = await resolvedBackend.globInfo(pattern, path);\n\n if (infos.length === 0) {\n return `No files found matching pattern '${pattern}'`;\n }\n\n return infos.map((info) => info.path).join(\"\\n\");\n },\n {\n name: \"glob\",\n description: customDescription || GLOB_TOOL_DESCRIPTION,\n schema: z3.object({\n pattern: z3.string().describe(\"Glob pattern (e.g., '*.py', '**/*.ts')\"),\n path: z3\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n }),\n }\n );\n}\n\n/**\n * Create grep tool using backend.\n */\nfunction createGrepTool(\n backend: BackendProtocol | BackendFactory,\n options: { customDescription: string | undefined }\n) {\n const { customDescription } = options;\n return tool(\n async (input, config) => {\n const stateAndStore: StateAndStore = {\n state: getCurrentTaskInput(config),\n store: (config as any).store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const { pattern, path = \"/\", glob = null } = input;\n const result = await resolvedBackend.grepRaw(pattern, path, glob);\n\n // If string, it's an error\n if (typeof result === \"string\") {\n return result;\n }\n\n if (result.length === 0) {\n return `No matches found for pattern '${pattern}'`;\n }\n\n // Format output: group by file\n const lines: string[] = [];\n let currentFile: string | null = null;\n for (const match of result) {\n if (match.path !== currentFile) {\n currentFile = match.path;\n lines.push(`\\n${currentFile}:`);\n }\n lines.push(` ${match.line}: ${match.text}`);\n }\n\n return lines.join(\"\\n\");\n },\n {\n name: \"grep\",\n description: customDescription || GREP_TOOL_DESCRIPTION,\n schema: z3.object({\n pattern: z3.string().describe(\"Regex pattern to search for\"),\n path: z3\n .string()\n .optional()\n .default(\"/\")\n .describe(\"Base path to search from (default: /)\"),\n glob: z3\n .string()\n .optional()\n .nullable()\n .describe(\"Optional glob pattern to filter files (e.g., '*.py')\"),\n }),\n }\n );\n}\n\n/**\n * Options for creating filesystem middleware.\n */\nexport interface FilesystemMiddlewareOptions {\n /** Backend instance or factory (default: StateBackend) */\n backend?: BackendProtocol | BackendFactory;\n /** Optional custom system prompt override */\n systemPrompt?: string | null;\n /** Optional custom tool descriptions override */\n customToolDescriptions?: Record<string, string> | null;\n /** Optional token limit before evicting a tool result to the filesystem (default: 20000 tokens, ~80KB) */\n toolTokenLimitBeforeEvict?: number | null;\n}\n\n/**\n * Create filesystem middleware with all tools and features.\n */\nexport function createFilesystemMiddleware(\n options: FilesystemMiddlewareOptions = {}\n) {\n const {\n backend = async (stateAndStore: StateAndStore) => new StateBackend(stateAndStore),\n systemPrompt: customSystemPrompt = null,\n customToolDescriptions = null,\n toolTokenLimitBeforeEvict = 20000,\n } = options;\n\n const systemPrompt = customSystemPrompt || FILESYSTEM_SYSTEM_PROMPT;\n\n const tools = [\n createLsTool(backend, {\n customDescription: customToolDescriptions?.ls,\n }),\n createReadFileTool(backend, {\n customDescription: customToolDescriptions?.read_file,\n }),\n createWriteFileTool(backend, {\n customDescription: customToolDescriptions?.write_file,\n }),\n createEditFileTool(backend, {\n customDescription: customToolDescriptions?.edit_file,\n }),\n createGlobTool(backend, {\n customDescription: customToolDescriptions?.glob,\n }),\n createGrepTool(backend, {\n customDescription: customToolDescriptions?.grep,\n }),\n ];\n\n return createMiddleware({\n name: \"FilesystemMiddleware\",\n stateSchema: FilesystemStateSchema as any,\n tools,\n wrapModelCall: systemPrompt\n ? async (request, handler: any) => {\n const currentSystemPrompt = request.systemPrompt || \"\";\n const newSystemPrompt = currentSystemPrompt\n ? `${currentSystemPrompt}\\n\\n${systemPrompt}`\n : systemPrompt;\n return handler({ ...request, systemPrompt: newSystemPrompt });\n }\n : undefined,\n wrapToolCall: toolTokenLimitBeforeEvict\n ? ((async (request: any, handler: any) => {\n const result = await handler(request);\n\n async function processToolMessage(msg: ToolMessage) {\n if (\n typeof msg.content === \"string\" &&\n msg.content.length > toolTokenLimitBeforeEvict! * 4\n ) {\n // Build StateAndStore from request\n const stateAndStore: StateAndStore = {\n state: request.state || {},\n store: request.config?.store,\n };\n const resolvedBackend = await getBackend(backend, stateAndStore);\n const sanitizedId = sanitizeToolCallId(\n request.toolCall?.id || msg.tool_call_id\n );\n const evictPath = `/large_tool_results/${sanitizedId}`;\n\n const writeResult = await resolvedBackend.write(\n evictPath,\n msg.content\n );\n\n if (writeResult.error) {\n return { message: msg, filesUpdate: null };\n }\n\n const truncatedMessage = new ToolMessage({\n content: `Tool result too large (${Math.round(\n msg.content.length / 4\n )} tokens). Content saved to ${evictPath}`,\n tool_call_id: msg.tool_call_id,\n name: msg.name,\n });\n\n return {\n message: truncatedMessage,\n filesUpdate: writeResult.filesUpdate,\n };\n }\n return { message: msg, filesUpdate: null };\n }\n\n if (result instanceof ToolMessage) {\n const processed = await processToolMessage(result);\n\n if (processed.filesUpdate) {\n return new Command({\n update: {\n files: processed.filesUpdate,\n messages: [processed.message],\n },\n });\n }\n\n return processed.message;\n }\n\n if (isCommand(result)) {\n const update = result.update as any;\n if (!update?.messages) {\n return result;\n }\n\n let hasLargeResults = false;\n const accumulatedFiles: Record<string, FileData> = {\n ...(update.files || {}),\n };\n const processedMessages: ToolMessage[] = [];\n\n for (const msg of update.messages) {\n if (msg instanceof ToolMessage) {\n const processed = await processToolMessage(msg);\n processedMessages.push(processed.message);\n\n if (processed.filesUpdate) {\n hasLargeResults = true;\n Object.assign(accumulatedFiles, processed.filesUpdate);\n }\n } else {\n processedMessages.push(msg);\n }\n }\n\n if (hasLargeResults) {\n return new Command({\n update: {\n ...update,\n messages: processedMessages,\n files: accumulatedFiles,\n },\n });\n }\n }\n\n return result;\n }) as any)\n : undefined,\n });\n}\n","/**\n * Shared utility functions for memory backend implementations.\n *\n * This module contains both user-facing string formatters and structured\n * helpers used by backends and the composite router. Structured helpers\n * enable composition without fragile string parsing.\n */\n\nimport micromatch from \"micromatch\";\nimport { basename } from \"path\";\nimport type { FileData, GrepMatch } from \"./protocol.js\";\n\n// Constants\nexport const EMPTY_CONTENT_WARNING =\n \"System reminder: File exists but has empty contents\";\nexport const MAX_LINE_LENGTH = 10000;\nexport const LINE_NUMBER_WIDTH = 6;\nexport const TOOL_RESULT_TOKEN_LIMIT = 20000; // Same threshold as eviction\nexport const TRUNCATION_GUIDANCE =\n \"... [results truncated, try being more specific with your parameters]\";\n\n/**\n * Sanitize tool_call_id to prevent path traversal and separator issues.\n *\n * Replaces dangerous characters (., /, \\) with underscores.\n */\nexport function sanitizeToolCallId(toolCallId: string): string {\n return toolCallId.replace(/\\./g, \"_\").replace(/\\//g, \"_\").replace(/\\\\/g, \"_\");\n}\n\n/**\n * Format file content with line numbers (cat -n style).\n *\n * Chunks lines longer than MAX_LINE_LENGTH with continuation markers (e.g., 5.1, 5.2).\n *\n * @param content - File content as string or list of lines\n * @param startLine - Starting line number (default: 1)\n * @returns Formatted content with line numbers and continuation markers\n */\nexport function formatContentWithLineNumbers(\n content: string | string[],\n startLine: number = 1,\n): string {\n let lines: string[];\n if (typeof content === \"string\") {\n lines = content.split(\"\\n\");\n if (lines.length > 0 && lines[lines.length - 1] === \"\") {\n lines = lines.slice(0, -1);\n }\n } else {\n lines = content;\n }\n\n const resultLines: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNum = i + startLine;\n\n if (line.length <= MAX_LINE_LENGTH) {\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${line}`,\n );\n } else {\n // Split long line into chunks with continuation markers\n const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH);\n for (let chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) {\n const start = chunkIdx * MAX_LINE_LENGTH;\n const end = Math.min(start + MAX_LINE_LENGTH, line.length);\n const chunk = line.substring(start, end);\n if (chunkIdx === 0) {\n // First chunk: use normal line number\n resultLines.push(\n `${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n } else {\n // Continuation chunks: use decimal notation (e.g., 5.1, 5.2)\n const continuationMarker = `${lineNum}.${chunkIdx}`;\n resultLines.push(\n `${continuationMarker.padStart(LINE_NUMBER_WIDTH)}\\t${chunk}`,\n );\n }\n }\n }\n }\n\n return resultLines.join(\"\\n\");\n}\n\n/**\n * Check if content is empty and return warning message.\n *\n * @param content - Content to check\n * @returns Warning message if empty, null otherwise\n */\nexport function checkEmptyContent(content: string): string | null {\n if (!content || content.trim() === \"\") {\n return EMPTY_CONTENT_WARNING;\n }\n return null;\n}\n\n/**\n * Convert FileData to plain string content.\n *\n * @param fileData - FileData object with 'content' key\n * @returns Content as string with lines joined by newlines\n */\nexport function fileDataToString(fileData: FileData): string {\n return fileData.content.join(\"\\n\");\n}\n\n/**\n * Create a FileData object with timestamps.\n *\n * @param content - File content as string\n * @param createdAt - Optional creation timestamp (ISO format)\n * @returns FileData object with content and timestamps\n */\nexport function createFileData(content: string, createdAt?: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: createdAt || now,\n modified_at: now,\n };\n}\n\n/**\n * Update FileData with new content, preserving creation timestamp.\n *\n * @param fileData - Existing FileData object\n * @param content - New content as string\n * @returns Updated FileData object\n */\nexport function updateFileData(fileData: FileData, content: string): FileData {\n const lines = typeof content === \"string\" ? content.split(\"\\n\") : content;\n const now = new Date().toISOString();\n\n return {\n content: lines,\n created_at: fileData.created_at,\n modified_at: now,\n };\n}\n\n/**\n * Format file data for read response with line numbers.\n *\n * @param fileData - FileData object\n * @param offset - Line offset (0-indexed)\n * @param limit - Maximum number of lines\n * @returns Formatted content or error message\n */\nexport function formatReadResponse(\n fileData: FileData,\n offset: number,\n limit: number,\n): string {\n const content = fileDataToString(fileData);\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n}\n\n/**\n * Perform string replacement with occurrence validation.\n *\n * @param content - Original content\n * @param oldString - String to replace\n * @param newString - Replacement string\n * @param replaceAll - Whether to replace all occurrences\n * @returns Tuple of [new_content, occurrences] on success, or error message string\n */\nexport function performStringReplacement(\n content: string,\n oldString: string,\n newString: string,\n replaceAll: boolean,\n): [string, number] | string {\n // Use split to count occurrences (simpler than regex)\n const occurrences = content.split(oldString).length - 1;\n\n if (occurrences === 0) {\n return `Error: String not found in file: '${oldString}'`;\n }\n\n if (occurrences > 1 && !replaceAll) {\n return `Error: String '${oldString}' appears ${occurrences} times in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`;\n }\n\n // Python's str.replace() replaces ALL occurrences\n // Use split/join for consistent behavior\n const newContent = content.split(oldString).join(newString);\n\n return [newContent, occurrences];\n}\n\n/**\n * Truncate list or string result if it exceeds token limit (rough estimate: 4 chars/token).\n */\nexport function truncateIfTooLong(\n result: string[] | string,\n): string[] | string {\n if (Array.isArray(result)) {\n const totalChars = result.reduce((sum, item) => sum + item.length, 0);\n if (totalChars > TOOL_RESULT_TOKEN_LIMIT * 4) {\n const truncateAt = Math.floor(\n (result.length * TOOL_RESULT_TOKEN_LIMIT * 4) / totalChars,\n );\n return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE];\n }\n return result;\n }\n // string\n if (result.length > TOOL_RESULT_TOKEN_LIMIT * 4) {\n return (\n result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4) +\n \"\\n\" +\n TRUNCATION_GUIDANCE\n );\n }\n return result;\n}\n\n/**\n * Validate and normalize a path.\n *\n * @param path - Path to validate\n * @returns Normalized path starting with / and ending with /\n * @throws Error if path is invalid\n */\nexport function validatePath(path: string | null | undefined): string {\n const pathStr = path || \"/\";\n if (!pathStr || pathStr.trim() === \"\") {\n throw new Error(\"Path cannot be empty\");\n }\n\n let normalized = pathStr.startsWith(\"/\") ? pathStr : \"/\" + pathStr;\n\n if (!normalized.endsWith(\"/\")) {\n normalized += \"/\";\n }\n\n return normalized;\n}\n\n/**\n * Search files dict for paths matching glob pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Glob pattern (e.g., `*.py`, `**\\/*.ts`)\n * @param path - Base path to search from\n * @returns Newline-separated file paths, sorted by modification time (most recent first).\n * Returns \"No files found\" if no matches.\n *\n * @example\n * ```typescript\n * const files = {\"/src/main.py\": FileData(...), \"/test.py\": FileData(...)};\n * globSearchFiles(files, \"*.py\", \"/\");\n * // Returns: \"/test.py\\n/src/main.py\" (sorted by modified_at)\n * ```\n */\nexport function globSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string = \"/\",\n): string {\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No files found\";\n }\n\n const filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n // Respect standard glob semantics:\n // - Patterns without path separators (e.g., \"*.py\") match only in the current\n // directory (non-recursive) relative to `path`.\n // - Use \"**\" explicitly for recursive matching.\n const effectivePattern = pattern;\n\n const matches: Array<[string, string]> = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n let relative = filePath.substring(normalizedPath.length);\n if (relative.startsWith(\"/\")) {\n relative = relative.substring(1);\n }\n if (!relative) {\n const parts = filePath.split(\"/\");\n relative = parts[parts.length - 1] || \"\";\n }\n\n if (\n micromatch.isMatch(relative, effectivePattern, {\n dot: true,\n nobrace: false,\n })\n ) {\n matches.push([filePath, fileData.modified_at]);\n }\n }\n\n matches.sort((a, b) => b[1].localeCompare(a[1])); // Sort by modified_at descending\n\n if (matches.length === 0) {\n return \"No files found\";\n }\n\n return matches.map(([fp]) => fp).join(\"\\n\");\n}\n\n/**\n * Format grep search results based on output mode.\n *\n * @param results - Dictionary mapping file paths to list of [line_num, line_content] tuples\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted string output\n */\nexport function formatGrepResults(\n results: Record<string, Array<[number, string]>>,\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (outputMode === \"files_with_matches\") {\n return Object.keys(results).sort().join(\"\\n\");\n }\n if (outputMode === \"count\") {\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n const count = results[filePath].length;\n lines.push(`${filePath}: ${count}`);\n }\n return lines.join(\"\\n\");\n }\n // content mode\n const lines: string[] = [];\n for (const filePath of Object.keys(results).sort()) {\n lines.push(`${filePath}:`);\n for (const [lineNum, line] of results[filePath]) {\n lines.push(` ${lineNum}: ${line}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Search file contents for regex pattern.\n *\n * @param files - Dictionary of file paths to FileData\n * @param pattern - Regex pattern to search for\n * @param path - Base path to search from\n * @param glob - Optional glob pattern to filter files (e.g., \"*.py\")\n * @param outputMode - Output format - \"files_with_matches\", \"content\", or \"count\"\n * @returns Formatted search results. Returns \"No matches found\" if no results.\n *\n * @example\n * ```typescript\n * const files = {\"/file.py\": FileData({content: [\"import os\", \"print('hi')\"], ...})};\n * grepSearchFiles(files, \"import\", \"/\");\n * // Returns: \"/file.py\" (with output_mode=\"files_with_matches\")\n * ```\n */\nexport function grepSearchFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n outputMode: \"files_with_matches\" | \"content\" | \"count\" = \"files_with_matches\",\n): string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return \"No matches found\";\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n if (!results[filePath]) {\n results[filePath] = [];\n }\n results[filePath].push([lineNum, line]);\n }\n }\n }\n\n if (Object.keys(results).length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(results, outputMode);\n}\n\n// -------- Structured helpers for composition --------\n\n/**\n * Return structured grep matches from an in-memory files mapping.\n *\n * Returns a list of GrepMatch on success, or a string for invalid inputs\n * (e.g., invalid regex). We deliberately do not raise here to keep backends\n * non-throwing in tool contexts and preserve user-facing error messages.\n */\nexport function grepMatchesFromFiles(\n files: Record<string, FileData>,\n pattern: string,\n path: string | null = null,\n glob: string | null = null,\n): GrepMatch[] | string {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n let normalizedPath: string;\n try {\n normalizedPath = validatePath(path);\n } catch {\n return [];\n }\n\n let filtered = Object.fromEntries(\n Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)),\n );\n\n if (glob) {\n filtered = Object.fromEntries(\n Object.entries(filtered).filter(([fp]) =>\n micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }),\n ),\n );\n }\n\n const matches: GrepMatch[] = [];\n for (const [filePath, fileData] of Object.entries(filtered)) {\n for (let i = 0; i < fileData.content.length; i++) {\n const line = fileData.content[i];\n const lineNum = i + 1;\n if (regex.test(line)) {\n matches.push({ path: filePath, line: lineNum, text: line });\n }\n }\n }\n\n return matches;\n}\n\n/**\n * Group structured matches into the legacy dict form used by formatters.\n */\nexport function buildGrepResultsDict(\n matches: GrepMatch[],\n): Record<string, Array<[number, string]>> {\n const grouped: Record<string, Array<[number, string]>> = {};\n for (const m of matches) {\n if (!grouped[m.path]) {\n grouped[m.path] = [];\n }\n grouped[m.path].push([m.line, m.text]);\n }\n return grouped;\n}\n\n/**\n * Format structured grep matches using existing formatting logic.\n */\nexport function formatGrepMatches(\n matches: GrepMatch[],\n outputMode: \"files_with_matches\" | \"content\" | \"count\",\n): string {\n if (matches.length === 0) {\n return \"No matches found\";\n }\n return formatGrepResults(buildGrepResultsDict(matches), outputMode);\n}\n","/**\n * StateBackend: Store files in LangGraph agent state (ephemeral).\n */\n\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileInfo,\n GrepMatch,\n StateAndStore,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n createFileData,\n fileDataToString,\n formatReadResponse,\n globSearchFiles,\n grepMatchesFromFiles,\n performStringReplacement,\n updateFileData,\n} from \"./utils.js\";\n\n/**\n * Backend that stores files in agent state (ephemeral).\n *\n * Uses LangGraph's state management and checkpointing. Files persist within\n * a conversation thread but not across threads. State is automatically\n * checkpointed after each agent step.\n *\n * Special handling: Since LangGraph state must be updated via Command objects\n * (not direct mutation), operations return filesUpdate in WriteResult/EditResult\n * for the middleware to apply via Command.\n */\nexport class StateBackend implements BackendProtocol {\n private stateAndStore: StateAndStore;\n\n constructor(stateAndStore: StateAndStore) {\n this.stateAndStore = stateAndStore;\n }\n\n /**\n * Get files from current state.\n */\n private getFiles(): Record<string, FileData> {\n return (\n ((this.stateAndStore.state as any).files as Record<string, FileData>) ||\n {}\n );\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param path - Absolute path to directory\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n lsInfo(path: string): FileInfo[] {\n const files = this.getFiles();\n const infos: FileInfo[] = [];\n const subdirs = new Set<string>();\n\n // Normalize path to have trailing slash for proper prefix matching\n const normalizedPath = path.endsWith(\"/\") ? path : path + \"/\";\n\n for (const [k, fd] of Object.entries(files)) {\n // Check if file is in the specified directory or a subdirectory\n if (!k.startsWith(normalizedPath)) {\n continue;\n }\n\n // Get the relative path after the directory\n const relative = k.substring(normalizedPath.length);\n\n // If relative path contains '/', it's in a subdirectory\n if (relative.includes(\"/\")) {\n // Extract the immediate subdirectory name\n const subdirName = relative.split(\"/\")[0];\n subdirs.add(normalizedPath + subdirName + \"/\");\n continue;\n }\n\n // This is a file directly in the current directory\n const size = fd.content.join(\"\\n\").length;\n infos.push({\n path: k,\n is_dir: false,\n size: size,\n modified_at: fd.modified_at,\n });\n }\n\n // Add directories to the results\n for (const subdir of Array.from(subdirs).sort()) {\n infos.push({\n path: subdir,\n is_dir: true,\n size: 0,\n modified_at: \"\",\n });\n }\n\n infos.sort((a, b) => a.path.localeCompare(b.path));\n return infos;\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n read(filePath: string, offset: number = 0, limit: number = 2000): string {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return `Error: File '${filePath}' not found`;\n }\n\n return formatReadResponse(fileData, offset, limit);\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n readRaw(filePath: string): FileData {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) throw new Error(`File '${filePath}' not found`);\n return fileData;\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult with filesUpdate to update LangGraph state.\n */\n write(filePath: string, content: string): WriteResult {\n const files = this.getFiles();\n\n if (filePath in files) {\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n }\n\n const newFileData = createFileData(content);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n };\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult with filesUpdate and occurrences.\n */\n edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false,\n ): EditResult {\n const files = this.getFiles();\n const fileData = files[filePath];\n\n if (!fileData) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const content = fileDataToString(fileData);\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll,\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n const newFileData = updateFileData(fileData, newContent);\n return {\n path: filePath,\n filesUpdate: { [filePath]: newFileData },\n occurrences: occurrences,\n };\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n grepRaw(\n pattern: string,\n path: string = \"/\",\n glob: string | null = null,\n ): GrepMatch[] | string {\n const files = this.getFiles();\n return grepMatchesFromFiles(files, pattern, path, glob);\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n globInfo(pattern: string, path: string = \"/\"): FileInfo[] {\n const files = this.getFiles();\n const result = globSearchFiles(files, pattern, path);\n\n if (result === \"No files found\") {\n return [];\n }\n\n const paths = result.split(\"\\n\");\n const infos: FileInfo[] = [];\n for (const p of paths) {\n const fd = files[p];\n const size = fd ? fd.content.join(\"\\n\").length : 0;\n infos.push({\n path: p,\n is_dir: false,\n size: size,\n modified_at: fd?.modified_at || \"\",\n });\n }\n return infos;\n }\n}\n","import { createCodeEvalMiddleware, CreateCodeEvalMiddlewareParams } from \"../../middlewares/codeEvalMiddleware\";\nimport { createBrowserMiddleware, CreateBrowserMiddlewareParams } from \"../../middlewares/browserMiddleware\";\nimport { createSqlMiddleware, CreateSqlMiddlewareParams } from \"../../middlewares/sqlMiddleware\";\nimport { createSkillMiddleware, CreateSkillMiddlewareParams as CreateSkillMiddlewareParamsType } from \"../../middlewares/skillMiddleware\";\nimport { createFilesystemMiddleware, FilesystemMiddlewareOptions } from \"../../deep_agent_new/middleware/fs\";\nimport { MiddlewareConfig } from \"../types\";\nimport { BackendFactory } from \"../../deep_agent_new/backends/protocol.js\";\n\nexport function createCommonMiddlewares(\n middlewareConfigs: MiddlewareConfig[],\n filesystemBackend?: BackendFactory\n): any[] {\n const middlewares: any[] = [];\n const filesystemConfig = middlewareConfigs.find(m => m.type === \"filesystem\");\n\n if (filesystemConfig?.enabled && filesystemBackend) {\n const options: FilesystemMiddlewareOptions = { backend: filesystemBackend };\n middlewares.push(createFilesystemMiddleware(options));\n }\n\n for (const config of middlewareConfigs) {\n if (!config.enabled || config.type === \"filesystem\") continue;\n\n switch (config.type) {\n case \"code_eval\":\n middlewares.push(createCodeEvalMiddleware(config.config as CreateCodeEvalMiddlewareParams));\n break;\n case \"browser\":\n middlewares.push(createBrowserMiddleware(config.config as CreateBrowserMiddlewareParams));\n break;\n case \"sql\":\n middlewares.push(createSqlMiddleware(config.config as CreateSqlMiddlewareParams));\n break;\n case \"skill\":\n middlewares.push(createSkillMiddleware(config.config as CreateSkillMiddlewareParamsType));\n break;\n }\n }\n\n return middlewares;\n}\n","import {\n createAgent,\n humanInTheLoopMiddleware,\n anthropicPromptCachingMiddleware,\n summarizationMiddleware,\n type AgentMiddleware,\n type ReactAgent,\n type InterruptOnConfig,\n} from \"langchain\";\nimport type { StructuredTool } from \"@langchain/core/tools\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type {\n BaseCheckpointSaver,\n BaseStore,\n} from \"@langchain/langgraph-checkpoint\";\n\nimport {\n createFilesystemMiddleware,\n createSubAgentMiddleware,\n createPatchToolCallsMiddleware,\n type SubAgent,\n} from \"./middleware/index.js\";\nimport { StateBackend, type BackendProtocol } from \"./backends/index.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { AnnotationRoot } from \"@langchain/langgraph\";\nimport { CompiledSubAgent } from \"./middleware/subagents.js\";\nimport { todoListMiddleware } from \"./middleware/todos.js\";\nimport { createSkillMiddleware } from \"../middlewares/skillMiddleware.js\";\n\n/**\n * Configuration parameters for creating a Deep Agent\n * Matches Python's create_deep_agent parameters\n */\nexport interface CreateDeepAgentParams<\n ContextSchema extends\n | AnnotationRoot<any>\n | InteropZodObject = AnnotationRoot<any>\n> {\n /** The model to use (model name string or LanguageModelLike instance). Defaults to claude-sonnet-4-5-20250929 */\n model?: BaseLanguageModel | string;\n /** Tools the agent should have access to */\n tools?: StructuredTool[];\n /** Custom system prompt for the agent. This will be combined with the base agent prompt */\n systemPrompt?: string;\n /** Custom middleware to apply after standard middleware */\n middleware?: AgentMiddleware[];\n /** List of subagent specifications for task delegation */\n subagents?: (SubAgent | CompiledSubAgent)[];\n /** Structured output response format for the agent */\n responseFormat?: any; // ResponseFormat type is complex, using any for now\n /** Optional schema for context (not persisted between invocations) */\n contextSchema?: ContextSchema;\n /** Optional checkpointer for persisting agent state between runs */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** Optional store for persisting longterm memories */\n store?: BaseStore;\n /**\n * Optional backend for filesystem operations.\n * Can be either a backend instance or a factory function that creates one.\n * The factory receives a config object with state and store.\n */\n backend?:\n | BackendProtocol\n | ((config: { state: unknown; store?: BaseStore }) => Promise<BackendProtocol>);\n /** Optional interrupt configuration mapping tool names to interrupt configs */\n interruptOn?: Record<string, boolean | InterruptOnConfig>;\n /** The name of the agent */\n name?: string;\n\n skills?: string[];\n\n}\n\nconst BASE_PROMPT = `In order to complete the objective that the user asks of you, you have access to a number of standard tools.`;\n\n/**\n * Create a Deep Agent with middleware-based architecture.\n *\n * Matches Python's create_deep_agent function, using middleware for all features:\n * - Todo management (todoListMiddleware)\n * - Filesystem tools (createFilesystemMiddleware)\n * - Subagent delegation (createSubAgentMiddleware)\n * - Conversation summarization (summarizationMiddleware)\n * - Prompt caching (anthropicPromptCachingMiddleware)\n * - Tool call patching (createPatchToolCallsMiddleware)\n * - Human-in-the-loop (humanInTheLoopMiddleware) - optional\n *\n * @param params Configuration parameters for the agent\n * @returns ReactAgent instance ready for invocation\n */\nexport function createDeepAgent<\n ContextSchema extends\n | AnnotationRoot<any>\n | InteropZodObject = AnnotationRoot<any>\n>(\n params: CreateDeepAgentParams<ContextSchema> = {}\n): ReactAgent<any, any, ContextSchema, any> {\n const {\n model = \"claude-sonnet-4-5-20250929\",\n tools = [],\n systemPrompt,\n middleware: customMiddleware = [],\n subagents = [],\n responseFormat,\n contextSchema,\n checkpointer,\n store,\n backend,\n interruptOn,\n name,\n skills,\n } = params;\n\n // Combine system prompt with base prompt like Python implementation\n const finalSystemPrompt = systemPrompt\n ? `${systemPrompt}\\n\\n${BASE_PROMPT}`\n : BASE_PROMPT;\n\n // Create backend configuration for filesystem middleware\n // If no backend is provided, use a factory that creates a StateBackend\n const filesystemBackend = backend\n ? backend\n : async (config: { state: unknown; store?: BaseStore }) =>\n new StateBackend(config);\n\n const middleware: AgentMiddleware[] = [\n // Provides todo list management capabilities for tracking tasks\n todoListMiddleware(),\n // Enables filesystem operations and optional long-term memory storage\n createFilesystemMiddleware({ backend: filesystemBackend }),\n // Enables delegation to specialized subagents for complex tasks\n createSubAgentMiddleware({\n defaultModel: model,\n defaultTools: tools,\n defaultMiddleware: [\n // Subagent middleware: Todo list management\n todoListMiddleware(),\n // Subagent middleware: Filesystem operations\n createFilesystemMiddleware({\n backend: filesystemBackend,\n }),\n // Subagent middleware: Automatic conversation summarization when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Subagent middleware: Anthropic prompt caching for improved performance\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Subagent middleware: Patches tool calls for compatibility\n createPatchToolCallsMiddleware(),\n ],\n defaultInterruptOn: interruptOn,\n subagents,\n generalPurposeAgent: false,\n }),\n // Automatically summarizes conversation history when token limits are approached\n summarizationMiddleware({\n model,\n trigger: { tokens: 170_000 },\n keep: { messages: 6 },\n }),\n // Enables Anthropic prompt caching for improved performance and reduced costs\n anthropicPromptCachingMiddleware({\n unsupportedModelBehavior: \"ignore\",\n }),\n // Patches tool calls to ensure compatibility across different model providers\n createPatchToolCallsMiddleware()\n\n ];\n\n // Add human-in-the-loop middleware if interrupt config provided\n if (interruptOn) {\n middleware.push(humanInTheLoopMiddleware({ interruptOn }));\n }\n\n // Add custom middleware last (after all built-in middleware)\n middleware.push(...customMiddleware);\n\n return createAgent({\n model,\n systemPrompt: finalSystemPrompt,\n tools,\n middleware,\n responseFormat,\n contextSchema,\n checkpointer,\n store,\n name,\n });\n}\n","import { z } from \"zod/v3\";\nimport {\n createMiddleware,\n createAgent,\n AgentMiddleware,\n tool,\n ToolMessage,\n humanInTheLoopMiddleware,\n type InterruptOnConfig,\n type ReactAgent,\n StructuredTool,\n} from \"langchain\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { Runnable } from \"@langchain/core/runnables\";\nimport { HumanMessage } from \"@langchain/core/messages\";\nimport { AgentClient } from \"@agent_lattice\";\nimport { agentWorkerGraph } from \"../../agent_worker/agent_worker_graph\";\nexport type { AgentMiddleware };\n\n// Constants\nconst DEFAULT_SUBAGENT_PROMPT =\n \"In order to complete the objective that the user asks of you, you have access to a number of standard tools.\";\n\n// State keys that should be excluded when passing state to subagents\nconst EXCLUDED_STATE_KEYS = [\"messages\", \"todos\", \"jumpTo\"] as const;\n\nconst DEFAULT_GENERAL_PURPOSE_DESCRIPTION =\n \"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. This agent has access to all tools as the main agent.\";\n\n// Comprehensive task tool description from Python\nfunction getTaskToolDescription(subagentDescriptions: string[]): string {\n return `\nLaunch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.\n\nAvailable agent types and the tools they have access to:\n${subagentDescriptions.join(\"\\n\")}\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n## Usage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent.\n\n### Example usage of the general-purpose agent:\n\n<example_agent_descriptions>\n\"general-purpose\": use this agent for general purpose tasks, it has access to all tools as the main agent.\n</example_agent_descriptions>\n\n<example>\nUser: \"I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them.\"\nAssistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*\nAssistant: *Synthesizes the results of the three isolated research tasks and responds to the User*\n<commentary>\nResearch is a complex, multi-step task in it of itself.\nThe research of each individual player is not dependent on the research of the other players.\nThe assistant uses the task tool to break down the complex objective into three isolated tasks.\nEach research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result.\nThis means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other.\n</commentary>\n</example>\n\n<example>\nUser: \"Analyze a single large code repository for security vulnerabilities and generate a report.\"\nAssistant: *Launches a single \\`task\\` subagent for the repository analysis*\nAssistant: *Receives report and integrates results into final summary*\n<commentary>\nSubagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details.\nIf the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money.\n</commentary>\n</example>\n\n<example>\nUser: \"Schedule two meetings for me and prepare agendas for each.\"\nAssistant: *Calls the task tool in parallel to launch two \\`task\\` subagents (one per meeting) to prepare agendas*\nAssistant: *Returns final schedules and agendas*\n<commentary>\nTasks are simple individually, but subagents help silo agenda preparation.\nEach subagent only needs to worry about the agenda for one meeting.\n</commentary>\n</example>\n\n<example>\nUser: \"I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\"\nAssistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway*\n<commentary>\nThe assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.\nIt is better to just complete the task directly and NOT use the \\`task\\`tool.\n</commentary>\n</example>\n\n### Example usage with custom agents:\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\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\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 `.trim();\n}\n\nconst TASK_SYSTEM_PROMPT = `## \\`task\\` (subagent spawner)\n\nYou have access to a \\`task\\` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result.\n\nWhen to use the task tool:\n- When a task is complex and multi-step, and can be fully delegated in isolation\n- When a task is independent of other tasks and can run in parallel\n- When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread\n- When sandboxing improves reliability (e.g. code execution, structured searches, data formatting)\n- When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.)\n\nSubagent lifecycle:\n1. **Spawn** → Provide clear role, instructions, and expected output\n2. **Run** → The subagent completes the task autonomously\n3. **Return** → The subagent provides a single structured result\n4. **Reconcile** → Incorporate or synthesize the result into the main thread\n\nWhen NOT to use the task tool:\n- If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them)\n- If the task is trivial (a few tool calls or simple lookup)\n- If delegating does not reduce token usage, complexity, or context switching\n- If splitting would add latency without benefit\n\n## Important Task Tool Usage Notes to Remember\n- Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important.\n- Remember to use the \\`task\\` tool to silo independent tasks within a multi-part objective.\n- You should use the \\`task\\` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient.`;\n\n/**\n * Type definitions for pre-compiled agents.\n */\nexport interface CompiledSubAgent {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The agent instance */\n runnable: AgentClient | Runnable;\n}\n\n/**\n * Type definitions for subagents\n */\nexport interface SubAgent {\n /** The name of the agent */\n name: string;\n /** The description of the agent */\n description: string;\n /** The system prompt to use for the agent */\n systemPrompt: string;\n /** The tools to use for the agent (tool instances, not names). Defaults to defaultTools */\n tools?: StructuredTool[];\n /** The model for the agent. Defaults to default_model */\n model?: LanguageModelLike | string;\n /** Additional middleware to append after default_middleware */\n middleware?: AgentMiddleware[];\n /** The tool configs to use for the agent */\n interruptOn?: Record<string, boolean | InterruptOnConfig>;\n}\n\n/**\n * Filter state to exclude certain keys when passing to subagents\n */\nfunction filterStateForSubagent(\n state: Record<string, unknown>\n): Record<string, unknown> {\n const filtered: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(state)) {\n if (!EXCLUDED_STATE_KEYS.includes(key as never)) {\n filtered[key] = value;\n }\n }\n return filtered;\n}\n\n/**\n * Create Command with filtered state update from subagent result\n */\nfunction returnCommandWithStateUpdate(\n result: Record<string, unknown>,\n toolCallId: string\n): Command {\n const stateUpdate = filterStateForSubagent(result);\n const messages = result.messages as Array<{ content: string }>;\n const lastMessage = messages?.[messages.length - 1];\n\n return new Command({\n update: {\n ...stateUpdate,\n messages: [\n new ToolMessage({\n content: lastMessage?.content || \"Task completed\",\n tool_call_id: toolCallId,\n name: \"task\",\n }),\n ],\n },\n });\n}\n\n/**\n * Create subagent instances from specifications\n */\nfunction getSubagents(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n}): {\n agents: Record<string, ReactAgent<any, any, any, any> | Runnable>;\n descriptions: string[];\n} {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n } = options;\n\n const defaultSubagentMiddleware = defaultMiddleware || [];\n const agents: Record<string, ReactAgent<any, any, any, any> | Runnable> = {};\n const subagentDescriptions: string[] = [];\n\n // Create general-purpose agent if enabled\n if (generalPurposeAgent) {\n const generalPurposeMiddleware = [...defaultSubagentMiddleware];\n if (defaultInterruptOn) {\n generalPurposeMiddleware.push(\n humanInTheLoopMiddleware({ interruptOn: defaultInterruptOn })\n );\n }\n\n const generalPurposeSubagent = createAgent({\n model: defaultModel,\n systemPrompt: DEFAULT_SUBAGENT_PROMPT,\n tools: defaultTools as any,\n middleware: generalPurposeMiddleware,\n });\n\n agents[\"general-purpose\"] = generalPurposeSubagent;\n subagentDescriptions.push(\n `- general-purpose: ${DEFAULT_GENERAL_PURPOSE_DESCRIPTION}`\n );\n }\n\n // Process custom subagents\n for (const agentParams of subagents) {\n subagentDescriptions.push(\n `- ${agentParams.name}: ${agentParams.description}`\n );\n\n if (\"runnable\" in agentParams) {\n agents[agentParams.name] = agentParams.runnable;\n } else {\n const middleware = agentParams.middleware\n ? [...defaultSubagentMiddleware, ...agentParams.middleware]\n : [...defaultSubagentMiddleware];\n\n const interruptOn = agentParams.interruptOn || defaultInterruptOn;\n if (interruptOn)\n middleware.push(humanInTheLoopMiddleware({ interruptOn }));\n\n agents[agentParams.name] = createAgent({\n model: agentParams.model ?? defaultModel,\n systemPrompt: agentParams.systemPrompt,\n tools: agentParams.tools ?? defaultTools,\n middleware,\n });\n }\n }\n\n return { agents, descriptions: subagentDescriptions };\n}\n\n/**\n * Create the task tool for invoking subagents\n */\nfunction createTaskTool(options: {\n defaultModel: LanguageModelLike | string;\n defaultTools: StructuredTool[];\n defaultMiddleware: AgentMiddleware[] | null;\n defaultInterruptOn: Record<string, boolean | InterruptOnConfig> | null;\n subagents: (SubAgent | CompiledSubAgent)[];\n generalPurposeAgent: boolean;\n taskDescription: string | null;\n}) {\n const {\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n } = options;\n\n const { agents: subagentGraphs, descriptions: subagentDescriptions } =\n getSubagents({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n });\n\n const finalTaskDescription = taskDescription\n ? taskDescription\n : getTaskToolDescription(subagentDescriptions);\n\n return tool(\n async (\n input: { description: string; subagent_type: string },\n config\n ): Promise<Command | string> => {\n const { description, subagent_type } = input;\n\n // Validate subagent type\n if (!(subagent_type in subagentGraphs)) {\n const allowedTypes = Object.keys(subagentGraphs)\n .map((k) => `\\`${k}\\``)\n .join(\", \");\n throw new Error(\n `Error: invoked agent of type ${subagent_type}, the only allowed types are ${allowedTypes}`\n );\n }\n\n const subagent = subagentGraphs[subagent_type];\n\n // Get current state and filter it for subagent\n const currentState = getCurrentTaskInput<Record<string, unknown>>();\n const subagentState = filterStateForSubagent(currentState);\n subagentState.messages = [new HumanMessage({ content: description })];\n\n const subagent_thread_id =\n config.configurable?.thread_id +\n \"____\" +\n subagent_type +\n \"_\" +\n config.toolCall.id;\n console.log(subagent_thread_id);\n // Invoke the subagent\n // const result = (await subagent.invoke(subagentState, {\n // configurable: { thread_id: subagent_thread_id },\n // })) as Record<string, unknown>;\n\n const workerResult = await agentWorkerGraph.invoke({\n assistant_id: subagent_type,\n thread_id: subagent_thread_id,\n input: { ...subagentState, message: description },\n });\n\n const result = workerResult.finalState?.values as Record<string, unknown>;\n\n // console.log(\"workerResult\", workerResult);\n\n // const result = (await AgentManager.getInstance().callAgentInQueue(\n // {\n // assistant_id: subagent_type,\n // thread_id: subagent_type + \"_\" + config.toolCall.id,\n // input: { ...subagentState, message: description },\n // },\n // true\n // )) as any;\n\n // Return command with filtered state update\n if (!config.toolCall?.id) {\n throw new Error(\"Tool call ID is required for subagent invocation\");\n }\n\n return returnCommandWithStateUpdate(result, config.toolCall.id);\n },\n {\n name: \"task\",\n description: finalTaskDescription,\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: ${Object.keys(\n subagentGraphs\n ).join(\", \")}`\n ),\n }),\n }\n );\n}\n\n/**\n * Options for creating subagent middleware\n */\nexport interface SubAgentMiddlewareOptions {\n /** The model to use for subagents */\n defaultModel: LanguageModelLike | string;\n /** The tools to use for the default general-purpose subagent */\n defaultTools?: StructuredTool[];\n /** Default middleware to apply to all subagents */\n defaultMiddleware?: AgentMiddleware[] | null;\n /** The tool configs for the default general-purpose subagent */\n defaultInterruptOn?: Record<string, boolean | InterruptOnConfig> | null;\n /** A list of additional subagents to provide to the agent */\n subagents?: (SubAgent | CompiledSubAgent)[];\n /** Full system prompt override */\n systemPrompt?: string | null;\n /** Whether to include the general-purpose agent */\n generalPurposeAgent?: boolean;\n /** Custom description for the task tool */\n taskDescription?: string | null;\n}\n\n/**\n * Create subagent middleware with task tool\n */\nexport function createSubAgentMiddleware(\n options: SubAgentMiddlewareOptions\n): AgentMiddleware {\n const {\n defaultModel,\n defaultTools = [],\n defaultMiddleware = null,\n defaultInterruptOn = null,\n subagents = [],\n systemPrompt = TASK_SYSTEM_PROMPT,\n generalPurposeAgent = true,\n taskDescription = null,\n } = options;\n\n const taskTool = createTaskTool({\n defaultModel,\n defaultTools,\n defaultMiddleware,\n defaultInterruptOn,\n subagents,\n generalPurposeAgent,\n taskDescription,\n });\n\n return createMiddleware({\n name: \"subAgentMiddleware\",\n tools: [taskTool],\n wrapModelCall: async (request, handler) => {\n if (systemPrompt !== null) {\n const currentPrompt = request.systemPrompt || \"\";\n const newPrompt = currentPrompt\n ? `${currentPrompt}\\n\\n${systemPrompt}`\n : systemPrompt;\n\n return handler({\n ...request,\n systemPrompt: newPrompt,\n });\n }\n return handler(request);\n },\n });\n}\n","import {\n StateGraph,\n END,\n START,\n interrupt,\n Annotation,\n} from \"@langchain/langgraph\";\nimport { AgentManager } from \"../services/AgentManager\";\n\n/**\n * State schema for the agent worker graph\n */\nconst AgentWorkerState = Annotation.Root({\n // Input parameters\n assistant_id: Annotation<string>({\n reducer: (x: string, y: string) => y ?? x,\n default: () => \"\",\n }),\n thread_id: Annotation<string>({\n reducer: (x: string, y: string) => y ?? x,\n default: () => \"\",\n }),\n input: Annotation<Record<string, unknown>>({\n reducer: (x: Record<string, unknown>, y: Record<string, unknown>) => y ?? x,\n default: () => ({}),\n }),\n command2: Annotation<any>({\n reducer: (x: any, y: any) => y ?? x,\n default: () => undefined,\n }),\n\n // Execution result\n result: Annotation<any>({\n reducer: (x: any, y: any) => y ?? x,\n default: () => undefined,\n }),\n // Interrupt data\n interruptValue: Annotation<any>({\n reducer: (x: any, y: any) => y ?? x,\n default: () => undefined,\n }),\n // Final state to return\n finalState: Annotation<Record<string, unknown> | undefined>({\n reducer: (\n x: Record<string, unknown> | undefined,\n y: Record<string, unknown> | undefined\n ) => y ?? x,\n default: () => undefined,\n }),\n});\n\ntype AgentWorkerStateType = typeof AgentWorkerState.State;\n\n/**\n * Execute node: Calls AgentManager.callAgentInQueue\n * Uses command parameter if available (after interrupt response), otherwise uses input\n */\nasync function executeNode(\n state: AgentWorkerStateType\n): Promise<Partial<AgentWorkerStateType>> {\n const { assistant_id, thread_id, input, command2 } = state;\n\n // If command exists (after interrupt response), use command; otherwise use input\n const callParams: {\n assistant_id: string;\n thread_id: string;\n input?: any;\n command?: any;\n } = {\n assistant_id,\n thread_id,\n input,\n command: command2,\n };\n\n const result = (await AgentManager.getInstance().callAgentInQueue(\n callParams,\n true\n )) as any;\n\n return {\n result,\n };\n}\n\n/**\n * Interrupt node: Throws interrupt and waits for response\n */\nasync function interruptNode(\n state: AgentWorkerStateType\n): Promise<Partial<AgentWorkerStateType>> {\n const { result } = state;\n\n // Extract interrupt value from result.tasks[0].interrupts[0].value\n const interruptValue = result?.tasks?.[0]?.interrupts?.[0]?.value;\n\n if (!interruptValue) {\n throw new Error(\n \"Interrupt node called but no interrupt value found in result\"\n );\n }\n\n // Throw interrupt and wait for response\n const response = await interrupt(interruptValue);\n\n // After response, save the response as command for the next executeNode call\n return {\n command2: {\n resume: response,\n },\n };\n}\n\n/**\n * Conditional routing function\n * Routes to interrupt node if result.tasks has values, otherwise ends\n */\nfunction shouldInterrupt(state: AgentWorkerStateType): \"interrupt\" | \"end\" {\n const { result } = state;\n\n // Check if result.tasks exists and has values\n if (result?.tasks && Array.isArray(result.tasks) && result.tasks.length > 0) {\n // Check if there are interrupts\n if (result.tasks[0]?.interrupts && result.tasks[0].interrupts.length > 0) {\n return \"interrupt\";\n }\n }\n\n return \"end\";\n}\n\n/**\n * End node: Returns the final state and clears intermediate process states\n */\nfunction endNode(state: AgentWorkerStateType): Partial<AgentWorkerStateType> {\n // Save final state from result or input\n const finalState = state.result;\n\n // Clear intermediate process states\n return {\n finalState,\n // Clear intermediate states\n result: undefined,\n interruptValue: undefined,\n command2: undefined,\n };\n}\n\n/**\n * Create the agent worker graph\n */\nexport function createAgentWorkerGraph() {\n const workflow = new StateGraph(AgentWorkerState);\n\n // Add nodes\n workflow.addNode(\"execute\", executeNode);\n workflow.addNode(\"interrupt\", interruptNode);\n workflow.addNode(\"end\", endNode);\n\n // Set entry point: connect START to execute node\n (workflow as any).setEntryPoint(\"execute\");\n\n // Add conditional edge from execute node\n (workflow as any).addConditionalEdges(\"execute\", shouldInterrupt, {\n interrupt: \"interrupt\",\n end: \"end\",\n });\n\n // After interrupt, return to execute node\n (workflow as any).addEdge(\"interrupt\", \"execute\");\n\n // End node leads to END\n (workflow as any).addEdge(\"end\", END);\n\n return workflow.compile();\n}\nexport const agentWorkerGraph = createAgentWorkerGraph();\n","// Agent task event names\nexport const AGENT_TASK_EVENT = \"agent:execute\";\n\n\n\n","import { EventEmitter } from \"events\";\nimport { queueLatticeManager } from \"../queue_lattice\";\n\n/**\n * Event bus service\n * Used for event publishing and subscription between internal system components\n */\nclass EventBus {\n private emitter: EventEmitter;\n private defaultQueueKey: string = \"default\";\n\n constructor() {\n this.emitter = new EventEmitter();\n // Set maximum listener count to avoid memory leak warnings\n this.emitter.setMaxListeners(100);\n }\n\n /**\n * Set the default queue key for queue operations\n * @param queueKey Queue key name\n */\n setDefaultQueueKey(queueKey: string): void {\n this.defaultQueueKey = queueKey;\n }\n\n /**\n * Publish event\n * @param eventName Event name\n * @param data Event data\n * @param useQueue Whether to use queue for publishing\n */\n publish(eventName: string, data: any, useQueue: boolean = false): void {\n if (useQueue) {\n // Push to queue if queue service is available\n if (queueLatticeManager.hasLattice(this.defaultQueueKey)) {\n const queue = queueLatticeManager.getQueueLattice(this.defaultQueueKey);\n queue.push(data).catch((error) => {\n console.error(\"Failed to push event to queue:\", error);\n });\n } else {\n console.warn(\n `Queue \"${this.defaultQueueKey}\" not found. Event will not be queued.`\n );\n }\n } else {\n this.emitter.emit(eventName, data);\n }\n }\n\n /**\n * Subscribe to event\n * @param eventName Event name\n * @param callback Callback function\n */\n subscribe(eventName: string, callback: (data: any) => void): void {\n this.emitter.on(eventName, callback);\n }\n\n /**\n * Unsubscribe from event\n * @param eventName Event name\n * @param callback Callback function\n */\n unsubscribe(eventName: string, callback: (data: any) => void): void {\n this.emitter.off(eventName, callback);\n }\n\n /**\n * Subscribe to event once\n * @param eventName Event name\n * @param callback Callback function\n */\n subscribeOnce(eventName: string, callback: (data: any) => void): void {\n this.emitter.once(eventName, callback);\n }\n}\n\n// Create singleton instance\nconst eventBus = new EventBus();\n\nexport default eventBus;\nexport { eventBus };\n","/**\n * QueueLatticeManager\n *\n * Queue Lattice manager for registering and managing queue services\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n QueueLatticeProtocol,\n QueueConfig,\n QueueType,\n QueueClient,\n} from \"@axiom-lattice/protocols\";\nimport { MemoryQueueClient } from \"./MemoryQueueClient\";\n\n/**\n * Queue Lattice interface\n */\nexport interface QueueLattice extends QueueLatticeProtocol {\n key: string;\n config: QueueConfig;\n client: QueueLatticeProtocol[\"client\"];\n}\n\n/**\n * QueueLatticeManager - Singleton queue Lattice manager\n * Responsible for registering and managing various queue service Lattices\n */\nexport class QueueLatticeManager extends BaseLatticeManager<QueueLattice> {\n private static _instance: QueueLatticeManager;\n\n /**\n * Get QueueLatticeManager singleton instance\n */\n public static getInstance(): QueueLatticeManager {\n if (!QueueLatticeManager._instance) {\n QueueLatticeManager._instance = new QueueLatticeManager();\n }\n return QueueLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"queues\";\n }\n\n /**\n * Register queue Lattice\n * @param key Lattice key name\n * @param config Queue configuration\n * @param client Optional queue client. If not provided, will create based on config type.\n * For REDIS type, client must be provided (use @axiom-lattice/queue-redis).\n */\n public registerLattice(\n key: string,\n config: QueueConfig,\n client?: QueueClient\n ): void {\n // Create client based on queue type if not provided\n let queueClient: QueueLatticeProtocol[\"client\"];\n\n if (client) {\n // Use provided client\n queueClient = client;\n } else {\n const queueName = config.queueName || process.env.QUEUE_NAME || \"tasks\";\n\n if (config.type === QueueType.REDIS) {\n throw new Error(\n `Redis queue client must be provided. Please install @axiom-lattice/queue-redis and pass the client to registerLattice. Example: registerLattice(key, config, new RedisQueueClient(queueName, options))`\n );\n } else {\n // Default to memory\n queueClient = new MemoryQueueClient(queueName);\n }\n }\n\n // Create queue Lattice object\n const queueLattice: QueueLattice = {\n key,\n config,\n client: queueClient,\n push: async (item: any) => {\n return queueClient.push(item);\n },\n pop: async () => {\n return queueClient.pop();\n },\n createQueue: queueClient.createQueue\n ? async () => {\n return queueClient.createQueue!();\n }\n : undefined,\n };\n\n // Call base class register method\n this.register(key, queueLattice);\n }\n\n /**\n * Get QueueLattice\n * @param key Lattice key name\n */\n public getQueueLattice(key: string): QueueLattice {\n const queueLattice = this.get(key);\n if (!queueLattice) {\n throw new Error(`QueueLattice ${key} not found`);\n }\n return queueLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): QueueLattice[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const queueLatticeManager = QueueLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerQueueLattice = (\n key: string,\n config: QueueConfig,\n client?: QueueClient\n) => queueLatticeManager.registerLattice(key, config, client);\n\nexport const getQueueLattice = (key: string) =>\n queueLatticeManager.getQueueLattice(key);\n\n","/**\n * MemoryQueueClient\n *\n * In-memory queue service implementation\n */\n\nimport { QueueClient, QueueResult } from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory storage for queues: Map<queue_name, message[]>\n * Using Map to support multiple queues (e.g., per tenant)\n */\nconst queues = new Map<string, any[]>();\n\n/**\n * Initialize queue if it doesn't exist\n */\nconst ensureQueue = (queueName: string): void => {\n if (!queues.has(queueName)) {\n queues.set(queueName, []);\n }\n};\n\n/**\n * Memory-based queue client implementation\n */\nexport class MemoryQueueClient implements QueueClient {\n private queueName: string;\n\n constructor(queueName: string = \"tasks\") {\n this.queueName = queueName;\n ensureQueue(this.queueName);\n }\n\n /**\n * Enqueue message (equivalent to lPush - push to left/beginning)\n */\n async push(item: any): Promise<QueueResult<number>> {\n try {\n ensureQueue(this.queueName);\n const queue = queues.get(this.queueName)!;\n\n // lPush behavior: add to the beginning of the array\n queue.unshift(item);\n\n const result = queue.length;\n console.log(\"lPush (memory)\", result);\n return { data: result, error: null };\n } catch (error) {\n console.error(error);\n return { data: null, error };\n }\n }\n\n /**\n * Dequeue message (equivalent to rPop - pop from right/end)\n */\n async pop(): Promise<QueueResult<any>> {\n try {\n ensureQueue(this.queueName);\n const queue = queues.get(this.queueName)!;\n\n // rPop behavior: remove from the end of the array\n // This creates FIFO behavior when combined with lPush (unshift + pop = FIFO)\n const message = queue.pop();\n\n if (message) {\n return { data: message, error: null };\n }\n return { data: null, error: null };\n } catch (error) {\n console.error(error);\n return { data: null, error };\n }\n }\n\n /**\n * Create queue (initialize in memory)\n */\n async createQueue(): Promise<{\n success: boolean;\n queue_name?: string;\n error?: any;\n }> {\n try {\n ensureQueue(this.queueName);\n const queue = queues.get(this.queueName)!;\n const exists = queue !== undefined;\n return { success: true, queue_name: this.queueName };\n } catch (error) {\n console.error(error);\n return { success: false, error };\n }\n }\n}\n\n\n\n","import { AGENT_TASK_EVENT } from \"../constants/agent_task_types\";\nimport eventBus from \"./event_bus\";\n\nexport class AgentManager {\n private static instance: AgentManager;\n private constructor() {}\n private agents: { name: string; agent: any }[] = [];\n\n public static getInstance(): AgentManager {\n if (!AgentManager.instance) {\n AgentManager.instance = new AgentManager();\n }\n return AgentManager.instance;\n }\n\n callAgentInQueue(\n queue: {\n assistant_id: string;\n input?: any;\n thread_id: string;\n command?: any;\n \"x-tenant-id\"?: string;\n },\n return_agent_state?: boolean\n ) {\n return new Promise((resolve, reject) => {\n const callback_event = `${queue.assistant_id}::${queue.thread_id}`;\n if (return_agent_state) {\n eventBus.subscribeOnce(callback_event, (data) => {\n if (data.success) {\n // console.log(\"AgentManager callAgentInQueue success\", data);\n resolve(data.state);\n } else {\n // console.log(\"AgentManager callAgentInQueue error\", data);\n reject(data.error);\n }\n });\n }\n\n try {\n eventBus.publish(\n AGENT_TASK_EVENT,\n {\n ...queue,\n callback_event,\n },\n true\n );\n // without return_agent_state, resolve the promise\n !return_agent_state &&\n resolve({ callback_event_id: callback_event, success: true });\n } catch (error) {\n // without return_agent_state, reject the promise\n !return_agent_state &&\n reject({\n callback_event_id: callback_event,\n success: false,\n error: error,\n });\n }\n });\n }\n}\n","import {\n createMiddleware,\n AgentMiddleware,\n ToolMessage,\n AIMessage,\n} from \"langchain\";\nimport { RemoveMessage } from \"@langchain/core/messages\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\n\n/**\n * Create middleware that patches dangling tool calls in the messages history.\n *\n * When an AI message contains tool_calls but subsequent messages don't include\n * the corresponding ToolMessage responses, this middleware adds synthetic\n * ToolMessages saying the tool call was cancelled.\n *\n * @returns AgentMiddleware that patches dangling tool calls\n *\n * @example\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { createPatchToolCallsMiddleware } from \"./middleware/patch_tool_calls\";\n *\n * const agent = createAgent({\n * model: \"claude-sonnet-4-5-20250929\",\n * middleware: [createPatchToolCallsMiddleware()],\n * });\n * ```\n */\nexport function createPatchToolCallsMiddleware(): AgentMiddleware {\n return createMiddleware({\n name: \"patchToolCallsMiddleware\",\n beforeAgent: async (state) => {\n const messages = state.messages;\n\n if (!messages || messages.length === 0) {\n return;\n }\n\n const patchedMessages: any[] = [];\n\n // Iterate over the messages and add any dangling tool calls\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n patchedMessages.push(msg);\n\n // Check if this is an AI message with tool calls\n if (AIMessage.isInstance(msg) && msg.tool_calls != null) {\n for (const toolCall of msg.tool_calls) {\n // Look for a corresponding ToolMessage in the messages after this one\n const correspondingToolMsg = messages\n .slice(i)\n .find(\n (m: any) =>\n ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id\n );\n\n if (!correspondingToolMsg) {\n // We have a dangling tool call which needs a ToolMessage\n const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`;\n patchedMessages.push(\n new ToolMessage({\n content: toolMsg,\n name: toolCall.name,\n tool_call_id: toolCall.id!,\n })\n );\n }\n }\n }\n }\n\n // Return state update with RemoveMessage followed by patched messages\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n ...patchedMessages,\n ],\n };\n },\n });\n}\n","/**\n * FilesystemBackend: Read and write files directly from the filesystem.\n *\n * Security and search upgrades:\n * - Secure path resolution with root containment when in virtual_mode (sandboxed to cwd)\n * - Prevent symlink-following on file I/O using O_NOFOLLOW when available\n * - Ripgrep-powered grep with JSON parsing, plus regex fallback\n * and optional glob include filtering, while preserving virtual path behavior\n */\n\nimport * as fs from \"fs/promises\";\nimport * as fsSync from \"fs\";\nimport * as path from \"path\";\nimport { spawn } from \"child_process\";\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\nimport type {\n BackendProtocol,\n EditResult,\n FileData,\n FileInfo,\n GrepMatch,\n WriteResult,\n} from \"./protocol.js\";\nimport {\n checkEmptyContent,\n formatContentWithLineNumbers,\n performStringReplacement,\n} from \"./utils.js\";\n\nconst SUPPORTS_NOFOLLOW = fsSync.constants.O_NOFOLLOW !== undefined;\n\n/**\n * Backend that reads and writes files directly from the filesystem.\n *\n * Files are accessed using their actual filesystem paths. Relative paths are\n * resolved relative to the current working directory. Content is read/written\n * as plain text, and metadata (timestamps) are derived from filesystem stats.\n */\nexport class FilesystemBackend implements BackendProtocol {\n private cwd: string;\n private virtualMode: boolean;\n private maxFileSizeBytes: number;\n\n constructor(\n options: {\n rootDir?: string;\n virtualMode?: boolean;\n maxFileSizeMb?: number;\n } = {}\n ) {\n const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options;\n this.cwd = rootDir ? path.resolve(rootDir) : process.cwd();\n this.virtualMode = virtualMode;\n this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024;\n }\n\n /**\n * Resolve a file path with security checks.\n *\n * When virtualMode=true, treat incoming paths as virtual absolute paths under\n * this.cwd, disallow traversal (.., ~) and ensure resolved path stays within root.\n * When virtualMode=false, preserve legacy behavior: absolute paths are allowed\n * as-is; relative paths resolve under cwd.\n *\n * @param key - File path (absolute, relative, or virtual when virtualMode=true)\n * @returns Resolved absolute path string\n * @throws Error if path traversal detected or path outside root\n */\n private resolvePath(key: string): string {\n if (this.virtualMode) {\n const vpath = key.startsWith(\"/\") ? key : \"/\" + key;\n if (vpath.includes(\"..\") || vpath.startsWith(\"~\")) {\n throw new Error(\"Path traversal not allowed\");\n }\n const full = path.resolve(this.cwd, vpath.substring(1));\n const relative = path.relative(this.cwd, full);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Path: ${full} outside root directory: ${this.cwd}`);\n }\n return full;\n }\n\n if (path.isAbsolute(key)) {\n return key;\n }\n return path.resolve(this.cwd, key);\n }\n\n /**\n * List files and directories in the specified directory (non-recursive).\n *\n * @param dirPath - Absolute directory path to list files from\n * @returns List of FileInfo objects for files and directories directly in the directory.\n * Directories have a trailing / in their path and is_dir=true.\n */\n async lsInfo(dirPath: string): Promise<FileInfo[]> {\n try {\n const resolvedPath = this.resolvePath(dirPath);\n const stat = await fs.stat(resolvedPath);\n\n if (!stat.isDirectory()) {\n return [];\n }\n\n const entries = await fs.readdir(resolvedPath, { withFileTypes: true });\n const results: FileInfo[] = [];\n\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n\n for (const entry of entries) {\n const fullPath = path.join(resolvedPath, entry.name);\n\n try {\n const entryStat = await fs.stat(fullPath);\n const isFile = entryStat.isFile();\n const isDir = entryStat.isDirectory();\n\n if (!this.virtualMode) {\n // Non-virtual mode: use absolute paths\n if (isFile) {\n results.push({\n path: fullPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: fullPath + path.sep,\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n } else {\n let relativePath: string;\n if (fullPath.startsWith(cwdStr)) {\n relativePath = fullPath.substring(cwdStr.length);\n } else if (fullPath.startsWith(this.cwd)) {\n relativePath = fullPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = fullPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virtPath = \"/\" + relativePath;\n\n if (isFile) {\n results.push({\n path: virtPath,\n is_dir: false,\n size: entryStat.size,\n modified_at: entryStat.mtime.toISOString(),\n });\n } else if (isDir) {\n results.push({\n path: virtPath + \"/\",\n is_dir: true,\n size: 0,\n modified_at: entryStat.mtime.toISOString(),\n });\n }\n }\n } catch {\n // Skip entries we can't stat\n continue;\n }\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n } catch (e: any) {\n console.error(`Error listing files in ${dirPath}:`, e);\n return [];\n }\n }\n\n /**\n * Read file content with line numbers.\n *\n * @param filePath - Absolute or relative file path\n * @param offset - Line offset to start reading from (0-indexed)\n * @param limit - Maximum number of lines to read\n * @returns Formatted file content with line numbers, or error message\n */\n async read(\n filePath: string,\n offset: number = 0,\n limit: number = 2000\n ): Promise<string> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return `Error: Symlinks are not allowed: ${filePath}`;\n }\n if (!stat.isFile()) {\n return `Error: File '${filePath}' not found`;\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const emptyMsg = checkEmptyContent(content);\n if (emptyMsg) {\n return emptyMsg;\n }\n\n const lines = content.split(\"\\n\");\n const startIdx = offset;\n const endIdx = Math.min(startIdx + limit, lines.length);\n\n if (startIdx >= lines.length) {\n return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`;\n }\n\n const selectedLines = lines.slice(startIdx, endIdx);\n return formatContentWithLineNumbers(selectedLines, startIdx + 1);\n } catch (e: any) {\n return `Error reading file '${filePath}': ${e.message}`;\n }\n }\n\n /**\n * Read file content as raw FileData.\n *\n * @param filePath - Absolute file path\n * @returns Raw file content as FileData\n */\n async readRaw(filePath: string): Promise<FileData> {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n let stat: fsSync.Stats;\n\n if (SUPPORTS_NOFOLLOW) {\n stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) throw new Error(`File '${filePath}' not found`);\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n throw new Error(`Symlinks are not allowed: ${filePath}`);\n }\n if (!stat.isFile()) throw new Error(`File '${filePath}' not found`);\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n return {\n content: content.split(\"\\n\"),\n created_at: stat.ctime.toISOString(),\n modified_at: stat.mtime.toISOString(),\n };\n }\n\n /**\n * Create a new file with content.\n * Returns WriteResult. External storage sets filesUpdate=null.\n */\n async write(filePath: string, content: string): Promise<WriteResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n try {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return {\n error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.`,\n };\n }\n return {\n error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`,\n };\n } catch {\n // File doesn't exist, good to proceed\n }\n\n await fs.mkdir(path.dirname(resolvedPath), { recursive: true });\n\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_CREAT |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags, 0o644);\n try {\n await fd.writeFile(content, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, content, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null };\n } catch (e: any) {\n return { error: `Error writing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Edit a file by replacing string occurrences.\n * Returns EditResult. External storage sets filesUpdate=null.\n */\n async edit(\n filePath: string,\n oldString: string,\n newString: string,\n replaceAll: boolean = false\n ): Promise<EditResult> {\n try {\n const resolvedPath = this.resolvePath(filePath);\n\n let content: string;\n\n if (SUPPORTS_NOFOLLOW) {\n const stat = await fs.stat(resolvedPath);\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n\n const fd = await fs.open(\n resolvedPath,\n fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW\n );\n try {\n content = await fd.readFile({ encoding: \"utf-8\" });\n } finally {\n await fd.close();\n }\n } else {\n const stat = await fs.lstat(resolvedPath);\n if (stat.isSymbolicLink()) {\n return { error: `Error: Symlinks are not allowed: ${filePath}` };\n }\n if (!stat.isFile()) {\n return { error: `Error: File '${filePath}' not found` };\n }\n content = await fs.readFile(resolvedPath, \"utf-8\");\n }\n\n const result = performStringReplacement(\n content,\n oldString,\n newString,\n replaceAll\n );\n\n if (typeof result === \"string\") {\n return { error: result };\n }\n\n const [newContent, occurrences] = result;\n\n // Write securely\n if (SUPPORTS_NOFOLLOW) {\n const flags =\n fsSync.constants.O_WRONLY |\n fsSync.constants.O_TRUNC |\n fsSync.constants.O_NOFOLLOW;\n\n const fd = await fs.open(resolvedPath, flags);\n try {\n await fd.writeFile(newContent, \"utf-8\");\n } finally {\n await fd.close();\n }\n } else {\n await fs.writeFile(resolvedPath, newContent, \"utf-8\");\n }\n\n return { path: filePath, filesUpdate: null, occurrences: occurrences };\n } catch (e: any) {\n return { error: `Error editing file '${filePath}': ${e.message}` };\n }\n }\n\n /**\n * Structured search results or error string for invalid input.\n */\n async grepRaw(\n pattern: string,\n dirPath: string = \"/\",\n glob: string | null = null\n ): Promise<GrepMatch[] | string> {\n // Validate regex\n try {\n new RegExp(pattern);\n } catch (e: any) {\n return `Invalid regex pattern: ${e.message}`;\n }\n\n // Resolve base path\n let baseFull: string;\n try {\n baseFull = this.resolvePath(dirPath || \".\");\n } catch {\n return [];\n }\n\n try {\n await fs.stat(baseFull);\n } catch {\n return [];\n }\n\n // Try ripgrep first, fallback to regex search\n let results = await this.ripgrepSearch(pattern, baseFull, glob);\n if (results === null) {\n results = await this.pythonSearch(pattern, baseFull, glob);\n }\n\n const matches: GrepMatch[] = [];\n for (const [fpath, items] of Object.entries(results)) {\n for (const [lineNum, lineText] of items) {\n matches.push({ path: fpath, line: lineNum, text: lineText });\n }\n }\n return matches;\n }\n\n /**\n * Try to use ripgrep for fast searching.\n * Returns null if ripgrep is not available or fails.\n */\n private async ripgrepSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null\n ): Promise<Record<string, Array<[number, string]>> | null> {\n return new Promise((resolve) => {\n const args = [\"--json\"];\n if (includeGlob) {\n args.push(\"--glob\", includeGlob);\n }\n args.push(\"--\", pattern, baseFull);\n\n const proc = spawn(\"rg\", args, { timeout: 30000 });\n const results: Record<string, Array<[number, string]>> = {};\n let output = \"\";\n\n proc.stdout.on(\"data\", (data) => {\n output += data.toString();\n });\n\n proc.on(\"close\", (code) => {\n if (code !== 0 && code !== 1) {\n // Error (code 1 means no matches, which is ok)\n resolve(null);\n return;\n }\n\n for (const line of output.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const data = JSON.parse(line);\n if (data.type !== \"match\") continue;\n\n const pdata = data.data || {};\n const ftext = pdata.path?.text;\n if (!ftext) continue;\n\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const resolved = path.resolve(ftext);\n const relative = path.relative(this.cwd, resolved);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = ftext;\n }\n\n const ln = pdata.line_number;\n const lt = pdata.lines?.text?.replace(/\\n$/, \"\") || \"\";\n if (ln === undefined) continue;\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([ln, lt]);\n } catch {\n // Skip invalid JSON\n continue;\n }\n }\n\n resolve(results);\n });\n\n proc.on(\"error\", () => {\n resolve(null);\n });\n });\n }\n\n /**\n * Fallback regex search implementation.\n */\n private async pythonSearch(\n pattern: string,\n baseFull: string,\n includeGlob: string | null\n ): Promise<Record<string, Array<[number, string]>>> {\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch {\n return {};\n }\n\n const results: Record<string, Array<[number, string]>> = {};\n const stat = await fs.stat(baseFull);\n const root = stat.isDirectory() ? baseFull : path.dirname(baseFull);\n\n // Use fast-glob to recursively find all files\n const files = await fg(\"**/*\", {\n cwd: root,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const fp of files) {\n try {\n // Filter by glob if provided\n if (\n includeGlob &&\n !micromatch.isMatch(path.basename(fp), includeGlob)\n ) {\n continue;\n }\n\n // Check file size\n const stat = await fs.stat(fp);\n if (stat.size > this.maxFileSizeBytes) {\n continue;\n }\n\n // Read and search\n const content = await fs.readFile(fp, \"utf-8\");\n const lines = content.split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (regex.test(line)) {\n let virtPath: string;\n if (this.virtualMode) {\n try {\n const relative = path.relative(this.cwd, fp);\n if (relative.startsWith(\"..\")) continue;\n const normalizedRelative = relative.split(path.sep).join(\"/\");\n virtPath = \"/\" + normalizedRelative;\n } catch {\n continue;\n }\n } else {\n virtPath = fp;\n }\n\n if (!results[virtPath]) {\n results[virtPath] = [];\n }\n results[virtPath].push([i + 1, line]);\n }\n }\n } catch {\n // Skip files we can't read\n continue;\n }\n }\n\n return results;\n }\n\n /**\n * Structured glob matching returning FileInfo objects.\n */\n async globInfo(\n pattern: string,\n searchPath: string = \"/\"\n ): Promise<FileInfo[]> {\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.substring(1);\n }\n\n const resolvedSearchPath =\n searchPath === \"/\" ? this.cwd : this.resolvePath(searchPath);\n\n try {\n const stat = await fs.stat(resolvedSearchPath);\n if (!stat.isDirectory()) {\n return [];\n }\n } catch {\n return [];\n }\n\n const results: FileInfo[] = [];\n\n try {\n // Use fast-glob for pattern matching\n const matches = await fg(pattern, {\n cwd: resolvedSearchPath,\n absolute: true,\n onlyFiles: true,\n dot: true,\n });\n\n for (const matchedPath of matches) {\n try {\n const stat = await fs.stat(matchedPath);\n if (!stat.isFile()) continue;\n\n // Normalize fast-glob paths to platform separators\n // fast-glob returns forward slashes on all platforms, but we need\n // platform-native separators for path comparisons on Windows\n const normalizedPath = matchedPath.split(\"/\").join(path.sep);\n\n if (!this.virtualMode) {\n results.push({\n path: normalizedPath,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n } else {\n const cwdStr = this.cwd.endsWith(path.sep)\n ? this.cwd\n : this.cwd + path.sep;\n let relativePath: string;\n\n if (normalizedPath.startsWith(cwdStr)) {\n relativePath = normalizedPath.substring(cwdStr.length);\n } else if (normalizedPath.startsWith(this.cwd)) {\n relativePath = normalizedPath\n .substring(this.cwd.length)\n .replace(/^[/\\\\]/, \"\");\n } else {\n relativePath = normalizedPath;\n }\n\n relativePath = relativePath.split(path.sep).join(\"/\");\n const virt = \"/\" + relativePath;\n results.push({\n path: virt,\n is_dir: false,\n size: stat.size,\n modified_at: stat.mtime.toISOString(),\n });\n }\n } catch {\n // Skip files we can't stat\n continue;\n }\n }\n } catch {\n // Ignore glob errors\n }\n\n results.sort((a, b) => a.path.localeCompare(b.path));\n return results;\n }\n}\n","import { Command } from \"@langchain/langgraph\";\nimport { z } from \"zod\";\nimport { createMiddleware, tool, ToolMessage } from \"langchain\";\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.\nIt also helps the user understand the progress of the task and overall progress of their requests.\nOnly use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.\n\n## When to Use This Tool\nUse this tool in these scenarios:\n\n1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions\n2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations\n3. User explicitly requests todo list - When the user directly asks you to use the todo list\n4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\n5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful.\n\n## How to Use This Tool\n1. When you start working on a task - Mark it as in_progress BEFORE beginning work.\n2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.\n3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.\n4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.\n\n## When NOT to Use This Tool\nIt is important to skip using this tool when:\n1. There is only a single, straightforward task\n2. The task is trivial and tracking it provides no benefit\n3. The task can be completed in less than 3 trivial steps\n4. The task is purely conversational or informational\n\n## Examples of When to Use the Todo List\n\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\n<reasoning>\nThe assistant used the todo list because:\n1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes\n2. The assistant inferred that tests and build need to pass by adding \"Ensure tests and build succeed\" as the final task\n3. Both of the user's requests are complex and require multiple steps to complete.\n</reasoning>\n</example>\n\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\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\n</reasoning>\n</example>\n\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\n<reasoning>\nThe assistant used the todo list because:\n1. 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 (>3)\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\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\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>\n\n## Examples of When NOT to Use the Todo List\n\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.</assistant>\n\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\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\n- Check soil moisture by inserting your finger about 1-2 inches into the soil\n- Water thoroughly when the top inch feels dry, allowing water to drain from the bottom\n- Use room temperature water and water in the morning when possible\n- Avoid 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\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\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\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>\n\n<example>\nUser: I need to write a function that checks if a number is prime and then test it out.\nAssistant: I'll help you write a function that checks if a number is prime and then test it out.\n*Writes function that checks if a number is prime*\n*Tests the function*\n\n<reasoning>\nEven though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens.\n</reasoning>\n</example>\n\n<example>\nUser: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\nAssistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\n*Orders a pizza from Dominos*\n*Orders a burger from McDonald's*\n*Orders a salad from Subway*\n\n<reasoning>\nEven though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls. \nUsing the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.\n</reasoning>\n</example>\n\n\n## Task States and Management\n\n1. **Task States**: Use these states to track progress:\n - pending: Task not yet started\n - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)\n - completed: Task finished successfully\n\n2. **Task Management**:\n - Update task status in real-time as you work\n - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)\n - Complete current tasks before starting new ones\n - Remove tasks that are no longer relevant from the list entirely\n - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.\n - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something.\n\n3. **Task Completion Requirements**:\n - ONLY mark a task as completed when you have FULLY accomplished it\n - If you encounter errors, blockers, or cannot finish, keep the task as in_progress\n - When blocked, create a new task describing what needs to be resolved\n - Never mark a task as completed if:\n - There are unresolved issues or errors\n - Work is partial or incomplete\n - You encountered blockers that prevent completion\n - You couldn't find necessary resources or dependencies\n - Quality standards haven't been met\n\n4. **Task Breakdown**:\n - Create specific, actionable items\n - Break complex tasks into smaller, manageable steps\n - Use clear, descriptive task names\n\nBeing proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully\nRemember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`;\nconst TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = `## \\`write_todos\\`\n\nYou have access to the \\`write_todos\\` tool to help you manage and plan complex objectives. \nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\n\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\n\n## Important To-Do List Usage Notes to Remember\n- The \\`write_todos\\` tool should never be called multiple times in parallel.\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`;\nconst TodoStatus = z\n .enum([\"pending\", \"in_progress\", \"completed\"])\n .describe(\"Status of the todo\");\nconst TodoSchema = z.object({\n content: z.string().describe(\"Content of the todo item\"),\n status: TodoStatus,\n});\nconst stateSchema = z.object({ todos: z.array(TodoSchema).default([]) });\n\nexport function todoListMiddleware(options?: {\n systemPrompt?: string;\n toolDescription?: string;\n}) {\n /**\n * Write todos tool - manages todo list with Command return\n */\n const writeTodos = tool(\n ({ todos }, config) => {\n return new Command({\n update: {\n todos,\n messages: [\n new ToolMessage({\n content: genUIMarkdown(\"todo_list\", todos),\n tool_call_id: config.toolCall?.id,\n }),\n ],\n },\n });\n },\n {\n name: \"write_todos\",\n description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION,\n schema: z.object({\n todos: z.array(TodoSchema).describe(\"List of todo items to update\"),\n }),\n }\n );\n return createMiddleware({\n name: \"todoListMiddleware\",\n stateSchema,\n tools: [writeTodos],\n wrapModelCall: (request, handler) =>\n handler({\n ...request,\n systemPrompt:\n (request.systemPrompt ? `${request.systemPrompt}\\n\\n` : \"\") +\n (options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT),\n }),\n });\n}\n","/**\n * Deep Agent Graph Builder\n *\n * 实现 Deep Agent 类型的 Agent Graph 构建\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { createDeepAgent } from \"../../deep_agent_new/agent\";\nimport { AgentLattice, AgentBuildParams, AgentClient, MiddlewareConfig } from \"../types\";\nimport { AgentGraphBuilder } from \"./AgentGraphBuilder\";\nimport { getToolClient } from \"../../tool_lattice/ToolLatticeManager\";\nimport { AgentMiddleware } from \"langchain\";\nimport { createAgentClientFromAgentLattice } from \"@agent_lattice/AgentLatticeManager\";\nimport { getCheckpointSaver } from \"@memory_lattice/MemoryLatticeManager\";\nimport { sandboxLatticeManager } from \"../../sandbox_lattice/SandboxLatticeManager\";\nimport { SandboxFilesystem } from \"../../deep_agent_new/backends/sandboxFiles\";\nimport { createCommonMiddlewares } from \"./commonMiddleware\";\n\nexport class DeepAgentGraphBuilder implements AgentGraphBuilder {\n /**\n * 根据 middleware 配置创建 backend factory\n */\n private createFilesystemBackendFactory(\n middlewareConfigs: MiddlewareConfig[]\n ): ((config: { state: unknown; store?: any }) => Promise<any>) | undefined {\n const filesystemConfig = middlewareConfigs.find(m => m.type === \"filesystem\");\n\n if (!filesystemConfig || !filesystemConfig.enabled) {\n return undefined;\n }\n\n const isolatedLevel = filesystemConfig.config?.isolatedLevel || \"global\";\n\n return async (config: { state: unknown }) => {\n let sandboxName = \"global\";\n\n if (isolatedLevel === \"agent\") {\n sandboxName = \"agent\";\n } else if (isolatedLevel === \"thread\") {\n sandboxName = \"thread\";\n }\n\n const sandboxManager = sandboxLatticeManager.getSandboxLattice(\"default\");\n if (!sandboxManager) {\n throw new Error(\"Sandbox manager not found\");\n }\n\n return new SandboxFilesystem({\n sandboxInstance: await sandboxManager.createSandbox(sandboxName),\n });\n };\n }\n\n /**\n * 根据 middleware 配置创建 middlewares\n */\n private createMiddlewares(middlewareConfigs: MiddlewareConfig[]) {\n return createCommonMiddlewares(middlewareConfigs);\n }\n\n /**\n * 构建Deep Agent Graph\n *\n * @param agentLattice Agent Lattice对象\n * @param params Agent构建参数\n * @returns 返回CompiledGraph对象\n */\n build(agentLattice: AgentLattice, params: AgentBuildParams): AgentClient {\n const tools = params.tools\n .map((t) => {\n const toolClient = getToolClient(t.key);\n return toolClient;\n })\n .filter((tool) => tool !== undefined);\n\n const subagents = params.subAgents.map((sa) => {\n if (sa.client) {\n return {\n name: sa.config.name,\n description: sa.config.description,\n runnable: sa.client,\n };\n } else {\n const subagentClient = createAgentClientFromAgentLattice({\n config: sa.config,\n });\n return {\n name: sa.config.name,\n description: sa.config.description,\n runnable: subagentClient,\n };\n }\n });\n\n const middlewareConfigs = params.middleware || [];\n const filesystemBackend = this.createFilesystemBackendFactory(middlewareConfigs);\n const middlewares = this.createMiddlewares(middlewareConfigs);\n\n const deepAgent = createDeepAgent({\n tools: tools,\n model: params.model,\n contextSchema: params.stateSchema,\n systemPrompt: params.prompt,\n subagents,\n checkpointer: getCheckpointSaver(\"default\"),\n skills: params.skillCategories,\n backend: filesystemBackend,\n middleware: middlewares,\n });\n\n return deepAgent as AgentClient;\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\";\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 }\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 skills = isDeepAgentConfig(agentLattice.config) ? agentLattice.config.skillCategories : undefined;\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 skillCategories: skills,\n middleware: agentLattice.config.middleware,\n };\n }\n}\n","import { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n AgentConfig,\n AgentClient,\n AgentLattice,\n GraphBuildOptions,\n AgentBuildParams,\n AgentType,\n} from \"./types\";\nimport { AgentGraphBuilderFactory } from \"./builders/AgentGraphBuilderFactory\";\nimport { AgentParamsBuilder } from \"./builders/AgentParamsBuilder\";\nimport \"../tool_lattice\";\nimport eventBus from \"../services/event_bus\";\nimport type { Assistant } from \"@axiom-lattice/protocols\";\nimport { getStoreLattice } from \"../store_lattice\";\n\nfunction assistantToConfig(assistant: Assistant): AgentConfig {\n const graphDef = typeof assistant.graphDefinition === \"object\" && assistant.graphDefinition !== null\n ? assistant.graphDefinition\n : {};\n\n const config: AgentConfig = {\n key: assistant.id,\n name: assistant.name ?? (graphDef as any).name ?? assistant.id,\n description: assistant.description ?? (graphDef as any).description ?? \"\",\n type: AgentType.REACT,\n prompt: typeof assistant.graphDefinition === \"string\"\n ? assistant.graphDefinition\n : JSON.stringify(assistant.graphDefinition),\n };\n\n if (graphDef) {\n Object.assign(config, graphDef);\n }\n return config;\n}\n\n/**\n * AgentLatticeManager - 单例Agent Lattice管理器\n * 负责注册、管理各种Agent Lattice\n */\nexport class AgentLatticeManager extends BaseLatticeManager<AgentLattice> {\n private static _instance: AgentLatticeManager;\n private initialized: boolean = false;\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 private constructor() {\n super();\n this.subscribeToAssistantEvents();\n }\n\n private async initializeStoredAssistants(): Promise<void> {\n if (this.initialized) return;\n\n try {\n const storeLattice = getStoreLattice(\"default\", \"assistant\");\n const assistants = await storeLattice.store.getAllAssistants();\n\n for (const assistant of assistants) {\n if (this.has(assistant.id)) continue;\n const config = assistantToConfig(assistant);\n this.registerLattice(config);\n }\n\n this.initialized = true;\n } catch (error) {\n console.error(\"Failed to initialize stored assistants:\", error);\n }\n }\n\n private subscribeToAssistantEvents(): void {\n eventBus.subscribe(\"assistant:created\", (data: { id: string }) => {\n this.handleAssistantChange(data.id);\n });\n eventBus.subscribe(\"assistant:updated\", (data: { id: string }) => {\n this.handleAssistantChange(data.id);\n });\n eventBus.subscribe(\"assistant:deleted\", (data: { id: string }) => {\n this.handleAssistantDelete(data.id);\n });\n }\n\n private async handleAssistantChange(assistantId: string): Promise<void> {\n try {\n const storeLattice = getStoreLattice(\"default\", \"assistant\");\n const assistant = await storeLattice.store.getAssistantById(assistantId);\n\n if (assistant) {\n if (this.has(assistantId)) {\n this.remove(assistantId);\n }\n const config = assistantToConfig(assistant);\n this.registerLattice(config);\n }\n } catch (error) {\n console.error(`Failed to handle assistant change for ${assistantId}:`, error);\n }\n }\n\n private handleAssistantDelete(assistantId: string): void {\n if (this.has(assistantId)) {\n this.remove(assistantId);\n }\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 * code-configured 和 stored assistants 都已注册到 registry\n */\n public async getAllAgentConfigs(): Promise<AgentConfig[]> {\n await this.initializeStoredAssistants();\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 {\n ReplaySubject,\n Observable,\n Subscription,\n observeOn,\n asyncScheduler,\n} 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 ?? 100000, // 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 if (!buffer) {\n const now = Date.now();\n buffer = {\n threadId,\n chunks$: new ReplaySubject<MessageChunk>(this.config.maxChunks),\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>(this.config.maxChunks);\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 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 let pendingError: Error | null = null; // Track errors that occur when not waiting\n\n const subscription = buffer.chunks$\n .pipe(observeOn(asyncScheduler))\n .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 pendingError = err; // Always store the error\n\n if (errorNext) {\n const reject = errorNext;\n errorNext = null;\n reject(err);\n } else if (resolveNext) {\n // If waiting on resolveNext, wake it up to check pendingError\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n complete: () => {\n isCompleted = true;\n if (resolveNext) {\n const resolve = resolveNext;\n resolveNext = null;\n resolve();\n }\n },\n });\n let startYieldChunk = false;\n\n try {\n while (true) {\n if (pendingError) {\n throw pendingError;\n }\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 // Check error again after waking up\n if (pendingError) {\n throw pendingError;\n }\n while (queue.length > 0) {\n const chunk = queue.shift();\n if (!chunk) continue;\n\n if (chunk.data?.id === messageId) {\n startYieldChunk = true;\n accumulatedContent += chunk.data?.content || \"\";\n }\n // if (accumulatedContent.length > knownContent.length) {\n // startYieldChunk = true;\n // }\n if (startYieldChunk) {\n yield chunk;\n }\n\n // if (accumulatedContent.length > knownContent.length) {\n // if (accumulatedContent.startsWith(knownContent)) {\n // yield chunk;\n // } else {\n // console.log(\n // \"accumulatedContent not starts with knownContent\",\n // accumulatedContent,\n // knownContent\n // );\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","/**\n * ScheduleLatticeManager\n *\n * Schedule Lattice manager for registering and managing schedule services\n * Supports both one-time and cron-style recurring tasks\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n ScheduleLatticeProtocol,\n ScheduleConfig,\n ScheduleType,\n ScheduleClient,\n ScheduleStorage,\n ScheduledTaskDefinition,\n TaskHandler,\n ScheduleOnceOptions,\n ScheduleCronOptions,\n} from \"@axiom-lattice/protocols\";\nimport { DefaultScheduleClient } from \"./DefaultScheduleClient\";\nimport { MemoryScheduleStorage } from \"./MemoryScheduleStorage\";\n\n/**\n * Schedule Lattice interface\n */\nexport interface ScheduleLattice extends ScheduleLatticeProtocol {\n key: string;\n config: ScheduleConfig;\n client: ScheduleLatticeProtocol[\"client\"];\n}\n\n/**\n * ScheduleLatticeManager - Singleton schedule Lattice manager\n * Responsible for registering and managing various schedule service Lattices\n */\nexport class ScheduleLatticeManager extends BaseLatticeManager<ScheduleLattice> {\n private static _instance: ScheduleLatticeManager;\n\n /**\n * Get ScheduleLatticeManager singleton instance\n */\n public static getInstance(): ScheduleLatticeManager {\n if (!ScheduleLatticeManager._instance) {\n ScheduleLatticeManager._instance = new ScheduleLatticeManager();\n }\n return ScheduleLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"schedules\";\n }\n\n /**\n * Register schedule Lattice\n * @param key Lattice key name\n * @param config Schedule configuration\n * @param client Optional schedule client. If not provided, will create based on config type.\n */\n public registerLattice(\n key: string,\n config: ScheduleConfig,\n client?: ScheduleClient\n ): void {\n // Create client based on schedule type if not provided\n let scheduleClient: ScheduleLatticeProtocol[\"client\"];\n\n if (client) {\n // Use provided client\n scheduleClient = client;\n // If storage is provided in config, set it on the client\n if (config.storage) {\n scheduleClient.setStorage(config.storage);\n }\n } else {\n // Create storage based on config\n let storage: ScheduleStorage;\n if (config.storage) {\n storage = config.storage;\n } else {\n // Default to memory storage\n storage = new MemoryScheduleStorage();\n }\n\n if (config.type === ScheduleType.MEMORY) {\n scheduleClient = new DefaultScheduleClient(storage);\n } else if (config.type === ScheduleType.POSTGRES) {\n // For Postgres, storage must be provided\n if (!config.storage) {\n throw new Error(\n `PostgreSQL schedule storage must be provided. Please install @axiom-lattice/pg-stores and pass the storage in config.storage.`\n );\n }\n scheduleClient = new DefaultScheduleClient(storage);\n } else {\n // Default to memory with memory storage\n scheduleClient = new DefaultScheduleClient(storage);\n }\n }\n\n // Create schedule Lattice object\n const scheduleLattice: ScheduleLattice = {\n key,\n config,\n client: scheduleClient,\n\n // Handler registration\n registerHandler: (taskType: string, handler: TaskHandler) => {\n scheduleClient.registerHandler(taskType, handler);\n },\n unregisterHandler: (taskType: string) => {\n return scheduleClient.unregisterHandler(taskType);\n },\n hasHandler: (taskType: string) => {\n return scheduleClient.hasHandler(taskType);\n },\n getHandlerTypes: () => {\n return scheduleClient.getHandlerTypes();\n },\n\n // One-time task scheduling\n scheduleOnce: async (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ) => {\n return scheduleClient.scheduleOnce(taskId, taskType, payload, options);\n },\n\n // Cron task scheduling\n scheduleCron: async (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ) => {\n return scheduleClient.scheduleCron(taskId, taskType, payload, options);\n },\n\n // Task management\n cancel: async (taskId: string) => {\n return scheduleClient.cancel(taskId);\n },\n pause: async (taskId: string) => {\n return scheduleClient.pause(taskId);\n },\n resume: async (taskId: string) => {\n return scheduleClient.resume(taskId);\n },\n has: async (taskId: string) => {\n return scheduleClient.has(taskId);\n },\n getTask: async (\n taskId: string\n ): Promise<ScheduledTaskDefinition | null> => {\n return scheduleClient.getTask(taskId);\n },\n getRemainingTime: async (taskId: string) => {\n return scheduleClient.getRemainingTime(taskId);\n },\n getActiveTaskCount: async () => {\n return scheduleClient.getActiveTaskCount();\n },\n getActiveTaskIds: async () => {\n return scheduleClient.getActiveTaskIds();\n },\n cancelAll: async () => {\n return scheduleClient.cancelAll();\n },\n\n // Recovery\n restore: async () => {\n return scheduleClient.restore();\n },\n };\n\n // Call base class register method\n this.register(key, scheduleLattice);\n }\n\n /**\n * Get ScheduleLattice\n * @param key Lattice key name\n */\n public getScheduleLattice(key: string): ScheduleLattice {\n const scheduleLattice = this.get(key);\n if (!scheduleLattice) {\n throw new Error(`ScheduleLattice ${key} not found`);\n }\n return scheduleLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): ScheduleLattice[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const scheduleLatticeManager = ScheduleLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerScheduleLattice = (\n key: string,\n config: ScheduleConfig,\n client?: ScheduleClient\n) => scheduleLatticeManager.registerLattice(key, config, client);\n\nexport const getScheduleLattice = (key: string) =>\n scheduleLatticeManager.getScheduleLattice(key);\n","/**\n * DefaultScheduleClient\n *\n * Default schedule client implementation with full protocol support\n * Core scheduling engine that handles timer management, cron parsing, and task execution\n * Supports both one-time and cron-style recurring tasks\n * Storage backend is pluggable - uses MemoryScheduleStorage by default\n */\n\nimport {\n ScheduleClient,\n ScheduleStorage,\n ScheduledTaskDefinition,\n ScheduledTaskStatus,\n ScheduleExecutionType,\n TaskHandler,\n ScheduleOnceOptions,\n ScheduleCronOptions,\n} from \"@axiom-lattice/protocols\";\nimport { MemoryScheduleStorage } from \"./MemoryScheduleStorage\";\nimport { getNextCronTime, isValidCronExpression } from \"./CronParser\";\n\n/**\n * Active timer info for in-memory scheduling\n */\ninterface ActiveTimer {\n timerId: NodeJS.Timeout;\n taskId: string;\n}\n\n/**\n * Default schedule client implementation\n * Core scheduling engine with pluggable storage backend\n */\nexport class DefaultScheduleClient implements ScheduleClient {\n private static instance: DefaultScheduleClient | null = null;\n\n private handlers: Map<string, TaskHandler> = new Map();\n private timers: Map<string, ActiveTimer> = new Map();\n private storage: ScheduleStorage;\n\n constructor(storage?: ScheduleStorage) {\n this.storage = storage || new MemoryScheduleStorage();\n }\n\n /**\n * Get the singleton instance of DefaultScheduleClient\n */\n public static getInstance(storage?: ScheduleStorage): DefaultScheduleClient {\n if (!DefaultScheduleClient.instance) {\n DefaultScheduleClient.instance = new DefaultScheduleClient(storage);\n }\n return DefaultScheduleClient.instance;\n }\n\n /**\n * Reset the singleton instance (useful for testing)\n */\n public static resetInstance(): void {\n if (DefaultScheduleClient.instance) {\n DefaultScheduleClient.instance.cancelAll();\n DefaultScheduleClient.instance = null;\n }\n }\n\n // ===== Handler Registration =====\n\n registerHandler(taskType: string, handler: TaskHandler): void {\n this.handlers.set(taskType, handler);\n console.log(`[Scheduler] Handler registered for task type: ${taskType}`);\n }\n\n unregisterHandler(taskType: string): boolean {\n const result = this.handlers.delete(taskType);\n if (result) {\n console.log(\n `[Scheduler] Handler unregistered for task type: ${taskType}`\n );\n }\n return result;\n }\n\n hasHandler(taskType: string): boolean {\n return this.handlers.has(taskType);\n }\n\n getHandlerTypes(): string[] {\n return Array.from(this.handlers.keys());\n }\n\n // ===== One-time Task Scheduling =====\n\n async scheduleOnce(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ): Promise<boolean> {\n // Validate handler exists\n if (!this.handlers.has(taskType)) {\n console.error(\n `[Scheduler] No handler registered for task type: ${taskType}`\n );\n return false;\n }\n\n // Calculate execute time\n let executeAt: number;\n if (options.executeAt !== undefined) {\n executeAt = options.executeAt;\n } else if (options.delayMs !== undefined) {\n executeAt = Date.now() + options.delayMs;\n } else {\n console.error(\"[Scheduler] Either executeAt or delayMs must be provided\");\n return false;\n }\n\n // Cancel existing task with same ID\n if (await this.has(taskId)) {\n await this.cancel(taskId);\n }\n\n const now = Date.now();\n const task: ScheduledTaskDefinition = {\n taskId,\n taskType,\n payload,\n assistantId: options.assistantId,\n threadId: options.threadId,\n executionType: ScheduleExecutionType.ONCE,\n executeAt,\n delayMs: options.delayMs,\n status: ScheduledTaskStatus.PENDING,\n runCount: 0,\n retryCount: 0,\n maxRetries: options.maxRetries ?? 0,\n createdAt: now,\n updatedAt: now,\n metadata: options.metadata,\n };\n\n // Save to storage\n await this.storage.save(task);\n\n // Schedule timer\n this.scheduleTimer(task);\n\n console.log(\n `[Scheduler] One-time task scheduled: ${taskId}, executes at ${new Date(\n executeAt\n ).toISOString()}`\n );\n return true;\n }\n\n // ===== Cron Task Scheduling =====\n\n async scheduleCron(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ): Promise<boolean> {\n // Validate handler exists\n if (!this.handlers.has(taskType)) {\n console.error(\n `[Scheduler] No handler registered for task type: ${taskType}`\n );\n return false;\n }\n\n // Validate cron expression\n if (!isValidCronExpression(options.cronExpression)) {\n console.error(\n `[Scheduler] Invalid cron expression: ${options.cronExpression}`\n );\n return false;\n }\n\n // Cancel existing task with same ID\n if (await this.has(taskId)) {\n await this.cancel(taskId);\n }\n\n const now = Date.now();\n const nextRunAt = getNextCronTime(options.cronExpression, new Date(now));\n\n const task: ScheduledTaskDefinition = {\n taskId,\n taskType,\n payload,\n assistantId: options.assistantId,\n threadId: options.threadId,\n executionType: ScheduleExecutionType.CRON,\n cronExpression: options.cronExpression,\n timezone: options.timezone,\n nextRunAt: nextRunAt.getTime(),\n status: ScheduledTaskStatus.PENDING,\n runCount: 0,\n maxRuns: options.maxRuns,\n retryCount: 0,\n maxRetries: options.maxRetries ?? 0,\n createdAt: now,\n updatedAt: now,\n expiresAt: options.expiresAt,\n metadata: options.metadata,\n };\n\n // Save to storage\n await this.storage.save(task);\n\n // Schedule timer\n this.scheduleTimer(task);\n\n console.log(\n `[Scheduler] Cron task scheduled: ${taskId}, expression: ${\n options.cronExpression\n }, next run: ${nextRunAt.toISOString()}`\n );\n return true;\n }\n\n // ===== Task Management =====\n\n async cancel(taskId: string): Promise<boolean> {\n // Clear timer\n const timer = this.timers.get(taskId);\n if (timer) {\n clearTimeout(timer.timerId);\n this.timers.delete(taskId);\n }\n\n // Update storage\n const task = await this.storage.get(taskId);\n if (task) {\n await this.storage.update(taskId, {\n status: ScheduledTaskStatus.CANCELLED,\n });\n console.log(`[Scheduler] Task cancelled: ${taskId}`);\n return true;\n }\n\n return false;\n }\n\n async pause(taskId: string): Promise<boolean> {\n const task = await this.storage.get(taskId);\n if (!task || task.executionType !== ScheduleExecutionType.CRON) {\n console.error(`[Scheduler] Can only pause CRON tasks: ${taskId}`);\n return false;\n }\n\n if (task.status !== ScheduledTaskStatus.PENDING) {\n console.error(`[Scheduler] Can only pause PENDING tasks: ${taskId}`);\n return false;\n }\n\n // Clear timer\n const timer = this.timers.get(taskId);\n if (timer) {\n clearTimeout(timer.timerId);\n this.timers.delete(taskId);\n }\n\n await this.storage.update(taskId, {\n status: ScheduledTaskStatus.PAUSED,\n });\n\n console.log(`[Scheduler] Task paused: ${taskId}`);\n return true;\n }\n\n async resume(taskId: string): Promise<boolean> {\n const task = await this.storage.get(taskId);\n if (!task || task.executionType !== ScheduleExecutionType.CRON) {\n console.error(`[Scheduler] Can only resume CRON tasks: ${taskId}`);\n return false;\n }\n\n if (task.status !== ScheduledTaskStatus.PAUSED) {\n console.error(`[Scheduler] Can only resume PAUSED tasks: ${taskId}`);\n return false;\n }\n\n // Calculate next run time\n const nextRunAt = getNextCronTime(task.cronExpression!);\n\n await this.storage.update(taskId, {\n status: ScheduledTaskStatus.PENDING,\n nextRunAt: nextRunAt.getTime(),\n });\n\n // Re-fetch updated task and schedule\n const updatedTask = await this.storage.get(taskId);\n if (updatedTask) {\n this.scheduleTimer(updatedTask);\n }\n\n console.log(`[Scheduler] Task resumed: ${taskId}`);\n return true;\n }\n\n async has(taskId: string): Promise<boolean> {\n const task = await this.storage.get(taskId);\n return task !== null;\n }\n\n async getTask(taskId: string): Promise<ScheduledTaskDefinition | null> {\n return this.storage.get(taskId);\n }\n\n async getRemainingTime(taskId: string): Promise<number> {\n const task = await this.storage.get(taskId);\n if (!task) {\n return -1;\n }\n\n const targetTime =\n task.executionType === ScheduleExecutionType.CRON\n ? task.nextRunAt\n : task.executeAt;\n\n if (targetTime === undefined) {\n return -1;\n }\n\n return Math.max(0, targetTime - Date.now());\n }\n\n async getActiveTaskCount(): Promise<number> {\n const tasks = await this.storage.getActiveTasks();\n return tasks.length;\n }\n\n async getActiveTaskIds(): Promise<string[]> {\n const tasks = await this.storage.getActiveTasks();\n return tasks.map((t) => t.taskId);\n }\n\n async cancelAll(): Promise<void> {\n // Clear all timers\n for (const timer of this.timers.values()) {\n clearTimeout(timer.timerId);\n }\n this.timers.clear();\n\n // Update all active tasks to cancelled\n const activeTasks = await this.storage.getActiveTasks();\n for (const task of activeTasks) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.CANCELLED,\n });\n }\n\n console.log(`[Scheduler] All tasks cancelled`);\n }\n\n // ===== Recovery =====\n\n async restore(): Promise<number> {\n const activeTasks = await this.storage.getActiveTasks();\n let restored = 0;\n\n for (const task of activeTasks) {\n // Skip if no handler registered\n if (!this.handlers.has(task.taskType)) {\n console.warn(\n `[Scheduler] No handler for task type ${task.taskType}, skipping restore for task ${task.taskId}`\n );\n continue;\n }\n\n // Skip paused tasks (they'll be resumed manually)\n if (task.status === ScheduledTaskStatus.PAUSED) {\n continue;\n }\n\n if (task.executionType === ScheduleExecutionType.ONCE) {\n // For one-time tasks, check if execution time has passed\n if (task.executeAt && task.executeAt <= Date.now()) {\n // Execute immediately\n console.log(\n `[Scheduler] Executing overdue one-time task: ${task.taskId}`\n );\n this.executeTask(task);\n } else {\n // Schedule for remaining time\n this.scheduleTimer(task);\n }\n } else if (task.executionType === ScheduleExecutionType.CRON) {\n // For cron tasks, calculate next run time\n const nextRunAt = getNextCronTime(task.cronExpression!);\n await this.storage.update(task.taskId, {\n nextRunAt: nextRunAt.getTime(),\n });\n\n const updatedTask = await this.storage.get(task.taskId);\n if (updatedTask) {\n this.scheduleTimer(updatedTask);\n }\n }\n\n restored++;\n }\n\n console.log(`[Scheduler] Restored ${restored} tasks`);\n return restored;\n }\n\n // ===== Storage =====\n\n setStorage(storage: ScheduleStorage): void {\n this.storage = storage;\n }\n\n getStorage(): ScheduleStorage | null {\n return this.storage;\n }\n\n // ===== Private Methods =====\n\n private scheduleTimer(task: ScheduledTaskDefinition): void {\n const targetTime =\n task.executionType === ScheduleExecutionType.CRON\n ? task.nextRunAt\n : task.executeAt;\n\n if (targetTime === undefined) {\n console.error(`[Scheduler] No execution time for task: ${task.taskId}`);\n return;\n }\n\n const delay = Math.max(0, targetTime - Date.now());\n\n const timerId = setTimeout(() => {\n this.executeTask(task);\n }, delay);\n\n this.timers.set(task.taskId, {\n timerId,\n taskId: task.taskId,\n });\n }\n\n private async executeTask(task: ScheduledTaskDefinition): Promise<void> {\n const handler = this.handlers.get(task.taskType);\n if (!handler) {\n console.error(\n `[Scheduler] No handler for task type: ${task.taskType}, task: ${task.taskId}`\n );\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.FAILED,\n lastError: `No handler registered for task type: ${task.taskType}`,\n });\n return;\n }\n\n // Update status to running\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.RUNNING,\n });\n\n console.log(`[Scheduler] Executing task: ${task.taskId}`);\n\n try {\n // Get latest task state\n const latestTask = await this.storage.get(task.taskId);\n if (!latestTask) {\n console.error(`[Scheduler] Task not found: ${task.taskId}`);\n return;\n }\n\n await handler(latestTask.payload, latestTask);\n\n const newRunCount = latestTask.runCount + 1;\n console.log(`[Scheduler] Task completed: ${task.taskId}`);\n\n // Handle completion based on execution type\n if (task.executionType === ScheduleExecutionType.ONCE) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.COMPLETED,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n });\n this.timers.delete(task.taskId);\n } else if (task.executionType === ScheduleExecutionType.CRON) {\n // Check if max runs reached\n if (task.maxRuns !== undefined && newRunCount >= task.maxRuns) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.COMPLETED,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n });\n this.timers.delete(task.taskId);\n console.log(\n `[Scheduler] Cron task completed (max runs): ${task.taskId}`\n );\n return;\n }\n\n // Check if expired\n if (task.expiresAt !== undefined && Date.now() >= task.expiresAt) {\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.COMPLETED,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n });\n this.timers.delete(task.taskId);\n console.log(\n `[Scheduler] Cron task completed (expired): ${task.taskId}`\n );\n return;\n }\n\n // Schedule next run\n const nextRunAt = getNextCronTime(task.cronExpression!);\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.PENDING,\n runCount: newRunCount,\n lastRunAt: Date.now(),\n nextRunAt: nextRunAt.getTime(),\n retryCount: 0, // Reset retry count on success\n });\n\n const updatedTask = await this.storage.get(task.taskId);\n if (updatedTask) {\n this.scheduleTimer(updatedTask);\n console.log(\n `[Scheduler] Next cron run scheduled: ${\n task.taskId\n } at ${nextRunAt.toISOString()}`\n );\n }\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n console.error(`[Scheduler] Task failed: ${task.taskId}`, error);\n\n const latestTask = await this.storage.get(task.taskId);\n if (!latestTask) return;\n\n const newRetryCount = latestTask.retryCount + 1;\n\n // Check if can retry\n if (newRetryCount <= latestTask.maxRetries) {\n console.log(\n `[Scheduler] Retrying task: ${task.taskId} (attempt ${newRetryCount}/${latestTask.maxRetries})`\n );\n\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.PENDING,\n retryCount: newRetryCount,\n lastError: errorMessage,\n });\n\n // Retry with exponential backoff\n const retryDelay = Math.min(\n 1000 * Math.pow(2, newRetryCount - 1),\n 60000\n );\n const retryTask = await this.storage.get(task.taskId);\n if (retryTask) {\n if (task.executionType === ScheduleExecutionType.ONCE) {\n retryTask.executeAt = Date.now() + retryDelay;\n } else {\n retryTask.nextRunAt = Date.now() + retryDelay;\n }\n await this.storage.update(task.taskId, {\n executeAt: retryTask.executeAt,\n nextRunAt: retryTask.nextRunAt,\n });\n this.scheduleTimer(retryTask);\n }\n } else {\n // Max retries exceeded\n await this.storage.update(task.taskId, {\n status: ScheduledTaskStatus.FAILED,\n retryCount: newRetryCount,\n lastError: errorMessage,\n });\n this.timers.delete(task.taskId);\n console.error(\n `[Scheduler] Task failed permanently: ${task.taskId} (max retries exceeded)`\n );\n }\n }\n }\n}\n","/**\n * MemoryScheduleStorage\n *\n * In-memory storage implementation for scheduled tasks\n * Useful for development and testing, not recommended for production\n * Data is lost on service restart\n */\n\nimport {\n ScheduleStorage,\n ScheduledTaskDefinition,\n ScheduledTaskStatus,\n ScheduleExecutionType,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * In-memory storage for scheduled tasks\n */\nexport class MemoryScheduleStorage implements ScheduleStorage {\n private tasks: Map<string, ScheduledTaskDefinition> = new Map();\n\n /**\n * Save a new task\n */\n async save(task: ScheduledTaskDefinition): Promise<void> {\n this.tasks.set(task.taskId, { ...task });\n }\n\n /**\n * Get task by ID\n */\n async get(taskId: string): Promise<ScheduledTaskDefinition | null> {\n const task = this.tasks.get(taskId);\n return task ? { ...task } : null;\n }\n\n /**\n * Update task\n */\n async update(\n taskId: string,\n updates: Partial<ScheduledTaskDefinition>\n ): Promise<void> {\n const task = this.tasks.get(taskId);\n if (task) {\n this.tasks.set(taskId, {\n ...task,\n ...updates,\n updatedAt: Date.now(),\n });\n }\n }\n\n /**\n * Delete task\n */\n async delete(taskId: string): Promise<void> {\n this.tasks.delete(taskId);\n }\n\n /**\n * Get all active tasks (pending or paused)\n */\n async getActiveTasks(): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (\n task.status === ScheduledTaskStatus.PENDING ||\n task.status === ScheduledTaskStatus.PAUSED\n ) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by type\n */\n async getTasksByType(taskType: string): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.taskType === taskType) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by status\n */\n async getTasksByStatus(\n status: ScheduledTaskStatus\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.status === status) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by execution type\n */\n async getTasksByExecutionType(\n executionType: ScheduleExecutionType\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.executionType === executionType) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by assistant ID\n */\n async getTasksByAssistantId(\n assistantId: string\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.assistantId === assistantId) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get tasks by thread ID\n */\n async getTasksByThreadId(\n threadId: string\n ): Promise<ScheduledTaskDefinition[]> {\n const result: ScheduledTaskDefinition[] = [];\n for (const task of this.tasks.values()) {\n if (task.threadId === threadId) {\n result.push({ ...task });\n }\n }\n return result;\n }\n\n /**\n * Get all tasks with optional filters\n */\n async getAllTasks(filters?: {\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n limit?: number;\n offset?: number;\n }): Promise<ScheduledTaskDefinition[]> {\n let result: ScheduledTaskDefinition[] = [];\n\n for (const task of this.tasks.values()) {\n let match = true;\n\n if (filters?.status !== undefined && task.status !== filters.status) {\n match = false;\n }\n if (\n filters?.executionType !== undefined &&\n task.executionType !== filters.executionType\n ) {\n match = false;\n }\n if (\n filters?.taskType !== undefined &&\n task.taskType !== filters.taskType\n ) {\n match = false;\n }\n if (\n filters?.assistantId !== undefined &&\n task.assistantId !== filters.assistantId\n ) {\n match = false;\n }\n if (\n filters?.threadId !== undefined &&\n task.threadId !== filters.threadId\n ) {\n match = false;\n }\n\n if (match) {\n result.push({ ...task });\n }\n }\n\n // Sort by createdAt descending\n result.sort((a, b) => b.createdAt - a.createdAt);\n\n // Apply offset and limit\n const offset = filters?.offset || 0;\n const limit = filters?.limit;\n\n if (limit !== undefined) {\n result = result.slice(offset, offset + limit);\n } else if (offset > 0) {\n result = result.slice(offset);\n }\n\n return result;\n }\n\n /**\n * Count tasks with optional filters\n */\n async countTasks(filters?: {\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n }): Promise<number> {\n let count = 0;\n\n for (const task of this.tasks.values()) {\n let match = true;\n\n if (filters?.status !== undefined && task.status !== filters.status) {\n match = false;\n }\n if (\n filters?.executionType !== undefined &&\n task.executionType !== filters.executionType\n ) {\n match = false;\n }\n if (\n filters?.taskType !== undefined &&\n task.taskType !== filters.taskType\n ) {\n match = false;\n }\n if (\n filters?.assistantId !== undefined &&\n task.assistantId !== filters.assistantId\n ) {\n match = false;\n }\n if (\n filters?.threadId !== undefined &&\n task.threadId !== filters.threadId\n ) {\n match = false;\n }\n\n if (match) {\n count++;\n }\n }\n\n return count;\n }\n\n /**\n * Delete completed/cancelled tasks older than specified time\n */\n async deleteOldTasks(olderThanMs: number): Promise<number> {\n const cutoff = Date.now() - olderThanMs;\n let deleted = 0;\n\n for (const [taskId, task] of this.tasks.entries()) {\n if (\n (task.status === ScheduledTaskStatus.COMPLETED ||\n task.status === ScheduledTaskStatus.CANCELLED ||\n task.status === ScheduledTaskStatus.FAILED) &&\n task.updatedAt < cutoff\n ) {\n this.tasks.delete(taskId);\n deleted++;\n }\n }\n\n return deleted;\n }\n\n /**\n * Clear all tasks (useful for testing)\n */\n clear(): void {\n this.tasks.clear();\n }\n\n /**\n * Get total task count (useful for debugging)\n */\n size(): number {\n return this.tasks.size;\n }\n}\n","/**\n * CronParser\n *\n * Simple cron expression parser for calculating next execution time\n * Supports standard 5-field cron format: minute hour day-of-month month day-of-week\n *\n * Field values:\n * minute: 0-59\n * hour: 0-23\n * day-of-month: 1-31\n * month: 1-12\n * day-of-week: 0-7 (0 and 7 are Sunday)\n *\n * Special characters:\n * asterisk (*) : any value\n * comma (,) : value list separator (1,3,5)\n * dash (-) : range of values (1-5)\n * slash (/) : step values (asterisk/5 = every 5)\n */\n\nexport interface CronFields {\n minute: number[];\n hour: number[];\n dayOfMonth: number[];\n month: number[];\n dayOfWeek: number[];\n}\n\n/**\n * Parse a cron expression into field arrays\n */\nexport function parseCronExpression(expression: string): CronFields {\n const parts = expression.trim().split(/\\s+/);\n\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression: expected 5 fields, got ${parts.length}`\n );\n }\n\n return {\n minute: parseField(parts[0], 0, 59),\n hour: parseField(parts[1], 0, 23),\n dayOfMonth: parseField(parts[2], 1, 31),\n month: parseField(parts[3], 1, 12),\n dayOfWeek: parseField(parts[4], 0, 7).map((d) => (d === 7 ? 0 : d)), // Normalize Sunday\n };\n}\n\n/**\n * Parse a single cron field\n */\nfunction parseField(field: string, min: number, max: number): number[] {\n const values = new Set<number>();\n\n // Handle comma-separated values\n const segments = field.split(\",\");\n\n for (const segment of segments) {\n // Handle step values (*/5 or 1-10/2)\n const [range, stepStr] = segment.split(\"/\");\n const step = stepStr ? parseInt(stepStr, 10) : 1;\n\n if (isNaN(step) || step < 1) {\n throw new Error(`Invalid step value: ${stepStr}`);\n }\n\n let rangeStart: number;\n let rangeEnd: number;\n\n if (range === \"*\") {\n rangeStart = min;\n rangeEnd = max;\n } else if (range.includes(\"-\")) {\n // Handle range (1-5)\n const [startStr, endStr] = range.split(\"-\");\n rangeStart = parseInt(startStr, 10);\n rangeEnd = parseInt(endStr, 10);\n\n if (isNaN(rangeStart) || isNaN(rangeEnd)) {\n throw new Error(`Invalid range: ${range}`);\n }\n } else {\n // Single value\n const value = parseInt(range, 10);\n if (isNaN(value)) {\n throw new Error(`Invalid value: ${range}`);\n }\n rangeStart = value;\n rangeEnd = value;\n }\n\n // Validate range\n if (rangeStart < min || rangeEnd > max || rangeStart > rangeEnd) {\n throw new Error(`Value out of range: ${range} (expected ${min}-${max})`);\n }\n\n // Add values with step\n for (let i = rangeStart; i <= rangeEnd; i += step) {\n values.add(i);\n }\n }\n\n return Array.from(values).sort((a, b) => a - b);\n}\n\n/**\n * Get the next execution time after the given date\n */\nexport function getNextCronTime(\n expression: string,\n after: Date = new Date(),\n timezone?: string\n): Date {\n const fields = parseCronExpression(expression);\n\n // Start from the next minute\n const next = new Date(after.getTime());\n next.setSeconds(0, 0);\n next.setMinutes(next.getMinutes() + 1);\n\n // Maximum iterations to prevent infinite loop\n const maxIterations = 366 * 24 * 60; // 1 year in minutes\n let iterations = 0;\n\n while (iterations < maxIterations) {\n iterations++;\n\n // Check month\n const month = next.getMonth() + 1; // JS months are 0-based\n if (!fields.month.includes(month)) {\n // Move to next valid month\n const nextMonth = fields.month.find((m) => m > month);\n if (nextMonth !== undefined) {\n next.setMonth(nextMonth - 1, 1);\n } else {\n // Next year, first valid month\n next.setFullYear(next.getFullYear() + 1);\n next.setMonth(fields.month[0] - 1, 1);\n }\n next.setHours(fields.hour[0], fields.minute[0], 0, 0);\n continue;\n }\n\n // Check day of month\n const dayOfMonth = next.getDate();\n const maxDayOfMonth = new Date(\n next.getFullYear(),\n next.getMonth() + 1,\n 0\n ).getDate();\n\n // Check day of week\n const dayOfWeek = next.getDay();\n\n // Both dayOfMonth and dayOfWeek must match if not wildcard\n const dayOfMonthMatch = fields.dayOfMonth.includes(dayOfMonth);\n const dayOfWeekMatch = fields.dayOfWeek.includes(dayOfWeek);\n\n // If either field is not *, both must match; if one is *, only the other needs to match\n const dayOfMonthWildcard =\n fields.dayOfMonth.length === 31 &&\n fields.dayOfMonth[0] === 1 &&\n fields.dayOfMonth[30] === 31;\n const dayOfWeekWildcard =\n fields.dayOfWeek.length >= 7 ||\n (fields.dayOfWeek.length === 1 && fields.dayOfWeek.includes(0));\n\n let dayMatch: boolean;\n if (dayOfMonthWildcard && dayOfWeekWildcard) {\n dayMatch = true;\n } else if (dayOfMonthWildcard) {\n dayMatch = dayOfWeekMatch;\n } else if (dayOfWeekWildcard) {\n dayMatch = dayOfMonthMatch;\n } else {\n // Standard cron behavior: OR between dayOfMonth and dayOfWeek when both are specified\n dayMatch = dayOfMonthMatch || dayOfWeekMatch;\n }\n\n if (!dayMatch || dayOfMonth > maxDayOfMonth) {\n // Move to next day\n next.setDate(next.getDate() + 1);\n next.setHours(fields.hour[0], fields.minute[0], 0, 0);\n continue;\n }\n\n // Check hour\n const hour = next.getHours();\n if (!fields.hour.includes(hour)) {\n const nextHour = fields.hour.find((h) => h > hour);\n if (nextHour !== undefined) {\n next.setHours(nextHour, fields.minute[0], 0, 0);\n } else {\n // Next day, first valid hour\n next.setDate(next.getDate() + 1);\n next.setHours(fields.hour[0], fields.minute[0], 0, 0);\n }\n continue;\n }\n\n // Check minute\n const minute = next.getMinutes();\n if (!fields.minute.includes(minute)) {\n const nextMinute = fields.minute.find((m) => m > minute);\n if (nextMinute !== undefined) {\n next.setMinutes(nextMinute, 0, 0);\n } else {\n // Next hour\n next.setHours(next.getHours() + 1, fields.minute[0], 0, 0);\n }\n continue;\n }\n\n // All fields match!\n return next;\n }\n\n throw new Error(\"Could not find next cron time within 1 year\");\n}\n\n/**\n * Validate a cron expression\n */\nexport function isValidCronExpression(expression: string): boolean {\n try {\n parseCronExpression(expression);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get a human-readable description of a cron expression\n */\nexport function describeCronExpression(expression: string): string {\n const fields = parseCronExpression(expression);\n\n const parts: string[] = [];\n\n // Minute\n if (fields.minute.length === 60) {\n parts.push(\"every minute\");\n } else if (fields.minute.length === 1) {\n parts.push(`at minute ${fields.minute[0]}`);\n } else {\n parts.push(`at minutes ${fields.minute.join(\", \")}`);\n }\n\n // Hour\n if (fields.hour.length === 24) {\n parts.push(\"of every hour\");\n } else if (fields.hour.length === 1) {\n parts.push(`of hour ${fields.hour[0]}`);\n } else {\n parts.push(`of hours ${fields.hour.join(\", \")}`);\n }\n\n // Day of month\n if (fields.dayOfMonth.length < 31) {\n if (fields.dayOfMonth.length === 1) {\n parts.push(`on day ${fields.dayOfMonth[0]}`);\n } else {\n parts.push(`on days ${fields.dayOfMonth.join(\", \")}`);\n }\n }\n\n // Month\n const monthNames = [\n \"\",\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n ];\n if (fields.month.length < 12) {\n const months = fields.month.map((m) => monthNames[m]);\n parts.push(`in ${months.join(\", \")}`);\n }\n\n // Day of week\n const dayNames = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n const uniqueDays = [...new Set(fields.dayOfWeek)];\n if (uniqueDays.length < 7) {\n const days = uniqueDays.map((d) => dayNames[d]);\n parts.push(`on ${days.join(\", \")}`);\n }\n\n return parts.join(\" \");\n}\n","import { Embeddings } from \"@langchain/core/embeddings\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\n\n/**\n * Embeddings Lattice Interface\n * Defines the structure of an embeddings lattice entry\n */\nexport interface EmbeddingsLatticeInterface {\n key: string;\n client: Embeddings;\n}\n\n/**\n * EmbeddingsLatticeManager - Singleton embeddings Lattice manager\n * Responsible for registering and managing various embeddings model Lattices\n */\nexport class EmbeddingsLatticeManager extends BaseLatticeManager<EmbeddingsLatticeInterface> {\n private static _instance: EmbeddingsLatticeManager;\n\n /**\n * Get EmbeddingsLatticeManager singleton instance\n */\n public static getInstance(): EmbeddingsLatticeManager {\n if (!EmbeddingsLatticeManager._instance) {\n EmbeddingsLatticeManager._instance = new EmbeddingsLatticeManager();\n }\n return EmbeddingsLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"embeddings\";\n }\n\n /**\n * Register embeddings Lattice\n * @param key Lattice key name\n * @param embeddings Embeddings instance\n */\n public registerLattice(key: string, embeddings: Embeddings): void {\n // Create embeddings Lattice object\n const embeddingsLattice: EmbeddingsLatticeInterface = {\n key,\n client: embeddings,\n };\n\n // Call base class register method\n this.register(key, embeddingsLattice);\n }\n\n /**\n * Get EmbeddingsLattice\n * @param key Lattice key name\n */\n public getEmbeddingsLattice(key: string): EmbeddingsLatticeInterface {\n const embeddingsLattice = this.get(key);\n if (!embeddingsLattice) {\n throw new Error(`EmbeddingsLattice ${key} not found`);\n }\n return embeddingsLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): EmbeddingsLatticeInterface[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * Get embeddings client\n * @param key Lattice key name\n */\n public getEmbeddingsClient(key: string): Embeddings {\n const embeddingsLattice = this.getEmbeddingsLattice(key);\n return embeddingsLattice.client;\n }\n}\n\n// Export singleton instance\nexport const embeddingsLatticeManager = EmbeddingsLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerEmbeddingsLattice = (\n key: string,\n embeddings: Embeddings\n) => embeddingsLatticeManager.registerLattice(key, embeddings);\n\nexport const getEmbeddingsLattice = (key: string) =>\n embeddingsLatticeManager.getEmbeddingsLattice(key);\n\nexport const getEmbeddingsClient = (key: string) =>\n embeddingsLatticeManager.getEmbeddingsClient(key);\n","import { VectorStore } from \"@langchain/core/vectorstores\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\n\n/**\n * VectorStore Lattice Interface\n * Defines the structure of a vector store lattice entry\n */\nexport interface VectorStoreLatticeInterface {\n key: string;\n client: VectorStore;\n}\n\n/**\n * VectorStoreLatticeManager - Singleton vector store Lattice manager\n * Responsible for registering and managing various vector store Lattices\n */\nexport class VectorStoreLatticeManager extends BaseLatticeManager<VectorStoreLatticeInterface> {\n private static _instance: VectorStoreLatticeManager;\n\n /**\n * Get VectorStoreLatticeManager singleton instance\n */\n public static getInstance(): VectorStoreLatticeManager {\n if (!VectorStoreLatticeManager._instance) {\n VectorStoreLatticeManager._instance = new VectorStoreLatticeManager();\n }\n return VectorStoreLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"vectorstores\";\n }\n\n /**\n * Register vector store Lattice\n * @param key Lattice key name\n * @param vectorStore VectorStore instance\n */\n public registerLattice(key: string, vectorStore: VectorStore): void {\n // Create vector store Lattice object\n const vectorStoreLattice: VectorStoreLatticeInterface = {\n key,\n client: vectorStore,\n };\n\n // Call base class register method\n this.register(key, vectorStoreLattice);\n }\n\n /**\n * Get VectorStoreLattice\n * @param key Lattice key name\n */\n public getVectorStoreLattice(key: string): VectorStoreLatticeInterface {\n const vectorStoreLattice = this.get(key);\n if (!vectorStoreLattice) {\n throw new Error(`VectorStoreLattice ${key} not found`);\n }\n return vectorStoreLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): VectorStoreLatticeInterface[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * Get vector store client\n * @param key Lattice key name\n */\n public getVectorStoreClient(key: string): VectorStore {\n const vectorStoreLattice = this.getVectorStoreLattice(key);\n return vectorStoreLattice.client;\n }\n}\n\n// Export singleton instance\nexport const vectorStoreLatticeManager = VectorStoreLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerVectorStoreLattice = (key: string, vectorStore: VectorStore) =>\n vectorStoreLatticeManager.registerLattice(key, vectorStore);\n\nexport const getVectorStoreLattice = (key: string) =>\n vectorStoreLatticeManager.getVectorStoreLattice(key);\n\nexport const getVectorStoreClient = (key: string) =>\n vectorStoreLatticeManager.getVectorStoreClient(key);\n\n","/**\n * LoggerLatticeManager\n *\n * Logger Lattice manager for registering and managing logger services\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n LoggerLatticeProtocol,\n LoggerConfig,\n LoggerType,\n LoggerClient,\n} from \"@axiom-lattice/protocols\";\nimport { PinoLoggerClient } from \"./PinoLoggerClient\";\nimport { ConsoleLoggerClient } from \"./ConsoleLoggerClient\";\n\n/**\n * Logger Lattice interface\n */\nexport interface LoggerLattice extends LoggerLatticeProtocol {\n key: string;\n config: LoggerConfig;\n client: LoggerLatticeProtocol[\"client\"];\n}\n\n/**\n * LoggerLatticeManager - Singleton logger Lattice manager\n * Responsible for registering and managing various logger service Lattices\n */\nexport class LoggerLatticeManager extends BaseLatticeManager<LoggerLattice> {\n private static _instance: LoggerLatticeManager;\n\n /**\n * Get LoggerLatticeManager singleton instance\n */\n public static getInstance(): LoggerLatticeManager {\n if (!LoggerLatticeManager._instance) {\n LoggerLatticeManager._instance = new LoggerLatticeManager();\n }\n return LoggerLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"loggers\";\n }\n\n /**\n * Register logger Lattice\n * @param key Lattice key name\n * @param config Logger configuration\n * @param client Optional logger client. If not provided, will create based on config type.\n */\n public registerLattice(\n key: string,\n config: LoggerConfig,\n client?: LoggerClient\n ): void {\n // Create client based on logger type if not provided\n let loggerClient: LoggerLatticeProtocol[\"client\"];\n\n if (client) {\n // Use provided client\n loggerClient = client;\n } else {\n if (config.type === LoggerType.PINO) {\n loggerClient = new PinoLoggerClient(config);\n } else if (config.type === LoggerType.CONSOLE) {\n loggerClient = new ConsoleLoggerClient(config);\n } else if (config.type === LoggerType.CUSTOM) {\n // For custom type, client must be provided\n throw new Error(\n `Custom logger client must be provided. Please pass the client to registerLattice.`\n );\n } else {\n // Default to pino\n loggerClient = new PinoLoggerClient(config);\n }\n }\n\n // Create logger Lattice object\n const loggerLattice: LoggerLattice = {\n key,\n config,\n client: loggerClient,\n\n // Logger operations\n info: (msg: string, obj?: object) => {\n loggerClient.info(msg, obj);\n },\n error: (msg: string, obj?: object | Error) => {\n loggerClient.error(msg, obj);\n },\n warn: (msg: string, obj?: object) => {\n loggerClient.warn(msg, obj);\n },\n debug: (msg: string, obj?: object) => {\n loggerClient.debug(msg, obj);\n },\n updateContext: loggerClient.updateContext\n ? (context) => {\n loggerClient.updateContext!(context);\n }\n : undefined,\n child: loggerClient.child\n ? (options) => {\n return loggerClient.child!(options);\n }\n : undefined,\n };\n\n // Call base class register method\n this.register(key, loggerLattice);\n }\n\n /**\n * Get LoggerLattice\n * @param key Lattice key name\n */\n public getLoggerLattice(key: string): LoggerLattice {\n const loggerLattice = this.get(key);\n if (!loggerLattice) {\n throw new Error(`LoggerLattice ${key} not found`);\n }\n return loggerLattice;\n }\n\n /**\n * Get all Lattices\n */\n public getAllLattices(): LoggerLattice[] {\n return this.getAll();\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public removeLattice(key: string): boolean {\n return this.remove(key);\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n}\n\n// Export singleton instance\nexport const loggerLatticeManager = LoggerLatticeManager.getInstance();\n\n// Export convenience methods\nexport const registerLoggerLattice = (\n key: string,\n config: LoggerConfig,\n client?: LoggerClient\n) => loggerLatticeManager.registerLattice(key, config, client);\n\nexport const getLoggerLattice = (key: string) =>\n loggerLatticeManager.getLoggerLattice(key);\n","/**\n * PinoLoggerClient\n *\n * Pino-based logger client implementation\n */\n\nimport pino from \"pino\";\nimport \"pino-pretty\";\nimport \"pino-roll\";\nimport {\n LoggerClient,\n LoggerContext,\n LoggerConfig,\n PinoFileOptions,\n} from \"@axiom-lattice/protocols\";\n\n/**\n * Pino-based logger client implementation\n * Supports custom file paths and pino configurations\n */\nexport class PinoLoggerClient implements LoggerClient {\n private pinoLogger: pino.Logger;\n private config: LoggerConfig;\n private context: LoggerContext;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n this.context = config.context || {};\n\n // Create pino logger with custom configuration\n const loggerConfig: pino.LoggerOptions = {\n // Custom timestamp format\n timestamp: () => `,\"@timestamp\":\"${new Date().toISOString()}\"`,\n\n // Base metadata\n base: {\n \"@version\": \"1\",\n app_name: \"lattice\",\n service_name: config.serviceName || \"lattice-service\",\n thread_name: \"main\",\n logger_name: config.loggerName || config.name || \"lattice-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 // Determine if we should use file logging\n const useFileLogging = this.shouldUseFileLogging(config);\n const fileOptions = this.getFileOptions(config);\n\n if (useFileLogging && fileOptions) {\n // Use file logging with pino-roll\n try {\n this.pinoLogger = pino(\n loggerConfig,\n pino.transport({\n target: \"pino-roll\",\n options: {\n file: fileOptions.file || \"./logs/app\",\n frequency: fileOptions.frequency || \"daily\",\n mkdir: fileOptions.mkdir !== false, // Default to true\n size: fileOptions.size,\n maxFiles: fileOptions.maxFiles,\n },\n })\n );\n } catch (error) {\n console.error(\n \"Failed to initialize pino-roll logger, falling back to console\",\n error\n );\n // Fallback to console logging\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n } else {\n // Use console logging with pretty output\n this.pinoLogger = pino({\n ...loggerConfig,\n transport: {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n },\n });\n }\n }\n\n /**\n * Determine if file logging should be used\n */\n private shouldUseFileLogging(config: LoggerConfig): boolean {\n // Use file logging if:\n // 1. file option is provided, OR\n // 2. NODE_ENV is production (unless explicitly disabled)\n const hasFileConfig = config.file !== undefined;\n const isProduction = process.env.NODE_ENV === \"production\";\n return hasFileConfig || isProduction;\n }\n\n /**\n * Get file options from config\n */\n private getFileOptions(config: LoggerConfig): PinoFileOptions | null {\n if (!config.file) {\n // If no file config but in production, use default\n if (process.env.NODE_ENV === \"production\") {\n return {\n file: \"./logs/app\",\n frequency: \"daily\",\n mkdir: true,\n };\n }\n return null;\n }\n\n // If file is a string, convert to PinoFileOptions\n if (typeof config.file === \"string\") {\n return {\n file: config.file,\n frequency: \"daily\",\n mkdir: true,\n };\n }\n\n // Otherwise, it's already PinoFileOptions\n return config.file;\n }\n\n /**\n * Get contextual logger with merged context\n */\n private getContextualLogger(additionalContext?: object): pino.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-thread-id\": this.context[\"x-thread-id\"] || \"\",\n service_name: this.config.serviceName || \"lattice-service\",\n logger_name:\n this.config.loggerName || this.config.name || \"lattice-logger\",\n ...additionalContext,\n };\n\n return this.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 updateContext(context: Partial<LoggerContext>): void {\n this.context = {\n ...this.context,\n ...context,\n };\n }\n\n child(options: Partial<LoggerConfig>): LoggerClient {\n // Create a new PinoLoggerClient with merged config\n return new PinoLoggerClient({\n ...this.config,\n ...options,\n context: {\n ...this.context,\n ...options.context,\n },\n });\n }\n}\n","/**\n * ConsoleLoggerClient\n *\n * Simple console-based logger client implementation\n */\n\nimport { LoggerClient, LoggerContext, LoggerConfig } from \"@axiom-lattice/protocols\";\n\n/**\n * Console-based logger client implementation\n */\nexport class ConsoleLoggerClient implements LoggerClient {\n private config: LoggerConfig;\n private context: LoggerContext;\n\n constructor(config: LoggerConfig) {\n this.config = config;\n this.context = config.context || {};\n }\n\n private formatMessage(level: string, msg: string, obj?: object): string {\n const timestamp = new Date().toISOString();\n const contextStr = Object.keys(this.context).length > 0\n ? ` [${JSON.stringify(this.context)}]`\n : \"\";\n const objStr = obj ? ` ${JSON.stringify(obj)}` : \"\";\n return `[${timestamp}] [${level}]${contextStr} ${msg}${objStr}`;\n }\n\n info(msg: string, obj?: object): void {\n console.log(this.formatMessage(\"INFO\", msg, obj));\n }\n\n error(msg: string, obj?: object | Error): void {\n console.error(this.formatMessage(\"ERROR\", msg, obj));\n }\n\n warn(msg: string, obj?: object): void {\n console.warn(this.formatMessage(\"WARN\", msg, obj));\n }\n\n debug(msg: string, obj?: object): void {\n console.debug(this.formatMessage(\"DEBUG\", msg, obj));\n }\n\n updateContext(context: Partial<LoggerContext>): void {\n this.context = {\n ...this.context,\n ...context,\n };\n }\n\n child(options: Partial<LoggerConfig>): LoggerClient {\n const childClient = new ConsoleLoggerClient({\n ...this.config,\n ...options,\n context: {\n ...this.context,\n ...options.context,\n },\n });\n return childClient;\n }\n}\n","/**\n * SkillLatticeManager\n *\n * Skill Lattice manager for registering and managing skill components\n */\n\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport {\n SkillConfig,\n SkillLatticeProtocol,\n SkillClient,\n SkillClientType,\n SkillStore,\n} from \"@axiom-lattice/protocols\";\nimport { storeLatticeManager } from \"../store_lattice/StoreLatticeManager\";\nimport { validateSkillName } from \"./skillNameValidator\";\n\n/**\n * Skill Lattice interface\n */\nexport interface SkillLattice {\n key: string;\n config: SkillConfig;\n client: SkillClient | null;\n}\n\n/**\n * SkillLatticeManager - Singleton skill Lattice manager\n * Responsible for registering and managing various skill Lattices\n */\nexport class SkillLatticeManager extends BaseLatticeManager<SkillLattice> {\n private static _instance: SkillLatticeManager;\n private storeKey?: string;\n\n /**\n * Get SkillLatticeManager singleton instance\n */\n public static getInstance(): SkillLatticeManager {\n if (!SkillLatticeManager._instance) {\n SkillLatticeManager._instance = new SkillLatticeManager();\n }\n return SkillLatticeManager._instance;\n }\n\n /**\n * Get Lattice type prefix\n */\n protected getLatticeType(): string {\n return \"skills\";\n }\n\n /**\n * Configure store for persistence\n * @param storeKey Store key name registered in StoreLatticeManager\n */\n public configureStore(storeKey: string): void {\n this.storeKey = storeKey;\n }\n\n /**\n * Get configured store\n * @returns SkillStore instance if configured, null otherwise\n */\n private getStore(): SkillStore | null {\n if (!this.storeKey) {\n return null;\n }\n\n try {\n const storeLattice = storeLatticeManager.getStoreLattice(\n this.storeKey,\n \"skill\"\n );\n return storeLattice.store;\n } catch {\n return null;\n }\n }\n\n /**\n * Inject store into client if client supports it\n * @param client Skill client instance\n * @param store Store instance to inject\n */\n private injectStoreIntoClient(client: SkillClientType, store: SkillStore): void {\n if (!client || typeof client !== \"object\") {\n return;\n }\n\n // Try setStore method first\n if (typeof client.setStore === \"function\") {\n client.setStore(store);\n }\n\n // Also set store property directly\n client.store = store;\n }\n\n /**\n * Register a skill Lattice\n * @param key Lattice key name\n * @param config Skill configuration\n * @param client Optional skill client implementation\n */\n public async registerLattice(\n key: string,\n config: SkillConfig,\n client?: SkillClient\n ): Promise<void> {\n // Validate required fields\n if (!config.name) {\n throw new Error(\"Skill name is required\");\n }\n if (!config.description) {\n throw new Error(\"Skill description is required\");\n }\n\n // Validate name format\n validateSkillName(config.name);\n\n // Validate that key equals name (name is used for path addressing)\n if (key !== config.name) {\n throw new Error(\n `Skill key \"${key}\" must equal name \"${config.name}\" (name is used for path addressing)`\n );\n }\n\n // Get store instance\n const store = this.getStore();\n\n // Inject store into client if provided\n if (client && store) {\n this.injectStoreIntoClient(client, store);\n }\n\n // Create skill Lattice object\n const skillLattice: SkillLattice = {\n key,\n config,\n client: client ?? null,\n };\n\n // Call base class register method\n this.register(key, skillLattice);\n\n // Persist to store if configured\n if (store) {\n try {\n await store.createSkill(key, {\n name: config.name,\n description: config.description,\n license: config.license,\n compatibility: config.compatibility,\n metadata: config.metadata,\n content: config.content,\n subSkills: config.subSkills,\n });\n } catch (error) {\n // Log error but don't fail registration\n console.warn(\n `Failed to persist skill ${key} to store:`,\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n }\n\n /**\n * Get skill Lattice by key\n * @param key Lattice key name\n */\n public getSkillLattice(key: string): SkillLattice | undefined {\n return this.get(key);\n }\n\n /**\n * Get all skill Lattices from store\n * Always reads from the configured store and merges with in-memory clients\n */\n public async getAllLattices(): Promise<SkillLattice[]> {\n const store = this.getStore();\n if (!store) {\n // If no store configured, fall back to memory\n return this.getAll();\n }\n\n const skills = await store.getAllSkills();\n\n return skills.map((skill) => {\n // Check if there's an in-memory lattice with a client\n const memoryLattice = this.get(skill.id);\n const client = memoryLattice?.client || null;\n\n // Inject store into client if it exists\n if (client && store) {\n this.injectStoreIntoClient(client, store);\n }\n\n return {\n key: skill.id,\n config: {\n name: skill.name,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n content: skill.content,\n subSkills: skill.subSkills,\n },\n client,\n };\n });\n }\n\n /**\n * Check if Lattice exists\n * @param key Lattice key name\n */\n public hasLattice(key: string): boolean {\n return this.has(key);\n }\n\n /**\n * Remove Lattice\n * @param key Lattice key name\n */\n public async removeLattice(key: string): Promise<boolean> {\n const removed = this.remove(key);\n\n // Remove from store if configured\n if (removed) {\n const store = this.getStore();\n if (store) {\n try {\n await store.deleteSkill(key);\n } catch (error) {\n // Log error but don't fail removal\n console.warn(\n `Failed to remove skill ${key} from store:`,\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n }\n\n return removed;\n }\n\n /**\n * Clear all Lattices\n */\n public clearLattices(): void {\n this.clear();\n }\n\n /**\n * Get Lattice count\n */\n public getLatticeCount(): number {\n return this.count();\n }\n\n /**\n * Get Lattice key name list\n */\n public getLatticeKeys(): string[] {\n return this.keys();\n }\n\n /**\n * Get skill configuration\n * @param key Lattice key name\n */\n public getSkillConfig(key: string): SkillConfig {\n const skillLattice = this.getSkillLattice(key);\n if (!skillLattice) {\n throw new Error(`SkillLattice ${key} not found`);\n }\n return skillLattice.config;\n }\n\n /**\n * Get skill client\n * Ensures client has store access if store is configured\n * @param key Lattice key name\n */\n public getSkillClient(key: string): SkillClient | null {\n const skillLattice = this.getSkillLattice(key);\n if (!skillLattice) {\n throw new Error(`SkillLattice ${key} not found`);\n }\n\n const client = skillLattice.client;\n if (!client) {\n return null;\n }\n\n // Ensure client has store access if store is configured\n const store = this.getStore();\n if (store && client) {\n this.injectStoreIntoClient(client, store);\n }\n\n return client;\n }\n\n /**\n * Get all skill configurations from store\n * Always reads from the configured store, not from memory\n */\n public async getAllSkillConfigs(): Promise<SkillConfig[]> {\n const lattices = await this.getAllLattices();\n return lattices.map((lattice) => lattice.config);\n }\n\n /**\n * Search skills by metadata\n * @param metadataKey Metadata key to search for\n * @param metadataValue Metadata value to match\n */\n public async searchByMetadata(\n metadataKey: string,\n metadataValue: string\n ): Promise<SkillLattice[]> {\n const lattices = await this.getAllLattices();\n return lattices.filter((lattice) => {\n return (\n lattice.config.metadata &&\n lattice.config.metadata[metadataKey] === metadataValue\n );\n });\n }\n\n /**\n * Filter skills by compatibility\n * @param compatibility Compatibility string to filter by\n */\n public async filterByCompatibility(compatibility: string): Promise<SkillLattice[]> {\n const lattices = await this.getAllLattices();\n return lattices.filter((lattice) => {\n return lattice.config.compatibility === compatibility;\n });\n }\n\n /**\n * Filter skills by license\n * @param license License string to filter by\n */\n public async filterByLicense(license: string): Promise<SkillLattice[]> {\n const lattices = await this.getAllLattices();\n return lattices.filter((lattice) => {\n return lattice.config.license === license;\n });\n }\n\n /**\n * Load skills from configured store\n * This method loads all skills from the store and registers them in memory\n */\n public async loadFromStore(): Promise<void> {\n const store = this.getStore();\n if (!store) {\n throw new Error(\"No store configured. Call configureStore() first.\");\n }\n\n const skills = await store.getAllSkills();\n for (const skill of skills) {\n // Register skill in memory without persisting back to store\n const skillLattice: SkillLattice = {\n key: skill.id,\n config: {\n name: skill.name,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n metadata: skill.metadata,\n content: skill.content,\n subSkills: skill.subSkills,\n },\n client: null,\n };\n\n // Use base class register method directly to avoid double persistence\n this.register(skill.id, skillLattice);\n\n // Note: If a client is later added to this skill, it will receive store access\n // via getSkillClient() method\n }\n }\n\n /**\n * Update skill in store\n * @param key Skill key\n * @param updates Partial skill data to update\n */\n public async updateSkillInStore(\n key: string,\n updates: Partial<SkillConfig>\n ): Promise<void> {\n const store = this.getStore();\n if (!store) {\n throw new Error(\"No store configured. Call configureStore() first.\");\n }\n\n // Update in memory\n const skillLattice = this.getSkillLattice(key);\n if (!skillLattice) {\n throw new Error(`SkillLattice ${key} not found`);\n }\n\n const updatedConfig: SkillConfig = {\n ...skillLattice.config,\n ...updates,\n };\n\n skillLattice.config = updatedConfig;\n\n // Update in store\n await store.updateSkill(key, {\n name: updatedConfig.name,\n description: updatedConfig.description,\n license: updatedConfig.license,\n compatibility: updatedConfig.compatibility,\n metadata: updatedConfig.metadata,\n content: updatedConfig.content,\n subSkills: updatedConfig.subSkills,\n });\n }\n}\n\n// Export singleton instance\nexport const skillLatticeManager = SkillLatticeManager.getInstance();\n","/**\n * McpLatticeManager\n *\n * MCP Lattice Manager - Manages MCP client connections using MultiServerMCPClient\n * Follows the singleton pattern for global access\n */\n\nimport { MultiServerMCPClient } from \"@langchain/mcp-adapters\";\nimport { BaseLatticeManager } from \"../base/BaseLatticeManager\";\nimport type { Connection } from \"@langchain/mcp-adapters\";\nimport { toolLatticeManager } from \"../tool_lattice\";\n\nexport interface McpServerInfo {\n name: string;\n connection: Connection;\n}\n\nexport interface McpLatticeInterface {\n client: MultiServerMCPClient;\n servers: Map<string, McpServerInfo>;\n}\n\nexport class McpLatticeManager extends BaseLatticeManager<McpLatticeInterface> {\n private static _instance: McpLatticeManager;\n private client: MultiServerMCPClient | null = null;\n private servers: Map<string, McpServerInfo> = new Map();\n\n public static getInstance(): McpLatticeManager {\n if (!McpLatticeManager._instance) {\n McpLatticeManager._instance = new McpLatticeManager();\n }\n return McpLatticeManager._instance;\n }\n\n protected getLatticeType(): string {\n return \"mcp\";\n }\n\n public registerServers(servers: McpServerInfo[]): void {\n for (const server of servers) {\n if (this.servers.has(server.name)) {\n console.warn(`[MCP] Server '${server.name}' already registered, skipping`);\n continue;\n }\n this.servers.set(server.name, server);\n console.log(`[MCP] Registered server: ${server.name}`);\n }\n }\n\n public addServer(name: string, connection: Connection): void {\n this.registerServers([{ name, connection }]);\n }\n\n public removeServer(name: string): boolean {\n const deleted = this.servers.delete(name);\n if (deleted) {\n console.log(`[MCP] Removed server: ${name}`);\n }\n return deleted;\n }\n\n public async connect(): Promise<void> {\n if (this.client) {\n console.warn(\"[MCP] Client already connected\");\n return;\n }\n\n const serverConfigs: Record<string, Connection> = {};\n for (const [name, info] of this.servers) {\n serverConfigs[name] = info.connection;\n }\n\n if (Object.keys(serverConfigs).length === 0) {\n console.warn(\"[MCP] No servers registered\");\n return;\n }\n\n this.client = new MultiServerMCPClient({\n mcpServers: serverConfigs,\n });\n\n console.log(`[MCP] Connecting to ${this.servers.size} servers...`);\n await this.client.initializeConnections();\n console.log(\"[MCP] All servers connected\");\n }\n\n public async disconnect(): Promise<void> {\n if (this.client) {\n await this.client.close();\n this.client = null;\n console.log(\"[MCP] Disconnected\");\n }\n }\n\n public isConnected(): boolean {\n return this.client !== null;\n }\n\n public async getAllTools(): Promise<any[]> {\n if (!this.client) {\n throw new Error(\"MCP client not connected\");\n }\n return this.client.getTools();\n }\n\n public getServerNames(): string[] {\n return Array.from(this.servers.keys());\n }\n\n public hasServer(name: string): boolean {\n return this.servers.has(name);\n }\n\n /**\n * 将 MCP 工具注册到 Tool Lattice\n * @param prefix 工具键名前缀,用于区分不同服务器的工具\n */\n public async registerToolsToToolLattice(prefix?: string): Promise<void> {\n if (!this.client) {\n throw new Error(\"MCP client not connected\");\n }\n\n const tools = await this.getAllTools();\n console.log(`[MCP] Registering ${tools.length} tools to Tool Lattice...`);\n\n for (const tool of tools) {\n const toolKey = prefix ? `${prefix}_${tool.name}` : tool.name;\n tool.name = toolKey;\n toolLatticeManager.registerExistingTool(toolKey, tool);\n console.log(`[MCP] Registered tool: ${toolKey}`);\n }\n\n console.log(`[MCP] Successfully registered ${tools.length} tools to Tool Lattice`);\n }\n}\n\nexport const mcpManager = McpLatticeManager.getInstance();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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C,KAAK,QAAQ;AAChB,YAAM,IAAI,MAAM,0BAA0B;AAAA,IAC5C;AACA,WAAO,KAAK,OAAO,SAAS;AAAA,EAC9B;AAAA,EAEO,iBAA2B;AAChC,WAAO,MAAM,KAAK,KAAK,QAAQ,KAAK,CAAC;AAAA,EACvC;AAAA,EAEO,UAAU,MAAuB;AACtC,WAAO,KAAK,QAAQ,IAAI,IAAI;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAa,2BAA2B,QAAgC;AACtE,QAAI,CAAC,KAAK,QAAQ;AAChB,YAAM,IAAI,MAAM,0BAA0B;AAAA,IAC5C;AAEA,UAAM,QAAQ,MAAM,KAAK,YAAY;AACrC,YAAQ,IAAI,qBAAqB,MAAM,MAAM,2BAA2B;AAExE,eAAWC,UAAQ,OAAO;AACxB,YAAM,UAAU,SAAS,GAAG,MAAM,IAAIA,OAAK,IAAI,KAAKA,OAAK;AACzD,MAAAA,OAAK,OAAO;AACZ,yBAAmB,qBAAqB,SAASA,MAAI;AACrD,cAAQ,IAAI,0BAA0B,OAAO,EAAE;AAAA,IACjD;AAEA,YAAQ,IAAI,iCAAiC,MAAM,MAAM,wBAAwB;AAAA,EACnF;AACF;AAEO,IAAM,aAAa,kBAAkB,YAAY;;;A5F9GxD,gBAA2B;","names":["tool","z","import_zod","z","import_zod","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_zod","import_langchain","z","import_langgraph","import_protocols","import_zod","import_langgraph","import_langchain","import_sandbox","path","relative","import_langchain","import_langchain","import_langchain","import_langchain","path","colonIndex","key","value","import_zod","import_langchain","z","import_zod","import_langchain","z","import_langchain","import_langgraph","import_zod","path","relative","micromatch","path","micromatch","path","relative","z3","result","path","tool","stateSchema","import_langchain","import_v3","import_langchain","import_langgraph","import_langgraph","import_protocols","resolve","import_langchain","import_messages","import_langgraph","import_micromatch","import_langgraph","import_zod","import_langchain","tool","import_protocols","ThreadStatus","resolve","import_protocols","import_protocols","import_protocols","import_protocols","pino","tool"]}