@stll/agent-input 0.0.1-placeholder.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1974 @@
1
+ import { foldToAscii } from "@stll/text-normalize";
2
+ import { COUNTRY_ALPHA3_BY_CODE, COUNTRY_CODES, countryCodeFromAlpha3, isCountryCode } from "@stll/country-codes";
3
+ import { DATE_FORMAT_STYLES } from "@stll/template-conditions";
4
+ import { Result, panic } from "better-result";
5
+ import { Temporal, parsePlainDate } from "@stll/time";
6
+ //#region src/absent.ts
7
+ /**
8
+ * Placeholders on optional filters.
9
+ *
10
+ * A model fills every slot a schema shows it, so a filter it means to leave
11
+ * unset still arrives as `"any"`, `"-"` or `"none"`. Those words name no
12
+ * court, no type, no record: read as a value they match nothing and the call
13
+ * returns an empty page the model then explains away. The set is closed and
14
+ * short on purpose; a word outside it is a value and goes to the kind's own
15
+ * reader.
16
+ *
17
+ * This is not for free text. `"none"` is a fine answer to a question and `"-"`
18
+ * a fine clause body, so the caller decides which inputs a placeholder can
19
+ * stand in for.
20
+ */
21
+ /** The words, already in the folded lowercase form they are compared in. */
22
+ const ABSENT_PLACEHOLDERS = [
23
+ "-",
24
+ "--",
25
+ "–",
26
+ "—",
27
+ "*",
28
+ "all",
29
+ "any",
30
+ "none",
31
+ "null",
32
+ "nil",
33
+ "undefined",
34
+ "n/a",
35
+ "(none)",
36
+ "<none>",
37
+ "(any)",
38
+ "(all)"
39
+ ];
40
+ const PLACEHOLDERS = new Set(ABSENT_PLACEHOLDERS);
41
+ /** Whether a string stands for "no value" on an optional filter: blank, or one
42
+ * of the placeholder words in any case and spacing. */
43
+ const isAbsentPlaceholder = (input) => {
44
+ if (typeof input !== "string") return false;
45
+ const trimmed = input.trim();
46
+ return trimmed === "" || PLACEHOLDERS.has(foldToAscii(trimmed).toLowerCase());
47
+ };
48
+ //#endregion
49
+ //#region src/normalized.ts
50
+ /** Wire values carry matter content and personal data, so an echo back to the
51
+ * model is bounded to the length of a spelling. */
52
+ const MAX_RECEIVED_CHARS = 80;
53
+ /** The input as one quoted token: what the agent sent, ready to drop into a
54
+ * sentence. */
55
+ const describeInput = (input) => {
56
+ const spelled = typeof input === "function" || typeof input === "symbol" ? void 0 : JSON.stringify(input);
57
+ const rendered = input === void 0 ? "undefined" : spelled ?? `a ${typeof input}`;
58
+ return rendered.length <= MAX_RECEIVED_CHARS ? rendered : `${rendered.slice(0, MAX_RECEIVED_CHARS)}…`;
59
+ };
60
+ const readValue = (value) => ({
61
+ ok: true,
62
+ value
63
+ });
64
+ /**
65
+ * The canonical value, plus the "read X as Y" note when the agent's spelling
66
+ * was not already the canonical one. That sentence is spelled here alone, so
67
+ * every kind reports a coercion the same way. `canonical` overrides how the
68
+ * result is rendered in the note, for a kind whose canonical spelling is not
69
+ * the JSON form of its value.
70
+ */
71
+ const readValueAs = (input, value, canonical = describeInput(value)) => {
72
+ const received = describeInput(input);
73
+ return received === canonical ? {
74
+ ok: true,
75
+ value
76
+ } : {
77
+ ok: true,
78
+ value,
79
+ note: `Read ${received} as ${canonical}.`
80
+ };
81
+ };
82
+ const askForFix = ({ input, expected, hint }) => ({
83
+ ok: false,
84
+ received: describeInput(input),
85
+ expected,
86
+ hint
87
+ });
88
+ /** The ask as one sentence, for a caller whose issue shape carries a message
89
+ * beside the hint. */
90
+ const askSentence = (ask) => `${ask.received} is not ${ask.expected}.`;
91
+ /** The absent outcome, with the one "read X as no value" sentence every kind
92
+ * reports it with. `reason` says why, when the spelling alone does not. */
93
+ const readAsAbsent = (input, reason) => {
94
+ const received = describeInput(input);
95
+ return {
96
+ ok: "absent",
97
+ received,
98
+ note: reason === void 0 ? `Read ${received} as no value.` : `Read ${received} as no value: ${reason}.`
99
+ };
100
+ };
101
+ //#endregion
102
+ //#region src/boolean.ts
103
+ /**
104
+ * Yes/no answers on the agent wire.
105
+ *
106
+ * A model asked for a boolean answers in the language of the document it is
107
+ * drafting as often as in JSON, so the words below are the ones that occur in
108
+ * the workspace's languages plus the checkbox vocabulary. The set is closed:
109
+ * anything outside it asks rather than falling back to JavaScript truthiness,
110
+ * where `"false"` and `"ne"` are both true.
111
+ */
112
+ const BOOLEAN_EXPECTED = "a yes/no answer";
113
+ const BOOLEAN_HINT = "Send true or false as a JSON boolean; the words yes/no, y/n, 1/0, on/off, ano/ne, tak/nie, ja/nein and checked/unchecked are read as well.";
114
+ const TRUE_WORDS = [
115
+ "true",
116
+ "yes",
117
+ "y",
118
+ "1",
119
+ "on",
120
+ "ano",
121
+ "tak",
122
+ "ja",
123
+ "checked"
124
+ ];
125
+ const FALSE_WORDS = [
126
+ "false",
127
+ "no",
128
+ "n",
129
+ "0",
130
+ "off",
131
+ "ne",
132
+ "nie",
133
+ "nein",
134
+ "unchecked"
135
+ ];
136
+ const WORDS = new Map([...TRUE_WORDS.map((word) => [word, true]), ...FALSE_WORDS.map((word) => [word, false])]);
137
+ /** Read a yes/no answer an agent spelled its own way. */
138
+ const normalizeBoolean = (input) => {
139
+ if (typeof input === "boolean") return readValueAs(input, input);
140
+ if (typeof input === "number") {
141
+ if (input === 1 || input === 0) return readValueAs(input, input === 1);
142
+ return askForFix({
143
+ input,
144
+ expected: BOOLEAN_EXPECTED,
145
+ hint: BOOLEAN_HINT
146
+ });
147
+ }
148
+ if (typeof input !== "string") return askForFix({
149
+ input,
150
+ expected: BOOLEAN_EXPECTED,
151
+ hint: BOOLEAN_HINT
152
+ });
153
+ const word = WORDS.get(foldToAscii(input.trim()).toLowerCase());
154
+ if (word === void 0) return askForFix({
155
+ input,
156
+ expected: BOOLEAN_EXPECTED,
157
+ hint: BOOLEAN_HINT
158
+ });
159
+ return readValueAs(input, word);
160
+ };
161
+ //#endregion
162
+ //#region src/country.ts
163
+ /**
164
+ * Jurisdictions that publish law without being ISO 3166-1 countries.
165
+ *
166
+ * The EU is the one this corpus holds: the Court of Justice and the Official
167
+ * Journal are supranational, and legal corpora and ELI identifiers spell that
168
+ * jurisdiction `EU`. CLDR carries `EU` as a region, so its names arrive from
169
+ * the same place as a country's, and ISO assigns it neither alpha-2 nor
170
+ * alpha-3, so `EU` is both.
171
+ */
172
+ const SUPRANATIONAL_CODES = ["EU"];
173
+ /**
174
+ * The languages whose spellings are read.
175
+ *
176
+ * These are the languages this corpus's jurisdictions legislate and adjudicate
177
+ * in, plus English, which every model falls back to. A locale added here widens
178
+ * what is accepted and can only introduce an ambiguity that the index reports
179
+ * rather than guesses.
180
+ */
181
+ const NAME_LOCALES = [
182
+ "en",
183
+ "cs",
184
+ "sk",
185
+ "pl",
186
+ "de",
187
+ "hu"
188
+ ];
189
+ /**
190
+ * Official long forms CLDR does not carry, keyed by CLDR region.
191
+ *
192
+ * CLDR holds the short name a locale uses day to day (`Česko`, `Slovensko`),
193
+ * while a model drafting a legal document reaches for the constitutional name.
194
+ * Listed are the jurisdictions this corpus serves, plus Germany, whose language
195
+ * the corpus serves and whose law gets asked about in it. Each entry is in
196
+ * English or in one of those languages: an entry earns its place by being a
197
+ * name some surface actually receives, not by completeness. Case, spacing and
198
+ * diacritics need no entries of their own, because the index keys on the folded
199
+ * form.
200
+ */
201
+ const OFFICIAL_NAMES = {
202
+ AT: [
203
+ "Republic of Austria",
204
+ "Republik Österreich",
205
+ "Rakouská republika"
206
+ ],
207
+ CZ: [
208
+ "Czech Republic",
209
+ "Česká republika",
210
+ "Tschechische Republik",
211
+ "Republika Czeska"
212
+ ],
213
+ DE: ["Federal Republic of Germany", "Bundesrepublik Deutschland"],
214
+ HU: ["Republic of Hungary", "Magyar Köztársaság"],
215
+ PL: [
216
+ "Republic of Poland",
217
+ "Rzeczpospolita Polska",
218
+ "Polská republika"
219
+ ],
220
+ SK: [
221
+ "Slovak Republic",
222
+ "Slovenská republika",
223
+ "Slowakische Republik",
224
+ "Republika Słowacka"
225
+ ],
226
+ EU: ["European Communities"]
227
+ };
228
+ /**
229
+ * Tokens that name two countries at once.
230
+ *
231
+ * Each maps to the readings the ask must name. A token here must not be a valid
232
+ * alpha-2 code: the codes are read as themselves, and this table exists for the
233
+ * spellings that are not codes at all.
234
+ */
235
+ const AMBIGUOUS_TOKENS = /* @__PURE__ */ new Map([["cs", ["CZE", "SVK"]]]);
236
+ /** The comparison form of a name: case, diacritics and spacing carry no
237
+ * meaning in a country name, so none of them reach the index key. */
238
+ const fold$2 = (value) => foldToAscii(value.trim()).toLowerCase().replaceAll(/\s+/gu, " ");
239
+ /**
240
+ * The name index, built once on first read.
241
+ *
242
+ * `Intl.DisplayNames` is thousands of lookups across every region and locale,
243
+ * so it is deferred rather than run at import: a module that only ever reads a
244
+ * code should not pay for the names, and a shared module must not do work when
245
+ * it is loaded.
246
+ */
247
+ let cachedIndex = null;
248
+ const buildIndex = () => {
249
+ const regions = [...COUNTRY_CODES, ...SUPRANATIONAL_CODES];
250
+ const collected = /* @__PURE__ */ new Map();
251
+ const add = (name, region) => {
252
+ const key = fold$2(name);
253
+ if (key.length === 0) return;
254
+ const existing = collected.get(key);
255
+ if (existing === void 0) {
256
+ collected.set(key, [region]);
257
+ return;
258
+ }
259
+ if (!existing.includes(region)) existing.push(region);
260
+ };
261
+ for (const locale of NAME_LOCALES) for (const style of ["long", "short"]) {
262
+ const display = new Intl.DisplayNames([locale], {
263
+ type: "region",
264
+ style,
265
+ fallback: "none"
266
+ });
267
+ for (const region of regions) {
268
+ const name = display.of(region);
269
+ if (name !== void 0 && name !== region) add(name, region);
270
+ }
271
+ }
272
+ for (const [region, names] of Object.entries(OFFICIAL_NAMES)) for (const name of names) add(name, region);
273
+ return { regionsByName: collected };
274
+ };
275
+ const index = () => {
276
+ cachedIndex ??= buildIndex();
277
+ return cachedIndex;
278
+ };
279
+ const isSupranational = (value) => SUPRANATIONAL_CODES.some((code) => code === value);
280
+ /** The canonical pair a CLDR region names. */
281
+ const valueOfRegion = (region) => {
282
+ if (isSupranational(region)) return {
283
+ alpha3: region,
284
+ alpha2: region
285
+ };
286
+ return isCountryCode(region) ? {
287
+ alpha3: COUNTRY_ALPHA3_BY_CODE[region],
288
+ alpha2: region
289
+ } : null;
290
+ };
291
+ /** The canonical pair a code names, in either ISO length. */
292
+ const valueOfCode = (upper) => {
293
+ if (isSupranational(upper)) return {
294
+ alpha3: upper,
295
+ alpha2: upper
296
+ };
297
+ const fromAlpha3 = countryCodeFromAlpha3(upper);
298
+ if (fromAlpha3 !== null) return {
299
+ alpha3: COUNTRY_ALPHA3_BY_CODE[fromAlpha3],
300
+ alpha2: fromAlpha3
301
+ };
302
+ return isCountryCode(upper) ? {
303
+ alpha3: COUNTRY_ALPHA3_BY_CODE[upper],
304
+ alpha2: upper
305
+ } : null;
306
+ };
307
+ /**
308
+ * The longest country spelling a wire schema accepts.
309
+ *
310
+ * A country's own name is a spelling this reader reads, so the bound is a
311
+ * name's length rather than a code's: `Federal Republic of Germany` is a
312
+ * country input, and a schema capped at three characters was what turned it
313
+ * into a rejection before the reader ever saw it. It lives with the reader so
314
+ * the declared bound and what can be read cannot drift apart.
315
+ */
316
+ const COUNTRY_INPUT_MAX_CHARS = 64;
317
+ const COUNTRY_EXPECTED = "a country";
318
+ /** The code a caller keeping `spelling` stores. */
319
+ const countryCodeIn = (value, spelling = "alpha-3") => spelling === "alpha-2" ? value.alpha2 : value.alpha3;
320
+ /**
321
+ * How the canonical value is quoted in a coercion note.
322
+ *
323
+ * The note compares against the spelling the agent sent, which is the quoted
324
+ * JSON of a string, so the canonical code is quoted the same way. Without it,
325
+ * `"CZE"` would be reported as read into `CZE` and a canonical input would not
326
+ * be the fixed point it is.
327
+ */
328
+ const canonicalSpelling = (value, options) => JSON.stringify(countryCodeIn(value, options.spelling));
329
+ const admittedSentence = (admitted) => admitted === void 0 || admitted.length === 0 ? "" : ` Admitted: ${admitted.join(", ")}.`;
330
+ /** Where to make the correction, as far as the caller told us. */
331
+ const target = ({ tool, parameter }) => {
332
+ const property = parameter ?? "country";
333
+ return tool === void 0 ? `\`${property}\`` : `\`${property}\` on ${tool}`;
334
+ };
335
+ const expectedWith = (options) => {
336
+ const admitted = options.admitted;
337
+ return admitted === void 0 || admitted.length === 0 ? COUNTRY_EXPECTED : `a country code, one of ${admitted.join(", ")}`;
338
+ };
339
+ /** The spellings the reader accepts, as one clause a hint drops in. */
340
+ const ACCEPTED_SPELLINGS = "an ISO 3166-1 code, alpha-3 or alpha-2 (\"CZE\", \"CZ\"); the country's name in English or in a language the corpus serves (\"Czechia\", \"Česko\", \"Česká republika\") is read as well.";
341
+ const spellingHint = (options) => `Set ${target(options)} to ${ACCEPTED_SPELLINGS}${admittedSentence(options.admitted)}`;
342
+ /**
343
+ * Read a country an agent spelled its own way.
344
+ *
345
+ * An absent value asks rather than defaulting: a corpus country decides which
346
+ * body of law is searched, and picking one on the model's behalf answers a
347
+ * question about Czech law with Slovak decisions.
348
+ */
349
+ const normalizeCountry = (input, options = {}) => {
350
+ if (input === void 0 || input === null || typeof input === "string" && input.trim().length === 0) return askForFix({
351
+ input,
352
+ expected: expectedWith(options),
353
+ hint: `${target(options)} is required. ${spellingHint(options)}`
354
+ });
355
+ if (typeof input !== "string") return askForFix({
356
+ input,
357
+ expected: expectedWith(options),
358
+ hint: spellingHint(options)
359
+ });
360
+ const collapsed = input.trim().replaceAll(/\s+/gu, " ");
361
+ const byCode = valueOfCode(collapsed.toUpperCase());
362
+ if (byCode !== null) return readValueAs(input, byCode, canonicalSpelling(byCode, options));
363
+ const key = fold$2(collapsed);
364
+ const ambiguous = AMBIGUOUS_TOKENS.get(key);
365
+ if (ambiguous !== void 0) return askForFix({
366
+ input,
367
+ expected: expectedWith(options),
368
+ hint: `"${collapsed}" names more than one country here: ${ambiguous.join(" or ")}. Set ${target(options)} to the one you mean.${admittedSentence(options.admitted)}`
369
+ });
370
+ const regions = index().regionsByName.get(key);
371
+ const single = regions?.length === 1 ? regions.at(0) : void 0;
372
+ if (single !== void 0) {
373
+ const value = valueOfRegion(single);
374
+ if (value !== null) return readValueAs(input, value, canonicalSpelling(value, options));
375
+ }
376
+ if (regions !== void 0 && regions.length > 1) {
377
+ const readings = regions.map((region) => valueOfRegion(region)?.alpha3).filter((alpha3) => alpha3 !== void 0);
378
+ return askForFix({
379
+ input,
380
+ expected: expectedWith(options),
381
+ hint: `"${collapsed}" names more than one country here: ${readings.join(" or ")}. Set ${target(options)} to the one you mean.${admittedSentence(options.admitted)}`
382
+ });
383
+ }
384
+ return askForFix({
385
+ input,
386
+ expected: expectedWith(options),
387
+ hint: spellingHint(options)
388
+ });
389
+ };
390
+ //#endregion
391
+ //#region src/enum-value.ts
392
+ /**
393
+ * Closed vocabularies on the agent wire: a style name, a registry slug, an
394
+ * input type, a select option.
395
+ *
396
+ * Case and surrounding whitespace never carry meaning in a closed set, so they
397
+ * are read. A near miss is not: `"lookup"` for `"lookups"` is one edit away
398
+ * from a real value and also one edit away from a value the model invented, so
399
+ * it asks and names the closest allowed value instead of guessing which.
400
+ */
401
+ /** How far a spelling may sit from an allowed value and still be reported as
402
+ * "did you mean". Beyond one edit the closest value is noise. */
403
+ const NEAR_MISS_DISTANCE = 1;
404
+ const fold$1 = (value) => foldToAscii(value.trim()).toLowerCase();
405
+ const quote = (values) => values.map((value) => `"${value}"`).join(", ");
406
+ /**
407
+ * Levenshtein distance, abandoned once it exceeds `limit`. Only the "did you
408
+ * mean" ranking reads it, so the exact distance beyond the limit is not
409
+ * interesting and the early exit keeps a long value cheap.
410
+ */
411
+ const editDistanceWithin = (left, right, limit) => {
412
+ if (Math.abs(left.length - right.length) > limit) return limit + 1;
413
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
414
+ for (let row = 1; row <= left.length; row += 1) {
415
+ const current = [row];
416
+ let best = row;
417
+ for (let column = 1; column <= right.length; column += 1) {
418
+ const substitution = (previous[column - 1] ?? 0) + (left[row - 1] === right[column - 1] ? 0 : 1);
419
+ const distance = Math.min(substitution, (previous[column] ?? 0) + 1, (current[column - 1] ?? 0) + 1);
420
+ current.push(distance);
421
+ best = Math.min(best, distance);
422
+ }
423
+ if (best > limit) return limit + 1;
424
+ previous = current;
425
+ }
426
+ return previous[right.length] ?? limit + 1;
427
+ };
428
+ /**
429
+ * Read one value of a closed set. An exact hit is taken verbatim; a hit that
430
+ * differs only in case, spacing, or diacritics is read with a note; a value one
431
+ * edit from an allowed one asks and names it; anything else asks with the whole
432
+ * set, which is short enough to copy from.
433
+ */
434
+ const normalizeEnumValue = (input, allowed, options) => {
435
+ const label = options?.label ?? "The allowed values";
436
+ const expected = options?.expected ?? "one of a closed set of values";
437
+ const listed = `${label} are ${quote(allowed)}.`;
438
+ if (typeof input !== "string") return askForFix({
439
+ input,
440
+ expected,
441
+ hint: listed
442
+ });
443
+ const exact = allowed.find((value) => value === input);
444
+ if (exact !== void 0) return readValueAs(input, exact);
445
+ const folded = fold$1(input);
446
+ const loose = allowed.find((value) => fold$1(value) === folded);
447
+ if (loose !== void 0) return readValueAs(input, loose);
448
+ const closest = allowed.find((value) => editDistanceWithin(folded, fold$1(value), NEAR_MISS_DISTANCE) <= NEAR_MISS_DISTANCE);
449
+ return askForFix({
450
+ input,
451
+ expected,
452
+ hint: closest === void 0 ? listed : `Did you mean "${closest}"? ${listed}`
453
+ });
454
+ };
455
+ //#endregion
456
+ //#region src/locale.ts
457
+ /**
458
+ * Locale tags on the agent wire.
459
+ *
460
+ * `Intl` is the authority on both halves: it refuses a structurally malformed
461
+ * tag (a well-formed but unknown one passes and merely falls back at format
462
+ * time) and it spells the canonical form. Underscores are the ICU/POSIX
463
+ * spelling of the same tag, and case carries no meaning, so `cs_cz` and
464
+ * `cs-CZ` are one locale — but only the canonical spelling may be stored,
465
+ * because `new Intl.DateTimeFormat("cs_CZ")` throws.
466
+ */
467
+ const LOCALE_EXPECTED = "a BCP-47 language tag";
468
+ const LOCALE_HINT = "Write the tag as language or language-REGION: \"cs\", \"pl\", \"en-GB\", \"pt-BR\".";
469
+ /** The canonical spelling of a well-formed tag, or null. `Intl` throws a
470
+ * RangeError on a malformed tag rather than reporting it. */
471
+ const canonicalize = (candidate) => {
472
+ const canonical = Result.try({
473
+ try: () => Intl.getCanonicalLocales(candidate),
474
+ catch: (cause) => cause
475
+ });
476
+ return canonical.isOk() ? canonical.value.at(0) ?? null : null;
477
+ };
478
+ /**
479
+ * Whether a tag is already the spelling `Intl` accepts. This is the check a
480
+ * stored or advertised locale passes: a value that reaches
481
+ * `Intl.DateTimeFormat` at fill time must not be able to make it throw, so the
482
+ * leniency below stops at the boundary and never reaches persistence.
483
+ */
484
+ const isPlausibleLocale = (value) => canonicalize(value) !== null;
485
+ /** Read a locale an agent spelled its own way, canonically. */
486
+ const normalizeLocale = (input) => {
487
+ if (typeof input !== "string") return askForFix({
488
+ input,
489
+ expected: LOCALE_EXPECTED,
490
+ hint: LOCALE_HINT
491
+ });
492
+ const canonical = canonicalize(input.trim().replaceAll("_", "-"));
493
+ if (canonical === null) return askForFix({
494
+ input,
495
+ expected: LOCALE_EXPECTED,
496
+ hint: LOCALE_HINT
497
+ });
498
+ return readValueAs(input, canonical);
499
+ };
500
+ //#endregion
501
+ //#region src/date-format-spec.ts
502
+ /**
503
+ * How a date field renders: a locale and a style.
504
+ *
505
+ * The same pair reaches the engine two ways — as one string in a marker's
506
+ * `date("pl-long")` filter, and as a `{ locale, style }` object on the tool
507
+ * wire — so both are read here and both produce the canonical pair. A locale
508
+ * carries its own hyphens (`en-GB`, `pt-BR`), so only a final segment that
509
+ * names a style is one, and the style test runs first: `date("iso")` names a
510
+ * style, not a three-letter language tag. A bare style asks for the locale it
511
+ * is missing, except `iso`, whose output has none.
512
+ */
513
+ /** Narrow `unknown` to a plain object (not null, not array). */
514
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
515
+ /** What a spec means when it names only a locale. */
516
+ const DEFAULT_DATE_FORMAT_STYLE = "long";
517
+ const quoted = (values) => values.map((value) => `"${value}"`).join(", ");
518
+ const DATE_FORMAT_SPEC_EXPECTED = "a locale with an optional style";
519
+ const DATE_FORMAT_SPEC_HINT = `Write the BCP-47 locale, optionally suffixed with a style: "pl", "cs-CZ", "pl-long", "en-GB-short". The styles are ${quoted(DATE_FORMAT_STYLES)} and the default is "${DEFAULT_DATE_FORMAT_STYLE}"; "iso" stands alone, since an ISO date reads the same in every language.`;
520
+ /**
521
+ * Style names a model reaches for that are not the catalogue's own. `full` is
522
+ * `Intl`'s longest date style and `numeric` its all-digit one, so each names
523
+ * exactly one of ours.
524
+ */
525
+ const STYLE_SYNONYMS = /* @__PURE__ */ new Map([["full", "long"], ["numeric", "short"]]);
526
+ const readStyle = (input) => {
527
+ const synonym = typeof input === "string" ? STYLE_SYNONYMS.get(input.trim().toLowerCase()) : void 0;
528
+ return normalizeEnumValue(synonym ?? input, DATE_FORMAT_STYLES, {
529
+ label: "The styles",
530
+ expected: "a date style"
531
+ });
532
+ };
533
+ const specAsk = (input) => askForFix({
534
+ input,
535
+ expected: DATE_FORMAT_SPEC_EXPECTED,
536
+ hint: DATE_FORMAT_SPEC_HINT
537
+ });
538
+ /** Split a spec into the locale text and the style it names, if any. Only a
539
+ * final segment that reads as a style is one; everything else is the tag. */
540
+ const splitSpec = (spec) => {
541
+ const cut = Math.max(spec.lastIndexOf("-"), spec.lastIndexOf("_"));
542
+ if (cut <= 0) return {
543
+ localeText: spec,
544
+ style: null
545
+ };
546
+ const tail = readStyle(spec.slice(cut + 1));
547
+ return tail.ok ? {
548
+ localeText: spec.slice(0, cut),
549
+ style: tail.value
550
+ } : {
551
+ localeText: spec,
552
+ style: null
553
+ };
554
+ };
555
+ /**
556
+ * The one style whose output names no language: `2028-06-13` is the same
557
+ * string in every locale, so `iso` on its own is a complete format. The pair
558
+ * still carries a locale because the rendering shape has one, and `en` is the
559
+ * carrier that never reaches a rendered date.
560
+ */
561
+ const LOCALE_FREE_STYLE = "iso";
562
+ const LOCALE_FREE_STYLE_LOCALE = "en";
563
+ /** `pl-long`, `cs`, `en-GB`, `cs_CZ`, `en-GB-short`, `pl-full`, `iso`. */
564
+ const readStringSpec = (input) => {
565
+ const spec = input.trim();
566
+ if (spec === "") return specAsk(input);
567
+ const bare = readStyle(spec);
568
+ if (bare.ok) return bare.value === LOCALE_FREE_STYLE ? readValueAs(input, {
569
+ locale: LOCALE_FREE_STYLE_LOCALE,
570
+ style: bare.value
571
+ }, `"${LOCALE_FREE_STYLE}"`) : specAsk(input);
572
+ const { localeText, style } = splitSpec(spec);
573
+ const locale = normalizeLocale(localeText);
574
+ if (!locale.ok) return specAsk(input);
575
+ const value = {
576
+ locale: locale.value,
577
+ style: style ?? DEFAULT_DATE_FORMAT_STYLE
578
+ };
579
+ return readValueAs(input, value, style === null ? `"${value.locale}"` : `"${value.locale}-${value.style}"`);
580
+ };
581
+ const SPEC_KEYS = ["locale", "style"];
582
+ const entryFor = (entries, name) => entries.find(([key]) => key.toLowerCase() === name)?.[1];
583
+ /** `{ locale, style }` with either key casing, and `style` optional. */
584
+ const readObjectSpec = (input) => {
585
+ const entries = Object.entries(input);
586
+ if (entries.filter(([key]) => !SPEC_KEYS.some((name) => name === key.toLowerCase())).length > 0) return askForFix({
587
+ input,
588
+ expected: DATE_FORMAT_SPEC_EXPECTED,
589
+ hint: `A date format carries ${quoted([...SPEC_KEYS])} and nothing else. ${DATE_FORMAT_SPEC_HINT}`
590
+ });
591
+ const rawLocale = entryFor(entries, "locale");
592
+ if (rawLocale === void 0 || rawLocale === null) return specAsk(input);
593
+ const locale = normalizeLocale(rawLocale);
594
+ if (!locale.ok) return locale;
595
+ const rawStyle = entryFor(entries, "style");
596
+ if (rawStyle === void 0 || rawStyle === null) return readValueAs(input, {
597
+ locale: locale.value,
598
+ style: DEFAULT_DATE_FORMAT_STYLE
599
+ });
600
+ const style = readStyle(rawStyle);
601
+ if (!style.ok) return style;
602
+ return readValueAs(input, {
603
+ locale: locale.value,
604
+ style: style.value
605
+ });
606
+ };
607
+ /** Read a date-format spec an agent spelled its own way, as one string or as
608
+ * the wire object. */
609
+ const normalizeDateFormatSpec = (input) => {
610
+ if (typeof input === "string") return readStringSpec(input);
611
+ if (isRecord$1(input)) return readObjectSpec(input);
612
+ return specAsk(input);
613
+ };
614
+ //#endregion
615
+ //#region src/date-value.ts
616
+ /**
617
+ * Calendar dates on the agent wire.
618
+ *
619
+ * ISO `YYYY-MM-DD` is the canonical form and the only one a document may store,
620
+ * but a model drafting a Czech lease writes `1. 10. 2026` and one drafting an
621
+ * English one writes `October 1, 2026`. Those spellings carry one meaning each,
622
+ * so they are read.
623
+ *
624
+ * `01/02/2026` does not: it is 1 February under most of the world's convention
625
+ * and 2 January under the United States', and nothing inside the string decides
626
+ * which. A wrong date on an instrument is not a cosmetic defect, so an
627
+ * ambiguous spelling is asked about with both readings named rather than
628
+ * guessed from a default. Same for a two-digit year (`02-03-26`), which is
629
+ * ambiguous in the day/month order as well as the century.
630
+ *
631
+ * A range bound (`date_from`, `date_to`) reads more, because which end it is
632
+ * decides what a partial date means: `2020` as a start is 1 January and as an
633
+ * end is 31 December, and `0001-01-01` or `9999-12-31` is the model saying the
634
+ * range is open on that side. A single date is never read that way, since
635
+ * nothing tells a lone `2020` which day of the year it is.
636
+ */
637
+ const DATE_VALUE_EXPECTED = "a calendar date";
638
+ const DATE_VALUE_HINT = "Send the date as ISO YYYY-MM-DD (\"2026-10-01\"). The unambiguous spellings \"1. 10. 2026\", \"1 October 2026\" and \"October 1, 2026\" are read as well.";
639
+ /** Day-first with dots is one convention wherever it is written, so it needs
640
+ * no disambiguation: `1.10.2026`, `01. 10. 2026`, `1. 10. 2026.` */
641
+ const DOTTED_DAY_FIRST_RE = /^(?<day>\d{1,2})\.\s*(?<month>\d{1,2})\.\s*(?<year>\d{4})\.?$/u;
642
+ /** Year-first with any separator: the four-digit head fixes the order. */
643
+ const YEAR_FIRST_RE = /^(?<year>\d{4})[-./]\s*(?<month>\d{1,2})[-./]\s*(?<day>\d{1,2})\.?$/u;
644
+ /** Slash- or dash-separated with a four-digit year at the end: the day/month
645
+ * order still has to be decided. */
646
+ const YEAR_LAST_RE = /^(?<first>\d{1,2})[/-](?<second>\d{1,2})[/-](?<year>\d{4})$/u;
647
+ /** An ISO datetime: the date part is the calendar date it names. */
648
+ const ISO_DATETIME_RE = /^(?<date>\d{4}-\d{2}-\d{2})[T ]\S*/u;
649
+ /** `1 October 2026`, `1. října 2026`, `1st October 2026`. */
650
+ const DAY_MONTH_YEAR_RE = /^(?<day>\d{1,2})(?:st|nd|rd|th)?\.?\s+(?<month>\p{L}+\.?)\s+(?<year>\d{4})$/u;
651
+ /** `October 1, 2026`, `Oct. 1 2026`. */
652
+ const MONTH_DAY_YEAR_RE = /^(?<month>\p{L}+\.?)\s+(?<day>\d{1,2})(?:st|nd|rd|th)?,?\s+(?<year>\d{4})$/u;
653
+ const MAX_MONTH = 12;
654
+ const pad = (value) => String(value).padStart(2, "0");
655
+ /** The ISO spelling of a real calendar date, or null. */
656
+ const isoDate = (year, month, day) => parsePlainDate(`${String(year).padStart(4, "0")}-${pad(month)}-${pad(day)}`)?.toString() ?? null;
657
+ /** A month name folded to the form the tables below are keyed by: lowercase,
658
+ * no trailing abbreviation dot, diacritics kept (they distinguish nothing a
659
+ * model gets wrong, and ICU emits them). */
660
+ const foldMonthName = (name) => name.toLowerCase().replace(/\.$/u, "").trim();
661
+ /**
662
+ * Month names for one locale, in both the standalone form (`říjen`) and the
663
+ * form ICU uses inside a full date (`října`, the Czech genitive), long and
664
+ * abbreviated. Built from `Intl`, so a locale's names never have to be
665
+ * hand-listed.
666
+ */
667
+ const monthNamesFor = (locale) => {
668
+ const names = /* @__PURE__ */ new Map();
669
+ const record = (name, month) => {
670
+ if (name !== void 0 && /\p{L}/u.test(name)) names.set(foldMonthName(name), month);
671
+ };
672
+ for (const style of ["long", "short"]) {
673
+ const standalone = new Intl.DateTimeFormat(locale, {
674
+ month: style,
675
+ timeZone: "UTC"
676
+ });
677
+ const inDate = new Intl.DateTimeFormat(locale, {
678
+ day: "numeric",
679
+ month: style,
680
+ year: "numeric",
681
+ timeZone: "UTC"
682
+ });
683
+ for (let month = 1; month <= MAX_MONTH; month += 1) {
684
+ const instant = Temporal.PlainDate.from({
685
+ year: 2026,
686
+ month,
687
+ day: 15
688
+ }).toZonedDateTime("UTC").epochMilliseconds;
689
+ record(standalone.format(instant), month);
690
+ record(inDate.formatToParts(instant).find((part) => part.type === "month")?.value, month);
691
+ }
692
+ }
693
+ return names;
694
+ };
695
+ const monthNameCache = /* @__PURE__ */ new Map();
696
+ const monthNumber = (name, locales) => {
697
+ const folded = foldMonthName(name);
698
+ for (const locale of locales) {
699
+ const cached = monthNameCache.get(locale) ?? monthNamesFor(locale);
700
+ monthNameCache.set(locale, cached);
701
+ const month = cached.get(folded);
702
+ if (month !== void 0) return month;
703
+ }
704
+ return null;
705
+ };
706
+ const readNamedMonth = (spec, locales) => {
707
+ const groups = (DAY_MONTH_YEAR_RE.exec(spec) ?? MONTH_DAY_YEAR_RE.exec(spec))?.groups;
708
+ if (groups === void 0) return null;
709
+ const month = monthNumber(groups["month"] ?? "", locales);
710
+ return month === null ? null : {
711
+ year: Number(groups["year"]),
712
+ month,
713
+ day: Number(groups["day"])
714
+ };
715
+ };
716
+ const readNumeric = (spec) => {
717
+ const groups = (DOTTED_DAY_FIRST_RE.exec(spec) ?? YEAR_FIRST_RE.exec(spec))?.groups;
718
+ return groups === void 0 ? null : {
719
+ year: Number(groups["year"]),
720
+ month: Number(groups["month"]),
721
+ day: Number(groups["day"])
722
+ };
723
+ };
724
+ /** The month styles a date field renders in, and therefore the structures a
725
+ * model copies back out of the document. */
726
+ const READ_MONTH_STYLES = ["long", "short"];
727
+ /** The instant every locale probe is formatted at: a two-digit day and a
728
+ * two-digit month, so no part of the layout is a single character by
729
+ * accident. */
730
+ const LAYOUT_PROBE = Temporal.PlainDate.from("2026-10-15").toZonedDateTime("UTC").epochMilliseconds;
731
+ /** Separators alone. A layout whose month is numeric and whose literals are
732
+ * only these is `01/02/2026` with one locale's ordering imposed on it, which
733
+ * is the reading this module refuses to guess. */
734
+ const SEPARATORS_ONLY_RE = /^[\s./,-]*$/u;
735
+ const REGEXP_META_RE = /[.*+?^${}()|[\]\\]/gu;
736
+ /** A literal ICU emits between the parts (`. `, ` de `, `年`), matched with the
737
+ * whitespace around it left to the writer. */
738
+ const literalPattern = (literal) => literal.split(/\s+/u).map((chunk) => chunk.replace(REGEXP_META_RE, (meta) => `\\${meta}`)).join(String.raw`\s*`);
739
+ /** The parts a calendar-date layout is built from. A formatter asked for a
740
+ * day, a month and a year emits nothing else; anything else means the layout
741
+ * is not one this reader can rebuild. */
742
+ const LAYOUT_PART_KINDS = [
743
+ "day",
744
+ "month",
745
+ "year",
746
+ "literal"
747
+ ];
748
+ const layoutPartKind = (type) => LAYOUT_PART_KINDS.find((kind) => kind === type) ?? null;
749
+ /**
750
+ * The date structures one locale actually renders, as patterns: ICU's own
751
+ * ordering and its own literals, so `1 de outubro de 2026` and
752
+ * `2026. október 1.` are read where the field renders them that way. A layout
753
+ * whose month is a number separated by nothing but punctuation is dropped: it
754
+ * carries the day/month ambiguity this module never guesses at.
755
+ */
756
+ const localeLayouts = (locale) => {
757
+ const layouts = [];
758
+ for (const month of READ_MONTH_STYLES) {
759
+ const parts = new Intl.DateTimeFormat(locale, {
760
+ day: "numeric",
761
+ month,
762
+ year: "numeric",
763
+ timeZone: "UTC"
764
+ }).formatToParts(LAYOUT_PROBE);
765
+ let source = "";
766
+ let literals = "";
767
+ let named = false;
768
+ let readable = true;
769
+ for (const part of parts) {
770
+ const kind = layoutPartKind(part.type);
771
+ if (kind === null) {
772
+ readable = false;
773
+ continue;
774
+ }
775
+ switch (kind) {
776
+ case "day":
777
+ source += String.raw`(?<day>\d{1,2})`;
778
+ break;
779
+ case "year":
780
+ source += String.raw`(?<year>\d{4})`;
781
+ break;
782
+ case "month":
783
+ named = /\p{L}/u.test(part.value);
784
+ source += named ? String.raw`(?<month>[\p{L}\p{M}]+\.?)` : String.raw`(?<month>\d{1,2})`;
785
+ break;
786
+ case "literal":
787
+ literals += part.value;
788
+ source += literalPattern(part.value);
789
+ }
790
+ }
791
+ if (readable && (named || !SEPARATORS_ONLY_RE.test(literals))) layouts.push(new RegExp(String.raw`^\s*${source}\s*$`, "u"));
792
+ }
793
+ return layouts;
794
+ };
795
+ const layoutCache = /* @__PURE__ */ new Map();
796
+ const NUMERIC_RE = /^\d+$/u;
797
+ const readLocaleLayout = (spec, locales) => {
798
+ for (const locale of locales) {
799
+ const layouts = layoutCache.get(locale) ?? localeLayouts(locale);
800
+ layoutCache.set(locale, layouts);
801
+ for (const layout of layouts) {
802
+ const groups = layout.exec(spec)?.groups;
803
+ if (groups === void 0) continue;
804
+ const spelled = groups["month"] ?? "";
805
+ const month = NUMERIC_RE.test(spelled) ? Number(spelled) : monthNumber(spelled, [locale]);
806
+ if (month !== null) return {
807
+ year: Number(groups["year"]),
808
+ month,
809
+ day: Number(groups["day"])
810
+ };
811
+ }
812
+ }
813
+ return null;
814
+ };
815
+ /** English is always read: it is the language of the schema and of most model
816
+ * output, whatever the document's own language is. */
817
+ const readingLocales = (options) => ["en", ...options?.locales ?? []];
818
+ const invalidAsk = (input) => askForFix({
819
+ input,
820
+ expected: DATE_VALUE_EXPECTED,
821
+ hint: DATE_VALUE_HINT
822
+ });
823
+ /** Both readings of a day/month pair, named, so the ask carries the fix rather
824
+ * than a rule the model has to look up. */
825
+ const ambiguousAsk$1 = ({ input, first, second, year }) => {
826
+ const dayFirst = isoDate(year, second, first);
827
+ const monthFirst = isoDate(year, first, second);
828
+ if (dayFirst === null || monthFirst === null) return invalidAsk(input);
829
+ return askForFix({
830
+ input,
831
+ expected: DATE_VALUE_EXPECTED,
832
+ hint: `That reads as ${dayFirst} with the day first, or ${monthFirst} with the month first. Send "${dayFirst}" or "${monthFirst}".`
833
+ });
834
+ };
835
+ /** One whole calendar date, the reading every field shares. */
836
+ const readCalendarDate = (input, options) => {
837
+ if (typeof input !== "string") return invalidAsk(input);
838
+ const trimmed = input.trim();
839
+ if (trimmed === "") return invalidAsk(input);
840
+ const spec = ISO_DATETIME_RE.exec(trimmed)?.groups?.["date"] ?? trimmed;
841
+ const locales = readingLocales(options);
842
+ const unambiguous = readNumeric(spec) ?? readNamedMonth(spec, locales) ?? readLocaleLayout(spec, locales);
843
+ if (unambiguous !== null) {
844
+ const iso = isoDate(unambiguous.year, unambiguous.month, unambiguous.day);
845
+ return iso === null ? invalidAsk(input) : readValueAs(input, iso);
846
+ }
847
+ const yearLast = YEAR_LAST_RE.exec(spec)?.groups;
848
+ if (yearLast === void 0) return invalidAsk(input);
849
+ const first = Number(yearLast["first"]);
850
+ const second = Number(yearLast["second"]);
851
+ const year = Number(yearLast["year"]);
852
+ if (first > MAX_MONTH && second <= MAX_MONTH) {
853
+ const iso = isoDate(year, second, first);
854
+ return iso === null ? invalidAsk(input) : readValueAs(input, iso);
855
+ }
856
+ if (second > MAX_MONTH && first <= MAX_MONTH) {
857
+ const iso = isoDate(year, first, second);
858
+ return iso === null ? invalidAsk(input) : readValueAs(input, iso);
859
+ }
860
+ if (first > MAX_MONTH && second > MAX_MONTH) return invalidAsk(input);
861
+ if (first === second) {
862
+ const iso = isoDate(year, first, second);
863
+ return iso === null ? invalidAsk(input) : readValueAs(input, iso);
864
+ }
865
+ return ambiguousAsk$1({
866
+ input,
867
+ first,
868
+ second,
869
+ year
870
+ });
871
+ };
872
+ const YEAR_ONLY_RE = /^(?<year>\d{4})$/u;
873
+ /** `2020-05`, `2020/5`: the four-digit head fixes which part is the year. */
874
+ const YEAR_MONTH_RE = /^(?<year>\d{4})[-/](?<month>\d{1,2})$/u;
875
+ /** `05/2020`, `5/2020`, `05.2020`: the four-digit tail fixes it the same way. */
876
+ const MONTH_YEAR_RE = /^(?<month>\d{1,2})[-/.]\s*(?<year>\d{4})$/u;
877
+ /**
878
+ * A bare year or month as the first or last day it covers. Only a bound reads
879
+ * these: as a start, `2020` means from the first day of 2020, and as an end,
880
+ * through its last, which is what a model filtering "decisions from 2020"
881
+ * means by it.
882
+ */
883
+ const readPartialDate = (trimmed, bound) => {
884
+ const yearOnly = YEAR_ONLY_RE.exec(trimmed)?.groups;
885
+ if (yearOnly !== void 0) {
886
+ const year = Number(yearOnly["year"]);
887
+ return bound === "start" ? isoDate(year, 1, 1) : isoDate(year, 12, 31);
888
+ }
889
+ const groups = (YEAR_MONTH_RE.exec(trimmed) ?? MONTH_YEAR_RE.exec(trimmed))?.groups;
890
+ if (groups === void 0) return null;
891
+ const year = Number(groups["year"]);
892
+ const month = Number(groups["month"]);
893
+ const first = isoDate(year, month, 1);
894
+ if (first === null || bound === "start") return first;
895
+ return isoDate(year, month, Temporal.PlainDate.from(first).daysInMonth);
896
+ };
897
+ /** How a model writes both ends of a range in one string, matched on the
898
+ * string with its whitespace runs collapsed to one space (halves are trimmed
899
+ * after the split), so no separator backtracks over a run of whitespace. The
900
+ * unspaced dash and the slash split only where both halves are dates on
901
+ * their own, so a single `2020-05` or `5/2020` never reads as two. */
902
+ const RANGE_SEPARATORS = [
903
+ /\.\./u,
904
+ /[–—]/u,
905
+ / to /iu,
906
+ / - /u,
907
+ /\//u,
908
+ /-/u
909
+ ];
910
+ const WHITESPACE_RUN_RE = /\s+/gu;
911
+ /** One bound read on its own: a whole date, else a partial one. */
912
+ const readBoundHalf = (half, bound, options) => {
913
+ const whole = readCalendarDate(half, options);
914
+ return whole.ok ? whole.value : readPartialDate(half, bound);
915
+ };
916
+ /** Both ends of a range, when the string is one written into a single bound. */
917
+ const readRange = (trimmed, options) => {
918
+ const spaced = trimmed.replace(WHITESPACE_RUN_RE, " ");
919
+ for (const separator of RANGE_SEPARATORS) {
920
+ const halves = spaced.split(separator).map((half) => half.trim());
921
+ const [left, right] = halves;
922
+ if (halves.length !== 2 || left === void 0 || right === void 0) continue;
923
+ const start = readBoundHalf(left, "start", options);
924
+ const end = readBoundHalf(right, "end", options);
925
+ if (start !== null && end !== null) return {
926
+ start,
927
+ end
928
+ };
929
+ }
930
+ return null;
931
+ };
932
+ const rangeAsk = (input, range) => askForFix({
933
+ input,
934
+ expected: "a single date",
935
+ hint: `This is one bound of a range: send the start and the end as two separate date properties (for example date_from "${range.start}" and date_to "${range.end}").`
936
+ });
937
+ /** Read a calendar date an agent spelled its own way, as ISO YYYY-MM-DD. With
938
+ * a `bound`, a bare year or month reads as that end's day, and a whole range
939
+ * in the one field asks for its two halves. */
940
+ const normalizeDateValue = (input, options) => {
941
+ const bound = options?.bound;
942
+ if (bound === void 0 || typeof input !== "string") return readCalendarDate(input, options);
943
+ const trimmed = input.trim();
944
+ const range = readRange(trimmed, options);
945
+ if (range !== null) return rangeAsk(input, range);
946
+ const whole = readCalendarDate(input, options);
947
+ if (whole.ok) return whole;
948
+ const partial = readPartialDate(trimmed, bound);
949
+ return partial === null ? whole : readValueAs(input, partial);
950
+ };
951
+ /** Years no range filter means literally: `0001-01-01` and `9999-12-31` are
952
+ * how a database and a model spell "no limit on this side". Year 1000 is kept,
953
+ * since a medieval charter is a real bound in a legal corpus. */
954
+ const OPEN_BOUND_YEAR_BELOW = 1e3;
955
+ const OPEN_BOUND_YEAR_FROM = 9e3;
956
+ /**
957
+ * Read one end of a date range. A placeholder or an open-ended sentinel date
958
+ * is no bound at all, so the caller drops the property rather than filtering
959
+ * to the year 1 or 9999.
960
+ */
961
+ const normalizeDateBound = (input, options) => {
962
+ if (isAbsentPlaceholder(input)) return readAsAbsent(input);
963
+ const result = normalizeDateValue(input, options);
964
+ if (!result.ok) return result;
965
+ const year = Temporal.PlainDate.from(result.value).year;
966
+ return year < OPEN_BOUND_YEAR_BELOW || year >= OPEN_BOUND_YEAR_FROM ? readAsAbsent(input, "an open bound") : result;
967
+ };
968
+ //#endregion
969
+ //#region src/eli.ts
970
+ const ELI_EXPECTED = "an ELI";
971
+ const ELI_HINT = "Pass the eli a search result returned.";
972
+ /** An origin with a scheme, or a bare host a model pasted without one; a bare
973
+ * host needs a dot so `cz/sb/...` is never taken for one. */
974
+ const ORIGIN_RE = /^(?:(?<scheme>https?):\/\/(?<host>[^/\s]+)|(?<bareHost>[a-z0-9-]+(?:\.[a-z0-9-]+)+))(?=\/|$)/iu;
975
+ const JURISDICTION_RE = /^[a-z]{2,3}$/u;
976
+ const COLLECTION_RE = /^[a-z0-9-]+$/u;
977
+ const DIGITS_RE = /^\d+$/u;
978
+ const FOUR_DIGITS_RE = /^\d{4}$/u;
979
+ /** A version date past the work: `2024-01-01` or `20240101`. */
980
+ const DATE_SEGMENT_RE = /^\d{4}-?\d{2}-?\d{2}$/u;
981
+ const EARLIEST_YEAR = 1800;
982
+ const LATEST_YEAR = 2100;
983
+ const isYear = (segment) => {
984
+ if (!FOUR_DIGITS_RE.test(segment)) return false;
985
+ const year = Number(segment);
986
+ return year >= EARLIEST_YEAR && year <= LATEST_YEAR;
987
+ };
988
+ /** The parts of an ELI in any of its spellings, or null when the input is not
989
+ * shaped like one at all. */
990
+ const parseEli = (trimmed) => {
991
+ const originMatch = ORIGIN_RE.exec(trimmed);
992
+ const groups = originMatch?.groups;
993
+ const host = groups?.["host"] ?? groups?.["bareHost"];
994
+ const scheme = groups?.["scheme"]?.toLowerCase() ?? "https";
995
+ const origin = host === void 0 ? null : `${scheme}://${host.toLowerCase()}`;
996
+ const segments = trimmed.slice(originMatch?.[0].length ?? 0).split("/").filter((segment) => segment !== "");
997
+ const [head, ...afterHead] = segments;
998
+ const hasEliSegment = head?.toLowerCase() === "eli";
999
+ if (origin !== null && !hasEliSegment) return null;
1000
+ const [jurisdiction, collection, first, second, ...extra] = hasEliSegment ? afterHead : segments;
1001
+ if (jurisdiction === void 0 || collection === void 0 || first === void 0 || second === void 0) return null;
1002
+ const lowerJurisdiction = jurisdiction.toLowerCase();
1003
+ const lowerCollection = collection.toLowerCase();
1004
+ return JURISDICTION_RE.test(lowerJurisdiction) && COLLECTION_RE.test(lowerCollection) && DIGITS_RE.test(first) && DIGITS_RE.test(second) ? {
1005
+ origin,
1006
+ jurisdiction: lowerJurisdiction,
1007
+ collection: lowerCollection,
1008
+ first,
1009
+ second,
1010
+ extra
1011
+ } : null;
1012
+ };
1013
+ /** A host with its trailing slashes cut, scanned from the end so a long run
1014
+ * of slashes costs one pass. */
1015
+ const withoutTrailingSlashes = (host) => {
1016
+ if (host === void 0) return;
1017
+ let end = host.length;
1018
+ while (end > 0 && host[end - 1] === "/") end -= 1;
1019
+ return host.slice(0, end);
1020
+ };
1021
+ const eliOf = (origin, { jurisdiction, collection }, year, number) => `${origin}/eli/${jurisdiction}/${collection}/${year}/${number}`;
1022
+ /**
1023
+ * Read an ELI an agent spelled its own way, as the canonical work identifier
1024
+ * under its publisher's origin. An input that is not an ELI goes through the
1025
+ * caller's citation reader before it asks.
1026
+ */
1027
+ const normalizeEli = (input, options) => {
1028
+ const notAnEli = () => askForFix({
1029
+ input,
1030
+ expected: ELI_EXPECTED,
1031
+ hint: options.hint ?? ELI_HINT
1032
+ });
1033
+ if (typeof input !== "string") return notAnEli();
1034
+ const trimmed = input.trim();
1035
+ const parsed = parseEli(trimmed);
1036
+ if (parsed === null) {
1037
+ const cited = options.readCitation?.(trimmed);
1038
+ if (cited === void 0) return notAnEli();
1039
+ const read = normalizeEli(cited, {
1040
+ ...options,
1041
+ readCitation: void 0
1042
+ });
1043
+ return read.ok ? readValueAs(input, read.value) : read;
1044
+ }
1045
+ const origin = withoutTrailingSlashes(options.hosts[parsed.jurisdiction]) ?? parsed.origin;
1046
+ if (origin === null) return askForFix({
1047
+ input,
1048
+ expected: ELI_EXPECTED,
1049
+ hint: `No publisher is known for the jurisdiction "${parsed.jurisdiction}". ${options.hint ?? ELI_HINT}`
1050
+ });
1051
+ const firstIsYear = isYear(parsed.first);
1052
+ const secondIsYear = isYear(parsed.second);
1053
+ if (firstIsYear && secondIsYear) {
1054
+ const asWritten = eliOf(origin, parsed, parsed.first, parsed.second);
1055
+ if (input === asWritten) return readValueAs(input, asWritten);
1056
+ const swapped = eliOf(origin, parsed, parsed.second, parsed.first);
1057
+ return askForFix({
1058
+ input,
1059
+ expected: ELI_EXPECTED,
1060
+ hint: `Both ${parsed.first} and ${parsed.second} read as a year, so this names "${asWritten}" or "${swapped}". Pass the one you mean.`
1061
+ });
1062
+ }
1063
+ const work = firstIsYear || !secondIsYear ? eliOf(origin, parsed, parsed.first, parsed.second) : eliOf(origin, parsed, parsed.second, parsed.first);
1064
+ if (parsed.extra.length > 0) {
1065
+ const dated = parsed.extra.some((segment) => DATE_SEGMENT_RE.test(segment));
1066
+ return askForFix({
1067
+ input,
1068
+ expected: "the ELI of a work",
1069
+ hint: dated ? `Pass the work ELI "${work}" as eli; a date goes in as_of.` : `Pass the work ELI "${work}" as eli.`
1070
+ });
1071
+ }
1072
+ return readValueAs(input, work);
1073
+ };
1074
+ //#endregion
1075
+ //#region src/number.ts
1076
+ /**
1077
+ * Numbers on the agent wire.
1078
+ *
1079
+ * A model writing a rent, a deposit, or a headcount copies the notation of the
1080
+ * document it is drafting: `4 000`, `4,000.50`, `1 234,50`, `1.234,50`,
1081
+ * `EUR 100`, `100 EUR`, `100.-`, `1e3`. Group separators, currency, and the
1082
+ * accounting dash carry no numeric meaning and are read away.
1083
+ *
1084
+ * `1,234` is the one form that carries two meanings — 1234 under English
1085
+ * grouping, 1.234 under continental decimals — and no amount of context inside
1086
+ * the string decides it. A caller that knows the field's locale passes it and
1087
+ * the locale decides; otherwise the value is asked for again, naming both
1088
+ * readings. Guessing here is a silent factor-of-1000 error on a monetary term.
1089
+ */
1090
+ const NUMBER_EXPECTED = "a number";
1091
+ const NUMBER_HINT = "Send the number as a JSON number (1234.5). Digit grouping (\"4 000\"), a currency (\"EUR 100\"), and scientific notation (\"1e3\") are read as well.";
1092
+ /** The separators a model uses to group thousands. `\s` covers the narrow and
1093
+ * non-breaking spaces `Intl` itself emits. */
1094
+ const GROUPING_SPACE_RE = /[\s']/gu;
1095
+ /** Currency notation is accepted only as one affix, never as prose interleaved
1096
+ * with digits. ISO codes cover the portable spelling; this small set covers
1097
+ * alphabetic symbols emitted by the locales exercised by Stella today. */
1098
+ const ISO_CURRENCY_CODES = new Set(Intl.supportedValuesOf("currency"));
1099
+ const ALPHABETIC_CURRENCY_SYMBOLS = /* @__PURE__ */ new Set([
1100
+ "Kč",
1101
+ "zł",
1102
+ "kr",
1103
+ "lei",
1104
+ "Ft"
1105
+ ]);
1106
+ const CURRENCY_TOKEN_RE = /[\p{L}\p{Sc}]+/gu;
1107
+ const CURRENCY_SYMBOL_RE = /^(?:[A-Z]{1,2})?\p{Sc}$/u;
1108
+ const ISO_CURRENCY_CODE_RE = /^[A-Za-z]{3}$/u;
1109
+ /** The accounting "and no cents" dash: `100.-`, `100,-`. */
1110
+ const ACCOUNTING_DASH_RE = /[.,]\s*-$/u;
1111
+ const SCIENTIFIC_RE = /^[+-]?\d+(?:\.\d+)?[eE][+-]?\d+$/u;
1112
+ /** Digits and separators only, at least one digit. The head before the first
1113
+ * digit is separators alone, so no two quantifiers compete for the same
1114
+ * character and the match is linear in the input. */
1115
+ const DIGITS_AND_SEPARATORS_RE = /^[+-]?[.,]*\d[\d.,]*$/u;
1116
+ /** A single separator with exactly three digits behind it: a thousands group
1117
+ * and a three-decimal fraction are spelled identically. */
1118
+ const THREE_DIGIT_TAIL_RE = /^\d{1,3}[.,]\d{3}$/u;
1119
+ /** The decimal mark the locale uses, or null when `Intl` refuses the tag. */
1120
+ const localeDecimalMark = (locale) => {
1121
+ const parts = Result.try({
1122
+ try: () => new Intl.NumberFormat(locale).formatToParts(1.5),
1123
+ catch: (cause) => cause
1124
+ });
1125
+ if (parts.isErr()) return null;
1126
+ return parts.value.find((part) => part.type === "decimal")?.value ?? null;
1127
+ };
1128
+ /** Which of `,` and `.` marks the fraction, given both appear: whichever comes
1129
+ * last, because the other one has to be grouping. */
1130
+ const lastSeparator = (body) => {
1131
+ return body.lastIndexOf(",") > body.lastIndexOf(".") ? "," : ".";
1132
+ };
1133
+ const toNumber = (body, decimalMark) => Number(decimalMark === null ? body.replaceAll(",", "").replaceAll(".", "") : body.replaceAll(decimalMark === "," ? "." : ",", "").replace(decimalMark, "."));
1134
+ /** The separator carries both readings and no locale decides it. A symbol,
1135
+ * not a string, so the decision cannot be confused with a decimal mark. */
1136
+ const AMBIGUOUS = Symbol("ambiguous decimal mark");
1137
+ const ambiguousAsk = (input, body, separator) => {
1138
+ const grouped = toNumber(body, null);
1139
+ const fractional = toNumber(body, separator);
1140
+ return askForFix({
1141
+ input,
1142
+ expected: NUMBER_EXPECTED,
1143
+ hint: `"${body}" reads as ${grouped} with "${separator}" grouping the thousands, or as ${fractional} with "${separator}" as the decimal mark. Send ${grouped} or ${fractional} as a JSON number.`
1144
+ });
1145
+ };
1146
+ const isCurrencyToken = (token) => CURRENCY_SYMBOL_RE.test(token) || ALPHABETIC_CURRENCY_SYMBOLS.has(token) || ISO_CURRENCY_CODE_RE.test(token) && ISO_CURRENCY_CODES.has(token.toUpperCase());
1147
+ const withoutCurrencyAffix = (input) => {
1148
+ const tokens = [...input.matchAll(CURRENCY_TOKEN_RE)];
1149
+ if (tokens.length === 0) return input;
1150
+ if (tokens.length !== 1) return null;
1151
+ const token = tokens.at(0);
1152
+ if (token === void 0 || !isCurrencyToken(token[0])) return null;
1153
+ const index = token.index;
1154
+ const before = input.slice(0, index);
1155
+ const after = input.slice(index + token[0].length);
1156
+ if (/\d/u.test(before) && /\d/u.test(after)) return null;
1157
+ return `${before}${after}`;
1158
+ };
1159
+ /** Read a number an agent spelled its own way. */
1160
+ const normalizeNumber = (input, options) => {
1161
+ if (typeof input === "number") return Number.isFinite(input) ? readValue(input) : askForFix({
1162
+ input,
1163
+ expected: NUMBER_EXPECTED,
1164
+ hint: NUMBER_HINT
1165
+ });
1166
+ if (typeof input !== "string") return askForFix({
1167
+ input,
1168
+ expected: NUMBER_EXPECTED,
1169
+ hint: NUMBER_HINT
1170
+ });
1171
+ const trimmed = input.trim();
1172
+ if (SCIENTIFIC_RE.test(trimmed)) {
1173
+ const exponential = Number(trimmed);
1174
+ return Number.isFinite(exponential) ? readValueAs(input, exponential) : askForFix({
1175
+ input,
1176
+ expected: NUMBER_EXPECTED,
1177
+ hint: NUMBER_HINT
1178
+ });
1179
+ }
1180
+ const withoutCurrency = withoutCurrencyAffix(trimmed);
1181
+ if (withoutCurrency === null) return askForFix({
1182
+ input,
1183
+ expected: NUMBER_EXPECTED,
1184
+ hint: NUMBER_HINT
1185
+ });
1186
+ const stripped = withoutCurrency.trim().replace(ACCOUNTING_DASH_RE, "").replace(GROUPING_SPACE_RE, "");
1187
+ if (!DIGITS_AND_SEPARATORS_RE.test(stripped)) return askForFix({
1188
+ input,
1189
+ expected: NUMBER_EXPECTED,
1190
+ hint: NUMBER_HINT
1191
+ });
1192
+ const sign = stripped.startsWith("-") ? -1 : 1;
1193
+ const body = stripped.replace(/^[+-]/u, "");
1194
+ const commas = body.split(",").length - 1;
1195
+ const dots = body.split(".").length - 1;
1196
+ const decimalMark = (() => {
1197
+ if (commas > 0 && dots > 0) return lastSeparator(body);
1198
+ if (commas + dots === 0) return null;
1199
+ if (commas > 1 || dots > 1) return null;
1200
+ const separator = commas === 1 ? "," : ".";
1201
+ if (!THREE_DIGIT_TAIL_RE.test(body)) return separator;
1202
+ const mark = options?.locale === void 0 ? null : localeDecimalMark(options.locale);
1203
+ if (mark === null) return AMBIGUOUS;
1204
+ return mark === separator ? separator : null;
1205
+ })();
1206
+ if (decimalMark === AMBIGUOUS) return ambiguousAsk(input, body, commas === 1 ? "," : ".");
1207
+ const magnitude = toNumber(body, decimalMark);
1208
+ if (!Number.isFinite(magnitude)) return askForFix({
1209
+ input,
1210
+ expected: NUMBER_EXPECTED,
1211
+ hint: NUMBER_HINT
1212
+ });
1213
+ return readValueAs(input, sign * magnitude);
1214
+ };
1215
+ const rangeClause = ({ minimum, maximum }) => {
1216
+ if (minimum !== void 0 && maximum !== void 0) return ` from ${minimum} to ${maximum}`;
1217
+ if (minimum !== void 0) return ` of at least ${minimum}`;
1218
+ return maximum === void 0 ? "" : ` of at most ${maximum}`;
1219
+ };
1220
+ /**
1221
+ * Read a bounded count (a page size, a result limit) and clamp it into range.
1222
+ *
1223
+ * `limit: 500` against a cap of 100 has one sensible reading, the most the
1224
+ * tool returns, and asking would cost a round trip to learn a number the note
1225
+ * can state. The caller decides which fields clamp: a monetary amount out of
1226
+ * range is a mistake to ask about, not a value to move.
1227
+ */
1228
+ const normalizeNumberInRange = (input, options) => {
1229
+ const read = normalizeNumber(input, options);
1230
+ if (!read.ok) return read;
1231
+ if (options.integer === true && !Number.isInteger(read.value)) return askForFix({
1232
+ input,
1233
+ expected: "a whole number",
1234
+ hint: `Send a whole number${rangeClause(options)} as a JSON number.`
1235
+ });
1236
+ const clampTo = (value, why) => {
1237
+ const clampNote = `Read ${read.value} as ${value}, ${why}.`;
1238
+ return {
1239
+ ok: true,
1240
+ value,
1241
+ note: read.note === void 0 ? clampNote : `${read.note} ${clampNote}`
1242
+ };
1243
+ };
1244
+ const { minimum, maximum } = options;
1245
+ if (maximum !== void 0 && read.value > maximum) return clampTo(maximum, "the most this accepts");
1246
+ if (minimum !== void 0 && read.value < minimum) return clampTo(minimum, "the least this accepts");
1247
+ return read;
1248
+ };
1249
+ //#endregion
1250
+ //#region src/string-list.ts
1251
+ /**
1252
+ * Lists of strings on the agent wire.
1253
+ *
1254
+ * A model asked for an array often sends the array's JSON as a string
1255
+ * (`"[\"a\", \"b\"]"`), or one bare string where the schema wanted a list of
1256
+ * one. Both carry one meaning and are read. A comma-separated string carries
1257
+ * one meaning only where an item cannot itself hold a comma: a list of court
1258
+ * ids can be split, a list of search phrases cannot (`"Smith, J."` is one
1259
+ * phrase), so the caller says which by `split`.
1260
+ */
1261
+ const STRING_LIST_EXPECTED = "a list of strings";
1262
+ const STRING_LIST_HINT = "Send a JSON array of strings, for example [\"a\", \"b\"]";
1263
+ const DELIMITERS_RE = /[,;\r\n]/u;
1264
+ const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
1265
+ /** The array a string spells as JSON, or null when it spells something else. */
1266
+ const parseJsonArray = (trimmed) => {
1267
+ if (!trimmed.startsWith("[")) return null;
1268
+ const parsed = Result.try(() => JSON.parse(trimmed));
1269
+ return parsed.isOk() && isStringArray(parsed.value) ? parsed.value : null;
1270
+ };
1271
+ /** Read a list of strings an agent spelled its own way. Only the list's own
1272
+ * shape is read here: an array is taken as it is, and one holding anything
1273
+ * but strings asks, since what an item should have been is the item's
1274
+ * question, not the list's. */
1275
+ const normalizeStringList = (input, options) => {
1276
+ if (isStringArray(input)) return readValue(input);
1277
+ if (typeof input !== "string") return askForFix({
1278
+ input,
1279
+ expected: STRING_LIST_EXPECTED,
1280
+ hint: STRING_LIST_HINT
1281
+ });
1282
+ const parsed = parseJsonArray(input.trim());
1283
+ if (parsed !== null) return readValueAs(input, parsed);
1284
+ if (options.split === "never") return readValueAs(input, [input]);
1285
+ const pieces = input.split(DELIMITERS_RE).map((piece) => piece.trim()).filter((piece) => piece !== "");
1286
+ return readValueAs(input, pieces);
1287
+ };
1288
+ //#endregion
1289
+ //#region src/uuid.ts
1290
+ /**
1291
+ * Record ids on the agent wire.
1292
+ *
1293
+ * Stella ids are lowercase dashed uuids, but a model copies an id through
1294
+ * whatever it last saw it in: an uppercase .NET dump, a `{...}` registry form,
1295
+ * a `urn:uuid:` URI, a dashless database column. Each of those names the same
1296
+ * 128 bits, so each is read.
1297
+ *
1298
+ * A model with no id to hand invents one, and it invents the same few: the nil
1299
+ * uuid, a run of one digit, or the example from the RFC and the tutorials it
1300
+ * trained on. Those name no record anywhere. On a required id the handler's
1301
+ * `not_found` answers them; on an optional filter they mean "not filtering",
1302
+ * so they are read as no value rather than matched against nothing.
1303
+ */
1304
+ /** Documentation uuids a model reproduces when it has no real id: RFC 4122
1305
+ * and RFC 9562 examples, and the ones tutorials and SDK docs print. */
1306
+ const SENTINEL_UUIDS = [
1307
+ "123e4567-e89b-12d3-a456-426614174000",
1308
+ "123e4567-e89b-12d3-a456-426655440000",
1309
+ "01234567-89ab-cdef-0123-456789abcdef",
1310
+ "12345678-1234-1234-1234-123456789012",
1311
+ "12345678-1234-5678-1234-567812345678",
1312
+ "12345678-90ab-cdef-1234-567890abcdef",
1313
+ "00000000-0000-0000-0000-000000000001"
1314
+ ];
1315
+ const SENTINELS = new Set(SENTINEL_UUIDS);
1316
+ const DASHED_RE = /^(?<a>[0-9a-f]{8})-(?<b>[0-9a-f]{4})-(?<c>[0-9a-f]{4})-(?<d>[0-9a-f]{4})-(?<e>[0-9a-f]{12})$/u;
1317
+ const DASHLESS_RE = /^(?<a>[0-9a-f]{8})(?<b>[0-9a-f]{4})(?<c>[0-9a-f]{4})(?<d>[0-9a-f]{4})(?<e>[0-9a-f]{12})$/u;
1318
+ const URN_PREFIX_RE = /^urn:uuid:/u;
1319
+ const BRACED_RE = /^\{(?<inner>.*)\}$/u;
1320
+ /** One hex digit repeated 32 times: the nil uuid, the max uuid, and every
1321
+ * `1111…` a model types to fill a slot. */
1322
+ const REPEATED_DIGIT_RE = /^(?<digit>[0-9a-f])\k<digit>{31}$/u;
1323
+ const UUID_EXPECTED = "an id";
1324
+ const UUID_HINT = "Pass an id a previous call returned, or omit the property when not filtering by it.";
1325
+ /** Whether a canonical uuid is one a model writes for "some id" rather than a
1326
+ * record's: nil, max, one repeated digit, or a documentation example. */
1327
+ const isSentinelUuid = (canonical) => SENTINELS.has(canonical) || REPEATED_DIGIT_RE.test(canonical.replaceAll("-", ""));
1328
+ /** The lowercase dashed form of a uuid in any of the spellings that name one
1329
+ * value, or null. */
1330
+ const canonicalUuid = (input) => {
1331
+ const lowered = input.trim().toLowerCase().replace(URN_PREFIX_RE, "");
1332
+ const unbraced = BRACED_RE.exec(lowered)?.groups?.["inner"] ?? lowered;
1333
+ const groups = (DASHED_RE.exec(unbraced) ?? DASHLESS_RE.exec(unbraced))?.groups;
1334
+ if (groups === void 0) return null;
1335
+ return [
1336
+ groups["a"],
1337
+ groups["b"],
1338
+ groups["c"],
1339
+ groups["d"],
1340
+ groups["e"]
1341
+ ].join("-");
1342
+ };
1343
+ /** Read an id an agent spelled its own way, as a lowercase dashed uuid. A
1344
+ * placeholder or an invented id is no value. */
1345
+ const normalizeUuid = (input, options = {}) => {
1346
+ if (isAbsentPlaceholder(input)) return readAsAbsent(input);
1347
+ const canonical = typeof input === "string" ? canonicalUuid(input) : null;
1348
+ if (canonical === null) return askForFix({
1349
+ input,
1350
+ expected: options.expected ?? UUID_EXPECTED,
1351
+ hint: options.hint ?? UUID_HINT
1352
+ });
1353
+ if (isSentinelUuid(canonical)) return readAsAbsent(input, "a placeholder id, not a record");
1354
+ return readValueAs(input, canonical);
1355
+ };
1356
+ //#endregion
1357
+ //#region src/vocabulary.ts
1358
+ /**
1359
+ * Filter values whose allowed set comes from data: court names, decision types,
1360
+ * register sections.
1361
+ *
1362
+ * A closed schema enum is short and fixed, so `normalizeEnumValue` reads case
1363
+ * and spacing and asks about anything else. A data vocabulary is neither: it
1364
+ * holds hundreds of court names the model has only ever seen in running text,
1365
+ * where they appear with the country appended (`Ústavní soud České republiky`),
1366
+ * without diacritics, abbreviated, or cut short (`Krajský soud`). Each of those
1367
+ * still names one entry often enough to be worth reading, and names several
1368
+ * often enough that guessing would quietly filter to the wrong court.
1369
+ *
1370
+ * So the reader works in widening steps and stops at the first one that finds
1371
+ * exactly one entry: the value itself, the value folded, an alias folded, an
1372
+ * entry whose every word the input contains, then an entry that contains every
1373
+ * word of the input. Several at one step is an ask naming them.
1374
+ */
1375
+ const DEFAULT_MAX_LISTED = 12;
1376
+ const VOCABULARY_EXPECTED = "one of the known values";
1377
+ /** Punctuation a name picks up in running text (`Nejvyšší soud ČR,`,
1378
+ * `"Krajský soud"`) without changing which entry it names. */
1379
+ const IGNORED_PUNCTUATION_RE = /[.,;:()"']/gu;
1380
+ const WORD_JOINER_RE = /[-_]/gu;
1381
+ const WHITESPACE_RE = /\s+/gu;
1382
+ /** The comparison form: case, diacritics, punctuation and word joiners carry
1383
+ * no meaning in a name drawn from data. */
1384
+ const fold = (value) => foldToAscii(value).toLowerCase().replace(IGNORED_PUNCTUATION_RE, "").replace(WORD_JOINER_RE, " ").replace(WHITESPACE_RE, " ").trim();
1385
+ const tokensOf = (folded) => new Set(folded === "" ? [] : folded.split(" "));
1386
+ const isSubset = (inner, outer) => [...inner].every((token) => outer.has(token));
1387
+ /** Every spelling an entry answers to, as token sets. */
1388
+ const formsOf = (entry) => [entry.value, ...entry.aliases ?? []].map((form) => tokensOf(fold(form))).filter((tokens) => tokens.size > 0);
1389
+ const quoteBounded = (values, maxListed) => {
1390
+ const listed = values.slice(0, maxListed).map((value) => `"${value}"`).join(", ");
1391
+ const rest = values.length - maxListed;
1392
+ return rest > 0 ? `${listed}, and ${rest} more` : listed;
1393
+ };
1394
+ /** Values in the caller's order, each once: aliases of one entry, or two
1395
+ * entries sharing a value, must not list it twice. */
1396
+ const distinctValues = (entries) => [...new Set(entries.map((entry) => entry.value))];
1397
+ /**
1398
+ * Read one value of a vocabulary drawn from data. A placeholder is no value; a
1399
+ * spelling that narrows to one entry reads as it with a note; a spelling that
1400
+ * matches several, or none, asks and names what there is.
1401
+ */
1402
+ const normalizeVocabularyValue = (input, entries, options = {}) => {
1403
+ const expected = options.expected ?? VOCABULARY_EXPECTED;
1404
+ const maxListed = options.maxListed ?? DEFAULT_MAX_LISTED;
1405
+ const allValues = distinctValues(entries);
1406
+ const listed = allValues.length === 0 ? "No values are known for this filter; omit the property." : `${options.label ?? "The values"} include ${quoteBounded(allValues, maxListed)}.`;
1407
+ const askListing = () => askForFix({
1408
+ input,
1409
+ expected,
1410
+ hint: listed
1411
+ });
1412
+ const askAmong = (candidates) => askForFix({
1413
+ input,
1414
+ expected,
1415
+ hint: `Did you mean one of ${quoteBounded(distinctValues(candidates), maxListed)}?`
1416
+ });
1417
+ if (typeof input !== "string") return askListing();
1418
+ if (isAbsentPlaceholder(input)) return readAsAbsent(input);
1419
+ const exact = entries.find((entry) => entry.value === input);
1420
+ if (exact !== void 0) return readValueAs(input, exact.value);
1421
+ const folded = fold(input);
1422
+ const readOneOf = (matches) => {
1423
+ const [only, ...others] = distinctValues(matches);
1424
+ if (only === void 0) return;
1425
+ return others.length === 0 ? readValueAs(input, only) : askAmong(matches);
1426
+ };
1427
+ const byValue = readOneOf(entries.filter((entry) => fold(entry.value) === folded));
1428
+ if (byValue !== void 0) return byValue;
1429
+ const byAlias = readOneOf(entries.filter((entry) => (entry.aliases ?? []).some((alias) => fold(alias) === folded)));
1430
+ if (byAlias !== void 0) return byAlias;
1431
+ const inputTokens = tokensOf(folded);
1432
+ if (inputTokens.size === 0) return askListing();
1433
+ const contained = entries.map((entry) => ({
1434
+ entry,
1435
+ size: Math.max(0, ...formsOf(entry).filter((tokens) => isSubset(tokens, inputTokens)).map((tokens) => tokens.size))
1436
+ })).filter(({ size }) => size > 0);
1437
+ const largest = Math.max(0, ...contained.map(({ size }) => size));
1438
+ const containedBest = contained.filter(({ size }) => size === largest).map(({ entry }) => entry);
1439
+ const [onlyContained, ...otherContained] = distinctValues(containedBest);
1440
+ if (onlyContained !== void 0) return otherContained.length === 0 ? readValueAs(input, onlyContained) : askAmong(containedBest);
1441
+ const containing = entries.filter((entry) => formsOf(entry).some((tokens) => isSubset(inputTokens, tokens)));
1442
+ const [onlyContaining, ...otherContaining] = distinctValues(containing);
1443
+ if (onlyContaining === void 0) return askListing();
1444
+ return otherContaining.length === 0 ? readValueAs(input, onlyContaining) : askAmong(containing);
1445
+ };
1446
+ //#endregion
1447
+ //#region src/schema.ts
1448
+ const AGENT_INPUT_NORMALIZATION_KEY = "x-stella-agent-input";
1449
+ const AGENT_INPUT_NORMALIZATION_KIND = {
1450
+ boolean: "boolean",
1451
+ country: "country",
1452
+ date: "date",
1453
+ dateFormat: "date-format",
1454
+ eli: "eli",
1455
+ enum: "enum",
1456
+ filter: "filter",
1457
+ locale: "locale",
1458
+ number: "number",
1459
+ stringList: "string-list",
1460
+ uuid: "uuid"
1461
+ };
1462
+ /** Attach an explicit normalization kind to a canonical JSON Schema field. */
1463
+ const agentInputNormalization = (annotation) => ({ [AGENT_INPUT_NORMALIZATION_KEY]: annotation });
1464
+ /** Concise model guidance derived from the same kind dispatch executes. */
1465
+ const agentInputNormalizationGuidance = (annotation) => {
1466
+ switch (annotation.kind) {
1467
+ case "boolean": return "Use a JSON boolean; common unambiguous yes/no words are normalized.";
1468
+ case "country": return "An ISO 3166-1 alpha-3 or alpha-2 code, or the country's name, is read.";
1469
+ case "date": return annotation.bound === void 0 ? "Use ISO YYYY-MM-DD; unambiguous localized calendar dates are normalized." : `Use ISO YYYY-MM-DD; a bare year or year-month reads as its ${annotation.bound === "start" ? "first" : "last"} day.`;
1470
+ case "date-format": return "Use an object with a BCP-47 locale, such as {\"locale\":\"en-GB\",\"style\":\"short\"}; an unambiguous combined string such as \"en-GB-short\" is normalized.";
1471
+ case "eli": return "A short, prefix-less or reordered ELI is read as the canonical one.";
1472
+ case "enum": return "Use an advertised value; case and surrounding whitespace are normalized.";
1473
+ case "filter": return "Omit it to search without this filter; a placeholder such as \"all\" or \"-\" reads as no filter.";
1474
+ case "locale": return "Use a BCP-47 language tag, for example \"cs\" or \"en-GB\".";
1475
+ case "number": return annotation.range === "clamp" ? "Use a JSON number; a value outside the range is clamped to it." : "Use a JSON number; unambiguous localized numeric notation is normalized.";
1476
+ case "string-list": return "Use a JSON array of strings; a single string is read as a one-item list.";
1477
+ case "uuid": return "Use an id a previous call returned; a placeholder id such as all zeros reads as no value.";
1478
+ default: return panic("Unhandled agent input normalization kind");
1479
+ }
1480
+ };
1481
+ /** Schema metadata shared by MCP descriptions and generated CLI help. */
1482
+ const agentInputNormalizationMetadata = (annotation, description) => {
1483
+ const guidance = agentInputNormalizationGuidance(annotation);
1484
+ const authored = description?.trim();
1485
+ return {
1486
+ ...agentInputNormalization(annotation),
1487
+ description: authored === void 0 || authored.length === 0 ? guidance : `${authored}${/[.!?]$/u.test(authored) ? " " : ". "}${guidance}`
1488
+ };
1489
+ };
1490
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1491
+ const isUnknownArray = (value) => Array.isArray(value);
1492
+ const joinPath = (path, segment) => path.length === 0 ? segment : `${path}.${segment}`;
1493
+ const annotationOf = (schema) => {
1494
+ const annotation = schema[AGENT_INPUT_NORMALIZATION_KEY];
1495
+ if (!isRecord(annotation)) return;
1496
+ const kind = annotation["kind"];
1497
+ const normalizedKind = Object.values(AGENT_INPUT_NORMALIZATION_KIND).find((candidate) => candidate === kind);
1498
+ if (normalizedKind === void 0) return;
1499
+ const locale = annotation["locale"];
1500
+ const disposition = annotation["invalidValueDisposition"] === "handler-owned" ? "handler-owned" : void 0;
1501
+ const bound = annotation["bound"];
1502
+ const common = {
1503
+ ...disposition === void 0 ? {} : { invalidValueDisposition: disposition },
1504
+ ...typeof locale === "string" ? { locale } : {},
1505
+ ...bound === "start" || bound === "end" ? { bound } : {},
1506
+ ...annotation["range"] === "clamp" ? { range: "clamp" } : {}
1507
+ };
1508
+ if (normalizedKind === AGENT_INPUT_NORMALIZATION_KIND.country) {
1509
+ const country = countryAnnotationOf(annotation["country"]);
1510
+ return country === void 0 ? void 0 : {
1511
+ ...common,
1512
+ kind: normalizedKind,
1513
+ country
1514
+ };
1515
+ }
1516
+ return {
1517
+ ...common,
1518
+ kind: normalizedKind
1519
+ };
1520
+ };
1521
+ /** The country half of an annotation, read back from the emitted schema. */
1522
+ const countryAnnotationOf = (value) => {
1523
+ if (!isRecord(value)) return;
1524
+ const spelling = value["spelling"];
1525
+ if (spelling !== "alpha-3" && spelling !== "alpha-2") return;
1526
+ const admitted = value["admitted"];
1527
+ const tool = value["tool"];
1528
+ return {
1529
+ spelling,
1530
+ ...isUnknownArray(admitted) && admitted.every((code) => typeof code === "string") ? { admitted } : {},
1531
+ ...typeof tool === "string" ? { tool } : {}
1532
+ };
1533
+ };
1534
+ const stringEnumOf = (schema) => {
1535
+ const values = schema["enum"];
1536
+ if (isUnknownArray(values) && values.length > 0 && values.every((value) => typeof value === "string")) return values;
1537
+ if (typeof schema["const"] === "string") return [schema["const"]];
1538
+ for (const keyword of ["anyOf", "oneOf"]) {
1539
+ const branches = schema[keyword];
1540
+ if (!isUnknownArray(branches)) continue;
1541
+ const literals = [];
1542
+ for (const branch of branches) {
1543
+ if (!isRecord(branch)) return;
1544
+ if (branch["type"] === "null") continue;
1545
+ if (typeof branch["const"] !== "string") return;
1546
+ literals.push(branch["const"]);
1547
+ }
1548
+ return literals.length > 0 ? literals : void 0;
1549
+ }
1550
+ };
1551
+ const inferredAnnotationOf = (schema) => {
1552
+ const explicit = annotationOf(schema);
1553
+ if (explicit !== void 0) return explicit;
1554
+ if (schema["format"] === "date") return { kind: AGENT_INPUT_NORMALIZATION_KIND.date };
1555
+ const types = isUnknownArray(schema["type"]) ? schema["type"] : [schema["type"]];
1556
+ if (schema["format"] === "uuid" && types.includes("string")) return { kind: AGENT_INPUT_NORMALIZATION_KIND.uuid };
1557
+ if (types.includes("number") || types.includes("integer")) return { kind: AGENT_INPUT_NORMALIZATION_KIND.number };
1558
+ if (types.includes("boolean")) return { kind: AGENT_INPUT_NORMALIZATION_KIND.boolean };
1559
+ return stringEnumOf(schema) === void 0 ? void 0 : { kind: AGENT_INPUT_NORMALIZATION_KIND.enum };
1560
+ };
1561
+ /**
1562
+ * A country field carries a string, not the pair the reader returns, so the
1563
+ * canonical value is projected into the spelling the surface stores. The
1564
+ * annotation is what says which one; a country field declared without it would
1565
+ * silently store alpha-3 where a column holds alpha-2, so it is required.
1566
+ */
1567
+ const normalizeCountryLeaf = ({ country, path, value }) => {
1568
+ const spelling = country.spelling;
1569
+ const read = normalizeCountry(value, {
1570
+ spelling,
1571
+ admitted: country.admitted,
1572
+ tool: country.tool,
1573
+ parameter: path.split(".").at(-1)
1574
+ });
1575
+ return read.ok ? {
1576
+ ok: true,
1577
+ value: countryCodeIn(read.value, spelling),
1578
+ ...read.note === void 0 ? {} : { note: read.note }
1579
+ } : read;
1580
+ };
1581
+ const numericKeyword = (schema, keyword) => {
1582
+ const value = schema[keyword];
1583
+ return typeof value === "number" ? value : void 0;
1584
+ };
1585
+ const normalizeLeaf = ({ annotation, path, readers, schema, value }) => {
1586
+ switch (annotation.kind) {
1587
+ case "boolean": return normalizeBoolean(value);
1588
+ case "country": return normalizeCountryLeaf({
1589
+ country: annotation.country,
1590
+ path,
1591
+ value
1592
+ });
1593
+ case "date": {
1594
+ const locales = annotation.locale === void 0 ? void 0 : [annotation.locale];
1595
+ return annotation.bound === void 0 ? normalizeDateValue(value, locales === void 0 ? void 0 : { locales }) : normalizeDateBound(value, {
1596
+ bound: annotation.bound,
1597
+ locales
1598
+ });
1599
+ }
1600
+ case "date-format": return normalizeDateFormatSpec(value);
1601
+ case "eli": return readers.eli === void 0 ? void 0 : normalizeEli(value, readers.eli);
1602
+ case "enum": return normalizeEnumValue(value, stringEnumOf(schema) ?? []);
1603
+ case "filter": return isAbsentPlaceholder(value) ? readAsAbsent(value, "no filter") : {
1604
+ ok: true,
1605
+ value
1606
+ };
1607
+ case "locale": return normalizeLocale(value);
1608
+ case "number": {
1609
+ const locale = annotation.locale;
1610
+ if (annotation.range === "clamp") {
1611
+ const types = isUnknownArray(schema["type"]) ? schema["type"] : [schema["type"]];
1612
+ return normalizeNumberInRange(value, {
1613
+ minimum: numericKeyword(schema, "minimum"),
1614
+ maximum: numericKeyword(schema, "maximum"),
1615
+ integer: types.includes("integer"),
1616
+ ...locale === void 0 ? {} : { locale }
1617
+ });
1618
+ }
1619
+ return normalizeNumber(value, locale === void 0 ? void 0 : { locale });
1620
+ }
1621
+ case "string-list": return normalizeStringList(value, { split: "never" });
1622
+ case "uuid": return normalizeUuid(value);
1623
+ default: return panic("Unhandled agent input normalization kind");
1624
+ }
1625
+ };
1626
+ /**
1627
+ * A placeholder where a value is required is not an omission the caller may
1628
+ * make, so it is asked about rather than dropped: the call cannot mean
1629
+ * anything without the property.
1630
+ */
1631
+ const placeholderIssue = (path, absent, presence) => {
1632
+ const subject = path.length === 0 ? "This value" : `'${path}'`;
1633
+ return {
1634
+ path,
1635
+ received: absent.received,
1636
+ expected: "a real value",
1637
+ hint: presence === "required" ? `${subject} is required: pass a value a previous call returned, not a placeholder.` : `${subject} holds a placeholder: omit it, or pass a value a previous call returned.`
1638
+ };
1639
+ };
1640
+ /** Whether an array schema holds strings, so a lone string can be its one item. */
1641
+ const holdsStrings = (items) => {
1642
+ if (!isRecord(items)) return false;
1643
+ return (isUnknownArray(items["type"]) ? items["type"] : [items["type"]]).includes("string") || stringEnumOf(items) !== void 0;
1644
+ };
1645
+ /**
1646
+ * Whether a string list's items are constrained tokens (an id, a code, an
1647
+ * advertised value), which never carry a comma of their own, so a
1648
+ * comma-joined string is a list. Free text is never split.
1649
+ */
1650
+ const holdsTokens = (items) => isRecord(items) && (typeof items["format"] === "string" || typeof items["pattern"] === "string" || stringEnumOf(items) !== void 0);
1651
+ const MAX_SCHEMA_REFERENCE_DEPTH = 64;
1652
+ const valueMatchesType = (type, value) => {
1653
+ switch (type) {
1654
+ case "array": return Array.isArray(value) || typeof value === "string";
1655
+ case "boolean": return typeof value === "boolean" || typeof value === "string";
1656
+ case "integer":
1657
+ case "number": return typeof value === "number" || typeof value === "string";
1658
+ case "null": return value === null;
1659
+ case "object": return isRecord(value);
1660
+ case "string": return typeof value === "string";
1661
+ default: return true;
1662
+ }
1663
+ };
1664
+ const walkUnion = ({ branches, value, path, context }) => {
1665
+ const results = branches.filter((branch) => isRecord(branch) && valueMatchesType(branch["type"], value)).map((branch) => walkSchema({
1666
+ schema: branch,
1667
+ value,
1668
+ path,
1669
+ context
1670
+ }));
1671
+ const successful = results.filter((result) => result.status === "normalized" || result.status === "absent");
1672
+ if (successful.length === 0) {
1673
+ if (results.some((result) => result.status === "not-applicable")) return { status: "not-applicable" };
1674
+ const invalid = results.filter((result) => result.status === "invalid");
1675
+ return invalid.length === 1 ? invalid.at(0) ?? { status: "not-applicable" } : { status: "not-applicable" };
1676
+ }
1677
+ const canonical = /* @__PURE__ */ new Map();
1678
+ for (const result of successful) canonical.set(result.status === "absent" ? "absent" : JSON.stringify(result.value), result);
1679
+ if (canonical.size !== 1) return { status: "not-applicable" };
1680
+ return canonical.values().next().value ?? { status: "not-applicable" };
1681
+ };
1682
+ const resolveLocalReference = (reference, rootSchema) => {
1683
+ if (reference === "#") return rootSchema;
1684
+ if (!reference.startsWith("#/")) return;
1685
+ let resolved = rootSchema;
1686
+ for (const rawSegment of reference.slice(2).split("/")) {
1687
+ if (!isRecord(resolved)) return;
1688
+ const segment = rawSegment.replaceAll("~1", "/").replaceAll("~0", "~");
1689
+ resolved = resolved[segment];
1690
+ }
1691
+ return resolved;
1692
+ };
1693
+ const walkIntersection = ({ schema, branches, value, path, context }) => {
1694
+ let current = value;
1695
+ const notes = [];
1696
+ const issues = [];
1697
+ let applied = false;
1698
+ for (const branch of branches) {
1699
+ const result = walkSchema({
1700
+ schema: branch,
1701
+ value: current,
1702
+ path,
1703
+ context
1704
+ });
1705
+ if (result.status === "invalid") {
1706
+ issues.push(...result.issues);
1707
+ continue;
1708
+ }
1709
+ if (result.status === "absent") return result;
1710
+ if (result.status === "normalized") {
1711
+ applied = true;
1712
+ current = result.value;
1713
+ notes.push(...result.notes);
1714
+ }
1715
+ }
1716
+ if (issues.length > 0) return {
1717
+ status: "invalid",
1718
+ issues
1719
+ };
1720
+ const { allOf: _allOf, ...siblings } = schema;
1721
+ const siblingResult = walkSchema({
1722
+ schema: siblings,
1723
+ value: current,
1724
+ path,
1725
+ context
1726
+ });
1727
+ if (siblingResult.status === "invalid" || siblingResult.status === "absent") return siblingResult;
1728
+ if (siblingResult.status === "normalized") return {
1729
+ status: "normalized",
1730
+ value: siblingResult.value,
1731
+ notes: [...notes, ...siblingResult.notes]
1732
+ };
1733
+ return applied ? {
1734
+ status: "normalized",
1735
+ value: current,
1736
+ notes
1737
+ } : { status: "not-applicable" };
1738
+ };
1739
+ const walkSchema = ({ schema, value, path, context }) => {
1740
+ if (!isRecord(schema)) return { status: "not-applicable" };
1741
+ const reference = schema["$ref"];
1742
+ if (typeof reference === "string") {
1743
+ if (context.remainingReferenceDepth === 0) return { status: "not-applicable" };
1744
+ const resolved = resolveLocalReference(reference, context.rootSchema);
1745
+ return resolved === void 0 || resolved === schema ? { status: "not-applicable" } : walkSchema({
1746
+ schema: resolved,
1747
+ value,
1748
+ path,
1749
+ context: {
1750
+ ...context,
1751
+ remainingReferenceDepth: context.remainingReferenceDepth - 1
1752
+ }
1753
+ });
1754
+ }
1755
+ const intersections = schema["allOf"];
1756
+ if (isUnknownArray(intersections)) return walkIntersection({
1757
+ schema,
1758
+ branches: intersections,
1759
+ value,
1760
+ path,
1761
+ context
1762
+ });
1763
+ const explicitAnnotation = annotationOf(schema);
1764
+ if (explicitAnnotation === void 0) for (const keyword of ["anyOf", "oneOf"]) {
1765
+ const branches = schema[keyword];
1766
+ if (isUnknownArray(branches)) return walkUnion({
1767
+ branches,
1768
+ value,
1769
+ path,
1770
+ context
1771
+ });
1772
+ }
1773
+ const annotation = explicitAnnotation ?? inferredAnnotationOf(schema);
1774
+ const types = isUnknownArray(schema["type"]) ? schema["type"] : [schema["type"]];
1775
+ if (annotation !== void 0 && !(value === null && types.includes("null"))) {
1776
+ const normalized = normalizeLeaf({
1777
+ annotation,
1778
+ path,
1779
+ readers: context.readers,
1780
+ schema,
1781
+ value
1782
+ });
1783
+ if (normalized === void 0) return { status: "not-applicable" };
1784
+ if (normalized.ok === "absent") return {
1785
+ status: "absent",
1786
+ received: normalized.received,
1787
+ note: normalized.note
1788
+ };
1789
+ if (!normalized.ok) {
1790
+ if (annotation.invalidValueDisposition === "handler-owned") return { status: "not-applicable" };
1791
+ const { expected, hint, received } = normalized;
1792
+ return {
1793
+ status: "invalid",
1794
+ issues: [{
1795
+ path,
1796
+ received,
1797
+ expected,
1798
+ hint
1799
+ }]
1800
+ };
1801
+ }
1802
+ return {
1803
+ status: "normalized",
1804
+ value: normalized.value,
1805
+ notes: normalized.note === void 0 ? [] : [normalized.note]
1806
+ };
1807
+ }
1808
+ for (const keyword of ["anyOf", "oneOf"]) {
1809
+ const branches = schema[keyword];
1810
+ if (isUnknownArray(branches)) return walkUnion({
1811
+ branches,
1812
+ value,
1813
+ path,
1814
+ context
1815
+ });
1816
+ }
1817
+ const properties = schema["properties"];
1818
+ const patternProperties = schema["patternProperties"];
1819
+ if (isRecord(value) && (isRecord(properties) || isRecord(patternProperties))) return walkObject({
1820
+ schema,
1821
+ value,
1822
+ path,
1823
+ context
1824
+ });
1825
+ const items = schema["items"];
1826
+ return items === void 0 ? { status: "not-applicable" } : walkList({
1827
+ items,
1828
+ value,
1829
+ path,
1830
+ context
1831
+ });
1832
+ };
1833
+ /** The schemas one property of an object is read against, in order. */
1834
+ const childSchemasOf = (schema, key) => {
1835
+ const properties = schema["properties"];
1836
+ const patternProperties = schema["patternProperties"];
1837
+ const childSchemas = [];
1838
+ if (isRecord(properties) && key in properties) childSchemas.push(properties[key]);
1839
+ if (isRecord(patternProperties)) {
1840
+ for (const [pattern, childSchema] of Object.entries(patternProperties)) if (new RegExp(pattern, "u").test(key)) childSchemas.push(childSchema);
1841
+ }
1842
+ const additionalProperties = schema["additionalProperties"];
1843
+ if (childSchemas.length === 0 && isRecord(additionalProperties)) childSchemas.push(additionalProperties);
1844
+ return childSchemas;
1845
+ };
1846
+ const walkObject = ({ schema, value, path, context }) => {
1847
+ const output = {};
1848
+ const notes = [];
1849
+ const issues = [];
1850
+ const requiredKeys = schema["required"];
1851
+ const required = new Set(isUnknownArray(requiredKeys) ? requiredKeys : []);
1852
+ for (const [key, entry] of Object.entries(value)) {
1853
+ let reading = {
1854
+ status: "value",
1855
+ value: entry
1856
+ };
1857
+ for (const childSchema of childSchemasOf(schema, key)) {
1858
+ if (reading.status === "absent") break;
1859
+ const child = walkSchema({
1860
+ schema: childSchema,
1861
+ value: reading.value,
1862
+ path: joinPath(path, key),
1863
+ context
1864
+ });
1865
+ if (child.status === "invalid") issues.push(...child.issues);
1866
+ else if (child.status === "absent") {
1867
+ const presence = required.has(key) ? "required" : "optional";
1868
+ if (presence === "required" || context.placeholders === "ask") issues.push(placeholderIssue(joinPath(path, key), child, presence));
1869
+ else {
1870
+ reading = { status: "absent" };
1871
+ notes.push(child.note);
1872
+ }
1873
+ } else if (child.status === "normalized") {
1874
+ reading = {
1875
+ status: "value",
1876
+ value: child.value
1877
+ };
1878
+ notes.push(...child.notes);
1879
+ }
1880
+ }
1881
+ if (reading.status === "value") output[key] = reading.value;
1882
+ }
1883
+ return issues.length > 0 ? {
1884
+ status: "invalid",
1885
+ issues
1886
+ } : {
1887
+ status: "normalized",
1888
+ value: output,
1889
+ notes
1890
+ };
1891
+ };
1892
+ const walkList = ({ items, value, path, context }) => {
1893
+ const notes = [];
1894
+ let list = value;
1895
+ if (typeof value === "string" && holdsStrings(items)) {
1896
+ const read = normalizeStringList(value, { split: holdsTokens(items) ? "delimiters" : "never" });
1897
+ if (!read.ok) {
1898
+ const { expected, hint, received } = read;
1899
+ return {
1900
+ status: "invalid",
1901
+ issues: [{
1902
+ path,
1903
+ received,
1904
+ expected,
1905
+ hint
1906
+ }]
1907
+ };
1908
+ }
1909
+ list = read.value;
1910
+ if (read.note !== void 0) notes.push(read.note);
1911
+ }
1912
+ if (!isUnknownArray(list)) return { status: "not-applicable" };
1913
+ const output = [];
1914
+ const issues = [];
1915
+ for (const [index, entry] of list.entries()) {
1916
+ const child = walkSchema({
1917
+ schema: items,
1918
+ value: entry,
1919
+ path: joinPath(path, String(index)),
1920
+ context
1921
+ });
1922
+ if (child.status === "invalid") issues.push(...child.issues);
1923
+ else if (child.status === "absent") issues.push(placeholderIssue(joinPath(path, String(index)), child, "required"));
1924
+ else if (child.status === "normalized") notes.push(...child.notes);
1925
+ output.push(child.status === "normalized" ? child.value : entry);
1926
+ }
1927
+ return issues.length > 0 ? {
1928
+ status: "invalid",
1929
+ issues
1930
+ } : {
1931
+ status: "normalized",
1932
+ value: output,
1933
+ notes
1934
+ };
1935
+ };
1936
+ /**
1937
+ * Normalize one agent-written value from its canonical JSON Schema. Standard
1938
+ * `type`, `format: date`, and string `enum` keywords are the annotations for
1939
+ * numbers, booleans, dates, and closed vocabularies. The extension key handles
1940
+ * kinds JSON Schema cannot name, such as locales and date-format specs.
1941
+ */
1942
+ const normalizeAgentInput = ({ path = "", placeholders = "absent", readers = {}, schema, value }) => {
1943
+ const result = walkSchema({
1944
+ schema,
1945
+ value,
1946
+ path,
1947
+ context: {
1948
+ placeholders,
1949
+ readers,
1950
+ rootSchema: schema,
1951
+ remainingReferenceDepth: MAX_SCHEMA_REFERENCE_DEPTH
1952
+ }
1953
+ });
1954
+ if (result.status === "invalid") return {
1955
+ ok: false,
1956
+ issues: result.issues
1957
+ };
1958
+ if (result.status === "absent") return {
1959
+ ok: true,
1960
+ value: void 0,
1961
+ notes: [result.note]
1962
+ };
1963
+ return result.status === "normalized" ? {
1964
+ ok: true,
1965
+ value: result.value,
1966
+ notes: result.notes
1967
+ } : {
1968
+ ok: true,
1969
+ value,
1970
+ notes: []
1971
+ };
1972
+ };
1973
+ //#endregion
1974
+ export { ABSENT_PLACEHOLDERS, AGENT_INPUT_NORMALIZATION_KEY, AGENT_INPUT_NORMALIZATION_KIND, COUNTRY_INPUT_MAX_CHARS, DATE_FORMAT_SPEC_HINT, DATE_VALUE_HINT, SENTINEL_UUIDS, agentInputNormalization, agentInputNormalizationGuidance, agentInputNormalizationMetadata, askForFix, askSentence, countryCodeIn, isAbsentPlaceholder, isPlausibleLocale, isSentinelUuid, normalizeAgentInput, normalizeBoolean, normalizeCountry, normalizeDateBound, normalizeDateFormatSpec, normalizeDateValue, normalizeEli, normalizeEnumValue, normalizeLocale, normalizeNumber, normalizeNumberInRange, normalizeStringList, normalizeUuid, normalizeVocabularyValue, readAsAbsent };