tool_discovery.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. """Per-run model visibility over Yaovi's already admitted tool catalog.
  2. The registry and original dispatch remain the execution authority. Discovery
  3. only publishes schemas at a model-request boundary; it never calls a target.
  4. """
  5. from copy import deepcopy
  6. from functools import wraps
  7. import hashlib
  8. import json
  9. from pathlib import Path
  10. import re
  11. import threading
  12. import time
  13. import uuid
  14. DISCOVER = 'workspace_tools_discover'
  15. RESULT_READ = 'harness_result_read'
  16. RESULT_PREFIX = 'mcp-result-'
  17. _hooks_installed = False
  18. _hooks_lock = threading.Lock()
  19. DISCOVERY_SCHEMA = {'type': 'function', 'function': {
  20. 'name': DISCOVER,
  21. 'description': 'Find and load admitted tools for the next request. Use a short query or exact original names. This does not execute or authorize them.',
  22. 'parameters': {'type': 'object', 'properties': {
  23. 'query': {'type': 'string', 'minLength': 1, 'maxLength': 500},
  24. 'names': {'type': 'array', 'minItems': 1, 'maxItems': 8, 'uniqueItems': True,
  25. 'items': {'type': 'string', 'minLength': 1, 'maxLength': 256}},
  26. 'expectedCatalogRevision': {'type': 'string', 'pattern': '^[a-f0-9]{64}$'},
  27. 'limit': {'type': 'integer', 'minimum': 1, 'maximum': 8}}, 'additionalProperties': False}}}
  28. RESULT_SCHEMA = {'type': 'function', 'function': {
  29. 'name': RESULT_READ, 'description': 'Read a saved tool result by its opaque resultId. Follow nextOffset to read all text; unavailable results must not cause the original action to be repeated.',
  30. 'parameters': {'type': 'object', 'properties': {'id': {'type': 'string', 'minLength': 1, 'maxLength': 256},
  31. 'offset': {'type': 'integer', 'minimum': 0}, 'length': {'type': 'integer', 'minimum': 1, 'maximum': 16000}},
  32. 'required': ['id'], 'additionalProperties': False}}}
  33. def _name(definition):
  34. return (definition.get('function') or {}).get('name', '')
  35. def _digest(value):
  36. return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
  37. def utf16_length(text):
  38. return len(text.encode('utf-16-le')) // 2
  39. def _clip(text, length):
  40. return text.encode('utf-16-le')[:length * 2].decode('utf-16-le', errors='ignore')
  41. def _error(code, message):
  42. return {'isError': True, 'code': code, 'error': message, 'targetExecuted': False}
  43. class ToolDiscovery:
  44. def __init__(self, agent, request, registry):
  45. self.agent, self.registry = agent, registry
  46. self.lock = threading.RLock()
  47. self.catalog, self.conflicts = {}, set()
  48. for definition in deepcopy(agent.tools):
  49. name = _name(definition)
  50. if name in self.catalog:
  51. self.conflicts.add(name)
  52. elif name:
  53. self.catalog[name] = definition
  54. self.admitted_names = set(self.catalog)
  55. requested_names = {t['name'] for t in request.get('tools', [])}
  56. # Native skill handlers may replace the bridge names during startup;
  57. # they retain their existing native visibility rather than being
  58. # mistaken for deferred workspace tools merely because names match.
  59. self.mcp_names = set(getattr(agent, '_yaovi_mcp_names', ()))
  60. workspace_names, self.unclassified = set(), set()
  61. for name in self.catalog:
  62. try:
  63. source = getattr(registry.get_entry(name), 'toolset', '')
  64. except Exception:
  65. # Registry introspection is an optimization, not a prerequisite
  66. # for answering. Unknown origins stay blocked until rechecked.
  67. self.unclassified.add(name)
  68. continue
  69. if source == 'yaovi' and name in requested_names:
  70. workspace_names.add(name)
  71. elif str(source).startswith('mcp-'):
  72. self.mcp_names.add(name)
  73. self.conflicts.update(requested_names & set(getattr(agent, '_yaovi_mcp_names', ())))
  74. self.native_names = set(self.catalog) - workspace_names - self.mcp_names - self.unclassified
  75. self.config = deepcopy(request.get('toolDiscovery'))
  76. self.scope = [request.get(k) for k in ('workspaceId', 'ownerId', 'botId', 'sessionId', 'runId')]
  77. self.scope.append(getattr(agent, 'platform', None))
  78. self.compact_enabled = request.get('compactResults') is True
  79. self.results = {}
  80. self.pending, self.stale = set(), set()
  81. self.unavailable = self.unclassified.copy()
  82. self.degraded = bool(self.unavailable)
  83. self._native_complete = False
  84. self.mode, self.fallback = 'eager', 'disabled'
  85. self.core = set()
  86. if isinstance(self.config, dict):
  87. names = self.config.get('coreNames', [])
  88. if self.config.get('version') != 1:
  89. self.fallback = 'unsupported'
  90. elif (self.config.get('mode') == 'on_demand' and isinstance(names, list)
  91. and len(names) <= 64
  92. and all(isinstance(n, str) and 0 < utf16_length(n) <= 256 for n in names)
  93. and len(set(names)) == len(names)
  94. and re.fullmatch('[a-f0-9]{64}', str(self.config.get('catalogRevision', '')))
  95. and all(0 < utf16_length(n) <= 256 for n in self.catalog)
  96. and DISCOVER not in self.catalog):
  97. self.mode, self.fallback = 'on_demand', None
  98. self.core = set(names) & workspace_names & set(self.catalog)
  99. elif self.config.get('mode') != 'eager':
  100. self.fallback = 'catalog_unavailable'
  101. self.core |= self.native_names
  102. if self.compact_enabled and RESULT_READ not in self.catalog:
  103. self.catalog[RESULT_READ] = deepcopy(RESULT_SCHEMA)
  104. if RESULT_READ in self.catalog:
  105. self.core.add(RESULT_READ)
  106. if self.degraded:
  107. self.mode, self.fallback = 'eager', 'registry_unavailable'
  108. self.loaded = (set(self.catalog) if self.mode == 'eager' else self.core.copy()) - self.unavailable
  109. self.revision = self._revision()
  110. self._publish()
  111. def _revision(self):
  112. return _digest({'scope': self.scope, 'hostRevision': (self.config or {}).get('catalogRevision') if isinstance(self.config, dict) else None,
  113. 'unavailable': sorted(self.unavailable),
  114. 'tools': [(n, 'mcp' if n in self.mcp_names else 'workspace', self.catalog[n]) for n in sorted(self.catalog)]})
  115. @property
  116. def active(self):
  117. return self.mode == 'on_demand' or self.compact_enabled or self.degraded
  118. def _catalog_failed(self, name):
  119. # Stay eager for this run, bounded to its original admission snapshot.
  120. # Failed MCP entries remain hidden AND execution-blocked; falling back
  121. # never means treating an unknown current handler as authorized.
  122. self.degraded = True
  123. self.mode, self.fallback = 'eager', 'registry_unavailable'
  124. self.unavailable.add(name)
  125. self.loaded = set(self.catalog) - self.unavailable - self.stale
  126. self.pending.clear()
  127. def _capture_native(self):
  128. # AIAgent adds memory/context-engine schemas after load_tools. Capture
  129. # those once after construction, never search the process-wide registry.
  130. if self._native_complete:
  131. return
  132. for definition in self.agent.tools:
  133. name = _name(definition)
  134. if name and name != DISCOVER and name not in self.catalog:
  135. self.catalog[name] = deepcopy(definition)
  136. self.admitted_names.add(name)
  137. self.native_names.add(name)
  138. self.core.add(name)
  139. self.loaded.add(name)
  140. self._native_complete = True
  141. self.revision = self._revision()
  142. def _refresh_mcp(self):
  143. previous_revision = self.revision
  144. previous_unavailable = self.unavailable.copy()
  145. changed = False
  146. for name in tuple(self.unclassified):
  147. try:
  148. entry = self.registry.get_entry(name)
  149. source = getattr(entry, 'toolset', '')
  150. except Exception:
  151. self._catalog_failed(name)
  152. continue
  153. self.unclassified.discard(name)
  154. self.unavailable.discard(name)
  155. changed = True
  156. if entry is None:
  157. self.catalog.pop(name, None)
  158. self.stale.add(name)
  159. self.loaded.discard(name)
  160. elif str(source).startswith('mcp-'):
  161. self.mcp_names.add(name)
  162. for name in self.mcp_names:
  163. if name in self.unclassified:
  164. continue
  165. previous = self.catalog.get(name)
  166. if previous is None:
  167. continue # A removed tool cannot re-enter this run automatically.
  168. try:
  169. entry = self.registry.get_entry(name)
  170. schema = self.registry.get_schema(name) if entry is not None else None
  171. replacement = {'type': 'function', 'function': deepcopy(schema)} if schema else None
  172. if replacement:
  173. if _name(replacement) != name:
  174. raise ValueError('Registry schema name does not match the admitted tool')
  175. if replacement != previous:
  176. _digest(replacement) # Reject unusable schemas inside the same fail-closed boundary.
  177. # Reconnection may replace the handler while leaving schema
  178. # bytes identical. Its original per-call approval still applies.
  179. from agent.runtime_context import _require_approval
  180. _require_approval(entry, name)
  181. except Exception:
  182. self._catalog_failed(name)
  183. continue
  184. self.unavailable.discard(name)
  185. if replacement != previous:
  186. changed = True
  187. self.stale.add(name)
  188. self.loaded.discard(name)
  189. self.pending.discard(name)
  190. if replacement:
  191. self.catalog[name] = replacement
  192. else:
  193. self.catalog.pop(name, None)
  194. if changed or previous_unavailable != self.unavailable:
  195. self.revision = self._revision()
  196. return self.revision != previous_revision
  197. def _publish(self):
  198. definitions = [deepcopy(definition) for name, definition in self.catalog.items()
  199. if name in self.loaded and name not in self.unavailable and name not in self.stale]
  200. if self.mode == 'on_demand':
  201. definitions.append(deepcopy(DISCOVERY_SCHEMA))
  202. from tools.mcp_tool_agent import _agent_tools_lock
  203. with _agent_tools_lock:
  204. self.agent.tools = definitions
  205. self.agent.valid_tool_names = {_name(d) for d in definitions}
  206. def prepare(self):
  207. with self.lock:
  208. self._capture_native()
  209. if self.mode == 'on_demand' or self.degraded:
  210. self._refresh_mcp()
  211. if self.degraded:
  212. # Updated schemas become callable only after a model-request
  213. # boundary has published them. A prior refused call is never run.
  214. self.loaded = set(self.catalog) - self.unavailable
  215. self.stale.difference_update(self.loaded)
  216. else:
  217. self.loaded.update(self.pending & self.catalog.keys())
  218. self.pending.clear()
  219. self._publish()
  220. def metadata(self):
  221. with self.lock:
  222. self._capture_native()
  223. self._publish()
  224. return {'version': 1, 'mode': self.mode, 'catalogRevision': self.revision,
  225. 'visibleToolCount': len(self.agent.tools), **({'fallbackReason': self.fallback} if self.fallback else {})}
  226. def discover(self, args):
  227. if not isinstance(args, dict) or set(args) - {'query', 'names', 'limit', 'expectedCatalogRevision'}:
  228. return _error('invalid_request', 'Provide query or names, with optional expectedCatalogRevision.')
  229. query, names, limit = args.get('query'), args.get('names'), args.get('limit', 4)
  230. exact = 'names' in args
  231. if ('query' in args) == exact or (exact and ('limit' in args or not isinstance(names, list)
  232. or not 1 <= len(names) <= 8 or any(not isinstance(n, str) or not 1 <= utf16_length(n) <= 256 for n in names)
  233. or len(set(names)) != len(names))):
  234. return _error('invalid_request', 'Use one nonempty query or 1–8 distinct original names; names cannot include limit.')
  235. if not exact and (not isinstance(query, str) or not 1 <= utf16_length(query.strip()) <= 500
  236. or type(limit) is not int or not 1 <= limit <= 8):
  237. return _error('invalid_request', 'query must be 1–500 characters and limit an integer from 1 to 8.')
  238. expected = args.get('expectedCatalogRevision')
  239. if expected is not None and (not isinstance(expected, str) or not re.fullmatch('[a-f0-9]{64}', expected)):
  240. return _error('invalid_request', 'Invalid catalog revision.')
  241. with self.lock:
  242. self._refresh_mcp()
  243. if expected is not None and expected != self.revision:
  244. return {**_error('tool_catalog_stale', 'Catalog changed; discover against the current revision.'), 'catalogRevision': self.revision}
  245. if self.mode != 'on_demand':
  246. if self.degraded:
  247. return {**_error('tool_catalog_unavailable', 'Discovery is unavailable; this run uses its admitted eager catalog. Unverifiable tools remain blocked.'),
  248. 'mode': self.mode, 'fallbackReason': self.fallback, 'catalogRevision': self.revision}
  249. return _error('invalid_request', 'This run uses the eager catalog.')
  250. if not exact:
  251. tokens = re.findall(r'\w+', query.casefold())
  252. ranked = []
  253. for name, definition in self.catalog.items():
  254. haystack = (name + ' ' + definition['function'].get('description', '')).casefold()
  255. score = sum(1 for token in tokens if token in haystack)
  256. if score:
  257. ranked.append((-score, name))
  258. names = [name for _, name in sorted(ranked)[:limit]]
  259. if any(name in self.conflicts for name in names):
  260. return _error('tool_name_conflict', 'Original tool name is ambiguous; no target was executed.')
  261. found = [name for name in names if name in self.catalog]
  262. self.pending.update(found)
  263. self.stale.difference_update(found)
  264. return {'catalogRevision': self.revision,
  265. 'matches': [{'name': name, 'source': 'mcp' if name in self.mcp_names else 'workspace',
  266. 'summary': _clip(' '.join(self.catalog[name]['function'].get('description', '').split()), 200), 'loaded': True} for name in found],
  267. 'loadedNames': found, 'notFound': [name for name in names if name not in self.catalog]}
  268. def guard(self, name):
  269. if self.mode != 'on_demand' and not self.degraded:
  270. return None
  271. with self.lock:
  272. self._refresh_mcp()
  273. if name in self.conflicts:
  274. return _error('tool_name_conflict', 'Original tool name is ambiguous; no target was executed.')
  275. if name in self.unavailable:
  276. return _error('tool_catalog_unavailable', 'The current tool registration cannot be verified. No target was executed; do not automatically replay prior operations.')
  277. if name in self.stale:
  278. return {**_error('tool_catalog_stale', 'Tool schema changed; use the next request catalog before a new call.' if self.degraded else 'Tool schema changed; discover it before a new call.'), 'catalogRevision': self.revision}
  279. if name != DISCOVER and name not in self.loaded:
  280. return _error('tool_not_loaded', 'Tool is not in the current request catalog. Wait for the next request catalog and issue a new call only if available; prior receipts remain authoritative.' if self.degraded else 'Tool is not loaded for this run. Use workspace_tools_discover, then issue a new call. Previous operation receipts remain authoritative.')
  281. return None
  282. def compact(self, result, name, args, ids):
  283. if not self.compact_enabled or name not in self.mcp_names or not isinstance(result, str) or utf16_length(result) <= 8000:
  284. return result
  285. # The native renderer can already have capped a flood or represented
  286. # binary media as MEDIA tags. Keep its existing limit/media handling;
  287. # never claim that our text reference restores an already-lost body.
  288. if any(marker in result for marker in ('[MCP RESULT TRUNCATED -', '[MCP content dropped:', 'MEDIA:')):
  289. return result
  290. from tools.tool_result_storage import _write_to_spillover, get_spillover_dir
  291. result_id = RESULT_PREFIX + uuid.uuid4().hex
  292. try:
  293. saved = _write_to_spillover(result, result_id + '.txt')
  294. if not saved:
  295. return result
  296. path = Path(saved)
  297. if path.is_symlink() or not path.resolve().is_relative_to(get_spillover_dir().resolve()):
  298. return result
  299. body = path.read_text(encoding='utf-8')
  300. if body != result:
  301. return result
  302. digest = hashlib.sha256(result.encode()).hexdigest()
  303. with self.lock:
  304. self.results[result_id] = {'path': path, 'root': get_spillover_dir().resolve(),
  305. 'tool': name, 'args': deepcopy(args), 'ids': dict(ids), 'hash': digest}
  306. flags = {}
  307. try:
  308. parsed = json.loads(result)
  309. if isinstance(parsed, dict):
  310. flags = {key: parsed[key] for key in ('isError', 'outcomeUnknown', 'exitCode', 'exit_code', 'status', 'completed') if key in parsed}
  311. if isinstance(parsed.get('error'), str):
  312. flags['error'] = _clip(parsed['error'], 400)
  313. except ValueError:
  314. pass
  315. return json.dumps({'resultId': result_id, 'length': utf16_length(result), 'preview': _clip(result, 1500),
  316. 'truncated': True, 'resultVersion': 1, 'available': True, 'sourceTool': name, 'contentHash': digest,
  317. 'instruction': 'Read the complete result with harness_result_read(id=resultId) and nextOffset before relying on omitted evidence. Do not repeat the original operation.', **flags}, ensure_ascii=False)
  318. except (OSError, UnicodeError):
  319. return result
  320. def read(self, args):
  321. unavailable = _error('result_unavailable', 'Saved result is unavailable in this run. This does not mean the original operation was unexecuted; do not repeat it automatically.')
  322. if (not isinstance(args, dict) or set(args) - {'id', 'offset', 'length'}
  323. or not isinstance(args.get('id'), str) or not 1 <= utf16_length(args['id']) <= 256):
  324. return _error('invalid_request', 'id must be an opaque result ID of 1–256 characters; only offset and length are optional.')
  325. offset, length = args.get('offset', 0), args.get('length', 12000)
  326. if type(offset) is not int or offset < 0 or offset > 9007199254740991 or type(length) is not int or not 1 <= length <= 16000:
  327. return _error('invalid_request', 'offset must be a nonnegative safe integer; length must be 1–16000.')
  328. with self.lock:
  329. entry = self.results.get(args['id'])
  330. if entry is None:
  331. return unavailable
  332. from native_authorization import check_only
  333. from tools.tool_result_storage import SPILLOVER_MAX_AGE_HOURS
  334. with self.lock:
  335. self._refresh_mcp()
  336. if entry['tool'] in self.unavailable:
  337. return unavailable
  338. try:
  339. registered = self.registry.get_entry(entry['tool']) is not None
  340. except Exception:
  341. self._catalog_failed(entry['tool'])
  342. self.revision = self._revision()
  343. return unavailable
  344. try:
  345. if (entry['tool'] not in self.catalog or not registered
  346. or not check_only(entry['tool'], entry['args'], **entry['ids'])
  347. or entry['path'].is_symlink() or not entry['path'].resolve().is_relative_to(entry['root'])
  348. or time.time() - entry['path'].stat().st_mtime >= SPILLOVER_MAX_AGE_HOURS * 3600):
  349. return unavailable
  350. text = entry['path'].read_text(encoding='utf-8')
  351. if hashlib.sha256(text.encode()).hexdigest() != entry['hash']:
  352. return unavailable
  353. encoded = text.encode('utf-16-le')
  354. total = len(encoded) // 2
  355. start, end = min(offset, total), min(offset + length, total)
  356. if start < total and 0xDC00 <= int.from_bytes(encoded[start * 2:start * 2 + 2], 'little') <= 0xDFFF:
  357. return _error('invalid_request', 'offset splits a Unicode character; use the previous page nextOffset.')
  358. if end < total and end > start and 0xD800 <= int.from_bytes(encoded[(end - 1) * 2:end * 2], 'little') <= 0xDBFF:
  359. end -= 1
  360. if end == start and start < total:
  361. return _error('invalid_request', 'length is too short for the next Unicode character; increase length.')
  362. return {'text': encoded[start * 2:end * 2].decode('utf-16-le'), 'offset': start, 'length': total,
  363. 'hasMore': end < total, 'nextOffset': end}
  364. except (OSError, UnicodeError):
  365. return unavailable
  366. def metadata(agent):
  367. state = getattr(agent, '_yaovi_tool_discovery', None)
  368. return state.metadata() if state else {'version': 1, 'mode': 'eager', 'catalogRevision': _digest(getattr(agent, 'tools', [])),
  369. 'visibleToolCount': len(getattr(agent, 'tools', [])), 'fallbackReason': 'disabled'}
  370. def configure(agent, request, *, registry=None, install_hooks=True):
  371. if registry is None:
  372. from tools.registry import registry
  373. state = ToolDiscovery(agent, request, registry)
  374. agent._yaovi_tool_discovery = state
  375. repair = getattr(agent, '_repair_tool_call', None)
  376. if (state.mode == 'on_demand' or state.degraded) and callable(repair):
  377. # A guessed exact deferred name must not fuzzy-match a different core
  378. # tool before the executor has a chance to reject it.
  379. agent._repair_tool_call = lambda name: None if name in state.admitted_names or name in state.conflicts else repair(name)
  380. if install_hooks:
  381. _install_hooks()
  382. return state
  383. def _install_hooks():
  384. global _hooks_installed
  385. with _hooks_lock:
  386. if _hooks_installed:
  387. return
  388. from agent import chat_completion_helpers, conversation_loop, tool_executor
  389. original_assemble = conversation_loop.assemble_api_request
  390. original_build = chat_completion_helpers.build_api_kwargs
  391. original_restore = conversation_loop._restore_pinned_tools
  392. original_invalid = conversation_loop._invalid_tool_name_error_content
  393. original_execute = tool_executor._dispatch_authorized_once
  394. @wraps(original_assemble)
  395. def assemble(agent, **kwargs):
  396. state = getattr(agent, '_yaovi_tool_discovery', None)
  397. if state and state.active:
  398. # Publish BEFORE prompt-cache decoration takes a request-local
  399. # copy, and before token-pressure measurement sees the tools.
  400. state.prepare()
  401. return original_assemble(agent, **kwargs)
  402. @wraps(original_build)
  403. def build(agent, messages, tools_for_api=None):
  404. state = getattr(agent, '_yaovi_tool_discovery', None)
  405. if state and state.active:
  406. state.prepare()
  407. if tools_for_api is not None:
  408. tools_for_api = [d for d in tools_for_api if _name(d) in agent.valid_tool_names]
  409. if state.degraded:
  410. # The registry may change between assembly's decorated
  411. # snapshot and this final send boundary. Keep request-
  412. # local cache annotations, but never send an old schema
  413. # after the eager guard has accepted its replacement.
  414. current = {_name(d): d for d in agent.tools}
  415. tools_for_api = [{**d, 'function': deepcopy(current[_name(d)]['function'])}
  416. for d in tools_for_api]
  417. return original_build(agent, messages, tools_for_api)
  418. @wraps(original_restore)
  419. def restore(agent, row):
  420. state = getattr(agent, '_yaovi_tool_discovery', None)
  421. if state and state.active:
  422. return [_name(d) for d in agent.tools]
  423. return original_restore(agent, row)
  424. @wraps(original_invalid)
  425. def invalid(name, valid_names):
  426. if DISCOVER in valid_names and name:
  427. return json.dumps(_error('tool_not_loaded', 'Tool is not loaded in this run. Use workspace_tools_discover and issue a new call after discovery. Prior receipts remain authoritative.'), ensure_ascii=False)
  428. return original_invalid(name, valid_names)
  429. @wraps(original_execute)
  430. def execute(agent, managed, ref, **kwargs):
  431. state = getattr(agent, '_yaovi_tool_discovery', None)
  432. if state is None or not state.active:
  433. return original_execute(agent, managed, ref, **kwargs)
  434. invoke = kwargs['execute']
  435. def admitted(args):
  436. refusal = state.guard(ref.name)
  437. if refusal is not None:
  438. return json.dumps(refusal, ensure_ascii=False)
  439. if ref.name == DISCOVER and (state.mode == 'on_demand' or state.degraded):
  440. return json.dumps(state.discover(args), ensure_ascii=False)
  441. if ref.name == RESULT_READ and str(args.get('id', '')).startswith(RESULT_PREFIX):
  442. return json.dumps(state.read(args), ensure_ascii=False)
  443. result = invoke(args)
  444. return state.compact(result, ref.name, args, {'tool_call_id': ref.call_id, 'task_id': ref.task_id,
  445. 'session_id': getattr(agent, 'session_id', None)})
  446. return original_execute(agent, managed, ref, **{**kwargs, 'execute': admitted})
  447. chat_completion_helpers.build_api_kwargs = build
  448. conversation_loop.assemble_api_request = assemble
  449. conversation_loop._restore_pinned_tools = restore
  450. conversation_loop._invalid_tool_name_error_content = invalid
  451. tool_executor._dispatch_authorized_once = execute
  452. _hooks_installed = True