包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
606 lines
23 KiB
Python
606 lines
23 KiB
Python
"""
|
||
Claude Code 改码引擎
|
||
====================
|
||
|
||
【功能说明】
|
||
把 Claude Code CLI 作为「改码执行器」接入 Agent 系统。
|
||
当 CODING_ENGINE=claude_code 时,Worker 的 modify 节点调用
|
||
Claude Code 完成代码阅读、理解、修改,替代自研工具链。
|
||
|
||
【技术选型理由】
|
||
1. 选 subprocess 调用 claude CLI 而非 Agent SDK:
|
||
CLI 成熟稳定、已配置好 ccswitch 模型路由、无需额外依赖。
|
||
2. 非交互模式(-p / --print):一次调用完成任务并输出结果,
|
||
适合编排集成。
|
||
3. 工作目录指向项目代码根目录:Claude Code 在该目录下读写文件。
|
||
|
||
【实现思路】
|
||
- build_prompt():把任务描述、目标文件线索、上次失败原因组装成 Prompt;
|
||
- execute():subprocess 调用 claude CLI,捕获输出;
|
||
- 结果解析:提取 Claude Code 的改动摘要与执行结论。
|
||
|
||
【潜在风险与应对】
|
||
风险1:claude CLI 不可用(未安装/PATH 缺失)。
|
||
应对:启动时探测,失败则降级到 builtin 引擎并告警。
|
||
风险2:Claude Code 改码范围过大(改无关文件)。
|
||
应对:Prompt 中明确约束「只改指定文件的指定问题」,
|
||
执行前对目标目录做快照(复用 file_tools 的备份机制)。
|
||
风险3:执行时间长(Claude Code 自主循环改码)。
|
||
应对:超时默认 300 秒,超时后终止并降级。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import shutil
|
||
import subprocess
|
||
import uuid
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from app.tools.audit import log_action
|
||
from app.tools.file_tools import _backup_file
|
||
|
||
logger = logging.getLogger("agent.claude_engine")
|
||
|
||
# 运行中的子进程注册表:task_id → Popen(供「停止」按钮 kill 用)
|
||
_running_processes: dict[str, subprocess.Popen] = {}
|
||
|
||
|
||
def kill_process(task_id: str) -> bool:
|
||
"""
|
||
强制终止指定任务的 Claude CLI 子进程。
|
||
|
||
【用途】用户点「停止」时调用,防止进程失控。
|
||
【返回】是否成功 kill
|
||
"""
|
||
proc = _running_processes.pop(task_id, None)
|
||
if proc is None:
|
||
return False
|
||
try:
|
||
proc.kill()
|
||
proc.wait()
|
||
logger.info("已终止任务 %s 的 Claude 进程", task_id)
|
||
return True
|
||
except Exception as exc: # noqa: BLE001
|
||
logger.warning("终止进程失败:%s", exc)
|
||
return False
|
||
|
||
|
||
class ClaudeCodeError(RuntimeError):
|
||
"""Claude Code 引擎异常"""
|
||
|
||
def __init__(self, message: str, *, error_type: str = "ClaudeCodeError") -> None:
|
||
super().__init__(message)
|
||
self.error_type = error_type
|
||
|
||
|
||
def is_available() -> bool:
|
||
"""检测 claude CLI 是否可用。"""
|
||
return shutil.which("claude") is not None
|
||
|
||
|
||
def get_claude_path() -> str:
|
||
"""
|
||
获取 claude CLI 的完整可执行路径。
|
||
|
||
【Windows 坑】subprocess.run(["claude"], shell=False) 找不到 claude.CMD,
|
||
因为不走 PATHEXT 扩展名解析。必须用 shutil.which 拿到完整路径再调用。
|
||
"""
|
||
path = shutil.which("claude")
|
||
if not path:
|
||
raise ClaudeCodeError(
|
||
"claude CLI 不可用,请确认已安装 Claude Code 并加入 PATH",
|
||
error_type="ClaudeNotFound",
|
||
)
|
||
return path
|
||
|
||
|
||
def _extract_session_id_from_line(line: str) -> str:
|
||
"""从单行 stream-json 中取 session_id(取不到返回空串)。"""
|
||
import json as _json
|
||
|
||
line = line.strip()
|
||
if not line:
|
||
return ""
|
||
try:
|
||
obj = _json.loads(line)
|
||
except Exception: # noqa: BLE001
|
||
return ""
|
||
if isinstance(obj, dict) and obj.get("session_id"):
|
||
return str(obj["session_id"])
|
||
return ""
|
||
|
||
|
||
class _StreamTextExtractor:
|
||
"""
|
||
从 Claude Code stream-json 逐行提取可展示文本(有状态)。
|
||
|
||
【为什么要状态】
|
||
`--include-partial-messages` 打开后,同一条回复会出现两遍:
|
||
① 增量:{"type":"stream_event","event":{"type":"content_block_delta",
|
||
"delta":{"type":"text_delta","text":"..."}}}
|
||
② 成块:{"type":"assistant","message":{"content":[{"type":"text","text":"..."}]}}
|
||
两者都推给前端,文本会翻倍。故:已推过增量就跳过成块文本。
|
||
|
||
【兼容的三种形状】
|
||
A. Claude Code CLI 增量(嵌在 event 里)
|
||
B. Messages API 增量(顶层 delta)—— 历史实现按此解析,保留兼容
|
||
C. 成块文本(assistant / message.content)—— 未开 partial 时的兜底
|
||
|
||
【刻意不推】
|
||
`result` 是最终汇总,前端已通过增量/成块累积过,再推必重复(沿用 BUG-2 原则)。
|
||
"""
|
||
|
||
def __init__(self) -> None:
|
||
self._saw_delta = False
|
||
|
||
def feed(self, line: str) -> str:
|
||
line = line.strip()
|
||
if not line:
|
||
return ""
|
||
import json as _json
|
||
|
||
try:
|
||
obj = _json.loads(line)
|
||
except Exception: # noqa: BLE001 - 非 JSON 行,原样透出
|
||
return line + "\n"
|
||
if not isinstance(obj, dict):
|
||
return ""
|
||
|
||
# ① 错误事件必须透出,用户要看到失败原因
|
||
if obj.get("type") == "error" and isinstance(obj.get("message"), str):
|
||
return f"\n[错误] {obj['message']}"
|
||
|
||
# ② 增量形状 A:CLI 的 stream_event 嵌套
|
||
event = obj.get("event")
|
||
if isinstance(event, dict):
|
||
delta = event.get("delta")
|
||
if isinstance(delta, dict) and isinstance(delta.get("text"), str):
|
||
self._saw_delta = True
|
||
return delta["text"]
|
||
|
||
# ③ 增量形状 B:Messages API 顶层 delta
|
||
delta = obj.get("delta")
|
||
if isinstance(delta, dict) and isinstance(delta.get("text"), str):
|
||
self._saw_delta = True
|
||
return delta["text"]
|
||
|
||
# ④ 成块文本(形状 C):已有增量就跳过,防重复
|
||
if self._saw_delta:
|
||
return ""
|
||
return self._block_text(obj)
|
||
|
||
@staticmethod
|
||
def _block_text(obj: dict) -> str:
|
||
"""取成块文本:只认 type=text 的 content block,跳过 tool_use / tool_result。"""
|
||
if isinstance(obj.get("result"), str):
|
||
return "" # 最终汇总不推流式,防重复
|
||
msg = obj.get("message")
|
||
source = msg if isinstance(msg, dict) else obj
|
||
content = source.get("content")
|
||
if isinstance(content, str):
|
||
return content
|
||
if isinstance(content, list):
|
||
parts = [
|
||
block.get("text", "")
|
||
for block in content
|
||
if isinstance(block, dict)
|
||
and block.get("type") == "text"
|
||
and isinstance(block.get("text"), str)
|
||
]
|
||
return "".join(parts)
|
||
return ""
|
||
|
||
|
||
def _extract_stream_text(line: str) -> str:
|
||
"""
|
||
无状态便捷入口:单行提取文本(不跨行去重)。
|
||
|
||
【注意】execute() 内部用有状态的 _StreamTextExtractor;
|
||
此函数仅供单行调试/兼容旧调用,跨行场景会失去 delta/成块去重能力。
|
||
"""
|
||
return _StreamTextExtractor().feed(line)
|
||
|
||
|
||
def _extract_final_text(stdout: str) -> str:
|
||
"""
|
||
从 stream-json 全量输出中提取最终完整文本。
|
||
|
||
优先取顶层 `result` 字段(Claude 的最终汇总,最权威);
|
||
没有 result 行时用 _StreamTextExtractor 累积(自动去重 delta 与成块文本)。
|
||
"""
|
||
import json as _json
|
||
|
||
for line in stdout.splitlines():
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
obj = _json.loads(line)
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
if isinstance(obj, dict) and isinstance(obj.get("result"), str):
|
||
return obj["result"]
|
||
|
||
extractor = _StreamTextExtractor()
|
||
parts = [text for text in (extractor.feed(line) for line in stdout.splitlines()) if text]
|
||
return "".join(parts)
|
||
|
||
|
||
def _extract_session_id(stdout: str) -> str:
|
||
"""
|
||
从 stream-json 输出中提取 Claude 会话 ID。
|
||
|
||
stream-json 开头会有:{"type":"system","subtype":"init","session_id":"xxx",...}
|
||
"""
|
||
for line in stdout.splitlines():
|
||
sid = _extract_session_id_from_line(line)
|
||
if sid:
|
||
return sid
|
||
return ""
|
||
|
||
|
||
def _normalize_model_id(model: str) -> str:
|
||
"""
|
||
从模型注册表 key 中提取真实 model_id。
|
||
|
||
【背景】模型管理的注册表 key 格式是 "provider_key/model_id"(如 "小米6360/mimo-v2.6-pro"),
|
||
但 Claude CLI 只认 model_id(如 "mimo-v2.6-pro"),不认带前缀的 key。
|
||
【规则】含 "/" 时取最后一段作为 model_id;不含则原样返回。
|
||
"""
|
||
if not model:
|
||
return model
|
||
return model.rsplit("/", 1)[-1] if "/" in model else model
|
||
|
||
|
||
def prepare_claude_config(model_id: str, session_id: str = "") -> Path:
|
||
"""
|
||
生成 Claude Code 独立配置目录(不动用户的 ~/.claude/settings.json)。
|
||
|
||
【方案】在 ~/.claude/agent-{session_id}/ 下写一份 settings.json,
|
||
连接信息(base_url + api_key)从 Provider 管理读,
|
||
模型名从用户提交时选的 model_id 取。
|
||
【关键】目录名用 session_id 做持久化——续聊时复用同一目录,
|
||
否则 --resume 找不到上一轮的会话!
|
||
【调用时】通过 CLAUDE_CONFIG_DIR 环境变量让 claude CLI 用这份配置。
|
||
"""
|
||
import json as _json
|
||
|
||
# 用 session_id 做目录名,确保续聊时复用同一目录(会话文件在里面)
|
||
dir_name = f"agent-{session_id[:12]}" if session_id else f"agent-{uuid.uuid4().hex[:12]}"
|
||
cfg_dir = Path.home() / ".claude" / dir_name
|
||
cfg_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
# 1. 从模型配置找 provider_key → 从 Provider 管理拿 base_url + api_key
|
||
# 注意:model_id 可能是注册表 key("provider_key/model_id"),需要提取真实 model_id
|
||
real_model_id = _normalize_model_id(model_id)
|
||
base_url, api_key = "", ""
|
||
try:
|
||
from app.store.model_config_store import get_model_config_store
|
||
from app.store.provider_store import get_provider_store
|
||
|
||
# 按 model_id 找模型配置(取第一个匹配的)
|
||
mc_store = get_model_config_store()
|
||
all_models = mc_store.list_all()
|
||
target_model = next((m for m in all_models if m.model_id == real_model_id), None)
|
||
if target_model:
|
||
provider_key = target_model.provider_key
|
||
provider = get_provider_store().get_with_key(provider_key)
|
||
if provider:
|
||
base_url = provider.get("base_url", "")
|
||
api_key = provider.get("api_key", "")
|
||
except Exception: # noqa: BLE001 - 读不到就降级为空(走 CLI 默认)
|
||
pass
|
||
|
||
# 2. 继承用户 settings.json 的非模型字段(如 AUTH_TOKEN),只替换核心的
|
||
user_cfg_path = Path.home() / ".claude" / "settings.json"
|
||
user_env: dict = {}
|
||
if user_cfg_path.exists():
|
||
try:
|
||
user_cfg = _json.loads(user_cfg_path.read_text(encoding="utf-8"))
|
||
user_env = dict(user_cfg.get("env", {}))
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
# 3. 组装独立配置:连接信息覆盖为 Provider 管理的值,模型覆盖为用户选的
|
||
env = {
|
||
**user_env,
|
||
"ANTHROPIC_MODEL": real_model_id,
|
||
"CLAUDE_CODE_SUBAGENT_MODEL": real_model_id,
|
||
}
|
||
if base_url:
|
||
env["ANTHROPIC_BASE_URL"] = base_url
|
||
if api_key:
|
||
env["ANTHROPIC_AUTH_TOKEN"] = api_key
|
||
|
||
clean_cfg = {"env": env, "model": real_model_id}
|
||
settings_file = cfg_dir / "settings.json"
|
||
settings_file.write_text(
|
||
_json.dumps(clean_cfg, ensure_ascii=False, indent=2), encoding="utf-8"
|
||
)
|
||
logger.info(
|
||
"已生成 Claude Code 独立配置:%s(模型=%s,provider_base_url=%s)",
|
||
settings_file, real_model_id, base_url or "继承",
|
||
)
|
||
return cfg_dir
|
||
|
||
|
||
def build_prompt(
|
||
step_description: str,
|
||
expected_output: str,
|
||
target_files: list[str],
|
||
prev_error: str = "",
|
||
retry: int = 0,
|
||
) -> str:
|
||
"""
|
||
构建 Claude Code 的改码 Prompt。
|
||
|
||
【要点】
|
||
- 明确任务范围(只改指定文件);
|
||
- 附带上次失败原因(修复循环);
|
||
- 要求代码注释(符合项目规范)。
|
||
"""
|
||
files_desc = "\n".join(f" - {f}" for f in target_files[:5]) if target_files else " - 请自行定位相关文件"
|
||
|
||
retry_hint = f"\n【上次修改失败原因,请修正】{prev_error}" if prev_error else ""
|
||
|
||
return f"""你是一个 Java 项目代码修复工程师。请完成以下修改任务。
|
||
|
||
【修改任务】{step_description}
|
||
【预期产出】{expected_output}
|
||
【重试次数】{retry}{retry_hint}
|
||
|
||
【候选文件】
|
||
{files_desc}
|
||
|
||
【硬性要求】
|
||
1. 只修改与本任务直接相关的代码,禁止改动无关文件;
|
||
2. 修改处必须加中文注释(说明功能、修改原因);
|
||
3. 修改完成后自行检查代码语法正确性;
|
||
4. 完成后在最后一行输出固定格式摘要:DONE: <一句话修改说明>。"""
|
||
|
||
|
||
def execute(
|
||
project_root: Path,
|
||
prompt: str,
|
||
task_id: str = "",
|
||
timeout: int = 0,
|
||
model: str = "",
|
||
on_output=None,
|
||
session_id: str = "",
|
||
resume: bool = False,
|
||
skip_snapshot: bool = False,
|
||
on_session=None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
调用 Claude Code CLI 执行任务(零限制,流式输出,会话续聊)。
|
||
|
||
【参数】
|
||
project_root:项目代码根目录
|
||
prompt:用户原话,不做任何包装
|
||
task_id:任务 ID(用于审计与快照)
|
||
timeout:0=不超时,跑完为止
|
||
model:模型名
|
||
on_output:流式回调 fn(text),每提取到一段可展示文本调用一次
|
||
session_id:Claude 会话 ID(首次传入 = 指定会话;resume 时 = 续接该会话)
|
||
resume:True = 用 --resume 续接已有会话(Claude 自己管上下文)
|
||
skip_snapshot:True = 跳过文件快照(对话续聊不需要快照代码)
|
||
on_session:会话就绪回调 fn(session_id),CLI 一吐出 init 事件立刻触发
|
||
—— 供调用方提前落库,避免执行完才补写时进程已死
|
||
"""
|
||
project_root = Path(project_root)
|
||
if not project_root.exists():
|
||
raise ClaudeCodeError(f"项目根目录不存在:{project_root}", error_type="PathNotFound")
|
||
claude_path = get_claude_path() # 拿完整路径,绕过 Windows PATHEXT 问题
|
||
|
||
# 执行前对项目做快照(对话续聊跳过,代码改码才需要)
|
||
if not skip_snapshot:
|
||
try:
|
||
snapshot_count = 0
|
||
for java_file in project_root.rglob("*.java"):
|
||
if _backup_file(java_file, task_id):
|
||
snapshot_count += 1
|
||
if snapshot_count >= 20:
|
||
break
|
||
logger.info("改码前快照完成:%d 个文件", snapshot_count)
|
||
except Exception as exc: # noqa: BLE001
|
||
logger.warning("改码前快照失败(继续执行):%s", exc)
|
||
|
||
import time
|
||
|
||
start = time.time()
|
||
logger.info("调用 Claude Code 执行改码任务(cwd=%s)", project_root)
|
||
|
||
cfg_dir: Path | None = None # 临时配置目录,finally 中清理
|
||
try:
|
||
real_model = _normalize_model_id(model) if model else ""
|
||
cmd = [
|
||
claude_path,
|
||
"-p", # --print 模式,prompt 从 STDIN 读取
|
||
"--permission-mode", "acceptEdits",
|
||
"--output-format", "stream-json",
|
||
# 【13.7 修复】不加这个参数,stream-json 只吐成块消息,没有逐字增量,
|
||
# 前端只能在 done 时一把出。加了才会输出 stream_event/content_block_delta。
|
||
"--include-partial-messages",
|
||
"--verbose",
|
||
]
|
||
# 会话机制(终端同款):续聊用 --resume,首轮/无 session_id 时必须用 --session-id
|
||
# 【关键】session_id 为空也必须传 --session-id(随机 UUID),
|
||
# 否则 Claude CLI 默认续接 cwd 下的上一个会话 → 串台!
|
||
use_resume = bool(resume and session_id)
|
||
if use_resume:
|
||
cmd += ["--resume", session_id]
|
||
else:
|
||
if not session_id:
|
||
session_id = str(uuid.uuid4())
|
||
cmd += ["--session-id", session_id]
|
||
if real_model and real_model != "auto" and real_model.startswith("claude-"):
|
||
cmd += ["--model", real_model]
|
||
|
||
import os
|
||
env = os.environ.copy()
|
||
if real_model and real_model != "auto":
|
||
env["ANTHROPIC_MODEL"] = real_model
|
||
# 【关键】用 session_id 做目录名持久化,续聊时复用同一目录
|
||
cfg_dir = prepare_claude_config(real_model, session_id)
|
||
env["CLAUDE_CONFIG_DIR"] = str(cfg_dir)
|
||
else:
|
||
env.pop("ANTHROPIC_MODEL", None)
|
||
|
||
# 流式执行:prompt 从 STDIN 传入(避免命令行截断/乱码)
|
||
import subprocess as sp
|
||
|
||
from app.tools.proc_flags import hidden_popen_kwargs
|
||
|
||
process = sp.Popen(
|
||
cmd,
|
||
cwd=str(project_root),
|
||
stdin=sp.PIPE,
|
||
stdout=sp.PIPE,
|
||
stderr=sp.STDOUT,
|
||
text=True,
|
||
encoding="utf-8",
|
||
errors="replace",
|
||
env=env,
|
||
shell=False,
|
||
bufsize=1, # 行缓冲,逐行输出
|
||
# 【弹窗修复】claude 的入口是 claude.CMD(控制台程序),
|
||
# 直接拉起会分配可见控制台窗口。CREATE_NO_WINDOW 让它照常跑但不弹窗。
|
||
# 注意:不要用 DETACHED_PROCESS,它才是弹窗元凶(见 proc_flags 实测表)。
|
||
**hidden_popen_kwargs(),
|
||
)
|
||
# 写入 prompt 到 STDIN 并关闭
|
||
process.stdin.write(prompt)
|
||
process.stdin.close()
|
||
# 注册进程,供外部「停止」按钮 kill
|
||
if task_id:
|
||
_running_processes[task_id] = process
|
||
try:
|
||
output_lines: list[str] = []
|
||
extractor = _StreamTextExtractor()
|
||
session_reported = False
|
||
# 逐行读取 stream-json,提取文本内容后回调
|
||
while True:
|
||
line = process.stdout.readline()
|
||
if not line and process.poll() is not None:
|
||
break
|
||
if line:
|
||
output_lines.append(line)
|
||
# 【13.8 修复】会话 ID 一拿到就立刻回调落库,
|
||
# 不等 execute() 返回——进程随时可能被 reload 杀掉。
|
||
if on_session and not session_reported:
|
||
sid = _extract_session_id_from_line(line)
|
||
if sid:
|
||
session_reported = True
|
||
try:
|
||
on_session(sid)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
if on_output:
|
||
try:
|
||
text = extractor.feed(line)
|
||
if text:
|
||
on_output(text)
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
process.wait(timeout=timeout if timeout and timeout > 0 else None)
|
||
finally:
|
||
# 【BUG-3 修复】异常/退出时确保子进程被清理,防止僵尸进程
|
||
if process.poll() is None:
|
||
process.kill()
|
||
process.wait()
|
||
|
||
class _FakeCompleted:
|
||
"""模拟 subprocess.run 返回结构,统一后续处理"""
|
||
def __init__(self, rc: int) -> None:
|
||
self.returncode = rc
|
||
self.stdout = "".join(output_lines)
|
||
self.stderr = ""
|
||
|
||
completed = _FakeCompleted(process.returncode)
|
||
|
||
duration = round(time.time() - start, 1)
|
||
stdout = completed.stdout or ""
|
||
|
||
# 从 stream-json 提取完整文本输出(result 字段)
|
||
output = _extract_final_text(stdout)
|
||
if not output:
|
||
# 【BUG-3 修复】降级兜底时过滤 JSON 行,只保留纯文本
|
||
text_lines = []
|
||
for line in stdout.splitlines():
|
||
stripped = line.strip()
|
||
if stripped.startswith("{") and stripped.endswith("}"):
|
||
continue # 跳过 stream-json 行
|
||
if stripped:
|
||
text_lines.append(stripped)
|
||
output = "\n".join(text_lines) if text_lines else stdout
|
||
|
||
# 提取 Claude 会话 ID(供 --resume 续聊用)
|
||
detected_session_id = _extract_session_id(stdout)
|
||
|
||
# 成功判定:returncode==0 即算成功
|
||
success = completed.returncode == 0
|
||
|
||
# 【13.8 兜底】--resume 找不到会话(配置目录丢失 / 会话被清理)时,
|
||
# 回退成 --session-id 重跑一次,避免整轮对话直接失败且上下文全丢。
|
||
if use_resume and not success and "No conversation found" in stdout:
|
||
logger.warning("会话 %s 已丢失,回退 --session-id 重跑一次", session_id)
|
||
return execute(
|
||
project_root=project_root,
|
||
prompt=prompt,
|
||
task_id=task_id,
|
||
timeout=timeout,
|
||
model=model,
|
||
on_output=on_output,
|
||
session_id=session_id,
|
||
resume=False,
|
||
skip_snapshot=True, # 首跑已快照过,重跑不再重复
|
||
on_session=on_session,
|
||
)
|
||
|
||
result = {
|
||
"success": success,
|
||
"output": output,
|
||
"summary": output.strip().splitlines()[-1][:200] if output.strip() else "(无输出)",
|
||
"duration": duration,
|
||
"returncode": completed.returncode,
|
||
"session_id": detected_session_id,
|
||
}
|
||
|
||
log_action(
|
||
action="claude_code_execute",
|
||
target=str(project_root),
|
||
result="success" if success else "failure",
|
||
details={
|
||
"summary": result["summary"][:200],
|
||
"duration": duration,
|
||
"returncode": completed.returncode,
|
||
"task_id": task_id,
|
||
},
|
||
)
|
||
logger.info("Claude Code 执行完成:success=%s, duration=%ss", success, duration)
|
||
return result
|
||
|
||
except FileNotFoundError as exc:
|
||
raise ClaudeCodeError(
|
||
f"claude CLI 未找到(路径:{claude_path}),请确认已安装 Claude Code",
|
||
error_type="ClaudeNotFound",
|
||
) from exc
|
||
except subprocess.TimeoutExpired as exc:
|
||
log_action(
|
||
action="claude_code_execute",
|
||
target=str(project_root),
|
||
result="failure",
|
||
details={"error": "timeout", "timeout": timeout, "task_id": task_id},
|
||
)
|
||
raise ClaudeCodeError(
|
||
f"Claude Code 执行超时(>{timeout}秒)", error_type="Timeout"
|
||
) from exc
|
||
finally:
|
||
# 注销进程
|
||
if task_id:
|
||
_running_processes.pop(task_id, None)
|
||
# 【注意】配置目录不能删!Claude 会话文件在里面,删了 --resume 就找不到了。
|
||
# 目录在任务删除时由 delete_task 统一清理。
|