@amical/aiagent-sdk 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +476 -0
- package/dist/index.d.ts +476 -0
- package/dist/index.js +968 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +951 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +7 -1
- package/.agents/skills/Viral_Writer/SKILL.md +0 -239
- package/.cline_memory.json +0 -58
- package/.node-version +0 -1
- package/Agents.md +0 -95
- package/src/agent/Agent.ts +0 -566
- package/src/agent/index.ts +0 -1
- package/src/index.ts +0 -15
- package/src/llm/NodeApiHandler.ts +0 -117
- package/src/llm/WebApiHandler.ts +0 -118
- package/src/llm/index.ts +0 -47
- package/src/mcp/NodeMcpManager.ts +0 -158
- package/src/mcp/WebMcpManager.ts +0 -30
- package/src/mcp/index.ts +0 -56
- package/src/memory/NodeMemoryManager.ts +0 -82
- package/src/memory/WebMemoryManager.ts +0 -89
- package/src/memory/index.ts +0 -36
- package/src/parser/diff.ts +0 -855
- package/src/parser/index.ts +0 -111
- package/src/parser/parse-assistant-message.ts +0 -240
- package/src/prompt/NodePromptManager.ts +0 -276
- package/src/prompt/WebPromptManager.ts +0 -277
- package/src/prompt/index.ts +0 -28
- package/src/runtime/nodeRuntime.ts +0 -112
- package/src/runtime/web.test.ts +0 -95
- package/src/runtime/webRuntime.ts +0 -119
- package/src/runtime.ts +0 -46
- package/src/shared/tools.ts +0 -270
- package/test-node-agent.ts +0 -113
- package/test-runtime.mjs +0 -36
- package/test.md +0 -33
- package/tsconfig.json +0 -28
- package/tsup.config.ts +0 -21
- package/uapi.ts +0 -3
- package/webFetch.ts +0 -49
- package/webSearch.ts +0 -19
|
@@ -1,277 +0,0 @@
|
|
|
1
|
-
import { IPromptManager } from "./index";
|
|
2
|
-
import { defaultTools } from "@/shared/tools";
|
|
3
|
-
|
|
4
|
-
export class WebPromptManager implements IPromptManager {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
async getSystemPrompt(context: { cwd: string; os: string; shell: string; skills: any; customInstructions?: string; allowDefaultTools?: string[]; customTools?: any[]; }): Promise<string> {
|
|
8
|
-
let prompt = `# Role
|
|
9
|
-
you are a highly skilled software engineer AI running in a Node.js/Desktop environment.
|
|
10
|
-
You have FULL access to the local file system and can execute arbitrary shell commands on the user's machine.
|
|
11
|
-
|
|
12
|
-
# Capabilities & Rules
|
|
13
|
-
1. **File System**: You can read, write, create, and delete files/directories anywhere accessible to the user process. Always use absolute paths or paths relative to the Current Working Directory.
|
|
14
|
-
2. **Terminal**: You can execute system commands (e.g., git, npm, python, file manipulation) directly.
|
|
15
|
-
3. **Context**: You are running on a real machine, meaning you have access to real environment variables, local servers (localhost), and local network.
|
|
16
|
-
4. **Destructive Actions**: Be extremely careful when executing commands that modify system state or delete files. Double-check paths and commands before execution.
|
|
17
|
-
5. **Step-by-step**: Use tools one at a time. Do not assume the outcome of any tool use. Each step must be informed by the previous step's result.
|
|
18
|
-
6. **Verification**: Always verify the result of your actions (e.g., run tests, compile code, list directories) before proceeding to the next step or completing the task.
|
|
19
|
-
7. **Communication**: Be concise and technical. Formulate your output strictly according to the tools' XML specification.
|
|
20
|
-
|
|
21
|
-
TOOL USE
|
|
22
|
-
|
|
23
|
-
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
|
|
24
|
-
|
|
25
|
-
# Tool Use Formatting
|
|
26
|
-
|
|
27
|
-
Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
|
|
28
|
-
|
|
29
|
-
<tool_name>
|
|
30
|
-
<parameter1_name>value1</parameter1_name>
|
|
31
|
-
<parameter2_name>value2</parameter2_name>
|
|
32
|
-
...
|
|
33
|
-
</tool_name>
|
|
34
|
-
|
|
35
|
-
For example:
|
|
36
|
-
|
|
37
|
-
<agent_read_file>
|
|
38
|
-
<path>src/main.js</path>
|
|
39
|
-
<task_progress>
|
|
40
|
-
Checklist here (optional)
|
|
41
|
-
</task_progress>
|
|
42
|
-
</agent_read_file>
|
|
43
|
-
|
|
44
|
-
Always adhere to this format for the tool use to ensure proper parsing and execution.
|
|
45
|
-
`;
|
|
46
|
-
|
|
47
|
-
const skillsPrompt = await this.getSkillsPrompt(context.skills);
|
|
48
|
-
if (skillsPrompt) {
|
|
49
|
-
prompt += `\n${skillsPrompt}\n`;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
prompt += `\n${this.getToolInstructions(context)}\n`;
|
|
53
|
-
|
|
54
|
-
const envPrompt = this.getEnvironmentInfoPrompt(context);
|
|
55
|
-
if (envPrompt) {
|
|
56
|
-
prompt += `\n${envPrompt}\n`;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (context.customInstructions) {
|
|
60
|
-
prompt += `\n# User Custom Instructions\n${context.customInstructions}\n`;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return prompt;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
getEnvironmentInfoPrompt(context: { cwd: string; os: string; shell: string }): string {
|
|
67
|
-
let environmentPrompt = `<environment_details>
|
|
68
|
-
# Environment Info
|
|
69
|
-
- **Current Working Directory**: \`${context.cwd}\`
|
|
70
|
-
- **Operating System**: \`${context.os}\`\n`;
|
|
71
|
-
if (context.shell) {
|
|
72
|
-
environmentPrompt += `- **Current Shell**: \`${context.shell}\`\n`;
|
|
73
|
-
}
|
|
74
|
-
return environmentPrompt + `\n</environment_details>`;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
async getSkillsPrompt(skills: any[]): Promise<string> {
|
|
78
|
-
if (!skills || skills.length === 0) return "";
|
|
79
|
-
|
|
80
|
-
try {
|
|
81
|
-
let prompt = `# Available Skills\n`;
|
|
82
|
-
prompt += `You have access to the following skills. You can use the \`agent_load_skill\` tool to load any of them when needed.\n`;
|
|
83
|
-
for (const skill of skills) {
|
|
84
|
-
if (skill && skill.name && skill.description) {
|
|
85
|
-
prompt += `- **${skill.name}**: ${skill.description}\n`;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return prompt;
|
|
89
|
-
} catch (e) {
|
|
90
|
-
// Directory might not exist or not accessible
|
|
91
|
-
return "";
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
getToolInstructions(context: { cwd: string; os: string; allowDefaultTools?: string[]; customTools?: any[] }): string {
|
|
96
|
-
const allowDefaultTools = context.allowDefaultTools;
|
|
97
|
-
const customTools = context.customTools || [];
|
|
98
|
-
// 可用
|
|
99
|
-
let useDefaultTools = [...defaultTools] as any[];
|
|
100
|
-
if (allowDefaultTools) {
|
|
101
|
-
useDefaultTools = defaultTools.filter((tool: any) => allowDefaultTools.includes(tool.name));
|
|
102
|
-
}
|
|
103
|
-
return `# Available Tools
|
|
104
|
-
You can use the following tools by formatting your output as XML blocks. Only use ONE tool per message, and ALWAYS wait for the user's response with the execution result before proceeding.
|
|
105
|
-
|
|
106
|
-
${[...useDefaultTools, ...customTools].map((tool: any) => {
|
|
107
|
-
return `### ${tool.name}
|
|
108
|
-
Description: ${tool.description}
|
|
109
|
-
Parameters:
|
|
110
|
-
${Object.entries(tool.params as Record<string, string>).map(([name, description]) => `- ${name}: ${description.replaceAll('${context.cwd}', context.cwd)}`).join('\n')}
|
|
111
|
-
- task_progress: (optional) A checklist showing task progress after this tool use is completed. The task_progress parameter must be included as a separate parameter inside of the parent tool call, it must be separate from other parameters such as content, arguments, etc. (See 'UPDATING TASK PROGRESS' section for more details)
|
|
112
|
-
Usage:
|
|
113
|
-
<${tool.name}>
|
|
114
|
-
${Object.entries(tool.params as Record<string, string>).map(([name, description]) => `<${name}>${description.replaceAll('${context.cwd}', context.cwd)}</${name}>`).join('\n')}
|
|
115
|
-
<task_progress>Checklist here (optional)</task_progress>
|
|
116
|
-
</${tool.name}>
|
|
117
|
-
`;
|
|
118
|
-
}).join('\n')}
|
|
119
|
-
|
|
120
|
-
# Tool Use Examples
|
|
121
|
-
${useDefaultTools.filter(item => Boolean(item.example)).map((item: any) => item.example).join('\n')}}
|
|
122
|
-
|
|
123
|
-
# Tool Use Guidelines
|
|
124
|
-
|
|
125
|
-
1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
|
|
126
|
-
2. Choose the most appropriate tool based on the task and the tool descriptions provided. Assess if you need additional information to proceed, and which of the available tools would be most effective for gathering this information. For example using the list_files tool is more effective than running a command like \`ls\` in the terminal. It's critical that you think about each available tool and use the one that best fits the current step in the task.
|
|
127
|
-
3. If multiple actions are needed, use one tool at a time per message to accomplish the task iteratively, with each tool use being informed by the result of the previous tool use. Do not assume the outcome of any tool use. Each step must be informed by the previous step's result.
|
|
128
|
-
4. Formulate your tool use using the XML format specified for each tool.
|
|
129
|
-
5. After each tool use, the user will respond with the result of that tool use. This result will provide you with the necessary information to continue your task or make further decisions. This response may include:
|
|
130
|
-
- Information about whether the tool succeeded or failed, along with any reasons for failure.
|
|
131
|
-
- Linter errors that may have arisen due to the changes you made, which you'll need to address.
|
|
132
|
-
- New terminal output in reaction to the changes, which you may need to consider or act upon.
|
|
133
|
-
- Any other relevant feedback or information related to the tool use.
|
|
134
|
-
6. ALWAYS wait for user confirmation after each tool use before proceeding. Never assume the success of a tool use without explicit confirmation of the result from the user.
|
|
135
|
-
|
|
136
|
-
It is crucial to proceed step-by-step, waiting for the user's message after each tool use before moving forward with the task. This approach allows you to:
|
|
137
|
-
1. Confirm the success of each step before proceeding.
|
|
138
|
-
2. Address any issues or errors that arise immediately.
|
|
139
|
-
3. Adapt your approach based on new information or unexpected results.
|
|
140
|
-
4. Ensure that each action builds correctly on the previous ones.
|
|
141
|
-
|
|
142
|
-
By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.
|
|
143
|
-
|
|
144
|
-
====
|
|
145
|
-
|
|
146
|
-
UPDATING TASK PROGRESS
|
|
147
|
-
|
|
148
|
-
You can track and communicate your progress on the overall task using the task_progress parameter supported by every tool call. Using task_progress ensures you remain on task, and stay focused on completing the user's objective. This parameter can be used in any mode, and with any tool call.
|
|
149
|
-
|
|
150
|
-
- When switching from PLAN MODE to ACT MODE, you must create a comprehensive todo list for the task using the task_progress parameter
|
|
151
|
-
- Todo list updates should be done silently using the task_progress parameter - do not announce these updates to the user
|
|
152
|
-
- Use standard Markdown checklist format: "- [ ]" for incomplete items and "- [x]" for completed items
|
|
153
|
-
- Keep items focused on meaningful progress milestones rather than minor technical details. The checklist should not be so granular that minor implementation details clutter the progress tracking.
|
|
154
|
-
- For simple tasks, short checklists with even a single item are acceptable. For complex tasks, avoid making the checklist too long or verbose.
|
|
155
|
-
- If you are creating this checklist for the first time, and the tool use completes the first step in the checklist, make sure to mark it as completed in your task_progress parameter.
|
|
156
|
-
- Provide the whole checklist of steps you intend to complete in the task, and keep the checkboxes updated as you make progress. It's okay to rewrite this checklist as needed if it becomes invalid due to scope changes or new information.
|
|
157
|
-
- If a checklist is being used, be sure to update it any time a step has been completed.
|
|
158
|
-
- The system will automatically include todo list context in your prompts when appropriate - these reminders are important.
|
|
159
|
-
|
|
160
|
-
Example:
|
|
161
|
-
<agent_execute_command>
|
|
162
|
-
<command>npm install react</command>
|
|
163
|
-
<requires_approval>false</requires_approval>
|
|
164
|
-
<task_progress>
|
|
165
|
-
- [x] Set up project structure
|
|
166
|
-
- [x] Install dependencies
|
|
167
|
-
- [ ] Create components
|
|
168
|
-
- [ ] Test application
|
|
169
|
-
</task_progress>
|
|
170
|
-
</agent_execute_command>
|
|
171
|
-
|
|
172
|
-
====
|
|
173
|
-
|
|
174
|
-
EDITING FILES
|
|
175
|
-
|
|
176
|
-
You have access to two tools for working with files: **agent_write_to_file** and **agent_replace_in_file**. Understanding their roles and selecting the right one for the job will help ensure efficient and accurate modifications.
|
|
177
|
-
|
|
178
|
-
# agent_write_to_file
|
|
179
|
-
|
|
180
|
-
## Purpose
|
|
181
|
-
|
|
182
|
-
- Create a new file, or overwrite the entire contents of an existing file.
|
|
183
|
-
|
|
184
|
-
## When to Use
|
|
185
|
-
|
|
186
|
-
- Initial file creation, such as when scaffolding a new project.
|
|
187
|
-
- Overwriting large boilerplate files where you want to replace the entire content at once.
|
|
188
|
-
- When the complexity or number of changes would make agent_replace_in_file unwieldy or error-prone.
|
|
189
|
-
- When you need to completely restructure a file's content or change its fundamental organization.
|
|
190
|
-
|
|
191
|
-
## Important Considerations
|
|
192
|
-
|
|
193
|
-
- Using agent_write_to_file requires providing the file's complete final content.
|
|
194
|
-
- If you only need to make small changes to an existing file, consider using agent_replace_in_file instead to avoid unnecessarily rewriting the entire file.
|
|
195
|
-
- While agent_write_to_file should not be your default choice, don't hesitate to use it when the situation truly calls for it.
|
|
196
|
-
|
|
197
|
-
# agent_replace_in_file
|
|
198
|
-
|
|
199
|
-
## Purpose
|
|
200
|
-
|
|
201
|
-
- Make targeted edits to specific parts of an existing file without overwriting the entire file.
|
|
202
|
-
|
|
203
|
-
## When to Use
|
|
204
|
-
|
|
205
|
-
- Small, localized changes like updating a few lines, function implementations, changing variable names, modifying a section of text, etc.
|
|
206
|
-
- Targeted improvements where only specific portions of the file's content needs to be altered.
|
|
207
|
-
- Especially useful for long files where much of the file will remain unchanged.
|
|
208
|
-
|
|
209
|
-
## Advantages
|
|
210
|
-
|
|
211
|
-
- More efficient for minor edits, since you don't need to supply the entire file content.
|
|
212
|
-
- Reduces the chance of errors that can occur when overwriting large files.
|
|
213
|
-
|
|
214
|
-
# Choosing the Appropriate Tool
|
|
215
|
-
|
|
216
|
-
- **Default to agent_replace_in_file** for most changes. It's the safer, more precise option that minimizes potential issues.
|
|
217
|
-
- **Use agent_write_to_file** when:
|
|
218
|
-
- Creating new files
|
|
219
|
-
- The changes are so extensive that using agent_replace_in_file would be more complex or risky
|
|
220
|
-
- You need to completely reorganize or restructure a file
|
|
221
|
-
- The file is relatively small and the changes affect most of its content
|
|
222
|
-
- You're generating boilerplate or template files
|
|
223
|
-
|
|
224
|
-
# Auto-formatting Considerations
|
|
225
|
-
|
|
226
|
-
- After using either agent_write_to_file or agent_replace_in_file, the user's editor may automatically format the file
|
|
227
|
-
- This auto-formatting may modify the file contents, for example:
|
|
228
|
-
- Breaking single lines into multiple lines
|
|
229
|
-
- Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
|
|
230
|
-
- Converting single quotes to double quotes (or vice versa based on project preferences)
|
|
231
|
-
- Organizing imports (e.g. sorting, grouping by type)
|
|
232
|
-
- Adding/removing trailing commas in objects and arrays
|
|
233
|
-
- Enforcing consistent brace style (e.g. same-line vs new-line)
|
|
234
|
-
- Standardizing semicolon usage (adding or removing based on style)
|
|
235
|
-
- The agent_write_to_file and agent_replace_in_file tool responses will include the final state of the file after any auto-formatting
|
|
236
|
-
- Use this final state as your reference point for any subsequent edits. This is ESPECIALLY important when crafting SEARCH blocks for replace_in_file which require the content to match what's in the file exactly.
|
|
237
|
-
|
|
238
|
-
# Workflow Tips
|
|
239
|
-
|
|
240
|
-
1. Before editing, assess the scope of your changes and decide which tool to use.
|
|
241
|
-
2. For targeted edits, apply agent_replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single agent_replace_in_file call.
|
|
242
|
-
3. IMPORTANT: When you determine that you need to make several changes to the same file, prefer to use a single replace_in_file call with multiple SEARCH/REPLACE blocks. DO NOT prefer to make multiple successive replace_in_file calls for the same file. For example, if you were to add a component to a file, you would use a single replace_in_file call with a SEARCH/REPLACE block to add the import statement and another SEARCH/REPLACE block to add the component usage, rather than making one replace_in_file call for the import statement and then another separate replace_in_file call for the component usage.
|
|
243
|
-
4. For major overhauls or initial file creation, rely on agent_write_to_file.
|
|
244
|
-
5. Once the file has been edited with either agent_write_to_file or agent_replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
|
|
245
|
-
By thoughtfully selecting between agent_write_to_file and agent_replace_in_file, you can make your file editing process smoother, safer, and more efficient.
|
|
246
|
-
|
|
247
|
-
====
|
|
248
|
-
`;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
getNoUseToolInstructions(context: any): string {
|
|
252
|
-
return `[ERROR] You did not use a tool in your previous response! Please retry with a tool use.
|
|
253
|
-
|
|
254
|
-
# Reminder: Instructions for Tool Use
|
|
255
|
-
Tool uses are formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
|
|
256
|
-
<tool_name>
|
|
257
|
-
<parameter1_name>value1</parameter1_name>
|
|
258
|
-
<parameter2_name>value2</parameter2_name>
|
|
259
|
-
...
|
|
260
|
-
</tool_name>
|
|
261
|
-
For example:
|
|
262
|
-
<agent_attempt_completion>
|
|
263
|
-
<result>
|
|
264
|
-
I have completed the task...
|
|
265
|
-
</result>
|
|
266
|
-
</agent_attempt_completion>
|
|
267
|
-
Always adhere to this format for all tool uses to ensure proper parsing and execution.
|
|
268
|
-
|
|
269
|
-
# Next Steps
|
|
270
|
-
|
|
271
|
-
If you have completed the user's task, use the attempt_completion tool.
|
|
272
|
-
If you require additional information from the user, use the ask_followup_question tool.
|
|
273
|
-
Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task.
|
|
274
|
-
(This is an automated message, so do not respond to it conversationally.)
|
|
275
|
-
${this?.getEnvironmentInfoPrompt?.(context)}`;
|
|
276
|
-
}
|
|
277
|
-
}
|
package/src/prompt/index.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 抽象的 System Prompt 管理器。
|
|
3
|
-
* 替代原始项目中复杂的 templates/variants,交由宿主自行提供或使用默认简单实现。
|
|
4
|
-
*/
|
|
5
|
-
export interface IPromptManager {
|
|
6
|
-
/**
|
|
7
|
-
* 根据当前运行环境与动态参数,获取最终的系统提示词
|
|
8
|
-
*/
|
|
9
|
-
getSystemPrompt(context: any): Promise<string>;
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* 获取特定工具或技能的指令文本
|
|
13
|
-
*/
|
|
14
|
-
getToolInstructions?(context: any): string;
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* 获取环境信息提示词
|
|
18
|
-
*/
|
|
19
|
-
getEnvironmentInfoPrompt?(context: any): string;
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* 获取未使用工具的错误提示词
|
|
23
|
-
*/
|
|
24
|
-
getNoUseToolInstructions(context: any): string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export * from './NodePromptManager';
|
|
28
|
-
export * from './WebPromptManager';;
|
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
import { IAgentRuntime } from "../runtime";
|
|
2
|
-
import { ClineAgent } from "../agent";
|
|
3
|
-
import { NodeApiHandler, NodeApiHandlerConfig } from "../llm/NodeApiHandler";
|
|
4
|
-
import { NodePromptManager } from "../prompt/NodePromptManager";
|
|
5
|
-
import { NodeMemoryManager } from "../memory/NodeMemoryManager";
|
|
6
|
-
import { AgentDefaultTool } from "../shared/tools";
|
|
7
|
-
import * as fs from "fs/promises";
|
|
8
|
-
import * as os from "os";
|
|
9
|
-
import * as path from "path";
|
|
10
|
-
import { exec } from "child_process";
|
|
11
|
-
import { promisify } from "util";
|
|
12
|
-
import { WebMemoryManager } from "../memory/WebMemoryManager";
|
|
13
|
-
|
|
14
|
-
const execAsync = promisify(exec);
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* 默认的 Node.js 运行时实现
|
|
18
|
-
*/
|
|
19
|
-
export class DefaultNodeRuntime implements IAgentRuntime {
|
|
20
|
-
fs = {
|
|
21
|
-
readFile: async (filepath: string) => fs.readFile(filepath, "utf-8"),
|
|
22
|
-
writeFile: async (filepath: string, content: string) => {
|
|
23
|
-
await fs.mkdir(path.dirname(filepath), { recursive: true });
|
|
24
|
-
await fs.writeFile(filepath, content, "utf-8");
|
|
25
|
-
},
|
|
26
|
-
deleteFile: (filepath: string) => fs.unlink(filepath),
|
|
27
|
-
deleteDirectory: (dirpath: string) => fs.rm(dirpath, { recursive: true, force: true }),
|
|
28
|
-
fileExists: async (filepath: string) => {
|
|
29
|
-
try {
|
|
30
|
-
await fs.access(filepath);
|
|
31
|
-
return true;
|
|
32
|
-
} catch {
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
},
|
|
36
|
-
readDir: (dirpath: string) => fs.readdir(dirpath, { withFileTypes: true }),
|
|
37
|
-
mkdir: async (dirpath: string) => {
|
|
38
|
-
await fs.mkdir(dirpath, { recursive: true });
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
path = {
|
|
43
|
-
join: (...paths: string[]) => path.join(...paths),
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
env = {
|
|
47
|
-
get: (key: string) => process.env[key],
|
|
48
|
-
cwd: () => process.cwd(),
|
|
49
|
-
osInfo: () => `${os.type()} ${os.release()} ${os.arch()}`,
|
|
50
|
-
shell: () => process.env.SHELL || process.env.ComSpec || "unknown"
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
terminal = {
|
|
54
|
-
execCommand: async (command: string, options?: { cwd?: string }) => {
|
|
55
|
-
try {
|
|
56
|
-
const { stdout, stderr } = await execAsync(command, { cwd: options?.cwd || process.cwd() });
|
|
57
|
-
return { stdout, stderr, exitCode: 0 };
|
|
58
|
-
} catch (err: any) {
|
|
59
|
-
return { stdout: err.stdout || "", stderr: err.stderr || err.message, exitCode: err.code || 1 };
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export interface NodeAgentOptions {
|
|
66
|
-
apiConfig: NodeApiHandlerConfig;
|
|
67
|
-
dbPath?: string;
|
|
68
|
-
customInstructions?: string;
|
|
69
|
-
customTools?: any[];
|
|
70
|
-
allowDefaultTools?: string[];
|
|
71
|
-
memory?: NodeMemoryManager | WebMemoryManager;
|
|
72
|
-
maxLoopCount?: number;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* 快速创建 Node 端 Agent 的工厂方法
|
|
77
|
-
*/
|
|
78
|
-
export function createNodeAgent(options: NodeAgentOptions): ClineAgent {
|
|
79
|
-
const runtime = new DefaultNodeRuntime();
|
|
80
|
-
const api = new NodeApiHandler(options.apiConfig);
|
|
81
|
-
const memory = options.memory || new NodeMemoryManager(options.dbPath || path.join(runtime.env.cwd(), ".cline_memory.json"));
|
|
82
|
-
const customTools = options.customTools || [];
|
|
83
|
-
const customToolNames = new Set<string>(customTools.map((t: any) => t.name));
|
|
84
|
-
|
|
85
|
-
const promptManager = new NodePromptManager();
|
|
86
|
-
|
|
87
|
-
const agent = new ClineAgent({
|
|
88
|
-
runtime,
|
|
89
|
-
api,
|
|
90
|
-
promptManager,
|
|
91
|
-
memory,
|
|
92
|
-
customTools,
|
|
93
|
-
allowDefaultTools: options.allowDefaultTools,
|
|
94
|
-
maxLoopCount: options.maxLoopCount,
|
|
95
|
-
customInstructions: options.customInstructions,
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
agent.onToolCall = async (tool) => {
|
|
99
|
-
if (customToolNames.has(tool.name)) {
|
|
100
|
-
const customTool = customTools.find((t: any) => t.name === tool.name);
|
|
101
|
-
if (customTool.onCall) {
|
|
102
|
-
return customTool.onCall(tool.params);
|
|
103
|
-
}
|
|
104
|
-
return `Error: Custom tool "${tool.name}" does not have an onCall method.`;
|
|
105
|
-
}
|
|
106
|
-
};
|
|
107
|
-
|
|
108
|
-
return agent;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export * from "../index";
|
|
112
|
-
export * from "../mcp/NodeMcpManager";
|
package/src/runtime/web.test.ts
DELETED
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, beforeEach } from "vitest";
|
|
2
|
-
import { DefaultWebRuntime } from "./webRuntime";
|
|
3
|
-
|
|
4
|
-
describe("DefaultWebRuntime (memfs VFS)", () => {
|
|
5
|
-
let runtime: DefaultWebRuntime;
|
|
6
|
-
|
|
7
|
-
beforeEach(() => {
|
|
8
|
-
runtime = new DefaultWebRuntime();
|
|
9
|
-
});
|
|
10
|
-
|
|
11
|
-
describe("File System Operations", () => {
|
|
12
|
-
it("should write and read a file successfully", async () => {
|
|
13
|
-
const filepath = "/workspace/test.txt";
|
|
14
|
-
const content = "Hello, Web Agent!";
|
|
15
|
-
|
|
16
|
-
await runtime.fs.writeFile(filepath, content);
|
|
17
|
-
|
|
18
|
-
const result = await runtime.fs.readFile(filepath);
|
|
19
|
-
expect(result).toBe(content);
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
it("should auto-create nested directories when writing a file", async () => {
|
|
23
|
-
const filepath = "/workspace/deep/nested/dir/test.txt";
|
|
24
|
-
const content = "Deep content";
|
|
25
|
-
|
|
26
|
-
await runtime.fs.writeFile(filepath, content);
|
|
27
|
-
|
|
28
|
-
const result = await runtime.fs.readFile(filepath);
|
|
29
|
-
expect(result).toBe(content);
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
it("should return true for fileExists if file exists", async () => {
|
|
33
|
-
const filepath = "/workspace/exists.txt";
|
|
34
|
-
|
|
35
|
-
expect(await runtime.fs.fileExists(filepath)).toBe(false);
|
|
36
|
-
|
|
37
|
-
await runtime.fs.writeFile(filepath, "data");
|
|
38
|
-
|
|
39
|
-
expect(await runtime.fs.fileExists(filepath)).toBe(true);
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
it("should throw an error when reading a non-existent file", async () => {
|
|
43
|
-
await expect(runtime.fs.readFile("/workspace/missing.txt")).rejects.toThrow();
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
it("should list files and directories correctly", async () => {
|
|
47
|
-
await runtime.fs.writeFile("/workspace/file1.txt", "1");
|
|
48
|
-
await runtime.fs.writeFile("/workspace/file2.txt", "2");
|
|
49
|
-
await runtime.fs.mkdir("/workspace/subdir");
|
|
50
|
-
await runtime.fs.writeFile("/workspace/subdir/file3.txt", "3");
|
|
51
|
-
|
|
52
|
-
const list = await runtime.fs.readDir("/workspace");
|
|
53
|
-
|
|
54
|
-
expect(list).toContain("file1.txt");
|
|
55
|
-
expect(list).toContain("file2.txt");
|
|
56
|
-
expect(list).toContain("subdir");
|
|
57
|
-
expect(list.length).toBe(3);
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
it("should explicitly create directories via mkdir", async () => {
|
|
61
|
-
const dirpath = "/workspace/explicit_dir";
|
|
62
|
-
await runtime.fs.mkdir(dirpath);
|
|
63
|
-
|
|
64
|
-
// we can test it exists by listing the parent
|
|
65
|
-
const list = await runtime.fs.readDir("/workspace");
|
|
66
|
-
expect(list).toContain("explicit_dir");
|
|
67
|
-
});
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
describe("Environment Operations", () => {
|
|
71
|
-
it("should return undefined for get()", () => {
|
|
72
|
-
expect(runtime.env.get("ANY_KEY")).toBeUndefined();
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
it("should return /workspace for cwd()", () => {
|
|
76
|
-
expect(runtime.env.cwd()).toBe("/workspace");
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
it("should return Web Browser or user agent for osInfo()", () => {
|
|
80
|
-
expect(runtime.env.osInfo()).toBeTruthy();
|
|
81
|
-
expect(typeof runtime.env.osInfo()).toBe("string");
|
|
82
|
-
});
|
|
83
|
-
});
|
|
84
|
-
|
|
85
|
-
describe("Terminal Operations", () => {
|
|
86
|
-
it("should mock terminal command execution", async () => {
|
|
87
|
-
const result = await runtime.terminal.execCommand("echo hello");
|
|
88
|
-
|
|
89
|
-
expect(result.exitCode).toBe(0);
|
|
90
|
-
expect(result.stderr).toBe("");
|
|
91
|
-
expect(result.stdout).toContain("[Mock]");
|
|
92
|
-
expect(result.stdout).toContain("echo hello");
|
|
93
|
-
});
|
|
94
|
-
});
|
|
95
|
-
});
|
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
import { IAgentRuntime } from "../runtime";
|
|
2
|
-
import { ClineAgent } from "../agent";
|
|
3
|
-
import { WebApiHandler, WebApiHandlerConfig } from "../llm/WebApiHandler";
|
|
4
|
-
import { WebPromptManager } from "../prompt/WebPromptManager";
|
|
5
|
-
import { WebMemoryManager } from "../memory/WebMemoryManager";
|
|
6
|
-
import { AgentDefaultTool } from "../shared/tools";
|
|
7
|
-
import { Volume, createFsFromVolume } from "memfs";
|
|
8
|
-
import path from "path-browserify";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* 默认的 Web 运行时实现
|
|
12
|
-
* 提供了基于 memfs 的虚拟文件系统和模拟终端。
|
|
13
|
-
* 宿主环境如果使用了 WebContainer 或 OPFS,应覆盖此实现。
|
|
14
|
-
*/
|
|
15
|
-
export class DefaultWebRuntime implements IAgentRuntime {
|
|
16
|
-
private vol = new Volume();
|
|
17
|
-
private memfs = createFsFromVolume(this.vol).promises;
|
|
18
|
-
|
|
19
|
-
fs = {
|
|
20
|
-
readFile: async (filepath: string) => {
|
|
21
|
-
const content = await this.memfs.readFile(filepath, "utf-8");
|
|
22
|
-
return content.toString();
|
|
23
|
-
},
|
|
24
|
-
writeFile: async (filepath: string, content: string) => {
|
|
25
|
-
const dir = filepath.substring(0, filepath.lastIndexOf("/"));
|
|
26
|
-
if (dir && dir !== filepath) {
|
|
27
|
-
await this.memfs.mkdir(dir, { recursive: true });
|
|
28
|
-
}
|
|
29
|
-
await this.memfs.writeFile(filepath, content);
|
|
30
|
-
},
|
|
31
|
-
deleteFile: (filepath: string) => this.memfs.unlink(filepath),
|
|
32
|
-
deleteDirectory: (dirpath: string) => this.memfs.rm(dirpath, { recursive: true, force: true }),
|
|
33
|
-
fileExists: async (filepath: string) => {
|
|
34
|
-
try {
|
|
35
|
-
await this.memfs.access(filepath);
|
|
36
|
-
return true;
|
|
37
|
-
} catch {
|
|
38
|
-
return false;
|
|
39
|
-
}
|
|
40
|
-
},
|
|
41
|
-
readDir: (dirpath: string) => {
|
|
42
|
-
return this.memfs.readdir(dirpath, { withFileTypes: true }) as any;
|
|
43
|
-
},
|
|
44
|
-
mkdir: async (dirpath: string) => {
|
|
45
|
-
await this.memfs.mkdir(dirpath, { recursive: true });
|
|
46
|
-
},
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
path = {
|
|
50
|
-
join: (...paths: string[]) => path.join(...paths),
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
env = {
|
|
54
|
-
get: (key: string) => undefined, // 浏览器环境中无系统环境变量
|
|
55
|
-
cwd: () => "/workspace",
|
|
56
|
-
osInfo: () => typeof navigator !== "undefined" ? navigator.userAgent : "Web Browser",
|
|
57
|
-
shell: () => '', // 浏览器环境中无真实 shell
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
terminal = {
|
|
61
|
-
execCommand: async (command: string, options?: { cwd?: string }) => {
|
|
62
|
-
// 在纯浏览器环境中,终端被 Mock
|
|
63
|
-
return {
|
|
64
|
-
stdout: `[Mock] Command '${command}' executed in browser sandbox.`,
|
|
65
|
-
stderr: "",
|
|
66
|
-
exitCode: 0,
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export interface WebAgentOptions {
|
|
73
|
-
apiConfig: WebApiHandlerConfig;
|
|
74
|
-
dbPath?: string;
|
|
75
|
-
customInstructions?: string;
|
|
76
|
-
customTools?: any[];
|
|
77
|
-
allowDefaultTools?: string[];
|
|
78
|
-
memory?: WebMemoryManager;
|
|
79
|
-
maxLoopCount?: number;
|
|
80
|
-
storageKey?: string;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* 快速创建 Web 端 Agent 的工厂方法
|
|
85
|
-
*/
|
|
86
|
-
export function createWebAgent(options: WebAgentOptions): ClineAgent {
|
|
87
|
-
const runtime = new DefaultWebRuntime();
|
|
88
|
-
const api = new WebApiHandler(options.apiConfig);
|
|
89
|
-
const promptManager = new WebPromptManager();
|
|
90
|
-
const memory = new WebMemoryManager(options.storageKey || "cline_agent_memory");
|
|
91
|
-
const customTools = options.customTools || [];
|
|
92
|
-
const customToolNames = new Set<string>(customTools.map((t: any) => t.name));
|
|
93
|
-
|
|
94
|
-
const agent = new ClineAgent({
|
|
95
|
-
runtime,
|
|
96
|
-
api,
|
|
97
|
-
promptManager,
|
|
98
|
-
memory,
|
|
99
|
-
customTools,
|
|
100
|
-
allowDefaultTools: options.allowDefaultTools,
|
|
101
|
-
maxLoopCount: options.maxLoopCount,
|
|
102
|
-
customInstructions: options.customInstructions,
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
agent.onToolCall = async (tool) => {
|
|
106
|
-
if (customToolNames.has(tool.name)) {
|
|
107
|
-
const customTool = customTools.find((t: any) => t.name === tool.name);
|
|
108
|
-
if (customTool.onCall) {
|
|
109
|
-
return customTool.onCall(tool.params);
|
|
110
|
-
}
|
|
111
|
-
return `Error: Custom tool "${tool.name}" does not have an onCall method.`;
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
|
|
115
|
-
return agent;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
export * from "../index";
|
|
119
|
-
export * from "../mcp/WebMcpManager";
|
package/src/runtime.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* IAgentRuntime 抽象了所有与特定宿主环境(Node.js, Web, VS Code 等)相关的能力。
|
|
3
|
-
* 通过注入 IAgentRuntime,Agent 的核心逻辑可以运行在任何平台上。
|
|
4
|
-
*/
|
|
5
|
-
export interface IAgentRuntime {
|
|
6
|
-
/**
|
|
7
|
-
* 文件系统相关操作
|
|
8
|
-
*/
|
|
9
|
-
fs: {
|
|
10
|
-
readFile(path: string): Promise<string>;
|
|
11
|
-
writeFile(path: string, content: string): Promise<void>;
|
|
12
|
-
deleteFile(path: string): Promise<void>;
|
|
13
|
-
deleteDirectory(path: string): Promise<void>;
|
|
14
|
-
fileExists(path: string): Promise<boolean>;
|
|
15
|
-
readDir(path: string): Promise<any[]>;
|
|
16
|
-
mkdir(path: string): Promise<void>;
|
|
17
|
-
/**
|
|
18
|
-
* 跨文件正则搜索
|
|
19
|
-
* @param path 搜索目录
|
|
20
|
-
* @param regex 正则表达式字符串
|
|
21
|
-
* @param filePattern (可选) 文件名匹配模式,比如 '*.ts'
|
|
22
|
-
* @returns 返回格式化后的包含上下文的搜索结果字符串
|
|
23
|
-
*/
|
|
24
|
-
searchFiles?(path: string, regex: string, filePattern?: string): Promise<string>;
|
|
25
|
-
};
|
|
26
|
-
path: {
|
|
27
|
-
join(...paths: string[]): string;
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* 环境变量和系统信息
|
|
32
|
-
*/
|
|
33
|
-
env: {
|
|
34
|
-
get(key: string): string | undefined;
|
|
35
|
-
cwd(): string;
|
|
36
|
-
osInfo(): string; // 比如返回类似 'Windows 10' 或 'Web Browser' 的标识
|
|
37
|
-
shell(): string; // 返回当前 shell 的类型,比如 'bash', 'zsh', 'cmd', 'powershell',Web 环境下返回空字符串
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* 终端/命令行相关操作
|
|
42
|
-
*/
|
|
43
|
-
terminal: {
|
|
44
|
-
execCommand(command: string, options?: { cwd?: string }): Promise<{ stdout: string; stderr: string; exitCode: number }>;
|
|
45
|
-
};
|
|
46
|
-
}
|