sil-openclaw 0.2.3 → 0.2.4

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.
package/CHANGELOG.md CHANGED
@@ -10,6 +10,23 @@ release (`clawhub package publish --changelog`). See [README](./README.md#releas
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.2.4] - 2026-06-18
14
+
15
+ ### Fixed
16
+
17
+ - **`sil_register` now steers users into their device's default browser before the
18
+ Auth0 leg, so registration completes first-try from in-app/embedded webviews.** An
19
+ auth link opened in an app's built-in webview dead-ends — Auth0 can't set its
20
+ session cookie in a partitioned webview, so login bounces with `?error=`. The
21
+ `awaiting_browser` return now carries an explicit instruction, in both the
22
+ human-facing `message` and the agent-facing `instructions`, to open the link in the
23
+ **default browser (Safari, Chrome, …), not this app's built-in browser** — before
24
+ the link is ever opened, steering a webview user out ahead of the Auth0 leg. The
25
+ `auth_url` value is byte-for-byte unchanged and the link stays atomically
26
+ angle-bracket-wrapped on its own line (the #24 invariants hold); no new tool and no
27
+ webview detection (the host exposes no surface signal, so the steer ships
28
+ unconditionally). (#25)
29
+
13
30
  ## [0.2.3] - 2026-06-16
14
31
 
15
32
  ### Added
package/README.md CHANGED
@@ -149,7 +149,7 @@ pnpm test # vitest (unit + integration)
149
149
  pnpm typecheck # tsc --noEmit
150
150
  ```
151
151
 
152
- Releasing is two steps: `pnpm version <patch|minor|major>` (bump → sync manifest → cut changelog → test → tag → push), then `pnpm release` (build → pack → npm `sil-openclaw` + ClawHub `@4gpts/sil` — the same contents, re-packed under each registry's name). Full guide in [`CLAUDE.md`](./CLAUDE.md#releasing); release notes in [`CHANGELOG.md`](./CHANGELOG.md). Adding a tool is three steps, enforced by a drift-guard test — see [`CLAUDE.md`](./CLAUDE.md#how-to-add-a-tool).
152
+ Releasing is two steps: `pnpm version <patch|minor|major>` (bump → sync manifest → cut changelog → test → tag → push), then `pnpm release` (build → pack → npm `sil-openclaw` + ClawHub `@4gpts/sil` — the same contents, re-packed under each registry's name). Release notes in [`CHANGELOG.md`](https://github.com/Context4GPTs/sil-openclaw/blob/main/CHANGELOG.md). Adding a tool is three steps, enforced by a drift-guard test.
153
153
 
154
154
  ---
155
155
 
@@ -69,9 +69,15 @@ export function startPoll(opts) {
69
69
  result = await opts.poll();
70
70
  }
71
71
  catch {
72
- // A throw from the injected step is treated as non-terminal: the
73
- // sil-client wrapper already maps network errors to a retryable result,
74
- // so this is belt-and-braces; let the next tick (within budget) retry.
72
+ // A throw from the injected step is treated as non-terminal — the next
73
+ // tick (within budget) retries. This is correct ONLY for the claim call:
74
+ // the sil-client wrapper already maps network errors to a `retryable`
75
+ // result, so a genuine throw here is a rare transient. A TERMINAL failure
76
+ // that must NOT be retried (e.g. the token-persist failure) is never a
77
+ // throw that reaches this catch — `claimStep` classifies it and RETURNS a
78
+ // `{ done: true, outcome: "persist_failed", error }` terminal, so the
79
+ // poller stays generic over `done` and the terminal settles like any
80
+ // other. Do not move classification of a throw into this catch.
75
81
  result = { done: false };
76
82
  }
77
83
  finally {
@@ -30,8 +30,8 @@
30
30
  * inside execute(), never at register time.
31
31
  */
32
32
  import { Type } from "typebox";
33
- import { getWebUrl, getApiUrl } from "../lib/config.js";
34
- import { clearTokens, hasTokens, readConfig, readTokens, writeConfig, writeTokens, } from "../lib/credentials.js";
33
+ import { getWebUrl, getWebUrlSource, getApiUrl } from "../lib/config.js";
34
+ import { clearTokens, getTokensPath, hasTokens, readConfig, readTokens, writeConfig, writeTokens, } from "../lib/credentials.js";
35
35
  import { deriveChallenge, newSessionId, newVerifier } from "../lib/pkce.js";
36
36
  import { POLL_DEADLINE_MS, POLL_INTERVAL_MS, startPoll, } from "../lib/poller.js";
37
37
  import { claimSession, fetchIdentity, refreshAndRetryOnce, } from "../lib/sil-client.js";
@@ -59,14 +59,21 @@ function registerRegister(api) {
59
59
  user: config?.user ?? null,
60
60
  });
61
61
  }
62
+ // A fresh registration attempt clears any prior in-process persist-failure
63
+ // marker: this process is starting over, so a stale marker from an earlier
64
+ // failed attempt must not make a later genuine `not_registered` (or this
65
+ // attempt's own outcome) masquerade as `persistence_failed`. (FIX C.)
66
+ clearPersistFailure();
62
67
  // 2 — mint PKCE. The verifier stays in this closure (never on disk).
63
68
  const sessionId = newSessionId();
64
69
  const verifier = newVerifier();
65
70
  const challenge = deriveChallenge(verifier);
66
- const apiUrl = getWebUrl();
71
+ // The sil-WEB origin (auth authority) — this is what the auth URL is built
72
+ // from. The local was historically misnamed `apiUrl`; it is the web origin.
73
+ const webUrl = getWebUrl();
67
74
  // 3 — build the auth URL. Opening it (by the user's browser) is what
68
75
  // creates the pending session server-side; the plugin does not pre-POST.
69
- const authUrl = `${stripTrailingSlash(apiUrl)}/authorize`
76
+ const authUrl = `${stripTrailingSlash(webUrl)}/authorize`
70
77
  + `?session=${sessionId}&code_challenge=${challenge}`;
71
78
  // 4 — fire-and-forget bounded poll. Not awaited: execute() returns now.
72
79
  // The poll step maps each claim outcome to the loop's done/continue
@@ -76,18 +83,35 @@ function registerRegister(api) {
76
83
  startPoll({
77
84
  intervalMs: POLL_INTERVAL_MS,
78
85
  deadlineMs: POLL_DEADLINE_MS,
79
- poll: () => claimStep(apiUrl, sessionId, verifier),
86
+ poll: () => claimStep(webUrl, sessionId, verifier),
80
87
  onDone: (result) => handleDone(api, sessionId, result),
81
88
  });
82
89
  api.logger.info("sil_register_started", { session_id: sessionId });
83
90
  return jsonResult({
84
91
  status: "awaiting_browser",
85
- message: `Open this URL in a browser to register: ${authUrl}`,
92
+ // The steer lead line routes the user into their OWN default browser
93
+ // BEFORE the Auth0 leg (where Auth0's session cookie works on its own
94
+ // domain), instead of an in-app/embedded webview that partitions it and
95
+ // dead-ends the login. It is a SEPARATE line ABOVE the link, so the link
96
+ // line stays exactly `<authUrl>` — ONE atomic, angle-bracket-wrapped
97
+ // target that a greedy chat auto-linker captures WHOLE (`&code_challenge`
98
+ // included) instead of truncating at the `&` and 400-ing
99
+ // `invalid_code_challenge`. `auth_url` below stays the canonical,
100
+ // UNWRAPPED machine field agents parse. (FIX A + system-browser steer.)
101
+ message: BROWSER_STEER_HUMAN
102
+ + "\n"
103
+ + presentAuthLink(authUrl),
86
104
  auth_url: authUrl,
87
105
  session_id: sessionId,
88
- instructions: "Share the auth URL with the user. The plugin is polling in the"
89
- + " background — once the user finishes signing in, call sil_register"
90
- + " again to confirm (it will report already_registered).",
106
+ // The agent-facing steer MUST agree with the human `message` (both built
107
+ // from the shared BROWSER_STEER_NEGATIVE clause) so an agent relaying the
108
+ // instruction can't paraphrase it back to a generic "a browser" and
109
+ // re-open the cookie-blocking-webview gap.
110
+ instructions: "Share the auth URL with the user and tell them to "
111
+ + BROWSER_STEER_AGENT
112
+ + " The plugin is polling in the background — once the user finishes"
113
+ + " signing in, call sil_register again to confirm (it will report"
114
+ + " already_registered).",
91
115
  });
92
116
  },
93
117
  });
@@ -132,11 +156,35 @@ function registerWhoami(api) {
132
156
  + " the recovery action (run sil_register).",
133
157
  parameters: Type.Object({}),
134
158
  async execute() {
135
- // 1 — not registered: terminal, zero network calls.
159
+ // 1 — not registered: terminal, zero network calls. If THIS process saw a
160
+ // token-persist failure (auth succeeded but the write failed), surface the
161
+ // distinct `persistence_failed` state instead — the no-tokens.json state on
162
+ // disk is identical for both, so the in-process marker is the only signal
163
+ // that tells them apart (FIX C; cold-restart correctly degrades to
164
+ // not_registered — see the persistence_failed/notRegistered helpers).
136
165
  const stored = readTokens();
137
166
  if (stored === null) {
138
- return notRegistered();
167
+ const failure = getPersistFailure();
168
+ return failure !== null ? persistenceFailed(failure) : notRegistered();
139
169
  }
170
+ // B (origin visibility): resolve the sil-WEB origin (the origin the
171
+ // registration link is built from) + its source, surface it on the success
172
+ // payload so a wrong/staging origin is diagnosable BEFORE anything 404s,
173
+ // and emit a single warn when the source is non-default. Warn-only — a
174
+ // staging/self-host origin is legitimate, so it is NEVER rejected. Scope is
175
+ // the WEB origin only; the sil-api read origin is out of scope. (FIX B.)
176
+ const webOrigin = getWebUrl();
177
+ const webOriginSource = getWebUrlSource();
178
+ if (webOriginSource !== "default") {
179
+ api.logger.warn("sil_whoami_web_origin_override", {
180
+ web_origin: webOrigin,
181
+ web_origin_source: webOriginSource,
182
+ });
183
+ }
184
+ const originBlock = {
185
+ web_origin: webOrigin,
186
+ web_origin_source: webOriginSource,
187
+ };
140
188
  // 2 — read identity; on a 401 refresh-and-retry ONCE via the shared
141
189
  // choreography (the SAME `refreshAndRetryOnce` path sil_search /
142
190
  // sil_product_get use — 401 recovery is uniform across every
@@ -152,7 +200,7 @@ function registerWhoami(api) {
152
200
  // logs-only, no token material, NOT a payload field (the agent never sees it).
153
201
  if (recovered.refreshed)
154
202
  api.logger.info("sil_whoami_refreshed", {});
155
- return identityOutcomeToResult(api, recovered.outcome);
203
+ return identityOutcomeToResult(api, recovered.outcome, originBlock);
156
204
  case "must_reregister":
157
205
  // The refresh token is dead (invalid_grant) → clear the now-known-dead
158
206
  // pair so the user's sil_register recovery is not blocked by stale
@@ -175,11 +223,13 @@ function registerWhoami(api) {
175
223
  });
176
224
  }
177
225
  /** Map a non-401 identity outcome to the agent-facing result. (401 is handled
178
- * inline by the refresh path; it never reaches here.) */
179
- function identityOutcomeToResult(api, outcome) {
226
+ * inline by the refresh path; it never reaches here.) The origin block rides the
227
+ * SUCCESS payload (the point is pre-failure diagnosis); the terminal/transient
228
+ * envelopes don't carry it. */
229
+ function identityOutcomeToResult(api, outcome, originBlock) {
180
230
  switch (outcome.kind) {
181
231
  case "ok":
182
- return identityResult(outcome.identity);
232
+ return identityResult(outcome.identity, originBlock);
183
233
  case "forbidden":
184
234
  // Decision B — the dead-token clear is UNIFORM across all three sil-api tools.
185
235
  // `sil_whoami` is the tool that is legible TODAY; an agent that diagnoses the
@@ -203,9 +253,11 @@ function identityOutcomeToResult(api, outcome) {
203
253
  return mustReregister();
204
254
  }
205
255
  }
206
- /** Success: the identity payload ONLY — no token, no Bearer header. */
207
- function identityResult(identity) {
208
- return jsonResult({ status: "ok", identity });
256
+ /** Success: the identity payload + the web-origin visibility block (FIX B) —
257
+ * no token, no Bearer header. The origin block (strings only) lets the agent
258
+ * relay the resolved origin + its source so a wrong origin is diagnosable. */
259
+ function identityResult(identity, originBlock) {
260
+ return jsonResult({ status: "ok", identity, ...originBlock });
209
261
  }
210
262
  /** Not registered: a distinct, actionable outcome naming the recovery tool. No
211
263
  * identity fields (name/addresses) so the agent can't mistake it for a read. */
@@ -217,6 +269,25 @@ function notRegistered() {
217
269
  recovery: "sil_register",
218
270
  });
219
271
  }
272
+ /**
273
+ * Registered-but-persistence-failed (FIX C): auth succeeded in THIS process but
274
+ * the token write failed, so nothing reached disk. DISTINCT from `not_registered`
275
+ * because the recovery differs — the user must FIX THE DATA DIR (the path + cause
276
+ * name what to fix), THEN re-register; a bare "run sil_register" would just fail
277
+ * to persist again, looping. `error` carries the "<path>: <cause>" from the
278
+ * in-process marker. No identity fields (the tokens never landed).
279
+ */
280
+ function persistenceFailed(error) {
281
+ return jsonResult({
282
+ status: "persistence_failed",
283
+ message: "Registration authenticated but the credentials could NOT be written to"
284
+ + " disk, so it did not stick. Fix the data directory (it must be writable"
285
+ + " — check permissions / free space / that $SIL_DATA_DIR is a directory),"
286
+ + " then run sil_register again.",
287
+ error,
288
+ recovery: "sil_register",
289
+ });
290
+ }
220
291
  /** Terminal: the session is fully expired (refresh rejected). Re-register. */
221
292
  function mustReregister() {
222
293
  return jsonResult({
@@ -243,6 +314,29 @@ function transient() {
243
314
  message: "sil is temporarily unavailable. Please try sil_whoami again.",
244
315
  });
245
316
  }
317
+ /**
318
+ * In-process persist-failure marker (FIX C). A failed token write leaves NO
319
+ * `tokens.json` on disk — exactly the state a never-registered user has — so the
320
+ * two are indistinguishable from disk alone. This module-level marker is the only
321
+ * signal that tells `sil_whoami` "auth succeeded in THIS process but persistence
322
+ * failed" apart from a bare `not_registered`. It is intentionally in-process only:
323
+ * the failure mode IS an unwritable data dir, so an on-disk sentinel would fail to
324
+ * write for the same reason — and after a cold restart `not_registered` is the
325
+ * TRUE state (no creds exist), with a re-run of `sil_register` re-surfacing the
326
+ * write failure loudly. Set by `claimStep` on the persist_failed terminal; reset
327
+ * on a fresh `sil_register` start so a stale marker can't mislabel a later genuine
328
+ * not_registered (and resettable in tests via that same fresh-start path).
329
+ */
330
+ let _persistFailure = null;
331
+ function setPersistFailure(error) {
332
+ _persistFailure = error;
333
+ }
334
+ function getPersistFailure() {
335
+ return _persistFailure;
336
+ }
337
+ function clearPersistFailure() {
338
+ _persistFailure = null;
339
+ }
246
340
  /**
247
341
  * One poll step: claim, then map the outcome to the loop's done/continue signal.
248
342
  * `pending`/`retryable`/`not_found` keep the loop alive (`done:false`). The 404
@@ -263,11 +357,26 @@ async function claimStep(apiUrl, sessionId, verifier) {
263
357
  case "not_found":
264
358
  return { done: false };
265
359
  case "success":
266
- await writeTokens({
267
- access_token: outcome.access_token,
268
- refresh_token: outcome.refresh_token,
269
- });
270
- await writeConfig({ user: outcome.user });
360
+ // Persist the bearer pair + identity. FIX C: wrap ONLY the persist calls
361
+ // (never the whole step — a too-wide catch could mislabel a genuine claim
362
+ // success). A write failure (unwritable / missing-and-uncreatable / full
363
+ // $SIL_DATA_DIR) is TERMINAL, not transient: re-polling the claim cannot
364
+ // make the data dir writable, and the claim is single-use server-side. So
365
+ // return a descriptive `persist_failed` terminal (path + cause) and set the
366
+ // in-process marker — instead of letting the throw reach the poller's catch,
367
+ // which would swallow it as a retry and end the run as a misleading timeout.
368
+ try {
369
+ await writeTokens({
370
+ access_token: outcome.access_token,
371
+ refresh_token: outcome.refresh_token,
372
+ });
373
+ await writeConfig({ user: outcome.user });
374
+ }
375
+ catch (err) {
376
+ const error = `${getTokensPath()}: ${describeCause(err)}`;
377
+ setPersistFailure(error);
378
+ return { done: true, outcome: "persist_failed", error };
379
+ }
271
380
  return { done: true, outcome: "success", user_id: outcome.user.id };
272
381
  case "expired":
273
382
  case "already_claimed":
@@ -289,6 +398,18 @@ function handleDone(api, sessionId, result) {
289
398
  });
290
399
  return;
291
400
  }
401
+ // FIX C: a token-persist failure is logged LOUDLY at error — the most severe
402
+ // terminal, distinct from the routine info/warn terminals — carrying the path +
403
+ // cause (in `step.error`) so an operator sees persistence failed, NOT that the
404
+ // user abandoned the flow. The tokens never reached disk, so there is no token
405
+ // material to leak; only the session id + the path/cause error are logged.
406
+ if (step.outcome === "persist_failed") {
407
+ api.logger.error("sil_register_persist_failed", {
408
+ session_id: sessionId,
409
+ error: typeof step.error === "string" ? step.error : "",
410
+ });
411
+ return;
412
+ }
292
413
  if ("timedOut" in step && step.timedOut === true) {
293
414
  api.logger.info("sil_register_timeout", { session_id: sessionId });
294
415
  return;
@@ -310,3 +431,60 @@ function handleDone(api, sessionId, result) {
310
431
  function stripTrailingSlash(url) {
311
432
  return url.endsWith("/") ? url.slice(0, -1) : url;
312
433
  }
434
+ /**
435
+ * Render an errno-style cause from a caught (unknown) persist error, for the
436
+ * loud log + whoami `persistence_failed` state (FIX C). A Node fs error carries
437
+ * a `.code` (EACCES/ENOSPC/ENOTDIR/ENOENT…) and a `.message` that already names
438
+ * the code and the human cause ("not a directory") — surface the code first
439
+ * (prominent for an operator) then the full message. Carries NO token material:
440
+ * an fs error names paths/errnos only, and the tokens never reached this point.
441
+ */
442
+ function describeCause(err) {
443
+ if (err instanceof Error) {
444
+ const code = err.code;
445
+ return code ? `${code}: ${err.message}` : err.message;
446
+ }
447
+ return String(err);
448
+ }
449
+ /**
450
+ * Present an auth URL as a single atomic link target for a human-rendered chat
451
+ * surface: angle-bracket wrapped (`<…>`). The angle brackets are the RFC-3986 /
452
+ * Markdown convention that bounds a URL so a greedy auto-linker captures the
453
+ * WHOLE span — including the `&code_challenge=…` query param — instead of
454
+ * terminating the link at the first `&` (the reported production break that
455
+ * dropped `code_challenge` and 400-ed `invalid_code_challenge`). The caller puts
456
+ * the returned token on its OWN line so no surrounding prose can be folded into
457
+ * the link. Pure (no I/O) — the [unit] seam for the atomic-link contract. The
458
+ * structured `auth_url` field is the UNWRAPPED canonical URL; this is the
459
+ * human-presentation form only, and it carries the same params byte-for-byte (it
460
+ * never re-encodes, never adds the verifier).
461
+ */
462
+ function presentAuthLink(authUrl) {
463
+ return `<${authUrl}>`;
464
+ }
465
+ /**
466
+ * System-browser steer copy (the proactive webview → default-browser handoff).
467
+ *
468
+ * Auth0's hosted login sets its session cookie on its OWN domain; an app's
469
+ * embedded/in-app webview routinely partitions or blocks that cookie, so opening
470
+ * the auth URL there dead-ends the login. The plugin CANNOT detect the surface —
471
+ * the host `api` exposes no client/UA/surface signal (see openclaw.d.ts) and a
472
+ * tool's execute receives no request context — so the steer ships UNCONDITIONALLY
473
+ * at presentation time, BEFORE the Auth0 leg (not as a post-failure recovery; that
474
+ * reactive path is sil-services #50). Phrased as a neutral setup step, not a
475
+ * warning — onboarding first-impression is the metric.
476
+ *
477
+ * One shared NEGATIVE clause feeds both the human `message` and the agent
478
+ * `instructions` so the two copies cannot drift — an agent paraphrasing must
479
+ * carry the same "not the in-app browser" half, never collapse it back to a
480
+ * generic "a browser". Plain "default browser (Safari/Chrome)" is used over the
481
+ * term "system browser": it names the concrete action a non-technical user can
482
+ * follow on their own device.
483
+ */
484
+ const BROWSER_STEER_NEGATIVE = "your device's default browser (Safari, Chrome, …), not this app's"
485
+ + " built-in / in-app browser";
486
+ /** Human-facing lead line — the line ABOVE the atomic link in `message`. */
487
+ const BROWSER_STEER_HUMAN = `Open this link in ${BROWSER_STEER_NEGATIVE}:`;
488
+ /** Agent-facing steer — embedded mid-sentence in `instructions` (lower-cased lead
489
+ * so it reads naturally after "tell them to …"). */
490
+ const BROWSER_STEER_AGENT = `open the link in ${BROWSER_STEER_NEGATIVE}.`;
@@ -2,7 +2,7 @@
2
2
  "id": "sil",
3
3
  "name": "sil",
4
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.3",
5
+ "version": "0.2.4",
6
6
  "skills": ["./skill"],
7
7
  "activation": {
8
8
  "onCapabilities": ["tool"]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sil-openclaw",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "OpenClaw plugin for sil — register an identity and search and look up products in the sil commerce catalog from an agent.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {