Repository navigation
Expand file tree
/
Copy pathmodel_tools.py
More file actions
1188 lines (1048 loc) · 48.7 KB
/
Copy pathmodel_tools.py
File metadata and controls
1188 lines (1048 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Model Tools Module
Thin orchestration layer over the tool registry. Each tool file in tools/
self-registers its schema, handler, and metadata via tools.registry.register().
This module triggers discovery (by importing all tool modules), then provides
the public API that run_agent.py, cli.py, batch_runner.py, and the RL
environments consume.
Public API (names and arguments preserved from the original 2,400-line version):
await get_tool_definitions(enabled_toolsets, disabled_toolsets, quiet_mode) -> list
await handle_function_call(function_name, function_args, task_id, user_task) -> str
TOOL_TO_TOOLSET_MAP: dict (for batch_runner.py)
TOOLSET_REQUIREMENTS: dict (for cli.py, doctor.py)
await get_all_tool_names() -> list
await get_toolset_for_tool(name) -> str
await get_available_toolsets() -> dict
await check_toolset_requirements() -> dict
await check_tool_availability(quiet) -> tuple
"""
import asyncio
import os
import json
import re
import logging
import time
import aiofiles.os
# Built-in discovery executes tool source from an async in-memory loader, but
# ``terminal_tool``'s retained lifecycle graph imports httpx. httpx imports
# Rich, whose module initializer snapshots ``os.getcwd()`` synchronously.
# Prime only that fixed transport dependency at this process import boundary;
# user/plugin discovery stays lazy and awaited, and cold tool discovery does
# not call a blocking cwd helper from the event-loop thread.
import httpx as _httpx_bootstrap # noqa: F401
from tools import self_repo_guard as _SelfRepoGuardBootstrap # noqa: F401
from contextvars import ContextVar
from typing import Any
from tools.registry import (
CHECK_FN_CACHE_BYPASS,
check_fn_cache_scope,
discover_builtin_tools,
registry,
tool_error,
)
from toolsets import resolve_toolset, validate_toolset
logger = logging.getLogger(__name__)
# Per-dispatch state that is not part of Hermes' public
# ``handle_function_call`` signature. ContextVar keeps concurrent agents and
# TaskGroup tool calls isolated while preserving the upstream call contract.
_TOOL_HANDLER_CONTEXT: ContextVar[dict[str, Any] | None] = ContextVar(
"tool_handler_context",
default=None,
)
# Tracks platform-bundle names already flagged in disabled_toolsets so the
# advisory (#33924) is logged once per name, not on every tool recompute.
_WARNED_DISABLED_BUNDLES: set = set()
# =============================================================================
# Tool Discovery (importing each module triggers its registry.register calls)
# =============================================================================
_builtin_tools_discovered = False
_public_maps_generation = -1
async def _ensure_builtin_tools_discovered() -> None:
"""Discover built-ins once at the first awaited model-tool boundary."""
global _builtin_tools_discovered, _public_maps_generation
if not _builtin_tools_discovered:
# ``discover_builtin_tools`` owns the process-wide, loop-neutral import
# claim. Keeping a second import-time asyncio.Lock here binds this
# public library module to whichever loop happens to discover first.
await discover_builtin_tools()
_builtin_tools_discovered = True
if _public_maps_generation != registry._generation:
TOOL_TO_TOOLSET_MAP.clear()
TOOL_TO_TOOLSET_MAP.update(registry.get_tool_to_toolset_map())
TOOLSET_REQUIREMENTS.clear()
TOOLSET_REQUIREMENTS.update(registry.get_toolset_requirements())
_public_maps_generation = registry._generation
# MCP discovery is deliberately lazy. A conversation's async turn prologue
# awaits it after the agent has entered its own event loop, avoiding import-time
# network I/O and preserving per-conversation prompt-cache construction.
# This training runtime accepts capabilities through configured external MCP
# servers and file-based Skills. Do not import the separate Hermes plugin
# runtime here: plugins can register arbitrary additional model tools as an
# import side effect and would defeat the fixed training tool surface.
# =============================================================================
# Backward-compat constants (built once after discovery)
# =============================================================================
TOOL_TO_TOOLSET_MAP: dict[str, str] = registry.get_tool_to_toolset_map()
TOOLSET_REQUIREMENTS: dict[str, dict] = registry.get_toolset_requirements()
# =============================================================================
# Legacy toolset name mapping (old _tools-suffixed names -> tool name lists)
# =============================================================================
_LEGACY_TOOLSET_MAP = {
"web_tools": ["web_search", "web_extract"],
"terminal_tools": ["terminal"],
"vision_tools": ["vision_analyze"],
"image_tools": ["image_generate"],
"skills_tools": ["skills_list", "skill_view", "skill_manage"],
"browser_tools": [
"browser_navigate", "browser_snapshot", "browser_click",
"browser_type", "browser_scroll", "browser_back",
"browser_press", "browser_get_images",
"browser_vision", "browser_console"
],
"file_tools": ["read_file", "write_file", "patch", "search_files"],
"tts_tools": ["text_to_speech"],
}
# =============================================================================
# get_tool_definitions (the main schema provider)
# =============================================================================
# Module-level memoization for get_tool_definitions(). Keyed on
# (frozenset(enabled_toolsets), frozenset(disabled_toolsets), registry._generation).
# Hot callers invoke this at each async tool-snapshot refresh
# with quiet_mode=True; caching avoids ~7 ms of registry walking + schema
# filtering + check_fn probing per call. Only active when quiet_mode=True
# because quiet_mode=False has stdout side effects (tool-selection prints).
#
# Invalidation happens transparently via the registry's _generation counter,
# which bumps on register() / deregister() / register_toolset_alias(). The
# inner check_fn TTL cache in registry.py handles environment drift (Docker
# daemon start/stop, env var changes, etc.) on a 30 s horizon.
_tool_defs_cache: dict[tuple, list[dict[str, Any]]] = {}
# Hard cap on memoized get_tool_definitions() results. A long-lived embedding
# process sees many distinct toolset/config fingerprints over its lifetime;
# without a
# bound the cache grows unboundedly. 8 comfortably covers the warm working
# set while keeping the cap small. (#19251)
_TOOL_DEFS_CACHE_MAX = 8
def _clear_tool_defs_cache() -> None:
"""Drop memoized get_tool_definitions() results."""
_tool_defs_cache.clear()
async def get_tool_definitions(
enabled_toolsets: list[str] | None = None,
disabled_toolsets: list[str] | None = None,
quiet_mode: bool = False,
skip_tool_search_assembly: bool = False,
) -> list[dict[str, Any]]:
"""
Get tool definitions for model API calls with toolset-based filtering.
All tools must be part of a toolset to be accessible.
Args:
enabled_toolsets: Only include tools from these toolsets.
disabled_toolsets: Exclude tools from these toolsets (if enabled_toolsets is None).
quiet_mode: Suppress status prints.
skip_tool_search_assembly: When True, return the pre-assembly tool list
(raw schemas for every enabled tool). Used internally by the
tool_search / tool_describe bridge handlers so they can read the
real catalog, not the already-collapsed one. Public callers should
leave this False.
Returns:
Filtered list of OpenAI-format tool definitions.
"""
await _ensure_builtin_tools_discovered()
# Fast path: memoized result when the caller doesn't need stdout prints.
# The cache key captures every argument-level input; the registry
# generation captures registry mutations (MCP refresh, plugin load).
# check_fn results are TTL-cached one level down, inside
# registry.get_definitions. The config-mtime fingerprint below captures
# user-visible config edits that affect dynamic schemas without needing an explicit
# invalidate hook on every config-writer.
if quiet_mode:
cache_key = None
try:
from hermes_cli.config import get_config_path
cfg_path = get_config_path()
cfg_stat = await aiofiles.os.stat(cfg_path)
cfg_fp = (cfg_stat.st_mtime_ns, cfg_stat.st_size)
except (FileNotFoundError, OSError, ImportError):
cfg_fp = None
profile_scope = await check_fn_cache_scope()
if profile_scope != CHECK_FN_CACHE_BYPASS:
cache_key = (
frozenset(enabled_toolsets) if enabled_toolsets is not None else None,
frozenset(disabled_toolsets) if disabled_toolsets else None,
registry._generation,
cfg_fp,
bool(skip_tool_search_assembly),
profile_scope,
)
cached = _tool_defs_cache.get(cache_key) if cache_key is not None else None
if cached is not None:
# Return a shallow copy of the list but share the dict references —
# schemas are treated as read-only by all known callers.
return list(cached)
result = await _compute_tool_definitions(
enabled_toolsets,
disabled_toolsets,
quiet_mode,
skip_tool_search_assembly=skip_tool_search_assembly,
)
if quiet_mode and cache_key is not None:
# Cache the freshly-computed list, but hand callers a shallow copy so
# downstream mutations (e.g. run_agent appending memory/LCM tool
# schemas to self.tools) don't poison the cache. Without this, a
# long-lived Gateway process accumulates duplicate tool names across
# agent inits and providers that enforce unique tool names
# (DeepSeek, Xiaomi MiMo, Moonshot Kimi) reject the request with
# HTTP 400. Mirrors the cache-hit path above. (issue #17335)
# Bound the cache with LRU eviction so a long-lived Gateway process
# doesn't accumulate entries unboundedly across the many distinct
# toolset/config fingerprints it sees over its lifetime (#19251).
if len(_tool_defs_cache) >= _TOOL_DEFS_CACHE_MAX:
_tool_defs_cache.pop(next(iter(_tool_defs_cache))) # evict oldest
_tool_defs_cache[cache_key] = result
return list(result)
if quiet_mode:
return list(result)
return result
async def _compute_tool_definitions(
enabled_toolsets: list[str] | None = None,
disabled_toolsets: list[str] | None = None,
quiet_mode: bool = False,
skip_tool_search_assembly: bool = False,
) -> list[dict[str, Any]]:
"""Uncached implementation of :func:`get_tool_definitions`."""
# Determine which tool names the caller wants
tools_to_include: set = set()
if enabled_toolsets is not None:
for toolset_name in enabled_toolsets:
if validate_toolset(toolset_name):
resolved = resolve_toolset(toolset_name)
tools_to_include.update(resolved)
if not quiet_mode:
print(f"✅ Enabled toolset '{toolset_name}': {', '.join(resolved) if resolved else 'no tools'}")
elif toolset_name in _LEGACY_TOOLSET_MAP:
legacy_tools = _LEGACY_TOOLSET_MAP[toolset_name]
tools_to_include.update(legacy_tools)
if not quiet_mode:
print(f"✅ Enabled legacy toolset '{toolset_name}': {', '.join(legacy_tools)}")
elif not quiet_mode:
print(f"⚠️ Unknown toolset: {toolset_name}")
else:
# Default: start with everything
from toolsets import get_all_toolsets
for ts_name in get_all_toolsets():
tools_to_include.update(resolve_toolset(ts_name))
# Always apply disabled toolsets as a subtraction step at the end.
# This ensures that even if a composite toolset (like hermes-cli)
# is enabled, any tools belonging to a disabled toolset are strictly
# stripped out. See issue #17309.
if disabled_toolsets:
for toolset_name in disabled_toolsets:
if validate_toolset(toolset_name):
from toolsets import bundle_non_core_tools, get_toolset
if toolset_name.startswith("hermes-") or (get_toolset(toolset_name) or {}).get("posture"):
# Platform bundles (hermes-*) include _HERMES_CORE_TOOLS, and
# posture toolsets (`posture: True`, e.g. `coding`) re-list
# those same core tools without owning them, so subtracting
# the whole toolset would strip core tools shared by other
# enabled toolsets and empty the tool list (#33924, #57315).
# Subtract only the non-core delta; keep core.
to_remove = bundle_non_core_tools(toolset_name)
tools_to_include.difference_update(to_remove)
resolved = sorted(to_remove)
if (not quiet_mode and toolset_name.startswith("hermes-")
and toolset_name not in _WARNED_DISABLED_BUNDLES):
_WARNED_DISABLED_BUNDLES.add(toolset_name)
logger.info(
"agent.disabled_toolsets contains platform-bundle "
"name '%s'; core tools are preserved and only its "
"platform-specific tools (%s) are removed. Bundle "
"names usually belong in `toolsets:`, not "
"`disabled_toolsets` (#33924).",
toolset_name,
", ".join(resolved) if resolved else "none",
)
else:
resolved = resolve_toolset(toolset_name)
tools_to_include.difference_update(resolved)
if not quiet_mode:
print(f"🚫 Disabled toolset '{toolset_name}': {', '.join(resolved) if resolved else 'no tools'}")
elif toolset_name in _LEGACY_TOOLSET_MAP:
legacy_tools = _LEGACY_TOOLSET_MAP[toolset_name]
tools_to_include.difference_update(legacy_tools)
if not quiet_mode:
print(f"🚫 Disabled legacy toolset '{toolset_name}': {', '.join(legacy_tools)}")
elif not quiet_mode:
print(f"⚠️ Unknown toolset: {toolset_name}")
# Ask the registry for schemas (only returns tools whose check_fn passes)
filtered_tools = await registry.get_definitions(
tools_to_include,
quiet=quiet_mode,
)
available_tool_names = {
tool["function"]["name"] for tool in filtered_tools
}
if "execute_code" in available_tool_names:
from tools.code_execution_tool import (
SANDBOX_ALLOWED_TOOLS,
_get_execution_mode,
build_execute_code_schema,
)
sandbox_enabled = SANDBOX_ALLOWED_TOOLS & available_tool_names
dynamic_schema = await build_execute_code_schema(
sandbox_enabled,
mode=await _get_execution_mode(),
)
for index, definition in enumerate(filtered_tools):
if definition.get("function", {}).get("name") == "execute_code":
filtered_tools[index] = {
"type": "function",
"function": dynamic_schema,
}
break
if not quiet_mode:
if filtered_tools:
tool_names = [t["function"]["name"] for t in filtered_tools]
print(f"🛠️ Final tool selection ({len(filtered_tools)} tools): {', '.join(tool_names)}")
else:
print("🛠️ No tools selected (all filtered out or unavailable)")
# Sanitize schemas for broad backend compatibility. llama.cpp's
# json-schema-to-grammar converter (used by its OAI server to build
# GBNF tool-call parsers) rejects some shapes that cloud providers
# silently accept — bare "type": "object" with no properties,
# string-valued schema nodes from malformed MCP servers, etc. This
# is a no-op for schemas that are already well-formed.
try:
from tools.schema_sanitizer import sanitize_tool_schemas
filtered_tools = sanitize_tool_schemas(filtered_tools)
except Exception as e: # pragma: no cover — defensive
logger.warning("Schema sanitization skipped: %s", e)
# Conditionally collapse MCP tools behind Hermes' progressive-disclosure
# bridge. This remains the final assembly step so prompt/tool schemas stay
# byte-stable for the conversation after the initial snapshot.
try:
from tools.tool_search import assemble_tool_defs, load_config
tool_search_config = await load_config()
if not skip_tool_search_assembly and tool_search_config.enabled != "off":
assembly = await assemble_tool_defs(
filtered_tools,
context_length=await _resolve_active_context_length(),
config=tool_search_config,
)
if assembly.activated and not quiet_mode:
listing_forms = {
"full": "catalog listing embedded",
"names": "names-only listing embedded",
"mixed": "listing embedded (oversized servers summarized)",
"groups": "server summary embedded (search-only discovery)",
"none": "no listing (search-only)",
}
print(
f"🔎 Tool Search (tier {assembly.tier}): "
f"{assembly.deferred_count} MCP/plugin tools deferred "
f"(~{assembly.deferred_tokens} tokens) behind "
"tool_search/describe/call — "
f"{listing_forms.get(assembly.listing_form, assembly.listing_form)}."
)
filtered_tools = assembly.tool_defs
except Exception as exc: # pragma: no cover - never break tool loading
logger.warning("Tool search assembly skipped: %s", exc)
return filtered_tools
async def _resolve_active_context_length() -> int:
"""Look up the active model's context length for the tool-search gate.
Returns 0 when the model can't be resolved — ``should_activate`` falls
back to a fixed token cutoff in that case.
"""
try:
from hermes_cli.config import load_config_readonly
cfg = await load_config_readonly() or {}
model_cfg = cfg.get("model") if isinstance(cfg.get("model"), dict) else {}
if not isinstance(model_cfg, dict):
model_cfg = {}
_raw_model_id = model_cfg.get("model") or model_cfg.get("default") or ""
if isinstance(_raw_model_id, dict):
from hermes_cli.config import split_model_config_default
_raw_model_id, _ = split_model_config_default(_raw_model_id)
model_id = str(_raw_model_id).strip()
if not model_id:
return 0
from agent.model_metadata import get_model_context_length
raw_ctx = model_cfg.get("context_length")
config_ctx = raw_ctx if isinstance(raw_ctx, int) and raw_ctx > 0 else None
provider = str(model_cfg.get("provider") or "").strip()
base_url = str(model_cfg.get("base_url") or "").strip()
api_key = ""
if provider:
try:
from hermes_cli.runtime_provider import resolve_runtime_provider
runtime = await resolve_runtime_provider(
requested=provider,
target_model=model_id,
) or {}
base_url = str(runtime.get("base_url") or base_url or "").strip()
api_key = str(runtime.get("api_key") or "").strip()
except Exception as runtime_error:
logger.debug(
"Runtime credential resolution failed for tool-search "
"context gate (provider=%s): %s — using config values only",
provider,
runtime_error,
)
return int(await get_model_context_length(
model_id,
base_url=base_url,
api_key=api_key,
config_context_length=config_ctx,
provider=provider,
) or 0)
except Exception as e:
logger.debug("Could not resolve active context length: %s", e)
return 0
# =============================================================================
# handle_function_call (the main dispatcher)
# =============================================================================
_AGENT_LOOP_TOOLS = {"todo", "memory", "session_search", "delegate_task"}
_READ_SEARCH_TOOLS = {"read_file", "search_files"}
# =========================================================================
# Tool error sanitization
# =========================================================================
#
# Tool exceptions can carry arbitrary text into the model's context as the
# `tool` message content. json.dumps() handles quote/backslash escaping so a
# raw injection of `</tool_call>` won't break message framing, but the model
# still *reads* those tokens and they can confuse downstream tool-call
# parsing or, in adversarial cases, nudge it toward role-confusion framing.
#
# This helper strips structural framing tokens (XML role tags, CDATA,
# markdown code fences) and caps the message at a sane upper bound before it
# becomes part of the conversation. It's defense-in-depth — the json layer
# already prevents framing escape — but cheap and worth having.
#
# Ported from ironclaw#1639.
_TOOL_ERROR_ROLE_TAG_RE = re.compile(
r'</?(?:tool_call|function_call|result|response|output|input|system|assistant|user)>',
re.IGNORECASE,
)
_TOOL_ERROR_FENCE_OPEN_RE = re.compile(r'^\s*```(?:json|xml|html|markdown)?\s*', re.MULTILINE)
_TOOL_ERROR_FENCE_CLOSE_RE = re.compile(r'\s*```\s*$', re.MULTILINE)
_TOOL_ERROR_CDATA_RE = re.compile(r'<!\[CDATA\[.*?\]\]>', re.DOTALL)
_TOOL_ERROR_MAX_LEN = 2000
def _sanitize_tool_error(error_msg: str) -> str:
"""Strip structural framing tokens from a tool error before showing it to the model.
See _TOOL_ERROR_ROLE_TAG_RE docstring above for rationale.
"""
if not error_msg:
return "[TOOL_ERROR] "
sanitized = _TOOL_ERROR_ROLE_TAG_RE.sub("", error_msg)
sanitized = _TOOL_ERROR_FENCE_OPEN_RE.sub("", sanitized)
sanitized = _TOOL_ERROR_FENCE_CLOSE_RE.sub("", sanitized)
sanitized = _TOOL_ERROR_CDATA_RE.sub("", sanitized)
if len(sanitized) > _TOOL_ERROR_MAX_LEN:
sanitized = sanitized[:_TOOL_ERROR_MAX_LEN - 3] + "..."
return f"[TOOL_ERROR] {sanitized}"
# =========================================================================
# Tool argument type coercion
# =========================================================================
def coerce_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
"""Coerce tool call arguments to match their JSON Schema types.
LLMs frequently return numbers as strings (``"42"`` instead of ``42``)
and booleans as strings (``"true"`` instead of ``true``). This compares
each argument value against the tool's registered JSON Schema and attempts
safe coercion when the value is a string but the schema expects a different
type. Original values are preserved when coercion fails.
Handles ``"type": "integer"``, ``"type": "number"``, ``"type": "boolean"``,
and union types (``"type": ["integer", "string"]``).
Also wraps bare scalar values in a single-element list when the schema
declares ``"type": "array"``. Open-weight models (DeepSeek, Qwen, GLM)
sometimes emit ``{"urls": "https://a.com"}`` when the tool expects
``{"urls": ["https://a.com"]}``; wrapping here avoids a confusing tool
failure on what is otherwise a well-formed call.
"""
if not args or not isinstance(args, dict):
return args
schema = registry.get_schema(tool_name)
if not schema:
return args
properties = (schema.get("parameters") or {}).get("properties")
if not properties:
return args
# The model saw the SANITIZED schema — property keys violating provider
# patterns (e.g. Cloudflare's ``issue_class~neq``) were renamed before
# the request. Map any sanitized keys back to the registry's original
# wire names before schema lookup / dispatch.
try:
from tools.schema_sanitizer import unrename_tool_args
args = unrename_tool_args(schema.get("parameters"), args)
except Exception: # pragma: no cover — never break dispatch
pass
for key, value in list(args.items()):
prop_schema = properties.get(key)
if not prop_schema:
continue
expected = prop_schema.get("type")
# Wrap bare non-list values when the schema declares ``array``.
# Strings still go through _coerce_value first so JSON-encoded
# arrays (``'["a","b"]'``) get parsed and nullable ``"null"``
# becomes ``None`` rather than ``["null"]``.
# ``None`` itself is preserved — we don't know whether the model
# meant "omit" or "empty list", and tools with sensible defaults
# (e.g. read_file's normalize_read_pagination) already handle it.
if expected == "array" and value is not None and not isinstance(value, (list, tuple)):
if isinstance(value, str):
coerced = _coerce_value(value, expected, schema=prop_schema)
if coerced is not value:
# _coerce_value handled it (JSON-parsed list or
# nullable "null" → None).
args[key] = coerced
continue
# If the string looks like a JSON array but _coerce_value
# failed to parse it, warn clearly instead of silently wrapping.
if value.strip().startswith("["):
logger.warning(
"coerce_tool_args: %s.%s looks like a JSON array string "
"but could not be parsed — model may have emitted a "
"JSON-encoded string instead of a native array. "
"Falling back to single-element list.",
tool_name, key,
)
args[key] = [value]
logger.info(
"coerce_tool_args: wrapped bare string in list for %s.%s",
tool_name, key,
)
continue
args[key] = [value]
logger.info(
"coerce_tool_args: wrapped bare %s in list for %s.%s",
type(value).__name__, tool_name, key,
)
continue
if not isinstance(value, str):
# Recurse into already-native containers so JSON-encoded
# *elements* (array items) and *sub-fields* (nested object
# properties) get normalized too — e.g. ``todos: ['{"id":...}']``
# or ``tasks: [{"goal": "..."}]`` where an element was emitted as
# a JSON string. The top-level coercion above only repairs the
# outermost value.
if expected == "array" and isinstance(value, (list, tuple)):
args[key] = _normalize_json_strings_for_schema(value, prop_schema)
elif expected == "object" and isinstance(value, dict):
args[key] = _normalize_json_strings_for_schema(value, prop_schema)
continue
if not expected and not _schema_allows_null(prop_schema):
continue
coerced = _coerce_value(value, expected, schema=prop_schema)
if coerced is not value:
args[key] = coerced
# If we just JSON-parsed a string into a container, recurse so
# nested JSON-encoded elements/fields get normalized as well.
if isinstance(coerced, (list, tuple, dict)):
args[key] = _normalize_json_strings_for_schema(coerced, prop_schema)
return args
def _schema_accepts_kind(schema: Any, kind: str) -> bool:
"""Return True when *schema* permits a value of JSON type *kind*.
Looks at ``type`` (string or list) and recurses through
``anyOf``/``oneOf``/``allOf`` branches — matching the JSON-Schema shapes
open-weight models emit against. ``kind`` is ``"array"`` or ``"object"``.
"""
if not isinstance(schema, dict):
return False
t = schema.get("type")
if t == kind or (isinstance(t, list) and kind in t):
return True
for union_key in ("anyOf", "oneOf", "allOf"):
branches = schema.get(union_key)
if isinstance(branches, list) and any(
_schema_accepts_kind(b, kind) for b in branches
):
return True
return False
def _normalize_json_strings_for_schema(value: Any, schema: Any) -> Any:
"""Recursively parse JSON-encoded string values that a schema expects to
be arrays or objects, including nested array items and object properties.
Open-weight models (DeepSeek, Qwen, GLM, and others) sometimes emit a
structured field — or an *element* of a structured field — as a
JSON-encoded string instead of a native value. The top-level
:func:`coerce_tool_args` pass repairs the outermost value; this helper
walks the rest of the tree so cases like::
{"todos": ["{\\"id\\": \\"1\\", \\"content\\": \\"x\\"}"]}
(a list whose elements are JSON strings) and nested object sub-fields are
repaired too. Parsing is schema-guided: a string is only parsed when the
matching schema position actually expects an array or object, so
legitimate JSON-looking string fields (``type: string``) are preserved.
Ported from cline/cline#11803, adapted to hermes-agent's coercion layer.
Returns the original value object when nothing changed (identity preserved
so callers can cheaply detect no-ops).
"""
if not isinstance(schema, dict):
return value
# Parse a JSON-encoded string into the container the schema expects.
if isinstance(value, str):
trimmed = value.strip()
expects_array = _schema_accepts_kind(schema, "array")
expects_object = _schema_accepts_kind(schema, "object")
if (expects_array and trimmed.startswith("[")) or (
expects_object and trimmed.startswith("{")
):
try:
parsed = json.loads(trimmed)
except (ValueError, TypeError):
return value
if isinstance(parsed, list) and expects_array:
value = parsed
elif isinstance(parsed, dict) and expects_object:
value = parsed
else:
return value
else:
return value
# Recurse into list items using the ``items`` schema.
if isinstance(value, list):
items_schema = schema.get("items")
if not isinstance(items_schema, dict):
return value
changed = False
out = []
for item in value:
nxt = _normalize_json_strings_for_schema(item, items_schema)
changed = changed or (nxt is not item)
out.append(nxt)
return out if changed else value
# Recurse into object properties using each property's schema.
if isinstance(value, dict):
props = schema.get("properties")
if not isinstance(props, dict):
return value
changed = False
out = dict(value)
for k, prop_schema in props.items():
if k not in value or not isinstance(prop_schema, dict):
continue
nxt = _normalize_json_strings_for_schema(value[k], prop_schema)
if nxt is not value[k]:
out[k] = nxt
changed = True
return out if changed else value
return value
def _coerce_value(value: str, expected_type, schema: dict | None = None):
"""Attempt to coerce a string *value* to *expected_type*.
Returns the original string when coercion is not applicable or fails.
"""
if _schema_allows_null(schema) and value.strip().lower() == "null":
return None
if isinstance(expected_type, list):
# Union type — try each in order, return first successful coercion
for t in expected_type:
result = _coerce_value(value, t, schema=schema)
if result is not value:
return result
return value
if expected_type in {"integer", "number"}:
return _coerce_number(value, integer_only=(expected_type == "integer"))
if expected_type == "boolean":
return _coerce_boolean(value)
if expected_type == "array":
return _coerce_json(value, list)
if expected_type == "object":
return _coerce_json(value, dict)
if expected_type == "null" and value.strip().lower() == "null":
return None
return value
def _schema_allows_null(schema: dict | None) -> bool:
"""Return True when a JSON Schema fragment explicitly permits null."""
if not isinstance(schema, dict):
return False
schema_type = schema.get("type")
if schema_type == "null":
return True
if isinstance(schema_type, list) and "null" in schema_type:
return True
if schema.get("nullable") is True:
return True
for union_key in ("anyOf", "oneOf"):
variants = schema.get(union_key)
if not isinstance(variants, list):
continue
for variant in variants:
if isinstance(variant, dict) and variant.get("type") == "null":
return True
return False
def _coerce_json(value: str, expected_python_type: type):
"""Parse *value* as JSON when the schema expects an array or object.
Handles model output drift where a complex oneOf/discriminated-union schema
causes the LLM to emit the array/object as a JSON string instead of a native
structure. Returns the original string if parsing fails or yields the wrong
Python type.
"""
try:
parsed = json.loads(value)
except (ValueError, TypeError) as exc:
logger.warning(
"coerce_tool_args: failed to parse string as JSON for expected type %s: %s",
expected_python_type.__name__,
exc,
)
return value
if isinstance(parsed, expected_python_type):
logger.debug(
"coerce_tool_args: coerced string to %s via json.loads",
expected_python_type.__name__,
)
return parsed
logger.warning(
"coerce_tool_args: JSON-parsed value is %s, expected %s — skipping coercion",
type(parsed).__name__,
expected_python_type.__name__,
)
return value
def _coerce_number(value: str, integer_only: bool = False):
"""Try to parse *value* as a number. Returns original string on failure."""
try:
f = float(value)
except (ValueError, OverflowError):
return value
# Guard against inf/nan — not JSON-serializable, keep original string
if f != f or f == float("inf") or f == float("-inf"):
return value
# If it looks like an integer (no fractional part), return int
if f == int(f):
return int(f)
if integer_only:
# Schema wants an integer but value has decimals — keep as string
return value
return f
def _coerce_boolean(value: str):
"""Try to parse *value* as a boolean. Returns original string on failure."""
low = value.strip().lower()
if low == "true":
return True
if low == "false":
return False
return value
def _tool_result_observer_fields(result: Any) -> tuple[str, str | None, str | None]:
try:
parsed_result = json.loads(result) if isinstance(result, str) else result
if isinstance(parsed_result, dict) and parsed_result.get("error"):
return "error", "tool_error", str(parsed_result.get("error"))
except Exception:
pass
return "ok", None, None
async def _emit_post_tool_call_hook(
*,
function_name: str,
function_args: dict[str, Any],
result: Any,
task_id: str | None = None,
session_id: str | None = None,
tool_call_id: str | None = None,
turn_id: str | None = None,
api_request_id: str | None = None,
duration_ms: int = 0,
status: str | None = None,
error_type: str | None = None,
error_message: str | None = None,
middleware_trace: list[dict[str, Any]] | None = None,
) -> None:
"""Emit the ``post_tool_call`` observer hook.
No-ops cheaply when no plugin has registered for ``post_tool_call`` —
the ``has_hook`` gate skips both the result-field derivation and the
payload dispatch so the no-listener path costs one dict lookup. When
``status`` is not supplied, the ok/error fields are derived from the
result *after* the gate (parsing the result is only worth it when a
listener will actually consume it).
"""
try:
from hermes_cli.lifecycle import has_hook, invoke_hook
if not has_hook("post_tool_call"):
return
if status is None:
status, error_type, error_message = _tool_result_observer_fields(result)
await invoke_hook(
"post_tool_call",
tool_name=function_name,
args=function_args,
result=result,
task_id=task_id or "",
session_id=session_id or "",
tool_call_id=tool_call_id or "",
turn_id=turn_id or "",
api_request_id=api_request_id or "",
duration_ms=duration_ms,
status=status,
error_type=error_type,
error_message=error_message,
middleware_trace=list(middleware_trace or []),
)
except Exception as _hook_err:
logger.debug("post_tool_call hook error: %s", _hook_err)
async def handle_function_call(
function_name: str,
function_args: dict[str, Any],
task_id: str | None = None,
tool_call_id: str | None = None,
session_id: str | None = None,
turn_id: str | None = None,
api_request_id: str | None = None,
user_task: str | None = None,
enabled_tools: list[str] | None = None,
skip_pre_tool_call_hook: bool = False,
skip_tool_request_middleware: bool = False,
skip_tool_execution_middleware: bool = False,
tool_request_middleware_trace: list[dict[str, Any]] | None = None,
enabled_toolsets: list[str] | None = None,
disabled_toolsets: list[str] | None = None,
) -> str | dict:
"""Dispatch one tool through the native async plugin lifecycle.
Request middleware, pre-tool policy, execution middleware, observer hooks,
and result transforms keep their established order. Callers that already
own those phases use the existing ``skip_*`` arguments so each phase fires
exactly once.
"""
await _ensure_builtin_tools_discovered()
function_args = coerce_tool_args(function_name, function_args)
if not isinstance(function_args, dict):
function_args = {}
tool_search_module = None
try:
from tools import tool_search as tool_search_module
except Exception:
pass
if (
tool_search_module is not None
and tool_search_module.is_bridge_tool(function_name)
):
try:
current_definitions = await get_tool_definitions(
enabled_toolsets=enabled_toolsets,
disabled_toolsets=disabled_toolsets,
quiet_mode=True,
skip_tool_search_assembly=True,
) or []
except Exception:
current_definitions = []
if function_name == tool_search_module.TOOL_SEARCH_NAME:
return await tool_search_module.dispatch_tool_search(
function_args,
current_tool_defs=current_definitions,
)
if function_name == tool_search_module.TOOL_DESCRIBE_NAME:
return tool_search_module.dispatch_tool_describe(
function_args,
current_tool_defs=current_definitions,
)
underlying_name, underlying_args, error = (
tool_search_module.resolve_underlying_call(function_args)
)
if error or not underlying_name:
return tool_error(error or "tool_call could not be resolved")
scoped_names = tool_search_module.scoped_deferrable_names(
current_definitions
)
if underlying_name not in scoped_names:
return tool_error(
f"'{underlying_name}' is not available in this session. "
"Use tool_search to find tools you can call."
)
validation_error = tool_search_module.validate_deferred_call_args(
underlying_name,
underlying_args,
)
if validation_error is not None:
return validation_error
return await handle_function_call(
function_name=underlying_name,
function_args=underlying_args,
task_id=task_id,
tool_call_id=tool_call_id,
session_id=session_id,
user_task=user_task,
enabled_tools=enabled_tools,
skip_pre_tool_call_hook=skip_pre_tool_call_hook,
skip_tool_request_middleware=skip_tool_request_middleware,
skip_tool_execution_middleware=skip_tool_execution_middleware,
tool_request_middleware_trace=list(tool_request_middleware_trace or []),
enabled_toolsets=enabled_toolsets,
disabled_toolsets=disabled_toolsets,
)
original_args = dict(function_args)
middleware_trace = list(tool_request_middleware_trace or [])
handler_context = _TOOL_HANDLER_CONTEXT.get() or {}
if not skip_tool_request_middleware:
try:
from hermes_cli.middleware import apply_tool_request_middleware
request_result = await apply_tool_request_middleware(
function_name,
function_args,
task_id=task_id or "",
session_id=session_id or "",
tool_call_id=tool_call_id or "",
turn_id=turn_id or "",
api_request_id=api_request_id or "",
)
function_args = request_result.payload
original_args = request_result.original_payload
middleware_trace = request_result.trace
except asyncio.CancelledError: