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: 修复并发会话创建定时任务时 deliveryThreadId 串台
Fancy1234567fcfc6a26e247
diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.pyindex 185293771c..cd22511d9f 100644--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py@@ -37,9 +37,20 @@ from jiuwenswarm.common.mcp_config import (bind_active_office_claw_mcp_tools,bind_office_claw_from_agent,get_active_office_claw_mcp_tool_ids,+ is_office_claw_tool_name_live_concurrent,resolve_active_office_claw_tool_id,)++def _office_claw_tool_env_value(tool: Any, key: str) -> str:+ params = getattr(tool, "_params", None)+ if not isinstance(params, dict):+ return ""+ env = params.get("env")+ if not isinstance(env, dict):+ return ""+ return str(env.get(key) or "").strip()+logger = logging.getLogger(__name__)_LOG_PREFIX = "[ProgressiveToolRail]"@@ -51,6 +62,13 @@ _DEEPRESEARCH_CONTEXT_TOOLS = frozenset({"deepresearch_commit_rewrite","deepresearch_generate_rewrite_html",})+_OFFICE_CLAW_SCHEDULE_THREAD_PIN_TOOLS = frozenset(+ {+ "office_claw_register_scheduled_task",+ "office_claw_preview_scheduled_task",+ "office_claw_update_scheduled_task",+ }+)def _json_safe_value(value: Any) -> Any:@@ -122,15 +140,29 @@ class ProgressiveToolRail(DeepAgentRail):# Interaction rounds do not inherit the facade ContextVar, so# invoke_tool re-binds from this attribute before tool execution.self._office_claw_active_tool_ids: frozenset[str] | None = None+ self._office_claw_delivery_thread_id: str | None = None+ self._office_claw_invocation_id: str | None = None- def set_office_claw_active_tool_ids(self, tool_ids: Iterable[str] | None) -> None:+ def set_office_claw_active_tool_ids(+ self,+ tool_ids: Iterable[str] | None,+ *,+ delivery_thread_id: str | None = None,+ invocation_id: str | None = None,+ ) -> None:"""Publish or clear this rail's OfficeClaw request-scoped allowlist."""if tool_ids is None:self._office_claw_active_tool_ids = None+ self._office_claw_delivery_thread_id = None+ self._office_claw_invocation_id = Nonereturnself._office_claw_active_tool_ids = frozenset(str(tool_id).strip() for tool_id in tool_ids if str(tool_id).strip())+ thread = str(delivery_thread_id or "").strip()+ inv = str(invocation_id or "").strip()+ self._office_claw_delivery_thread_id = thread or None+ self._office_claw_invocation_id = inv or None@contextmanagerdef _bind_deepresearch_context(self, tool_name: str) -> Iterator[None]:@@ -272,9 +304,16 @@ class ProgressiveToolRail(DeepAgentRail):self._meta_active = Falsedef init(self, agent: Any) -> None:- card = getattr(agent, "card", None)- resolved_card_id = str(getattr(card, "id", "") or "").strip() or None- self.update_agent_card_id(resolved_card_id)+ # ``AgentCard.id`` is a persistence identity shared by every session+ # adapter for the same agent. Constructor already receives a+ # session-scoped owner id (``{card}_s_{session}``). Overwriting it with+ # the shared card id collapses ``invoke_tool`` / ``tools_search`` onto+ # one process-global resource_mgr entry — last session's rail (and its+ # OfficeClaw pin) then serves every concurrent session.+ if not self.agent_card_id:+ card = getattr(agent, "card", None)+ resolved_card_id = str(getattr(card, "id", "") or "").strip() or None+ self.update_agent_card_id(resolved_card_id)self._deep_agent = agentself._runtime_agent = agentself.invalidate_deferred_tool_cache()@@ -845,8 +884,62 @@ class ProgressiveToolRail(DeepAgentRail):)return None+ def _owned_office_claw_tool_id(self, tool_name: str) -> str:+ """Return this rail's allowlisted request-scoped id for ``tool_name``."""+ owned = getattr(self, "_office_claw_active_tool_ids", None)+ if not owned:+ return ""+ suffix = f".{tool_name}"+ matches = [+ tool_id+ for tool_id in owned+ if tool_id.endswith(suffix) or tool_id.rsplit(".", 1)[-1] == tool_name+ ]+ if not matches:+ return ""+ preferred = []+ for tool_id in matches:+ if tool_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX) and tool_id.endswith(+ suffix+ ):+ preferred.append(tool_id)+ return preferred[0] if preferred else matches[0]++ def _is_foreign_office_claw_tool_id(+ self,+ tool_id: str,+ tool_name: str,+ *,+ allowed: frozenset[str] | None,+ ) -> bool:+ """True when ``tool_id`` must not be used for this request."""+ if not tool_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX):+ return False+ owned = getattr(self, "_office_claw_active_tool_ids", None)+ if owned is not None:+ return tool_id not in owned+ if allowed is not None:+ return tool_id not in allowed+ # No request binding: never trust a live request-scoped card under+ # concurrency (ask_user resume races), and never trust one without a+ # rail pin even when only one registration remains — it may belong to+ # another session after our own MCP was cleaned.+ if is_office_claw_tool_name_live_concurrent(tool_name):+ return True+ return not bool(+ str(getattr(self, "_office_claw_invocation_id", None) or "").strip()+ )+def _tool_instance_available(self, tool_name: str, tool_id: str) -> bool:"""True when cache id or this request's active OfficeClaw id still resolves."""+ owned_id = self._owned_office_claw_tool_id(tool_name)+ if owned_id:+ return self._lookup_tool_instance(owned_id) is not None+ if tool_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX):+ if self._is_foreign_office_claw_tool_id(+ tool_id, tool_name, allowed=get_active_office_claw_mcp_tool_ids()+ ):+ return Falseif self._lookup_tool_instance(tool_id) is not None:return Trueactive_id = resolve_active_office_claw_tool_id(tool_name)@@ -864,15 +957,39 @@ class ProgressiveToolRail(DeepAgentRail):"""Resolve a live tool instance, recovering from stale card ids.Order:- 1. this request's ``bind_active_office_claw_mcp_tools`` allowlist- (authoritative for OfficeClaw MCP even when short-name AM / deferred- cache still points at a concurrent request's live card)- 2. preferred_id from deferred cache / AbilityManager card — skipped when- it is a foreign ``office-claw-request-*`` id under an active allowlist- 3. refresh AbilityManager cache and retry if the live card id changed+ 1. this rail's request-scoped OfficeClaw allowlist (session pin)+ 2. this request's ``bind_active_office_claw_mcp_tools`` allowlist+ 3. preferred_id from deferred cache / AbilityManager card — skipped when+ it is a foreign ``office-claw-request-*`` id+ 4. refresh AbilityManager cache and retry if the live card id changedReturns ``(tool, resolved_id, refreshed_id_for_diagnostics)``."""+ owned_id = self._owned_office_claw_tool_id(tool_name)+ if owned_id:+ target_tool = self._lookup_tool_instance(owned_id)+ if target_tool is not None:+ if owned_id != preferred_id:+ logger.info(+ "%s rail-owned OfficeClaw tool_id preferred: tool_name=%s "+ "preferred_id=%s owned_id=%s",+ _LOG_PREFIX,+ tool_name,+ preferred_id,+ owned_id,+ )+ return target_tool, owned_id, ""+ logger.warning(+ "%s rail-owned OfficeClaw tool instance missing: tool_name=%s "+ "owned_id=%s preferred_id=%s",+ _LOG_PREFIX,+ tool_name,+ owned_id,+ preferred_id,+ )+ # Fail closed: never fall through to another request's live tool.+ return None, owned_id, ""+active_id = resolve_active_office_claw_tool_id(tool_name)if active_id:target_tool = self._lookup_tool_instance(active_id)@@ -889,10 +1006,8 @@ class ProgressiveToolRail(DeepAgentRail):return target_tool, active_id, ""allowed = get_active_office_claw_mcp_tool_ids()- preferred_is_foreign_office_claw = (- preferred_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX)- and allowed is not None- and preferred_id not in allowed+ preferred_is_foreign_office_claw = self._is_foreign_office_claw_tool_id(+ preferred_id, tool_name, allowed=allowed)if not preferred_is_foreign_office_claw:target_tool = self._lookup_tool_instance(preferred_id)@@ -900,10 +1015,14 @@ class ProgressiveToolRail(DeepAgentRail):return target_tool, preferred_id, ""elif preferred_id:logger.info(- "%s skip foreign OfficeClaw preferred_id: tool_name=%s preferred_id=%s",+ "%s skip foreign OfficeClaw preferred_id: tool_name=%s preferred_id=%s "+ "allowed_bound=%s concurrent=%s rail_bound=%s",_LOG_PREFIX,tool_name,preferred_id,+ allowed is not None,+ is_office_claw_tool_name_live_concurrent(tool_name),+ getattr(self, "_office_claw_active_tool_ids", None) is not None,)logger.info(@@ -922,10 +1041,8 @@ class ProgressiveToolRail(DeepAgentRail):str(getattr(refreshed_card, "id", "") or "") if refreshed_card is not None else "")if refreshed_id and refreshed_id != preferred_id:- refreshed_is_foreign = (- refreshed_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX)- and allowed is not None- and refreshed_id not in allowed+ refreshed_is_foreign = self._is_foreign_office_claw_tool_id(+ refreshed_id, tool_name, allowed=allowed)if not refreshed_is_foreign:target_tool = self._lookup_tool_instance(refreshed_id)@@ -953,15 +1070,19 @@ class ProgressiveToolRail(DeepAgentRail):) -> dict[str, Any]:"""Invoke a deferred tool with validated arguments."""owned = self._office_claw_active_tool_ids- bind_cm = (- bind_active_office_claw_mcp_tools(owned)- if owned is not None- else nullcontext()- )- with bind_cm:- return await self._invoke_target_tool_with_binding(- session, params, **kwargs+ runtime_agent = self._resolve_runtime_agent()+ # AM carrier may be stale/cleared across ask_user resume races; bind it+ # first, then re-assert the rail pin so this session's request wins.+ with bind_office_claw_from_agent(runtime_agent):+ bind_cm = (+ bind_active_office_claw_mcp_tools(owned)+ if owned is not None+ else nullcontext())+ with bind_cm:+ return await self._invoke_target_tool_with_binding(+ session, params, **kwargs+ )async def _invoke_target_tool_with_binding(self,@@ -987,123 +1108,220 @@ class ProgressiveToolRail(DeepAgentRail):"tool_name": tool_name,}- # Re-bind the OfficeClaw tool id allowlist from the shared ability_manager.- # The supervisor / round task (where this code runs) was created at- # session startup, before ``bind_active_office_claw_mcp_tools`` set- # the ContextVar in the caller's task. ``bind_office_claw_from_agent``- # reads the ids stored on the shared ability_manager by- # ``register_request_scoped_office_claw_mcp`` and sets the ContextVar- # for this task so that both tool resolution- # (``resolve_active_office_claw_tool_id``) and tool invocation- # (``ensure_request_scoped_office_claw_tool_allowed``) pass.- runtime_agent = self._resolve_runtime_agent()- with bind_office_claw_from_agent(runtime_agent):- target_tool_card = None- for tool in self._cached_deferred_tool_infos:- if str(getattr(tool, "name", "") or "") == tool_name:- target_tool_card = tool- break-- if target_tool_card is None:- agent = self._resolve_runtime_agent()- ability_manager = getattr(agent, "ability_manager", None)- lookup_timeout = getattr(AbilityManager, "_resolve_call_timeout")(None)- try:- with anyio.fail_after(lookup_timeout):- if ability_manager is not None:- try:- await ability_manager.list_tool_info()- except Exception as exc:- logger.warning(- "%s invoke fallback list_tool_info failed: %s",- _LOG_PREFIX,- exc,- )- await self._refresh_deferred_tool_cache()- for tool in self._cached_deferred_tool_infos:- if str(getattr(tool, "name", "") or "") == tool_name:- target_tool_card = tool- break- except TimeoutError:- return {- "success": False,- "error": (- f"Tool lookup for '{tool_name}' timed out after "- f"{lookup_timeout}s"- ),- "tool_name": tool_name,- }+ target_tool_card = None+ for tool in self._cached_deferred_tool_infos:+ if str(getattr(tool, "name", "") or "") == tool_name:+ target_tool_card = tool+ break- if target_tool_card is None:+ if target_tool_card is None:+ agent = self._resolve_runtime_agent()+ ability_manager = getattr(agent, "ability_manager", None)+ lookup_timeout = getattr(AbilityManager, "_resolve_call_timeout")(None)+ try:+ with anyio.fail_after(lookup_timeout):+ if ability_manager is not None:+ try:+ await ability_manager.list_tool_info()+ except Exception as exc:+ logger.warning(+ "%s invoke fallback list_tool_info failed: %s",+ _LOG_PREFIX,+ exc,+ )+ await self._refresh_deferred_tool_cache()+ for tool in self._cached_deferred_tool_infos:+ if str(getattr(tool, "name", "") or "") == tool_name:+ target_tool_card = tool+ break+ except TimeoutError:return {"success": False,- "error": f"工具 '{tool_name}' 未注册或不在按需可见工具列表中。",+ "error": (+ f"Tool lookup for '{tool_name}' timed out after "+ f"{lookup_timeout}s"+ ),"tool_name": tool_name,}- preferred_id = str(getattr(target_tool_card, "id", "") or "")- target_tool, target_tool_id, refreshed_id = await self._resolve_tool_instance_with_recovery(- tool_name,- preferred_id,- )-- if target_tool is None:- logger.warning(- "%s invoke tool=%s failed: instance not found, "- "tool_id=%s, refresh_attempted=True, refreshed_id=%s, active_id=%s",- _LOG_PREFIX,- tool_name,- target_tool_id,- refreshed_id,- resolve_active_office_claw_tool_id(tool_name) or "",- )+ owned_id = self._owned_office_claw_tool_id(tool_name)+ if target_tool_card is None and not owned_id:+ concurrent = is_office_claw_tool_name_live_concurrent(tool_name)+ if concurrent or tool_name.startswith("office_claw_"):return {"success": False,- "error": f"无法获取工具 '{tool_name}' 的实例。",+ "error": (+ f"工具 '{tool_name}' 当前不可用(可能被并发会话清理),"+ "请稍后重试注册/调用。"+ ),"tool_name": tool_name,}+ return {+ "success": False,+ "error": f"工具 '{tool_name}' 未注册或不在按需可见工具列表中。",+ "tool_name": tool_name,+ }- try:- kwargs_without_session = {k: v for k, v in kwargs.items() if k != "session"}- owned = self._office_claw_active_tool_ids- if owned is not None:- kwargs_without_session[OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG] = owned- call_timeout = getattr(AbilityManager, "_resolve_call_timeout")(- target_tool_card+ preferred_id = owned_id or str(getattr(target_tool_card, "id", "") or "")+ target_tool, target_tool_id, refreshed_id = await self._resolve_tool_instance_with_recovery(+ tool_name,+ preferred_id,+ )++ if target_tool is None:+ logger.warning(+ "%s invoke tool=%s failed: instance not found, "+ "tool_id=%s, refresh_attempted=True, refreshed_id=%s, active_id=%s "+ "owned_id=%s concurrent=%s",+ _LOG_PREFIX,+ tool_name,+ target_tool_id,+ refreshed_id,+ resolve_active_office_claw_tool_id(tool_name) or "",+ owned_id or "",+ is_office_claw_tool_name_live_concurrent(tool_name),+ )+ if tool_name.startswith("office_claw_") or is_office_claw_tool_name_live_concurrent(+ tool_name+ ):+ error = (+ f"无法获取工具 '{tool_name}' 的实例"+ "(可能被并发请求清理),请稍后重试。")- with self._bind_deepresearch_context(tool_name):- try:- with anyio.fail_after(call_timeout) as timeout_scope:- result = await target_tool.invoke(- arguments, session=session, **kwargs_without_session- )- except TimeoutError as exc:- if not timeout_scope.cancel_called:- raise- raise TimeoutError(- f"Tool '{tool_name}' timed out after {call_timeout}s"- ) from exc- logger.info(- "%s invoke tool=%s success=True result_type=%s",- _LOG_PREFIX,- tool_name,- type(result).__name__,+ else:+ error = f"无法获取工具 '{tool_name}' 的实例。"+ return {+ "success": False,+ "error": error,+ "tool_name": tool_name,+ }++ expected_invocation = str(self._office_claw_invocation_id or "").strip()+ actual_invocation = _office_claw_tool_env_value(+ target_tool, "OFFICE_CLAW_INVOCATION_ID"+ )+ active_allowed = get_active_office_claw_mcp_tool_ids()+ is_request_tool_without_binding = (+ target_tool_id.startswith(OFFICE_CLAW_REQUEST_TOOL_ID_PREFIX)+ and not expected_invocation+ and self._office_claw_active_tool_ids is None+ and active_allowed is None+ )+ if is_request_tool_without_binding:+ logger.warning(+ "%s refuse OfficeClaw tool without request binding: "+ "tool_name=%s tool_id=%s actual_inv=%s",+ _LOG_PREFIX,+ tool_name,+ target_tool_id,+ (actual_invocation[:8] + "…") if actual_invocation else "-",+ )+ return {+ "success": False,+ "error": (+ "OfficeClaw MCP tools are not bound for this request; "+ "refusing cross-session invoke — please retry"+ ),+ "tool_name": tool_name,+ }+ if expected_invocation:+ if actual_invocation and actual_invocation != expected_invocation:+ active_id = resolve_active_office_claw_tool_id(tool_name) or owned_id+ recovered = (+ self._lookup_tool_instance(active_id) if active_id else None)- return {- "success": True,- "tool_name": tool_name,- "result": _json_safe_value(result),- }- except Exception as exc:- logger.warning(- "%s invoke tool=%s failed: %s",- _LOG_PREFIX,- tool_name,- exc,- exc_info=True,+ recovered_inv = (+ _office_claw_tool_env_value(+ recovered, "OFFICE_CLAW_INVOCATION_ID"+ )+ if recovered is not None+ else "")- return {- "success": False,- "error": str(exc),- "tool_name": tool_name,- }+ if recovered is not None and recovered_inv == expected_invocation:+ logger.warning(+ "%s replaced cross-request OfficeClaw tool instance: "+ "tool_name=%s stale_id=%s active_id=%s",+ _LOG_PREFIX,+ tool_name,+ target_tool_id,+ active_id,+ )+ target_tool = recovered+ target_tool_id = active_id or target_tool_id+ else:+ logger.warning(+ "%s refuse OfficeClaw tool credential mismatch: "+ "tool_name=%s tool_id=%s expected_inv=%s actual_inv=%s",+ _LOG_PREFIX,+ tool_name,+ target_tool_id,+ expected_invocation[:8],+ actual_invocation[:8],+ )+ return {+ "success": False,+ "error": (+ "OfficeClaw MCP tool credentials belong to another "+ "request; refusing cross-session invoke"+ ),+ "tool_name": tool_name,+ }++ pinned_thread = str(self._office_claw_delivery_thread_id or "").strip()+ if (+ pinned_thread+ and tool_name in _OFFICE_CLAW_SCHEDULE_THREAD_PIN_TOOLS+ ):+ arguments["deliveryThreadId"] = pinned_thread++ try:+ kwargs_without_session = {k: v for k, v in kwargs.items() if k != "session"}+ owned = self._office_claw_active_tool_ids+ if owned is not None:+ kwargs_without_session[OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG] = owned+ call_timeout = getattr(AbilityManager, "_resolve_call_timeout")(+ target_tool_card+ )+ with self._bind_deepresearch_context(tool_name):+ try:+ with anyio.fail_after(call_timeout) as timeout_scope:+ result = await target_tool.invoke(+ arguments, session=session, **kwargs_without_session+ )+ except TimeoutError as exc:+ if not timeout_scope.cancel_called:+ raise+ raise TimeoutError(+ f"Tool '{tool_name}' timed out after {call_timeout}s"+ ) from exc+ env_inv = _office_claw_tool_env_value(+ target_tool, "OFFICE_CLAW_INVOCATION_ID"+ )+ logger.info(+ "%s invoke tool=%s success=True result_type=%s tool_id=%s "+ "env_invocation_id=%s delivery_thread_id=%s",+ _LOG_PREFIX,+ tool_name,+ type(result).__name__,+ target_tool_id,+ (env_inv[:8] + "…") if env_inv else "-",+ pinned_thread or "-",+ )+ return {+ "success": True,+ "tool_name": tool_name,+ "result": _json_safe_value(result),+ }+ except Exception as exc:+ logger.warning(+ "%s invoke tool=%s failed: %s",+ _LOG_PREFIX,+ tool_name,+ exc,+ exc_info=True,+ )+ return {+ "success": False,+ "error": str(exc),+ "tool_name": tool_name,+ }diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex fa4942c4f1..8e165d6cf9 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -813,6 +813,9 @@ class OfficeClawMcpRegistration:tool_ids: tuple[str, ...]tool_names: tuple[str, ...]tool_instances: tuple[RequestScopedOfficeClawMcpTool, ...] = ()+ # Relay callback invocation id pinned into the MCP subprocess env for this+ # request (OFFICE_CLAW_INVOCATION_ID). Empty when unknown / not office-claw.+ invocation_id: str = ""# Request-scoped long-lived MCP worker pool@@ -1320,6 +1323,45 @@ def get_live_office_claw_allowlist_for_tool_instance(return _live_office_claw_tool_instances.get(tool)+def _office_claw_invocation_id_from_params(params: Mapping[str, Any] | None) -> str:+ """Extract OFFICE_CLAW_INVOCATION_ID from MCP connect params, if present."""++ if not isinstance(params, Mapping):+ return ""+ env = params.get("env")+ if not isinstance(env, Mapping):+ return ""+ return str(env.get("OFFICE_CLAW_INVOCATION_ID") or "").strip()+++def resolve_active_office_claw_invocation_id() -> str | None:+ """Return the callback invocation id owned by the active allowlist, if known.++ Looks up live request-scoped tool instances whose registered allowlist matches+ the ContextVar binding. Used to refuse invokes whose subprocess env was pinned+ to a different Relay invocation (cross-session credential mix-ups).+ """++ allowed = get_active_office_claw_mcp_tool_ids()+ if not allowed:+ return None+ allowed_ids = frozenset(allowed)+ exact_match: str | None = None+ card_match: str | None = None+ with _live_office_claw_allowlist_lock:+ for tool, ids in _live_office_claw_tool_instances.items():+ inv = _office_claw_invocation_id_from_params(getattr(tool, "_params", None))+ if not inv:+ continue+ if ids == allowed_ids:+ exact_match = inv+ break+ tool_id = str(getattr(getattr(tool, "_card", None), "id", "") or "")+ if card_match is None and tool_id in allowed_ids:+ card_match = inv+ return exact_match or card_match++def _clear_live_office_claw_allowlists_for_tests() -> None:with _live_office_claw_allowlist_lock:_live_office_claw_allowlists_by_tool_id.clear()@@ -1440,6 +1482,22 @@ def ensure_request_scoped_office_claw_tool_allowed(tool_id: str) -> None:)+def ensure_office_claw_tool_invocation_matches_active(+ tool: RequestScopedOfficeClawMcpTool,+) -> None:+ """Refuse when the tool's MCP env invocation disagrees with the active allowlist."""++ expected = resolve_active_office_claw_invocation_id()+ if not expected:+ return+ actual = _office_claw_invocation_id_from_params(getattr(tool, "_params", None))+ if actual and actual != expected:+ raise RuntimeError(+ "OfficeClaw MCP tool env invocation mismatches active request binding; "+ "refusing cross-request invoke"+ )++def get_active_office_claw_mcp_tool_ids() -> frozenset[str] | None:"""Return the request-local OfficeClaw tool id allowlist, if bound."""@@ -1968,7 +2026,13 @@ class RequestScopedOfficeClawMcpTool(Tool):server_name: str = "",) -> None:super().__init__(card)- self._params = dict(params)+ # Deep-copy env so concurrent registrations cannot mutate each other's+ # OFFICE_CLAW_INVOCATION_ID via a shared nested dict reference.+ copied = dict(params)+ env = copied.get("env")+ if isinstance(env, Mapping):+ copied["env"] = dict(env)+ self._params = copiedself._request_id = str(request_id or "")self._server_name = str(server_name or "")@@ -2022,6 +2086,7 @@ class RequestScopedOfficeClawMcpTool(Tool):tool_id = str(getattr(self._card, "id", "") or "")try:ensure_request_scoped_office_claw_tool_allowed(tool_id)+ ensure_office_claw_tool_invocation_matches_active(self)except RuntimeError as exc:raise build_error(StatusCode.TOOL_MCP_EXECUTION_ERROR,@@ -2074,6 +2139,7 @@ __all__ = ["build_enabled_mcp_server_configs","build_mcp_server_config","create_mcp_tool",+ "ensure_office_claw_tool_invocation_matches_active","ensure_request_scoped_office_claw_tool_allowed","extract_enabled_mcp_server_entries","extract_office_claw_mcp",@@ -2089,6 +2155,7 @@ __all__ = ["publish_live_office_claw_allowlist","register_live_office_claw_tool_instance","release_request_scoped_mcp_sessions",+ "resolve_active_office_claw_invocation_id","resolve_active_office_claw_tool_id","revoke_live_office_claw_allowlist","unregister_live_office_claw_tool_instance",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex bfa3f26017..c07f63373b 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -3821,6 +3821,7 @@ class JiuWenSwarmDeepAdapter:tool_ids: list[str] = []tool_names: list[str] = []registered_tools: list[RequestScopedOfficeClawMcpTool] = []+ invocation_id = "-"try:request_scope = hashlib.sha256(f"{request.session_id}:{request.request_id}".encode("utf-8")@@ -3830,7 +3831,6 @@ class JiuWenSwarmDeepAdapter:seen_names: set[str] = set()# --- Source 1: 自带 office-claw MCP(identity-pinned)。 ---- invocation_id = "-"if raw_config is not None:params = validate_office_claw_mcp_config(raw_config)tool_defs = await list_office_claw_mcp_tools(params)@@ -3862,6 +3862,7 @@ class JiuWenSwarmDeepAdapter:# are still fully removable by the common cleanup path.tool_ids.append(tool_id)tool_names.append(tool_name)+ registered_tools.append(tool)self._install_office_claw_ability_card(card)request_env = params.get("env") if isinstance(params.get("env"), dict) else {}invocation_id = str(request_env.get("OFFICE_CLAW_INVOCATION_ID") or "").strip() or "-"@@ -3946,8 +3947,24 @@ class JiuWenSwarmDeepAdapter:continuetool_ids.append(tool_id)tool_names.append(tool_name)+ registered_tools.append(tool)self._install_office_claw_ability_card(card)_connector_registered += 1+ if (+ server_name == "office-claw"+ and invocation_id == "-"+ ):+ connector_env = (+ connector_params.get("env")+ if isinstance(connector_params.get("env"), dict)+ else {}+ )+ invocation_id = (+ str(+ connector_env.get("OFFICE_CLAW_INVOCATION_ID") or ""+ ).strip()+ or "-"+ )if _connector_registered == 0:logger.error("[JiuWenSwarmDeepAdapter] request-scoped MCP connector "@@ -3971,6 +3988,7 @@ class JiuWenSwarmDeepAdapter:tool_ids=tuple(tool_ids),tool_names=tuple(tool_names),tool_instances=tuple(registered_tools),+ invocation_id="" if invocation_id == "-" else invocation_id,)self._active_office_claw_mcp = registration# Store tool_ids on the agent's shared ability_manager so the@@ -3983,15 +4001,23 @@ class JiuWenSwarmDeepAdapter:registered_tool,registration.tool_ids,)- self._sync_office_claw_allowlist_to_progressive_rail(registration.tool_ids)+ self._sync_office_claw_allowlist_to_progressive_rail(+ registration.tool_ids,+ delivery_thread_id=self._office_claw_thread_id_from_tools(+ registered_tools+ ),+ invocation_id="" if invocation_id == "-" else invocation_id,+ )logger.info("[JiuWenSwarmDeepAdapter] request-scoped OfficeClaw MCP registered: "- "request_id=%s session_id=%s invocation_id=%s tools=%s tool_ids=%s",+ "request_id=%s session_id=%s invocation_id=%s tools=%s tool_ids=%s "+ "tool_instances=%d",request.request_id,request.session_id,invocation_id,tool_names,tool_ids,+ len(registered_tools),)logger.info("[latency] stage=2 name=mcp request_id=%s", request.request_id)return registration@@ -4001,6 +4027,7 @@ class JiuWenSwarmDeepAdapter:tool_ids=tuple(tool_ids),tool_names=tuple(tool_names),tool_instances=tuple(registered_tools),+ invocation_id="" if invocation_id == "-" else invocation_id,)await self.cleanup_request_scoped_office_claw_mcp(registration)raise@@ -4010,6 +4037,7 @@ class JiuWenSwarmDeepAdapter:tool_ids=tuple(tool_ids),tool_names=tuple(tool_names),tool_instances=tuple(registered_tools),+ invocation_id="" if invocation_id == "-" else invocation_id,)await self.cleanup_request_scoped_office_claw_mcp(registration)_raw_command = str(raw_config.get("command") or "").strip() if isinstance(raw_config, dict) else ""@@ -4166,8 +4194,20 @@ class JiuWenSwarmDeepAdapter:):self._active_office_claw_mcp = Noneself._sync_office_claw_allowlist_to_progressive_rail(None)- # Clear the shared ability_manager allowlist so stale ids are not reused.- clear_agent_office_claw_tool_ids(self._instance)+ # Only clear the shared AM allowlist when we are cleaning the *current*+ # active registration. A superseded request's cleanup must not wipe the+ # newer request's allowlist (ask_user resume race → active_id empty).+ clear_agent_office_claw_tool_ids(self._instance)+ elif self._active_office_claw_mcp is None:+ clear_agent_office_claw_tool_ids(self._instance)+ self._sync_office_claw_allowlist_to_progressive_rail(None)+ else:+ logger.info(+ "[JiuWenSwarmDeepAdapter] cleanup skipped clearing active OfficeClaw "+ "allowlist: cleaned_request=%s active_request=%s",+ registration.request_id,+ self._active_office_claw_mcp.request_id,+ )revoke_live_office_claw_allowlist(registration.tool_ids)# 销毁本请求池化的长生命周期 stdio session(如 chrome-devtools-mcp 浏览器进程),# 以免其活过 chat.send。best-effort,不阻塞清理。@@ -4188,6 +4228,9 @@ class JiuWenSwarmDeepAdapter:def _sync_office_claw_allowlist_to_progressive_rail(self,tool_ids: tuple[str, ...] | list[str] | frozenset[str] | None,+ *,+ delivery_thread_id: str | None = None,+ invocation_id: str | None = None,) -> None:"""Keep ProgressiveToolRail's interaction-round allowlist in sync."""@@ -4196,6 +4239,13 @@ class JiuWenSwarmDeepAdapter:if not callable(setter):returntry:+ setter(+ tool_ids,+ delivery_thread_id=delivery_thread_id,+ invocation_id=invocation_id,+ )+ except TypeError:+ # Older rail signature without keyword binding metadata.setter(tool_ids)except Exception as exc:logger.warning(@@ -4204,6 +4254,22 @@ class JiuWenSwarmDeepAdapter:exc,)+ @staticmethod+ def _office_claw_thread_id_from_tools(+ tools: list[RequestScopedOfficeClawMcpTool],+ ) -> str:+ for tool in tools:+ params = getattr(tool, "_params", None)+ if not isinstance(params, dict):+ continue+ env = params.get("env")+ if not isinstance(env, dict):+ continue+ thread_id = str(env.get("OFFICE_CLAW_THREAD_ID") or "").strip()+ if thread_id:+ return thread_id+ return ""+async def _register_mcp_servers_from_config(self, config_base: dict[str, Any], *, tag: str = "agent.main") -> None:@@ -7960,6 +8026,18 @@ class JiuWenSwarmDeepAdapter:progressive_tool_rail = self._build_progressive_tool_rail(config)if progressive_tool_rail is not None:self._progressive_tool_rail = progressive_tool_rail+ # Rebuild wipes rail-local OfficeClaw pins; re-sync from the+ # still-active request registration so concurrent schedule+ # creates do not invoke unbound / foreign MCP tools.+ active_mcp = self._active_office_claw_mcp+ if active_mcp is not None:+ self._sync_office_claw_allowlist_to_progressive_rail(+ active_mcp.tool_ids,+ delivery_thread_id=self._office_claw_thread_id_from_tools(+ list(active_mcp.tool_instances)+ ),+ invocation_id=active_mcp.invocation_id or None,+ )elif old_progressive_tool_rail is not None:rails_to_unregister.append(old_progressive_tool_rail)diff --git a/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py b/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.pyindex 5c25bf0b22..2b4d97bf69 100644--- a/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py+++ b/tests/unit_tests/agentserver/test_progressive_tool_rail_stale_id.py@@ -28,7 +28,13 @@ from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (@pytest.mark.asyncioasync def test_invoke_retries_with_refreshed_id_when_cached_id_is_stale():"""When get_tool(stale_id) returns None, the rail refreshes the cache- and retries with the new id from the refreshed card."""+ and retries with the new id from the refreshed card.++ Same-session MCP rebind must keep the request allowlist (rail pin or+ ContextVar) pointed at the fresh id; without that pin, request-scoped+ OfficeClaw cards fail closed under concurrency.+ """+ from jiuwenswarm.common.mcp_config import bind_active_office_claw_mcp_toolsold_card = SimpleNamespace(name="office_claw_register_scheduled_task",@@ -59,7 +65,7 @@ async def test_invoke_retries_with_refreshed_id_when_cached_id_is_stale():return targetreturn None- with patch.object(+ with bind_active_office_claw_mcp_tools([new_card.id]), patch.object(Runner.resource_mgr, "get_tool", side_effect=_get_tool_side_effect), patch.object(rail, "_refresh_deferred_tool_cache", new=_fake_refresh@@ -426,3 +432,40 @@ def test_resolve_active_office_claw_tool_id_maps_short_name():assert resolve_active_office_claw_tool_id("missing_tool") is Noneassert resolve_active_office_claw_tool_id("office_claw_preview_scheduled_task") is None+++def test_rail_init_preserves_session_scoped_meta_tool_owner_id():+ """Concurrent session adapters share AgentCard.id; meta tools must not.++ Regression: ProgressiveToolRail.init() used to overwrite the constructor's+ ``{card}_s_{session}`` owner with the shared AgentCard.id, so every+ session registered the same InvokeToolTool id and last writer's OfficeClaw+ pin served all sessions (scheduled-task deliveryThreadId cross-bind).+ """+ shared_card_id = "office-agent-card"+ rail_a = ProgressiveToolRail(+ eager_tools=["tools_search", "invoke_tool"],+ agent_card_id=f"{shared_card_id}_s_session_a",+ agent_id=f"{shared_card_id}_s_session_a",+ )+ rail_b = ProgressiveToolRail(+ eager_tools=["tools_search", "invoke_tool"],+ agent_card_id=f"{shared_card_id}_s_session_b",+ agent_id=f"{shared_card_id}_s_session_b",+ )+ shared_agent_a = SimpleNamespace(card=SimpleNamespace(id=shared_card_id))+ shared_agent_b = SimpleNamespace(card=SimpleNamespace(id=shared_card_id))++ rail_a.init(shared_agent_a)+ rail_b.init(shared_agent_b)++ assert rail_a.agent_card_id == f"{shared_card_id}_s_session_a"+ assert rail_b.agent_card_id == f"{shared_card_id}_s_session_b"++ id_a = {tool.card.id for tool in rail_a._meta_tool_instances()}+ id_b = {tool.card.id for tool in rail_b._meta_tool_instances()}+ assert id_a.isdisjoint(id_b)+ assert any("_s_session_a" in tool_id for tool_id in id_a)+ assert any("_s_session_b" in tool_id for tool_id in id_b)+ assert not any("_s_session_b" in tool_id for tool_id in id_a)+ assert not any("_s_session_a" in tool_id for tool_id in id_b)diff --git a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.pyindex c3e8a1792a..e2faf48c7d 100644--- a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py+++ b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py@@ -351,14 +351,22 @@ async def test_registers_exact_tool_names_and_cleans_them_up("office_claw_preview_scheduled_task","office_claw_multi_mention",)+ assert registration.invocation_id == "invoke-1"+ assert len(registration.tool_instances) == 2assert set(adapter._instance.ability_manager.cards) == set(registration.tool_names)assert len(resource_manager.tools) == 2assert adapter._active_office_claw_mcp == registration- from jiuwenswarm.common.mcp_config import get_live_office_claw_allowlist_for_tool_id+ from jiuwenswarm.common.mcp_config import (+ get_live_office_claw_allowlist_for_tool_id,+ get_live_office_claw_allowlist_for_tool_instance,+ )assert get_live_office_claw_allowlist_for_tool_id(registration.tool_ids[0]) == frozenset(registration.tool_ids)+ assert get_live_office_claw_allowlist_for_tool_instance(+ registration.tool_instances[0]+ ) == frozenset(registration.tool_ids)await adapter.cleanup_request_scoped_office_claw_mcp(registration)@@ -651,3 +659,288 @@ def test_clear_agent_office_claw_tool_ids_unbinds() -> None:with bind_office_claw_from_agent(agent):with pytest.raises(RuntimeError, match="without an active request binding"):ensure_request_scoped_office_claw_tool_allowed(tool_id)+++async def test_cleanup_superseded_request_preserves_active_allowlist(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Old request cleanup must not wipe the newer request's AM allowlist."""+ from jiuwenswarm.common.mcp_config import (+ _OFFICE_CLAW_TOOL_IDS_ATTR,+ _clear_live_office_claw_allowlists_for_tests,+ )++ for key, value in _startup_env().items():+ monkeypatch.setenv(key, value)+ resource_manager = _ResourceManager()+ monkeypatch.setattr(interface_deep.Runner, "resource_mgr", resource_manager)+ monkeypatch.setattr(+ interface_deep,+ "list_office_claw_mcp_tools",+ AsyncMock(return_value=_tool_list()),+ )+ _clear_live_office_claw_allowlists_for_tests()+ adapter = _bare_session_adapter()++ old_reg = await adapter.register_request_scoped_office_claw_mcp(+ _request(+ _valid_config(invocation_id="inv-old"),+ request_id="req-old",+ session_id="sess-1",+ )+ )+ assert old_reg is not None++ new_reg = await adapter.register_request_scoped_office_claw_mcp(+ _request(+ _valid_config(invocation_id="inv-new"),+ request_id="req-new",+ session_id="sess-1",+ )+ )+ assert new_reg is not None+ assert adapter._active_office_claw_mcp == new_reg+ ability = adapter._instance.ability_manager+ assert getattr(ability, _OFFICE_CLAW_TOOL_IDS_ATTR) == frozenset(new_reg.tool_ids)++ await adapter.cleanup_request_scoped_office_claw_mcp(old_reg)++ assert adapter._active_office_claw_mcp == new_reg+ assert getattr(ability, _OFFICE_CLAW_TOOL_IDS_ATTR) == frozenset(new_reg.tool_ids)+ with bind_office_claw_from_agent(adapter._instance):+ ensure_request_scoped_office_claw_tool_allowed(new_reg.tool_ids[0])++ await adapter.cleanup_request_scoped_office_claw_mcp(new_reg)+ _clear_live_office_claw_allowlists_for_tests()+++async def test_invoke_refuses_env_invocation_mismatch_against_active_allowlist() -> None:+ from jiuwenswarm.common.mcp_config import (+ _clear_live_office_claw_allowlists_for_tests,+ publish_live_office_claw_allowlist,+ register_live_office_claw_tool_instance,+ revoke_live_office_claw_allowlist,+ unregister_live_office_claw_tool_instance,+ )++ _clear_live_office_claw_allowlists_for_tests()+ tool_id = "office-claw-request-aaa.office-claw.office_claw_register_scheduled_task"+ card = ToolCard(+ id=tool_id,+ name="office_claw_register_scheduled_task",+ description="register",+ input_params={},+ )+ live_tool = RequestScopedOfficeClawMcpTool(+ card,+ {+ "command": "node",+ "args": ["index.js"],+ "cwd": ".",+ "env": {"OFFICE_CLAW_INVOCATION_ID": "inv-a"},+ },+ request_id="req-a",+ server_name="office-claw",+ )+ wrong_env_tool = RequestScopedOfficeClawMcpTool(+ card,+ {+ "command": "node",+ "args": ["index.js"],+ "cwd": ".",+ "env": {"OFFICE_CLAW_INVOCATION_ID": "inv-c"},+ },+ request_id="req-c",+ server_name="office-claw",+ )+ publish_live_office_claw_allowlist([tool_id])+ register_live_office_claw_tool_instance(live_tool, [tool_id])++ try:+ with bind_active_office_claw_mcp_tools([tool_id]):+ with pytest.raises(Exception, match="env invocation mismatches"):+ await wrong_env_tool.invoke({})+ finally:+ unregister_live_office_claw_tool_instance(live_tool)+ revoke_live_office_claw_allowlist([tool_id])+ _clear_live_office_claw_allowlists_for_tests()+++async def test_concurrent_unbound_preferred_id_is_skipped_by_rail() -> None:+ """When allowlist is unbound and the short name is live-concurrent, refuse preferred_id."""+ from jiuwenswarm.common.mcp_config import (+ _clear_live_office_claw_allowlists_for_tests,+ publish_live_office_claw_allowlist,+ revoke_live_office_claw_allowlist,+ )+ from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (+ ProgressiveToolRail,+ )++ _clear_live_office_claw_allowlists_for_tests()+ owned_id = "office-claw-request-aaa.office-claw.office_claw_register_scheduled_task"+ foreign_id = "office-claw-request-ccc.office-claw.office_claw_register_scheduled_task"+ publish_live_office_claw_allowlist([owned_id])+ publish_live_office_claw_allowlist([foreign_id])++ rail = object.__new__(ProgressiveToolRail)+ rail._office_claw_active_tool_ids = None+ rail._office_claw_invocation_id = None+ rail._office_claw_delivery_thread_id = None+ rail._cached_deferred_tool_infos = []+ foreign_tool = SimpleNamespace(card=SimpleNamespace(id=foreign_id))+ rail._lookup_tool_instance = lambda tool_id: ( # type: ignore[method-assign]+ foreign_tool if tool_id == foreign_id else None+ )+ rail._refresh_deferred_tool_cache = AsyncMock()++ try:+ # ContextVar unbound + concurrent live → must not return foreign preferred.+ tool, resolved_id, _ = await rail._resolve_tool_instance_with_recovery(+ "office_claw_register_scheduled_task",+ foreign_id,+ )+ assert tool is None+ assert resolved_id == foreign_id+ finally:+ revoke_live_office_claw_allowlist([owned_id])+ revoke_live_office_claw_allowlist([foreign_id])+ _clear_live_office_claw_allowlists_for_tests()+++async def test_rail_owned_allowlist_beats_foreign_preferred_id() -> None:+ """Rail pin must resolve the owned instance even if AM preferred is foreign."""+ from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (+ ProgressiveToolRail,+ )++ owned_id = "office-claw-request-aaa.office-claw.office_claw_register_scheduled_task"+ foreign_id = "office-claw-request-ccc.office-claw.office_claw_register_scheduled_task"+ owned_tool = SimpleNamespace(_params={"env": {"OFFICE_CLAW_INVOCATION_ID": "inv-mine"}})+ foreign_tool = SimpleNamespace(_params={"env": {"OFFICE_CLAW_INVOCATION_ID": "inv-other"}})++ rail = object.__new__(ProgressiveToolRail)+ rail.set_office_claw_active_tool_ids(+ [owned_id],+ delivery_thread_id="thread_mine",+ invocation_id="inv-mine",+ )+ rail._cached_deferred_tool_infos = []+ rail._lookup_tool_instance = lambda tool_id: ( # type: ignore[method-assign]+ owned_tool if tool_id == owned_id else foreign_tool if tool_id == foreign_id else None+ )+ rail._refresh_deferred_tool_cache = AsyncMock()++ tool, resolved_id, _ = await rail._resolve_tool_instance_with_recovery(+ "office_claw_register_scheduled_task",+ foreign_id,+ )+ assert tool is owned_tool+ assert resolved_id == owned_id+++async def test_unpinned_single_live_office_claw_preferred_is_refused() -> None:+ """Without rail pin, a sole remaining request-scoped card is still unsafe."""+ from jiuwenswarm.common.mcp_config import (+ _clear_live_office_claw_allowlists_for_tests,+ publish_live_office_claw_allowlist,+ revoke_live_office_claw_allowlist,+ )+ from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (+ ProgressiveToolRail,+ )++ _clear_live_office_claw_allowlists_for_tests()+ foreign_id = "office-claw-request-ccc.office-claw.office_claw_register_scheduled_task"+ publish_live_office_claw_allowlist([foreign_id])++ rail = object.__new__(ProgressiveToolRail)+ rail._office_claw_active_tool_ids = None+ rail._office_claw_invocation_id = None+ rail._office_claw_delivery_thread_id = None+ rail._cached_deferred_tool_infos = []+ foreign_tool = SimpleNamespace(_params={"env": {"OFFICE_CLAW_INVOCATION_ID": "inv-other"}})+ rail._lookup_tool_instance = lambda tool_id: ( # type: ignore[method-assign]+ foreign_tool if tool_id == foreign_id else None+ )+ rail._refresh_deferred_tool_cache = AsyncMock()++ try:+ tool, resolved_id, _ = await rail._resolve_tool_instance_with_recovery(+ "office_claw_register_scheduled_task",+ foreign_id,+ )+ assert tool is None+ assert resolved_id == foreign_id+ finally:+ revoke_live_office_claw_allowlist([foreign_id])+ _clear_live_office_claw_allowlists_for_tests()+++async def test_invoke_refuses_office_claw_without_request_binding() -> None:+ """Unpinned request-scoped invoke must fail closed (no silent cross-session)."""+ from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (+ ProgressiveToolRail,+ )+ from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (+ InvokeToolInput,+ )++ tool_id = "office-claw-request-ccc.office-claw.office_claw_register_scheduled_task"+ live_tool = SimpleNamespace(+ _params={"env": {"OFFICE_CLAW_INVOCATION_ID": "inv-other"}},+ invoke=AsyncMock(return_value={"ok": True}),+ )+ card = SimpleNamespace(id=tool_id, name="office_claw_register_scheduled_task")++ rail = object.__new__(ProgressiveToolRail)+ rail._office_claw_active_tool_ids = None+ rail._office_claw_invocation_id = None+ rail._office_claw_delivery_thread_id = None+ rail.eager_tools = ["tools_search", "invoke_tool"]+ rail._cached_deferred_tool_infos = [card]+ rail._deepresearch_context_provider = None+ rail._lookup_tool_instance = lambda tid: live_tool if tid == tool_id else None # type: ignore[method-assign]+ rail._refresh_deferred_tool_cache = AsyncMock()+ rail._resolve_runtime_agent = lambda: None # type: ignore[method-assign]++ result = await rail._invoke_target_tool(+ session=None,+ params=InvokeToolInput(+ tool_name="office_claw_register_scheduled_task",+ arguments={"templateId": "reminder"},+ ),+ )+ assert result["success"] is False+ # Fail closed at resolve (foreign/unpinned) or refuse-without-binding.+ assert (+ "not bound" in result["error"]+ or "无法获取" in result["error"]+ or "不可用" in result["error"]+ )+ assert "未注册" not in result["error"]+ live_tool.invoke.assert_not_called()+++def test_rail_set_office_claw_binding_stores_thread_and_invocation() -> None:+ from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (+ ProgressiveToolRail,+ )++ rail = object.__new__(ProgressiveToolRail)+ rail.set_office_claw_active_tool_ids(+ ["office-claw-request-aaa.office-claw.office_claw_register_scheduled_task"],+ delivery_thread_id="thread_mine",+ invocation_id="inv-mine",+ )+ assert rail._office_claw_delivery_thread_id == "thread_mine"+ assert rail._office_claw_invocation_id == "inv-mine"+ rail.set_office_claw_active_tool_ids(None)+ assert rail._office_claw_delivery_thread_id is None+ assert rail._office_claw_invocation_id is None