bridge_runtime.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. """Process-private, session-scoped tool capabilities for Hermes v0.21.0.
  2. Only this canonical module owns bindings. Nothing is written into prompts,
  3. global MCP settings, the Hermes environment or persistent session metadata.
  4. """
  5. from __future__ import annotations
  6. import base64
  7. import hmac
  8. import hashlib
  9. import json
  10. import math
  11. import mimetypes
  12. import os
  13. import re
  14. import sys
  15. import threading
  16. import time
  17. import urllib.error
  18. import urllib.parse
  19. import urllib.request
  20. import uuid
  21. from contextvars import ContextVar
  22. from contextlib import contextmanager
  23. from dataclasses import dataclass, field
  24. from pathlib import Path
  25. from typing import Any
  26. VERSION = 1
  27. PLUGIN_VERSION = "1.3.0"
  28. def _plugin_fingerprint():
  29. root = Path(__file__).parent
  30. digest = hashlib.sha256()
  31. for path in sorted(p for p in root.rglob('*') if p.is_file() and '__pycache__' not in p.parts
  32. and 'tests' not in p.relative_to(root).parts and (p.suffix == '.py' or p.name in ('plugin.yaml', 'manifest.json'))):
  33. digest.update(path.relative_to(root).as_posix().encode() + b'\0' + path.read_bytes() + b'\0')
  34. return digest.hexdigest()
  35. # Freeze at module load: files copied later must not masquerade as loaded code.
  36. PLUGIN_FINGERPRINT = _plugin_fingerprint()
  37. MAX_LEASE_MS = 30 * 60 * 1000
  38. MAX_RESPONSE_BYTES = 64 * 1024 * 1024
  39. registered = False
  40. _lock = threading.RLock()
  41. _bindings: dict[str, "Binding"] = {}
  42. # Remember revoked generations while the live gateway object exists so an old
  43. # HTTP bind arriving after unbind cannot reinstate an obsolete capability.
  44. _generations: dict[str, tuple[dict, set[str]]] = {}
  45. _contexts: dict[Path, Any] = {}
  46. _children: dict[str, tuple["Binding", Any]] = {}
  47. _skill_review_scope: ContextVar[Any] = ContextVar("yaoyao_skill_review", default=None)
  48. _SKILL_REVIEW_TOOLS = frozenset({"skills_list", "skill_view", "skill_manage"})
  49. class BridgeError(Exception):
  50. def __init__(self, message: str, status: int = 403, code: str = "forbidden"):
  51. super().__init__(message)
  52. self.status = status
  53. self.code = code
  54. @dataclass(repr=False)
  55. class Binding:
  56. session_id: str
  57. stored_session_id: str
  58. profile: str
  59. profile_home: Path
  60. generation: str
  61. bridge_url: str
  62. token: str
  63. expires_at: float
  64. owner: tuple[str, str]
  65. session: dict
  66. agent: Any
  67. toolset: str = ""
  68. registrations: list = field(default_factory=list)
  69. native_names: set = field(default_factory=set)
  70. catalog_fingerprint: str = ""
  71. sampling: dict = field(default_factory=dict)
  72. computer_policy: dict | None = None
  73. workspace_memory: bool = False
  74. profile_memory_tools: set = field(default_factory=set)
  75. transfer_namespaces: set = field(default_factory=set)
  76. def _cleanup_file_transfers(namespaces):
  77. import subprocess
  78. for namespace in namespaces:
  79. try:
  80. subprocess.run([sys.executable, str(Path(__file__).with_name('file_transfer.py')), namespace],
  81. input=json.dumps({'op': 'transfer-cleanup'}), text=True, capture_output=True, timeout=5)
  82. except Exception:
  83. pass
  84. def register_context(ctx):
  85. from hermes_constants import get_hermes_home
  86. _contexts[Path(get_hermes_home()).resolve()] = ctx
  87. if callable(getattr(ctx, "register_hook", None)):
  88. ctx.register_hook("subagent_start", inherit_child)
  89. ctx.register_hook("subagent_stop", release_child)
  90. ctx.register_hook("pre_tool_call", refresh_catalog)
  91. ctx.register_hook("pre_tool_call", computer_directive)
  92. def _refresh_agent_tools(agent, binding):
  93. # Dashboard /bind runs outside the session's Profile context. Hermes keys
  94. # plugin registries and tool-definition caches by the active home; without
  95. # this scope a named Profile silently receives the default Profile catalog.
  96. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  97. context = set_hermes_home_override(binding.profile_home)
  98. try:
  99. _refresh_profile_agent_tools(agent, binding)
  100. finally:
  101. reset_hermes_home_override(context)
  102. def _hermes_cron_tool(tool_name):
  103. name = str(tool_name or "")
  104. return name in {"cron", "cronjob"} or name.startswith(("cron_", "cronjob_"))
  105. def _block_hermes_cron():
  106. return {"action": "block", "message": "此 Bot 的定时任务使用 workspace_list_routines、workspace_create_routine、workspace_update_routine 和 workspace_delete_routine。不要使用 Hermes cron。到点后在该 Bot 的单聊中执行。"}
  107. def _refresh_profile_agent_tools(agent, binding):
  108. # Bot sessions keep their own routines. Hermes cron stays available to ordinary profile chat.
  109. agent.disabled_toolsets = list(dict.fromkeys([*(getattr(agent, "disabled_toolsets", None) or []), "cron", "cronjob"]))
  110. if binding.workspace_memory:
  111. _isolate_profile_memory(agent, binding)
  112. _isolate_profile_context(agent, binding)
  113. # Hermes currently injects worker guidance when kanban_show is merely
  114. # available in a Profile. A Bot session is not a dispatched Kanban worker.
  115. # Keep the tools for explicit board requests, but remove the false mandate.
  116. if not os.getenv("HERMES_KANBAN_TASK", "").strip():
  117. agent._kanban_worker_guidance = ""
  118. from model_tools import get_tool_definitions, get_toolset_for_tool
  119. if not hasattr(agent, "_yaoyao_base_toolsets"):
  120. agent._yaoyao_base_toolsets = getattr(agent, "enabled_toolsets", None)
  121. base = agent._yaoyao_base_toolsets
  122. definitions = get_tool_definitions(enabled_toolsets=base,
  123. disabled_toolsets=getattr(agent, "disabled_toolsets", None), quiet_mode=True,
  124. skip_tool_search_assembly=True) or []
  125. # Expand wildcard scopes before adding a private lease. Otherwise an
  126. # `all` Agent's Tool Search could enumerate another Bot's dynamic schemas.
  127. enabled = sorted({toolset for tool in definitions
  128. if (toolset := get_toolset_for_tool(tool.get("function", {}).get("name", "")))
  129. and not toolset.startswith("yaoyao_turn_")})
  130. if binding.toolset and binding.toolset not in enabled:
  131. enabled.append(binding.toolset)
  132. agent.enabled_toolsets = enabled
  133. agent.tools = get_tool_definitions(enabled_toolsets=enabled,
  134. disabled_toolsets=getattr(agent, "disabled_toolsets", None), quiet_mode=True) or []
  135. agent.valid_tool_names = {tool["function"]["name"] for tool in agent.tools}
  136. if hasattr(agent, "_memory_manager"):
  137. from agent.memory_manager import inject_memory_provider_tools
  138. inject_memory_provider_tools(agent)
  139. invalidate = getattr(agent, "_invalidate_system_prompt", None)
  140. if callable(invalidate):
  141. invalidate()
  142. def _retire(binding):
  143. namespaces = tuple(binding.transfer_namespaces)
  144. binding.transfer_namespaces.clear()
  145. if namespaces:
  146. threading.Thread(target=_cleanup_file_transfers, args=(namespaces,), daemon=True).start()
  147. for child_id, (owner, _) in list(_children.items()):
  148. if owner is binding:
  149. _children.pop(child_id, None)
  150. for registration in reversed(binding.registrations):
  151. if registration is not None:
  152. registration.dispose()
  153. binding.registrations.clear()
  154. if binding.toolset:
  155. if hasattr(binding.agent, "_yaoyao_base_toolsets"):
  156. binding.agent.enabled_toolsets = binding.agent._yaoyao_base_toolsets
  157. del binding.agent._yaoyao_base_toolsets
  158. def inherit_child(parent_session_id=None, child_session_id=None, **kwargs):
  159. """Only the core lifecycle can introduce a child; model args cannot."""
  160. try:
  161. binding = _resolve(parent_session_id)
  162. inherited = _children.get(parent_session_id) or next((entry for entry in _children.values() if getattr(entry[1], "session_id", None) == parent_session_id), None)
  163. parent = inherited[1] if inherited else binding.agent
  164. child = next((item for item in getattr(parent, "_active_children", [])
  165. if getattr(item, "session_id", None) == child_session_id), None)
  166. if child is None or not child_session_id:
  167. return
  168. with _lock:
  169. _children[child_session_id] = (binding, child)
  170. _refresh_agent_tools(child, binding)
  171. except BridgeError:
  172. return
  173. def release_child(child_session_id=None, **kwargs):
  174. with _lock:
  175. for key, (_, child) in list(_children.items()):
  176. if key == child_session_id or getattr(child, "session_id", None) == child_session_id:
  177. _children.pop(key, None)
  178. def refresh_catalog(session_id=None, function_name=None, tool_name=None, **kwargs):
  179. if _skill_review_scope.get() is not None:
  180. return
  181. if (function_name or tool_name) not in {"tool_search", "tool_describe", "yaoyao_tools"}:
  182. return
  183. try:
  184. binding = _resolve(session_id)
  185. if binding.toolset:
  186. with _lock:
  187. _mount_native_tools(binding)
  188. except BridgeError:
  189. return
  190. def _mount_native_tools(binding, *, timeout=10):
  191. """Register session-scoped schemas in Hermes' own searchable catalog."""
  192. ctx = _contexts.get(binding.profile_home)
  193. if ctx is None:
  194. raise BridgeError("请安装新版工具桥并重新打开 Hermes 会话", 409, "tools_unavailable")
  195. catalog = _request(binding, "/tools/list", timeout=timeout)
  196. fingerprint = hashlib.sha256(json.dumps(catalog.get("tools", []), sort_keys=True).encode()).hexdigest()
  197. if fingerprint == binding.catalog_fingerprint:
  198. return
  199. for registration in reversed(binding.registrations):
  200. registration.dispose()
  201. binding.registrations.clear()
  202. binding.native_names.clear()
  203. binding.toolset = "yaoyao_turn_" + hashlib.sha256(binding.generation.encode()).hexdigest()[:16]
  204. for tool in catalog.get("tools", []):
  205. tool_id = _string(tool, "id")
  206. label = _string(tool, "name")
  207. name = "yaoyao_" + re.sub(r"[^a-zA-Z0-9_]", "_", label)[:30] + "_" + hashlib.sha256(tool_id.encode()).hexdigest()[:12]
  208. description = f"夭夭 Bot {label}。" + str(tool.get("description") or "")
  209. def handler(args, _tool_id=tool_id, **kwargs):
  210. try:
  211. if _resolve(kwargs.get("session_id", "")) is not binding:
  212. raise BridgeError("此工具属于其他轮次,授权已失效")
  213. return call_tool({"toolId": _tool_id, "arguments": args}, **kwargs)
  214. except BridgeError as exc:
  215. return json.dumps({"error": str(exc), "code": exc.code}, ensure_ascii=False)
  216. handle = ctx.register_tool(name=name, toolset=binding.toolset, description=description,
  217. schema={"name": name, "description": description, "parameters": tool.get("inputSchema") or {"type": "object", "properties": {}}}, handler=handler)
  218. if handle is None:
  219. raise BridgeError("Hermes 无法注册本轮工具", 503, "unsupported_runtime")
  220. binding.registrations.append(handle)
  221. binding.native_names.add(name)
  222. _refresh_agent_tools(binding.agent, binding)
  223. for owner, child in list(_children.values()):
  224. if owner is binding:
  225. _refresh_agent_tools(child, binding)
  226. binding.catalog_fingerprint = fingerprint
  227. async def sampling_request(owner, body):
  228. """Reuse Hermes' bounded native MCP sampling, scoped to this turn/profile."""
  229. binding = _resolve(_string(body, "session_id"))
  230. if binding.owner != owner or binding.generation != _string(body, "generation"):
  231. raise BridgeError("采样请求不属于当前轮次")
  232. name = _string(body, "server", 128)
  233. params = body.get("params")
  234. if not isinstance(params, dict):
  235. raise BridgeError("采样请求格式无效", 400)
  236. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  237. from tools.mcp_tool import SamplingHandler, _ensure_mcp_sdk
  238. _ensure_mcp_sdk()
  239. from mcp.types import CreateMessageRequestParams
  240. parsed = CreateMessageRequestParams.model_validate(params)
  241. context = set_hermes_home_override(binding.profile_home)
  242. try:
  243. handler = binding.sampling.setdefault(name, SamplingHandler(name, {"max_rpm": 10, "timeout": 30, "max_tokens_cap": 4096}))
  244. result = await handler(None, parsed)
  245. if _resolve(binding.session_id) is not binding:
  246. raise BridgeError("采样结果所属轮次已经结束")
  247. return result.model_dump(by_alias=True, exclude_none=True)
  248. finally:
  249. reset_hermes_home_override(context)
  250. def _web():
  251. # This module must execute inside the real Dashboard. Never create a new
  252. # Dashboard with a new auth token when a plugin is imported in another host.
  253. web = sys.modules.get("hermes_cli.web_server")
  254. if web is None or not callable(getattr(web, "_has_valid_session_token", None)):
  255. raise BridgeError("当前进程不是受支持的 Hermes Dashboard", 503, "unsupported_runtime")
  256. return web
  257. def _server():
  258. try:
  259. from tui_gateway import server
  260. except ImportError:
  261. raise BridgeError("Hermes 会话接口不可用", 503, "unsupported_runtime") from None
  262. if not isinstance(getattr(server, "_sessions", None), dict) or not hasattr(server, "_sessions_lock"):
  263. raise BridgeError("Hermes 会话接口不兼容,请修复工具桥或更新 Hermes", 503, "unsupported_runtime")
  264. if not callable(getattr(server, "_turn_isolation_enabled", None)):
  265. raise BridgeError("无法确认 Hermes 的运行模式", 503, "unsupported_runtime")
  266. try:
  267. isolated = server._turn_isolation_enabled()
  268. except Exception:
  269. raise BridgeError("无法确认 Hermes 的运行模式", 503, "unsupported_runtime") from None
  270. if isolated:
  271. raise BridgeError("工具桥仅支持 Hermes 非隔离运行模式", 503, "unsupported_mode")
  272. return server
  273. def request_identity(request) -> tuple[str, str]:
  274. """Use only the core HTTP gate's verified principal, never request JSON."""
  275. web = _web()
  276. if bool(getattr(web.app.state, "auth_required", False)):
  277. session = getattr(request.state, "session", None)
  278. user = getattr(session, "user_id", None)
  279. provider = getattr(session, "provider", None)
  280. if not isinstance(user, str) or not user or not isinstance(provider, str) or not provider:
  281. raise BridgeError("请先登录 Hermes Dashboard", 401, "unauthorized")
  282. if provider == "server-internal" or getattr(session, "expires_at", 0) <= time.time():
  283. raise BridgeError("Hermes 登录已过期", 401, "unauthorized")
  284. return provider, user
  285. if not web._has_valid_session_token(request):
  286. raise BridgeError("Hermes 本机令牌无效", 401, "unauthorized")
  287. return "local-session-token", "dashboard"
  288. def _transport_identity(transport) -> tuple[str, str]:
  289. from tui_gateway.ws import WSTransport
  290. if not isinstance(transport, WSTransport):
  291. raise BridgeError("仅支持已认证的 Dashboard WebSocket 会话")
  292. identity = getattr(transport, "auth_identity", None)
  293. web = _web()
  294. if bool(getattr(web.app.state, "auth_required", False)):
  295. if not isinstance(identity, dict):
  296. raise BridgeError("WebSocket 会话缺少可信身份")
  297. user, provider = identity.get("user_id"), identity.get("provider")
  298. if not isinstance(user, str) or not user or not isinstance(provider, str) or not provider or provider == "server-internal":
  299. raise BridgeError("WebSocket 会话身份不受支持")
  300. return provider, user
  301. # Identity None alone is not authority: stdio and unauthenticated fakes also
  302. # have no identity. Require the canonical token on the admitted WS object.
  303. ws = getattr(transport, "_ws", None)
  304. token = getattr(ws, "query_params", {}).get("token", "")
  305. expected = getattr(web, "_SESSION_TOKEN", "")
  306. if identity is not None or not isinstance(token, str) or not expected or not hmac.compare_digest(token, expected):
  307. raise BridgeError("WebSocket 会话与本机登录不匹配")
  308. return "local-session-token", "dashboard"
  309. def capabilities(profile: str = "default") -> dict:
  310. in_process = False
  311. try:
  312. _web()
  313. if not isinstance(profile, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", profile):
  314. raise BridgeError("Profile 名称无效", 400, "invalid_profile")
  315. from hermes_cli.profiles import get_profile_dir, profile_exists
  316. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  317. if not profile_exists(profile):
  318. raise BridgeError("Hermes Profile 不存在", 404, "profile_missing")
  319. home = get_profile_dir(profile)
  320. # Dashboard APIs mount independently of the lazy tool-plugin loader.
  321. from hermes_cli.plugins import discover_plugins
  322. from hermes_cli.config import load_config
  323. from model_tools import get_tool_definitions
  324. context = set_hermes_home_override(home)
  325. try:
  326. server = _server()
  327. in_process = True
  328. discover_plugins()
  329. config = load_config()
  330. agent_config = config.get("agent") or {}
  331. definitions = get_tool_definitions(
  332. enabled_toolsets=server._load_enabled_toolsets(),
  333. disabled_toolsets=agent_config.get("disabled_toolsets") if isinstance(agent_config, dict) else None,
  334. quiet_mode=True, skip_tool_search_assembly=True,
  335. ) or []
  336. names = {t.get("function", {}).get("name") for t in definitions if isinstance(t, dict)}
  337. if not {"yaoyao_tools", "yaoyao_call"} <= names:
  338. raise BridgeError(f"Profile {profile} 尚未安装或启用夭夭工具桥,请检查该 Profile 的插件与工具集设置", 503, "profile_tools_unavailable")
  339. return {"version": VERSION, "ready": True, "in_process": True, "profile": profile, "native_tools": True,
  340. "computer_runtime_version": 2, "plugin_version": PLUGIN_VERSION, "plugin_fingerprint": PLUGIN_FINGERPRINT,
  341. "memory_isolation": True, "memory_isolation_transport": "bridge-bind-v1", "memory_extraction": True,
  342. "isolated_context_files": True, "skill_learning": True, "model_settings_version": 1, "file_transfer_version": 1}
  343. finally:
  344. reset_hermes_home_override(context)
  345. except Exception as exc:
  346. reason = str(exc) if isinstance(exc, BridgeError) else "无法确认 Hermes 插件接口兼容性"
  347. return {"version": VERSION, "ready": False, "in_process": in_process, "profile": profile, "reason": reason,
  348. "plugin_version": PLUGIN_VERSION, "plugin_fingerprint": PLUGIN_FINGERPRINT}
  349. def _string(body: dict, key: str, maximum: int = 512) -> str:
  350. value = body.get(key)
  351. if not isinstance(value, str) or not value or len(value) > maximum or any(ord(c) < 32 for c in value):
  352. raise BridgeError(f"参数 {key} 无效", 400, "invalid_request")
  353. return value
  354. def _bridge_url(value: str) -> str:
  355. try:
  356. parsed = urllib.parse.urlsplit(value)
  357. port = parsed.port
  358. if (
  359. parsed.scheme != "http" or parsed.hostname != "127.0.0.1"
  360. or not port or not 1 <= port <= 65535
  361. or parsed.username is not None or parsed.password is not None
  362. or parsed.path or parsed.query or parsed.fragment
  363. or value != f"http://127.0.0.1:{port}"
  364. ):
  365. raise ValueError()
  366. except ValueError:
  367. raise BridgeError("工具桥地址必须是本机 127.0.0.1 的 HTTP 端口", 400, "invalid_request") from None
  368. return value
  369. def _profile_home(session: dict, profile: str) -> Path:
  370. from hermes_cli.profiles import get_profile_dir, profile_matches_home
  371. from hermes_constants import get_process_hermes_home
  372. actual = Path(session.get("profile_home") or get_process_hermes_home()).resolve()
  373. if not profile_matches_home(profile, actual):
  374. raise BridgeError("Profile 与 Hermes 会话不匹配")
  375. return Path(get_profile_dir(profile)).resolve()
  376. def _check_session_mode(session: dict) -> None:
  377. # A session created before the process-wide setting changed can still own
  378. # a compute host. Its worker cannot share this process-private table.
  379. if session.get("_compute_host_active"):
  380. raise BridgeError("此 Hermes 会话仍使用隔离计算进程,请在非隔离模式下新建会话", 503, "unsupported_mode")
  381. def _expiry(body: dict) -> float:
  382. value = body.get("expires_at")
  383. now = time.time() * 1000
  384. if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not now < value <= now + MAX_LEASE_MS + 5000:
  385. raise BridgeError("工具桥授权有效期无效", 400, "invalid_request")
  386. return value
  387. def _agent_has_tools(agent, home: Path) -> bool:
  388. required = {"yaoyao_tools", "yaoyao_call"}
  389. names = {
  390. t.get("function", {}).get("name")
  391. for t in (getattr(agent, "tools", None) or []) if isinstance(t, dict)
  392. }
  393. if required <= names:
  394. return True
  395. if not {"tool_call", "tool_describe"} <= names or not hasattr(agent, "enabled_toolsets") or not hasattr(agent, "disabled_toolsets"):
  396. return False
  397. # Current Hermes defers plugin schemas behind Tool Search. Check the same
  398. # scoped pre-assembly catalog its dispatcher uses, not process-global names
  399. # or text in the model-visible tool_search description.
  400. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  401. from model_tools import get_tool_definitions
  402. context = set_hermes_home_override(home)
  403. try:
  404. definitions = get_tool_definitions(
  405. enabled_toolsets=agent.enabled_toolsets,
  406. disabled_toolsets=agent.disabled_toolsets,
  407. quiet_mode=True, skip_tool_search_assembly=True,
  408. ) or []
  409. return required <= {t.get("function", {}).get("name") for t in definitions if isinstance(t, dict)}
  410. finally:
  411. reset_hermes_home_override(context)
  412. def _purge(server) -> None:
  413. now = time.time() * 1000
  414. for sid, binding in list(_bindings.items()):
  415. if binding.expires_at <= now or server._sessions.get(sid) is not binding.session:
  416. _bindings.pop(sid, None)
  417. _retire(binding)
  418. for sid, (session, _) in list(_generations.items()):
  419. if server._sessions.get(sid) is not session:
  420. _generations.pop(sid, None)
  421. for sid, (binding, _) in list(_children.items()):
  422. if _bindings.get(binding.session_id) is not binding:
  423. _children.pop(sid, None)
  424. @contextmanager
  425. def _bind_locks(server, deadline):
  426. # Lock contention is part of the binding deadline, not an unbounded wait
  427. # outside it. In particular a stalled earlier bind must not trap retries.
  428. acquired = []
  429. try:
  430. for lock in (server._sessions_lock, _lock):
  431. if not lock.acquire(timeout=max(0, deadline - time.monotonic())):
  432. raise BridgeError("Hermes 工具桥正在处理其他绑定,请稍后重试", 409, "binding_busy")
  433. acquired.append(lock)
  434. yield
  435. finally:
  436. for lock in reversed(acquired):
  437. lock.release()
  438. def bind(owner: tuple[str, str], body: dict, *, wait_seconds: float = 20) -> dict:
  439. workspace_memory = body.get("workspace_memory", False)
  440. if type(workspace_memory) is not bool:
  441. raise BridgeError("记忆隔离设置格式无效", 400, "invalid_memory_policy")
  442. policy = body.get("computer_policy")
  443. if policy is not None and (not isinstance(policy, dict) or set(policy) != {"mode", "hostAccess"}
  444. or policy.get("mode") not in {"isolated", "profile"}
  445. or type(policy.get("hostAccess")) is not bool):
  446. raise BridgeError("电脑会话权限格式无效", 400, "invalid_computer_policy")
  447. server = _server()
  448. sid = _string(body, "session_id")
  449. stored = _string(body, "stored_session_id")
  450. profile = _string(body, "profile", 128)
  451. generation = _string(body, "generation", 128)
  452. url = _bridge_url(_string(body, "bridge_url", 128))
  453. token = _string(body, "token", 512)
  454. if len(token) < 32:
  455. raise BridgeError("工具桥令牌长度不足", 400, "invalid_request")
  456. expiry = _expiry(body)
  457. deadline = time.monotonic() + wait_seconds
  458. build_requested = False
  459. while True:
  460. with _bind_locks(server, deadline):
  461. session = server._sessions.get(sid)
  462. if not isinstance(session, dict):
  463. raise BridgeError("Hermes 会话不存在", 404, "session_missing")
  464. _check_session_mode(session)
  465. if _transport_identity(session.get("transport")) != owner:
  466. raise BridgeError("当前登录不能绑定此会话")
  467. home = _profile_home(session, profile)
  468. if session.get("_finalized"):
  469. raise BridgeError("Hermes 会话已经结束", 409, "session_closed")
  470. agent = session.get("agent")
  471. if session.get("agent_error"):
  472. # Provider errors can contain credentials. Keep this response
  473. # bounded and let Hermes retain its detailed initialization log.
  474. raise BridgeError("Hermes Profile 初始化失败,工具桥尚未绑定", 409, "agent_initialization_failed")
  475. current = _bindings.get(sid)
  476. busy = bool(session.get("running")) and not (current and current.generation == generation)
  477. if agent is not None and not busy:
  478. break
  479. start_build = getattr(server, "_start_agent_build", None)
  480. needs_build = agent is None and not busy and not build_requested and callable(start_build)
  481. if needs_build:
  482. # Native, idempotent startup also covers resumed lazy sessions.
  483. # Never submit a prompt merely to trigger initialization: it would
  484. # run the first turn before memory/tools have been bound.
  485. build_requested = True
  486. start_build(sid, session)
  487. if time.monotonic() >= deadline:
  488. if busy:
  489. raise BridgeError("Hermes 会话正在运行,不能更换轮次授权", 409, "session_busy")
  490. raise BridgeError("Hermes 会话仍在初始化,请重试", 409, "initializing")
  491. time.sleep(0.1)
  492. with _bind_locks(server, deadline):
  493. _purge(server)
  494. expiry = _expiry(body)
  495. if server._sessions.get(sid) is not session or session.get("agent") is not agent:
  496. raise BridgeError("Hermes 会话已改变,请重试", 409, "session_changed")
  497. _check_session_mode(session)
  498. if _transport_identity(session.get("transport")) != owner or _profile_home(session, profile) != home:
  499. raise BridgeError("Hermes 会话身份或 Profile 已改变")
  500. current_keys = {str(session.get("session_key") or ""), str(getattr(agent, "session_id", "") or "")}
  501. if stored not in current_keys:
  502. raise BridgeError("持久会话 ID 与当前会话不匹配", 409, "session_changed")
  503. if not _agent_has_tools(agent, home):
  504. raise BridgeError("此会话尚未加载工具桥,请启用 yaoyao_bot_bridge 工具集并新建会话", 409, "tools_unavailable")
  505. current = _bindings.get(sid)
  506. if current and current.generation == generation:
  507. if current.session is not session or current.agent is not agent or current.owner != owner or current.profile != profile or current.bridge_url != url or current.computer_policy != policy or current.workspace_memory != workspace_memory or not hmac.compare_digest(current.token, token):
  508. raise BridgeError("不能更改现有轮次的工具授权", 409, "generation_conflict")
  509. current.expires_at = max(current.expires_at, expiry)
  510. current.stored_session_id = stored
  511. return {"ok": True, "generation": generation, "expires_at": current.expires_at,
  512. "native_tools": bool(current.toolset), "computer_runtime_version": 2, "workspace_memory": current.workspace_memory}
  513. previous = _generations.get(sid)
  514. seen = previous[1] if previous and previous[0] is session else set()
  515. if generation in seen:
  516. raise BridgeError("该轮次授权已撤销", 409, "generation_revoked")
  517. if session.get("running"):
  518. raise BridgeError("Hermes 会话正在运行,不能更换轮次授权", 409, "session_busy")
  519. if session.get("_yaoyao_workspace_memory") and not workspace_memory:
  520. raise BridgeError("此 Bot 会话必须继续使用独立记忆,请新建会话后更改模式", 409, "memory_policy_conflict")
  521. if len(seen) >= 4096:
  522. raise BridgeError("请恢复会话以更新工具桥授权记录", 409, "session_renewal_required")
  523. seen.add(generation)
  524. _generations[sid] = (session, seen)
  525. if current:
  526. _retire(current)
  527. binding = Binding(sid, stored, profile, home, generation, url, token, expiry, owner, session, agent)
  528. binding.computer_policy = dict(policy) if policy else None
  529. binding.workspace_memory = workspace_memory
  530. if workspace_memory:
  531. _isolate_profile_memory(agent, binding)
  532. session["_yaoyao_workspace_memory"] = True
  533. _isolate_profile_context(agent, binding)
  534. if policy:
  535. # Private runtime state survives unbind so a stale tool call cannot
  536. # fall back to the unrestricted native Profile after revocation.
  537. session["_yaoyao_computer_policy"] = dict(policy)
  538. _bindings[sid] = binding
  539. if body.get("native_tools") is True:
  540. try:
  541. _mount_native_tools(binding, timeout=max(0.1, min(10, deadline - time.monotonic())))
  542. except Exception:
  543. _bindings.pop(sid, None)
  544. _retire(binding)
  545. raise
  546. return {"ok": True, "generation": generation, "expires_at": expiry, "native_tools": bool(binding.toolset),
  547. "computer_runtime_version": 2, "workspace_memory": binding.workspace_memory}
  548. def unbind(owner: tuple[str, str], body: dict) -> dict:
  549. server = _server()
  550. sid, generation = _string(body, "session_id"), _string(body, "generation", 128)
  551. with server._sessions_lock, _lock:
  552. _purge(server)
  553. binding = _bindings.get(sid)
  554. if binding is None:
  555. return {"ok": True, "removed": False}
  556. if binding.owner != owner:
  557. raise BridgeError("当前登录不能撤销此会话的授权")
  558. if binding.generation != generation:
  559. return {"ok": True, "removed": False}
  560. _bindings.pop(sid, None)
  561. _retire(binding)
  562. return {"ok": True, "removed": True}
  563. def _resolve(session_id: str) -> Binding:
  564. # session_id is supplied by Hermes' tool dispatcher kwargs, never args.
  565. if not isinstance(session_id, str) or not session_id:
  566. raise BridgeError("工具调用缺少可信 Hermes 会话身份")
  567. server = _server()
  568. with server._sessions_lock, _lock:
  569. _purge(server)
  570. inherited = _children.get(session_id)
  571. if inherited is None:
  572. inherited = next((value for value in _children.values() if getattr(value[1], "session_id", None) == session_id), None)
  573. if inherited:
  574. binding, child = inherited
  575. if _bindings.get(binding.session_id) is not binding or getattr(child, "session_id", None) != session_id:
  576. raise BridgeError("子代理工具授权已失效")
  577. session_id = binding.session_id
  578. matches = [
  579. (sid, session) for sid, session in server._sessions.items()
  580. if session_id in {
  581. sid, str(session.get("session_key") or ""),
  582. str(getattr(session.get("agent"), "session_id", "") or ""),
  583. }
  584. ]
  585. if len(matches) != 1:
  586. raise BridgeError("无法确定工具调用所属的唯一会话")
  587. sid, session = matches[0]
  588. _check_session_mode(session)
  589. binding = _bindings.get(sid)
  590. if binding is None:
  591. raise BridgeError("本轮没有可用的夭夭工具授权,或授权已经结束")
  592. if binding.session is not session or session.get("agent") is not binding.agent:
  593. raise BridgeError("Hermes 会话已更换,旧工具授权失效")
  594. if _transport_identity(session.get("transport")) != binding.owner or _profile_home(session, binding.profile) != binding.profile_home:
  595. raise BridgeError("工具调用的身份或 Profile 已改变")
  596. if not session.get("running") or session.get("_finalized"):
  597. raise BridgeError("本轮已经停止,工具授权不可使用")
  598. return binding
  599. class _NoRedirect(urllib.request.HTTPRedirectHandler):
  600. def redirect_request(self, req, fp, code, msg, headers, newurl):
  601. raise BridgeError("工具桥拒绝重定向", 502, "bridge_redirect")
  602. def _request(binding: Binding, path: str, body: dict | None = None, *, timeout=600) -> dict:
  603. remaining = (binding.expires_at - time.time() * 1000) / 1000
  604. if remaining <= 0:
  605. raise BridgeError("本轮工具授权已过期")
  606. request = urllib.request.Request(
  607. binding.bridge_url + path,
  608. data=json.dumps({} if body is None else body, ensure_ascii=False).encode(),
  609. headers={"Authorization": "Bearer " + binding.token, "Content-Type": "application/json"},
  610. method="POST",
  611. )
  612. # Loopback never uses machine proxy settings; redirects must not leak token.
  613. opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
  614. try:
  615. with opener.open(request, timeout=min(remaining, timeout)) as response:
  616. raw = response.read(MAX_RESPONSE_BYTES + 1)
  617. if len(raw) > MAX_RESPONSE_BYTES:
  618. raise BridgeError("工具结果过大,请改用文件附件", 502, "result_too_large")
  619. result = json.loads(raw)
  620. if not isinstance(result, dict):
  621. raise ValueError()
  622. return result
  623. except urllib.error.HTTPError as exc:
  624. # Do not reflect upstream response/request objects: they can carry keys.
  625. raise BridgeError(f"工具桥拒绝请求(HTTP {exc.code})", 502, "bridge_rejected") from None
  626. except (urllib.error.URLError, TimeoutError, OSError):
  627. if path == "/tools/list":
  628. raise BridgeError("Hermes 未能读取夭夭的本轮工具目录,尚未提交聊天消息", 502, "bridge_catalog_unreachable") from None
  629. raise BridgeError("工具桥连接中断;操作可能已执行,请先检查结果,不要自动重试", 502, "bridge_unreachable") from None
  630. except (ValueError, UnicodeError):
  631. raise BridgeError("工具桥返回了无效结果", 502, "invalid_result") from None
  632. def _attachment(binding: Binding, data: bytes, mime: str) -> str:
  633. # Immutable UUID filenames, private directory and private files. Persist
  634. # outside conversations so file references survive Dashboard restarts.
  635. parent = binding.profile_home / "attachments"
  636. directory = parent / "yaoyao-bot-bridge"
  637. if parent.is_symlink() or directory.is_symlink():
  638. raise BridgeError("工具附件目录不能是符号链接", 502, "invalid_attachment_directory")
  639. parent.mkdir(mode=0o700, parents=True, exist_ok=True)
  640. extension = mimetypes.guess_extension(mime) or ".bin"
  641. if not re.fullmatch(r"\.[a-zA-Z0-9]{1,10}", extension):
  642. extension = ".bin"
  643. path = directory / (str(uuid.uuid4()) + extension)
  644. directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
  645. parent_fd = os.open(parent, directory_flags)
  646. try:
  647. try:
  648. os.mkdir("yaoyao-bot-bridge", mode=0o700, dir_fd=parent_fd)
  649. except FileExistsError:
  650. pass
  651. directory_fd = os.open("yaoyao-bot-bridge", directory_flags, dir_fd=parent_fd)
  652. try:
  653. os.fchmod(directory_fd, 0o700)
  654. fd = os.open(path.name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=directory_fd)
  655. with os.fdopen(fd, "wb") as stream:
  656. stream.write(data)
  657. finally:
  658. os.close(directory_fd)
  659. finally:
  660. os.close(parent_fd)
  661. return str(path)
  662. def _decode(value: Any) -> bytes:
  663. if not isinstance(value, str):
  664. raise BridgeError("工具附件缺少有效内容", 502, "invalid_result")
  665. try:
  666. return base64.b64decode(value, validate=True)
  667. except (ValueError, TypeError):
  668. raise BridgeError("工具附件编码无效", 502, "invalid_result") from None
  669. def normalize_result(result: dict, binding: Binding) -> str | dict:
  670. """Preserve MCP blocks; adapt pictures to Hermes' native vision envelope."""
  671. parts: list[dict] = []
  672. texts: list[str] = []
  673. has_image = False
  674. def text(value: str):
  675. texts.append(value)
  676. parts.append({"type": "text", "text": value})
  677. if result.get("isError"):
  678. text("工具执行失败:")
  679. blocks = result.get("content", [])
  680. if not isinstance(blocks, list):
  681. raise BridgeError("工具结果 content 无效", 502, "invalid_result")
  682. for block in blocks:
  683. if not isinstance(block, dict):
  684. text(json.dumps(block, ensure_ascii=False))
  685. continue
  686. kind = block.get("type")
  687. if kind == "text":
  688. text(str(block.get("text", "")))
  689. elif kind in {"image", "audio"}:
  690. mime = str(block.get("mimeType") or "application/octet-stream")
  691. data = _decode(block.get("data"))
  692. if kind == "image" and mime in {"image/png", "image/jpeg", "image/gif", "image/webp"}:
  693. has_image = True
  694. parts.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{base64.b64encode(data).decode()}"}})
  695. texts.append(f"[图像 {mime},{len(data)} 字节]")
  696. else:
  697. path = _attachment(binding, data, mime)
  698. text(f"附件({mime}):{path}")
  699. elif kind == "resource" and isinstance(block.get("resource"), dict):
  700. resource = block["resource"]
  701. mime = str(resource.get("mimeType") or "application/octet-stream")
  702. if "blob" in resource:
  703. path = _attachment(binding, _decode(resource["blob"]), mime)
  704. text(f"附件({mime},来源 {resource.get('uri', '')}):{path}")
  705. elif "text" in resource:
  706. text(f"资源 {resource.get('uri', '')}\n{resource['text']}")
  707. else:
  708. text(json.dumps(block, ensure_ascii=False))
  709. elif kind == "resource_link":
  710. text(json.dumps(block, ensure_ascii=False))
  711. else:
  712. # Unknown future MCP content stays available as a JSON attachment,
  713. # rather than silently dropping bytes or sending invalid AI parts.
  714. path = _attachment(binding, json.dumps(block, ensure_ascii=False).encode(), "application/json")
  715. text(f"扩展工具结果:{path}")
  716. if "structuredContent" in result:
  717. text(json.dumps(result["structuredContent"], ensure_ascii=False))
  718. if not blocks and "structuredContent" not in result:
  719. text(json.dumps(result, ensure_ascii=False))
  720. summary = "\n".join(texts)
  721. return {"_multimodal": True, "content": parts, "text_summary": summary} if has_image else summary
  722. def list_tools(args: dict, **kwargs) -> str:
  723. try:
  724. if not isinstance(args, dict) or set(args) - {"service", "query", "offset", "limit"}:
  725. raise BridgeError("查询工具仅接受 service、query、offset 和 limit", 400, "invalid_request")
  726. for key in ("service", "query"):
  727. if key in args and (not isinstance(args[key], str) or len(args[key]) > 200):
  728. raise BridgeError("工具筛选必须是最多 200 字符的文本", 400, "invalid_request")
  729. for key, maximum in (("offset", 10000), ("limit", 50)):
  730. if key in args and (type(args[key]) is not int or not (0 if key == "offset" else 1) <= args[key] <= maximum):
  731. raise BridgeError("工具目录分页参数无效", 400, "invalid_request")
  732. binding = _resolve(kwargs.get("session_id", ""))
  733. result = _request(binding, "/tools/list")
  734. if _resolve(kwargs.get("session_id", "")) is not binding:
  735. raise BridgeError("本轮工具授权已经更换")
  736. if args:
  737. service = args.get("service", "").strip().casefold()
  738. terms = args.get("query", "").casefold().split()
  739. # Plugin descriptions start with the server-owned service label.
  740. # Keep the actual lease IDs and schemas; filtering grants no tools.
  741. tools = [tool for tool in result.get("tools", [])
  742. if (not service or service in str(tool.get("description", "")).partition(" · ")[0].casefold())
  743. and all(term in (str(tool.get("name", "")) + " " + str(tool.get("description", ""))).casefold() for term in terms)]
  744. offset, limit = args.get("offset", 0), args.get("limit", 20)
  745. result = {**result, "tools": tools[offset:offset + limit], "total": len(tools),
  746. "nextOffset": offset + limit if offset + limit < len(tools) else None}
  747. return json.dumps(result, ensure_ascii=False)
  748. except BridgeError as exc:
  749. return json.dumps({"error": str(exc), "code": exc.code}, ensure_ascii=False)
  750. def call_tool(args: dict, **kwargs) -> str | dict:
  751. try:
  752. if not isinstance(args, dict) or set(args) != {"toolId", "arguments"} or not isinstance(args.get("arguments"), dict):
  753. raise BridgeError("调用必须只包含 toolId 和 arguments", 400, "invalid_request")
  754. tool_id = _string(args, "toolId")
  755. binding = _resolve(kwargs.get("session_id", ""))
  756. # The model cannot pick identity, credentials or a replay identifier.
  757. # One UUID per invocation. No automatic retry of side-effecting tools.
  758. invocation = kwargs.get("tool_call_id")
  759. call_id = hashlib.sha256((str(kwargs.get("session_id")) + ":" + invocation).encode()).hexdigest() if isinstance(invocation, str) and invocation else str(uuid.uuid4())
  760. result = _request(binding, "/tools/call", {"toolId": tool_id, "arguments": args["arguments"], "callId": call_id})
  761. # A cancelled or replaced grant may finish in the background. Do not
  762. # release its result to a different turn after an HTTP round trip.
  763. if _resolve(kwargs.get("session_id", "")) is not binding:
  764. raise BridgeError("本轮工具授权已经更换")
  765. return normalize_result(result, binding)
  766. except BridgeError as exc:
  767. return json.dumps({"error": str(exc), "code": exc.code}, ensure_ascii=False)
  768. # Native Hermes remains the only owner of Profile configuration, skills and
  769. # authenticated integrations. The Runner never opens those files itself.
  770. def _isolate_profile_context(agent, binding):
  771. """Disable automatic host instruction files only for isolated Bot sessions.
  772. Apply on every bind/rebuild, including inherited children, before the model
  773. runs. Skills have their own loader; history and Profile config stay intact.
  774. """
  775. if (binding.computer_policy or {}).get("mode") != "isolated":
  776. return
  777. invalidate = getattr(agent, "_invalidate_system_prompt", None)
  778. if not all(hasattr(agent, name) for name in ("skip_context_files", "load_soul_identity")) or not callable(invalidate):
  779. raise BridgeError("当前 Hermes 不支持工具桥的会话上下文隔离", 409, "context_isolation_unavailable")
  780. agent.skip_context_files = True
  781. # This override loads SOUL even when skip_context_files is true.
  782. agent.load_soul_identity = False
  783. invalidate()
  784. def _isolate_profile_memory(agent, binding):
  785. """Apply the existing agent controls before any prompt, without editing Profile config.
  786. session.create is Hermes' strict public contract; memory isolation belongs
  787. to this authenticated session binding instead of invented RPC parameters.
  788. """
  789. required = ("_memory_store", "_memory_manager", "_memory_enabled", "_user_profile_enabled", "skip_background_review")
  790. if not all(hasattr(agent, name) for name in required) or not callable(getattr(agent, "_invalidate_system_prompt", None)):
  791. raise BridgeError("当前 Hermes 不支持工具桥的会话记忆隔离", 409, "memory_isolation_unavailable")
  792. manager = agent._memory_manager
  793. binding.profile_memory_tools.add("memory")
  794. if manager:
  795. binding.profile_memory_tools.update(manager.get_all_tool_names())
  796. agent._memory_store = None
  797. agent._memory_manager = None
  798. agent._memory_enabled = False
  799. agent._user_profile_enabled = False
  800. agent.skip_background_review = True
  801. agent.disabled_toolsets = list(dict.fromkeys([*(agent.disabled_toolsets or []), "memory"]))
  802. if manager:
  803. manager.shutdown_all()
  804. agent._invalidate_system_prompt()
  805. if agent is binding.agent:
  806. _enable_skill_review(agent, binding)
  807. @dataclass
  808. class _SkillReviewScope:
  809. parent: Any
  810. binding: Binding
  811. deadline: float
  812. agent: Any = None
  813. run: Any = None
  814. class _SkillReviewParent:
  815. """Keep Hermes' review lifecycle on the real parent; constrain its detached fork.
  816. Hermes registers the fork before its first model request. Intercept that
  817. per-instance assignment, without patching Hermes classes or global config.
  818. """
  819. def __init__(self, scope):
  820. object.__setattr__(self, "_scope", scope)
  821. def __getattr__(self, name):
  822. return getattr(self._scope.parent, name)
  823. def __setattr__(self, name, value):
  824. scope = self._scope
  825. if name == "_background_review_run" and value is not None:
  826. scope.run = value
  827. if name == "_background_review_agent" and value is not None:
  828. # Routed review models rebuild their prompt; same-model reviews may
  829. # rebuild after compaction. Both must retain the parent's isolation.
  830. value.skip_context_files = scope.parent.skip_context_files
  831. value.load_soul_identity = scope.parent.load_soul_identity
  832. value.skip_background_review = True
  833. value._memory_store = value._memory_manager = None
  834. value._memory_enabled = value._user_profile_enabled = False
  835. from model_tools import get_tool_definitions
  836. value.tools = [tool for tool in get_tool_definitions(enabled_toolsets=["skills"],
  837. disabled_toolsets=scope.parent.disabled_toolsets, quiet_mode=True,
  838. skip_tool_search_assembly=True) or [] if tool.get("function", {}).get("name") in _SKILL_REVIEW_TOOLS]
  839. value.valid_tool_names = {tool["function"]["name"] for tool in value.tools}
  840. value._invalidate_system_prompt()
  841. scope.agent = value
  842. setattr(scope.parent, name, value)
  843. def _enable_skill_review(agent, binding):
  844. """Use Hermes' native trigger/queue/review, while allowing skills only."""
  845. native = getattr(agent, "_spawn_background_review_now", None)
  846. required = ("skip_context_files", "load_soul_identity", "_background_review_agent", "_background_review_run")
  847. if (not all(hasattr(agent, name) for name in required) or not callable(native)
  848. or (not callable(getattr(native, "__func__", None)) and not hasattr(agent, "_yaoyao_skill_review_native"))):
  849. raise BridgeError("当前 Hermes 不支持工具桥的技能复盘", 409, "skill_review_unavailable")
  850. agent._yaoyao_skill_review_binding = binding
  851. if not hasattr(agent, "_yaoyao_skill_review_native"):
  852. agent._yaoyao_skill_review_native = native.__func__
  853. def skills_only(messages_snapshot, review_memory=False, review_skills=False, focus=None,
  854. task_cfg=None, _requeue_attempts=0, explicit=False):
  855. if not review_skills:
  856. return
  857. scope = _SkillReviewScope(agent, agent._yaoyao_skill_review_binding,
  858. time.monotonic() + MAX_LEASE_MS / 1000)
  859. token = _skill_review_scope.set(scope)
  860. try:
  861. # Hermes copies ContextVars into its review/tool threads. The
  862. # main turn never inherits this narrow post-turn permission.
  863. return agent._yaoyao_skill_review_native(_SkillReviewParent(scope), messages_snapshot,
  864. review_memory=False, review_skills=True, focus=focus, task_cfg=task_cfg,
  865. _requeue_attempts=_requeue_attempts, explicit=explicit)
  866. finally:
  867. _skill_review_scope.reset(token)
  868. agent._spawn_background_review_now = skills_only
  869. agent.skip_background_review = False
  870. def _skill_review_directive(scope, session_id, tool_name):
  871. from hermes_constants import get_hermes_home
  872. if (time.monotonic() >= scope.deadline or scope.agent is None or scope.run is None
  873. or getattr(scope.parent, "_background_review_agent", None) is not scope.agent
  874. or getattr(scope.parent, "_background_review_run", None) is not scope.run
  875. or scope.run.cancel_requested.is_set()
  876. or session_id != scope.agent.session_id
  877. or Path(get_hermes_home()).resolve() != scope.binding.profile_home.resolve()):
  878. return {"action": "block", "message": "本次技能复盘已结束或 Profile 不匹配。"}
  879. if tool_name not in _SKILL_REVIEW_TOOLS:
  880. return {"action": "block", "message": "技能复盘仅允许 skills_list、skill_view 和 skill_manage;不要调用记忆、文件、电脑或协作工具。"}
  881. return None
  882. def computer_directive(session_id=None, tool_name=None, args=None, **kwargs):
  883. scope = _skill_review_scope.get()
  884. if scope is not None:
  885. return _skill_review_directive(scope, session_id, tool_name)
  886. if _hermes_cron_tool(tool_name):
  887. try:
  888. _resolve(session_id)
  889. except BridgeError:
  890. pass
  891. else:
  892. return _block_hermes_cron()
  893. try:
  894. server = _server()
  895. except BridgeError:
  896. return None
  897. with server._sessions_lock, _lock:
  898. inherited = _children.get(session_id)
  899. sessions = [inherited[0].session] if inherited else [s for sid, s in server._sessions.items()
  900. if session_id in {sid, s.get("session_key"), getattr(s.get("agent"), "session_id", None)}]
  901. managed = next((s for s in sessions if s.get("_yaoyao_computer_policy") or s.get("_yaoyao_workspace_memory")), None)
  902. if managed is None:
  903. return None
  904. try:
  905. binding = _resolve(session_id)
  906. except BridgeError:
  907. return {"action": "block", "message": "电脑会话授权已经结束,请在当前 Bot 中发起新一轮。"}
  908. policy = binding.computer_policy
  909. if tool_name in {"kanban_show", "kanban_comment", "kanban_heartbeat"}:
  910. task_id = args.get("task_id") if isinstance(args, dict) else None
  911. if not (isinstance(task_id, str) and task_id.strip()) and not os.getenv("HERMES_KANBAN_TASK", "").strip():
  912. return {"action": "block", "message": "当前 Bot 对话没有 Hermes 看板 task_id;跳过看板步骤,继续用户原始任务。仅当用户需要看板操作时查询真实任务 ID,不要重试相同缺参调用,也不要用夭夭 run/task ID 代替。"}
  913. if binding.workspace_memory and tool_name in binding.profile_memory_tools:
  914. return {"action": "block", "message": "此 Bot 使用独立记忆,请使用本轮授权的 workspace 记忆工具。"}
  915. if not policy:
  916. return None if binding.workspace_memory else {"action": "block", "message": "当前轮次缺少电脑权限声明。"}
  917. if policy["mode"] == "profile" or policy["hostAccess"]:
  918. return None
  919. # Skill discovery, vision, and authenticated services retain the Profile's
  920. # existing tool permissions. Host commands/files/UI require Hermes approval.
  921. host_tools = {"terminal", "process", "process_manage", "read_file", "write_file", "patch", "search_files",
  922. "execute_code", "code_execution", "delegate_task", "computer_use", "desktop_project", "session_search"}
  923. host = tool_name in host_tools or str(tool_name).startswith(("browser_", "host_", "yaoyao_computer_copy_file_"))
  924. if not host:
  925. return None
  926. fingerprint = hashlib.sha256(json.dumps([tool_name, args], sort_keys=True, ensure_ascii=False).encode()).hexdigest()
  927. try:
  928. from agent.redact import redact_sensitive_text
  929. details = redact_sensitive_text(json.dumps(args or {}, ensure_ascii=False), force=True)[:4000]
  930. except Exception:
  931. return {"action": "block", "message": "无法安全显示本机操作内容,请使用虚拟机工具或重新发起请求。"}
  932. return {"action": "approve", "message": f"隔离 Bot 请求使用 Hermes 本机工具 {tool_name}。\n具体操作:{details}",
  933. "rule_key": "yaoyao-host:" + fingerprint}
  934. def computer_file(owner, body):
  935. binding = _resolve(_string(body, "session_id"))
  936. if binding.owner != owner or binding.generation != _string(body, "generation") or not binding.computer_policy:
  937. raise BridgeError("文件请求不属于当前电脑会话")
  938. action, raw = body.get("action"), _string(body, "path", 4096)
  939. transfer = body.get("transfer") if action == "transfer" else None
  940. if action == "transfer":
  941. action = body.get("direction")
  942. operations = {"read": {"transfer-read-open", "transfer-read", "transfer-status", "transfer-abort"},
  943. "write": {"transfer-write-open", "transfer-append", "transfer-finish", "transfer-status", "transfer-abort"}}
  944. if not isinstance(transfer, dict) or transfer.get("op") not in operations.get(action, set()):
  945. raise BridgeError("文件分块请求格式无效", 400)
  946. if action not in {"read", "write"} or "\0" in raw:
  947. raise BridgeError("文件请求格式无效", 400)
  948. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  949. context = set_hermes_home_override(binding.profile_home)
  950. try:
  951. cwd = Path(binding.session.get("cwd") or binding.profile_home)
  952. path = Path(raw).expanduser()
  953. path = (cwd / path).resolve() if not path.is_absolute() else path.resolve()
  954. # Respect Hermes' internal protected paths as well as regular-file and
  955. # size bounds; model-selected paths never become configuration inputs.
  956. from tools.file_tools import _check_sensitive_path, _check_protected_instruction_write, _check_approval_required_write
  957. from agent.file_safety import get_read_block_error
  958. error = get_read_block_error(str(path)) if action == "read" else _check_sensitive_path(str(path), str(binding.agent.session_id))
  959. if action == "write" and not error:
  960. error = (_check_protected_instruction_write([str(path)], str(binding.agent.session_id))
  961. or _check_approval_required_write([str(path)], str(binding.agent.session_id)))
  962. if error:
  963. raise BridgeError("该文件不在 Hermes 允许的文件访问范围内")
  964. if transfer is not None:
  965. import subprocess
  966. namespace = hashlib.sha256(json.dumps([binding.owner, binding.session_id, binding.generation, action, str(path)]).encode()).hexdigest()
  967. payload = dict(transfer)
  968. if payload.get("op") in {"transfer-read-open", "transfer-write-open"}:
  969. payload["path"] = str(path)
  970. with _lock:
  971. if _resolve(binding.session_id) is not binding:
  972. raise BridgeError("文件所属轮次已经结束")
  973. binding.transfer_namespaces.add(namespace)
  974. try:
  975. completed = subprocess.run([sys.executable, str(Path(__file__).with_name("file_transfer.py")), namespace],
  976. input=json.dumps(payload), text=True, capture_output=True, cwd=str(cwd), timeout=30)
  977. finally:
  978. if _bindings.get(binding.session_id) is not binding:
  979. _cleanup_file_transfers((namespace,))
  980. if completed.returncode:
  981. raise BridgeError("文件分块传输失败:" + completed.stderr.strip().split("\n")[-1][:300], 400)
  982. if _resolve(binding.session_id) is not binding:
  983. raise BridgeError("文件所属轮次已经结束")
  984. result = json.loads(completed.stdout)
  985. if "path" in result: result["path"] = raw
  986. return {"ok": True, **result}
  987. limit = 25 * 1024 * 1024
  988. if action == "read":
  989. import stat
  990. fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0))
  991. with os.fdopen(fd, "rb") as stream:
  992. info = os.fstat(stream.fileno())
  993. if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
  994. raise BridgeError("只支持不超过 25 MiB 的普通文件", 400)
  995. data = stream.read(limit + 1)
  996. if len(data) > limit:
  997. raise BridgeError("文件超过 25 MiB", 413)
  998. result = {"ok": True, "data": base64.b64encode(data).decode()}
  999. else:
  1000. encoded = body.get("data")
  1001. if not isinstance(encoded, str) or len(encoded) > (limit + 2) // 3 * 4:
  1002. raise BridgeError("文件超过 25 MiB", 413)
  1003. try:
  1004. data = base64.b64decode(encoded, validate=True)
  1005. except ValueError:
  1006. raise BridgeError("文件编码无效", 400) from None
  1007. if len(data) > limit:
  1008. raise BridgeError("文件超过 25 MiB", 413)
  1009. _resolve(binding.session_id)
  1010. path.parent.mkdir(parents=True, exist_ok=True)
  1011. # Atomic replacement never follows an existing destination symlink.
  1012. import tempfile
  1013. fd, temporary = tempfile.mkstemp(prefix=".yaoyao-transfer-", dir=path.parent)
  1014. try:
  1015. with os.fdopen(fd, "wb") as stream:
  1016. stream.write(data)
  1017. _resolve(binding.session_id)
  1018. os.replace(temporary, path)
  1019. finally:
  1020. Path(temporary).unlink(missing_ok=True)
  1021. result = {"ok": True}
  1022. if _resolve(binding.session_id) is not binding:
  1023. raise BridgeError("文件所属轮次已经结束")
  1024. return result
  1025. finally:
  1026. reset_hermes_home_override(context)
  1027. async def extract_memory(profile, prompt):
  1028. import asyncio
  1029. if not isinstance(profile, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", profile):
  1030. raise BridgeError("Profile 名称无效", 400)
  1031. if not isinstance(prompt, str) or not 0 < len(prompt) <= 65000:
  1032. raise BridgeError("记忆提炼输入无效", 400)
  1033. from hermes_cli.profiles import get_profile_dir, profile_exists
  1034. from hermes_constants import set_hermes_home_override, reset_hermes_home_override
  1035. if not profile_exists(profile):
  1036. raise BridgeError("Hermes Profile 不存在", 404)
  1037. context = set_hermes_home_override(get_profile_dir(profile))
  1038. try:
  1039. from agent.auxiliary_client import async_call_llm, extract_content_or_reasoning
  1040. from hermes_cli.config import load_config_readonly
  1041. from hermes_cli.runtime_provider import resolve_runtime_provider
  1042. model = load_config_readonly().get("model") or {}
  1043. if not isinstance(model, dict) or not model.get("default"):
  1044. raise BridgeError("Hermes Profile 尚未配置模型", 409)
  1045. runtime = resolve_runtime_provider(requested=model.get("provider"), target_model=model["default"],
  1046. explicit_base_url=model.get("base_url"), explicit_api_key=model.get("api_key"))
  1047. # An HTTP request has no agent turn context: never borrow the last
  1048. # multiplexed Profile's runtime from the auxiliary client's mirrors.
  1049. response = await asyncio.wait_for(async_call_llm(task="compression", messages=[
  1050. {"role": "system", "content": "仅从给定材料提炼记忆。不调用工具,不补充未经确认的事实。"},
  1051. {"role": "user", "content": prompt}], tools=[], max_tokens=4096, timeout=90,
  1052. main_runtime={**runtime, "model": model["default"]}), timeout=90)
  1053. return {"text": extract_content_or_reasoning(response)}
  1054. finally:
  1055. reset_hermes_home_override(context)