host_runtime.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Yaovi's Host tools and trusted per-turn working directory.
  2. The workspace owns this policy. Hermes supplies the real native handlers; its
  3. upstream source and the VM/client bridges remain unchanged. This directory is a
  4. default working directory, not an operating-system sandbox.
  5. """
  6. from copy import deepcopy
  7. from functools import wraps
  8. import os
  9. from pathlib import Path
  10. HOST_TOOLS = ('terminal', 'process_manage', 'read_file', 'write_file', 'patch', 'search_files', 'execute_code')
  11. _cwd = None
  12. def authorization_inputs(tool, args, ids):
  13. """Resolve native file targets before policy sees them, including every patch target."""
  14. if _cwd is None or tool not in ('read_file', 'write_file', 'patch', 'search_files') or not isinstance(args, dict):
  15. return [args]
  16. from tools.terminal_tool import get_session_cwd
  17. cwd = get_session_cwd(ids.get('task_id') or ids.get('session_id')) or _cwd
  18. paths = [args.get('path', '.' if tool == 'search_files' else None)]
  19. if tool == 'patch' and args.get('mode') == 'patch' and isinstance(args.get('patch'), str):
  20. from tools.file_tools import _collect_v4a_header_paths
  21. parsed = _collect_v4a_header_paths(args['patch'])
  22. if not isinstance(parsed, str):
  23. paths = parsed[0]
  24. resolved = []
  25. for raw in paths:
  26. if not isinstance(raw, str) or not raw:
  27. continue # The native handler rejects its malformed input without effects.
  28. path = Path(os.path.expanduser(raw))
  29. target = path if path.is_absolute() else Path(cwd) / path
  30. resolved.append({**args, 'path': str(target.resolve()), 'host_original_paths': [raw]})
  31. return resolved or [args]
  32. def install(request):
  33. global _cwd
  34. workspace = request.get('hostWorkspace')
  35. if workspace is None:
  36. return None
  37. if (not isinstance(workspace, dict) or set(workspace) != {'cwd'}
  38. or not isinstance(workspace['cwd'], str) or not os.path.isabs(workspace['cwd'])):
  39. raise ValueError('Invalid Host workspace')
  40. path = Path(workspace['cwd'])
  41. if not path.is_dir() or path.is_symlink():
  42. raise ValueError('Host workspace is unavailable')
  43. cwd = str(path.resolve(strict=True))
  44. _cwd = cwd
  45. # A worker is one turn and one Host. All Hermes worker/child threads copy
  46. # contextvars; the explicit scope never falls back to .env/config backends.
  47. from tools.terminal_scope import set_terminal_scope
  48. from agent.runtime_cwd import set_session_cwd
  49. set_terminal_scope({'TERMINAL_ENV': 'local', 'TERMINAL_CWD': cwd})
  50. set_session_cwd(cwd)
  51. from agent import runtime_context
  52. original = runtime_context.load_tools
  53. @wraps(original)
  54. def load_tools(agent):
  55. loaded = original(agent)
  56. if not loaded or request.get('reportOnlyReview') or request.get('review'):
  57. return loaded
  58. # Import the native modules rather than replacing them with workspace
  59. # RPC handlers. native_authorization still checks each real dispatch.
  60. from tools import terminal_tool, process_registry, file_tools, code_execution_tool # noqa: F401
  61. from tools.registry import registry
  62. names = {tool['function']['name'] for tool in agent.tools}
  63. for name in HOST_TOOLS:
  64. if name in names:
  65. raise RuntimeError(f'Host tool conflicts with workspace tool: {name}')
  66. schema = deepcopy(registry.get_schema(name))
  67. if not schema:
  68. raise RuntimeError(f'Host native tool unavailable: {name}')
  69. schema['description'] = ('Runs in the Bot Host environment. The default task directory is '
  70. f'{cwd}. VM operations use computer_*; client desktop operations use desktop_*. '
  71. + schema.get('description', ''))
  72. agent.tools.append({'type': 'function', 'function': schema})
  73. agent.valid_tool_names = {tool['function']['name'] for tool in agent.tools}
  74. agent.enabled_toolsets = list(dict.fromkeys([*agent.enabled_toolsets, 'terminal', 'file', 'code_execution']))
  75. agent._tool_snapshot_generation = registry._generation
  76. # The discovery layer captures post-builder native schemas before the
  77. # first request (the same path used by native memory/context tools).
  78. return loaded
  79. runtime_context.load_tools = load_tools
  80. return cwd