sil-openclaw 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1033 @@
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.
6
+ *
7
+ * Wire contract (pinned to the already-merged sil-web routes —
8
+ * sil-services/apps/sil-web/src/app/api/v1/...):
9
+ *
10
+ * POST /api/v1/sessions/{id}/claim body { code_verifier }
11
+ * 200 { access_token, refresh_token, user:{id} } → success (EXACTLY once)
12
+ * 200 { status: "pending" } → pending
13
+ * 409 → already_claimed
14
+ * 410 → expired
15
+ * 404 → not_found (wrong verifier
16
+ * ≡ unknown session, uniform)
17
+ * 5xx / network / abort → retryable
18
+ *
19
+ * POST /api/v1/auth/refresh body { refresh_token }
20
+ * 200 { access_token, refresh_token, ... } → refreshed
21
+ * 401 → invalid_grant (terminal)
22
+ * 5xx / network / abort → retryable
23
+ *
24
+ * Wire contract for the sil-API identity read (a SECOND origin — sil-api, the
25
+ * Fastify domain service — NOT sil-web; bare path, not /api/v1; see the
26
+ * sil-whoami card). The authenticated self-read is a BODYLESS GET; the
27
+ * Authorization header carries the stored access token and IS the principal —
28
+ * sil-api derives the user from the JWT `sub`, not a request body:
29
+ *
30
+ * GET <silApiUrl>/identity Authorization: Bearer <access_token>
31
+ * (no body, no content-type)
32
+ * 200 <UCP envelope>{ result: { name, addresses } } → ok (carries identity)
33
+ * 401 → unauthorized (→ refresh)
34
+ * 403 { error: user_not_provisioned | principal_mismatch } → forbidden (terminal)
35
+ * 5xx / network / abort → retryable
36
+ *
37
+ * Wire contract for the sil-API catalog search (SAME origin as the identity
38
+ * read — sil-api, bare path, NOT /api/v1; see the sil-search card). A simplified
39
+ * structured query in, ranked purchasable products out. sil-api owns the UCP
40
+ * envelope + enrichment; the plugin sends NO envelope and fills NO defaults:
41
+ *
42
+ * POST <silApiUrl>/catalog/search Authorization: Bearer <access_token>
43
+ * body { query?, filters?:{ categories?, price?:{ min?, max? } },
44
+ * pagination?:{ cursor?, limit? } } (no context, no envelope)
45
+ * 200 <FLAT UCP envelope>{ ucp, products: SilCatalogProduct[],
46
+ * pagination?:{ has_next_page, cursor? } } → ok
47
+ * (sil-api's `withUcpMeta(body) → { ucp, ...body }`: `products`/`pagination`
48
+ * at the TOP LEVEL beside `ucp`, NO `result` wrapper)
49
+ * 400 { error:"empty_search_input", message } → invalid_request
50
+ * 401 → unauthorized (→ refresh)
51
+ * 5xx / network / abort → retryable
52
+ *
53
+ * Wire contract for the sil-API catalog LOOKUP (SAME origin/path style as search —
54
+ * sil-api, bare `/catalog/lookup`, NOT /api/v1; see the sil-product-get card). The
55
+ * lookup COMPANION to search: an agent passes ids it already holds and gets fresh
56
+ * RICH detail back (search is LEAN). sil-api owns enrichment + the `not_found`
57
+ * messaging + the envelope; the plugin sends just `{ ids }` (NO filters/context,
58
+ * NO envelope). The two structural deltas from search's response: NO `pagination`
59
+ * (a batch resolve, not a list) and a `messages[]` carrying the misses:
60
+ *
61
+ * POST <silApiUrl>/catalog/lookup Authorization: Bearer <access_token>
62
+ * body { ids: string[] } (≥1; no filters/context)
63
+ * 200 <FLAT UCP envelope>{ ucp, products: SilCatalogProduct[],
64
+ * messages?:[{ type:"info", code:"not_found", content:<id> }] } → ok
65
+ * (same flat `withUcpMeta` shape: `products`/`messages` at the TOP LEVEL
66
+ * beside `ucp`, NO `result` wrapper)
67
+ * 400 (schema: empty `ids` / request_too_large) → invalid_request
68
+ * 401 → unauthorized (→ refresh)
69
+ * 5xx / network / abort → retryable
70
+ *
71
+ * A lookup MISS is partial-SUCCESS data, NEVER an error: an unresolved id is a
72
+ * `not_found` info `message` (the server omits `messages` entirely on full
73
+ * success), surfaced on the `ok` outcome as a `not_found: string[]`. Each looked-up
74
+ * variant carries an `inputs:[{ id, match }]` correlation (lookup's defining
75
+ * feature over search — the response does NOT preserve request order and one id
76
+ * may resolve to a variant of another id's product, so `inputs` is the only way to
77
+ * map a request id to its result). `classifyLookupResponse` gates `ok` on a real
78
+ * `Array.isArray(products)` on the FLAT envelope's top-level `products` — a 200
79
+ * with no usable products array is `retryable`, NEVER a false-green; a genuine
80
+ * ALL-MISSED lookup is a 200 whose top-level `products` IS `[]` WITH a populated
81
+ * `not_found` → `ok` (success: "none of these exist anymore"), the discriminator
82
+ * being array PRESENCE, never length.
83
+ *
84
+ * `SilCatalogProduct` = a UCP product PLUS a required `source`; each variant PLUS
85
+ * a required non-empty `checkout_url` (sil-services `@sil/schemas` catalog.ts —
86
+ * the byte-shape of truth; `@ucp-js/sdk` carries ZERO catalog types). The plugin
87
+ * does NOT depend on `@sil/schemas` (cross-repo): it re-declares the read-subset
88
+ * it consumes locally (the `Search*` types below) and narrows the untrusted body
89
+ * defensively in `extractSearchResult`. The tool reads `products` straight off the
90
+ * FLAT envelope's top level (NO `result` unwrap — search/lookup are always flat,
91
+ * only the identity read carries the `result ?? envelope` dual shape), picks the
92
+ * FIRST (featured) variant per product (UCP: "Platforms SHOULD treat the first
93
+ * element as featured"), projects each to the product-level `{ id, title, source }`
94
+ * plus the nested featured `variant` `{ id, title, price, availability,
95
+ * checkout_url }`, and hoists the top-level `pagination.cursor` to a top-level
96
+ * cursor (present iff `has_next_page`). `classifySearchResponse` gates `ok` on a
97
+ * real `Array.isArray(products)` over that top-level `products` — a 200 with no
98
+ * usable products array is `retryable`, NEVER a false-green empty match (the same
99
+ * anti-false-green guard as the identity `name`-gate). A genuine empty match is a
100
+ * 200 whose top-level `products` IS an empty array → `ok` + `products: []`
101
+ * (success, not an error — UCP: "empty search returns an empty array … this is not
102
+ * an error").
103
+ *
104
+ * The VERB is load-bearing: sil-api's `POST /identity` is the agent enrich-STUB
105
+ * ({kind, verified, subject, ...} — no name/addresses); `GET /identity` is the
106
+ * real self-read returning {id, name, addresses} (sil-api `handlers/identity.ts`,
107
+ * PR #7). The identity lives in the envelope's `result` (the tool unwraps it so
108
+ * the agent sees identity, not transport metadata). `classifyIdentityResponse`
109
+ * still narrows DEFENSIVELY — a 200 whose result has no usable identity (no
110
+ * `name`) falls to `retryable`, NEVER to a false `ok`, so a stray stub 200 (or a
111
+ * malformed body) can't be green while the product promise is unmet. An EMPTY
112
+ * `addresses: []` IS a valid identity (a provisioned, address-less user).
113
+ *
114
+ * THE subtle correctness point (architect Risk "claim taxonomy mis-mapping"):
115
+ * 200-pending and 200-success are BOTH HTTP 200. `classifyClaimResponse` branches
116
+ * on the BODY SHAPE (both tokens present) — never on `res.ok` — so "keep polling"
117
+ * is never conflated with "success". A malformed/partial 200 falls to the SAFE
118
+ * non-terminal `pending` path, never to a false success that would persist a
119
+ * non-credential as tokens. The classifier is exported and pure so it can be
120
+ * unit-tested in isolation, since misclassifying two 200s is the highest-risk
121
+ * subtle bug in the whole flow.
122
+ *
123
+ * Tokens never appear in a log line here (mirrors sil-web's invariant) — they
124
+ * only travel inside the returned union variant.
125
+ *
126
+ * node:fetch (global) only; no dependency.
127
+ */
128
+ import { getWebUrl } from "./config.js";
129
+ import { readTokens, writeTokens } from "./credentials.js";
130
+ /** Per-request timeout: a stalled endpoint (DNS hang, SYN drop) must not wedge
131
+ * a poll tick forever. Mirrors the 15s ceiling the klodi poller uses. */
132
+ const REQUEST_TIMEOUT_MS = 15_000;
133
+ /**
134
+ * Classify a claim response from its HTTP status AND body. The discriminant for
135
+ * the two-200s split is the PRESENCE OF BOTH TOKENS in the body — never the
136
+ * status code. A 200 that is not a complete token pair is `pending` (the safe
137
+ * non-terminal landing); 409/410/404 are distinct terminals; 5xx is retryable.
138
+ *
139
+ * Pure and exported — this is the highest-risk subtle branch, unit-tested in
140
+ * isolation (sil-client.test.ts).
141
+ */
142
+ export function classifyClaimResponse(status, body) {
143
+ if (status === 409)
144
+ return { kind: "already_claimed" };
145
+ if (status === 410)
146
+ return { kind: "expired" };
147
+ if (status === 404)
148
+ return { kind: "not_found" };
149
+ if (status >= 500)
150
+ return { kind: "retryable" };
151
+ if (status !== 200) {
152
+ // 400 (malformed request) or any other unexpected 4xx: terminal not_found
153
+ // (re-polling can't fix a bad request); surface a re-run hint, not a spin.
154
+ return { kind: "not_found" };
155
+ }
156
+ // 200 — classify by body shape. Both tokens required for a clean success;
157
+ // anything short of that is the safe non-terminal `pending`.
158
+ const obj = asRecord(body);
159
+ if (obj === null)
160
+ return { kind: "pending" };
161
+ const accessToken = obj["access_token"];
162
+ const refreshToken = obj["refresh_token"];
163
+ if (typeof accessToken === "string" && typeof refreshToken === "string") {
164
+ return {
165
+ kind: "success",
166
+ access_token: accessToken,
167
+ refresh_token: refreshToken,
168
+ user: extractUser(obj["user"]),
169
+ };
170
+ }
171
+ return { kind: "pending" };
172
+ }
173
+ /**
174
+ * Classify a refresh response. 200 with both tokens → refreshed; 401 → terminal
175
+ * invalid_grant ("must re-register"); 5xx / other → retryable.
176
+ */
177
+ export function classifyRefreshResponse(status, body) {
178
+ if (status === 401)
179
+ return { kind: "invalid_grant" };
180
+ if (status >= 500)
181
+ return { kind: "retryable" };
182
+ if (status !== 200)
183
+ return { kind: "invalid_grant" };
184
+ const obj = asRecord(body);
185
+ const accessToken = obj?.["access_token"];
186
+ const refreshToken = obj?.["refresh_token"];
187
+ if (typeof accessToken === "string" && typeof refreshToken === "string") {
188
+ return { kind: "refreshed", access_token: accessToken, refresh_token: refreshToken };
189
+ }
190
+ return { kind: "retryable" };
191
+ }
192
+ /**
193
+ * Classify a sil-api identity response from its HTTP status AND body. Branches
194
+ * on STATUS (and, for 200, the body shape) — never on `res.ok`:
195
+ * 401 → unauthorized (the ONLY refresh trigger)
196
+ * 403 → forbidden (terminal; carries user_not_provisioned/principal_mismatch)
197
+ * 5xx / non-200 → retryable
198
+ * 200 → unwrap the envelope `result` and narrow to {name, addresses}; a 200
199
+ * that yields no usable identity (no `name`) is `retryable`, NEVER `ok`
200
+ * (the anti-false-green guard — a partial/garbage 200, or the current
201
+ * /identity STUB shape with no name, must not read as success).
202
+ *
203
+ * Pure and exported — unit-tested in isolation like `classifyClaimResponse`;
204
+ * mis-splitting 401 (refreshable) from 403 (terminal) is the highest-risk
205
+ * auth-branch bug in this flow.
206
+ */
207
+ export function classifyIdentityResponse(status, body) {
208
+ if (status === 401)
209
+ return { kind: "unauthorized" };
210
+ if (status === 403)
211
+ return { kind: "forbidden", reason: extractForbiddenReason(body) };
212
+ if (status >= 500)
213
+ return { kind: "retryable" };
214
+ if (status !== 200)
215
+ return { kind: "retryable" };
216
+ const identity = extractIdentity(body);
217
+ if (identity === null)
218
+ return { kind: "retryable" };
219
+ return { kind: "ok", identity };
220
+ }
221
+ /**
222
+ * Classify a sil-api catalog-search response from its HTTP status AND body.
223
+ * Branches on STATUS (and, for 200, the body shape) — never on `res.ok`:
224
+ * 400 → invalid_request (surface sil-api's structured `{ error, message }`,
225
+ * e.g. `empty_search_input` — distinct from both the empty-match success
226
+ * and a transient failure; the agent must learn to fix its query, not
227
+ * retry or re-register)
228
+ * 401 → unauthorized (the refresh trigger — the caller drives transparent
229
+ * refresh-and-retry-once via `refreshAndRetryOnce`, not terminal)
230
+ * 5xx / other non-200 → retryable
231
+ * 200 → read `products` off sil-api's FLAT envelope (`{ ucp, products,
232
+ * pagination? }` — top level, no `result` wrapper), normalize, and require
233
+ * `products` to be a real ARRAY. A 200 that yields no usable top-level
234
+ * products array (a partial / garbage / stub-shaped body, or one carrying
235
+ * only `ucp` metadata) is `retryable`, NEVER `ok` — the
236
+ * `Array.isArray(products)` gate is the anti-false-green guard, the
237
+ * analogue of the identity `name`-gate. A genuine empty match (200 whose
238
+ * top-level `products` IS `[]`) is `ok` with an empty product list: a
239
+ * SUCCESS, distinct from the no-array guard.
240
+ *
241
+ * Pure and exported — unit-tested in isolation like `classifyIdentityResponse`;
242
+ * conflating the empty-match success with a partial-200 false-green, or with the
243
+ * 400/401/5xx error classes, is the highest-risk subtle bug in this flow.
244
+ */
245
+ export function classifySearchResponse(status, body) {
246
+ if (status === 400) {
247
+ const { error, message } = extractApiError(body);
248
+ return { kind: "invalid_request", error, message };
249
+ }
250
+ if (status === 401)
251
+ return { kind: "unauthorized" };
252
+ if (status !== 200)
253
+ return { kind: "retryable" };
254
+ const result = extractSearchResult(body);
255
+ if (result === null)
256
+ return { kind: "retryable" };
257
+ return { kind: "ok", ...result };
258
+ }
259
+ /**
260
+ * Classify a sil-api catalog-LOOKUP response from its HTTP status AND body.
261
+ * Branches on STATUS (and, for 200, the body shape) — never on `res.ok`. The
262
+ * SAME class structure as `classifySearchResponse` (so the two catalog tools
263
+ * share one error vocabulary), minus search's `empty_search_input` subtlety:
264
+ * 400 → invalid_request (a SCHEMA-validation 400 — an empty/missing `ids`
265
+ * rejected by `CatalogLookupRequest.ids` `minItems:1`, or a
266
+ * `request_too_large` over-batch — surface the server's `{ error,
267
+ * message }`. NOTE: this is NOT search's `empty_search_input` SourceError,
268
+ * which never arises on the lookup route; do not special-case it.)
269
+ * 401 → unauthorized (the refresh trigger — the caller drives transparent
270
+ * refresh-and-retry-once via `refreshAndRetryOnce`, parity with search)
271
+ * 5xx / other non-200 → retryable
272
+ * 200 → read `products` off sil-api's FLAT envelope (`{ ucp, products,
273
+ * messages? }` — top level, no `result` wrapper), normalize, and require
274
+ * `products` to be a real ARRAY. A 200 that yields no usable top-level
275
+ * products array (a partial / garbage / stub-shaped body) is `retryable`,
276
+ * NEVER `ok` — the `Array.isArray(products)` gate is the anti-false-green
277
+ * guard, the analogue of the identity `name`-gate and search's
278
+ * products-array gate.
279
+ *
280
+ * THE subtle correctness point: an all-MISSED lookup is a genuine SUCCESS — a 200
281
+ * whose top-level `products` IS an empty array WITH a populated `not_found` list
282
+ * ("none of these ids exist anymore"). It is `ok` with empty `products` + full
283
+ * `not_found`, distinct from the no-array guard above. The discriminator between
284
+ * "valid all-missed" and "garbage 200" is the `products`-array PRESENCE, NEVER
285
+ * array length — exactly as search distinguishes empty-match from a partial-200
286
+ * false-green.
287
+ *
288
+ * Pure and exported — unit-tested in isolation like `classifySearchResponse`.
289
+ */
290
+ export function classifyLookupResponse(status, body) {
291
+ if (status === 400) {
292
+ const { error, message } = extractApiError(body);
293
+ return { kind: "invalid_request", error, message };
294
+ }
295
+ if (status === 401)
296
+ return { kind: "unauthorized" };
297
+ if (status !== 200)
298
+ return { kind: "retryable" };
299
+ const result = extractLookupResult(body);
300
+ if (result === null)
301
+ return { kind: "retryable" };
302
+ return { kind: "ok", ...result };
303
+ }
304
+ /**
305
+ * Attempt to claim the token pair for `sessionId` with `verifier`. The verifier
306
+ * is sent in the body; sil-web derives the same challenge server-side and the
307
+ * CAS compares digest-to-digest (the plugin sends the verifier, not the digest).
308
+ * A network error / timeout maps to `retryable` so the poll budget governs.
309
+ */
310
+ export async function claimSession(apiUrl, sessionId, verifier) {
311
+ const url = `${stripTrailingSlash(apiUrl)}/api/v1/sessions/${sessionId}/claim`;
312
+ let res;
313
+ try {
314
+ res = await postJson(url, { code_verifier: verifier });
315
+ }
316
+ catch {
317
+ return { kind: "retryable" };
318
+ }
319
+ const body = await readJsonBody(res);
320
+ return classifyClaimResponse(res.status, body);
321
+ }
322
+ /**
323
+ * Refresh the bearer pair via sil-web (NEVER Auth0 directly — sil-web is the
324
+ * sole auth authority and the only holder of the Auth0 client secret).
325
+ */
326
+ export async function refreshSession(apiUrl, refreshToken) {
327
+ const url = `${stripTrailingSlash(apiUrl)}/api/v1/auth/refresh`;
328
+ let res;
329
+ try {
330
+ res = await postJson(url, { refresh_token: refreshToken });
331
+ }
332
+ catch {
333
+ return { kind: "retryable" };
334
+ }
335
+ const body = await readJsonBody(res);
336
+ return classifyRefreshResponse(res.status, body);
337
+ }
338
+ /**
339
+ * Read the authenticated user's identity from sil-api (the SECOND origin — the
340
+ * Fastify domain service, NOT sil-web). This is a bodyless `GET <silApiUrl>/identity`:
341
+ * sil-api's authenticated self-read derives the principal from the JWT `sub`
342
+ * (the `Authorization: Bearer <token>` header), loads that user's addresses,
343
+ * and returns `{ id, name, addresses }` in the UCP envelope's `result`
344
+ * (sil-api `handlers/identity.ts` GET route — declares only a response schema,
345
+ * takes no request body). The verb is the whole point: POST hits the agent
346
+ * enrich-STUB (no name/addresses), GET hits the real self-read. No `agent_id`
347
+ * or `on_behalf_of` is sent — the GET self-read has no body, so the principal
348
+ * is unambiguously the token subject and the `principal_mismatch` 403 path is
349
+ * eliminated entirely. A network error / timeout → `retryable`.
350
+ *
351
+ * The Bearer header is built HERE and never logged; the token travels only in
352
+ * the outbound request, never into the returned union.
353
+ */
354
+ export async function fetchIdentity(silApiUrl, token) {
355
+ const url = `${stripTrailingSlash(silApiUrl)}/identity`;
356
+ let res;
357
+ try {
358
+ res = await getJson(url, { authorization: `Bearer ${token}` });
359
+ }
360
+ catch {
361
+ return { kind: "retryable" };
362
+ }
363
+ const body = await readJsonBody(res);
364
+ return classifyIdentityResponse(res.status, body);
365
+ }
366
+ /**
367
+ * Run a catalog search against sil-api (the SAME origin as the identity read —
368
+ * NOT sil-web; bare `/catalog/search`, no `/api/v1`). The simplified
369
+ * {@link SearchParams} are mapped into the sil-api `CatalogSearchRequest` body
370
+ * (`{ query?, filters:{ categories?, price:{ min?, max? } }, pagination:{ cursor?, limit? } }`)
371
+ * — building NO UCP envelope and filling NO defaults the agent did not supply.
372
+ * Only the keys the agent actually provided are emitted (an absent filter is an
373
+ * omitted key, not an empty object), so a free-text-only query sends just
374
+ * `{ query }` and sil-api applies its own context resolution.
375
+ *
376
+ * The Bearer header is built HERE and never logged; the token travels only in
377
+ * the outbound request, never into the returned union. A network error / timeout
378
+ * maps to `retryable`.
379
+ */
380
+ export async function searchCatalog(silApiUrl, token, params) {
381
+ const url = `${stripTrailingSlash(silApiUrl)}/catalog/search`;
382
+ let res;
383
+ try {
384
+ res = await postJson(url, buildSearchBody(params), {
385
+ authorization: `Bearer ${token}`,
386
+ });
387
+ }
388
+ catch {
389
+ return { kind: "retryable" };
390
+ }
391
+ const body = await readJsonBody(res);
392
+ return classifySearchResponse(res.status, body);
393
+ }
394
+ /**
395
+ * Resolve catalog ids against sil-api (the SAME origin as the identity read and
396
+ * `searchCatalog` — NOT sil-web; bare `/catalog/lookup`, no `/api/v1`). The agent
397
+ * already holds the ids (from a prior `sil_search`, a saved list, or cart
398
+ * validation); this re-fetches CURRENT detail for them — building NO UCP envelope
399
+ * and filling NO defaults. The body is just `{ ids }` (the simplified contract;
400
+ * `filters`/`context` are sil-api options this tool does not expose). The ids are
401
+ * forwarded AS GIVEN — sil-api owns dedup (its seam already dedups) and any batch
402
+ * cap; the tool does not pre-dedup (which would mask a seam regression).
403
+ *
404
+ * The Bearer header is built HERE and never logged; the token travels only in the
405
+ * outbound request, never into the returned union. A network error / timeout maps
406
+ * to `retryable`.
407
+ */
408
+ export async function lookupCatalog(silApiUrl, token, ids) {
409
+ const url = `${stripTrailingSlash(silApiUrl)}/catalog/lookup`;
410
+ let res;
411
+ try {
412
+ res = await postJson(url, { ids }, { authorization: `Bearer ${token}` });
413
+ }
414
+ catch {
415
+ return { kind: "retryable" };
416
+ }
417
+ const body = await readJsonBody(res);
418
+ return classifyLookupResponse(res.status, body);
419
+ }
420
+ /**
421
+ * SC7/F7 entry point: read the stored refresh token, exchange it via sil-web,
422
+ * and rotate `tokens.json` with the new pair on success.
423
+ *
424
+ * Contacts ONLY the resolved `sil_web_url` origin — sil-web is the sole auth
425
+ * authority; the plugin never talks to Auth0 directly (sil-web holds the Auth0
426
+ * client secret). On a 401 the refresh token is dead: return a terminal
427
+ * "must re-register" signal and DO NOT rotate (a rejected refresh must never be
428
+ * presented as a fresh, valid pair). A 5xx / network blip is retryable.
429
+ */
430
+ export async function refreshStoredTokens() {
431
+ const stored = readTokens();
432
+ if (stored === null) {
433
+ return { status: "must_reregister", reason: "no_stored_tokens" };
434
+ }
435
+ const outcome = await refreshSession(getWebUrl(), stored.refresh_token);
436
+ switch (outcome.kind) {
437
+ case "refreshed":
438
+ await writeTokens({
439
+ access_token: outcome.access_token,
440
+ refresh_token: outcome.refresh_token,
441
+ });
442
+ return { status: "refreshed" };
443
+ case "invalid_grant":
444
+ return { status: "must_reregister", reason: "invalid_grant" };
445
+ case "retryable":
446
+ return { status: "retryable" };
447
+ }
448
+ }
449
+ /**
450
+ * THE single 401 refresh-and-retry-once choreography, shared by every
451
+ * sil-api-calling tool (`sil_search`, `sil_product_get`, `sil_whoami`) so the 401
452
+ * behaviour cannot drift apart between them (FLAG-10). The control flow IS the
453
+ * contract — straight-line, AT MOST one refresh + AT MOST one retry, no loop:
454
+ *
455
+ * 1. `first` not unauthorized → passthrough `{ result, first }`. The
456
+ * refresh path is reachable ONLY via a 401.
457
+ * 2. `first` unauthorized → refresh ONCE via {@link refreshStoredTokens} (sil-web;
458
+ * rotates tokens.json):
459
+ * must_reregister (invalid_grant / → terminal, NO retry (a failed refresh
460
+ * no_stored_tokens) leaves no rotated token to retry with).
461
+ * retryable (5xx/network) → transient, NO retry.
462
+ * refreshed → re-read the rotated pair THROUGH the
463
+ * module's `readTokens` (so a TOCTOU on
464
+ * the on-disk pair is observed):
465
+ * re-read empty (TOCTOU) → must_reregister(no_stored_tokens), NO retry.
466
+ * re-read ok → retry ONCE with the rotated access token:
467
+ * retry still unauthorized → second_unauthorized (the rotated token is
468
+ * structurally dead — NEVER refresh again).
469
+ * retry otherwise → `{ result, retry }`.
470
+ *
471
+ * The helper owns the bound, the rotation re-read, and the TOCTOU + second-401
472
+ * guards. The caller owns ONLY: the `isUnauthorized` predicate, the token-bearing
473
+ * `retryWithToken` thunk (closing over its params + the rotated token), the
474
+ * envelope mapping, `clearTokens()` on the clearing terminals, and logging.
475
+ * Credential side-effects beyond the rotation `refreshStoredTokens` already does
476
+ * stay at the call site (mirrors `identity.ts`).
477
+ */
478
+ export async function refreshAndRetryOnce(first, isUnauthorized, retryWithToken) {
479
+ if (!isUnauthorized(first)) {
480
+ // First-try passthrough: no refresh happened, so the caller must NOT emit its
481
+ // `<tool>_refreshed` marker. `refreshed: false` is the negative half of the
482
+ // observability discriminant.
483
+ return { kind: "result", outcome: first, refreshed: false };
484
+ }
485
+ const refresh = await refreshStoredTokens();
486
+ if (refresh.status === "must_reregister") {
487
+ return { kind: "must_reregister", reason: refresh.reason };
488
+ }
489
+ if (refresh.status === "retryable") {
490
+ return { kind: "retryable" };
491
+ }
492
+ // refresh.status === "refreshed" — re-read the rotated pair through the module
493
+ // binding (the TOCTOU seam: tokens.json may have vanished between the rotate
494
+ // inside refreshStoredTokens and this read).
495
+ const rotated = readTokens();
496
+ if (rotated === null) {
497
+ return { kind: "must_reregister", reason: "no_stored_tokens" };
498
+ }
499
+ const retry = await retryWithToken(rotated.access_token);
500
+ if (isUnauthorized(retry)) {
501
+ // A freshly-rotated token STILL rejected is structurally dead — terminal,
502
+ // never another refresh cycle.
503
+ return { kind: "second_unauthorized" };
504
+ }
505
+ // Silent-recovery success: this outcome was produced via refresh+retry, so the
506
+ // caller emits its `<tool>_refreshed` operator marker. `refreshed: true` is the
507
+ // positive half of the observability discriminant — logs-only, never a payload field.
508
+ return { kind: "result", outcome: retry, refreshed: true };
509
+ }
510
+ /**
511
+ * Unwrap + narrow a sil-api identity response body to a typed `Identity`, or
512
+ * null if it carries no usable identity. Defends against the latent wire shape:
513
+ * the identity may be wrapped in the UCP envelope's `result` OR (if the
514
+ * follow-on returns it bare) at the top level, so we try `result` first and
515
+ * fall back to the body itself.
516
+ *
517
+ * A usable identity REQUIRES a non-empty `name` string (the authoritative human
518
+ * name) and that `addresses` is an ARRAY — but the array may be EMPTY. sil-api
519
+ * returns `addresses: []` for a provisioned user who has onboarded a name but
520
+ * not yet added an address (`handlers/identity.ts` → `buildIdentityReadResult`);
521
+ * that is a real, authenticated identity, NOT a not-yet-ready read. Rejecting it
522
+ * would strand such a user on a false `retryable` they could never escape by
523
+ * retrying. The `name` gate is the load-bearing anti-false-green guard: the
524
+ * current /identity STUB shape ({kind, verified, subject, ...}) has NO name, so
525
+ * it still returns null → `retryable`, never a false `ok`. Extra fields on each
526
+ * address are preserved (addresses pass through opaque — see `IdentityAddress`).
527
+ */
528
+ function extractIdentity(body) {
529
+ const envelope = asRecord(body);
530
+ if (envelope === null)
531
+ return null;
532
+ const result = asRecord(envelope["result"]);
533
+ const source = result ?? envelope;
534
+ const name = source["name"];
535
+ if (typeof name !== "string" || name.length === 0)
536
+ return null;
537
+ const rawAddresses = source["addresses"];
538
+ if (!Array.isArray(rawAddresses))
539
+ return null;
540
+ const addresses = rawAddresses.filter((a) => asRecord(a) !== null);
541
+ return { name, addresses };
542
+ }
543
+ /** Pull the actionable reason out of a 403 body (`user_not_provisioned` /
544
+ * `principal_mismatch`), defaulting to a generic marker when the shape is
545
+ * unexpected — the tool surfaces this to drive the right recovery hint. */
546
+ function extractForbiddenReason(body) {
547
+ const obj = asRecord(body);
548
+ const error = obj?.["error"];
549
+ return typeof error === "string" && error.length > 0 ? error : "forbidden";
550
+ }
551
+ /**
552
+ * Map the simplified {@link SearchParams} into the sil-api `CatalogSearchRequest`
553
+ * body. Only keys the agent supplied are emitted — an absent filter is an OMITTED
554
+ * key (sil-api's body is `additionalProperties: false`, but every field is
555
+ * optional), never an empty `{}`. The singular `category` maps into the UCP
556
+ * `filters.categories` ARRAY (sil-api's filter is multi-taxonomy; the simplified
557
+ * contract takes one). `price_min`/`price_max` map into `filters.price.{min,max}`.
558
+ * The tool clamps nothing and validates no cursor opacity — sil-api owns those.
559
+ *
560
+ * THE load-bearing rename: the agent arg `ship_to` (singular) becomes the wire key
561
+ * `filters.ships_to` (plural). `ships_from`/`condition`/`available` keep their name
562
+ * under `filters.*`. These four ride sil-api's OPEN `SearchFilters`
563
+ * (`additionalProperties: true`), which SILENTLY accepts an unknown key — so the
564
+ * exact emitted key name is the only thing standing between a working serviceability
565
+ * filter and a no-op (a wrong rename fails GREEN). Each is forwarded ONLY when
566
+ * supplied (omit-when-absent, identical to `category`/`price`/`pagination`); NO
567
+ * client-injected default (the server applies `available: true`). A supplied
568
+ * `available: false` is narrowed with `typeof === "boolean"`, never `if (v)`, so the
569
+ * meaningful `false` (include unavailable items) survives.
570
+ *
571
+ * COUNTRY-CASE NORMALIZATION is the wire layer's job (the read site owns FORMAT
572
+ * rejection): `ships_to.country` and `ships_from.country` are emitted UPPERCASE
573
+ * (`us` → `US`), the alpha-2 contract `@sil/schemas` `ShipTo`/`ShipFrom` mirrors
574
+ * byte-for-byte. A lowercase code on the wire would diverge from the sibling and
575
+ * (depending on the server's case-sensitivity) silently mis-filter. `region` and
576
+ * `postal_code` are forwarded VERBATIM — they passed their pattern at the read site,
577
+ * and the wire normalizes only country case.
578
+ */
579
+ function buildSearchBody(params) {
580
+ const body = {};
581
+ if (typeof params.query === "string")
582
+ body["query"] = params.query;
583
+ const filters = {};
584
+ if (typeof params.category === "string") {
585
+ filters["categories"] = [params.category];
586
+ }
587
+ const price = {};
588
+ if (typeof params.price_min === "number")
589
+ price["min"] = params.price_min;
590
+ if (typeof params.price_max === "number")
591
+ price["max"] = params.price_max;
592
+ if (Object.keys(price).length > 0)
593
+ filters["price"] = price;
594
+ // The four serviceability/localization filters — the `ship_to` → `ships_to`
595
+ // rename happens here; the other three keep their name. Country is uppercased
596
+ // on emit (region/postal forwarded verbatim); the other three pass through as-is.
597
+ if (params.ship_to !== undefined)
598
+ filters["ships_to"] = withUppercaseCountry(params.ship_to);
599
+ if (params.ships_from !== undefined) {
600
+ filters["ships_from"] = withUppercaseCountry(params.ships_from);
601
+ }
602
+ if (params.condition !== undefined)
603
+ filters["condition"] = params.condition;
604
+ if (typeof params.available === "boolean")
605
+ filters["available"] = params.available;
606
+ if (Object.keys(filters).length > 0)
607
+ body["filters"] = filters;
608
+ const pagination = {};
609
+ if (typeof params.cursor === "string")
610
+ pagination["cursor"] = params.cursor;
611
+ if (typeof params.limit === "number")
612
+ pagination["limit"] = params.limit;
613
+ if (Object.keys(pagination).length > 0)
614
+ body["pagination"] = pagination;
615
+ return body;
616
+ }
617
+ /** Emit a ship-to/ships-from object with its alpha-2 `country` UPPERCASED on the
618
+ * wire (`us` → `US`); every other field (`region`/`postal_code` on `ShipTo`) is
619
+ * preserved verbatim. The spread-then-overwrite keeps the shape generic over both
620
+ * {@link ShipTo} and {@link ShipsFrom} without reshaping or dropping a field. */
621
+ function withUppercaseCountry(value) {
622
+ return { ...value, country: value.country.toUpperCase() };
623
+ }
624
+ /**
625
+ * Unwrap + narrow a sil-api catalog-search response body to a typed
626
+ * {@link SearchResult}, or null if it carries no usable products array. sil-api
627
+ * emits a FLAT UCP envelope (`withUcpMeta(body) → { ucp, ...body }` —
628
+ * sil-services `.../sil-api/src/envelope.ts`): `products` and `pagination` sit at
629
+ * the TOP LEVEL beside `ucp`, there is NO `result` wrapper. Read them straight
630
+ * off the body. (There is no nested-`result` fallback to keep: search has no
631
+ * second route that ever returns one, so a `result`-wrapper expectation would be
632
+ * dead weight and — worse — a latent false-green a stray `result` key could shadow
633
+ * the real top-level `products`.)
634
+ *
635
+ * The load-bearing anti-false-green guard is the `Array.isArray(products)` check:
636
+ * a 200 lacking a real top-level `products` array (a partial / garbage / stub
637
+ * `{ stub: true }` body, or one carrying only `ucp` metadata) returns null →
638
+ * `retryable`, never a false-green empty match. An EMPTY array is a VALID empty
639
+ * match (a genuine "nothing matched") and returns an empty `products` list —
640
+ * distinct from the no-array guard. Individual products that are unusable (no
641
+ * projectable featured variant, missing checkout_url) are dropped via
642
+ * `projectProduct` returning null, never fabricated.
643
+ *
644
+ * The opaque cursor is hoisted from `pagination.cursor` and surfaced ONLY when
645
+ * `pagination.has_next_page` is true (end-of-results is the absent cursor — never
646
+ * derived from `products.length`).
647
+ */
648
+ function extractSearchResult(body) {
649
+ const envelope = asRecord(body);
650
+ if (envelope === null)
651
+ return null;
652
+ const rawProducts = envelope["products"];
653
+ if (!Array.isArray(rawProducts))
654
+ return null;
655
+ const products = rawProducts
656
+ .map(projectProduct)
657
+ .filter((p) => p !== null);
658
+ const cursor = extractCursor(envelope["pagination"]);
659
+ return cursor === null ? { products } : { products, cursor };
660
+ }
661
+ /**
662
+ * Project one `SilCatalogProduct` to the agent-facing {@link SearchProduct}, or
663
+ * null if it is unusable. Carries the product-level `id`/`title`/`source` AND the
664
+ * featured variant nested under `variant`. Picks the FIRST (featured) variant —
665
+ * UCP: "Platforms SHOULD treat the first element as featured". A product whose
666
+ * featured variant has no non-empty `checkout_url` (the one field the agent acts
667
+ * on to buy), or that is missing any required field, is dropped rather than
668
+ * surfaced as a non-purchasable result.
669
+ */
670
+ function projectProduct(raw) {
671
+ const product = asRecord(raw);
672
+ if (product === null)
673
+ return null;
674
+ const productId = product["id"];
675
+ const productTitle = product["title"];
676
+ const source = product["source"];
677
+ if (typeof productId !== "string" || productId.length === 0)
678
+ return null;
679
+ if (typeof productTitle !== "string")
680
+ return null;
681
+ if (typeof source !== "string" || source.length === 0)
682
+ return null;
683
+ const variants = product["variants"];
684
+ if (!Array.isArray(variants) || variants.length === 0)
685
+ return null;
686
+ const variant = projectVariant(variants[0]);
687
+ if (variant === null)
688
+ return null;
689
+ return { id: productId, title: productTitle, source, variant };
690
+ }
691
+ /**
692
+ * Project a `SilCatalogVariant` to the agent-facing {@link SearchVariant}, or
693
+ * null if it is not a usable purchasable variant. Requires `id`, `title`, a price
694
+ * object, and a non-empty `checkout_url`; `price`/`availability` pass through
695
+ * opaque.
696
+ */
697
+ function projectVariant(raw) {
698
+ const variant = asRecord(raw);
699
+ if (variant === null)
700
+ return null;
701
+ const id = variant["id"];
702
+ const title = variant["title"];
703
+ const checkoutUrl = variant["checkout_url"];
704
+ if (typeof id !== "string" || id.length === 0)
705
+ return null;
706
+ if (typeof title !== "string")
707
+ return null;
708
+ if (typeof checkoutUrl !== "string" || checkoutUrl.length === 0)
709
+ return null;
710
+ const price = extractPrice(variant["price"]);
711
+ if (price === null)
712
+ return null;
713
+ return {
714
+ id,
715
+ title,
716
+ price,
717
+ availability: extractAvailability(variant["availability"]),
718
+ checkout_url: checkoutUrl,
719
+ };
720
+ }
721
+ /**
722
+ * Unwrap + narrow a sil-api catalog-LOOKUP response body to a typed
723
+ * {@link LookupResult}, or null if it carries no usable products array. Like
724
+ * `extractSearchResult`, it reads sil-api's FLAT UCP envelope
725
+ * (`withUcpMeta(body) → { ucp, ...body }`): `products` and `messages` sit at the
726
+ * TOP LEVEL beside `ucp`, there is NO `result` wrapper — read them straight off
727
+ * the body (no nested-`result` fallback; lookup has no route that returns one).
728
+ *
729
+ * It shares search's load-bearing anti-false-green guard — `Array.isArray(products)`
730
+ * on the TOP-LEVEL `products`; a 200 lacking it (partial / garbage / stub
731
+ * `{ stub: true }`, or only `ucp` metadata) returns null → `retryable`. An EMPTY
732
+ * array is a VALID all-missed lookup (the products gate passes; `not_found`
733
+ * carries the ids) — distinct from the no-array guard. The two structural deltas
734
+ * from search:
735
+ * - NO cursor hoist — lookup is a batch resolve, not a list (no `pagination`).
736
+ * - `not_found` is parsed from the top-level `messages`: each
737
+ * `{ code: 'not_found', content: <id> }` entry's `content` IS a missed request
738
+ * id (server emits one per unresolved id, in input order, and OMITS `messages`
739
+ * on full success). The `not_found` key is omitted here when there are no misses.
740
+ *
741
+ * Products unusable in lookup terms (no projectable featured variant, missing
742
+ * `checkout_url`) are dropped via `projectLookupProduct` returning null, never
743
+ * fabricated — same null-drop discipline as search.
744
+ */
745
+ function extractLookupResult(body) {
746
+ const envelope = asRecord(body);
747
+ if (envelope === null)
748
+ return null;
749
+ const rawProducts = envelope["products"];
750
+ if (!Array.isArray(rawProducts))
751
+ return null;
752
+ const products = rawProducts
753
+ .map(projectLookupProduct)
754
+ .filter((p) => p !== null);
755
+ const notFound = extractNotFound(envelope["messages"]);
756
+ return notFound.length === 0 ? { products } : { products, not_found: notFound };
757
+ }
758
+ /**
759
+ * Project one `SilCatalogProduct` to the agent-facing {@link LookupProduct}, or
760
+ * null if it is unusable. RICHER than search's `projectProduct`: carries the
761
+ * product-level `description`, `price_range`, `categories?` and `handle?` (a lookup
762
+ * caller is making a purchase decision) plus the featured variant nested under
763
+ * `variant`. Picks the FIRST (featured) variant — `lookup_catalog` returns one
764
+ * featured variant per product; UCP: "Platforms SHOULD treat the first element as
765
+ * featured". A product whose featured variant has no non-empty `checkout_url`, or
766
+ * that is missing any required field, is dropped rather than surfaced as a
767
+ * non-purchasable result.
768
+ */
769
+ function projectLookupProduct(raw) {
770
+ const product = asRecord(raw);
771
+ if (product === null)
772
+ return null;
773
+ const id = product["id"];
774
+ const title = product["title"];
775
+ const source = product["source"];
776
+ if (typeof id !== "string" || id.length === 0)
777
+ return null;
778
+ if (typeof title !== "string")
779
+ return null;
780
+ if (typeof source !== "string" || source.length === 0)
781
+ return null;
782
+ const description = asRecord(product["description"]);
783
+ if (description === null)
784
+ return null;
785
+ const priceRange = product["price_range"];
786
+ if (asRecord(priceRange) === null)
787
+ return null;
788
+ const variants = product["variants"];
789
+ if (!Array.isArray(variants) || variants.length === 0)
790
+ return null;
791
+ const variant = projectLookupVariant(variants[0]);
792
+ if (variant === null)
793
+ return null;
794
+ const result = {
795
+ id,
796
+ title,
797
+ description,
798
+ price_range: priceRange,
799
+ source,
800
+ variant,
801
+ };
802
+ const categories = passThroughObjects(product["categories"]);
803
+ if (categories !== null)
804
+ result.categories = categories;
805
+ const handle = product["handle"];
806
+ if (typeof handle === "string" && handle.length > 0)
807
+ result.handle = handle;
808
+ return result;
809
+ }
810
+ /**
811
+ * Project a `SilCatalogVariant` to the agent-facing {@link LookupVariant}, or null
812
+ * if it is not a usable purchasable variant. RICHER than search's `projectVariant`:
813
+ * adds `sku`, `options` (which configuration this variant is), and the lookup-only
814
+ * `inputs` correlation. Requires `id`, `title`, a price object, and a non-empty
815
+ * `checkout_url`; `price`/`availability` pass through opaque. Optional rich fields
816
+ * are omitted when absent rather than emitted as `undefined`.
817
+ */
818
+ function projectLookupVariant(raw) {
819
+ const variant = asRecord(raw);
820
+ if (variant === null)
821
+ return null;
822
+ const id = variant["id"];
823
+ const title = variant["title"];
824
+ const checkoutUrl = variant["checkout_url"];
825
+ if (typeof id !== "string" || id.length === 0)
826
+ return null;
827
+ if (typeof title !== "string")
828
+ return null;
829
+ if (typeof checkoutUrl !== "string" || checkoutUrl.length === 0)
830
+ return null;
831
+ const price = extractPrice(variant["price"]);
832
+ if (price === null)
833
+ return null;
834
+ const result = {
835
+ id,
836
+ title,
837
+ price,
838
+ availability: extractAvailability(variant["availability"]),
839
+ checkout_url: checkoutUrl,
840
+ };
841
+ const sku = variant["sku"];
842
+ if (typeof sku === "string" && sku.length > 0)
843
+ result.sku = sku;
844
+ const options = passThroughObjects(variant["options"]);
845
+ if (options !== null)
846
+ result.options = options;
847
+ const inputs = extractInputs(variant["inputs"]);
848
+ if (inputs !== null)
849
+ result.inputs = inputs;
850
+ return result;
851
+ }
852
+ /** Pass a wire array of objects through OPAQUE — filter to plain objects, preserve
853
+ * each verbatim, never read or remap individual fields. Used for `categories` and
854
+ * the variant's `options`: contextual display data the tool SURFACES but does not
855
+ * interpret (it is not a purchasability gate — that is `checkout_url`/`price`).
856
+ * Mirrors how identity `addresses` pass through (the wire field names — `value` vs
857
+ * `name` on a category — are the source's to define, not the tool's to assert).
858
+ * Returns null when the field is absent/non-array or yields no usable object, so
859
+ * the caller omits the key rather than emitting an empty array. */
860
+ function passThroughObjects(raw) {
861
+ if (!Array.isArray(raw))
862
+ return null;
863
+ const objects = raw.filter((o) => asRecord(o) !== null);
864
+ return objects.length === 0 ? null : objects;
865
+ }
866
+ /** Narrow a wire `inputs` correlation array to {@link LookupInput}[] — each entry
867
+ * needs a non-empty `id` (the request id that resolved to this variant); a missing
868
+ * or non-string `match` is dropped (not coerced). Returns null when the field is
869
+ * absent or yields no usable entry, so the caller omits the key. Surfacing this is
870
+ * what makes a multi-id lookup correlatable — without it the agent cannot map "the
871
+ * id I asked about" to "the variant I got back". */
872
+ function extractInputs(raw) {
873
+ if (!Array.isArray(raw))
874
+ return null;
875
+ const inputs = raw
876
+ .map((i) => {
877
+ const obj = asRecord(i);
878
+ if (obj === null)
879
+ return null;
880
+ const id = obj["id"];
881
+ if (typeof id !== "string" || id.length === 0)
882
+ return null;
883
+ const match = obj["match"];
884
+ return typeof match === "string" ? { id, match } : { id };
885
+ })
886
+ .filter((i) => i !== null);
887
+ return inputs.length === 0 ? null : inputs;
888
+ }
889
+ /** Parse the missed request ids out of a wire `messages` array. Each
890
+ * `{ code: 'not_found', content: <id> }` info entry's `content` IS an unresolved
891
+ * id (sil-api emits one per miss, in input order; `messages` is OMITTED on full
892
+ * success). Returns the ids in order — an empty array when there are no misses
893
+ * (the caller then omits the `not_found` key). Only `not_found` codes are
894
+ * surfaced; any other message code (a future UCP `warning`/`delayed_fulfillment`)
895
+ * is ignored here — broader message passthrough is out of scope. */
896
+ function extractNotFound(raw) {
897
+ if (!Array.isArray(raw))
898
+ return [];
899
+ const ids = [];
900
+ for (const entry of raw) {
901
+ const obj = asRecord(entry);
902
+ if (obj === null)
903
+ continue;
904
+ if (obj["code"] !== "not_found")
905
+ continue;
906
+ const content = obj["content"];
907
+ if (typeof content === "string" && content.length > 0)
908
+ ids.push(content);
909
+ }
910
+ return ids;
911
+ }
912
+ /** Narrow a wire price (`{ amount: number, currency: string }`) — passed through
913
+ * opaque (extra fields preserved), or null if the two required fields are absent
914
+ * (an unpriced variant is not a usable purchasable result). */
915
+ function extractPrice(raw) {
916
+ const obj = asRecord(raw);
917
+ if (obj === null)
918
+ return null;
919
+ const amount = obj["amount"];
920
+ const currency = obj["currency"];
921
+ if (typeof amount !== "number" || typeof currency !== "string")
922
+ return null;
923
+ return { ...obj, amount, currency };
924
+ }
925
+ /** Narrow a wire availability object (`{ available?, status? }`) — passed through
926
+ * opaque (NOT flattened to a bare boolean; extra fields preserved). A missing or
927
+ * non-object availability yields an empty object (the agent reads no signal,
928
+ * rather than the tool inventing one). */
929
+ function extractAvailability(raw) {
930
+ const obj = asRecord(raw);
931
+ if (obj === null)
932
+ return {};
933
+ const result = { ...obj };
934
+ const available = obj["available"];
935
+ const status = obj["status"];
936
+ result.available = typeof available === "boolean" ? available : undefined;
937
+ result.status = typeof status === "string" ? status : undefined;
938
+ return result;
939
+ }
940
+ /** Hoist the opaque next-page cursor from a wire `pagination` object. Returns the
941
+ * cursor string ONLY when `has_next_page` is true AND a non-empty `cursor` is
942
+ * present; null otherwise (last page, or no pagination). End-of-results is the
943
+ * absent cursor — never `products.length === limit`. */
944
+ function extractCursor(raw) {
945
+ const obj = asRecord(raw);
946
+ if (obj === null)
947
+ return null;
948
+ if (obj["has_next_page"] !== true)
949
+ return null;
950
+ const cursor = obj["cursor"];
951
+ return typeof cursor === "string" && cursor.length > 0 ? cursor : null;
952
+ }
953
+ /** Pull sil-api's structured `{ error, message }` out of a 400 body, defaulting
954
+ * each field when the shape is unexpected so the agent always gets an actionable
955
+ * (if generic) hint rather than `undefined`. */
956
+ function extractApiError(body) {
957
+ const obj = asRecord(body);
958
+ const error = obj?.["error"];
959
+ const message = obj?.["message"];
960
+ return {
961
+ error: typeof error === "string" && error.length > 0 ? error : "invalid_request",
962
+ message: typeof message === "string" && message.length > 0
963
+ ? message
964
+ : "The search request was rejected. Provide a search query or at least one filter.",
965
+ };
966
+ }
967
+ /** Narrow the `user` field of a claim body to a typed identity. */
968
+ function extractUser(raw) {
969
+ const obj = asRecord(raw);
970
+ if (obj === null)
971
+ return { id: "" };
972
+ const id = obj["id"];
973
+ const name = obj["name"];
974
+ return {
975
+ id: typeof id === "string" ? id : "",
976
+ ...(typeof name === "string" ? { name } : {}),
977
+ };
978
+ }
979
+ /** A non-null plain object, or null for anything else (incl. arrays/primitives). */
980
+ function asRecord(value) {
981
+ return value !== null && typeof value === "object"
982
+ ? value
983
+ : null;
984
+ }
985
+ /** POST a JSON body with a hard per-request timeout (AbortController). Extra
986
+ * headers (e.g. an Authorization bearer) merge over the JSON content-type; the
987
+ * header values are passed straight to fetch and never logged. */
988
+ async function postJson(url, body, extraHeaders) {
989
+ const controller = new AbortController();
990
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
991
+ try {
992
+ return await fetch(url, {
993
+ method: "POST",
994
+ headers: { "content-type": "application/json", ...extraHeaders },
995
+ body: JSON.stringify(body),
996
+ signal: controller.signal,
997
+ });
998
+ }
999
+ finally {
1000
+ clearTimeout(timer);
1001
+ }
1002
+ }
1003
+ /** GET with a hard per-request timeout (AbortController), sharing `postJson`'s
1004
+ * timeout and never-log-the-token invariants. Sends NO `content-type` and NO
1005
+ * body — a GET body is at best ignored and in strict fetch environments throws,
1006
+ * and the sil-api self-read derives its principal from the Bearer JWT, not a
1007
+ * body. Extra headers (e.g. an Authorization bearer) are passed straight to
1008
+ * fetch and never logged. */
1009
+ async function getJson(url, extraHeaders) {
1010
+ const controller = new AbortController();
1011
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
1012
+ try {
1013
+ return await fetch(url, {
1014
+ method: "GET",
1015
+ headers: { ...extraHeaders },
1016
+ signal: controller.signal,
1017
+ });
1018
+ }
1019
+ finally {
1020
+ clearTimeout(timer);
1021
+ }
1022
+ }
1023
+ async function readJsonBody(res) {
1024
+ try {
1025
+ return await res.json();
1026
+ }
1027
+ catch {
1028
+ return null;
1029
+ }
1030
+ }
1031
+ function stripTrailingSlash(url) {
1032
+ return url.endsWith("/") ? url.slice(0, -1) : url;
1033
+ }