sil-openclaw 0.4.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/README.md +33 -45
  3. package/dist/gateway/search-results.js +11 -7
  4. package/dist/index.js +24 -24
  5. package/dist/lib/allowlist-script.js +13 -0
  6. package/dist/lib/artifacts.js +30 -0
  7. package/dist/lib/credentials.js +2 -3
  8. package/dist/lib/host-wiring.js +44 -15
  9. package/dist/lib/pkce.js +3 -3
  10. package/dist/lib/search-results-log.js +23 -0
  11. package/dist/lib/search-results-store.js +13 -10
  12. package/dist/lib/shopping-call.js +143 -0
  13. package/dist/lib/sil-client.js +185 -1046
  14. package/dist/lib/tool-result.js +10 -3
  15. package/dist/tools/catalog.js +311 -1197
  16. package/dist/tools/doctor.js +25 -63
  17. package/dist/tools/identity.js +110 -245
  18. package/openclaw.plugin.json +16 -12
  19. package/package.json +7 -6
  20. package/schema/PROVENANCE.md +15 -0
  21. package/schema/shopping-brief-create-request.schema.json +98 -0
  22. package/schema/shopping-brief-create-response.schema.json +24 -0
  23. package/schema/shopping-brief-edit-request.schema.json +125 -0
  24. package/schema/shopping-brief-edit-response.schema.json +24 -0
  25. package/schema/shopping-brief-read-request.schema.json +15 -0
  26. package/schema/shopping-brief-read-response.schema.json +235 -0
  27. package/schema/shopping-domain-create-request.schema.json +160 -0
  28. package/schema/shopping-domain-create-response.schema.json +60 -0
  29. package/schema/shopping-domain-get-request.schema.json +18 -0
  30. package/schema/shopping-domain-get-response.schema.json +307 -0
  31. package/schema/shopping-domain-search-request.schema.json +18 -0
  32. package/schema/shopping-domain-search-response.schema.json +92 -0
  33. package/schema/shopping-offers-request.schema.json +31 -0
  34. package/schema/shopping-offers-response.schema.json +172 -0
  35. package/schema/shopping-product-get-request.schema.json +24 -0
  36. package/schema/shopping-product-get-response.schema.json +121 -0
  37. package/schema/shopping-profile-edit-request.schema.json +97 -0
  38. package/schema/shopping-profile-edit-response.schema.json +17 -0
  39. package/schema/shopping-search-request.schema.json +106 -0
  40. package/schema/shopping-search-response.schema.json +182 -0
  41. package/schema/shopping-seller-get-request.schema.json +24 -0
  42. package/schema/shopping-seller-get-response.schema.json +342 -0
  43. package/scripts/allowlist-openclaw.mjs +4 -5
  44. package/sil-shopping/SKILL.md +196 -97
  45. package/sil-shopping/references/mint.md +190 -0
  46. package/dist/lib/bind-channel.js +0 -10
  47. package/dist/lib/creation-entrypoint.js +0 -111
  48. package/dist/lib/derive-agent-id.js +0 -36
  49. package/dist/lib/profile-store.js +0 -568
  50. package/dist/tools/profile.js +0 -300
  51. package/scripts/create-shopper.mjs +0 -677
  52. package/sil-shopping/examples/multi_domain_shopper_walkthrough.md +0 -65
  53. package/sil-shopping/references/agent_creation_engine.md +0 -223
  54. package/sil-shopping/references/fill_and_feedback.md +0 -102
  55. package/sil-shopping/references/method_and_prds.md +0 -143
  56. package/sil-shopping/references/setup_onboarding.md +0 -64
  57. package/sil-shopping/references/shop_loop.md +0 -118
@@ -1,99 +1,66 @@
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 / invalid_request /
23
- * timeout) persist nothing; the agent learns the outcome by re-calling
24
- * sil_register (→ already_registered) or sil_whoami. A claim 404 (`not_found`)
25
- * is NOT a terminal — it is the normal pre-session early state and keeps the
26
- * poll ticking; a session that never appears ends as `timeout` at the deadline.
27
- *
28
- * register() must stay synchronous and side-effect-free beyond registering the
29
- * tool — no fetch, no timer, no unawaited promise here. The poll timer is armed
30
- * inside execute(), never at register time.
31
- */
32
1
  import { Type } from "typebox";
33
2
  import { getWebUrl, getWebUrlSource, getApiUrl } from "../lib/config.js";
34
3
  import { clearTokens, getTokensPath, hasTokens, readConfig, readTokens, writeConfig, writeTokens, } from "../lib/credentials.js";
35
4
  import { wiringAdvisories } from "../lib/host-wiring.js";
36
5
  import { deriveChallenge, newSessionId, newVerifier } from "../lib/pkce.js";
37
6
  import { POLL_DEADLINE_MS, POLL_INTERVAL_MS, startPoll, } from "../lib/poller.js";
38
- import { claimSession, fetchIdentity, refreshAndRetryOnce, } from "../lib/sil-client.js";
7
+ import { claimSession, fetchIdentity, refreshAndRetryOnce, stripTrailingSlash, } from "../lib/sil-client.js";
39
8
  import { jsonResult } from "../lib/tool-result.js";
40
9
  export function registerIdentityTools(api) {
41
10
  registerRegister(api);
42
11
  registerWhoami(api);
43
12
  }
13
+ /**
14
+ * All of registration's I/O lives in execute(): a fresh call mints PKCE, returns
15
+ * the link at once, and arms ONE bounded background poll of the claim endpoint,
16
+ * which persists the token pair on its only success. A claim 404 is the normal
17
+ * pre-open state and keeps polling; every other terminal persists nothing and is
18
+ * learnt by calling sil_register again.
19
+ */
44
20
  function registerRegister(api) {
45
21
  api.registerTool({
46
22
  name: "sil_register",
47
23
  label: "Register on sil",
48
- description: "Start browser-based registration on sil. Returns an auth URL for the"
49
- + " user to open in a browser. The plugin polls the session in the"
50
- + " background until registration completes (then it stores credentials"
51
- + " locally), the link expires, or the attempt times out. Call this tool"
52
- + " again afterwards to confirm registration completed.",
24
+ description: "Hand the buyer a link that opens. `open` is the whole link: show it on its"
25
+ + " own line so nothing breaks it, and let the buyer open it themselves. The"
26
+ + " plugin polls in the background and stores the credentials once they"
27
+ + " finish, so call sil_register again to confirm — it answers"
28
+ + " already_registered. A buyer who is already registered gets that answer"
29
+ + " straight away: carry on with what they asked for, nothing is offered and"
30
+ + " nothing is created.",
53
31
  parameters: Type.Object({}),
54
32
  async execute() {
55
33
  // 1 — already registered: short-circuit, no mint, no poll, no overwrite.
56
- // `next_step` is an ADDITIVE, UNCONDITIONAL routing hint (not a decision):
57
- // it tells the skill "the moment after a confirmed registration is where to
58
- // introduce the shopper". identity.ts stays decoupled from the profile store
59
- // — it reads NO shopper state here; the skill owns the actual gate (a no-arg
60
- // sil_profile_get empty-store check) so a user who already has a shopper is
61
- // never offered a second one (the shopper is a singleton). The hint rides
62
- // ONLY this confirmed-registration path — never the pre-registration
63
- // `awaiting_browser` return, nor any poll/error terminal.
34
+ // Nothing is offered or created here (contract §3.10): the agent carries on.
64
35
  if (hasTokens()) {
65
36
  const config = readConfig();
66
37
  return jsonResult({
67
38
  status: "already_registered",
68
39
  user: config?.user ?? null,
69
- next_step: "offer_shopper",
70
- // Folded here but NOT onto `awaiting_browser`: this is a terminal
71
- // result, whereas that one is a mid-flow auth handoff whose whole job
72
- // is to get one link in front of the user.
40
+ // Folded here but NOT onto `awaiting_browser`: that one is a hand-off
41
+ // whose whole job is to get one link in front of the buyer.
73
42
  ...wiringAdvisories(api),
74
43
  });
75
44
  }
76
- // A fresh registration attempt clears any prior in-process persist-failure
77
- // marker: this process is starting over, so a stale marker from an earlier
78
- // failed attempt must not make a later genuine `not_registered` (or this
79
- // attempt's own outcome) masquerade as `persistence_failed`. (FIX C.)
45
+ // A fresh attempt clears any prior in-process persist-failure marker, so a
46
+ // stale one cannot make a later genuine `not_registered` read as
47
+ // `persistence_failed`.
80
48
  clearPersistFailure();
81
49
  // 2 — mint PKCE. The verifier stays in this closure (never on disk).
82
50
  const sessionId = newSessionId();
83
51
  const verifier = newVerifier();
84
52
  const challenge = deriveChallenge(verifier);
85
- // The sil-WEB origin (auth authority) — this is what the auth URL is built
86
- // from. The local was historically misnamed `apiUrl`; it is the web origin.
87
53
  const webUrl = getWebUrl();
88
- // 3 — build the auth URL. Opening it (by the user's browser) is what
89
- // creates the pending session server-side; the plugin does not pre-POST.
90
- const authUrl = `${stripTrailingSlash(webUrl)}/authorize`
91
- + `?session=${sessionId}&code_challenge=${challenge}`;
54
+ // 3 — the session rides in the PATH: every OpenClaw host masks the value of
55
+ // a query parameter named `session`, so a `?session=` link reaches the buyer
56
+ // as `session=***` and sil-web answers invalid_session. Opening this link is
57
+ // what creates the pending session server-side; the plugin does not pre-POST.
58
+ const open = `${stripTrailingSlash(webUrl)}/authorize/${sessionId}`
59
+ + `?code_challenge=${challenge}`;
92
60
  // 4 — fire-and-forget bounded poll. Not awaited: execute() returns now.
93
- // The poll step maps each claim outcome to the loop's done/continue
94
- // signal AND performs persistence on success (so the atomic write
95
- // completes inside the awaited tick, before onDone fires); the verifier
96
- // is captured here and never leaves memory.
61
+ // The poll step persists on success inside its own awaited tick, so the
62
+ // files are on disk before the loop settles; the verifier is captured here
63
+ // and never leaves memory.
97
64
  startPoll({
98
65
  intervalMs: POLL_INTERVAL_MS,
99
66
  deadlineMs: POLL_DEADLINE_MS,
@@ -103,90 +70,60 @@ function registerRegister(api) {
103
70
  api.logger.info("sil_register_started", { session_id: sessionId });
104
71
  return jsonResult({
105
72
  status: "awaiting_browser",
106
- // The steer lead line routes the user into their OWN default browser
107
- // BEFORE the Auth0 leg (where Auth0's session cookie works on its own
108
- // domain), instead of an in-app/embedded webview that partitions it and
109
- // dead-ends the login. It is a SEPARATE line ABOVE the link, so the link
110
- // line stays exactly `<authUrl>` — ONE atomic, angle-bracket-wrapped
111
- // target that a greedy chat auto-linker captures WHOLE (`&code_challenge`
112
- // included) instead of truncating at the `&` and 400-ing
113
- // `invalid_code_challenge`. `auth_url` below stays the canonical,
114
- // UNWRAPPED machine field agents parse. (FIX A + system-browser steer.)
115
- message: BROWSER_STEER_HUMAN
116
- + "\n"
117
- + presentAuthLink(authUrl),
118
- auth_url: authUrl,
119
- session_id: sessionId,
120
- // The agent-facing steer MUST agree with the human `message` (both built
121
- // from the shared BROWSER_STEER_NEGATIVE clause) so an agent relaying the
122
- // instruction can't paraphrase it back to a generic "a browser" and
123
- // re-open the cookie-blocking-webview gap.
124
- instructions: "Share the auth URL with the user and tell them to "
73
+ open,
74
+ // The steer is a SEPARATE line above the link, so the link line stays
75
+ // exactly `<open>` — one atomic target a greedy chat auto-linker captures
76
+ // whole rather than truncating mid-URL.
77
+ message: BROWSER_STEER_HUMAN + "\n" + presentAuthLink(open),
78
+ // Built from the same negative clause as `message`, so an agent relaying
79
+ // it cannot paraphrase back to a generic "a browser".
80
+ instructions: "Share the link with the buyer and tell them to "
125
81
  + BROWSER_STEER_AGENT
126
- + " The plugin is polling in the background — once the user finishes"
127
- + " signing in, call sil_register again to confirm (it will report"
82
+ + " The plugin is polling in the background — once they finish signing"
83
+ + " in, call sil_register again to confirm (it will report"
128
84
  + " already_registered).",
129
85
  });
130
86
  },
131
87
  });
132
88
  }
133
89
  /**
134
- * `sil_whoami` — read the registered user's live identity (name + addresses)
135
- * from sil-api with the stored Bearer token, refreshing transparently on an
136
- * expired session token.
137
- *
138
- * execute() flow (ALL I/O here; register() opens nothing, arms no timer —
139
- * whoami is a synchronous request/response, NOT a poll):
140
- * 1. Read tokens.json. Absent → terminal `not_registered` (run sil_register),
141
- * ZERO network calls (nothing to authenticate with).
142
- * 2. fetchIdentity(sil-api, access_token), then route the outcome through the
143
- * SHARED `refreshAndRetryOnce` choreography — the SAME path sil_search and
144
- * sil_product_get use, so 401 recovery is uniform across every
145
- * sil-api-calling tool (factored so the three cannot drift apart; FLAG-10).
146
- * The helper owns the bounded refresh-and-retry-once: on a 401 it refreshes
147
- * ONCE via sil-web (rotates tokens.json), re-reads the rotated pair, and
148
- * retries the read ONCE; a non-401 first outcome passes straight through.
149
- * 3. Map the helper's discriminant to the agent-facing result:
150
- * result → ok / forbidden / retryable mapped as usual (the first
151
- * non-401, OR the retry's non-401 outcome);
152
- * must_reregister → terminal (clear tokens on invalid_grant);
153
- * second_unauthorized→ terminal + clear tokens (a freshly-rotated token still
154
- * rejected is structurally dead — NEVER a second refresh);
155
- * retryable → terminal transient ("try again").
156
- * At most one refresh + one retry per call (structural in the helper).
157
- *
158
- * Privacy: the access/refresh tokens and the Bearer header never reach a log
159
- * line or the result; identity PII (name, addresses) is in the result (the
160
- * point) but never logged. Logs carry only non-credential status markers.
90
+ * A live read, never a poll. The 401 recovery is the SHARED `refreshAndRetryOnce`
91
+ * every `shopping_*` call uses, so the tools cannot drift apart: at most one
92
+ * refresh and one retry per call, and a freshly-rotated token still rejected is
93
+ * structurally dead — clear the pair, never refresh twice. Identity PII rides the
94
+ * result and is never logged; tokens reach neither.
161
95
  */
162
96
  function registerWhoami(api) {
163
97
  api.registerTool({
164
98
  name: "sil_whoami",
165
99
  label: "Who am I on sil",
166
- description: "Return the registered user's identity (name and addresses) from sil,"
167
- + " using the credentials stored by sil_register. If the stored session token"
168
- + " has expired it is refreshed transparently and the read is retried. If you"
169
- + " are not registered, or the session has fully expired, the result names"
170
- + " the recovery action (run sil_register).",
100
+ description: "The buyer's name, country, `gender`, `currency` and the addresses on file, and"
101
+ + " the `measurements` and `preferences` sil already holds for them — read live from"
102
+ + " sil with the credentials sil_register stored, a stale session token refreshed"
103
+ + " once and the read retried. `gender` is `male`, `female` or `other`, and is"
104
+ + " absent where the buyer never stated one; on anything worn it is the product"
105
+ + " spec `gender` in the registry's own spelling (male → `mens`, female →"
106
+ + " `womens`), asked once where this answers none and never inferred. `currency` is"
107
+ + " the ISO 4217 code they price in, absent where nothing on file says it: a money"
108
+ + " row that means theirs leaves `currency` off — with none on file, it names its"
109
+ + " own — and sil converts nothing. Call it at the start of a chat: it"
110
+ + " says where the buyer is, what they price in, how they measure and what they"
111
+ + " lastingly prefer, and you never ask them for anything it answers."
112
+ + " shopping_profile_edit is what writes those last three back. If they are not"
113
+ + " registered, or the session is past refreshing, the result names the recovery"
114
+ + " (sil_register).",
171
115
  parameters: Type.Object({}),
172
116
  async execute() {
173
- // 1 — not registered: terminal, zero network calls. If THIS process saw a
174
- // token-persist failure (auth succeeded but the write failed), surface the
175
- // distinct `persistence_failed` state instead — the no-tokens.json state on
176
- // disk is identical for both, so the in-process marker is the only signal
177
- // that tells them apart (FIX C; cold-restart correctly degrades to
178
- // not_registered — see the persistence_failed/notRegistered helpers).
117
+ // 1 — no tokens on disk is the SAME state for a never-registered buyer and
118
+ // for one whose token write failed in this process, so the in-process marker
119
+ // is the only thing that tells the two apart.
179
120
  const stored = readTokens();
180
121
  if (stored === null) {
181
122
  const failure = getPersistFailure();
182
123
  return failure !== null ? persistenceFailed(failure) : notRegistered();
183
124
  }
184
- // B (origin visibility): resolve the sil-WEB origin (the origin the
185
- // registration link is built from) + its source, surface it on the success
186
- // payload so a wrong/staging origin is diagnosable BEFORE anything 404s,
187
- // and emit a single warn when the source is non-default. Warn-only — a
188
- // staging/self-host origin is legitimate, so it is NEVER rejected. Scope is
189
- // the WEB origin only; the sil-api read origin is out of scope. (FIX B.)
125
+ // A staging/self-host web origin is legitimate, so it is surfaced and warned
126
+ // about, never rejected — a wrong one is then diagnosable before anything 404s.
190
127
  const webOrigin = getWebUrl();
191
128
  const webOriginSource = getWebUrlSource();
192
129
  if (webOriginSource !== "default") {
@@ -199,26 +136,20 @@ function registerWhoami(api) {
199
136
  web_origin: webOrigin,
200
137
  web_origin_source: webOriginSource,
201
138
  };
202
- // 2 — read identity; on a 401 refresh-and-retry ONCE via the shared
203
- // choreography (the SAME `refreshAndRetryOnce` path sil_search /
204
- // sil_product_get use — 401 recovery is uniform across every
205
- // sil-api-calling tool, factored so the three cannot drift apart).
139
+ // 2 — read identity; on a 401 refresh-and-retry ONCE, shared with every
140
+ // `shopping_*` call so the recovery cannot drift between tools.
206
141
  const first = await fetchIdentity(getApiUrl(), stored.access_token);
207
142
  const recovered = await refreshAndRetryOnce(first, (o) => o.kind === "unauthorized", (accessToken) => fetchIdentity(getApiUrl(), accessToken));
208
143
  switch (recovered.kind) {
209
144
  case "result":
210
- // The first non-401 outcome, OR the retry's non-401 outcome (ok /
211
- // forbidden / retryable) — mapped to its terminal/transient/success result.
212
- // On a silent recovery (`refreshed`: a 401 was healed by the refresh+retry)
213
- // emit the operator marker so a thrashing session is visible in logs —
214
- // logs-only, no token material, NOT a payload field (the agent never sees it).
145
+ // Logs-only, never a payload field: a session thrashing through silent
146
+ // 401 recoveries is invisible otherwise.
215
147
  if (recovered.refreshed)
216
148
  api.logger.info("sil_whoami_refreshed", {});
217
149
  return identityOutcomeToResult(api, recovered.outcome, originBlock);
218
150
  case "must_reregister":
219
- // The refresh token is dead (invalid_grant) → clear the now-known-dead
220
- // pair so the user's sil_register recovery is not blocked by stale
221
- // presence; a TOCTOU empty re-read (no_stored_tokens) has nothing to clear.
151
+ // Clear the known-dead pair so its stale presence cannot block the
152
+ // sil_register recovery; an empty re-read has nothing to clear.
222
153
  if (recovered.reason === "invalid_grant")
223
154
  clearTokens();
224
155
  api.logger.info("sil_whoami_must_reregister", { cause: recovered.reason });
@@ -236,24 +167,16 @@ function registerWhoami(api) {
236
167
  },
237
168
  });
238
169
  }
239
- /** Map a non-401 identity outcome to the agent-facing result. (401 is handled
240
- * inline by the refresh path; it never reaches here.) The origin block rides the
241
- * SUCCESS payload (the point is pre-failure diagnosis); the terminal/transient
242
- * envelopes don't carry it. */
170
+ /** Map a non-401 identity outcome to the agent-facing result. The origin block
171
+ * rides the SUCCESS payload only — pre-failure diagnosis is its whole point. */
243
172
  function identityOutcomeToResult(api, outcome, originBlock) {
244
173
  switch (outcome.kind) {
245
174
  case "ok":
246
175
  return identityResult(api, outcome.identity, originBlock);
247
176
  case "forbidden":
248
- // Decision B — the dead-token clear is UNIFORM across all three sil-api tools.
249
- // `sil_whoami` is the tool that is legible TODAY; an agent that diagnoses the
250
- // 403 via whoami, follows `recovery:"sil_register"`, and hits
251
- // `already_registered` is stranded identically to the catalog path. So clear on
252
- // `user_not_provisioned` HERE too (the held token maps to no account on this
253
- // backend; a refresh cannot help — structurally dead, like the invalid_grant
254
- // clear above). Gated on EXACT equality: `principal_mismatch` / unknown reasons
255
- // can be transient and must stay recoverable, so they keep the legible forbidden
256
- // envelope WITHOUT a destructive clear (AC9 clears, AC10 does not).
177
+ // A token that maps to no account is structurally dead, so clear it or the
178
+ // sil_register recovery answers `already_registered` and strands the buyer.
179
+ // EXACT equality: `principal_mismatch` can be transient and must survive.
257
180
  api.logger.warn("sil_whoami_forbidden", { reason: outcome.reason });
258
181
  if (outcome.reason === "user_not_provisioned")
259
182
  clearTokens();
@@ -267,9 +190,8 @@ function identityOutcomeToResult(api, outcome, originBlock) {
267
190
  return mustReregister();
268
191
  }
269
192
  }
270
- /** Success: the identity payload + the web-origin visibility block (FIX B) —
271
- * no token, no Bearer header. The origin block (strings only) lets the agent
272
- * relay the resolved origin + its source so a wrong origin is diagnosable. */
193
+ /** Success: `identity` carries the buyer's name, country, gender and currency (each when
194
+ * the read has one), addresses, measurements and preferences — no token, no Bearer header. */
273
195
  function identityResult(api, identity, originBlock) {
274
196
  return jsonResult({
275
197
  status: "ok",
@@ -289,12 +211,9 @@ function notRegistered() {
289
211
  });
290
212
  }
291
213
  /**
292
- * Registered-but-persistence-failed (FIX C): auth succeeded in THIS process but
293
- * the token write failed, so nothing reached disk. DISTINCT from `not_registered`
294
- * because the recovery differs — the user must FIX THE DATA DIR (the path + cause
295
- * name what to fix), THEN re-register; a bare "run sil_register" would just fail
296
- * to persist again, looping. `error` carries the "<path>: <cause>" from the
297
- * in-process marker. No identity fields (the tokens never landed).
214
+ * Auth succeeded but the token write failed. Distinct from `not_registered`
215
+ * because the recovery differs: a bare "run sil_register" fails to persist again
216
+ * and loops, so `error` names the path and cause to fix first.
298
217
  */
299
218
  function persistenceFailed(error) {
300
219
  return jsonResult({
@@ -334,17 +253,10 @@ function transient() {
334
253
  });
335
254
  }
336
255
  /**
337
- * In-process persist-failure marker (FIX C). A failed token write leaves NO
338
- * `tokens.json` on disk — exactly the state a never-registered user has — so the
339
- * two are indistinguishable from disk alone. This module-level marker is the only
340
- * signal that tells `sil_whoami` "auth succeeded in THIS process but persistence
341
- * failed" apart from a bare `not_registered`. It is intentionally in-process only:
342
- * the failure mode IS an unwritable data dir, so an on-disk sentinel would fail to
343
- * write for the same reason — and after a cold restart `not_registered` is the
344
- * TRUE state (no creds exist), with a re-run of `sil_register` re-surfacing the
345
- * write failure loudly. Set by `claimStep` on the persist_failed terminal; reset
346
- * on a fresh `sil_register` start so a stale marker can't mislabel a later genuine
347
- * not_registered (and resettable in tests via that same fresh-start path).
256
+ * The only thing that tells a failed token write apart from a never-registered
257
+ * buyer — both leave no `tokens.json`. In-process on purpose: the failure mode IS
258
+ * an unwritable data dir, so an on-disk sentinel would fail to write too, and
259
+ * after a restart `not_registered` is the true state.
348
260
  */
349
261
  let _persistFailure = null;
350
262
  function setPersistFailure(error) {
@@ -358,32 +270,23 @@ function clearPersistFailure() {
358
270
  }
359
271
  /**
360
272
  * One poll step: claim, then map the outcome to the loop's done/continue signal.
361
- * `pending`/`retryable`/`not_found` keep the loop alive (`done:false`). The 404
362
- * `not_found` is the NORMAL pre-session early state (the session row is INSERTed
363
- * server-side only when the user opens the auth URL), so it keeps polling exactly
364
- * like `pending`, bounded by the 30-min deadline — a session that never appears
365
- * settles as `timeout`, never as `not_found`. A successful claim is persisted
366
- * HERE — tokens.json + config.json written atomically inside this awaited tick —
367
- * so the files are on disk before the loop settles; the step then carries only
368
- * the user_id forward (the tokens never travel past this closure). The terminals
369
- * (expired / already_claimed / invalid_request) persist nothing.
273
+ * A 404 `not_found` is the normal state BEFORE the buyer opens the link (the
274
+ * session row is inserted server-side then), so it keeps polling like `pending`
275
+ * and a session that never appears settles as `timeout`. The success is persisted
276
+ * HERE, inside the awaited tick, so the files land before the loop settles.
370
277
  */
371
- async function claimStep(apiUrl, sessionId, verifier) {
372
- const outcome = await claimSession(apiUrl, sessionId, verifier);
278
+ async function claimStep(webUrl, sessionId, verifier) {
279
+ const outcome = await claimSession(webUrl, sessionId, verifier);
373
280
  switch (outcome.kind) {
374
281
  case "pending":
375
282
  case "retryable":
376
283
  case "not_found":
377
284
  return { done: false };
378
285
  case "success":
379
- // Persist the bearer pair + identity. FIX C: wrap ONLY the persist calls
380
- // (never the whole step — a too-wide catch could mislabel a genuine claim
381
- // success). A write failure (unwritable / missing-and-uncreatable / full
382
- // $SIL_DATA_DIR) is TERMINAL, not transient: re-polling the claim cannot
383
- // make the data dir writable, and the claim is single-use server-side. So
384
- // return a descriptive `persist_failed` terminal (path + cause) and set the
385
- // in-process marker — instead of letting the throw reach the poller's catch,
386
- // which would swallow it as a retry and end the run as a misleading timeout.
286
+ // ONLY the persist calls are wrapped — a wider catch could mislabel a
287
+ // genuine claim success. A write failure is TERMINAL: re-polling cannot make
288
+ // the data dir writable and the claim is single-use, so a throw reaching the
289
+ // poller's catch would end the run as a misleading timeout.
387
290
  try {
388
291
  await writeTokens({
389
292
  access_token: outcome.access_token,
@@ -417,11 +320,8 @@ function handleDone(api, sessionId, result) {
417
320
  });
418
321
  return;
419
322
  }
420
- // FIX C: a token-persist failure is logged LOUDLY at error — the most severe
421
- // terminal, distinct from the routine info/warn terminals — carrying the path +
422
- // cause (in `step.error`) so an operator sees persistence failed, NOT that the
423
- // user abandoned the flow. The tokens never reached disk, so there is no token
424
- // material to leak; only the session id + the path/cause error are logged.
323
+ // At error, alone among the terminals: an operator must see a persist failure
324
+ // rather than read it as a buyer who abandoned the flow.
425
325
  if (step.outcome === "persist_failed") {
426
326
  api.logger.error("sil_register_persist_failed", {
427
327
  session_id: sessionId,
@@ -433,11 +333,8 @@ function handleDone(api, sessionId, result) {
433
333
  api.logger.info("sil_register_timeout", { session_id: sessionId });
434
334
  return;
435
335
  }
436
- // expired / already_claimed / invalid_request — log the terminal so the outcome
437
- // is never silent; the agent learns it on its next sil_register / sil_whoami.
438
- // `invalid_request` logs at WARN: a malformed claim request is unreachable from
439
- // this client today, so it signals a contract-drift bug, not a user outcome —
440
- // make it loud (the genuine `expired`/`already_claimed` are routine, at info).
336
+ // `invalid_request` is WARN: this client cannot produce a malformed claim, so it
337
+ // signals contract drift rather than a buyer outcome. The rest are routine.
441
338
  const outcome = typeof step.outcome === "string" ? step.outcome : "unknown";
442
339
  const marker = `sil_register_${outcome}`;
443
340
  if (outcome === "invalid_request") {
@@ -447,17 +344,8 @@ function handleDone(api, sessionId, result) {
447
344
  api.logger.info(marker, { session_id: sessionId });
448
345
  }
449
346
  }
450
- function stripTrailingSlash(url) {
451
- return url.endsWith("/") ? url.slice(0, -1) : url;
452
- }
453
- /**
454
- * Render an errno-style cause from a caught (unknown) persist error, for the
455
- * loud log + whoami `persistence_failed` state (FIX C). A Node fs error carries
456
- * a `.code` (EACCES/ENOSPC/ENOTDIR/ENOENT…) and a `.message` that already names
457
- * the code and the human cause ("not a directory") — surface the code first
458
- * (prominent for an operator) then the full message. Carries NO token material:
459
- * an fs error names paths/errnos only, and the tokens never reached this point.
460
- */
347
+ /** The errno first, then the message: an operator scanning a log line reads
348
+ * EACCES/ENOSPC before the prose. An fs error names paths only, never a token. */
461
349
  function describeCause(err) {
462
350
  if (err instanceof Error) {
463
351
  const code = err.code;
@@ -465,40 +353,17 @@ function describeCause(err) {
465
353
  }
466
354
  return String(err);
467
355
  }
468
- /**
469
- * Present an auth URL as a single atomic link target for a human-rendered chat
470
- * surface: angle-bracket wrapped (`<…>`). The angle brackets are the RFC-3986 /
471
- * Markdown convention that bounds a URL so a greedy auto-linker captures the
472
- * WHOLE span — including the `&code_challenge=…` query param — instead of
473
- * terminating the link at the first `&` (the reported production break that
474
- * dropped `code_challenge` and 400-ed `invalid_code_challenge`). The caller puts
475
- * the returned token on its OWN line so no surrounding prose can be folded into
476
- * the link. Pure (no I/O) — the [unit] seam for the atomic-link contract. The
477
- * structured `auth_url` field is the UNWRAPPED canonical URL; this is the
478
- * human-presentation form only, and it carries the same params byte-for-byte (it
479
- * never re-encodes, never adds the verifier).
480
- */
481
- function presentAuthLink(authUrl) {
482
- return `<${authUrl}>`;
356
+ /** Angle brackets are the RFC-3986 convention that bounds a URL, so a greedy chat
357
+ * auto-linker captures the WHOLE span instead of stopping at a separator. The
358
+ * caller puts it on its own line so no prose can be folded into the link. */
359
+ function presentAuthLink(open) {
360
+ return `<${open}>`;
483
361
  }
484
362
  /**
485
- * System-browser steer copy (the proactive webview → default-browser handoff).
486
- *
487
- * Auth0's hosted login sets its session cookie on its OWN domain; an app's
488
- * embedded/in-app webview routinely partitions or blocks that cookie, so opening
489
- * the auth URL there dead-ends the login. The plugin CANNOT detect the surface —
490
- * the host `api` exposes no client/UA/surface signal (see openclaw.d.ts) and a
491
- * tool's execute receives no request context — so the steer ships UNCONDITIONALLY
492
- * at presentation time, BEFORE the Auth0 leg (not as a post-failure recovery; that
493
- * reactive path is sil-services #50). Phrased as a neutral setup step, not a
494
- * warning — onboarding first-impression is the metric.
495
- *
496
- * One shared NEGATIVE clause feeds both the human `message` and the agent
497
- * `instructions` so the two copies cannot drift — an agent paraphrasing must
498
- * carry the same "not the in-app browser" half, never collapse it back to a
499
- * generic "a browser". Plain "default browser (Safari/Chrome)" is used over the
500
- * term "system browser": it names the concrete action a non-technical user can
501
- * follow on their own device.
363
+ * Auth0 sets its session cookie on its own domain and an embedded webview
364
+ * partitions it, so the link dead-ends there. The host exposes no surface signal
365
+ * to detect that, so the steer ships unconditionally — and ONE negative clause
366
+ * feeds both copies, so an agent relaying it cannot drop the half that matters.
502
367
  */
503
368
  const BROWSER_STEER_NEGATIVE = "your device's default browser (Safari, Chrome, …), not this app's"
504
369
  + " built-in / in-app browser";
@@ -2,23 +2,27 @@
2
2
  "id": "sil",
3
3
  "name": "sil",
4
4
  "description": "Turn your OpenClaw into an expert shopping agent.",
5
- "version": "0.4.5",
5
+ "version": "0.5.0",
6
6
  "skills": ["./sil-shopping"],
7
7
  "activation": {
8
- "onCapabilities": ["tool"]
8
+ "onCapabilities": ["tool"],
9
+ "onStartup": true
9
10
  },
10
11
  "contracts": {
11
12
  "tools": [
13
+ "shopping_brief_create",
14
+ "shopping_brief_edit",
15
+ "shopping_brief_read",
16
+ "shopping_domain_create",
17
+ "shopping_domain_get",
18
+ "shopping_domain_search",
19
+ "shopping_offers",
20
+ "shopping_product_get",
21
+ "shopping_profile_edit",
22
+ "shopping_search",
23
+ "shopping_seller_get",
12
24
  "sil_doctor",
13
- "sil_learn",
14
- "sil_product_get",
15
- "sil_profile_get",
16
- "sil_profile_materialize",
17
- "sil_profile_remove",
18
- "sil_profile_search",
19
25
  "sil_register",
20
- "sil_search",
21
- "sil_specs",
22
26
  "sil_whoami"
23
27
  ]
24
28
  },
@@ -54,7 +58,7 @@
54
58
  },
55
59
  "security": {
56
60
  "shipsRuntimeCode": true,
57
- "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 session 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 session token and call sil-api's catalog endpoints (search / lookup) with it — read-only on catalog data, no timer, but with the SAME bounded 401 recovery as sil_whoami: on a 401 they refresh ONCE via sil-web (rotating tokens.json) and retry the read ONCE; a second 401 or a dead (invalid_grant) refresh token clears tokens.json and is reported as a terminal re-register hint. A non-401 error writes no token. The five profile verbs make NO network call and read no token; they write the one sil shopper's SINGLETON behaviour artefacts under a fixed $SIL_DATA_DIR/shopper/ (owner-only, files 0600, dirs 0700) as frontmatter-as-truth markdown — there is NO profile.json manifest; each file's own frontmatter IS the source of truth, discovered by a filesystem scan. sil_profile_materialize is SETUP-ONLY: it writes shopper/user_spec.md (the shared person spec; its frontmatter carries the shopper name), minting no domain. sil_learn is the single target+change verb over shopper/domains/<slug>/{method.md, prds/<product>-<intent>.md, assets/}: create mints a whole method or PRD, fail-closed if one already exists; write replaces an existing doc's whole body with a caller-authored reconciled version, fail-closed if the target is absent — there is no in-place section edit, so every change rewrites the whole document; attach-asset persists image bytes (size-capped, image MIME allowlist) into the domain's assets/ owner-only and links them by RELATIVE path, never inline bytes. sil_profile_search scans artefact FRONTMATTER and returns coordinates only (no bodies) — a domain/PRD with malformed frontmatter is skipped and surfaced as unreadable, never silently dropped or half-read. sil_profile_get reads ONE whole body (method or PRD); sil_profile_remove deletes a whole validated domain subtree, or one PRD file, fail-closed on a malformed/traversal/\"main\" or missing slug (never the whole shopper). sil_doctor is a report-first diagnostic over the SAME $SIL_DATA_DIR state: it reads the data dir, file modes, tokens.json/config.json metadata, and artefact frontmatter, and returns a machine-readable findings array. It reads no token contents out and rotates no token: token health is metadata only (present / mode / parses / expired), where expiry is decoded from the access token's own JWT exp claim strictly LOCALLY (decode-only, no signature verification, no network, no claim other than exp extracted, never a token byte emitted or logged). Its only writes are two safe idempotent fixes under $SIL_DATA_DIR — tightening a too-open mode and creating the missing data dir; a tighten only ever NARROWS (it detects bits set outside the expected mask and chmods to mode & expected, which can only clear bits, never grant them). Enumerated entries under the data dir are lstat'd, and a symlink found among them is REPORTED, never chmod'd-through — that is what keeps a tighten inside the store. The data directory ROOT itself is stat'd rather than lstat'd, because chmod follows a symlink regardless (Linux exposes no lchmod), so lstat there would prevent nothing and merely re-report the same fix forever; a symlinked $SIL_DATA_DIR is an operator-declared indirection, so the tighten lands on the directory the plugin already stores everything in. anything that would mutate the bytes of an existing artefact (clearing a corrupt tokens.json, deleting an orphaned tmp file, repairing an artefact) is REPORTED as needs_confirmation and never run. It makes exactly ONE outbound request, and it is the only reason https://clawhub.ai is declared: an unauthenticated read-only GET of the published version of @4gpts/sil, bounded by an explicit timeout + abort, carrying no token, no PII, no store contents, and no Authorization header, pinned to that one host (redirects are refused). It fails soft to silence — an unreachable, slow, non-200, or unparseable response yields no finding at all and never fails the run. sil_doctor never acts on the version it reports: it installs nothing, spawns no process, writes no host config, and prompts nobody. The only caller-supplied path segments are the domain slug and the PRD key, both validated (lower-kebab, not \"main\") before any join; the shopper segment is a compile-time constant. Every write is atomic (tmp file → rename over target → chmod), so a reader sees a whole file or none. The persona is the shopper's host workspace SOUL.md, written by the host CLI (not this plugin, not a sil artefact), and the shopper's host-config wiring is driven separately by the host CLI. The PKCE verifier is held only in memory and is never written to disk. The plugin registers ONE gateway RPC method, sil.search_results (scope operator.read, which the host authorizes before the handler runs): a paired client calls it over the already-authenticated deviceToken WS to read back a sil_search page whose callId it already saw on the tool frames. It opens no socket, no port, and no route — registering it hands the host a closure, and the host owns the transport. The pages it serves live in a bounded IN-MEMORY buffer that is never written to disk: sil_search stores its own successful result there under the callId the host passed it (at most 32 pages, dropped 15 minutes after the search, evicted lazily on the next write with no timer, and gone entirely when the process exits). The method makes no network call, starts no agent run, and returns a page only to the sil account that produced it — every unknown, expired, or foreign reference gets one identical not-found body. Artefact bodies, tokens, and identity PII are never logged; the method logs only whether a page was found and how many products it held.",
61
+ "packagingNote": "Compiled JavaScript ships under ./dist. register() stays synchronous and opens nothing that must be closed: it registers the tools, ensures the data directory, and reads the eleven REQUEST artifacts under ./schema so each shopping tool can publish one as its own parameters (eleven synchronous readFileSync calls of tracked files inside the package, no network, no timer, no handle). The eleven RESPONSE artifacts ship beside them and none is read at runtime. ALL network 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 session 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. The eleven shopping_* tools read the stored session token and call sil-api's catalog, brief and profile endpoints with it — read-only except shopping_domain_create, which writes one registry row, and shopping_brief_create / shopping_brief_edit / shopping_profile_edit, which write the buyer's own brief and profile under their sil account and nowhere else — with no timer on any of them, but with the SAME bounded 401 recovery as sil_whoami: on a 401 they refresh ONCE via sil-web (rotating tokens.json) and retry the read ONCE; a second 401 or a dead (invalid_grant) refresh token clears tokens.json and is reported as a terminal re-register hint. A non-401 error writes no token. NOTHING of the buyer's is kept on disk: every tool that calls sil — sil_register, sil_whoami and the shopping_* tools — touches tokens.json and config.json and nothing else under the data directory: it reads the stored token, rewrites tokens.json when a refresh rotates it, and deletes tokens.json when sil says the session is past refreshing; and no caller-supplied value ever becomes a path segment anywhere. sil_doctor is a report-first diagnostic over that SAME $SIL_DATA_DIR state: it reads the data dir, file modes and tokens.json/config.json metadata, and returns a machine-readable findings array. It reads no token contents out and rotates no token: token health is metadata only (present / mode / parses / expired), where expiry is decoded from the access token's own JWT exp claim strictly LOCALLY (decode-only, no signature verification, no network, no claim other than exp extracted, never a token byte emitted or logged). Its writes under $SIL_DATA_DIR are two safe idempotent fixes — tightening a too-open mode and creating the missing data dir — plus an empty .doctor.<hex>.tmp probe it writes and unlinks to prove the directory is writable the way sil actually writes; a tighten only ever NARROWS (it detects bits set outside the expected mask and chmods to mode & expected, which can only clear bits, never grant them). Enumerated entries under the data dir are lstat'd, and a symlink found among them is REPORTED, never chmod'd-through — that is what keeps a tighten inside the data directory. The data directory ROOT itself is stat'd rather than lstat'd, because chmod follows a symlink regardless (Linux exposes no lchmod), so lstat there would prevent nothing and merely re-report the same fix forever; a symlinked $SIL_DATA_DIR is an operator-declared indirection, so the tighten lands on the directory the plugin already stores everything in. Anything that would mutate the bytes of an existing file (clearing a corrupt tokens.json, deleting an orphaned tmp file) is REPORTED as needs_confirmation and never run. It makes exactly ONE outbound request, and it is the only reason https://clawhub.ai is declared: an unauthenticated read-only GET of the published version of @4gpts/sil, bounded by an explicit timeout + abort, carrying no token, no PII, and no Authorization header, pinned to that one host (redirects are refused). It fails soft to silence — an unreachable, slow, non-200, or unparseable response yields no finding at all and never fails the run. sil_doctor never acts on the version it reports: it installs nothing, spawns no process, writes no host config, and prompts nobody. Every write is atomic (tmp file → rename over target → chmod), so a reader sees a whole file or none. The PKCE verifier is held only in memory and is never written to disk. The plugin registers ONE gateway RPC method, sil.search_results (scope operator.read, which the host authorizes before the handler runs): a paired client calls it over the already-authenticated deviceToken WS to read back a shopping_search page whose callId it already saw on the tool frames. It opens no socket, no port, and no route — registering it hands the host a closure, and the host owns the transport. The pages it serves live in a bounded IN-MEMORY buffer that is never written to disk: shopping_search stores its own successful result there under the callId the host passed it (at most 32 pages, dropped 15 minutes after the search, evicted lazily on the next write with no timer, and gone entirely when the process exits). The method makes no network call, starts no agent run, and returns a page only to the sil account that produced it — every unknown, expired, or foreign reference gets one identical not-found body. Tokens and identity PII are never logged; the method logs only whether a page was found and how many products it held.",
58
62
  "registersLongLivedService": false,
59
63
  "serviceIds": [],
60
64
  "runsTimers": true,
@@ -65,7 +69,7 @@
65
69
  "https://sil.4gpts.com"
66
70
  ],
67
71
  "filesystemScope": [
68
- "$SIL_DATA_DIR (default $XDG_DATA_HOME/sil, else ~/.local/share/sil) — tokens.json, config.json, shopper/user_spec.md + shopper/domains/<slug>/{method.md, prds/<product>-<intent>.md, assets/<content-hash>.<ext>} (the ONE sil shopper's singleton behaviour artefacts, frontmatter-as-truth with NO profile.json manifest: sil_profile_materialize writes the shared user_spec.md at setup (its frontmatter carries the shopper name), and sil_learn mints/refines per-domain methods, intent-keyed PRDs, and per-domain image assets. The `shopper` segment is a fixed compile-time constant, not caller input; the domain slug and PRD key are the only caller-supplied path segments, validated (lower-kebab, not \"main\") before any join. All writes are atomic + owner-only (files 0600, dirs 0700). The persona is the host workspace SOUL.md, not a sil artefact)"
72
+ "$SIL_DATA_DIR (default $XDG_DATA_HOME/sil, else ~/.local/share/sil) — tokens.json and config.json, and nothing else: a tool that calls sil reads them, rewrites tokens.json on a refresh and deletes it when the session is past refreshing, and no caller-supplied value ever becomes a path segment. sil_doctor reads whatever else it finds there, only ever tightens its mode, and writes one empty .doctor.<hex>.tmp writability probe it unlinks immediately. All writes are atomic + owner-only (files 0600, dirs 0700)"
69
73
  ],
70
74
  "credentialsOnDisk": [
71
75
  "tokens.json (access + refresh token)",