sil-openclaw 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/EXAMPLES.md +93 -0
  3. package/README.md +58 -120
  4. package/SECURITY.md +12 -9
  5. package/assets/banner-dark.svg +15 -0
  6. package/assets/banner.svg +15 -0
  7. package/dist/gateway/screen.js +174 -0
  8. package/dist/index.js +5 -9
  9. package/dist/lib/answers.js +59 -0
  10. package/dist/lib/screen-log.js +13 -0
  11. package/dist/lib/shopping-call.js +27 -28
  12. package/dist/lib/sil-client.js +49 -66
  13. package/dist/lib/tool-result.js +1 -1
  14. package/dist/tools/catalog.js +113 -272
  15. package/dist/tools/identity.js +79 -88
  16. package/openclaw.plugin.json +12 -7
  17. package/package.json +4 -2
  18. package/schema/PROVENANCE.md +7 -4
  19. package/schema/shopping-brief-read-request.schema.json +2 -1
  20. package/schema/shopping-brief-read-response.schema.json +98 -50
  21. package/schema/shopping-brief-write-request.schema.json +322 -0
  22. package/schema/{shopping-brief-create-response.schema.json → shopping-brief-write-response.schema.json} +3 -3
  23. package/schema/shopping-content-request.schema.json +12 -31
  24. package/schema/shopping-content-response.schema.json +14 -95
  25. package/schema/shopping-domain-get-request.schema.json +24 -1
  26. package/schema/shopping-domain-get-response.schema.json +23 -421
  27. package/schema/shopping-domain-search-request.schema.json +3 -3
  28. package/schema/shopping-domain-search-response.schema.json +3 -56
  29. package/schema/shopping-offers-request.schema.json +14 -9
  30. package/schema/shopping-offers-response.schema.json +368 -91
  31. package/schema/shopping-product-get-request.schema.json +4 -3
  32. package/schema/shopping-product-get-response.schema.json +347 -46
  33. package/schema/shopping-search-request.schema.json +53 -40
  34. package/schema/shopping-search-response.schema.json +408 -116
  35. package/schema/shopping-seller-get-request.schema.json +13 -1
  36. package/schema/shopping-seller-get-response.schema.json +594 -225
  37. package/schema/shopping-user-forget-request.schema.json +43 -0
  38. package/schema/shopping-user-forget-response.schema.json +74 -0
  39. package/schema/shopping-user-read-request.schema.json +37 -0
  40. package/schema/shopping-user-read-response.schema.json +372 -0
  41. package/schema/shopping-user-remember-request.schema.json +341 -0
  42. package/schema/shopping-user-remember-response.schema.json +66 -0
  43. package/schema/sil-whoami-request.schema.json +8 -0
  44. package/schema/sil-whoami-response.schema.json +99 -0
  45. package/sil-shopping/SKILL.md +149 -208
  46. package/dist/gateway/search-results.js +0 -99
  47. package/dist/lib/search-results-log.js +0 -23
  48. package/dist/lib/search-results-store.js +0 -116
  49. package/schema/shopping-brief-create-request.schema.json +0 -98
  50. package/schema/shopping-brief-edit-request.schema.json +0 -125
  51. package/schema/shopping-brief-edit-response.schema.json +0 -24
  52. package/schema/shopping-profile-edit-request.schema.json +0 -97
  53. package/schema/shopping-profile-edit-response.schema.json +0 -17
@@ -0,0 +1,174 @@
1
+ /**
2
+ * What the plugin answers a paired screen (contract §4): `sil.answer` reads back an answer
3
+ * the agent got; `sil.call` runs a read or a forget as the signed-in buyer. Not tools: they
4
+ * never reach the model. The host checks `operator.read` before either handler runs; the
5
+ * plugin checks the one thing it cannot — that the sil account signed in owns the answer.
6
+ */
7
+ import { randomUUID } from "node:crypto";
8
+ import { latestSession, readAnswer, signedInPrincipal } from "../lib/answers.js";
9
+ import { readHostVersion } from "../lib/host-wiring.js";
10
+ import { logScreen } from "../lib/screen-log.js";
11
+ import { callRoute } from "../lib/shopping-call.js";
12
+ import { readInstalledVersion } from "../lib/version-advisory.js";
13
+ import { SHOPPING_TOOLS } from "../tools/catalog.js";
14
+ export const ANSWER_METHOD = "sil.answer";
15
+ export const CALL_METHOD = "sil.call";
16
+ /** Unknown ≡ expired ≡ another account's ≡ signed out: one body, and never a method error,
17
+ * which a screen reads as a transport fault and retries forever. */
18
+ const NOT_FOUND = {
19
+ status: "not_found",
20
+ message: "Nothing to show for this: ask the agent again.",
21
+ };
22
+ const SCREEN_TOOLS = new Set([
23
+ "shopping_product_get",
24
+ "shopping_offers",
25
+ "shopping_seller_get",
26
+ "shopping_domain_get",
27
+ "shopping_content",
28
+ "shopping_user_read",
29
+ "shopping_user_forget",
30
+ ]);
31
+ /** sil reads three products an answer; a screen's Compare asks for up to ten. */
32
+ const PRODUCT_IDS_MAX = 10;
33
+ const PRODUCT_IDS_PER_READ = 3;
34
+ /** sil's record tells the buyer's taps from the agent's calls by this model. */
35
+ const SCREEN_MODEL = "studio/buyer";
36
+ /** sil-api's rules for `sil-tool-call-id` and `sil-session-id`. */
37
+ const REQUEST_ID = /^[\x21-\x7E]{1,256}$/;
38
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
39
+ /** Refusals whose recovery is signing in again: on a screen that is signed out. */
40
+ const SIGNED_OUT = new Set([
41
+ "not_registered",
42
+ "must_reregister",
43
+ "forbidden",
44
+ ]);
45
+ export function registerScreenMethods(api) {
46
+ const openclawVersion = readHostVersion(api);
47
+ const run = {
48
+ pluginVersion: readInstalledVersion(),
49
+ ...(openclawVersion !== null ? { openclawVersion } : {}),
50
+ };
51
+ api.registerGatewayMethod(ANSWER_METHOD, ({ params, respond }) => guarded(api, respond, () => answer(api, params, respond)), { scope: "operator.read" });
52
+ api.registerGatewayMethod(CALL_METHOD, ({ params, respond }) => guarded(api, respond, () => call(api, run, params, respond)), { scope: "operator.read" });
53
+ }
54
+ async function guarded(api, respond, handle) {
55
+ try {
56
+ await handle();
57
+ }
58
+ catch (err) {
59
+ logScreen(api, "error", "failed", {
60
+ error_type: err instanceof Error ? err.name : typeof err,
61
+ cause: err instanceof Error ? err.message : String(err),
62
+ stack: err instanceof Error ? (err.stack ?? "") : "",
63
+ });
64
+ respond(true, NOT_FOUND);
65
+ }
66
+ }
67
+ function answer(api, params, respond) {
68
+ const callId = params["callId"];
69
+ if (typeof callId !== "string" || callId.length === 0) {
70
+ invalid(api, respond, "sil.answer takes a non-empty string `callId`.");
71
+ return;
72
+ }
73
+ const principal = signedInPrincipal();
74
+ const read = principal === undefined ? { miss: "no_principal" } : readAnswer(callId, principal);
75
+ if ("miss" in read) {
76
+ logScreen(api, "info", "answer_miss", { callId, reason: read.miss });
77
+ respond(true, NOT_FOUND);
78
+ return;
79
+ }
80
+ logScreen(api, "info", "answer_hit", { callId });
81
+ respond(true, read.body);
82
+ }
83
+ async function call(api, run, params, respond) {
84
+ const parsed = parseCall(params);
85
+ if ("invalid" in parsed) {
86
+ invalid(api, respond, parsed.invalid);
87
+ return;
88
+ }
89
+ const { tool, reads, requestId } = parsed;
90
+ const principal = signedInPrincipal();
91
+ if (principal === undefined) {
92
+ logScreen(api, "info", "call_refused", { requestId, tool: tool.name, reason: "no_principal" });
93
+ respond(true, NOT_FOUND);
94
+ return;
95
+ }
96
+ // sil-api requires a conversation UUID: the one the screen shows, else the one the agent
97
+ // last answered in, else the screen's own.
98
+ const caller = {
99
+ ...run,
100
+ toolCallId: requestId,
101
+ model: SCREEN_MODEL,
102
+ sessionId: parsed.sessionId ?? latestSession(principal) ?? randomUUID(),
103
+ };
104
+ const answered = await readAll(api, tool, reads, caller);
105
+ if (answered.kind === "refused") {
106
+ const { status } = answered.body;
107
+ logScreen(api, "info", "call_refused", { requestId, tool: tool.name, reason: status });
108
+ respond(true, SIGNED_OUT.has(status) ? NOT_FOUND : answered.body);
109
+ return;
110
+ }
111
+ logScreen(api, "info", "call_answered", { requestId, tool: tool.name, reads: reads.length });
112
+ respond(true, answered.body);
113
+ }
114
+ function parseCall(params) {
115
+ const { tool: name, args, requestId, sessionId } = params;
116
+ const tool = SHOPPING_TOOLS.find((t) => t.name === name && SCREEN_TOOLS.has(t.name));
117
+ if (tool === undefined)
118
+ return { invalid: `sil.call runs only ${[...SCREEN_TOOLS].join(", ")}.` };
119
+ if (args === null || typeof args !== "object" || Array.isArray(args)) {
120
+ return { invalid: "sil.call takes `args`, the tool's arguments as an object." };
121
+ }
122
+ if (typeof requestId !== "string" || !REQUEST_ID.test(requestId)) {
123
+ return { invalid: "sil.call takes `requestId`, 1–256 printable characters, no spaces." };
124
+ }
125
+ if (sessionId !== undefined && (typeof sessionId !== "string" || !SESSION_ID.test(sessionId))) {
126
+ return { invalid: "sil.call takes `sessionId`, when sent, as a UUID." };
127
+ }
128
+ const body = args;
129
+ // A tap erases the rows it names; everything goes only on the buyer's word to the agent.
130
+ if (tool.name === "shopping_user_forget" && !namesRowsOnly(body)) {
131
+ return { invalid: "shopping_user_forget from a screen takes `ids` only." };
132
+ }
133
+ const reads = tool.name === "shopping_product_get" ? productReads(body) : [body];
134
+ if (reads === null) {
135
+ return { invalid: `shopping_product_get takes \`ids\`, 1–${PRODUCT_IDS_MAX} strings.` };
136
+ }
137
+ return { tool, reads, requestId, sessionId };
138
+ }
139
+ function namesRowsOnly(args) {
140
+ const ids = args["ids"];
141
+ return Object.keys(args).length === 1 && Array.isArray(ids) && ids.length > 0;
142
+ }
143
+ /** The reads at once — the refresh they may share is single-flight — the product reads'
144
+ * `products` joined in order, and the first refusal answering for all. */
145
+ async function readAll(api, tool, reads, caller) {
146
+ if (reads.length === 1)
147
+ return callRoute(api, tool, reads[0] ?? {}, caller);
148
+ const called = await Promise.all(reads.map((read) => callRoute(api, tool, read, caller)));
149
+ const refused = called.find((c) => c.kind === "refused");
150
+ if (refused !== undefined)
151
+ return refused;
152
+ const products = called.flatMap((c) => {
153
+ const page = c.body["products"];
154
+ return Array.isArray(page) ? page : [];
155
+ });
156
+ return { kind: "ok", body: { status: "ok", products } };
157
+ }
158
+ /** The ids cut into the threes sil reads, or null when they are not 1–10 strings. */
159
+ function productReads(args) {
160
+ const ids = args["ids"];
161
+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > PRODUCT_IDS_MAX)
162
+ return null;
163
+ if (!ids.every((id) => typeof id === "string" && id.length > 0))
164
+ return null;
165
+ const reads = [];
166
+ for (let at = 0; at < ids.length; at += PRODUCT_IDS_PER_READ) {
167
+ reads.push({ ...args, ids: ids.slice(at, at + PRODUCT_IDS_PER_READ) });
168
+ }
169
+ return reads;
170
+ }
171
+ function invalid(api, respond, message) {
172
+ logScreen(api, "info", "invalid", { message });
173
+ respond(true, { status: "invalid_request", message });
174
+ }
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * sil OpenClaw plugin — entry point.
3
3
  *
4
4
  * A UCP commerce plugin for sil. It registers its real tool groups — the account
5
- * tools (`sil_register`, `sil_whoami`, `sil_doctor`) and the ten `shopping_*`
5
+ * tools (`sil_register`, `sil_whoami`, `sil_doctor`) and the twelve `shopping_*`
6
6
  * catalog tools — so they load in an OpenClaw host.
7
7
  * There is no transport, no persistent service, and no background work at
8
8
  * register time — `register()` is strictly synchronous and opens nothing.
@@ -26,7 +26,7 @@
26
26
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
27
27
  import { applyPluginConfigOverrides, getWebUrl, getWebUrlSource, getApiUrl, getApiUrlSource, } from "./lib/config.js";
28
28
  import { ensureDataDir, getDataDir } from "./lib/credentials.js";
29
- import { registerSearchResultsMethod } from "./gateway/search-results.js";
29
+ import { registerScreenMethods } from "./gateway/screen.js";
30
30
  import { detectWiringDrift, readSilWiringFacts } from "./lib/host-wiring.js";
31
31
  import { registerCatalogTools } from "./tools/catalog.js";
32
32
  import { registerDoctorTools } from "./tools/doctor.js";
@@ -69,13 +69,9 @@ export default definePluginEntry({
69
69
  registerIdentityTools(api);
70
70
  registerCatalogTools(api);
71
71
  registerDoctorTools(api);
72
- // The pull surface a paired client resolves a search page from. Registering
73
- // a closure opens nothing — no socket, no timer — so the invariant above
74
- // holds; the store behind it is touched only inside the handler and inside
75
- // shopping_search's execute(). NOT a tool and NOT a `registerXTools` group: it
76
- // never reaches the model, and the manifest's `contracts` vocabulary has no
77
- // gateway-method key, so this call IS the declaration.
78
- registerSearchResultsMethod(api);
72
+ // Not tools, and not manifest-declarable: registration is the declaration. Registering
73
+ // a closure opens nothing, so the invariant above holds.
74
+ registerScreenMethods(api);
79
75
  // Host-wiring drift, at the ONE surface that survives it.
80
76
  //
81
77
  // `tools.alsoAllow` is GLOBAL, so the state where sil's tools are filtered
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Every `ok` answer a sil tool gave the agent, kept for the paired screen to read back by
3
+ * the host's `callId` (`sil.answer`). In memory and evicted lazily on write: `register()`
4
+ * opens no timer, and nothing of the buyer's rests on disk.
5
+ */
6
+ import { hasTokens, readConfig } from "./credentials.js";
7
+ import { logScreen } from "./screen-log.js";
8
+ /** A run reads about fifteen answers; prices are point-in-time, so they never outlive this. */
9
+ const RETENTION_MS = 15 * 60_000;
10
+ const MAX_ANSWERS = 64;
11
+ const answers = new Map();
12
+ /** The sil account holding a LIVE session: sign-out unlinks the tokens and keeps the config. */
13
+ export function signedInPrincipal() {
14
+ const id = hasTokens() ? readConfig()?.user?.id : undefined;
15
+ return id === undefined || id.length === 0 ? undefined : id;
16
+ }
17
+ /** A side effect of a tool's `ok` path; the agent's result is unchanged. */
18
+ export function keepAnswer(api, callId, sessionId, body) {
19
+ const principal = signedInPrincipal();
20
+ if (principal === undefined) {
21
+ logScreen(api, "info", "answer_skipped", { callId, reason: "no_principal" });
22
+ return;
23
+ }
24
+ const now = Date.now();
25
+ // Map order is age: a re-kept callId must move to the newest end.
26
+ answers.delete(callId);
27
+ for (const [id, kept] of answers)
28
+ if (kept.expiresAtMs <= now)
29
+ answers.delete(id);
30
+ while (answers.size >= MAX_ANSWERS) {
31
+ const oldest = answers.keys().next();
32
+ if (oldest.done === true)
33
+ break;
34
+ answers.delete(oldest.value);
35
+ }
36
+ answers.set(callId, { principal, sessionId, body, expiresAtMs: now + RETENTION_MS });
37
+ }
38
+ /** Pure: a read never evicts or consumes, so a screen reload re-reads the same answer. */
39
+ export function readAnswer(callId, principal) {
40
+ const kept = answers.get(callId);
41
+ if (kept === undefined)
42
+ return { miss: "unknown" };
43
+ if (kept.expiresAtMs <= Date.now())
44
+ return { miss: "expired" };
45
+ if (kept.principal !== principal)
46
+ return { miss: "principal_mismatch" };
47
+ return { body: kept.body };
48
+ }
49
+ /** The conversation of the principal's latest agent call — what the screen is showing. */
50
+ export function latestSession(principal) {
51
+ const now = Date.now();
52
+ let latest;
53
+ for (const kept of answers.values()) {
54
+ if (kept.principal === principal && kept.expiresAtMs > now && kept.sessionId !== undefined) {
55
+ latest = kept.sessionId;
56
+ }
57
+ }
58
+ return latest;
59
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The `sil_screen_*` operator markers. Fields repeat INLINE in the message: the host hands
3
+ * the structured object to the log file only, and the console line is the message alone.
4
+ */
5
+ const MAX_FIELD_CHARS = 128;
6
+ /** Ids come from the screen: a raw newline would forge a second marker line. */
7
+ const render = (value) => String(value)
8
+ .replace(/[^\x21-\x7E]/g, "_")
9
+ .slice(0, MAX_FIELD_CHARS);
10
+ export function logScreen(api, severity, event, fields) {
11
+ const pairs = Object.entries(fields).map(([key, value]) => `${key}=${render(value)}`);
12
+ api.logger[severity](`sil_screen_${event} ${pairs.join(" ")}`, fields);
13
+ }
@@ -6,12 +6,15 @@
6
6
  import { getApiUrl } from "./config.js";
7
7
  import { clearTokens, readTokens } from "./credentials.js";
8
8
  import { callShopping, refreshAndRetryOnce, } from "./sil-client.js";
9
- import { jsonResult } from "./tool-result.js";
10
9
  /** The guide read, as one route constant: two spellings of one path is a route nobody
11
10
  * owns. */
12
- export const DOMAIN_GET_ROUTE = { method: "GET", path: "/catalog/domains/:path" };
13
- function refused(status, result) {
14
- return { kind: "refused", status, result };
11
+ export const DOMAIN_GET_ROUTE = {
12
+ method: "GET",
13
+ path: "/catalog/domains/:path",
14
+ query: ["query", "spec_keywords", "page"],
15
+ };
16
+ function refused(body) {
17
+ return { kind: "refused", body };
15
18
  }
16
19
  /**
17
20
  * Call one route with the stored credentials, refreshing and retrying at most once.
@@ -21,7 +24,7 @@ function refused(status, result) {
21
24
  export async function callRoute(api, call, args, caller) {
22
25
  const stored = readTokens();
23
26
  if (stored === null)
24
- return refused("not_registered", notRegistered(call.name));
27
+ return refused(notRegistered(call.name));
25
28
  const first = await callShopping(getApiUrl(), stored.access_token, call, args, caller, 1);
26
29
  const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => callShopping(getApiUrl(), accessToken, call, args, caller, 2));
27
30
  switch (recovered.kind) {
@@ -33,14 +36,14 @@ export async function callRoute(api, call, args, caller) {
33
36
  if (recovered.reason === "invalid_grant")
34
37
  clearTokens();
35
38
  api.logger.info(`${call.name}_must_reregister`, { cause: recovered.reason });
36
- return refused("must_reregister", mustReregister(call.name));
39
+ return refused(mustReregister(call.name));
37
40
  case "second_unauthorized":
38
41
  clearTokens();
39
42
  api.logger.info(`${call.name}_must_reregister`, { cause: "retry_unauthorized" });
40
- return refused("must_reregister", mustReregister(call.name));
43
+ return refused(mustReregister(call.name));
41
44
  case "retryable":
42
45
  api.logger.info(`${call.name}_refresh_retryable`, {});
43
- return refused("retryable", transient(call.name));
46
+ return refused(transient(call.name));
44
47
  }
45
48
  }
46
49
  function mapOutcome(api, call, outcome) {
@@ -49,29 +52,29 @@ function mapOutcome(api, call, outcome) {
49
52
  return { kind: "ok", body: outcome.body };
50
53
  case "invalid_request":
51
54
  api.logger.info(`${call.name}_invalid_request`, {});
52
- return refused("invalid_request", refusal("invalid_request", outcome.message));
55
+ return refused(refusal("invalid_request", outcome.message));
53
56
  case "not_found":
54
57
  api.logger.info(`${call.name}_not_found`, {});
55
- return refused("not_found", refusal("not_found", outcome.message, call.recovery?.not_found));
58
+ return refused(refusal("not_found", outcome.message, call.recovery?.not_found));
56
59
  case "forbidden":
57
- return refused("forbidden", forbiddenResult(api, call.name, outcome.reason));
60
+ return refused(forbiddenResult(api, call.name, outcome.reason));
58
61
  case "retryable":
59
62
  api.logger.info(`${call.name}_retryable`, outcome.source ? { source: outcome.source } : {});
60
- return refused("retryable", transient(call.name, outcome.source, outcome.detail));
63
+ return refused(transient(call.name, outcome.source, outcome.detail));
61
64
  case "unauthorized":
62
65
  // Structurally unreachable past the 401 choreography, kept exhaustive so a
63
66
  // refactor cannot silently drop a variant.
64
- return refused("must_reregister", mustReregister(call.name));
67
+ return refused(mustReregister(call.name));
65
68
  }
66
69
  }
67
70
  /** Not registered: a distinct, actionable outcome naming the recovery tool, with
68
71
  * no results field the agent could mistake for an empty answer. */
69
72
  function notRegistered(tool) {
70
- return jsonResult({
73
+ return {
71
74
  status: "not_registered",
72
75
  message: `Not registered on sil. Run sil_register to authenticate, then call ${tool} again.`,
73
76
  recovery: "sil_register",
74
- });
77
+ };
75
78
  }
76
79
  /**
77
80
  * A refusal the route made before it spent, surfaced VERBATIM: the message names the
@@ -81,20 +84,16 @@ function notRegistered(tool) {
81
84
  * one: a next call that fits one of its causes is a hint that misleads on the rest.
82
85
  */
83
86
  function refusal(status, message, recovery) {
84
- return jsonResult({
85
- status,
86
- message,
87
- ...(recovery !== undefined ? { recovery } : {}),
88
- });
87
+ return { status, message, ...(recovery !== undefined ? { recovery } : {}) };
89
88
  }
90
89
  /** Terminal: the session is dead — reached only after the shared refresh-and-retry
91
90
  * choreography has exhausted its one refresh + one retry. */
92
91
  function mustReregister(tool) {
93
- return jsonResult({
92
+ return {
94
93
  status: "must_reregister",
95
94
  message: `Your sil session has expired. Run sil_register to sign in again, then call ${tool} again.`,
96
95
  recovery: "sil_register",
97
- });
96
+ };
98
97
  }
99
98
  /**
100
99
  * A 403 — the token is valid but the user is not provisioned (or a principal
@@ -115,7 +114,7 @@ function forbiddenResult(api, tool, reason) {
115
114
  + " sil_register) and try again."
116
115
  : "sil rejected this request (" + reason + "). Run sil_register to"
117
116
  + " re-establish your session, then try again.";
118
- return jsonResult({ status: "forbidden", reason, message, recovery: "sil_register" });
117
+ return { status: "forbidden", reason, message, recovery: "sil_register" };
119
118
  }
120
119
  /**
121
120
  * Transient: retry, NOT a re-register (a false terminal on a transient sends the
@@ -126,17 +125,17 @@ function forbiddenResult(api, tool, reason) {
126
125
  * the copy must never say "sil is unavailable". `detail` (the upstream cause) is
127
126
  * relayed as its own field rather than folded into our sentence.
128
127
  */
129
- export function transient(tool, source, detail) {
128
+ function transient(tool, source, detail) {
130
129
  if (source === undefined) {
131
- return jsonResult({
130
+ return {
132
131
  status: "retryable",
133
132
  message: `sil is temporarily unavailable. Please try ${tool} again.`,
134
- });
133
+ };
135
134
  }
136
- return jsonResult({
135
+ return {
137
136
  status: "retryable",
138
137
  message: `The catalog source "${source}" is temporarily unavailable.`
139
138
  + ` sil itself is fine — retry ${tool} shortly.`,
140
139
  ...(detail !== undefined ? { detail } : {}),
141
- });
140
+ };
142
141
  }
@@ -36,11 +36,14 @@
36
36
  * request body:
37
37
  *
38
38
  * GET <silApiUrl>/identity Authorization: Bearer <access_token>
39
- * 200 { name, country?, addresses, measurements?, preferences? } → ok
39
+ * 200 { status, name, country?, currency?, gender?, language?, addresses } → ok
40
40
  * 401 → unauthorized (→ refresh)
41
41
  * 403 { error: user_not_provisioned | principal_mismatch } → forbidden (terminal)
42
+ * 426 plugin older than sil accepts → refused (carries sil's message)
42
43
  * 5xx / network / abort → retryable
43
44
  *
45
+ * Shopping routes: 426 (plugin too old) → invalid_request, carrying sil's message.
46
+ *
44
47
  * THE SHOPPING WIRE IS NOT MIRRORED HERE. Each tool's request shape is the committed
45
48
  * artifact under `schema/`, registered as the tool's own `parameters`; each 200 body is
46
49
  * the agent contract's, handed back VERBATIM. So this file declares no product type at
@@ -61,7 +64,7 @@
61
64
  * The VERB is load-bearing: only `GET /identity` is the self-read — `POST` is the
62
65
  * agent enrich route and carries no name. The identity rides in the envelope's
63
66
  * `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.
67
+ * never to a false `ok`. A buyer with no address on file is a valid identity.
65
68
  *
66
69
  * Tokens never appear in a log line here (mirrors sil-web's invariant) — they
67
70
  * only travel inside the returned union variant.
@@ -74,15 +77,6 @@ import { readTokens, writeTokens } from "./credentials.js";
74
77
  * route that answers from what sil already holds — at 15 s the plugin refused 7 of 12 live
75
78
  * calls sil-api went on to finish (2026-09-15). */
76
79
  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
80
  /**
87
81
  * Classify a shopping response. One classifier for all ten routes — the contract
88
82
  * gives them one error vocabulary, so a second one could only drift.
@@ -94,8 +88,10 @@ export const requestTimeoutMs = (route) => route.path === SEARCH_PATH ? SEARCH_T
94
88
  * source, and a second opinion here would be the copy that drifts from it.
95
89
  */
96
90
  function classifyShoppingResponse(status, body) {
97
- if (status === 400)
91
+ // 426: sil refuses a plugin older than it accepts; its message says to update.
92
+ if (status === 400 || status === 426) {
98
93
  return { kind: "invalid_request", message: extractApiError(body).message };
94
+ }
99
95
  if (status === 401)
100
96
  return { kind: "unauthorized" };
101
97
  if (status === 403)
@@ -185,7 +181,7 @@ export function classifyRefreshResponse(status, body) {
185
181
  * 401 → unauthorized (the ONLY refresh trigger)
186
182
  * 403 → forbidden (terminal; carries user_not_provisioned/principal_mismatch)
187
183
  * 5xx / non-200 → retryable
188
- * 200 → unwrap the envelope `result` and narrow to {name, addresses}; a 200
184
+ * 200 → unwrap the envelope `result` and narrow to {name, …}; a 200
189
185
  * that yields no usable identity (no `name`) is `retryable`, NEVER `ok`
190
186
  * (the anti-false-green guard — a partial/garbage 200, or the current
191
187
  * /identity STUB shape with no name, must not read as success).
@@ -195,6 +191,9 @@ export function classifyRefreshResponse(status, body) {
195
191
  * auth-branch bug in this flow.
196
192
  */
197
193
  export function classifyIdentityResponse(status, body) {
194
+ // Not `invalid_request`: IdentityOutcome has no such variant; the tool surfaces it as one.
195
+ if (status === 426)
196
+ return { kind: "refused", message: extractApiError(body).message };
198
197
  if (status === 401)
199
198
  return { kind: "unauthorized" };
200
199
  if (status === 403)
@@ -244,17 +243,17 @@ export async function refreshSession(apiUrl, refreshToken) {
244
243
  }
245
244
  /**
246
245
  * Read the authenticated user's identity from sil-api (the SECOND origin, not
247
- * sil-web): a BODYLESS `GET /identity` answering `{ id, name, country?, addresses }`.
246
+ * sil-web): a BODYLESS `GET /identity` answering `{ status, name, country?, currency?, gender?, language?, address? }`.
248
247
  * Bodyless is the point — the principal is the token subject and nothing else, so
249
248
  * no `agent_id` is sendable and the `principal_mismatch` 403 cannot arise.
250
249
  *
251
250
  * The Bearer header is built HERE and never logged.
252
251
  */
253
- export async function fetchIdentity(silApiUrl, token) {
252
+ export async function fetchIdentity(silApiUrl, token, caller, attempt) {
254
253
  const url = `${stripTrailingSlash(silApiUrl)}/identity`;
255
254
  let res;
256
255
  try {
257
- res = await getJson(url, { authorization: `Bearer ${token}` });
256
+ res = await getJson(url, { authorization: `Bearer ${token}`, ...callerHeaders(caller, attempt) });
258
257
  }
259
258
  catch {
260
259
  return { kind: "retryable" };
@@ -286,7 +285,7 @@ export async function callShopping(silApiUrl, token, route, args, caller, attemp
286
285
  const headers = { authorization: `Bearer ${token}`, ...callerHeaders(caller, attempt) };
287
286
  let res;
288
287
  try {
289
- const timeoutMs = requestTimeoutMs(route);
288
+ const timeoutMs = REQUEST_TIMEOUT_MS;
290
289
  res =
291
290
  route.method === "GET"
292
291
  ? await getJson(url, headers, timeoutMs)
@@ -323,7 +322,7 @@ function callerHeaders(caller, attempt) {
323
322
  * Both halves are encoded, never concatenated: a dotted registry path is one PATH
324
323
  * SEGMENT (a stray `/` in it would re-route the call), and an unencoded query value
325
324
  * could inject a second parameter. Only the keys the agent actually sent travel — an
326
- * empty `q=` is a DIFFERENT request from an omitted `q`, and each gets its own refusal
325
+ * empty `query=` is a DIFFERENT request from an omitted `query`, and each gets its own refusal
327
326
  * message, which is the agent's whole recourse.
328
327
  */
329
328
  function routePath(route, args) {
@@ -343,8 +342,13 @@ function routePath(route, args) {
343
342
  const query = new URLSearchParams();
344
343
  for (const key of route.query ?? []) {
345
344
  const value = args[key];
346
- if (typeof value === "string")
347
- query.set(key, value);
345
+ if (typeof value === "string" || typeof value === "number")
346
+ query.set(key, String(value));
347
+ else if (Array.isArray(value)) {
348
+ for (const item of value)
349
+ if (typeof item === "string")
350
+ query.append(key, item);
351
+ }
348
352
  }
349
353
  const search = query.toString();
350
354
  return search === "" ? path : `${path}?${search}`;
@@ -359,7 +363,16 @@ function routePath(route, args) {
359
363
  * "must re-register" signal and DO NOT rotate (a rejected refresh must never be
360
364
  * presented as a fresh, valid pair). A 5xx / network blip is retryable.
361
365
  */
362
- export async function refreshStoredTokens() {
366
+ export function refreshStoredTokens() {
367
+ // Single-flight: sil-web rotates the refresh token, so a second exchange of the same one
368
+ // answers invalid_grant and its caller clears a live session.
369
+ refreshing ??= rotateStoredTokens().finally(() => {
370
+ refreshing = null;
371
+ });
372
+ return refreshing;
373
+ }
374
+ let refreshing = null;
375
+ async function rotateStoredTokens() {
363
376
  const stored = readTokens();
364
377
  if (stored === null) {
365
378
  return { status: "must_reregister", reason: "no_stored_tokens" };
@@ -441,53 +454,32 @@ export async function refreshAndRetryOnce(first, isUnauthorized, retryWithToken)
441
454
  }
442
455
  /**
443
456
  * Unwrap + narrow a sil-api identity body to a typed `Identity`, or null when it
444
- * carries none. The body may wrap the identity in `result` or return it bare.
445
- *
446
- * An EMPTY `addresses` is a real identity (a provisioned user who has not added
447
- * an address yet) — rejecting it would strand them on a `retryable` no retry can
448
- * clear. The non-empty `name` gate is what keeps a nameless body off `ok`.
457
+ * carries none. The body may wrap the identity in `result` or return it bare. The
458
+ * non-empty `name` gate is what keeps a nameless body off `ok`.
449
459
  */
450
460
  function extractIdentity(body) {
451
461
  const envelope = asRecord(body);
452
462
  if (envelope === null)
453
463
  return null;
454
- const result = asRecord(envelope["result"]);
455
- const source = result ?? envelope;
464
+ const source = asRecord(envelope["result"]) ?? envelope;
456
465
  const name = source["name"];
457
466
  if (typeof name !== "string" || name.length === 0)
458
467
  return null;
459
- const rawAddresses = source["addresses"];
460
- if (!Array.isArray(rawAddresses))
461
- return null;
462
- const addresses = rawAddresses.filter((a) => asRecord(a) !== null);
463
- // The profile halves are NOT a gate: a read that carries neither is a buyer who
464
- // has told sil nothing yet, and `[]` says exactly that — refusing here would
465
- // strand them on a `retryable` no retry can clear.
466
- const measurements = plainObjects(source["measurements"]);
467
- const preferences = plainObjects(source["preferences"]);
468
- // `country`, `gender` and `currency` are optional on the read and pass through only as
469
- // strings — an absent or non-string one is dropped, never coerced or inferred. The VALUE
470
- // is the route's to decide: a literal allow-list here would drop a vocabulary sil adds.
471
- const country = source["country"];
472
- const gender = source["gender"];
473
- const currency = source["currency"];
468
+ // Optional fields pass through only as the right shape — an absent or malformed one is
469
+ // dropped, never coerced. The VALUES are the route's to decide.
470
+ const addresses = Array.isArray(source["addresses"])
471
+ ? source["addresses"].flatMap((one) => asRecord(one) ?? [])
472
+ : [];
473
+ const optional = (key) => typeof source[key] === "string" ? { [key]: source[key] } : {};
474
474
  return {
475
475
  name,
476
- addresses,
477
- measurements,
478
- preferences,
479
- ...(typeof country === "string" ? { country } : {}),
480
- ...(typeof gender === "string" ? { gender } : {}),
481
- ...(typeof currency === "string" ? { currency } : {}),
476
+ ...optional("country"),
477
+ ...optional("gender"),
478
+ ...optional("currency"),
479
+ ...optional("language"),
480
+ addresses: addresses,
482
481
  };
483
482
  }
484
- /** The elements of `value` that are plain objects, as `addresses` are filtered:
485
- * absent or shapeless is `[]`, never a partial read of a malformed entry. */
486
- function plainObjects(value) {
487
- if (!Array.isArray(value))
488
- return [];
489
- return value.filter((e) => asRecord(e) !== null);
490
- }
491
483
  /** Pull the actionable reason out of a 403 body (`user_not_provisioned` /
492
484
  * `principal_mismatch`), defaulting to a generic marker when the shape is
493
485
  * unexpected — the tool surfaces this to drive the right recovery hint. */
@@ -559,16 +551,7 @@ function extractUser(raw) {
559
551
  ...(typeof name === "string" ? { name } : {}),
560
552
  };
561
553
  }
562
- /**
563
- * A non-null plain object, or null for anything else (incl. arrays/primitives).
564
- *
565
- * The array arm decides an OUTCOME at exactly one site, and it is not a body gate:
566
- * {@link extractIdentity} filters `addresses` through this PER ELEMENT, so the return
567
- * value is membership rather than a branch — without the arm a bare array survives and
568
- * ships as one of the buyer's own addresses (pinned in `whoami.integration.test.ts`).
569
- * At the body sites it changes nothing, because each reads a named key and a parsed
570
- * array has none; the element site is the whole reason it stays.
571
- */
554
+ /** A non-null plain object, or null for anything else (incl. arrays/primitives). */
572
555
  function asRecord(value) {
573
556
  return value !== null && typeof value === "object" && !Array.isArray(value)
574
557
  ? value
@@ -17,7 +17,7 @@ export function jsonResult(data, ...extra) {
17
17
  return {
18
18
  content: [data, ...extra].map((part) => ({
19
19
  type: "text",
20
- text: JSON.stringify(part, null, 2),
20
+ text: JSON.stringify(part),
21
21
  })),
22
22
  };
23
23
  }