deepagents 0.0.0

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.
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Prompt constants for Deep Agents
3
+ *
4
+ * All prompt strings ported from Python implementation with exact string content and formatting
5
+ * to ensure 1:1 compatibility with the Python version.
6
+ */
7
+ /**
8
+ * Description for the write_todos tool
9
+ * Ported exactly from Python WRITE_TODOS_DESCRIPTION
10
+ */
11
+ export const WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. It also helps the user understand the progress of the task and overall progress of their requests.
12
+
13
+ When to Use This Tool
14
+ Use this tool proactively in these scenarios:
15
+
16
+ Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
17
+ Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
18
+ User explicitly requests todo list - When the user directly asks you to use the todo list
19
+ User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
20
+ After receiving new instructions - Immediately capture user requirements as todos
21
+ When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
22
+ After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
23
+ When NOT to Use This Tool
24
+ Skip using this tool when:
25
+
26
+ There is only a single, straightforward task
27
+ The task is trivial and tracking it provides no organizational benefit
28
+ The task can be completed in less than 3 trivial steps
29
+ The task is purely conversational or informational
30
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
31
+
32
+ Examples of When to Use the Todo List
33
+ <example>
34
+ 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!
35
+ Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
36
+ *Creates todo list with the following items:*
37
+ 1. Create dark mode toggle component in Settings page
38
+ 2. Add dark mode state management (context/store)
39
+ 3. Implement CSS-in-JS styles for dark theme
40
+ 4. Update existing components to support theme switching
41
+ 5. Run tests and build process, addressing any failures or errors that occur
42
+ *Begins working on the first task*
43
+ <reasoning>
44
+ The assistant used the todo list because:
45
+ 1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
46
+ 2. The user explicitly requested tests and build be run afterward
47
+ 3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
48
+ </reasoning>
49
+ </example>
50
+ <example>
51
+ User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
52
+ 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.
53
+ *Creates todo list with the following items:*
54
+ 1. Define target audience and key messaging
55
+ 2. Create social media content calendar and posting schedule
56
+ 3. Design email marketing sequence and automation flows
57
+ 4. Draft press release and identify media contacts
58
+ 5. Set up tracking and analytics for campaign performance
59
+ 6. Create visual assets and brand materials
60
+ 7. Coordinate launch timeline and deliverables
61
+ *Begins working on the first task*
62
+ <reasoning>
63
+ The assistant used the todo list because:
64
+ 1. Marketing campaign planning involves multiple distinct channels and activities
65
+ 2. Each component requires careful coordination and planning
66
+ 3. The systematic approach ensures all aspects of the launch are covered
67
+ 4. Progress tracking helps maintain timeline and deliverables
68
+ </reasoning>
69
+ </example>
70
+ <example>
71
+ User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
72
+ Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
73
+ *Uses search tools to locate all instances of getCwd in the codebase*
74
+ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
75
+ *Creates todo list with specific items for each file that needs updating*
76
+ <reasoning>
77
+ The assistant used the todo list because:
78
+ 1. First, the assistant searched to understand the scope of the task
79
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
80
+ 3. The todo list helps ensure every instance is tracked and updated systematically
81
+ 4. This approach prevents missing any occurrences and maintains consistency
82
+ </reasoning>
83
+ </example>
84
+ <example>
85
+ User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
86
+ Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
87
+ *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*
88
+ Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
89
+ <reasoning>
90
+ The assistant used the todo list because:
91
+ 1. The user provided multiple distinct organizational tasks
92
+ 2. Each area requires different approaches and careful planning
93
+ 3. Home organization benefits from systematic, step-by-step completion
94
+ 4. Progress tracking ensures all areas are addressed thoroughly
95
+ </reasoning>
96
+ </example>
97
+ Examples of When NOT to Use the Todo List
98
+ <example>
99
+ User: How do I print 'Hello World' in Python?
100
+ Assistant: In Python, you can print "Hello World" with this simple code:
101
+
102
+ \`\`\`python
103
+ print("Hello World")
104
+ \`\`\`
105
+
106
+ This will output the text "Hello World" to the console when executed.
107
+ <reasoning>
108
+ 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.
109
+ </reasoning>
110
+ </example>
111
+ <example>
112
+ User: What's the best way to water houseplants?
113
+ Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
114
+
115
+ Check soil moisture by inserting your finger about 1-2 inches into the soil
116
+ Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
117
+ Use room temperature water and water in the morning when possible
118
+ Avoid overwatering, which is more harmful than underwatering for most plants
119
+
120
+ Different plants have different needs, so it's important to research your specific varieties for optimal care.
121
+
122
+ <reasoning>
123
+ 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.
124
+ </reasoning>
125
+ </example>
126
+ <example>
127
+ User: Can you add a comment to the calculateTotal function to explain what it does?
128
+ Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
129
+ * Uses the Edit tool to add a comment to the calculateTotal function *
130
+ <reasoning>
131
+ 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.
132
+ </reasoning>
133
+ </example>
134
+ <example>
135
+ User: What time is it in Tokyo right now?
136
+ Assistant: I'll check the current time in Tokyo for you.
137
+
138
+ *Searches for current time in Tokyo*
139
+
140
+ The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
141
+
142
+ <reasoning>
143
+ 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.
144
+ </reasoning>
145
+ </example>
146
+ Task States and Management
147
+ Task States: Use these states to track progress:
148
+
149
+ pending: Task not yet started
150
+ in_progress: Currently working on (limit to ONE task at a time)
151
+ completed: Task finished successfully
152
+ Task Management:
153
+
154
+ Update task status in real-time as you work
155
+ Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
156
+ Only have ONE task in_progress at any time
157
+ Complete current tasks before starting new ones
158
+ Remove tasks that are no longer relevant from the list entirely
159
+ Task Completion Requirements:
160
+
161
+ ONLY mark a task as completed when you have FULLY accomplished it
162
+ If you encounter errors, blockers, or cannot finish, keep the task as in_progress
163
+ When blocked, create a new task describing what needs to be resolved
164
+ Never mark a task as completed if:
165
+ There are unresolved issues or errors
166
+ Work is partial or incomplete
167
+ You encountered blockers that prevent completion
168
+ You couldn't find necessary resources or dependencies
169
+ Quality standards haven't been met
170
+ Task Breakdown:
171
+
172
+ Create specific, actionable items
173
+ Break complex tasks into smaller, manageable steps
174
+ Use clear, descriptive task names
175
+ When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`;
176
+ /**
177
+ * Prefix for task tool description
178
+ * Ported exactly from Python TASK_DESCRIPTION_PREFIX
179
+ */
180
+ export const TASK_DESCRIPTION_PREFIX = `Launch a new agent to handle complex, multi-step tasks autonomously.
181
+
182
+ Available agent types and the tools they have access to:
183
+
184
+ general-purpose: General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. (Tools: *)
185
+ {other_agents}
186
+ `;
187
+ /**
188
+ * Suffix for task tool description
189
+ * Ported exactly from Python TASK_DESCRIPTION_SUFFIX
190
+ */
191
+ export const TASK_DESCRIPTION_SUFFIX = `When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
192
+
193
+ When to use the Agent tool:
194
+
195
+ When you are instructed to execute custom slash commands. Use the Agent tool with the slash command invocation as the entire prompt. The slash command can take arguments. For example: Task(description="Check the file", prompt="/check-file path/to/file.py")
196
+ When NOT to use the Agent tool:
197
+
198
+ If you want to read a specific file path, use the Read or Glob tool instead of the Agent tool, to find the match more quickly
199
+ If you are searching for a specific term or definition within a known location, use the Glob tool instead, to find the match more quickly
200
+ If you are searching for content within a specific file or set of 2-3 files, use the Read tool instead of the Agent tool, to find the match more quickly
201
+ Other tasks that are not related to the agent descriptions above
202
+ Usage notes:
203
+
204
+ Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
205
+ When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
206
+ Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
207
+ The agent's outputs should generally be trusted
208
+ Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
209
+ If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
210
+ Example usage:
211
+
212
+ <example_agent_descriptions>
213
+ "content-reviewer": use this agent after you are done creating significant content or documents
214
+ "greeting-responder": use this agent when to respond to user greetings with a friendly joke
215
+ "research-analyst": use this agent to conduct thorough research on complex topics
216
+ </example_agent_description>
217
+
218
+ <example>
219
+ user: "Please write a function that checks if a number is prime"
220
+ assistant: Sure let me write a function that checks if a number is prime
221
+ assistant: First let me use the Write tool to write a function that checks if a number is prime
222
+ assistant: I'm going to use the Write tool to write the following code:
223
+ <code>
224
+ function isPrime(n) {
225
+ if (n <= 1) return false
226
+ for (let i = 2; i * i <= n; i++) {
227
+ if (n % i === 0) return false
228
+ }
229
+ return true
230
+ }
231
+ </code>
232
+ <commentary>
233
+ Since significant content was created and the task was completed, now use the content-reviewer agent to review the work
234
+ </commentary>
235
+ assistant: Now let me use the content-reviewer agent to review the code
236
+ assistant: Uses the Task tool to launch with the content-reviewer agent
237
+ </example>
238
+ <example>
239
+ user: "Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?"
240
+ <commentary>
241
+ This is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis
242
+ </commentary>
243
+ assistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic.
244
+ assistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take
245
+ </example>
246
+ <example>
247
+ user: "Hello"
248
+ <commentary>
249
+ Since the user is greeting, use the greeting-responder agent to respond with a friendly joke
250
+ </commentary>
251
+ assistant: "I'm going to use the Task tool to launch with the greeting-responder agent"
252
+ </example>`;
253
+ /**
254
+ * Description for the edit_file tool
255
+ * Ported exactly from Python EDIT_DESCRIPTION
256
+ */
257
+ export const EDIT_DESCRIPTION = `Performs exact string replacements in files.
258
+ Usage:
259
+
260
+ You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
261
+ When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
262
+ ALWAYS prefer editing existing files. NEVER write new files unless explicitly required.
263
+ Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
264
+ The edit will FAIL if old_string is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use replace_all to change every instance of old_string.
265
+ Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;
266
+ /**
267
+ * Description for the read_file tool
268
+ * Ported exactly from Python TOOL_DESCRIPTION
269
+ */
270
+ export const TOOL_DESCRIPTION = `Reads a file from the local filesystem. You can access any file directly by using this tool. Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
271
+ Usage:
272
+
273
+ The file_path parameter must be an absolute path, not a relative path
274
+ By default, it reads up to 2000 lines starting from the beginning of the file
275
+ You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
276
+ Any lines longer than 2000 characters will be truncated
277
+ Results are returned using cat -n format, with line numbers starting at 1
278
+ You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
279
+ If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * State definitions for Deep Agents
3
+ *
4
+ * TypeScript equivalents of the Python state classes using LangGraph's Annotation.Root() pattern.
5
+ * Defines Todo interface and DeepAgentState using MessagesAnnotation as base with proper reducer functions.
6
+ */
7
+ import "@langchain/langgraph/zod";
8
+ import type { Todo } from "./types.js";
9
+ import { z } from "zod";
10
+ /**
11
+ * File reducer function that merges file dictionaries
12
+ * Matches the Python file_reducer function behavior exactly
13
+ */
14
+ export declare function fileReducer(left: Record<string, string> | null | undefined, right: Record<string, string> | null | undefined): Record<string, string>;
15
+ /**
16
+ * Todo reducer function that replaces the entire todo list
17
+ * This matches the Python behavior where todos are completely replaced
18
+ */
19
+ export declare function todoReducer(left: Todo[] | null | undefined, right: Todo[] | null | undefined): Todo[];
20
+ /**
21
+ * DeepAgentState using LangGraph's Annotation.Root() pattern
22
+ * Extends MessagesAnnotation (equivalent to Python's AgentState) with todos and files channels
23
+ */
24
+ export declare const DeepAgentState: z.ZodObject<{
25
+ messages: import("@langchain/langgraph/zod").ReducedZodChannel<z.ZodType<import("@langchain/core/messages").BaseMessage[], z.ZodTypeDef, import("@langchain/core/messages").BaseMessage[]>, import("@langchain/core/utils/types").InteropZodType<import("@langchain/langgraph").Messages>>;
26
+ } & {
27
+ todos: import("@langchain/langgraph/zod").ReducedZodChannel<z.ZodType<Todo[], z.ZodTypeDef, Todo[]>, import("@langchain/core/utils/types").InteropZodType<Todo[] | null | undefined>>;
28
+ files: import("@langchain/langgraph/zod").ReducedZodChannel<z.ZodType<Record<string, string>, z.ZodTypeDef, Record<string, string>>, import("@langchain/core/utils/types").InteropZodType<Record<string, string> | null | undefined>>;
29
+ }, "strip", z.ZodTypeAny, {
30
+ todos: Todo[];
31
+ files: Record<string, string>;
32
+ messages: import("@langchain/core/messages").BaseMessage[];
33
+ }, {
34
+ todos: Todo[];
35
+ files: Record<string, string>;
36
+ messages: import("@langchain/core/messages").BaseMessage[];
37
+ }>;
package/dist/state.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * State definitions for Deep Agents
3
+ *
4
+ * TypeScript equivalents of the Python state classes using LangGraph's Annotation.Root() pattern.
5
+ * Defines Todo interface and DeepAgentState using MessagesAnnotation as base with proper reducer functions.
6
+ */
7
+ import "@langchain/langgraph/zod";
8
+ import { MessagesZodState } from "@langchain/langgraph";
9
+ import { withLangGraph } from "@langchain/langgraph/zod";
10
+ import { z } from "zod";
11
+ /**
12
+ * File reducer function that merges file dictionaries
13
+ * Matches the Python file_reducer function behavior exactly
14
+ */
15
+ export function fileReducer(left, right) {
16
+ if (left == null) {
17
+ return right || {};
18
+ }
19
+ else if (right == null) {
20
+ return left;
21
+ }
22
+ else {
23
+ return { ...left, ...right };
24
+ }
25
+ }
26
+ /**
27
+ * Todo reducer function that replaces the entire todo list
28
+ * This matches the Python behavior where todos are completely replaced
29
+ */
30
+ export function todoReducer(left, right) {
31
+ if (right != null) {
32
+ return right;
33
+ }
34
+ return left || [];
35
+ }
36
+ /**
37
+ * DeepAgentState using LangGraph's Annotation.Root() pattern
38
+ * Extends MessagesAnnotation (equivalent to Python's AgentState) with todos and files channels
39
+ */
40
+ export const DeepAgentState = MessagesZodState.extend({
41
+ todos: withLangGraph(z.custom(), {
42
+ reducer: {
43
+ schema: z.custom(),
44
+ fn: todoReducer,
45
+ },
46
+ }),
47
+ files: withLangGraph(z.custom(), {
48
+ reducer: {
49
+ schema: z.custom(),
50
+ fn: fileReducer,
51
+ },
52
+ }),
53
+ });
@@ -0,0 +1,41 @@
1
+ /**
2
+ * SubAgent implementation for Deep Agents
3
+ *
4
+ * Task tool creation and sub-agent management.
5
+ * Creates SubAgent interface matching Python's TypedDict structure and implements
6
+ * createTaskTool() function that creates agents map, handles tool resolution by name,
7
+ * and returns a tool function that uses createReactAgent for sub-agents.
8
+ */
9
+ import { StructuredTool } from "@langchain/core/tools";
10
+ import { ToolMessage } from "@langchain/core/messages";
11
+ import { Command } from "@langchain/langgraph";
12
+ import { z } from "zod";
13
+ import type { LanguageModelLike, SubAgent } from "./types.js";
14
+ /**
15
+ * Create task tool function that creates agents map, handles tool resolution by name,
16
+ * and returns a tool function that uses createReactAgent for sub-agents.
17
+ * Uses Command for state updates and navigation between agents.
18
+ */
19
+ export declare function createTaskTool<StateSchema extends z.ZodObject<any, any, any, any, any>>(inputs: {
20
+ subagents: SubAgent[];
21
+ tools: Record<string, StructuredTool>;
22
+ model: LanguageModelLike;
23
+ stateSchema: StateSchema;
24
+ }): import("@langchain/core/tools").DynamicStructuredTool<z.ZodObject<{
25
+ agent_name: z.ZodString;
26
+ task: z.ZodString;
27
+ }, "strip", z.ZodTypeAny, {
28
+ agent_name: string;
29
+ task: string;
30
+ }, {
31
+ agent_name: string;
32
+ task: string;
33
+ }>, {
34
+ agent_name: string;
35
+ task: string;
36
+ }, {
37
+ agent_name: string;
38
+ task: string;
39
+ }, string | Command<unknown, {
40
+ messages: ToolMessage[];
41
+ }, string>>;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * SubAgent implementation for Deep Agents
3
+ *
4
+ * Task tool creation and sub-agent management.
5
+ * Creates SubAgent interface matching Python's TypedDict structure and implements
6
+ * createTaskTool() function that creates agents map, handles tool resolution by name,
7
+ * and returns a tool function that uses createReactAgent for sub-agents.
8
+ */
9
+ import { tool } from "@langchain/core/tools";
10
+ import { ToolMessage } from "@langchain/core/messages";
11
+ import { Command, getCurrentTaskInput } from "@langchain/langgraph";
12
+ import { createReactAgent } from "@langchain/langgraph/prebuilt";
13
+ import { z } from "zod";
14
+ import { getDefaultModel } from "./model.js";
15
+ import { writeTodos, readFile, writeFile, editFile, ls } from "./tools.js";
16
+ /**
17
+ * Built-in tools map for tool resolution by name
18
+ */
19
+ const BUILTIN_TOOLS = {
20
+ write_todos: writeTodos,
21
+ read_file: readFile,
22
+ write_file: writeFile,
23
+ edit_file: editFile,
24
+ ls: ls,
25
+ };
26
+ /**
27
+ * Create task tool function that creates agents map, handles tool resolution by name,
28
+ * and returns a tool function that uses createReactAgent for sub-agents.
29
+ * Uses Command for state updates and navigation between agents.
30
+ */
31
+ export function createTaskTool(inputs) {
32
+ const { subagents, tools = {}, model = getDefaultModel(), stateSchema, } = inputs;
33
+ // Create agents map from subagents array
34
+ const agentsMap = new Map();
35
+ for (const subagent of subagents) {
36
+ agentsMap.set(subagent.name, subagent);
37
+ }
38
+ // Combine built-in tools with provided tools for tool resolution
39
+ const allTools = { ...BUILTIN_TOOLS, ...tools };
40
+ return tool(async (input, config) => {
41
+ const { agent_name, task } = input;
42
+ // Get the subagent configuration
43
+ const subagent = agentsMap.get(agent_name);
44
+ if (!subagent) {
45
+ return `Error: Agent '${agent_name}' not found. Available agents: ${Array.from(agentsMap.keys()).join(", ")}`;
46
+ }
47
+ // Resolve tools by name for this subagent
48
+ const subagentTools = [];
49
+ if (subagent.tools) {
50
+ for (const toolName of subagent.tools) {
51
+ const resolvedTool = allTools[toolName];
52
+ if (resolvedTool) {
53
+ subagentTools.push(resolvedTool);
54
+ }
55
+ else {
56
+ // eslint-disable-next-line no-console
57
+ console.warn(`Warning: Tool '${toolName}' not found for agent '${agent_name}'`);
58
+ }
59
+ }
60
+ }
61
+ try {
62
+ // Create react agent for the subagent
63
+ const reactAgent = createReactAgent({
64
+ llm: model,
65
+ tools: subagentTools,
66
+ stateSchema,
67
+ messageModifier: subagent.prompt,
68
+ });
69
+ // Get current state for context
70
+ const currentState = getCurrentTaskInput();
71
+ // Execute the subagent with the task
72
+ const result = await reactAgent.invoke({
73
+ ...currentState,
74
+ messages: [
75
+ {
76
+ role: "user",
77
+ content: task,
78
+ },
79
+ ],
80
+ }, config);
81
+ // Use Command for state updates and navigation between agents
82
+ return new Command({
83
+ update: {
84
+ ...result,
85
+ messages: [
86
+ new ToolMessage({
87
+ content: `Completed task '${task}' using agent '${agent_name}'. Result: ${JSON.stringify(result.messages?.slice(-1)[0]?.content || "Task completed")}`,
88
+ tool_call_id: config.toolCall?.id,
89
+ }),
90
+ ],
91
+ },
92
+ });
93
+ }
94
+ catch (error) {
95
+ // Handle errors gracefully
96
+ const errorMessage = error instanceof Error ? error.message : String(error);
97
+ return new Command({
98
+ update: {
99
+ messages: [
100
+ new ToolMessage({
101
+ content: `Error executing task '${task}' with agent '${agent_name}': ${errorMessage}`,
102
+ tool_call_id: config.toolCall?.id,
103
+ }),
104
+ ],
105
+ },
106
+ });
107
+ }
108
+ }, {
109
+ name: "task",
110
+ description: `Execute a task using a specialized sub-agent. Available agents: ${subagents.map((a) => `${a.name} - ${a.description}`).join("; ")}`,
111
+ schema: z.object({
112
+ agent_name: z
113
+ .string()
114
+ .describe(`Name of the agent to use. Available: ${subagents.map((a) => a.name).join(", ")}`),
115
+ task: z
116
+ .string()
117
+ .describe("The task to execute with the selected agent"),
118
+ }),
119
+ });
120
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Tool functions for Deep Agents
3
+ *
4
+ * TypeScript versions of all tools using @langchain/core/tools tool() function.
5
+ * Uses getCurrentTaskInput() for state access and returns Command objects for state updates.
6
+ * Implements mock filesystem operations using state.files similar to Python version.
7
+ */
8
+ import { ToolMessage } from "@langchain/core/messages";
9
+ import { Command } from "@langchain/langgraph";
10
+ import { z } from "zod";
11
+ /**
12
+ * Write todos tool - manages todo list with Command return
13
+ * Uses getCurrentTaskInput() instead of Python's InjectedState
14
+ */
15
+ export declare const writeTodos: import("@langchain/core/tools").DynamicStructuredTool<z.ZodObject<{
16
+ todos: z.ZodArray<z.ZodObject<{
17
+ content: z.ZodString;
18
+ status: z.ZodEnum<["pending", "in_progress", "completed"]>;
19
+ }, "strip", z.ZodTypeAny, {
20
+ status: "pending" | "in_progress" | "completed";
21
+ content: string;
22
+ }, {
23
+ status: "pending" | "in_progress" | "completed";
24
+ content: string;
25
+ }>, "many">;
26
+ }, "strip", z.ZodTypeAny, {
27
+ todos: {
28
+ status: "pending" | "in_progress" | "completed";
29
+ content: string;
30
+ }[];
31
+ }, {
32
+ todos: {
33
+ status: "pending" | "in_progress" | "completed";
34
+ content: string;
35
+ }[];
36
+ }>, {
37
+ todos: {
38
+ status: "pending" | "in_progress" | "completed";
39
+ content: string;
40
+ }[];
41
+ }, {
42
+ todos: {
43
+ status: "pending" | "in_progress" | "completed";
44
+ content: string;
45
+ }[];
46
+ }, {
47
+ update: {
48
+ todos: {
49
+ status: "pending" | "in_progress" | "completed";
50
+ content: string;
51
+ }[];
52
+ messages: ToolMessage[];
53
+ };
54
+ }>;
55
+ /**
56
+ * List files tool - returns list of files from state.files
57
+ * Equivalent to Python's ls function
58
+ */
59
+ export declare const ls: import("@langchain/core/tools").DynamicStructuredTool<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>, {}, {}, string[]>;
60
+ /**
61
+ * Read file tool - reads from mock filesystem in state.files
62
+ * Matches Python read_file function behavior exactly
63
+ */
64
+ export declare const readFile: import("@langchain/core/tools").DynamicStructuredTool<z.ZodObject<{
65
+ file_path: z.ZodString;
66
+ offset: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
67
+ limit: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
68
+ }, "strip", z.ZodTypeAny, {
69
+ file_path: string;
70
+ offset: number;
71
+ limit: number;
72
+ }, {
73
+ file_path: string;
74
+ offset?: number | undefined;
75
+ limit?: number | undefined;
76
+ }>, {
77
+ file_path: string;
78
+ offset?: number;
79
+ limit?: number;
80
+ }, {
81
+ file_path: string;
82
+ offset?: number | undefined;
83
+ limit?: number | undefined;
84
+ }, string>;
85
+ /**
86
+ * Write file tool - writes to mock filesystem with Command return
87
+ * Matches Python write_file function behavior exactly
88
+ */
89
+ export declare const writeFile: import("@langchain/core/tools").DynamicStructuredTool<z.ZodObject<{
90
+ file_path: z.ZodString;
91
+ content: z.ZodString;
92
+ }, "strip", z.ZodTypeAny, {
93
+ content: string;
94
+ file_path: string;
95
+ }, {
96
+ content: string;
97
+ file_path: string;
98
+ }>, {
99
+ file_path: string;
100
+ content: string;
101
+ }, {
102
+ content: string;
103
+ file_path: string;
104
+ }, Command<unknown, {
105
+ files: {
106
+ [x: string]: string;
107
+ };
108
+ messages: ToolMessage[];
109
+ }, string>>;
110
+ /**
111
+ * Edit file tool - edits files in mock filesystem with Command return
112
+ * Matches Python edit_file function behavior exactly
113
+ */
114
+ export declare const editFile: import("@langchain/core/tools").DynamicStructuredTool<z.ZodObject<{
115
+ file_path: z.ZodString;
116
+ old_string: z.ZodString;
117
+ new_string: z.ZodString;
118
+ replace_all: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
119
+ }, "strip", z.ZodTypeAny, {
120
+ file_path: string;
121
+ old_string: string;
122
+ new_string: string;
123
+ replace_all: boolean;
124
+ }, {
125
+ file_path: string;
126
+ old_string: string;
127
+ new_string: string;
128
+ replace_all?: boolean | undefined;
129
+ }>, {
130
+ file_path: string;
131
+ old_string: string;
132
+ new_string: string;
133
+ replace_all?: boolean;
134
+ }, {
135
+ file_path: string;
136
+ old_string: string;
137
+ new_string: string;
138
+ replace_all?: boolean | undefined;
139
+ }, string | Command<unknown, {
140
+ files: {
141
+ [x: string]: string;
142
+ };
143
+ messages: ToolMessage[];
144
+ }, string>>;