sil-openclaw 0.4.6 → 0.5.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +33 -45
  3. package/dist/gateway/search-results.js +11 -7
  4. package/dist/index.js +24 -24
  5. package/dist/lib/allowlist-script.js +13 -0
  6. package/dist/lib/artifacts.js +30 -0
  7. package/dist/lib/credentials.js +2 -3
  8. package/dist/lib/host-wiring.js +44 -15
  9. package/dist/lib/pkce.js +3 -3
  10. package/dist/lib/search-results-log.js +23 -0
  11. package/dist/lib/search-results-store.js +4 -4
  12. package/dist/lib/shopping-call.js +143 -0
  13. package/dist/lib/sil-client.js +185 -1046
  14. package/dist/lib/tool-result.js +10 -3
  15. package/dist/tools/catalog.js +311 -1197
  16. package/dist/tools/doctor.js +25 -63
  17. package/dist/tools/identity.js +110 -245
  18. package/openclaw.plugin.json +14 -11
  19. package/package.json +7 -6
  20. package/schema/PROVENANCE.md +15 -0
  21. package/schema/shopping-brief-create-request.schema.json +98 -0
  22. package/schema/shopping-brief-create-response.schema.json +24 -0
  23. package/schema/shopping-brief-edit-request.schema.json +125 -0
  24. package/schema/shopping-brief-edit-response.schema.json +24 -0
  25. package/schema/shopping-brief-read-request.schema.json +15 -0
  26. package/schema/shopping-brief-read-response.schema.json +235 -0
  27. package/schema/shopping-domain-create-request.schema.json +160 -0
  28. package/schema/shopping-domain-create-response.schema.json +60 -0
  29. package/schema/shopping-domain-get-request.schema.json +18 -0
  30. package/schema/shopping-domain-get-response.schema.json +307 -0
  31. package/schema/shopping-domain-search-request.schema.json +18 -0
  32. package/schema/shopping-domain-search-response.schema.json +92 -0
  33. package/schema/shopping-offers-request.schema.json +31 -0
  34. package/schema/shopping-offers-response.schema.json +172 -0
  35. package/schema/shopping-product-get-request.schema.json +24 -0
  36. package/schema/shopping-product-get-response.schema.json +121 -0
  37. package/schema/shopping-profile-edit-request.schema.json +97 -0
  38. package/schema/shopping-profile-edit-response.schema.json +17 -0
  39. package/schema/shopping-search-request.schema.json +106 -0
  40. package/schema/shopping-search-response.schema.json +182 -0
  41. package/schema/shopping-seller-get-request.schema.json +24 -0
  42. package/schema/shopping-seller-get-response.schema.json +342 -0
  43. package/scripts/allowlist-openclaw.mjs +4 -5
  44. package/sil-shopping/SKILL.md +196 -97
  45. package/sil-shopping/references/mint.md +190 -0
  46. package/dist/lib/bind-channel.js +0 -10
  47. package/dist/lib/creation-entrypoint.js +0 -111
  48. package/dist/lib/derive-agent-id.js +0 -36
  49. package/dist/lib/profile-store.js +0 -568
  50. package/dist/tools/profile.js +0 -300
  51. package/scripts/create-shopper.mjs +0 -677
  52. package/sil-shopping/examples/multi_domain_shopper_walkthrough.md +0 -65
  53. package/sil-shopping/references/agent_creation_engine.md +0 -223
  54. package/sil-shopping/references/fill_and_feedback.md +0 -102
  55. package/sil-shopping/references/method_and_prds.md +0 -143
  56. package/sil-shopping/references/setup_onboarding.md +0 -64
  57. package/sil-shopping/references/shop_loop.md +0 -118
@@ -1,1215 +1,329 @@
1
1
  /**
2
- * Catalog tools for the sil plugin.
2
+ * The eleven `shopping_*` tools, 1:1 with the sil-api catalog, brief and profile routes.
3
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 session 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
- * 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
- *
56
- * `register()` stays synchronous and side-effect-free beyond registering tools —
57
- * no fetch, no timer, no unawaited promise. All I/O is inside `execute()`.
4
+ * A projection on the way back would drop exactly the fields the agent's honesty reading
5
+ * is computed from (`fit`, `unknown`, `variants`, `printed`) while looking healthy, so the
6
+ * body crosses verbatim. A new `registerXTools` group has to be hand-wired into three guards
7
+ * or it silently NARROWS them (CLAUDE.md), which is why all eleven live in one group.
58
8
  */
59
- import { Type } from "typebox";
60
- import { getApiUrl } from "../lib/config.js";
61
- import { clearTokens, readConfig, readTokens } from "../lib/credentials.js";
62
- import { wiringAdvisories } from "../lib/host-wiring.js";
9
+ import { requestSchema } from "../lib/artifacts.js";
10
+ import { readConfig } from "../lib/credentials.js";
11
+ import { wiringAdvisoryBlocks } from "../lib/host-wiring.js";
12
+ import { logSearchResults } from "../lib/search-results-log.js";
63
13
  import { putSearchResult } from "../lib/search-results-store.js";
64
- import { lookupCatalog, refreshAndRetryOnce, searchCatalog, specsCatalog, } from "../lib/sil-client.js";
14
+ import { DOMAIN_GET_ROUTE, callRoute } from "../lib/shopping-call.js";
65
15
  import { jsonResult } from "../lib/tool-result.js";
16
+ /** The tool whose page a paired client can pull back by `callId`. */
17
+ const SEARCH_TOOL = "shopping_search";
18
+ export const SHOPPING_TOOLS = [
19
+ {
20
+ name: "shopping_domain_search",
21
+ method: "GET",
22
+ path: "/catalog/domains",
23
+ query: ["q"],
24
+ label: "Read sil's registry for a domain",
25
+ description: "What sil holds, and where it shelves it: read the registry in the buyer's own"
26
+ + " words. `matches` are the domains that match, each with its path and a line on how"
27
+ + " the thing is bought — judge fit on `about`, then take that path verbatim, or"
28
+ + " descend under a broader one, never a sibling of a path that already stands. `tree`"
29
+ + " is every standing path grouped by family: hang a new leaf where a specialist shop"
30
+ + " would shelve it, and see that a setup of several things is several leaves."
31
+ + " `matches: []` is the ONLY answer that licenses shopping_domain_create, and a"
32
+ + " non-ok status is not an empty one. At most two reads per domain, then"
33
+ + " shopping_domain_get for the document and the keys of the path you take.",
34
+ },
35
+ {
36
+ name: "shopping_domain_get",
37
+ ...DOMAIN_GET_ROUTE,
38
+ label: "Read a domain's document and keys",
39
+ recovery: { not_found: "shopping_domain_search" },
40
+ description: "sil's own document on how this thing is bought well — read it before you ask the"
41
+ + " buyer anything, and again when a want fits no key: the document GROWS as sil reads"
42
+ + " pages. `guide` is markdown: what it is bought on, what goes wrong and what that"
43
+ + " costs the buyer, what to trust, and what buying it online takes. `name` is its one"
44
+ + " English name and `labels` the market's own words for it — read them, never send"
45
+ + " them. `specs` are the keys it is bought by and `seller_specs` the seller terms it"
46
+ + " is bought with; one read hands you both. Each key's `description` says how that"
47
+ + " key moves the fit: what it decides, what goes wrong at either end, and how a"
48
+ + " buyer's own fact becomes its value. Each key states its type, its operators, its"
49
+ + " unit, any closed set, the `step` a number moves by, and `forms` — what pages"
50
+ + " print, mapped to the value. Send that key and one of those operators, never a"
51
+ + " synonym you coined: `specs` go on the brief and to shopping_search,"
52
+ + " `seller_specs` on the brief's `seller` domain, where shopping_offers reads"
53
+ + " them. variant_spec marks the key an option is picked on (a size, a"
54
+ + " colour), answered under each product's variants; product_spec tells one product"
55
+ + " from the next. The root `product` always stands and carries the universals every"
56
+ + " domain inherits; a path that does not stand answers not_found, and the recovery is"
57
+ + " to read the registry again in their words.",
58
+ },
59
+ {
60
+ name: "shopping_domain_create",
61
+ method: "POST",
62
+ path: "/catalog/domains",
63
+ label: "Write a domain sil does not hold",
64
+ // A colliding path means the vocabulary is already there, so search that same path.
65
+ recovery: { already_exists: "shopping_search" },
66
+ description: "The FALLBACK, and the one permanent global write in sil: a curated domain already"
67
+ + " carries a document, and this writes one for a domain it does not hold. First: a"
68
+ + " shopping_domain_search read that came back `matches: []`, and research on how the"
69
+ + " domain is bought (never products). Hang the leaf where the `tree` shows its"
70
+ + " family: different keys are a different leaf, another value of the same keys is a"
71
+ + " value. `guide` is markdown every later buyer inherits: what the thing is bought"
72
+ + " on, what goes wrong and what that costs the buyer, and what buying it online takes"
73
+ + " — never \"go to a shop\". Each key's `description` does the same for one key. `name`"
74
+ + " is its one English name, `labels` the words shops print; a spec carries `step`,"
75
+ + " the increment its numbers move by, and `forms`, a printed form mapped to its"
76
+ + " value. Mark variant_spec on the key an option is picked on, product_spec on one"
77
+ + " telling products apart. Coin only keys a PRODUCT is bought by: seller terms are"
78
+ + " never yours to coin, and shopping_domain_get answers them as `seller_specs`. You"
79
+ + " inherit every ancestor's key and may not rename one: re-declare only to change its"
80
+ + " unit, values or mark for your subtree; stating nothing new it answers `inherited:"
81
+ + " true`, and a key naming a standing one binds and answers `bound_from`. A refusal"
82
+ + " names the standing thing and the fix.",
83
+ },
84
+ {
85
+ name: "shopping_brief_create",
86
+ method: "POST",
87
+ path: "/briefs/create",
88
+ label: "Open the session's brief",
89
+ description: "Once per SESSION: open the one brief this conversation works from — across"
90
+ + " every domain the buyer asks about, never one per domain — and hold the `id`"
91
+ + " it answers for the rest of the session, because every search and every offers"
92
+ + " call names it. A new chat opens its own AFTER shopping_brief_read has shown what"
93
+ + " is on file: carry every spec an earlier brief still holds true into this one, then"
94
+ + " name that carry in the first shopping_brief_edit `decision`. `title` names the job"
95
+ + " in a few words. `narrative` is the spec of the buy in the buyer's own terms — what"
96
+ + " a good buy looks like for THEM, what it has to do for them, what would make it a"
97
+ + " bad one — and a want no keyed spec can carry lives there and still counts. An"
98
+ + " optional first `domain` with `specs` writes what they have already said: a"
99
+ + " domain path carries that domain's product specs, `seller` carries the seller"
100
+ + " specs, and each spec is a key and an operator shopping_domain_get listed whose"
101
+ + " `reason` quotes the buyer VERBATIM — their own words, or the measurement the"
102
+ + " guide converted — never a paraphrase and never a want they did not state. On"
103
+ + " anything worn, the `gender` sil_whoami holds is a product spec in the registry's"
104
+ + " own spelling — male → `gender eq mens`, female → `gender eq womens` — asked once"
105
+ + " where the profile answers none or `other`, and never inferred. Everything after"
106
+ + " this is shopping_brief_edit.",
107
+ },
108
+ {
109
+ name: "shopping_brief_edit",
110
+ method: "POST",
111
+ path: "/briefs/edit",
112
+ label: "Write a want or a decision into the brief",
113
+ // The id is the only thing a 404 can be about here, and the bare read lists what is.
114
+ recovery: { not_found: "shopping_brief_read" },
115
+ description: "The brief's write: put every want the buyer states into the brief as it is settled,"
116
+ + " with `reason` quoting their own words VERBATIM — never a"
117
+ + " paraphrase, never a want they did not state. A want that reaches"
118
+ + " no brief is a want the next call drops. A MEASUREMENT is never the spec: 27.2 cm is"
119
+ + " the buyer's, and the spec is the size the thing is sold in —"
120
+ + " `mondo_size in [27, 27.5]`, with that measurement as its `reason`; the key's"
121
+ + " `description` says how one becomes the other."
122
+ + " One write per `domain`: a domain path carries"
123
+ + " that domain's product specs, `price` among them, and `seller` carries the"
124
+ + " seller specs, which belong to the whole brief. `specs` REPLACE every spec on the"
125
+ + " keys they name — a range is the two rows on its key — `remove` names the keys"
126
+ + " whose specs go, and `narrative` replaces the whole narrative. When the buyer"
127
+ + " changes their mind — and only then — send the new spec together with `decision`:"
128
+ + " one sentence ABOUT them, never in their voice, saying what they changed and"
129
+ + " why. A new want's words are its spec's `reason`, never a `decision`, and never a"
130
+ + " log of what you have just written down."
131
+ + " Send `status: \"closed\"` when the job is over. An"
132
+ + " invalid_request names the key and shows a spec on it that passes — fix that row"
133
+ + " and send it again, and never give the want up. A brief id that is not the"
134
+ + " buyer's answers not_found; shopping_brief_read with no `id` lists their briefs.",
135
+ },
136
+ {
137
+ name: "shopping_brief_read",
138
+ method: "POST",
139
+ path: "/briefs/read",
140
+ label: "Read the brief, or list the buyer's briefs",
141
+ description: "The first read of a new chat: with no `id` it answers the buyer's briefs,"
142
+ + " newest first, each with its title, its domains and when it was last written."
143
+ + " Call it with sil_whoami before you ask the buyer anything, so a job already"
144
+ + " under way is continued rather than interviewed a second time. With an `id` it"
145
+ + " answers that brief whole: the title, the narrative, every spec under the domain"
146
+ + " it sits on (`seller` for the seller specs), and the decisions already taken with"
147
+ + " the time of each. What comes back is a READ: it says what the buyer has already"
148
+ + " settled so you ask none of it again, and the specs still true are carried into"
149
+ + " this session's own brief with shopping_brief_create — the search runs on that"
150
+ + " one, never on an earlier session's. New wants go in through shopping_brief_edit.",
151
+ },
152
+ {
153
+ name: "shopping_profile_edit",
154
+ method: "POST",
155
+ path: "/profile/edit",
156
+ label: "Write what is true of the buyer",
157
+ description: "The person rather than the job: write what is true of the buyer whatever"
158
+ + " they are buying, the moment they say it and BEFORE the next search — only what"
159
+ + " they stated UNAMBIGUOUSLY about themselves. A phrase that could mean two things"
160
+ + " (\"wide forefoot and bit short\" — the foot, or the buyer?) is asked about, never"
161
+ + " written here, because a lasting fact written wrong follows them into every"
162
+ + " domain. Every `name` is lower snake_case: `foot_length`, never \"foot length\"."
163
+ + " A"
164
+ + " `measurements` entry is a number with its `unit`, or a size exactly as it is"
165
+ + " printed; a `preferences` entry is a lasting taste in the buyer's own words."
166
+ + " An entry replaces the one of the same `name`, and `remove` names the entries"
167
+ + " that stopped being true. `currency` is the ISO 4217 code they price in, and"
168
+ + " every money row naming none means it: \"my prices in dollars from now on\" is"
169
+ + " `currency: \"USD\"`, which changes which offers come first and never a price —"
170
+ + " sil converts nothing. sil_whoami reads all of it back, so a fact written here"
171
+ + " is one you never ask for again. What belongs to THIS job — a budget, a size for"
172
+ + " these boots — is the brief's, through shopping_brief_edit: a measurement is the"
173
+ + " buyer's, and the spec the domain's guide turns it into carries that"
174
+ + " measurement as its `reason`.",
175
+ },
176
+ {
177
+ name: SEARCH_TOOL,
178
+ method: "POST",
179
+ path: "/catalog/search",
180
+ label: "Search sil in one settled domain",
181
+ // A 404 here is the `brief` id and nothing else: a domain that does not stand is
182
+ // refused as `invalid_request`, naming the path.
183
+ recovery: { not_found: "shopping_brief_read" },
184
+ description: "The products that fit the brief, in one settled domain. Search as often as the job"
185
+ + " needs — a re-worded `query`, a different `n` — it is cheap and it is how you learn"
186
+ + " what is out there. Send `brief` (the session's brief id) on EVERY call,"
187
+ + " the domain path, and `query` — the thing as a shop lists it and the numbers"
188
+ + " that pick the product, never a sentence; a budget, a market, a unit, a standard's"
189
+ + " name, \"in stock\" and \"online\" are specs, and cost most of the offers."
190
+ + " `n` counts VARIANTS — one size, one option — max 10. `specs`: every product"
191
+ + " spec the brief holds for this domain, all of them and UNCHANGED — never a looser"
192
+ + " bound, never one it does not hold — money a decimal STRING (`\"300\"`, never 300)."
193
+ + " The brief's `seller` specs are shopping_offers' to read off the brief, never on"
194
+ + " the search. Keep the server's order, never re-rank; quote each variant's OWN"
195
+ + " `price` with its size. `fit` answers the ask key by key: the value sil verified,"
196
+ + " or \"unknown\" where it holds none — a gap to dig into with shopping_product_get,"
197
+ + " never a failed one."
198
+ + " `host` is the shop; `printed` is that page's own pairs, never verified —"
199
+ + " say \"the page says\". A `variants` entry with no option"
200
+ + " values is a listing whose sizes sil has not read: say so — it prices like any"
201
+ + " other. sil never says what it left out, so a want left off `specs` is one you will"
202
+ + " not know you missed.",
203
+ },
204
+ {
205
+ name: "shopping_product_get",
206
+ method: "POST",
207
+ path: "/catalog/product",
208
+ label: "Read the whole dossier on a shortlisted variant",
209
+ description: "The dossier: send 1–10 variant ids from a shopping_search answer and get"
210
+ + " the whole of what sil holds for each — the title, the maker, the page's own"
211
+ + " description, the images, every key sil holds for it (not only the ones you"
212
+ + " asked about), and `sources` naming which site each reading came from and when."
213
+ + " This is where a key the search answered \"unknown\" is dug out. A variant with no"
214
+ + " option values is a listing whose sizes sil has not read, and its id opens here"
215
+ + " like any other: the answer carries that page whole, so the sizes it prints are"
216
+ + " the page's own words — say the size is unread, never that it is in stock."
217
+ + " Compare the shortlist on this before recommending, and quote a source's date"
218
+ + " rather than implying sil read it just now. An id sil cannot place is simply"
219
+ + " absent from the answer — say that listing could not be placed, and never"
220
+ + " substitute another product. Ids are opaque: pass them back exactly as sil"
221
+ + " minted them, and never read one.",
222
+ },
223
+ {
224
+ name: "shopping_offers",
225
+ method: "POST",
226
+ path: "/catalog/offers",
227
+ label: "List who sells a variant, at what price and on what terms",
228
+ // Same as the search: the only 404 this route answers is a brief that is not
229
+ // the buyer's.
230
+ recovery: { not_found: "shopping_brief_read" },
231
+ description: "Who sells it, at what price, on what terms — the only live read of a price."
232
+ + " Worth a call once the buyer wants something: pricing a whole shortlist buries the"
233
+ + " fit answer they asked for. Send `brief` (the session's brief id) and 1–10 picked"
234
+ + " variant ids, and nothing else: sil reads the brief's `seller` specs, its `price`"
235
+ + " ceiling, the buyer's default address and their currency itself, so a seller term"
236
+ + " the buyer states goes on the brief. The first three picks are also looked for on"
237
+ + " the web, so put the one they want first; the rest answer from shops sil holds. A"
238
+ + " variant with no option values is priced as its page prints. An offer is the pick"
239
+ + " at one shop, read live: the seller, the price in its own currency (sil converts"
240
+ + " nothing), its availability, the listing URL, `observed_at`, and `seller_fit`:"
241
+ + " `ships` always — serviceable, not_serviceable or unknown for that address — and"
242
+ + " each brief seller key where sil holds the seller's value. An offer over the"
243
+ + " brief's price in that price's currency is left out; one in another currency was"
244
+ + " not tested against it — say so. `unknown` keeps the offer: say sil could not"
245
+ + " confirm shipping. A key absent from `seller_fit` is a term sil has not read. The"
246
+ + " order is the buyer's currency and market first, then sellers known to reach them,"
247
+ + " then the rest — keep it, never re-rank. Several offers ARE the price spread, and"
248
+ + " the spread is the answer.",
249
+ },
250
+ {
251
+ name: "shopping_seller_get",
252
+ method: "POST",
253
+ path: "/catalog/sellers",
254
+ label: "Read one seller's whole terms",
255
+ description: "One seller's WHOLE terms: send 1–10 seller ids from shopping_offers, and"
256
+ + " nothing else. Each seller comes back with its name, host and country, `specs` —"
257
+ + " every seller key sil holds a value for, base and branch, as the dossier's `specs`"
258
+ + " are a product's — and `ships`, which answers for the buyer's default address:"
259
+ + " serviceable (sil read a route covering it), not_serviceable (sil read this"
260
+ + " seller's policy and it excludes it), or unknown (sil has read nothing about this"
261
+ + " seller). `unknown` is an ordinary answer that keeps the seller — say sil could not"
262
+ + " confirm shipping, and hand the buyer the listing; an empty `specs` is the same"
263
+ + " answer about its terms. Where sil has read them, `shipping` carries the routes"
264
+ + " with their cost, free-over threshold and days, and `returns` the window and any"
265
+ + " restocking fee; a term the page never stated is simply absent, which is never zero"
266
+ + " and never free. A `policy_url` of null means the terms were read off a product"
267
+ + " page and sil holds no policy page. This is the details read: whether an offer"
268
+ + " meets the buyer's own seller rows is `seller_fit` on that offer, from"
269
+ + " shopping_offers.",
270
+ },
271
+ ];
66
272
  /**
67
- * The TIGHTENED ship-to format contract (founder re-spec 2026-06-11), pinned as a
68
- * `pattern` BOTH the local schema and sil-api's `@sil/schemas` `ShipTo` enforce
69
- * IDENTICALLY (byte-for-byte) — so the plugin rejects a malformed value client-side
70
- * instead of forwarding free text and eating an opaque, fail-late sil-api 400. These
71
- * same patterns are the schema `pattern` (so the host validates) AND the read-site
72
- * format gate (so a drifted on-disk call is rejected), defined once here to keep the
73
- * two in lockstep. The sil-services sibling
74
- * (`attach-buyer-ship-to-context-server-side-in-sil-ap`) MUST mirror these exactly;
75
- * the sil-stage eval verifies it end-to-end.
76
- * - country (ships_to): ISO 3166-1 alpha-2, a 2-letter code.
77
- * - region: ISO 3166-2 subdivision code (CA/NY/BY/97), bounded — NOT a place name.
78
- * - postal_code: a single self-contained pattern (a length-cap lookahead 2–12
79
- * chars, separators counted, + a structural body of alnum runs joined by single
80
- * internal space/hyphen, no leading/trailing/doubled separator) — accepts real
81
- * national formats (94107 / EC1A 1BB / K1A 0B1), rejects prose/injection/overlong.
273
+ * Registers the eleven, reading each one's request artifact off disk as it goes.
274
+ *
275
+ * That read is the ONE exception to "register() opens nothing": eleven synchronous
276
+ * `readFileSync`s that return immediately and hold no resource open, exactly as
277
+ * `ensureDataDir`'s `mkdirSync` does. It is deliberately eager — an unreadable artifact
278
+ * is a broken build, and failing loud at load beats a tool whose `parameters` the host
279
+ * has already published by the time anyone finds out.
82
280
  */
83
- const COUNTRY_PATTERN = "^[A-Za-z]{2}$";
84
- const REGION_PATTERN = "^[A-Za-z0-9]{1,3}$";
85
- const POSTAL_PATTERN = "^(?=[A-Za-z0-9 -]{2,12}$)[A-Za-z0-9]+(?:[ -][A-Za-z0-9]+)*$";
86
- /** The `sil_specs` coined-definition schema. Unlike the search predicate's `value`
87
- * (an op→value read-site rule the schema can't express), a `SpecDefinition` is
88
- * FULLY TypeBox-expressible — a closed `data_type` union of four literals plus
89
- * `minLength:1` identity fields and optional context — so the host validates the
90
- * shape directly. Mirrors `@sil/schemas` `SpecDefinition` (the frozen wire contract). */
91
- const SPEC_DEFINITION_SCHEMA = Type.Object({
92
- namespace: Type.String({
93
- minLength: 1,
94
- description: "The spec NAMESPACE (e.g. \"product\", \"seller\", \"shipping\") — a free"
95
- + " string coined bottom-up; NOT dotted with the key.",
96
- }),
97
- key: Type.String({
98
- minLength: 1,
99
- description: "The spec KEY within the namespace (e.g. \"waterproof_rating\","
100
- + " \"rating_average\") — a free string coined bottom-up.",
101
- }),
102
- display_name: Type.String({
103
- minLength: 1,
104
- description: "A short human label for the spec (e.g. \"Waterproof rating\").",
105
- }),
106
- data_type: Type.Union([
107
- Type.Literal("number"),
108
- Type.Literal("text"),
109
- Type.Literal("boolean"),
110
- Type.Literal("enum"),
111
- ], {
112
- description: "The spec's value type: number, text, boolean, or enum (use enum with"
113
- + " allowed_values for a closed set).",
114
- }),
115
- description: Type.Optional(Type.String({
116
- description: "Optional prose describing what the spec means — sharpens the registry's"
117
- + " dedupe (a clearer definition reduces false matches).",
118
- })),
119
- unit: Type.Optional(Type.String({
120
- description: "Optional unit for a numeric spec (e.g. \"mm\", \"GB\", \"days\").",
121
- })),
122
- allowed_values: Type.Optional(Type.Array(Type.String(), {
123
- description: "For an enum spec, the closed set of permitted values.",
124
- })),
125
- });
126
281
  export function registerCatalogTools(api) {
127
- registerSearch(api);
128
- registerProductGet(api);
129
- registerSpecs(api);
130
- }
131
- function registerSearch(api) {
132
- api.registerTool({
133
- name: "sil_search",
134
- label: "Search the sil catalog",
135
- description: "Search sil's catalog for purchasable products. Pass a free-text `query`"
136
- + " and/or filters (`category`, `price_min`/`price_max` in the currency's"
137
- + " minor units, e.g. cents). Returns a ranked list (best match first —"
138
- + " present results in order, do not re-rank), each item a purchasable"
139
- + " variant with id, title, price, availability, checkout_url, and source,"
140
- + " plus (where the source provides them) the evaluate-before-buy fields:"
141
- + " product and variant `url`, a short `description`, `media`, the product"
142
- + " `options` (the menu of choices), the `seller` (with policy/info links),"
143
- + " and arbitrary `metadata`. THREE DISTINCT ACTIONS the agent must not"
144
- + " conflate: (1) VIEW — a product's or variant's `url` opens the PAGE to"
145
- + " view / learn more; hand it to the user to SEE the item, it is NOT a"
146
- + " purchase. (2) DIG IN — `seller.links` are the seller's policy / info"
147
- + " links (refund policy, shipping policy, terms); follow one to answer"
148
- + " \"what's their return policy?\" without a web search. (3) BUY —"
149
- + " `checkout_url` is the variant permalink that commits the purchase; use it"
150
- + " ONLY to buy. A variant's `url` and its `checkout_url` are DIFFERENT"
151
- + " targets: `url` is the page (view / learn more) whereas `checkout_url`"
152
- + " buys — never hand back `checkout_url` for a \"show me / learn more\""
153
- + " intent, and never stall on `url` when the user said \"buy\"."
154
- + " Use the returned `cursor` to fetch the next page (its absence means no"
155
- + " more results — never infer end-of-results from the page size). An empty"
156
- + " result list means nothing matched (a normal outcome, not an error)."
157
- + " For the location filters, ALWAYS send standard ISO CODES, NOT free text or"
158
- + " natural-language place names — send the 2-letter country code \"US\", never"
159
- + " the name \"United States\"; send the subdivision code \"CA\", never the place"
160
- + " name \"California\". A free-text name is rejected; the code is not."
161
- + " Delivery destination: LEAVE `ship_to` EMPTY for \"ship to me\" — when it is"
162
- + " absent, sil-api resolves the user's REGISTERED DEFAULT ADDRESS server-side"
163
- + " and localizes results to it. Do NOT call sil_whoami (or any identity read)"
164
- + " to fetch the user's address and put it in `ship_to` — that round-trip is"
165
- + " wasted work and yields the same result as omitting it. Set `ship_to` ONLY"
166
- + " to OVERRIDE the default — to ship to a DIFFERENT destination than the"
167
- + " user's registered address (e.g. \"ship it to my office in Berlin\"). Its"
168
- + " fields: `country` = the 2-letter ISO 3166-1 alpha-2 code (US, GB, DE — a"
169
- + " code, NOT a country name); `region` (optional) = the ISO 3166-2 subdivision"
170
- + " code (CA, NY, BY — a code, NOT a place name); `postal_code` (optional) ="
171
- + " the destination postal/ZIP code. The other optional filters need no prior"
172
- + " tool call: `condition` (array; the values are exactly \"new\" or"
173
- + " \"secondhand\", lowercase) filters by product condition; `available`"
174
- + " (boolean) controls availability — the server returns only sale-ready items"
175
- + " by default, so set `available: false` to INCLUDE out-of-stock/unavailable"
176
- + " items. `local_merchants` (boolean) is a BEST-EFFORT BIAS toward shops based"
177
- + " in the user's OWN country (home-country / domestic / local sellers) — set it"
178
- + " ONLY when the shopper asks for local/domestic shops; it nudges local shops up"
179
- + " the ranking but does NOT restrict results to them, so never tell the user the"
180
- + " results are all local. To surface MORE local shops you MAY also issue the"
181
- + " `query` in that country's language (a Greek-language query surfaces Greek"
182
- + " shops) — optional, and never an override of a language the user deliberately"
183
- + " chose; pass NO country — sil resolves it server-side. `specs` is the"
184
- + " STRUCTURED requirement channel — a list of typed predicates ({ ns, key, op,"
185
- + " value, unit?, hard? }) for the OPEN LONG-TAIL of attributes that have no"
186
- + " dedicated param (e.g. product.capacity_gb, seller.rating_average,"
187
- + " shipping.delivery_max_days). PREFER A DEDICATED PARAM OVER A `specs`"
188
- + " PREDICATE FOR THE SAME ATTRIBUTE: route price to price_min/price_max,"
189
- + " category to category, condition to condition, availability to available,"
190
- + " and the delivery destination to ship_to — never send both a dedicated"
191
- + " param and a `specs` predicate for the one attribute (that risks an"
192
- + " over-narrow or divergent result). Mark a predicate `hard: true` when the"
193
- + " requirement is inviolable. Requires registration (run"
194
- + " sil_register first).",
195
- parameters: Type.Object({
196
- query: Type.Optional(Type.String({
197
- description: "Free-text search query. Either this or at least one filter is required.",
198
- })),
199
- category: Type.Optional(Type.String({
200
- description: "Restrict results to a single product category.",
201
- })),
202
- price_min: Type.Optional(Type.Integer({
203
- minimum: 0,
204
- description: "Minimum price, in the currency's ISO 4217 minor unit (e.g. cents).",
205
- })),
206
- price_max: Type.Optional(Type.Integer({
207
- minimum: 0,
208
- description: "Maximum price, in the currency's ISO 4217 minor unit (e.g. cents).",
209
- })),
210
- cursor: Type.Optional(Type.String({
211
- description: "Opaque pagination cursor from a prior search's result.",
212
- })),
213
- limit: Type.Optional(Type.Integer({
214
- minimum: 1,
215
- description: "Requested maximum number of results. The server may return fewer.",
216
- })),
217
- ship_to: Type.Optional(Type.Object({
218
- country: Type.String({
219
- pattern: COUNTRY_PATTERN,
220
- description: "Destination country as a 2-letter ISO 3166-1 alpha-2 CODE (US, GB,"
221
- + " DE) — a code, NOT a country name (\"United States\" is rejected).",
222
- }),
223
- region: Type.Optional(Type.String({
224
- pattern: REGION_PATTERN,
225
- description: "Destination region as an ISO 3166-2 subdivision CODE (CA, NY, BY)"
226
- + " — a code, NOT a place name (\"California\" is rejected). Optional.",
227
- })),
228
- postal_code: Type.Optional(Type.String({
229
- pattern: POSTAL_PATTERN,
230
- description: "Destination postal/ZIP code (e.g. 94107, EC1A 1BB, K1A 0B1)."
231
- + " Optional refinement.",
232
- })),
233
- }, {
234
- description: "Deliver-to destination for serviceability + localization. LEAVE EMPTY"
235
- + " for \"ship to me\": when absent/omitted, sil-api uses the user's"
236
- + " REGISTERED DEFAULT ADDRESS (resolved server-side) — do NOT call"
237
- + " sil_whoami to fetch and resubmit it. Set this ONLY to OVERRIDE the"
238
- + " default with a DIFFERENT destination than the registered address."
239
- + " Send ISO CODES, never free-text place names.",
240
- })),
241
- local_merchants: Type.Optional(Type.Boolean({
242
- description: "Bias results toward shops based in the USER'S OWN country (home-country"
243
- + " / domestic / local sellers) — set true ONLY when the shopper asks for"
244
- + " local or domestic shops (e.g. \"buy from a Greek shop\", \"support"
245
- + " local businesses\"). This is a BEST-EFFORT BIAS, NOT a filter: it"
246
- + " nudges local shops up the ranking but does NOT restrict results to them"
247
- + " and does NOT guarantee every result is local — some local shops won't"
248
- + " be detected and some non-local shops may still appear, so never tell"
249
- + " the user the results are all local sellers. To surface MORE local"
250
- + " shops you MAY also issue the `query` in that country's language (a"
251
- + " Greek-language query surfaces Greek shops; an English query will not)"
252
- + " — optional, never overriding a language the user deliberately chose. You pass NO"
253
- + " country — sil resolves the user's country server-side from their"
254
- + " registered address, so do NOT call sil_whoami or pass a country. Omit"
255
- + " (or false) for the normal unbiased ranking.",
256
- })),
257
- condition: Type.Optional(Type.Array(Type.String(), {
258
- description: "Filter by product condition. The values are exactly \"new\" or"
259
- + " \"secondhand\" (lowercase; multiple are OR'd). Omit for no condition"
260
- + " filter.",
261
- })),
262
- available: Type.Optional(Type.Boolean({
263
- description: "Availability filter. The server returns only sale-ready items by"
264
- + " default; set false to INCLUDE unavailable/out-of-stock items. Omit"
265
- + " to keep the default (available only).",
266
- })),
267
- specs: Type.Optional(Type.Array(Type.Object({
268
- ns: Type.String({
269
- description: "The predicate NAMESPACE (e.g. \"product\", \"seller\", \"shipping\")"
270
- + " — a free string, coined bottom-up; NOT dotted with the key.",
271
- }),
272
- key: Type.String({
273
- description: "The predicate KEY within the namespace (e.g. \"capacity_gb\","
274
- + " \"rating_average\") — a free string, coined bottom-up.",
275
- }),
276
- op: Type.Union([
277
- Type.Literal("eq"),
278
- Type.Literal("neq"),
279
- Type.Literal("gte"),
280
- Type.Literal("lte"),
281
- Type.Literal("in"),
282
- Type.Literal("nin"),
283
- Type.Literal("exists"),
284
- ], {
285
- description: "The comparison operator. `gte`/`lte` need a number `value`;"
286
- + " `in`/`nin` need an array `value`; `eq`/`neq` need a scalar"
287
- + " `value`; `exists` takes NO `value`.",
288
- }),
289
- value: Type.Optional(Type.Union([
290
- Type.Number(),
291
- Type.String(),
292
- Type.Boolean(),
293
- Type.Array(Type.Union([Type.String(), Type.Number()])),
294
- ], {
295
- description: "The compared value, matching the op (omit it for `exists`).",
296
- })),
297
- unit: Type.Optional(Type.String({
298
- description: "The value's unit (e.g. \"mm\", \"GB\", \"days\") — optional context"
299
- + " carried on the wire.",
300
- })),
301
- hard: Type.Optional(Type.Boolean({
302
- description: "Set true when the requirement is INVIOLABLE (a hard constraint the"
303
- + " result must satisfy), false/omit for a soft preference.",
304
- })),
305
- }), {
306
- description: "Structured requirement predicates for the OPEN LONG-TAIL of attributes"
307
- + " with no dedicated param (product.capacity_gb, seller.rating_average,"
308
- + " shipping.delivery_max_days). Each { ns, key, op, value, unit?, hard? }"
309
- + " rides the request under one namespaced `filters.specs` key. PREFER a"
310
- + " dedicated param (price_min/price_max, category, condition, available,"
311
- + " ship_to) over a `specs` predicate for the SAME attribute — never send"
312
- + " both. Omit when there are no structured requirements.",
313
- })),
314
- }),
282
+ for (const tool of SHOPPING_TOOLS)
283
+ api.registerTool(defineTool(api, tool));
284
+ }
285
+ function defineTool(api, tool) {
286
+ return {
287
+ name: tool.name,
288
+ label: tool.label,
289
+ description: tool.description,
290
+ parameters: requestSchema(tool.name),
315
291
  async execute(callId, params) {
316
- // 1 — not registered: terminal, zero network calls.
317
- const stored = readTokens();
318
- if (stored === null) {
319
- return notRegistered("sil_search");
320
- }
321
- // Narrow the untrusted params (the SDK types `params` as
322
- // Record<string, unknown>; the host validates against the schema, but the
323
- // read site still guards — mirrors the defensive narrowing in sil-client).
324
- // A present-but-malformed location filter (bad FORMAT, not wrong type) is
325
- // rejected client-side BEFORE the input guard or any network call — a clear
326
- // `invalid_filter` beats an opaque, fail-late sil-api 400 (re-spec).
327
- const read = readSearchParams(params);
328
- if (read.kind === "invalid") {
329
- if (read.code === "invalid_spec") {
330
- api.logger.info("sil_search_invalid_spec", { field: read.field });
331
- return invalidSpec(read.field);
332
- }
333
- api.logger.info("sil_search_invalid_filter", { field: read.field });
334
- return invalidFilter(read.field);
335
- }
336
- const search = read.params;
337
- // 2 — client-side input guard: reject the obviously-empty request before
338
- // any network call. A filter-only request is a valid browse, not rejected.
339
- // (The new location filters are REFINEMENTS, not inputs — `hasUsableInput` is
340
- // unchanged, so a request of only-new-args is rejected as empty input.)
341
- if (!hasUsableInput(search)) {
342
- return invalidInput();
343
- }
344
- // 3 — search; on a 401 refresh-and-retry ONCE via the shared choreography
345
- // (the SAME path sil_whoami / sil_product_get use — 401 recovery is uniform
346
- // across every sil-api-calling tool, never per-tool).
347
- const first = await searchCatalog(getApiUrl(), stored.access_token, search);
348
- const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => searchCatalog(getApiUrl(), accessToken, search));
349
- switch (recovered.kind) {
350
- case "result":
351
- // On a silent recovery (`refreshed`: a 401 was healed by the refresh+retry)
352
- // emit the operator marker so a thrashing session is visible in logs —
353
- // logs-only, no token material, NOT a payload field (the agent never sees it).
354
- if (recovered.refreshed)
355
- api.logger.info("sil_search_refreshed", {});
356
- // Buffer the page for a paired client to pull by this exact `callId`
357
- // (`sil.search_results`). A PURE SIDE EFFECT: the envelope returned
358
- // below is byte-identical to what every channel got before this
359
- // existed — no reference, no flag, no listener check. Only `ok` is
360
- // stored; the other outcomes steer the agent's recovery and carry no
361
- // product data to deliver. `advisories` stay OFF the stored page —
362
- // they are operator/agent copy, not products.
363
- if (recovered.outcome.kind === "ok") {
364
- const { kind: _kind, ...page } = recovered.outcome;
365
- const principal = readConfig()?.user?.id;
366
- if (principal !== undefined) {
367
- putSearchResult(callId, { status: "ok", ...page }, principal);
368
- }
369
- }
370
- return mapSearchOutcome(api, recovered.outcome);
371
- case "must_reregister":
372
- // A dead refresh token (invalid_grant) is cleared so the agent's
373
- // sil_register recovery is not blocked by stale presence; a TOCTOU
374
- // empty re-read (no_stored_tokens) has nothing to clear.
375
- if (recovered.reason === "invalid_grant")
376
- clearTokens();
377
- api.logger.info("sil_search_must_reregister", { cause: recovered.reason });
378
- return mustReregister("sil_search");
379
- case "second_unauthorized":
380
- // A freshly-rotated token STILL rejected is structurally dead — clear it.
381
- clearTokens();
382
- api.logger.info("sil_search_must_reregister", { cause: "retry_unauthorized" });
383
- return mustReregister("sil_search");
384
- case "retryable":
385
- api.logger.info("sil_search_refresh_retryable", {});
386
- return transient("sil_search");
292
+ const called = await callRoute(api, tool, params);
293
+ if (called.kind === "refused") {
294
+ if (tool.name === SEARCH_TOOL)
295
+ skipped(api, callId, `refused:${called.status}`);
296
+ return called.result;
387
297
  }
298
+ if (tool.name === SEARCH_TOOL)
299
+ bufferPage(api, callId, called.body);
300
+ // VERBATIM, and the advisory rides its own block: the body's keys are the API's
301
+ // contract, so nothing of ours may sit beside them.
302
+ return jsonResult(called.body, ...wiringAdvisoryBlocks(api));
388
303
  },
389
- });
390
- }
391
- /** Map a search outcome that has ALREADY cleared the 401-recovery path (so it is
392
- * never `unauthorized` — that is the refresh trigger, handled by the caller via
393
- * {@link refreshAndRetryOnce}) to the agent-facing envelope. The `unauthorized`
394
- * arm is structurally unreachable but kept exhaustive so a future refactor can't
395
- * silently drop a variant — it falls to the same terminal re-register. */
396
- function mapSearchOutcome(api, outcome) {
397
- switch (outcome.kind) {
398
- case "ok":
399
- return searchResult(api, outcome);
400
- case "forbidden":
401
- // A 403 surfaces the SAME forbidden envelope `sil_whoami` emits — never the
402
- // false-transient `retryable`. On `user_not_provisioned` (and ONLY that exact
403
- // reason) the held token maps to no account on this backend and a refresh
404
- // cannot help — structurally dead, like the invalid_grant/second_unauthorized
405
- // clears below — so clear it HERE (the tool call site, never the pure
406
- // classifier) and the next sil_register re-onboards instead of short-circuiting
407
- // to already_registered. A `principal_mismatch` / unknown reason can be
408
- // transient and stays recoverable — it MUST NOT clear (the exact-equality gate
409
- // is the correctness boundary: a startsWith/truthy check would wrongly wipe a
410
- // good session).
411
- api.logger.warn("sil_search_forbidden", { reason: outcome.reason });
412
- if (outcome.reason === "user_not_provisioned")
413
- clearTokens();
414
- return forbidden(outcome.reason);
415
- case "invalid_request":
416
- api.logger.info("sil_search_invalid_request", { error: outcome.error });
417
- return invalidRequest(outcome.error, outcome.message);
418
- case "retryable":
419
- // A source-attributed 5xx names the failed source (outcome b); a sil/network
420
- // blip carries no source and stays the generic copy (outcome a). The log marker
421
- // records the source when present so a flaky source is visible to operators.
422
- api.logger.info("sil_search_retryable", outcome.source ? { source: outcome.source } : {});
423
- return transient("sil_search", outcome.source, outcome.detail);
424
- case "unauthorized":
425
- return mustReregister("sil_search");
426
- }
304
+ };
427
305
  }
428
306
  /**
429
- * `sil_product_get` — the lookup COMPANION to `sil_search`. The agent passes ids
430
- * it already holds (from a prior `sil_search`, a saved list, deep links, or cart
431
- * validation) and gets back the matching products in UCP shape, each with its
432
- * FRESH featured variant `{ id, title, price, availability, checkout_url, ... }`.
433
- * RICH where search is LEAN: lookup adds the description, the variant's options,
434
- * and — its defining feature — the per-variant `inputs` correlation, because the
435
- * response does NOT preserve request order and one id can resolve to a variant of
436
- * another id's product. The agent builds no envelope and fills no defaults; the
437
- * tool sends just `{ ids }`, sil-api owns enrichment + the `not_found` messaging.
438
- *
439
- * `execute()` flow (ALL I/O here; `register()` opens nothing — a synchronous
440
- * request/response, NOT a poll). MIRRORS `sil_search` and shares its taxonomy:
441
- * 1. Not registered (no stored tokens) → terminal `not_registered` + a
442
- * `recovery: sil_register` hint, ZERO network calls. Mirrors `sil_whoami`.
443
- * 2. Client-side guard: an empty `ids` (after dropping non-strings) is rejected
444
- * with a structured validation error and NO network call (sil-api's
445
- * `minItems:1` schema 400 is the authoritative backstop).
446
- * 3. lookupCatalog(getApiUrl(), token, ids) → map the `LookupOutcome`:
447
- * ok → the resolved products + the `not_found` id list (a PARTIAL
448
- * or ALL-MISSED hit is `status:"ok"` — a SUCCESS, never an
449
- * error, with NO recovery hint: re-running won't conjure a
450
- * delisted product);
451
- * invalid_request (400) → surface sil-api's `{ error, message }`;
452
- * unauthorized (401) → refresh-and-retry ONCE via the shared
453
- * `refreshAndRetryOnce` choreography (parity with
454
- * `sil_search` and `sil_whoami` — 401 recovery is
455
- * uniform). Recovered 401 is invisible; second 401 /
456
- * dead refresh is terminal re-register (tokens
457
- * cleared); a refresh 5xx/network blip is transient;
458
- * retryable (5xx/net) → transient "try again", NO re-register hint.
459
- *
460
- * The unfound-ids outcome is the headline: a lookup that resolves SOME (or NONE)
461
- * of its ids is a success the agent relays ("3 of your 4 items are still
462
- * available; 1 is no longer listed"), distinguished from the two true-error
463
- * classes (not-registered/401 and source/transport failure) by DISTINCT recovery
464
- * hints. One wrong hint = one misdirected user.
465
- *
466
- * Privacy + freshness: the session token and Bearer header never reach a log line
467
- * or the result; the products are always live-fetched (never cached — freshness is
468
- * the reason this tool exists; a cached `checkout_url`/price is a broken purchase).
307
+ * Buffer an `ok` search page for a paired client to pull by this exact `callId`
308
+ * (`sil.search_results`). A PURE SIDE EFFECT: the result returned to the agent is
309
+ * byte-identical to what every channel got before this existed. Only a body that
310
+ * actually carries its `products` list is stored — the pull surface counts it.
469
311
  */
470
- function registerProductGet(api) {
471
- api.registerTool({
472
- name: "sil_product_get",
473
- label: "Look up sil products by id",
474
- description: "Look up sil products or variants by id — the companion to sil_search."
475
- + " Pass `ids` (one or more product/variant ids you already hold, e.g. from"
476
- + " a prior sil_search result) and get the matching products back with FRESH"
477
- + " detail: each product's description plus its featured purchasable variant"
478
- + " (id, title, price, availability, checkout_url, options), and — where the"
479
- + " source provides them — the same evaluate-before-buy fields sil_search"
480
- + " surfaces: product and variant `url`, `media`, the product `options` menu,"
481
- + " the `seller` (with policy/info links), and `metadata`. The SAME three"
482
- + " distinct actions apply: (1) VIEW — a product's or variant's `url` opens"
483
- + " the PAGE to view / learn more (NOT a purchase); (2) DIG IN —"
484
- + " `seller.links` follow the seller's policy / info links (refund, shipping,"
485
- + " terms); (3) BUY — `checkout_url` is the variant permalink that commits the"
486
- + " purchase. A variant's `url` and its `checkout_url` are DIFFERENT targets:"
487
- + " `url` is the page (view) whereas `checkout_url` buys — do not conflate"
488
- + " them. Re-fetch right"
489
- + " before the user buys — prices, availability, and checkout_url are"
490
- + " point-in-time, not guarantees. Each variant carries an `inputs` list"
491
- + " correlating it back to the id(s) you asked about (the response is NOT in"
492
- + " request order). Ids that no longer resolve come back in a `not_found`"
493
- + " list — that is a normal outcome, not an error (the other products are"
494
- + " still valid). Requires registration (run sil_register first).",
495
- parameters: Type.Object({
496
- ids: Type.Array(Type.String(), {
497
- minItems: 1,
498
- description: "Product or variant ids to resolve (at least one). Typically ids from a"
499
- + " prior sil_search result, a saved list, or a deep link.",
500
- }),
501
- }),
502
- async execute(_callId, params) {
503
- // 1 — not registered: terminal, zero network calls.
504
- const stored = readTokens();
505
- if (stored === null) {
506
- return notRegistered("sil_product_get");
507
- }
508
- // Narrow the untrusted params (the SDK types `params` as
509
- // Record<string, unknown>; the host validates against the schema, but the
510
- // read site still guards — non-string entries are dropped, not coerced).
511
- const ids = readIds(params);
512
- // 2 — client-side input guard: reject an empty `ids` before any network
513
- // call (sil-api's `minItems:1` schema 400 is the authoritative backstop).
514
- if (ids.length === 0) {
515
- return invalidIds();
516
- }
517
- // 3 — look up; on a 401 refresh-and-retry ONCE via the shared choreography
518
- // (the SAME path sil_whoami / sil_search use). A partial/all-missed hit is
519
- // `ok` + `not_found`.
520
- const first = await lookupCatalog(getApiUrl(), stored.access_token, ids);
521
- const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => lookupCatalog(getApiUrl(), accessToken, ids));
522
- switch (recovered.kind) {
523
- case "result":
524
- // On a silent recovery (`refreshed`: a 401 was healed by the refresh+retry)
525
- // emit the operator marker so a thrashing session is visible in logs —
526
- // logs-only, no token material, NOT a payload field (the agent never sees it).
527
- if (recovered.refreshed)
528
- api.logger.info("sil_product_get_refreshed", {});
529
- return mapLookupOutcome(api, recovered.outcome);
530
- case "must_reregister":
531
- if (recovered.reason === "invalid_grant")
532
- clearTokens();
533
- api.logger.info("sil_product_get_must_reregister", { cause: recovered.reason });
534
- return mustReregister("sil_product_get");
535
- case "second_unauthorized":
536
- clearTokens();
537
- api.logger.info("sil_product_get_must_reregister", { cause: "retry_unauthorized" });
538
- return mustReregister("sil_product_get");
539
- case "retryable":
540
- api.logger.info("sil_product_get_refresh_retryable", {});
541
- return transient("sil_product_get");
542
- }
543
- },
544
- });
545
- }
546
- /** Map a lookup outcome that has ALREADY cleared the 401-recovery path (never
547
- * `unauthorized` — the refresh trigger handled by {@link refreshAndRetryOnce}) to
548
- * the agent-facing envelope. The `unauthorized` arm is structurally unreachable
549
- * but kept exhaustive (falls to the same terminal re-register) so a future
550
- * refactor can't silently drop a variant. */
551
- function mapLookupOutcome(api, outcome) {
552
- switch (outcome.kind) {
553
- case "ok":
554
- return lookupResult(api, outcome);
555
- case "forbidden":
556
- // Symmetric with sil_search (one vocabulary, AC2/AC7/AC10): a 403 is the shared
557
- // forbidden envelope, and `user_not_provisioned` — and ONLY that exact reason —
558
- // clears the structurally-dead token at this call site so recovery terminates
559
- // regardless of which catalog tool revealed the state. `principal_mismatch` /
560
- // unknown reasons survive (recoverable; the same exact-equality gate).
561
- api.logger.warn("sil_product_get_forbidden", { reason: outcome.reason });
562
- if (outcome.reason === "user_not_provisioned")
563
- clearTokens();
564
- return forbidden(outcome.reason);
565
- case "invalid_request":
566
- api.logger.info("sil_product_get_invalid_request", { error: outcome.error });
567
- return invalidRequest(outcome.error, outcome.message);
568
- case "retryable":
569
- // Symmetric with sil_search: a source-attributed 5xx names the source (outcome
570
- // b); a sil/network blip is the generic copy (outcome a). One error vocabulary.
571
- api.logger.info("sil_product_get_retryable", outcome.source ? { source: outcome.source } : {});
572
- return transient("sil_product_get", outcome.source, outcome.detail);
573
- case "unauthorized":
574
- return mustReregister("sil_product_get");
575
- }
576
- }
577
- /**
578
- * `sil_specs` — the spec-REGISTRY canonicalize-or-create tool. Driven by the
579
- * sil-shopping method at Beat 2 (mint/refresh), NOT directly by the buyer: the
580
- * method coins its niche `ns.key` vocabulary bottom-up from research, submits the
581
- * coined DEFINITIONS here, and gets back the canonical name per spec to adopt BEFORE
582
- * it persists — so the method is born speaking canonical names and the whole
583
- * catalog's `filters.specs` vocabulary converges (that convergence is what makes
584
- * `filters.specs` actually filter). A `matched` spec adopts the existing canonical
585
- * name (drop the private synonym); a `created` spec keeps its own (it is canonical
586
- * going forward).
587
- *
588
- * `execute()` flow (ALL I/O here; `register()` opens nothing — a synchronous
589
- * request/response, NOT a poll). MIRRORS `sil_search` and shares its taxonomy, minus
590
- * search's 422 arm and source attribution (the registry is sil's own Postgres):
591
- * 1. Not registered (no stored tokens) → terminal `not_registered` + a
592
- * `recovery: sil_register` hint, ZERO network calls. Mirrors `sil_whoami`.
593
- * 2. Client-side guard: a blank/absent `query` OR an empty/all-dropped `specs`
594
- * array → `invalid_request` (`empty_specs_input`), NO network call (sil-api's
595
- * `minLength`/`minItems` schema 400 is the authoritative backstop). A single
596
- * MALFORMED definition rejects the WHOLE request (`invalid_spec`) — a silently
597
- * dropped coined spec would never canonicalize and never converge.
598
- * 3. specsCatalog(getApiUrl(), token, params) → map the `SpecsOutcome`:
599
- * ok → the `resolved` array (one resolution per submitted spec);
600
- * invalid_request (400) → surface sil-api's `{ error, message }`;
601
- * unauthorized (401) → refresh-and-retry ONCE via the shared
602
- * `refreshAndRetryOnce` choreography (parity with
603
- * `sil_search`/`sil_product_get`/`sil_whoami` — 401
604
- * recovery is uniform). Recovered 401 is invisible;
605
- * second 401 / dead refresh is terminal re-register
606
- * (tokens cleared);
607
- * retryable (5xx/net) → transient "try again", NO re-register hint (BARE —
608
- * no source; the method degrades to raw coined names).
609
- *
610
- * GRACEFUL DEGRADATION is the load-bearing product invariant (AC14): a non-`ok`
611
- * outcome never blocks the mint — the method proceeds with the RAW coined names
612
- * (every predicate `applied:false`) and converges on the next mint/refresh. The tool
613
- * only surfaces the registry's verdict; the method decides to degrade.
614
- *
615
- * Privacy: the session token and Bearer header never reach a log line or the result.
616
- */
617
- function registerSpecs(api) {
618
- api.registerTool({
619
- name: "sil_specs",
620
- label: "Canonicalize coined spec definitions",
621
- description: "Canonicalize the coined spec DEFINITIONS a method invents for a niche — the"
622
- + " dedupe-or-create registry call at method mint/refresh. Pass the motivating"
623
- + " `query` and `specs` (coined { namespace, key, display_name, data_type,"
624
- + " description?, unit?, allowed_values? }). Each resolves 1:1: `matched` → adopt"
625
- + " the returned canonical { namespace, key } and drop your synonym; `created` →"
626
- + " yours is novel, keep it. Rewrite the method's search vocabulary + any PRD"
627
- + " predicates to the canonical names before persisting. Internal plumbing — never"
628
- + " surface ns.key to the buyer. If not `ok`, do NOT block the mint: persist raw and"
629
- + " converge on the next mint/refresh. Requires registration.",
630
- parameters: Type.Object({
631
- query: Type.String({
632
- description: "The motivating shopping query — what the shopper is buying. Governance /"
633
- + " dedupe context for the registry; required and non-empty.",
634
- }),
635
- specs: Type.Array(SPEC_DEFINITION_SCHEMA, {
636
- minItems: 1,
637
- description: "The coined spec definitions to canonicalize (at least one). Each is a"
638
- + " { namespace, key, display_name, data_type, description?, unit?,"
639
- + " allowed_values? } the method coined bottom-up from research.",
640
- }),
641
- }),
642
- async execute(_callId, params) {
643
- // 1 — not registered: terminal, zero network calls.
644
- const stored = readTokens();
645
- if (stored === null) {
646
- return notRegistered("sil_specs");
647
- }
648
- // 2 — client-side guard (defensive drifted-call backstop; the host validates
649
- // the schema, but a blank query / empty specs / malformed definition is
650
- // rejected BEFORE any network call). An empty input is `empty_specs_input`; a
651
- // present-but-malformed definition rejects the WHOLE request (`invalid_spec`) —
652
- // a silently dropped coined spec never canonicalizes → never converges.
653
- const read = readSpecsParams(params);
654
- if (read.kind === "invalid") {
655
- if (read.code === "invalid_spec") {
656
- api.logger.info("sil_specs_invalid_spec", { field: read.field });
657
- return invalidSpecDefinition(read.field);
658
- }
659
- api.logger.info("sil_specs_invalid_request", { error: "empty_specs_input" });
660
- return invalidSpecsInput();
661
- }
662
- const specsParams = read.params;
663
- // 3 — canonicalize; on a 401 refresh-and-retry ONCE via the shared
664
- // choreography (the SAME path sil_whoami / sil_search / sil_product_get use).
665
- const first = await specsCatalog(getApiUrl(), stored.access_token, specsParams);
666
- const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => specsCatalog(getApiUrl(), accessToken, specsParams));
667
- switch (recovered.kind) {
668
- case "result":
669
- if (recovered.refreshed)
670
- api.logger.info("sil_specs_refreshed", {});
671
- return mapSpecsOutcome(api, recovered.outcome);
672
- case "must_reregister":
673
- if (recovered.reason === "invalid_grant")
674
- clearTokens();
675
- api.logger.info("sil_specs_must_reregister", { cause: recovered.reason });
676
- return mustReregister("sil_specs");
677
- case "second_unauthorized":
678
- clearTokens();
679
- api.logger.info("sil_specs_must_reregister", { cause: "retry_unauthorized" });
680
- return mustReregister("sil_specs");
681
- case "retryable":
682
- api.logger.info("sil_specs_refresh_retryable", {});
683
- return transient("sil_specs");
684
- }
685
- },
686
- });
687
- }
688
- /** Map a specs outcome that has ALREADY cleared the 401-recovery path (never
689
- * `unauthorized` — the refresh trigger handled by {@link refreshAndRetryOnce}) to
690
- * the agent-facing envelope. Mirrors `mapSearchOutcome`, minus the source-attributed
691
- * `retryable` (specs has no external source): a 5xx/network blip is the GENERIC
692
- * transient. The `unauthorized` arm is structurally unreachable but kept exhaustive
693
- * (falls to the same terminal re-register) so a future refactor can't drop a variant. */
694
- function mapSpecsOutcome(api, outcome) {
695
- switch (outcome.kind) {
696
- case "ok":
697
- return specsResult(api, outcome);
698
- case "forbidden":
699
- // Symmetric with sil_search/sil_product_get (one vocabulary): a 403 is the
700
- // shared forbidden envelope, and `user_not_provisioned` — and ONLY that exact
701
- // reason — clears the structurally-dead token at this call site.
702
- api.logger.warn("sil_specs_forbidden", { reason: outcome.reason });
703
- if (outcome.reason === "user_not_provisioned")
704
- clearTokens();
705
- return forbidden(outcome.reason);
706
- case "invalid_request":
707
- api.logger.info("sil_specs_invalid_request", { error: outcome.error });
708
- return invalidRequest(outcome.error, outcome.message);
709
- case "retryable":
710
- // BARE transient — the registry is sil's own Postgres, so there is no external
711
- // source to name (unlike sil_search's outcome-b). Generic "try again" copy.
712
- api.logger.info("sil_specs_retryable", {});
713
- return transient("sil_specs");
714
- case "unauthorized":
715
- return mustReregister("sil_specs");
716
- }
717
- }
718
- /** Narrow the untrusted `params` to a string[] of ids. A non-string entry is
719
- * DROPPED (treated as absent), not coerced — the host has already validated
720
- * against the schema, but a drifted on-disk call must not slip a non-string into
721
- * the id list. No `any`, no unchecked `as`. */
722
- function readIds(params) {
723
- const raw = params["ids"];
724
- if (!Array.isArray(raw))
725
- return [];
726
- return raw.filter((id) => typeof id === "string");
727
- }
728
- /** Success: the resolved products + optional `not_found` id list — no token, no
729
- * Bearer header. An empty `products` list WITH a `not_found` list is a valid,
730
- * successful all-missed lookup. The `ok` outcome already carries `products` (+
731
- * optional `not_found`); spread its payload (minus the `kind` discriminant) onto
732
- * the agent-facing `{ status: "ok", ... }` envelope. A `not_found` list is
733
- * partial-success DATA, NOT an error and NOT a recovery hint. */
734
- function lookupResult(api, outcome) {
735
- const { kind: _kind, ...payload } = outcome;
736
- return jsonResult({ status: "ok", ...payload, ...wiringAdvisories(api) });
737
- }
738
- /** Client-side validation: the request named no usable id. Distinct from a sil-api
739
- * 400 (which carries the server's structured error) — this never hit the network.
740
- * No `recovery: sil_register` (auth is fine; the input is the problem). */
741
- function invalidIds() {
742
- return jsonResult({
743
- status: "invalid_request",
744
- error: "empty_ids",
745
- message: "Provide at least one product or variant id to look up.",
746
- });
747
- }
748
- /** Narrow the untrusted `params` to the simplified {@link SearchParams}, or report
749
- * the first bad-FORMAT filter field. A field of the wrong type is dropped (treated
750
- * as absent), not coerced — the host has already validated against the schema, but
751
- * a drifted on-disk call must not slip a non-string into the query mapping. No
752
- * `any`, no unchecked `as`.
753
- *
754
- * The serviceability/localization filters narrow by their own type: `ship_to` to an
755
- * object with a string `country` (a primitive/number is DROPPED), `condition` to a
756
- * string[] (a bare string is dropped), `available` and `local_merchants` to a boolean
757
- * (a string is dropped). The drop is TYPE-driven, never value-driven, so a valid
758
- * `available: false` survives — it is a boolean, the meaningful "include unavailable
759
- * items" signal, not a falsy value to discard.
760
- *
761
- * Beyond TYPE narrowing, `ship_to` also FORMAT-validates every provided string field
762
- * (country alpha-2, region 3166-2, postal bounded) against the shared patterns: a
763
- * present-but-malformed value returns an `invalid` read so the tool rejects the
764
- * request client-side with a clear `invalid_filter` error (better agent UX than an
765
- * opaque, fail-late sil-api 400). `condition` is NOT format-validated — its wire
766
- * stays OPEN (an unrecognized value still forwards; steering to new/secondhand lives
767
- * in the description only). `local_merchants` is a plain boolean bias (no format, no
768
- * country) — its whole steer lives in the description. The first bad field wins. */
769
- function readSearchParams(params) {
770
- const result = {};
771
- const query = params["query"];
772
- if (typeof query === "string")
773
- result.query = query;
774
- const category = params["category"];
775
- if (typeof category === "string")
776
- result.category = category;
777
- const priceMin = params["price_min"];
778
- if (typeof priceMin === "number")
779
- result.price_min = priceMin;
780
- const priceMax = params["price_max"];
781
- if (typeof priceMax === "number")
782
- result.price_max = priceMax;
783
- const cursor = params["cursor"];
784
- if (typeof cursor === "string")
785
- result.cursor = cursor;
786
- const limit = params["limit"];
787
- if (typeof limit === "number")
788
- result.limit = limit;
789
- const shipTo = readShipTo(params["ship_to"]);
790
- if (shipTo.kind === "invalid") {
791
- return { kind: "invalid", field: shipTo.field, code: "invalid_filter" };
312
+ function bufferPage(api, callId, body) {
313
+ const principal = readConfig()?.user?.id;
314
+ if (principal === undefined) {
315
+ skipped(api, callId, "no_principal");
316
+ return;
792
317
  }
793
- if (shipTo.kind === "ok")
794
- result.ship_to = shipTo.value;
795
- const condition = readCondition(params["condition"]);
796
- if (condition !== null)
797
- result.condition = condition;
798
- const available = params["available"];
799
- if (typeof available === "boolean")
800
- result.available = available;
801
- // `local_merchants` is a plain boolean bias narrowed exactly like `available`:
802
- // a wrong type is DROPPED (treated as absent), never coerced. A valid `false`
803
- // survives the read site (type-driven, not value-driven); the omit-when-falsy
804
- // discipline for the BIAS itself lives at the wire (`buildSearchBody`), since
805
- // unlike `available:false`, a false bias carries no ranking signal.
806
- const localMerchants = params["local_merchants"];
807
- if (typeof localMerchants === "boolean")
808
- result.local_merchants = localMerchants;
809
- // `specs` is a THIRD input class (a real constraint, not a refinement): a
810
- // malformed predicate rejects the whole request client-side (`invalid_spec`,
811
- // zero network — the `invalid_filter` twin); a non-array is DROPPED (the
812
- // `readIds` discipline); a benign empty `[]` reads `ok` and no-ops downstream.
813
- const specs = readSpecs(params["specs"]);
814
- if (specs.kind === "invalid") {
815
- return { kind: "invalid", field: specs.field, code: "invalid_spec" };
318
+ if (!Array.isArray(body["products"])) {
319
+ skipped(api, callId, "no_products");
320
+ return;
816
321
  }
817
- if (specs.kind === "ok")
818
- result.specs = specs.value;
819
- return { kind: "ok", params: result };
322
+ putSearchResult(callId, body, principal);
820
323
  }
821
- /** A non-null plain object, or null for anything else (arrays/primitives). */
822
- function asRecord(value) {
823
- return value !== null && typeof value === "object" && !Array.isArray(value)
824
- ? value
825
- : null;
826
- }
827
- /** Narrow a `ship_to` arg to {@link ShipTo}. A non-object (a primitive `"US"`, a
828
- * number) or a missing/non-string `country` is `absent` (DROPPED — the wrong-TYPE
829
- * discipline). A provided string that fails its FORMAT pattern (`country`,
830
- * `region`, or `postal_code`) is `invalid` (REJECT the request). `country` is
831
- * uppercased on the WIRE (`buildSearchBody`), not here — the read site validates
832
- * FORMAT, the wire normalizes case; region/postal are carried verbatim. */
833
- function readShipTo(raw) {
834
- const obj = asRecord(raw);
835
- if (obj === null)
836
- return { kind: "absent" };
837
- const country = obj["country"];
838
- if (typeof country !== "string" || country.length === 0)
839
- return { kind: "absent" };
840
- if (!matchesPattern(country, COUNTRY_PATTERN)) {
841
- return { kind: "invalid", field: "ship_to.country" };
842
- }
843
- const result = { country };
844
- const region = obj["region"];
845
- if (typeof region === "string") {
846
- if (!matchesPattern(region, REGION_PATTERN)) {
847
- return { kind: "invalid", field: "ship_to.region" };
848
- }
849
- result.region = region;
850
- }
851
- const postalCode = obj["postal_code"];
852
- if (typeof postalCode === "string") {
853
- if (!matchesPattern(postalCode, POSTAL_PATTERN)) {
854
- return { kind: "invalid", field: "ship_to.postal_code" };
855
- }
856
- result.postal_code = postalCode;
857
- }
858
- return { kind: "ok", value: result };
859
- }
860
- /** Test a value against one of the shared schema patterns, anchored exactly as the
861
- * schema's `pattern` is (the constants carry their own `^…$`). A fresh `RegExp` per
862
- * call keeps the patterns as plain shared strings (the schema needs the string form;
863
- * the read site needs to execute it) with no stateful `lastIndex` to reset. */
864
- function matchesPattern(value, pattern) {
865
- return new RegExp(pattern).test(value);
866
- }
867
- /** Narrow a `condition` arg to string[], or null if unusable. Requires an array (a
868
- * bare string is DROPPED, not wrapped); non-string entries are dropped. Returns
869
- * null for an empty/all-dropped array so the key is omitted rather than emitted
870
- * empty. The wire stays OPEN — values are NOT format-validated against a known set
871
- * (an unrecognized value like "refurbished" still forwards; steering to
872
- * new/secondhand is the description's job, not validation's). */
873
- function readCondition(raw) {
874
- if (!Array.isArray(raw))
875
- return null;
876
- const values = raw.filter((c) => typeof c === "string");
877
- return values.length === 0 ? null : values;
878
- }
879
- /** The seven spec ops, the ONLY closed part of the predicate contract (the `ns`/
880
- * `key` vocabulary is deliberately open — [[sds-specs-vocabulary-is-bottom-up]]). */
881
- const SPEC_OPS = ["eq", "neq", "gte", "lte", "in", "nin", "exists"];
882
- function isSpecOp(op) {
883
- return SPEC_OPS.includes(op);
884
- }
885
- /** The op→value validity rule, enforced at the READ SITE (the flat-schema +
886
- * read-site idiom — the schema keeps `value` optional so `exists` fits; the
887
- * per-op requirement lives here, not in TypeBox):
888
- * - `exists` carries NO value;
889
- * - `in`/`nin` need a NON-EMPTY array of string|number;
890
- * - `gte`/`lte` need a number;
891
- * - `eq`/`neq` need a scalar (string|number|boolean).
892
- * Exhaustive over {@link SpecOp} — a new op forces a case here. */
893
- function specValueMatchesOp(op, value) {
894
- switch (op) {
895
- case "exists":
896
- return value === undefined;
897
- case "in":
898
- case "nin":
899
- return (Array.isArray(value)
900
- && value.length > 0
901
- && value.every((v) => typeof v === "string" || typeof v === "number"));
902
- case "gte":
903
- case "lte":
904
- return typeof value === "number";
905
- case "eq":
906
- case "neq":
907
- return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
908
- }
909
- }
910
- /** Narrow the untrusted `specs` arg to {@link SpecPredicate}[], or report the FIRST
911
- * malformed predicate. A non-array is DROPPED (treated absent — the `readIds`
912
- * discipline; a drifted on-disk call must not slip a non-array through). Each entry
913
- * must be an object with a non-blank `ns` and `key`, an `op` in the seven, and a
914
- * `value` matching the op ({@link specValueMatchesOp}) — else the WHOLE request is
915
- * rejected client-side (`invalid_spec`, zero network — the `invalid_filter` twin),
916
- * because a malformed hard predicate silently dropped would be a fail-worse honesty
917
- * hole. `unit`/`hard` are carried when the right type, dropped otherwise. No `any`,
918
- * no unchecked `as` (the one cast is gated by {@link specValueMatchesOp}). */
919
- function readSpecs(raw) {
920
- if (!Array.isArray(raw))
921
- return { kind: "absent" };
922
- const specs = [];
923
- for (let index = 0; index < raw.length; index++) {
924
- const read = readSpec(raw[index], index);
925
- if (read.kind === "invalid")
926
- return read;
927
- specs.push(read.value);
928
- }
929
- return { kind: "ok", value: specs };
930
- }
931
- /** Narrow ONE untrusted predicate to {@link SpecPredicate}, or report the offending
932
- * field (`specs[i]`, `specs[i].ns`, `specs[i].op`, `specs[i].value`, …) for a clear
933
- * client-side reject. */
934
- function readSpec(raw, index) {
935
- const at = (suffix) => `specs[${index}]${suffix}`;
936
- const obj = asRecord(raw);
937
- if (obj === null)
938
- return { kind: "invalid", field: at("") };
939
- const ns = obj["ns"];
940
- if (typeof ns !== "string" || ns.trim().length === 0)
941
- return { kind: "invalid", field: at(".ns") };
942
- const key = obj["key"];
943
- if (typeof key !== "string" || key.trim().length === 0)
944
- return { kind: "invalid", field: at(".key") };
945
- const op = obj["op"];
946
- if (typeof op !== "string" || !isSpecOp(op))
947
- return { kind: "invalid", field: at(".op") };
948
- const value = obj["value"];
949
- if (!specValueMatchesOp(op, value))
950
- return { kind: "invalid", field: at(".value") };
951
- const spec = { ns, key, op };
952
- // `exists` carries no value (validated above); the others carry the op-checked value.
953
- if (op !== "exists")
954
- spec.value = value;
955
- const unit = obj["unit"];
956
- if (typeof unit === "string")
957
- spec.unit = unit;
958
- const hard = obj["hard"];
959
- if (typeof hard === "boolean")
960
- spec.hard = hard;
961
- return { kind: "ok", value: spec };
962
- }
963
- /** The `sil_specs` read-site closed value-types (the defensive backstop for the
964
- * host-validated `data_type`; `namespace`/`key` stay open — the coined vocabulary). */
965
- const SPEC_DATA_TYPES = ["number", "text", "boolean", "enum"];
966
- function isSpecDataType(value) {
967
- return typeof value === "string" && SPEC_DATA_TYPES.includes(value);
968
- }
969
- /** Narrow the untrusted `sil_specs` params to the typed {@link SpecsParams}, or
970
- * report the reject. A blank `query` or an empty/non-array/all-dropped `specs` is
971
- * `empty_specs_input` (no network); the FIRST malformed definition rejects the WHOLE
972
- * request `invalid_spec` (a silently-dropped coined spec never canonicalizes → never
973
- * converges — the same honesty rule as search's `readSpecs`). No `any`, no unchecked
974
- * `as`. The host has already validated the schema; this is a drifted-call backstop. */
975
- function readSpecsParams(params) {
976
- const query = params["query"];
977
- if (typeof query !== "string" || query.trim().length === 0) {
978
- return { kind: "invalid", code: "empty_specs_input" };
979
- }
980
- const rawSpecs = params["specs"];
981
- if (!Array.isArray(rawSpecs) || rawSpecs.length === 0) {
982
- return { kind: "invalid", code: "empty_specs_input" };
983
- }
984
- const specs = [];
985
- for (let index = 0; index < rawSpecs.length; index++) {
986
- const read = readSpecDefinition(rawSpecs[index], index);
987
- if (read.kind === "invalid") {
988
- return { kind: "invalid", code: "invalid_spec", field: read.field };
989
- }
990
- specs.push(read.value);
991
- }
992
- return { kind: "ok", params: { query, specs } };
993
- }
994
- /** Narrow ONE untrusted definition to {@link SpecDefinition}, or report the
995
- * offending field (`specs[i]`, `specs[i].namespace`, `specs[i].data_type`, …).
996
- * Requires a non-blank `namespace`/`key`/`display_name` and a `data_type` in the
997
- * closed set; optional `description`/`unit`/`allowed_values` are carried when the
998
- * right type, dropped otherwise. */
999
- function readSpecDefinition(raw, index) {
1000
- const at = (suffix) => `specs[${index}]${suffix}`;
1001
- const obj = asRecord(raw);
1002
- if (obj === null)
1003
- return { kind: "invalid", field: at("") };
1004
- const namespace = obj["namespace"];
1005
- if (typeof namespace !== "string" || namespace.trim().length === 0) {
1006
- return { kind: "invalid", field: at(".namespace") };
1007
- }
1008
- const key = obj["key"];
1009
- if (typeof key !== "string" || key.trim().length === 0) {
1010
- return { kind: "invalid", field: at(".key") };
1011
- }
1012
- const displayName = obj["display_name"];
1013
- if (typeof displayName !== "string" || displayName.trim().length === 0) {
1014
- return { kind: "invalid", field: at(".display_name") };
1015
- }
1016
- const dataType = obj["data_type"];
1017
- if (!isSpecDataType(dataType))
1018
- return { kind: "invalid", field: at(".data_type") };
1019
- const value = { namespace, key, display_name: displayName, data_type: dataType };
1020
- const description = obj["description"];
1021
- if (typeof description === "string")
1022
- value.description = description;
1023
- const unit = obj["unit"];
1024
- if (typeof unit === "string")
1025
- value.unit = unit;
1026
- const allowedValues = obj["allowed_values"];
1027
- if (Array.isArray(allowedValues)) {
1028
- const values = allowedValues.filter((v) => typeof v === "string");
1029
- if (values.length > 0)
1030
- value.allowed_values = values;
1031
- }
1032
- return { kind: "ok", value };
1033
- }
1034
- /** The one client-side invariant the tool owns: at least one recognized input.
1035
- * A non-whitespace `query`, any filter (`category` / `price_min` / `price_max`),
1036
- * OR a non-empty well-formed `specs` list suffices — a spec is a real constraint
1037
- * (it renders + filters), not a refinement. A bare `{}`, a whitespace-only `query`
1038
- * with no filter, or a present-but-EMPTY `specs: []` with nothing else is rejected;
1039
- * pagination params alone (`cursor`/`limit`) are NOT inputs — they refine an
1040
- * existing search, they do not constitute one. */
1041
- function hasUsableInput(params) {
1042
- const hasQuery = typeof params.query === "string" && params.query.trim().length > 0;
1043
- const hasFilter = typeof params.category === "string"
1044
- || typeof params.price_min === "number"
1045
- || typeof params.price_max === "number";
1046
- const hasSpecs = Array.isArray(params.specs) && params.specs.length > 0;
1047
- return hasQuery || hasFilter || hasSpecs;
1048
- }
1049
- /** Success: the ranked products + optional cursor — no token, no Bearer header.
1050
- * An empty `products` list is a valid, successful empty match. The `ok` outcome
1051
- * already carries `products` (+ optional `cursor`); spread its payload (minus the
1052
- * `kind` discriminant) onto the agent-facing `{ status: "ok", ... }` envelope. */
1053
- function searchResult(api, outcome) {
1054
- const { kind: _kind, ...payload } = outcome;
1055
- return jsonResult({ status: "ok", ...payload, ...wiringAdvisories(api) });
1056
- }
1057
- /** Not registered: a distinct, actionable outcome naming the recovery tool. No
1058
- * products field so the agent can't mistake it for an empty match. The `tool`
1059
- * name keeps the message actionable per-tool (re-run THIS tool) while the
1060
- * status/recovery taxonomy stays shared across the catalog tools. */
1061
- function notRegistered(tool) {
1062
- return jsonResult({
1063
- status: "not_registered",
1064
- message: `Not registered on sil. Run sil_register to authenticate, then call ${tool} again.`,
1065
- recovery: "sil_register",
1066
- });
1067
- }
1068
- /** Client-side validation: the request named no usable input. Distinct from a
1069
- * sil-api 400 (which carries the server's structured error) — this never hit the
1070
- * network. No `recovery: sil_register` (auth is fine; the query is the problem). */
1071
- function invalidInput() {
1072
- return jsonResult({
1073
- status: "invalid_request",
1074
- error: "empty_search_input",
1075
- message: "Provide a search query or at least one filter (category, price_min, or"
1076
- + " price_max).",
1077
- });
1078
- }
1079
- /** Client-side validation: a location filter carried a malformed value (bad FORMAT,
1080
- * not wrong type) — rejected BEFORE any network call (re-spec). Distinct from the
1081
- * empty-input case (`empty_search_input`) and from a sil-api 400; the pinned machine
1082
- * code is `invalid_filter`. No `recovery: sil_register` — auth is fine; the value
1083
- * FORMAT is the problem. The message names the offending field and the required ISO
1084
- * code form so the agent re-sends a code, not free text. */
1085
- function invalidFilter(field) {
1086
- return jsonResult({
1087
- status: "invalid_request",
1088
- error: "invalid_filter",
1089
- message: `The \`${field}\` filter is malformed. Send standard ISO codes, not`
1090
- + " free-text names: country as a 2-letter ISO 3166-1 alpha-2 code (e.g."
1091
- + " \"US\"), region as an ISO 3166-2 subdivision code (e.g. \"CA\"), and"
1092
- + " postal_code as a destination postal/ZIP code.",
1093
- });
1094
- }
1095
- /** Client-side validation: a `specs` predicate is malformed (blank `ns`/`key`, an
1096
- * `op` outside the seven, or a value shape contradicting the op) — rejected BEFORE
1097
- * any network call, the twin of {@link invalidFilter} for `ship_to`. Distinct
1098
- * machine code `invalid_spec`; `field` names the offending predicate index/field.
1099
- * No `recovery: sil_register` — auth is fine; the predicate is the problem. */
1100
- function invalidSpec(field) {
1101
- return jsonResult({
1102
- status: "invalid_request",
1103
- error: "invalid_spec",
1104
- message: `The \`${field}\` spec predicate is malformed. Each predicate needs a`
1105
- + " non-empty `ns` and `key`, an `op` of eq/neq/gte/lte/in/nin/exists, and a"
1106
- + " `value` matching the op: a number for gte/lte, a non-empty array for"
1107
- + " in/nin, a scalar for eq/neq, and NO value for exists.",
1108
- });
1109
- }
1110
- /** Success: the resolved canonicalizations — no token, no Bearer header. The `ok`
1111
- * outcome carries `resolved` directly; spread its payload (minus the `kind`
1112
- * discriminant) onto the agent-facing `{ status: "ok", resolved }` envelope. */
1113
- function specsResult(api, outcome) {
1114
- const { kind: _kind, ...payload } = outcome;
1115
- return jsonResult({ status: "ok", ...payload, ...wiringAdvisories(api) });
1116
- }
1117
- /** Client-side validation: no usable canonicalization input (a blank `query` or an
1118
- * empty/all-dropped `specs`). Distinct from a sil-api 400 — this never hit the
1119
- * network. No `recovery: sil_register` (auth is fine; the input is the problem). */
1120
- function invalidSpecsInput() {
1121
- return jsonResult({
1122
- status: "invalid_request",
1123
- error: "empty_specs_input",
1124
- message: "Provide a non-empty `query` and at least one coined spec definition to"
1125
- + " canonicalize.",
1126
- });
1127
- }
1128
- /** Client-side validation: a `specs` definition is malformed (blank
1129
- * `namespace`/`key`/`display_name`, or a `data_type` outside
1130
- * number/text/boolean/enum) — the WHOLE request is rejected BEFORE any network call,
1131
- * so no coined spec is silently dropped from canonicalization. Machine code
1132
- * `invalid_spec`; `field` names the offending definition. No `recovery: sil_register`. */
1133
- function invalidSpecDefinition(field) {
1134
- return jsonResult({
1135
- status: "invalid_request",
1136
- error: "invalid_spec",
1137
- message: `The \`${field}\` spec definition is malformed. Each definition needs a`
1138
- + " non-empty `namespace`, `key`, and `display_name`, and a `data_type` of"
1139
- + " number, text, boolean, or enum.",
1140
- });
1141
- }
1142
- /** sil-api rejected the request (a structured 400, e.g. empty_search_input).
1143
- * Surface the server's `{ error, message }` so the agent fixes its query — NOT a
1144
- * re-register (auth is fine) and NOT a transient retry (retrying the same bad
1145
- * request won't help). Distinct from both the empty-match success and the 5xx. */
1146
- function invalidRequest(error, message) {
1147
- return jsonResult({ status: "invalid_request", error, message });
1148
- }
1149
- /** Terminal: the session is dead — reached only after the shared refresh-and-retry
1150
- * choreography ({@link refreshAndRetryOnce}) has exhausted its one refresh + one
1151
- * retry (a second 401, or a dead `invalid_grant` refresh token). Re-register. The
1152
- * `tool` name keeps the message actionable while the taxonomy stays shared. */
1153
- function mustReregister(tool) {
1154
- return jsonResult({
1155
- status: "must_reregister",
1156
- message: `Your sil session has expired. Run sil_register to sign in again, then call ${tool} again.`,
1157
- recovery: "sil_register",
1158
- });
1159
- }
1160
- /** Terminal-but-distinct: a 403 — the token is valid but the user isn't provisioned
1161
- * (or a principal mismatch / other reason). Refreshing would not help (a 403 is not
1162
- * a 401). Surfaces the SAME envelope `sil_whoami`'s `forbidden()` (identity.ts) emits
1163
- * — `{ status:"forbidden", reason, message, recovery:"sil_register" }`, byte-identical
1164
- * including the reason-driven message branch — so the three sil-api tools speak ONE
1165
- * error vocabulary (AC5). `user_not_provisioned` reads as an actionable onboarding
1166
- * prompt; any other reason is the generic forbidden copy carrying the reason. The
1167
- * recovery hint is always `sil_register` (the message names it, tool-agnostic — the
1168
- * parity with `sil_whoami`'s envelope is byte-exact, so it carries no per-tool name).
1169
- * The dead-token CLEAR is NOT here — it is the caller's decision (gated on
1170
- * `user_not_provisioned`), so a `principal_mismatch` that still wants the legible
1171
- * envelope does not have its token wiped. */
1172
- function forbidden(reason) {
1173
- const message = reason === "user_not_provisioned"
1174
- ? "Your sil account is not fully set up. Complete onboarding (run"
1175
- + " sil_register) and try again."
1176
- : "sil rejected this request (" + reason + "). Run sil_register to"
1177
- + " re-establish your session, then try again.";
1178
- return jsonResult({ status: "forbidden", reason, message, recovery: "sil_register" });
1179
- }
1180
- /** Transient: a retryable blip — try again, NOT a re-register (a false terminal on
1181
- * a transient would send the agent down a recovery path that can't fix it). The two
1182
- * causally-distinct transient failures share `status: "retryable"` (both succeed on
1183
- * backoff) but split on ATTRIBUTION, which is the whole point of this card:
1184
- *
1185
- * - `source` ABSENT (outcome a) — sil itself / the network / transport is down,
1186
- * OR a refresh-leg blip. The agent retries the same call; the copy stays the
1187
- * GENERIC "sil is temporarily unavailable" and names no source it cannot
1188
- * identify (attribution honesty).
1189
- * - `source` PRESENT (outcome b) — a specific catalog source is down or
1190
- * rate-limited. The copy NAMES that source and must NEVER say "sil is …
1191
- * unavailable" / "sil is down": sil is healthy, one source is degraded, often
1192
- * for seconds, and mis-attributing it to sil makes the agent abandon a working
1193
- * platform. `detail` (the upstream cause) is relayed when present.
1194
- *
1195
- * The source is named ONLY when the wire actually carried it (the classifier gates
1196
- * on a real `source` field — see `retryableFromBody` in sil-client). The named-source
1197
- * copy is SELF-AUTHORED around the source token rather than echoing the raw upstream
1198
- * `detail` prose verbatim — the upstream wording is sil-api's to change and could
1199
- * itself contain "sil is …" phrasing that would muddy the attribution; `detail` is
1200
- * surfaced as a separate, clearly-delimited field instead. The `tool` name keeps the
1201
- * retry guidance actionable; the status taxonomy is shared. */
1202
- function transient(tool, source, detail) {
1203
- if (source === undefined) {
1204
- return jsonResult({
1205
- status: "retryable",
1206
- message: `sil is temporarily unavailable. Please try ${tool} again.`,
1207
- });
1208
- }
1209
- return jsonResult({
1210
- status: "retryable",
1211
- message: `The catalog source "${source}" is temporarily unavailable.`
1212
- + ` sil itself is fine — retry ${tool} shortly.`,
1213
- ...(detail !== undefined ? { detail } : {}),
1214
- });
324
+ /** Why this `callId` will resolve nothing, logged where the decision is made. The pull
325
+ * says only `not_found` — deliberately — so this line is the whole of an operator's
326
+ * account of a search a client could not render. */
327
+ function skipped(api, callId, reason) {
328
+ logSearchResults(api, "info", "skipped", { callId, reason });
1215
329
  }