JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:增强skillTurbo约束解决假成功问题
Chenchong_RD858140af5b79
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.pyindex 42378b375f..ba7a9c0da4 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.py@@ -2,15 +2,27 @@ from __future__ import annotationsimport loggingfrom collections.abc import AsyncIterator+from pathlib import Pathfrom typing import Anyfrom jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortError, PlanNodefrom jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_common import PptCommon+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.utils.bash_utils import (+ normalize_tool_text,+)logger = logging.getLogger(__name__)_DEFAULT_STRUCTURAL_PAGES = 2+_SEND_FAIL_MARKERS = (+ "发送文件失败",+ "所有文件均不存在",+ "没有可发送的文件",+ "提交文件失败",+ "文件不存在,未发送",+)+def _looks_like_path(value: str) -> bool:return "/" in value or "\\" in value or value.endswith(".html")@@ -79,12 +91,13 @@ class DeliveryNode(PlanNode):"summary": "交付失败:pages_dir 为空",}- pptx_ok = bool(pptx_path) and export_status != "failed"+ pptx_ok = bool(pptx_path) and export_status != "failed" and Path(pptx_path).is_file()if not pptx_ok:logger.error(- "[P10] PPTX 产物异常 pptx_path=%s export_status=%s",+ "[P10] PPTX 产物异常 pptx_path=%s export_status=%s exists=%s",bool(pptx_path),export_status,+ bool(pptx_path and Path(pptx_path).is_file()),)pages_ok = await self._check_pages(pages_dir, total_pages)@@ -93,17 +106,16 @@ class DeliveryNode(PlanNode):if pptx_ok and pptx_path:send_file_status = await self._send_file(pptx_path)- if not pptx_ok:+ if not pptx_ok or send_file_status == "failed":delivery_status = "failed"elif not pages_ok:delivery_status = "partial"else:delivery_status = "ok"- # 当 PPT 已成功发送给用户时,HTML 页面校验失败不应影响"任务已完成"判定:- # send_file_status=sent 表示用户已实际收到 PPT,task_completed 用于 __artifact__.info,- # 让 DeepAgent 主链路 LLM 能明确识别任务已完成,避免误调 skill_tool 重跑流程。- task_completed = send_file_status == "sent"+ # 仅当文件真实存在且工具确认发送成功时,才标记 task_completed。+ # send_file_to_user 在文件缺失时返回错误字符串但不抛异常,旧逻辑会误标 sent。+ task_completed = send_file_status == "sent" and pptx_okneed_artifact = send_file_status != "sent"artifact_tag = f"<!-- artifact:pptx {pages_dir} -->" if need_artifact and pages_dir else ""@@ -147,11 +159,19 @@ class DeliveryNode(PlanNode):logger.info("[P10] send_file_to_user 工具不可用,跳过文件发送")return "skipped"+ if not Path(pptx_path).is_file():+ logger.error("[P10] send_file 前文件不存在: %s", pptx_path)+ return "failed"+try:- await self.call_tool(+ result = await self.call_tool("send_file_to_user",abs_file_path_list=[pptx_path],)+ text = normalize_tool_text(result)+ if self._is_send_failure(text):+ logger.error("[P10] send_file_to_user 发送失败: %s", text[:500])+ return "failed"logger.info("[P10] send_file_to_user 发送成功: %s", pptx_path)return "sent"except Exception as e:@@ -160,6 +180,17 @@ class DeliveryNode(PlanNode):logger.warning("[P10] send_file_to_user 发送失败: %s", e)return "failed"+ @staticmethod+ def _is_send_failure(text: str) -> bool:+ if not text or not text.strip():+ # 空结果视为失败,避免“无回执当成功”+ return True+ lowered = text.strip()+ # 明确成功 / 会话内已投递过 → 不算失败+ if "成功发送" in lowered or "文件已在本次会话发送过" in lowered:+ return False+ return any(marker in lowered for marker in _SEND_FAIL_MARKERS)+async def _check_pages(self, pages_dir: str, page_count: int) -> bool:files: list[str] = []if self.has_tool("list_dir"):diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.pyindex 8e513d0c89..f16c5a3ac5 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.py@@ -4,7 +4,6 @@ import loggingimport refrom collections.abc import AsyncIteratorfrom dataclasses import dataclass-from pathlib import Pathfrom typing import Anyfrom jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortError, PlanNode@@ -53,24 +52,6 @@ class ExportPaths:pptx_root: str-def _pptx_exists_status(pptx_path: str) -> str:- """node stat 失败时的 pathlib 回退:存在且 ≥10KB→ok,>0→partial,否则 failed。"""- path = Path(pptx_path)- if path.is_file():- size = path.stat().st_size- if size >= 10 * 1024:- logger.info("[P9] PPTX Python fallback 验证通过 size=%d", size)- return "ok"- elif size > 0:- logger.warning("[P9] PPTX Python fallback 文件过小 size=%d", size)- return "partial"- else:- logger.warning("[P9] PPTX Python fallback 文件大小为 0")- return "failed"- logger.warning("[P9] PPTX 文件确认不存在: %s", pptx_path)- return "failed"--class PPTExportNode(PlanNode):"""P9 — PPTX 导出(对应 SKILL Stage 8)。"""@@ -116,7 +97,9 @@ class PPTExportNode(PlanNode):"- fill.js check 出现内容质量类 HARD 错误:export_status = failed(manifest 声明类警告忽略)\n""- snapshot-template-dna / template-safe fix 失败:export_status = failed\n""- cli.js convert 失败:export_status = failed,pptx_path 为空\n"+ "- PPTX 不存在 / stat 失败:export_status = failed\n""- PPTX 文件过小(< 10KB):export_status = partial\n"+ "- 上游 missing_pages 非空或 ppt_gen_status=failed:export_status = failed\n""- bash 不可用:export_status = failed\n"),)@@ -143,6 +126,24 @@ class PPTExportNode(PlanNode):pptx_root = str(inputs.get("pptx_root") or "").strip()+ # 上游 P8 缺页时 convert 必然因页码不连续失败;提前硬失败,避免假 status=ok。+ missing_pages = inputs.get("missing_pages") or []+ if isinstance(missing_pages, list) and missing_pages:+ logger.error("[P9] 上游页面缺失 missing=%s,拒绝导出", missing_pages)+ return {+ "pptx_path": "",+ "pptx_filename": pptx_filename,+ "export_status": "failed",+ }+ ppt_gen_status = str(inputs.get("ppt_gen_status") or "").strip()+ if ppt_gen_status == "failed":+ logger.error("[P9] 上游 ppt_gen_status=failed,拒绝导出")+ return {+ "pptx_path": "",+ "pptx_filename": pptx_filename,+ "export_status": "failed",+ }+# 模板画布分支:style_mode == template_canvas 时走模板终检导出流程style_mode = str(inputs.get("style_mode") or "").strip()if style_mode == "template_canvas":@@ -310,6 +311,14 @@ class PPTExportNode(PlanNode):"export_status": "failed",}+ export_status = await self._validate_pptx(pptx_path, pptx_root)+ if export_status == "failed":+ return {+ "pptx_path": "",+ "pptx_filename": pptx_filename,+ "export_status": "failed",+ }+# 6. 产物硬闸try:artifact_cmd = (@@ -325,11 +334,11 @@ class PPTExportNode(PlanNode):except BashExecError as e:logger.warning("[P9-TF] check-pptx-artifact 异常: %s(不阻塞交付)", e)- logger.info("[P9-TF] 模板终检导出完成: %s", pptx_path)+ logger.info("[P9-TF] 模板终检导出完成: %s status=%s", pptx_path, export_status)return {"pptx_path": pptx_path,"pptx_filename": pptx_filename,- "export_status": "ok",+ "export_status": export_status,}async def _run_convert(self, pages_dir: str, pptx_path: str, pptx_root: str) -> bool:@@ -365,19 +374,15 @@ class PPTExportNode(PlanNode):timeout_seconds=30, required=False, workdir=pptx_root,)if result.exit_code != 0:- logger.warning(- "[P9] PPTX stat 失败 exit=%d,尝试 Python fallback: %s",- result.exit_code, pptx_path,- )- return _pptx_exists_status(pptx_path)- stdout_stripped = result.stdout.strip()- if not stdout_stripped or not stdout_stripped.lstrip('-').isdigit():- logger.warning(- "[P9] PPTX stat 输出非数字,尝试 Python fallback: %s",- stdout_stripped[:200] if stdout_stripped else "(empty)",- )- return _pptx_exists_status(pptx_path)- size = int(stdout_stripped)+ detail = (result.stderr or result.stdout or "").strip()+ logger.error("[P9] PPTX 不存在或 stat 失败,导出判定 failed: %s", detail[:500])+ return "failed"+ size_text = (result.stdout or "").strip()+ try:+ size = int(size_text or "0")+ except ValueError:+ logger.error("[P9] PPTX 大小解析失败 stdout=%r", size_text[:200])+ return "failed"if size < 10 * 1024:logger.warning("[P9] PPTX 文件过小 size=%d < 10KB", size)return "partial"@@ -386,8 +391,8 @@ class PPTExportNode(PlanNode):except Exception as e:if isinstance(e, AbortError):raise- logger.warning("[P9] PPTX 验证失败,尝试 Python fallback: %s", e)- return _pptx_exists_status(pptx_path)+ logger.error("[P9] PPTX 验证失败: %s", e)+ return "failed"async def _execute_stream(self, inputs: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:result = await self._execute(inputs)diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.pyindex 9df7913784..c00f420bfc 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.py@@ -22,6 +22,9 @@ logger = logging.getLogger(__name__)_CHART_CANDIDATE_TYPES = {"data", "comparison", "technology", "trend"}+# P8.2:只读校验 / 单页 fix 硬超时,避免 read_file 或 bash 挂死拖死 gather。+_P82_READ_TIMEOUT_SECONDS = 60.0+_P82_FIX_ONE_TIMEOUT_SECONDS = 360.0def _extract_designer_section(@@ -439,6 +442,100 @@ def _has_placeholder_slop(text: str) -> bool:return normalized in _PLACEHOLDER_SLOP_VALUES+def _plain_text_fragment(html_fragment: str) -> str:+ return re.sub(r"<[^>]+>", "", html_fragment or "").strip()+++def _extract_filled_title_inner(filled_html: str) -> str:+ match = _H1_INNER_TEXT_RE.search(filled_html or "")+ if match:+ return match.group(2).strip()+ match = _TITLE_TAG_RE.search(filled_html or "")+ return match.group(2).strip() if match else ""+++def _extract_filled_footer_inner(filled_html: str) -> str:+ footer_block = _extract_footer_block(filled_html)+ if not footer_block:+ return ""+ match = _P_INNER_TEXT_RE.search(footer_block)+ return match.group(2).strip() if match else ""+++def _replace_main_inner_html(html: str, new_inner: str) -> str:+ open_match = _MAIN_OPEN_TAG_RE.search(html or "")+ if not open_match:+ return html or ""+ close_match = _MAIN_CLOSE_TAG_RE.search(html or "", open_match.end())+ if not close_match:+ return html or ""+ return (html or "")[:open_match.end()] + new_inner + (html or "")[close_match.start():]+++_REPAIRABLE_CONTENT_TEMPLATE_REASONS = frozenset({+ "content_template_chrome_changed",+ "main_tag_changed",+})+++def _repair_content_template_chrome(seed_html: str, filled_html: str) -> str | None:+ """Restore Page Chrome from seed; keep filled title/content/footer slot values.++ When the model rewrites head/header/footer/`<main>` chrome but still fills usable+ slots, reassemble onto the seed skeleton instead of forcing a full LLM retry.+ Returns None when filled output lacks extractable slot content.+ """+ if not (seed_html or "").strip() or not (filled_html or "").strip():+ return None++ title_inner = _extract_filled_title_inner(filled_html)+ if not title_inner or _has_placeholder_slop(_plain_text_fragment(title_inner)):+ return None++ main_inner = _extract_main_inner_html(filled_html)+ if not main_inner.strip() or "{{PAGE_CONTENT}}" in main_inner:+ return None++ footer_inner = _extract_filled_footer_inner(filled_html)+ if not footer_inner or _has_placeholder_slop(_plain_text_fragment(footer_inner)):+ return None++ out = seed_html+ if "{{PAGE_TITLE}}" in out:+ out = out.replace("{{PAGE_TITLE}}", title_inner)+ else:+ out = _TITLE_TAG_RE.sub(+ lambda m: f"{m.group(1)}{title_inner}{m.group(3)}",+ out,+ count=1,+ )+ out = _H1_INNER_TEXT_RE.sub(+ lambda m: f"{m.group(1)}{title_inner}{m.group(3)}",+ out,+ count=1,+ )++ if "{{PAGE_CONTENT}}" in out:+ out = out.replace("{{PAGE_CONTENT}}", main_inner)+ else:+ out = _replace_main_inner_html(out, main_inner)++ if "{{PAGE_FOOTER}}" in out:+ out = out.replace("{{PAGE_FOOTER}}", footer_inner)+ else:+ seed_footer = _extract_footer_block(out)+ if not seed_footer:+ return None+ repaired_footer = _P_INNER_TEXT_RE.sub(+ lambda m: f"{m.group(1)}{footer_inner}{m.group(3)}",+ seed_footer,+ count=1,+ )+ out = out.replace(seed_footer, repaired_footer, 1)++ return out++def _validate_content_template_fill_output(seed_html: str, filled_html: str) -> tuple[bool, str]:"""Stage 6 软门禁:内容页必须基于 seed 填槽,不能改 chrome。"""if not _is_valid_html(filled_html):@@ -575,6 +672,18 @@ def _build_content_template_fill_prompt("7. 每个占位符必须填有意义内容;禁止空串、`—`/`–`/`-`、`N/A`、`TBD`、`暂无`、`待补充`、`待定`、`占位`\n""8. 图表候选页必须优先激活模板内 `CHART_SCAFFOLD`,按模板注释填充 option;禁止额外手写第二套图表初始化框架\n""9. 直接输出完整 HTML,禁止 Markdown 代码块包裹与解释文字\n\n"+ "## Page Chrome 硬锁(违反将导致校验失败 `content_template_chrome_changed`)\n"+ "- **Chrome = 除 `{{PAGE_CONTENT}}` 以外的一切**:`<head>`(含 script/link/style/`tailwind.config`)、"+ "`.content-safe` 到 `<main>` 之前的 header 带、`<main>` 开标签、footer 骨架\n"+ "- **允许改动的仅是占位符文本**:\n"+ " - `<title>` / `<h1>` 内文字 ← `{{PAGE_TITLE}}`\n"+ " - footer 内首个 `<p>` 文字 ← `{{PAGE_FOOTER}}`\n"+ " - `<main>` **内部** HTML ← `{{PAGE_CONTENT}}`\n"+ "- **禁止**增删/重排 chrome 节点,禁止改 chrome 上的 class/style/属性/注释/空白结构,"+ "禁止把图表、卡片、遮罩、装饰线挪到 header/footer/`<head>`\n"+ "- **操作方式**:以预铺 HTML 为底稿,只做三处字符串级替换后原样输出;"+ "不要“重新生成一版更美观的同款页面”\n"+ "- **自检**:输出前对比预铺稿——若除上述三处文本/main 内部外仍有任何差异,必须撤回重填\n\n""## 风格文件(正文区配色/字体/组件权威;不得把风格元数据写成观众可见文字)\n"f"{style_text}\n\n""## 大纲 — 本页规划\n"@@ -588,7 +697,7 @@ def _build_content_template_fill_prompt(f"{designer_section}"f"{layout_template}\n"f"{rewrite_section}"- "## 预铺模板 HTML(只填槽,勿重写)\n"+ "## 预铺模板 HTML(只填槽,勿重写;Chrome 必须与下方稿逐字节一致,除三处占位符外)\n"f"{seed_html}\n")@@ -3641,8 +3750,11 @@ class PageWorkerNode(PlanNode):rewrite_hint=rewrite_hint,),system_prompt=(- "你是 PPT 内容页模板填充师。只替换模板中的 PAGE_TITLE、PAGE_CONTENT、PAGE_FOOTER,"- "直接输出完整 HTML 原文,不输出任何解释。"+ "你是 PPT 内容页模板填充师,不是设计师。"+ "唯一任务:在预铺 HTML 上替换 {{PAGE_TITLE}}、{{PAGE_CONTENT}}、{{PAGE_FOOTER}} 三处占位符。"+ "Page Chrome(head/header/`<main>` 开标签/footer 骨架/class/script/style)必须与预铺稿保持一致;"+ "改 chrome 会触发 content_template_chrome_changed 校验失败。"+ "只输出完整 HTML 原文,不要解释、不要 Markdown 代码块。"),node_name=f"p8_1_content_fill_{ctx.page_num}",concurrent=True,@@ -3667,6 +3779,34 @@ class PageWorkerNode(PlanNode):html = _strip_chart_header_unit(html)html = _fix_chart_height_chain(html)ok, reason = _validate_content_template_fill_output(seed_html, html)+ if not ok and reason in _REPAIRABLE_CONTENT_TEMPLATE_REASONS:+ repaired = _repair_content_template_chrome(seed_html, html)+ if repaired:+ repaired = _fix_echarts_svg_renderer(repaired)+ repaired = _strip_unsupported_fullpage_overlays(repaired)+ repaired = _strip_chart_header_unit(repaired)+ repaired = _fix_chart_height_chain(repaired)+ ok_repaired, reason_repaired = _validate_content_template_fill_output(+ seed_html,+ repaired,+ )+ if ok_repaired:+ logger.info(+ "[P8.1] repaired=content_template_chrome page=%d style=%s "+ "from_reason=%s",+ ctx.page_num,+ ctx.style_id,+ reason,+ )+ return repaired, "", ""+ logger.warning(+ "[P8.1] 内容页 chrome 自动修复后仍失败 page=%d style=%s "+ "from_reason=%s repair_reason=%s",+ ctx.page_num,+ ctx.style_id,+ reason,+ reason_repaired,+ )if not ok:logger.warning("[P8.1] 内容页填槽校验失败 page=%d style=%s reason=%s",@@ -3886,8 +4026,18 @@ class QAFixNode(PlanNode):if not path or not self.has_tool("read_file"):return ""try:- result = await self.call_tool("read_file", file_path=path)+ result = await asyncio.wait_for(+ self.call_tool("read_file", file_path=path),+ timeout=_P82_READ_TIMEOUT_SECONDS,+ )return PptCommon.parse_tool_file_content(result)+ except TimeoutError:+ logger.warning(+ "[P8.2] 读取页面超时 path=%s timeout=%.0fs",+ path,+ _P82_READ_TIMEOUT_SECONDS,+ )+ return ""except Exception as e:if isinstance(e, AbortError):raise@@ -3945,51 +4095,69 @@ class QAFixNode(PlanNode):"""仅对指定页面并发执行新版 pptx-craft fix。"""sem = asyncio.Semaphore(10)+ async def _fix_one_body(page_num: int) -> tuple[int, bool, str]:+ page_path = f"{pages_dir}/page-{page_num}.pptx.html"+ before_html = await self._read_page_file(page_path)+ before_ok = bool(before_html) and _is_slide_exportable(before_html)++ style_arg = (+ f" --style {quote_path(style_file_path)}"+ if style_file_path+ else ""+ )+ cmd = (+ f"{cli_path('fix', pptx_root)} {quote_path(pages_dir + '/')} "+ f"--fix --pages {page_num}{style_arg}"+ )+ result = await run_bash(+ self,+ cmd,+ timeout_seconds=300,+ required=False,+ workdir=pptx_root,+ )+ output = combined_output(result)[:500]+ ok = result.exit_code == 0+ if not ok:+ logger.warning(+ "[P8.2] page-%d fix 失败 exit=%d",+ page_num,+ result.exit_code,+ )++ after_html = await self._read_page_file(page_path)+ after_ok = bool(after_html) and _is_slide_exportable(after_html)+ if before_ok and not after_ok:+ backup_path = await self._find_latest_backup_path(pages_dir, page_num)+ if backup_path:+ backup_html = await self._read_page_file(backup_path)+ if backup_html and _is_slide_exportable(backup_html):+ if await self._write_page_file(page_path, backup_html):+ logger.warning(+ "[P8.2] page-%d fix 破坏 DOM,已回退 backup",+ page_num,+ )+ output = f"{output} dom_restored_from_backup"+ return page_num, ok, output+async def _fix_one(page_num: int) -> tuple[int, bool, str]:async with sem:- page_path = f"{pages_dir}/page-{page_num}.pptx.html"- before_html = await self._read_page_file(page_path)- before_ok = bool(before_html) and _is_slide_exportable(before_html)-- style_arg = (- f" --style {quote_path(style_file_path)}"- if style_file_path- else ""- )- cmd = (- f"{cli_path('fix', pptx_root)} {quote_path(pages_dir + '/')} "- f"--fix --pages {page_num}{style_arg}"- )- result = await run_bash(- self,- cmd,- timeout_seconds=300,- required=False,- workdir=pptx_root,- )- output = combined_output(result)[:500]- ok = result.exit_code == 0- if not ok:- logger.warning(- "[P8.2] page-%d fix 失败 exit=%d",+ try:+ return await asyncio.wait_for(+ _fix_one_body(page_num),+ timeout=_P82_FIX_ONE_TIMEOUT_SECONDS,+ )+ except TimeoutError:+ logger.error(+ "[P8.2] page-%d fix 整体超时 timeout=%.0fs",page_num,- result.exit_code,+ _P82_FIX_ONE_TIMEOUT_SECONDS,)-- after_html = await self._read_page_file(page_path)- after_ok = bool(after_html) and _is_slide_exportable(after_html)- if before_ok and not after_ok:- backup_path = await self._find_latest_backup_path(pages_dir, page_num)- if backup_path:- backup_html = await self._read_page_file(backup_path)- if backup_html and _is_slide_exportable(backup_html):- if await self._write_page_file(page_path, backup_html):- logger.warning(- "[P8.2] page-%d fix 破坏 DOM,已回退 backup",- page_num,- )- output = f"{output} dom_restored_from_backup"- return page_num, ok, output+ return page_num, False, "fix_one_timeout"+ except AbortError:+ raise+ except asyncio.CancelledError:+ raiseresults = await asyncio.gather(*[_fix_one(page_num) for page_num in page_nums],@@ -4905,12 +5073,15 @@ class PPTPageGenNode(PlanNode):async def _execute_stream(self, inputs: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:result = await self._execute(inputs)status_map = {"ok": "ok", "partial": "warning", "failed": "error"}+ page_files = result.get("page_files") or []+ missing = result.get("missing_pages") or []+ status = result.get("ppt_gen_status", "")+ message = f"PPT 页面生成 status={status} 成功 {len(page_files)} 页"+ if missing:+ message += f",缺失 {len(missing)} 页(不可按成功交付)"yield {**result,"node": self.plan_name,- "status": status_map.get(result.get("ppt_gen_status", ""), "warning"),- "message": (- f"PPT 生成完成 status={result.get('ppt_gen_status')} "- f"成功 {len(result.get('page_files', []))} 页"- ),+ "status": status_map.get(status, "warning"),+ "message": message,}diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.pyindex af919c545a..a1488f1fc3 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.py@@ -8,6 +8,10 @@ from typing import Anyfrom jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortError, PlanNode+# bash 工具偶发只回 content="Exit code 1\n...",不带 exit_code 字段;+# 若不识别会把失败当成功(P9 convert 假完成)。+_EXIT_CODE_RE = re.compile(r"(?im)^\s*Exit code\s+(\d+)\s*$")+class BashExecError(RuntimeError):"""bash 命令执行失败(required=True 时抛出)。"""@@ -49,6 +53,39 @@ def cli_path(subcommand: str, pptx_root: str) -> str:return f"node {quote_path(str(cli))} {subcommand}"+def _exit_code_from_text(*parts: str) -> int | None:+ for part in parts:+ if not part:+ continue+ for line in str(part).splitlines():+ matched = _EXIT_CODE_RE.match(line.strip())+ if matched:+ return int(matched.group(1))+ return None+++def _coerce_exit_code(+ exit_code: int,+ *,+ stdout: str = "",+ stderr: str = "",+ success: bool | None = None,+ error: str = "",+) -> int:+ if exit_code != 0:+ return exit_code+ if success is False:+ return 1+ if error.strip():+ return 1+ if "[ERROR]" in stdout or "[ERROR]" in stderr:+ return 1+ inferred = _exit_code_from_text(stdout, stderr)+ if inferred is not None and inferred != 0:+ return inferred+ return exit_code++def normalize_tool_text(result: Any) -> str:if result is None:return ""@@ -95,16 +132,25 @@ def parse_bash_payload(text: str) -> BashResult:try:payload = json.loads(stripped)except json.JSONDecodeError:- return BashResult(exit_code=0, stdout=stripped, stderr="", raw=text)+ exit_code = _coerce_exit_code(0, stdout=stripped)+ return BashResult(exit_code=exit_code, stdout=stripped, stderr="", raw=text)if not isinstance(payload, dict):- return BashResult(exit_code=0, stdout=stripped, stderr="", raw=text)+ exit_code = _coerce_exit_code(0, stdout=stripped)+ return BashResult(exit_code=exit_code, stdout=stripped, stderr="", raw=text)exit_code = int(payload.get("exit_code", 0) or 0)- stdout = str(payload.get("stdout") or "")+ stdout = str(payload.get("stdout") or payload.get("content") or "")stderr = str(payload.get("stderr") or "")- if exit_code == 0 and "[ERROR]" in stdout:- exit_code = 1+ success = payload.get("success")+ error = str(payload.get("error") or "")+ exit_code = _coerce_exit_code(+ exit_code,+ stdout=stdout,+ stderr=stderr,+ success=success if isinstance(success, bool) else None,+ error=error,+ )return BashResult(exit_code=exit_code, stdout=stdout, stderr=stderr, raw=text)@@ -148,14 +194,23 @@ def _extract_bash_result(raw: Any) -> BashResult | None:stdout = valuebreakstderr = str(data.get("stderr") or "")- if exit_code == 0 and "[ERROR]" in stdout:- exit_code = 1- if exit_code == 0 and success is False:- exit_code = 1- if exit_code == 0 and stdout:- parsed_exit = _parse_exit_code_from_text(stdout)- if parsed_exit is not None:- exit_code = parsed_exit+ success = data.get("success")+ if not isinstance(success, bool) and hasattr(raw, "success"):+ # 直接属性访问;禁止 getattr(builtin skill_code AST 校验)+ raw_success = raw.success+ success = raw_success if isinstance(raw_success, bool) else None+ error = str(data.get("error") or "")+ if not error and hasattr(raw, "error"):+ raw_error = raw.error+ if isinstance(raw_error, str):+ error = raw_error+ exit_code = _coerce_exit_code(+ exit_code,+ stdout=stdout,+ stderr=stderr,+ success=success if isinstance(success, bool) else None,+ error=error,+ )return BashResult(exit_code=exit_code, stdout=stdout, stderr=stderr, raw=str(raw))