native_authorization.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """Yaovi-owned admission for native Hermes tools; upstream remains unmodified.
  2. The request carries only the enforcement switch. Every actual native call asks
  3. the control plane for a fresh decision; no permission result is cached here.
  4. """
  5. from contextvars import ContextVar
  6. from functools import wraps
  7. import json
  8. _call_context = ContextVar('yaovi_native_tool_call', default={})
  9. _authorization = None
  10. def enabled():
  11. return _authorization is not None
  12. def metadata(**values):
  13. result = {**_call_context.get(), **{k: v for k, v in values.items() if v is not None}}
  14. if not result.get('tool_call_id'):
  15. from tools.approval_context import _approval_tool_call_id
  16. result['tool_call_id'] = _approval_tool_call_id.get() or None
  17. return result
  18. def authorize(tool, args, **values):
  19. """Return an error result on refusal/unavailable authority, otherwise None."""
  20. if _authorization is None:
  21. return None
  22. return _authorization.check(tool, args, **values)
  23. def check_only(tool, args, **values):
  24. """Revalidate passive reads without requesting or waiting for new approval."""
  25. if _authorization is None:
  26. return True
  27. return _authorization.check_only(tool, args, **values)
  28. class NativeAuthorization:
  29. def __init__(self, request, dispatch):
  30. self.request = request
  31. self.dispatch = dispatch
  32. def check(self, tool, args, **values):
  33. try:
  34. ids = metadata(**values)
  35. ids.setdefault('session_id', self.request.get('sessionId'))
  36. from host_runtime import authorization_inputs
  37. for checked_args in authorization_inputs(tool, args, ids):
  38. verdict = self.dispatch('yaovi_native_authorize', {'tool': tool, 'args': checked_args}, **ids)
  39. verdict = json.loads(verdict) if isinstance(verdict, str) else verdict
  40. if not isinstance(verdict, dict) or verdict.get('allow') is not True:
  41. message = verdict.get('error') if isinstance(verdict, dict) else None
  42. return json.dumps({'error': message or '此 Bot 未获授权,工具未执行。', 'isError': True}, ensure_ascii=False)
  43. return None
  44. except Exception:
  45. return json.dumps({'error': '无法确认 Bot 权限,工具未执行。', 'isError': True}, ensure_ascii=False)
  46. def check_only(self, tool, args, **values):
  47. try:
  48. ids = metadata(**values)
  49. ids.setdefault('session_id', self.request.get('sessionId'))
  50. from host_runtime import authorization_inputs
  51. for checked_args in authorization_inputs(tool, args, ids):
  52. verdict = self.dispatch('yaovi_native_check', {'tool': tool, 'args': checked_args}, **ids)
  53. verdict = json.loads(verdict) if isinstance(verdict, str) else verdict
  54. if not isinstance(verdict, dict) or verdict.get('allow') is not True:
  55. return False
  56. return True
  57. except Exception:
  58. return False
  59. def install(request, dispatch, *, registry=None, agent_class=None, executor=None):
  60. """Install once before agent construction; return a restoration hook for tests."""
  61. global _authorization
  62. if request.get('botPolicy', {}).get('enabled') is not True:
  63. return lambda: None
  64. if registry is None:
  65. from tools.registry import registry
  66. if agent_class is None:
  67. from run_agent import AIAgent as agent_class
  68. if executor is None:
  69. from agent import tool_executor as executor
  70. previous = _authorization
  71. authority = NativeAuthorization(request, dispatch)
  72. _authorization = authority
  73. admitted = {entry['name'] for entry in request.get('tools', [])}
  74. original_registry = registry.dispatch
  75. original_delegate = agent_class._dispatch_delegate_task
  76. original_execute = executor._dispatch_authorized_once
  77. @wraps(original_registry)
  78. def guarded_registry(name, args, *, scope=None, **kwargs):
  79. entry = registry.get_entry(name, scope=scope)
  80. # Only actual workspace bridge handlers are already checked by TS.
  81. # Native skills can replace catalog entries with the same name.
  82. bridged = name in admitted and entry is not None and entry.toolset == 'yaovi'
  83. refusal = None if bridged else authority.check(name, args, **kwargs)
  84. return refusal if refusal is not None else original_registry(name, args, scope=scope, **kwargs)
  85. @wraps(original_delegate)
  86. def guarded_delegate(self, args):
  87. refusal = authority.check('delegate_task', args, session_id=getattr(self, 'session_id', None))
  88. return refusal if refusal is not None else original_delegate(self, args)
  89. @wraps(original_execute)
  90. def contextual_execute(agent, state, ref, **kwargs):
  91. # Inline delegate/memory calls bypass model_tools' observability binding.
  92. token = _call_context.set({'tool_call_id': ref.call_id, 'task_id': ref.task_id,
  93. 'session_id': getattr(agent, 'session_id', None)})
  94. try:
  95. return original_execute(agent, state, ref, **kwargs)
  96. finally:
  97. _call_context.reset(token)
  98. registry.dispatch = guarded_registry
  99. agent_class._dispatch_delegate_task = guarded_delegate
  100. executor._dispatch_authorized_once = contextual_execute
  101. def restore():
  102. global _authorization
  103. registry.dispatch = original_registry
  104. agent_class._dispatch_delegate_task = original_delegate
  105. executor._dispatch_authorized_once = original_execute
  106. _authorization = previous
  107. return restore