bridge_runtime.py 45 KB

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