sil-openclaw 0.4.6 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +34 -46
  3. package/SECURITY.md +61 -11
  4. package/dist/gateway/search-results.js +11 -7
  5. package/dist/index.js +24 -24
  6. package/dist/lib/allowlist-script.js +13 -0
  7. package/dist/lib/artifacts.js +30 -0
  8. package/dist/lib/credentials.js +2 -3
  9. package/dist/lib/host-wiring.js +44 -15
  10. package/dist/lib/pkce.js +3 -3
  11. package/dist/lib/search-results-log.js +23 -0
  12. package/dist/lib/search-results-store.js +4 -4
  13. package/dist/lib/shopping-call.js +143 -0
  14. package/dist/lib/sil-client.js +185 -1046
  15. package/dist/lib/tool-result.js +10 -3
  16. package/dist/tools/catalog.js +311 -1197
  17. package/dist/tools/doctor.js +25 -63
  18. package/dist/tools/identity.js +110 -245
  19. package/openclaw.plugin.json +12 -33
  20. package/package.json +10 -9
  21. package/schema/PROVENANCE.md +15 -0
  22. package/schema/shopping-brief-create-request.schema.json +98 -0
  23. package/schema/shopping-brief-create-response.schema.json +24 -0
  24. package/schema/shopping-brief-edit-request.schema.json +125 -0
  25. package/schema/shopping-brief-edit-response.schema.json +24 -0
  26. package/schema/shopping-brief-read-request.schema.json +15 -0
  27. package/schema/shopping-brief-read-response.schema.json +235 -0
  28. package/schema/shopping-domain-create-request.schema.json +160 -0
  29. package/schema/shopping-domain-create-response.schema.json +60 -0
  30. package/schema/shopping-domain-get-request.schema.json +18 -0
  31. package/schema/shopping-domain-get-response.schema.json +307 -0
  32. package/schema/shopping-domain-search-request.schema.json +18 -0
  33. package/schema/shopping-domain-search-response.schema.json +92 -0
  34. package/schema/shopping-offers-request.schema.json +31 -0
  35. package/schema/shopping-offers-response.schema.json +172 -0
  36. package/schema/shopping-product-get-request.schema.json +24 -0
  37. package/schema/shopping-product-get-response.schema.json +121 -0
  38. package/schema/shopping-profile-edit-request.schema.json +97 -0
  39. package/schema/shopping-profile-edit-response.schema.json +17 -0
  40. package/schema/shopping-search-request.schema.json +106 -0
  41. package/schema/shopping-search-response.schema.json +182 -0
  42. package/schema/shopping-seller-get-request.schema.json +24 -0
  43. package/schema/shopping-seller-get-response.schema.json +342 -0
  44. package/scripts/allowlist-openclaw.mjs +6 -7
  45. package/sil-shopping/SKILL.md +196 -97
  46. package/sil-shopping/references/mint.md +190 -0
  47. package/dist/lib/bind-channel.js +0 -10
  48. package/dist/lib/creation-entrypoint.js +0 -111
  49. package/dist/lib/derive-agent-id.js +0 -36
  50. package/dist/lib/profile-store.js +0 -568
  51. package/dist/tools/profile.js +0 -300
  52. package/scripts/create-shopper.mjs +0 -677
  53. package/sil-shopping/examples/multi_domain_shopper_walkthrough.md +0 -65
  54. package/sil-shopping/references/agent_creation_engine.md +0 -223
  55. package/sil-shopping/references/fill_and_feedback.md +0 -102
  56. package/sil-shopping/references/method_and_prds.md +0 -143
  57. package/sil-shopping/references/setup_onboarding.md +0 -64
  58. package/sil-shopping/references/shop_loop.md +0 -118
@@ -1,8 +1,9 @@
1
1
  /**
2
- * Typed HTTP wrappers for the two sil-web endpoints the plugin calls, each
3
- * returning a DISCRIMINATED UNION over the documented outcomes so the status
4
- * taxonomy lives in exactly one place and the caller switches on `kind` rather
5
- * than re-deriving meaning from `res.status` at every site.
2
+ * Typed HTTP wrappers for every endpoint the plugin calls — the two sil-web auth
3
+ * endpoints, the sil-api identity read and the eleven shopping routes — each returning
4
+ * a DISCRIMINATED UNION over the documented outcomes so the status taxonomy lives in
5
+ * exactly one place and the caller switches on `kind` rather than re-deriving meaning
6
+ * from `res.status` at every site.
6
7
  *
7
8
  * Wire contract (pinned to the already-merged sil-web routes —
8
9
  * sil-services/apps/sil-web/src/app/api/v1/...):
@@ -29,118 +30,24 @@
29
30
  * 5xx / network / abort → retryable
30
31
  *
31
32
  * Wire contract for the sil-API identity read (a SECOND origin — sil-api, the
32
- * Fastify domain service — NOT sil-web; bare path, not /api/v1; see the
33
- * sil-whoami card). The authenticated self-read is a BODYLESS GET; the
34
- * Authorization header carries the stored session token and IS the principal —
35
- * sil-api derives the user from the JWT `sub`, not a request body:
33
+ * Fastify domain service — NOT sil-web; bare path, not /api/v1). The authenticated
34
+ * self-read is a BODYLESS GET; the Authorization header carries the stored session
35
+ * token and IS the principal — sil-api derives the user from the JWT `sub`, not a
36
+ * request body:
36
37
  *
37
38
  * GET <silApiUrl>/identity Authorization: Bearer <access_token>
38
- * (no body, no content-type)
39
- * 200 { name, addresses } → ok (carries identity)
39
+ * 200 { name, country?, addresses, measurements?, preferences? } → ok
40
40
  * 401 → unauthorized (→ refresh)
41
41
  * 403 { error: user_not_provisioned | principal_mismatch } → forbidden (terminal)
42
42
  * 5xx / network / abort → retryable
43
43
  *
44
- * Wire contract for the sil-API catalog search (SAME origin as the identity
45
- * read — sil-api, bare path, NOT /api/v1; see the sil-search card). A simplified
46
- * structured query in, ranked purchasable products out. sil-api owns the
47
- * enrichment; the plugin sends NO envelope and fills NO defaults:
48
- *
49
- * POST <silApiUrl>/catalog/search Authorization: Bearer <access_token>
50
- * body { query?, filters?:{ categories?, price?:{ min?, max? } },
51
- * pagination?:{ cursor?, limit? } } (no context, no envelope)
52
- * 200 { products: SilCatalogProduct[],
53
- * pagination?:{ has_next_page, cursor? } } → ok
54
- * (`products`/`pagination` at the TOP LEVEL, NO `result` wrapper)
55
- * 400 { error:"empty_search_input", message } → invalid_request
56
- * 401 → unauthorized (→ refresh)
57
- * 5xx / network / abort → retryable
58
- *
59
- * Wire contract for the sil-API catalog LOOKUP (SAME origin/path style as search —
60
- * sil-api, bare `/catalog/lookup`, NOT /api/v1; see the sil-product-get card). The
61
- * lookup COMPANION to search: an agent passes ids it already holds and gets fresh
62
- * RICH detail back (search is LEAN). sil-api owns enrichment + the `not_found`
63
- * messaging; the plugin sends just `{ ids }` (NO filters/context,
64
- * NO envelope). The two structural deltas from search's response: NO `pagination`
65
- * (a batch resolve, not a list) and a `messages[]` carrying the misses:
66
- *
67
- * POST <silApiUrl>/catalog/lookup Authorization: Bearer <access_token>
68
- * body { ids: string[] } (≥1; no filters/context)
69
- * 200 { products: SilCatalogProduct[],
70
- * messages?:[{ type:"info", code:"not_found", content:<id> }] } → ok
71
- * (`products`/`messages` at the TOP LEVEL, NO `result` wrapper)
72
- * 400 (schema: empty `ids` / request_too_large) → invalid_request
73
- * 401 → unauthorized (→ refresh)
74
- * 5xx / network / abort → retryable
75
- *
76
- * A lookup MISS is partial-SUCCESS data, NEVER an error: an unresolved id is a
77
- * `not_found` info `message` (the server omits `messages` entirely on full
78
- * success), surfaced on the `ok` outcome as a `not_found: string[]`. Each looked-up
79
- * variant carries an `inputs:[{ id, match }]` correlation (lookup's defining
80
- * feature over search — the response does NOT preserve request order and one id
81
- * may resolve to a variant of another id's product, so `inputs` is the only way to
82
- * map a request id to its result). `classifyLookupResponse` gates `ok` on a real
83
- * `Array.isArray(products)` on the FLAT envelope's top-level `products` — a 200
84
- * with no usable products array is `retryable`, NEVER a false-green; a genuine
85
- * ALL-MISSED lookup is a 200 whose top-level `products` IS `[]` WITH a populated
86
- * `not_found` → `ok` (success: "none of these exist anymore"), the discriminator
87
- * being array PRESENCE, never length.
88
- *
89
- * Wire contract for the sil-API spec REGISTRY (SAME origin/path style as search —
90
- * sil-api, bare `/catalog/specs`, NOT /api/v1; see the sds-specs-client-tool card).
91
- * The dedupe-or-create up-flow: at method mint/refresh the method submits its coined
92
- * spec DEFINITIONS and gets back the canonical `ns.key` to adopt (born canonical,
93
- * BEFORE persist). sil-api owns the dedupe authority; the plugin sends `{ query,
94
- * specs }` (NO envelope) and reads the resolutions straight off the body:
95
- *
96
- * POST <silApiUrl>/catalog/specs Authorization: Bearer <access_token>
97
- * body { query, specs: SpecDefinition[] } (both required; specs ≥1)
98
- * 200 { resolved: SpecResolution[] } → ok
99
- * (BARE `{ resolved }` at the TOP LEVEL — NO `ucp` meta, NO `result`
100
- * wrapper; specs is an INTERNAL agent↔service op, not a UCP message)
101
- * 400 (schema: empty specs / blank query) → invalid_request
102
- * 401 → unauthorized (→ refresh)
103
- * 403 { error } → forbidden (terminal)
104
- * 5xx / network / abort → retryable
105
- *
106
- * The error arms are a STRICT SUBSET of search's: there is NO 422 SourceError arm
107
- * and NO `source` attribution — the registry is sil's OWN Postgres, not an external
108
- * source (handlers/specs.ts), so a specs `retryable` is always BARE. Every
109
- * well-formed request resolves EVERY submitted spec 1:1 (`matched`|`created`);
110
- * `classifySpecsResponse` gates `ok` on `Array.isArray(resolved)` AND a NON-EMPTY
111
- * array of fully-formed resolutions — a partial / garbage / EMPTY-`resolved` 200
112
- * falls WHOLE to `retryable` (the method can't adopt a canonical name it never got
113
- * back, and there is NO valid empty-match success here, unlike search's empty list).
114
- *
115
- * `SilCatalogProduct` = a UCP product PLUS a required `source`; each variant PLUS
116
- * a required non-empty `checkout_url` (sil-services `@sil/schemas` catalog.ts —
117
- * the byte-shape of truth; `@ucp-js/sdk` carries ZERO catalog types). The plugin
118
- * does NOT depend on `@sil/schemas` (cross-repo): it re-declares the read-subset
119
- * it consumes locally (the `Search*` types below) and narrows the untrusted body
120
- * defensively in `extractSearchResult`. The tool reads `products` straight off the
121
- * FLAT envelope's top level (NO `result` unwrap — search/lookup are always flat,
122
- * only the identity read carries the `result ?? envelope` dual shape), picks the
123
- * FIRST (featured) variant per product (UCP: "Platforms SHOULD treat the first
124
- * element as featured"), projects each to the product-level `{ id, title, source }`
125
- * plus the nested featured `variant` `{ id, title, price, availability,
126
- * checkout_url }`, and hoists the top-level `pagination.cursor` to a top-level
127
- * cursor (present iff `has_next_page`). `classifySearchResponse` gates `ok` on a
128
- * real `Array.isArray(products)` over that top-level `products` — a 200 with no
129
- * usable products array is `retryable`, NEVER a false-green empty match (the same
130
- * anti-false-green guard as the identity `name`-gate). A genuine empty match is a
131
- * 200 whose top-level `products` IS an empty array → `ok` + `products: []`
132
- * (success, not an error — UCP: "empty search returns an empty array … this is not
133
- * an error").
134
- *
135
- * The VERB is load-bearing: sil-api's `POST /identity` is the agent enrich-STUB
136
- * ({kind, verified, subject, ...} — no name/addresses); `GET /identity` is the
137
- * real self-read returning {id, name, addresses} (sil-api `handlers/identity.ts`,
138
- * PR #7). The identity lives in the envelope's `result` (the tool unwraps it so
139
- * the agent sees identity, not transport metadata). `classifyIdentityResponse`
140
- * still narrows DEFENSIVELY — a 200 whose result has no usable identity (no
141
- * `name`) falls to `retryable`, NEVER to a false `ok`, so a stray stub 200 (or a
142
- * malformed body) can't be green while the product promise is unmet. An EMPTY
143
- * `addresses: []` IS a valid identity (a provisioned, address-less user).
44
+ * THE SHOPPING WIRE IS NOT MIRRORED HERE. Each tool's request shape is the committed
45
+ * artifact under `schema/`, registered as the tool's own `parameters`; each 200 body is
46
+ * the agent contract's, handed back VERBATIM. So this file declares no product type at
47
+ * all — a hand-mirror of the response would be a second copy of the contract, and the
48
+ * first thing to drift from it. {@link classifyShoppingResponse} gates the 200 on the
49
+ * ONE thing the plugin genuinely owns (a plain object stating `status: "ok"`) and maps
50
+ * every other status onto the contract's §4 vocabulary.
144
51
  *
145
52
  * THE subtle correctness point (architect Risk "claim taxonomy mis-mapping"):
146
53
  * 200-pending and 200-success are BOTH HTTP 200. `classifyClaimResponse` branches
@@ -151,6 +58,11 @@
151
58
  * unit-tested in isolation, since misclassifying two 200s is the highest-risk
152
59
  * subtle bug in the whole flow.
153
60
  *
61
+ * The VERB is load-bearing: only `GET /identity` is the self-read — `POST` is the
62
+ * agent enrich route and carries no name. The identity rides in the envelope's
63
+ * `result`, and a 200 with no usable identity (no `name`) falls to `retryable`,
64
+ * never to a false `ok`. An EMPTY `addresses: []` IS a valid identity.
65
+ *
154
66
  * Tokens never appear in a log line here (mirrors sil-web's invariant) — they
155
67
  * only travel inside the returned union variant.
156
68
  *
@@ -158,9 +70,47 @@
158
70
  */
159
71
  import { getWebUrl } from "./config.js";
160
72
  import { readTokens, writeTokens } from "./credentials.js";
161
- /** Per-request timeout: a stalled endpoint (DNS hang, SYN drop) must not wedge
162
- * a poll tick forever. Mirrors the 15s ceiling the klodi poller uses. */
163
- const REQUEST_TIMEOUT_MS = 15_000;
73
+ /** Per-request timeout: a stalled endpoint must not wedge a call forever. 45 s for every
74
+ * route that answers from what sil already holds — at 15 s the plugin refused 7 of 12 live
75
+ * calls sil-api went on to finish (2026-09-15). */
76
+ const REQUEST_TIMEOUT_MS = 45_000;
77
+ /** The search alone waits out its web leg, which the agent contract gives 120 s. Aborting
78
+ * short of that changes nothing sil does — the index is billed, the pages are read and the
79
+ * row is written — it only hides the answer from the agent that asked for it. */
80
+ const SEARCH_TIMEOUT_MS = 130_000;
81
+ /** The search route, the one call that waits out a web leg. Resolved by PATH so a route
82
+ * renamed in the tool table falls back to the shared ceiling loudly — `lib/sil-client.test.ts`
83
+ * reads this off the production table. */
84
+ const SEARCH_PATH = "/catalog/search";
85
+ export const requestTimeoutMs = (route) => route.path === SEARCH_PATH ? SEARCH_TIMEOUT_MS : REQUEST_TIMEOUT_MS;
86
+ /**
87
+ * Classify a shopping response. One classifier for all eleven routes — the contract
88
+ * gives them one error vocabulary, so a second one could only drift.
89
+ *
90
+ * The 200 gate is the whole of what the plugin owns: a plain object stating
91
+ * `status: "ok"`. Every 200 the API means as an answer says so, and a 200 that does
92
+ * not is a broken contract rather than a degraded answer — `retryable`, never `ok`.
93
+ * Nothing below the top level is inspected: the response artifact is the shape's one
94
+ * source, and a second opinion here would be the copy that drifts from it.
95
+ */
96
+ function classifyShoppingResponse(status, body) {
97
+ if (status === 400)
98
+ return { kind: "invalid_request", message: extractApiError(body).message };
99
+ if (status === 401)
100
+ return { kind: "unauthorized" };
101
+ if (status === 403)
102
+ return { kind: "forbidden", reason: extractForbiddenReason(body) };
103
+ if (status === 404)
104
+ return { kind: "not_found", message: extractApiError(body).message };
105
+ if (status === 409)
106
+ return { kind: "already_exists", message: extractApiError(body).message };
107
+ if (status !== 200)
108
+ return retryableFromBody(body);
109
+ const envelope = asRecord(body);
110
+ if (envelope === null || envelope["status"] !== "ok")
111
+ return { kind: "retryable" };
112
+ return { kind: "ok", body: envelope };
113
+ }
164
114
  /**
165
115
  * Classify a claim response from its HTTP status AND body. The discriminant for
166
116
  * the two-200s split is the PRESENCE OF BOTH TOKENS in the body — never the
@@ -260,165 +210,6 @@ export function classifyIdentityResponse(status, body) {
260
210
  return { kind: "retryable" };
261
211
  return { kind: "ok", identity };
262
212
  }
263
- /**
264
- * Classify a sil-api catalog-search response from its HTTP status AND body.
265
- * Branches on STATUS (and, for 200, the body shape) — never on `res.ok`:
266
- * 400 → invalid_request (surface sil-api's structured `{ error, message }`,
267
- * e.g. `empty_search_input` — distinct from both the empty-match success
268
- * and a transient failure; the agent must learn to fix its query, not
269
- * retry or re-register)
270
- * 401 → unauthorized (the refresh trigger — the caller drives transparent
271
- * refresh-and-retry-once via `refreshAndRetryOnce`, not terminal)
272
- * 403 → forbidden (terminal-but-recoverable; carries the actionable reason
273
- * `user_not_provisioned`/`principal_mismatch`, defaulting to the generic
274
- * `"forbidden"` marker on an unexpected body — parity with
275
- * `classifyIdentityResponse`). A 403 is NOT a 401: it surfaces as the
276
- * shared forbidden envelope, never the false-transient `retryable`, and a
277
- * valid-but-unprovisioned token gains nothing from a refresh.
278
- * 5xx / other non-200 → retryable
279
- * 200 → read `products` off sil-api's FLAT body (`{ products, pagination? }` —
280
- * top level, no `result` wrapper), normalize, and require
281
- * `products` to be a real ARRAY. A 200 that yields no usable top-level
282
- * products array (a partial / garbage / stub-shaped body) is `retryable`,
283
- * NEVER `ok` — the
284
- * `Array.isArray(products)` gate is the anti-false-green guard, the
285
- * analogue of the identity `name`-gate. A genuine empty match (200 whose
286
- * top-level `products` IS `[]`) is `ok` with an empty product list: a
287
- * SUCCESS, distinct from the no-array guard.
288
- *
289
- * Pure and exported — unit-tested in isolation like `classifyIdentityResponse`;
290
- * conflating the empty-match success with a partial-200 false-green, or with the
291
- * 400/401/403/5xx error classes, is the highest-risk subtle bug in this flow.
292
- */
293
- export function classifySearchResponse(status, body) {
294
- if (status === 400) {
295
- const { error, message } = extractApiError(body);
296
- return { kind: "invalid_request", error, message };
297
- }
298
- if (status === 401)
299
- return { kind: "unauthorized" };
300
- if (status === 403)
301
- return { kind: "forbidden", reason: extractForbiddenReason(body) };
302
- // 422 source_rejected: the source LOOKED at this exact request and refused it —
303
- // it can never succeed unchanged, so it is non-retryable invalid_request carrying
304
- // the real upstream cause, NOT the source-named `retryable` the fallthrough below
305
- // would produce (a 422 body names a `source`, so `retryableFromBody` would emit
306
- // outcome (b) and tell the agent to retry a doomed request). This is the third
307
- // arm of the 401-vs-403-vs-422 split: 401 refresh-and-retry, 403 forbidden
308
- // (refresh won't help), 422 invalid_request (fix the request, don't retry).
309
- // Matches EXACTLY 422 — a 5xx/429 source_unavailable stays `retryable` (outcome b).
310
- if (status === 422) {
311
- const { error, message } = extractApiError(body);
312
- return { kind: "invalid_request", error, message };
313
- }
314
- if (status !== 200)
315
- return retryableFromBody(body);
316
- const result = extractSearchResult(body);
317
- if (result === null)
318
- return { kind: "retryable" };
319
- return { kind: "ok", ...result };
320
- }
321
- /**
322
- * Classify a sil-api catalog-LOOKUP response from its HTTP status AND body.
323
- * Branches on STATUS (and, for 200, the body shape) — never on `res.ok`. The
324
- * SAME class structure as `classifySearchResponse` (so the two catalog tools
325
- * share one error vocabulary), minus search's `empty_search_input` subtlety:
326
- * 400 → invalid_request (a SCHEMA-validation 400 — an empty/missing `ids`
327
- * rejected by `CatalogLookupRequest.ids` `minItems:1`, or a
328
- * `request_too_large` over-batch — surface the server's `{ error,
329
- * message }`. NOTE: this is NOT search's `empty_search_input` SourceError,
330
- * which never arises on the lookup route; do not special-case it.)
331
- * 401 → unauthorized (the refresh trigger — the caller drives transparent
332
- * refresh-and-retry-once via `refreshAndRetryOnce`, parity with search)
333
- * 403 → forbidden (terminal-but-recoverable; carries the actionable reason
334
- * `user_not_provisioned`/`principal_mismatch`, defaulting to the generic
335
- * `"forbidden"` marker on an unexpected body — parity with search and
336
- * `classifyIdentityResponse`). A 403 surfaces as the shared forbidden
337
- * envelope, never the false-transient `retryable`; it is NOT a 401, so no
338
- * refresh is triggered.
339
- * 5xx / other non-200 → retryable
340
- * 200 → read `products` off sil-api's FLAT body (`{ products, messages? }` —
341
- * top level, no `result` wrapper), normalize, and require
342
- * `products` to be a real ARRAY. A 200 that yields no usable top-level
343
- * products array (a partial / garbage / stub-shaped body) is `retryable`,
344
- * NEVER `ok` — the `Array.isArray(products)` gate is the anti-false-green
345
- * guard, the analogue of the identity `name`-gate and search's
346
- * products-array gate.
347
- *
348
- * THE subtle correctness point: an all-MISSED lookup is a genuine SUCCESS — a 200
349
- * whose top-level `products` IS an empty array WITH a populated `not_found` list
350
- * ("none of these ids exist anymore"). It is `ok` with empty `products` + full
351
- * `not_found`, distinct from the no-array guard above. The discriminator between
352
- * "valid all-missed" and "garbage 200" is the `products`-array PRESENCE, NEVER
353
- * array length — exactly as search distinguishes empty-match from a partial-200
354
- * false-green.
355
- *
356
- * Pure and exported — unit-tested in isolation like `classifySearchResponse`.
357
- */
358
- export function classifyLookupResponse(status, body) {
359
- if (status === 400) {
360
- const { error, message } = extractApiError(body);
361
- return { kind: "invalid_request", error, message };
362
- }
363
- if (status === 401)
364
- return { kind: "unauthorized" };
365
- if (status === 403)
366
- return { kind: "forbidden", reason: extractForbiddenReason(body) };
367
- // 422 source_rejected: the twin seam of `classifySearchResponse` — sil-api emits
368
- // 422 on the SHARED source layer backing both catalog routes, so a source-rejected
369
- // lookup is the same non-retryable invalid_request, carrying the upstream cause,
370
- // NOT the source-named `retryable` the fallthrough would produce. Same one error
371
- // vocabulary across both catalog tools (see this fn's doc-comment). Matches EXACTLY
372
- // 422 — a 5xx/429 source_unavailable stays `retryable` (outcome b).
373
- if (status === 422) {
374
- const { error, message } = extractApiError(body);
375
- return { kind: "invalid_request", error, message };
376
- }
377
- if (status !== 200)
378
- return retryableFromBody(body);
379
- const result = extractLookupResult(body);
380
- if (result === null)
381
- return { kind: "retryable" };
382
- return { kind: "ok", ...result };
383
- }
384
- /**
385
- * Classify a sil-api spec-REGISTRY response from its HTTP status AND body. A STRICT
386
- * SUBSET of `classifySearchResponse` — same 400/401/403 arms, but NO 422 arm and a
387
- * BARE `retryable` (the registry has no external source to attribute):
388
- * 400 → invalid_request (schema reject: empty `specs` / blank `query` — surface
389
- * the server's `{ error, message }`; NOT retryable, NOT re-register)
390
- * 401 → unauthorized (the refresh trigger — the caller drives transparent
391
- * refresh-and-retry-once via `refreshAndRetryOnce`, parity with search)
392
- * 403 → forbidden (terminal-but-recoverable; carries the actionable reason
393
- * `user_not_provisioned`/`principal_mismatch`, defaulting to `"forbidden"`)
394
- * 5xx / other non-200 → retryable (BARE — no `source`/`detail`; the registry is
395
- * sil's own Postgres, so there is nothing external to name)
396
- * 200 → read `resolved` off the FLAT body (`{ resolved }` — top level, NO `ucp`
397
- * meta, NO `result` wrapper) and require a NON-EMPTY array of fully-formed
398
- * resolutions via {@link extractSpecsResult}. A 200 with no usable array (a
399
- * partial / garbage / stub / EMPTY-`resolved` body) is `retryable`, NEVER
400
- * `ok` — `Array.isArray(resolved)` is the anti-false-green gate. Unlike
401
- * search there is NO valid empty-match: the server owes a 1:1 resolution, so
402
- * an empty or short `resolved` is a malformed 200, not a success.
403
- *
404
- * Pure and exported — unit-tested in isolation like `classifySearchResponse`.
405
- */
406
- export function classifySpecsResponse(status, body) {
407
- if (status === 400) {
408
- const { error, message } = extractApiError(body);
409
- return { kind: "invalid_request", error, message };
410
- }
411
- if (status === 401)
412
- return { kind: "unauthorized" };
413
- if (status === 403)
414
- return { kind: "forbidden", reason: extractForbiddenReason(body) };
415
- if (status !== 200)
416
- return { kind: "retryable" };
417
- const resolved = extractSpecsResult(body);
418
- if (resolved === null)
419
- return { kind: "retryable" };
420
- return { kind: "ok", resolved };
421
- }
422
213
  /**
423
214
  * Attempt to claim the token pair for `sessionId` with `verifier`. The verifier
424
215
  * is sent in the body; sil-web derives the same challenge server-side and the
@@ -454,20 +245,12 @@ export async function refreshSession(apiUrl, refreshToken) {
454
245
  return classifyRefreshResponse(res.status, body);
455
246
  }
456
247
  /**
457
- * Read the authenticated user's identity from sil-api (the SECOND origin — the
458
- * Fastify domain service, NOT sil-web). This is a bodyless `GET <silApiUrl>/identity`:
459
- * sil-api's authenticated self-read derives the principal from the JWT `sub`
460
- * (the `Authorization: Bearer <token>` header), loads that user's addresses,
461
- * and returns `{ id, name, addresses }` (sil-api `handlers/identity.ts` GET route —
462
- * declares only a response schema, takes no request body). The verb is the whole
463
- * point: POST hits the agent
464
- * enrich-STUB (no name/addresses), GET hits the real self-read. No `agent_id`
465
- * or `on_behalf_of` is sent — the GET self-read has no body, so the principal
466
- * is unambiguously the token subject and the `principal_mismatch` 403 path is
467
- * eliminated entirely. A network error / timeout → `retryable`.
248
+ * Read the authenticated user's identity from sil-api (the SECOND origin, not
249
+ * sil-web): a BODYLESS `GET /identity` answering `{ id, name, country?, addresses }`.
250
+ * Bodyless is the point — the principal is the token subject and nothing else, so
251
+ * no `agent_id` is sendable and the `principal_mismatch` 403 cannot arise.
468
252
  *
469
- * The Bearer header is built HERE and never logged; the token travels only in
470
- * the outbound request, never into the returned union.
253
+ * The Bearer header is built HERE and never logged.
471
254
  */
472
255
  export async function fetchIdentity(silApiUrl, token) {
473
256
  const url = `${stripTrailingSlash(silApiUrl)}/identity`;
@@ -482,82 +265,76 @@ export async function fetchIdentity(silApiUrl, token) {
482
265
  return classifyIdentityResponse(res.status, body);
483
266
  }
484
267
  /**
485
- * Run a catalog search against sil-api (the SAME origin as the identity read —
486
- * NOT sil-web; bare `/catalog/search`, no `/api/v1`). The simplified
487
- * {@link SearchParams} are mapped into the sil-api `CatalogSearchRequest` body
488
- * (`{ query?, filters:{ categories?, price:{ min?, max? } }, pagination:{ cursor?, limit? } }`)
489
- * — building NO UCP envelope and filling NO defaults the agent did not supply.
490
- * Only the keys the agent actually provided are emitted (an absent filter is an
491
- * omitted key, not an empty object), so a free-text-only query sends just
492
- * `{ query }` and sil-api applies its own context resolution.
493
- *
494
- * The Bearer header is built HERE and never logged; the token travels only in
495
- * the outbound request, never into the returned union. A network error / timeout
496
- * maps to `retryable`.
497
- */
498
- export async function searchCatalog(silApiUrl, token, params) {
499
- const url = `${stripTrailingSlash(silApiUrl)}/catalog/search`;
500
- let res;
501
- try {
502
- res = await postJson(url, buildSearchBody(params), {
503
- authorization: `Bearer ${token}`,
504
- });
505
- }
506
- catch {
507
- return { kind: "retryable" };
508
- }
509
- const body = await readJsonBody(res);
510
- return classifySearchResponse(res.status, body);
511
- }
512
- /**
513
- * Resolve catalog ids against sil-api (the SAME origin as the identity read and
514
- * `searchCatalog` — NOT sil-web; bare `/catalog/lookup`, no `/api/v1`). The agent
515
- * already holds the ids (from a prior `sil_search`, a saved list, or cart
516
- * validation); this re-fetches CURRENT detail for them — building NO UCP envelope
517
- * and filling NO defaults. The body is just `{ ids }` (the simplified contract;
518
- * `filters`/`context` are sil-api options this tool does not expose). The ids are
519
- * forwarded AS GIVEN — sil-api owns dedup (its seam already dedups) and any batch
520
- * cap; the tool does not pre-dedup (which would mask a seam regression).
268
+ * Call one shopping route. `args` are the host-validated tool arguments, forwarded AS
269
+ * GIVEN: the plugin fills no default, clamps no bound and re-validates nothing, because
270
+ * the route refuses before it spends and names the offender in its own message — a
271
+ * second validator here would buy nothing and drift from the artifact that already
272
+ * bounds the input.
521
273
  *
522
274
  * The Bearer header is built HERE and never logged; the token travels only in the
523
- * outbound request, never into the returned union. A network error / timeout maps
524
- * to `retryable`.
275
+ * outbound request, never into the returned union.
525
276
  */
526
- export async function lookupCatalog(silApiUrl, token, ids) {
527
- const url = `${stripTrailingSlash(silApiUrl)}/catalog/lookup`;
277
+ export async function callShopping(silApiUrl, token, route, args) {
278
+ const path = routePath(route, args);
279
+ if (typeof path !== "string") {
280
+ return {
281
+ kind: "invalid_request",
282
+ message: `\`${path.missing}\` is required and must be a string. Nothing was sent to sil:`
283
+ + ` it names a path SEGMENT, so an empty one would call a different route and`
284
+ + ` sil would answer about that route instead of about your request.`,
285
+ };
286
+ }
287
+ const url = `${stripTrailingSlash(silApiUrl)}${path}`;
528
288
  let res;
529
289
  try {
530
- res = await postJson(url, { ids }, { authorization: `Bearer ${token}` });
290
+ const timeoutMs = requestTimeoutMs(route);
291
+ res =
292
+ route.method === "GET"
293
+ ? await getJson(url, { authorization: `Bearer ${token}` }, timeoutMs)
294
+ : await postJson(url, args, { authorization: `Bearer ${token}` }, timeoutMs);
531
295
  }
532
296
  catch {
533
297
  return { kind: "retryable" };
534
298
  }
535
- const body = await readJsonBody(res);
536
- return classifyLookupResponse(res.status, body);
299
+ return classifyShoppingResponse(res.status, await readJsonBody(res));
537
300
  }
538
301
  /**
539
- * Canonicalize coined spec definitions against sil-api's registry (the SAME origin
540
- * as the identity read / `searchCatalog` / `lookupCatalog` — NOT sil-web; bare
541
- * `/catalog/specs`, no `/api/v1`). The method submits `{ query, specs }` at mint/
542
- * refresh and gets back the canonical `ns.key` per submitted spec — building NO UCP
543
- * envelope and NO filter mapping (the wire body is EXACTLY `{ query, specs }`).
544
- *
545
- * The Bearer header is built HERE and never logged; the token travels only in the
546
- * outbound request, never into the returned union. A network error / timeout maps
547
- * to `retryable` (bare) so the method degrades gracefully to raw coined names — a
548
- * registry hiccup never blocks the mint.
302
+ * The route's path with its `:name` segment filled and its querystring built — or the
303
+ * name of the segment the arguments could not fill.
304
+ *
305
+ * THE SEGMENT IS THE ONE THING REFUSED LOCALLY, and it is not a second validator: an
306
+ * absent one does not make a bad request, it makes a request to a DIFFERENT ROUTE, and
307
+ * sil then answers truthfully about that route while the agent reads the answer as being
308
+ * about its own. Everything else travels as sent, because the route names the offender.
309
+ *
310
+ * Both halves are encoded, never concatenated: a dotted registry path is one PATH
311
+ * SEGMENT (a stray `/` in it would re-route the call), and an unencoded query value
312
+ * could inject a second parameter. Only the keys the agent actually sent travel — an
313
+ * empty `q=` is a DIFFERENT request from an omitted `q`, and each gets its own refusal
314
+ * message, which is the agent's whole recourse.
549
315
  */
550
- export async function specsCatalog(silApiUrl, token, params) {
551
- const url = `${stripTrailingSlash(silApiUrl)}/catalog/specs`;
552
- let res;
553
- try {
554
- res = await postJson(url, { query: params.query, specs: params.specs }, { authorization: `Bearer ${token}` });
555
- }
556
- catch {
557
- return { kind: "retryable" };
558
- }
559
- const body = await readJsonBody(res);
560
- return classifySpecsResponse(res.status, body);
316
+ function routePath(route, args) {
317
+ let missing;
318
+ const path = route.path.replace(/:([a-z_]+)/g, (_match, name) => {
319
+ const value = args[name];
320
+ if (typeof value !== "string" || value.length === 0) {
321
+ missing ??= name;
322
+ return "";
323
+ }
324
+ return encodeURIComponent(value);
325
+ });
326
+ if (missing !== undefined)
327
+ return { missing };
328
+ if (route.method !== "GET")
329
+ return path;
330
+ const query = new URLSearchParams();
331
+ for (const key of route.query ?? []) {
332
+ const value = args[key];
333
+ if (typeof value === "string")
334
+ query.set(key, value);
335
+ }
336
+ const search = query.toString();
337
+ return search === "" ? path : `${path}?${search}`;
561
338
  }
562
339
  /**
563
340
  * SC7/F7 entry point: read the stored refresh token, exchange it via sil-web,
@@ -590,7 +367,7 @@ export async function refreshStoredTokens() {
590
367
  }
591
368
  /**
592
369
  * THE single 401 refresh-and-retry-once choreography, shared by every
593
- * sil-api-calling tool (`sil_search`, `sil_product_get`, `sil_whoami`) so the 401
370
+ * sil-api-calling tool (every `shopping_*` call and `sil_whoami`) so the 401
594
371
  * behaviour cannot drift apart between them (FLAG-10). The control flow IS the
595
372
  * contract — straight-line, AT MOST one refresh + AT MOST one retry, no loop:
596
373
  *
@@ -650,22 +427,12 @@ export async function refreshAndRetryOnce(first, isUnauthorized, retryWithToken)
650
427
  return { kind: "result", outcome: retry, refreshed: true };
651
428
  }
652
429
  /**
653
- * Unwrap + narrow a sil-api identity response body to a typed `Identity`, or
654
- * null if it carries no usable identity. Defends against the latent wire shape:
655
- * the identity may be wrapped in a `result` field OR (if the follow-on returns it
656
- * bare) at the top level, so we try `result` first and fall back to the body
657
- * itself.
430
+ * Unwrap + narrow a sil-api identity body to a typed `Identity`, or null when it
431
+ * carries none. The body may wrap the identity in `result` or return it bare.
658
432
  *
659
- * A usable identity REQUIRES a non-empty `name` string (the authoritative human
660
- * name) and that `addresses` is an ARRAY — but the array may be EMPTY. sil-api
661
- * returns `addresses: []` for a provisioned user who has onboarded a name but
662
- * not yet added an address (`handlers/identity.ts` → `buildIdentityReadResult`);
663
- * that is a real, authenticated identity, NOT a not-yet-ready read. Rejecting it
664
- * would strand such a user on a false `retryable` they could never escape by
665
- * retrying. The `name` gate is the load-bearing anti-false-green guard: the
666
- * current /identity STUB shape ({kind, verified, subject, ...}) has NO name, so
667
- * it still returns null → `retryable`, never a false `ok`. Extra fields on each
668
- * address are preserved (addresses pass through opaque — see `IdentityAddress`).
433
+ * An EMPTY `addresses` is a real identity (a provisioned user who has not added
434
+ * an address yet) — rejecting it would strand them on a `retryable` no retry can
435
+ * clear. The non-empty `name` gate is what keeps a nameless body off `ok`.
669
436
  */
670
437
  function extractIdentity(body) {
671
438
  const envelope = asRecord(body);
@@ -680,7 +447,33 @@ function extractIdentity(body) {
680
447
  if (!Array.isArray(rawAddresses))
681
448
  return null;
682
449
  const addresses = rawAddresses.filter((a) => asRecord(a) !== null);
683
- return { name, addresses };
450
+ // The profile halves are NOT a gate: a read that carries neither is a buyer who
451
+ // has told sil nothing yet, and `[]` says exactly that — refusing here would
452
+ // strand them on a `retryable` no retry can clear.
453
+ const measurements = plainObjects(source["measurements"]);
454
+ const preferences = plainObjects(source["preferences"]);
455
+ // `country`, `gender` and `currency` are optional on the read and pass through only as
456
+ // strings — an absent or non-string one is dropped, never coerced or inferred. The VALUE
457
+ // is the route's to decide: a literal allow-list here would drop a vocabulary sil adds.
458
+ const country = source["country"];
459
+ const gender = source["gender"];
460
+ const currency = source["currency"];
461
+ return {
462
+ name,
463
+ addresses,
464
+ measurements,
465
+ preferences,
466
+ ...(typeof country === "string" ? { country } : {}),
467
+ ...(typeof gender === "string" ? { gender } : {}),
468
+ ...(typeof currency === "string" ? { currency } : {}),
469
+ };
470
+ }
471
+ /** The elements of `value` that are plain objects, as `addresses` are filtered:
472
+ * absent or shapeless is `[]`, never a partial read of a malformed entry. */
473
+ function plainObjects(value) {
474
+ if (!Array.isArray(value))
475
+ return [];
476
+ return value.filter((e) => asRecord(e) !== null);
684
477
  }
685
478
  /** Pull the actionable reason out of a 403 body (`user_not_provisioned` /
686
479
  * `principal_mismatch`), defaulting to a generic marker when the shape is
@@ -690,674 +483,6 @@ function extractForbiddenReason(body) {
690
483
  const error = obj?.["error"];
691
484
  return typeof error === "string" && error.length > 0 ? error : "forbidden";
692
485
  }
693
- /**
694
- * Map the simplified {@link SearchParams} into the sil-api `CatalogSearchRequest`
695
- * body. Only keys the agent supplied are emitted — an absent filter is an OMITTED
696
- * key (sil-api's body is `additionalProperties: false`, but every field is
697
- * optional), never an empty `{}`. The singular `category` maps into the UCP
698
- * `filters.categories` ARRAY (sil-api's filter is multi-taxonomy; the simplified
699
- * contract takes one). `price_min`/`price_max` map into `filters.price.{min,max}`.
700
- * The tool clamps nothing and validates no cursor opacity — sil-api owns those.
701
- *
702
- * THE load-bearing rename: the agent arg `ship_to` (singular) becomes the wire key
703
- * `filters.ships_to` (plural). `condition`/`available` keep their name under
704
- * `filters.*`. These three ride sil-api's OPEN `SearchFilters`
705
- * (`additionalProperties: true`), which SILENTLY accepts an unknown key — so the
706
- * exact emitted key name is the only thing standing between a working serviceability
707
- * filter and a no-op (a wrong rename fails GREEN). Each is forwarded ONLY when
708
- * supplied (omit-when-absent, identical to `category`/`price`/`pagination`); NO
709
- * client-injected default (the server applies `available: true`). A supplied
710
- * `available: false` is narrowed with `typeof === "boolean"`, never `if (v)`, so the
711
- * meaningful `false` (include unavailable items) survives.
712
- *
713
- * `local_merchants` is the ONE field that does NOT ride `filters`. It is a
714
- * sil-PRIVATE ranking-bias signal, not a UCP/Global-Catalog filter — `filters` is
715
- * forwarded to the cross-shop Global Catalog, whose OPEN schema would silently
716
- * accept and ignore an unknown `local_merchants` key (the exact wrong-placement
717
- * no-op the rename hazard above warns of). So it is emitted at the TOP LEVEL of the
718
- * body (beside `query`/`filters`/`pagination`), and ONLY when exactly `true`: unlike
719
- * `available: false` (a meaningful include-unavailable signal that survives), a
720
- * `false` bias carries NO signal (== the server's unbiased default), so `false` and
721
- * absent both omit the key (narrow on the VALUE, not just the type — emit iff true).
722
- *
723
- * COUNTRY-CASE NORMALIZATION is the wire layer's job (the read site owns FORMAT
724
- * rejection): `ships_to.country` is emitted UPPERCASE (`us` → `US`), the alpha-2
725
- * contract `@sil/schemas` `ShipTo` mirrors byte-for-byte. A lowercase code on the
726
- * wire would diverge from the sibling and (depending on the server's
727
- * case-sensitivity) silently mis-filter. `region` and `postal_code` are forwarded
728
- * VERBATIM — they passed their pattern at the read site, and the wire normalizes
729
- * only country case.
730
- */
731
- function buildSearchBody(params) {
732
- const body = {};
733
- // The agent's free-text `query` is forwarded VERBATIM. The plugin is pure
734
- // transport — a `specs` predicate NEVER folds into `query` (that lossy/unsafe job
735
- // belongs to the agent, which authors the free-text from the requirements).
736
- if (typeof params.query === "string")
737
- body["query"] = params.query;
738
- const filters = {};
739
- if (typeof params.category === "string") {
740
- filters["categories"] = [params.category];
741
- }
742
- const price = {};
743
- if (typeof params.price_min === "number")
744
- price["min"] = params.price_min;
745
- if (typeof params.price_max === "number")
746
- price["max"] = params.price_max;
747
- if (Object.keys(price).length > 0)
748
- filters["price"] = price;
749
- // The three serviceability/localization filters — the `ship_to` → `ships_to`
750
- // rename happens here; the other two keep their name. Country is uppercased on
751
- // emit (region/postal forwarded verbatim); the other two pass through as-is.
752
- if (params.ship_to !== undefined)
753
- filters["ships_to"] = withUppercaseCountry(params.ship_to);
754
- if (params.condition !== undefined)
755
- filters["condition"] = params.condition;
756
- if (typeof params.available === "boolean")
757
- filters["available"] = params.available;
758
- // The structured requirement predicates ride ONE namespaced well-known key —
759
- // `filters.specs` holds the WHOLE array (never spread as `filters.<key>`, which
760
- // would collide with a typed filter and fail-green on the open `SearchFilters`;
761
- // never top-level — unlike the sil-private `local_merchants`, `specs` is a
762
- // backend-bound filter). `hard` rides each entry UNCHANGED. A present-but-empty
763
- // `[]` emits nothing (the query is unchanged, `filters.specs` omitted).
764
- if (Array.isArray(params.specs) && params.specs.length > 0)
765
- filters["specs"] = params.specs;
766
- if (Object.keys(filters).length > 0)
767
- body["filters"] = filters;
768
- // `local_merchants` is a sil-PRIVATE ranking bias — it rides at the TOP LEVEL of
769
- // the body (a sibling of `query`/`filters`/`pagination`), NEVER under `filters`
770
- // (those are forwarded to the Global Catalog, which would silently swallow it).
771
- // Emitted ONLY when exactly `true`: a `false`/absent bias carries no signal (it is
772
- // the server's unbiased default), so — unlike `available:false` — it is omitted.
773
- // Narrow on the VALUE, not just the type: `=== true`, never a truthiness coerce.
774
- if (params.local_merchants === true)
775
- body["local_merchants"] = true;
776
- const pagination = {};
777
- if (typeof params.cursor === "string")
778
- pagination["cursor"] = params.cursor;
779
- if (typeof params.limit === "number")
780
- pagination["limit"] = params.limit;
781
- if (Object.keys(pagination).length > 0)
782
- body["pagination"] = pagination;
783
- return body;
784
- }
785
- /** Emit a ship-to object with its alpha-2 `country` UPPERCASED on the wire
786
- * (`us` → `US`); every other field (`region`/`postal_code` on {@link ShipTo}) is
787
- * preserved verbatim. The spread-then-overwrite keeps the shape generic over any
788
- * `{ country }`-bearing value without reshaping or dropping a field. */
789
- function withUppercaseCountry(value) {
790
- return { ...value, country: value.country.toUpperCase() };
791
- }
792
- /**
793
- * Unwrap + narrow a sil-api catalog-search response body to a typed
794
- * {@link SearchResult}, or null if it carries no usable products array. sil-api
795
- * emits a FLAT body: `products` and `pagination` sit at the TOP LEVEL, there is
796
- * NO `result` wrapper. Read them straight
797
- * off the body. (There is no nested-`result` fallback to keep: search has no
798
- * second route that ever returns one, so a `result`-wrapper expectation would be
799
- * dead weight and — worse — a latent false-green a stray `result` key could shadow
800
- * the real top-level `products`.)
801
- *
802
- * The load-bearing anti-false-green guard is the `Array.isArray(products)` check:
803
- * a 200 lacking a real top-level `products` array (a partial / garbage / stub
804
- * `{ stub: true }` body) returns null →
805
- * `retryable`, never a false-green empty match. An EMPTY array is a VALID empty
806
- * match (a genuine "nothing matched") and returns an empty `products` list —
807
- * distinct from the no-array guard. Individual products that are unusable (no
808
- * projectable featured variant, missing checkout_url) are dropped via
809
- * `projectProduct` returning null, never fabricated.
810
- *
811
- * The opaque cursor is hoisted from `pagination.cursor` and surfaced ONLY when
812
- * `pagination.has_next_page` is true (end-of-results is the absent cursor — never
813
- * derived from `products.length`).
814
- *
815
- * `specs_status` is read off the SAME flat envelope as a sibling of `products`
816
- * (via {@link extractSpecsStatus}), so the observable per-predicate applied-status
817
- * surfaces even on an empty match. It is informational — NEVER a purchasability
818
- * gate; the `Array.isArray(products)` anti-false-green guard is unchanged.
819
- */
820
- function extractSearchResult(body) {
821
- const envelope = asRecord(body);
822
- if (envelope === null)
823
- return null;
824
- const rawProducts = envelope["products"];
825
- if (!Array.isArray(rawProducts))
826
- return null;
827
- const products = rawProducts
828
- .map(projectProduct)
829
- .filter((p) => p !== null);
830
- const result = { products };
831
- const cursor = extractCursor(envelope["pagination"]);
832
- if (cursor !== null)
833
- result.cursor = cursor;
834
- const specsStatus = extractSpecsStatus(envelope["specs_status"]);
835
- if (specsStatus !== null)
836
- result.specs_status = specsStatus;
837
- return result;
838
- }
839
- /** Narrow the wire `specs_status` to {@link SpecStatus}[], or null to OMIT the
840
- * key. Each usable entry needs a non-empty string `ns`, a non-empty string `key`,
841
- * and a BOOLEAN `applied`; a malformed entry is DROPPED (never fabricated
842
- * `applied:true`, never a crash). Returns null when the field is absent/non-array
843
- * OR when no entry survives — the no-fabrication discipline: interpreting the
844
- * ABSENCE of a status is reflection's job, not the tool's. A fully-`applied:false`
845
- * array is the honest "not indexed yet" shape and passes through whole. */
846
- function extractSpecsStatus(raw) {
847
- if (!Array.isArray(raw))
848
- return null;
849
- const statuses = raw
850
- .map((entry) => {
851
- const obj = asRecord(entry);
852
- if (obj === null)
853
- return null;
854
- const ns = obj["ns"];
855
- const key = obj["key"];
856
- const applied = obj["applied"];
857
- if (typeof ns !== "string" || ns.length === 0)
858
- return null;
859
- if (typeof key !== "string" || key.length === 0)
860
- return null;
861
- if (typeof applied !== "boolean")
862
- return null;
863
- return { ns, key, applied };
864
- })
865
- .filter((s) => s !== null);
866
- return statuses.length === 0 ? null : statuses;
867
- }
868
- /**
869
- * Project one `SilCatalogProduct` to the agent-facing {@link SearchProduct}, or
870
- * null if it is unusable. Carries the product-level `id`/`title`/`source` AND the
871
- * featured variant nested under `variant`. Picks the FIRST (featured) variant —
872
- * UCP: "Platforms SHOULD treat the first element as featured". A product whose
873
- * featured variant has no non-empty `checkout_url` (the one field the agent acts
874
- * on to buy), or that is missing any required field, is dropped rather than
875
- * surfaced as a non-purchasable result.
876
- */
877
- function projectProduct(raw) {
878
- const product = asRecord(raw);
879
- if (product === null)
880
- return null;
881
- const productId = product["id"];
882
- const productTitle = product["title"];
883
- const source = product["source"];
884
- if (typeof productId !== "string" || productId.length === 0)
885
- return null;
886
- if (typeof productTitle !== "string")
887
- return null;
888
- if (typeof source !== "string" || source.length === 0)
889
- return null;
890
- const variants = product["variants"];
891
- if (!Array.isArray(variants) || variants.length === 0)
892
- return null;
893
- const variant = projectVariant(variants[0]);
894
- if (variant === null)
895
- return null;
896
- const result = { id: productId, title: productTitle, source, variant };
897
- attachProductEnrichment(result, product);
898
- return result;
899
- }
900
- /**
901
- * Project a `SilCatalogVariant` to the agent-facing {@link SearchVariant}, or
902
- * null if it is not a usable purchasable variant. Requires `id`, `title`, a price
903
- * object, and a non-empty `checkout_url`; `price`/`availability` pass through
904
- * opaque. The PURCHASABILITY gate is unchanged — the enriched fields are additive
905
- * context, never a new gate: a variant lacking a non-empty `checkout_url` is still
906
- * dropped even when it carries `url`/`seller`/`media`.
907
- *
908
- * The enriched per-variant surface (`url`/`seller`/`media`/`metadata`) is attached
909
- * via {@link attachVariantEnrichment}, each ONLY when present.
910
- */
911
- function projectVariant(raw) {
912
- const variant = asRecord(raw);
913
- if (variant === null)
914
- return null;
915
- const id = variant["id"];
916
- const title = variant["title"];
917
- const checkoutUrl = variant["checkout_url"];
918
- if (typeof id !== "string" || id.length === 0)
919
- return null;
920
- if (typeof title !== "string")
921
- return null;
922
- if (typeof checkoutUrl !== "string" || checkoutUrl.length === 0)
923
- return null;
924
- const price = extractPrice(variant["price"]);
925
- if (price === null)
926
- return null;
927
- const result = {
928
- id,
929
- title,
930
- price,
931
- availability: extractAvailability(variant["availability"]),
932
- checkout_url: checkoutUrl,
933
- };
934
- attachVariantEnrichment(result, variant);
935
- return result;
936
- }
937
- /**
938
- * Unwrap + narrow a sil-api catalog-LOOKUP response body to a typed
939
- * {@link LookupResult}, or null if it carries no usable products array. Like
940
- * `extractSearchResult`, it reads sil-api's FLAT body: `products` and `messages`
941
- * sit at the TOP LEVEL, there is NO `result` wrapper — read them straight off
942
- * the body (no nested-`result` fallback; lookup has no route that returns one).
943
- *
944
- * It shares search's load-bearing anti-false-green guard — `Array.isArray(products)`
945
- * on the TOP-LEVEL `products`; a 200 lacking it (partial / garbage / stub
946
- * `{ stub: true }`) returns null → `retryable`. An EMPTY
947
- * array is a VALID all-missed lookup (the products gate passes; `not_found`
948
- * carries the ids) — distinct from the no-array guard. The two structural deltas
949
- * from search:
950
- * - NO cursor hoist — lookup is a batch resolve, not a list (no `pagination`).
951
- * - `not_found` is parsed from the top-level `messages`: each
952
- * `{ code: 'not_found', content: <id> }` entry's `content` IS a missed request
953
- * id (server emits one per unresolved id, in input order, and OMITS `messages`
954
- * on full success). The `not_found` key is omitted here when there are no misses.
955
- *
956
- * Products unusable in lookup terms (no projectable featured variant, missing
957
- * `checkout_url`) are dropped via `projectLookupProduct` returning null, never
958
- * fabricated — same null-drop discipline as search.
959
- */
960
- function extractLookupResult(body) {
961
- const envelope = asRecord(body);
962
- if (envelope === null)
963
- return null;
964
- const rawProducts = envelope["products"];
965
- if (!Array.isArray(rawProducts))
966
- return null;
967
- const products = rawProducts
968
- .map(projectLookupProduct)
969
- .filter((p) => p !== null);
970
- const notFound = extractNotFound(envelope["messages"]);
971
- return notFound.length === 0 ? { products } : { products, not_found: notFound };
972
- }
973
- /** The closed spec value-types, the anti-false-green enum for a resolution's
974
- * `data_type` (the vocabulary `namespace`/`key` stay open). */
975
- const SPEC_DATA_TYPES = ["number", "text", "boolean", "enum"];
976
- function isSpecDataType(value) {
977
- return typeof value === "string" && SPEC_DATA_TYPES.includes(value);
978
- }
979
- /**
980
- * Narrow a sil-api spec-registry response body to the typed {@link SpecResolution}[],
981
- * or null if it carries no usable resolution array. sil-api emits a FLAT body:
982
- * `resolved` sits at the TOP LEVEL, there is NO `ucp` meta and NO `result` wrapper —
983
- * read it straight off the body.
984
- *
985
- * The load-bearing anti-false-green guard is `Array.isArray(resolved)` AND a
986
- * NON-EMPTY array. This is STRICTER than search's products gate: the server owes a
987
- * 1:1 resolution for every submitted spec, so there is NO valid empty-match — an
988
- * empty `resolved: []` is itself a malformed 200 and returns null → `retryable`.
989
- *
990
- * FAIL-WHOLE (design decision, product-owner AC1/AC9 "no partial adopt"): because
991
- * the method cannot adopt a canonical name it never got back, a SINGLE malformed
992
- * entry (missing/blank `canonical` ref, bad `status`, bad `data_type`, missing flag)
993
- * falls the WHOLE 200 to `retryable` — unlike search, which drops one unusable
994
- * product from a best-effort list. Every entry must project cleanly or none do.
995
- */
996
- function extractSpecsResult(body) {
997
- const envelope = asRecord(body);
998
- if (envelope === null)
999
- return null;
1000
- const rawResolved = envelope["resolved"];
1001
- if (!Array.isArray(rawResolved) || rawResolved.length === 0)
1002
- return null;
1003
- const resolved = [];
1004
- for (const raw of rawResolved) {
1005
- const one = projectResolution(raw);
1006
- if (one === null)
1007
- return null; // fail-whole: no half-canonical vocabulary
1008
- resolved.push(one);
1009
- }
1010
- return resolved;
1011
- }
1012
- /**
1013
- * Project ONE wire resolution to the typed {@link SpecResolution}, or null if any
1014
- * required field is malformed (fail-whole, per {@link extractSpecsResult}). Requires
1015
- * the flat canonical definition (`namespace`/`key`/`display_name` non-empty,
1016
- * `data_type` in the closed enum), the `submitted`/`canonical` refs, a valid
1017
- * `status`, and both boolean capability flags. Optional `description`/`unit`/
1018
- * `allowed_values` pass through when the right type. No `any`, no unchecked `as`.
1019
- */
1020
- function projectResolution(raw) {
1021
- const obj = asRecord(raw);
1022
- if (obj === null)
1023
- return null;
1024
- const namespace = obj["namespace"];
1025
- const key = obj["key"];
1026
- const displayName = obj["display_name"];
1027
- if (typeof namespace !== "string" || namespace.length === 0)
1028
- return null;
1029
- if (typeof key !== "string" || key.length === 0)
1030
- return null;
1031
- if (typeof displayName !== "string" || displayName.length === 0)
1032
- return null;
1033
- const dataType = obj["data_type"];
1034
- if (!isSpecDataType(dataType))
1035
- return null;
1036
- const submitted = extractSpecRef(obj["submitted"]);
1037
- const canonical = extractSpecRef(obj["canonical"]);
1038
- if (submitted === null || canonical === null)
1039
- return null;
1040
- const status = obj["status"];
1041
- if (status !== "matched" && status !== "created")
1042
- return null;
1043
- const isFilterable = obj["is_filterable"];
1044
- const isComparable = obj["is_comparable"];
1045
- if (typeof isFilterable !== "boolean" || typeof isComparable !== "boolean")
1046
- return null;
1047
- const result = {
1048
- namespace,
1049
- key,
1050
- display_name: displayName,
1051
- data_type: dataType,
1052
- submitted,
1053
- canonical,
1054
- status,
1055
- is_filterable: isFilterable,
1056
- is_comparable: isComparable,
1057
- };
1058
- const description = obj["description"];
1059
- if (typeof description === "string")
1060
- result.description = description;
1061
- const unit = obj["unit"];
1062
- if (typeof unit === "string")
1063
- result.unit = unit;
1064
- const allowedValues = obj["allowed_values"];
1065
- if (Array.isArray(allowedValues)) {
1066
- const values = allowedValues.filter((v) => typeof v === "string");
1067
- if (values.length > 0)
1068
- result.allowed_values = values;
1069
- }
1070
- return result;
1071
- }
1072
- /** Narrow a wire `{ namespace, key }` reference (the `submitted` / `canonical`
1073
- * fields), or null if either is missing/blank — the load-bearing gate a resolution
1074
- * needs so the method can adopt the canonical name. */
1075
- function extractSpecRef(raw) {
1076
- const obj = asRecord(raw);
1077
- if (obj === null)
1078
- return null;
1079
- const namespace = obj["namespace"];
1080
- const key = obj["key"];
1081
- if (typeof namespace !== "string" || namespace.length === 0)
1082
- return null;
1083
- if (typeof key !== "string" || key.length === 0)
1084
- return null;
1085
- return { namespace, key };
1086
- }
1087
- /**
1088
- * Project one `SilCatalogProduct` to the agent-facing {@link LookupProduct}, or
1089
- * null if it is unusable. RICHER than search's `projectProduct`: carries the
1090
- * product-level `description`, `price_range`, `categories?` and `handle?` (a lookup
1091
- * caller is making a purchase decision) plus the featured variant nested under
1092
- * `variant`. Picks the FIRST (featured) variant — `lookup_catalog` returns one
1093
- * featured variant per product; UCP: "Platforms SHOULD treat the first element as
1094
- * featured". A product whose featured variant has no non-empty `checkout_url`, or
1095
- * that is missing any required field, is dropped rather than surfaced as a
1096
- * non-purchasable result.
1097
- */
1098
- function projectLookupProduct(raw) {
1099
- const product = asRecord(raw);
1100
- if (product === null)
1101
- return null;
1102
- const id = product["id"];
1103
- const title = product["title"];
1104
- const source = product["source"];
1105
- if (typeof id !== "string" || id.length === 0)
1106
- return null;
1107
- if (typeof title !== "string")
1108
- return null;
1109
- if (typeof source !== "string" || source.length === 0)
1110
- return null;
1111
- const priceRange = product["price_range"];
1112
- if (asRecord(priceRange) === null)
1113
- return null;
1114
- const variants = product["variants"];
1115
- if (!Array.isArray(variants) || variants.length === 0)
1116
- return null;
1117
- const variant = projectLookupVariant(variants[0]);
1118
- if (variant === null)
1119
- return null;
1120
- const result = {
1121
- id,
1122
- title,
1123
- price_range: priceRange,
1124
- source,
1125
- variant,
1126
- };
1127
- const categories = passThroughObjects(product["categories"]);
1128
- if (categories !== null)
1129
- result.categories = categories;
1130
- const handle = product["handle"];
1131
- if (typeof handle === "string" && handle.length > 0)
1132
- result.handle = handle;
1133
- // `description` is now the `{ plain }` lift (ONE vocabulary with search), NOT the
1134
- // whole opaque object — omitted entirely when `plain` is absent/empty. Reuses the
1135
- // SAME product-enrichment attach as search so both tools surface the identical
1136
- // enriched shape (`url`/`description`/`media`/`options`/`metadata`).
1137
- attachProductEnrichment(result, product);
1138
- return result;
1139
- }
1140
- /**
1141
- * Project a `SilCatalogVariant` to the agent-facing {@link LookupVariant}, or null
1142
- * if it is not a usable purchasable variant. RICHER than search's `projectVariant`:
1143
- * adds `sku`, `options` (which configuration this variant is), and the lookup-only
1144
- * `inputs` correlation. Requires `id`, `title`, a price object, and a non-empty
1145
- * `checkout_url`; `price`/`availability` pass through opaque. Optional rich fields
1146
- * are omitted when absent rather than emitted as `undefined`.
1147
- */
1148
- function projectLookupVariant(raw) {
1149
- const variant = asRecord(raw);
1150
- if (variant === null)
1151
- return null;
1152
- const id = variant["id"];
1153
- const title = variant["title"];
1154
- const checkoutUrl = variant["checkout_url"];
1155
- if (typeof id !== "string" || id.length === 0)
1156
- return null;
1157
- if (typeof title !== "string")
1158
- return null;
1159
- if (typeof checkoutUrl !== "string" || checkoutUrl.length === 0)
1160
- return null;
1161
- const price = extractPrice(variant["price"]);
1162
- if (price === null)
1163
- return null;
1164
- const result = {
1165
- id,
1166
- title,
1167
- price,
1168
- availability: extractAvailability(variant["availability"]),
1169
- checkout_url: checkoutUrl,
1170
- };
1171
- const sku = variant["sku"];
1172
- if (typeof sku === "string" && sku.length > 0)
1173
- result.sku = sku;
1174
- const options = passThroughObjects(variant["options"]);
1175
- if (options !== null)
1176
- result.options = options;
1177
- const inputs = extractInputs(variant["inputs"]);
1178
- if (inputs !== null)
1179
- result.inputs = inputs;
1180
- // The SAME enriched per-variant surface as search (ONE vocabulary):
1181
- // `url`/`seller`/`media`/`metadata`, each only when present. The variant's
1182
- // `options` SELECTIONS above and these enriched fields are distinct, additive.
1183
- attachVariantEnrichment(result, variant);
1184
- return result;
1185
- }
1186
- /** Pass a wire array of objects through OPAQUE — filter to plain objects, preserve
1187
- * each verbatim, never read or remap individual fields. Used for `categories` and
1188
- * the variant's `options`: contextual display data the tool SURFACES but does not
1189
- * interpret (it is not a purchasability gate — that is `checkout_url`/`price`).
1190
- * Mirrors how identity `addresses` pass through (the wire field names — `value` vs
1191
- * `name` on a category — are the source's to define, not the tool's to assert).
1192
- * Returns null when the field is absent/non-array or yields no usable object, so
1193
- * the caller omits the key rather than emitting an empty array. */
1194
- function passThroughObjects(raw) {
1195
- if (!Array.isArray(raw))
1196
- return null;
1197
- const objects = raw.filter((o) => asRecord(o) !== null);
1198
- return objects.length === 0 ? null : objects;
1199
- }
1200
- /** Pass a single wire OBJECT through OPAQUE — forward it verbatim when it is a
1201
- * plain object, never reading or remapping individual fields. The single-object
1202
- * counterpart to {@link passThroughObjects}, for `seller` and `metadata`: contextual
1203
- * data the tool SURFACES but does not interpret. This is the load-bearing
1204
- * narrow-vs-pass-through guard ([[sil-shared-catalog-client]]) — a typed
1205
- * `{ name, links }` narrow on `seller` would silently DROP the Shopify extension
1206
- * keys (`seller.url`/`seller.domain`) the source attaches, and pass a naive fixture;
1207
- * opaque pass-through keeps both the base shape and any extension/drift. An ARRAY is
1208
- * NOT a usable object here (a `seller`/`metadata` that arrived as `[]` is garbage),
1209
- * so arrays return null and the caller omits the key. */
1210
- function passThroughObject(raw) {
1211
- return raw !== null && typeof raw === "object" && !Array.isArray(raw)
1212
- ? raw
1213
- : null;
1214
- }
1215
- /** Lift the agent-facing {@link ProductDescription} (`{ plain }`) from a wire
1216
- * `description` object, or null to OMIT. Surfaces ONLY the `plain` UCP format, and
1217
- * ONLY when it is a non-empty string — `html`/`markdown` are never substituted into
1218
- * `plain` (the spec flags `html` as untrusted rich text), and an absent/empty `plain`
1219
- * omits the whole `description` key. This is the one SCALAR read in the enriched
1220
- * surface (a stable, named UCP sub-field), and lifting it identically on both catalog
1221
- * tools is what keeps them on ONE `description` shape. */
1222
- function liftDescriptionPlain(raw) {
1223
- const obj = asRecord(raw);
1224
- if (obj === null)
1225
- return null;
1226
- const plain = obj["plain"];
1227
- return typeof plain === "string" && plain.length > 0 ? { plain } : null;
1228
- }
1229
- /** Attach the enriched PRODUCT surface (`url`/`description`/`media`/`options`/
1230
- * `metadata`) onto a projected product, each ONLY when present on the wire object.
1231
- * Shared verbatim by `projectProduct` (search) and `projectLookupProduct` (lookup)
1232
- * so BOTH tools surface the IDENTICAL enriched shape — the ONE-vocabulary property.
1233
- * Mutates `target` in place (it is a freshly-built projection the caller owns). Every
1234
- * field is OPAQUE pass-through keyed on PRESENCE; the only scalar read is
1235
- * `description.plain`. Omit-when-absent is per-field — an absent / empty-`plain` /
1236
- * no-`metadata` / all-garbage-array field leaves its key off entirely (no null/''/[]). */
1237
- function attachProductEnrichment(target, product) {
1238
- const url = product["url"];
1239
- if (typeof url === "string" && url.length > 0)
1240
- target.url = url;
1241
- const description = liftDescriptionPlain(product["description"]);
1242
- if (description !== null)
1243
- target.description = description;
1244
- const media = passThroughObjects(product["media"]);
1245
- if (media !== null)
1246
- target.media = media;
1247
- const options = passThroughObjects(product["options"]);
1248
- if (options !== null)
1249
- target.options = options;
1250
- const metadata = passThroughObject(product["metadata"]);
1251
- if (metadata !== null)
1252
- target.metadata = metadata;
1253
- }
1254
- /** Attach the enriched per-VARIANT surface (`url`/`seller`/`media`/`metadata`) onto a
1255
- * projected variant, each ONLY when present. Shared verbatim by `projectVariant`
1256
- * (search) and `projectLookupVariant` (lookup) — the variant half of the
1257
- * ONE-vocabulary property. `seller` (incl. `seller.links[]`) and `metadata` are
1258
- * single-object opaque pass-through; `media` is array pass-through. Same
1259
- * omit-when-absent, per-field, never-narrow discipline as the product surface. */
1260
- function attachVariantEnrichment(target, variant) {
1261
- const url = variant["url"];
1262
- if (typeof url === "string" && url.length > 0)
1263
- target.url = url;
1264
- const seller = passThroughObject(variant["seller"]);
1265
- if (seller !== null)
1266
- target.seller = seller;
1267
- const media = passThroughObjects(variant["media"]);
1268
- if (media !== null)
1269
- target.media = media;
1270
- const metadata = passThroughObject(variant["metadata"]);
1271
- if (metadata !== null)
1272
- target.metadata = metadata;
1273
- }
1274
- /** Narrow a wire `inputs` correlation array to {@link LookupInput}[] — each entry
1275
- * needs a non-empty `id` (the request id that resolved to this variant); a missing
1276
- * or non-string `match` is dropped (not coerced). Returns null when the field is
1277
- * absent or yields no usable entry, so the caller omits the key. Surfacing this is
1278
- * what makes a multi-id lookup correlatable — without it the agent cannot map "the
1279
- * id I asked about" to "the variant I got back". */
1280
- function extractInputs(raw) {
1281
- if (!Array.isArray(raw))
1282
- return null;
1283
- const inputs = raw
1284
- .map((i) => {
1285
- const obj = asRecord(i);
1286
- if (obj === null)
1287
- return null;
1288
- const id = obj["id"];
1289
- if (typeof id !== "string" || id.length === 0)
1290
- return null;
1291
- const match = obj["match"];
1292
- return typeof match === "string" ? { id, match } : { id };
1293
- })
1294
- .filter((i) => i !== null);
1295
- return inputs.length === 0 ? null : inputs;
1296
- }
1297
- /** Parse the missed request ids out of a wire `messages` array. Each
1298
- * `{ code: 'not_found', content: <id> }` info entry's `content` IS an unresolved
1299
- * id (sil-api emits one per miss, in input order; `messages` is OMITTED on full
1300
- * success). Returns the ids in order — an empty array when there are no misses
1301
- * (the caller then omits the `not_found` key). Only `not_found` codes are
1302
- * surfaced; any other message code (a future UCP `warning`/`delayed_fulfillment`)
1303
- * is ignored here — broader message passthrough is out of scope. */
1304
- function extractNotFound(raw) {
1305
- if (!Array.isArray(raw))
1306
- return [];
1307
- const ids = [];
1308
- for (const entry of raw) {
1309
- const obj = asRecord(entry);
1310
- if (obj === null)
1311
- continue;
1312
- if (obj["code"] !== "not_found")
1313
- continue;
1314
- const content = obj["content"];
1315
- if (typeof content === "string" && content.length > 0)
1316
- ids.push(content);
1317
- }
1318
- return ids;
1319
- }
1320
- /** Narrow a wire price (`{ amount: number, currency: string }`) — passed through
1321
- * opaque (extra fields preserved), or null if the two required fields are absent
1322
- * (an unpriced variant is not a usable purchasable result). */
1323
- function extractPrice(raw) {
1324
- const obj = asRecord(raw);
1325
- if (obj === null)
1326
- return null;
1327
- const amount = obj["amount"];
1328
- const currency = obj["currency"];
1329
- if (typeof amount !== "number" || typeof currency !== "string")
1330
- return null;
1331
- return { ...obj, amount, currency };
1332
- }
1333
- /** Narrow a wire availability object (`{ available?, status? }`) — passed through
1334
- * opaque (NOT flattened to a bare boolean; extra fields preserved). A missing or
1335
- * non-object availability yields an empty object (the agent reads no signal,
1336
- * rather than the tool inventing one). */
1337
- function extractAvailability(raw) {
1338
- const obj = asRecord(raw);
1339
- if (obj === null)
1340
- return {};
1341
- const result = { ...obj };
1342
- const available = obj["available"];
1343
- const status = obj["status"];
1344
- result.available = typeof available === "boolean" ? available : undefined;
1345
- result.status = typeof status === "string" ? status : undefined;
1346
- return result;
1347
- }
1348
- /** Hoist the opaque next-page cursor from a wire `pagination` object. Returns the
1349
- * cursor string ONLY when `has_next_page` is true AND a non-empty `cursor` is
1350
- * present; null otherwise (last page, or no pagination). End-of-results is the
1351
- * absent cursor — never `products.length === limit`. */
1352
- function extractCursor(raw) {
1353
- const obj = asRecord(raw);
1354
- if (obj === null)
1355
- return null;
1356
- if (obj["has_next_page"] !== true)
1357
- return null;
1358
- const cursor = obj["cursor"];
1359
- return typeof cursor === "string" && cursor.length > 0 ? cursor : null;
1360
- }
1361
486
  /**
1362
487
  * Build the `retryable` outcome for a non-200, non-{400,401} response, attaching
1363
488
  * the failed catalog `source` (+ a `detail` carrying the upstream cause) ONLY when
@@ -1365,7 +490,8 @@ function extractCursor(raw) {
1365
490
  *
1366
491
  * This is the seam where outcome (a) (sil/network down → bare retryable, generic
1367
492
  * copy) and outcome (b) (a named source down → source-named retryable) become
1368
- * distinguishable — see {@link SearchOutcome}. The gate is the PRESENCE of a real
493
+ * distinguishable — see {@link ShoppingOutcome}'s `retryable` arm. The gate is the
494
+ * PRESENCE of a real
1369
495
  * non-empty-string `source` field on the body, NEVER the `message` prose: a
1370
496
  * sil-internal 5xx (no `source`), a bodyless/garbage non-200, or a `source` that is
1371
497
  * null/number/empty/object/array all fall back to the bare sourceless retryable.
@@ -1392,9 +518,11 @@ function retryableFromBody(body) {
1392
518
  : source;
1393
519
  return { kind: "retryable", source, detail };
1394
520
  }
1395
- /** Pull sil-api's structured `{ error, message }` out of a 400 body, defaulting
1396
- * each field when the shape is unexpected so the agent always gets an actionable
1397
- * (if generic) hint rather than `undefined`. */
521
+ /** Pull sil-api's structured `{ error, message }` out of a refusal body, verbatim.
522
+ * Every v0 route names the offender in its own message by design, so the message
523
+ * is the agent's whole recourse and is never rewritten here — the defaults only
524
+ * cover a body that carried neither field, so the agent gets a sentence rather
525
+ * than `undefined`. */
1398
526
  function extractApiError(body) {
1399
527
  const obj = asRecord(body);
1400
528
  const error = obj?.["error"];
@@ -1403,7 +531,7 @@ function extractApiError(body) {
1403
531
  error: typeof error === "string" && error.length > 0 ? error : "invalid_request",
1404
532
  message: typeof message === "string" && message.length > 0
1405
533
  ? message
1406
- : "The search request was rejected. Provide a search query or at least one filter.",
534
+ : "sil rejected this request and gave no reason.",
1407
535
  };
1408
536
  }
1409
537
  /** Narrow the `user` field of a claim body to a typed identity. */
@@ -1418,18 +546,27 @@ function extractUser(raw) {
1418
546
  ...(typeof name === "string" ? { name } : {}),
1419
547
  };
1420
548
  }
1421
- /** A non-null plain object, or null for anything else (incl. arrays/primitives). */
549
+ /**
550
+ * A non-null plain object, or null for anything else (incl. arrays/primitives).
551
+ *
552
+ * The array arm decides an OUTCOME at exactly one site, and it is not a body gate:
553
+ * {@link extractIdentity} filters `addresses` through this PER ELEMENT, so the return
554
+ * value is membership rather than a branch — without the arm a bare array survives and
555
+ * ships as one of the buyer's own addresses (pinned in `whoami.integration.test.ts`).
556
+ * At the body sites it changes nothing, because each reads a named key and a parsed
557
+ * array has none; the element site is the whole reason it stays.
558
+ */
1422
559
  function asRecord(value) {
1423
- return value !== null && typeof value === "object"
560
+ return value !== null && typeof value === "object" && !Array.isArray(value)
1424
561
  ? value
1425
562
  : null;
1426
563
  }
1427
564
  /** POST a JSON body with a hard per-request timeout (AbortController). Extra
1428
565
  * headers (e.g. an Authorization bearer) merge over the JSON content-type; the
1429
566
  * header values are passed straight to fetch and never logged. */
1430
- async function postJson(url, body, extraHeaders) {
567
+ async function postJson(url, body, extraHeaders, timeoutMs = REQUEST_TIMEOUT_MS) {
1431
568
  const controller = new AbortController();
1432
- const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
569
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1433
570
  try {
1434
571
  return await fetch(url, {
1435
572
  method: "POST",
@@ -1448,9 +585,9 @@ async function postJson(url, body, extraHeaders) {
1448
585
  * and the sil-api self-read derives its principal from the Bearer JWT, not a
1449
586
  * body. Extra headers (e.g. an Authorization bearer) are passed straight to
1450
587
  * fetch and never logged. */
1451
- async function getJson(url, extraHeaders) {
588
+ async function getJson(url, extraHeaders, timeoutMs = REQUEST_TIMEOUT_MS) {
1452
589
  const controller = new AbortController();
1453
- const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
590
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1454
591
  try {
1455
592
  return await fetch(url, {
1456
593
  method: "GET",
@@ -1470,6 +607,8 @@ async function readJsonBody(res) {
1470
607
  return null;
1471
608
  }
1472
609
  }
1473
- function stripTrailingSlash(url) {
610
+ /** Every URL here is built by concatenation, so a configured origin with a
611
+ * trailing slash would emit a doubled `//` path the route does not match. */
612
+ export function stripTrailingSlash(url) {
1474
613
  return url.endsWith("/") ? url.slice(0, -1) : url;
1475
614
  }