jarvis-ai-assistant 0.1.212__py3-none-any.whl → 0.1.214__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.
jarvis/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """Jarvis AI Assistant"""
3
3
 
4
- __version__ = "0.1.212"
4
+ __version__ = "0.1.214"
@@ -119,13 +119,17 @@ origin_agent_system_prompt = f"""
119
119
 
120
120
 
121
121
  class OutputHandlerProtocol(Protocol):
122
- def name(self) -> str: ...
122
+ def name(self) -> str:
123
+ ...
123
124
 
124
- def can_handle(self, response: str) -> bool: ...
125
+ def can_handle(self, response: str) -> bool:
126
+ ...
125
127
 
126
- def prompt(self) -> str: ...
128
+ def prompt(self) -> str:
129
+ ...
127
130
 
128
- def handle(self, response: str, agent: Any) -> Tuple[bool, Any]: ...
131
+ def handle(self, response: str, agent: Any) -> Tuple[bool, Any]:
132
+ ...
129
133
 
130
134
 
131
135
  class Agent:
@@ -191,9 +195,7 @@ class Agent:
191
195
  if isinstance(platform, str):
192
196
  self.model = PlatformRegistry().create_platform(platform)
193
197
  if self.model is None:
194
- PrettyOutput.print(
195
- f"平台 {platform} 不存在,将使用普通模型", OutputType.WARNING
196
- )
198
+ PrettyOutput.print(f"平台 {platform} 不存在,将使用普通模型", OutputType.WARNING)
197
199
  self.model = PlatformRegistry().get_normal_platform()
198
200
  else:
199
201
  self.model = platform
@@ -356,6 +358,33 @@ class Agent:
356
358
  """
357
359
  self.after_tool_call_cb = cb
358
360
 
361
+ def save_session(self) -> bool:
362
+ """保存当前会话状态到文件"""
363
+ if not self.model:
364
+ PrettyOutput.print("没有可用的模型实例来保存会话。", OutputType.ERROR)
365
+ return False
366
+ session_dir = os.path.join(os.getcwd(), ".jarvis")
367
+ os.makedirs(session_dir, exist_ok=True)
368
+ session_file = os.path.join(session_dir, "saved_session.json")
369
+ return self.model.save(session_file)
370
+
371
+ def restore_session(self) -> bool:
372
+ """从文件恢复会话状态"""
373
+ if not self.model:
374
+ return False # No model, cannot restore
375
+ session_file = os.path.join(os.getcwd(), ".jarvis", "saved_session.json")
376
+ if not os.path.exists(session_file):
377
+ return False
378
+
379
+ if self.model.restore(session_file):
380
+ try:
381
+ os.remove(session_file)
382
+ PrettyOutput.print("会话已恢复,并已删除会话文件。", OutputType.SUCCESS)
383
+ except OSError as e:
384
+ PrettyOutput.print(f"删除会话文件失败: {e}", OutputType.ERROR)
385
+ return True
386
+ return False
387
+
359
388
  def get_tool_registry(self) -> Optional[Any]:
360
389
  """获取工具注册表实例"""
361
390
  from jarvis.jarvis_tools.registry import ToolRegistry
@@ -781,18 +810,14 @@ arguments:
781
810
 
782
811
  if get_interrupt():
783
812
  set_interrupt(False)
784
- user_input = self.multiline_inputer(
785
- f"模型交互期间被中断,请输入用户干预信息:"
786
- )
813
+ user_input = self.multiline_inputer(f"模型交互期间被中断,请输入用户干预信息:")
787
814
  if user_input:
788
815
  # 如果有工具调用且用户确认继续,则将干预信息和工具执行结果拼接为prompt
789
816
  if any(
790
817
  handler.can_handle(current_response)
791
818
  for handler in self.output_handler
792
819
  ):
793
- if user_confirm(
794
- "检测到有工具调用,是否继续处理工具调用?", True
795
- ):
820
+ if user_confirm("检测到有工具调用,是否继续处理工具调用?", True):
796
821
  self.prompt = f"{user_input}\n\n{current_response}"
797
822
  continue
798
823
  self.prompt += f"{user_input}"
@@ -838,9 +863,7 @@ arguments:
838
863
  if self.use_methodology:
839
864
  if not upload_methodology(self.model, other_files=self.files):
840
865
  if self.files:
841
- PrettyOutput.print(
842
- "文件上传失败,将忽略文件列表", OutputType.WARNING
843
- )
866
+ PrettyOutput.print("文件上传失败,将忽略文件列表", OutputType.WARNING)
844
867
  # 上传失败则回退到本地加载
845
868
  msg = self.prompt
846
869
  for handler in self.input_handler:
@@ -848,14 +871,14 @@ arguments:
848
871
  self.prompt = f"{self.prompt}\n\n以下是历史类似问题的执行经验,可参考:\n{load_methodology(msg, self.get_tool_registry())}"
849
872
  else:
850
873
  if self.files:
851
- self.prompt = f"{self.prompt}\n\n上传的文件包含历史对话信息和方法论文件,可以从中获取一些经验信息。"
874
+ self.prompt = (
875
+ f"{self.prompt}\n\n上传的文件包含历史对话信息和方法论文件,可以从中获取一些经验信息。"
876
+ )
852
877
  else:
853
878
  self.prompt = f"{self.prompt}\n\n上传的文件包含历史对话信息,可以从中获取一些经验信息。"
854
879
  elif self.files:
855
880
  if not self.model.upload_files(self.files):
856
- PrettyOutput.print(
857
- "文件上传失败,将忽略文件列表", OutputType.WARNING
858
- )
881
+ PrettyOutput.print("文件上传失败,将忽略文件列表", OutputType.WARNING)
859
882
  else:
860
883
  self.prompt = f"{self.prompt}\n\n上传的文件包含历史对话信息,可以从中获取一些经验信息。"
861
884
  else:
@@ -1,5 +1,6 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  import re
3
+ import sys
3
4
  from typing import Any, Tuple
4
5
 
5
6
  from jarvis.jarvis_utils.config import get_replace_map
@@ -29,7 +30,6 @@ def builtin_input_handler(user_input: str, agent_: Any) -> Tuple[str, bool]:
29
30
  replace_map = get_replace_map()
30
31
  # 处理每个标记
31
32
  for tag in special_tags:
32
-
33
33
  # 优先处理特殊标记
34
34
  if tag == "Summary":
35
35
  agent._summarize_and_clear_history()
@@ -51,6 +51,17 @@ def builtin_input_handler(user_input: str, agent_: Any) -> Tuple[str, bool]:
51
51
 
52
52
  load_config()
53
53
  return "", True
54
+ elif tag == "SaveSession":
55
+ if agent.save_session():
56
+ from jarvis.jarvis_utils.output import OutputType, PrettyOutput
57
+
58
+ PrettyOutput.print("会话已成功保存。正在退出...", OutputType.SUCCESS)
59
+ sys.exit(0)
60
+ else:
61
+ from jarvis.jarvis_utils.output import OutputType, PrettyOutput
62
+
63
+ PrettyOutput.print("保存会话失败。", OutputType.ERROR)
64
+ return "", True
54
65
 
55
66
  processed_tag = set()
56
67
  add_on_prompt = ""
@@ -206,48 +206,60 @@ class EditFileHandler(OutputHandler):
206
206
  exact_search = search_text
207
207
 
208
208
  if exact_search in modified_content:
209
- if modified_content.count(exact_search) > 1:
210
- PrettyOutput.print(
211
- f"搜索文本在文件中存在多处匹配:\n{exact_search}",
212
- output_type=OutputType.WARNING,
213
- )
214
- return False, f"搜索文本在文件中存在多处匹配:\n{exact_search}"
215
-
216
209
  # 直接执行替换(保留所有原始格式)
217
210
  modified_content = modified_content.replace(
218
211
  exact_search, replace_text
219
212
  )
220
213
  print(f"✅ 补丁 #{patch_count} 应用成功")
221
214
  else:
222
- # 尝试增加缩进重试
223
215
  found = False
224
- for space_count in range(1, 17):
225
- indented_search = "\n".join(
226
- " " * space_count + line if line.strip() else line
227
- for line in search_text.split("\n")
228
- )
229
- indented_replace = "\n".join(
230
- " " * space_count + line if line.strip() else line
231
- for line in replace_text.split("\n")
232
- )
233
- if indented_search in modified_content:
234
- if modified_content.count(indented_search) > 1:
235
- PrettyOutput.print(
236
- f"搜索文本在文件中存在多处匹配:\n{indented_search}",
237
- output_type=OutputType.WARNING,
238
- )
239
- return (
240
- False,
241
- f"搜索文本在文件中存在多处匹配:\n{indented_search}",
242
- )
216
+ # 如果匹配不到,并且search与replace块的首尾都是换行,尝试去掉第一个和最后一个换行
217
+ if (
218
+ search_text.startswith("\n")
219
+ and search_text.endswith("\n")
220
+ and replace_text.startswith("\n")
221
+ and replace_text.endswith("\n")
222
+ ):
223
+ stripped_search = search_text[1:-1]
224
+ stripped_replace = replace_text[1:-1]
225
+ if stripped_search in modified_content:
243
226
  modified_content = modified_content.replace(
244
- indented_search, indented_replace
245
- )
246
- print(
247
- f"✅ 补丁 #{patch_count} 应用成功 (自动增加 {space_count} 个空格缩进)"
227
+ stripped_search, stripped_replace
248
228
  )
229
+ print(f"✅ 补丁 #{patch_count} 应用成功 (自动去除首尾换行)")
249
230
  found = True
250
- break
231
+
232
+ if not found:
233
+ # 尝试增加缩进重试
234
+ current_search = search_text
235
+ current_replace = replace_text
236
+ if (
237
+ current_search.startswith("\n")
238
+ and current_search.endswith("\n")
239
+ and current_replace.startswith("\n")
240
+ and current_replace.endswith("\n")
241
+ ):
242
+ current_search = current_search[1:-1]
243
+ current_replace = current_replace[1:-1]
244
+
245
+ for space_count in range(1, 17):
246
+ indented_search = "\n".join(
247
+ " " * space_count + line if line.strip() else line
248
+ for line in current_search.split("\n")
249
+ )
250
+ indented_replace = "\n".join(
251
+ " " * space_count + line if line.strip() else line
252
+ for line in current_replace.split("\n")
253
+ )
254
+ if indented_search in modified_content:
255
+ modified_content = modified_content.replace(
256
+ indented_search, indented_replace
257
+ )
258
+ print(
259
+ f"✅ 补丁 #{patch_count} 应用成功 (自动增加 {space_count} 个空格缩进)"
260
+ )
261
+ found = True
262
+ break
251
263
 
252
264
  if not found:
253
265
  PrettyOutput.print(
@@ -131,7 +131,7 @@ class CodeAgent:
131
131
  input_handler=[shell_input_handler, builtin_input_handler],
132
132
  need_summary=need_summary,
133
133
  use_methodology=False, # 禁用方法论
134
- use_analysis=False # 禁用分析
134
+ use_analysis=False, # 禁用分析
135
135
  )
136
136
 
137
137
  self.agent.set_after_tool_call_cb(self.after_tool_call_cb)
@@ -359,9 +359,7 @@ class CodeAgent:
359
359
 
360
360
  # 添加提交信息到final_ret
361
361
  if commits:
362
- final_ret += (
363
- f"\n\n代码已修改完成\n补丁内容:\n```diff\n{diff}\n```\n"
364
- )
362
+ final_ret += f"\n\n代码已修改完成\n补丁内容:\n```diff\n{diff}\n```\n"
365
363
  # 修改后的提示逻辑
366
364
  lint_tools_info = "\n".join(
367
365
  f" - {file}: 使用 {'、'.join(get_lint_tools(file))}"
@@ -380,6 +378,7 @@ class CodeAgent:
380
378
  {file_list}
381
379
  {tool_info}
382
380
  如果本次修改引入了警告和错误,请根据警告和错误信息修复代码
381
+ 注意:如果要进行静态检查,需要在所有的修改都完成之后进行集中检查
383
382
  """
384
383
  agent.set_addon_prompt(addon_prompt)
385
384
  else:
@@ -428,6 +427,13 @@ def main() -> None:
428
427
 
429
428
  try:
430
429
  agent = CodeAgent(platform=args.platform, model=args.model, need_summary=False)
430
+
431
+ # 尝试恢复会话
432
+ if agent.agent.restore_session():
433
+ PrettyOutput.print(
434
+ "已从 .jarvis/saved_session.json 恢复会话。", OutputType.SUCCESS
435
+ )
436
+
431
437
  if args.requirement:
432
438
  agent.run(args.requirement)
433
439
  else: