langchain 1.5.18 → 1.5.19

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.
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.cjs","names":["z","tool","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 task 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});\nexport type Todo = z.infer<typeof TodoSchema>;\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 name: \"write_todos\",\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 name: \"write_todos\",\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsNhC,MAAa,qCAAqC;;;;;;;;;;;;;AAclD,MAAM,aAAaA,OAAAA,EAChB,KAAK;CAAC;CAAW;CAAe;AAAW,CAAC,CAAC,CAC7C,SAAS,oBAAoB;AAChC,MAAM,aAAaA,OAAAA,EAAE,OAAO;CAC1B,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,0BAA0B;CACvD,QAAQ;AACV,CAAC;AAGD,MAAM,cAAcA,OAAAA,EAAE,OAAO,EAC3B,OAAOA,OAAAA,EAAE,MAAM,UAAU,CAAC,CAAC,QAAQ,CAAC,CAAC,EACvC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDD,SAAgB,mBAAmB,SAAqC;;;;CAItE,MAAM,cAAA,GAAaC,sBAAAA,KAAAA,EAChB,EAAE,SAAS,WAAW;EACrB,OAAO,IAAIC,qBAAAA,QAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAIC,yBAAAA,YAAY;IACd,SAAS,wBAAwB,KAAK,UAAU,KAAK;IACrD,cAAc,OAAO,UAAU;IAC/B,MAAM;GACR,CAAC,CACH;EACF,EACF,CAAC;CACH,GACA;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQH,OAAAA,EAAE,OAAO,EACf,OAAOA,OAAAA,EAAE,MAAM,UAAU,CAAC,CAAC,SAAS,8BAA8B,EACpE,CAAC;CACH,CACF;CAEA,OAAOI,mBAAAA,iBAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAU;EAClB,gBAAgB,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,OAAO,SAAS,gBAAgB,oCAClC;EACF,CAAC;EACH,aAAa,UAAU;;;;;;;;;;GAUrB,MAAM,WAAW,MAAM;GACvB,IAAI,CAAC,YAAY,SAAS,WAAW,GACnC;;;;GAMF,MAAM,YAAY,CAAC,GAAG,QAAQ,CAAC,CAC5B,QAAQ,CAAC,CACT,MAAM,QAAQC,yBAAAA,UAAU,WAAW,GAAG,CAAC;GAC1C,IACE,CAAC,aACD,CAAC,UAAU,cACX,UAAU,WAAW,WAAW,GAEhC;;;;GAMF,MAAM,kBAAkB,UAAU,WAAW,QAC1C,OAAO,GAAG,SAAS,WAAW,IACjC;GAEA,IAAI,gBAAgB,SAAS;;;;;GAqB3B,OAAO,EAAE,UAjBa,gBAAgB,KACnC,OACC,IAAIF,yBAAAA,YAAY;IACd,SACE;IAGF,cAAc,GAAG;IACjB,MAAM;IACN,QAAQ;GACV,CAAC,CAO0B,EAAE;EAIrC;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"todoListMiddleware.cjs","names":["z","tool","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 and organize complex tasks.\n\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 task directly.\n\n## When to Use This Tool\n\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\n\n## How to Use This Tool\n\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\n\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## 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.\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 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\n## When You Finish\n\n\\`write_todos\\` tracks your work; it does not deliver the answer. Whatever the user asked for — computations, summaries, comparisons, data — must appear as text content in a message after your final \\`write_todos\\` call. Marking the last todo complete is not itself an answer to the user.`;\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.\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\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\n## Finishing a task\n\nWhen you finish all work, write your final answer in the message AFTER your last \\`write_todos\\` call — not in the same turn as that call. Start the final message with the substantive content the user asked for — the data, computation, summary, or analysis. The user wants the result, not confirmation that the work is done.`;\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});\nexport type Todo = z.infer<typeof TodoSchema>;\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 name: \"write_todos\",\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 name: \"write_todos\",\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEhC,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;AAmBlD,MAAM,aAAaA,OAAAA,EAChB,KAAK;CAAC;CAAW;CAAe;AAAW,CAAC,CAAC,CAC7C,SAAS,oBAAoB;AAChC,MAAM,aAAaA,OAAAA,EAAE,OAAO;CAC1B,SAASA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,0BAA0B;CACvD,QAAQ;AACV,CAAC;AAGD,MAAM,cAAcA,OAAAA,EAAE,OAAO,EAC3B,OAAOA,OAAAA,EAAE,MAAM,UAAU,CAAC,CAAC,QAAQ,CAAC,CAAC,EACvC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDD,SAAgB,mBAAmB,SAAqC;;;;CAItE,MAAM,cAAA,GAAaC,sBAAAA,KAAAA,EAChB,EAAE,SAAS,WAAW;EACrB,OAAO,IAAIC,qBAAAA,QAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAIC,yBAAAA,YAAY;IACd,SAAS,wBAAwB,KAAK,UAAU,KAAK;IACrD,cAAc,OAAO,UAAU;IAC/B,MAAM;GACR,CAAC,CACH;EACF,EACF,CAAC;CACH,GACA;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQH,OAAAA,EAAE,OAAO,EACf,OAAOA,OAAAA,EAAE,MAAM,UAAU,CAAC,CAAC,SAAS,8BAA8B,EACpE,CAAC;CACH,CACF;CAEA,OAAOI,mBAAAA,iBAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAU;EAClB,gBAAgB,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,OAAO,SAAS,gBAAgB,oCAClC;EACF,CAAC;EACH,aAAa,UAAU;;;;;;;;;;GAUrB,MAAM,WAAW,MAAM;GACvB,IAAI,CAAC,YAAY,SAAS,WAAW,GACnC;;;;GAMF,MAAM,YAAY,CAAC,GAAG,QAAQ,CAAC,CAC5B,QAAQ,CAAC,CACT,MAAM,QAAQC,yBAAAA,UAAU,WAAW,GAAG,CAAC;GAC1C,IACE,CAAC,aACD,CAAC,UAAU,cACX,UAAU,WAAW,WAAW,GAEhC;;;;GAMF,MAAM,kBAAkB,UAAU,WAAW,QAC1C,OAAO,GAAG,SAAS,WAAW,IACjC;GAEA,IAAI,gBAAgB,SAAS;;;;;GAqB3B,OAAO,EAAE,UAjBa,gBAAgB,KACnC,OACC,IAAIF,yBAAAA,YAAY;IACd,SACE;IAGF,cAAc,GAAG;IACjB,MAAM;IACN,QAAQ;GACV,CAAC,CAO0B,EAAE;EAIrC;CACF,CAAC;AACH"}
@@ -3,7 +3,7 @@ import { ToolMessage } from "@langchain/core/messages";
3
3
  import { Command } from "@langchain/langgraph";
4
4
  import { z } from "zod/v3";
5
5
  //#region src/agents/middleware/todoListMiddleware.d.ts
6
- export 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.";
6
+ export 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.\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\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\n## Finishing a task\n\nWhen you finish all work, write your final answer in the message AFTER your last `write_todos` call — not in the same turn as that call. Start the final message with the substantive content the user asked for — the data, computation, summary, or analysis. The user wants the result, not confirmation that the work is done.";
7
7
  declare const TodoSchema: z.ZodObject<{
8
8
  content: z.ZodString;
9
9
  status: z.ZodEnum<["pending", "in_progress", "completed"]>;
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.d.cts","names":["_$__types_js0.AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"mappings":";;;;;qBAiOa;cAiBP,YAAU,EAAA;;;;;;;;;;YAIJ,OAAO,EAAE,aAAa;iBAOjB;;;;;EAKf;;;;;EAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAsCc,mBAAmB,UAAU,4CAAyB,EAAA"}
1
+ {"version":3,"file":"todoListMiddleware.d.cts","names":["_$__types_js0.AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"mappings":";;;;;qBA8Ea;cAsBP,YAAU,EAAA;;;;;;;;;;YAIJ,OAAO,EAAE,aAAa;iBAOjB;;;;;EAKf;;;;;EAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAsCc,mBAAmB,UAAU,4CAAyB,EAAA"}
@@ -3,7 +3,7 @@ import { ToolMessage } from "@langchain/core/messages";
3
3
  import { Command } from "@langchain/langgraph";
4
4
  import { z } from "zod/v3";
5
5
  //#region src/agents/middleware/todoListMiddleware.d.ts
6
- export 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.";
6
+ export 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.\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\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\n## Finishing a task\n\nWhen you finish all work, write your final answer in the message AFTER your last `write_todos` call — not in the same turn as that call. Start the final message with the substantive content the user asked for — the data, computation, summary, or analysis. The user wants the result, not confirmation that the work is done.";
7
7
  declare const TodoSchema: z.ZodObject<{
8
8
  content: z.ZodString;
9
9
  status: z.ZodEnum<["pending", "in_progress", "completed"]>;
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.d.ts","names":["_$__types_js0.AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"mappings":";;;;;qBAiOa;cAiBP,YAAU,EAAA;;;;;;;;;;YAIJ,OAAO,EAAE,aAAa;iBAOjB;;;;;EAKf;;;;;EAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAsCc,mBAAmB,UAAU,4CAAyB,EAAA"}
1
+ {"version":3,"file":"todoListMiddleware.d.ts","names":["_$__types_js0.AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.ts"],"mappings":";;;;;qBA8Ea;cAsBP,YAAU,EAAA;;;;;;;;;;YAIJ,OAAO,EAAE,aAAa;iBAOjB;;;;;EAKf;;;;;EAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAsCc,mBAAmB,UAAU,4CAAyB,EAAA"}
@@ -9,223 +9,76 @@ import { z } from "zod/v3";
9
9
  * Description for the write_todos tool
10
10
  * Ported exactly from Python WRITE_TODOS_DESCRIPTION
11
11
  */
12
- const WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
13
- It also helps the user understand the progress of the task and overall progress of their requests.
12
+ const WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress and organize complex tasks.
13
+
14
14
  Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly.
15
15
 
16
16
  ## When to Use This Tool
17
+
17
18
  Use this tool in these scenarios:
18
19
 
19
20
  1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
20
21
  2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
21
22
  3. User explicitly requests todo list - When the user directly asks you to use the todo list
22
23
  4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
23
- 5. 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.
24
+ 5. The plan may need future revisions or updates based on results from the first few steps
24
25
 
25
26
  ## How to Use This Tool
27
+
26
28
  1. When you start working on a task - Mark it as in_progress BEFORE beginning work.
27
29
  2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.
28
30
  3. 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.
29
31
  4. 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.
30
32
 
31
33
  ## When NOT to Use This Tool
34
+
32
35
  It is important to skip using this tool when:
33
36
  1. There is only a single, straightforward task
34
37
  2. The task is trivial and tracking it provides no benefit
35
38
  3. The task can be completed in less than 3 trivial steps
36
39
  4. The task is purely conversational or informational
37
40
 
38
- ## Examples of When to Use the Todo List
39
-
40
- <example>
41
- User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
42
- Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
43
- *Creates todo list with the following items:*
44
- 1. Create dark mode toggle component in Settings page
45
- 2. Add dark mode state management (context/store)
46
- 3. Implement CSS-in-JS styles for dark theme
47
- 4. Update existing components to support theme switching
48
- 5. Run tests and build process, addressing any failures or errors that occur
49
- *Begins working on the first task*
50
-
51
- <reasoning>
52
- The assistant used the todo list because:
53
- 1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes
54
- 2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
55
- 3. Both of the user's requests are complex and require multiple steps to complete.
56
- </reasoning>
57
- </example>
58
-
59
- <example>
60
- User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
61
- Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components.
62
- *Creates todo list with the following items:*
63
- 1. Define target audience and key messaging
64
- 2. Create social media content calendar and posting schedule
65
- 3. Design email marketing sequence and automation flows
66
- 4. Draft press release and identify media contacts
67
- 5. Set up tracking and analytics for campaign performance
68
- 6. Create visual assets and brand materials
69
- 7. Coordinate launch timeline and deliverables
70
- *Begins working on the first task*
71
-
72
- <reasoning>
73
- The assistant used the todo list because:
74
- 1. Marketing campaign planning involves multiple distinct channels and activities
75
- 2. Each component requires careful coordination and planning
76
- 3. The systematic approach ensures all aspects of the launch are covered
77
- </reasoning>
78
- </example>
79
-
80
- <example>
81
- User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
82
- Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
83
- *Uses search tools to locate all instances of getCwd in the codebase*
84
- Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
85
- *Creates todo list with specific items for each file that needs updating*
86
-
87
- <reasoning>
88
- The assistant used the todo list because:
89
- 1. The assistant searched to understand the scope of the task
90
- 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3)
91
- 3. The todo list helps ensure every instance is tracked and updated systematically
92
- 4. This approach prevents missing any occurrences and maintains consistency.
93
- </reasoning>
94
- </example>
95
-
96
- <example>
97
- User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
98
- Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
99
- *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*
100
- Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
101
-
102
- <reasoning>
103
- The assistant used the todo list because:
104
- 1. The user provided multiple distinct organizational tasks
105
- 2. Each area requires different approaches and careful planning
106
- 3. Home organization benefits from systematic, step-by-step completion
107
- 4. Progress tracking ensures all areas are addressed thoroughly
108
- </reasoning>
109
- </example>
110
-
111
- ## Examples of When NOT to Use the Todo List
112
-
113
- <example>
114
- User: How do I print 'Hello World' in Python?
115
- Assistant: In Python, you can print "Hello World" with this simple code:
116
-
117
- \`\`\`python
118
- print("Hello World")
119
- \`\`\`
120
-
121
- This will output the text "Hello World" to the console when executed.</assistant>
122
-
123
- <reasoning>
124
- The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
125
- </reasoning>
126
- </example>
127
-
128
- <example>
129
- User: What's the best way to water houseplants?
130
- Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
131
-
132
- - Check soil moisture by inserting your finger about 1-2 inches into the soil
133
- - Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
134
- - Use room temperature water and water in the morning when possible
135
- - Avoid overwatering, which is more harmful than underwatering for most plants
136
-
137
- Different plants have different needs, so it's important to research your specific varieties for optimal care.
138
-
139
- <reasoning>
140
- The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities.
141
- </reasoning>
142
- </example>
143
-
144
- <example>
145
- User: Can you add a comment to the calculateTotal function to explain what it does?
146
- Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
147
- * Uses the Edit tool to add a comment to the calculateTotal function *
148
-
149
- <reasoning>
150
- The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization.
151
- </reasoning>
152
- </example>
153
-
154
- <example>
155
- User: What time is it in Tokyo right now?
156
- Assistant: I'll check the current time in Tokyo for you.
157
-
158
- *Searches for current time in Tokyo*
159
-
160
- The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
161
-
162
- <reasoning>
163
- The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request.
164
- </reasoning>
165
- </example>
166
-
167
- <example>
168
- User: I need to write a function that checks if a number is prime and then test it out.
169
- Assistant: I'll help you write a function that checks if a number is prime and then test it out.
170
- *Writes function that checks if a number is prime*
171
- *Tests the function*
172
-
173
- <reasoning>
174
- Even 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.
175
- </reasoning>
176
- </example>
177
-
178
- <example>
179
- User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
180
- Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.
181
- *Orders a pizza from Dominos*
182
- *Orders a burger from McDonald's*
183
- *Orders a salad from Subway*
184
-
185
- <reasoning>
186
- Even 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.
187
- Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact.
188
- </reasoning>
189
- </example>
190
-
191
-
192
41
  ## Task States and Management
193
42
 
194
43
  1. **Task States**: Use these states to track progress:
195
- - pending: Task not yet started
196
- - 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)
197
- - completed: Task finished successfully
44
+ - pending: Task not yet started
45
+ - 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)
46
+ - completed: Task finished successfully
198
47
 
199
48
  2. **Task Management**:
200
- - Update task status in real-time as you work
201
- - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
202
- - Complete current tasks before starting new ones
203
- - Remove tasks that are no longer relevant from the list entirely
204
- - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
205
- - 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.
49
+ - Update task status in real-time as you work
50
+ - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
51
+ - Complete current tasks before starting new ones
52
+ - Remove tasks that are no longer relevant from the list entirely
53
+ - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.
54
+ - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress.
206
55
 
207
56
  3. **Task Completion Requirements**:
208
- - ONLY mark a task as completed when you have FULLY accomplished it
209
- - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
210
- - When blocked, create a new task describing what needs to be resolved
211
- - Never mark a task as completed if:
212
- - There are unresolved issues or errors
213
- - Work is partial or incomplete
214
- - You encountered blockers that prevent completion
215
- - You couldn't find necessary resources or dependencies
216
- - Quality standards haven't been met
57
+ - ONLY mark a task as completed when you have FULLY accomplished it
58
+ - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
59
+ - When blocked, create a new task describing what needs to be resolved
60
+ - Never mark a task as completed if:
61
+ - There are unresolved issues or errors
62
+ - Work is partial or incomplete
63
+ - You encountered blockers that prevent completion
64
+ - You couldn't find necessary resources or dependencies
65
+ - Quality standards haven't been met
217
66
 
218
67
  4. **Task Breakdown**:
219
- - Create specific, actionable items
220
- - Break complex tasks into smaller, manageable steps
221
- - Use clear, descriptive task names
68
+ - Create specific, actionable items
69
+ - Break complex tasks into smaller, manageable steps
70
+ - Use clear, descriptive task names
71
+
72
+ Being proactive with task management ensures you complete all requirements successfully
73
+ Remember: 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.
222
74
 
223
- Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully
224
- Remember: 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.`;
75
+ ## When You Finish
76
+
77
+ \`write_todos\` tracks your work; it does not deliver the answer. Whatever the user asked for — computations, summaries, comparisons, data — must appear as text content in a message after your final \`write_todos\` call. Marking the last todo complete is not itself an answer to the user.`;
225
78
  const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = `## \`write_todos\`
226
79
 
227
- You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
228
- Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.
80
+ You have access to the \`write_todos\` tool to help you manage and plan complex objectives.
81
+ Use this tool for complex objectives to ensure that you are tracking each necessary step.
229
82
  This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.
230
83
 
231
84
  It 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.
@@ -233,8 +86,13 @@ For simple objectives that only require a few steps, it is better to just comple
233
86
  Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.
234
87
 
235
88
  ## Important To-Do List Usage Notes to Remember
89
+
236
90
  - The \`write_todos\` tool should never be called multiple times in parallel.
237
- - 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.`;
91
+ - 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.
92
+
93
+ ## Finishing a task
94
+
95
+ When you finish all work, write your final answer in the message AFTER your last \`write_todos\` call — not in the same turn as that call. Start the final message with the substantive content the user asked for — the data, computation, summary, or analysis. The user wants the result, not confirmation that the work is done.`;
238
96
  const TodoStatus = z.enum([
239
97
  "pending",
240
98
  "in_progress",
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.js","names":[],"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 task 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});\nexport type Todo = z.infer<typeof TodoSchema>;\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 name: \"write_todos\",\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 name: \"write_todos\",\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsNhC,MAAa,qCAAqC;;;;;;;;;;;;;AAclD,MAAM,aAAa,EAChB,KAAK;CAAC;CAAW;CAAe;AAAW,CAAC,CAAC,CAC7C,SAAS,oBAAoB;AAChC,MAAM,aAAa,EAAE,OAAO;CAC1B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,0BAA0B;CACvD,QAAQ;AACV,CAAC;AAGD,MAAM,cAAc,EAAE,OAAO,EAC3B,OAAO,EAAE,MAAM,UAAU,CAAC,CAAC,QAAQ,CAAC,CAAC,EACvC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDD,SAAgB,mBAAmB,SAAqC;;;;CAItE,MAAM,aAAa,MAChB,EAAE,SAAS,WAAW;EACrB,OAAO,IAAI,QAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAI,YAAY;IACd,SAAS,wBAAwB,KAAK,UAAU,KAAK;IACrD,cAAc,OAAO,UAAU;IAC/B,MAAM;GACR,CAAC,CACH;EACF,EACF,CAAC;CACH,GACA;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQ,EAAE,OAAO,EACf,OAAO,EAAE,MAAM,UAAU,CAAC,CAAC,SAAS,8BAA8B,EACpE,CAAC;CACH,CACF;CAEA,OAAO,iBAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAU;EAClB,gBAAgB,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,OAAO,SAAS,gBAAgB,oCAClC;EACF,CAAC;EACH,aAAa,UAAU;;;;;;;;;;GAUrB,MAAM,WAAW,MAAM;GACvB,IAAI,CAAC,YAAY,SAAS,WAAW,GACnC;;;;GAMF,MAAM,YAAY,CAAC,GAAG,QAAQ,CAAC,CAC5B,QAAQ,CAAC,CACT,MAAM,QAAQ,UAAU,WAAW,GAAG,CAAC;GAC1C,IACE,CAAC,aACD,CAAC,UAAU,cACX,UAAU,WAAW,WAAW,GAEhC;;;;GAMF,MAAM,kBAAkB,UAAU,WAAW,QAC1C,OAAO,GAAG,SAAS,WAAW,IACjC;GAEA,IAAI,gBAAgB,SAAS;;;;;GAqB3B,OAAO,EAAE,UAjBa,gBAAgB,KACnC,OACC,IAAI,YAAY;IACd,SACE;IAGF,cAAc,GAAG;IACjB,MAAM;IACN,QAAQ;GACV,CAAC,CAO0B,EAAE;EAIrC;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"todoListMiddleware.js","names":[],"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 and organize complex tasks.\n\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 task directly.\n\n## When to Use This Tool\n\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\n\n## How to Use This Tool\n\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\n\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## 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.\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 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\n## When You Finish\n\n\\`write_todos\\` tracks your work; it does not deliver the answer. Whatever the user asked for — computations, summaries, comparisons, data — must appear as text content in a message after your final \\`write_todos\\` call. Marking the last todo complete is not itself an answer to the user.`;\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.\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\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\n## Finishing a task\n\nWhen you finish all work, write your final answer in the message AFTER your last \\`write_todos\\` call — not in the same turn as that call. Start the final message with the substantive content the user asked for — the data, computation, summary, or analysis. The user wants the result, not confirmation that the work is done.`;\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});\nexport type Todo = z.infer<typeof TodoSchema>;\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 name: \"write_todos\",\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 name: \"write_todos\",\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEhC,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;AAmBlD,MAAM,aAAa,EAChB,KAAK;CAAC;CAAW;CAAe;AAAW,CAAC,CAAC,CAC7C,SAAS,oBAAoB;AAChC,MAAM,aAAa,EAAE,OAAO;CAC1B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,0BAA0B;CACvD,QAAQ;AACV,CAAC;AAGD,MAAM,cAAc,EAAE,OAAO,EAC3B,OAAO,EAAE,MAAM,UAAU,CAAC,CAAC,QAAQ,CAAC,CAAC,EACvC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDD,SAAgB,mBAAmB,SAAqC;;;;CAItE,MAAM,aAAa,MAChB,EAAE,SAAS,WAAW;EACrB,OAAO,IAAI,QAAQ,EACjB,QAAQ;GACN;GACA,UAAU,CACR,IAAI,YAAY;IACd,SAAS,wBAAwB,KAAK,UAAU,KAAK;IACrD,cAAc,OAAO,UAAU;IAC/B,MAAM;GACR,CAAC,CACH;EACF,EACF,CAAC;CACH,GACA;EACE,MAAM;EACN,aAAa,SAAS,mBAAmB;EACzC,QAAQ,EAAE,OAAO,EACf,OAAO,EAAE,MAAM,UAAU,CAAC,CAAC,SAAS,8BAA8B,EACpE,CAAC;CACH,CACF;CAEA,OAAO,iBAAiB;EACtB,MAAM;EACN;EACA,OAAO,CAAC,UAAU;EAClB,gBAAgB,SAAS,YACvB,QAAQ;GACN,GAAG;GACH,eAAe,QAAQ,cAAc,OACnC,OAAO,SAAS,gBAAgB,oCAClC;EACF,CAAC;EACH,aAAa,UAAU;;;;;;;;;;GAUrB,MAAM,WAAW,MAAM;GACvB,IAAI,CAAC,YAAY,SAAS,WAAW,GACnC;;;;GAMF,MAAM,YAAY,CAAC,GAAG,QAAQ,CAAC,CAC5B,QAAQ,CAAC,CACT,MAAM,QAAQ,UAAU,WAAW,GAAG,CAAC;GAC1C,IACE,CAAC,aACD,CAAC,UAAU,cACX,UAAU,WAAW,WAAW,GAEhC;;;;GAMF,MAAM,kBAAkB,UAAU,WAAW,QAC1C,OAAO,GAAG,SAAS,WAAW,IACjC;GAEA,IAAI,gBAAgB,SAAS;;;;;GAqB3B,OAAO,EAAE,UAjBa,gBAAgB,KACnC,OACC,IAAI,YAAY;IACd,SACE;IAGF,cAAc,GAAG;IACjB,MAAM;IACN,QAAQ;GACV,CAAC,CAO0B,EAAE;EAIrC;CACF,CAAC;AACH"}
@@ -243,7 +243,7 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
243
243
  */
244
244
  config,
245
245
  toolCallId: toolCall.id,
246
- state: config.configurable?.__pregel_scratchpad?.currentTaskInput,
246
+ state,
247
247
  signal: require_utils.mergeAbortSignals(this.signal, config.signal)
248
248
  });
249
249
  if (_langchain_core_messages.ToolMessage.isInstance(output) || (0, _langchain_langgraph.isCommand)(output)) return output;
@@ -314,7 +314,19 @@ var ToolNode = class extends require_RunnableCallable.RunnableCallable {
314
314
  let outputs;
315
315
  if (isSendInput(state)) {
316
316
  const { lg_tool_call: _, jumpTo: __, ...newState } = state;
317
- outputs = [await this.runTool(state.lg_tool_call, config, newState)];
317
+ let toolState = newState;
318
+ if (Object.keys(newState).length === 0 && this.options?.stateKeys) {
319
+ const read = config.configurable?.__pregel_read;
320
+ if (typeof read !== "function") throw new Error("ToolNode requires a graph state reader for compact Send inputs.");
321
+ toolState = read(this.options.stateKeys, true);
322
+ if (!isMessagesState(toolState)) throw new Error("ToolNode could not read messages from graph state.");
323
+ const scratchpad = config.configurable?.__pregel_scratchpad;
324
+ if (scratchpad) scratchpad.currentTaskInput = {
325
+ ...toolState,
326
+ ...state
327
+ };
328
+ }
329
+ outputs = [await this.runTool(state.lg_tool_call, config, toolState)];
318
330
  } else {
319
331
  let messages;
320
332
  if (isBaseMessageArray(state)) messages = state;