sil-openclaw 0.3.9 → 0.4.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.
@@ -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,157 @@ 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 shopping method invents for a"
606
+ + " niche — the dedupe-or-create registry call at method mint/refresh (Beat 2)."
607
+ + " Pass the motivating `query` (what the shopper is buying — governance /"
608
+ + " dedupe context) and `specs`, a list of coined definitions ({ namespace,"
609
+ + " key, display_name, data_type, description?, unit?, allowed_values? }). Each"
610
+ + " submitted spec resolves 1:1: a `matched` result means an equivalent"
611
+ + " canonical spec already exists — ADOPT its `canonical` { namespace, key }"
612
+ + " and DROP your coined synonym (this convergence is what makes filters.specs"
613
+ + " actually filter across methods); a `created` result means yours is novel and"
614
+ + " registered as canonical (`canonical` === `submitted`, keep it). Rewrite the"
615
+ + " method's `## Search vocabulary` and any PRD `specs` predicates to the"
616
+ + " returned canonical names BEFORE persisting — the method is born canonical,"
617
+ + " never write-then-amend. On REFRESH submit ONLY the specs that do not yet"
618
+ + " carry a canonical name; already-canonical names are stable, do not resubmit"
619
+ + " them. This is INTERNAL plumbing: never surface `ns.key` names or"
620
+ + " \"converged your specs\" to the buyer. If the call is not `ok` (retryable /"
621
+ + " forbidden / must_reregister), do NOT block the mint — persist the method"
622
+ + " with the raw coined names and shop on; convergence retries on the next"
623
+ + " mint/refresh. Requires registration (run sil_register first).",
624
+ parameters: Type.Object({
625
+ query: Type.String({
626
+ description: "The motivating shopping query — what the shopper is buying. Governance /"
627
+ + " dedupe context for the registry; required and non-empty.",
628
+ }),
629
+ specs: Type.Array(SPEC_DEFINITION_SCHEMA, {
630
+ minItems: 1,
631
+ description: "The coined spec definitions to canonicalize (at least one). Each is a"
632
+ + " { namespace, key, display_name, data_type, description?, unit?,"
633
+ + " allowed_values? } the method coined bottom-up from research.",
634
+ }),
635
+ }),
636
+ async execute(_callId, params) {
637
+ // 1 — not registered: terminal, zero network calls.
638
+ const stored = readTokens();
639
+ if (stored === null) {
640
+ return notRegistered("sil_specs");
641
+ }
642
+ // 2 — client-side guard (defensive drifted-call backstop; the host validates
643
+ // the schema, but a blank query / empty specs / malformed definition is
644
+ // rejected BEFORE any network call). An empty input is `empty_specs_input`; a
645
+ // present-but-malformed definition rejects the WHOLE request (`invalid_spec`) —
646
+ // a silently dropped coined spec never canonicalizes → never converges.
647
+ const read = readSpecsParams(params);
648
+ if (read.kind === "invalid") {
649
+ if (read.code === "invalid_spec") {
650
+ api.logger.info("sil_specs_invalid_spec", { field: read.field });
651
+ return invalidSpecDefinition(read.field);
652
+ }
653
+ api.logger.info("sil_specs_invalid_request", { error: "empty_specs_input" });
654
+ return invalidSpecsInput();
655
+ }
656
+ const specsParams = read.params;
657
+ // 3 — canonicalize; on a 401 refresh-and-retry ONCE via the shared
658
+ // choreography (the SAME path sil_whoami / sil_search / sil_product_get use).
659
+ const first = await specsCatalog(getApiUrl(), stored.access_token, specsParams);
660
+ const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => specsCatalog(getApiUrl(), accessToken, specsParams));
661
+ switch (recovered.kind) {
662
+ case "result":
663
+ if (recovered.refreshed)
664
+ api.logger.info("sil_specs_refreshed", {});
665
+ return mapSpecsOutcome(api, recovered.outcome);
666
+ case "must_reregister":
667
+ if (recovered.reason === "invalid_grant")
668
+ clearTokens();
669
+ api.logger.info("sil_specs_must_reregister", { cause: recovered.reason });
670
+ return mustReregister("sil_specs");
671
+ case "second_unauthorized":
672
+ clearTokens();
673
+ api.logger.info("sil_specs_must_reregister", { cause: "retry_unauthorized" });
674
+ return mustReregister("sil_specs");
675
+ case "retryable":
676
+ api.logger.info("sil_specs_refresh_retryable", {});
677
+ return transient("sil_specs");
678
+ }
679
+ },
680
+ });
681
+ }
682
+ /** Map a specs outcome that has ALREADY cleared the 401-recovery path (never
683
+ * `unauthorized` — the refresh trigger handled by {@link refreshAndRetryOnce}) to
684
+ * the agent-facing envelope. Mirrors `mapSearchOutcome`, minus the source-attributed
685
+ * `retryable` (specs has no external source): a 5xx/network blip is the GENERIC
686
+ * transient. The `unauthorized` arm is structurally unreachable but kept exhaustive
687
+ * (falls to the same terminal re-register) so a future refactor can't drop a variant. */
688
+ function mapSpecsOutcome(api, outcome) {
689
+ switch (outcome.kind) {
690
+ case "ok":
691
+ return specsResult(outcome);
692
+ case "forbidden":
693
+ // Symmetric with sil_search/sil_product_get (one vocabulary): a 403 is the
694
+ // shared forbidden envelope, and `user_not_provisioned` — and ONLY that exact
695
+ // reason — clears the structurally-dead token at this call site.
696
+ api.logger.warn("sil_specs_forbidden", { reason: outcome.reason });
697
+ if (outcome.reason === "user_not_provisioned")
698
+ clearTokens();
699
+ return forbidden(outcome.reason);
700
+ case "invalid_request":
701
+ api.logger.info("sil_specs_invalid_request", { error: outcome.error });
702
+ return invalidRequest(outcome.error, outcome.message);
703
+ case "retryable":
704
+ // BARE transient — the registry is sil's own Postgres, so there is no external
705
+ // source to name (unlike sil_search's outcome-b). Generic "try again" copy.
706
+ api.logger.info("sil_specs_retryable", {});
707
+ return transient("sil_specs");
708
+ case "unauthorized":
709
+ return mustReregister("sil_specs");
710
+ }
711
+ }
450
712
  /** Narrow the untrusted `params` to a string[] of ids. A non-string entry is
451
713
  * DROPPED (treated as absent), not coerced — the host has already validated
452
714
  * against the schema, but a drifted on-disk call must not slip a non-string into
@@ -519,8 +781,9 @@ function readSearchParams(params) {
519
781
  if (typeof limit === "number")
520
782
  result.limit = limit;
521
783
  const shipTo = readShipTo(params["ship_to"]);
522
- if (shipTo.kind === "invalid")
523
- return { kind: "invalid", field: shipTo.field };
784
+ if (shipTo.kind === "invalid") {
785
+ return { kind: "invalid", field: shipTo.field, code: "invalid_filter" };
786
+ }
524
787
  if (shipTo.kind === "ok")
525
788
  result.ship_to = shipTo.value;
526
789
  const condition = readCondition(params["condition"]);
@@ -537,6 +800,16 @@ function readSearchParams(params) {
537
800
  const localMerchants = params["local_merchants"];
538
801
  if (typeof localMerchants === "boolean")
539
802
  result.local_merchants = localMerchants;
803
+ // `specs` is a THIRD input class (a real constraint, not a refinement): a
804
+ // malformed predicate rejects the whole request client-side (`invalid_spec`,
805
+ // zero network — the `invalid_filter` twin); a non-array is DROPPED (the
806
+ // `readIds` discipline); a benign empty `[]` reads `ok` and no-ops downstream.
807
+ const specs = readSpecs(params["specs"]);
808
+ if (specs.kind === "invalid") {
809
+ return { kind: "invalid", field: specs.field, code: "invalid_spec" };
810
+ }
811
+ if (specs.kind === "ok")
812
+ result.specs = specs.value;
540
813
  return { kind: "ok", params: result };
541
814
  }
542
815
  /** A non-null plain object, or null for anything else (arrays/primitives). */
@@ -597,9 +870,166 @@ function readCondition(raw) {
597
870
  const values = raw.filter((c) => typeof c === "string");
598
871
  return values.length === 0 ? null : values;
599
872
  }
873
+ /** The seven spec ops, the ONLY closed part of the predicate contract (the `ns`/
874
+ * `key` vocabulary is deliberately open — [[sds-specs-vocabulary-is-bottom-up]]). */
875
+ const SPEC_OPS = ["eq", "neq", "gte", "lte", "in", "nin", "exists"];
876
+ function isSpecOp(op) {
877
+ return SPEC_OPS.includes(op);
878
+ }
879
+ /** The op→value validity rule, enforced at the READ SITE (the flat-schema +
880
+ * read-site idiom — the schema keeps `value` optional so `exists` fits; the
881
+ * per-op requirement lives here, not in TypeBox):
882
+ * - `exists` carries NO value;
883
+ * - `in`/`nin` need a NON-EMPTY array of string|number;
884
+ * - `gte`/`lte` need a number;
885
+ * - `eq`/`neq` need a scalar (string|number|boolean).
886
+ * Exhaustive over {@link SpecOp} — a new op forces a case here. */
887
+ function specValueMatchesOp(op, value) {
888
+ switch (op) {
889
+ case "exists":
890
+ return value === undefined;
891
+ case "in":
892
+ case "nin":
893
+ return (Array.isArray(value)
894
+ && value.length > 0
895
+ && value.every((v) => typeof v === "string" || typeof v === "number"));
896
+ case "gte":
897
+ case "lte":
898
+ return typeof value === "number";
899
+ case "eq":
900
+ case "neq":
901
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
902
+ }
903
+ }
904
+ /** Narrow the untrusted `specs` arg to {@link SpecPredicate}[], or report the FIRST
905
+ * malformed predicate. A non-array is DROPPED (treated absent — the `readIds`
906
+ * discipline; a drifted on-disk call must not slip a non-array through). Each entry
907
+ * must be an object with a non-blank `ns` and `key`, an `op` in the seven, and a
908
+ * `value` matching the op ({@link specValueMatchesOp}) — else the WHOLE request is
909
+ * rejected client-side (`invalid_spec`, zero network — the `invalid_filter` twin),
910
+ * because a malformed hard predicate silently dropped would be a fail-worse honesty
911
+ * hole. `unit`/`hard` are carried when the right type, dropped otherwise. No `any`,
912
+ * no unchecked `as` (the one cast is gated by {@link specValueMatchesOp}). */
913
+ function readSpecs(raw) {
914
+ if (!Array.isArray(raw))
915
+ return { kind: "absent" };
916
+ const specs = [];
917
+ for (let index = 0; index < raw.length; index++) {
918
+ const read = readSpec(raw[index], index);
919
+ if (read.kind === "invalid")
920
+ return read;
921
+ specs.push(read.value);
922
+ }
923
+ return { kind: "ok", value: specs };
924
+ }
925
+ /** Narrow ONE untrusted predicate to {@link SpecPredicate}, or report the offending
926
+ * field (`specs[i]`, `specs[i].ns`, `specs[i].op`, `specs[i].value`, …) for a clear
927
+ * client-side reject. */
928
+ function readSpec(raw, index) {
929
+ const at = (suffix) => `specs[${index}]${suffix}`;
930
+ const obj = asRecord(raw);
931
+ if (obj === null)
932
+ return { kind: "invalid", field: at("") };
933
+ const ns = obj["ns"];
934
+ if (typeof ns !== "string" || ns.trim().length === 0)
935
+ return { kind: "invalid", field: at(".ns") };
936
+ const key = obj["key"];
937
+ if (typeof key !== "string" || key.trim().length === 0)
938
+ return { kind: "invalid", field: at(".key") };
939
+ const op = obj["op"];
940
+ if (typeof op !== "string" || !isSpecOp(op))
941
+ return { kind: "invalid", field: at(".op") };
942
+ const value = obj["value"];
943
+ if (!specValueMatchesOp(op, value))
944
+ return { kind: "invalid", field: at(".value") };
945
+ const spec = { ns, key, op };
946
+ // `exists` carries no value (validated above); the others carry the op-checked value.
947
+ if (op !== "exists")
948
+ spec.value = value;
949
+ const unit = obj["unit"];
950
+ if (typeof unit === "string")
951
+ spec.unit = unit;
952
+ const hard = obj["hard"];
953
+ if (typeof hard === "boolean")
954
+ spec.hard = hard;
955
+ return { kind: "ok", value: spec };
956
+ }
957
+ /** The `sil_specs` read-site closed value-types (the defensive backstop for the
958
+ * host-validated `data_type`; `namespace`/`key` stay open — the coined vocabulary). */
959
+ const SPEC_DATA_TYPES = ["number", "text", "boolean", "enum"];
960
+ function isSpecDataType(value) {
961
+ return typeof value === "string" && SPEC_DATA_TYPES.includes(value);
962
+ }
963
+ /** Narrow the untrusted `sil_specs` params to the typed {@link SpecsParams}, or
964
+ * report the reject. A blank `query` or an empty/non-array/all-dropped `specs` is
965
+ * `empty_specs_input` (no network); the FIRST malformed definition rejects the WHOLE
966
+ * request `invalid_spec` (a silently-dropped coined spec never canonicalizes → never
967
+ * converges — the same honesty rule as search's `readSpecs`). No `any`, no unchecked
968
+ * `as`. The host has already validated the schema; this is a drifted-call backstop. */
969
+ function readSpecsParams(params) {
970
+ const query = params["query"];
971
+ if (typeof query !== "string" || query.trim().length === 0) {
972
+ return { kind: "invalid", code: "empty_specs_input" };
973
+ }
974
+ const rawSpecs = params["specs"];
975
+ if (!Array.isArray(rawSpecs) || rawSpecs.length === 0) {
976
+ return { kind: "invalid", code: "empty_specs_input" };
977
+ }
978
+ const specs = [];
979
+ for (let index = 0; index < rawSpecs.length; index++) {
980
+ const read = readSpecDefinition(rawSpecs[index], index);
981
+ if (read.kind === "invalid") {
982
+ return { kind: "invalid", code: "invalid_spec", field: read.field };
983
+ }
984
+ specs.push(read.value);
985
+ }
986
+ return { kind: "ok", params: { query, specs } };
987
+ }
988
+ /** Narrow ONE untrusted definition to {@link SpecDefinition}, or report the
989
+ * offending field (`specs[i]`, `specs[i].namespace`, `specs[i].data_type`, …).
990
+ * Requires a non-blank `namespace`/`key`/`display_name` and a `data_type` in the
991
+ * closed set; optional `description`/`unit`/`allowed_values` are carried when the
992
+ * right type, dropped otherwise. */
993
+ function readSpecDefinition(raw, index) {
994
+ const at = (suffix) => `specs[${index}]${suffix}`;
995
+ const obj = asRecord(raw);
996
+ if (obj === null)
997
+ return { kind: "invalid", field: at("") };
998
+ const namespace = obj["namespace"];
999
+ if (typeof namespace !== "string" || namespace.trim().length === 0) {
1000
+ return { kind: "invalid", field: at(".namespace") };
1001
+ }
1002
+ const key = obj["key"];
1003
+ if (typeof key !== "string" || key.trim().length === 0) {
1004
+ return { kind: "invalid", field: at(".key") };
1005
+ }
1006
+ const displayName = obj["display_name"];
1007
+ if (typeof displayName !== "string" || displayName.trim().length === 0) {
1008
+ return { kind: "invalid", field: at(".display_name") };
1009
+ }
1010
+ const dataType = obj["data_type"];
1011
+ if (!isSpecDataType(dataType))
1012
+ return { kind: "invalid", field: at(".data_type") };
1013
+ const value = { namespace, key, display_name: displayName, data_type: dataType };
1014
+ const description = obj["description"];
1015
+ if (typeof description === "string")
1016
+ value.description = description;
1017
+ const unit = obj["unit"];
1018
+ if (typeof unit === "string")
1019
+ value.unit = unit;
1020
+ const allowedValues = obj["allowed_values"];
1021
+ if (Array.isArray(allowedValues)) {
1022
+ const values = allowedValues.filter((v) => typeof v === "string");
1023
+ if (values.length > 0)
1024
+ value.allowed_values = values;
1025
+ }
1026
+ return { kind: "ok", value };
1027
+ }
600
1028
  /** 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;
1029
+ * A non-whitespace `query`, any filter (`category` / `price_min` / `price_max`),
1030
+ * OR a non-empty well-formed `specs` list suffices — a spec is a real constraint
1031
+ * (it renders + filters), not a refinement. A bare `{}`, a whitespace-only `query`
1032
+ * with no filter, or a present-but-EMPTY `specs: []` with nothing else is rejected;
603
1033
  * pagination params alone (`cursor`/`limit`) are NOT inputs — they refine an
604
1034
  * existing search, they do not constitute one. */
605
1035
  function hasUsableInput(params) {
@@ -607,7 +1037,8 @@ function hasUsableInput(params) {
607
1037
  const hasFilter = typeof params.category === "string"
608
1038
  || typeof params.price_min === "number"
609
1039
  || typeof params.price_max === "number";
610
- return hasQuery || hasFilter;
1040
+ const hasSpecs = Array.isArray(params.specs) && params.specs.length > 0;
1041
+ return hasQuery || hasFilter || hasSpecs;
611
1042
  }
612
1043
  /** Success: the ranked products + optional cursor — no token, no Bearer header.
613
1044
  * An empty `products` list is a valid, successful empty match. The `ok` outcome
@@ -655,6 +1086,53 @@ function invalidFilter(field) {
655
1086
  + " postal_code as a destination postal/ZIP code.",
656
1087
  });
657
1088
  }
1089
+ /** Client-side validation: a `specs` predicate is malformed (blank `ns`/`key`, an
1090
+ * `op` outside the seven, or a value shape contradicting the op) — rejected BEFORE
1091
+ * any network call, the twin of {@link invalidFilter} for `ship_to`. Distinct
1092
+ * machine code `invalid_spec`; `field` names the offending predicate index/field.
1093
+ * No `recovery: sil_register` — auth is fine; the predicate is the problem. */
1094
+ function invalidSpec(field) {
1095
+ return jsonResult({
1096
+ status: "invalid_request",
1097
+ error: "invalid_spec",
1098
+ message: `The \`${field}\` spec predicate is malformed. Each predicate needs a`
1099
+ + " non-empty `ns` and `key`, an `op` of eq/neq/gte/lte/in/nin/exists, and a"
1100
+ + " `value` matching the op: a number for gte/lte, a non-empty array for"
1101
+ + " in/nin, a scalar for eq/neq, and NO value for exists.",
1102
+ });
1103
+ }
1104
+ /** Success: the resolved canonicalizations — no token, no Bearer header. The `ok`
1105
+ * outcome carries `resolved` directly; spread its payload (minus the `kind`
1106
+ * discriminant) onto the agent-facing `{ status: "ok", resolved }` envelope. */
1107
+ function specsResult(outcome) {
1108
+ const { kind: _kind, ...payload } = outcome;
1109
+ return jsonResult({ status: "ok", ...payload });
1110
+ }
1111
+ /** Client-side validation: no usable canonicalization input (a blank `query` or an
1112
+ * empty/all-dropped `specs`). Distinct from a sil-api 400 — this never hit the
1113
+ * network. No `recovery: sil_register` (auth is fine; the input is the problem). */
1114
+ function invalidSpecsInput() {
1115
+ return jsonResult({
1116
+ status: "invalid_request",
1117
+ error: "empty_specs_input",
1118
+ message: "Provide a non-empty `query` and at least one coined spec definition to"
1119
+ + " canonicalize.",
1120
+ });
1121
+ }
1122
+ /** Client-side validation: a `specs` definition is malformed (blank
1123
+ * `namespace`/`key`/`display_name`, or a `data_type` outside
1124
+ * number/text/boolean/enum) — the WHOLE request is rejected BEFORE any network call,
1125
+ * so no coined spec is silently dropped from canonicalization. Machine code
1126
+ * `invalid_spec`; `field` names the offending definition. No `recovery: sil_register`. */
1127
+ function invalidSpecDefinition(field) {
1128
+ return jsonResult({
1129
+ status: "invalid_request",
1130
+ error: "invalid_spec",
1131
+ message: `The \`${field}\` spec definition is malformed. Each definition needs a`
1132
+ + " non-empty `namespace`, `key`, and `display_name`, and a `data_type` of"
1133
+ + " number, text, boolean, or enum.",
1134
+ });
1135
+ }
658
1136
  /** sil-api rejected the request (a structured 400, e.g. empty_search_input).
659
1137
  * Surface the server's `{ error, message }` so the agent fixes its query — NOT a
660
1138
  * re-register (auth is fine) and NOT a transient retry (retrying the same bad