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(skill): 修复技能凭据注入链路与 active_skill 生命周期
ZHan9964ffe7cc3032
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_active_state.py b/jiuwenswarm/agents/harness/common/rails/skill_active_state.pyindex 83f96c503d..746a3a4728 100644--- a/jiuwenswarm/agents/harness/common/rails/skill_active_state.py+++ b/jiuwenswarm/agents/harness/common/rails/skill_active_state.py@@ -23,10 +23,6 @@ _DEFAULT_SESSION_ID = "default"# when ToolCallInputs has no conversation_id (contextvars alone are not enough# across gather / nested callbacks)._SESSION_ID_EXTRA_KEY = "__jiuwenswarm_session_id__"-# Written by _build_inputs / before_invoke so after_invoke is not required to-# re-parse chat.send params. When true, active skill survives this invoke.-_PRESERVE_SKILL_ACTIVE_EXTRA_KEY = "__jiuwenswarm_preserve_skill_active__"-_CHAT_SEND_SOURCE_EXTRA_KEY = "__jiuwenswarm_chat_send_source__"_current_session_var: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar("skill_active_session_id",@@ -40,10 +36,14 @@ class _SkillSessionState:# When the record is keyed under ``default``, the real session that produced# it (if known). Blocks cross-session adoption of orphan credentials.source_session: Optional[str] = None+ # 连续「无该技能 skill_tool 调用」的 invoke 计数(过期兜底,改动 3):+ # 每次 before_invoke 递增,skill_tool 激活时清零;达到上限自动清空。+ invokes_since_skill_tool: int = 0def reset(self) -> None:self.active_skill = Noneself.source_session = None+ self.invokes_since_skill_tool = 0_sessions: dict[str, _SkillSessionState] = {}@@ -84,8 +84,8 @@ def adopt_default_active_skill(session_id: str) -> Optional[str]:Only migrate when the orphan's ``source_session`` is unknown or equals*session_id* — never hand another session's active skill (and its``skill_envs``) to a caller that merely shares the process. Intended for- HITL resume / ``before_invoke`` paths that already know the conversation- id; the injection rail must not call this on every bash read.+ ``before_invoke`` paths that already know the conversation id; the+ injection rail must not call this on every bash read."""sid = _nonempty_str(session_id)if not sid or sid == _DEFAULT_SESSION_ID:@@ -110,6 +110,8 @@ def adopt_default_active_skill(session_id: str) -> Optional[str]:target = _get_or_create_state(sid)target.active_skill = orphantarget.source_session = None+ # 迁移即确认激活,过期计数从零开始。+ target.invokes_since_skill_tool = 0_drop_session_state(_DEFAULT_SESSION_ID)logger.info("[SkillActiveStateRail] adopted active '%s' from default -> session=%s "@@ -128,18 +130,6 @@ def _nonempty_str(value: Any) -> Optional[str]:return text or None-def should_preserve_skill_active_from_params(params: Any) -> bool:- """Keep prior active skill across permission / confirm / ask_user HITL.-- Source alone is enough: a partial resume payload must not clear the skill- (otherwise hwocr credentials are not injected after security approval).- Evolution / legacy approval sources are intentionally out of scope.- """- if not isinstance(params, dict):- return False- return is_interrupt_resume_source(params.get("source"))--def _extract_session_id(ctx: AgentCallbackContext) -> Optional[str]:inputs = getattr(ctx, "inputs", None)if inputs is not None:@@ -183,52 +173,6 @@ def resolve_skill_session_id()-def _run_context_extra(inputs: Any) -> dict[str, Any]:- run_context = getattr(inputs, "run_context", None)- if run_context is None and isinstance(inputs, dict):- run = inputs.get("run")- if isinstance(run, dict):- context = run.get("context")- if isinstance(context, dict):- extra = context.get("extra")- return extra if isinstance(extra, dict) else {}- return {}- extra = getattr(run_context, "extra", None) if run_context is not None else None- return extra if isinstance(extra, dict) else {}---def _chat_send_source_from_ctx(ctx: AgentCallbackContext) -> Optional[str]:- extra = getattr(ctx, "extra", None)- if isinstance(extra, dict):- source = _nonempty_str(- extra.get(_CHAT_SEND_SOURCE_EXTRA_KEY) or extra.get("chat_send_source")- )- if source:- return source- run_extra = _run_context_extra(getattr(ctx, "inputs", None))- return _nonempty_str(- run_extra.get(_CHAT_SEND_SOURCE_EXTRA_KEY) or run_extra.get("chat_send_source")- )---def _should_preserve_skill_active(ctx: AgentCallbackContext) -> bool:- # Permission/confirm/ask_user source wins over an explicit False flag:- # _build_inputs used to write preserve=False on incomplete payloads and- # cleared active skill on every security HITL resume.- if is_interrupt_resume_source(_chat_send_source_from_ctx(ctx)):- return True-- extra = getattr(ctx, "extra", None)- if isinstance(extra, dict) and _PRESERVE_SKILL_ACTIVE_EXTRA_KEY in extra:- return bool(extra.get(_PRESERVE_SKILL_ACTIVE_EXTRA_KEY))-- inputs = getattr(ctx, "inputs", None)- run_extra = _run_context_extra(inputs)- if _PRESERVE_SKILL_ACTIVE_EXTRA_KEY in run_extra:- return bool(run_extra.get(_PRESERVE_SKILL_ACTIVE_EXTRA_KEY))- return False--def _str_content(msg: Any) -> str:content = getattr(msg, "content", "")return content if isinstance(content, str) else str(content)@@ -255,16 +199,33 @@ def _get_arg(tool_call: Any, name: str, default: str = "") -> str:class SkillActiveStateRail(DeepAgentRail):"""Track which skill is active after skill_tool loads SKILL.md.- Active skill survives HITL interrupt continuations (permission / confirm /- ask_user / …). It is cleared when a real new user task starts, on- ``skill_complete``, or when the session adapter is torn down.+ Active skill is per-session lifecycle state — it is NOT cleared per+ invoke: it survives new user tasks and HITL interrupt continuations+ (permission / confirm / ask_user / …). It is cleared only when the skill+ completes (``skill_complete``), when another skill is activated (switch),+ when the session ends (adapter cache eviction / teardown calls+ ``clear_session_skill_state``), or when it expires: after+ ``stale_invoke_limit`` consecutive invokes without any ``skill_tool``+ call for it (skill_complete compliance is unreliable, so the expiry is+ the safety net that keeps a forgotten skill from holding credentials+ for a whole session)."""priority = 25-- def __init__(self, session_id: Optional[str] = None) -> None:+ # 过期兜底默认值:连续 5 轮 invoke 无 skill_tool 调用 → 自动清空。+ DEFAULT_STALE_INVOKE_LIMIT = 5++ def __init__(+ self,+ session_id: Optional[str] = None,+ stale_invoke_limit: Optional[int] = None,+ ) -> None:super().__init__()self._preset_session_id = _nonempty_str(session_id)+ # None → 默认值;<= 0 → 显式禁用过期兜底。+ if stale_invoke_limit is None:+ stale_invoke_limit = self.DEFAULT_STALE_INVOKE_LIMIT+ self._stale_invoke_limit = int(stale_invoke_limit)def _resolve_session_id(self, ctx: AgentCallbackContext) -> str:return resolve_skill_session_id(ctx, self._preset_session_id)@@ -282,44 +243,49 @@ class SkillActiveStateRail(DeepAgentRail):if not existing or existing == _DEFAULT_SESSION_ID or session_id != _DEFAULT_SESSION_ID:extra[_SESSION_ID_EXTRA_KEY] = session_id- def _sync_preserve_flag_to_ctx_extra(self, ctx: AgentCallbackContext) -> bool:- preserve = _should_preserve_skill_active(ctx)- extra = getattr(ctx, "extra", None)- if isinstance(extra, dict):- extra[_PRESERVE_SKILL_ACTIVE_EXTRA_KEY] = preserve- run_extra = _run_context_extra(getattr(ctx, "inputs", None))- source = _nonempty_str(- run_extra.get(_CHAT_SEND_SOURCE_EXTRA_KEY)- or run_extra.get("chat_send_source")+ def _expire_stale_active_skill(self, session_id: str) -> None:+ """过期兜底(改动 3):连续 N 轮 invoke 无 skill_tool 调用 → 清空。++ skill_complete 遵从性不可靠(实测用户显式要求结束后模型仍不调+ 用),该兜底防技能状态挂满整场会话、凭据注入窗口无限延长。+ ``stale_invoke_limit <= 0`` 时禁用。计数语义:每次 before_invoke+ 递增(本轮"尚未"调用 skill_tool),skill_tool 激活清零——连续+ N 轮无调用后,第 N+1 轮开始时清空。+ """+ if self._stale_invoke_limit is None or self._stale_invoke_limit <= 0:+ return+ state = _sessions.get(session_id)+ if state is None or not state.active_skill:+ return+ if state.invokes_since_skill_tool >= self._stale_invoke_limit:+ logger.info(+ "[SkillActiveStateRail] expired active '%s' after %d invokes "+ "without skill_tool, session=%s",+ state.active_skill,+ state.invokes_since_skill_tool,+ session_id,)- if source:- extra[_CHAT_SEND_SOURCE_EXTRA_KEY] = source- return preserve+ _drop_session_state(session_id)+ return+ state.invokes_since_skill_tool += 1async def before_invoke(self, ctx: AgentCallbackContext) -> None:session_id = self._resolve_session_id(ctx)- preserve = self._sync_preserve_flag_to_ctx_extra(ctx)- if not preserve:- prior = get_session_active_skill(session_id)- if prior:- logger.info(- "[SkillActiveStateRail] clear active '%s' for new user task "- "session=%s",- prior,- session_id,- )- _drop_session_state(session_id)- else:- # HITL resume knows conversation_id: migrate a same-owner default- # orphan once here instead of on every credential-injection read.- adopt_default_active_skill(session_id)+ # 生命周期修正:before_invoke 不清空 active_skill(新用户任务不清、+ # HITL 恢复轮也不再需要特殊保护)。清空只发生在 skill_complete、+ # 切换到另一个 skill(after_tool_call 覆盖替换)、会话结束+ # (adapter 淘汰 / teardown 调 clear_session_skill_state)、或+ # 连续 N 轮无 skill_tool 调用的过期兜底。+ # 这里只做过期检查 + 把 default 哨兵下的孤儿态收养到真实会话+ # (ToolCallInputs 缺 conversation_id 时可能记录在 default 下)。+ self._expire_stale_active_skill(session_id)+ adopt_default_active_skill(session_id)self._bind_session_id(ctx, session_id)async def after_invoke(self, ctx: AgentCallbackContext) -> None:- # Do not drop here: the invoke that raises permission/ask_user interrupt- # is a normal user turn, but the skill must survive until the HITL- # resume chat.send. Cleanup happens in before_invoke(new task),- # skill_complete, or session teardown.+ # Do not drop here: active skill is per-session lifecycle state, not+ # per-invoke state. Cleanup happens on skill_complete, on switching to+ # another skill, or on session teardown (clear_session_skill_state).returndef _owner_hint_for_default(self, ctx: AgentCallbackContext) -> Optional[str]:@@ -364,6 +330,16 @@ class SkillActiveStateRail(DeepAgentRail):session_id,)state.reset()+ elif skill_name and state.active_skill and state.active_skill != skill_name:+ # 激活名 ≠ 完成名:不清空(保持当前激活态),但留痕,+ # 防"状态挂死且无从排查"。+ logger.warning(+ "[SkillActiveStateRail] skill_complete(%s) ignored: active is "+ "'%s' session=%s (complete only clears on name match)",+ skill_name,+ state.active_skill,+ session_id,+ )returnif tool_name != "skill_tool":@@ -375,7 +351,18 @@ class SkillActiveStateRail(DeepAgentRail):skill_name = (meta.get("skill_name") or _get_arg(tool_call, "skill_name", "") or "").strip()if not skill_name:return+ prior_skill = state.active_skill+ if prior_skill and prior_skill != skill_name:+ # 切换到另一个 skill:旧 active_skill 在此清空(被新技能替换)。+ logger.info(+ "[SkillActiveStateRail] switch active '%s' -> '%s' session=%s",+ prior_skill,+ skill_name,+ session_id,+ )state.active_skill = skill_name+ # 本轮有 skill_tool 调用,过期计数清零。+ state.invokes_since_skill_tool = 0if session_id == _DEFAULT_SESSION_ID:# Attribution for later adopt; never claim a foreign session.state.source_session = self._owner_hint_for_default(ctx)@@ -393,9 +380,7 @@ class SkillActiveStateRail(DeepAgentRail):__all__ = ["SkillActiveStateRail",- "_CHAT_SEND_SOURCE_EXTRA_KEY","_DEFAULT_SESSION_ID",- "_PRESERVE_SKILL_ACTIVE_EXTRA_KEY","_SESSION_ID_EXTRA_KEY","_current_session_var","adopt_default_active_skill",@@ -403,5 +388,4 @@ __all__ = ["get_session_active_skill","is_interrupt_resume_source","resolve_skill_session_id",- "should_preserve_skill_active_from_params",]diff --git a/jiuwenswarm/agents/harness/common/rails/skill_credential_injection_rail.py b/jiuwenswarm/agents/harness/common/rails/skill_credential_injection_rail.pyindex 1dea7e2d2b..3229afa8ba 100644--- a/jiuwenswarm/agents/harness/common/rails/skill_credential_injection_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/skill_credential_injection_rail.py@@ -1,16 +1,25 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""Inject per-skill credentials into shell tool calls via tool_args["env"]."""+"""Inject per-skill credentials into shell tool calls via tool_args["env"].++另含 SKILL_GATE 闸门:命令以「解释器 + 脚本」形态直接运行另一个有凭据技能+的脚本而该技能未激活时,拒绝执行并指引先调用 skill_tool 激活,防止凭据+静默缺失(脚本缺 key 失败)与跨技能凭据泄漏。+"""from __future__ import annotationsimport jsonimport logging-from typing import Any+import re+from typing import Any, Iterablefrom openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ToolCallInputsfrom openjiuwen.harness.rails.base import DeepAgentRail+from jiuwenswarm.agents.harness.common.rails.read_file_validation import (+ resolve_language_from_context,+)from jiuwenswarm.agents.harness.common.rails.skill_active_state import (get_session_active_skill,resolve_skill_session_id,@@ -31,6 +40,102 @@ SHELL_PERMISSION_TOOLS = frozenset()_DEFAULT_SHELL_TYPES = frozenset({"auto", "cmd", "bash", "sh"})+SKILL_GATE_PREFIX = "[SKILL_GATE]"++GATE_MESSAGE_CN = (+ f"{SKILL_GATE_PREFIX} 检测到直接运行技能「{{skill}}」的脚本,但当前激活的技能不是它,"+ "其凭据环境变量不会被注入,脚本将因缺少 key 而失败。"+ '请先调用 skill_tool(skill_name="{skill}"),然后重新执行原命令。'+)+GATE_MESSAGE_EN = (+ f"{SKILL_GATE_PREFIX} The command directly runs a script of skill \"{{skill}}\", "+ "which is not the active skill: its credential env vars will NOT be injected "+ 'and the script would fail on a missing key. Call '+ 'skill_tool(skill_name="{skill}") first, then rerun the original command.'+)++# 「技能路径 + 脚本」形态:含路径分隔符且以 .py/.js/.mjs 结尾的 token+# (归一化 \ → / 后匹配)。不要求解释器前缀——真实命令的解释器常为带+# 引号的绝对路径("C:\...\python3.exe" "D:\...\skill\scripts\x.py")。+# token 允许成对引号包裹(含空格路径);pip3 -r .../requirements.txt、+# cat .../SKILL.md 等非 .py/.js/.mjs 结尾的引用天然不命中。+_SCRIPT_TOKEN_RE = re.compile(+ r"""(?:"[^"]*/[^"]*\.(?:py|js|mjs)\b"|'[^']*/[^']*\.(?:py|js|mjs)\b'|[^"'\s]*/[^"'\s]*\.(?:py|js|mjs)\b)""",+ re.IGNORECASE,+)+++def _iter_script_tokens(command: str) -> Iterable[str]:+ for match in _SCRIPT_TOKEN_RE.finditer(command):+ token = match.group(0).strip()+ if len(token) >= 2 and token[0] == token[-1] and token[0] in ("'", '"'):+ token = token[1:-1]+ yield token+++def match_skills_in_command(command: str, known_skills: Iterable[str]) -> list[str]:+ """Return every distinct known skill referenced by a script-path token.++ 命令归一化(反斜杠→斜杠)后,提取所有「含路径分隔符且以+ .py/.js/.mjs 结尾」的 token(引号包裹的含空格路径亦可),对每个+ token 的路径**逐段**扫描,任一段精确命中已知技能名即算引用(整段+ 边界,mx-a-x 不会误匹配 mx-a;大小写不敏感)。覆盖+ ``<skill>/scripts/x.py`` 子目录与 ``<skill>/x.py`` 根目录两种布局,+ 以及带引号绝对路径解释器的真实调用形态。按命令中出现顺序去重返回。++ 注意不能用「/skill/ 后缀到脚本」的单个捕获组正则:finditer 非重叠+ 匹配会让最靠前的无关段(如 /Object/、/relay-claw/)吞掉整个匹配,+ 真正的技能段轮不到检查。+ """+ if not command or not known_skills:+ return []+ canonical: dict[str, str] = {}+ for name in known_skills:+ text = _nonempty_str(name)+ if text:+ canonical.setdefault(text.lower(), text)+ if not canonical:+ return []+ matched: list[str] = []+ seen: set[str] = set()+ for token in _iter_script_tokens(command.replace("\\", "/")):+ for segment in re.split(r"/+", token):+ name = canonical.get(segment.strip().lower())+ if name is not None and name not in seen:+ seen.add(name)+ matched.append(name)+ return matched+++def match_skill_in_command(command: str, known_skills: Iterable[str]) -> str | None:+ """Return the first known skill referenced by the command, else None."""+ matches = match_skills_in_command(command, known_skills)+ return matches[0] if matches else None+++def build_skill_gate_message(skill: str, language: str = "cn") -> str:+ template = GATE_MESSAGE_EN if str(language).lower() == "en" else GATE_MESSAGE_CN+ return template.format(skill=skill)+++def _write_gate_tool_result(ctx: AgentCallbackContext, message: str) -> None:+ """Skip 后给模型/UI 的错误结果(照抄 read_file_validation 的写入模式)。"""+ from openjiuwen.core.foundation.llm import ToolMessage++ if not isinstance(ctx.inputs, ToolCallInputs):+ return+ tool_call = ctx.inputs.tool_call+ tool_call_id = getattr(tool_call, "id", "") if tool_call else ""+ text = str(message or "")+ ctx.inputs.tool_result = text+ tool_msg = getattr(ctx.inputs, "tool_msg", None)+ if tool_msg is not None:+ tool_msg.content = text+ if tool_call_id and getattr(tool_msg, "tool_call_id", None) in (None, ""):+ tool_msg.tool_call_id = tool_call_id+ else:+ ctx.inputs.tool_msg = ToolMessage(content=text, tool_call_id=tool_call_id)+def _should_strip_powershell_amp_prefix(tool_name: str, command: Any, shell_type: Any@@ -80,7 +185,16 @@ def coalesce_config_skill_envs(config: Any, previous: Any) -> Any:class SkillCredentialInjectionRail(DeepAgentRail):- """Inject per-skill credentials into shell tool calls."""+ """Inject per-skill credentials into shell tool calls.++ 三分支:+ 1. 命令可解析为「正在跑当前激活技能的脚本」→ 注入该技能凭据;+ 2. 命令在跑**另一个**有凭据技能的脚本 → 闸门拒绝并指引激活(逃生口:+ tool_args["env"] 显式携带该技能凭据 key 时放行,且不再注入 active+ 技能的凭据,避免跨技能泄漏);+ 3. 命令静态不可解析(cd+相对路径 / 裸文件名 / 无凭据技能 / 非脚本+ 形态)→ 回退按 active 注入,与既有行为一致(零回归)。+ """priority = 5@@ -113,8 +227,42 @@ class SkillCredentialInjectionRail(DeepAgentRail):session_id = self._resolve_session_id(ctx)# Read-only lookup: do not adopt default orphans here (cross-session- # credential leak). Migration runs on HITL preserve before_invoke.+ # credential leak). Migration runs in SkillActiveStateRail.before_invoke.active_skill = get_session_active_skill(session_id)++ tool_args = self._coerce_tool_args_dict(ctx.inputs)+ command = (+ str(tool_args.get("command") or "") if isinstance(tool_args, dict) else ""+ )+ matched_skills = match_skills_in_command(command, self._skill_envs.keys())+ other_skills = [s for s in matched_skills if s != active_skill]++ if other_skills:+ gate_skill = other_skills[0]+ if self._has_explicit_skill_env(tool_args, gate_skill):+ # 逃生口:模型显式传了该技能的凭据 key,按原样执行;+ # 不再注入 active 技能凭据(防跨技能泄漏)。+ logger.info(+ "[SkillCredentialInjectionRail] explicit env for skill=%s, "+ "skip active-skill injection (active=%s) session=%s",+ gate_skill,+ active_skill,+ session_id,+ )+ return+ logger.info(+ "[SkillCredentialInjectionRail] gate: blocked direct run of "+ "skill=%s (active=%s) session=%s tool=%s",+ gate_skill,+ active_skill,+ session_id,+ tool_name,+ )+ self._reject_with_guidance(ctx, gate_skill)+ return++ # matched 与 active 一致,或命令不可解析(cd+相对路径/裸文件名/+ # 无凭据技能/非脚本形态):按 active 注入,与既有行为一致。if not active_skill:return@@ -132,6 +280,40 @@ class SkillCredentialInjectionRail(DeepAgentRail):tool_name,)+ def _coerce_tool_args_dict(+ self, inputs: ToolCallInputs+ ) -> dict[str, Any] | None:+ """JSON 字符串 tool_args 原地解析为 dict(与 _inject_credentials 共享)。"""+ tool_args = inputs.tool_args+ if isinstance(tool_args, dict):+ return tool_args+ if isinstance(tool_args, str):+ try:+ parsed = json.loads(tool_args)+ except (json.JSONDecodeError, TypeError):+ return None+ if isinstance(parsed, dict):+ inputs.tool_args = parsed+ return parsed+ return None++ def _has_explicit_skill_env(self, tool_args: Any, skill: str) -> bool:+ """逃生口判定:tool_args["env"] 显式携带了该技能的任一凭据 key。"""+ if not isinstance(tool_args, dict):+ return False+ env = tool_args.get("env")+ if not isinstance(env, dict):+ return False+ credential_keys = set(self._skill_envs.get(skill, {}))+ return bool(credential_keys & set(env))++ def _reject_with_guidance(self, ctx: AgentCallbackContext, skill: str) -> None:+ """拒绝执行(_skip_tool 短路)并写入激活指引,模型可据此自愈。"""+ language = resolve_language_from_context(ctx)+ message = build_skill_gate_message(skill, language)+ ctx.extra["_skip_tool"] = True+ _write_gate_tool_result(ctx, message)+def _resolve_session_id(self, ctx: AgentCallbackContext) -> str:return resolve_skill_session_id(ctx, self._preset_session_id)@@ -173,8 +355,14 @@ class SkillCredentialInjectionRail(DeepAgentRail):__all__ = [- "SkillCredentialInjectionRail",+ "GATE_MESSAGE_CN",+ "GATE_MESSAGE_EN","SHELL_PERMISSION_TOOLS",+ "SKILL_GATE_PREFIX",+ "SkillCredentialInjectionRail",+ "build_skill_gate_message","coalesce_config_skill_envs","coalesce_skill_envs",+ "match_skill_in_command",+ "match_skills_in_command",]diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 41c2d43888..b172a39a1b 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1752,49 +1752,6 @@ class JiuWenSwarm:context,)- # HITL resume metadata for SkillActiveStateRail: keep active skill across- # permission/confirm/ask_user interrupt continuations.- try:- from jiuwenswarm.agents.harness.common.rails.skill_active_state import (- _CHAT_SEND_SOURCE_EXTRA_KEY,- _PRESERVE_SKILL_ACTIVE_EXTRA_KEY,- is_interrupt_resume_source,- should_preserve_skill_active_from_params,- )-- chat_send_source = (- params.get("source").strip()- if isinstance(params.get("source"), str) and params.get("source").strip()- else ""- )- # HITL source alone must preserve; never write preserve=False for- # permission/confirm/ask_user (that cleared hwocr credentials).- preserve_skill = should_preserve_skill_active_from_params(params) or (- is_interrupt_resume_source(chat_send_source)- )- if preserve_skill or chat_send_source:- run_payload = inputs.get("run")- if not isinstance(run_payload, dict):- run_payload = {}- inputs["run"] = run_payload- context = run_payload.get("context")- if not isinstance(context, dict):- context = {}- run_payload["context"] = context- extra = context.get("extra")- if not isinstance(extra, dict):- extra = {}- context["extra"] = extra- if chat_send_source:- extra[_CHAT_SEND_SOURCE_EXTRA_KEY] = chat_send_source- extra["chat_send_source"] = chat_send_source- extra[_PRESERVE_SKILL_ACTIVE_EXTRA_KEY] = bool(preserve_skill)- except Exception:- logger.debug(- "[_build_inputs] failed to attach skill-active preserve flags",- exc_info=True,- )-# Per-request workspace_dir scopes one prompt's cwd to the given# directory; threaded into inputs["cwd"] which downstream init_cwd# installs onto openjiuwen's CwdState ContextVar. See E2A-protocol.mddiff --git a/tests/unit_tests/agentserver/test_skill_active_state.py b/tests/unit_tests/agentserver/test_skill_active_state.pyindex 06ff2f73fb..d9a343baa4 100644--- a/tests/unit_tests/agentserver/test_skill_active_state.py+++ b/tests/unit_tests/agentserver/test_skill_active_state.py@@ -1,6 +1,6 @@# coding: utf-8# pylint: disable=protected-access-"""Tests for skill active-state session id + HITL preserve behavior."""+"""Tests for skill active-state lifecycle: activation, switch, completion, teardown."""import asyncioimport unittest@@ -13,16 +13,13 @@ from openjiuwen.core.single_agent.rail.base import ()from jiuwenswarm.agents.harness.common.rails.skill_active_state import (- _CHAT_SEND_SOURCE_EXTRA_KEY,_DEFAULT_SESSION_ID,- _PRESERVE_SKILL_ACTIVE_EXTRA_KEY,_SESSION_ID_EXTRA_KEY,SkillActiveStateRail,clear_session_skill_state,get_session_active_skill,is_interrupt_resume_source,resolve_skill_session_id,- should_preserve_skill_active_from_params,)from jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail import (SkillCredentialInjectionRail,@@ -73,7 +70,7 @@ class TestResolveSkillSessionId(unittest.TestCase):assert resolve_skill_session_id(ctx) == _DEFAULT_SESSION_ID-class TestPreserveSkillActiveParams(unittest.TestCase):+class TestInterruptResumeSource(unittest.TestCase):def test_interrupt_sources(self):assert is_interrupt_resume_source("permission_interrupt")assert is_interrupt_resume_source("confirm_interrupt")@@ -85,48 +82,6 @@ class TestPreserveSkillActiveParams(unittest.TestCase):assert not is_interrupt_resume_source("user")assert not is_interrupt_resume_source("")- def test_params_permission_resume(self):- assert should_preserve_skill_active_from_params(- {- "source": "permission_interrupt",- "request_id": "req-1",- "query": "",- "answers": [{"x": 1}],- }- )-- def test_params_answers_only_no_source(self):- assert not should_preserve_skill_active_from_params(- {"query": "", "answers": [{"selected_options": ["本次允许"]}]}- )-- def test_params_source_without_request_id_still_preserves(self):- # Source alone is enough to keep active skill across security HITL.- assert should_preserve_skill_active_from_params(- {- "source": "permission_interrupt",- "query": "",- "answers": [{"x": 1}],- }- )- assert should_preserve_skill_active_from_params(- {"source": "permission_interrupt", "query": ""}- )-- def test_params_evolution_source_not_preserved_here(self):- assert not should_preserve_skill_active_from_params(- {- "source": "evolution_interrupt",- "request_id": "req-1",- "answers": [{"x": 1}],- }- )-- def test_params_new_user_query(self):- assert not should_preserve_skill_active_from_params(- {"query": "再用 hwocr 识别", "source": ""}- )-class TestSkillActiveStateRailPreset(unittest.TestCase):def tearDown(self):@@ -165,7 +120,7 @@ class TestSkillActiveStateRailPreset(unittest.TestCase):assert ctx.extra[_SESSION_ID_EXTRA_KEY] == "officeclaw_preset_sess"-class TestHitlPreserveActiveSkill(unittest.TestCase):+class TestSkillActiveLifecycle(unittest.TestCase):sid = "officeclaw_hitl_sess"def tearDown(self):@@ -174,34 +129,27 @@ class TestHitlPreserveActiveSkill(unittest.TestCase):def _rail(self):return SkillActiveStateRail(session_id=self.sid)- def _activate(self, rail):+ def _activate(self, rail, skill_name="hwocr"):ctx = AgentCallbackContext(agent=MagicMock())tool_call = MagicMock()- tool_call.arguments = {"skill_name": "hwocr"}+ tool_call.arguments = {"skill_name": skill_name}tool_msg = MagicMock()- tool_msg.metadata = {"skill_name": "hwocr"}+ tool_msg.metadata = {"skill_name": skill_name}ctx.inputs = ToolCallInputs(tool_call=tool_call,tool_name="skill_tool",- tool_args={"skill_name": "hwocr"},+ tool_args={"skill_name": skill_name},tool_result=None,tool_msg=tool_msg,)ctx.extra = {}asyncio.run(rail.after_tool_call(ctx))- def _invoke_ctx(self, *, query="hello", preserve=False, source=""):+ def _invoke_ctx(self, *, query="hello"):ctx = AgentCallbackContext(agent=MagicMock())- run_context = MagicMock()- run_context.extra = {- _PRESERVE_SKILL_ACTIVE_EXTRA_KEY: preserve,- }- if source:- run_context.extra[_CHAT_SEND_SOURCE_EXTRA_KEY] = sourcectx.inputs = InvokeInputs(query=query,conversation_id=self.sid,- run_context=run_context,)ctx.extra = {}return ctx@@ -209,33 +157,36 @@ class TestHitlPreserveActiveSkill(unittest.TestCase):def test_after_invoke_does_not_clear(self):rail = self._rail()self._activate(rail)- ctx = self._invoke_ctx(preserve=False)- asyncio.run(rail.after_invoke(ctx))+ asyncio.run(rail.after_invoke(self._invoke_ctx()))assert get_session_active_skill(self.sid) == "hwocr"def test_permission_resume_before_invoke_keeps_active(self):rail = self._rail()self._activate(rail)- ctx = self._invoke_ctx(- query="",- preserve=True,- source="permission_interrupt",- )- asyncio.run(rail.before_invoke(ctx))+ asyncio.run(rail.before_invoke(self._invoke_ctx(query="")))assert get_session_active_skill(self.sid) == "hwocr"- def test_ask_user_resume_keeps_active(self):+ def test_new_user_task_before_invoke_keeps_active(self):+ # 生命周期修正:新用户任务不再清空 active_skill。rail = self._rail()self._activate(rail)- ctx = self._invoke_ctx(preserve=True, source="ask_user_interrupt")- asyncio.run(rail.before_invoke(ctx))+ asyncio.run(rail.before_invoke(self._invoke_ctx(query="下一题")))+ assert get_session_active_skill(self.sid) == "hwocr"++ def test_switch_to_another_skill_replaces_active(self):+ # 切换到另一个 skill:旧 skill 清空,仅新 skill 激活。+ rail = self._rail()+ self._activate(rail, "hwocr")assert get_session_active_skill(self.sid) == "hwocr"+ self._activate(rail, "ppt-creation")+ assert get_session_active_skill(self.sid) == "ppt-creation"- def test_new_user_task_before_invoke_clears(self):+ def test_session_teardown_clears_active(self):+ # 会话结束:clear_session_skill_state(adapter 淘汰 / teardown)清空。rail = self._rail()self._activate(rail)- ctx = self._invoke_ctx(query="下一题", preserve=False)- asyncio.run(rail.before_invoke(ctx))+ assert get_session_active_skill(self.sid) == "hwocr"+ clear_session_skill_state(self.sid)assert get_session_active_skill(self.sid) is Nonedef test_resume_then_inject_bash(self):@@ -246,13 +197,9 @@ class TestHitlPreserveActiveSkill(unittest.TestCase):)self._activate(rail)# Simulate interrupted invoke ending without clearing.- asyncio.run(rail.after_invoke(self._invoke_ctx(preserve=False)))+ asyncio.run(rail.after_invoke(self._invoke_ctx()))# Permission resume.- asyncio.run(- rail.before_invoke(- self._invoke_ctx(preserve=True, source="permission_interrupt")- )- )+ asyncio.run(rail.before_invoke(self._invoke_ctx(query="")))bash_ctx = AgentCallbackContext(agent=MagicMock())bash_ctx.inputs = ToolCallInputs(tool_call=MagicMock(),@@ -284,6 +231,112 @@ class TestHitlPreserveActiveSkill(unittest.TestCase):asyncio.run(rail.after_tool_call(ctx))assert get_session_active_skill(self.sid) is None+ def test_skill_complete_name_mismatch_keeps_active_and_warns(self):+ # 激活名 ≠ 完成名:不清空当前激活态,但记录 warn 便于排查+ rail = self._rail()+ self._activate(rail, "hwocr")+ ctx = AgentCallbackContext(agent=MagicMock())+ tool_call = MagicMock()+ tool_call.arguments = {"skill_name": "ppt-creation"}+ tool_msg = MagicMock()+ tool_msg.metadata = {}+ ctx.inputs = ToolCallInputs(+ tool_call=tool_call,+ tool_name="skill_complete",+ tool_args={"skill_name": "ppt-creation"},+ tool_result=None,+ tool_msg=tool_msg,+ )+ ctx.extra = {}+ with self.assertLogs(+ "jiuwenswarm.agents.harness.common.rails.skill_active_state",+ level="WARNING",+ ) as captured:+ asyncio.run(rail.after_tool_call(ctx))+ assert get_session_active_skill(self.sid) == "hwocr"+ assert any("ignored" in line for line in captured.output)+++class TestStaleInvokeExpiry(unittest.TestCase):+ """改动 3:连续 N 轮 invoke 无 skill_tool 调用 → 过期清空 active_skill。"""++ sid = "officeclaw_stale_sess"++ def tearDown(self):+ clear_session_skill_state(self.sid)++ def _rail(self, limit=5):+ return SkillActiveStateRail(+ session_id=self.sid, stale_invoke_limit=limit+ )++ def _activate(self, rail, skill_name="hwocr"):+ ctx = AgentCallbackContext(agent=MagicMock())+ tool_call = MagicMock()+ tool_call.arguments = {"skill_name": skill_name}+ tool_msg = MagicMock()+ tool_msg.metadata = {"skill_name": skill_name}+ ctx.inputs = ToolCallInputs(+ tool_call=tool_call,+ tool_name="skill_tool",+ tool_args={"skill_name": skill_name},+ tool_result=None,+ tool_msg=tool_msg,+ )+ ctx.extra = {}+ asyncio.run(rail.after_tool_call(ctx))++ def _invoke(self, rail, query="q"):+ ctx = AgentCallbackContext(agent=MagicMock())+ ctx.inputs = InvokeInputs(query=query, conversation_id=self.sid)+ ctx.extra = {}+ asyncio.run(rail.before_invoke(ctx))++ def test_expires_after_limit(self):+ rail = self._rail(limit=5)+ self._activate(rail)+ for i in range(5):+ self._invoke(rail, query=f"q{i}")+ # 连续 5 轮无 skill_tool 调用,第 5 轮结束仍存活+ assert get_session_active_skill(self.sid) == "hwocr"+ # 第 6 轮开始时清空+ self._invoke(rail, query="q6")+ assert get_session_active_skill(self.sid) is None++ def test_skill_tool_call_resets_counter(self):+ rail = self._rail(limit=3)+ self._activate(rail)+ self._invoke(rail)+ self._invoke(rail)+ # 重新 skill_tool 调用 → 计数清零,重新累计+ self._activate(rail)+ self._invoke(rail)+ self._invoke(rail)+ assert get_session_active_skill(self.sid) == "hwocr"+ self._invoke(rail)+ assert get_session_active_skill(self.sid) == "hwocr"+ self._invoke(rail)+ assert get_session_active_skill(self.sid) is None++ def test_switch_resets_counter(self):+ rail = self._rail(limit=2)+ self._activate(rail, "hwocr")+ self._invoke(rail)+ # 切换技能 → 新技能计数从零开始+ self._activate(rail, "ppt-creation")+ self._invoke(rail)+ self._invoke(rail)+ assert get_session_active_skill(self.sid) == "ppt-creation"+ self._invoke(rail)+ assert get_session_active_skill(self.sid) is None++ def test_limit_nonpositive_disables_expiry(self):+ rail = self._rail(limit=0)+ self._activate(rail)+ for _ in range(10):+ self._invoke(rail)+ assert get_session_active_skill(self.sid) == "hwocr"+class TestCredentialInjectionUsesPreset(unittest.TestCase):def tearDown(self):@@ -397,19 +450,13 @@ class TestAdoptDefaultActiveSkill(unittest.TestCase):assert get_session_active_skill("officeclaw_adopt_sess") == "hwocr"assert get_session_active_skill(_DEFAULT_SESSION_ID) is None- def test_hitl_before_invoke_adopts_unowned_orphan(self):+ def test_before_invoke_adopts_unowned_orphan(self):self._activate_under_default()rail = SkillActiveStateRail(session_id="officeclaw_adopt_sess")- run_context = MagicMock()- run_context.extra = {- _PRESERVE_SKILL_ACTIVE_EXTRA_KEY: True,- _CHAT_SEND_SOURCE_EXTRA_KEY: "permission_interrupt",- }invoke_ctx = AgentCallbackContext(agent=MagicMock())invoke_ctx.inputs = InvokeInputs(query="",conversation_id="officeclaw_adopt_sess",- run_context=run_context,)invoke_ctx.extra = {}asyncio.run(rail.before_invoke(invoke_ctx))@@ -433,44 +480,5 @@ class TestAdoptDefaultActiveSkill(unittest.TestCase):assert bash_ctx.inputs.tool_args["env"]["HWOCR_AK"] == "ak"-class TestFalsePreserveFlagWithInterruptSource(unittest.TestCase):- sid = "officeclaw_false_preserve"-- def tearDown(self):- clear_session_skill_state(self.sid)-- def test_interrupt_source_overrides_false_preserve_flag(self):- rail = SkillActiveStateRail(session_id=self.sid)- ctx = AgentCallbackContext(agent=MagicMock())- tool_call = MagicMock()- tool_call.arguments = {"skill_name": "hwocr"}- tool_msg = MagicMock()- tool_msg.metadata = {"skill_name": "hwocr"}- ctx.inputs = ToolCallInputs(- tool_call=tool_call,- tool_name="skill_tool",- tool_args={"skill_name": "hwocr"},- tool_result=None,- tool_msg=tool_msg,- )- ctx.extra = {}- asyncio.run(rail.after_tool_call(ctx))-- run_context = MagicMock()- run_context.extra = {- _PRESERVE_SKILL_ACTIVE_EXTRA_KEY: False,- _CHAT_SEND_SOURCE_EXTRA_KEY: "permission_interrupt",- }- invoke_ctx = AgentCallbackContext(agent=MagicMock())- invoke_ctx.inputs = InvokeInputs(- query="",- conversation_id=self.sid,- run_context=run_context,- )- invoke_ctx.extra = {}- asyncio.run(rail.before_invoke(invoke_ctx))- assert get_session_active_skill(self.sid) == "hwocr"--if __name__ == "__main__":unittest.main()diff --git a/tests/unit_tests/agentserver/test_skill_credential_injection_rail.py b/tests/unit_tests/agentserver/test_skill_credential_injection_rail.pyindex 23b56d371f..98dfd07b64 100644--- a/tests/unit_tests/agentserver/test_skill_credential_injection_rail.py+++ b/tests/unit_tests/agentserver/test_skill_credential_injection_rail.py@@ -14,6 +14,8 @@ from jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail impSkillCredentialInjectionRail,coalesce_config_skill_envs,coalesce_skill_envs,+ match_skill_in_command,+ match_skills_in_command,)from jiuwenswarm.agents.harness.common.tools.command_tools import _build_subprocess_env@@ -150,5 +152,279 @@ class TestCredentialInjection(unittest.TestCase):assert "env" not in ctx.inputs.tool_args+class TestMatchSkillInCommand(unittest.TestCase):+ KNOWN = ("hwocr", "ppt-creation", "mx-finance-data", "delayed-restart-app")++ def test_subdir_script_form(self):+ # 内置技能主流形态:脚本在 <skill>/scripts/ 子目录下+ cmd = "python3 /root/.jiuwenswarm/agent/skills/hwocr/scripts/run.py --x 1"+ assert match_skill_in_command(cmd, self.KNOWN) == "hwocr"++ def test_root_script_form_windows_backslash(self):+ cmd = (+ "python %USERPROFILE%\\.jiuwenswarm\\agent\\skills\\"+ "delayed-restart-app\\launch_delayed_restart.py --pid 123"+ )+ assert match_skill_in_command(cmd, self.KNOWN) == "delayed-restart-app"++ def test_segment_boundary_no_partial_match(self):+ assert match_skill_in_command("python3 /opt/mx-finance-data-x/run.py", self.KNOWN) is None++ def test_pip_install_not_matched(self):+ cmd = "pip3 install -r /opt/skills/hwocr/requirements.txt"+ assert match_skill_in_command(cmd, self.KNOWN) is None++ def test_cat_ls_not_matched(self):+ assert match_skill_in_command("cat /opt/hwocr/SKILL.md", self.KNOWN) is None+ assert match_skill_in_command("ls /opt/hwocr", self.KNOWN) is None++ def test_bare_or_cd_relative_not_matched(self):+ # 静态不可解析形态 → 匹配 None(rail 侧回退按 active 注入)+ assert match_skill_in_command("python3 app.py", self.KNOWN) is None+ assert match_skill_in_command("cd /opt/hwocr && python3 run.py", self.KNOWN) is None++ def test_case_insensitive_mixed_separators(self):+ assert match_skill_in_command(+ "python3 D:\\Skills\\HWOCR\\scripts\\Run.PY", self.KNOWN+ ) == "hwocr"++ def test_node_mjs(self):+ assert match_skill_in_command(+ "node skills/ppt-creation/components/build.mjs", self.KNOWN+ ) == "ppt-creation"++ def test_quoted_path_with_spaces(self):+ assert match_skill_in_command(+ 'python "C:\\My Skills\\hwocr\\scripts\\run.py"', self.KNOWN+ ) == "hwocr"++ def test_python_dash_c_not_matched(self):+ assert match_skill_in_command('python -c "print(1)"', self.KNOWN) is None+ assert match_skill_in_command("python -c \"open('f.py')\"", self.KNOWN) is None++ def test_bare_filename_without_path_separator_not_matched(self):+ # 无路径分隔符的 .py 文件名(copy hwocr.py dest.py / python3 app.py)+ # 无技能段可扫,不命中+ assert match_skill_in_command("copy hwocr.py dest.py", self.KNOWN) is None+ assert match_skill_in_command("python3 app.py", self.KNOWN) is None++ def test_quoted_absolute_interpreter_with_backslash_script(self):+ # history.json 实录形态:带引号绝对路径解释器 + 反斜杠脚本路径 ++ # 中文参数。旧实现因解释器前缀失配(P1),本用例固化修复。+ known = self.KNOWN + ("mx-finance-search",)+ cmd = (+ '"C:\\Users\\Administrator\\AppData\\Local\\Python\\bin\\python3.exe" '+ '"D:\\Object\\skill-setConfig\\relay-claw\\office-claw-skills\\'+ 'mx-finance-search\\scripts\\get_data.py" 查询 --no-save 2>&1'+ )+ assert match_skill_in_command(cmd, known) == "mx-finance-search"++ def test_backslash_unquoted_path_matched(self):+ cmd = (+ "python3 D:\\Object\\skill-setConfig\\relay-claw\\office-claw-skills\\"+ "mx-finance-search\\scripts\\get_data.py 查询 --no-save"+ )+ assert (+ match_skill_in_command(cmd, ("mx-finance-search",)) == "mx-finance-search"+ )++ def test_false_positives_fixed(self):+ # 验收方实测的三条误报检查固化+ known = ("mx-finance-search",)+ assert (+ match_skill_in_command(+ 'pip3 install -r "D:\\Object\\skills\\mx-finance-search\\requirements.txt"',+ known,+ )+ is None+ )+ assert (+ match_skill_in_command(+ 'cat "D:\\Object\\skills\\mx-finance-search\\SKILL.md"', known+ )+ is None+ )+ assert match_skill_in_command('python -c "print(1)"', known) is None++ def test_flag_tolerant(self):+ assert match_skill_in_command(+ "python3 -u /opt/hwocr/scripts/run.py", self.KNOWN+ ) == "hwocr"++ def test_multiple_skills_ordered_distinct(self):+ cmd = (+ "python3 /a/hwocr/x.py && python3 /b/ppt-creation/y.py "+ "&& python3 /c/hwocr/z.py"+ )+ assert match_skills_in_command(cmd, self.KNOWN) == ["hwocr", "ppt-creation"]+++class TestSkillGateAndFallback(unittest.TestCase):+ def _make_rail(self):+ return SkillCredentialInjectionRail(+ skill_envs={+ "hwocr": {"HWOCR_AK": "ak", "HWOCR_SK": "sk"},+ "ppt-creation": {"PPT_TOKEN": "tok"},+ }+ )++ def _make_ctx(self, tool_name="bash", tool_args=None):+ ctx = AgentCallbackContext(agent=MagicMock())+ tool_call = MagicMock()+ tool_call.id = "call-1"+ inputs = ToolCallInputs(+ tool_call=tool_call,+ tool_name=tool_name,+ tool_args=tool_args or {"command": "echo hello"},+ tool_result=None,+ tool_msg=None,+ )+ inputs.conversation_id = "gate-session"+ ctx.inputs = inputs+ ctx.extra = {}+ return ctx++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_matched_active_subdir_injects(self, mock_get_skill):+ mock_get_skill.return_value = "hwocr"+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={"command": "python3 /opt/skills/hwocr/scripts/run.py"}+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert ctx.inputs.tool_args["env"]["HWOCR_AK"] == "ak"+ assert ctx.inputs.tool_args["env"]["HWOCR_SK"] == "sk"+ assert not ctx.extra.get("_skip_tool")++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_no_active_gate_blocks_and_guides(self, mock_get_skill):+ # 原始故障的新表现:未激活直接重跑技能脚本 → 从静默缺 key 失败+ # 变为可自愈的拦截 + 指引+ mock_get_skill.return_value = None+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={"command": "python3 /opt/skills/hwocr/scripts/run.py"}+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert ctx.extra.get("_skip_tool") is True+ assert 'skill_tool(skill_name="hwocr")' in str(ctx.inputs.tool_result)+ assert ctx.inputs.tool_msg is not None+ assert "env" not in ctx.inputs.tool_args++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_active_other_skill_blocked(self, mock_get_skill):+ # 跨技能保护核心用例:active=A 时直跑 B 的脚本 → 拒绝且不注入 A 凭据+ mock_get_skill.return_value = "hwocr"+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={"command": "node /opt/skills/ppt-creation/build.mjs"}+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert ctx.extra.get("_skip_tool") is True+ assert "env" not in ctx.inputs.tool_args++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_escape_hatch_explicit_env_allows(self, mock_get_skill):+ # 逃生口:显式带了目标技能凭据 key → 放行且不注入 active 凭据+ mock_get_skill.return_value = "hwocr"+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={+ "command": "python3 /opt/skills/ppt-creation/scripts/build.py",+ "env": {"PPT_TOKEN": "explicit"},+ }+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert not ctx.extra.get("_skip_tool")+ assert ctx.inputs.tool_args["env"]["PPT_TOKEN"] == "explicit"+ assert "HWOCR_AK" not in ctx.inputs.tool_args["env"]++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_cd_relative_falls_back_to_active(self, mock_get_skill):+ # 静态不可解析(cd + 裸文件名)→ 回退按 active 注入(零回归)+ mock_get_skill.return_value = "hwocr"+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={"command": "cd /opt/skills/hwocr && python3 run.py"}+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert not ctx.extra.get("_skip_tool")+ assert ctx.inputs.tool_args["env"]["HWOCR_AK"] == "ak"++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_pip_install_with_active_falls_back(self, mock_get_skill):+ # 防误报回归:pip3 install 不触发闸门+ mock_get_skill.return_value = "hwocr"+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={+ "command": "pip3 install -r /opt/skills/hwocr/requirements.txt"+ }+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert not ctx.extra.get("_skip_tool")+ assert ctx.inputs.tool_args["env"]["HWOCR_AK"] == "ak"++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_no_credential_skill_falls_back(self, mock_get_skill):+ # 引用的技能无凭据(不在 skill_envs)→ 匹配不到 → 回退注入 active+ mock_get_skill.return_value = "hwocr"+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={+ "command": "python3 /opt/skills/gitcode-api/scripts/cli.py --help"+ }+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert not ctx.extra.get("_skip_tool")+ assert ctx.inputs.tool_args["env"]["HWOCR_AK"] == "ak"++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_gate_with_json_string_tool_args(self, mock_get_skill):+ mock_get_skill.return_value = None+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args=json.dumps(+ {"command": "python3 /opt/skills/hwocr/scripts/run.py"}+ )+ )+ asyncio.run(rail.before_tool_call(ctx))+ assert ctx.extra.get("_skip_tool") is True+ assert isinstance(ctx.inputs.tool_args, dict)+ assert 'skill_tool(skill_name="hwocr")' in str(ctx.inputs.tool_result)++ @patch(+ "jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail.get_session_active_skill"+ )+ def test_gate_message_english(self, mock_get_skill):+ mock_get_skill.return_value = None+ rail = self._make_rail()+ ctx = self._make_ctx(+ tool_args={"command": "python3 /opt/skills/hwocr/scripts/run.py"}+ )+ ctx.extra["language"] = "en"+ asyncio.run(rail.before_tool_call(ctx))+ assert ctx.extra.get("_skip_tool") is True+ message = str(ctx.inputs.tool_result)+ assert "skill_tool" in message+ assert "credential" in message.lower()++if __name__ == "__main__":unittest.main(verbosity=2)diff --git a/tests/unit_tests/test_session_history_buffer.py b/tests/unit_tests/test_session_history_buffer.pyindex cc004295cc..3bcbd8e836 100644--- a/tests/unit_tests/test_session_history_buffer.py+++ b/tests/unit_tests/test_session_history_buffer.py@@ -37,6 +37,48 @@ def _stop_flush_thread():sh._flush_stop_event.clear()+class TestStripSkillEnvFromHistoryItem:+ """P1 修复配套:persist 侧 env 剥离固化(tool_call/tool_calls/arguments 三形态)。"""++ def test_tool_call_dict_arguments_stripped(self):+ item = {+ "tool_call": {+ "name": "bash",+ "arguments": {"command": "echo hi", "env": {"EM_API_KEY": "k"}},+ }+ }+ sh._strip_skill_env_from_history_item(item)+ assert "env" not in item["tool_call"]["arguments"]+ assert item["tool_call"]["arguments"]["command"] == "echo hi"++ def test_tool_calls_list_stripped(self):+ item = {+ "tool_calls": [+ {"name": "bash", "arguments": {"env": {"EM_API_KEY": "k"}}},+ {+ "name": "bash",+ "arguments": json.dumps(+ {"command": "x", "env": {"EM_API_KEY": "k"}}+ ),+ },+ ]+ }+ sh._strip_skill_env_from_history_item(item)+ assert "env" not in item["tool_calls"][0]["arguments"]+ assert "env" not in json.loads(item["tool_calls"][1]["arguments"])++ def test_item_level_arguments_stripped(self):+ item = {"arguments": json.dumps({"env": {"EM_API_KEY": "k"}, "a": 1})}+ sh._strip_skill_env_from_history_item(item)+ assert "env" not in json.loads(item["arguments"])++ def test_no_env_untouched(self):+ item = {"arguments": {"command": "echo hi"}}+ snapshot = json.dumps(item, sort_keys=True)+ sh._strip_skill_env_from_history_item(item)+ assert json.dumps(item, sort_keys=True) == snapshot++@pytest.fixture(autouse=True)def _reset_buffer_state():"""每个测试前后清空全局缓冲状态,避免互相污染。"""