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,291 @@
1
+ /**
2
+ * Identity tools for the sil plugin.
3
+ *
4
+ * `sil_register` is the real browser-based registration tool (the first tool to
5
+ * replace a stub). It follows the klodi register pattern, adapted to sil-web's
6
+ * PKCE contract and to this skeleton's constraints (no NATS, no system-event
7
+ * wake — the declared SDK has neither).
8
+ *
9
+ * `execute()` flow (ALL I/O lives here — `register()` opens nothing):
10
+ * 1. Already-registered short-circuit. If `tokens.json` exists, return
11
+ * `{ status: "already_registered", user }` — mint nothing, poll nothing,
12
+ * overwrite nothing. (Presence-based, not freshness-based: refresh is SC7.)
13
+ * 2. Mint PKCE in-process. session_id (UUID), verifier (base64url 32 bytes),
14
+ * challenge = S256(verifier). The verifier is held ONLY in the poll step
15
+ * closure below — it never touches disk.
16
+ * 3. Build the auth URL `<apiUrl>/authorize?session=<id>&code_challenge=<chal>`.
17
+ * The plugin does NOT pre-POST to sil-web: the pending session row is
18
+ * INSERTed server-side when the USER's browser opens this URL.
19
+ * 4. Start a fire-and-forget bounded poll of the claim endpoint, then return
20
+ * promptly with `{ status: "awaiting_browser", auth_url, session_id }`.
21
+ * 5. On the poll's terminal success, persist tokens.json + config.json
22
+ * atomically. Other terminals (expired / already_claimed / not_found /
23
+ * timeout) persist nothing; the agent learns the outcome by re-calling
24
+ * sil_register (→ already_registered) or sil_whoami.
25
+ *
26
+ * register() must stay synchronous and side-effect-free beyond registering the
27
+ * tool — no fetch, no timer, no unawaited promise here. The poll timer is armed
28
+ * inside execute(), never at register time.
29
+ */
30
+ import { Type } from "typebox";
31
+ import { getWebUrl, getApiUrl } from "../lib/config.js";
32
+ import { clearTokens, hasTokens, readConfig, readTokens, writeConfig, writeTokens, } from "../lib/credentials.js";
33
+ import { deriveChallenge, newSessionId, newVerifier } from "../lib/pkce.js";
34
+ import { POLL_DEADLINE_MS, POLL_INTERVAL_MS, startPoll, } from "../lib/poller.js";
35
+ import { claimSession, fetchIdentity, refreshAndRetryOnce, } from "../lib/sil-client.js";
36
+ import { jsonResult } from "../lib/tool-result.js";
37
+ export function registerIdentityTools(api) {
38
+ registerRegister(api);
39
+ registerWhoami(api);
40
+ }
41
+ function registerRegister(api) {
42
+ api.registerTool({
43
+ name: "sil_register",
44
+ label: "Register on sil",
45
+ description: "Start browser-based registration on sil. Returns an auth URL for the"
46
+ + " user to open in a browser. The plugin polls the session in the"
47
+ + " background until registration completes (then it stores credentials"
48
+ + " locally), the link expires, or the attempt times out. Call this tool"
49
+ + " again afterwards to confirm registration completed.",
50
+ parameters: Type.Object({}),
51
+ async execute() {
52
+ // 1 — already registered: short-circuit, no mint, no poll, no overwrite.
53
+ if (hasTokens()) {
54
+ const config = readConfig();
55
+ return jsonResult({
56
+ status: "already_registered",
57
+ user: config?.user ?? null,
58
+ });
59
+ }
60
+ // 2 — mint PKCE. The verifier stays in this closure (never on disk).
61
+ const sessionId = newSessionId();
62
+ const verifier = newVerifier();
63
+ const challenge = deriveChallenge(verifier);
64
+ const apiUrl = getWebUrl();
65
+ // 3 — build the auth URL. Opening it (by the user's browser) is what
66
+ // creates the pending session server-side; the plugin does not pre-POST.
67
+ const authUrl = `${stripTrailingSlash(apiUrl)}/authorize`
68
+ + `?session=${sessionId}&code_challenge=${challenge}`;
69
+ // 4 — fire-and-forget bounded poll. Not awaited: execute() returns now.
70
+ // The poll step maps each claim outcome to the loop's done/continue
71
+ // signal AND performs persistence on success (so the atomic write
72
+ // completes inside the awaited tick, before onDone fires); the verifier
73
+ // is captured here and never leaves memory.
74
+ startPoll({
75
+ intervalMs: POLL_INTERVAL_MS,
76
+ deadlineMs: POLL_DEADLINE_MS,
77
+ poll: () => claimStep(apiUrl, sessionId, verifier),
78
+ onDone: (result) => handleDone(api, sessionId, result),
79
+ });
80
+ api.logger.info("sil_register_started", { session_id: sessionId });
81
+ return jsonResult({
82
+ status: "awaiting_browser",
83
+ message: `Open this URL in a browser to register: ${authUrl}`,
84
+ auth_url: authUrl,
85
+ session_id: sessionId,
86
+ instructions: "Share the auth URL with the user. The plugin is polling in the"
87
+ + " background — once the user finishes signing in, call sil_register"
88
+ + " again to confirm (it will report already_registered).",
89
+ });
90
+ },
91
+ });
92
+ }
93
+ /**
94
+ * `sil_whoami` — read the registered user's live identity (name + addresses)
95
+ * from sil-api with the stored Bearer token, refreshing transparently on an
96
+ * expired access token.
97
+ *
98
+ * execute() flow (ALL I/O here; register() opens nothing, arms no timer —
99
+ * whoami is a synchronous request/response, NOT a poll):
100
+ * 1. Read tokens.json. Absent → terminal `not_registered` (run sil_register),
101
+ * ZERO network calls (nothing to authenticate with).
102
+ * 2. fetchIdentity(sil-api, access_token), then route the outcome through the
103
+ * SHARED `refreshAndRetryOnce` choreography — the SAME path sil_search and
104
+ * sil_product_get use, so 401 recovery is uniform across every
105
+ * sil-api-calling tool (factored so the three cannot drift apart; FLAG-10).
106
+ * The helper owns the bounded refresh-and-retry-once: on a 401 it refreshes
107
+ * ONCE via sil-web (rotates tokens.json), re-reads the rotated pair, and
108
+ * retries the read ONCE; a non-401 first outcome passes straight through.
109
+ * 3. Map the helper's discriminant to the agent-facing result:
110
+ * result → ok / forbidden / retryable mapped as usual (the first
111
+ * non-401, OR the retry's non-401 outcome);
112
+ * must_reregister → terminal (clear tokens on invalid_grant);
113
+ * second_unauthorized→ terminal + clear tokens (a freshly-rotated token still
114
+ * rejected is structurally dead — NEVER a second refresh);
115
+ * retryable → terminal transient ("try again").
116
+ * At most one refresh + one retry per call (structural in the helper).
117
+ *
118
+ * Privacy: the access/refresh tokens and the Bearer header never reach a log
119
+ * line or the result; identity PII (name, addresses) is in the result (the
120
+ * point) but never logged. Logs carry only non-credential status markers.
121
+ */
122
+ function registerWhoami(api) {
123
+ api.registerTool({
124
+ name: "sil_whoami",
125
+ label: "Who am I on sil",
126
+ description: "Return the registered user's identity (name and addresses) from sil,"
127
+ + " using the credentials stored by sil_register. If the access token has"
128
+ + " expired it is refreshed transparently and the read is retried. If you"
129
+ + " are not registered, or the session has fully expired, the result names"
130
+ + " the recovery action (run sil_register).",
131
+ parameters: Type.Object({}),
132
+ async execute() {
133
+ // 1 — not registered: terminal, zero network calls.
134
+ const stored = readTokens();
135
+ if (stored === null) {
136
+ return notRegistered();
137
+ }
138
+ // 2 — read identity; on a 401 refresh-and-retry ONCE via the shared
139
+ // choreography (the SAME `refreshAndRetryOnce` path sil_search /
140
+ // sil_product_get use — 401 recovery is uniform across every
141
+ // sil-api-calling tool, factored so the three cannot drift apart).
142
+ const first = await fetchIdentity(getApiUrl(), stored.access_token);
143
+ const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => fetchIdentity(getApiUrl(), accessToken));
144
+ switch (recovered.kind) {
145
+ case "result":
146
+ // The first non-401 outcome, OR the retry's non-401 outcome (ok /
147
+ // forbidden / retryable) — mapped to its terminal/transient/success result.
148
+ // On a silent recovery (`refreshed`: a 401 was healed by the refresh+retry)
149
+ // emit the operator marker so a thrashing session is visible in logs —
150
+ // logs-only, no token material, NOT a payload field (the agent never sees it).
151
+ if (recovered.refreshed)
152
+ api.logger.info("sil_whoami_refreshed", {});
153
+ return identityOutcomeToResult(api, recovered.outcome);
154
+ case "must_reregister":
155
+ // The refresh token is dead (invalid_grant) → clear the now-known-dead
156
+ // pair so the user's sil_register recovery is not blocked by stale
157
+ // presence; a TOCTOU empty re-read (no_stored_tokens) has nothing to clear.
158
+ if (recovered.reason === "invalid_grant")
159
+ clearTokens();
160
+ api.logger.info("sil_whoami_must_reregister", { cause: recovered.reason });
161
+ return mustReregister();
162
+ case "second_unauthorized":
163
+ // A freshly-rotated token STILL rejected is structurally dead — terminal,
164
+ // never another refresh. Clear the dead pair.
165
+ clearTokens();
166
+ api.logger.info("sil_whoami_must_reregister", { cause: "retry_unauthorized" });
167
+ return mustReregister();
168
+ case "retryable":
169
+ api.logger.info("sil_whoami_refresh_retryable", {});
170
+ return transient();
171
+ }
172
+ },
173
+ });
174
+ }
175
+ /** Map a non-401 identity outcome to the agent-facing result. (401 is handled
176
+ * inline by the refresh path; it never reaches here.) */
177
+ function identityOutcomeToResult(api, outcome) {
178
+ switch (outcome.kind) {
179
+ case "ok":
180
+ return identityResult(outcome.identity);
181
+ case "forbidden":
182
+ api.logger.warn("sil_whoami_forbidden", { reason: outcome.reason });
183
+ return forbidden(outcome.reason);
184
+ case "retryable":
185
+ api.logger.info("sil_whoami_retryable", {});
186
+ return transient();
187
+ case "unauthorized":
188
+ // Unreachable in practice (the caller intercepts 401), but the switch is
189
+ // exhaustive so a future refactor can't silently drop a variant.
190
+ return mustReregister();
191
+ }
192
+ }
193
+ /** Success: the identity payload ONLY — no token, no Bearer header. */
194
+ function identityResult(identity) {
195
+ return jsonResult({ status: "ok", identity });
196
+ }
197
+ /** Not registered: a distinct, actionable outcome naming the recovery tool. No
198
+ * identity fields (name/addresses) so the agent can't mistake it for a read. */
199
+ function notRegistered() {
200
+ return jsonResult({
201
+ status: "not_registered",
202
+ message: "Not registered on sil. Run sil_register to authenticate, then call"
203
+ + " sil_whoami again.",
204
+ recovery: "sil_register",
205
+ });
206
+ }
207
+ /** Terminal: the session is fully expired (refresh rejected). Re-register. */
208
+ function mustReregister() {
209
+ return jsonResult({
210
+ status: "must_reregister",
211
+ message: "Your sil session has expired. Run sil_register to sign in again, then"
212
+ + " call sil_whoami again.",
213
+ recovery: "sil_register",
214
+ });
215
+ }
216
+ /** Terminal-but-distinct: the token is valid but the user isn't provisioned (or
217
+ * a principal mismatch). Refreshing would not help — guide the right recovery. */
218
+ function forbidden(reason) {
219
+ const message = reason === "user_not_provisioned"
220
+ ? "Your sil account is not fully set up. Complete onboarding (run"
221
+ + " sil_register) and try again."
222
+ : "sil rejected this request (" + reason + "). Run sil_register to"
223
+ + " re-establish your session, then try again.";
224
+ return jsonResult({ status: "forbidden", reason, message, recovery: "sil_register" });
225
+ }
226
+ /** Transient: a network/5xx blip — try again, NOT a re-register (false terminal). */
227
+ function transient() {
228
+ return jsonResult({
229
+ status: "retryable",
230
+ message: "sil is temporarily unavailable. Please try sil_whoami again.",
231
+ });
232
+ }
233
+ /**
234
+ * One poll step: claim, then map the outcome to the loop's done/continue signal.
235
+ * `pending`/`retryable` keep the loop alive (`done:false`). A successful claim
236
+ * is persisted HERE — tokens.json + config.json written atomically inside this
237
+ * awaited tick — so the files are on disk before the loop settles; the step then
238
+ * carries only the user_id forward (the tokens never travel past this closure).
239
+ * Other terminals (expired / already_claimed / not_found) persist nothing.
240
+ */
241
+ async function claimStep(apiUrl, sessionId, verifier) {
242
+ const outcome = await claimSession(apiUrl, sessionId, verifier);
243
+ switch (outcome.kind) {
244
+ case "pending":
245
+ case "retryable":
246
+ return { done: false };
247
+ case "success":
248
+ await writeTokens({
249
+ access_token: outcome.access_token,
250
+ refresh_token: outcome.refresh_token,
251
+ });
252
+ await writeConfig({ user: outcome.user });
253
+ return { done: true, outcome: "success", user_id: outcome.user.id };
254
+ case "expired":
255
+ case "already_claimed":
256
+ case "not_found":
257
+ return { done: true, outcome: outcome.kind };
258
+ }
259
+ }
260
+ /**
261
+ * Record a structured log on every terminal so no outcome is silent. Tokens are
262
+ * already persisted (in `claimStep`) and are NEVER logged — the success case
263
+ * logs only the user id.
264
+ */
265
+ function handleDone(api, sessionId, result) {
266
+ const step = result;
267
+ if (step.outcome === "success") {
268
+ api.logger.info("sil_register_claimed", {
269
+ session_id: sessionId,
270
+ user_id: typeof step.user_id === "string" ? step.user_id : "",
271
+ });
272
+ return;
273
+ }
274
+ if ("timedOut" in step && step.timedOut === true) {
275
+ api.logger.info("sil_register_timeout", { session_id: sessionId });
276
+ return;
277
+ }
278
+ // expired / already_claimed / not_found — log the terminal so the outcome is
279
+ // never silent; the agent learns it on its next sil_register / sil_whoami.
280
+ const outcome = typeof step.outcome === "string" ? step.outcome : "unknown";
281
+ const marker = `sil_register_${outcome}`;
282
+ if (outcome === "not_found") {
283
+ api.logger.warn(marker, { session_id: sessionId });
284
+ }
285
+ else {
286
+ api.logger.info(marker, { session_id: sessionId });
287
+ }
288
+ }
289
+ function stripTrailingSlash(url) {
290
+ return url.endsWith("/") ? url.slice(0, -1) : url;
291
+ }
@@ -0,0 +1,71 @@
1
+ {
2
+ "id": "sil",
3
+ "name": "sil",
4
+ "description": "sil commerce plugin for OpenClaw — register on sil, read your identity, and search and look up products in the sil catalog.",
5
+ "version": "0.2.0",
6
+ "skills": ["./skill"],
7
+ "activation": {
8
+ "onCapabilities": ["tool"]
9
+ },
10
+ "contracts": {
11
+ "tools": [
12
+ "sil_product_get",
13
+ "sil_register",
14
+ "sil_search",
15
+ "sil_whoami"
16
+ ]
17
+ },
18
+ "configSchema": {
19
+ "type": "object",
20
+ "additionalProperties": false,
21
+ "properties": {
22
+ "sil_web_url": {
23
+ "type": "string",
24
+ "format": "uri",
25
+ "description": "Override for the sil-web origin (the auth authority — token refresh, registration). Falls back to the SIL_WEB_URL env var, then https://sil.4gpts.com."
26
+ },
27
+ "sil_api_url": {
28
+ "type": "string",
29
+ "format": "uri",
30
+ "description": "Override for the sil-api origin (the domain service — sil_whoami's identity read). Distinct from sil_web_url (sil-web). Falls back to the SIL_API_URL env var, then https://sil-api.4gpts.com. Set this at deploy to pin the sil-api host (or to the same origin as sil_web_url if a single gateway fronts both)."
31
+ }
32
+ }
33
+ },
34
+ "uiHints": {
35
+ "sil_web_url": {
36
+ "label": "sil-web URL (auth)",
37
+ "help": "The sil-web origin — handles registration and token refresh. Override only for staging or self-hosted deployments.",
38
+ "placeholder": "https://sil.4gpts.com",
39
+ "advanced": true
40
+ },
41
+ "sil_api_url": {
42
+ "label": "sil-api URL (identity)",
43
+ "help": "The sil-api origin — sil_whoami reads the user's identity here. Distinct from the sil-web URL. Override for staging or self-hosted deployments.",
44
+ "placeholder": "https://sil-api.4gpts.com",
45
+ "advanced": true
46
+ }
47
+ },
48
+ "security": {
49
+ "shipsRuntimeCode": true,
50
+ "packagingNote": "Compiled JavaScript ships under ./dist. register() stays synchronous and opens nothing — it only registers tools. ALL I/O happens inside a tool's execute(): sil_register calls sil-web over the network, writes tokens.json + config.json to the plugin data directory (owner-only, 0600), and arms a bounded background poll timer that stops on the first terminal claim outcome or after the session deadline. sil_whoami reads the stored access token and calls sil-api for the user's identity, refreshing transparently via sil-web on a 401 (at most one refresh + one retry per call, no timer); a confirmed-dead session clears tokens.json. sil_search and sil_product_get read the stored access token and call sil-api's catalog endpoints (search / lookup) with it — read-only, no token write, no timer, a single round-trip (a 401 is a terminal re-register hint, no refresh). The PKCE verifier is held only in memory and is never written to disk. Tokens and identity PII are never logged.",
51
+ "registersLongLivedService": false,
52
+ "serviceIds": [],
53
+ "runsTimers": true,
54
+ "inboundHttpRoutes": [],
55
+ "networkEndpoints": [
56
+ "https://sil-api.4gpts.com",
57
+ "https://sil.4gpts.com"
58
+ ],
59
+ "filesystemScope": [
60
+ "$SIL_DATA_DIR (default $XDG_DATA_HOME/sil, else ~/.local/share/sil) — tokens.json, config.json"
61
+ ],
62
+ "credentialsOnDisk": [
63
+ "tokens.json (access + refresh token)",
64
+ "config.json (user identity)"
65
+ ],
66
+ "noNativeModules": true,
67
+ "noChildProcess": true,
68
+ "noInstallScripts": true,
69
+ "reportVulnerabilitiesTo": "https://x.com/4gpts"
70
+ }
71
+ }
package/package.json ADDED
@@ -0,0 +1,97 @@
1
+ {
2
+ "name": "sil-openclaw",
3
+ "version": "0.2.0",
4
+ "description": "OpenClaw plugin for sil — register an identity and search and look up products in the sil commerce catalog from an agent.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Context4GPTs/sil-openclaw.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/Context4GPTs/sil-openclaw/issues"
12
+ },
13
+ "homepage": "https://4gpts.com",
14
+ "keywords": [
15
+ "openclaw",
16
+ "openclaw-plugin",
17
+ "sil",
18
+ "commerce",
19
+ "catalog",
20
+ "agent",
21
+ "ucp",
22
+ "4gpts"
23
+ ],
24
+ "type": "module",
25
+ "engines": {
26
+ "node": ">=22"
27
+ },
28
+ "main": "./dist/index.js",
29
+ "files": [
30
+ "dist",
31
+ "skill",
32
+ "openclaw.plugin.json",
33
+ "README.md",
34
+ "CHANGELOG.md",
35
+ "SECURITY.md",
36
+ "LICENSE",
37
+ "NOTICE"
38
+ ],
39
+ "publishConfig": {
40
+ "registry": "https://registry.npmjs.org/"
41
+ },
42
+ "openclaw": {
43
+ "extensions": [
44
+ "./dist/index.js"
45
+ ],
46
+ "compat": {
47
+ "pluginApi": ">=2026.4.1",
48
+ "minGatewayVersion": ">=2026.4.15"
49
+ },
50
+ "build": {
51
+ "openclawVersion": "2026.4.15",
52
+ "pluginSdkVersion": "2026.4.15"
53
+ },
54
+ "hostTargets": [
55
+ "darwin-arm64",
56
+ "darwin-x64",
57
+ "linux-x64",
58
+ "linux-arm64",
59
+ "win32-x64"
60
+ ],
61
+ "environment": {
62
+ "externalServices": [
63
+ "sil-web",
64
+ "sil-api"
65
+ ]
66
+ },
67
+ "install": {
68
+ "npmSpec": "sil-openclaw",
69
+ "localPath": "./",
70
+ "defaultChoice": "npm",
71
+ "minHostVersion": ">=2026.4.15"
72
+ }
73
+ },
74
+ "scripts": {
75
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
76
+ "build": "pnpm clean && tsc -p tsconfig.build.json",
77
+ "typecheck": "tsc --noEmit",
78
+ "dev": "tsc -p tsconfig.build.json --watch",
79
+ "test": "vitest run --passWithNoTests",
80
+ "test:watch": "vitest",
81
+ "sync-version": "node scripts/sync-version.mjs",
82
+ "preversion": "pnpm typecheck && pnpm test",
83
+ "version": "pnpm sync-version && node scripts/changelog.mjs cut && git add openclaw.plugin.json CHANGELOG.md",
84
+ "postversion": "git push --follow-tags",
85
+ "prepack": "pnpm build",
86
+ "release": "node scripts/release.mjs",
87
+ "release:dry": "node scripts/release.mjs --dry-run"
88
+ },
89
+ "dependencies": {
90
+ "typebox": "^1.2.2"
91
+ },
92
+ "devDependencies": {
93
+ "@types/node": "22.15.3",
94
+ "typescript": "5.8.3",
95
+ "vitest": "4.1.2"
96
+ }
97
+ }
package/skill/SKILL.md ADDED
@@ -0,0 +1,62 @@
1
+ ---
2
+ name: sil
3
+ description: This skill should be used when the user wants to shop on sil — register an identity, see who they are, search the catalog for purchasable products, or look up specific products by id. The plugin exposes sil_register, sil_whoami, sil_search, and sil_product_get.
4
+ metadata:
5
+ openclaw:
6
+ emoji: "\U0001F6D2"
7
+ ---
8
+
9
+ # sil
10
+
11
+ ## 1. Role
12
+
13
+ Drive the sil plugin's tools on the user's behalf: register them on sil, read their identity, and help them find purchasable products in the sil catalog. Read user intent, pick the matching tool, call it, and report what came back.
14
+
15
+ Principles:
16
+
17
+ - **Act, don't narrate.** When intent maps to a tool, call it. Don't re-confirm what was already stated.
18
+ - **Fail visibly, recover correctly.** Every tool returns a `status`. On a non-`ok` status, say what happened and follow the tool's own `recovery` hint — never improvise a different one (re-registering can't fix a bad query or a transient 5xx, and would derail the user).
19
+ - **Relay prices as point-in-time.** A product's price, availability, and `checkout_url` are a snapshot, not a guarantee. Before the user buys, re-fetch with `sil_product_get` rather than trusting an earlier `sil_search` result.
20
+
21
+ ## 2. Session start
22
+
23
+ Confirm the `sil_*` tools are exposed. If they are missing from the available tool list, the host runtime is filtering them out — tell the user to consult the host's tool-allowlist docs and stop.
24
+
25
+ Most flows need an identity. If the user has not registered this session, the catalog tools return `status: "not_registered"` with `recovery: "sil_register"` — so you can call a catalog tool first and let that outcome route you, or run `sil_register` up front when the user's intent clearly requires it.
26
+
27
+ ## 3. Acting on user intent
28
+
29
+ When intent maps to a tool, execute:
30
+
31
+ | Intent | Tool |
32
+ |---|---|
33
+ | "sign me up" / "log me in to sil" / "register" | `sil_register` (takes no arguments; returns an auth URL to open in a browser) |
34
+ | "who am I?" / "what's on my account" / show my saved name + addresses | `sil_whoami` (takes no arguments) |
35
+ | "find X" / "search for X" / browse a category or price range | `sil_search` (free-text `query` and/or `category`, `price_min`, `price_max`; paginate with `cursor`/`limit`) |
36
+ | "look up these items" / re-check ids from a prior result, a saved list, or a deep link | `sil_product_get` (pass `ids` — one or more product/variant ids) |
37
+
38
+ How each behaves:
39
+
40
+ - **`sil_register`** starts browser-based registration. It returns promptly with `status: "awaiting_browser"` and an `auth_url` — share that URL with the user. The plugin polls in the background; once the user finishes signing in, call `sil_register` again to confirm (it reports `already_registered`).
41
+ - **`sil_whoami`** returns the registered user's identity (name and addresses). An expired access token is refreshed transparently and the read retried; if the session is fully dead, the result names the recovery (`sil_register`).
42
+ - **`sil_search`** returns a ranked list of purchasable variants (`id`, `title`, `price`, `availability`, `checkout_url`, `source`), best match first — present them in order, do not re-rank. An empty list means nothing matched: a normal `ok` outcome, not an error. Use the returned `cursor` for the next page; its absence means no more results (never infer end-of-results from page size).
43
+ - **`sil_product_get`** is the lookup companion to `sil_search`. Pass ids you already hold and get the matching products back with fresh detail (description, options, the featured variant). Each variant carries an `inputs` list correlating it back to the id(s) you asked about (the response is NOT in request order). Ids that no longer resolve come back in a `not_found` list — a normal partial-success outcome, not an error; the other products are still valid.
44
+
45
+ All four return the canonical envelope: a single text content block whose JSON body carries a `status`. Prices are in the currency's ISO 4217 minor unit (e.g. cents).
46
+
47
+ ### Status taxonomy (shared across the tools)
48
+
49
+ | `status` | Meaning | What to do |
50
+ |---|---|---|
51
+ | `ok` | Success. Catalog results may be empty (`products: []`) or partial (`not_found: [...]`) — still a success. | Relay the data. |
52
+ | `not_registered` | No stored credentials. | Run `sil_register`, then retry the tool. |
53
+ | `must_reregister` | The session is dead (refresh rejected / 401). | Run `sil_register` to sign in again, then retry. |
54
+ | `forbidden` | Authenticated but not authorized (e.g. account not provisioned). | Follow the message; usually complete onboarding via `sil_register`. |
55
+ | `invalid_request` | The query/ids were rejected (e.g. empty input). | Fix the input and call again — do NOT re-register. |
56
+ | `retryable` | A transient network/5xx blip. | Try the same call again — do NOT re-register. |
57
+
58
+ ## 4. Adding a real tool
59
+
60
+ The mechanical steps live in the repo's `CLAUDE.md` ("How to add a tool"); the short version is three steps: register the tool inside a `registerXTools(api)` group in `src/tools/`, wire that group into `register()` in `src/index.ts`, and add the tool's name to `openclaw.plugin.json#contracts.tools`. The manifest↔code drift-guard test fails if those disagree, which keeps the pattern self-enforcing.
61
+
62
+ The reference group is `src/tools/identity.ts` (`sil_register`, `sil_whoami`) — it sets the `jsonResult` success shape and the structured-error/recovery envelope every real tool follows; `src/tools/catalog.ts` (`sil_search`, `sil_product_get`) is the catalog counterpart. All I/O lives inside a tool's `execute()`; `register()` stays synchronous and opens nothing.