bridge_runtime.py 51 KB

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