Skip to content

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

自定义Tool扩展

yt2026d0b0a26bff6e
diff --git a/deploy/enterprise/.env.example b/deploy/enterprise/.env.example
index 9fd55b3ba0..f1025406c4 100644
--- a/deploy/enterprise/.env.example
+++ b/deploy/enterprise/.env.example
@@ -337,6 +337,9 @@ AGENT_SERVER_IMAGE=""
#拓展配置自定义rail
AGENT_EXTRA_RAILS=""
+#拓展配置自定义tool(模块需暴露 register_tools() 工厂,分号分隔多个模块路径)
+AGENT_EXTRA_TOOLS=""
+
# PIP 安装扩展依赖时的额外参数
# 示例配置阿里云PyPI镜像源,优化内网/国内环境包下载速度,可根据实际环境自定义调整
PIP_EXTRA_ARGS="-i https://mirrors.aliyun.com/pypi/simple"
diff --git a/deploy/enterprise/templates/gateway.template.env b/deploy/enterprise/templates/gateway.template.env
index 8ed4107ac9..7b548c3dd2 100644
--- a/deploy/enterprise/templates/gateway.template.env
+++ b/deploy/enterprise/templates/gateway.template.env
@@ -29,6 +29,9 @@ STREAMING_TOOL_WAIT_TIMEOUT_S=<<STREAMING_TOOL_WAIT_TIMEOUT_S>>
# use extension config to construct rail
AGENT_EXTRA_RAILS=<<AGENT_EXTRA_RAILS>>
+# use extension modules to register extra tools (register_tools() factories)
+AGENT_EXTRA_TOOLS=<<AGENT_EXTRA_TOOLS>>
+
# ServiceManager Configuration
AGENT_SERVER_MIN_IDLE_SERVICES=1
AGENT_SERVER_MAX_SERVICES=20
diff --git a/examples/custom_extension_tool.py b/examples/custom_extension_tool.py
new file mode 100644
index 0000000000..42aedc62b1
--- /dev/null
+++ b/examples/custom_extension_tool.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python
+"""自定义 Tool 示例:通过环境变量非侵入式注册(AGENT_EXTRA_TOOLS,仅企业版)。
+
+使用方式:
+ export AGENT_EXTRA_TOOLS=examples.custom_extension_tool
+ # 多模块分号分隔:examples.custom_extension_tool;my.pkg.other_tools
+ # 然后启动 AgentServer;env 变更需重启进程生效
+
+部署契约(docs/zh/自定义Tool扩展设计.md §5.3):
+ 1. 本模块及其第三方依赖须预装在 AgentServer 运行时 Python 环境
+ (与 AGENT_EXTRA_RAILS 扩展同一部署链路);
+ 2. register_tools() 返回模块级 @tool 单例——工具实例进程级共享,
+ 不要在工厂里新建实例;
+ 3. per-session 数据只经 contextvars 或工具参数传入,禁止模块级
+ 可变状态缓存会话数据(并发会话下会串数据)。
+
+本模块演示两个工具:
+ - query_system_api:渠道系统调用示例,演示安全契约——模型只能给
+ system_code/api_code,下游地址由模块内白名单解析;禁止把裸 url
+ 暴露为模型可填参数(提示词注入可驱动服务端任意内网访问)。
+ - get_current_user:用户信息示例,演示契约 3——当前用户经
+ contextvars 注入读取(通常由客户自己的 AGENT_EXTRA_RAILS rail 在
+ before_tool_call 时 set),工具侧只读,不落任何全局可变状态。
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import json
+import logging
+from typing import Any
+
+from openjiuwen.core.foundation.tool import Tool, tool
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# 契约 3:per-session 上下文只走 contextvar。注入点在调用链路(示例:客户
+# 自定义 rail 的 before_tool_call 中 ``CURRENT_USER.set(run_context...)``),
+# 工具侧只读。这里用 default="" 兜底,未注入时显式报错而不是串到别的会话。
+# ---------------------------------------------------------------------------
+CURRENT_USER: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "current_user", default=""
+)
+
+# 模块级【不可变】白名单:允许的 (system_code, api_code) -> 下游地址。
+# 这是常量注册表,不是会话状态;真实集成里换成签名客户端配置。
+SYSTEM_API_REGISTRY: dict[tuple[str, str], str] = {
+ ("core", "query_account_balance"): "https://core.example.psbc/balance",
+ ("core", "query_account_detail"): "https://core.example.psbc/detail",
+ ("channel", "submit_transaction"): "https://channel.example.psbc/submit",
+}
+
+# 超时钳制:模型可填 timeout 参数,但不能给离谱值拖垮会话
+_TIMEOUT_CLAMP_S = (1, 60)
+
+
+@tool(
+ name="query_system_api",
+ description=(
+ "通过渠道系统调用第三方系统 API。传入 system_code 与 api_code,"
+ "返回下游系统响应 JSON 文本。仅支持白名单内的系统与接口。"
+ ),
+)
+async def query_system_api(
+ system_code: str,
+ api_code: str,
+ payload: str = "{}",
+ timeout: int = 10,
+) -> str:
+ """调用白名单内的第三方系统接口。
+
+ Args:
+ system_code: 目标系统编码,如 core / channel。
+ api_code: 接口编码,如 query_account_balance。
+ payload: 业务请求报文(JSON 字符串)。
+ timeout: 超时秒数,范围 1-60,超范围自动钳制。
+ """
+ url = SYSTEM_API_REGISTRY.get((system_code, api_code))
+ if url is None:
+ # 白名单外直接拒绝,不回显任何路由能力
+ return json.dumps(
+ {"error": f"unregistered system/api: {system_code}/{api_code}"},
+ ensure_ascii=False,
+ )
+
+ clamped = max(_TIMEOUT_CLAMP_S[0], min(_TIMEOUT_CLAMP_S[1], timeout))
+ # 真实集成:在此用 httpx/aiohttp + 签名客户端请求 url;
+ # 样例用 sleep 模拟网络往返,保持零第三方依赖、可直接挂载。
+ await asyncio.sleep(0.05)
+ logger.info(
+ "[custom_extension_tool] query_system_api user=%s system=%s api=%s timeout=%ss",
+ CURRENT_USER.get() or "anonymous",
+ system_code,
+ api_code,
+ clamped,
+ )
+ return json.dumps(
+ {
+ "system": system_code,
+ "api": api_code,
+ "endpoint": url,
+ "echo": payload,
+ },
+ ensure_ascii=False,
+ )
+
+
+@tool(
+ name="get_current_user",
+ description="查询当前会话的用户信息。无需参数。",
+)
+async def get_current_user() -> str:
+ """返回当前会话上下文中的用户信息(contextvars 注入,工具侧只读)。"""
+ user = CURRENT_USER.get()
+ if not user:
+ return json.dumps(
+ {"error": "当前调用链路未注入用户上下文"}, ensure_ascii=False
+ )
+ return json.dumps({"user_id": user}, ensure_ascii=False)
+
+
+def register_tools() -> list[Tool]:
+ """AGENT_EXTRA_TOOLS 注册入口:返回要挂载的工具实例列表。
+
+ 必须返回模块级 @tool 单例(上面的函数对象本身),不要在这里
+ 构造新实例——实例被所有并发会话共享。
+ """
+ return [query_system_api, get_current_user]
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index aa86852b2e..890edfadce 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -1987,6 +1987,12 @@ class JiuWenSwarmDeepAdapter:
SESSION_ADAPTER_EVICT_BATCH_SIZE = 3
SESSION_ADAPTER_RELOAD_RETRY_INTERVAL_SEC = 30.0
_RUNTIME_STATE_WRITE_LIMIT = threading.BoundedSemaphore(2)
+ # Process-level cache for AGENT_EXTRA_TOOLS loads, keyed by module path
+ # (see _load_extra_tools_from_env): session-scoped adapters rebuild per
+ # session, and extra tools register process-shared under their card id,
+ # so the same module must resolve to the same instances on every build.
+ _EXTRA_TOOLS_CACHE: dict[str, list[Any]] = {}
+ _EXTRA_TOOLS_CACHE_LOCK = threading.Lock()
"""Deep SDK 适配器,实现 AgentAdapter 协议.
@@ -6805,6 +6811,66 @@ class JiuWenSwarmDeepAdapter:
)
return extra_rails
+ @staticmethod
+ def _load_extra_tools_from_env() -> list[Any]:
+ """Load extra tools from AGENT_EXTRA_TOOLS env var.
+
+ Env format (semicolon-separated module paths):
+ AGENT_EXTRA_TOOLS=path.to.module1;path.to.module2
+
+ Each module must expose a ``register_tools()`` function that returns
+ a list of Tool instances. Only honored under enterprise edition.
+
+ Results are cached per module for the process lifetime: session-scoped
+ adapters rebuild per session, and extra tools register process-shared
+ under their card id — without the cache, a factory returning fresh
+ instances would register a new id on every build (registry leak,
+ since stateless registrations are never torn down). Failures are not
+ cached, so a transient failure retries on the next build.
+ """
+ if not is_enterprise():
+ return []
+ env_value = os.getenv("AGENT_EXTRA_TOOLS", "").strip()
+ if not env_value:
+ return []
+
+ extra_tools: list[Any] = []
+ for module_path in [p.strip() for p in env_value.split(";") if p.strip()]:
+ try:
+ # The lock spans cache lookup + import + factory call: concurrent
+ # session builds must not race past a not-yet-written cache entry
+ # and invoke register_tools() twice (double-checked locking cannot
+ # close that gap when the factory runs between the checks).
+ with JiuWenSwarmDeepAdapter._EXTRA_TOOLS_CACHE_LOCK:
+ cached = JiuWenSwarmDeepAdapter._EXTRA_TOOLS_CACHE.get(module_path)
+ if cached is None:
+ mod = importlib.import_module(module_path)
+ register_fn = getattr(mod, "register_tools", None)
+ if register_fn is None:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] Extra tool module '%s' has no register_tools(), skipping",
+ module_path,
+ )
+ continue
+ tools = register_fn()
+ if tools and not isinstance(tools, list):
+ tools = [tools]
+ cached = tools or []
+ JiuWenSwarmDeepAdapter._EXTRA_TOOLS_CACHE[module_path] = cached
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] Loaded %d tool(s) from '%s'",
+ len(cached),
+ module_path,
+ )
+ extra_tools.extend(cached)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] Failed to load extra tools from '%s': %s",
+ module_path,
+ exc,
+ )
+ return extra_tools
+
@staticmethod
def _build_multimodal_image_rail(
enable_image_multimodal: bool | None = None,
@@ -7841,6 +7907,52 @@ class JiuWenSwarmDeepAdapter:
]
tool_cards.extend(registered_cards)
+ def _append_extra_tool_cards(self, tool_cards: list[Any]) -> None:
+ """Append extra tools loaded from AGENT_EXTRA_TOOLS to ``tool_cards``.
+
+ Non-invasive tool extension mirroring ``AGENT_EXTRA_RAILS`` (see
+ ``_load_extra_tools_from_env``): enterprise only, semicolon-separated
+ module paths, each exposing ``register_tools()``. Every tool is
+ registered process-shared (``_register_shared_tool``) and its card
+ joins ``tool_cards``, so it flows through the same config pipeline as
+ builtin tools (model visibility, ``disabled_tools`` filtering).
+
+ Isolation: a tool without a card name, a name conflicting with an
+ already-collected card, or a failing registration is logged and
+ skipped — one bad extension tool never blocks the agent build nor
+ the remaining tools (same convention as the vision/audio/extension
+ registration blocks above).
+
+ Args:
+ tool_cards: Cards collected so far by ``_get_tool_cards``; extra
+ cards are appended in place.
+ """
+ existing_names = {card.name for card in tool_cards}
+ for tool in self._load_extra_tools_from_env():
+ tname = getattr(getattr(tool, "card", None), "name", "")
+ if not tname:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] extra tool without card.name, skip"
+ )
+ continue
+ if tname in existing_names:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] extra tool '%s' conflicts with existing tool, skip",
+ tname,
+ )
+ continue
+ try:
+ registered = self._register_shared_tool(tool)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] extra tool '%s' registration failed: %s",
+ tname,
+ exc,
+ )
+ continue
+ tool_cards.append(registered.card)
+ existing_names.add(tname)
+
async def _get_tool_cards(self, agent_id: str):
"""Get tool cards."""
tool_cards = []
@@ -8046,6 +8158,9 @@ class JiuWenSwarmDeepAdapter:
self._register_deepresearch_tool_cards(tool_cards)
+ # 动态加载环境变量配置的非侵入式工具扩展(AGENT_EXTRA_TOOLS,仅企业版)
+ self._append_extra_tool_cards(tool_cards)
+
return tool_cards
def _build_cron_tools(self) -> list[Any]:
diff --git a/tests/unit_tests/agentserver/test_extra_tools_env.py b/tests/unit_tests/agentserver/test_extra_tools_env.py
new file mode 100644
index 0000000000..441d525f10
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_extra_tools_env.py
@@ -0,0 +1,451 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for the AGENT_EXTRA_TOOLS non-invasive tool extension.
+
+Covers: env/edition gating, per-module failure isolation, process-level
+instance caching (register_tools() runs exactly once per module per process),
+tool_cards integration with conflict and registration isolation, and the
+per-session context contract for shared tool instances.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import importlib
+import logging
+import pathlib
+from concurrent.futures import ThreadPoolExecutor
+from typing import Any
+from uuid import uuid4
+
+import pytest
+
+from jiuwenswarm.server.runtime.agent_adapter import interface_deep
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+
+
+class _FakeCard:
+ def __init__(self, name: str) -> None:
+ self.name = name
+ self.id = f"{name}_{uuid4().hex}"
+ self.stateless = False
+
+
+class _FakeTool:
+ def __init__(self, name: str) -> None:
+ self.card = _FakeCard(name)
+
+
+# Customer-side module double: mimics a `@tool` module whose factory builds
+# fresh instances on every call (card id = uuid4), so only the process-level
+# cache can keep repeat builds idempotent.
+_TOOL_MODULE_TEMPLATE = '''
+from uuid import uuid4
+
+
+class _Card:
+ def __init__(self, name):
+ self.name = name
+ self.id = "{prefix}_" + name + "_" + uuid4().hex
+ self.stateless = False
+
+
+class _Tool:
+ def __init__(self, name):
+ self.card = _Card(name)
+
+
+CALLS = 0
+
+
+def register_tools():
+ global CALLS
+ CALLS += 1
+ return [_Tool("psbc_system_tool"), _Tool("get_current_user")]
+'''
+
+_SINGLE_TOOL_MODULE = '''
+from uuid import uuid4
+
+
+class _Card:
+ def __init__(self, name):
+ self.name = name
+ self.id = "single_" + name + "_" + uuid4().hex
+ self.stateless = False
+
+
+class _Tool:
+ def __init__(self, name):
+ self.card = _Card(name)
+
+
+def register_tools():
+ return _Tool("solo_tool")
+'''
+
+_RAISING_MODULE = '''
+CALLS = 0
+
+
+def register_tools():
+ global CALLS
+ CALLS += 1
+ raise RuntimeError("factory exploded")
+'''
+
+_MIXED_MODULE = '''
+from uuid import uuid4
+
+
+class _Card:
+ def __init__(self, name):
+ self.name = name
+ self.id = "mixed_" + (name or "nameless") + "_" + uuid4().hex
+ self.stateless = False
+
+
+class _Tool:
+ def __init__(self, name):
+ self.card = _Card(name)
+
+
+def register_tools():
+ return [
+ _Tool("psbc_system_tool"),
+ _Tool("wiki_query"),
+ _Tool(""),
+ ]
+'''
+
+
+def _write_tool_module(
+ tmp_path: pathlib.Path,
+ monkeypatch: pytest.MonkeyPatch,
+ name: str,
+ body: str,
+) -> str:
+ """Write an importable module into ``tmp_path`` and return its import name."""
+ (tmp_path / f"{name}.py").write_text(body, encoding="utf-8")
+ monkeypatch.syspath_prepend(str(tmp_path))
+ return name
+
+
+def _make_adapter() -> JiuWenSwarmDeepAdapter:
+ """Create a bare adapter, mirroring the other deep-adapter unit tests."""
+ return object.__new__(JiuWenSwarmDeepAdapter)
+
+
+class _LogCapture:
+ """Simple in-memory log capture for assertion checks."""
+
+ def __init__(self) -> None:
+ self.records: list[logging.LogRecord] = []
+
+ def add_record(self, record: logging.LogRecord) -> None:
+ self.records.append(record)
+
+ @property
+ def text(self) -> str:
+ return "\n".join(record.getMessage() for record in self.records)
+
+
+def _make_log_capture() -> tuple[_LogCapture, logging.Handler]:
+ """Create a custom log capture handler since pytest caplog doesn't capture
+ in this project's logging configuration (propagate=False on the root)."""
+ capture = _LogCapture()
+ handler = logging.Handler()
+ handler.emit = capture.add_record
+ return capture, handler
+
+
[email protected](autouse=True)
+def _reset_extra_tools_cache():
+ """The process-level cache must not leak instances between tests."""
+ JiuWenSwarmDeepAdapter._EXTRA_TOOLS_CACHE.clear()
+ yield
+ JiuWenSwarmDeepAdapter._EXTRA_TOOLS_CACHE.clear()
+
+
+class _FakeResourceMgr:
+ """In-memory double of ``Runner.resource_mgr`` (get_tool/add_tool contract)."""
+
+ def __init__(self) -> None:
+ self.tools: dict[str, Any] = {}
+ self.add_calls = 0
+
+ def get_tool(self, tool_id: str) -> Any:
+ return self.tools.get(tool_id)
+
+ def add_tool(self, tool: Any, skip_if_exists: bool = False) -> None:
+ self.add_calls += 1
+ self.tools[tool.card.id] = tool
+ return None
+
+
+def fake_resource_mgr(monkeypatch: pytest.MonkeyPatch) -> _FakeResourceMgr:
+ from openjiuwen.core.runner import Runner
+
+ mgr = _FakeResourceMgr()
+ monkeypatch.setattr(Runner, "resource_mgr", mgr, raising=False)
+ return mgr
+
+
+def enterprise(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(interface_deep, "is_enterprise", lambda: True)
+
+
+# ---------------------------------------------------------------------------
+# loader gating and per-module isolation
+# ---------------------------------------------------------------------------
+
+
+def test_not_enterprise_ignores_env(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: pathlib.Path,
+) -> None:
+ """The env var only takes effect under the enterprise edition."""
+ _write_tool_module(
+ tmp_path, monkeypatch, "xtool_valid", _TOOL_MODULE_TEMPLATE.format(prefix="gating")
+ )
+ monkeypatch.setattr(interface_deep, "is_enterprise", lambda: False)
+ monkeypatch.setenv("AGENT_EXTRA_TOOLS", "xtool_valid")
+
+ assert JiuWenSwarmDeepAdapter._load_extra_tools_from_env() == []
+
+
[email protected]("env_value", [None, "", " "])
+def test_empty_env_returns_empty(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ env_value: str | None,
+) -> None:
+ """Missing, empty, and whitespace-only env values all load nothing."""
+ if env_value is None:
+ monkeypatch.delenv("AGENT_EXTRA_TOOLS", raising=False)
+ else:
+ monkeypatch.setenv("AGENT_EXTRA_TOOLS", env_value)
+
+ assert JiuWenSwarmDeepAdapter._load_extra_tools_from_env() == []
+
+
+def test_module_without_register_tools_is_skipped(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ tmp_path: pathlib.Path,
+) -> None:
+ """A module without a register_tools() factory is skipped; the rest load."""
+ _write_tool_module(tmp_path, monkeypatch, "xtool_no_factory", "PLACEHOLDER = 1\n")
+ _write_tool_module(
+ tmp_path, monkeypatch, "xtool_valid", _TOOL_MODULE_TEMPLATE.format(prefix="nofactory")
+ )
+ monkeypatch.setenv("AGENT_EXTRA_TOOLS", "xtool_no_factory;xtool_valid")
+
+ tools = JiuWenSwarmDeepAdapter._load_extra_tools_from_env()
+
+ assert [tool.card.name for tool in tools] == ["psbc_system_tool", "get_current_user"]
+
+
+def test_single_tool_factory_result_is_wrapped(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ tmp_path: pathlib.Path,
+) -> None:
+ """A factory returning a bare tool (not a list) is auto-wrapped."""
+ monkeypatch.setenv(
+ "AGENT_EXTRA_TOOLS",
+ _write_tool_module(tmp_path, monkeypatch, "xtool_single", _SINGLE_TOOL_MODULE),
+ )
+
+ tools = JiuWenSwarmDeepAdapter._load_extra_tools_from_env()
+
+ assert [tool.card.name for tool in tools] == ["solo_tool"]
+
+
+def test_factory_exception_is_skipped_and_retried(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ tmp_path: pathlib.Path,
+) -> None:
+ """A raising factory is isolated and — unlike success — not cached."""
+ raising = _write_tool_module(tmp_path, monkeypatch, "xtool_raises", _RAISING_MODULE)
+ _write_tool_module(
+ tmp_path, monkeypatch, "xtool_valid", _TOOL_MODULE_TEMPLATE.format(prefix="raises")
+ )
+ monkeypatch.setenv("AGENT_EXTRA_TOOLS", "xtool_raises;xtool_valid")
+
+ first = JiuWenSwarmDeepAdapter._load_extra_tools_from_env()
+ second = JiuWenSwarmDeepAdapter._load_extra_tools_from_env()
+
+ assert [tool.card.name for tool in first] == ["psbc_system_tool", "get_current_user"]
+ assert second == first
+ # Failures stay retryable per build: the factory ran on both loader calls.
+ assert importlib.import_module(raising).CALLS == 2
+
+
+# ---------------------------------------------------------------------------
+# _get_tool_cards integration
+# ---------------------------------------------------------------------------
+
+
+def test_extra_tool_cards_enter_tool_cards_with_conflict_and_nameless_skip(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ tmp_path: pathlib.Path,
+ fake_resource_mgr: _FakeResourceMgr,
+) -> None:
+ """Extra cards join tool_cards; conflicts and nameless tools are skipped."""
+ monkeypatch.setenv(
+ "AGENT_EXTRA_TOOLS",
+ _write_tool_module(tmp_path, monkeypatch, "xtool_mixed", _MIXED_MODULE),
+ )
+ adapter = _make_adapter()
+ tool_cards: list[Any] = [_FakeCard("wiki_query")]
+ capture, handler = _make_log_capture()
+ adapter_logger = logging.getLogger(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep"
+ )
+ adapter_logger.addHandler(handler)
+ try:
+ adapter._append_extra_tool_cards(tool_cards)
+ finally:
+ adapter_logger.removeHandler(handler)
+
+ # The conflicting "wiki_query" and the nameless tool never made it in.
+ assert [card.name for card in tool_cards] == ["wiki_query", "psbc_system_tool"]
+ assert len(fake_resource_mgr.tools) == 1
+ registered = next(iter(fake_resource_mgr.tools.values()))
+ assert registered.card.name == "psbc_system_tool"
+ assert registered.card.stateless is True # process-shared via mark_stateless
+ assert "conflicts with existing tool" in capture.text
+ assert "without card.name" in capture.text
+
+
+# ---------------------------------------------------------------------------
+# registration-stage isolation
+# ---------------------------------------------------------------------------
+
+
+def test_single_registration_failure_does_not_block_others(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ tmp_path: pathlib.Path,
+ fake_resource_mgr: _FakeResourceMgr,
+) -> None:
+ """One tool blowing up in _register_shared_tool must not fail the build."""
+ monkeypatch.setenv(
+ "AGENT_EXTRA_TOOLS",
+ _write_tool_module(
+ tmp_path, monkeypatch, "xtool_pair", _TOOL_MODULE_TEMPLATE.format(prefix="pair")
+ ),
+ )
+ adapter = _make_adapter()
+ original = JiuWenSwarmDeepAdapter._register_shared_tool
+
+ def _flaky_register(tool: Any) -> Any:
+ if tool.card.name == "psbc_system_tool":
+ raise RuntimeError("resource_mgr exploded")
+ return original(tool)
+
+ monkeypatch.setattr(
+ JiuWenSwarmDeepAdapter, "_register_shared_tool", staticmethod(_flaky_register)
+ )
+
+ tool_cards: list[Any] = []
+ adapter._append_extra_tool_cards(tool_cards) # must not raise
+
+ assert [card.name for card in tool_cards] == ["get_current_user"]
+ assert len(fake_resource_mgr.tools) == 1
+
+
+# ---------------------------------------------------------------------------
+# instance stability across repeat / concurrent builds
+# ---------------------------------------------------------------------------
+
+
+def test_repeat_and_concurrent_builds_share_cached_instances(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ tmp_path: pathlib.Path,
+) -> None:
+ """register_tools() runs once per process; every build gets the same batch."""
+ name = _write_tool_module(
+ tmp_path, monkeypatch, "xtool_fresh", _TOOL_MODULE_TEMPLATE.format(prefix="fresh")
+ )
+ monkeypatch.setenv("AGENT_EXTRA_TOOLS", name)
+
+ first = JiuWenSwarmDeepAdapter._load_extra_tools_from_env()
+ second = JiuWenSwarmDeepAdapter._load_extra_tools_from_env()
+
+ # The factory builds fresh instances per call; only the cache makes the
+ # second build identical instead of a new-registration leak.
+ assert second == first
+ assert importlib.import_module(name).CALLS == 1
+
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ batches = list(
+ pool.map(lambda _: JiuWenSwarmDeepAdapter._load_extra_tools_from_env(), range(8))
+ )
+
+ assert all(batch == first for batch in batches)
+ assert importlib.import_module(name).CALLS == 1
+
+
+def test_two_session_adapters_register_the_tool_once(
+ monkeypatch: pytest.MonkeyPatch,
+ enterprise: None,
+ tmp_path: pathlib.Path,
+ fake_resource_mgr: _FakeResourceMgr,
+) -> None:
+ """A second session-scoped adapter must not re-register the shared tools."""
+ monkeypatch.setenv(
+ "AGENT_EXTRA_TOOLS",
+ _write_tool_module(
+ tmp_path, monkeypatch, "xtool_shared", _TOOL_MODULE_TEMPLATE.format(prefix="shared")
+ ),
+ )
+ first = _make_adapter()
+ second = _make_adapter()
+ cards_first: list[Any] = []
+ cards_second: list[Any] = []
+
+ first._append_extra_tool_cards(cards_first)
+ second._append_extra_tool_cards(cards_second)
+
+ # Two tools registered once each; the second adapter's ensure_tool_registered
+ # hit the existing ids instead of adding again.
+ assert fake_resource_mgr.add_calls == 2
+ assert [card.id for card in cards_second] == [card.id for card in cards_first]
+
+
+# ---------------------------------------------------------------------------
+# per-session context contract for shared instances
+# ---------------------------------------------------------------------------
+
+
+_CURRENT_USER: contextvars.ContextVar[str] = contextvars.ContextVar("current_user")
+
+
+async def test_shared_tool_reads_per_session_context_isolation() -> None:
+ """Contract regression: per-session data only via contextvars.
+
+ One shared tool instance serves concurrent sessions; a contextvar keeps
+ each session's value isolated. Module-level mutable state would conflate
+ alice and bob here.
+ """
+
+ async def get_current_user() -> str:
+ return _CURRENT_USER.get()
+
+ async def session(user: str) -> str:
+ _CURRENT_USER.set(user)
+ await asyncio.sleep(0.01) # interleave with the other session
+ return await get_current_user()
+
+ results = await asyncio.gather(session("alice"), session("bob"))
+
+ assert results == ["alice", "bob"]