bridge_runtime.py 56 KB

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