jarvis-ai-assistant 0.1.138__py3-none-any.whl → 0.1.141__py3-none-any.whl

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.

Potentially problematic release.


This version of jarvis-ai-assistant might be problematic. Click here for more details.

Files changed (85) hide show
  1. jarvis/__init__.py +1 -1
  2. jarvis/jarvis_agent/__init__.py +62 -14
  3. jarvis/jarvis_agent/builtin_input_handler.py +4 -14
  4. jarvis/jarvis_agent/main.py +1 -1
  5. jarvis/jarvis_agent/patch.py +37 -40
  6. jarvis/jarvis_agent/shell_input_handler.py +2 -3
  7. jarvis/jarvis_code_agent/code_agent.py +23 -30
  8. jarvis/jarvis_code_analysis/checklists/__init__.py +3 -0
  9. jarvis/jarvis_code_analysis/checklists/c_cpp.py +50 -0
  10. jarvis/jarvis_code_analysis/checklists/csharp.py +75 -0
  11. jarvis/jarvis_code_analysis/checklists/data_format.py +82 -0
  12. jarvis/jarvis_code_analysis/checklists/devops.py +107 -0
  13. jarvis/jarvis_code_analysis/checklists/docs.py +87 -0
  14. jarvis/jarvis_code_analysis/checklists/go.py +52 -0
  15. jarvis/jarvis_code_analysis/checklists/infrastructure.py +98 -0
  16. jarvis/jarvis_code_analysis/checklists/java.py +66 -0
  17. jarvis/jarvis_code_analysis/checklists/javascript.py +73 -0
  18. jarvis/jarvis_code_analysis/checklists/kotlin.py +107 -0
  19. jarvis/jarvis_code_analysis/checklists/loader.py +76 -0
  20. jarvis/jarvis_code_analysis/checklists/php.py +77 -0
  21. jarvis/jarvis_code_analysis/checklists/python.py +56 -0
  22. jarvis/jarvis_code_analysis/checklists/ruby.py +107 -0
  23. jarvis/jarvis_code_analysis/checklists/rust.py +58 -0
  24. jarvis/jarvis_code_analysis/checklists/shell.py +75 -0
  25. jarvis/jarvis_code_analysis/checklists/sql.py +72 -0
  26. jarvis/jarvis_code_analysis/checklists/swift.py +77 -0
  27. jarvis/jarvis_code_analysis/checklists/web.py +97 -0
  28. jarvis/jarvis_code_analysis/code_review.py +660 -0
  29. jarvis/jarvis_dev/main.py +61 -88
  30. jarvis/jarvis_git_squash/main.py +3 -3
  31. jarvis/jarvis_git_utils/git_commiter.py +242 -0
  32. jarvis/jarvis_init/main.py +62 -0
  33. jarvis/jarvis_platform/base.py +4 -0
  34. jarvis/jarvis_platform/kimi.py +173 -5
  35. jarvis/jarvis_platform/openai.py +3 -0
  36. jarvis/jarvis_platform/registry.py +1 -0
  37. jarvis/jarvis_platform/yuanbao.py +275 -5
  38. jarvis/jarvis_tools/ask_codebase.py +6 -9
  39. jarvis/jarvis_tools/ask_user.py +17 -5
  40. jarvis/jarvis_tools/base.py +3 -1
  41. jarvis/jarvis_tools/chdir.py +1 -0
  42. jarvis/jarvis_tools/create_code_agent.py +4 -3
  43. jarvis/jarvis_tools/create_sub_agent.py +1 -0
  44. jarvis/jarvis_tools/execute_script.py +170 -0
  45. jarvis/jarvis_tools/file_analyzer.py +90 -239
  46. jarvis/jarvis_tools/file_operation.py +99 -31
  47. jarvis/jarvis_tools/{find_methodolopy.py → find_methodology.py} +2 -1
  48. jarvis/jarvis_tools/lsp_get_diagnostics.py +2 -0
  49. jarvis/jarvis_tools/methodology.py +11 -11
  50. jarvis/jarvis_tools/read_code.py +2 -0
  51. jarvis/jarvis_tools/read_webpage.py +33 -196
  52. jarvis/jarvis_tools/registry.py +68 -131
  53. jarvis/jarvis_tools/search_web.py +14 -6
  54. jarvis/jarvis_tools/virtual_tty.py +399 -0
  55. jarvis/jarvis_utils/config.py +29 -3
  56. jarvis/jarvis_utils/embedding.py +0 -317
  57. jarvis/jarvis_utils/file_processors.py +343 -0
  58. jarvis/jarvis_utils/input.py +0 -1
  59. jarvis/jarvis_utils/methodology.py +94 -435
  60. jarvis/jarvis_utils/utils.py +207 -9
  61. {jarvis_ai_assistant-0.1.138.dist-info → jarvis_ai_assistant-0.1.141.dist-info}/METADATA +4 -4
  62. jarvis_ai_assistant-0.1.141.dist-info/RECORD +94 -0
  63. {jarvis_ai_assistant-0.1.138.dist-info → jarvis_ai_assistant-0.1.141.dist-info}/entry_points.txt +4 -4
  64. jarvis/jarvis_code_agent/file_select.py +0 -202
  65. jarvis/jarvis_platform/ai8.py +0 -268
  66. jarvis/jarvis_platform/ollama.py +0 -137
  67. jarvis/jarvis_platform/oyi.py +0 -307
  68. jarvis/jarvis_rag/file_processors.py +0 -138
  69. jarvis/jarvis_rag/main.py +0 -1734
  70. jarvis/jarvis_tools/code_review.py +0 -333
  71. jarvis/jarvis_tools/execute_python_script.py +0 -58
  72. jarvis/jarvis_tools/execute_shell.py +0 -97
  73. jarvis/jarvis_tools/execute_shell_script.py +0 -58
  74. jarvis/jarvis_tools/find_caller.py +0 -278
  75. jarvis/jarvis_tools/find_symbol.py +0 -295
  76. jarvis/jarvis_tools/function_analyzer.py +0 -331
  77. jarvis/jarvis_tools/git_commiter.py +0 -167
  78. jarvis/jarvis_tools/project_analyzer.py +0 -304
  79. jarvis/jarvis_tools/rag.py +0 -143
  80. jarvis/jarvis_tools/tool_generator.py +0 -221
  81. jarvis_ai_assistant-0.1.138.dist-info/RECORD +0 -85
  82. /jarvis/{jarvis_rag → jarvis_init}/__init__.py +0 -0
  83. {jarvis_ai_assistant-0.1.138.dist-info → jarvis_ai_assistant-0.1.141.dist-info}/LICENSE +0 -0
  84. {jarvis_ai_assistant-0.1.138.dist-info → jarvis_ai_assistant-0.1.141.dist-info}/WHEEL +0 -0
  85. {jarvis_ai_assistant-0.1.138.dist-info → jarvis_ai_assistant-0.1.141.dist-info}/top_level.txt +0 -0
@@ -1,333 +0,0 @@
1
- from typing import Dict, Any
2
- import subprocess
3
- import os
4
-
5
- from yaspin import yaspin
6
- from jarvis.jarvis_platform.registry import PlatformRegistry
7
- from jarvis.jarvis_tools.read_code import ReadCodeTool
8
- from jarvis.jarvis_tools.registry import ToolRegistry
9
- from jarvis.jarvis_agent import Agent
10
- import re
11
-
12
- from jarvis.jarvis_utils.output import OutputType, PrettyOutput
13
- from jarvis.jarvis_utils.utils import ct, ot, init_env
14
-
15
- class CodeReviewTool:
16
- name = "code_review"
17
- description = "自动代码审查工具,用于分析代码变更"
18
- parameters = {
19
- "type": "object",
20
- "properties": {
21
- "review_type": {
22
- "type": "string",
23
- "description": "审查类型:'commit' 审查特定提交,'current' 审查当前变更,'range' 审查提交范围,'file' 审查特定文件",
24
- "enum": ["commit", "current", "range", "file"],
25
- "default": "current"
26
- },
27
- "commit_sha": {
28
- "type": "string",
29
- "description": "要分析的提交SHA(review_type='commit'时必填)"
30
- },
31
- "start_commit": {
32
- "type": "string",
33
- "description": "起始提交SHA(review_type='range'时必填)"
34
- },
35
- "end_commit": {
36
- "type": "string",
37
- "description": "结束提交SHA(review_type='range'时必填)"
38
- },
39
- "file_path": {
40
- "type": "string",
41
- "description": "要审查的文件路径(review_type='file'时必填)"
42
- },
43
- "root_dir": {
44
- "type": "string",
45
- "description": "代码库根目录路径(可选)",
46
- "default": "."
47
- }
48
- },
49
- "required": []
50
- }
51
-
52
- def execute(self, args: Dict[str, Any]) -> Dict[str, Any]:
53
- try:
54
- review_type = args.get("review_type", "current").strip()
55
- root_dir = args.get("root_dir", ".")
56
-
57
- # Store current directory
58
- original_dir = os.getcwd()
59
-
60
- try:
61
- # Change to root_dir
62
- os.chdir(root_dir)
63
-
64
- # Build git diff command based on review type
65
- with yaspin(text="正在获取代码变更...", color="cyan") as spinner:
66
- if review_type == "commit":
67
- if "commit_sha" not in args:
68
- return {
69
- "success": False,
70
- "stdout": {},
71
- "stderr": "commit_sha is required for commit review type"
72
- }
73
- commit_sha = args["commit_sha"].strip()
74
- diff_cmd = f"git show {commit_sha} | cat -"
75
- elif review_type == "range":
76
- if "start_commit" not in args or "end_commit" not in args:
77
- return {
78
- "success": False,
79
- "stdout": {},
80
- "stderr": "start_commit and end_commit are required for range review type"
81
- }
82
- start_commit = args["start_commit"].strip()
83
- end_commit = args["end_commit"].strip()
84
- diff_cmd = f"git diff {start_commit}..{end_commit} | cat -"
85
- elif review_type == "file":
86
- if "file_path" not in args:
87
- return {
88
- "success": False,
89
- "stdout": {},
90
- "stderr": "file_path is required for file review type"
91
- }
92
- file_path = args["file_path"].strip()
93
- diff_cmd = ReadCodeTool().execute({"files": [{"path": file_path}]})["stdout"]
94
- else: # current changes
95
- diff_cmd = "git diff HEAD | cat -"
96
-
97
- # Execute git diff command
98
- try:
99
- diff_output = subprocess.check_output(diff_cmd, shell=True, text=True)
100
- if not diff_output:
101
- return {
102
- "success": False,
103
- "stdout": {},
104
- "stderr": "No changes to review"
105
- }
106
- PrettyOutput.print(diff_output, OutputType.CODE, lang="diff")
107
- except subprocess.CalledProcessError as e:
108
- return {
109
- "success": False,
110
- "stdout": {},
111
- "stderr": f"Failed to get diff: {str(e)}"
112
- }
113
- spinner.text = "代码变更获取完成"
114
- spinner.ok("✅")
115
-
116
- system_prompt = """你是一位精益求精的首席代码审查专家,拥有多年企业级代码审计经验。你需要对所有代码变更进行极其全面、严谨且深入的审查,确保代码质量达到最高标准。
117
-
118
- # 代码审查工具选择
119
- 优先使用执行shell命令进行静态分析,而非依赖内置代码审查功能:
120
-
121
- | 分析需求 | 首选工具 | 备选工具 |
122
- |---------|---------|----------|
123
- | 代码质量检查 | execute_shell | - |
124
- | 语法检查 | 语言特定lint工具 | - |
125
- | 安全分析 | 安全扫描工具 | - |
126
- | 代码统计 | loc | - |
127
-
128
- # 推荐命令
129
- - Python: `pylint <file_path>`, `flake8 <file_path>`, `mypy <file_path>`
130
- - JavaScript/TypeScript: `eslint <file_path>`, `tsc --noEmit <file_path>`
131
- - Java: `checkstyle <file_path>`, `pmd -d <file_path>`
132
- - C/C++: `cppcheck <file_path>`, `clang-tidy <file_path>`
133
- - Go: `golint <file_path>`, `go vet <file_path>`
134
- - Rust: `cargo clippy`, `rustfmt --check <file_path>`
135
- - 通用搜索:`rg "pattern" <files>` 查找特定代码模式
136
-
137
- # 专家审查标准
138
- 1. 必须逐行分析每个修改文件,细致审查每一处变更,不遗漏任何细节
139
- 2. 基于坚实的证据识别问题,不做主观臆测,给出明确的问题定位和详细分析
140
- 3. 对每个问题提供完整可执行的解决方案,包括精确的改进代码
141
- 4. 确保报告条理清晰、层次分明,便于工程师快速采取行动
142
-
143
- # 全面审查框架 (SCRIPPPS)
144
- ## S - 安全与风险 (Security & Risk)
145
- - 发现所有潜在安全漏洞:注入攻击、授权缺陷、数据泄露风险
146
- - 检查加密实现、密钥管理、敏感数据处理
147
- - 审核权限验证逻辑、身份认证机制
148
- - 检测OWASP Top 10安全风险和针对特定语言/框架的漏洞
149
-
150
- ## C - 正确性与完整性 (Correctness & Completeness)
151
- - 验证业务逻辑和算法实现的准确性
152
- - 全面检查条件边界、空值处理和异常情况
153
- - 审核所有输入验证、参数校验和返回值处理
154
- - 确保循环和递归的正确终止条件
155
- - 严格检查线程安全和并发控制机制
156
-
157
- ## R - 可靠性与鲁棒性 (Reliability & Robustness)
158
- - 评估代码在异常情况下的行为和恢复能力
159
- - 审查错误处理、异常捕获和恢复策略
160
- - 检查资源管理:内存、文件句柄、连接池、线程
161
- - 评估容错设计和失败优雅降级机制
162
-
163
- ## I - 接口与集成 (Interface & Integration)
164
- - 检查API合约遵守情况和向后兼容性
165
- - 审核与外部系统的集成点和交互逻辑
166
- - 验证数据格式、序列化和协议实现
167
- - 评估系统边界处理和跨服务通信安全性
168
-
169
- ## P - 性能与效率 (Performance & Efficiency)
170
- - 识别潜在性能瓶颈:CPU、内存、I/O、网络
171
- - 审查数据结构选择和算法复杂度
172
- - 检查资源密集型操作、数据库查询优化
173
- - 评估缓存策略、批处理优化和并行处理机会
174
-
175
- ## P - 可移植性与平台适配 (Portability & Platform Compatibility)
176
- - 检查跨平台兼容性问题和依赖项管理
177
- - 评估配置管理和环境适配设计
178
- - 审核国际化和本地化支持
179
- - 验证部署和运行时环境需求
180
-
181
- ## S - 结构与可维护性 (Structure & Maintainability)
182
- - 评估代码组织、模块划分和架构符合性
183
- - 审查代码重复、设计模式应用和抽象水平
184
- - 检查命名规范、代码风格和项目约定
185
- - 评估文档完整性、注释质量和代码可读性
186
-
187
- # 问题严重程度分级
188
- - 严重 (P0): 安全漏洞、数据丢失风险、系统崩溃、功能严重缺陷
189
- - 高危 (P1): 显著性能问题、可能导致部分功能失效、系统不稳定
190
- - 中等 (P2): 功能局部缺陷、次优设计、明显的技术债务
191
- - 低危 (P3): 代码风格问题、轻微优化机会、文档改进建议
192
-
193
- # 输出规范
194
- 针对每个文件的问题必须包含:
195
- - 精确文件路径和问题影响范围
196
- - 问题位置(起始行号-结束行号)
197
- - 详尽问题描述,包括具体影响和潜在风险
198
- - 严重程度分级(P0-P3)并说明理由
199
- - 具体改进建议,提供完整、可执行的代码示例
200
-
201
- 所有审查发现必须:
202
- 1. 基于确凿的代码证据
203
- 2. 说明具体问题而非笼统评论
204
- 3. 提供清晰的技术原理分析
205
- 4. 给出完整的改进实施步骤"""
206
-
207
- tool_registry = ToolRegistry()
208
- tool_registry.dont_use_tools(["code_review"])
209
- agent = Agent(
210
- system_prompt=system_prompt,
211
- name="Code Review Agent",
212
- summary_prompt=f"""请生成一份专业级别的代码审查报告,对每处变更进行全面深入分析。将完整报告放在REPORT标签内,格式如下:
213
-
214
- {ot("REPORT")}
215
- # 整体评估
216
- [提供对整体代码质量、架构和主要关注点的简明概述,总结主要发现]
217
-
218
- # 详细问题清单
219
-
220
- ## 文件: [文件路径]
221
- [如果该文件没有发现问题,则明确说明"未发现问题"]
222
-
223
- ### 问题 1
224
- - **位置**: [起始行号-结束行号]
225
- - **分类**: [使用SCRIPPPS框架中相关类别]
226
- - **严重程度**: [P0/P1/P2/P3] - [简要说明判定理由]
227
- - **问题描述**:
228
- [详细描述问题,包括技术原理和潜在影响]
229
- - **改进建议**:
230
- ```
231
- [提供完整、可执行的代码示例,而非概念性建议]
232
- ```
233
-
234
- ### 问题 2
235
- ...
236
-
237
- ## 文件: [文件路径2]
238
- ...
239
-
240
- # 最佳实践建议
241
- [提供适用于整个代码库的改进建议和最佳实践]
242
-
243
- # 总结
244
- [总结主要问题和优先处理建议]
245
- {ct("REPORT")}
246
-
247
- 如果没有发现任何问题,请在REPORT标签内进行全面分析后明确说明"经过全面审查,未发现问题"并解释原因。
248
- 必须确保对所有修改的文件都进行了审查,并在报告中明确提及每个文件,即使某些文件没有发现问题。""",
249
- output_handler=[tool_registry],
250
- platform=PlatformRegistry().get_thinking_platform(),
251
- auto_complete=True
252
- )
253
- result = agent.run(diff_output)
254
- return {
255
- "success": True,
256
- "stdout": result,
257
- "stderr": ""
258
- }
259
- finally:
260
- # Always restore original directory
261
- os.chdir(original_dir)
262
-
263
- except Exception as e:
264
- return {
265
- "success": False,
266
- "stdout": {},
267
- "stderr": f"Review failed: {str(e)}"
268
- }
269
-
270
-
271
- def extract_code_report(result: str) -> str:
272
- sm = re.search(ot("REPORT")+r'\n(.*?)\n'+ct("REPORT"), result, re.DOTALL)
273
- if sm:
274
- return sm.group(1)
275
- return ""
276
-
277
- def main():
278
- """CLI entry point"""
279
- import argparse
280
-
281
- init_env()
282
-
283
- parser = argparse.ArgumentParser(description='Autonomous code review tool')
284
- subparsers = parser.add_subparsers(dest='type')
285
-
286
- # Commit subcommand
287
- commit_parser = subparsers.add_parser('commit', help='Review specific commit')
288
- commit_parser.add_argument('commit', help='Commit SHA to review')
289
-
290
- # Current subcommand
291
- current_parser = subparsers.add_parser('current', help='Review current changes')
292
-
293
- # Range subcommand
294
- range_parser = subparsers.add_parser('range', help='Review commit range')
295
- range_parser.add_argument('start_commit', help='Start commit SHA')
296
- range_parser.add_argument('end_commit', help='End commit SHA')
297
-
298
- # File subcommand
299
- file_parser = subparsers.add_parser('file', help='Review specific file')
300
- file_parser.add_argument('file', help='File path to review')
301
-
302
- # Common arguments
303
- parser.add_argument('--root-dir', type=str, help='Root directory of the codebase', default=".")
304
-
305
- # Set default subcommand to 'current'
306
- parser.set_defaults(type='current')
307
- args = parser.parse_args()
308
-
309
- tool = CodeReviewTool()
310
- tool_args = {
311
- "review_type": args.type,
312
- "root_dir": args.root_dir
313
- }
314
- if args.type == 'commit':
315
- tool_args["commit_sha"] = args.commit
316
- elif args.type == 'range':
317
- tool_args["start_commit"] = args.start_commit
318
- tool_args["end_commit"] = args.end_commit
319
- elif args.type == 'file':
320
- tool_args["file_path"] = args.file
321
-
322
- result = tool.execute(tool_args)
323
-
324
- if result["success"]:
325
- PrettyOutput.section("自动代码审查结果:", OutputType.SUCCESS)
326
- report = extract_code_report(result["stdout"])
327
- PrettyOutput.print(report, OutputType.SUCCESS, lang="markdown")
328
-
329
- else:
330
- PrettyOutput.print(result["stderr"], OutputType.WARNING)
331
-
332
- if __name__ == "__main__":
333
- main()
@@ -1,58 +0,0 @@
1
- from typing import Dict, Any
2
- import os
3
- import tempfile
4
- from pathlib import Path
5
-
6
- from jarvis.jarvis_utils.output import OutputType, PrettyOutput
7
-
8
-
9
- class PythonScriptTool:
10
- name = "execute_python_script"
11
- description = "执行Python脚本文件并返回结果"
12
- parameters = {
13
- "type": "object",
14
- "properties": {
15
- "script_content": {
16
- "type": "string",
17
- "description": "要执行的Python脚本内容"
18
- }
19
- },
20
- "required": ["script_content"]
21
- }
22
- def execute(self, args: Dict) -> Dict[str, Any]:
23
- """Execute Python script content"""
24
- try:
25
- script_content = args.get("script_content", "").strip()
26
- if not script_content:
27
- return {
28
- "success": False,
29
- "stdout": "",
30
- "stderr": "Missing or empty script_content parameter"
31
- }
32
-
33
- # Create temporary script file
34
- script_path = os.path.join(tempfile.gettempdir(), f"jarvis_script_{os.getpid()}.py")
35
- try:
36
- with open(script_path, 'w', encoding='utf-8', errors="ignore") as f:
37
- f.write(script_content)
38
- # Use execute_shell to run the script
39
- from jarvis.jarvis_tools.execute_shell import ShellTool
40
- shell_tool = ShellTool()
41
- result = shell_tool.execute({"command": f"python3 {script_path}"})
42
-
43
- return {
44
- "success": result["success"],
45
- "stdout": result["stdout"],
46
- "stderr": result["stderr"]
47
- }
48
- finally:
49
- # Clean up temporary script file
50
- Path(script_path).unlink(missing_ok=True)
51
-
52
- except Exception as e:
53
- PrettyOutput.print(str(e), OutputType.ERROR)
54
- return {
55
- "success": False,
56
- "stdout": "",
57
- "stderr": str(e)
58
- }
@@ -1,97 +0,0 @@
1
- # Shell command execution module
2
- #
3
- # Provides functionality to execute shell commands safely with:
4
- # - Command escaping
5
- # - Output capturing
6
- # - Temporary file management
7
- # - Error handling
8
- from typing import Dict, Any
9
- import os
10
- import tempfile
11
- from pathlib import Path
12
- from jarvis.jarvis_utils.output import OutputType, PrettyOutput
13
- class ShellTool:
14
- """Shell command execution tool
15
-
16
- Attributes:
17
- name: Tool identifier used in API
18
- description: Tool description for API documentation
19
- parameters: JSON schema for command parameters
20
- """
21
- name = "execute_shell"
22
- description = "执行Shell命令并返回结果"
23
- parameters = {
24
- "type": "object",
25
- "properties": {
26
- "command": {
27
- "type": "string",
28
- "description": "要执行的Shell命令"
29
- }
30
- },
31
- "required": ["command"]
32
- }
33
- def _escape_command(self, cmd: str) -> str:
34
- """Escape special characters in command to prevent shell injection
35
-
36
- Args:
37
- cmd: Raw command string
38
-
39
- Returns:
40
- Escaped command string with single quotes properly handled
41
- """
42
- return cmd.replace("'", "'\"'\"'")
43
- def execute(self, args: Dict) -> Dict[str, Any]:
44
- try:
45
- # Get and clean command input
46
- command = args["command"].strip()
47
-
48
- # Generate temporary file name using process ID for uniqueness
49
- script_file = os.path.join(tempfile.gettempdir(), f"jarvis_shell_{os.getpid()}.sh")
50
- output_file = os.path.join(tempfile.gettempdir(), f"jarvis_shell_{os.getpid()}.log")
51
-
52
- # Write command to script file
53
- with open(script_file, 'w', encoding='utf-8') as f:
54
- f.write(f"#!/bin/bash\n{command}")
55
-
56
- # Use script command to capture both stdout and stderr
57
- tee_command = f"script -q -c 'bash {script_file}' {output_file}"
58
-
59
- # Execute command and capture return code
60
- os.system(tee_command)
61
-
62
- # Read and process output file
63
- try:
64
- with open(output_file, 'r', encoding='utf-8', errors='ignore') as f:
65
- output = f.read()
66
- # Remove header and footer added by script command (if any)
67
- if output:
68
- lines = output.splitlines()
69
- if len(lines) > 2:
70
- output = "\n".join(lines[1:-1])
71
- except Exception as e:
72
- output = f"读取输出文件失败: {str(e)}"
73
- finally:
74
- # Clean up temporary files
75
- Path(script_file).unlink(missing_ok=True)
76
- Path(output_file).unlink(missing_ok=True)
77
-
78
- # Return successful result
79
- return {
80
- "success": True,
81
- "stdout": output,
82
- "stderr": "",
83
- }
84
-
85
- except Exception as e:
86
- # Ensure temporary files are cleaned up even if error occurs
87
- if 'script_file' in locals():
88
- Path(script_file).unlink(missing_ok=True)
89
- if 'output_file' in locals():
90
- Path(output_file).unlink(missing_ok=True)
91
- PrettyOutput.print(str(e), OutputType.ERROR)
92
- return {
93
- "success": False,
94
- "stdout": "",
95
- "stderr": str(e)
96
- }
97
-
@@ -1,58 +0,0 @@
1
- from typing import Dict, Any
2
- import os
3
- import tempfile
4
- from pathlib import Path
5
-
6
- from jarvis.jarvis_utils.output import OutputType, PrettyOutput
7
-
8
-
9
- class ShellScriptTool:
10
- name = "execute_shell_script"
11
- description = "执行Shell脚本文件并返回结果"
12
- parameters = {
13
- "type": "object",
14
- "properties": {
15
- "script_content": {
16
- "type": "string",
17
- "description": "要执行的Shell脚本内容"
18
- }
19
- },
20
- "required": ["script_content"]
21
- }
22
- def execute(self, args: Dict) -> Dict[str, Any]:
23
- """Execute shell script content"""
24
- try:
25
- script_content = args.get("script_content", "").strip()
26
- if not script_content:
27
- return {
28
- "success": False,
29
- "stdout": "",
30
- "stderr": "Missing or empty script_content parameter"
31
- }
32
-
33
- # Create temporary script file
34
- script_path = os.path.join(tempfile.gettempdir(), f"jarvis_shell_script_{os.getpid()}.sh")
35
- try:
36
- with open(script_path, 'w', encoding='utf-8', errors="ignore") as f:
37
- f.write(script_content)
38
- # Use execute_shell to run the script
39
- from jarvis.jarvis_tools.execute_shell import ShellTool
40
- shell_tool = ShellTool()
41
- result = shell_tool.execute({"command": f"bash {script_path}"})
42
-
43
- return {
44
- "success": result["success"],
45
- "stdout": result["stdout"],
46
- "stderr": result["stderr"]
47
- }
48
- finally:
49
- # Clean up temporary script file
50
- Path(script_path).unlink(missing_ok=True)
51
-
52
- except Exception as e:
53
- PrettyOutput.print(str(e), OutputType.ERROR)
54
- return {
55
- "success": False,
56
- "stdout": "",
57
- "stderr": str(e)
58
- }