@axiom-lattice/core 2.1.44 → 2.1.46

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 CHANGED
@@ -48,7 +48,7 @@ __export(index_exports, {
48
48
  FileSystemSkillStore: () => FileSystemSkillStore,
49
49
  FilesystemBackend: () => FilesystemBackend,
50
50
  GraphBuildOptions: () => import_protocols.GraphBuildOptions,
51
- HumanMessage: () => import_messages3.HumanMessage,
51
+ HumanMessage: () => import_messages4.HumanMessage,
52
52
  InMemoryAssistantStore: () => InMemoryAssistantStore,
53
53
  InMemoryChunkBuffer: () => InMemoryChunkBuffer,
54
54
  InMemoryDatabaseConfigStore: () => InMemoryDatabaseConfigStore,
@@ -116,6 +116,7 @@ __export(index_exports, {
116
116
  createQueryTablesListTool: () => createQueryTablesListTool,
117
117
  createTeamMiddleware: () => createTeamMiddleware,
118
118
  createTeammateTools: () => createTeammateTools,
119
+ createUnknownToolHandlerMiddleware: () => createUnknownToolHandlerMiddleware,
119
120
  createWidgetMiddleware: () => createWidgetMiddleware,
120
121
  decrypt: () => decrypt,
121
122
  describeCronExpression: () => describeCronExpression,
@@ -845,11 +846,11 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
845
846
  * @param key Lattice键名
846
847
  * @param tool 已有的StructuredTool实例
847
848
  */
848
- registerExistingTool(key, tool50) {
849
+ registerExistingTool(key, tool51) {
849
850
  const config = {
850
- name: tool50.name,
851
- description: tool50.description,
852
- schema: tool50.schema,
851
+ name: tool51.name,
852
+ description: tool51.description,
853
+ schema: tool51.schema,
853
854
  // StructuredTool的schema已经是Zod兼容的
854
855
  needUserApprove: false
855
856
  // MCP工具默认不需要用户批准
@@ -857,7 +858,7 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
857
858
  const toolLattice = {
858
859
  key,
859
860
  config,
860
- client: tool50
861
+ client: tool51
861
862
  };
862
863
  this.register(key, toolLattice);
863
864
  }
@@ -883,7 +884,7 @@ var ToolLatticeManager = class _ToolLatticeManager extends BaseLatticeManager {
883
884
  };
884
885
  var toolLatticeManager = ToolLatticeManager.getInstance();
885
886
  var registerToolLattice = (key, config, executor) => toolLatticeManager.registerLattice(key, config, executor);
886
- var registerExistingTool = (key, tool50) => toolLatticeManager.registerExistingTool(key, tool50);
887
+ var registerExistingTool = (key, tool51) => toolLatticeManager.registerExistingTool(key, tool51);
887
888
  var getToolLattice = (key) => toolLatticeManager.getToolLattice(key);
888
889
  var getToolDefinition = (key) => toolLatticeManager.getToolDefinition(key);
889
890
  var getToolClient = (key) => toolLatticeManager.getToolClient(key);
@@ -4737,7 +4738,7 @@ var createBrowserGetInfoTool = ({ isolatedLevel }) => {
4737
4738
  };
4738
4739
 
4739
4740
  // src/index.ts
4740
- var import_messages3 = require("@langchain/core/messages");
4741
+ var import_messages4 = require("@langchain/core/messages");
4741
4742
 
4742
4743
  // src/agent_lattice/types.ts
4743
4744
  var import_protocols = require("@axiom-lattice/protocols");
@@ -4830,7 +4831,7 @@ var createReactAgentSchema = (schema) => {
4830
4831
  };
4831
4832
 
4832
4833
  // src/agent_lattice/builders/ReActAgentGraphBuilder.ts
4833
- var import_langchain53 = require("langchain");
4834
+ var import_langchain55 = require("langchain");
4834
4835
 
4835
4836
  // src/deep_agent_new/backends/sandboxFiles.ts
4836
4837
  var import_sandbox2 = require("@agent-infra/sandbox");
@@ -5200,7 +5201,7 @@ var InMemoryThreadStore = class {
5200
5201
  /**
5201
5202
  * Get all threads for a specific tenant and assistant
5202
5203
  */
5203
- async getThreadsByAssistantId(tenantId, assistantId) {
5204
+ async getThreadsByAssistantId(tenantId, assistantId, metadataFilter) {
5204
5205
  const tenantThreads = this.threads.get(tenantId);
5205
5206
  if (!tenantThreads) {
5206
5207
  return [];
@@ -5209,7 +5210,15 @@ var InMemoryThreadStore = class {
5209
5210
  if (!assistantThreads) {
5210
5211
  return [];
5211
5212
  }
5212
- return Array.from(assistantThreads.values());
5213
+ let threads = Array.from(assistantThreads.values());
5214
+ if (metadataFilter && Object.keys(metadataFilter).length > 0) {
5215
+ threads = threads.filter(
5216
+ (thread) => Object.entries(metadataFilter).every(
5217
+ ([key, value]) => thread.metadata?.[key] === value
5218
+ )
5219
+ );
5220
+ }
5221
+ return threads;
5213
5222
  }
5214
5223
  /**
5215
5224
  * Get a thread by ID for a specific tenant
@@ -6635,7 +6644,7 @@ var InMemoryThreadMessageQueueStore = class {
6635
6644
  return this.messages.get(threadId);
6636
6645
  }
6637
6646
  async addMessage(params) {
6638
- const { threadId, tenantId, assistantId, content, type = "human", priority = 0, command, id } = params;
6647
+ const { threadId, tenantId, assistantId, content, type = "human", priority = 0, command, custom_run_config, id } = params;
6639
6648
  const threadMessages = this.getMessagesForThread(threadId);
6640
6649
  const message = {
6641
6650
  id: id || this.generateId(),
@@ -6647,18 +6656,20 @@ var InMemoryThreadMessageQueueStore = class {
6647
6656
  tenantId,
6648
6657
  assistantId,
6649
6658
  priority,
6650
- command
6659
+ command,
6660
+ custom_run_config
6651
6661
  };
6652
6662
  threadMessages.push(message);
6653
6663
  return message;
6654
6664
  }
6655
- async addMessageAtHead(threadId, content, type = "system", id, command) {
6665
+ async addMessageAtHead(params) {
6666
+ const { threadId, tenantId, assistantId, content, type = "system", id, command, custom_run_config } = params;
6656
6667
  const threadMessages = this.getMessagesForThread(threadId);
6657
- let tenantId = "default";
6658
- let assistantId = "";
6659
- if (threadMessages.length > 0) {
6660
- tenantId = threadMessages[0].tenantId || "default";
6661
- assistantId = threadMessages[0].assistantId || "";
6668
+ let resolvedTenantId = tenantId || "default";
6669
+ let resolvedAssistantId = assistantId || "";
6670
+ if (!tenantId && !assistantId && threadMessages.length > 0) {
6671
+ resolvedTenantId = threadMessages[0].tenantId || "default";
6672
+ resolvedAssistantId = threadMessages[0].assistantId || "";
6662
6673
  }
6663
6674
  const nextSequence = threadMessages.length;
6664
6675
  const message = {
@@ -6668,11 +6679,12 @@ var InMemoryThreadMessageQueueStore = class {
6668
6679
  sequence: nextSequence,
6669
6680
  createdAt: /* @__PURE__ */ new Date(),
6670
6681
  status: "pending",
6671
- tenantId,
6672
- assistantId,
6682
+ tenantId: resolvedTenantId,
6683
+ assistantId: resolvedAssistantId,
6673
6684
  priority: 100,
6674
6685
  // High priority for head messages (STEER/Command)
6675
- command
6686
+ command,
6687
+ custom_run_config
6676
6688
  };
6677
6689
  threadMessages.push(message);
6678
6690
  return message;
@@ -9411,7 +9423,7 @@ function createShowWidgetTool() {
9411
9423
  },
9412
9424
  {
9413
9425
  name: "show_widget",
9414
- description: "Render an interactive HTML widget or SVG diagram visible to the user. Use for: charts, dashboards, calculators, forms, diagrams, timers, games, visualizations. The widget appears in a panel next to the chat. Users can interact with it and send data back via window.sendToAgent(data). IMPORTANT: Always call load_guidelines before your first show_widget.",
9426
+ description: "Render an interactive HTML widget or SVG diagram visible to the user. Use for: charts, dashboards, calculators, forms, diagrams, timers, games, visualizations. The widget appears in a panel next to the chat. Users can interact with it and send data back via window.sendPrompt(data). IMPORTANT: Always call load_guidelines before your first show_widget.",
9415
9427
  schema: ShowWidgetInputSchema
9416
9428
  }
9417
9429
  );
@@ -9942,9 +9954,198 @@ ${bootstrapSections.join("\n\n")}
9942
9954
  });
9943
9955
  }
9944
9956
 
9957
+ // src/middlewares/unknownToolHandlerMiddleware.ts
9958
+ var import_langchain53 = require("langchain");
9959
+ var import_messages = require("@langchain/core/messages");
9960
+ function createUnknownToolHandlerMiddleware(config = {}) {
9961
+ const {
9962
+ strategy = "error",
9963
+ errorMessageTemplate = (name, tools) => `Error: Tool "${name}" does not exist.
9964
+
9965
+ Available tools:
9966
+ ` + tools.map((t) => ` - ${t}`).join("\n") + `
9967
+
9968
+ Please select a valid tool from the list above.`
9969
+ } = config;
9970
+ return (0, import_langchain53.createMiddleware)({
9971
+ name: "UnknownToolHandlerMiddleware",
9972
+ /**
9973
+ * wrapModelCall hook
9974
+ *
9975
+ * The only place to access request.tools (all available tools).
9976
+ * Identifies unknown tools and stores error info in metadata.
9977
+ *
9978
+ * Key: Preserve all tool_calls in original AIMessage, including unknown ones.
9979
+ * This allows the model to see what it selected in the next round.
9980
+ */
9981
+ wrapModelCall: async (request, handler) => {
9982
+ const availableTools = request.tools || [];
9983
+ const availableToolNames = availableTools.map((t) => t.name);
9984
+ const availableToolSet = new Set(availableToolNames);
9985
+ const aiResponse = await handler(request);
9986
+ if (!aiResponse.tool_calls || aiResponse.tool_calls.length === 0) {
9987
+ return aiResponse;
9988
+ }
9989
+ const unknownToolCalls = [];
9990
+ for (const toolCall of aiResponse.tool_calls) {
9991
+ if (!availableToolSet.has(toolCall.name)) {
9992
+ unknownToolCalls.push(toolCall);
9993
+ }
9994
+ }
9995
+ if (unknownToolCalls.length === 0) {
9996
+ return aiResponse;
9997
+ }
9998
+ if (strategy === "strict") {
9999
+ const unknownNames = unknownToolCalls.map((t) => t.name).join(", ");
10000
+ throw new Error(
10001
+ `Unknown tools detected: ${unknownNames}. Available tools: ${availableToolNames.join(", ")}`
10002
+ );
10003
+ }
10004
+ const unknownToolErrors = unknownToolCalls.map((toolCall) => ({
10005
+ toolName: toolCall.name,
10006
+ toolCallId: toolCall.id,
10007
+ errorMessage: errorMessageTemplate(toolCall.name, availableToolNames)
10008
+ }));
10009
+ const modifiedResponse = new import_messages.AIMessage({
10010
+ content: aiResponse.content,
10011
+ tool_calls: aiResponse.tool_calls,
10012
+ // Key: preserve all tool_calls, don't delete unknown
10013
+ response_metadata: {
10014
+ ...aiResponse.response_metadata,
10015
+ _unknownToolErrors: unknownToolErrors
10016
+ }
10017
+ });
10018
+ if (aiResponse.id) {
10019
+ modifiedResponse.id = aiResponse.id;
10020
+ }
10021
+ return modifiedResponse;
10022
+ },
10023
+ /**
10024
+ * afterModel hook
10025
+ *
10026
+ * Processes unknown tool errors stored in metadata.
10027
+ * Generates error ToolMessages and jumps back to model.
10028
+ *
10029
+ * Key: Uses jumpTo: "model" to form agent loop.
10030
+ * Without jumpTo, the graph would end after ToolNode without returning to model.
10031
+ */
10032
+ afterModel: {
10033
+ canJumpTo: ["model"],
10034
+ hook: async (state) => {
10035
+ const { messages } = state;
10036
+ if (!messages || messages.length === 0) {
10037
+ return;
10038
+ }
10039
+ const lastMessage = messages[messages.length - 1];
10040
+ if (!import_messages.AIMessage.isInstance(lastMessage)) {
10041
+ return;
10042
+ }
10043
+ const unknownToolErrors = lastMessage.response_metadata?._unknownToolErrors;
10044
+ if (!unknownToolErrors || !Array.isArray(unknownToolErrors) || unknownToolErrors.length === 0) {
10045
+ return;
10046
+ }
10047
+ const errorToolMessages = unknownToolErrors.map(
10048
+ (error) => new import_messages.ToolMessage({
10049
+ content: error.errorMessage,
10050
+ name: error.toolName,
10051
+ tool_call_id: error.toolCallId,
10052
+ status: "error"
10053
+ })
10054
+ );
10055
+ delete lastMessage.response_metadata._unknownToolErrors;
10056
+ return {
10057
+ messages: errorToolMessages,
10058
+ jumpTo: "model"
10059
+ };
10060
+ }
10061
+ }
10062
+ });
10063
+ }
10064
+
10065
+ // src/deep_agent_new/middleware/date.ts
10066
+ var import_langchain54 = require("langchain");
10067
+ var import_zod49 = require("zod");
10068
+ function formatCurrentDate(timezone = "UTC") {
10069
+ const now = /* @__PURE__ */ new Date();
10070
+ let validTimezone = timezone;
10071
+ try {
10072
+ Intl.DateTimeFormat(void 0, { timeZone: timezone });
10073
+ } catch {
10074
+ validTimezone = "UTC";
10075
+ }
10076
+ const dateFormatOptions = {
10077
+ timeZone: validTimezone,
10078
+ year: "numeric",
10079
+ month: "2-digit",
10080
+ day: "2-digit"
10081
+ };
10082
+ return new Intl.DateTimeFormat("en-US", dateFormatOptions).format(now);
10083
+ }
10084
+ function generateDateContext(timezone = "UTC") {
10085
+ const formattedDate = formatCurrentDate(timezone);
10086
+ if (timezone === "UTC") {
10087
+ return `Current Date: ${formattedDate}`;
10088
+ }
10089
+ const utcDate = formatCurrentDate("UTC");
10090
+ return `Current Date: ${formattedDate} (UTC: ${utcDate})`;
10091
+ }
10092
+ function createDateMiddleware(options = {}) {
10093
+ const timezone = options.timezone || "UTC";
10094
+ const dateContext = generateDateContext(timezone);
10095
+ return (0, import_langchain54.createMiddleware)({
10096
+ name: "DateMiddleware",
10097
+ tools: [
10098
+ (0, import_langchain54.tool)(
10099
+ async () => {
10100
+ const now = /* @__PURE__ */ new Date();
10101
+ let validTimezone = timezone;
10102
+ try {
10103
+ Intl.DateTimeFormat(void 0, { timeZone: timezone });
10104
+ } catch {
10105
+ validTimezone = "UTC";
10106
+ }
10107
+ const localTimeOptions = {
10108
+ timeZone: validTimezone,
10109
+ year: "numeric",
10110
+ month: "2-digit",
10111
+ day: "2-digit",
10112
+ hour: "2-digit",
10113
+ minute: "2-digit",
10114
+ second: "2-digit",
10115
+ hour12: false
10116
+ };
10117
+ const localTime = new Intl.DateTimeFormat("en-US", localTimeOptions).format(now);
10118
+ return JSON.stringify({
10119
+ local_time: `${localTime} (${validTimezone})`,
10120
+ iso_date: now.toISOString().split("T")[0],
10121
+ timestamp: now.toISOString(),
10122
+ timezone: validTimezone
10123
+ });
10124
+ },
10125
+ {
10126
+ name: "get_current_date_time",
10127
+ description: "Get the exact current date and time at the moment of invocation. Use this when the user asks about the current time (e.g., 'what time is it', '\u51E0\u70B9\u4E86', '\u73B0\u5728\u51E0\u70B9'), or when you need to know the precise time for scheduling, deadlines, or time-sensitive operations.",
10128
+ schema: import_zod49.z.object({})
10129
+ }
10130
+ )
10131
+ ],
10132
+ wrapModelCall: async (request, handler) => {
10133
+ const currentSystemPrompt = request.systemPrompt || "";
10134
+ const newSystemPrompt = currentSystemPrompt ? `${dateContext}
10135
+
10136
+ ${currentSystemPrompt}` : dateContext;
10137
+ return handler({
10138
+ ...request,
10139
+ systemPrompt: newSystemPrompt
10140
+ });
10141
+ }
10142
+ });
10143
+ }
10144
+
9945
10145
  // src/agent_lattice/builders/commonMiddleware.ts
9946
10146
  async function createCommonMiddlewares(middlewareConfigs, filesystemBackend) {
9947
10147
  const middlewares = [];
10148
+ middlewares.push(createUnknownToolHandlerMiddleware());
9948
10149
  middlewares.push(createModelSelectorMiddleware());
9949
10150
  const filesystemConfig = middlewareConfigs.find((m) => m.type === "filesystem");
9950
10151
  if (filesystemConfig?.enabled && filesystemBackend) {
@@ -10005,6 +10206,9 @@ async function createCommonMiddlewares(middlewareConfigs, filesystemBackend) {
10005
10206
  }));
10006
10207
  }
10007
10208
  break;
10209
+ case "date":
10210
+ middlewares.push(createDateMiddleware(config.config));
10211
+ break;
10008
10212
  }
10009
10213
  }
10010
10214
  return middlewares;
@@ -10058,14 +10262,14 @@ var ReActAgentGraphBuilder = class {
10058
10262
  */
10059
10263
  async build(agentLattice, params) {
10060
10264
  const tools = params.tools.map((t) => {
10061
- const tool50 = getToolClient(t.key);
10062
- return tool50;
10063
- }).filter((tool50) => tool50 !== void 0);
10265
+ const tool51 = getToolClient(t.key);
10266
+ return tool51;
10267
+ }).filter((tool51) => tool51 !== void 0);
10064
10268
  const stateSchema2 = createReactAgentSchema(params.stateSchema);
10065
10269
  const middlewareConfigs = params.middleware || [];
10066
10270
  const filesystemBackend = this.createFilesystemBackendFactory(middlewareConfigs, agentLattice);
10067
10271
  const middlewares = await createCommonMiddlewares(middlewareConfigs, filesystemBackend);
10068
- return (0, import_langchain53.createAgent)({
10272
+ return (0, import_langchain55.createAgent)({
10069
10273
  model: params.model,
10070
10274
  tools,
10071
10275
  systemPrompt: params.prompt,
@@ -10078,13 +10282,13 @@ var ReActAgentGraphBuilder = class {
10078
10282
  };
10079
10283
 
10080
10284
  // src/deep_agent_new/agent.ts
10081
- var import_langchain57 = require("langchain");
10285
+ var import_langchain59 = require("langchain");
10082
10286
 
10083
10287
  // src/deep_agent_new/middleware/subagents.ts
10084
10288
  var import_v32 = require("zod/v3");
10085
- var import_langchain54 = require("langchain");
10289
+ var import_langchain56 = require("langchain");
10086
10290
  var import_langgraph7 = require("@langchain/langgraph");
10087
- var import_messages = require("@langchain/core/messages");
10291
+ var import_messages2 = require("@langchain/core/messages");
10088
10292
 
10089
10293
  // src/agent_worker/agent_worker_graph.ts
10090
10294
  var import_langgraph6 = require("@langchain/langgraph");
@@ -10644,7 +10848,7 @@ function returnCommandWithStateUpdate(result, toolCallId) {
10644
10848
  update: {
10645
10849
  ...stateUpdate,
10646
10850
  messages: [
10647
- new import_langchain54.ToolMessage({
10851
+ new import_langchain56.ToolMessage({
10648
10852
  content: lastMessage?.content || "Task Failed to complete",
10649
10853
  tool_call_id: toolCallId,
10650
10854
  name: "task"
@@ -10669,10 +10873,10 @@ function getSubagents(options) {
10669
10873
  const generalPurposeMiddleware = [...defaultSubagentMiddleware];
10670
10874
  if (defaultInterruptOn) {
10671
10875
  generalPurposeMiddleware.push(
10672
- (0, import_langchain54.humanInTheLoopMiddleware)({ interruptOn: defaultInterruptOn })
10876
+ (0, import_langchain56.humanInTheLoopMiddleware)({ interruptOn: defaultInterruptOn })
10673
10877
  );
10674
10878
  }
10675
- const generalPurposeSubagent = (0, import_langchain54.createAgent)({
10879
+ const generalPurposeSubagent = (0, import_langchain56.createAgent)({
10676
10880
  model: defaultModel,
10677
10881
  systemPrompt: DEFAULT_SUBAGENT_PROMPT,
10678
10882
  tools: defaultTools,
@@ -10695,8 +10899,8 @@ function getSubagents(options) {
10695
10899
  const middleware = agentParams.middleware ? [...defaultSubagentMiddleware, ...agentParams.middleware] : [...defaultSubagentMiddleware];
10696
10900
  const interruptOn = agentParams.interruptOn || defaultInterruptOn;
10697
10901
  if (interruptOn)
10698
- middleware.push((0, import_langchain54.humanInTheLoopMiddleware)({ interruptOn }));
10699
- agents[agentParams.key] = (0, import_langchain54.createAgent)({
10902
+ middleware.push((0, import_langchain56.humanInTheLoopMiddleware)({ interruptOn }));
10903
+ agents[agentParams.key] = (0, import_langchain56.createAgent)({
10700
10904
  model: agentParams.model ?? defaultModel,
10701
10905
  systemPrompt: agentParams.systemPrompt,
10702
10906
  tools: agentParams.tools ?? defaultTools,
@@ -10726,7 +10930,7 @@ function createTaskTool(options) {
10726
10930
  generalPurposeAgent
10727
10931
  });
10728
10932
  const finalTaskDescription = taskDescription ? taskDescription : getTaskToolDescription(subagentDescriptions);
10729
- return (0, import_langchain54.tool)(
10933
+ return (0, import_langchain56.tool)(
10730
10934
  async (input, config) => {
10731
10935
  const { description, subagent_type } = input;
10732
10936
  let assistant_id = subagent_type;
@@ -10756,7 +10960,7 @@ function createTaskTool(options) {
10756
10960
  }
10757
10961
  const currentState = (0, import_langgraph7.getCurrentTaskInput)();
10758
10962
  const subagentState = filterStateForSubagent(currentState);
10759
- subagentState.messages = [new import_messages.HumanMessage({ content: description })];
10963
+ subagentState.messages = [new import_messages2.HumanMessage({ content: description })];
10760
10964
  const subagent_thread_id = config.configurable?.thread_id + "____" + assistant_id + "_" + config.toolCall.id;
10761
10965
  const workerResult = await agentWorkerGraph.invoke({
10762
10966
  assistant_id,
@@ -10780,7 +10984,7 @@ function createTaskTool(options) {
10780
10984
  return new import_langgraph7.Command({
10781
10985
  update: {
10782
10986
  messages: [
10783
- new import_langchain54.ToolMessage({
10987
+ new import_langchain56.ToolMessage({
10784
10988
  content: error instanceof Error ? error.message : "Task Failed to complete",
10785
10989
  tool_call_id: config.toolCall.id,
10786
10990
  name: "task"
@@ -10824,7 +11028,7 @@ function createSubAgentMiddleware(options) {
10824
11028
  generalPurposeAgent,
10825
11029
  taskDescription
10826
11030
  });
10827
- return (0, import_langchain54.createMiddleware)({
11031
+ return (0, import_langchain56.createMiddleware)({
10828
11032
  name: "subAgentMiddleware",
10829
11033
  tools: [taskTool],
10830
11034
  wrapModelCall: async (request, handler) => {
@@ -10844,11 +11048,11 @@ ${systemPrompt}` : systemPrompt;
10844
11048
  }
10845
11049
 
10846
11050
  // src/deep_agent_new/middleware/patch_tool_calls.ts
10847
- var import_langchain55 = require("langchain");
10848
- var import_messages2 = require("@langchain/core/messages");
11051
+ var import_langchain57 = require("langchain");
11052
+ var import_messages3 = require("@langchain/core/messages");
10849
11053
  var import_langgraph8 = require("@langchain/langgraph");
10850
11054
  function createPatchToolCallsMiddleware() {
10851
- return (0, import_langchain55.createMiddleware)({
11055
+ return (0, import_langchain57.createMiddleware)({
10852
11056
  name: "patchToolCallsMiddleware",
10853
11057
  beforeAgent: async (state) => {
10854
11058
  const messages = state.messages;
@@ -10859,15 +11063,15 @@ function createPatchToolCallsMiddleware() {
10859
11063
  for (let i = 0; i < messages.length; i++) {
10860
11064
  const msg = messages[i];
10861
11065
  patchedMessages.push(msg);
10862
- if (import_langchain55.AIMessage.isInstance(msg) && msg.tool_calls != null) {
11066
+ if (import_langchain57.AIMessage.isInstance(msg) && msg.tool_calls != null) {
10863
11067
  for (const toolCall of msg.tool_calls) {
10864
11068
  const correspondingToolMsg = messages.slice(i).find(
10865
- (m) => import_langchain55.ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id
11069
+ (m) => import_langchain57.ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id
10866
11070
  );
10867
11071
  if (!correspondingToolMsg) {
10868
11072
  const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`;
10869
11073
  patchedMessages.push(
10870
- new import_langchain55.ToolMessage({
11074
+ new import_langchain57.ToolMessage({
10871
11075
  content: toolMsg,
10872
11076
  name: toolCall.name,
10873
11077
  tool_call_id: toolCall.id
@@ -10879,7 +11083,7 @@ function createPatchToolCallsMiddleware() {
10879
11083
  }
10880
11084
  return {
10881
11085
  messages: [
10882
- new import_messages2.RemoveMessage({ id: import_langgraph8.REMOVE_ALL_MESSAGES }),
11086
+ new import_messages3.RemoveMessage({ id: import_langgraph8.REMOVE_ALL_MESSAGES }),
10883
11087
  ...patchedMessages
10884
11088
  ]
10885
11089
  };
@@ -11984,8 +12188,8 @@ var MemoryBackend = class {
11984
12188
 
11985
12189
  // src/deep_agent_new/middleware/todos.ts
11986
12190
  var import_langgraph9 = require("@langchain/langgraph");
11987
- var import_zod49 = require("zod");
11988
- var import_langchain56 = require("langchain");
12191
+ var import_zod50 = require("zod");
12192
+ var import_langchain58 = require("langchain");
11989
12193
  var WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
11990
12194
  It also helps the user understand the progress of the task and overall progress of their requests.
11991
12195
  Only 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.
@@ -12212,20 +12416,20 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
12212
12416
  ## Important To-Do List Usage Notes to Remember
12213
12417
  - The \`write_todos\` tool should never be called multiple times in parallel.
12214
12418
  - 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.`;
12215
- var TodoStatus = import_zod49.z.enum(["pending", "in_progress", "completed"]).describe("Status of the todo");
12216
- var TodoSchema = import_zod49.z.object({
12217
- content: import_zod49.z.string().describe("Content of the todo item"),
12419
+ var TodoStatus = import_zod50.z.enum(["pending", "in_progress", "completed"]).describe("Status of the todo");
12420
+ var TodoSchema = import_zod50.z.object({
12421
+ content: import_zod50.z.string().describe("Content of the todo item"),
12218
12422
  status: TodoStatus
12219
12423
  });
12220
- var stateSchema = import_zod49.z.object({ todos: import_zod49.z.array(TodoSchema).default([]) });
12424
+ var stateSchema = import_zod50.z.object({ todos: import_zod50.z.array(TodoSchema).default([]) });
12221
12425
  function todoListMiddleware(options) {
12222
- const writeTodos = (0, import_langchain56.tool)(
12426
+ const writeTodos = (0, import_langchain58.tool)(
12223
12427
  ({ todos }, config) => {
12224
12428
  return new import_langgraph9.Command({
12225
12429
  update: {
12226
12430
  todos,
12227
12431
  messages: [
12228
- new import_langchain56.ToolMessage({
12432
+ new import_langchain58.ToolMessage({
12229
12433
  content: genUIMarkdown("todo_list", todos),
12230
12434
  tool_call_id: config.toolCall?.id
12231
12435
  })
@@ -12236,12 +12440,12 @@ function todoListMiddleware(options) {
12236
12440
  {
12237
12441
  name: "write_todos",
12238
12442
  description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION,
12239
- schema: import_zod49.z.object({
12240
- todos: import_zod49.z.array(TodoSchema).describe("List of todo items to update")
12443
+ schema: import_zod50.z.object({
12444
+ todos: import_zod50.z.array(TodoSchema).describe("List of todo items to update")
12241
12445
  })
12242
12446
  }
12243
12447
  );
12244
- return (0, import_langchain56.createMiddleware)({
12448
+ return (0, import_langchain58.createMiddleware)({
12245
12449
  name: "todoListMiddleware",
12246
12450
  stateSchema,
12247
12451
  tools: [writeTodos],
@@ -12293,13 +12497,13 @@ ${BASE_PROMPT}` : BASE_PROMPT;
12293
12497
  backend: filesystemBackend
12294
12498
  }),
12295
12499
  // Subagent middleware: Automatic conversation summarization when token limits are approached
12296
- (0, import_langchain57.summarizationMiddleware)({
12500
+ (0, import_langchain59.summarizationMiddleware)({
12297
12501
  model,
12298
12502
  trigger: { tokens: 17e4 },
12299
12503
  keep: { messages: 6 }
12300
12504
  }),
12301
12505
  // Subagent middleware: Anthropic prompt caching for improved performance
12302
- (0, import_langchain57.anthropicPromptCachingMiddleware)({
12506
+ (0, import_langchain59.anthropicPromptCachingMiddleware)({
12303
12507
  unsupportedModelBehavior: "ignore"
12304
12508
  }),
12305
12509
  // Subagent middleware: Patches tool calls for compatibility
@@ -12311,23 +12515,23 @@ ${BASE_PROMPT}` : BASE_PROMPT;
12311
12515
  generalPurposeAgent: true
12312
12516
  }),
12313
12517
  // Automatically summarizes conversation history when token limits are approached
12314
- (0, import_langchain57.summarizationMiddleware)({
12518
+ (0, import_langchain59.summarizationMiddleware)({
12315
12519
  model,
12316
12520
  trigger: { tokens: 17e4 },
12317
12521
  keep: { messages: 6 }
12318
12522
  }),
12319
12523
  // Enables Anthropic prompt caching for improved performance and reduced costs
12320
- (0, import_langchain57.anthropicPromptCachingMiddleware)({
12524
+ (0, import_langchain59.anthropicPromptCachingMiddleware)({
12321
12525
  unsupportedModelBehavior: "ignore"
12322
12526
  }),
12323
12527
  // Patches tool calls to ensure compatibility across different model providers
12324
12528
  createPatchToolCallsMiddleware()
12325
12529
  ];
12326
12530
  if (interruptOn) {
12327
- middleware.push((0, import_langchain57.humanInTheLoopMiddleware)({ interruptOn }));
12531
+ middleware.push((0, import_langchain59.humanInTheLoopMiddleware)({ interruptOn }));
12328
12532
  }
12329
12533
  middleware.push(...customMiddleware);
12330
- return (0, import_langchain57.createAgent)({
12534
+ return (0, import_langchain59.createAgent)({
12331
12535
  model,
12332
12536
  systemPrompt: finalSystemPrompt,
12333
12537
  tools,
@@ -12395,7 +12599,7 @@ var DeepAgentGraphBuilder = class {
12395
12599
  const tools = params.tools.map((t) => {
12396
12600
  const toolClient = getToolClient(t.key);
12397
12601
  return toolClient;
12398
- }).filter((tool50) => tool50 !== void 0);
12602
+ }).filter((tool51) => tool51 !== void 0);
12399
12603
  const subagents = await Promise.all(params.subAgents.map(async (sa) => {
12400
12604
  if (sa.client) {
12401
12605
  return {
@@ -12436,7 +12640,7 @@ var DeepAgentGraphBuilder = class {
12436
12640
 
12437
12641
  // src/agent_team/agent_team.ts
12438
12642
  var import_v35 = require("zod/v3");
12439
- var import_langchain60 = require("langchain");
12643
+ var import_langchain62 = require("langchain");
12440
12644
 
12441
12645
  // src/agent_team/types.ts
12442
12646
  var TaskStatus = /* @__PURE__ */ ((TaskStatus3) => {
@@ -12872,13 +13076,13 @@ var InMemoryMailboxStore = class {
12872
13076
 
12873
13077
  // src/agent_team/middleware/team.ts
12874
13078
  var import_v34 = require("zod/v3");
12875
- var import_langchain59 = require("langchain");
13079
+ var import_langchain61 = require("langchain");
12876
13080
  var import_langgraph11 = require("@langchain/langgraph");
12877
13081
  var import_uuid = require("uuid");
12878
13082
 
12879
13083
  // src/agent_team/middleware/teammate_tools.ts
12880
13084
  var import_v33 = require("zod/v3");
12881
- var import_langchain58 = require("langchain");
13085
+ var import_langchain60 = require("langchain");
12882
13086
  var import_langgraph10 = require("@langchain/langgraph");
12883
13087
 
12884
13088
  // src/agent_team/middleware/formatMessages.ts
@@ -12903,7 +13107,7 @@ ${meta}${body}`;
12903
13107
  // src/agent_team/middleware/teammate_tools.ts
12904
13108
  function createTeammateTools(options) {
12905
13109
  const { teamId, agentId, taskListStore, mailboxStore } = options;
12906
- const claimTaskTool = (0, import_langchain58.tool)(
13110
+ const claimTaskTool = (0, import_langchain60.tool)(
12907
13111
  async (input) => {
12908
13112
  const task = await taskListStore.claimTaskById(
12909
13113
  teamId,
@@ -12933,7 +13137,7 @@ function createTeammateTools(options) {
12933
13137
  })
12934
13138
  }
12935
13139
  );
12936
- const completeTaskTool = (0, import_langchain58.tool)(
13140
+ const completeTaskTool = (0, import_langchain60.tool)(
12937
13141
  async (input) => {
12938
13142
  const task = await taskListStore.completeTask(
12939
13143
  teamId,
@@ -12960,7 +13164,7 @@ function createTeammateTools(options) {
12960
13164
  })
12961
13165
  }
12962
13166
  );
12963
- const failTaskTool = (0, import_langchain58.tool)(
13167
+ const failTaskTool = (0, import_langchain60.tool)(
12964
13168
  async (input) => {
12965
13169
  const task = await taskListStore.failTask(
12966
13170
  teamId,
@@ -12987,7 +13191,7 @@ function createTeammateTools(options) {
12987
13191
  })
12988
13192
  }
12989
13193
  );
12990
- const sendMessageTool = (0, import_langchain58.tool)(
13194
+ const sendMessageTool = (0, import_langchain60.tool)(
12991
13195
  async (input) => {
12992
13196
  await mailboxStore.sendMessage(
12993
13197
  teamId,
@@ -13025,7 +13229,7 @@ function createTeammateTools(options) {
13025
13229
  read: msg.read
13026
13230
  }));
13027
13231
  };
13028
- const readMessagesTool = (0, import_langchain58.tool)(
13232
+ const readMessagesTool = (0, import_langchain60.tool)(
13029
13233
  async (input, config) => {
13030
13234
  const formatAndMarkAsRead = async (msgs2) => {
13031
13235
  for (const msg of msgs2) {
@@ -13037,7 +13241,7 @@ function createTeammateTools(options) {
13037
13241
  if (msgs.length > 0) {
13038
13242
  const formatted2 = await formatAndMarkAsRead(msgs);
13039
13243
  const relevantMsgs2 = await getRelevantMessagesForState();
13040
- const toolMessage2 = new import_langchain58.ToolMessage({
13244
+ const toolMessage2 = new import_langchain60.ToolMessage({
13041
13245
  content: formatted2,
13042
13246
  tool_call_id: config.toolCall?.id,
13043
13247
  name: "read_messages"
@@ -13062,7 +13266,7 @@ function createTeammateTools(options) {
13062
13266
  });
13063
13267
  const relevantMsgs = await getRelevantMessagesForState();
13064
13268
  if (msgs.length === 0) {
13065
- const toolMessage2 = new import_langchain58.ToolMessage({
13269
+ const toolMessage2 = new import_langchain60.ToolMessage({
13066
13270
  content: "No unread messages.",
13067
13271
  tool_call_id: config.toolCall?.id,
13068
13272
  name: "read_messages"
@@ -13072,7 +13276,7 @@ function createTeammateTools(options) {
13072
13276
  });
13073
13277
  }
13074
13278
  const formatted = await formatAndMarkAsRead(msgs);
13075
- const toolMessage = new import_langchain58.ToolMessage({
13279
+ const toolMessage = new import_langchain60.ToolMessage({
13076
13280
  content: formatted,
13077
13281
  tool_call_id: config.toolCall?.id,
13078
13282
  name: "read_messages"
@@ -13087,7 +13291,7 @@ function createTeammateTools(options) {
13087
13291
  schema: import_v33.z.object({})
13088
13292
  }
13089
13293
  );
13090
- const checkTasksTool = (0, import_langchain58.tool)(
13294
+ const checkTasksTool = (0, import_langchain60.tool)(
13091
13295
  async () => {
13092
13296
  const tasks = await taskListStore.getAllTasks(teamId);
13093
13297
  return formatTaskSummary(tasks);
@@ -13098,7 +13302,7 @@ function createTeammateTools(options) {
13098
13302
  schema: import_v33.z.object({})
13099
13303
  }
13100
13304
  );
13101
- const broadcastMessageTool = (0, import_langchain58.tool)(
13305
+ const broadcastMessageTool = (0, import_langchain60.tool)(
13102
13306
  async (input) => {
13103
13307
  const allAgents = await mailboxStore.getRegisteredAgents(teamId);
13104
13308
  const recipients = allAgents.filter((a) => a !== agentId);
@@ -13283,7 +13487,7 @@ You have access to these tools:
13283
13487
  - \`read_messages\`: Read messages from team_lead or teammates
13284
13488
  - \`check_tasks\`: Get current status of all tasks in the team`;
13285
13489
  const assistantId = getTeammateAssistantId(ctx.teamId, spec.name);
13286
- agent = (0, import_langchain59.createAgent)({
13490
+ agent = (0, import_langchain61.createAgent)({
13287
13491
  model: spec.model ?? ctx.defaultModel,
13288
13492
  systemPrompt: teammatePrompt,
13289
13493
  tools: allTools,
@@ -13352,12 +13556,12 @@ async function spawnTeammate(options) {
13352
13556
  function createTeamMiddleware(options) {
13353
13557
  const { teamConfig, taskListStore, mailboxStore, tenantId } = options;
13354
13558
  const defaultModel = teamConfig.model ?? "claude-sonnet-4-5-20250929";
13355
- const createTeamTool = (0, import_langchain59.tool)(
13559
+ const createTeamTool = (0, import_langchain61.tool)(
13356
13560
  async (input, config) => {
13357
13561
  const state = (0, import_langgraph11.getCurrentTaskInput)();
13358
13562
  if (state?.team?.teamId) {
13359
13563
  const existingId = state.team.teamId;
13360
- const msg = new import_langchain59.ToolMessage({
13564
+ const msg = new import_langchain61.ToolMessage({
13361
13565
  content: `A team is already active (id: ${existingId}). Use this team_id for \`check_tasks\`, \`read_messages\`, \`add_tasks\`, \`send_message\`, \`assign_task\`, \`set_task_status\`, and \`set_task_dependencies\`. Do not call \`create_team\` again unless you need a fresh team for a new objective.`,
13362
13566
  tool_call_id: config.toolCall?.id,
13363
13567
  name: "create_team"
@@ -13446,7 +13650,7 @@ Teammates are now working in the background. Keep calling \`check_tasks\` and \`
13446
13650
  \`\`\`json
13447
13651
  ${teamJson}
13448
13652
  \`\`\``;
13449
- const toolMessage = new import_langchain59.ToolMessage({
13653
+ const toolMessage = new import_langchain61.ToolMessage({
13450
13654
  content: summary,
13451
13655
  tool_call_id: config.toolCall?.id,
13452
13656
  name: "create_team"
@@ -13531,7 +13735,7 @@ After calling create_team, you MUST:
13531
13735
  if (state?.team?.teamId) return state.team.teamId;
13532
13736
  throw new Error("No team_id provided and no team in state. Call create_team first.");
13533
13737
  };
13534
- const addTasksTool = (0, import_langchain59.tool)(
13738
+ const addTasksTool = (0, import_langchain61.tool)(
13535
13739
  async (input, config) => {
13536
13740
  const teamId = resolveTeamId();
13537
13741
  const created = await taskListStore.addTasks(
@@ -13545,7 +13749,7 @@ After calling create_team, you MUST:
13545
13749
  }))
13546
13750
  );
13547
13751
  const summary = created.map((t) => `- ${t.id}: "${t.title}"`).join("\n");
13548
- return new import_langchain59.ToolMessage({
13752
+ return new import_langchain61.ToolMessage({
13549
13753
  content: `Added ${created.length} task(s) to team ${teamId}:
13550
13754
  ${summary}
13551
13755
  Sleeping teammates will wake up and claim these.`,
@@ -13596,20 +13800,20 @@ IMPORTANT: Assigning to a specific teammate
13596
13800
  })
13597
13801
  }
13598
13802
  );
13599
- const assignTaskTool = (0, import_langchain59.tool)(
13803
+ const assignTaskTool = (0, import_langchain61.tool)(
13600
13804
  async (input, config) => {
13601
13805
  const teamId = resolveTeamId();
13602
13806
  const task = await taskListStore.updateTask(teamId, input.task_id, {
13603
13807
  assignee: input.assignee
13604
13808
  });
13605
13809
  if (!task) {
13606
- return new import_langchain59.ToolMessage({
13810
+ return new import_langchain61.ToolMessage({
13607
13811
  content: `Task ${input.task_id} not found in team ${teamId}.`,
13608
13812
  tool_call_id: config.toolCall?.id,
13609
13813
  name: "assign_task"
13610
13814
  });
13611
13815
  }
13612
- return new import_langchain59.ToolMessage({
13816
+ return new import_langchain61.ToolMessage({
13613
13817
  content: `Task "${task.title}" (${task.id}) assigned to ${input.assignee}.`,
13614
13818
  tool_call_id: config.toolCall?.id,
13615
13819
  name: "assign_task"
@@ -13624,20 +13828,20 @@ IMPORTANT: Assigning to a specific teammate
13624
13828
  })
13625
13829
  }
13626
13830
  );
13627
- const setTaskStatusTool = (0, import_langchain59.tool)(
13831
+ const setTaskStatusTool = (0, import_langchain61.tool)(
13628
13832
  async (input, config) => {
13629
13833
  const teamId = resolveTeamId();
13630
13834
  const task = await taskListStore.updateTask(teamId, input.task_id, {
13631
13835
  status: input.status
13632
13836
  });
13633
13837
  if (!task) {
13634
- return new import_langchain59.ToolMessage({
13838
+ return new import_langchain61.ToolMessage({
13635
13839
  content: `Task ${input.task_id} not found in team ${teamId}.`,
13636
13840
  tool_call_id: config.toolCall?.id,
13637
13841
  name: "set_task_status"
13638
13842
  });
13639
13843
  }
13640
- return new import_langchain59.ToolMessage({
13844
+ return new import_langchain61.ToolMessage({
13641
13845
  content: `Task "${task.title}" (${task.id}) status set to ${input.status}.`,
13642
13846
  tool_call_id: config.toolCall?.id,
13643
13847
  name: "set_task_status"
@@ -13652,20 +13856,20 @@ IMPORTANT: Assigning to a specific teammate
13652
13856
  })
13653
13857
  }
13654
13858
  );
13655
- const setTaskDependenciesTool = (0, import_langchain59.tool)(
13859
+ const setTaskDependenciesTool = (0, import_langchain61.tool)(
13656
13860
  async (input, config) => {
13657
13861
  const teamId = resolveTeamId();
13658
13862
  const task = await taskListStore.updateTask(teamId, input.task_id, {
13659
13863
  dependencies: input.dependencies
13660
13864
  });
13661
13865
  if (!task) {
13662
- return new import_langchain59.ToolMessage({
13866
+ return new import_langchain61.ToolMessage({
13663
13867
  content: `Task ${input.task_id} not found in team ${teamId}.`,
13664
13868
  tool_call_id: config.toolCall?.id,
13665
13869
  name: "set_task_dependencies"
13666
13870
  });
13667
13871
  }
13668
- return new import_langchain59.ToolMessage({
13872
+ return new import_langchain61.ToolMessage({
13669
13873
  content: `Task "${task.title}" (${task.id}) dependencies set to [${input.dependencies.join(", ")}].`,
13670
13874
  tool_call_id: config.toolCall?.id,
13671
13875
  name: "set_task_dependencies"
@@ -13680,7 +13884,7 @@ IMPORTANT: Assigning to a specific teammate
13680
13884
  })
13681
13885
  }
13682
13886
  );
13683
- const checkTasksTool = (0, import_langchain59.tool)(
13887
+ const checkTasksTool = (0, import_langchain61.tool)(
13684
13888
  async (input, config) => {
13685
13889
  const teamId = resolveTeamId();
13686
13890
  const tasks = await taskListStore.getAllTasks(teamId);
@@ -13689,7 +13893,7 @@ IMPORTANT: Assigning to a specific teammate
13689
13893
  update: {
13690
13894
  tasks: tasksSnapshot,
13691
13895
  messages: [
13692
- new import_langchain59.ToolMessage({
13896
+ new import_langchain61.ToolMessage({
13693
13897
  content: formatTaskSummary(tasks),
13694
13898
  tool_call_id: config.toolCall?.id,
13695
13899
  name: "check_tasks"
@@ -13725,7 +13929,7 @@ Task Status Values:
13725
13929
  })
13726
13930
  }
13727
13931
  );
13728
- const sendMessageTool = (0, import_langchain59.tool)(
13932
+ const sendMessageTool = (0, import_langchain61.tool)(
13729
13933
  async (input, config) => {
13730
13934
  const teamId = resolveTeamId();
13731
13935
  await mailboxStore.sendMessage(
@@ -13735,7 +13939,7 @@ Task Status Values:
13735
13939
  input.content,
13736
13940
  "direct_message" /* DIRECT_MESSAGE */
13737
13941
  );
13738
- return new import_langchain59.ToolMessage({
13942
+ return new import_langchain61.ToolMessage({
13739
13943
  content: `Message sent to ${input.to}.`,
13740
13944
  tool_call_id: config.toolCall?.id,
13741
13945
  name: "send_message"
@@ -13750,7 +13954,7 @@ Task Status Values:
13750
13954
  })
13751
13955
  }
13752
13956
  );
13753
- const readMessagesTool = (0, import_langchain59.tool)(
13957
+ const readMessagesTool = (0, import_langchain61.tool)(
13754
13958
  async (input, config) => {
13755
13959
  const teamId = resolveTeamId();
13756
13960
  const formatAndMarkAsRead = async (msgs2) => {
@@ -13778,7 +13982,7 @@ Task Status Values:
13778
13982
  if (msgs.length > 0) {
13779
13983
  const formatted2 = await formatAndMarkAsRead(msgs);
13780
13984
  const allTeamMessages2 = await getAllTeamMessagesForState();
13781
- const toolMessage2 = new import_langchain59.ToolMessage({
13985
+ const toolMessage2 = new import_langchain61.ToolMessage({
13782
13986
  content: formatted2,
13783
13987
  tool_call_id: config.toolCall?.id,
13784
13988
  name: "read_messages"
@@ -13810,7 +14014,7 @@ Task Status Values:
13810
14014
  );
13811
14015
  const allTeamMessages = await getAllTeamMessagesForState();
13812
14016
  if (msgs.length === 0) {
13813
- const toolMessage2 = new import_langchain59.ToolMessage({
14017
+ const toolMessage2 = new import_langchain61.ToolMessage({
13814
14018
  content: "No unread messages from teammates.",
13815
14019
  tool_call_id: config.toolCall?.id,
13816
14020
  name: "read_messages"
@@ -13820,7 +14024,7 @@ Task Status Values:
13820
14024
  });
13821
14025
  }
13822
14026
  const formatted = await formatAndMarkAsRead(msgs);
13823
- const toolMessage = new import_langchain59.ToolMessage({
14027
+ const toolMessage = new import_langchain61.ToolMessage({
13824
14028
  content: formatted,
13825
14029
  tool_call_id: config.toolCall?.id,
13826
14030
  name: "read_messages"
@@ -13837,7 +14041,7 @@ Task Status Values:
13837
14041
  })
13838
14042
  }
13839
14043
  );
13840
- const disbandTeamTool = (0, import_langchain59.tool)(
14044
+ const disbandTeamTool = (0, import_langchain61.tool)(
13841
14045
  async (input, config) => {
13842
14046
  const teamId = resolveTeamId();
13843
14047
  await mailboxStore.broadcastMessage(
@@ -13847,7 +14051,7 @@ Task Status Values:
13847
14051
  "shutdown_request" /* SHUTDOWN_REQUEST */
13848
14052
  );
13849
14053
  await new Promise((r) => setTimeout(r, 2e3));
13850
- return new import_langchain59.ToolMessage({
14054
+ return new import_langchain61.ToolMessage({
13851
14055
  content: `Team ${teamId} has been disbanded. All teammates notified and resources cleaned up.`,
13852
14056
  tool_call_id: config.toolCall?.id,
13853
14057
  name: "disband_team"
@@ -13858,7 +14062,7 @@ Task Status Values:
13858
14062
  description: "Disband a team when all work is done. Before calling: (1) Call check_tasks to verify no tasks are still pending/in_progress; (2) if any are, discuss with the team via read_messages and broadcast_message/send_message whether to continue or stop/cancel them; (3) only after alignment (all tasks completed/failed or explicitly stopped), then call this tool. This will: 1) Send a shutdown message to all teammates, 2) Wait briefly for them to clean up, 3) Clear all tasks and messages. Omit team_id to use the active team from state."
13859
14063
  }
13860
14064
  );
13861
- const broadcastMessageTool = (0, import_langchain59.tool)(
14065
+ const broadcastMessageTool = (0, import_langchain61.tool)(
13862
14066
  async (input, config) => {
13863
14067
  const teamId = resolveTeamId();
13864
14068
  await mailboxStore.broadcastMessage(
@@ -13867,7 +14071,7 @@ Task Status Values:
13867
14071
  input.content,
13868
14072
  "broadcast" /* BROADCAST */
13869
14073
  );
13870
- return new import_langchain59.ToolMessage({
14074
+ return new import_langchain61.ToolMessage({
13871
14075
  content: `Broadcast message sent to all teammates.`,
13872
14076
  tool_call_id: config.toolCall?.id,
13873
14077
  name: "broadcast_message"
@@ -13881,7 +14085,7 @@ Task Status Values:
13881
14085
  })
13882
14086
  }
13883
14087
  );
13884
- return (0, import_langchain59.createMiddleware)({
14088
+ return (0, import_langchain61.createMiddleware)({
13885
14089
  name: "teamMiddleware",
13886
14090
  tools: [
13887
14091
  createTeamTool,
@@ -13990,7 +14194,7 @@ function createAgentTeam(config) {
13990
14194
  ];
13991
14195
  const systemPrompt = config.systemPrompt + "\n\n" + TEAM_LEAD_BASE_PROMPT;
13992
14196
  const stateSchema2 = createReactAgentSchema(TEAM_STATE_SCHEMA);
13993
- return (0, import_langchain60.createAgent)({
14197
+ return (0, import_langchain62.createAgent)({
13994
14198
  model: config.model ?? "claude-sonnet-4-5-20250929",
13995
14199
  systemPrompt,
13996
14200
  tools: [],
@@ -14020,7 +14224,7 @@ var TeamAgentGraphBuilder = class {
14020
14224
  const tools = params.tools.map((t) => {
14021
14225
  const toolClient = getToolClient(t.key);
14022
14226
  return toolClient;
14023
- }).filter((tool50) => tool50 !== void 0);
14227
+ }).filter((tool51) => tool51 !== void 0);
14024
14228
  const teammates = params.subAgents.map((sa) => {
14025
14229
  const baseConfig = sa.config;
14026
14230
  return {
@@ -14745,6 +14949,9 @@ var InMemoryChunkBuffer = class extends ChunkBuffer {
14745
14949
  buffer2.expiresAt = Date.now() + this.config.ttl;
14746
14950
  buffer2.status = "active" /* ACTIVE */;
14747
14951
  }
14952
+ async ensureThread(threadId) {
14953
+ this.getOrCreateBuffer(threadId);
14954
+ }
14748
14955
  async completeThread(threadId) {
14749
14956
  const buffer2 = this.getBufferIfValid(threadId);
14750
14957
  if (buffer2) {
@@ -16889,10 +17096,10 @@ var McpLatticeManager = class _McpLatticeManager extends BaseLatticeManager {
16889
17096
  }
16890
17097
  const tools = await this.getAllTools();
16891
17098
  console.log(`[MCP] Registering ${tools.length} tools to Tool Lattice...`);
16892
- for (const tool50 of tools) {
16893
- const toolKey = prefix ? `${prefix}_${tool50.name}` : tool50.name;
16894
- tool50.name = toolKey;
16895
- toolLatticeManager.registerExistingTool(toolKey, tool50);
17099
+ for (const tool51 of tools) {
17100
+ const toolKey = prefix ? `${prefix}_${tool51.name}` : tool51.name;
17101
+ tool51.name = toolKey;
17102
+ toolLatticeManager.registerExistingTool(toolKey, tool51);
16896
17103
  console.log(`[MCP] Registered tool: ${toolKey}`);
16897
17104
  }
16898
17105
  console.log(`[MCP] Successfully registered ${tools.length} tools to Tool Lattice`);
@@ -16910,7 +17117,7 @@ var QueueMode = /* @__PURE__ */ ((QueueMode2) => {
16910
17117
 
16911
17118
  // src/services/Agent.ts
16912
17119
  var import_langgraph12 = require("@langchain/langgraph");
16913
- var import_langchain61 = require("langchain");
17120
+ var import_langchain63 = require("langchain");
16914
17121
  var import_uuid2 = require("uuid");
16915
17122
  var ThreadStatus2 = /* @__PURE__ */ ((ThreadStatus3) => {
16916
17123
  ThreadStatus3["IDLE"] = "idle";
@@ -17099,6 +17306,7 @@ var Agent = class {
17099
17306
  break;
17100
17307
  }
17101
17308
  const firstMessage = pendings[0];
17309
+ const files = firstMessage.content?.queueMessage?.input?.files;
17102
17310
  const hasCommand = firstMessage.command;
17103
17311
  if (hasCommand) {
17104
17312
  for (const p of pendings) {
@@ -17115,14 +17323,17 @@ var Agent = class {
17115
17323
  });
17116
17324
  const humanContent = p.content;
17117
17325
  const input = {
17118
- messages: [new import_langchain61.HumanMessage({ id: humanContent.id, content: humanContent.message })]
17326
+ messages: [new import_langchain63.HumanMessage({ id: humanContent.id, content: humanContent.message })]
17119
17327
  };
17328
+ if (files) {
17329
+ input.files = files;
17330
+ }
17120
17331
  const queueMessageData = humanContent.queueMessage;
17121
17332
  try {
17122
17333
  await this.agentStreamExecutor({
17123
17334
  input,
17124
17335
  command: p.command,
17125
- custom_run_config: queueMessageData.custom_run_config
17336
+ custom_run_config: p.custom_run_config ?? queueMessageData.custom_run_config
17126
17337
  }, signal);
17127
17338
  await this.queueStore?.markCompleted(p.id);
17128
17339
  const runStatus = await this.getRunStatus();
@@ -17178,7 +17389,7 @@ var Agent = class {
17178
17389
  remainingPendings.forEach((p) => {
17179
17390
  this.queueStore?.markProcessing(p.id);
17180
17391
  const humanContent = p.content;
17181
- userMessages.push(new import_langchain61.HumanMessage({ id: humanContent.id, content: humanContent.message }));
17392
+ userMessages.push(new import_langchain63.HumanMessage({ id: humanContent.id, content: humanContent.message }));
17182
17393
  this.publish("message:started", {
17183
17394
  type: "message:started",
17184
17395
  messageId: humanContent.id,
@@ -17188,10 +17399,16 @@ var Agent = class {
17188
17399
  });
17189
17400
  });
17190
17401
  const firstQueueMessage = remainingPendings[0] ? this.getHumanPendingContent(remainingPendings[0]).queueMessage : void 0;
17402
+ const input = {
17403
+ messages: userMessages
17404
+ };
17405
+ if (files) {
17406
+ input.files = files;
17407
+ }
17191
17408
  try {
17192
17409
  await this.agentStreamExecutor({
17193
- input: { messages: userMessages },
17194
- custom_run_config: firstQueueMessage?.custom_run_config
17410
+ input,
17411
+ custom_run_config: remainingPendings[0]?.custom_run_config ?? firstQueueMessage?.custom_run_config
17195
17412
  }, signal);
17196
17413
  const runStatus = await this.getRunStatus();
17197
17414
  const state = await this.getCurrentState();
@@ -17246,7 +17463,7 @@ var Agent = class {
17246
17463
  if (signal?.aborted) break;
17247
17464
  await this.queueStore?.markProcessing(p.id);
17248
17465
  const humanContent = p.content;
17249
- const message = new import_langchain61.HumanMessage({ id: humanContent.id, content: humanContent.message });
17466
+ const message = new import_langchain63.HumanMessage({ id: humanContent.id, content: humanContent.message });
17250
17467
  const startTime = Date.now();
17251
17468
  this.publish("message:started", {
17252
17469
  type: "message:started",
@@ -17256,10 +17473,16 @@ var Agent = class {
17256
17473
  queueMode: "followup" /* FOLLOWUP */
17257
17474
  });
17258
17475
  const queueMessageData = humanContent.queueMessage || {};
17476
+ const input = {
17477
+ messages: [message]
17478
+ };
17479
+ if (files) {
17480
+ input.files = files;
17481
+ }
17259
17482
  try {
17260
17483
  await this.agentStreamExecutor({
17261
- input: { messages: [message] },
17262
- custom_run_config: queueMessageData.custom_run_config
17484
+ input,
17485
+ custom_run_config: p.custom_run_config ?? queueMessageData.custom_run_config
17263
17486
  }, signal);
17264
17487
  await this.queueStore?.markCompleted(p.id);
17265
17488
  const runStatus = await this.getRunStatus();
@@ -17383,7 +17606,7 @@ var Agent = class {
17383
17606
  const messageId = (0, import_uuid2.v4)();
17384
17607
  const input = {
17385
17608
  ...queueMessage.input,
17386
- messages: [new import_langchain61.HumanMessage({ id: messageId, content: queueMessage.input.message })]
17609
+ messages: [new import_langchain63.HumanMessage({ id: messageId, content: queueMessage.input.message })]
17387
17610
  };
17388
17611
  const inputMessage = { ...queueMessage, input };
17389
17612
  return this.agentExecutor(inputMessage, signal);
@@ -17456,7 +17679,16 @@ var Agent = class {
17456
17679
  }
17457
17680
  };
17458
17681
  if (isHighPriority) {
17459
- await store.addMessageAtHead(this.thread_id, content, "human", messageId, queueMessage.command);
17682
+ await store.addMessageAtHead({
17683
+ threadId: this.thread_id,
17684
+ tenantId: this.tenant_id,
17685
+ assistantId: this.assistant_id,
17686
+ content,
17687
+ type: "human",
17688
+ command: queueMessage.command,
17689
+ custom_run_config: queueMessage.custom_run_config,
17690
+ id: messageId
17691
+ });
17460
17692
  if (useMode === "steer" /* STEER */) {
17461
17693
  this.stopQueueProcessor();
17462
17694
  await store.resetProcessingToPending(this.thread_id);
@@ -17470,9 +17702,11 @@ var Agent = class {
17470
17702
  content,
17471
17703
  type: "human",
17472
17704
  command: queueMessage.command,
17705
+ custom_run_config: queueMessage.custom_run_config,
17473
17706
  id: messageId
17474
17707
  });
17475
17708
  }
17709
+ await this.chunkBuffer.ensureThread(this.thread_id);
17476
17710
  this.startQueueProcessorIfNeeded().catch((err) => {
17477
17711
  console.error("Failed to start queue processor:", err);
17478
17712
  });
@@ -17529,11 +17763,13 @@ var Agent = class {
17529
17763
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
17530
17764
  }
17531
17765
  };
17532
- await this.queueStore.addMessageAtHead(
17533
- thread.threadId,
17534
- reminderContent,
17535
- "system"
17536
- );
17766
+ await this.queueStore.addMessageAtHead({
17767
+ threadId: thread.threadId,
17768
+ tenantId: thread.tenantId,
17769
+ assistantId: thread.assistantId,
17770
+ content: reminderContent,
17771
+ type: "system"
17772
+ });
17537
17773
  }
17538
17774
  async getCurrentState() {
17539
17775
  const { runnable_agent } = await this.getLatticeClientAndRuntimeConfig();
@@ -17545,7 +17781,7 @@ var Agent = class {
17545
17781
  async getCurrentMessages() {
17546
17782
  const state = await this.getCurrentState();
17547
17783
  const messages = state.values.messages || [];
17548
- const filteredMessages = (0, import_langchain61.filterMessages)(messages, {
17784
+ const filteredMessages = (0, import_langchain63.filterMessages)(messages, {
17549
17785
  includeTypes: ["ai", "human", "tool"]
17550
17786
  //["human", "ai", "tool"],
17551
17787
  });
@@ -17604,12 +17840,16 @@ var Agent = class {
17604
17840
  /**
17605
17841
  * Abort the current agent execution
17606
17842
  * This will cancel any ongoing invoke or stream operations
17843
+ * and clear all queued messages (pending + processing)
17607
17844
  */
17608
- abort() {
17845
+ async abort() {
17609
17846
  if (this.abortController) {
17610
17847
  this.abortController.abort();
17611
17848
  this.abortController = null;
17612
17849
  }
17850
+ await this.chunkBuffer.abortThread(this.thread_id);
17851
+ const store = this.getQueueStore();
17852
+ await store.clearMessages(this.thread_id);
17613
17853
  }
17614
17854
  /**
17615
17855
  * Check if the agent is currently being aborted
@@ -17918,6 +18158,7 @@ function clearEncryptionKeyCache() {
17918
18158
  createQueryTablesListTool,
17919
18159
  createTeamMiddleware,
17920
18160
  createTeammateTools,
18161
+ createUnknownToolHandlerMiddleware,
17921
18162
  createWidgetMiddleware,
17922
18163
  decrypt,
17923
18164
  describeCronExpression,