bridge_runtime.py 46 KB

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