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