runtime_context.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. def configuration(defaults: dict[str, Any]) -> dict[str, Any] | None:
  66. if _context is None:
  67. return None
  68. def merge(base, overlay):
  69. result = deepcopy(base)
  70. for key, value in overlay.items():
  71. result[key] = merge(result[key], value) if isinstance(value, dict) and isinstance(result.get(key), dict) else deepcopy(value)
  72. return result
  73. return merge(defaults, _context.get("config", {}))
  74. def load_tools(agent) -> bool:
  75. if _context is None:
  76. return False
  77. from tools.registry import registry
  78. catalog = _context.get("tools", [])
  79. if "skills" in _context:
  80. catalog = [t for t in catalog if t["name"] not in ("skills_list", "skill_view", "skill_manage")]
  81. child = getattr(agent, "platform", None) == "subagent"
  82. if child:
  83. # Temporary workers cannot mutate long-lived identities, shared learning,
  84. # teams or schedules. They retain the parent's admitted device tools.
  85. catalog = [t for t in catalog if (
  86. (not t["name"].startswith("workspace_") or t["name"].startswith(("workspace_get_", "workspace_list_", "workspace_history_search", "workspace_memory_search", "workspace_memory_file_read")))
  87. and t["name"] not in ("skill_propose", "skill_feedback", "task_checkpoint_update")
  88. and not t["name"].startswith("routine_")
  89. )]
  90. for entry in catalog:
  91. def handler(args, task_id=None, _name=entry["name"], **kwargs):
  92. return _dispatch(_name, args, task_id=task_id, **kwargs)
  93. # Media still executes through Hermes's native dispatchers behind the workspace bridge;
  94. # this explicit registration keeps receipts and generated attachments in the owning turn.
  95. registry.register(name=entry["name"], toolset="yaovi", schema={"name": entry["name"], "description": entry["description"], "parameters": entry["parameters"]}, handler=handler,
  96. override=entry["name"] in ("image_generate", "video_generate", "web_search", "web_extract", "tool_search", "tool_describe", "tool_call", "manage_connections"))
  97. agent.tools = [{"type": "function", "function": entry} for entry in catalog]
  98. if not child and not _context.get("review"):
  99. from tools import clarify_tool
  100. agent.tools.append({"type":"function","function":registry.get_schema("clarify")})
  101. # User mode uses workspace memory tools; peer mode injects its native provider
  102. # schemas after initialization. The builtin Hermes ``memory`` tool stays absent.
  103. if _context.get("config", {}).get("delegation", {}).get("enabled", True) and (not child or "delegation" in (getattr(agent, "enabled_toolsets", None) or [])):
  104. from tools import delegate_tool # register the native Hermes subagent tool
  105. schema = registry.get_schema("delegate_task")
  106. if schema:
  107. agent.tools.append({"type": "function", "function": schema})
  108. import native_skills
  109. if "skills" in _context:
  110. native_skills.register(agent, writable=not child)
  111. mcp_toolsets = [] if _context.get("review") else load_mcp_tools(agent)
  112. agent._skip_mcp_refresh = True
  113. agent.valid_tool_names = {t["function"]["name"] for t in agent.tools}
  114. agent.enabled_toolsets = ["yaovi", "skills", "delegation", *(["memory"] if _context.get("nativeMemory") else []), *mcp_toolsets]
  115. agent.disabled_toolsets = []
  116. agent._tool_snapshot_generation = registry._generation
  117. agent._kanban_worker_guidance = ""
  118. if _context.get("toolDiscovery") is not None or _context.get("compactResults") is True:
  119. from tool_discovery import configure
  120. configure(agent, _context, registry=registry)
  121. return True
  122. def load_mcp_tools(agent) -> list[str]:
  123. """Connect the admitted Hermes ``mcp_servers`` (compiled per Bot by Yaovi) and expose their
  124. ``mcp_<server>_<tool>`` tools. A failing server is skipped; the turn still runs."""
  125. servers = (_context or {}).get("config", {}).get("mcp_servers") or {}
  126. names = [n for n, cfg in servers.items() if isinstance(cfg, dict) and cfg.get("enabled", True) is not False]
  127. if not names:
  128. return []
  129. try:
  130. from tools.mcp_tool_discovery import discover_mcp_tools
  131. from tools.registry import registry
  132. tool_names = set(discover_mcp_tools(names))
  133. except Exception:
  134. import logging
  135. logging.getLogger(__name__).warning("MCP discovery failed", exc_info=True)
  136. return []
  137. agent._yaovi_mcp_names = set(tool_names)
  138. have = {t["function"]["name"] for t in agent.tools}
  139. for name in tool_names:
  140. _require_approval(registry.get_entry(name), name)
  141. agent.tools.extend(d for d in registry.get_definitions(tool_names, quiet=True) if d["function"]["name"] not in have)
  142. return [f"mcp-{n}" for n in names]
  143. _MCP_READ_ONLY_UTILITIES = ("_list_resources", "_read_resource", "_list_prompts", "_get_prompt")
  144. def _require_approval(entry, name: str) -> None:
  145. """Every MCP tool call (except the built-in resource/prompt readers) waits for Yaovi's per-call approval,
  146. exactly as the former Yaovi MCP client did; a denial returns an error to the model without calling the server."""
  147. if entry is None or getattr(entry.handler, "_yaovi_guarded", False) or name.endswith(_MCP_READ_ONLY_UTILITIES):
  148. return
  149. import json
  150. original = entry.handler
  151. def guarded(args, **kwargs):
  152. verdict = _dispatch("yaovi_mcp_approve", {"tool": name, "args": args}, task_id=kwargs.get("task_id"))
  153. try:
  154. allowed = bool(json.loads(verdict).get("allow")) if isinstance(verdict, str) else bool((verdict or {}).get("allow"))
  155. except Exception:
  156. allowed = False
  157. if not allowed:
  158. return json.dumps({"error": f"用户未批准调用 MCP 工具 {name},未执行。"}, ensure_ascii=False)
  159. return original(args, **kwargs)
  160. guarded._yaovi_guarded = True
  161. entry.handler = guarded