@axiom-lattice/core 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.eslintrc.json +22 -0
  2. package/.turbo/turbo-build.log +21 -0
  3. package/README.md +47 -0
  4. package/dist/index.d.mts +356 -0
  5. package/dist/index.d.ts +356 -0
  6. package/dist/index.js +2191 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/index.mjs +2159 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/jest.config.js +21 -0
  11. package/package.json +63 -0
  12. package/src/__tests__/AgentManager.test.ts +202 -0
  13. package/src/__tests__/setup.ts +5 -0
  14. package/src/agent_lattice/AgentLatticeManager.ts +216 -0
  15. package/src/agent_lattice/builders/AgentBuilder.ts +79 -0
  16. package/src/agent_lattice/builders/AgentGraphBuilder.ts +22 -0
  17. package/src/agent_lattice/builders/AgentGraphBuilderFactory.ts +70 -0
  18. package/src/agent_lattice/builders/AgentParamsBuilder.ts +86 -0
  19. package/src/agent_lattice/builders/DeepAgentGraphBuilder.ts +46 -0
  20. package/src/agent_lattice/builders/PlanExecuteAgentGraphBuilder.ts +46 -0
  21. package/src/agent_lattice/builders/ReActAgentGraphBuilder.ts +42 -0
  22. package/src/agent_lattice/builders/index.ts +14 -0
  23. package/src/agent_lattice/index.ts +27 -0
  24. package/src/agent_lattice/types.ts +42 -0
  25. package/src/base/BaseLatticeManager.ts +145 -0
  26. package/src/base/index.ts +1 -0
  27. package/src/createPlanExecuteAgent.ts +475 -0
  28. package/src/deep_agent/graph.ts +106 -0
  29. package/src/deep_agent/index.ts +25 -0
  30. package/src/deep_agent/prompts.ts +284 -0
  31. package/src/deep_agent/state.ts +63 -0
  32. package/src/deep_agent/subAgent.ts +185 -0
  33. package/src/deep_agent/tools.ts +273 -0
  34. package/src/deep_agent/types.ts +71 -0
  35. package/src/index.ts +9 -0
  36. package/src/logger/Logger.ts +186 -0
  37. package/src/memory_lattice/DefaultMemorySaver.ts +4 -0
  38. package/src/memory_lattice/MemoryLatticeManager.ts +105 -0
  39. package/src/memory_lattice/index.ts +9 -0
  40. package/src/model_lattice/ModelLattice.ts +208 -0
  41. package/src/model_lattice/ModelLatticeManager.ts +125 -0
  42. package/src/model_lattice/index.ts +1 -0
  43. package/src/tool_lattice/ToolLatticeManager.ts +221 -0
  44. package/src/tool_lattice/get_current_date_time/index.ts +14 -0
  45. package/src/tool_lattice/index.ts +2 -0
  46. package/src/tool_lattice/internet_search/index.ts +66 -0
  47. package/src/types.ts +28 -0
  48. package/src/util/PGMemory.ts +16 -0
  49. package/src/util/genUICard.ts +3 -0
  50. package/src/util/genUIMarkdown.ts +3 -0
  51. package/src/util/getLastHumanMessageData.ts +41 -0
  52. package/src/util/returnAIResponse.ts +30 -0
  53. package/src/util/returnErrorResponse.ts +26 -0
  54. package/src/util/returnFeedbackResponse.ts +25 -0
  55. package/src/util/returnToolResponse.ts +32 -0
  56. package/src/util/withAgentName.ts +220 -0
  57. package/src/util/zod-to-prompt.ts +50 -0
  58. package/tsconfig.json +26 -0
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Main createDeepAgent function for Deep Agents
3
+ *
4
+ * Main entry point for creating deep agents with TypeScript types for all parameters:
5
+ * tools, instructions, model, subagents, and stateSchema. Combines built-in tools with
6
+ * provided tools, creates task tool using createTaskTool(), and returns createReactAgent
7
+ * with proper configuration. Ensures exact parameter matching and behavior with Python version.
8
+ */
9
+
10
+ // import "@langchain/anthropic/zod";
11
+ import { createTaskTool } from "./subAgent";
12
+ import { writeTodos, readFile, writeFile, editFile, ls } from "./tools";
13
+ import type { CreateDeepAgentParams } from "./types";
14
+ import type { StructuredTool } from "@langchain/core/tools";
15
+ import { z } from "zod";
16
+ import { DeepAgentState } from "./state";
17
+ import { getModelLattice } from "../model_lattice/ModelLatticeManager";
18
+ import { createReactAgent } from "@langchain/langgraph/prebuilt";
19
+ import { getCheckpointSaver } from "@memory_lattice/MemoryLatticeManager";
20
+
21
+ /**
22
+ * Base prompt that provides instructions about available tools
23
+ * Ported from Python implementation to ensure consistent behavior
24
+ */
25
+ const BASE_PROMPT = `You have access to a number of standard tools
26
+
27
+ ## \`write_todos\`
28
+
29
+ You have access to the \`write_todos\` tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
30
+ These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
31
+
32
+ It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
33
+ ## \`task\`
34
+
35
+ - When doing web search, prefer to use the \`task\` tool in order to reduce context usage.`;
36
+
37
+ /**
38
+ * Built-in tools that are always available in Deep Agents
39
+ */
40
+ const BUILTIN_TOOLS: StructuredTool[] = [
41
+ writeTodos,
42
+ readFile,
43
+ writeFile,
44
+ editFile,
45
+ ls,
46
+ ];
47
+
48
+ /**
49
+ * Create a Deep Agent with TypeScript types for all parameters.
50
+ * Combines built-in tools with provided tools, creates task tool using createTaskTool(),
51
+ * and returns createReactAgent with proper configuration.
52
+ * Ensures exact parameter matching and behavior with Python version.
53
+ */
54
+ export function createDeepAgent<
55
+ StateSchema extends z.ZodObject<any, any, any, any, any>
56
+ >(params: CreateDeepAgentParams<StateSchema> = {}) {
57
+ const {
58
+ tools = [],
59
+ instructions,
60
+ model = getModelLattice("default")?.client,
61
+ subagents = [],
62
+ } = params;
63
+
64
+ if (!model) {
65
+ throw new Error("Model not found");
66
+ }
67
+
68
+ const stateSchema = params.stateSchema
69
+ ? DeepAgentState.extend(params.stateSchema.shape)
70
+ : DeepAgentState;
71
+
72
+ // Combine built-in tools with provided tools
73
+ const allTools: StructuredTool[] = [...BUILTIN_TOOLS, ...tools];
74
+ // Create task tool using createTaskTool() if subagents are provided
75
+ if (subagents.length > 0) {
76
+ // Create tools map for task tool creation
77
+ const toolsMap: Record<string, StructuredTool> = {};
78
+ for (const tool of allTools) {
79
+ if (tool.name) {
80
+ toolsMap[tool.name] = tool;
81
+ }
82
+ }
83
+
84
+ const taskTool = createTaskTool({
85
+ subagents,
86
+ tools: toolsMap,
87
+ model,
88
+ stateSchema,
89
+ });
90
+ allTools.push(taskTool);
91
+ }
92
+
93
+ // Combine instructions with base prompt like Python implementation
94
+ const finalInstructions = instructions
95
+ ? instructions + BASE_PROMPT
96
+ : BASE_PROMPT;
97
+
98
+ // Return createReactAgent with proper configuration
99
+ return createReactAgent({
100
+ llm: model,
101
+ tools: allTools,
102
+ stateSchema: stateSchema,
103
+ prompt: finalInstructions,
104
+ checkpointer: getCheckpointSaver("default"),
105
+ });
106
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Deep Agents TypeScript Implementation
3
+ *
4
+ * A TypeScript port of the Python Deep Agents library for building controllable AI agents with LangGraph.
5
+ * This implementation maintains 1:1 compatibility with the Python version.
6
+ */
7
+
8
+ export { createDeepAgent } from "./graph";
9
+ export { writeTodos, readFile, writeFile, editFile, ls } from "./tools";
10
+ export { DeepAgentState, fileReducer } from "./state";
11
+ export {
12
+ WRITE_TODOS_DESCRIPTION,
13
+ TASK_DESCRIPTION_PREFIX,
14
+ TASK_DESCRIPTION_SUFFIX,
15
+ EDIT_DESCRIPTION,
16
+ TOOL_DESCRIPTION,
17
+ } from "./prompts";
18
+ export type {
19
+ SubAgent,
20
+ Todo,
21
+ DeepAgentStateType,
22
+ CreateDeepAgentParams,
23
+ CreateTaskToolParams,
24
+ TodoStatus,
25
+ } from "./types";
@@ -0,0 +1,284 @@
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
+ /**
9
+ * Description for the write_todos tool
10
+ * Ported exactly from Python WRITE_TODOS_DESCRIPTION
11
+ */
12
+ 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.
13
+
14
+ When to Use This Tool
15
+ Use this tool proactively in these scenarios:
16
+
17
+ Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
18
+ Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
19
+ User explicitly requests todo list - When the user directly asks you to use the todo list
20
+ User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
21
+ After receiving new instructions - Immediately capture user requirements as todos
22
+ 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
23
+ After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
24
+ When NOT to Use This Tool
25
+ Skip using this tool when:
26
+
27
+ There is only a single, straightforward task
28
+ The task is trivial and tracking it provides no organizational benefit
29
+ The task can be completed in less than 3 trivial steps
30
+ The task is purely conversational or informational
31
+ 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.
32
+
33
+ Examples of When to Use the Todo List
34
+ <example>
35
+ 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!
36
+ Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
37
+ *Creates todo list with the following items:*
38
+ 1. Create dark mode toggle component in Settings page
39
+ 2. Add dark mode state management (context/store)
40
+ 3. Implement CSS-in-JS styles for dark theme
41
+ 4. Update existing components to support theme switching
42
+ 5. Run tests and build process, addressing any failures or errors that occur
43
+ *Begins working on the first task*
44
+ <reasoning>
45
+ The assistant used the todo list because:
46
+ 1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
47
+ 2. The user explicitly requested tests and build be run afterward
48
+ 3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
49
+ </reasoning>
50
+ </example>
51
+ <example>
52
+ User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases.
53
+ 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.
54
+ *Creates todo list with the following items:*
55
+ 1. Define target audience and key messaging
56
+ 2. Create social media content calendar and posting schedule
57
+ 3. Design email marketing sequence and automation flows
58
+ 4. Draft press release and identify media contacts
59
+ 5. Set up tracking and analytics for campaign performance
60
+ 6. Create visual assets and brand materials
61
+ 7. Coordinate launch timeline and deliverables
62
+ *Begins working on the first task*
63
+ <reasoning>
64
+ The assistant used the todo list because:
65
+ 1. Marketing campaign planning involves multiple distinct channels and activities
66
+ 2. Each component requires careful coordination and planning
67
+ 3. The systematic approach ensures all aspects of the launch are covered
68
+ 4. Progress tracking helps maintain timeline and deliverables
69
+ </reasoning>
70
+ </example>
71
+ <example>
72
+ User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
73
+ Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
74
+ *Uses search tools to locate all instances of getCwd in the codebase*
75
+ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
76
+ *Creates todo list with specific items for each file that needs updating*
77
+ <reasoning>
78
+ The assistant used the todo list because:
79
+ 1. First, the assistant searched to understand the scope of the task
80
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
81
+ 3. The todo list helps ensure every instance is tracked and updated systematically
82
+ 4. This approach prevents missing any occurrences and maintains consistency
83
+ </reasoning>
84
+ </example>
85
+ <example>
86
+ User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow.
87
+ Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization.
88
+ *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*
89
+ Let's start with decluttering your desk space to create a clean foundation for the other organizational systems.
90
+ <reasoning>
91
+ The assistant used the todo list because:
92
+ 1. The user provided multiple distinct organizational tasks
93
+ 2. Each area requires different approaches and careful planning
94
+ 3. Home organization benefits from systematic, step-by-step completion
95
+ 4. Progress tracking ensures all areas are addressed thoroughly
96
+ </reasoning>
97
+ </example>
98
+ Examples of When NOT to Use the Todo List
99
+ <example>
100
+ User: How do I print 'Hello World' in Python?
101
+ Assistant: In Python, you can print "Hello World" with this simple code:
102
+
103
+ \`\`\`python
104
+ print("Hello World")
105
+ \`\`\`
106
+
107
+ This will output the text "Hello World" to the console when executed.
108
+ <reasoning>
109
+ 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.
110
+ </reasoning>
111
+ </example>
112
+ <example>
113
+ User: What's the best way to water houseplants?
114
+ Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines:
115
+
116
+ Check soil moisture by inserting your finger about 1-2 inches into the soil
117
+ Water thoroughly when the top inch feels dry, allowing water to drain from the bottom
118
+ Use room temperature water and water in the morning when possible
119
+ Avoid overwatering, which is more harmful than underwatering for most plants
120
+
121
+ Different plants have different needs, so it's important to research your specific varieties for optimal care.
122
+
123
+ <reasoning>
124
+ 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.
125
+ </reasoning>
126
+ </example>
127
+ <example>
128
+ User: Can you add a comment to the calculateTotal function to explain what it does?
129
+ Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
130
+ * Uses the Edit tool to add a comment to the calculateTotal function *
131
+ <reasoning>
132
+ 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.
133
+ </reasoning>
134
+ </example>
135
+ <example>
136
+ User: What time is it in Tokyo right now?
137
+ Assistant: I'll check the current time in Tokyo for you.
138
+
139
+ *Searches for current time in Tokyo*
140
+
141
+ The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9.
142
+
143
+ <reasoning>
144
+ 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.
145
+ </reasoning>
146
+ </example>
147
+ Task States and Management
148
+ Task States: Use these states to track progress:
149
+
150
+ pending: Task not yet started
151
+ in_progress: Currently working on (limit to ONE task at a time)
152
+ completed: Task finished successfully
153
+ Task Management:
154
+
155
+ Update task status in real-time as you work
156
+ Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
157
+ Only have ONE task in_progress at any time
158
+ Complete current tasks before starting new ones
159
+ Remove tasks that are no longer relevant from the list entirely
160
+ Task Completion Requirements:
161
+
162
+ ONLY mark a task as completed when you have FULLY accomplished it
163
+ If you encounter errors, blockers, or cannot finish, keep the task as in_progress
164
+ When blocked, create a new task describing what needs to be resolved
165
+ Never mark a task as completed if:
166
+ There are unresolved issues or errors
167
+ Work is partial or incomplete
168
+ You encountered blockers that prevent completion
169
+ You couldn't find necessary resources or dependencies
170
+ Quality standards haven't been met
171
+ Task Breakdown:
172
+
173
+ Create specific, actionable items
174
+ Break complex tasks into smaller, manageable steps
175
+ Use clear, descriptive task names
176
+ When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`;
177
+
178
+ /**
179
+ * Prefix for task tool description
180
+ * Ported exactly from Python TASK_DESCRIPTION_PREFIX
181
+ */
182
+ export const TASK_DESCRIPTION_PREFIX = `Launch a new agent to handle complex, multi-step tasks autonomously.
183
+
184
+ Available agent types and the tools they have access to:
185
+
186
+ 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: *)
187
+ {other_agents}
188
+ `;
189
+
190
+ /**
191
+ * Suffix for task tool description
192
+ * Ported exactly from Python TASK_DESCRIPTION_SUFFIX
193
+ */
194
+ export const TASK_DESCRIPTION_SUFFIX = `When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
195
+
196
+ When to use the Agent tool:
197
+
198
+ 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")
199
+ When NOT to use the Agent tool:
200
+
201
+ 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
202
+ 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
203
+ 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
204
+ Other tasks that are not related to the agent descriptions above
205
+ Usage notes:
206
+
207
+ Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
208
+ 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.
209
+ 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.
210
+ The agent's outputs should generally be trusted
211
+ 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
212
+ 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.
213
+ Example usage:
214
+
215
+ <example_agent_descriptions>
216
+ "content-reviewer": use this agent after you are done creating significant content or documents
217
+ "greeting-responder": use this agent when to respond to user greetings with a friendly joke
218
+ "research-analyst": use this agent to conduct thorough research on complex topics
219
+ </example_agent_description>
220
+
221
+ <example>
222
+ user: "Please write a function that checks if a number is prime"
223
+ assistant: Sure let me write a function that checks if a number is prime
224
+ assistant: First let me use the Write tool to write a function that checks if a number is prime
225
+ assistant: I'm going to use the Write tool to write the following code:
226
+ <code>
227
+ function isPrime(n) {
228
+ if (n <= 1) return false
229
+ for (let i = 2; i * i <= n; i++) {
230
+ if (n % i === 0) return false
231
+ }
232
+ return true
233
+ }
234
+ </code>
235
+ <commentary>
236
+ Since significant content was created and the task was completed, now use the content-reviewer agent to review the work
237
+ </commentary>
238
+ assistant: Now let me use the content-reviewer agent to review the code
239
+ assistant: Uses the Task tool to launch with the content-reviewer agent
240
+ </example>
241
+ <example>
242
+ user: "Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?"
243
+ <commentary>
244
+ This is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis
245
+ </commentary>
246
+ 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.
247
+ 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
248
+ </example>
249
+ <example>
250
+ user: "Hello"
251
+ <commentary>
252
+ Since the user is greeting, use the greeting-responder agent to respond with a friendly joke
253
+ </commentary>
254
+ assistant: "I'm going to use the Task tool to launch with the greeting-responder agent"
255
+ </example>`;
256
+
257
+ /**
258
+ * Description for the edit_file tool
259
+ * Ported exactly from Python EDIT_DESCRIPTION
260
+ */
261
+ export const EDIT_DESCRIPTION = `Performs exact string replacements in files.
262
+ Usage:
263
+
264
+ 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.
265
+ 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.
266
+ ALWAYS prefer editing existing files. NEVER write new files unless explicitly required.
267
+ Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
268
+ 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.
269
+ Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;
270
+
271
+ /**
272
+ * Description for the read_file tool
273
+ * Ported exactly from Python TOOL_DESCRIPTION
274
+ */
275
+ 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.
276
+ Usage:
277
+
278
+ The file_path parameter must be an absolute path, not a relative path
279
+ By default, it reads up to 2000 lines starting from the beginning of the file
280
+ 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
281
+ Any lines longer than 2000 characters will be truncated
282
+ Results are returned using cat -n format, with line numbers starting at 1
283
+ 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.
284
+ 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,63 @@
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
+
8
+ import "@langchain/langgraph/zod";
9
+ import { MessagesZodState } from "@langchain/langgraph";
10
+ import type { Todo } from "./types";
11
+ import { withLangGraph } from "@langchain/langgraph/zod";
12
+ import { z } from "zod";
13
+
14
+ /**
15
+ * File reducer function that merges file dictionaries
16
+ * Matches the Python file_reducer function behavior exactly
17
+ */
18
+ export function fileReducer(
19
+ left: Record<string, string> | null | undefined,
20
+ right: Record<string, string> | null | undefined
21
+ ): Record<string, string> {
22
+ if (left == null) {
23
+ return right || {};
24
+ } else if (right == null) {
25
+ return left;
26
+ } else {
27
+ return { ...left, ...right };
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Todo reducer function that replaces the entire todo list
33
+ * This matches the Python behavior where todos are completely replaced
34
+ */
35
+ export function todoReducer(
36
+ left: Todo[] | null | undefined,
37
+ right: Todo[] | null | undefined
38
+ ): Todo[] {
39
+ if (right != null) {
40
+ return right;
41
+ }
42
+ return left || [];
43
+ }
44
+
45
+ /**
46
+ * DeepAgentState using LangGraph's Annotation.Root() pattern
47
+ * Extends MessagesAnnotation (equivalent to Python's AgentState) with todos and files channels
48
+ */
49
+ export const DeepAgentState = MessagesZodState.extend({
50
+ todos: withLangGraph(z.custom<Todo[]>(), {
51
+ reducer: {
52
+ schema: z.custom<Todo[]>(),
53
+ fn: todoReducer,
54
+ },
55
+ }),
56
+
57
+ files: withLangGraph(z.custom<Record<string, string>>(), {
58
+ reducer: {
59
+ schema: z.custom<Record<string, string>>(),
60
+ fn: fileReducer,
61
+ },
62
+ }),
63
+ });
@@ -0,0 +1,185 @@
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
+
10
+ import { tool, StructuredTool } from "@langchain/core/tools";
11
+ import { ToolMessage } from "@langchain/core/messages";
12
+ import {
13
+ Command,
14
+ getCurrentTaskInput,
15
+ GraphInterrupt,
16
+ } from "@langchain/langgraph";
17
+ import { ToolRunnableConfig } from "@langchain/core/tools";
18
+ import { createReactAgent } from "@langchain/langgraph/prebuilt";
19
+ import { z } from "zod";
20
+ import type { LanguageModelLike, SubAgent } from "./types";
21
+ import { writeTodos, readFile, writeFile, editFile, ls } from "./tools";
22
+ import { TASK_DESCRIPTION_PREFIX, TASK_DESCRIPTION_SUFFIX } from "./prompts";
23
+ import { ModelLattice } from "../model_lattice/ModelLattice";
24
+ import { getModelLattice } from "../model_lattice/ModelLatticeManager";
25
+
26
+ /**
27
+ * Built-in tools map for tool resolution by name
28
+ */
29
+ const BUILTIN_TOOLS: Record<string, StructuredTool> = {
30
+ write_todos: writeTodos,
31
+ read_file: readFile,
32
+ write_file: writeFile,
33
+ edit_file: editFile,
34
+ ls: ls,
35
+ };
36
+
37
+ /**
38
+ * Create task tool function that creates agents map, handles tool resolution by name,
39
+ * and returns a tool function that uses createReactAgent for sub-agents.
40
+ * Uses Command for state updates and navigation between agents.
41
+ */
42
+ export function createTaskTool<
43
+ StateSchema extends z.ZodObject<any, any, any, any, any>
44
+ >(inputs: {
45
+ subagents: SubAgent[];
46
+ tools: Record<string, StructuredTool>;
47
+ model: ModelLattice;
48
+ stateSchema: StateSchema;
49
+ }) {
50
+ const {
51
+ subagents,
52
+ tools = {},
53
+ model = getModelLattice("default")?.client,
54
+ stateSchema,
55
+ } = inputs;
56
+
57
+ if (!model) {
58
+ throw new Error("Model not found");
59
+ }
60
+
61
+ // Combine built-in tools with provided tools for tool resolution
62
+ const allTools = { ...BUILTIN_TOOLS, ...tools };
63
+
64
+ // Pre-create all agents like Python does
65
+ const agentsMap = new Map<string, any>();
66
+ for (const subagent of subagents) {
67
+ // Resolve tools by name for this subagent
68
+ const subagentTools: StructuredTool[] = [];
69
+ if (subagent.tools) {
70
+ for (const toolName of subagent.tools) {
71
+ const resolvedTool = allTools[toolName];
72
+ if (resolvedTool) {
73
+ subagentTools.push(resolvedTool);
74
+ } else {
75
+ // eslint-disable-next-line no-console
76
+ console.warn(
77
+ `Warning: Tool '${toolName}' not found for agent '${subagent.name}'`
78
+ );
79
+ }
80
+ }
81
+ } else {
82
+ // If no tools specified, use all tools like Python does
83
+ subagentTools.push(...Object.values(allTools));
84
+ }
85
+
86
+ // Create react agent for the subagent (pre-create like Python)
87
+ const reactAgent = createReactAgent({
88
+ llm: model,
89
+ tools: subagentTools,
90
+ stateSchema: stateSchema as any,
91
+ messageModifier: subagent.prompt,
92
+ checkpointer: false,
93
+ });
94
+
95
+ agentsMap.set(subagent.name, reactAgent);
96
+ }
97
+
98
+ return tool(
99
+ async (
100
+ input: { description: string; subagent_type: string },
101
+ config: ToolRunnableConfig
102
+ ) => {
103
+ const { description, subagent_type } = input;
104
+
105
+ // Get the pre-created agent
106
+ const reactAgent = agentsMap.get(subagent_type);
107
+ if (!reactAgent) {
108
+ return `Error: Agent '${subagent_type}' not found. Available agents: ${Array.from(
109
+ agentsMap.keys()
110
+ ).join(", ")}`;
111
+ }
112
+
113
+ try {
114
+ // Get current state for context
115
+ const currentState = getCurrentTaskInput<z.infer<typeof stateSchema>>();
116
+
117
+ // Modify state messages like Python does
118
+ const modifiedState = {
119
+ ...currentState,
120
+ messages: [
121
+ {
122
+ role: "user",
123
+ content: description,
124
+ },
125
+ ],
126
+ };
127
+
128
+ // Execute the subagent with the task
129
+ const result = await reactAgent.invoke(modifiedState, config);
130
+
131
+ // Use Command for state updates and navigation between agents
132
+ // Return the result using Command to properly handle subgraph state
133
+ return new Command({
134
+ update: {
135
+ files: result.files || {},
136
+ messages: [
137
+ new ToolMessage({
138
+ content:
139
+ result.messages?.slice(-1)[0]?.content || "Task completed",
140
+ tool_call_id: config.toolCall?.id as string,
141
+ }),
142
+ ],
143
+ },
144
+ });
145
+ } catch (error) {
146
+ if (error instanceof GraphInterrupt) {
147
+ throw error;
148
+ }
149
+ // Handle errors gracefully
150
+ const errorMessage =
151
+ error instanceof Error ? error.message : String(error);
152
+ return new Command({
153
+ update: {
154
+ messages: [
155
+ new ToolMessage({
156
+ content: `Error executing task '${description}' with agent '${subagent_type}': ${errorMessage}`,
157
+ tool_call_id: config.toolCall?.id as string,
158
+ }),
159
+ ],
160
+ },
161
+ });
162
+ }
163
+ },
164
+ {
165
+ name: "task",
166
+ description:
167
+ TASK_DESCRIPTION_PREFIX.replace(
168
+ "{other_agents}",
169
+ subagents.map((a) => `- ${a.name}: ${a.description}`).join("\n")
170
+ ) + TASK_DESCRIPTION_SUFFIX,
171
+ schema: z.object({
172
+ description: z
173
+ .string()
174
+ .describe("The task to execute with the selected agent"),
175
+ subagent_type: z
176
+ .string()
177
+ .describe(
178
+ `Name of the agent to use. Available: ${subagents
179
+ .map((a) => a.name)
180
+ .join(", ")}`
181
+ ),
182
+ }),
183
+ }
184
+ );
185
+ }