jarvis-ai-assistant 0.1.129__py3-none-any.whl → 0.1.131__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 (61) hide show
  1. jarvis/__init__.py +1 -1
  2. jarvis/jarvis_agent/__init__.py +41 -27
  3. jarvis/jarvis_agent/builtin_input_handler.py +73 -0
  4. jarvis/{jarvis_code_agent → jarvis_agent}/file_input_handler.py +1 -1
  5. jarvis/jarvis_agent/main.py +1 -1
  6. jarvis/jarvis_agent/patch.py +461 -0
  7. jarvis/{jarvis_code_agent → jarvis_agent}/shell_input_handler.py +0 -1
  8. jarvis/jarvis_code_agent/code_agent.py +94 -89
  9. jarvis/jarvis_codebase/main.py +5 -5
  10. jarvis/jarvis_dev/main.py +833 -741
  11. jarvis/jarvis_git_squash/main.py +1 -1
  12. jarvis/jarvis_lsp/base.py +2 -26
  13. jarvis/jarvis_lsp/cpp.py +2 -14
  14. jarvis/jarvis_lsp/go.py +0 -13
  15. jarvis/jarvis_lsp/python.py +1 -30
  16. jarvis/jarvis_lsp/registry.py +10 -14
  17. jarvis/jarvis_lsp/rust.py +0 -12
  18. jarvis/jarvis_multi_agent/__init__.py +63 -53
  19. jarvis/jarvis_platform/registry.py +1 -2
  20. jarvis/jarvis_platform_manager/main.py +3 -3
  21. jarvis/jarvis_rag/main.py +1 -1
  22. jarvis/jarvis_tools/ask_codebase.py +40 -20
  23. jarvis/jarvis_tools/code_review.py +180 -143
  24. jarvis/jarvis_tools/create_code_agent.py +76 -72
  25. jarvis/jarvis_tools/create_sub_agent.py +31 -21
  26. jarvis/jarvis_tools/execute_shell.py +2 -2
  27. jarvis/jarvis_tools/execute_shell_script.py +1 -1
  28. jarvis/jarvis_tools/file_operation.py +2 -2
  29. jarvis/jarvis_tools/git_commiter.py +88 -68
  30. jarvis/jarvis_tools/lsp_find_definition.py +83 -67
  31. jarvis/jarvis_tools/lsp_find_references.py +62 -46
  32. jarvis/jarvis_tools/lsp_get_diagnostics.py +90 -74
  33. jarvis/jarvis_tools/methodology.py +3 -3
  34. jarvis/jarvis_tools/read_code.py +2 -2
  35. jarvis/jarvis_tools/search_web.py +18 -20
  36. jarvis/jarvis_tools/tool_generator.py +1 -1
  37. jarvis/jarvis_tools/treesitter_analyzer.py +331 -0
  38. jarvis/jarvis_treesitter/README.md +104 -0
  39. jarvis/jarvis_treesitter/__init__.py +20 -0
  40. jarvis/jarvis_treesitter/database.py +258 -0
  41. jarvis/jarvis_treesitter/example.py +115 -0
  42. jarvis/jarvis_treesitter/grammar_builder.py +182 -0
  43. jarvis/jarvis_treesitter/language.py +117 -0
  44. jarvis/jarvis_treesitter/symbol.py +31 -0
  45. jarvis/jarvis_treesitter/tools_usage.md +121 -0
  46. jarvis/jarvis_utils/git_utils.py +10 -2
  47. jarvis/jarvis_utils/input.py +3 -1
  48. jarvis/jarvis_utils/methodology.py +1 -1
  49. jarvis/jarvis_utils/output.py +2 -2
  50. jarvis/jarvis_utils/utils.py +3 -3
  51. {jarvis_ai_assistant-0.1.129.dist-info → jarvis_ai_assistant-0.1.131.dist-info}/METADATA +2 -4
  52. jarvis_ai_assistant-0.1.131.dist-info/RECORD +85 -0
  53. jarvis/jarvis_code_agent/builtin_input_handler.py +0 -43
  54. jarvis/jarvis_code_agent/patch.py +0 -276
  55. jarvis/jarvis_tools/lsp_get_document_symbols.py +0 -87
  56. jarvis/jarvis_tools/lsp_prepare_rename.py +0 -130
  57. jarvis_ai_assistant-0.1.129.dist-info/RECORD +0 -78
  58. {jarvis_ai_assistant-0.1.129.dist-info → jarvis_ai_assistant-0.1.131.dist-info}/LICENSE +0 -0
  59. {jarvis_ai_assistant-0.1.129.dist-info → jarvis_ai_assistant-0.1.131.dist-info}/WHEEL +0 -0
  60. {jarvis_ai_assistant-0.1.129.dist-info → jarvis_ai_assistant-0.1.131.dist-info}/entry_points.txt +0 -0
  61. {jarvis_ai_assistant-0.1.129.dist-info → jarvis_ai_assistant-0.1.131.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,461 @@
1
+ import re
2
+ from typing import Dict, Any, Tuple
3
+ import os
4
+
5
+ from yaspin import yaspin
6
+
7
+ from jarvis.jarvis_agent.output_handler import OutputHandler
8
+ from jarvis.jarvis_platform.registry import PlatformRegistry
9
+ from jarvis.jarvis_tools.git_commiter import GitCommitTool
10
+ from jarvis.jarvis_tools.file_operation import FileOperationTool
11
+ from jarvis.jarvis_utils.config import is_confirm_before_apply_patch
12
+ from jarvis.jarvis_utils.git_utils import get_commits_between, get_latest_commit_hash
13
+ from jarvis.jarvis_utils.input import get_multiline_input
14
+ from jarvis.jarvis_utils.output import OutputType, PrettyOutput
15
+ from jarvis.jarvis_utils.utils import get_file_line_count, user_confirm
16
+
17
+ class PatchOutputHandler(OutputHandler):
18
+ def name(self) -> str:
19
+ return "PATCH"
20
+ def handle(self, response: str) -> Tuple[bool, Any]:
21
+ return False, apply_patch(response)
22
+
23
+ def can_handle(self, response: str) -> bool:
24
+ if _parse_patch(response):
25
+ return True
26
+ return False
27
+
28
+ def prompt(self) -> str:
29
+ return """
30
+ # 代码补丁规范
31
+
32
+ ## 补丁格式定义
33
+ 使用<PATCH>块来精确指定代码更改:
34
+ ```
35
+ <PATCH>
36
+ File: [文件路径]
37
+ Reason: [修改原因]
38
+ [上下文代码片段]
39
+ </PATCH>
40
+ ```
41
+
42
+ ## 核心原则
43
+ 1. **上下文完整性**:代码片段必须包含足够的上下文(修改前后各3行)
44
+ 2. **精准修改**:只显示需要修改的代码部分,不需要展示整个文件内容
45
+ 3. **格式严格保持**:
46
+ - 严格保持原始代码的缩进方式(空格或制表符)
47
+ - 保持原始代码的空行数量和位置
48
+ - 保持原始代码的行尾空格处理方式
49
+ - 不改变原始代码的换行风格
50
+ 4. **新旧区分**:
51
+ - 对于新文件:提供完整的代码内容
52
+ - 对于现有文件:保留周围未更改的代码,突出显示变更部分
53
+ 5. **理由说明**:每个补丁必须包含清晰的修改理由,解释为什么需要此更改
54
+
55
+ ## 格式兼容性要求
56
+ 1. **缩进一致性**:
57
+ - 如果原代码使用4个空格缩进,补丁也必须使用4个空格缩进
58
+ - 如果原代码使用制表符缩进,补丁也必须使用制表符缩进
59
+ 2. **空行保留**:
60
+ - 如果原代码在函数之间有两个空行,补丁也必须保留这两个空行
61
+ - 如果原代码在类方法之间有一个空行,补丁也必须保留这一个空行
62
+ 3. **行尾处理**:
63
+ - 如果原代码行尾没有空格,补丁也不应添加行尾空格
64
+ - 如果原代码使用特定的行尾注释风格,补丁也应保持该风格
65
+
66
+ ## 补丁示例
67
+ ```
68
+ <PATCH>
69
+ File: src/utils/math.py
70
+ Reason: 修复除零错误,增加参数验证以提高函数健壮性
71
+ def safe_divide(a, b):
72
+ # 添加参数验证
73
+ if b == 0:
74
+ raise ValueError("除数不能为零")
75
+ return a / b
76
+ # 现有代码 ...
77
+ def add(a, b):
78
+ return a + b
79
+ </PATCH>
80
+ ```
81
+
82
+ ## 最佳实践
83
+ - 每个补丁专注于单一职责的修改
84
+ - 提供足够的上下文,但避免包含过多无关代码
85
+ - 确保修改理由清晰明确,便于理解变更目的
86
+ - 保持代码风格一致性,遵循项目现有的编码规范
87
+ - 在修改前仔细分析原代码的格式风格,确保补丁与之完全兼容
88
+ """
89
+
90
+ def _parse_patch(patch_str: str) -> Dict[str, str]:
91
+ """解析新的上下文补丁格式"""
92
+ result = {}
93
+ patches = re.findall(r'<PATCH>\n?(.*?)\n?</PATCH>', patch_str, re.DOTALL)
94
+ if patches:
95
+ for patch in patches:
96
+ first_line = patch.splitlines()[0]
97
+ sm = re.match(r'^File:\s*(.+)$', first_line)
98
+ if not sm:
99
+ PrettyOutput.print("无效的补丁格式", OutputType.WARNING)
100
+ continue
101
+ filepath = sm.group(1).strip()
102
+ if filepath not in result:
103
+ result[filepath] = patch
104
+ else:
105
+ result[filepath] += "\n\n" + patch
106
+ return result
107
+
108
+ def apply_patch(output_str: str) -> str:
109
+ """Apply patches to files"""
110
+ with yaspin(text="正在应用补丁...", color="cyan") as spinner:
111
+ try:
112
+ patches = _parse_patch(output_str)
113
+ except Exception as e:
114
+ PrettyOutput.print(f"解析补丁失败: {str(e)}", OutputType.ERROR)
115
+ return ""
116
+
117
+ # 获取当前提交hash作为起始点
118
+ spinner.text= "开始获取当前提交hash..."
119
+ start_hash = get_latest_commit_hash()
120
+ spinner.write("✅ 当前提交hash获取完成")
121
+
122
+ # 按文件逐个处理
123
+ for filepath, patch_content in patches.items():
124
+ try:
125
+ spinner.text = f"正在处理文件: {filepath}"
126
+ if not os.path.exists(filepath):
127
+ # 新建文件
128
+ spinner.text = "文件不存在,正在创建文件..."
129
+ os.makedirs(os.path.dirname(filepath), exist_ok=True)
130
+ open(filepath, 'w', encoding='utf-8').close()
131
+ spinner.write("✅ 文件创建完成")
132
+ with spinner.hidden():
133
+ while not handle_code_operation(filepath, patch_content):
134
+ if user_confirm("补丁应用失败,是否重试?", default=True):
135
+ pass
136
+ else:
137
+ raise Exception("补丁应用失败")
138
+ spinner.write(f"✅ 文件 {filepath} 处理完成")
139
+ except Exception as e:
140
+ spinner.text = f"文件 {filepath} 处理失败: {str(e)}, 回滚文件"
141
+ revert_file(filepath) # 回滚单个文件
142
+ spinner.write(f"✅ 文件 {filepath} 回滚完成")
143
+
144
+ final_ret = ""
145
+ diff = get_diff()
146
+ if diff:
147
+ PrettyOutput.print(diff, OutputType.CODE, lang="diff")
148
+ with spinner.hidden():
149
+ commited = handle_commit_workflow()
150
+ if commited:
151
+ # 获取提交信息
152
+ end_hash = get_latest_commit_hash()
153
+ commits = get_commits_between(start_hash, end_hash)
154
+
155
+ # 添加提交信息到final_ret
156
+ if commits:
157
+ final_ret += "✅ 补丁已应用\n"
158
+ final_ret += "提交信息:\n"
159
+ for commit_hash, commit_message in commits:
160
+ final_ret += f"- {commit_hash[:7]}: {commit_message}\n"
161
+
162
+ final_ret += f"应用补丁:\n{diff}"
163
+
164
+ else:
165
+ final_ret += "✅ 补丁已应用(没有新的提交)"
166
+ else:
167
+ final_ret += "❌ 我拒绝应用此补丁\n"
168
+ final_ret += "补丁预览:\n"
169
+ final_ret += diff
170
+ else:
171
+ final_ret += "❌ 没有要提交的更改\n"
172
+ # 用户确认最终结果
173
+ with spinner.hidden():
174
+ PrettyOutput.print(final_ret, OutputType.USER)
175
+ if not is_confirm_before_apply_patch() or user_confirm("是否使用此回复?", default=True):
176
+ return final_ret
177
+ return get_multiline_input("请输入自定义回复")
178
+
179
+ def revert_file(filepath: str):
180
+ """增强版git恢复,处理新文件"""
181
+ import subprocess
182
+ try:
183
+ # 检查文件是否在版本控制中
184
+ result = subprocess.run(
185
+ ['git', 'ls-files', '--error-unmatch', filepath],
186
+ stderr=subprocess.PIPE
187
+ )
188
+ if result.returncode == 0:
189
+ subprocess.run(['git', 'checkout', 'HEAD', '--', filepath], check=True)
190
+ else:
191
+ if os.path.exists(filepath):
192
+ os.remove(filepath)
193
+ subprocess.run(['git', 'clean', '-f', '--', filepath], check=True)
194
+ except subprocess.CalledProcessError as e:
195
+ PrettyOutput.print(f"恢复文件失败: {str(e)}", OutputType.ERROR)
196
+ # 修改后的恢复函数
197
+ def revert_change():
198
+ import subprocess
199
+ subprocess.run(['git', 'reset', '--hard', 'HEAD'], check=True)
200
+ subprocess.run(['git', 'clean', '-fd'], check=True)
201
+ # 修改后的获取差异函数
202
+ def get_diff() -> str:
203
+ """使用git获取暂存区差异"""
204
+ import subprocess
205
+ try:
206
+ subprocess.run(['git', 'add', '.'], check=True)
207
+ result = subprocess.run(
208
+ ['git', 'diff', '--cached'],
209
+ capture_output=True,
210
+ text=True,
211
+ check=True
212
+ )
213
+ ret = result.stdout
214
+ subprocess.run(['git', "reset", "--mixed", "HEAD"], check=True)
215
+ return ret
216
+ except subprocess.CalledProcessError as e:
217
+ return f"获取差异失败: {str(e)}"
218
+
219
+ def handle_commit_workflow()->bool:
220
+ """Handle the git commit workflow and return the commit details.
221
+
222
+ Returns:
223
+ tuple[bool, str, str]: (continue_execution, commit_id, commit_message)
224
+ """
225
+ if is_confirm_before_apply_patch() and not user_confirm("是否要提交代码?", default=True):
226
+ revert_change()
227
+ return False
228
+ git_commiter = GitCommitTool()
229
+ commit_result = git_commiter.execute({})
230
+ return commit_result["success"]
231
+
232
+
233
+ def handle_code_operation(filepath: str, patch_content: str) -> bool:
234
+ """处理代码操作"""
235
+ if get_file_line_count(filepath) < 100:
236
+ return handle_small_code_operation(filepath, patch_content)
237
+ else:
238
+ retry_count = 3
239
+ while retry_count > 0:
240
+ retry_count -= 1
241
+ if handle_large_code_operation(filepath, patch_content):
242
+ return True
243
+ return handle_small_code_operation(filepath, patch_content)
244
+
245
+
246
+ def handle_small_code_operation(filepath: str, patch_content: str) -> bool:
247
+ """处理基于上下文的代码片段"""
248
+ with yaspin(text=f"正在修改文件 {filepath}...", color="cyan") as spinner:
249
+ try:
250
+ with spinner.hidden():
251
+ old_file_content = FileOperationTool().execute({"operation": "read", "files": [{"path": filepath}]})
252
+ if not old_file_content["success"]:
253
+ spinner.write("❌ 文件读取失败")
254
+ return False
255
+
256
+ prompt = f"""
257
+ # 代码合并专家指南
258
+
259
+ ## 任务描述
260
+ 你是一位精确的代码审查与合并专家,需要将补丁内容与原始代码智能合并。
261
+
262
+ ## 输入资料
263
+ ### 原始代码
264
+ ```
265
+ {old_file_content["stdout"]}
266
+ ```
267
+
268
+ ### 补丁内容
269
+ ```
270
+ {patch_content}
271
+ ```
272
+
273
+ ## 合并要求
274
+ 1. **精确性**:严格按照补丁的意图修改代码
275
+ 2. **完整性**:确保所有需要的更改都被应用
276
+ 3. **一致性**:严格保留原始代码的格式、空行和缩进风格
277
+ 4. **上下文保留**:保持未修改部分的代码完全不变
278
+
279
+ ## 输出格式规范
280
+ - 仅在<MERGED_CODE>标签内输出合并后的完整代码
281
+ - 每次最多输出300行代码
282
+ - 不要使用markdown代码块(```)或反引号,除非修改的是markdown文件
283
+ - 除了合并后的代码,不要输出任何其他文本
284
+ - 所有代码输出完成后,输出<!!!FINISHED!!!>标记
285
+
286
+ ## 输出模板
287
+ <MERGED_CODE>
288
+ [合并后的完整代码,包括所有空行和缩进]
289
+ </MERGED_CODE>
290
+ """
291
+ model = PlatformRegistry().get_codegen_platform()
292
+ model.set_suppress_output(False)
293
+ count = 30
294
+ start_line = -1
295
+ end_line = -1
296
+ code = []
297
+ finished = False
298
+ while count>0:
299
+ count -= 1
300
+ with spinner.hidden():
301
+ response = model.chat_until_success(prompt).splitlines()
302
+ try:
303
+ start_line = response.index("<MERGED_CODE>") + 1
304
+ try:
305
+ end_line = response.index("</MERGED_CODE>")
306
+ code = response[start_line:end_line]
307
+ except:
308
+ pass
309
+ except:
310
+ pass
311
+
312
+ try:
313
+ response.index("<!!!FINISHED!!!>")
314
+ finished = True
315
+ break
316
+ except:
317
+ prompt += f"""
318
+ # 继续输出
319
+
320
+ ## 说明
321
+ 请继续输出接下来的300行代码
322
+
323
+ ## 要求
324
+ - 严格保留原始代码的格式、空行和缩进
325
+ - 仅在<MERGED_CODE>块中包含实际代码内容
326
+ - 不要使用markdown代码块(```)或反引号
327
+ - 除了合并后的代码,不要输出任何其他文本
328
+ - 所有代码输出完成后,输出<!!!FINISHED!!!>标记
329
+ """
330
+ pass
331
+ if not finished:
332
+ spinner.text = "生成代码失败"
333
+ spinner.fail("❌")
334
+ return False
335
+ # 写入合并后的代码
336
+ spinner.text = "写入合并后的代码..."
337
+ with open(filepath, 'w', encoding='utf-8', errors="ignore") as f:
338
+ f.write("\n".join(code)+"\n")
339
+ spinner.write("✅ 合并后的代码写入完成")
340
+ spinner.text = "代码修改完成"
341
+ spinner.ok("✅")
342
+ return True
343
+ except Exception as e:
344
+ spinner.text = "代码修改失败"
345
+ spinner.fail("❌")
346
+ return False
347
+
348
+
349
+ def handle_large_code_operation(filepath: str, patch_content: str) -> bool:
350
+ """处理大型代码文件的补丁操作,使用差异化补丁格式"""
351
+ with yaspin(text=f"正在处理文件 {filepath}...", color="cyan") as spinner:
352
+ try:
353
+ # 读取原始文件内容
354
+ old_file_content = FileOperationTool().execute({"operation": "read", "files": [{"path": filepath}]})
355
+ if not old_file_content["success"]:
356
+ spinner.text = "文件读取失败"
357
+ spinner.fail("❌")
358
+ return False
359
+
360
+ model = PlatformRegistry().get_codegen_platform()
361
+ model.set_suppress_output(False)
362
+
363
+ prompt = f"""
364
+ # 代码补丁生成专家指南
365
+
366
+ ## 任务描述
367
+ 你是一位精确的代码补丁生成专家,需要根据补丁描述生成精确的代码差异。
368
+
369
+ ## 输入资料
370
+ ### 原始代码
371
+ ```
372
+ {old_file_content["stdout"]}
373
+ ```
374
+
375
+ ### 补丁内容
376
+ ```
377
+ {patch_content}
378
+ ```
379
+
380
+ ## 补丁生成要求
381
+ 1. **精确性**:严格按照补丁的意图修改代码
382
+ 2. **格式一致性**:严格保持原始代码的格式风格
383
+ - 缩进方式(空格或制表符)必须与原代码保持一致
384
+ - 空行数量和位置必须与原代码风格匹配
385
+ - 行尾空格处理必须与原代码一致
386
+ 3. **最小化修改**:只修改必要的代码部分,保持其他部分不变
387
+ 4. **上下文完整性**:提供足够的上下文,确保补丁能准确应用
388
+
389
+ ## 输出格式规范
390
+ - 使用<DIFF>块包围每个需要修改的代码段
391
+ - 每个<DIFF>块必须包含SEARCH部分和REPLACE部分
392
+ - SEARCH部分是需要查找的原始代码
393
+ - REPLACE部分是替换后的新代码
394
+ - 确保SEARCH部分能在原文件中唯一匹配
395
+ - 如果修改较大,可以使用多个<DIFF>块
396
+
397
+ ## 输出模板
398
+ <DIFF>
399
+ >>>>>> SEARCH
400
+ [需要查找的原始代码,包含足够上下文]
401
+ ======
402
+ [替换后的新代码]
403
+ <<<<<< REPLACE
404
+ </DIFF>
405
+
406
+ <DIFF>
407
+ >>>>>> SEARCH
408
+ [另一处需要查找的原始代码]
409
+ ======
410
+ [另一处替换后的新代码]
411
+ <<<<<< REPLACE
412
+ </DIFF>
413
+ """
414
+ # 获取补丁内容
415
+ with spinner.hidden():
416
+ response = model.chat_until_success(prompt)
417
+
418
+ # 解析差异化补丁
419
+ diff_blocks = re.finditer(r'<DIFF>\s*>{4,} SEARCH\n?(.*?)\n?={4,}\n?(.*?)\s*<{4,} REPLACE\n?</DIFF>',
420
+ response, re.DOTALL)
421
+
422
+ # 读取原始文件内容
423
+ with open(filepath, 'r', encoding='utf-8', errors="ignore") as f:
424
+ file_content = f.read()
425
+
426
+ # 应用所有差异化补丁
427
+ modified_content = file_content
428
+ patch_count = 0
429
+
430
+ for match in diff_blocks:
431
+ search_text = match.group(1).strip()
432
+ replace_text = match.group(2).strip()
433
+ patch_count += 1
434
+ # 检查搜索文本是否存在于文件中
435
+ if search_text in modified_content:
436
+ # 如果有多处,报错
437
+ if modified_content.count(search_text) > 1:
438
+ spinner.text = f"补丁 #{patch_count} 应用失败:找到多个匹配的代码段"
439
+ spinner.fail("❌")
440
+ return False
441
+ # 应用替换
442
+ modified_content = modified_content.replace(search_text, replace_text)
443
+ spinner.write(f"✅ 补丁 #{patch_count} 应用成功")
444
+ else:
445
+ spinner.text = f"补丁 #{patch_count} 应用失败:无法找到匹配的代码段"
446
+ spinner.fail("❌")
447
+ return False
448
+
449
+ # 写入修改后的内容
450
+ with open(filepath, 'w', encoding='utf-8', errors="ignore") as f:
451
+ f.write(modified_content)
452
+
453
+ spinner.text = f"文件 {filepath} 修改完成,应用了 {patch_count} 个补丁"
454
+ spinner.ok("✅")
455
+ return True
456
+
457
+ except Exception as e:
458
+ spinner.text = f"文件修改失败: {str(e)}"
459
+ spinner.fail("❌")
460
+ return False
461
+
@@ -2,7 +2,6 @@
2
2
 
3
3
  from typing import Any, Tuple
4
4
 
5
- from jarvis.jarvis_tools.execute_shell_script import ShellScriptTool
6
5
  from jarvis.jarvis_tools.registry import ToolRegistry
7
6
  from jarvis.jarvis_utils.output import OutputType, PrettyOutput
8
7
  from jarvis.jarvis_utils.utils import user_confirm