File size: 19,822 Bytes
2b42456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tool registry: schemas, protocol renderers, and argument normalisation.

Grading rests on normalisation, not string equality. Every tool declares how its
arguments are canonicalised so that semantically identical calls compare equal
(`Berlin` / `berlin ` / `Берлин`, `300` / `300.0`, `45+12` / `57`).
"""

from __future__ import annotations

import ast
import json
import math
import re
import unicodedata
from dataclasses import dataclass
from typing import Any, Callable, Mapping, Sequence

from .schema import Protocol


@dataclass(frozen=True)
class ToolSpec:
    name: str
    description: str
    parameters: Mapping[str, str]
    required: tuple[str, ...]
    normalizers: Mapping[str, Callable[[Any], Any]]
    optional: tuple[str, ...] = ()

    def schema(self) -> dict[str, Any]:
        return {
            "name": self.name,
            "description": self.description,
            "parameters": {
                "type": "object",
                "properties": {
                    key: {"type": param_type, "description": self.parameters[key]}
                    for key, param_type in self.parameters.items()
                },
                "required": list(self.required),
            },
        }


_QUOTES = str.maketrans({"«": "", "»": "", "“": "", "”": "", '"': "", "'": ""})


def _squash(value: Any) -> str:
    text = unicodedata.normalize("NFKC", str(value))
    text = text.translate(_QUOTES).replace("\u0451", "\u0435").replace("\u00eb", "e")
    text = re.sub(r"\s+", " ", text).strip().lower()
    return text


_CITY_ALIASES = {
    "spb": "saint petersburg",
    "st petersburg": "saint petersburg",
    "st. petersburg": "saint petersburg",
    "sankt peterburg": "saint petersburg",
    "petersburg": "saint petersburg",
    "\u043f\u0438\u0442\u0435\u0440": "saint petersburg",
    "\u0441\u0430\u043d\u043a\u0442-\u043f\u0435\u0442\u0435\u0440\u0431\u0443\u0440\u0433": "saint petersburg",
    "\u0441\u043f\u0431": "saint petersburg",
    "nyc": "new york",
    "new york city": "new york",
    "\u043d\u044c\u044e-\u0439\u043e\u0440\u043a": "new york",
    "msk": "moscow",
    "\u043c\u043e\u0441\u043a\u0432\u0430": "moscow",
    "kiev": "kyiv",
    "\u043a\u0438\u0435\u0432": "kyiv",
    "\u043a\u0438\u0457\u0432": "kyiv",
    "\u0431\u0435\u0440\u043b\u0438\u043d": "berlin",
    "\u043b\u043e\u043d\u0434\u043e\u043d": "london",
    "\u0442\u043e\u043a\u0438\u043e": "tokyo",
    "\u043f\u0430\u0440\u0438\u0436": "paris",
    "\u0434\u0443\u0431\u0430\u0439": "dubai",
    "\u0430\u043b\u043c\u0430\u0442\u044b": "almaty",
    "\u043a\u0430\u0437\u0430\u043d\u044c": "kazan",
}

_LANGUAGE_ALIASES = {
    "english": "en",
    "eng": "en",
    "en-us": "en",
    "en-gb": "en",
    "\u0430\u043d\u0433\u043b\u0438\u0439\u0441\u043a\u0438\u0439": "en",
    "russian": "ru",
    "rus": "ru",
    "ru-ru": "ru",
    "\u0440\u0443\u0441\u0441\u043a\u0438\u0439": "ru",
    "german": "de",
    "\u043d\u0435\u043c\u0435\u0446\u043a\u0438\u0439": "de",
    "germany": "de",
    "spanish": "es",
    "\u0438\u0441\u043f\u0430\u043d\u0441\u043a\u0438\u0439": "es",
    "french": "fr",
    "\u0444\u0440\u0430\u043d\u0446\u0443\u0437\u0441\u043a\u0438\u0439": "fr",
    "italian": "it",
    "\u0438\u0442\u0430\u043b\u044c\u044f\u043d\u0441\u043a\u0438\u0439": "it",
    "japanese": "ja",
    "\u044f\u043f\u043e\u043d\u0441\u043a\u0438\u0439": "ja",
    "chinese": "zh",
    "\u043a\u0438\u0442\u0430\u0439\u0441\u043a\u0438\u0439": "zh",
    "portuguese": "pt",
    "\u043f\u043e\u0440\u0442\u0443\u0433\u0430\u043b\u044c\u0441\u043a\u0438\u0439": "pt",
    "turkish": "tr",
    "\u0442\u0443\u0440\u0435\u0446\u043a\u0438\u0439": "tr",
    "kazakh": "kk",
    "\u043a\u0430\u0437\u0430\u0445\u0441\u043a\u0438\u0439": "kk",
    "ukrainian": "uk",
    "\u0443\u043a\u0440\u0430\u0438\u043d\u0441\u043a\u0438\u0439": "uk",
    "arabic": "ar",
    "\u0430\u0440\u0430\u0431\u0441\u043a\u0438\u0439": "ar",
    "korean": "ko",
    "\u043a\u043e\u0440\u0435\u0439\u0441\u043a\u0438\u0439": "ko",
    "dutch": "nl",
    "\u0433\u043e\u043b\u043b\u0430\u043d\u0434\u0441\u043a\u0438\u0439": "nl",
    "polish": "pl",
    "\u043f\u043e\u043b\u044c\u0441\u043a\u0438\u0439": "pl",
    "hindi": "hi",
}

_CURRENCY_ALIASES = {
    "$": "USD",
    "usd": "USD",
    "us dollar": "USD",
    "us dollars": "USD",
    "dollar": "USD",
    "dollars": "USD",
    "\u0434\u043e\u043b\u043b\u0430\u0440": "USD",
    "\u0434\u043e\u043b\u043b\u0430\u0440\u043e\u0432": "USD",
    "usd.": "USD",
    "\u20ac": "EUR",
    "eur": "EUR",
    "euro": "EUR",
    "euros": "EUR",
    "\u0435\u0432\u0440\u043e": "EUR",
    "\u20bd": "RUB",
    "rub": "RUB",
    "ruble": "RUB",
    "rubles": "RUB",
    "rouble": "RUB",
    "\u0440\u0443\u0431": "RUB",
    "\u0440\u0443\u0431\u043b\u044c": "RUB",
    "\u0440\u0443\u0431\u043b\u0435\u0439": "RUB",
    "\u20b8": "KZT",
    "kzt": "KZT",
    "tenge": "KZT",
    "\u0442\u0435\u043d\u0433\u0435": "KZT",
    "\u00a3": "GBP",
    "gbp": "GBP",
    "pound": "GBP",
    "pounds": "GBP",
    "sterling": "GBP",
    "\u0444\u0443\u043d\u0442": "GBP",
    "\u00a5": "JPY",
    "jpy": "JPY",
    "yen": "JPY",
    "\u0438\u0435\u043d\u0430": "JPY",
    "\u00a5\u00a5": "CNY",
    "cny": "CNY",
    "rmb": "CNY",
    "yuan": "CNY",
    "\u044e\u0430\u043d\u044c": "CNY",
    "try": "TRY",
    "\u20ba": "TRY",
    "lira": "TRY",
    "\u043b\u0438\u0440\u0430": "TRY",
    "\u20b4": "UAH",
    "uah": "UAH",
    "hryvnia": "UAH",
    "\u0433\u0440\u0438\u0432\u043d\u0430": "UAH",
    "\u20b9": "INR",
    "inr": "INR",
    "rupee": "INR",
    "rupees": "INR",
    "chf": "CHF",
    "franc": "CHF",
    "cad": "CAD",
    "aud": "AUD",
    "brl": "BRL",
    "real": "BRL",
    "sek": "SEK",
    "nok": "NOK",
    "pln": "PLN",
    "zloty": "PLN",
    "czk": "CZK",
    "krone": "NOK",
}

_UNIT_ALIASES = {
    "km": "km",
    "kilometer": "km",
    "kilometers": "km",
    "kilometre": "km",
    "kilometres": "km",
    "\u043a\u043c": "km",
    "\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440": "km",
    "\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440\u043e\u0432": "km",
    "mile": "mi",
    "miles": "mi",
    "mi": "mi",
    "\u043c\u0438\u043b\u044f": "mi",
    "\u043c\u0438\u043b\u044c": "mi",
    "\u043c\u0438\u043b\u0438": "mi",
    "m": "m",
    "meter": "m",
    "meters": "m",
    "metre": "m",
    "\u043c\u0435\u0442\u0440": "m",
    "\u043c\u0435\u0442\u0440\u043e\u0432": "m",
    "ft": "ft",
    "foot": "ft",
    "feet": "ft",
    "\u0444\u0443\u0442": "ft",
    "\u0444\u0443\u0442\u043e\u0432": "ft",
    "cm": "cm",
    "centimeter": "cm",
    "centimeters": "cm",
    "\u0441\u043c": "cm",
    "inch": "in",
    "inches": "in",
    "in": "in",
    "\u0434\u044e\u0439\u043c": "in",
    "\u0434\u044e\u0439\u043c\u043e\u0432": "in",
    "mm": "mm",
    "millimeter": "mm",
    "\u043c\u043c": "mm",
    "kg": "kg",
    "kilogram": "kg",
    "kilograms": "kg",
    "\u043a\u0433": "kg",
    "kilogramm": "kg",
    "lb": "lb",
    "lbs": "lb",
    "pound": "lb",
    "pounds": "lb",
    "\u0444\u0443\u043d\u0442": "lb",
    "g": "g",
    "gram": "g",
    "grams": "g",
    "\u0433": "g",
    "\u0433\u0440\u0430\u043c\u043c": "g",
    "\u0433\u0440\u0430\u043c\u043c\u043e\u0432": "g",
    "c": "celsius",
    "celsius": "celsius",
    "\u00b0c": "celsius",
    "\u0433\u0440\u0430\u0434\u0443\u0441\u043e\u0432": "celsius",
    "\u0446\u0435\u043b\u044c\u0441\u0438\u0439": "celsius",
    "f": "fahrenheit",
    "fahrenheit": "fahrenheit",
    "\u00b0f": "fahrenheit",
    "farenheit": "fahrenheit",
    "kph": "km/h",
    "km/h": "km/h",
    "kmh": "km/h",
    "\u043a\u043c/\u0447": "km/h",
    "mph": "mph",
    "m/s": "m/s",
    "l": "l",
    "liter": "l",
    "liters": "l",
    "litre": "l",
    "\u043b": "l",
    "\u043b\u0438\u0442\u0440": "l",
    "\u043b\u0438\u0442\u0440\u043e\u0432": "l",
    "ml": "ml",
    "\u043c\u043b": "ml",
    "gal": "gal",
    "gallon": "gal",
    "gallons": "gal",
    "hour": "h",
    "hours": "h",
    "h": "h",
    "\u0447\u0430\u0441": "h",
    "\u0447\u0430\u0441\u043e\u0432": "h",
    "\u0447": "h",
    "minute": "min",
    "minutes": "min",
    "\u043c\u0438\u043d\u0443\u0442": "min",
    "\u043c\u0438\u043d": "min",
    "day": "day",
    "days": "day",
    "\u0434\u0435\u043d\u044c": "day",
    "\u0434\u043d\u0435\u0439": "day",
}

_TIMEZONE_ALIASES = {
    "utc": "UTC",
    "gmt": "UTC",
    "moscow": "Europe/Moscow",
    "msk": "Europe/Moscow",
    "moscow time": "Europe/Moscow",
    "\u043c\u043e\u0441\u043a\u0432\u0430": "Europe/Moscow",
    "saint petersburg": "Europe/Moscow",
    "\u043c\u0441\u043a": "Europe/Moscow",
    "berlin": "Europe/Berlin",
    "london": "Europe/London",
    "paris": "Europe/Paris",
    "new york": "America/New_York",
    "nyc": "America/New_York",
    "los angeles": "America/Los_Angeles",
    "tokyo": "Asia/Tokyo",
    "dubai": "Asia/Dubai",
    "almaty": "Asia/Almaty",
    "shanghai": "Asia/Shanghai",
    "sydney": "Australia/Sydney",
    "kyiv": "Europe/Kyiv",
    "kiev": "Europe/Kyiv",
    "kazan": "Europe/Moscow",
    "warsaw": "Europe/Warsaw",
    "istanbul": "Europe/Istanbul",
    "singapore": "Asia/Singapore",
}

_MATH_FUNCS: dict[str, Callable[..., float]] = {
    "sqrt": math.sqrt,
    "abs": abs,
    "round": round,
    "floor": math.floor,
    "ceil": math.ceil,
    "min": min,
    "max": max,
    "pow": pow,
    "sin": math.sin,
    "cos": math.cos,
    "tan": math.tan,
    "log": math.log,
    "log10": math.log10,
    "exp": math.exp,
    "pi": lambda: math.pi,
    "e": lambda: math.e,
}


def eval_expression(expression: Any) -> float | None:
    """Evaluate arithmetic safely. Returns None when the expression is not arithmetic."""
    if isinstance(expression, bool):
        return None
    if isinstance(expression, (int, float)):
        return float(expression)
    text = _squash(expression).replace("\u00d7", "*").replace("\u00f7", "/").replace("\u0445", "*")
    text = text.replace("^", "**").replace(",", "").replace("%", "/100")
    text = re.sub(r"(?<=\d)\s+(\d)", r"*\1", text)
    if not text or not re.fullmatch(r"[0-9a-z_+\-*/().\s]*", text):
        return None
    try:
        tree = ast.parse(text, mode="eval")
    except SyntaxError:
        return None

    def walk(node: ast.AST) -> float:
        if isinstance(node, ast.Expression):
            return walk(node.body)
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return float(node.value)
        if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
            value = walk(node.operand)
            return value if isinstance(node.op, ast.UAdd) else -value
        if isinstance(node, ast.BinOp):
            left, right = walk(node.left), walk(node.right)
            ops: dict[type, Callable[[float, float], float]] = {
                ast.Add: lambda a, b: a + b,
                ast.Sub: lambda a, b: a - b,
                ast.Mult: lambda a, b: a * b,
                ast.Div: lambda a, b: a / b,
                ast.Pow: lambda a, b: a**b,
                ast.Mod: lambda a, b: a % b,
                ast.FloorDiv: lambda a, b: a // b,
            }
            for node_type, op in ops.items():
                if isinstance(node.op, node_type):
                    return op(left, right)
            raise ValueError("operator")
        if isinstance(node, ast.Call):
            if not isinstance(node.func, ast.Name):
                raise ValueError("call")
            func = _MATH_FUNCS.get(node.func.id)
            if func is None or node.keywords:
                raise ValueError("function")
            return float(func(*[walk(arg) for arg in node.args]))
        if isinstance(node, ast.Name):
            func = _MATH_FUNCS.get(node.id)
            if func is None:
                raise ValueError("name")
            return float(func())
        raise ValueError("node")

    try:
        result = walk(tree)
    except Exception:
        return None
    if not math.isfinite(result):
        return None
    return result


def norm_number(value: Any) -> float | None:
    if isinstance(value, bool):
        return None
    if isinstance(value, (int, float)):
        return float(value)
    text = _squash(value).replace(",", ".").replace(" ", "")
    text = re.sub(r"[^\d.\-e+]", "", text)
    if not text:
        return None
    try:
        return float(text)
    except ValueError:
        return None


def norm_expression(value: Any) -> Any:
    evaluated = eval_expression(value)
    if evaluated is not None:
        return round(evaluated, 6)
    return _squash(value).replace(" ", "")


def norm_from_aliases(aliases: Mapping[str, str], fallback: Callable[[str], str] | None = None) -> Callable[[Any], Any]:
    table = {_squash(key): _squash(value) for key, value in aliases.items()}
    tail: Callable[[str], str] = fallback or (lambda text: text)

    def normalizer(value: Any) -> Any:
        key = _squash(value)
        key = re.sub(r"^(в|to|from|into|in)\s+", "", key).strip()
        return table.get(key, tail(key))

    return normalizer


_norm_city = norm_from_aliases(_CITY_ALIASES, lambda t: t.rstrip(".,!?"))
_norm_language = norm_from_aliases(_LANGUAGE_ALIASES)
_norm_currency = norm_from_aliases(_CURRENCY_ALIASES)
_norm_unit = norm_from_aliases(_UNIT_ALIASES)
_norm_timezone = norm_from_aliases(_TIMEZONE_ALIASES)
_norm_text = lambda value: re.sub(r"\s+", " ", _squash(value)).strip(" .,!?\"'")


def norm_query(value: Any) -> Any:
    text = _norm_text(value)
    text = re.sub(r"[^\w\s\u0400-\u04ff]", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def norm_seconds(value: Any) -> Any:
    number = norm_number(value)
    if number is None:
        return _norm_text(value)
    return int(round(number))


REGISTRY: dict[str, ToolSpec] = {
    "calculator": ToolSpec(
        name="calculator",
        description="Evaluates a mathematical expression and returns the numeric result.",
        parameters={
            "expression": "string: the arithmetic expression to evaluate, e.g. '(45 + 12) * 3'"
        },
        required=("expression",),
        normalizers={"expression": norm_expression},
    ),
    "get_weather": ToolSpec(
        name="get_weather",
        description="Returns the current weather for a city.",
        parameters={
            "city": "string: city name",
            "unit": "string, optional: 'celsius' or 'fahrenheit'",
        },
        required=("city",),
        optional=("unit",),
        normalizers={"city": _norm_city, "unit": _norm_unit},
    ),
    "web_search": ToolSpec(
        name="web_search",
        description="Searches the web and returns ranked results for a query.",
        parameters={"query": "string: search query"},
        required=("query",),
        normalizers={"query": norm_query},
    ),
    "translate": ToolSpec(
        name="translate",
        description="Translates text into a target language.",
        parameters={
            "text": "string: the text to translate",
            "target_language": "string: ISO 639-1 code or language name",
        },
        required=("text", "target_language"),
        normalizers={"text": _norm_text, "target_language": _norm_language},
    ),
    "convert_currency": ToolSpec(
        name="convert_currency",
        description="Converts an amount from one currency to another using current rates.",
        parameters={
            "amount": "number: amount to convert",
            "from_currency": "string: ISO 4217 code or currency name",
            "to_currency": "string: ISO 4217 code or currency name",
        },
        required=("amount", "from_currency", "to_currency"),
        normalizers={
            "amount": norm_number,
            "from_currency": _norm_currency,
            "to_currency": _norm_currency,
        },
    ),
    "convert_units": ToolSpec(
        name="convert_units",
        description="Converts a value between measurement units.",
        parameters={
            "value": "number: value to convert",
            "from_unit": "string: source unit",
            "to_unit": "string: target unit",
        },
        required=("value", "from_unit", "to_unit"),
        normalizers={"value": norm_number, "from_unit": _norm_unit, "to_unit": _norm_unit},
    ),
    "set_timer": ToolSpec(
        name="set_timer",
        description="Starts a countdown timer for the given duration in seconds.",
        parameters={"seconds": "integer: duration of the timer in seconds"},
        required=("seconds",),
        normalizers={"seconds": norm_seconds},
    ),
    "save_note": ToolSpec(
        name="save_note",
        description="Saves a note with a title and body text.",
        parameters={"title": "string: short note title", "content": "string: note body"},
        required=("title", "content"),
        normalizers={"title": _norm_text, "content": _norm_text},
    ),
    "get_time": ToolSpec(
        name="get_time",
        description="Returns the current date and time in a given timezone.",
        parameters={"timezone": "string: IANA timezone name or city"},
        required=("timezone",),
        normalizers={"timezone": _norm_timezone},
    ),
}

TOOL_NAMES: tuple[str, ...] = tuple(REGISTRY)

# Handles seen in the wild that mean the same tool.
NAME_ALIASES: dict[str, str] = {
    "calc": "calculator",
    "calculate": "calculator",
    "math": "calculator",
    "evaluate_expression": "calculator",
    "weather": "get_weather",
    "weather_lookup": "get_weather",
    "get_current_weather": "get_weather",
    "search": "web_search",
    "search_web": "web_search",
    "google_search": "web_search",
    "currency_converter": "convert_currency",
    "convert": "convert_currency",
    "exchange_rate": "convert_currency",
    "unit_conversion": "convert_units",
    "convert_measurement": "convert_units",
    "timer": "set_timer",
    "create_timer": "set_timer",
    "start_timer": "set_timer",
    "note": "save_note",
    "add_note": "save_note",
    "create_note": "save_note",
    "time": "get_time",
    "current_time": "get_time",
    "get_current_time": "get_time",
    "translation": "translate",
}


def canonical_name(name: Any) -> str:
    key = _squash(name)
    return NAME_ALIASES.get(key, key)


def tools_for(names: Sequence[str]) -> tuple[ToolSpec, ...]:
    return tuple(REGISTRY[name] for name in names if name in REGISTRY)


def render_tools_json(specs: Sequence[ToolSpec]) -> str:
    payload = {"tools": [spec.schema() for spec in specs]}
    return json.dumps(payload, ensure_ascii=False, indent=2)


def render_tools_xml(specs: Sequence[ToolSpec]) -> str:
    lines: list[str] = []
    for spec in specs:
        lines.append(f"<tool name=\"{spec.name}\">")
        lines.append(f"  <description>{spec.description}</description>")
        lines.append("  <parameters>")
        for key, param_type in spec.parameters.items():
            marker = " required" if key in spec.required else ""
            lines.append(f"    <parameter name=\"{key}\" type=\"{param_type.split(':')[0]}\"{marker}/>")
        lines.append("  </parameters>")
        lines.append("</tool>")
    return "\n".join(lines)


def render_tools_plain(specs: Sequence[ToolSpec]) -> str:
    lines: list[str] = []
    for spec in specs:
        params = ", ".join(
            f"{key}{'' if key in spec.required else ' (optional)'}" for key in spec.parameters
        )
        lines.append(f"- {spec.name}({params}): {spec.description}")
    return "\n".join(lines)


def render_tools(specs: Sequence[ToolSpec], protocol: Protocol) -> str:
    return {
        "json": render_tools_json,
        "xml": render_tools_xml,
        "plain": render_tools_plain,
    }[protocol](specs)