@amical/aiagent-sdk 0.1.1 → 0.1.3

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,1577 @@
1
+ import { nanoid } from 'nanoid';
2
+ import matter from 'gray-matter';
3
+ import { streamText } from 'ai';
4
+ import { createOpenAI } from '@ai-sdk/openai';
5
+ import { createDifyProvider } from 'dify-ai-provider';
6
+ import * as fs2 from 'fs/promises';
7
+ import * as path2 from 'path';
8
+ import * as os from 'os';
9
+ import { exec } from 'child_process';
10
+ import { promisify } from 'util';
11
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
12
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
13
+
14
+ // src/shared/tools.ts
15
+ var AgentDefaultTool = /* @__PURE__ */ ((AgentDefaultTool2) => {
16
+ AgentDefaultTool2["ASK"] = "agent_ask_followup_question";
17
+ AgentDefaultTool2["ATTEMPT"] = "agent_attempt_completion";
18
+ AgentDefaultTool2["BASH"] = "agent_execute_command";
19
+ AgentDefaultTool2["FILE_EDIT"] = "agent_replace_in_file";
20
+ AgentDefaultTool2["FILE_READ"] = "agent_read_file";
21
+ AgentDefaultTool2["FILE_NEW"] = "agent_write_to_file";
22
+ AgentDefaultTool2["FILE_DELETE"] = "agent_delete_file";
23
+ AgentDefaultTool2["DIR_DELETE"] = "agent_delete_directory";
24
+ AgentDefaultTool2["SEARCH"] = "agent_search_files";
25
+ AgentDefaultTool2["LIST_FILES"] = "agent_list_files";
26
+ AgentDefaultTool2["LIST_CODE_DEF"] = "agent_list_code_definition_names";
27
+ AgentDefaultTool2["BROWSER"] = "agent_browser_action";
28
+ AgentDefaultTool2["MCP_USE"] = "agent_use_mcp_tool";
29
+ AgentDefaultTool2["MCP_ACCESS"] = "agent_access_mcp_resource";
30
+ AgentDefaultTool2["MCP_DOCS"] = "agent_load_mcp_documentation";
31
+ AgentDefaultTool2["NEW_TASK"] = "agent_new_task";
32
+ AgentDefaultTool2["PLAN_MODE"] = "agent_plan_mode_respond";
33
+ AgentDefaultTool2["ACT_MODE"] = "agent_act_mode_respond";
34
+ AgentDefaultTool2["TODO"] = "agent_focus_chain";
35
+ AgentDefaultTool2["WEB_FETCH"] = "agent_web_fetch";
36
+ AgentDefaultTool2["WEB_SEARCH"] = "agent_web_search";
37
+ AgentDefaultTool2["CONDENSE"] = "agent_condense";
38
+ AgentDefaultTool2["SUMMARIZE_TASK"] = "agent_summarize_task";
39
+ AgentDefaultTool2["REPORT_BUG"] = "agent_report_bug";
40
+ AgentDefaultTool2["NEW_RULE"] = "agent_new_rule";
41
+ AgentDefaultTool2["APPLY_PATCH"] = "agent_apply_patch";
42
+ AgentDefaultTool2["GENERATE_EXPLANATION"] = "agent_generate_explanation";
43
+ AgentDefaultTool2["LOAD_SKILL"] = "agent_load_skill";
44
+ AgentDefaultTool2["USE_SUBAGENTS"] = "agent_use_subagents";
45
+ return AgentDefaultTool2;
46
+ })(AgentDefaultTool || {});
47
+ var TOOL_RESULT_BLOCK = "tool_call_result";
48
+ var defaultTools = [
49
+ {
50
+ name: "agent_ask_followup_question" /* ASK */,
51
+ description: "Ask the user a clarifying question if more information is needed.",
52
+ params: {
53
+ question: "The question to ask the user."
54
+ }
55
+ },
56
+ {
57
+ name: "agent_attempt_completion" /* ATTEMPT */,
58
+ description: "After each tool use, the user will respond with the result of that tool use, i.e. if it succeeded or failed, along with any reasons for failure. Once you've received the results of tool uses and can confirm that the task is complete, use this tool to present the result of your work to the user. Optionally you may provide a CLI command to showcase the result of your work. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again. IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user that any previous tool uses were successful. Failure to do so will result in code corruption and system failure. Before using this tool, you must ask yourself in tags if you've confirmed from the user that any previous tool uses were successful. If not, then DO NOT use this tool. If you were using task_progress to update the task progress, you must include the completed list in the result as well.",
59
+ params: {
60
+ result: "(required) The result of the tool use. This should be a clear, specific description of the result."
61
+ },
62
+ example: `## Example: ${"agent_attempt_completion" /* ATTEMPT */}
63
+ <${"agent_attempt_completion" /* ATTEMPT */}>
64
+ <result>final result or message</result>
65
+ <task_progress>
66
+ - [x] Set up project structure
67
+ - [x] Install dependencies
68
+ - [x] Run command to start server
69
+ - [x] Test application
70
+ </task_progress>
71
+ </${"agent_attempt_completion" /* ATTEMPT */}>`
72
+ },
73
+ {
74
+ name: "agent_execute_command" /* BASH */,
75
+ description: "Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. For command chaining, use the appropriate chaining syntax for the user's shell. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: ${context.cwd} Use @workspace:path syntax (e.g., @frontend:src/index.ts) to specify a workspace.",
76
+ params: {
77
+ command: "(required) The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions."
78
+ },
79
+ example: `## Example: Requesting to execute a command
80
+
81
+ <${"agent_execute_command" /* BASH */}>
82
+ <command>npm run dev</command>
83
+ <requires_approval>false</requires_approval>
84
+ <task_progress>
85
+ - [x] Set up project structure
86
+ - [x] Install dependencies
87
+ - [ ] Run command to start server
88
+ - [ ] Test application
89
+ </task_progress>
90
+ </${"agent_execute_command" /* BASH */}>`
91
+ },
92
+ {
93
+ name: "agent_replace_in_file" /* FILE_EDIT */,
94
+ description: "Replace specific content in a file using a search/replace diff block.",
95
+ params: {
96
+ path: "(required) The absolute or relative file path to modify.",
97
+ diff: "(required) The diff content to apply."
98
+ },
99
+ example: `## Example: Requesting to make targeted edits to a file
100
+
101
+ <${"agent_replace_in_file" /* FILE_EDIT */}>
102
+ <path>src/components/App.tsx</path>
103
+ <diff>
104
+ ------- SEARCH
105
+ import React from 'react';
106
+ =======
107
+ import React, { useState } from 'react';
108
+ +++++++ REPLACE
109
+
110
+ ------- SEARCH
111
+ function handleSubmit() {
112
+ saveData();
113
+ setLoading(false);
114
+ }
115
+
116
+ =======
117
+ +++++++ REPLACE
118
+
119
+ ------- SEARCH
120
+ return (
121
+ <div>
122
+ =======
123
+ function handleSubmit() {
124
+ saveData();
125
+ setLoading(false);
126
+ }
127
+
128
+ return (
129
+ <div>
130
+ +++++++ REPLACE
131
+ </diff>
132
+ <task_progress>
133
+ - [x] Set up project structure
134
+ - [x] Install dependencies
135
+ - [ ] Create components
136
+ - [ ] Test application
137
+ </task_progress>
138
+ </${"agent_replace_in_file" /* FILE_EDIT */}>`
139
+ },
140
+ {
141
+ name: "agent_read_file" /* FILE_READ */,
142
+ description: "Read the contents of a specific file.",
143
+ params: {
144
+ path: "(required) The absolute or relative file path to read."
145
+ }
146
+ },
147
+ {
148
+ name: "agent_write_to_file" /* FILE_NEW */,
149
+ description: "Create or overwrite a file with new content.",
150
+ params: {
151
+ path: "(required) The path of the file to write to (relative to the current working directory ${context.cwd}) Use @workspace:path syntax (e.g., @frontend:src/index.ts) to specify a workspace.",
152
+ content: "(required) The content to write to the file."
153
+ },
154
+ example: `## Example: Requesting to create a new file
155
+
156
+ <${"agent_write_to_file" /* FILE_NEW */}>
157
+ <path>src/frontend-config.json</path>
158
+ <content>
159
+ {
160
+ "apiEndpoint": "https://api.example.com",
161
+ "theme": {
162
+ "primaryColor": "#007bff",
163
+ "secondaryColor": "#6c757d",
164
+ "fontFamily": "Arial, sans-serif"
165
+ },
166
+ "features": {
167
+ "darkMode": true,
168
+ "notifications": true,
169
+ "analytics": false
170
+ },
171
+ "version": "1.0.0"
172
+ }
173
+ </content>
174
+ <task_progress>
175
+ - [x] Set up project structure
176
+ - [x] Install dependencies
177
+ - [x] Create components
178
+ - [ ] Test application
179
+ </task_progress>
180
+ </${"agent_write_to_file" /* FILE_NEW */}>`
181
+ },
182
+ {
183
+ name: "agent_delete_file" /* FILE_DELETE */,
184
+ description: "Delete a file.",
185
+ params: {
186
+ path: "(required) The path of the file to delete to (relative to the current working directory ${context.cwd}) Use @workspace:path syntax (e.g., @frontend:src/index.ts) to specify a workspace."
187
+ }
188
+ },
189
+ {
190
+ name: "agent_delete_directory" /* DIR_DELETE */,
191
+ description: "Delete a directory.",
192
+ params: {
193
+ path: "(required) The path of the directory to delete to (relative to the current working directory ${context.cwd}) Use @workspace:path syntax (e.g., @frontend:src/index.ts) to specify a workspace."
194
+ }
195
+ },
196
+ {
197
+ name: "agent_search_files" /* SEARCH */,
198
+ description: "Search for files in a directory that match a regex pattern or glob pattern.",
199
+ params: {
200
+ path: "(required) The absolute or relative directory path to search.",
201
+ regex: "(required) The regex pattern to match files against.",
202
+ file_pattern: "(optional) glob pattern like *.ts."
203
+ }
204
+ },
205
+ {
206
+ name: "agent_list_files" /* LIST_FILES */,
207
+ description: "List all files in a directory.",
208
+ params: {
209
+ path: "(required) The absolute or relative directory path to list."
210
+ }
211
+ },
212
+ //================
213
+ {
214
+ name: "agent_new_task" /* NEW_TASK */,
215
+ description: "Create a new task with a given context.",
216
+ params: {
217
+ context: "(required) The context of the new task."
218
+ },
219
+ example: `## Example: Creating a new task
220
+ <${"agent_new_task" /* NEW_TASK */}>
221
+ <context>
222
+ 1. Current Work:
223
+ [Detailed description]
224
+
225
+ 2. Key Technical Concepts:
226
+ - [Concept 1]
227
+ - [Concept 2]
228
+ - [...]
229
+
230
+ 3. Relevant Files and Code:
231
+ - [File Name 1]
232
+ - [Summary of why this file is important]
233
+ - [Summary of the changes made to this file, if any]
234
+ - [Important Code Snippet]
235
+ - [File Name 2]
236
+ - [Important Code Snippet]
237
+ - [...]
238
+
239
+ 4. Problem Solving:
240
+ [Detailed description]
241
+
242
+ 5. Pending Tasks and Next Steps:
243
+ - [Task 1 details & next steps]
244
+ - [Task 2 details & next steps]
245
+ - [...]
246
+ </context>
247
+ </${"agent_new_task" /* NEW_TASK */}>`
248
+ },
249
+ {
250
+ name: "agent_load_skill" /* LOAD_SKILL */,
251
+ description: "Load a skill to perform a task. important: skill_name is required. must use this tool to load the skill; do not use any other method to read it.",
252
+ params: {
253
+ skill_name: "(required) The name of the skill to load."
254
+ }
255
+ }
256
+ ];
257
+ var toolUseNames = Object.values(AgentDefaultTool);
258
+ var dynamicToolUseNamesByNamespace = /* @__PURE__ */ new Map();
259
+ function setDynamicToolUseNames(namespace, names) {
260
+ dynamicToolUseNamesByNamespace.set(namespace, new Set(names.map((name) => name.trim()).filter(Boolean)));
261
+ }
262
+ function getToolUseNames() {
263
+ const defaults = [...toolUseNames];
264
+ const dynamic = Array.from(dynamicToolUseNamesByNamespace.values()).flatMap((set) => Array.from(set));
265
+ return Array.from(/* @__PURE__ */ new Set([...defaults, ...dynamic]));
266
+ }
267
+ var READ_ONLY_TOOLS = [
268
+ "agent_list_files" /* LIST_FILES */,
269
+ "agent_read_file" /* FILE_READ */,
270
+ "agent_search_files" /* SEARCH */,
271
+ "agent_list_code_definition_names" /* LIST_CODE_DEF */,
272
+ "agent_browser_action" /* BROWSER */,
273
+ "agent_ask_followup_question" /* ASK */,
274
+ "agent_web_search" /* WEB_SEARCH */,
275
+ "agent_web_fetch" /* WEB_FETCH */,
276
+ "agent_load_skill" /* LOAD_SKILL */,
277
+ "agent_use_subagents" /* USE_SUBAGENTS */
278
+ ];
279
+ function parseAssistantMessageV2(assistantMessage, toolParamNames2) {
280
+ const contentBlocks = [];
281
+ let currentTextContentStart = 0;
282
+ let currentTextContent;
283
+ let currentToolUseStart = 0;
284
+ let currentToolUse;
285
+ let currentParamValueStart = 0;
286
+ let currentParamName;
287
+ const toolUseOpenTags = /* @__PURE__ */ new Map();
288
+ const toolParamOpenTags = /* @__PURE__ */ new Map();
289
+ for (const name of getToolUseNames()) {
290
+ toolUseOpenTags.set(`<${name}>`, name);
291
+ }
292
+ for (const name of toolParamNames2) {
293
+ toolParamOpenTags.set(`<${name}>`, name);
294
+ }
295
+ const len = assistantMessage.length;
296
+ for (let i = 0; i < len; i++) {
297
+ const currentCharIndex = i;
298
+ if (currentToolUse && currentParamName) {
299
+ const closeTag = `</${currentParamName}>`;
300
+ if (currentCharIndex >= closeTag.length - 1 && assistantMessage.startsWith(
301
+ closeTag,
302
+ currentCharIndex - closeTag.length + 1
303
+ // Start checking from potential start of tag
304
+ )) {
305
+ const value = assistantMessage.slice(
306
+ currentParamValueStart,
307
+ // Start after the opening tag
308
+ currentCharIndex - closeTag.length + 1
309
+ // End before the closing tag
310
+ ).trim();
311
+ currentToolUse.params[currentParamName] = value;
312
+ currentParamName = void 0;
313
+ } else {
314
+ continue;
315
+ }
316
+ }
317
+ if (currentToolUse && !currentParamName) {
318
+ let startedNewParam = false;
319
+ for (const [tag, paramName] of toolParamOpenTags.entries()) {
320
+ if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
321
+ currentParamName = paramName;
322
+ currentParamValueStart = currentCharIndex + 1;
323
+ startedNewParam = true;
324
+ break;
325
+ }
326
+ }
327
+ if (startedNewParam) {
328
+ continue;
329
+ }
330
+ const toolCloseTag = `</${currentToolUse.name}>`;
331
+ if (currentCharIndex >= toolCloseTag.length - 1 && assistantMessage.startsWith(toolCloseTag, currentCharIndex - toolCloseTag.length + 1)) {
332
+ const toolContentSlice = assistantMessage.slice(
333
+ currentToolUseStart,
334
+ // From after the tool opening tag
335
+ currentCharIndex - toolCloseTag.length + 1
336
+ // To before the tool closing tag
337
+ );
338
+ const contentParamName = "content";
339
+ if (currentToolUse.name === "agent_write_to_file" /* FILE_NEW */ && toolContentSlice.includes(`<${contentParamName}>`)) {
340
+ const contentStartTag = `<${contentParamName}>`;
341
+ const contentEndTag = `</${contentParamName}>`;
342
+ const contentStart = toolContentSlice.indexOf(contentStartTag);
343
+ const contentEnd = toolContentSlice.lastIndexOf(contentEndTag);
344
+ if (contentStart !== -1 && contentEnd !== -1 && contentEnd > contentStart) {
345
+ const contentValue = toolContentSlice.slice(contentStart + contentStartTag.length, contentEnd).trim();
346
+ currentToolUse.params[contentParamName] = contentValue;
347
+ }
348
+ }
349
+ currentToolUse.partial = false;
350
+ contentBlocks.push(currentToolUse);
351
+ currentToolUse = void 0;
352
+ currentTextContentStart = currentCharIndex + 1;
353
+ continue;
354
+ }
355
+ continue;
356
+ }
357
+ if (!currentToolUse) {
358
+ let startedNewTool = false;
359
+ for (const [tag, toolName] of toolUseOpenTags.entries()) {
360
+ if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
361
+ if (currentTextContent) {
362
+ currentTextContent.content = assistantMessage.slice(
363
+ currentTextContentStart,
364
+ // From where text started
365
+ currentCharIndex - tag.length + 1
366
+ // To before the tool tag starts
367
+ ).trim();
368
+ currentTextContent.partial = false;
369
+ if (currentTextContent.content.length > 0) {
370
+ contentBlocks.push(currentTextContent);
371
+ }
372
+ currentTextContent = void 0;
373
+ } else {
374
+ const potentialText = assistantMessage.slice(
375
+ currentTextContentStart,
376
+ // From where text *might* have started
377
+ currentCharIndex - tag.length + 1
378
+ // To before the tool tag starts
379
+ ).trim();
380
+ if (potentialText.length > 0) {
381
+ contentBlocks.push({
382
+ type: "text",
383
+ content: potentialText,
384
+ partial: false
385
+ });
386
+ }
387
+ }
388
+ currentToolUse = {
389
+ type: "tool_use",
390
+ name: toolName,
391
+ params: {},
392
+ partial: true,
393
+ // Assume partial until closing tag is found
394
+ call_id: nanoid(8),
395
+ isNativeToolCall: false
396
+ };
397
+ currentToolUseStart = currentCharIndex + 1;
398
+ startedNewTool = true;
399
+ break;
400
+ }
401
+ }
402
+ if (startedNewTool) {
403
+ continue;
404
+ }
405
+ if (!currentTextContent) {
406
+ currentTextContentStart = currentCharIndex;
407
+ currentTextContent = {
408
+ type: "text",
409
+ content: "",
410
+ // Will be determined by slicing at the end or when a tool starts
411
+ partial: true
412
+ };
413
+ }
414
+ }
415
+ }
416
+ if (currentToolUse && currentParamName) {
417
+ currentToolUse.params[currentParamName] = assistantMessage.slice(currentParamValueStart).trim();
418
+ }
419
+ if (currentToolUse) {
420
+ contentBlocks.push(currentToolUse);
421
+ } else if (currentTextContent) {
422
+ currentTextContent.content = assistantMessage.slice(currentTextContentStart).trim();
423
+ if (currentTextContent.content.length > 0) {
424
+ contentBlocks.push(currentTextContent);
425
+ }
426
+ }
427
+ return contentBlocks;
428
+ }
429
+
430
+ // src/parser/index.ts
431
+ var toolParamNames = [
432
+ "command",
433
+ "requires_approval",
434
+ "path",
435
+ "absolutePath",
436
+ "content",
437
+ "diff",
438
+ "regex",
439
+ "file_pattern",
440
+ "recursive",
441
+ "action",
442
+ "url",
443
+ "coordinate",
444
+ "text",
445
+ "query",
446
+ "allowed_domains",
447
+ "blocked_domains",
448
+ "prompt",
449
+ "server_name",
450
+ "tool_name",
451
+ "arguments",
452
+ "uri",
453
+ "question",
454
+ "options",
455
+ "response",
456
+ "result",
457
+ "context",
458
+ "title",
459
+ "what_happened",
460
+ "steps_to_reproduce",
461
+ "api_request_output",
462
+ "additional_context",
463
+ "needs_more_exploration",
464
+ "task_progress",
465
+ "timeout",
466
+ "input",
467
+ "from_ref",
468
+ "to_ref",
469
+ "skill_name",
470
+ "prompt_1",
471
+ "prompt_2",
472
+ "prompt_3",
473
+ "prompt_4",
474
+ "prompt_5",
475
+ "start_line",
476
+ "end_line"
477
+ ];
478
+ var AgentState = /* @__PURE__ */ ((AgentState2) => {
479
+ AgentState2["IDLE"] = "idle";
480
+ AgentState2["THINKING"] = "thinking";
481
+ AgentState2["WAITING_FOR_USER"] = "waiting_for_user";
482
+ AgentState2["FINISHED"] = "finished";
483
+ AgentState2["ERROR"] = "error";
484
+ return AgentState2;
485
+ })(AgentState || {});
486
+ var ClineAgent = class {
487
+ runtime;
488
+ api;
489
+ promptManager;
490
+ memory;
491
+ mcp;
492
+ state = "idle" /* IDLE */;
493
+ allToolParamNames = [...toolParamNames];
494
+ /** 循环计数器 */
495
+ loopCount = 0;
496
+ /** 最大循环次数 */
497
+ maxLoopCount;
498
+ skillDir;
499
+ customTools;
500
+ customToolNames;
501
+ allowDefaultTools;
502
+ customInstructions;
503
+ sysPrompt;
504
+ noUseTollSysPrompt;
505
+ // 简单的事件回调系统,供宿主环境注册以监听 Agent 内部事件
506
+ onStateChange;
507
+ onStreamChunk;
508
+ onToolCall;
509
+ constructor(options) {
510
+ this.runtime = options.runtime;
511
+ this.api = options.api;
512
+ this.promptManager = options.promptManager;
513
+ this.memory = options.memory;
514
+ this.mcp = options.mcp;
515
+ this.maxLoopCount = options.maxLoopCount ?? 150;
516
+ this.customTools = options.customTools || [];
517
+ this.allowDefaultTools = options.allowDefaultTools;
518
+ if (this.allowDefaultTools && !this.allowDefaultTools.includes("agent_attempt_completion" /* ATTEMPT */)) {
519
+ this.allowDefaultTools.push("agent_attempt_completion" /* ATTEMPT */);
520
+ }
521
+ this.customInstructions = options.customInstructions;
522
+ if (this.customTools.length > 0) {
523
+ const dynamicToolNames = /* @__PURE__ */ new Set();
524
+ const customToolParams = /* @__PURE__ */ new Set();
525
+ for (const customTool of this.customTools) {
526
+ dynamicToolNames.add(customTool.name);
527
+ if (customTool.params) {
528
+ for (const key in customTool.params) {
529
+ if (!Object.hasOwn(customTool.params, key)) continue;
530
+ customToolParams.add(key);
531
+ }
532
+ }
533
+ }
534
+ const defaultToolNames = Object.values(AgentDefaultTool);
535
+ const overlappingTools = Array.from(dynamicToolNames).filter((name) => defaultToolNames.includes(name));
536
+ if (overlappingTools.length > 0) {
537
+ throw new Error(`Custom tools and default tools have overlapping names: ${overlappingTools.join(", ")}`);
538
+ }
539
+ if (dynamicToolNames.size > 0) {
540
+ setDynamicToolUseNames("customUser", Array.from(dynamicToolNames));
541
+ }
542
+ if (customToolParams.size > 0) {
543
+ this.allToolParamNames = Array.from(/* @__PURE__ */ new Set([...this.allToolParamNames, ...Array.from(customToolParams)]));
544
+ }
545
+ }
546
+ this.customToolNames = new Set(this.customTools.map((t) => t.name));
547
+ this.skillDir = this.runtime.path.join(this.runtime.env.cwd(), ".agent/skills");
548
+ }
549
+ setState(newState) {
550
+ this.state = newState;
551
+ if (this.onStateChange) {
552
+ this.onStateChange(newState);
553
+ }
554
+ }
555
+ /**
556
+ * 获取当前 Agent 的系统提示词
557
+ * 如果 force 为 true,则强制重新获取系统提示词
558
+ */
559
+ async getPrompt(force = false) {
560
+ if (!force && this.sysPrompt && this.noUseTollSysPrompt) {
561
+ return { sysPrompt: this.sysPrompt, noUseTollSysPrompt: this.noUseTollSysPrompt };
562
+ }
563
+ const context = {
564
+ cwd: this.runtime.env.cwd(),
565
+ os: this.runtime.env.osInfo(),
566
+ shell: this.runtime.env.shell(),
567
+ skills: await this.getSkills(),
568
+ customTools: this.customTools,
569
+ allowDefaultTools: this.allowDefaultTools,
570
+ customInstructions: this.customInstructions
571
+ };
572
+ this.sysPrompt = await this.promptManager.getSystemPrompt(context);
573
+ this.noUseTollSysPrompt = this.promptManager.getNoUseToolInstructions(context);
574
+ return { sysPrompt: this.sysPrompt, noUseTollSysPrompt: this.noUseTollSysPrompt };
575
+ }
576
+ /**
577
+ * 启动一个新的任务
578
+ */
579
+ async startTask(taskDescription) {
580
+ this.setState("thinking" /* THINKING */);
581
+ try {
582
+ await this.memory.clear();
583
+ this.loopCount = 0;
584
+ await this.memory.appendMessage({
585
+ role: "user",
586
+ content: taskDescription
587
+ });
588
+ await this.loop();
589
+ } catch (err) {
590
+ this.setState("error" /* ERROR */);
591
+ throw err;
592
+ }
593
+ }
594
+ async getSkills() {
595
+ const skillDir = this.skillDir;
596
+ const skillList = [];
597
+ if (!this.runtime.fs.fileExists(skillDir)) {
598
+ return skillList;
599
+ }
600
+ const files = await this.runtime.fs.readDir(skillDir);
601
+ const skills = files.filter((item) => item.isDirectory()).map((item) => item.name);
602
+ if (skills.length === 0) {
603
+ return [];
604
+ }
605
+ for (const skill of skills) {
606
+ try {
607
+ const skillPath = this.runtime.path.join(skillDir, skill);
608
+ const files2 = await this.runtime.fs.readDir(skillPath);
609
+ const skillFile = files2.map((item) => item.isFile()).find((f) => f.toLowerCase() === "skill.md");
610
+ if (skillFile) {
611
+ const mdPath = this.runtime.path.join(skillPath, skillFile);
612
+ const mdContent = await this.runtime.fs.readFile(mdPath);
613
+ const parsed = matter(mdContent);
614
+ if (parsed.data && parsed.data.description) {
615
+ let description = String(parsed.data.description).trim();
616
+ description = description.replace(/\s+/g, " ").trim();
617
+ if (description) {
618
+ skillList.push({
619
+ name: skill,
620
+ description
621
+ });
622
+ }
623
+ }
624
+ }
625
+ } catch (e) {
626
+ return skillList;
627
+ }
628
+ }
629
+ }
630
+ /**
631
+ * 核心任务循环
632
+ */
633
+ async loop() {
634
+ const { sysPrompt, noUseTollSysPrompt } = await this.getPrompt(true);
635
+ const { customTools, customToolNames } = this;
636
+ while (this.state === "thinking" /* THINKING */) {
637
+ this.loopCount++;
638
+ if (this.loopCount > this.maxLoopCount) {
639
+ await this.memory.appendMessage({
640
+ role: "user",
641
+ content: `[ERROR] You have exceeded the maximum loop limit of ${this.maxLoopCount} times. Please immediately call the agent_attempt_completion tool to return the final result. If you have pending user-specified tools to execute, you may run them first before calling agent_attempt_completion.`
642
+ });
643
+ }
644
+ const history = await this.memory.getHistory();
645
+ const stream = this.api.createMessage(sysPrompt, history);
646
+ let fullResponseText = "";
647
+ for await (const chunk of stream) {
648
+ if (chunk.type === "text" && chunk.text) {
649
+ fullResponseText += chunk.text;
650
+ }
651
+ if (this.onStreamChunk) {
652
+ this.onStreamChunk(chunk);
653
+ }
654
+ }
655
+ await this.memory.appendMessage({
656
+ role: "assistant",
657
+ content: fullResponseText
658
+ });
659
+ const parsedBlocks = parseAssistantMessageV2(fullResponseText, this.allToolParamNames);
660
+ const toolUses = parsedBlocks.filter((b) => b.type === "tool_use");
661
+ if (toolUses.length === 0) {
662
+ await this.memory.appendMessage({
663
+ role: "user",
664
+ content: noUseTollSysPrompt
665
+ });
666
+ } else {
667
+ const toolResults = [];
668
+ for (const tool of toolUses) {
669
+ if (this.onToolCall) {
670
+ const hookResult = await this.onToolCall(tool);
671
+ if (hookResult) {
672
+ toolResults.push({ tool, result: hookResult });
673
+ continue;
674
+ }
675
+ }
676
+ if (customToolNames.has(tool.name)) {
677
+ const customTool = customTools.find((t) => t.name === tool.name);
678
+ if (customTool.onCall) {
679
+ try {
680
+ const res = await customTool.onCall(tool.params);
681
+ toolResults.push({ tool, result: res });
682
+ } catch (error) {
683
+ toolResults.push({ tool, result: `Error: ${error.message}` });
684
+ }
685
+ } else {
686
+ toolResults.push({ tool, result: `Error: Custom tool "${tool.name}" does not have an onCall method.` });
687
+ }
688
+ continue;
689
+ }
690
+ if (tool.name === "agent_attempt_completion" /* ATTEMPT */) {
691
+ toolResults.push({ tool, result: "Task marked as completed." });
692
+ this.setState("finished" /* FINISHED */);
693
+ break;
694
+ } else if (tool.name === "agent_read_file" /* FILE_READ */) {
695
+ const path3 = tool.params.path;
696
+ if (path3) {
697
+ try {
698
+ const content = await this.runtime.fs.readFile(path3);
699
+ toolResults.push({ tool, result: content });
700
+ } catch (error) {
701
+ toolResults.push({ tool, result: `Error: ${error.message}` });
702
+ }
703
+ } else {
704
+ toolResults.push({ tool, result: "Error: No path provided." });
705
+ }
706
+ } else if (tool.name === "agent_execute_command" /* BASH */) {
707
+ const cmd = tool.params.command;
708
+ if (cmd) {
709
+ const result = await this.runtime.terminal.execCommand(cmd);
710
+ toolResults.push({ tool, result: `STDOUT: ${result.stdout}
711
+ STDERR: ${result.stderr}` });
712
+ }
713
+ } else if (tool.name === "agent_write_to_file" /* FILE_NEW */) {
714
+ const path3 = tool.params.path;
715
+ const content = tool.params.content;
716
+ if (path3 && content !== void 0) {
717
+ try {
718
+ await this.runtime.fs.writeFile(path3, content);
719
+ toolResults.push({ tool, result: `Successfully wrote to ${path3}` });
720
+ } catch (error) {
721
+ toolResults.push({ tool, result: `Error: ${error.message}` });
722
+ }
723
+ }
724
+ } else if (tool.name === "agent_list_files" /* LIST_FILES */) {
725
+ const path3 = tool.params.path || this.runtime.env.cwd();
726
+ try {
727
+ const files = await this.runtime.fs.readDir(path3);
728
+ toolResults.push({ tool, result: files.map((f) => f.name + (f.isDirectory() ? "/" : "")).join("\n") });
729
+ } catch (e) {
730
+ toolResults.push({ tool, result: `Error: ${e.message}` });
731
+ }
732
+ } else if (tool.name === "agent_replace_in_file" /* FILE_EDIT */) {
733
+ const path3 = tool.params.path;
734
+ const diff = tool.params.diff;
735
+ if (path3 && diff) {
736
+ try {
737
+ const content = await this.runtime.fs.readFile(path3);
738
+ const newContent = this.applyDiff(content, diff);
739
+ await this.runtime.fs.writeFile(path3, newContent);
740
+ toolResults.push({ tool, result: `Successfully replaced content in ${path3}` });
741
+ } catch (e) {
742
+ toolResults.push({ tool, result: `Error: ${e.message}` });
743
+ }
744
+ } else {
745
+ toolResults.push({ tool, result: "Error: Missing path or diff." });
746
+ }
747
+ } else if (tool.name === "agent_delete_file" /* FILE_DELETE */) {
748
+ const path3 = tool.params.path;
749
+ if (path3) {
750
+ try {
751
+ await this.runtime.fs.deleteFile(path3);
752
+ toolResults.push({ tool, result: `Successfully deleted ${path3}` });
753
+ } catch (e) {
754
+ toolResults.push({ tool, result: `Error: ${e.message}` });
755
+ }
756
+ } else {
757
+ toolResults.push({ tool, result: "Error: Missing path." });
758
+ }
759
+ } else if (tool.name === "agent_delete_directory" /* DIR_DELETE */) {
760
+ const path3 = tool.params.path;
761
+ if (path3) {
762
+ try {
763
+ await this.runtime.fs.deleteDirectory(path3);
764
+ toolResults.push({ tool, result: `Successfully deleted ${path3}` });
765
+ } catch (e) {
766
+ toolResults.push({ tool, result: `Error: ${e.message}` });
767
+ }
768
+ } else {
769
+ toolResults.push({ tool, result: "Error: Missing path." });
770
+ }
771
+ } else if (tool.name === "agent_ask_followup_question" /* ASK */) {
772
+ const question = tool.params.question;
773
+ toolResults.push({ tool, result: `Asking user: ${question}` });
774
+ this.setState("waiting_for_user" /* WAITING_FOR_USER */);
775
+ break;
776
+ } else if (tool.name === "agent_search_files" /* SEARCH */) {
777
+ const path3 = tool.params.path || this.runtime.env.cwd();
778
+ const regexStr = tool.params.regex;
779
+ const filePattern = tool.params.file_pattern;
780
+ if (regexStr && this.runtime.fs.searchFiles) {
781
+ try {
782
+ const result = await this.runtime.fs.searchFiles(path3, regexStr, filePattern);
783
+ toolResults.push({ tool, result: `${result}` });
784
+ } catch (e) {
785
+ toolResults.push({ tool, result: `Error: ${e.message}` });
786
+ }
787
+ } else {
788
+ toolResults.push({ tool, result: `Error: searchFiles not supported by runtime or missing regex.` });
789
+ }
790
+ } else if (tool.name === "agent_use_mcp_tool" /* MCP_USE */) {
791
+ const serverName = tool.params.server_name;
792
+ const toolName = tool.params.tool_name;
793
+ const args = tool.params.arguments;
794
+ if (this.mcp && serverName && toolName) {
795
+ try {
796
+ let parsedArgs = args;
797
+ if (typeof args === "string") {
798
+ parsedArgs = JSON.parse(args);
799
+ }
800
+ const result = await this.mcp.callTool(serverName, toolName, parsedArgs);
801
+ if (result.isError) {
802
+ toolResults.push({ tool, result: `Error executing MCP tool: ${JSON.stringify(result.content)}` });
803
+ } else {
804
+ toolResults.push({ tool, result: `${JSON.stringify(result.content)}` });
805
+ }
806
+ } catch (e) {
807
+ toolResults.push({ tool, result: `Error: ${e.message}` });
808
+ }
809
+ } else {
810
+ toolResults.push({ tool, result: `Error: MCP Manager not available or missing parameters.` });
811
+ }
812
+ } else if (tool.name === "agent_access_mcp_resource" /* MCP_ACCESS */) {
813
+ const serverName = tool.params.server_name;
814
+ const uri = tool.params.uri;
815
+ if (this.mcp && this.mcp.readResource && serverName && uri) {
816
+ try {
817
+ const result = await this.mcp.readResource(serverName, uri);
818
+ toolResults.push({ tool, result: `${JSON.stringify(result)}` });
819
+ } catch (e) {
820
+ toolResults.push({ tool, result: `Error: ${e.message}` });
821
+ }
822
+ } else {
823
+ toolResults.push({ tool, result: `Error: MCP Manager not available, readResource not implemented, or missing parameters.` });
824
+ }
825
+ } else if (tool.name === "agent_load_mcp_documentation" /* MCP_DOCS */) {
826
+ const docs = `MCP (Model Context Protocol) is used to connect to external tools/resources. To build one, typically you create an HTTP/stdio server responding to MCP defined JSON-RPC messages...`;
827
+ toolResults.push({ tool, result: docs });
828
+ } else if (tool.name === "agent_list_code_definition_names" /* LIST_CODE_DEF */) {
829
+ const path3 = tool.params.path || this.runtime.env.cwd();
830
+ try {
831
+ const result = await this.runtime.fs.searchFiles?.(path3, "^(class|function|const|let|var|export|interface|type)\\s+\\w+", "*.ts|*.js");
832
+ toolResults.push({ tool, result: `${result ? result : "No definitions found or searchFiles not supported."}` });
833
+ } catch (e) {
834
+ toolResults.push({ tool, result: `Error: ${e.message}` });
835
+ }
836
+ } else if (tool.name === "agent_web_fetch" /* WEB_FETCH */) {
837
+ const url = tool.params.url;
838
+ if (url) {
839
+ try {
840
+ const res = await fetch(url);
841
+ const text = await res.text();
842
+ toolResults.push({ tool, result: text.substring(0, 3e3) });
843
+ } catch (e) {
844
+ toolResults.push({ tool, result: `Error: ${e.message}` });
845
+ }
846
+ }
847
+ } else if (tool.name === "agent_focus_chain" /* TODO */) {
848
+ toolResults.push({ tool, result: `Focus chain updated successfully.` });
849
+ } else if (tool.name === "agent_plan_mode_respond" /* PLAN_MODE */ || tool.name === "agent_act_mode_respond" /* ACT_MODE */) {
850
+ toolResults.push({ tool, result: `Mode switch acknowledged.` });
851
+ } else if (tool.name === "agent_new_rule" /* NEW_RULE */) {
852
+ toolResults.push({ tool, result: `Rule recorded in current context.` });
853
+ } else if (tool.name === "agent_new_task" /* NEW_TASK */) {
854
+ toolResults.push({ tool, result: `New task request received. Terminating current task.` });
855
+ this.setState("finished" /* FINISHED */);
856
+ break;
857
+ } else if (tool.name === "agent_load_skill" /* LOAD_SKILL */) {
858
+ const skillName = tool.params.skill_name || tool.params.skill;
859
+ if (!skillName) {
860
+ toolResults.push({ tool, result: `"Error: Missing required parameter 'skill_name'. Please provide the name of the skill to activate."` });
861
+ } else {
862
+ const skillDir = this.skillDir;
863
+ const skillFilePath = this.runtime.path.join(skillDir, skillName, "SKILL.md");
864
+ try {
865
+ const fileExists = await this.runtime.fs.fileExists(skillFilePath);
866
+ if (!fileExists) {
867
+ toolResults.push({ tool, result: `Error: Skill "${skillName}" not found at ${skillFilePath}.` });
868
+ } else {
869
+ const content = await this.runtime.fs.readFile(skillFilePath);
870
+ toolResults.push({
871
+ tool,
872
+ result: `# Skill "${skillName}" is now active
873
+
874
+ ${content}
875
+
876
+ ---
877
+ IMPORTANT: The skill is now loaded. Do NOT call agent_load_skill again for this task. Simply follow the instructions above to complete the user's request.`
878
+ });
879
+ }
880
+ } catch (err) {
881
+ toolResults.push({ tool, result: `Error loading skill "${skillName}": ${err.message}` });
882
+ }
883
+ }
884
+ } else if (tool.name === "agent_browser_action" /* BROWSER */ || tool.name === "agent_web_search" /* WEB_SEARCH */ || tool.name === "agent_apply_patch" /* APPLY_PATCH */) {
885
+ toolResults.push({ tool, result: `This tool requires specific host integration. If you see this, the host environment has not implemented it yet.` });
886
+ } else if (tool.name === "agent_condense" /* CONDENSE */ || tool.name === "agent_summarize_task" /* SUMMARIZE_TASK */ || tool.name === "agent_report_bug" /* REPORT_BUG */ || tool.name === "agent_generate_explanation" /* GENERATE_EXPLANATION */) {
887
+ toolResults.push({ tool, result: `Action logged successfully.` });
888
+ } else {
889
+ toolResults.push({ tool, result: `Executed by host or unsupported.` });
890
+ }
891
+ }
892
+ if (this.state === "thinking" /* THINKING */ && toolResults.length > 0) {
893
+ const toolResultsContext = toolResults.map((tr) => `<${TOOL_RESULT_BLOCK} tool_name="${tr.tool.name}">
894
+ ${typeof tr.result === "string" ? tr.result.trim() : JSON.stringify(tr.result)}
895
+ </${TOOL_RESULT_BLOCK}>`).join("\n\n");
896
+ if (this.onStreamChunk) {
897
+ this.onStreamChunk({ type: "text", text: toolResultsContext });
898
+ }
899
+ await this.memory.appendMessage({
900
+ role: "user",
901
+ content: toolResultsContext
902
+ });
903
+ }
904
+ }
905
+ }
906
+ }
907
+ /**
908
+ * 简单的 Diff 解析与替换辅助方法
909
+ */
910
+ applyDiff(content, diff) {
911
+ const regex = /-------\s*SEARCH\r?\n(.*?)\r?\n=======\r?\n(.*?)\r?\n\+\+\+\+\+\+\+\s*REPLACE/gs;
912
+ let newContent = content;
913
+ let match;
914
+ let matchCount = 0;
915
+ while ((match = regex.exec(diff)) !== null) {
916
+ matchCount++;
917
+ const searchBlock = match[1];
918
+ const replaceBlock = match[2];
919
+ const idx = newContent.indexOf(searchBlock);
920
+ if (idx !== -1) {
921
+ newContent = newContent.substring(0, idx) + replaceBlock + newContent.substring(idx + searchBlock.length);
922
+ } else {
923
+ throw new Error(`Search block not found in file:
924
+ ${searchBlock.substring(0, 100)}...`);
925
+ }
926
+ }
927
+ if (matchCount === 0) {
928
+ throw new Error(`No valid SEARCH/REPLACE blocks found in the diff.`);
929
+ }
930
+ return newContent;
931
+ }
932
+ /**
933
+ * 恢复被中断的循环(例如等待用户输入/确认后继续)
934
+ */
935
+ async resume(userInput) {
936
+ if (userInput) {
937
+ await this.memory.appendMessage({
938
+ role: "user",
939
+ content: userInput
940
+ });
941
+ }
942
+ this.setState("thinking" /* THINKING */);
943
+ await this.loop();
944
+ }
945
+ async appendHistory(history) {
946
+ for (const message of history) {
947
+ await this.memory.appendMessage(message);
948
+ }
949
+ }
950
+ async getHistory() {
951
+ return this.memory.getHistory();
952
+ }
953
+ };
954
+ var NodeApiHandler = class {
955
+ config;
956
+ conversationId;
957
+ constructor(config) {
958
+ this.config = config;
959
+ }
960
+ getModelInfo() {
961
+ return {
962
+ providerId: this.config.providerId || "openai-compatible",
963
+ modelId: this.config.modelId
964
+ };
965
+ }
966
+ async *createMessage(systemPrompt, messages) {
967
+ let model;
968
+ if (this.config.providerId === "dify") {
969
+ const customDify = createDifyProvider({
970
+ baseURL: this.config.baseURL,
971
+ headers: this.config.headers,
972
+ fetch: this.config.fetch
973
+ });
974
+ model = customDify(this.config.modelId || "", {
975
+ apiKey: this.config.apiKey,
976
+ responseMode: "streaming"
977
+ });
978
+ } else {
979
+ const customOpenAI = createOpenAI({
980
+ baseURL: this.config.baseURL,
981
+ apiKey: this.config.apiKey,
982
+ headers: this.config.headers,
983
+ fetch: this.config.fetch
984
+ });
985
+ model = customOpenAI(this.config.modelId || "");
986
+ }
987
+ try {
988
+ const streamOptions = {
989
+ model,
990
+ headers: {
991
+ ...this.config.headers
992
+ },
993
+ allowSystemInMessages: true
994
+ };
995
+ if (this.config.providerId === "dify" && this.conversationId) {
996
+ streamOptions.headers["chat-id"] = this.conversationId;
997
+ }
998
+ streamOptions.messages = [
999
+ { role: "system", content: systemPrompt },
1000
+ ...messages.map((m) => ({
1001
+ role: m.role === "system" ? "system" : m.role === "user" ? "user" : "assistant",
1002
+ content: m.content
1003
+ }))
1004
+ ];
1005
+ const { fullStream } = streamText(streamOptions);
1006
+ for await (const part of fullStream) {
1007
+ if (this.config.providerId === "dify" && !this.conversationId && part?.providerMetadata?.difyWorkflowData?.conversationId || part?.providerMetadata?.dify?.conversationId) {
1008
+ this.conversationId = part.providerMetadata?.difyWorkflowData?.conversationId || part.providerMetadata?.dify?.conversationId;
1009
+ }
1010
+ if (part.type === "text-delta") {
1011
+ yield {
1012
+ type: "text",
1013
+ text: part.textDelta || part.text || ""
1014
+ };
1015
+ } else if (part.type === "finish") {
1016
+ yield {
1017
+ type: "usage",
1018
+ usage: {
1019
+ inputTokens: part.usage?.promptTokens || part.totalUsage?.promptTokens || part.totalUsage?.inputTokens || 0,
1020
+ outputTokens: part.usage?.completionTokens || part.totalUsage?.completionTokens || part.totalUsage?.outputTokens || 0
1021
+ }
1022
+ };
1023
+ } else if (part.type === "error") {
1024
+ yield {
1025
+ type: "error",
1026
+ error: part.error
1027
+ };
1028
+ }
1029
+ }
1030
+ } catch (err) {
1031
+ yield {
1032
+ type: "error",
1033
+ error: err
1034
+ };
1035
+ }
1036
+ }
1037
+ };
1038
+
1039
+ // src/prompt/NodePromptManager.ts
1040
+ var NodePromptManager = class {
1041
+ async getSystemPrompt(context) {
1042
+ let prompt = `# Role
1043
+ you are a highly skilled software engineer AI running in a Node.js/Desktop environment.
1044
+ You have FULL access to the local file system and can execute arbitrary shell commands on the user's machine.
1045
+
1046
+ # Capabilities & Rules
1047
+ 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.
1048
+ 2. **Terminal**: You can execute system commands (e.g., git, npm, python, file manipulation) directly.
1049
+ 3. **Context**: You are running on a real machine, meaning you have access to real environment variables, local servers (localhost), and local network.
1050
+ 4. **Destructive Actions**: Be extremely careful when executing commands that modify system state or delete files. Double-check paths and commands before execution.
1051
+ 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.
1052
+ 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.
1053
+ 7. **Communication**: Be concise and technical. Formulate your output strictly according to the tools' XML specification.
1054
+
1055
+ TOOL USE
1056
+
1057
+ 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.
1058
+
1059
+ # Tool Use Formatting
1060
+
1061
+ 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:
1062
+
1063
+ <tool_name>
1064
+ <parameter1_name>value1</parameter1_name>
1065
+ <parameter2_name>value2</parameter2_name>
1066
+ ...
1067
+ </tool_name>
1068
+
1069
+ For example:
1070
+
1071
+ <agent_read_file>
1072
+ <path>src/main.js</path>
1073
+ <task_progress>
1074
+ Checklist here (optional)
1075
+ </task_progress>
1076
+ </agent_read_file>
1077
+
1078
+ Always adhere to this format for the tool use to ensure proper parsing and execution.
1079
+ `;
1080
+ const skillsPrompt = await this.getSkillsPrompt(context.skills);
1081
+ if (skillsPrompt) {
1082
+ prompt += `
1083
+ ${skillsPrompt}
1084
+ `;
1085
+ }
1086
+ prompt += `
1087
+ ${this.getToolInstructions(context)}
1088
+ `;
1089
+ const envPrompt = this.getEnvironmentInfoPrompt(context);
1090
+ if (envPrompt) {
1091
+ prompt += `
1092
+ ${envPrompt}
1093
+ `;
1094
+ }
1095
+ if (context.customInstructions) {
1096
+ prompt += `
1097
+ # User Custom Instructions
1098
+ ${context.customInstructions}
1099
+ `;
1100
+ }
1101
+ return prompt;
1102
+ }
1103
+ getEnvironmentInfoPrompt(context) {
1104
+ let environmentPrompt = `<environment_details>
1105
+ # Environment Info
1106
+ - **Current Working Directory**: \`${context.cwd}\`
1107
+ - **Operating System**: \`${context.os}\`
1108
+ `;
1109
+ if (context.shell) {
1110
+ environmentPrompt += `- **Current Shell**: \`${context.shell}\`
1111
+ `;
1112
+ }
1113
+ return environmentPrompt + `
1114
+ </environment_details>`;
1115
+ }
1116
+ async getSkillsPrompt(skills) {
1117
+ if (!skills || skills.length === 0) return "";
1118
+ try {
1119
+ let prompt = `# Available Skills
1120
+ `;
1121
+ prompt += `You have access to the following skills. You can use the \`agent_load_skill\` tool to load any of them when needed.
1122
+ `;
1123
+ for (const skill of skills) {
1124
+ if (skill && skill.name && skill.description) {
1125
+ prompt += `- **${skill.name}**: ${skill.description}
1126
+ `;
1127
+ }
1128
+ }
1129
+ return prompt;
1130
+ } catch (e) {
1131
+ return "";
1132
+ }
1133
+ }
1134
+ getToolInstructions(context) {
1135
+ const allowDefaultTools = context.allowDefaultTools;
1136
+ const customTools = context.customTools || [];
1137
+ let useDefaultTools = [...defaultTools];
1138
+ if (allowDefaultTools) {
1139
+ useDefaultTools = defaultTools.filter((tool) => allowDefaultTools.includes(tool.name));
1140
+ }
1141
+ return `# Available Tools
1142
+ 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.
1143
+
1144
+ ${[...useDefaultTools, ...customTools].map((tool) => {
1145
+ return `### ${tool.name}
1146
+ Description: ${tool.description}
1147
+ Parameters:
1148
+ ${Object.entries(tool.params).map(([name, description]) => `- ${name}: ${description.replaceAll("${context.cwd}", context.cwd)}`).join("\n")}
1149
+ - 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)
1150
+ Usage:
1151
+ <${tool.name}>
1152
+ ${Object.entries(tool.params).map(([name, description]) => `<${name}>${description.replaceAll("${context.cwd}", context.cwd)}</${name}>`).join("\n")}
1153
+ <task_progress>Checklist here (optional)</task_progress>
1154
+ </${tool.name}>
1155
+ `;
1156
+ }).join("\n")}
1157
+
1158
+ # Tool Use Examples
1159
+ ${useDefaultTools.filter((item) => Boolean(item.example)).map((item) => item.example).join("\n")}}
1160
+
1161
+ # Tool Use Guidelines
1162
+
1163
+ 1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
1164
+ 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.
1165
+ 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.
1166
+ 4. Formulate your tool use using the XML format specified for each tool.
1167
+ 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:
1168
+ - Information about whether the tool succeeded or failed, along with any reasons for failure.
1169
+ - Linter errors that may have arisen due to the changes you made, which you'll need to address.
1170
+ - New terminal output in reaction to the changes, which you may need to consider or act upon.
1171
+ - Any other relevant feedback or information related to the tool use.
1172
+ 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.
1173
+
1174
+ 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:
1175
+ 1. Confirm the success of each step before proceeding.
1176
+ 2. Address any issues or errors that arise immediately.
1177
+ 3. Adapt your approach based on new information or unexpected results.
1178
+ 4. Ensure that each action builds correctly on the previous ones.
1179
+
1180
+ 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.
1181
+
1182
+ ====
1183
+
1184
+ UPDATING TASK PROGRESS
1185
+
1186
+ 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.
1187
+
1188
+ - When switching from PLAN MODE to ACT MODE, you must create a comprehensive todo list for the task using the task_progress parameter
1189
+ - Todo list updates should be done silently using the task_progress parameter - do not announce these updates to the user
1190
+ - Use standard Markdown checklist format: "- [ ]" for incomplete items and "- [x]" for completed items
1191
+ - 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.
1192
+ - For simple tasks, short checklists with even a single item are acceptable. For complex tasks, avoid making the checklist too long or verbose.
1193
+ - 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.
1194
+ - 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.
1195
+ - If a checklist is being used, be sure to update it any time a step has been completed.
1196
+ - The system will automatically include todo list context in your prompts when appropriate - these reminders are important.
1197
+
1198
+ Example:
1199
+ <agent_execute_command>
1200
+ <command>npm install react</command>
1201
+ <requires_approval>false</requires_approval>
1202
+ <task_progress>
1203
+ - [x] Set up project structure
1204
+ - [x] Install dependencies
1205
+ - [ ] Create components
1206
+ - [ ] Test application
1207
+ </task_progress>
1208
+ </agent_execute_command>
1209
+
1210
+ ====
1211
+
1212
+ EDITING FILES
1213
+
1214
+ 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.
1215
+
1216
+ # agent_write_to_file
1217
+
1218
+ ## Purpose
1219
+
1220
+ - Create a new file, or overwrite the entire contents of an existing file.
1221
+
1222
+ ## When to Use
1223
+
1224
+ - Initial file creation, such as when scaffolding a new project.
1225
+ - Overwriting large boilerplate files where you want to replace the entire content at once.
1226
+ - When the complexity or number of changes would make agent_replace_in_file unwieldy or error-prone.
1227
+ - When you need to completely restructure a file's content or change its fundamental organization.
1228
+
1229
+ ## Important Considerations
1230
+
1231
+ - Using agent_write_to_file requires providing the file's complete final content.
1232
+ - 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.
1233
+ - While agent_write_to_file should not be your default choice, don't hesitate to use it when the situation truly calls for it.
1234
+
1235
+ # agent_replace_in_file
1236
+
1237
+ ## Purpose
1238
+
1239
+ - Make targeted edits to specific parts of an existing file without overwriting the entire file.
1240
+
1241
+ ## When to Use
1242
+
1243
+ - Small, localized changes like updating a few lines, function implementations, changing variable names, modifying a section of text, etc.
1244
+ - Targeted improvements where only specific portions of the file's content needs to be altered.
1245
+ - Especially useful for long files where much of the file will remain unchanged.
1246
+
1247
+ ## Advantages
1248
+
1249
+ - More efficient for minor edits, since you don't need to supply the entire file content.
1250
+ - Reduces the chance of errors that can occur when overwriting large files.
1251
+
1252
+ # Choosing the Appropriate Tool
1253
+
1254
+ - **Default to agent_replace_in_file** for most changes. It's the safer, more precise option that minimizes potential issues.
1255
+ - **Use agent_write_to_file** when:
1256
+ - Creating new files
1257
+ - The changes are so extensive that using agent_replace_in_file would be more complex or risky
1258
+ - You need to completely reorganize or restructure a file
1259
+ - The file is relatively small and the changes affect most of its content
1260
+ - You're generating boilerplate or template files
1261
+
1262
+ # Auto-formatting Considerations
1263
+
1264
+ - After using either agent_write_to_file or agent_replace_in_file, the user's editor may automatically format the file
1265
+ - This auto-formatting may modify the file contents, for example:
1266
+ - Breaking single lines into multiple lines
1267
+ - Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
1268
+ - Converting single quotes to double quotes (or vice versa based on project preferences)
1269
+ - Organizing imports (e.g. sorting, grouping by type)
1270
+ - Adding/removing trailing commas in objects and arrays
1271
+ - Enforcing consistent brace style (e.g. same-line vs new-line)
1272
+ - Standardizing semicolon usage (adding or removing based on style)
1273
+ - The agent_write_to_file and agent_replace_in_file tool responses will include the final state of the file after any auto-formatting
1274
+ - 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.
1275
+
1276
+ # Workflow Tips
1277
+
1278
+ 1. Before editing, assess the scope of your changes and decide which tool to use.
1279
+ 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.
1280
+ 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.
1281
+ 4. For major overhauls or initial file creation, rely on agent_write_to_file.
1282
+ 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.
1283
+ 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.
1284
+
1285
+ ====
1286
+ `;
1287
+ }
1288
+ getNoUseToolInstructions(context) {
1289
+ return `[ERROR] You did not use a tool in your previous response! Please retry with a tool use.
1290
+
1291
+ # Reminder: Instructions for Tool Use
1292
+ 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:
1293
+ <tool_name>
1294
+ <parameter1_name>value1</parameter1_name>
1295
+ <parameter2_name>value2</parameter2_name>
1296
+ ...
1297
+ </tool_name>
1298
+ For example:
1299
+ <agent_attempt_completion>
1300
+ <result>
1301
+ I have completed the task...
1302
+ </result>
1303
+ </agent_attempt_completion>
1304
+ Always adhere to this format for all tool uses to ensure proper parsing and execution.
1305
+
1306
+ # Next Steps
1307
+
1308
+ If you have completed the user's task, use the attempt_completion tool.
1309
+ If you require additional information from the user, use the ask_followup_question tool.
1310
+ Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task.
1311
+ (This is an automated message, so do not respond to it conversationally.)
1312
+ ${this?.getEnvironmentInfoPrompt?.(context)}`;
1313
+ }
1314
+ };
1315
+ var NodeMemoryManager = class {
1316
+ filePath;
1317
+ maxMessages;
1318
+ /**
1319
+ * @param dbPath 存储历史记录的本地文件路径(例如:'./.cline_memory.json')
1320
+ * @param maxMessages 保留的最大消息数量,用于简单的历史截断(默认 150)
1321
+ */
1322
+ constructor(dbPath, maxMessages = 150) {
1323
+ this.filePath = path2.resolve(dbPath);
1324
+ this.maxMessages = maxMessages;
1325
+ }
1326
+ async ensureFile() {
1327
+ try {
1328
+ await fs2.access(this.filePath);
1329
+ } catch {
1330
+ const dir = path2.dirname(this.filePath);
1331
+ await fs2.mkdir(dir, { recursive: true });
1332
+ await fs2.writeFile(this.filePath, "[]", "utf-8");
1333
+ }
1334
+ }
1335
+ async readMessages() {
1336
+ await this.ensureFile();
1337
+ const data = await fs2.readFile(this.filePath, "utf-8");
1338
+ try {
1339
+ return JSON.parse(data);
1340
+ } catch {
1341
+ return [];
1342
+ }
1343
+ }
1344
+ async writeMessages(messages) {
1345
+ await this.ensureFile();
1346
+ await fs2.writeFile(this.filePath, JSON.stringify(messages, null, 2), "utf-8");
1347
+ }
1348
+ async getHistory() {
1349
+ return this.readMessages();
1350
+ }
1351
+ async appendMessage(message) {
1352
+ const messages = await this.readMessages();
1353
+ messages.push(message);
1354
+ await this.writeMessages(messages);
1355
+ await this.condenseHistory();
1356
+ }
1357
+ async condenseHistory() {
1358
+ const messages = await this.readMessages();
1359
+ if (messages.length > this.maxMessages) {
1360
+ const firstMessage = messages[0];
1361
+ const isFirstSystem = firstMessage && firstMessage.role === "system";
1362
+ const sliceCount = messages.length - this.maxMessages;
1363
+ let condensed;
1364
+ if (isFirstSystem) {
1365
+ condensed = [firstMessage, ...messages.slice(sliceCount + 1)];
1366
+ } else {
1367
+ condensed = messages.slice(sliceCount);
1368
+ }
1369
+ await this.writeMessages(condensed);
1370
+ }
1371
+ }
1372
+ async clear() {
1373
+ await this.writeMessages([]);
1374
+ }
1375
+ };
1376
+
1377
+ // src/index.ts
1378
+ var VERSION = "0.1.0";
1379
+ globalThis.AI_SDK_LOG_WARNINGS = false;
1380
+ var NodeMcpManager = class {
1381
+ config;
1382
+ clients = /* @__PURE__ */ new Map();
1383
+ transports = /* @__PURE__ */ new Map();
1384
+ serverStatuses = /* @__PURE__ */ new Map();
1385
+ constructor(config) {
1386
+ this.config = config;
1387
+ }
1388
+ /**
1389
+ * 初始化并连接所有的 MCP Servers
1390
+ */
1391
+ async init() {
1392
+ const connectPromises = Object.entries(this.config.servers).map(async ([name, serverConfig]) => {
1393
+ this.serverStatuses.set(name, { name, status: "connecting" });
1394
+ try {
1395
+ const transport = new StdioClientTransport({
1396
+ command: serverConfig.command,
1397
+ args: serverConfig.args,
1398
+ env: { ...process.env, ...serverConfig.env }
1399
+ });
1400
+ const client = new Client(
1401
+ {
1402
+ name: "cline-agent-sdk",
1403
+ version: "0.1.0"
1404
+ },
1405
+ {
1406
+ capabilities: {}
1407
+ }
1408
+ );
1409
+ await client.connect(transport);
1410
+ this.clients.set(name, client);
1411
+ this.transports.set(name, transport);
1412
+ this.serverStatuses.set(name, { name, status: "connected" });
1413
+ } catch (err) {
1414
+ this.serverStatuses.set(name, { name, status: "disconnected", error: err.message });
1415
+ }
1416
+ });
1417
+ await Promise.all(connectPromises);
1418
+ }
1419
+ getServers() {
1420
+ return Array.from(this.serverStatuses.values());
1421
+ }
1422
+ async getTools() {
1423
+ const allTools = [];
1424
+ for (const [serverName, client] of this.clients.entries()) {
1425
+ try {
1426
+ const response = await client.listTools();
1427
+ if (response && response.tools) {
1428
+ for (const tool of response.tools) {
1429
+ allTools.push({
1430
+ name: `${serverName}__${tool.name}`,
1431
+ description: tool.description,
1432
+ inputSchema: tool.inputSchema
1433
+ });
1434
+ }
1435
+ }
1436
+ } catch (err) {
1437
+ console.error(`Failed to get tools from MCP server [${serverName}]: ${err.message}`);
1438
+ }
1439
+ }
1440
+ return allTools;
1441
+ }
1442
+ async callTool(serverName, toolName, args) {
1443
+ const client = this.clients.get(serverName);
1444
+ if (!client) {
1445
+ return {
1446
+ content: [{ type: "text", text: `MCP Server [${serverName}] is not connected.` }],
1447
+ isError: true
1448
+ };
1449
+ }
1450
+ const prefix = `${serverName}__`;
1451
+ const actualToolName = toolName.startsWith(prefix) ? toolName.slice(prefix.length) : toolName;
1452
+ try {
1453
+ const response = await client.callTool({
1454
+ name: actualToolName,
1455
+ arguments: args
1456
+ });
1457
+ return {
1458
+ content: response.content,
1459
+ isError: !!response.isError
1460
+ };
1461
+ } catch (err) {
1462
+ return {
1463
+ content: [{ type: "text", text: `Error calling tool ${toolName} on server ${serverName}: ${err.message}` }],
1464
+ isError: true
1465
+ };
1466
+ }
1467
+ }
1468
+ async readResource(serverName, uri) {
1469
+ const client = this.clients.get(serverName);
1470
+ if (!client) {
1471
+ throw new Error(`MCP Server [${serverName}] is not connected.`);
1472
+ }
1473
+ try {
1474
+ const response = await client.readResource({ uri });
1475
+ return response.contents;
1476
+ } catch (err) {
1477
+ throw new Error(`Error reading resource ${uri} from server ${serverName}: ${err.message}`);
1478
+ }
1479
+ }
1480
+ /**
1481
+ * 断开并清理所有的 MCP Servers
1482
+ */
1483
+ async destroy() {
1484
+ for (const [name, client] of this.clients.entries()) {
1485
+ try {
1486
+ await client.close();
1487
+ } catch (e) {
1488
+ }
1489
+ }
1490
+ for (const [name, transport] of this.transports.entries()) {
1491
+ try {
1492
+ await transport.close();
1493
+ } catch (e) {
1494
+ }
1495
+ }
1496
+ this.clients.clear();
1497
+ this.transports.clear();
1498
+ this.serverStatuses.clear();
1499
+ }
1500
+ };
1501
+
1502
+ // src/runtime/nodeRuntime.ts
1503
+ var execAsync = promisify(exec);
1504
+ var DefaultNodeRuntime = class {
1505
+ fs = {
1506
+ readFile: async (filepath) => fs2.readFile(filepath, "utf-8"),
1507
+ writeFile: async (filepath, content) => {
1508
+ await fs2.mkdir(path2.dirname(filepath), { recursive: true });
1509
+ await fs2.writeFile(filepath, content, "utf-8");
1510
+ },
1511
+ deleteFile: (filepath) => fs2.unlink(filepath),
1512
+ deleteDirectory: (dirpath) => fs2.rm(dirpath, { recursive: true, force: true }),
1513
+ fileExists: async (filepath) => {
1514
+ try {
1515
+ await fs2.access(filepath);
1516
+ return true;
1517
+ } catch {
1518
+ return false;
1519
+ }
1520
+ },
1521
+ readDir: (dirpath) => fs2.readdir(dirpath, { withFileTypes: true }),
1522
+ mkdir: async (dirpath) => {
1523
+ await fs2.mkdir(dirpath, { recursive: true });
1524
+ }
1525
+ };
1526
+ path = {
1527
+ join: (...paths) => path2.join(...paths)
1528
+ };
1529
+ env = {
1530
+ get: (key) => process.env[key],
1531
+ cwd: () => process.cwd(),
1532
+ osInfo: () => `${os.type()} ${os.release()} ${os.arch()}`,
1533
+ shell: () => process.env.SHELL || process.env.ComSpec || "unknown"
1534
+ };
1535
+ terminal = {
1536
+ execCommand: async (command, options) => {
1537
+ try {
1538
+ const { stdout, stderr } = await execAsync(command, { cwd: options?.cwd || process.cwd() });
1539
+ return { stdout, stderr, exitCode: 0 };
1540
+ } catch (err) {
1541
+ return { stdout: err.stdout || "", stderr: err.stderr || err.message, exitCode: err.code || 1 };
1542
+ }
1543
+ }
1544
+ };
1545
+ };
1546
+ function createNodeAgent(options) {
1547
+ const runtime = new DefaultNodeRuntime();
1548
+ const api = new NodeApiHandler(options.apiConfig);
1549
+ const memory = options.memory || new NodeMemoryManager(options.dbPath || path2.join(runtime.env.cwd(), ".cline_memory.json"));
1550
+ const customTools = options.customTools || [];
1551
+ const customToolNames = new Set(customTools.map((t) => t.name));
1552
+ const promptManager = new NodePromptManager();
1553
+ const agent = new ClineAgent({
1554
+ runtime,
1555
+ api,
1556
+ promptManager,
1557
+ memory,
1558
+ customTools,
1559
+ allowDefaultTools: options.allowDefaultTools,
1560
+ maxLoopCount: options.maxLoopCount,
1561
+ customInstructions: options.customInstructions
1562
+ });
1563
+ agent.onToolCall = async (tool) => {
1564
+ if (customToolNames.has(tool.name)) {
1565
+ const customTool = customTools.find((t) => t.name === tool.name);
1566
+ if (customTool.onCall) {
1567
+ return customTool.onCall(tool.params);
1568
+ }
1569
+ return `Error: Custom tool "${tool.name}" does not have an onCall method.`;
1570
+ }
1571
+ };
1572
+ return agent;
1573
+ }
1574
+
1575
+ export { AgentDefaultTool, AgentState, ClineAgent, DefaultNodeRuntime, NodeMcpManager, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, createNodeAgent, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames };
1576
+ //# sourceMappingURL=nodeRuntime.mjs.map
1577
+ //# sourceMappingURL=nodeRuntime.mjs.map