@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.
package/dist/index.mjs CHANGED
@@ -1,17 +1,5 @@
1
1
  import { nanoid } from 'nanoid';
2
- import { streamText } from 'ai';
3
- import { createOpenAI } from '@ai-sdk/openai';
4
- import { createDifyProvider } from 'dify-ai-provider';
5
2
  import matter from 'gray-matter';
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 '@modelcontextprotocol/sdk/client/index.js';
12
- import '@modelcontextprotocol/sdk/client/stdio.js';
13
- import { Volume, createFsFromVolume } from 'memfs';
14
- import path3 from 'path-browserify';
15
3
 
16
4
  // src/shared/tools.ts
17
5
  var AgentDefaultTool = /* @__PURE__ */ ((AgentDefaultTool2) => {
@@ -477,728 +465,6 @@ var toolParamNames = [
477
465
  "start_line",
478
466
  "end_line"
479
467
  ];
480
-
481
- // src/prompt/NodePromptManager.ts
482
- var NodePromptManager = class {
483
- async getSystemPrompt(context) {
484
- let prompt = `# Role
485
- you are a highly skilled software engineer AI running in a Node.js/Desktop environment.
486
- You have FULL access to the local file system and can execute arbitrary shell commands on the user's machine.
487
-
488
- # Capabilities & Rules
489
- 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.
490
- 2. **Terminal**: You can execute system commands (e.g., git, npm, python, file manipulation) directly.
491
- 3. **Context**: You are running on a real machine, meaning you have access to real environment variables, local servers (localhost), and local network.
492
- 4. **Destructive Actions**: Be extremely careful when executing commands that modify system state or delete files. Double-check paths and commands before execution.
493
- 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.
494
- 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.
495
- 7. **Communication**: Be concise and technical. Formulate your output strictly according to the tools' XML specification.
496
-
497
- TOOL USE
498
-
499
- 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.
500
-
501
- # Tool Use Formatting
502
-
503
- 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:
504
-
505
- <tool_name>
506
- <parameter1_name>value1</parameter1_name>
507
- <parameter2_name>value2</parameter2_name>
508
- ...
509
- </tool_name>
510
-
511
- For example:
512
-
513
- <agent_read_file>
514
- <path>src/main.js</path>
515
- <task_progress>
516
- Checklist here (optional)
517
- </task_progress>
518
- </agent_read_file>
519
-
520
- Always adhere to this format for the tool use to ensure proper parsing and execution.
521
- `;
522
- const skillsPrompt = await this.getSkillsPrompt(context.skills);
523
- if (skillsPrompt) {
524
- prompt += `
525
- ${skillsPrompt}
526
- `;
527
- }
528
- prompt += `
529
- ${this.getToolInstructions(context)}
530
- `;
531
- const envPrompt = this.getEnvironmentInfoPrompt(context);
532
- if (envPrompt) {
533
- prompt += `
534
- ${envPrompt}
535
- `;
536
- }
537
- if (context.customInstructions) {
538
- prompt += `
539
- # User Custom Instructions
540
- ${context.customInstructions}
541
- `;
542
- }
543
- return prompt;
544
- }
545
- getEnvironmentInfoPrompt(context) {
546
- let environmentPrompt = `<environment_details>
547
- # Environment Info
548
- - **Current Working Directory**: \`${context.cwd}\`
549
- - **Operating System**: \`${context.os}\`
550
- `;
551
- if (context.shell) {
552
- environmentPrompt += `- **Current Shell**: \`${context.shell}\`
553
- `;
554
- }
555
- return environmentPrompt + `
556
- </environment_details>`;
557
- }
558
- async getSkillsPrompt(skills) {
559
- if (!skills || skills.length === 0) return "";
560
- try {
561
- let prompt = `# Available Skills
562
- `;
563
- prompt += `You have access to the following skills. You can use the \`agent_load_skill\` tool to load any of them when needed.
564
- `;
565
- for (const skill of skills) {
566
- if (skill && skill.name && skill.description) {
567
- prompt += `- **${skill.name}**: ${skill.description}
568
- `;
569
- }
570
- }
571
- return prompt;
572
- } catch (e) {
573
- return "";
574
- }
575
- }
576
- getToolInstructions(context) {
577
- const allowDefaultTools = context.allowDefaultTools;
578
- const customTools = context.customTools || [];
579
- let useDefaultTools = [...defaultTools];
580
- if (allowDefaultTools) {
581
- useDefaultTools = defaultTools.filter((tool) => allowDefaultTools.includes(tool.name));
582
- }
583
- return `# Available Tools
584
- 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.
585
-
586
- ${[...useDefaultTools, ...customTools].map((tool) => {
587
- return `### ${tool.name}
588
- Description: ${tool.description}
589
- Parameters:
590
- ${Object.entries(tool.params).map(([name, description]) => `- ${name}: ${description.replaceAll("${context.cwd}", context.cwd)}`).join("\n")}
591
- - 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)
592
- Usage:
593
- <${tool.name}>
594
- ${Object.entries(tool.params).map(([name, description]) => `<${name}>${description.replaceAll("${context.cwd}", context.cwd)}</${name}>`).join("\n")}
595
- <task_progress>Checklist here (optional)</task_progress>
596
- </${tool.name}>
597
- `;
598
- }).join("\n")}
599
-
600
- # Tool Use Examples
601
- ${useDefaultTools.filter((item) => Boolean(item.example)).map((item) => item.example).join("\n")}}
602
-
603
- # Tool Use Guidelines
604
-
605
- 1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
606
- 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.
607
- 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.
608
- 4. Formulate your tool use using the XML format specified for each tool.
609
- 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:
610
- - Information about whether the tool succeeded or failed, along with any reasons for failure.
611
- - Linter errors that may have arisen due to the changes you made, which you'll need to address.
612
- - New terminal output in reaction to the changes, which you may need to consider or act upon.
613
- - Any other relevant feedback or information related to the tool use.
614
- 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.
615
-
616
- 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:
617
- 1. Confirm the success of each step before proceeding.
618
- 2. Address any issues or errors that arise immediately.
619
- 3. Adapt your approach based on new information or unexpected results.
620
- 4. Ensure that each action builds correctly on the previous ones.
621
-
622
- 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.
623
-
624
- ====
625
-
626
- UPDATING TASK PROGRESS
627
-
628
- 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.
629
-
630
- - When switching from PLAN MODE to ACT MODE, you must create a comprehensive todo list for the task using the task_progress parameter
631
- - Todo list updates should be done silently using the task_progress parameter - do not announce these updates to the user
632
- - Use standard Markdown checklist format: "- [ ]" for incomplete items and "- [x]" for completed items
633
- - 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.
634
- - For simple tasks, short checklists with even a single item are acceptable. For complex tasks, avoid making the checklist too long or verbose.
635
- - 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.
636
- - 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.
637
- - If a checklist is being used, be sure to update it any time a step has been completed.
638
- - The system will automatically include todo list context in your prompts when appropriate - these reminders are important.
639
-
640
- Example:
641
- <agent_execute_command>
642
- <command>npm install react</command>
643
- <requires_approval>false</requires_approval>
644
- <task_progress>
645
- - [x] Set up project structure
646
- - [x] Install dependencies
647
- - [ ] Create components
648
- - [ ] Test application
649
- </task_progress>
650
- </agent_execute_command>
651
-
652
- ====
653
-
654
- EDITING FILES
655
-
656
- 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.
657
-
658
- # agent_write_to_file
659
-
660
- ## Purpose
661
-
662
- - Create a new file, or overwrite the entire contents of an existing file.
663
-
664
- ## When to Use
665
-
666
- - Initial file creation, such as when scaffolding a new project.
667
- - Overwriting large boilerplate files where you want to replace the entire content at once.
668
- - When the complexity or number of changes would make agent_replace_in_file unwieldy or error-prone.
669
- - When you need to completely restructure a file's content or change its fundamental organization.
670
-
671
- ## Important Considerations
672
-
673
- - Using agent_write_to_file requires providing the file's complete final content.
674
- - 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.
675
- - While agent_write_to_file should not be your default choice, don't hesitate to use it when the situation truly calls for it.
676
-
677
- # agent_replace_in_file
678
-
679
- ## Purpose
680
-
681
- - Make targeted edits to specific parts of an existing file without overwriting the entire file.
682
-
683
- ## When to Use
684
-
685
- - Small, localized changes like updating a few lines, function implementations, changing variable names, modifying a section of text, etc.
686
- - Targeted improvements where only specific portions of the file's content needs to be altered.
687
- - Especially useful for long files where much of the file will remain unchanged.
688
-
689
- ## Advantages
690
-
691
- - More efficient for minor edits, since you don't need to supply the entire file content.
692
- - Reduces the chance of errors that can occur when overwriting large files.
693
-
694
- # Choosing the Appropriate Tool
695
-
696
- - **Default to agent_replace_in_file** for most changes. It's the safer, more precise option that minimizes potential issues.
697
- - **Use agent_write_to_file** when:
698
- - Creating new files
699
- - The changes are so extensive that using agent_replace_in_file would be more complex or risky
700
- - You need to completely reorganize or restructure a file
701
- - The file is relatively small and the changes affect most of its content
702
- - You're generating boilerplate or template files
703
-
704
- # Auto-formatting Considerations
705
-
706
- - After using either agent_write_to_file or agent_replace_in_file, the user's editor may automatically format the file
707
- - This auto-formatting may modify the file contents, for example:
708
- - Breaking single lines into multiple lines
709
- - Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
710
- - Converting single quotes to double quotes (or vice versa based on project preferences)
711
- - Organizing imports (e.g. sorting, grouping by type)
712
- - Adding/removing trailing commas in objects and arrays
713
- - Enforcing consistent brace style (e.g. same-line vs new-line)
714
- - Standardizing semicolon usage (adding or removing based on style)
715
- - The agent_write_to_file and agent_replace_in_file tool responses will include the final state of the file after any auto-formatting
716
- - 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.
717
-
718
- # Workflow Tips
719
-
720
- 1. Before editing, assess the scope of your changes and decide which tool to use.
721
- 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.
722
- 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.
723
- 4. For major overhauls or initial file creation, rely on agent_write_to_file.
724
- 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.
725
- 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.
726
-
727
- ====
728
- `;
729
- }
730
- getNoUseToolInstructions(context) {
731
- return `[ERROR] You did not use a tool in your previous response! Please retry with a tool use.
732
-
733
- # Reminder: Instructions for Tool Use
734
- 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:
735
- <tool_name>
736
- <parameter1_name>value1</parameter1_name>
737
- <parameter2_name>value2</parameter2_name>
738
- ...
739
- </tool_name>
740
- For example:
741
- <agent_attempt_completion>
742
- <result>
743
- I have completed the task...
744
- </result>
745
- </agent_attempt_completion>
746
- Always adhere to this format for all tool uses to ensure proper parsing and execution.
747
-
748
- # Next Steps
749
-
750
- If you have completed the user's task, use the attempt_completion tool.
751
- If you require additional information from the user, use the ask_followup_question tool.
752
- Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task.
753
- (This is an automated message, so do not respond to it conversationally.)
754
- ${this?.getEnvironmentInfoPrompt?.(context)}`;
755
- }
756
- };
757
-
758
- // src/prompt/WebPromptManager.ts
759
- var WebPromptManager = class {
760
- async getSystemPrompt(context) {
761
- let prompt = `# Role
762
- you are a highly skilled software engineer AI running in a Node.js/Desktop environment.
763
- You have FULL access to the local file system and can execute arbitrary shell commands on the user's machine.
764
-
765
- # Capabilities & Rules
766
- 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.
767
- 2. **Terminal**: You can execute system commands (e.g., git, npm, python, file manipulation) directly.
768
- 3. **Context**: You are running on a real machine, meaning you have access to real environment variables, local servers (localhost), and local network.
769
- 4. **Destructive Actions**: Be extremely careful when executing commands that modify system state or delete files. Double-check paths and commands before execution.
770
- 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.
771
- 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.
772
- 7. **Communication**: Be concise and technical. Formulate your output strictly according to the tools' XML specification.
773
-
774
- TOOL USE
775
-
776
- 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.
777
-
778
- # Tool Use Formatting
779
-
780
- 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:
781
-
782
- <tool_name>
783
- <parameter1_name>value1</parameter1_name>
784
- <parameter2_name>value2</parameter2_name>
785
- ...
786
- </tool_name>
787
-
788
- For example:
789
-
790
- <agent_read_file>
791
- <path>src/main.js</path>
792
- <task_progress>
793
- Checklist here (optional)
794
- </task_progress>
795
- </agent_read_file>
796
-
797
- Always adhere to this format for the tool use to ensure proper parsing and execution.
798
- `;
799
- const skillsPrompt = await this.getSkillsPrompt(context.skills);
800
- if (skillsPrompt) {
801
- prompt += `
802
- ${skillsPrompt}
803
- `;
804
- }
805
- prompt += `
806
- ${this.getToolInstructions(context)}
807
- `;
808
- const envPrompt = this.getEnvironmentInfoPrompt(context);
809
- if (envPrompt) {
810
- prompt += `
811
- ${envPrompt}
812
- `;
813
- }
814
- if (context.customInstructions) {
815
- prompt += `
816
- # User Custom Instructions
817
- ${context.customInstructions}
818
- `;
819
- }
820
- return prompt;
821
- }
822
- getEnvironmentInfoPrompt(context) {
823
- let environmentPrompt = `<environment_details>
824
- # Environment Info
825
- - **Current Working Directory**: \`${context.cwd}\`
826
- - **Operating System**: \`${context.os}\`
827
- `;
828
- if (context.shell) {
829
- environmentPrompt += `- **Current Shell**: \`${context.shell}\`
830
- `;
831
- }
832
- return environmentPrompt + `
833
- </environment_details>`;
834
- }
835
- async getSkillsPrompt(skills) {
836
- if (!skills || skills.length === 0) return "";
837
- try {
838
- let prompt = `# Available Skills
839
- `;
840
- prompt += `You have access to the following skills. You can use the \`agent_load_skill\` tool to load any of them when needed.
841
- `;
842
- for (const skill of skills) {
843
- if (skill && skill.name && skill.description) {
844
- prompt += `- **${skill.name}**: ${skill.description}
845
- `;
846
- }
847
- }
848
- return prompt;
849
- } catch (e) {
850
- return "";
851
- }
852
- }
853
- getToolInstructions(context) {
854
- const allowDefaultTools = context.allowDefaultTools;
855
- const customTools = context.customTools || [];
856
- let useDefaultTools = [...defaultTools];
857
- if (allowDefaultTools) {
858
- useDefaultTools = defaultTools.filter((tool) => allowDefaultTools.includes(tool.name));
859
- }
860
- return `# Available Tools
861
- 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.
862
-
863
- ${[...useDefaultTools, ...customTools].map((tool) => {
864
- return `### ${tool.name}
865
- Description: ${tool.description}
866
- Parameters:
867
- ${Object.entries(tool.params).map(([name, description]) => `- ${name}: ${description.replaceAll("${context.cwd}", context.cwd)}`).join("\n")}
868
- - 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)
869
- Usage:
870
- <${tool.name}>
871
- ${Object.entries(tool.params).map(([name, description]) => `<${name}>${description.replaceAll("${context.cwd}", context.cwd)}</${name}>`).join("\n")}
872
- <task_progress>Checklist here (optional)</task_progress>
873
- </${tool.name}>
874
- `;
875
- }).join("\n")}
876
-
877
- # Tool Use Examples
878
- ${useDefaultTools.filter((item) => Boolean(item.example)).map((item) => item.example).join("\n")}}
879
-
880
- # Tool Use Guidelines
881
-
882
- 1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
883
- 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.
884
- 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.
885
- 4. Formulate your tool use using the XML format specified for each tool.
886
- 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:
887
- - Information about whether the tool succeeded or failed, along with any reasons for failure.
888
- - Linter errors that may have arisen due to the changes you made, which you'll need to address.
889
- - New terminal output in reaction to the changes, which you may need to consider or act upon.
890
- - Any other relevant feedback or information related to the tool use.
891
- 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.
892
-
893
- 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:
894
- 1. Confirm the success of each step before proceeding.
895
- 2. Address any issues or errors that arise immediately.
896
- 3. Adapt your approach based on new information or unexpected results.
897
- 4. Ensure that each action builds correctly on the previous ones.
898
-
899
- 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.
900
-
901
- ====
902
-
903
- UPDATING TASK PROGRESS
904
-
905
- 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.
906
-
907
- - When switching from PLAN MODE to ACT MODE, you must create a comprehensive todo list for the task using the task_progress parameter
908
- - Todo list updates should be done silently using the task_progress parameter - do not announce these updates to the user
909
- - Use standard Markdown checklist format: "- [ ]" for incomplete items and "- [x]" for completed items
910
- - 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.
911
- - For simple tasks, short checklists with even a single item are acceptable. For complex tasks, avoid making the checklist too long or verbose.
912
- - 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.
913
- - 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.
914
- - If a checklist is being used, be sure to update it any time a step has been completed.
915
- - The system will automatically include todo list context in your prompts when appropriate - these reminders are important.
916
-
917
- Example:
918
- <agent_execute_command>
919
- <command>npm install react</command>
920
- <requires_approval>false</requires_approval>
921
- <task_progress>
922
- - [x] Set up project structure
923
- - [x] Install dependencies
924
- - [ ] Create components
925
- - [ ] Test application
926
- </task_progress>
927
- </agent_execute_command>
928
-
929
- ====
930
-
931
- EDITING FILES
932
-
933
- 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.
934
-
935
- # agent_write_to_file
936
-
937
- ## Purpose
938
-
939
- - Create a new file, or overwrite the entire contents of an existing file.
940
-
941
- ## When to Use
942
-
943
- - Initial file creation, such as when scaffolding a new project.
944
- - Overwriting large boilerplate files where you want to replace the entire content at once.
945
- - When the complexity or number of changes would make agent_replace_in_file unwieldy or error-prone.
946
- - When you need to completely restructure a file's content or change its fundamental organization.
947
-
948
- ## Important Considerations
949
-
950
- - Using agent_write_to_file requires providing the file's complete final content.
951
- - 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.
952
- - While agent_write_to_file should not be your default choice, don't hesitate to use it when the situation truly calls for it.
953
-
954
- # agent_replace_in_file
955
-
956
- ## Purpose
957
-
958
- - Make targeted edits to specific parts of an existing file without overwriting the entire file.
959
-
960
- ## When to Use
961
-
962
- - Small, localized changes like updating a few lines, function implementations, changing variable names, modifying a section of text, etc.
963
- - Targeted improvements where only specific portions of the file's content needs to be altered.
964
- - Especially useful for long files where much of the file will remain unchanged.
965
-
966
- ## Advantages
967
-
968
- - More efficient for minor edits, since you don't need to supply the entire file content.
969
- - Reduces the chance of errors that can occur when overwriting large files.
970
-
971
- # Choosing the Appropriate Tool
972
-
973
- - **Default to agent_replace_in_file** for most changes. It's the safer, more precise option that minimizes potential issues.
974
- - **Use agent_write_to_file** when:
975
- - Creating new files
976
- - The changes are so extensive that using agent_replace_in_file would be more complex or risky
977
- - You need to completely reorganize or restructure a file
978
- - The file is relatively small and the changes affect most of its content
979
- - You're generating boilerplate or template files
980
-
981
- # Auto-formatting Considerations
982
-
983
- - After using either agent_write_to_file or agent_replace_in_file, the user's editor may automatically format the file
984
- - This auto-formatting may modify the file contents, for example:
985
- - Breaking single lines into multiple lines
986
- - Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
987
- - Converting single quotes to double quotes (or vice versa based on project preferences)
988
- - Organizing imports (e.g. sorting, grouping by type)
989
- - Adding/removing trailing commas in objects and arrays
990
- - Enforcing consistent brace style (e.g. same-line vs new-line)
991
- - Standardizing semicolon usage (adding or removing based on style)
992
- - The agent_write_to_file and agent_replace_in_file tool responses will include the final state of the file after any auto-formatting
993
- - 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.
994
-
995
- # Workflow Tips
996
-
997
- 1. Before editing, assess the scope of your changes and decide which tool to use.
998
- 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.
999
- 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.
1000
- 4. For major overhauls or initial file creation, rely on agent_write_to_file.
1001
- 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.
1002
- 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.
1003
-
1004
- ====
1005
- `;
1006
- }
1007
- getNoUseToolInstructions(context) {
1008
- return `[ERROR] You did not use a tool in your previous response! Please retry with a tool use.
1009
-
1010
- # Reminder: Instructions for Tool Use
1011
- 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:
1012
- <tool_name>
1013
- <parameter1_name>value1</parameter1_name>
1014
- <parameter2_name>value2</parameter2_name>
1015
- ...
1016
- </tool_name>
1017
- For example:
1018
- <agent_attempt_completion>
1019
- <result>
1020
- I have completed the task...
1021
- </result>
1022
- </agent_attempt_completion>
1023
- Always adhere to this format for all tool uses to ensure proper parsing and execution.
1024
-
1025
- # Next Steps
1026
-
1027
- If you have completed the user's task, use the attempt_completion tool.
1028
- If you require additional information from the user, use the ask_followup_question tool.
1029
- Otherwise, if you have not completed the task and do not need additional information, then proceed with the next step of the task.
1030
- (This is an automated message, so do not respond to it conversationally.)
1031
- ${this?.getEnvironmentInfoPrompt?.(context)}`;
1032
- }
1033
- };
1034
- var NodeApiHandler = class {
1035
- config;
1036
- conversationId;
1037
- constructor(config) {
1038
- this.config = config;
1039
- }
1040
- getModelInfo() {
1041
- return {
1042
- providerId: this.config.providerId || "openai-compatible",
1043
- modelId: this.config.modelId
1044
- };
1045
- }
1046
- async *createMessage(systemPrompt, messages) {
1047
- let model;
1048
- if (this.config.providerId === "dify") {
1049
- const customDify = createDifyProvider({
1050
- baseURL: this.config.baseURL,
1051
- headers: this.config.headers,
1052
- fetch: this.config.fetch
1053
- });
1054
- model = customDify(this.config.modelId || "", {
1055
- apiKey: this.config.apiKey,
1056
- responseMode: "streaming"
1057
- });
1058
- } else {
1059
- const customOpenAI = createOpenAI({
1060
- baseURL: this.config.baseURL,
1061
- apiKey: this.config.apiKey,
1062
- headers: this.config.headers,
1063
- fetch: this.config.fetch
1064
- });
1065
- model = customOpenAI(this.config.modelId || "");
1066
- }
1067
- try {
1068
- const streamOptions = {
1069
- model,
1070
- headers: {
1071
- ...this.config.headers
1072
- },
1073
- allowSystemInMessages: true
1074
- };
1075
- if (this.config.providerId === "dify" && this.conversationId) {
1076
- streamOptions.headers["chat-id"] = this.conversationId;
1077
- }
1078
- streamOptions.messages = [
1079
- { role: "system", content: systemPrompt },
1080
- ...messages.map((m) => ({
1081
- role: m.role === "system" ? "system" : m.role === "user" ? "user" : "assistant",
1082
- content: m.content
1083
- }))
1084
- ];
1085
- const { fullStream } = streamText(streamOptions);
1086
- for await (const part of fullStream) {
1087
- if (this.config.providerId === "dify" && !this.conversationId && part?.providerMetadata?.difyWorkflowData?.conversationId || part?.providerMetadata?.dify?.conversationId) {
1088
- this.conversationId = part.providerMetadata?.difyWorkflowData?.conversationId || part.providerMetadata?.dify?.conversationId;
1089
- }
1090
- if (part.type === "text-delta") {
1091
- yield {
1092
- type: "text",
1093
- text: part.textDelta || part.text || ""
1094
- };
1095
- } else if (part.type === "finish") {
1096
- yield {
1097
- type: "usage",
1098
- usage: {
1099
- inputTokens: part.usage?.promptTokens || part.totalUsage?.promptTokens || part.totalUsage?.inputTokens || 0,
1100
- outputTokens: part.usage?.completionTokens || part.totalUsage?.completionTokens || part.totalUsage?.outputTokens || 0
1101
- }
1102
- };
1103
- } else if (part.type === "error") {
1104
- yield {
1105
- type: "error",
1106
- error: part.error
1107
- };
1108
- }
1109
- }
1110
- } catch (err) {
1111
- yield {
1112
- type: "error",
1113
- error: err
1114
- };
1115
- }
1116
- }
1117
- };
1118
- var WebApiHandler = class {
1119
- config;
1120
- conversationId;
1121
- constructor(config) {
1122
- this.config = config;
1123
- }
1124
- getModelInfo() {
1125
- return {
1126
- providerId: this.config.providerId || "openai-compatible",
1127
- modelId: this.config.modelId
1128
- };
1129
- }
1130
- async *createMessage(systemPrompt, messages) {
1131
- let model;
1132
- if (this.config.providerId === "dify") {
1133
- const customDify = createDifyProvider({
1134
- baseURL: this.config.baseURL,
1135
- headers: this.config.headers,
1136
- fetch: this.config.fetch
1137
- });
1138
- model = customDify(this.config.modelId || "", {
1139
- apiKey: this.config.apiKey,
1140
- responseMode: "streaming"
1141
- });
1142
- } else {
1143
- const customOpenAI = createOpenAI({
1144
- baseURL: this.config.baseURL,
1145
- apiKey: this.config.apiKey,
1146
- headers: this.config.headers,
1147
- fetch: this.config.fetch
1148
- });
1149
- model = customOpenAI(this.config.modelId || "");
1150
- }
1151
- try {
1152
- const streamOptions = {
1153
- model,
1154
- headers: {
1155
- ...this.config.headers
1156
- },
1157
- allowSystemInMessages: true
1158
- };
1159
- if (this.config.providerId === "dify" && this.conversationId) {
1160
- streamOptions.headers["chat-id"] = this.conversationId;
1161
- }
1162
- streamOptions.messages = [
1163
- { role: "system", content: systemPrompt },
1164
- ...messages.map((m) => ({
1165
- role: m.role === "system" ? "system" : m.role === "user" ? "user" : "assistant",
1166
- content: m.content
1167
- }))
1168
- ];
1169
- const { fullStream } = streamText(streamOptions);
1170
- for await (const part of fullStream) {
1171
- if (this.config.providerId === "dify" && !this.conversationId && part?.providerMetadata?.difyWorkflowData?.conversationId || part?.providerMetadata?.dify?.conversationId) {
1172
- this.conversationId = part.providerMetadata?.difyWorkflowData?.conversationId || part.providerMetadata?.dify?.conversationId;
1173
- }
1174
- if (part.type === "text-delta") {
1175
- yield {
1176
- type: "text",
1177
- text: part.textDelta || part.text || ""
1178
- };
1179
- } else if (part.type === "finish") {
1180
- yield {
1181
- type: "usage",
1182
- usage: {
1183
- inputTokens: part.usage?.promptTokens || part.totalUsage?.promptTokens || part.totalUsage?.inputTokens || 0,
1184
- outputTokens: part.usage?.completionTokens || part.totalUsage?.completionTokens || part.totalUsage?.outputTokens || 0
1185
- }
1186
- };
1187
- } else if (part.type === "error") {
1188
- yield {
1189
- type: "error",
1190
- error: part.error
1191
- };
1192
- }
1193
- }
1194
- } catch (err) {
1195
- yield {
1196
- type: "error",
1197
- error: err
1198
- };
1199
- }
1200
- }
1201
- };
1202
468
  var AgentState = /* @__PURE__ */ ((AgentState2) => {
1203
469
  AgentState2["IDLE"] = "idle";
1204
470
  AgentState2["THINKING"] = "thinking";
@@ -1416,10 +682,10 @@ var ClineAgent = class {
1416
682
  this.setState("finished" /* FINISHED */);
1417
683
  break;
1418
684
  } else if (tool.name === "agent_read_file" /* FILE_READ */) {
1419
- const path4 = tool.params.path;
1420
- if (path4) {
685
+ const path = tool.params.path;
686
+ if (path) {
1421
687
  try {
1422
- const content = await this.runtime.fs.readFile(path4);
688
+ const content = await this.runtime.fs.readFile(path);
1423
689
  toolResults.push({ tool, result: content });
1424
690
  } catch (error) {
1425
691
  toolResults.push({ tool, result: `Error: ${error.message}` });
@@ -1435,33 +701,33 @@ var ClineAgent = class {
1435
701
  STDERR: ${result.stderr}` });
1436
702
  }
1437
703
  } else if (tool.name === "agent_write_to_file" /* FILE_NEW */) {
1438
- const path4 = tool.params.path;
704
+ const path = tool.params.path;
1439
705
  const content = tool.params.content;
1440
- if (path4 && content !== void 0) {
706
+ if (path && content !== void 0) {
1441
707
  try {
1442
- await this.runtime.fs.writeFile(path4, content);
1443
- toolResults.push({ tool, result: `Successfully wrote to ${path4}` });
708
+ await this.runtime.fs.writeFile(path, content);
709
+ toolResults.push({ tool, result: `Successfully wrote to ${path}` });
1444
710
  } catch (error) {
1445
711
  toolResults.push({ tool, result: `Error: ${error.message}` });
1446
712
  }
1447
713
  }
1448
714
  } else if (tool.name === "agent_list_files" /* LIST_FILES */) {
1449
- const path4 = tool.params.path || this.runtime.env.cwd();
715
+ const path = tool.params.path || this.runtime.env.cwd();
1450
716
  try {
1451
- const files = await this.runtime.fs.readDir(path4);
717
+ const files = await this.runtime.fs.readDir(path);
1452
718
  toolResults.push({ tool, result: files.map((f) => f.name + (f.isDirectory() ? "/" : "")).join("\n") });
1453
719
  } catch (e) {
1454
720
  toolResults.push({ tool, result: `Error: ${e.message}` });
1455
721
  }
1456
722
  } else if (tool.name === "agent_replace_in_file" /* FILE_EDIT */) {
1457
- const path4 = tool.params.path;
723
+ const path = tool.params.path;
1458
724
  const diff = tool.params.diff;
1459
- if (path4 && diff) {
725
+ if (path && diff) {
1460
726
  try {
1461
- const content = await this.runtime.fs.readFile(path4);
727
+ const content = await this.runtime.fs.readFile(path);
1462
728
  const newContent = this.applyDiff(content, diff);
1463
- await this.runtime.fs.writeFile(path4, newContent);
1464
- toolResults.push({ tool, result: `Successfully replaced content in ${path4}` });
729
+ await this.runtime.fs.writeFile(path, newContent);
730
+ toolResults.push({ tool, result: `Successfully replaced content in ${path}` });
1465
731
  } catch (e) {
1466
732
  toolResults.push({ tool, result: `Error: ${e.message}` });
1467
733
  }
@@ -1469,11 +735,11 @@ STDERR: ${result.stderr}` });
1469
735
  toolResults.push({ tool, result: "Error: Missing path or diff." });
1470
736
  }
1471
737
  } else if (tool.name === "agent_delete_file" /* FILE_DELETE */) {
1472
- const path4 = tool.params.path;
1473
- if (path4) {
738
+ const path = tool.params.path;
739
+ if (path) {
1474
740
  try {
1475
- await this.runtime.fs.deleteFile(path4);
1476
- toolResults.push({ tool, result: `Successfully deleted ${path4}` });
741
+ await this.runtime.fs.deleteFile(path);
742
+ toolResults.push({ tool, result: `Successfully deleted ${path}` });
1477
743
  } catch (e) {
1478
744
  toolResults.push({ tool, result: `Error: ${e.message}` });
1479
745
  }
@@ -1481,11 +747,11 @@ STDERR: ${result.stderr}` });
1481
747
  toolResults.push({ tool, result: "Error: Missing path." });
1482
748
  }
1483
749
  } else if (tool.name === "agent_delete_directory" /* DIR_DELETE */) {
1484
- const path4 = tool.params.path;
1485
- if (path4) {
750
+ const path = tool.params.path;
751
+ if (path) {
1486
752
  try {
1487
- await this.runtime.fs.deleteDirectory(path4);
1488
- toolResults.push({ tool, result: `Successfully deleted ${path4}` });
753
+ await this.runtime.fs.deleteDirectory(path);
754
+ toolResults.push({ tool, result: `Successfully deleted ${path}` });
1489
755
  } catch (e) {
1490
756
  toolResults.push({ tool, result: `Error: ${e.message}` });
1491
757
  }
@@ -1498,12 +764,12 @@ STDERR: ${result.stderr}` });
1498
764
  this.setState("waiting_for_user" /* WAITING_FOR_USER */);
1499
765
  break;
1500
766
  } else if (tool.name === "agent_search_files" /* SEARCH */) {
1501
- const path4 = tool.params.path || this.runtime.env.cwd();
767
+ const path = tool.params.path || this.runtime.env.cwd();
1502
768
  const regexStr = tool.params.regex;
1503
769
  const filePattern = tool.params.file_pattern;
1504
770
  if (regexStr && this.runtime.fs.searchFiles) {
1505
771
  try {
1506
- const result = await this.runtime.fs.searchFiles(path4, regexStr, filePattern);
772
+ const result = await this.runtime.fs.searchFiles(path, regexStr, filePattern);
1507
773
  toolResults.push({ tool, result: `${result}` });
1508
774
  } catch (e) {
1509
775
  toolResults.push({ tool, result: `Error: ${e.message}` });
@@ -1550,9 +816,9 @@ STDERR: ${result.stderr}` });
1550
816
  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...`;
1551
817
  toolResults.push({ tool, result: docs });
1552
818
  } else if (tool.name === "agent_list_code_definition_names" /* LIST_CODE_DEF */) {
1553
- const path4 = tool.params.path || this.runtime.env.cwd();
819
+ const path = tool.params.path || this.runtime.env.cwd();
1554
820
  try {
1555
- const result = await this.runtime.fs.searchFiles?.(path4, "^(class|function|const|let|var|export|interface|type)\\s+\\w+", "*.ts|*.js");
821
+ const result = await this.runtime.fs.searchFiles?.(path, "^(class|function|const|let|var|export|interface|type)\\s+\\w+", "*.ts|*.js");
1556
822
  toolResults.push({ tool, result: `${result ? result : "No definitions found or searchFiles not supported."}` });
1557
823
  } catch (e) {
1558
824
  toolResults.push({ tool, result: `Error: ${e.message}` });
@@ -1675,298 +941,11 @@ ${searchBlock.substring(0, 100)}...`);
1675
941
  return this.memory.getHistory();
1676
942
  }
1677
943
  };
1678
- var NodeMemoryManager = class {
1679
- filePath;
1680
- maxMessages;
1681
- /**
1682
- * @param dbPath 存储历史记录的本地文件路径(例如:'./.cline_memory.json')
1683
- * @param maxMessages 保留的最大消息数量,用于简单的历史截断(默认 150)
1684
- */
1685
- constructor(dbPath, maxMessages = 150) {
1686
- this.filePath = path2.resolve(dbPath);
1687
- this.maxMessages = maxMessages;
1688
- }
1689
- async ensureFile() {
1690
- try {
1691
- await fs2.access(this.filePath);
1692
- } catch {
1693
- const dir = path2.dirname(this.filePath);
1694
- await fs2.mkdir(dir, { recursive: true });
1695
- await fs2.writeFile(this.filePath, "[]", "utf-8");
1696
- }
1697
- }
1698
- async readMessages() {
1699
- await this.ensureFile();
1700
- const data = await fs2.readFile(this.filePath, "utf-8");
1701
- try {
1702
- return JSON.parse(data);
1703
- } catch {
1704
- return [];
1705
- }
1706
- }
1707
- async writeMessages(messages) {
1708
- await this.ensureFile();
1709
- await fs2.writeFile(this.filePath, JSON.stringify(messages, null, 2), "utf-8");
1710
- }
1711
- async getHistory() {
1712
- return this.readMessages();
1713
- }
1714
- async appendMessage(message) {
1715
- const messages = await this.readMessages();
1716
- messages.push(message);
1717
- await this.writeMessages(messages);
1718
- await this.condenseHistory();
1719
- }
1720
- async condenseHistory() {
1721
- const messages = await this.readMessages();
1722
- if (messages.length > this.maxMessages) {
1723
- const firstMessage = messages[0];
1724
- const isFirstSystem = firstMessage && firstMessage.role === "system";
1725
- const sliceCount = messages.length - this.maxMessages;
1726
- let condensed;
1727
- if (isFirstSystem) {
1728
- condensed = [firstMessage, ...messages.slice(sliceCount + 1)];
1729
- } else {
1730
- condensed = messages.slice(sliceCount);
1731
- }
1732
- await this.writeMessages(condensed);
1733
- }
1734
- }
1735
- async clear() {
1736
- await this.writeMessages([]);
1737
- }
1738
- };
1739
-
1740
- // src/memory/WebMemoryManager.ts
1741
- var WebMemoryManager = class {
1742
- storageKey;
1743
- maxMessages;
1744
- inMemoryFallback = [];
1745
- /**
1746
- * @param storageKey SessionStorage 中的键名
1747
- * @param maxMessages 保留的最大消息数量,用于简单的历史截断(默认 150)
1748
- */
1749
- constructor(storageKey = "cline_agent_memory", maxMessages = 150) {
1750
- this.storageKey = storageKey;
1751
- this.maxMessages = maxMessages;
1752
- }
1753
- isStorageAvailable() {
1754
- try {
1755
- return typeof window !== "undefined" && typeof window.sessionStorage !== "undefined";
1756
- } catch {
1757
- return false;
1758
- }
1759
- }
1760
- readMessages() {
1761
- if (this.isStorageAvailable()) {
1762
- const data = window.sessionStorage.getItem(this.storageKey);
1763
- if (data) {
1764
- try {
1765
- return JSON.parse(data);
1766
- } catch {
1767
- return [];
1768
- }
1769
- }
1770
- return [];
1771
- }
1772
- return this.inMemoryFallback;
1773
- }
1774
- writeMessages(messages) {
1775
- if (this.isStorageAvailable()) {
1776
- window.sessionStorage.setItem(this.storageKey, JSON.stringify(messages));
1777
- } else {
1778
- this.inMemoryFallback = messages;
1779
- }
1780
- }
1781
- async getHistory() {
1782
- return Promise.resolve(this.readMessages());
1783
- }
1784
- async appendMessage(message) {
1785
- const messages = this.readMessages();
1786
- messages.push(message);
1787
- this.writeMessages(messages);
1788
- await this.condenseHistory();
1789
- }
1790
- async condenseHistory() {
1791
- const messages = this.readMessages();
1792
- if (messages.length > this.maxMessages) {
1793
- const firstMessage = messages[0];
1794
- const isFirstSystem = firstMessage && firstMessage.role === "system";
1795
- const sliceCount = messages.length - this.maxMessages;
1796
- let condensed;
1797
- if (isFirstSystem) {
1798
- condensed = [firstMessage, ...messages.slice(sliceCount + 1)];
1799
- } else {
1800
- condensed = messages.slice(sliceCount);
1801
- }
1802
- this.writeMessages(condensed);
1803
- }
1804
- return Promise.resolve();
1805
- }
1806
- async clear() {
1807
- this.writeMessages([]);
1808
- return Promise.resolve();
1809
- }
1810
- };
1811
-
1812
- // src/runtime/nodeRuntime.ts
1813
- var execAsync = promisify(exec);
1814
- var DefaultNodeRuntime = class {
1815
- fs = {
1816
- readFile: async (filepath) => fs2.readFile(filepath, "utf-8"),
1817
- writeFile: async (filepath, content) => {
1818
- await fs2.mkdir(path2.dirname(filepath), { recursive: true });
1819
- await fs2.writeFile(filepath, content, "utf-8");
1820
- },
1821
- deleteFile: (filepath) => fs2.unlink(filepath),
1822
- deleteDirectory: (dirpath) => fs2.rm(dirpath, { recursive: true, force: true }),
1823
- fileExists: async (filepath) => {
1824
- try {
1825
- await fs2.access(filepath);
1826
- return true;
1827
- } catch {
1828
- return false;
1829
- }
1830
- },
1831
- readDir: (dirpath) => fs2.readdir(dirpath, { withFileTypes: true }),
1832
- mkdir: async (dirpath) => {
1833
- await fs2.mkdir(dirpath, { recursive: true });
1834
- }
1835
- };
1836
- path = {
1837
- join: (...paths) => path2.join(...paths)
1838
- };
1839
- env = {
1840
- get: (key) => process.env[key],
1841
- cwd: () => process.cwd(),
1842
- osInfo: () => `${os.type()} ${os.release()} ${os.arch()}`,
1843
- shell: () => process.env.SHELL || process.env.ComSpec || "unknown"
1844
- };
1845
- terminal = {
1846
- execCommand: async (command, options) => {
1847
- try {
1848
- const { stdout, stderr } = await execAsync(command, { cwd: options?.cwd || process.cwd() });
1849
- return { stdout, stderr, exitCode: 0 };
1850
- } catch (err) {
1851
- return { stdout: err.stdout || "", stderr: err.stderr || err.message, exitCode: err.code || 1 };
1852
- }
1853
- }
1854
- };
1855
- };
1856
- function createNodeAgent(options) {
1857
- const runtime = new DefaultNodeRuntime();
1858
- const api = new NodeApiHandler(options.apiConfig);
1859
- const memory = options.memory || new NodeMemoryManager(options.dbPath || path2.join(runtime.env.cwd(), ".cline_memory.json"));
1860
- const customTools = options.customTools || [];
1861
- const customToolNames = new Set(customTools.map((t) => t.name));
1862
- const promptManager = new NodePromptManager();
1863
- const agent = new ClineAgent({
1864
- runtime,
1865
- api,
1866
- promptManager,
1867
- memory,
1868
- customTools,
1869
- allowDefaultTools: options.allowDefaultTools,
1870
- maxLoopCount: options.maxLoopCount,
1871
- customInstructions: options.customInstructions
1872
- });
1873
- agent.onToolCall = async (tool) => {
1874
- if (customToolNames.has(tool.name)) {
1875
- const customTool = customTools.find((t) => t.name === tool.name);
1876
- if (customTool.onCall) {
1877
- return customTool.onCall(tool.params);
1878
- }
1879
- return `Error: Custom tool "${tool.name}" does not have an onCall method.`;
1880
- }
1881
- };
1882
- return agent;
1883
- }
1884
- var DefaultWebRuntime = class {
1885
- vol = new Volume();
1886
- memfs = createFsFromVolume(this.vol).promises;
1887
- fs = {
1888
- readFile: async (filepath) => {
1889
- const content = await this.memfs.readFile(filepath, "utf-8");
1890
- return content.toString();
1891
- },
1892
- writeFile: async (filepath, content) => {
1893
- const dir = filepath.substring(0, filepath.lastIndexOf("/"));
1894
- if (dir && dir !== filepath) {
1895
- await this.memfs.mkdir(dir, { recursive: true });
1896
- }
1897
- await this.memfs.writeFile(filepath, content);
1898
- },
1899
- deleteFile: (filepath) => this.memfs.unlink(filepath),
1900
- deleteDirectory: (dirpath) => this.memfs.rm(dirpath, { recursive: true, force: true }),
1901
- fileExists: async (filepath) => {
1902
- try {
1903
- await this.memfs.access(filepath);
1904
- return true;
1905
- } catch {
1906
- return false;
1907
- }
1908
- },
1909
- readDir: (dirpath) => {
1910
- return this.memfs.readdir(dirpath, { withFileTypes: true });
1911
- },
1912
- mkdir: async (dirpath) => {
1913
- await this.memfs.mkdir(dirpath, { recursive: true });
1914
- }
1915
- };
1916
- path = {
1917
- join: (...paths) => path3.join(...paths)
1918
- };
1919
- env = {
1920
- get: (key) => void 0,
1921
- // 浏览器环境中无系统环境变量
1922
- cwd: () => "/workspace",
1923
- osInfo: () => typeof navigator !== "undefined" ? navigator.userAgent : "Web Browser",
1924
- shell: () => ""
1925
- // 浏览器环境中无真实 shell
1926
- };
1927
- terminal = {
1928
- execCommand: async (command, options) => {
1929
- return {
1930
- stdout: `[Mock] Command '${command}' executed in browser sandbox.`,
1931
- stderr: "",
1932
- exitCode: 0
1933
- };
1934
- }
1935
- };
1936
- };
1937
- function createWebAgent(options) {
1938
- const runtime = new DefaultWebRuntime();
1939
- const api = new WebApiHandler(options.apiConfig);
1940
- const promptManager = new WebPromptManager();
1941
- const memory = new WebMemoryManager(options.storageKey || "cline_agent_memory");
1942
- const customTools = options.customTools || [];
1943
- const customToolNames = new Set(customTools.map((t) => t.name));
1944
- const agent = new ClineAgent({
1945
- runtime,
1946
- api,
1947
- promptManager,
1948
- memory,
1949
- customTools,
1950
- allowDefaultTools: options.allowDefaultTools,
1951
- maxLoopCount: options.maxLoopCount,
1952
- customInstructions: options.customInstructions
1953
- });
1954
- agent.onToolCall = async (tool) => {
1955
- if (customToolNames.has(tool.name)) {
1956
- const customTool = customTools.find((t) => t.name === tool.name);
1957
- if (customTool.onCall) {
1958
- return customTool.onCall(tool.params);
1959
- }
1960
- return `Error: Custom tool "${tool.name}" does not have an onCall method.`;
1961
- }
1962
- };
1963
- return agent;
1964
- }
1965
944
 
1966
945
  // src/index.ts
1967
946
  var VERSION = "0.1.0";
1968
947
  globalThis.AI_SDK_LOG_WARNINGS = false;
1969
948
 
1970
- export { AgentDefaultTool, AgentState, ClineAgent, NodeApiHandler, NodeMemoryManager, NodePromptManager, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, WebApiHandler, WebMemoryManager, WebPromptManager, createNodeAgent, createWebAgent, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames };
949
+ export { AgentDefaultTool, AgentState, ClineAgent, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames };
1971
950
  //# sourceMappingURL=index.mjs.map
1972
951
  //# sourceMappingURL=index.mjs.map