bridge_runtime.py 54 KB

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