File size: 6,002 Bytes
1f36664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from collections.abc import Mapping, Sequence
from pathlib import PurePath
import re
from typing import Any
from urllib.parse import urlparse


_UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$")
_HASH_RE = re.compile(r"^[0-9a-fA-F]{16,}$")
_TIMESTAMP_RE = re.compile(
    r"^(?:\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?|\d{10,13})$"
)
_WINDOWS_PATH_RE = re.compile(r"^[A-Za-z]:[\\/]")
_RANDOM_ID_RE = re.compile(r"^(?:[A-Za-z]+[_-])?[0-9a-fA-F]{8,}$")
_SAFE_ENUM_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{0,31}$")
_URL_SCHEME_RE = re.compile(r"^(?:https?|ftp|s3|gs)://", re.IGNORECASE)


def _looks_like_path(value: str) -> bool:
    if _WINDOWS_PATH_RE.match(value):
        return True
    return value.startswith(("/", "./", "../", "~/")) or ("/" in value and " " not in value)


def _path_token(value: str) -> str:
    cleaned = value.replace("\\", "/")
    suffix = PurePath(cleaned).suffix.lower()
    suffix_token = suffix if suffix and len(suffix) <= 10 else ""
    scope = "ABS" if cleaned.startswith("/") or _WINDOWS_PATH_RE.match(value) else "REL"
    if any(part.lower() in {"tmp", "temp", "cache"} for part in cleaned.split("/")):
        scope = "TEMP"
    return f"<PATH:{scope}{':' + suffix_token if suffix_token else ''}>"


def normalize_parameter_value(value: Any, config: dict[str, Any] | None = None) -> str:
    config = config or {}
    keep_enums = bool(config.get("keep_stable_enum_values", True))
    if value is None:
        return "<NULL>"
    if isinstance(value, bool):
        return "<BOOL:TRUE>" if value else "<BOOL:FALSE>"
    if isinstance(value, int) and not isinstance(value, bool):
        if bool(config.get("keep_small_integers", True)) and -10 <= value <= 100:
            return f"<INT:{value}>"
        magnitude = "SMALL" if abs(value) < 1_000 else "MEDIUM" if abs(value) < 1_000_000 else "LARGE"
        return f"<INT:{magnitude}>"
    if isinstance(value, float):
        return "<FLOAT>"
    if isinstance(value, Mapping):
        return "<OBJECT>"
    if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
        return f"<LIST:{min(len(value), 20)}>"
    if isinstance(value, (bytes, bytearray)):
        return f"<BYTES:{len(value)}>"

    text = str(value).strip()
    if not text:
        return "<EMPTY>"
    if _UUID_RE.match(text):
        return "<UUID>"
    if _TIMESTAMP_RE.match(text):
        return "<TIMESTAMP>"
    if _HASH_RE.match(text):
        return "<HASH>"
    # ``urllib.parse.urlparse`` may raise ``ValueError: Invalid IPv6 URL``
    # for arbitrary tool arguments containing unmatched square brackets.  Most
    # parameter values are not URLs, so only invoke the parser when a supported
    # URL scheme is explicitly present.  Malformed URL-like values are mapped to a typed placeholder instead of
    # aborting feature construction.
    if _URL_SCHEME_RE.match(text):
        try:
            parsed = urlparse(text)
        except ValueError:
            return "<URL:MALFORMED>"
        if parsed.scheme.lower() in {"http", "https", "ftp", "s3", "gs"}:
            kind = parsed.scheme.upper()
            suffix = PurePath(parsed.path).suffix.lower()
            return f"<URL:{kind}{':' + suffix if suffix else ''}>"
    if _looks_like_path(text):
        return _path_token(text)
    if _RANDOM_ID_RE.match(text) and any(char.isdigit() for char in text):
        return "<ID>"
    if keep_enums and _SAFE_ENUM_RE.match(text) and len(text) <= int(config.get("max_enum_length", 32)):
        return text.lower()
    if text.isdigit():
        return "<NUMBER>"
    return "<TEXT>"


def flatten_parameters(value: Any, prefix: str = "arg", *, max_items: int = 64) -> list[tuple[str, Any]]:
    output: list[tuple[str, Any]] = []

    def visit(current: Any, path: str) -> None:
        if len(output) >= max_items:
            return
        if isinstance(current, Mapping):
            for key in sorted(current, key=lambda item: str(item)):
                visit(current[key], f"{path}.{key}")
            return
        if isinstance(current, Sequence) and not isinstance(current, (str, bytes, bytearray)):
            output.append((path, current))
            for index, item in enumerate(current[:5]):
                if isinstance(item, (Mapping, list, tuple)):
                    visit(item, f"{path}[]")
            return
        output.append((path, current))

    visit(value, prefix)
    return output


def normalized_call_tokens(
    tool_name: str,
    tool_input: Any,
    config: dict[str, Any] | None = None,
) -> tuple[str, list[str]]:
    """Return a normalized call signature and argument-role tokens.

    Raw paths, filenames, UUIDs, timestamps and random IDs are replaced with
    typed placeholders. Argument keys and stable enum values are retained because
    they often carry the discriminative semantics missing from the tool name.
    """
    config = config or {}
    tool = str(tool_name or "unknown_tool").strip().lower()
    pairs = flatten_parameters(
        tool_input if tool_input is not None else {},
        max_items=int(config.get("max_flattened_items", 64)),
    )
    role_tokens: list[str] = []
    signature_parts: list[str] = []
    for key, value in pairs:
        try:
            normalized = normalize_parameter_value(value, config)
        except (TypeError, ValueError, UnicodeError):
            # A single malformed argument must not abort feature construction.
            # Keep its parameter role while discarding the unsafe raw value.
            normalized = "<TEXT>"
        safe_key = re.sub(r"[^A-Za-z0-9_.\[\]-]+", "_", key.lower())
        signature_parts.append(f"{safe_key}={normalized}")
        role_tokens.append(f"param:{tool}:{safe_key}={normalized}")
    if not signature_parts:
        signature_parts.append("<NO_ARGS>")
    signature = f"call:{tool}[{'|'.join(signature_parts)}]"
    return signature, role_tokens