sil-openclaw 0.2.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.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Shared helper for formatting tool results.
3
+ *
4
+ * Every tool returns the same canonical success shape — a single text
5
+ * content part whose `text` is the JSON-stringified payload. `jsonResult`
6
+ * is the primitive (lifted from the reference adapter
7
+ * `klodi-plugin/adapters/openclaw/src/lib/tool-result.ts`). Each tool
8
+ * builds its own structured payload and wraps it here, so the agent sees
9
+ * one uniform envelope across the whole tool surface.
10
+ */
11
+ /** Format a successful JSON response as a tool result. */
12
+ export function jsonResult(data) {
13
+ return {
14
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
15
+ };
16
+ }
@@ -0,0 +1,630 @@
1
+ /**
2
+ * Catalog tools for the sil plugin.
3
+ *
4
+ * `sil_search` is a thin, typed product-discovery tool. An AI agent sends a
5
+ * SIMPLIFIED structured query — free-text `query` plus optional filters
6
+ * (`category`, `price_min`/`price_max`) and pagination (`cursor`/`limit`) — and
7
+ * gets back a flat, ranked list of purchasable options: one featured variant per
8
+ * product projected to `{ id, title, price, availability, checkout_url, source }`,
9
+ * plus an opaque pagination `cursor`. The agent builds no UCP envelope and fills
10
+ * no defaults; sil-api owns enrichment, ranking, and the envelope. The tool's job
11
+ * is: validate the one invariant it owns (≥1 input), attach the stored Bearer
12
+ * token, POST the bare `/catalog/search` on sil-api, and normalize the response.
13
+ *
14
+ * `execute()` flow (ALL I/O here; `register()` opens nothing — search is a
15
+ * synchronous request/response, NOT a poll):
16
+ * 1. Not registered (no stored tokens) → terminal `not_registered` + a
17
+ * `recovery: sil_register` hint, ZERO network calls (nothing to authenticate
18
+ * with). Mirrors `sil_whoami`'s not-registered path.
19
+ * 2. Client-side input guard: a request with neither a non-empty `query` nor
20
+ * any filter is rejected with a structured validation error and makes NO
21
+ * network call (sil-api's `empty_search_input` 400 is the authoritative
22
+ * backstop). A filter-only request (e.g. `category` alone) is a valid browse.
23
+ * 3. searchCatalog(getApiUrl(), token, params) → map the `SearchOutcome`:
24
+ * ok → the ranked products + cursor;
25
+ * invalid_request (400) → surface sil-api's `{ error, message }`;
26
+ * unauthorized (401) → refresh-and-retry ONCE via the shared
27
+ * `refreshAndRetryOnce` choreography (sil-web refresh,
28
+ * re-read rotated pair, retry once). The agent never
29
+ * sees a recovered 401; a second 401 or a dead refresh
30
+ * is terminal re-register (tokens cleared); a refresh
31
+ * 5xx/network blip is transient "try again". 401
32
+ * recovery is UNIFORM across sil_search /
33
+ * sil_product_get / sil_whoami — never per-tool;
34
+ * retryable (5xx/net) → transient "try again", NO re-register hint.
35
+ *
36
+ * The three distinct sil-api outcomes (empty match 200 / invalid 400 / source
37
+ * failure 500) surface as three DISTINGUISHABLE agent envelopes — an empty match
38
+ * is a SUCCESS (`status: "ok"`, `products: []`), never an error. Distinct recovery
39
+ * hints per error class, mirroring `identity.ts`: re-register sends the agent to
40
+ * `sil_register`; a transient/invalid must NOT (re-registering can't fix a 5xx or
41
+ * a bad query and would derail the user).
42
+ *
43
+ * Privacy: the access token and Bearer header never reach a log line or the
44
+ * result; logs carry only non-credential status markers (search params are not
45
+ * credentials, but are not logged either — nothing here needs them).
46
+ *
47
+ * `register()` stays synchronous and side-effect-free beyond registering tools —
48
+ * no fetch, no timer, no unawaited promise. All I/O is inside `execute()`.
49
+ */
50
+ import { Type } from "typebox";
51
+ import { getApiUrl } from "../lib/config.js";
52
+ import { clearTokens, readTokens } from "../lib/credentials.js";
53
+ import { lookupCatalog, refreshAndRetryOnce, searchCatalog, } from "../lib/sil-client.js";
54
+ import { jsonResult } from "../lib/tool-result.js";
55
+ /**
56
+ * The TIGHTENED ship-to/ships-from format contract (founder re-spec 2026-06-11),
57
+ * pinned as a `pattern` BOTH the local schema and sil-api's `@sil/schemas`
58
+ * `ShipTo`/`ShipFrom` enforce IDENTICALLY (byte-for-byte) — so the plugin rejects a
59
+ * malformed value client-side instead of forwarding free text and eating an opaque,
60
+ * fail-late sil-api 400. These same patterns are the schema `pattern` (so the host
61
+ * validates) AND the read-site format gate (so a drifted on-disk call is rejected),
62
+ * defined once here to keep the two in lockstep. The sil-services sibling
63
+ * (`attach-buyer-ship-to-context-server-side-in-sil-ap`) MUST mirror these exactly;
64
+ * the sil-stage eval verifies it end-to-end.
65
+ * - country (ships_to + ships_from): ISO 3166-1 alpha-2, a 2-letter code.
66
+ * - region: ISO 3166-2 subdivision code (CA/NY/BY/97), bounded — NOT a place name.
67
+ * - postal_code: a single self-contained pattern (a length-cap lookahead 2–12
68
+ * chars, separators counted, + a structural body of alnum runs joined by single
69
+ * internal space/hyphen, no leading/trailing/doubled separator) — accepts real
70
+ * national formats (94107 / EC1A 1BB / K1A 0B1), rejects prose/injection/overlong.
71
+ */
72
+ const COUNTRY_PATTERN = "^[A-Za-z]{2}$";
73
+ const REGION_PATTERN = "^[A-Za-z0-9]{1,3}$";
74
+ const POSTAL_PATTERN = "^(?=[A-Za-z0-9 -]{2,12}$)[A-Za-z0-9]+(?:[ -][A-Za-z0-9]+)*$";
75
+ export function registerCatalogTools(api) {
76
+ registerSearch(api);
77
+ registerProductGet(api);
78
+ }
79
+ function registerSearch(api) {
80
+ api.registerTool({
81
+ name: "sil_search",
82
+ label: "Search the sil catalog",
83
+ description: "Search sil's catalog for purchasable products. Pass a free-text `query`"
84
+ + " and/or filters (`category`, `price_min`/`price_max` in the currency's"
85
+ + " minor units, e.g. cents). Returns a ranked list (best match first —"
86
+ + " present results in order, do not re-rank), each item a purchasable"
87
+ + " variant with id, title, price, availability, checkout_url, and source."
88
+ + " Use the returned `cursor` to fetch the next page (its absence means no"
89
+ + " more results — never infer end-of-results from the page size). An empty"
90
+ + " result list means nothing matched (a normal outcome, not an error)."
91
+ + " For the location filters, ALWAYS send standard ISO CODES, NOT free text or"
92
+ + " natural-language place names — send the 2-letter country code \"US\", never"
93
+ + " the name \"United States\"; send the subdivision code \"CA\", never the place"
94
+ + " name \"California\". A free-text name is rejected; the code is not."
95
+ + " Delivery destination: LEAVE `ship_to` EMPTY for \"ship to me\" — when it is"
96
+ + " absent, sil-api resolves the user's REGISTERED DEFAULT ADDRESS server-side"
97
+ + " and localizes results to it. Do NOT call sil_whoami (or any identity read)"
98
+ + " to fetch the user's address and put it in `ship_to` — that round-trip is"
99
+ + " wasted work and yields the same result as omitting it. Set `ship_to` ONLY"
100
+ + " to OVERRIDE the default — to ship to a DIFFERENT destination than the"
101
+ + " user's registered address (e.g. \"ship it to my office in Berlin\"). Its"
102
+ + " fields: `country` = the 2-letter ISO 3166-1 alpha-2 code (US, GB, DE — a"
103
+ + " code, NOT a country name); `region` (optional) = the ISO 3166-2 subdivision"
104
+ + " code (CA, NY, BY — a code, NOT a place name); `postal_code` (optional) ="
105
+ + " the destination postal/ZIP code. The other optional filters need no prior"
106
+ + " tool call: `ships_from` (`{ country }`, the same 2-letter ISO 3166-1"
107
+ + " alpha-2 code — US/GB/DE) restricts to a merchant ORIGIN country; `condition`"
108
+ + " (array; the values are exactly \"new\" or \"secondhand\", lowercase) filters"
109
+ + " by product condition; `available` (boolean) controls availability — the"
110
+ + " server returns only sale-ready items by default, so set `available: false`"
111
+ + " to INCLUDE out-of-stock/unavailable items. Requires registration (run"
112
+ + " sil_register first).",
113
+ parameters: Type.Object({
114
+ query: Type.Optional(Type.String({
115
+ description: "Free-text search query. Either this or at least one filter is required.",
116
+ })),
117
+ category: Type.Optional(Type.String({
118
+ description: "Restrict results to a single product category.",
119
+ })),
120
+ price_min: Type.Optional(Type.Integer({
121
+ minimum: 0,
122
+ description: "Minimum price, in the currency's ISO 4217 minor unit (e.g. cents).",
123
+ })),
124
+ price_max: Type.Optional(Type.Integer({
125
+ minimum: 0,
126
+ description: "Maximum price, in the currency's ISO 4217 minor unit (e.g. cents).",
127
+ })),
128
+ cursor: Type.Optional(Type.String({
129
+ description: "Opaque pagination cursor from a prior search's result.",
130
+ })),
131
+ limit: Type.Optional(Type.Integer({
132
+ minimum: 1,
133
+ description: "Requested maximum number of results. The server may return fewer.",
134
+ })),
135
+ ship_to: Type.Optional(Type.Object({
136
+ country: Type.String({
137
+ pattern: COUNTRY_PATTERN,
138
+ description: "Destination country as a 2-letter ISO 3166-1 alpha-2 CODE (US, GB,"
139
+ + " DE) — a code, NOT a country name (\"United States\" is rejected).",
140
+ }),
141
+ region: Type.Optional(Type.String({
142
+ pattern: REGION_PATTERN,
143
+ description: "Destination region as an ISO 3166-2 subdivision CODE (CA, NY, BY)"
144
+ + " — a code, NOT a place name (\"California\" is rejected). Optional.",
145
+ })),
146
+ postal_code: Type.Optional(Type.String({
147
+ pattern: POSTAL_PATTERN,
148
+ description: "Destination postal/ZIP code (e.g. 94107, EC1A 1BB, K1A 0B1)."
149
+ + " Optional refinement.",
150
+ })),
151
+ }, {
152
+ description: "Deliver-to destination for serviceability + localization. LEAVE EMPTY"
153
+ + " for \"ship to me\": when absent/omitted, sil-api uses the user's"
154
+ + " REGISTERED DEFAULT ADDRESS (resolved server-side) — do NOT call"
155
+ + " sil_whoami to fetch and resubmit it. Set this ONLY to OVERRIDE the"
156
+ + " default with a DIFFERENT destination than the registered address."
157
+ + " Send ISO CODES, never free-text place names.",
158
+ })),
159
+ ships_from: Type.Optional(Type.Object({
160
+ country: Type.String({
161
+ pattern: COUNTRY_PATTERN,
162
+ description: "Merchant origin country as a 2-letter ISO 3166-1 alpha-2 CODE (US,"
163
+ + " GB, DE) — a code, NOT a country name.",
164
+ }),
165
+ }, {
166
+ description: "Restrict results to products that ship FROM a given merchant origin"
167
+ + " country (alpha-2 ISO code). Omit for no origin constraint.",
168
+ })),
169
+ condition: Type.Optional(Type.Array(Type.String(), {
170
+ description: "Filter by product condition. The values are exactly \"new\" or"
171
+ + " \"secondhand\" (lowercase; multiple are OR'd). Omit for no condition"
172
+ + " filter.",
173
+ })),
174
+ available: Type.Optional(Type.Boolean({
175
+ description: "Availability filter. The server returns only sale-ready items by"
176
+ + " default; set false to INCLUDE unavailable/out-of-stock items. Omit"
177
+ + " to keep the default (available only).",
178
+ })),
179
+ }),
180
+ async execute(_callId, params) {
181
+ // 1 — not registered: terminal, zero network calls.
182
+ const stored = readTokens();
183
+ if (stored === null) {
184
+ return notRegistered("sil_search");
185
+ }
186
+ // Narrow the untrusted params (the SDK types `params` as
187
+ // Record<string, unknown>; the host validates against the schema, but the
188
+ // read site still guards — mirrors the defensive narrowing in sil-client).
189
+ // A present-but-malformed location filter (bad FORMAT, not wrong type) is
190
+ // rejected client-side BEFORE the input guard or any network call — a clear
191
+ // `invalid_filter` beats an opaque, fail-late sil-api 400 (re-spec).
192
+ const read = readSearchParams(params);
193
+ if (read.kind === "invalid") {
194
+ api.logger.info("sil_search_invalid_filter", { field: read.field });
195
+ return invalidFilter(read.field);
196
+ }
197
+ const search = read.params;
198
+ // 2 — client-side input guard: reject the obviously-empty request before
199
+ // any network call. A filter-only request is a valid browse, not rejected.
200
+ // (The new location filters are REFINEMENTS, not inputs — `hasUsableInput` is
201
+ // unchanged, so a request of only-new-args is rejected as empty input.)
202
+ if (!hasUsableInput(search)) {
203
+ return invalidInput();
204
+ }
205
+ // 3 — search; on a 401 refresh-and-retry ONCE via the shared choreography
206
+ // (the SAME path sil_whoami / sil_product_get use — 401 recovery is uniform
207
+ // across every sil-api-calling tool, never per-tool).
208
+ const first = await searchCatalog(getApiUrl(), stored.access_token, search);
209
+ const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => searchCatalog(getApiUrl(), accessToken, search));
210
+ switch (recovered.kind) {
211
+ case "result":
212
+ // On a silent recovery (`refreshed`: a 401 was healed by the refresh+retry)
213
+ // emit the operator marker so a thrashing session is visible in logs —
214
+ // logs-only, no token material, NOT a payload field (the agent never sees it).
215
+ if (recovered.refreshed)
216
+ api.logger.info("sil_search_refreshed", {});
217
+ return mapSearchOutcome(api, recovered.outcome);
218
+ case "must_reregister":
219
+ // A dead refresh token (invalid_grant) is cleared so the agent's
220
+ // sil_register recovery is not blocked by stale presence; a TOCTOU
221
+ // empty re-read (no_stored_tokens) has nothing to clear.
222
+ if (recovered.reason === "invalid_grant")
223
+ clearTokens();
224
+ api.logger.info("sil_search_must_reregister", { cause: recovered.reason });
225
+ return mustReregister("sil_search");
226
+ case "second_unauthorized":
227
+ // A freshly-rotated token STILL rejected is structurally dead — clear it.
228
+ clearTokens();
229
+ api.logger.info("sil_search_must_reregister", { cause: "retry_unauthorized" });
230
+ return mustReregister("sil_search");
231
+ case "retryable":
232
+ api.logger.info("sil_search_refresh_retryable", {});
233
+ return transient("sil_search");
234
+ }
235
+ },
236
+ });
237
+ }
238
+ /** Map a search outcome that has ALREADY cleared the 401-recovery path (so it is
239
+ * never `unauthorized` — that is the refresh trigger, handled by the caller via
240
+ * {@link refreshAndRetryOnce}) to the agent-facing envelope. The `unauthorized`
241
+ * arm is structurally unreachable but kept exhaustive so a future refactor can't
242
+ * silently drop a variant — it falls to the same terminal re-register. */
243
+ function mapSearchOutcome(api, outcome) {
244
+ switch (outcome.kind) {
245
+ case "ok":
246
+ return searchResult(outcome);
247
+ case "invalid_request":
248
+ api.logger.info("sil_search_invalid_request", { error: outcome.error });
249
+ return invalidRequest(outcome.error, outcome.message);
250
+ case "retryable":
251
+ api.logger.info("sil_search_retryable", {});
252
+ return transient("sil_search");
253
+ case "unauthorized":
254
+ return mustReregister("sil_search");
255
+ }
256
+ }
257
+ /**
258
+ * `sil_product_get` — the lookup COMPANION to `sil_search`. The agent passes ids
259
+ * it already holds (from a prior `sil_search`, a saved list, deep links, or cart
260
+ * validation) and gets back the matching products in UCP shape, each with its
261
+ * FRESH featured variant `{ id, title, price, availability, checkout_url, ... }`.
262
+ * RICH where search is LEAN: lookup adds the description, the variant's options,
263
+ * and — its defining feature — the per-variant `inputs` correlation, because the
264
+ * response does NOT preserve request order and one id can resolve to a variant of
265
+ * another id's product. The agent builds no envelope and fills no defaults; the
266
+ * tool sends just `{ ids }`, sil-api owns enrichment + the `not_found` messaging.
267
+ *
268
+ * `execute()` flow (ALL I/O here; `register()` opens nothing — a synchronous
269
+ * request/response, NOT a poll). MIRRORS `sil_search` and shares its taxonomy:
270
+ * 1. Not registered (no stored tokens) → terminal `not_registered` + a
271
+ * `recovery: sil_register` hint, ZERO network calls. Mirrors `sil_whoami`.
272
+ * 2. Client-side guard: an empty `ids` (after dropping non-strings) is rejected
273
+ * with a structured validation error and NO network call (sil-api's
274
+ * `minItems:1` schema 400 is the authoritative backstop).
275
+ * 3. lookupCatalog(getApiUrl(), token, ids) → map the `LookupOutcome`:
276
+ * ok → the resolved products + the `not_found` id list (a PARTIAL
277
+ * or ALL-MISSED hit is `status:"ok"` — a SUCCESS, never an
278
+ * error, with NO recovery hint: re-running won't conjure a
279
+ * delisted product);
280
+ * invalid_request (400) → surface sil-api's `{ error, message }`;
281
+ * unauthorized (401) → refresh-and-retry ONCE via the shared
282
+ * `refreshAndRetryOnce` choreography (parity with
283
+ * `sil_search` and `sil_whoami` — 401 recovery is
284
+ * uniform). Recovered 401 is invisible; second 401 /
285
+ * dead refresh is terminal re-register (tokens
286
+ * cleared); a refresh 5xx/network blip is transient;
287
+ * retryable (5xx/net) → transient "try again", NO re-register hint.
288
+ *
289
+ * The unfound-ids outcome is the headline: a lookup that resolves SOME (or NONE)
290
+ * of its ids is a success the agent relays ("3 of your 4 items are still
291
+ * available; 1 is no longer listed"), distinguished from the two true-error
292
+ * classes (not-registered/401 and source/transport failure) by DISTINCT recovery
293
+ * hints. One wrong hint = one misdirected user.
294
+ *
295
+ * Privacy + freshness: the access token and Bearer header never reach a log line
296
+ * or the result; the products are always live-fetched (never cached — freshness is
297
+ * the reason this tool exists; a cached `checkout_url`/price is a broken purchase).
298
+ */
299
+ function registerProductGet(api) {
300
+ api.registerTool({
301
+ name: "sil_product_get",
302
+ label: "Look up sil products by id",
303
+ description: "Look up sil products or variants by id — the companion to sil_search."
304
+ + " Pass `ids` (one or more product/variant ids you already hold, e.g. from"
305
+ + " a prior sil_search result) and get the matching products back with FRESH"
306
+ + " detail: each product's description plus its featured purchasable variant"
307
+ + " (id, title, price, availability, checkout_url, options). Re-fetch right"
308
+ + " before the user buys — prices, availability, and checkout_url are"
309
+ + " point-in-time, not guarantees. Each variant carries an `inputs` list"
310
+ + " correlating it back to the id(s) you asked about (the response is NOT in"
311
+ + " request order). Ids that no longer resolve come back in a `not_found`"
312
+ + " list — that is a normal outcome, not an error (the other products are"
313
+ + " still valid). Requires registration (run sil_register first).",
314
+ parameters: Type.Object({
315
+ ids: Type.Array(Type.String(), {
316
+ minItems: 1,
317
+ description: "Product or variant ids to resolve (at least one). Typically ids from a"
318
+ + " prior sil_search result, a saved list, or a deep link.",
319
+ }),
320
+ }),
321
+ async execute(_callId, params) {
322
+ // 1 — not registered: terminal, zero network calls.
323
+ const stored = readTokens();
324
+ if (stored === null) {
325
+ return notRegistered("sil_product_get");
326
+ }
327
+ // Narrow the untrusted params (the SDK types `params` as
328
+ // Record<string, unknown>; the host validates against the schema, but the
329
+ // read site still guards — non-string entries are dropped, not coerced).
330
+ const ids = readIds(params);
331
+ // 2 — client-side input guard: reject an empty `ids` before any network
332
+ // call (sil-api's `minItems:1` schema 400 is the authoritative backstop).
333
+ if (ids.length === 0) {
334
+ return invalidIds();
335
+ }
336
+ // 3 — look up; on a 401 refresh-and-retry ONCE via the shared choreography
337
+ // (the SAME path sil_whoami / sil_search use). A partial/all-missed hit is
338
+ // `ok` + `not_found`.
339
+ const first = await lookupCatalog(getApiUrl(), stored.access_token, ids);
340
+ const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => lookupCatalog(getApiUrl(), accessToken, ids));
341
+ switch (recovered.kind) {
342
+ case "result":
343
+ // On a silent recovery (`refreshed`: a 401 was healed by the refresh+retry)
344
+ // emit the operator marker so a thrashing session is visible in logs —
345
+ // logs-only, no token material, NOT a payload field (the agent never sees it).
346
+ if (recovered.refreshed)
347
+ api.logger.info("sil_product_get_refreshed", {});
348
+ return mapLookupOutcome(api, recovered.outcome);
349
+ case "must_reregister":
350
+ if (recovered.reason === "invalid_grant")
351
+ clearTokens();
352
+ api.logger.info("sil_product_get_must_reregister", { cause: recovered.reason });
353
+ return mustReregister("sil_product_get");
354
+ case "second_unauthorized":
355
+ clearTokens();
356
+ api.logger.info("sil_product_get_must_reregister", { cause: "retry_unauthorized" });
357
+ return mustReregister("sil_product_get");
358
+ case "retryable":
359
+ api.logger.info("sil_product_get_refresh_retryable", {});
360
+ return transient("sil_product_get");
361
+ }
362
+ },
363
+ });
364
+ }
365
+ /** Map a lookup outcome that has ALREADY cleared the 401-recovery path (never
366
+ * `unauthorized` — the refresh trigger handled by {@link refreshAndRetryOnce}) to
367
+ * the agent-facing envelope. The `unauthorized` arm is structurally unreachable
368
+ * but kept exhaustive (falls to the same terminal re-register) so a future
369
+ * refactor can't silently drop a variant. */
370
+ function mapLookupOutcome(api, outcome) {
371
+ switch (outcome.kind) {
372
+ case "ok":
373
+ return lookupResult(outcome);
374
+ case "invalid_request":
375
+ api.logger.info("sil_product_get_invalid_request", { error: outcome.error });
376
+ return invalidRequest(outcome.error, outcome.message);
377
+ case "retryable":
378
+ api.logger.info("sil_product_get_retryable", {});
379
+ return transient("sil_product_get");
380
+ case "unauthorized":
381
+ return mustReregister("sil_product_get");
382
+ }
383
+ }
384
+ /** Narrow the untrusted `params` to a string[] of ids. A non-string entry is
385
+ * DROPPED (treated as absent), not coerced — the host has already validated
386
+ * against the schema, but a drifted on-disk call must not slip a non-string into
387
+ * the id list. No `any`, no unchecked `as`. */
388
+ function readIds(params) {
389
+ const raw = params["ids"];
390
+ if (!Array.isArray(raw))
391
+ return [];
392
+ return raw.filter((id) => typeof id === "string");
393
+ }
394
+ /** Success: the resolved products + optional `not_found` id list — no token, no
395
+ * Bearer header. An empty `products` list WITH a `not_found` list is a valid,
396
+ * successful all-missed lookup. The `ok` outcome already carries `products` (+
397
+ * optional `not_found`); spread its payload (minus the `kind` discriminant) onto
398
+ * the agent-facing `{ status: "ok", ... }` envelope. A `not_found` list is
399
+ * partial-success DATA, NOT an error and NOT a recovery hint. */
400
+ function lookupResult(outcome) {
401
+ const { kind: _kind, ...payload } = outcome;
402
+ return jsonResult({ status: "ok", ...payload });
403
+ }
404
+ /** Client-side validation: the request named no usable id. Distinct from a sil-api
405
+ * 400 (which carries the server's structured error) — this never hit the network.
406
+ * No `recovery: sil_register` (auth is fine; the input is the problem). */
407
+ function invalidIds() {
408
+ return jsonResult({
409
+ status: "invalid_request",
410
+ error: "empty_ids",
411
+ message: "Provide at least one product or variant id to look up.",
412
+ });
413
+ }
414
+ /** Narrow the untrusted `params` to the simplified {@link SearchParams}, or report
415
+ * the first bad-FORMAT filter field. A field of the wrong type is dropped (treated
416
+ * as absent), not coerced — the host has already validated against the schema, but
417
+ * a drifted on-disk call must not slip a non-string into the query mapping. No
418
+ * `any`, no unchecked `as`.
419
+ *
420
+ * The four serviceability/localization filters narrow by their own type: `ship_to`/
421
+ * `ships_from` to an object with a string `country` (a primitive/number is
422
+ * DROPPED), `condition` to a string[] (a bare string is dropped), `available` to a
423
+ * boolean (a string is dropped). The drop is TYPE-driven, never value-driven, so a
424
+ * valid `available: false` survives — it is a boolean, the meaningful "include
425
+ * unavailable items" signal, not a falsy value to discard.
426
+ *
427
+ * Beyond TYPE narrowing, `ship_to`/`ships_from` also FORMAT-validate every provided
428
+ * string field (country alpha-2, region 3166-2, postal bounded) against the shared
429
+ * patterns: a present-but-malformed value returns an `invalid` read so the tool
430
+ * rejects the request client-side with a clear `invalid_filter` error (better agent
431
+ * UX than an opaque, fail-late sil-api 400). `condition` is NOT format-validated —
432
+ * its wire stays OPEN (an unrecognized value still forwards; steering to
433
+ * new/secondhand lives in the description only). The first bad field wins. */
434
+ function readSearchParams(params) {
435
+ const result = {};
436
+ const query = params["query"];
437
+ if (typeof query === "string")
438
+ result.query = query;
439
+ const category = params["category"];
440
+ if (typeof category === "string")
441
+ result.category = category;
442
+ const priceMin = params["price_min"];
443
+ if (typeof priceMin === "number")
444
+ result.price_min = priceMin;
445
+ const priceMax = params["price_max"];
446
+ if (typeof priceMax === "number")
447
+ result.price_max = priceMax;
448
+ const cursor = params["cursor"];
449
+ if (typeof cursor === "string")
450
+ result.cursor = cursor;
451
+ const limit = params["limit"];
452
+ if (typeof limit === "number")
453
+ result.limit = limit;
454
+ const shipTo = readShipTo(params["ship_to"]);
455
+ if (shipTo.kind === "invalid")
456
+ return { kind: "invalid", field: shipTo.field };
457
+ if (shipTo.kind === "ok")
458
+ result.ship_to = shipTo.value;
459
+ const shipsFrom = readShipsFrom(params["ships_from"]);
460
+ if (shipsFrom.kind === "invalid")
461
+ return { kind: "invalid", field: shipsFrom.field };
462
+ if (shipsFrom.kind === "ok")
463
+ result.ships_from = shipsFrom.value;
464
+ const condition = readCondition(params["condition"]);
465
+ if (condition !== null)
466
+ result.condition = condition;
467
+ const available = params["available"];
468
+ if (typeof available === "boolean")
469
+ result.available = available;
470
+ return { kind: "ok", params: result };
471
+ }
472
+ /** A non-null plain object, or null for anything else (arrays/primitives). */
473
+ function asRecord(value) {
474
+ return value !== null && typeof value === "object" && !Array.isArray(value)
475
+ ? value
476
+ : null;
477
+ }
478
+ /** Narrow a `ship_to` arg to {@link ShipTo}. A non-object (a primitive `"US"`, a
479
+ * number) or a missing/non-string `country` is `absent` (DROPPED — the wrong-TYPE
480
+ * discipline). A provided string that fails its FORMAT pattern (`country`,
481
+ * `region`, or `postal_code`) is `invalid` (REJECT the request). `country` is
482
+ * uppercased on the WIRE (`buildSearchBody`), not here — the read site validates
483
+ * FORMAT, the wire normalizes case; region/postal are carried verbatim. */
484
+ function readShipTo(raw) {
485
+ const obj = asRecord(raw);
486
+ if (obj === null)
487
+ return { kind: "absent" };
488
+ const country = obj["country"];
489
+ if (typeof country !== "string" || country.length === 0)
490
+ return { kind: "absent" };
491
+ if (!matchesPattern(country, COUNTRY_PATTERN)) {
492
+ return { kind: "invalid", field: "ship_to.country" };
493
+ }
494
+ const result = { country };
495
+ const region = obj["region"];
496
+ if (typeof region === "string") {
497
+ if (!matchesPattern(region, REGION_PATTERN)) {
498
+ return { kind: "invalid", field: "ship_to.region" };
499
+ }
500
+ result.region = region;
501
+ }
502
+ const postalCode = obj["postal_code"];
503
+ if (typeof postalCode === "string") {
504
+ if (!matchesPattern(postalCode, POSTAL_PATTERN)) {
505
+ return { kind: "invalid", field: "ship_to.postal_code" };
506
+ }
507
+ result.postal_code = postalCode;
508
+ }
509
+ return { kind: "ok", value: result };
510
+ }
511
+ /** Narrow a `ships_from` arg to {@link ShipsFrom}. A non-object/missing-country is
512
+ * `absent` (DROPPED, wrong-TYPE discipline); a provided `country` string that fails
513
+ * the alpha-2 pattern is `invalid` (REJECT). Country is uppercased on the wire, not
514
+ * here. */
515
+ function readShipsFrom(raw) {
516
+ const obj = asRecord(raw);
517
+ if (obj === null)
518
+ return { kind: "absent" };
519
+ const country = obj["country"];
520
+ if (typeof country !== "string" || country.length === 0)
521
+ return { kind: "absent" };
522
+ if (!matchesPattern(country, COUNTRY_PATTERN)) {
523
+ return { kind: "invalid", field: "ships_from.country" };
524
+ }
525
+ return { kind: "ok", value: { country } };
526
+ }
527
+ /** Test a value against one of the shared schema patterns, anchored exactly as the
528
+ * schema's `pattern` is (the constants carry their own `^…$`). A fresh `RegExp` per
529
+ * call keeps the patterns as plain shared strings (the schema needs the string form;
530
+ * the read site needs to execute it) with no stateful `lastIndex` to reset. */
531
+ function matchesPattern(value, pattern) {
532
+ return new RegExp(pattern).test(value);
533
+ }
534
+ /** Narrow a `condition` arg to string[], or null if unusable. Requires an array (a
535
+ * bare string is DROPPED, not wrapped); non-string entries are dropped. Returns
536
+ * null for an empty/all-dropped array so the key is omitted rather than emitted
537
+ * empty. The wire stays OPEN — values are NOT format-validated against a known set
538
+ * (an unrecognized value like "refurbished" still forwards; steering to
539
+ * new/secondhand is the description's job, not validation's). */
540
+ function readCondition(raw) {
541
+ if (!Array.isArray(raw))
542
+ return null;
543
+ const values = raw.filter((c) => typeof c === "string");
544
+ return values.length === 0 ? null : values;
545
+ }
546
+ /** The one client-side invariant the tool owns: at least one recognized input.
547
+ * A non-whitespace `query` OR any filter (`category` / `price_min` / `price_max`)
548
+ * suffices. A bare `{}` or a whitespace-only `query` with no filter is rejected;
549
+ * pagination params alone (`cursor`/`limit`) are NOT inputs — they refine an
550
+ * existing search, they do not constitute one. */
551
+ function hasUsableInput(params) {
552
+ const hasQuery = typeof params.query === "string" && params.query.trim().length > 0;
553
+ const hasFilter = typeof params.category === "string"
554
+ || typeof params.price_min === "number"
555
+ || typeof params.price_max === "number";
556
+ return hasQuery || hasFilter;
557
+ }
558
+ /** Success: the ranked products + optional cursor — no token, no Bearer header.
559
+ * An empty `products` list is a valid, successful empty match. The `ok` outcome
560
+ * already carries `products` (+ optional `cursor`); spread its payload (minus the
561
+ * `kind` discriminant) onto the agent-facing `{ status: "ok", ... }` envelope. */
562
+ function searchResult(outcome) {
563
+ const { kind: _kind, ...payload } = outcome;
564
+ return jsonResult({ status: "ok", ...payload });
565
+ }
566
+ /** Not registered: a distinct, actionable outcome naming the recovery tool. No
567
+ * products field so the agent can't mistake it for an empty match. The `tool`
568
+ * name keeps the message actionable per-tool (re-run THIS tool) while the
569
+ * status/recovery taxonomy stays shared across the catalog tools. */
570
+ function notRegistered(tool) {
571
+ return jsonResult({
572
+ status: "not_registered",
573
+ message: `Not registered on sil. Run sil_register to authenticate, then call ${tool} again.`,
574
+ recovery: "sil_register",
575
+ });
576
+ }
577
+ /** Client-side validation: the request named no usable input. Distinct from a
578
+ * sil-api 400 (which carries the server's structured error) — this never hit the
579
+ * network. No `recovery: sil_register` (auth is fine; the query is the problem). */
580
+ function invalidInput() {
581
+ return jsonResult({
582
+ status: "invalid_request",
583
+ error: "empty_search_input",
584
+ message: "Provide a search query or at least one filter (category, price_min, or"
585
+ + " price_max).",
586
+ });
587
+ }
588
+ /** Client-side validation: a location filter carried a malformed value (bad FORMAT,
589
+ * not wrong type) — rejected BEFORE any network call (re-spec). Distinct from the
590
+ * empty-input case (`empty_search_input`) and from a sil-api 400; the pinned machine
591
+ * code is `invalid_filter`. No `recovery: sil_register` — auth is fine; the value
592
+ * FORMAT is the problem. The message names the offending field and the required ISO
593
+ * code form so the agent re-sends a code, not free text. */
594
+ function invalidFilter(field) {
595
+ return jsonResult({
596
+ status: "invalid_request",
597
+ error: "invalid_filter",
598
+ message: `The \`${field}\` filter is malformed. Send standard ISO codes, not`
599
+ + " free-text names: country as a 2-letter ISO 3166-1 alpha-2 code (e.g."
600
+ + " \"US\"), region as an ISO 3166-2 subdivision code (e.g. \"CA\"), and"
601
+ + " postal_code as a destination postal/ZIP code.",
602
+ });
603
+ }
604
+ /** sil-api rejected the request (a structured 400, e.g. empty_search_input).
605
+ * Surface the server's `{ error, message }` so the agent fixes its query — NOT a
606
+ * re-register (auth is fine) and NOT a transient retry (retrying the same bad
607
+ * request won't help). Distinct from both the empty-match success and the 5xx. */
608
+ function invalidRequest(error, message) {
609
+ return jsonResult({ status: "invalid_request", error, message });
610
+ }
611
+ /** Terminal: the session is dead — reached only after the shared refresh-and-retry
612
+ * choreography ({@link refreshAndRetryOnce}) has exhausted its one refresh + one
613
+ * retry (a second 401, or a dead `invalid_grant` refresh token). Re-register. The
614
+ * `tool` name keeps the message actionable while the taxonomy stays shared. */
615
+ function mustReregister(tool) {
616
+ return jsonResult({
617
+ status: "must_reregister",
618
+ message: `Your sil session has expired. Run sil_register to sign in again, then call ${tool} again.`,
619
+ recovery: "sil_register",
620
+ });
621
+ }
622
+ /** Transient: a network/5xx blip — try again, NOT a re-register (a false terminal
623
+ * on a transient would send the agent down a recovery path that can't fix it).
624
+ * The `tool` name keeps the retry guidance actionable; the taxonomy is shared. */
625
+ function transient(tool) {
626
+ return jsonResult({
627
+ status: "retryable",
628
+ message: `sil is temporarily unavailable. Please try ${tool} again.`,
629
+ });
630
+ }