sil-openclaw 0.3.9 → 0.4.1

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.
@@ -44,13 +44,22 @@
44
44
  * result; logs carry only non-credential status markers (search params are not
45
45
  * credentials, but are not logged either — nothing here needs them).
46
46
  *
47
+ * The group hosts THREE catalog tools sharing this origin, Bearer, and 401
48
+ * choreography: `sil_search` (discovery), `sil_product_get` (the lookup companion),
49
+ * and `sil_specs` (the spec-REGISTRY dedupe-or-create up-flow — the method
50
+ * canonicalizes its coined `ns.key` vocabulary at Beat-2 mint/refresh, so
51
+ * `filters.specs` converges). The structured-error envelope helpers (`notRegistered`
52
+ * / `mustReregister` / `transient` / `forbidden` / `invalidRequest`) are
53
+ * tool-parameterized and shared across all three — a new catalog tool reuses them,
54
+ * it does not fork them.
55
+ *
47
56
  * `register()` stays synchronous and side-effect-free beyond registering tools —
48
57
  * no fetch, no timer, no unawaited promise. All I/O is inside `execute()`.
49
58
  */
50
59
  import { Type } from "typebox";
51
60
  import { getApiUrl } from "../lib/config.js";
52
61
  import { clearTokens, readTokens } from "../lib/credentials.js";
53
- import { lookupCatalog, refreshAndRetryOnce, searchCatalog, } from "../lib/sil-client.js";
62
+ import { lookupCatalog, refreshAndRetryOnce, searchCatalog, specsCatalog, } from "../lib/sil-client.js";
54
63
  import { jsonResult } from "../lib/tool-result.js";
55
64
  /**
56
65
  * The TIGHTENED ship-to format contract (founder re-spec 2026-06-11), pinned as a
@@ -72,9 +81,50 @@ import { jsonResult } from "../lib/tool-result.js";
72
81
  const COUNTRY_PATTERN = "^[A-Za-z]{2}$";
73
82
  const REGION_PATTERN = "^[A-Za-z0-9]{1,3}$";
74
83
  const POSTAL_PATTERN = "^(?=[A-Za-z0-9 -]{2,12}$)[A-Za-z0-9]+(?:[ -][A-Za-z0-9]+)*$";
84
+ /** The `sil_specs` coined-definition schema. Unlike the search predicate's `value`
85
+ * (an op→value read-site rule the schema can't express), a `SpecDefinition` is
86
+ * FULLY TypeBox-expressible — a closed `data_type` union of four literals plus
87
+ * `minLength:1` identity fields and optional context — so the host validates the
88
+ * shape directly. Mirrors `@sil/schemas` `SpecDefinition` (the frozen wire contract). */
89
+ const SPEC_DEFINITION_SCHEMA = Type.Object({
90
+ namespace: Type.String({
91
+ minLength: 1,
92
+ description: "The spec NAMESPACE (e.g. \"product\", \"seller\", \"shipping\") — a free"
93
+ + " string coined bottom-up; NOT dotted with the key.",
94
+ }),
95
+ key: Type.String({
96
+ minLength: 1,
97
+ description: "The spec KEY within the namespace (e.g. \"waterproof_rating\","
98
+ + " \"rating_average\") — a free string coined bottom-up.",
99
+ }),
100
+ display_name: Type.String({
101
+ minLength: 1,
102
+ description: "A short human label for the spec (e.g. \"Waterproof rating\").",
103
+ }),
104
+ data_type: Type.Union([
105
+ Type.Literal("number"),
106
+ Type.Literal("text"),
107
+ Type.Literal("boolean"),
108
+ Type.Literal("enum"),
109
+ ], {
110
+ description: "The spec's value type: number, text, boolean, or enum (use enum with"
111
+ + " allowed_values for a closed set).",
112
+ }),
113
+ description: Type.Optional(Type.String({
114
+ description: "Optional prose describing what the spec means — sharpens the registry's"
115
+ + " dedupe (a clearer definition reduces false matches).",
116
+ })),
117
+ unit: Type.Optional(Type.String({
118
+ description: "Optional unit for a numeric spec (e.g. \"mm\", \"GB\", \"days\").",
119
+ })),
120
+ allowed_values: Type.Optional(Type.Array(Type.String(), {
121
+ description: "For an enum spec, the closed set of permitted values.",
122
+ })),
123
+ });
75
124
  export function registerCatalogTools(api) {
76
125
  registerSearch(api);
77
126
  registerProductGet(api);
127
+ registerSpecs(api);
78
128
  }
79
129
  function registerSearch(api) {
80
130
  api.registerTool({
@@ -128,7 +178,17 @@ function registerSearch(api) {
128
178
  + " results are all local. To surface MORE local shops you MAY also issue the"
129
179
  + " `query` in that country's language (a Greek-language query surfaces Greek"
130
180
  + " shops) — optional, and never an override of a language the user deliberately"
131
- + " chose; pass NO country — sil resolves it server-side. Requires registration (run"
181
+ + " chose; pass NO country — sil resolves it server-side. `specs` is the"
182
+ + " STRUCTURED requirement channel — a list of typed predicates ({ ns, key, op,"
183
+ + " value, unit?, hard? }) for the OPEN LONG-TAIL of attributes that have no"
184
+ + " dedicated param (e.g. product.capacity_gb, seller.rating_average,"
185
+ + " shipping.delivery_max_days). PREFER A DEDICATED PARAM OVER A `specs`"
186
+ + " PREDICATE FOR THE SAME ATTRIBUTE: route price to price_min/price_max,"
187
+ + " category to category, condition to condition, availability to available,"
188
+ + " and the delivery destination to ship_to — never send both a dedicated"
189
+ + " param and a `specs` predicate for the one attribute (that risks an"
190
+ + " over-narrow or divergent result). Mark a predicate `hard: true` when the"
191
+ + " requirement is inviolable. Requires registration (run"
132
192
  + " sil_register first).",
133
193
  parameters: Type.Object({
134
194
  query: Type.Optional(Type.String({
@@ -202,6 +262,53 @@ function registerSearch(api) {
202
262
  + " default; set false to INCLUDE unavailable/out-of-stock items. Omit"
203
263
  + " to keep the default (available only).",
204
264
  })),
265
+ specs: Type.Optional(Type.Array(Type.Object({
266
+ ns: Type.String({
267
+ description: "The predicate NAMESPACE (e.g. \"product\", \"seller\", \"shipping\")"
268
+ + " — a free string, coined bottom-up; NOT dotted with the key.",
269
+ }),
270
+ key: Type.String({
271
+ description: "The predicate KEY within the namespace (e.g. \"capacity_gb\","
272
+ + " \"rating_average\") — a free string, coined bottom-up.",
273
+ }),
274
+ op: Type.Union([
275
+ Type.Literal("eq"),
276
+ Type.Literal("neq"),
277
+ Type.Literal("gte"),
278
+ Type.Literal("lte"),
279
+ Type.Literal("in"),
280
+ Type.Literal("nin"),
281
+ Type.Literal("exists"),
282
+ ], {
283
+ description: "The comparison operator. `gte`/`lte` need a number `value`;"
284
+ + " `in`/`nin` need an array `value`; `eq`/`neq` need a scalar"
285
+ + " `value`; `exists` takes NO `value`.",
286
+ }),
287
+ value: Type.Optional(Type.Union([
288
+ Type.Number(),
289
+ Type.String(),
290
+ Type.Boolean(),
291
+ Type.Array(Type.Union([Type.String(), Type.Number()])),
292
+ ], {
293
+ description: "The compared value, matching the op (omit it for `exists`).",
294
+ })),
295
+ unit: Type.Optional(Type.String({
296
+ description: "The value's unit (e.g. \"mm\", \"GB\", \"days\") — optional context"
297
+ + " carried on the wire.",
298
+ })),
299
+ hard: Type.Optional(Type.Boolean({
300
+ description: "Set true when the requirement is INVIOLABLE (a hard constraint the"
301
+ + " result must satisfy), false/omit for a soft preference.",
302
+ })),
303
+ }), {
304
+ description: "Structured requirement predicates for the OPEN LONG-TAIL of attributes"
305
+ + " with no dedicated param (product.capacity_gb, seller.rating_average,"
306
+ + " shipping.delivery_max_days). Each { ns, key, op, value, unit?, hard? }"
307
+ + " rides the request under one namespaced `filters.specs` key. PREFER a"
308
+ + " dedicated param (price_min/price_max, category, condition, available,"
309
+ + " ship_to) over a `specs` predicate for the SAME attribute — never send"
310
+ + " both. Omit when there are no structured requirements.",
311
+ })),
205
312
  }),
206
313
  async execute(_callId, params) {
207
314
  // 1 — not registered: terminal, zero network calls.
@@ -217,6 +324,10 @@ function registerSearch(api) {
217
324
  // `invalid_filter` beats an opaque, fail-late sil-api 400 (re-spec).
218
325
  const read = readSearchParams(params);
219
326
  if (read.kind === "invalid") {
327
+ if (read.code === "invalid_spec") {
328
+ api.logger.info("sil_search_invalid_spec", { field: read.field });
329
+ return invalidSpec(read.field);
330
+ }
220
331
  api.logger.info("sil_search_invalid_filter", { field: read.field });
221
332
  return invalidFilter(read.field);
222
333
  }
@@ -447,6 +558,147 @@ function mapLookupOutcome(api, outcome) {
447
558
  return mustReregister("sil_product_get");
448
559
  }
449
560
  }
561
+ /**
562
+ * `sil_specs` — the spec-REGISTRY canonicalize-or-create tool. Driven by the
563
+ * sil-shopping method at Beat 2 (mint/refresh), NOT directly by the buyer: the
564
+ * method coins its niche `ns.key` vocabulary bottom-up from research, submits the
565
+ * coined DEFINITIONS here, and gets back the canonical name per spec to adopt BEFORE
566
+ * it persists — so the method is born speaking canonical names and the whole
567
+ * catalog's `filters.specs` vocabulary converges (that convergence is what makes
568
+ * `filters.specs` actually filter). A `matched` spec adopts the existing canonical
569
+ * name (drop the private synonym); a `created` spec keeps its own (it is canonical
570
+ * going forward).
571
+ *
572
+ * `execute()` flow (ALL I/O here; `register()` opens nothing — a synchronous
573
+ * request/response, NOT a poll). MIRRORS `sil_search` and shares its taxonomy, minus
574
+ * search's 422 arm and source attribution (the registry is sil's own Postgres):
575
+ * 1. Not registered (no stored tokens) → terminal `not_registered` + a
576
+ * `recovery: sil_register` hint, ZERO network calls. Mirrors `sil_whoami`.
577
+ * 2. Client-side guard: a blank/absent `query` OR an empty/all-dropped `specs`
578
+ * array → `invalid_request` (`empty_specs_input`), NO network call (sil-api's
579
+ * `minLength`/`minItems` schema 400 is the authoritative backstop). A single
580
+ * MALFORMED definition rejects the WHOLE request (`invalid_spec`) — a silently
581
+ * dropped coined spec would never canonicalize and never converge.
582
+ * 3. specsCatalog(getApiUrl(), token, params) → map the `SpecsOutcome`:
583
+ * ok → the `resolved` array (one resolution per submitted spec);
584
+ * invalid_request (400) → surface sil-api's `{ error, message }`;
585
+ * unauthorized (401) → refresh-and-retry ONCE via the shared
586
+ * `refreshAndRetryOnce` choreography (parity with
587
+ * `sil_search`/`sil_product_get`/`sil_whoami` — 401
588
+ * recovery is uniform). Recovered 401 is invisible;
589
+ * second 401 / dead refresh is terminal re-register
590
+ * (tokens cleared);
591
+ * retryable (5xx/net) → transient "try again", NO re-register hint (BARE —
592
+ * no source; the method degrades to raw coined names).
593
+ *
594
+ * GRACEFUL DEGRADATION is the load-bearing product invariant (AC14): a non-`ok`
595
+ * outcome never blocks the mint — the method proceeds with the RAW coined names
596
+ * (every predicate `applied:false`) and converges on the next mint/refresh. The tool
597
+ * only surfaces the registry's verdict; the method decides to degrade.
598
+ *
599
+ * Privacy: the session token and Bearer header never reach a log line or the result.
600
+ */
601
+ function registerSpecs(api) {
602
+ api.registerTool({
603
+ name: "sil_specs",
604
+ label: "Canonicalize coined spec definitions",
605
+ description: "Canonicalize the coined spec DEFINITIONS a method invents for a niche — the"
606
+ + " dedupe-or-create registry call at method mint/refresh. Pass the motivating"
607
+ + " `query` and `specs` (coined { namespace, key, display_name, data_type,"
608
+ + " description?, unit?, allowed_values? }). Each resolves 1:1: `matched` → adopt"
609
+ + " the returned canonical { namespace, key } and drop your synonym; `created` →"
610
+ + " yours is novel, keep it. Rewrite the method's search vocabulary + any PRD"
611
+ + " predicates to the canonical names before persisting. Internal plumbing — never"
612
+ + " surface ns.key to the buyer. If not `ok`, do NOT block the mint: persist raw and"
613
+ + " converge on the next mint/refresh. Requires registration.",
614
+ parameters: Type.Object({
615
+ query: Type.String({
616
+ description: "The motivating shopping query — what the shopper is buying. Governance /"
617
+ + " dedupe context for the registry; required and non-empty.",
618
+ }),
619
+ specs: Type.Array(SPEC_DEFINITION_SCHEMA, {
620
+ minItems: 1,
621
+ description: "The coined spec definitions to canonicalize (at least one). Each is a"
622
+ + " { namespace, key, display_name, data_type, description?, unit?,"
623
+ + " allowed_values? } the method coined bottom-up from research.",
624
+ }),
625
+ }),
626
+ async execute(_callId, params) {
627
+ // 1 — not registered: terminal, zero network calls.
628
+ const stored = readTokens();
629
+ if (stored === null) {
630
+ return notRegistered("sil_specs");
631
+ }
632
+ // 2 — client-side guard (defensive drifted-call backstop; the host validates
633
+ // the schema, but a blank query / empty specs / malformed definition is
634
+ // rejected BEFORE any network call). An empty input is `empty_specs_input`; a
635
+ // present-but-malformed definition rejects the WHOLE request (`invalid_spec`) —
636
+ // a silently dropped coined spec never canonicalizes → never converges.
637
+ const read = readSpecsParams(params);
638
+ if (read.kind === "invalid") {
639
+ if (read.code === "invalid_spec") {
640
+ api.logger.info("sil_specs_invalid_spec", { field: read.field });
641
+ return invalidSpecDefinition(read.field);
642
+ }
643
+ api.logger.info("sil_specs_invalid_request", { error: "empty_specs_input" });
644
+ return invalidSpecsInput();
645
+ }
646
+ const specsParams = read.params;
647
+ // 3 — canonicalize; on a 401 refresh-and-retry ONCE via the shared
648
+ // choreography (the SAME path sil_whoami / sil_search / sil_product_get use).
649
+ const first = await specsCatalog(getApiUrl(), stored.access_token, specsParams);
650
+ const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => specsCatalog(getApiUrl(), accessToken, specsParams));
651
+ switch (recovered.kind) {
652
+ case "result":
653
+ if (recovered.refreshed)
654
+ api.logger.info("sil_specs_refreshed", {});
655
+ return mapSpecsOutcome(api, recovered.outcome);
656
+ case "must_reregister":
657
+ if (recovered.reason === "invalid_grant")
658
+ clearTokens();
659
+ api.logger.info("sil_specs_must_reregister", { cause: recovered.reason });
660
+ return mustReregister("sil_specs");
661
+ case "second_unauthorized":
662
+ clearTokens();
663
+ api.logger.info("sil_specs_must_reregister", { cause: "retry_unauthorized" });
664
+ return mustReregister("sil_specs");
665
+ case "retryable":
666
+ api.logger.info("sil_specs_refresh_retryable", {});
667
+ return transient("sil_specs");
668
+ }
669
+ },
670
+ });
671
+ }
672
+ /** Map a specs outcome that has ALREADY cleared the 401-recovery path (never
673
+ * `unauthorized` — the refresh trigger handled by {@link refreshAndRetryOnce}) to
674
+ * the agent-facing envelope. Mirrors `mapSearchOutcome`, minus the source-attributed
675
+ * `retryable` (specs has no external source): a 5xx/network blip is the GENERIC
676
+ * transient. The `unauthorized` arm is structurally unreachable but kept exhaustive
677
+ * (falls to the same terminal re-register) so a future refactor can't drop a variant. */
678
+ function mapSpecsOutcome(api, outcome) {
679
+ switch (outcome.kind) {
680
+ case "ok":
681
+ return specsResult(outcome);
682
+ case "forbidden":
683
+ // Symmetric with sil_search/sil_product_get (one vocabulary): a 403 is the
684
+ // shared forbidden envelope, and `user_not_provisioned` — and ONLY that exact
685
+ // reason — clears the structurally-dead token at this call site.
686
+ api.logger.warn("sil_specs_forbidden", { reason: outcome.reason });
687
+ if (outcome.reason === "user_not_provisioned")
688
+ clearTokens();
689
+ return forbidden(outcome.reason);
690
+ case "invalid_request":
691
+ api.logger.info("sil_specs_invalid_request", { error: outcome.error });
692
+ return invalidRequest(outcome.error, outcome.message);
693
+ case "retryable":
694
+ // BARE transient — the registry is sil's own Postgres, so there is no external
695
+ // source to name (unlike sil_search's outcome-b). Generic "try again" copy.
696
+ api.logger.info("sil_specs_retryable", {});
697
+ return transient("sil_specs");
698
+ case "unauthorized":
699
+ return mustReregister("sil_specs");
700
+ }
701
+ }
450
702
  /** Narrow the untrusted `params` to a string[] of ids. A non-string entry is
451
703
  * DROPPED (treated as absent), not coerced — the host has already validated
452
704
  * against the schema, but a drifted on-disk call must not slip a non-string into
@@ -519,8 +771,9 @@ function readSearchParams(params) {
519
771
  if (typeof limit === "number")
520
772
  result.limit = limit;
521
773
  const shipTo = readShipTo(params["ship_to"]);
522
- if (shipTo.kind === "invalid")
523
- return { kind: "invalid", field: shipTo.field };
774
+ if (shipTo.kind === "invalid") {
775
+ return { kind: "invalid", field: shipTo.field, code: "invalid_filter" };
776
+ }
524
777
  if (shipTo.kind === "ok")
525
778
  result.ship_to = shipTo.value;
526
779
  const condition = readCondition(params["condition"]);
@@ -537,6 +790,16 @@ function readSearchParams(params) {
537
790
  const localMerchants = params["local_merchants"];
538
791
  if (typeof localMerchants === "boolean")
539
792
  result.local_merchants = localMerchants;
793
+ // `specs` is a THIRD input class (a real constraint, not a refinement): a
794
+ // malformed predicate rejects the whole request client-side (`invalid_spec`,
795
+ // zero network — the `invalid_filter` twin); a non-array is DROPPED (the
796
+ // `readIds` discipline); a benign empty `[]` reads `ok` and no-ops downstream.
797
+ const specs = readSpecs(params["specs"]);
798
+ if (specs.kind === "invalid") {
799
+ return { kind: "invalid", field: specs.field, code: "invalid_spec" };
800
+ }
801
+ if (specs.kind === "ok")
802
+ result.specs = specs.value;
540
803
  return { kind: "ok", params: result };
541
804
  }
542
805
  /** A non-null plain object, or null for anything else (arrays/primitives). */
@@ -597,9 +860,166 @@ function readCondition(raw) {
597
860
  const values = raw.filter((c) => typeof c === "string");
598
861
  return values.length === 0 ? null : values;
599
862
  }
863
+ /** The seven spec ops, the ONLY closed part of the predicate contract (the `ns`/
864
+ * `key` vocabulary is deliberately open — [[sds-specs-vocabulary-is-bottom-up]]). */
865
+ const SPEC_OPS = ["eq", "neq", "gte", "lte", "in", "nin", "exists"];
866
+ function isSpecOp(op) {
867
+ return SPEC_OPS.includes(op);
868
+ }
869
+ /** The op→value validity rule, enforced at the READ SITE (the flat-schema +
870
+ * read-site idiom — the schema keeps `value` optional so `exists` fits; the
871
+ * per-op requirement lives here, not in TypeBox):
872
+ * - `exists` carries NO value;
873
+ * - `in`/`nin` need a NON-EMPTY array of string|number;
874
+ * - `gte`/`lte` need a number;
875
+ * - `eq`/`neq` need a scalar (string|number|boolean).
876
+ * Exhaustive over {@link SpecOp} — a new op forces a case here. */
877
+ function specValueMatchesOp(op, value) {
878
+ switch (op) {
879
+ case "exists":
880
+ return value === undefined;
881
+ case "in":
882
+ case "nin":
883
+ return (Array.isArray(value)
884
+ && value.length > 0
885
+ && value.every((v) => typeof v === "string" || typeof v === "number"));
886
+ case "gte":
887
+ case "lte":
888
+ return typeof value === "number";
889
+ case "eq":
890
+ case "neq":
891
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
892
+ }
893
+ }
894
+ /** Narrow the untrusted `specs` arg to {@link SpecPredicate}[], or report the FIRST
895
+ * malformed predicate. A non-array is DROPPED (treated absent — the `readIds`
896
+ * discipline; a drifted on-disk call must not slip a non-array through). Each entry
897
+ * must be an object with a non-blank `ns` and `key`, an `op` in the seven, and a
898
+ * `value` matching the op ({@link specValueMatchesOp}) — else the WHOLE request is
899
+ * rejected client-side (`invalid_spec`, zero network — the `invalid_filter` twin),
900
+ * because a malformed hard predicate silently dropped would be a fail-worse honesty
901
+ * hole. `unit`/`hard` are carried when the right type, dropped otherwise. No `any`,
902
+ * no unchecked `as` (the one cast is gated by {@link specValueMatchesOp}). */
903
+ function readSpecs(raw) {
904
+ if (!Array.isArray(raw))
905
+ return { kind: "absent" };
906
+ const specs = [];
907
+ for (let index = 0; index < raw.length; index++) {
908
+ const read = readSpec(raw[index], index);
909
+ if (read.kind === "invalid")
910
+ return read;
911
+ specs.push(read.value);
912
+ }
913
+ return { kind: "ok", value: specs };
914
+ }
915
+ /** Narrow ONE untrusted predicate to {@link SpecPredicate}, or report the offending
916
+ * field (`specs[i]`, `specs[i].ns`, `specs[i].op`, `specs[i].value`, …) for a clear
917
+ * client-side reject. */
918
+ function readSpec(raw, index) {
919
+ const at = (suffix) => `specs[${index}]${suffix}`;
920
+ const obj = asRecord(raw);
921
+ if (obj === null)
922
+ return { kind: "invalid", field: at("") };
923
+ const ns = obj["ns"];
924
+ if (typeof ns !== "string" || ns.trim().length === 0)
925
+ return { kind: "invalid", field: at(".ns") };
926
+ const key = obj["key"];
927
+ if (typeof key !== "string" || key.trim().length === 0)
928
+ return { kind: "invalid", field: at(".key") };
929
+ const op = obj["op"];
930
+ if (typeof op !== "string" || !isSpecOp(op))
931
+ return { kind: "invalid", field: at(".op") };
932
+ const value = obj["value"];
933
+ if (!specValueMatchesOp(op, value))
934
+ return { kind: "invalid", field: at(".value") };
935
+ const spec = { ns, key, op };
936
+ // `exists` carries no value (validated above); the others carry the op-checked value.
937
+ if (op !== "exists")
938
+ spec.value = value;
939
+ const unit = obj["unit"];
940
+ if (typeof unit === "string")
941
+ spec.unit = unit;
942
+ const hard = obj["hard"];
943
+ if (typeof hard === "boolean")
944
+ spec.hard = hard;
945
+ return { kind: "ok", value: spec };
946
+ }
947
+ /** The `sil_specs` read-site closed value-types (the defensive backstop for the
948
+ * host-validated `data_type`; `namespace`/`key` stay open — the coined vocabulary). */
949
+ const SPEC_DATA_TYPES = ["number", "text", "boolean", "enum"];
950
+ function isSpecDataType(value) {
951
+ return typeof value === "string" && SPEC_DATA_TYPES.includes(value);
952
+ }
953
+ /** Narrow the untrusted `sil_specs` params to the typed {@link SpecsParams}, or
954
+ * report the reject. A blank `query` or an empty/non-array/all-dropped `specs` is
955
+ * `empty_specs_input` (no network); the FIRST malformed definition rejects the WHOLE
956
+ * request `invalid_spec` (a silently-dropped coined spec never canonicalizes → never
957
+ * converges — the same honesty rule as search's `readSpecs`). No `any`, no unchecked
958
+ * `as`. The host has already validated the schema; this is a drifted-call backstop. */
959
+ function readSpecsParams(params) {
960
+ const query = params["query"];
961
+ if (typeof query !== "string" || query.trim().length === 0) {
962
+ return { kind: "invalid", code: "empty_specs_input" };
963
+ }
964
+ const rawSpecs = params["specs"];
965
+ if (!Array.isArray(rawSpecs) || rawSpecs.length === 0) {
966
+ return { kind: "invalid", code: "empty_specs_input" };
967
+ }
968
+ const specs = [];
969
+ for (let index = 0; index < rawSpecs.length; index++) {
970
+ const read = readSpecDefinition(rawSpecs[index], index);
971
+ if (read.kind === "invalid") {
972
+ return { kind: "invalid", code: "invalid_spec", field: read.field };
973
+ }
974
+ specs.push(read.value);
975
+ }
976
+ return { kind: "ok", params: { query, specs } };
977
+ }
978
+ /** Narrow ONE untrusted definition to {@link SpecDefinition}, or report the
979
+ * offending field (`specs[i]`, `specs[i].namespace`, `specs[i].data_type`, …).
980
+ * Requires a non-blank `namespace`/`key`/`display_name` and a `data_type` in the
981
+ * closed set; optional `description`/`unit`/`allowed_values` are carried when the
982
+ * right type, dropped otherwise. */
983
+ function readSpecDefinition(raw, index) {
984
+ const at = (suffix) => `specs[${index}]${suffix}`;
985
+ const obj = asRecord(raw);
986
+ if (obj === null)
987
+ return { kind: "invalid", field: at("") };
988
+ const namespace = obj["namespace"];
989
+ if (typeof namespace !== "string" || namespace.trim().length === 0) {
990
+ return { kind: "invalid", field: at(".namespace") };
991
+ }
992
+ const key = obj["key"];
993
+ if (typeof key !== "string" || key.trim().length === 0) {
994
+ return { kind: "invalid", field: at(".key") };
995
+ }
996
+ const displayName = obj["display_name"];
997
+ if (typeof displayName !== "string" || displayName.trim().length === 0) {
998
+ return { kind: "invalid", field: at(".display_name") };
999
+ }
1000
+ const dataType = obj["data_type"];
1001
+ if (!isSpecDataType(dataType))
1002
+ return { kind: "invalid", field: at(".data_type") };
1003
+ const value = { namespace, key, display_name: displayName, data_type: dataType };
1004
+ const description = obj["description"];
1005
+ if (typeof description === "string")
1006
+ value.description = description;
1007
+ const unit = obj["unit"];
1008
+ if (typeof unit === "string")
1009
+ value.unit = unit;
1010
+ const allowedValues = obj["allowed_values"];
1011
+ if (Array.isArray(allowedValues)) {
1012
+ const values = allowedValues.filter((v) => typeof v === "string");
1013
+ if (values.length > 0)
1014
+ value.allowed_values = values;
1015
+ }
1016
+ return { kind: "ok", value };
1017
+ }
600
1018
  /** The one client-side invariant the tool owns: at least one recognized input.
601
- * A non-whitespace `query` OR any filter (`category` / `price_min` / `price_max`)
602
- * suffices. A bare `{}` or a whitespace-only `query` with no filter is rejected;
1019
+ * A non-whitespace `query`, any filter (`category` / `price_min` / `price_max`),
1020
+ * OR a non-empty well-formed `specs` list suffices — a spec is a real constraint
1021
+ * (it renders + filters), not a refinement. A bare `{}`, a whitespace-only `query`
1022
+ * with no filter, or a present-but-EMPTY `specs: []` with nothing else is rejected;
603
1023
  * pagination params alone (`cursor`/`limit`) are NOT inputs — they refine an
604
1024
  * existing search, they do not constitute one. */
605
1025
  function hasUsableInput(params) {
@@ -607,7 +1027,8 @@ function hasUsableInput(params) {
607
1027
  const hasFilter = typeof params.category === "string"
608
1028
  || typeof params.price_min === "number"
609
1029
  || typeof params.price_max === "number";
610
- return hasQuery || hasFilter;
1030
+ const hasSpecs = Array.isArray(params.specs) && params.specs.length > 0;
1031
+ return hasQuery || hasFilter || hasSpecs;
611
1032
  }
612
1033
  /** Success: the ranked products + optional cursor — no token, no Bearer header.
613
1034
  * An empty `products` list is a valid, successful empty match. The `ok` outcome
@@ -655,6 +1076,53 @@ function invalidFilter(field) {
655
1076
  + " postal_code as a destination postal/ZIP code.",
656
1077
  });
657
1078
  }
1079
+ /** Client-side validation: a `specs` predicate is malformed (blank `ns`/`key`, an
1080
+ * `op` outside the seven, or a value shape contradicting the op) — rejected BEFORE
1081
+ * any network call, the twin of {@link invalidFilter} for `ship_to`. Distinct
1082
+ * machine code `invalid_spec`; `field` names the offending predicate index/field.
1083
+ * No `recovery: sil_register` — auth is fine; the predicate is the problem. */
1084
+ function invalidSpec(field) {
1085
+ return jsonResult({
1086
+ status: "invalid_request",
1087
+ error: "invalid_spec",
1088
+ message: `The \`${field}\` spec predicate is malformed. Each predicate needs a`
1089
+ + " non-empty `ns` and `key`, an `op` of eq/neq/gte/lte/in/nin/exists, and a"
1090
+ + " `value` matching the op: a number for gte/lte, a non-empty array for"
1091
+ + " in/nin, a scalar for eq/neq, and NO value for exists.",
1092
+ });
1093
+ }
1094
+ /** Success: the resolved canonicalizations — no token, no Bearer header. The `ok`
1095
+ * outcome carries `resolved` directly; spread its payload (minus the `kind`
1096
+ * discriminant) onto the agent-facing `{ status: "ok", resolved }` envelope. */
1097
+ function specsResult(outcome) {
1098
+ const { kind: _kind, ...payload } = outcome;
1099
+ return jsonResult({ status: "ok", ...payload });
1100
+ }
1101
+ /** Client-side validation: no usable canonicalization input (a blank `query` or an
1102
+ * empty/all-dropped `specs`). Distinct from a sil-api 400 — this never hit the
1103
+ * network. No `recovery: sil_register` (auth is fine; the input is the problem). */
1104
+ function invalidSpecsInput() {
1105
+ return jsonResult({
1106
+ status: "invalid_request",
1107
+ error: "empty_specs_input",
1108
+ message: "Provide a non-empty `query` and at least one coined spec definition to"
1109
+ + " canonicalize.",
1110
+ });
1111
+ }
1112
+ /** Client-side validation: a `specs` definition is malformed (blank
1113
+ * `namespace`/`key`/`display_name`, or a `data_type` outside
1114
+ * number/text/boolean/enum) — the WHOLE request is rejected BEFORE any network call,
1115
+ * so no coined spec is silently dropped from canonicalization. Machine code
1116
+ * `invalid_spec`; `field` names the offending definition. No `recovery: sil_register`. */
1117
+ function invalidSpecDefinition(field) {
1118
+ return jsonResult({
1119
+ status: "invalid_request",
1120
+ error: "invalid_spec",
1121
+ message: `The \`${field}\` spec definition is malformed. Each definition needs a`
1122
+ + " non-empty `namespace`, `key`, and `display_name`, and a `data_type` of"
1123
+ + " number, text, boolean, or enum.",
1124
+ });
1125
+ }
658
1126
  /** sil-api rejected the request (a structured 400, e.g. empty_search_input).
659
1127
  * Surface the server's `{ error, message }` so the agent fixes its query — NOT a
660
1128
  * re-register (auth is fine) and NOT a transient retry (retrying the same bad