langchain 1.2.6 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/agents/ReactAgent.cjs +28 -0
  3. package/dist/agents/ReactAgent.cjs.map +1 -1
  4. package/dist/agents/ReactAgent.d.cts +50 -14
  5. package/dist/agents/ReactAgent.d.cts.map +1 -1
  6. package/dist/agents/ReactAgent.d.ts +50 -14
  7. package/dist/agents/ReactAgent.d.ts.map +1 -1
  8. package/dist/agents/ReactAgent.js +28 -0
  9. package/dist/agents/ReactAgent.js.map +1 -1
  10. package/dist/agents/index.cjs.map +1 -1
  11. package/dist/agents/index.d.cts +41 -29
  12. package/dist/agents/index.d.cts.map +1 -1
  13. package/dist/agents/index.d.ts +41 -29
  14. package/dist/agents/index.d.ts.map +1 -1
  15. package/dist/agents/index.js.map +1 -1
  16. package/dist/agents/middleware/contextEditing.d.cts +2 -1
  17. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  18. package/dist/agents/middleware/contextEditing.d.ts +2 -1
  19. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  20. package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -1
  21. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
  22. package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -1
  23. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  24. package/dist/agents/middleware/hitl.d.cts +9 -1
  25. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  26. package/dist/agents/middleware/hitl.d.ts +9 -1
  27. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  28. package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
  29. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  30. package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
  31. package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
  32. package/dist/agents/middleware/modelCallLimit.d.cts +6 -1
  33. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
  34. package/dist/agents/middleware/modelCallLimit.d.ts +6 -1
  35. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
  36. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +7 -1
  37. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
  38. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +7 -1
  39. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
  40. package/dist/agents/middleware/summarization.d.cts +30 -7
  41. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  42. package/dist/agents/middleware/summarization.d.ts +30 -7
  43. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  44. package/dist/agents/middleware/todoListMiddleware.cjs +42 -2
  45. package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
  46. package/dist/agents/middleware/todoListMiddleware.d.cts +45 -2
  47. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  48. package/dist/agents/middleware/todoListMiddleware.d.ts +45 -2
  49. package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
  50. package/dist/agents/middleware/todoListMiddleware.js +43 -3
  51. package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
  52. package/dist/agents/middleware/toolCallLimit.d.cts +2 -1
  53. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  54. package/dist/agents/middleware/toolCallLimit.d.ts +2 -1
  55. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  56. package/dist/agents/middleware/types.cjs.map +1 -1
  57. package/dist/agents/middleware/types.d.cts +125 -32
  58. package/dist/agents/middleware/types.d.cts.map +1 -1
  59. package/dist/agents/middleware/types.d.ts +125 -32
  60. package/dist/agents/middleware/types.d.ts.map +1 -1
  61. package/dist/agents/middleware/types.js.map +1 -1
  62. package/dist/agents/middleware.cjs +1 -1
  63. package/dist/agents/middleware.cjs.map +1 -1
  64. package/dist/agents/middleware.d.cts +4 -4
  65. package/dist/agents/middleware.d.cts.map +1 -1
  66. package/dist/agents/middleware.d.ts +4 -4
  67. package/dist/agents/middleware.d.ts.map +1 -1
  68. package/dist/agents/middleware.js +1 -1
  69. package/dist/agents/middleware.js.map +1 -1
  70. package/dist/agents/responses.d.cts.map +1 -1
  71. package/dist/agents/types.d.cts +254 -8
  72. package/dist/agents/types.d.cts.map +1 -1
  73. package/dist/agents/types.d.ts +254 -8
  74. package/dist/agents/types.d.ts.map +1 -1
  75. package/dist/index.d.cts +3 -3
  76. package/dist/index.d.ts +3 -3
  77. package/dist/load/import_constants.cjs +5 -5
  78. package/dist/load/import_constants.cjs.map +1 -1
  79. package/dist/load/import_constants.js +5 -5
  80. package/dist/load/import_constants.js.map +1 -1
  81. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.cjs","names":["z","options?: TodoListMiddlewareOptions","Command","ToolMessage","createMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { ToolMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../index.js\";\n\n/**\n * Description for the write_todos tool\n * Ported exactly from Python WRITE_TODOS_DESCRIPTION\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.`;\n\nexport const 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.`;\n\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({\n todos: z.array(TodoSchema).default([]),\n});\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\n\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport function todoListMiddleware(options?: TodoListMiddlewareOptions) {\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: `Updated todo list to ${JSON.stringify(todos)}`,\n tool_call_id: config.toolCall?.id as string,\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\n return createMiddleware({\n name: \"todoListMiddleware\",\n stateSchema,\n tools: [writeTodos],\n wrapModelCall: (request, handler) =>\n handler({\n ...request,\n systemMessage: request.systemMessage.concat(\n `\\n\\n${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`\n ),\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAWA,MAAM,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qLAoNoJ,CAAC;AAEtL,MAAa,qCAAqC,CAAC;;;;;;;;;;;;kJAY+F,CAAC;AAEnJ,MAAM,aAAaA,SAChB,KAAK;CAAC;CAAW;CAAe;AAAY,EAAC,CAC7C,SAAS,qBAAqB;AACjC,MAAM,aAAaA,SAAE,OAAO;CAC1B,SAASA,SAAE,QAAQ,CAAC,SAAS,2BAA2B;CACxD,QAAQ;AACT,EAAC;AACF,MAAM,cAAcA,SAAE,OAAO,EAC3B,OAAOA,SAAE,MAAM,WAAW,CAAC,QAAQ,CAAE,EAAC,CACvC,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDF,SAAgB,mBAAmBC,SAAqC;;;;CAItE,MAAM,8CACJ,CAAC,EAAE,OAAO,EAAE,WAAW;AACrB,SAAO,IAAIC,8BAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAIC,sCAAY;IACd,SAAS,CAAC,qBAAqB,EAAE,KAAK,UAAU,MAAM,EAAE;IACxD,cAAc,OAAO,UAAU;GAChC,EACF;EACF,EACF;CACF,GACD;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQH,SAAE,OAAO,EACf,OAAOA,SAAE,MAAM,WAAW,CAAC,SAAS,+BAA+B,CACpE,EAAC;CACH,EACF;AAED,QAAOI,oCAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAW;EACnB,eAAe,CAAC,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,CAAC,IAAI,EAAE,SAAS,gBAAgB,oCAAoC,CACrE;EACF,EAAC;CACL,EAAC;AACH"}
1
+ {"version":3,"file":"todoListMiddleware.cjs","names":["z","options?: TodoListMiddlewareOptions","Command","ToolMessage","createMiddleware","AIMessage"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { AIMessage, ToolMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../index.js\";\n\n/**\n * Description for the write_todos tool\n * Ported exactly from Python WRITE_TODOS_DESCRIPTION\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.`;\n\nexport const 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.`;\n\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({\n todos: z.array(TodoSchema).default([]),\n});\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\n\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively. It also enforces that the\n * `write_todos` tool is called at most once per model turn, since the tool replaces\n * the entire todo list and parallel calls would create ambiguity about precedence.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport function todoListMiddleware(options?: TodoListMiddlewareOptions) {\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: `Updated todo list to ${JSON.stringify(todos)}`,\n tool_call_id: config.toolCall?.id as string,\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\n return createMiddleware({\n name: \"todoListMiddleware\",\n stateSchema,\n tools: [writeTodos],\n wrapModelCall: (request, handler) =>\n handler({\n ...request,\n systemMessage: request.systemMessage.concat(\n `\\n\\n${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`\n ),\n }),\n afterModel: (state) => {\n /**\n * Check for parallel write_todos tool calls and return errors if detected.\n *\n * The todo list is designed to be updated at most once per model turn. Since\n * the `write_todos` tool replaces the entire todo list with each call, making\n * multiple parallel calls would create ambiguity about which update should take\n * precedence. This method prevents such conflicts by rejecting any response that\n * contains multiple write_todos tool calls.\n */\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return undefined;\n }\n\n /**\n * Find the last AI message\n */\n const lastAiMsg = [...messages]\n .reverse()\n .find((msg) => AIMessage.isInstance(msg));\n if (\n !lastAiMsg ||\n !lastAiMsg.tool_calls ||\n lastAiMsg.tool_calls.length === 0\n ) {\n return undefined;\n }\n\n /**\n * Count write_todos tool calls\n */\n const writeTodosCalls = lastAiMsg.tool_calls.filter(\n (tc) => tc.name === writeTodos.name\n );\n\n if (writeTodosCalls.length > 1) {\n /**\n * Create error tool messages for all write_todos calls\n */\n const errorMessages = writeTodosCalls.map(\n (tc) =>\n new ToolMessage({\n content:\n \"Error: The `write_todos` tool should never be called multiple times \" +\n \"in parallel. Please call it only once per model invocation to update \" +\n \"the todo list.\",\n tool_call_id: tc.id as string,\n status: \"error\",\n })\n );\n\n /**\n * Keep the tool calls in the AI message but return error messages\n * This follows the same pattern as HumanInTheLoopMiddleware\n */\n return { messages: errorMessages };\n }\n\n return undefined;\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAWA,MAAM,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qLAoNoJ,CAAC;AAEtL,MAAa,qCAAqC,CAAC;;;;;;;;;;;;kJAY+F,CAAC;AAEnJ,MAAM,aAAaA,SAChB,KAAK;CAAC;CAAW;CAAe;AAAY,EAAC,CAC7C,SAAS,qBAAqB;AACjC,MAAM,aAAaA,SAAE,OAAO;CAC1B,SAASA,SAAE,QAAQ,CAAC,SAAS,2BAA2B;CACxD,QAAQ;AACT,EAAC;AACF,MAAM,cAAcA,SAAE,OAAO,EAC3B,OAAOA,SAAE,MAAM,WAAW,CAAC,QAAQ,CAAE,EAAC,CACvC,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDF,SAAgB,mBAAmBC,SAAqC;;;;CAItE,MAAM,8CACJ,CAAC,EAAE,OAAO,EAAE,WAAW;AACrB,SAAO,IAAIC,8BAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAIC,sCAAY;IACd,SAAS,CAAC,qBAAqB,EAAE,KAAK,UAAU,MAAM,EAAE;IACxD,cAAc,OAAO,UAAU;GAChC,EACF;EACF,EACF;CACF,GACD;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQH,SAAE,OAAO,EACf,OAAOA,SAAE,MAAM,WAAW,CAAC,SAAS,+BAA+B,CACpE,EAAC;CACH,EACF;AAED,QAAOI,oCAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAW;EACnB,eAAe,CAAC,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,CAAC,IAAI,EAAE,SAAS,gBAAgB,oCAAoC,CACrE;EACF,EAAC;EACJ,YAAY,CAAC,UAAU;;;;;;;;;;GAUrB,MAAM,WAAW,MAAM;AACvB,OAAI,CAAC,YAAY,SAAS,WAAW,EACnC,QAAO;;;;GAMT,MAAM,YAAY,CAAC,GAAG,QAAS,EAC5B,SAAS,CACT,KAAK,CAAC,QAAQC,oCAAU,WAAW,IAAI,CAAC;AAC3C,OACE,CAAC,aACD,CAAC,UAAU,cACX,UAAU,WAAW,WAAW,EAEhC,QAAO;;;;GAMT,MAAM,kBAAkB,UAAU,WAAW,OAC3C,CAAC,OAAO,GAAG,SAAS,WAAW,KAChC;AAED,OAAI,gBAAgB,SAAS,GAAG;;;;IAI9B,MAAM,gBAAgB,gBAAgB,IACpC,CAAC,OACC,IAAIF,sCAAY;KACd,SACE;KAGF,cAAc,GAAG;KACjB,QAAQ;IACT,GACJ;;;;;AAMD,WAAO,EAAE,UAAU,cAAe;GACnC;AAED,UAAO;EACR;CACF,EAAC;AACH"}
@@ -1,4 +1,8 @@
1
1
  import { AgentMiddleware } from "./types.cjs";
2
+ import * as _langchain_core_messages26 from "@langchain/core/messages";
3
+ import { ToolMessage } from "@langchain/core/messages";
4
+ import * as _langchain_core_tools9 from "@langchain/core/tools";
5
+ import { Command } from "@langchain/langgraph";
2
6
  import { z } from "zod/v3";
3
7
 
4
8
  //#region src/agents/middleware/todoListMiddleware.d.ts
@@ -24,7 +28,9 @@ interface TodoListMiddlewareOptions {
24
28
  * into task completion status.
25
29
  *
26
30
  * The middleware automatically injects system prompts that guide the agent on when
27
- * and how to use the todo functionality effectively.
31
+ * and how to use the todo functionality effectively. It also enforces that the
32
+ * `write_todos` tool is called at most once per model turn, since the tool replaces
33
+ * the entire todo list and parallel calls would create ambiguity about precedence.
28
34
  *
29
35
  * @example
30
36
  * ```typescript
@@ -69,7 +75,44 @@ declare function todoListMiddleware(options?: TodoListMiddlewareOptions): AgentM
69
75
  content: string;
70
76
  status: "completed" | "in_progress" | "pending";
71
77
  }[] | undefined;
72
- }>, undefined, any>;
78
+ }>, undefined, unknown, readonly [_langchain_core_tools9.DynamicStructuredTool<z.ZodObject<{
79
+ todos: z.ZodArray<z.ZodObject<{
80
+ content: z.ZodString;
81
+ status: z.ZodEnum<["pending", "in_progress", "completed"]>;
82
+ }, "strip", z.ZodTypeAny, {
83
+ content: string;
84
+ status: "completed" | "in_progress" | "pending";
85
+ }, {
86
+ content: string;
87
+ status: "completed" | "in_progress" | "pending";
88
+ }>, "many">;
89
+ }, "strip", z.ZodTypeAny, {
90
+ todos: {
91
+ content: string;
92
+ status: "completed" | "in_progress" | "pending";
93
+ }[];
94
+ }, {
95
+ todos: {
96
+ content: string;
97
+ status: "completed" | "in_progress" | "pending";
98
+ }[];
99
+ }>, {
100
+ todos: {
101
+ content: string;
102
+ status: "completed" | "in_progress" | "pending";
103
+ }[];
104
+ }, {
105
+ todos: {
106
+ content: string;
107
+ status: "completed" | "in_progress" | "pending";
108
+ }[];
109
+ }, Command<unknown, {
110
+ todos: {
111
+ content: string;
112
+ status: "completed" | "in_progress" | "pending";
113
+ }[];
114
+ messages: ToolMessage<_langchain_core_messages26.MessageStructure<_langchain_core_messages26.MessageToolSet>>[];
115
+ }, string>, "write_todos">]>;
73
116
  //#endregion
74
117
  export { TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, TodoListMiddlewareOptions, todoListMiddleware };
75
118
  //# sourceMappingURL=todoListMiddleware.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.d.cts","names":["z","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","__types_js12","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nexport declare const 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.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, any>;\nexport {};\n//# sourceMappingURL=todoListMiddleware.d.ts.map"],"mappings":";;;;cACqBC,kCAAAA;UAwBJU,yBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6COC,kBAAAA,WAA6BD,4CAAiEX,CAAAA,CAAEM;SAC7GN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,SAASP,CAAAA,CAAEM;aACpBN,CAAAA,CAAEG;YACHH,CAAAA,CAAEI;cACFJ,CAAAA,CAAEK;;;;;;;YAONL,CAAAA,CAAEK"}
1
+ {"version":3,"file":"todoListMiddleware.d.cts","names":["_langchain_core_tools9","__types_js12","z","Command","ToolMessage","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","_langchain_core_messages26","MessageToolSet","MessageStructure","DynamicStructuredTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nexport declare const 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.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively. It also enforces that the\n * `write_todos` tool is called at most once per model turn, since the tool replaces\n * the entire todo list and parallel calls would create ambiguity about precedence.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, unknown, readonly [import(\"@langchain/core/tools\").DynamicStructuredTool<z.ZodObject<{\n todos: z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}>, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, Command<unknown, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n messages: ToolMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>>[];\n}, string>, \"write_todos\">]>;\nexport {};\n//# sourceMappingURL=todoListMiddleware.d.ts.map"],"mappings":";;;;;;;;cAGqBK,kCAAAA;AA4F8EY,UApElFF,yBAAAA,CAwGgGG;EAAcD;;;;;EAzDV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA7FD,kBAAAA,WAA6BD,4CAAiEb,CAAAA,CAAEQ;SAC7GR,CAAAA,CAAEU,WAAWV,CAAAA,CAAES,SAAST,CAAAA,CAAEQ;aACpBR,CAAAA,CAAEK;YACHL,CAAAA,CAAEM;cACFN,CAAAA,CAAEO;;;;;;;YAONP,CAAAA,CAAEO;;;;;;;;;;kCAyCJT,sBAAAA,CA/BwDoB,sBAAsBlB,CAAAA,CAAEQ;SAC/ER,CAAAA,CAAES,SAAST,CAAAA,CAAEQ;aACPR,CAAAA,CAAEK;YACHL,CAAAA,CAAEM;cACFN,CAAAA,CAAEO;;;;;;;YAONP,CAAAA,CAAEO;;;;;;;;;;;;;;;;;;;;GAoBXN;;;;;YAKWC,YAAiHa,0BAAAA,CAAlEE,iBApCsCF,0BAAAA,CAoCcC,cAAAA"}
@@ -1,4 +1,8 @@
1
1
  import { AgentMiddleware } from "./types.js";
2
+ import * as _langchain_core_messages26 from "@langchain/core/messages";
3
+ import { ToolMessage } from "@langchain/core/messages";
4
+ import * as _langchain_core_tools9 from "@langchain/core/tools";
5
+ import { Command } from "@langchain/langgraph";
2
6
  import { z } from "zod/v3";
3
7
 
4
8
  //#region src/agents/middleware/todoListMiddleware.d.ts
@@ -24,7 +28,9 @@ interface TodoListMiddlewareOptions {
24
28
  * into task completion status.
25
29
  *
26
30
  * The middleware automatically injects system prompts that guide the agent on when
27
- * and how to use the todo functionality effectively.
31
+ * and how to use the todo functionality effectively. It also enforces that the
32
+ * `write_todos` tool is called at most once per model turn, since the tool replaces
33
+ * the entire todo list and parallel calls would create ambiguity about precedence.
28
34
  *
29
35
  * @example
30
36
  * ```typescript
@@ -69,7 +75,44 @@ declare function todoListMiddleware(options?: TodoListMiddlewareOptions): AgentM
69
75
  content: string;
70
76
  status: "completed" | "in_progress" | "pending";
71
77
  }[] | undefined;
72
- }>, undefined, any>;
78
+ }>, undefined, unknown, readonly [_langchain_core_tools9.DynamicStructuredTool<z.ZodObject<{
79
+ todos: z.ZodArray<z.ZodObject<{
80
+ content: z.ZodString;
81
+ status: z.ZodEnum<["pending", "in_progress", "completed"]>;
82
+ }, "strip", z.ZodTypeAny, {
83
+ content: string;
84
+ status: "completed" | "in_progress" | "pending";
85
+ }, {
86
+ content: string;
87
+ status: "completed" | "in_progress" | "pending";
88
+ }>, "many">;
89
+ }, "strip", z.ZodTypeAny, {
90
+ todos: {
91
+ content: string;
92
+ status: "completed" | "in_progress" | "pending";
93
+ }[];
94
+ }, {
95
+ todos: {
96
+ content: string;
97
+ status: "completed" | "in_progress" | "pending";
98
+ }[];
99
+ }>, {
100
+ todos: {
101
+ content: string;
102
+ status: "completed" | "in_progress" | "pending";
103
+ }[];
104
+ }, {
105
+ todos: {
106
+ content: string;
107
+ status: "completed" | "in_progress" | "pending";
108
+ }[];
109
+ }, Command<unknown, {
110
+ todos: {
111
+ content: string;
112
+ status: "completed" | "in_progress" | "pending";
113
+ }[];
114
+ messages: ToolMessage<_langchain_core_messages26.MessageStructure<_langchain_core_messages26.MessageToolSet>>[];
115
+ }, string>, "write_todos">]>;
73
116
  //#endregion
74
117
  export { TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, TodoListMiddlewareOptions, todoListMiddleware };
75
118
  //# sourceMappingURL=todoListMiddleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.d.ts","names":["z","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","__types_js12","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nexport declare const 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.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, any>;\nexport {};\n//# sourceMappingURL=todoListMiddleware.d.ts.map"],"mappings":";;;;cACqBC,kCAAAA;UAwBJU,yBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6COC,kBAAAA,WAA6BD,4CAAiEX,CAAAA,CAAEM;SAC7GN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,SAASP,CAAAA,CAAEM;aACpBN,CAAAA,CAAEG;YACHH,CAAAA,CAAEI;cACFJ,CAAAA,CAAEK;;;;;;;YAONL,CAAAA,CAAEK"}
1
+ {"version":3,"file":"todoListMiddleware.d.ts","names":["_langchain_core_tools9","__types_js12","z","Command","ToolMessage","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","_langchain_core_messages26","MessageToolSet","MessageStructure","DynamicStructuredTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nexport declare const 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.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively. It also enforces that the\n * `write_todos` tool is called at most once per model turn, since the tool replaces\n * the entire todo list and parallel calls would create ambiguity about precedence.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, unknown, readonly [import(\"@langchain/core/tools\").DynamicStructuredTool<z.ZodObject<{\n todos: z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}>, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, Command<unknown, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n messages: ToolMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>>[];\n}, string>, \"write_todos\">]>;\nexport {};\n//# sourceMappingURL=todoListMiddleware.d.ts.map"],"mappings":";;;;;;;;cAGqBK,kCAAAA;AA4F8EY,UApElFF,yBAAAA,CAwGgGG;EAAcD;;;;;EAzDV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA7FD,kBAAAA,WAA6BD,4CAAiEb,CAAAA,CAAEQ;SAC7GR,CAAAA,CAAEU,WAAWV,CAAAA,CAAES,SAAST,CAAAA,CAAEQ;aACpBR,CAAAA,CAAEK;YACHL,CAAAA,CAAEM;cACFN,CAAAA,CAAEO;;;;;;;YAONP,CAAAA,CAAEO;;;;;;;;;;kCAyCJT,sBAAAA,CA/BwDoB,sBAAsBlB,CAAAA,CAAEQ;SAC/ER,CAAAA,CAAES,SAAST,CAAAA,CAAEQ;aACPR,CAAAA,CAAEK;YACHL,CAAAA,CAAEM;cACFN,CAAAA,CAAEO;;;;;;;YAONP,CAAAA,CAAEO;;;;;;;;;;;;;;;;;;;;GAoBXN;;;;;YAKWC,YAAiHa,0BAAAA,CAAlEE,iBApCsCF,0BAAAA,CAoCcC,cAAAA"}
@@ -1,6 +1,6 @@
1
1
  import { createMiddleware } from "../middleware.js";
2
2
  import "../index.js";
3
- import { ToolMessage } from "@langchain/core/messages";
3
+ import { AIMessage, ToolMessage } from "@langchain/core/messages";
4
4
  import { tool } from "@langchain/core/tools";
5
5
  import { Command } from "@langchain/langgraph";
6
6
  import { z } from "zod/v3";
@@ -255,7 +255,9 @@ const stateSchema = z.object({ todos: z.array(TodoSchema).default([]) });
255
255
  * into task completion status.
256
256
  *
257
257
  * The middleware automatically injects system prompts that guide the agent on when
258
- * and how to use the todo functionality effectively.
258
+ * and how to use the todo functionality effectively. It also enforces that the
259
+ * `write_todos` tool is called at most once per model turn, since the tool replaces
260
+ * the entire todo list and parallel calls would create ambiguity about precedence.
259
261
  *
260
262
  * @example
261
263
  * ```typescript
@@ -303,7 +305,45 @@ function todoListMiddleware(options) {
303
305
  wrapModelCall: (request, handler) => handler({
304
306
  ...request,
305
307
  systemMessage: request.systemMessage.concat(`\n\n${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`)
306
- })
308
+ }),
309
+ afterModel: (state) => {
310
+ /**
311
+ * Check for parallel write_todos tool calls and return errors if detected.
312
+ *
313
+ * The todo list is designed to be updated at most once per model turn. Since
314
+ * the `write_todos` tool replaces the entire todo list with each call, making
315
+ * multiple parallel calls would create ambiguity about which update should take
316
+ * precedence. This method prevents such conflicts by rejecting any response that
317
+ * contains multiple write_todos tool calls.
318
+ */
319
+ const messages = state.messages;
320
+ if (!messages || messages.length === 0) return void 0;
321
+ /**
322
+ * Find the last AI message
323
+ */
324
+ const lastAiMsg = [...messages].reverse().find((msg) => AIMessage.isInstance(msg));
325
+ if (!lastAiMsg || !lastAiMsg.tool_calls || lastAiMsg.tool_calls.length === 0) return void 0;
326
+ /**
327
+ * Count write_todos tool calls
328
+ */
329
+ const writeTodosCalls = lastAiMsg.tool_calls.filter((tc) => tc.name === writeTodos.name);
330
+ if (writeTodosCalls.length > 1) {
331
+ /**
332
+ * Create error tool messages for all write_todos calls
333
+ */
334
+ const errorMessages = writeTodosCalls.map((tc) => new ToolMessage({
335
+ content: "Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",
336
+ tool_call_id: tc.id,
337
+ status: "error"
338
+ }));
339
+ /**
340
+ * Keep the tool calls in the AI message but return error messages
341
+ * This follows the same pattern as HumanInTheLoopMiddleware
342
+ */
343
+ return { messages: errorMessages };
344
+ }
345
+ return void 0;
346
+ }
307
347
  });
308
348
  }
309
349
 
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.js","names":["options?: TodoListMiddlewareOptions"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { ToolMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../index.js\";\n\n/**\n * Description for the write_todos tool\n * Ported exactly from Python WRITE_TODOS_DESCRIPTION\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.`;\n\nexport const 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.`;\n\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({\n todos: z.array(TodoSchema).default([]),\n});\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\n\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport function todoListMiddleware(options?: TodoListMiddlewareOptions) {\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: `Updated todo list to ${JSON.stringify(todos)}`,\n tool_call_id: config.toolCall?.id as string,\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\n return createMiddleware({\n name: \"todoListMiddleware\",\n stateSchema,\n tools: [writeTodos],\n wrapModelCall: (request, handler) =>\n handler({\n ...request,\n systemMessage: request.systemMessage.concat(\n `\\n\\n${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`\n ),\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qLAoNoJ,CAAC;AAEtL,MAAa,qCAAqC,CAAC;;;;;;;;;;;;kJAY+F,CAAC;AAEnJ,MAAM,aAAa,EAChB,KAAK;CAAC;CAAW;CAAe;AAAY,EAAC,CAC7C,SAAS,qBAAqB;AACjC,MAAM,aAAa,EAAE,OAAO;CAC1B,SAAS,EAAE,QAAQ,CAAC,SAAS,2BAA2B;CACxD,QAAQ;AACT,EAAC;AACF,MAAM,cAAc,EAAE,OAAO,EAC3B,OAAO,EAAE,MAAM,WAAW,CAAC,QAAQ,CAAE,EAAC,CACvC,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDF,SAAgB,mBAAmBA,SAAqC;;;;CAItE,MAAM,aAAa,KACjB,CAAC,EAAE,OAAO,EAAE,WAAW;AACrB,SAAO,IAAI,QAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAI,YAAY;IACd,SAAS,CAAC,qBAAqB,EAAE,KAAK,UAAU,MAAM,EAAE;IACxD,cAAc,OAAO,UAAU;GAChC,EACF;EACF,EACF;CACF,GACD;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQ,EAAE,OAAO,EACf,OAAO,EAAE,MAAM,WAAW,CAAC,SAAS,+BAA+B,CACpE,EAAC;CACH,EACF;AAED,QAAO,iBAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAW;EACnB,eAAe,CAAC,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,CAAC,IAAI,EAAE,SAAS,gBAAgB,oCAAoC,CACrE;EACF,EAAC;CACL,EAAC;AACH"}
1
+ {"version":3,"file":"todoListMiddleware.js","names":["options?: TodoListMiddlewareOptions"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { tool } from \"@langchain/core/tools\";\nimport { AIMessage, ToolMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../index.js\";\n\n/**\n * Description for the write_todos tool\n * Ported exactly from Python WRITE_TODOS_DESCRIPTION\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.`;\n\nexport const 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.`;\n\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({\n todos: z.array(TodoSchema).default([]),\n});\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\n\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively. It also enforces that the\n * `write_todos` tool is called at most once per model turn, since the tool replaces\n * the entire todo list and parallel calls would create ambiguity about precedence.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport function todoListMiddleware(options?: TodoListMiddlewareOptions) {\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: `Updated todo list to ${JSON.stringify(todos)}`,\n tool_call_id: config.toolCall?.id as string,\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\n return createMiddleware({\n name: \"todoListMiddleware\",\n stateSchema,\n tools: [writeTodos],\n wrapModelCall: (request, handler) =>\n handler({\n ...request,\n systemMessage: request.systemMessage.concat(\n `\\n\\n${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`\n ),\n }),\n afterModel: (state) => {\n /**\n * Check for parallel write_todos tool calls and return errors if detected.\n *\n * The todo list is designed to be updated at most once per model turn. Since\n * the `write_todos` tool replaces the entire todo list with each call, making\n * multiple parallel calls would create ambiguity about which update should take\n * precedence. This method prevents such conflicts by rejecting any response that\n * contains multiple write_todos tool calls.\n */\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return undefined;\n }\n\n /**\n * Find the last AI message\n */\n const lastAiMsg = [...messages]\n .reverse()\n .find((msg) => AIMessage.isInstance(msg));\n if (\n !lastAiMsg ||\n !lastAiMsg.tool_calls ||\n lastAiMsg.tool_calls.length === 0\n ) {\n return undefined;\n }\n\n /**\n * Count write_todos tool calls\n */\n const writeTodosCalls = lastAiMsg.tool_calls.filter(\n (tc) => tc.name === writeTodos.name\n );\n\n if (writeTodosCalls.length > 1) {\n /**\n * Create error tool messages for all write_todos calls\n */\n const errorMessages = writeTodosCalls.map(\n (tc) =>\n new ToolMessage({\n content:\n \"Error: The `write_todos` tool should never be called multiple times \" +\n \"in parallel. Please call it only once per model invocation to update \" +\n \"the todo list.\",\n tool_call_id: tc.id as string,\n status: \"error\",\n })\n );\n\n /**\n * Keep the tool calls in the AI message but return error messages\n * This follows the same pattern as HumanInTheLoopMiddleware\n */\n return { messages: errorMessages };\n }\n\n return undefined;\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,0BAA0B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qLAoNoJ,CAAC;AAEtL,MAAa,qCAAqC,CAAC;;;;;;;;;;;;kJAY+F,CAAC;AAEnJ,MAAM,aAAa,EAChB,KAAK;CAAC;CAAW;CAAe;AAAY,EAAC,CAC7C,SAAS,qBAAqB;AACjC,MAAM,aAAa,EAAE,OAAO;CAC1B,SAAS,EAAE,QAAQ,CAAC,SAAS,2BAA2B;CACxD,QAAQ;AACT,EAAC;AACF,MAAM,cAAc,EAAE,OAAO,EAC3B,OAAO,EAAE,MAAM,WAAW,CAAC,QAAQ,CAAE,EAAC,CACvC,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDF,SAAgB,mBAAmBA,SAAqC;;;;CAItE,MAAM,aAAa,KACjB,CAAC,EAAE,OAAO,EAAE,WAAW;AACrB,SAAO,IAAI,QAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAI,YAAY;IACd,SAAS,CAAC,qBAAqB,EAAE,KAAK,UAAU,MAAM,EAAE;IACxD,cAAc,OAAO,UAAU;GAChC,EACF;EACF,EACF;CACF,GACD;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQ,EAAE,OAAO,EACf,OAAO,EAAE,MAAM,WAAW,CAAC,SAAS,+BAA+B,CACpE,EAAC;CACH,EACF;AAED,QAAO,iBAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAW;EACnB,eAAe,CAAC,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,CAAC,IAAI,EAAE,SAAS,gBAAgB,oCAAoC,CACrE;EACF,EAAC;EACJ,YAAY,CAAC,UAAU;;;;;;;;;;GAUrB,MAAM,WAAW,MAAM;AACvB,OAAI,CAAC,YAAY,SAAS,WAAW,EACnC,QAAO;;;;GAMT,MAAM,YAAY,CAAC,GAAG,QAAS,EAC5B,SAAS,CACT,KAAK,CAAC,QAAQ,UAAU,WAAW,IAAI,CAAC;AAC3C,OACE,CAAC,aACD,CAAC,UAAU,cACX,UAAU,WAAW,WAAW,EAEhC,QAAO;;;;GAMT,MAAM,kBAAkB,UAAU,WAAW,OAC3C,CAAC,OAAO,GAAG,SAAS,WAAW,KAChC;AAED,OAAI,gBAAgB,SAAS,GAAG;;;;IAI9B,MAAM,gBAAgB,gBAAgB,IACpC,CAAC,OACC,IAAI,YAAY;KACd,SACE;KAGF,cAAc,GAAG;KACjB,QAAQ;IACT,GACJ;;;;;AAMD,WAAO,EAAE,UAAU,cAAe;GACnC;AAED,UAAO;EACR;CACF,EAAC;AACH"}
@@ -1,4 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.cjs";
2
+ import * as _langchain_core_tools7 from "@langchain/core/tools";
2
3
  import { InferInteropZodInput } from "@langchain/core/utils/types";
3
4
  import { z } from "zod/v3";
4
5
 
@@ -163,7 +164,7 @@ declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): AgentMid
163
164
  }, {
164
165
  threadToolCallCount?: Record<string, number> | undefined;
165
166
  runToolCallCount?: Record<string, number> | undefined;
166
- }>, undefined, any>;
167
+ }>, undefined, unknown, readonly (_langchain_core_tools7.ServerTool | _langchain_core_tools7.ClientTool)[]>;
167
168
  //#endregion
168
169
  export { ToolCallLimitConfig, ToolCallLimitExceededError, toolCallLimitMiddleware };
169
170
  //# sourceMappingURL=toolCallLimit.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"toolCallLimit.d.cts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js11","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAIgBM,cA9BKJ,0BAAAA,SAAmCC,KAAK,CA8B7CG;EAKiBC;;;EAKjBD,WAAAA,EAAAA,MAAAA;EAWiBE;;;EAzBkBG,QAAAA,EAAAA,MAAAA;EAAS;AAqC5D;AAiFA;EAAyDC,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACLP;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACsBJ;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACVC,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAHwGC,cAtHjGP,0BAsHiGO,EAtHrEX,CAAAA,CAAEW,SAsHmEA,CAAAA;;AAAH;;YAlHrGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;;;;;eAKbL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA"}
1
+ {"version":3,"file":"toolCallLimit.d.cts","names":["__types_js11","z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","_langchain_core_tools7","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;;;AAQA;AA0BA;AAI8BM,cA9BTH,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAdC;;;EAUcC,WAAAA,EAAAA,MAAAA;EAAdD;;;EAYFI,QAAAA,EAAAA,MAAAA;EA1BqCC;AAAS;AAqC5D;EAiFwBE,WAAAA,EAAAA,MAAAA,GAAAA,SAAuB;EAAUD;;;EACjBE,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL;;;EACUK,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAMDM,cA9HFX,0BA8HEW,EA9H0Bf,CAAAA,CAAEW,SA8H5BI,CAAAA;EAR+FJ;;;YAlHxGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;EAkHqF;;;;eA7GlGL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA;kCARwGC,sBAAAA,CAS7DC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
@@ -1,4 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.js";
2
+ import * as _langchain_core_tools7 from "@langchain/core/tools";
2
3
  import { z } from "zod/v3";
3
4
  import { InferInteropZodInput } from "@langchain/core/utils/types";
4
5
 
@@ -163,7 +164,7 @@ declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): AgentMid
163
164
  }, {
164
165
  threadToolCallCount?: Record<string, number> | undefined;
165
166
  runToolCallCount?: Record<string, number> | undefined;
166
- }>, undefined, any>;
167
+ }>, undefined, unknown, readonly (_langchain_core_tools7.ServerTool | _langchain_core_tools7.ClientTool)[]>;
167
168
  //#endregion
168
169
  export { ToolCallLimitConfig, ToolCallLimitExceededError, toolCallLimitMiddleware };
169
170
  //# sourceMappingURL=toolCallLimit.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"toolCallLimit.d.ts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js11","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAIgBM,cA9BKJ,0BAAAA,SAAmCC,KAAK,CA8B7CG;EAKiBC;;;EAKjBD,WAAAA,EAAAA,MAAAA;EAWiBE;;;EAzBkBG,QAAAA,EAAAA,MAAAA;EAAS;AAqC5D;AAiFA;EAAyDC,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACLP;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACsBJ;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACVC,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAHwGC,cAtHjGP,0BAsHiGO,EAtHrEX,CAAAA,CAAEW,SAsHmEA,CAAAA;;AAAH;;YAlHrGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;;;;;eAKbL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA"}
1
+ {"version":3,"file":"toolCallLimit.d.ts","names":["__types_js11","z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","_langchain_core_tools7","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;;;AAQA;AA0BA;AAI8BM,cA9BTH,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAdC;;;EAUcC,WAAAA,EAAAA,MAAAA;EAAdD;;;EAYFI,QAAAA,EAAAA,MAAAA;EA1BqCC;AAAS;AAqC5D;EAiFwBE,WAAAA,EAAAA,MAAAA,GAAAA,SAAuB;EAAUD;;;EACjBE,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL;;;EACUK,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAMDM,cA9HFX,0BA8HEW,EA9H0Bf,CAAAA,CAAEW,SA8H5BI,CAAAA;EAR+FJ;;;YAlHxGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;EAkHqF;;;;eA7GlGL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA;kCARwGC,sBAAAA,CAS7DC,UAAAA,GAAUD,sBAAAA,CAAmCE"}