runtime_context.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. """Application-owned configuration for embedded Yaovi workers.
  2. One worker process serves one conversation. The snapshot is installed before
  3. the kernel is imported and shared with its child threads, never read from an
  4. external Hermes installation. Callers receive copies, so plugins cannot mutate
  5. the admitted configuration of another call.
  6. """
  7. from copy import deepcopy
  8. from typing import Any
  9. _context: dict[str, Any] | None = None
  10. _dispatch = None
  11. PRODUCT_HELP_GUIDANCE = (
  12. "You run in Yaoyao (夭夭 AI), a workstation with persistent Bots, group chats, "
  13. "devices, memory and skills. Use Yaoyao settings and the tools admitted for this "
  14. "task to configure or inspect the workstation. Bot settings own the runtime "
  15. "configuration; users do not manage a separate Agent Profile. Base product help "
  16. "on the current Yaoyao source, documentation and observed state."
  17. )
  18. def product_identity() -> str | None:
  19. if _context is None:
  20. return None
  21. from agent.prompt_builder import DEFAULT_AGENT_IDENTITY
  22. return DEFAULT_AGENT_IDENTITY.replace(
  23. "You are Hermes Agent, built by Nous Research.", "You are Yaoyao (夭夭 AI).", 1
  24. )
  25. def product_help_guidance() -> str | None:
  26. return PRODUCT_HELP_GUIDANCE if _context is not None else None
  27. def environment_hints_enabled() -> bool:
  28. # A Yaovi VM/client-only turn must not probe an ambient Hermes Docker/SSH
  29. # backend while building its prompt. Host tools install their own cwd scope.
  30. return _context is None or bool(_context.get('hostWorkspace'))
  31. def migrate_product_prompt(prompt: str | None) -> str | None:
  32. """Rename only the known built-in prefix on the next turn, preserving context.
  33. Never replace names in user prose, Bot roles, memory, tools, or history.
  34. Upstream module names and license attribution remain source metadata.
  35. """
  36. identity = product_identity()
  37. if not prompt or identity is None:
  38. return prompt
  39. from agent.prompt_builder import (
  40. DEFAULT_AGENT_IDENTITY, HERMES_AGENT_HELP_GUIDANCE,
  41. HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS,
  42. )
  43. for help_text in (HERMES_AGENT_HELP_GUIDANCE, HERMES_AGENT_HELP_GUIDANCE_NO_SKILLS):
  44. prefix = DEFAULT_AGENT_IDENTITY + "\n\n" + help_text
  45. if prompt.startswith(prefix):
  46. return identity + "\n\n" + PRODUCT_HELP_GUIDANCE + prompt[len(prefix):]
  47. return prompt
  48. def install(context: dict[str, Any], dispatch) -> None:
  49. global _context, _dispatch
  50. if _context is not None:
  51. raise RuntimeError("Runtime context is immutable after admission")
  52. _context = deepcopy(context)
  53. _dispatch = dispatch
  54. import native_skills
  55. if "skills" in _context:
  56. native_skills.install(_context, dispatch)
  57. _context.setdefault("config", {}).setdefault("skills", {}).update({"create_dir": str(native_skills.root()), "external_dirs": [], "inline_shell": False})
  58. def dispatch(name, args, **metadata):
  59. return _dispatch(name, args, **metadata)
  60. def current() -> dict[str, Any] | None:
  61. return deepcopy(_context)
  62. def compact_skill_index_enabled() -> bool:
  63. config = (_context or {}).get('toolDiscovery') or {}
  64. return config.get('version') == 1 and config.get('mode') == 'on_demand'
  65. # The admitted context is immutable, so the merged view is computed once per defaults object.
  66. _merged: tuple[int, dict[str, Any], dict[str, Any]] | None = None
  67. def _merged_configuration(defaults: dict[str, Any]) -> dict[str, Any]:
  68. global _merged
  69. if _merged is not None and _merged[0] == id(defaults) and _merged[1] is defaults:
  70. return _merged[2]
  71. def merge(base, overlay):
  72. result = deepcopy(base)
  73. for key, value in overlay.items():
  74. result[key] = merge(result[key], value) if isinstance(value, dict) and isinstance(result.get(key), dict) else deepcopy(value)
  75. return result
  76. merged = merge(defaults, _context.get("config", {}))
  77. _merged = (id(defaults), defaults, merged)
  78. return merged
  79. def configuration(defaults: dict[str, Any]) -> dict[str, Any] | None:
  80. """A private copy callers may mutate."""
  81. if _context is None:
  82. return None
  83. return deepcopy(_merged_configuration(defaults))
  84. def configuration_readonly(defaults: dict[str, Any]) -> dict[str, Any] | None:
  85. """The shared merged view; callers must not mutate it (``load_config_readonly`` contract)."""
  86. if _context is None:
  87. return None
  88. return _merged_configuration(defaults)
  89. def load_tools(agent) -> bool:
  90. if _context is None:
  91. return False
  92. from tools.registry import registry
  93. catalog = _context.get("tools", [])
  94. if "skills" in _context:
  95. catalog = [t for t in catalog if t["name"] not in ("skills_list", "skill_view", "skill_manage")]
  96. child = getattr(agent, "platform", None) == "subagent"
  97. if child:
  98. # Temporary workers cannot mutate long-lived identities, shared learning,
  99. # teams or schedules. They retain the parent's admitted device tools.
  100. catalog = [t for t in catalog if (
  101. (not t["name"].startswith("workspace_") or t["name"].startswith(("workspace_get_", "workspace_list_", "workspace_history_search", "workspace_memory_search", "workspace_memory_file_read")))
  102. and t["name"] not in ("skill_propose", "skill_feedback", "task_checkpoint_update")
  103. and not t["name"].startswith("routine_")
  104. )]
  105. for entry in catalog:
  106. def handler(args, task_id=None, _name=entry["name"], **kwargs):
  107. return _dispatch(_name, args, task_id=task_id, **kwargs)
  108. # Media still executes through Hermes's native dispatchers behind the workspace bridge;
  109. # this explicit registration keeps receipts and generated attachments in the owning turn.
  110. registry.register(name=entry["name"], toolset="yaovi", schema={"name": entry["name"], "description": entry["description"], "parameters": entry["parameters"]}, handler=handler,
  111. override=entry["name"] in ("image_generate", "video_generate", "web_search", "web_extract", "tool_search", "tool_describe", "tool_call", "manage_connections"))
  112. agent.tools = [{"type": "function", "function": entry} for entry in catalog]
  113. if not child and not _context.get("review"):
  114. from tools import clarify_tool
  115. agent.tools.append({"type":"function","function":registry.get_schema("clarify")})
  116. # User mode uses workspace memory tools; peer mode injects its native provider
  117. # schemas after initialization. The builtin Hermes ``memory`` tool stays absent.
  118. if _context.get("config", {}).get("delegation", {}).get("enabled", True) and (not child or "delegation" in (getattr(agent, "enabled_toolsets", None) or [])):
  119. from tools import delegate_tool # register the native Hermes subagent tool
  120. schema = registry.get_schema("delegate_task")
  121. if schema:
  122. agent.tools.append({"type": "function", "function": schema})
  123. import native_skills
  124. if "skills" in _context:
  125. native_skills.register(agent, writable=not child)
  126. mcp_toolsets = [] if _context.get("review") else load_mcp_tools(agent)
  127. agent._skip_mcp_refresh = True
  128. agent.valid_tool_names = {t["function"]["name"] for t in agent.tools}
  129. agent.enabled_toolsets = ["yaovi", "skills", "delegation", *(["memory"] if _context.get("nativeMemory") else []), *mcp_toolsets]
  130. agent.disabled_toolsets = []
  131. agent._tool_snapshot_generation = registry._generation
  132. agent._kanban_worker_guidance = ""
  133. if _context.get("toolDiscovery") is not None or _context.get("compactResults") is True:
  134. from tool_discovery import configure
  135. configure(agent, _context, registry=registry)
  136. return True
  137. def load_mcp_tools(agent) -> list[str]:
  138. """Connect the admitted Hermes ``mcp_servers`` (compiled per Bot by Yaovi) and expose their
  139. ``mcp_<server>_<tool>`` tools. A failing server is skipped; the turn still runs."""
  140. servers = (_context or {}).get("config", {}).get("mcp_servers") or {}
  141. names = [n for n, cfg in servers.items() if isinstance(cfg, dict) and cfg.get("enabled", True) is not False]
  142. if not names:
  143. return []
  144. try:
  145. from tools.mcp_tool_discovery import discover_mcp_tools
  146. from tools.registry import registry
  147. tool_names = set(discover_mcp_tools(names))
  148. except Exception:
  149. import logging
  150. logging.getLogger(__name__).warning("MCP discovery failed", exc_info=True)
  151. return []
  152. agent._yaovi_mcp_names = set(tool_names)
  153. have = {t["function"]["name"] for t in agent.tools}
  154. for name in tool_names:
  155. _require_approval(registry.get_entry(name), name)
  156. agent.tools.extend(d for d in registry.get_definitions(tool_names, quiet=True) if d["function"]["name"] not in have)
  157. return [f"mcp-{n}" for n in names]
  158. _MCP_READ_ONLY_UTILITIES = ("_list_resources", "_read_resource", "_list_prompts", "_get_prompt")
  159. def _require_approval(entry, name: str) -> None:
  160. """Every MCP tool call (except the built-in resource/prompt readers) waits for Yaovi's per-call approval,
  161. exactly as the former Yaovi MCP client did; a denial returns an error to the model without calling the server."""
  162. if entry is None or getattr(entry.handler, "_yaovi_guarded", False) or name.endswith(_MCP_READ_ONLY_UTILITIES):
  163. return
  164. import json
  165. original = entry.handler
  166. def guarded(args, **kwargs):
  167. verdict = _dispatch("yaovi_mcp_approve", {"tool": name, "args": args}, task_id=kwargs.get("task_id"))
  168. try:
  169. allowed = bool(json.loads(verdict).get("allow")) if isinstance(verdict, str) else bool((verdict or {}).get("allow"))
  170. except Exception:
  171. allowed = False
  172. if not allowed:
  173. return json.dumps({"error": f"用户未批准调用 MCP 工具 {name},未执行。"}, ensure_ascii=False)
  174. return original(args, **kwargs)
  175. guarded._yaovi_guarded = True
  176. entry.handler = guarded