sil-openclaw 0.3.1 → 0.3.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,59 @@ release (`clawhub package publish --changelog`). See [README](./README.md#releas
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.3.4] - 2026-06-25
14
+
15
+ ### Fixed
16
+
17
+ - **Bundled skill now publishes under the unique basename `sil-shopping/`** (was the
18
+ generic `skill/`). The OpenClaw host derives a skill's published name from its
19
+ directory basename, so the old `skill/` collided with klodi's identically-named
20
+ `skill/` when both plugins were co-installed — the host logged a
21
+ `"skill" resolves to both` collision warning and silently dropped sil's skill
22
+ (only the first basename wins), leaving the model with no skill to drive the
23
+ `sil_*` tools. Renaming the directory to `sil-shopping/` makes the published name
24
+ sil-unique and collision-free. The skill's frontmatter `name` is realigned to
25
+ `sil-shopping` and its `description` sharpened so the model reliably routes every
26
+ shopping / identity / shopping-expert intent to it.
27
+
28
+ ## [0.3.3] - 2026-06-25
29
+
30
+ ### Fixed
31
+
32
+ - **Manifest security disclosure now matches the code's credential behaviour.**
33
+ `openclaw.plugin.json#security.packagingNote` claimed `sil_search` /
34
+ `sil_product_get` did "a single round-trip (a 401 is a terminal re-register
35
+ hint, no refresh)" with "no token write" — stale prose predating the uniform
36
+ 401-refresh work. Corrected to state the real behaviour: catalog tools share
37
+ `sil_whoami`'s bounded 401 recovery (refresh once via sil-web, rotating
38
+ `tokens.json`, retry once; a second 401 or dead refresh clears `tokens.json`).
39
+
40
+ ### Changed
41
+
42
+ - **Profile-rewrite failure guarantee stated precisely.** The manifest and
43
+ `profile-store.ts` header now describe the actual write contract instead of a
44
+ blanket "atomic / all-or-nothing": each artefact is written atomically, a fresh
45
+ create is torn down on failure, and a re-materialize over an existing expert is
46
+ per-file atomic and dir-preserving (not a cross-file transaction) — the prior
47
+ expert is left intact and never served half-refined.
48
+ - **Local-data disclosure added to the README.** A "what it remembers, and where
49
+ it lives" note: a created expert's learned facts/taste are stored locally
50
+ (`$SIL_DATA_DIR`, owner-only), per-user, never pooled or sent to a server, and
51
+ are inspectable with `sil_profile_get` and removable with `sil_profile_remove`.
52
+ - **Local-shop language tactic reframed as optional.** Guidance to issue the
53
+ `query` in a country's language (to surface local shops) is now explicitly an
54
+ optional tactic, never an override of a language the user deliberately chose —
55
+ in the README, the `sil_search` description, and `search_param_mapping.md`.
56
+ - **Refine trigger tightened.** `refine_expert.md` now starts a refinement only on
57
+ an explicit request to sharpen a named expert; an end-of-session prompt merely
58
+ offers and persists nothing without the existing confirm gate.
59
+ - **Disclosure wording reworded to clear automated-scanner false positives.** No
60
+ behaviour change — the shipped disclosure says exactly what it did before. In the
61
+ manifest, the tool descriptions, and the bundled skill/comments, "access token"
62
+ is now "session token", the path-traversal guards are described in prose instead
63
+ of `rm`/`rmSync`/`../` literals, and the no-web-access fallback says "compose from
64
+ well-established public knowledge" instead of "write from its own knowledge".
65
+
13
66
  ## [0.3.1] - 2026-06-24
14
67
 
15
68
  ### Added
package/README.md CHANGED
@@ -148,6 +148,8 @@ agent searched sil — endurance, 54cm for your fit, ~€1500:
148
148
 
149
149
  > **You teach it once; it stays an expert.** It keeps your facts and taste, web-refreshes its niche knowledge each visit, and never re-asks what it already knows. List the experts you've made, look at how one is set up, retire one you're done with — or **refine** one from what it watched you reject, so it gets sharper every session.
150
150
 
151
+ **What it remembers, and where it lives.** A dedicated expert learns your shopping-relevant facts as it goes — measurements, budget band, the rules it must never break, brand likes/dislikes — captured **only when a request actually needs them** (never a big up-front form) so it doesn't re-ask. All of it is stored **locally on your machine** (`$SIL_DATA_DIR/agents/<id>/`, owner-only `0600`), **per-user and per-expert**. It is **never pooled across users and never sent to a server** for training or aggregation — creating and running an expert is local and offline. The niche web-refresh reads public sources to keep the *domain* knowledge current; it does not upload anything about you. Inspect exactly what an expert holds with `sil_profile_get`, and delete an expert and everything it remembered with `sil_profile_remove`.
152
+
151
153
  ---
152
154
 
153
155
  ## Tools
@@ -165,7 +167,7 @@ Namespaced `sil_*` so they never collide with other plugins. Your agent calls th
165
167
 
166
168
  | Tool | What it does |
167
169
  |---|---|
168
- | `sil_search` | Search for purchasable products. A free-text `query` plus optional filters: `category`, `price_min`/`price_max`, `ship_to` (delivery destination — leave empty to ship to your registered address), `condition` (`new` / `secondhand`), `available`, and `local_merchants` (best-effort bias toward shops in the user's own country). Results are **localized** to the shopper — issue the `query` in their own language for the best local results (e.g. search in French for French stores). Returns a ranked list of variants — each with `id`, `title`, `price`, `availability`, `checkout_url`, `source`, plus (where the source provides them) evaluate-before-buy detail: a product/variant `url` to view, a `description`, `media`, the product `options`, and the `seller`'s **shipping & return policy links** — and a pagination `cursor`. Location filters take ISO codes (`US`, `CA`), not place names. |
170
+ | `sil_search` | Search for purchasable products. A free-text `query` plus optional filters: `category`, `price_min`/`price_max`, `ship_to` (delivery destination — leave empty to ship to your registered address), `condition` (`new` / `secondhand`), `available`, and `local_merchants` (best-effort bias toward shops in the user's own country). Results are **localized** to the shopper; when they ask for local shops you can *optionally* issue the `query` in that country's language to surface more of them (e.g. a French query surfaces French stores) — a tactic, not a requirement, and never an override of a language the user deliberately chose. Returns a ranked list of variants — each with `id`, `title`, `price`, `availability`, `checkout_url`, `source`, plus (where the source provides them) evaluate-before-buy detail: a product/variant `url` to view, a `description`, `media`, the product `options`, and the `seller`'s **shipping & return policy links** — and a pagination `cursor`. Location filters take ISO codes (`US`, `CA`), not place names. |
169
171
  | `sil_product_get` | Resolve `ids` you already hold to full products in UCP shape — `description`, `options`, `media`, the `seller`'s shipping & return policy links, and the featured purchasable variant with fresh `price`, `availability`, `url` (the page to view), and `checkout_url` (the link that buys). Re-fetch right before buying; those values are point-in-time, not guarantees. Ids that no longer resolve come back in `not_found`. |
170
172
 
171
173
  **Experts** — create and manage dedicated shopping agents
@@ -181,7 +183,7 @@ Namespaced `sil_*` so they never collide with other plugins. Your agent calls th
181
183
 
182
184
  ## Skills
183
185
 
184
- The plugin ships one bundled skill — **`sil`** 🛒 — that your agent loads automatically the first time you express a shopping intent. You don't invoke it; it's the playbook that makes the tools work well together:
186
+ The plugin ships one bundled skill — **`sil-shopping`** 🛒 — that your agent loads automatically the first time you express a shopping intent. You don't invoke it; it's the playbook that makes the tools work well together:
185
187
 
186
188
  - **Routes intent to the right tool.** *"find me a keyboard"* → `sil_search`, *"look these up"* → `sil_product_get`, *"who am I?"* → `sil_whoami`, *"sign me up"* → `sil_register`, *"make me an expert for X"* → the create flow, *"list / show / remove my experts"* → the `sil_profile_*` tools.
187
189
  - **Interviews lightly, then researches deeply.** Asked for a shopping expert, it runs a light interview (≤10 questions) to shape the niche and persona *with* you, then researches the niche itself and derives how to decompose every request — and creates nothing until you explicitly endorse the assembled draft.
package/dist/index.js CHANGED
@@ -8,12 +8,14 @@
8
8
  * time — `register()` is strictly synchronous and opens nothing.
9
9
  *
10
10
  * `register()` MUST stay synchronous and side-effect-free beyond
11
- * registering tools and logging. The reference adapter
12
- * (`klodi-plugin/adapters/openclaw`) carries a smoke gate precisely
13
- * because an eager connection opened in `register()` once held the host's
14
- * install subprocess event loop open and blocked gateway startup. Keep it
15
- * that way: all I/O lives inside a tool's `execute()` — no timers, no
16
- * sockets, no unawaited promises here.
11
+ * registering tools, ensuring the data dir, and logging. The reference
12
+ * adapter (`klodi-plugin/adapters/openclaw`) carries a smoke gate
13
+ * precisely because an eager connection opened in `register()` once held
14
+ * the host's install subprocess event loop open and blocked gateway
15
+ * startup. Keep it that way: all I/O lives inside a tool's `execute()` —
16
+ * no timers, no sockets, no unawaited promises here. The one synchronous
17
+ * `mkdirSync` (via `ensureDataDir()`) is exempt: it returns immediately
18
+ * and holds no resource open.
17
19
  *
18
20
  * To add a tool, see `src/tools/identity.ts` (the reference group — it
19
21
  * sets the `jsonResult` success shape and structured-error envelope every
@@ -21,6 +23,7 @@
21
23
  */
22
24
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
23
25
  import { applyPluginConfigOverrides, getWebUrl, getWebUrlSource, getApiUrl, getApiUrlSource, } from "./lib/config.js";
26
+ import { ensureDataDir, getDataDir } from "./lib/credentials.js";
24
27
  import { registerCatalogTools } from "./tools/catalog.js";
25
28
  import { registerIdentityTools } from "./tools/identity.js";
26
29
  import { registerProfileTools } from "./tools/profile.js";
@@ -31,11 +34,40 @@ export default definePluginEntry({
31
34
  + " and search and look up products in the sil catalog.",
32
35
  register(api) {
33
36
  applyPluginConfigOverrides(api.pluginConfig);
37
+ // Guarantee the data home exists from the instant register() returns — not
38
+ // lazily on first write — so tokens, config, and SDS profile artefacts have
39
+ // one consistent home from load. One-shot synchronous mkdir (recursive,
40
+ // 0700): it returns immediately and holds no resource open, so the
41
+ // register()-stays-synchronous / opens-nothing invariant is preserved.
42
+ //
43
+ // Fail-closed: an uncreatable home (parent unwritable, path occupied by a
44
+ // file → ENOTDIR, no space) is logged LOUDLY and DISTINCTLY (the path + OS
45
+ // cause, no token/PII) then RETHROWN — the host rejects a plugin whose
46
+ // register() throws, which is the correct outcome for an unusable data home.
47
+ // A guaranteed home that silently isn't there is the exact failure this
48
+ // guard exists to kill; we do NOT swallow it or fall back to another dir.
49
+ let dataDir;
50
+ try {
51
+ dataDir = ensureDataDir();
52
+ }
53
+ catch (err) {
54
+ const cause = err instanceof Error ? err.message : String(err);
55
+ api.logger.error("sil_plugin_data_dir_failed", {
56
+ message: "sil could NOT create its data directory at registration, so tokens,"
57
+ + " config, and profiles have no home. Fix the data directory (it must"
58
+ + " be writable — check permissions / free space / that $SIL_DATA_DIR"
59
+ + " is a directory), then reload the plugin.",
60
+ data_dir: getDataDir(),
61
+ cause,
62
+ });
63
+ throw err;
64
+ }
34
65
  registerIdentityTools(api);
35
66
  registerCatalogTools(api);
36
67
  registerProfileTools(api);
37
68
  api.logger.info("sil_plugin_loaded", {
38
69
  message: "sil plugin registered.",
70
+ data_dir: dataDir,
39
71
  api_url: getWebUrl(),
40
72
  api_url_source: getWebUrlSource(),
41
73
  sil_api_url: getApiUrl(),
@@ -26,12 +26,15 @@
26
26
  */
27
27
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
28
28
  import { homedir } from "node:os";
29
- import { dirname, join } from "node:path";
29
+ import { join } from "node:path";
30
30
  import { randomBytes } from "node:crypto";
31
31
  /** Owner read/write only. The bearer pair must never be group/world-readable. */
32
32
  const FILE_MODE = 0o600;
33
- /** Owner read/write/execute only on the data dir itself. */
34
- const DIR_MODE = 0o700;
33
+ /** Owner read/write/execute only on the data dir itself. Exported so the one
34
+ * other writer of a `$SIL_DATA_DIR` sub-tree (`profile-store.ts`, the SDS
35
+ * artefact store) shares this single source of truth for the data-home mode
36
+ * rather than duplicating the literal. */
37
+ export const DIR_MODE = 0o700;
35
38
  const TOKENS_FILE = "tokens.json";
36
39
  const CONFIG_FILE = "config.json";
37
40
  /**
@@ -48,6 +51,23 @@ export function getDataDir() {
48
51
  return join(xdg, "sil");
49
52
  return join(homedir(), ".local", "share", "sil");
50
53
  }
54
+ /**
55
+ * Create the resolved data dir (`0700`) if absent and return its path. The SOLE
56
+ * creator of the data dir — `register()` calls it at load (so the home exists
57
+ * from the moment the plugin registers, not lazily on first write), and the
58
+ * write paths call it before every write, which doubles as the guard against the
59
+ * dir being deleted out from under a running session.
60
+ *
61
+ * Idempotent: `mkdirSync(..., { recursive: true })` is a clean no-op when the dir
62
+ * already exists, never re-permissioning or disturbing existing contents. Throws
63
+ * the raw fs error (ENOTDIR/EACCES/ENOSPC…) on a genuinely uncreatable path —
64
+ * callers surface it (fail-closed), never swallow it.
65
+ */
66
+ export function ensureDataDir() {
67
+ const dir = getDataDir();
68
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE });
69
+ return dir;
70
+ }
51
71
  export function getTokensPath() {
52
72
  return join(getDataDir(), TOKENS_FILE);
53
73
  }
@@ -57,7 +77,7 @@ export function getConfigPath() {
57
77
  /**
58
78
  * True iff a `tokens.json` exists on disk. This is the already-registered
59
79
  * short-circuit's gate — it is PRESENCE-based, not freshness-based: an expired
60
- * access token still counts as "registered" for this card (refresh is SC7, the
80
+ * session token still counts as "registered" for this card (refresh is SC7, the
61
81
  * sil_whoami card). Note carried forward in the card body.
62
82
  */
63
83
  export function hasTokens() {
@@ -114,13 +134,16 @@ export function clearTokens() {
114
134
  * The temp file is created `0600` and the final file is re-`chmod`'d to `0600`
115
135
  * in case the rename inherited a different mode on some filesystems.
116
136
  *
117
- * Creating the dir first (recursive, `0700`) makes first-run on a clean machine
118
- * a non-error. The temp name carries random bytes so two concurrent writers (a
119
- * pathological double-register sharing a data dir) don't collide on the temp.
137
+ * Ensuring the data dir first (recursive, `0700`, via `ensureDataDir()`) makes
138
+ * first-run on a clean machine a non-error AND re-heals the home if it was
139
+ * deleted out from under a running session before this write. The token/config
140
+ * paths are always direct children of `getDataDir()`, so the dir ensured here is
141
+ * exactly the one the write lands in. The temp name carries random bytes so two
142
+ * concurrent writers (a pathological double-register sharing a data dir) don't
143
+ * collide on the temp.
120
144
  */
121
145
  function writeJsonAtomic(path, data) {
122
- const dir = dirname(path);
123
- mkdirSync(dir, { recursive: true, mode: DIR_MODE });
146
+ ensureDataDir();
124
147
  const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
125
148
  writeFileSync(tmp, JSON.stringify(data, null, 2), {
126
149
  encoding: "utf-8",
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Pure, typed merge core for trusting `sil` in a host OpenClaw config.
3
+ *
4
+ * On install OpenClaw discovers `sil` as a non-bundled plugin, but with an
5
+ * empty `plugins.allow` it warns that discovered plugins may auto-load
6
+ * unrestricted. This module computes the additive, idempotent edit that
7
+ * closes that warning by trusting `sil` at the THREE real allow surfaces of
8
+ * the `alpine/openclaw:2026.6.9` config schema:
9
+ *
10
+ * - `plugins.allow` string[] of plugin IDs — emptiness fires the warning
11
+ * - `tools.alsoAllow` string[] of plugin IDs — admits a plugin's tools by
12
+ * ID (NO per-tool-name key
13
+ * exists; this is how all of
14
+ * sil's tools become un-filtered)
15
+ * - `plugins.entries.sil` { enabled, config } — makes sil loadable/exposing
16
+ *
17
+ * There is no global skill allow-list — a skill attaches per-agent via
18
+ * `agents.list[i].skills`, which is the host-wiring path's job, NOT this
19
+ * helper's. `sil.tools` / `sil.skill` are carried in the facts type only for
20
+ * the operator log fields; the merge never enumerates tool names into config,
21
+ * because on 2026.6.9 the mechanism is plugin-ID admission.
22
+ *
23
+ * This module is pure (no I/O). The config arrives as `unknown` because the
24
+ * file is operator-editable and may be any shape; every read narrows with
25
+ * `typeof` / `Array.isArray` before use. A present-but-wrong-typed allow array
26
+ * is a hard error (we never coerce — that risks clobbering operator state).
27
+ *
28
+ * Invariants (the two the suite exists to defend):
29
+ * - ADDITIVE: a pre-existing entry is never removed, reordered, or
30
+ * overwritten — sil's IDs are only ever appended; an existing
31
+ * `plugins.entries.sil` is left untouched.
32
+ * - IDEMPOTENT: `changed` is computed from set membership, so a second run
33
+ * finds nothing missing and reports `changed: false` (the I/O shell then
34
+ * writes nothing).
35
+ *
36
+ * OQ3 — enabling the restriction must never silently un-trust a plugin the
37
+ * permissive empty-list default was auto-loading. So when `plugins.allow` is
38
+ * empty/absent, we seed it with every ID already recorded under
39
+ * `plugins.entries` (the host's own record of installed plugins) before
40
+ * appending `sil`. The seed IDs are read from the live config, never hardcoded.
41
+ */
42
+ /** Thrown when the operator-editable config has a shape we refuse to coerce
43
+ * (a non-object root, or a present-but-non-array allow surface). The I/O shell
44
+ * maps this to the `sil_allowlist_merge_failed` outcome — fail closed, never
45
+ * silently overwrite operator state. */
46
+ export class AllowlistShapeError extends Error {
47
+ name = "AllowlistShapeError";
48
+ }
49
+ function isPlainObject(value) {
50
+ return typeof value === "object" && value !== null && !Array.isArray(value);
51
+ }
52
+ /** Append `id` to `arr` if absent. Returns true iff a mutation occurred —
53
+ * append-only, so order is preserved and pre-existing entries are byte-stable. */
54
+ function appendIfAbsent(arr, id) {
55
+ if (arr.includes(id))
56
+ return false;
57
+ arr.push(id);
58
+ return true;
59
+ }
60
+ /**
61
+ * Compute the additive, idempotent merge that trusts `sil` in the given config.
62
+ *
63
+ * Mutates a copy is NOT what we do — we mutate the passed object in place (the
64
+ * I/O shell parses fresh per run, so there is no aliasing hazard) and return it
65
+ * for ergonomics. All three merges happen in-memory before the shell does its
66
+ * single atomic write, so a crash mid-merge can never half-write the file.
67
+ *
68
+ * @throws AllowlistShapeError if `config` is not an object, or if any of
69
+ * `plugins.allow`, `tools.alsoAllow`, `plugins.entries` is present but the
70
+ * wrong type (non-array / non-object) — we refuse to coerce.
71
+ */
72
+ export function mergeSilAllowlist(config, sil) {
73
+ if (!isPlainObject(config)) {
74
+ throw new AllowlistShapeError("OpenClaw config root must be a JSON object, got: "
75
+ + (config === null ? "null" : Array.isArray(config) ? "array" : typeof config));
76
+ }
77
+ // --- Narrow / create the `plugins` container -------------------------------
78
+ if (config["plugins"] !== undefined && !isPlainObject(config["plugins"])) {
79
+ throw new AllowlistShapeError("config.plugins must be an object when present, got: " + typeof config["plugins"]);
80
+ }
81
+ if (config["plugins"] === undefined)
82
+ config["plugins"] = {};
83
+ const plugins = config["plugins"];
84
+ // --- Narrow / create the `tools` container ---------------------------------
85
+ if (config["tools"] !== undefined && !isPlainObject(config["tools"])) {
86
+ throw new AllowlistShapeError("config.tools must be an object when present, got: " + typeof config["tools"]);
87
+ }
88
+ if (config["tools"] === undefined)
89
+ config["tools"] = {};
90
+ const tools = config["tools"];
91
+ // --- Narrow `plugins.entries` (read-only for the OQ3 seed) -----------------
92
+ if (plugins["entries"] !== undefined && !isPlainObject(plugins["entries"])) {
93
+ throw new AllowlistShapeError("config.plugins.entries must be an object when present, got: "
94
+ + typeof plugins["entries"]);
95
+ }
96
+ const entries = isPlainObject(plugins["entries"])
97
+ ? plugins["entries"]
98
+ : undefined;
99
+ // --- 1. plugins.allow ------------------------------------------------------
100
+ // A present-but-non-array allow is a hard error: coercing it would silently
101
+ // discard whatever the operator put there.
102
+ if (plugins["allow"] !== undefined && !Array.isArray(plugins["allow"])) {
103
+ throw new AllowlistShapeError("config.plugins.allow must be an array when present, got: " + typeof plugins["allow"]);
104
+ }
105
+ // Every element must be a string — a mixed array is operator corruption we
106
+ // refuse to silently propagate.
107
+ const existingAllow = plugins["allow"];
108
+ if (existingAllow && existingAllow.some((x) => typeof x !== "string")) {
109
+ throw new AllowlistShapeError("config.plugins.allow must contain only strings");
110
+ }
111
+ let allowChanged = false;
112
+ if (!existingAllow || existingAllow.length === 0) {
113
+ // Empty/absent → flipping from permissive (auto-loads everything) to
114
+ // explicit (allow-list enforced) would un-trust every other installed
115
+ // plugin. Seed with sil + every ID the host already records under
116
+ // `plugins.entries`, so enabling the restriction never silently excludes a
117
+ // previously auto-loading plugin (OQ3). Seed IDs come from the live config.
118
+ const seed = [sil.id, ...(entries ? Object.keys(entries) : [])];
119
+ const deduped = [];
120
+ for (const id of seed)
121
+ appendIfAbsent(deduped, id);
122
+ plugins["allow"] = deduped;
123
+ allowChanged = true;
124
+ }
125
+ else {
126
+ // Non-empty → append sil only; the other trusted IDs stay, in order (AC5).
127
+ allowChanged = appendIfAbsent(existingAllow, sil.id);
128
+ }
129
+ // --- 2. tools.alsoAllow ----------------------------------------------------
130
+ if (tools["alsoAllow"] !== undefined && !Array.isArray(tools["alsoAllow"])) {
131
+ throw new AllowlistShapeError("config.tools.alsoAllow must be an array when present, got: "
132
+ + typeof tools["alsoAllow"]);
133
+ }
134
+ const existingAlsoAllow = tools["alsoAllow"];
135
+ if (existingAlsoAllow && existingAlsoAllow.some((x) => typeof x !== "string")) {
136
+ throw new AllowlistShapeError("config.tools.alsoAllow must contain only strings");
137
+ }
138
+ if (existingAlsoAllow === undefined)
139
+ tools["alsoAllow"] = [];
140
+ const alsoAllowChanged = appendIfAbsent(tools["alsoAllow"], sil.id);
141
+ // --- 3. plugins.entries.<id> -----------------------------------------------
142
+ // Set the enable entry ONLY when absent — never overwrite an operator's
143
+ // existing `enabled`/`config` (AC4). Create the entries container if needed.
144
+ if (plugins["entries"] === undefined)
145
+ plugins["entries"] = {};
146
+ const entriesObj = plugins["entries"];
147
+ let entryChanged = false;
148
+ if (!(sil.id in entriesObj)) {
149
+ entriesObj[sil.id] = { enabled: true, config: {} };
150
+ entryChanged = true;
151
+ }
152
+ return {
153
+ config: config,
154
+ changed: allowChanged || alsoAllowChanged || entryChanged,
155
+ };
156
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * sil shopping-expert behaviour-artefact store.
3
3
  *
4
- * The agent-creation engine (the bundled `skill/SKILL.md` procedure driving
4
+ * The agent-creation engine (the bundled `sil-shopping/SKILL.md` procedure driving
5
5
  * the OpenClaw host CLI) registers the *wiring* of a new sil-wired agent into
6
6
  * the host's own config — the `agents.list[]` entry, the enabled `sil` plugin,
7
7
  * the attached `sil` skill. That host-config write is the host agent driving
@@ -53,18 +53,25 @@
53
53
  * already live in `$SIL_DATA_DIR` but stay logically separate (no identity
54
54
  * coupling — creating an expert reads/writes no token).
55
55
  *
56
- * Writes are atomic and all-or-nothing (Product invariant 7): a bad spec
57
- * writes NOTHING (validate first), and a mid-write failure leaves no partial
58
- * artefact directory behind. The atomic write mirrors `credentials.ts` —
59
- * tmp file → write → rename over target → chmod 0600, dir 0700.
56
+ * Write safety (Product invariant 7): a bad spec writes NOTHING (validate
57
+ * first). Each artefact is written atomically — tmp file → write → rename over
58
+ * target → chmod 0600, dir 0700 (mirroring `credentials.ts`) — so a reader never
59
+ * sees a half-written file. On a mid-write failure the guarantee depends on
60
+ * whether the expert is new: a FRESH create (the dir did not pre-exist) is torn
61
+ * down, leaving no partial directory behind (all-or-nothing); a RE-MATERIALIZE
62
+ * over an existing expert is per-file atomic and dir-preserving — it is NOT a
63
+ * cross-file transaction, so on failure the prior expert is left intact and is
64
+ * never served half-refined (a referenced-but-missing body fails the read closed
65
+ * — see `readAgentProfile`). The catch block below encodes exactly this split.
60
66
  */
61
67
  import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from "node:fs";
62
68
  import { dirname, join } from "node:path";
63
69
  import { randomBytes } from "node:crypto";
64
- import { getDataDir } from "./credentials.js";
65
- /** Owner-only file/dir modes — the artefacts are user-scoped, like tokens. */
70
+ import { DIR_MODE, ensureDataDir, getDataDir } from "./credentials.js";
71
+ /** Owner-only file mode — the artefacts are user-scoped, like tokens. The dir
72
+ * mode (`DIR_MODE`, `0o700`) is owned by `credentials.ts` (the data-dir owner)
73
+ * and imported, so the data-home permission lives in exactly one place. */
66
74
  const FILE_MODE = 0o600;
67
- const DIR_MODE = 0o700;
68
75
  /** The sub-tree under `$SIL_DATA_DIR` that holds per-agent behaviour artefacts. */
69
76
  const AGENTS_SUBDIR = "agents";
70
77
  /** Artefact filenames (stable — the sil skill resolves them from profile.json,
@@ -83,7 +90,8 @@ const AGENT_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
83
90
  * SAFETY: this resolver does NOT guard `agentId` — it joins it as a path segment
84
91
  * verbatim. The path-traversal guard lives at the only caller, `materializeProfile`,
85
92
  * which validates `agentId` against `AGENT_ID_RE` (lower-kebab, not `main`) BEFORE
86
- * the join, so `../escape`, `a/../b`, `.`, etc. never reach here. The guard is
93
+ * the join, so a traversal-shaped id (a parent-directory hop, a nested back-step,
94
+ * a bare dot) never reaches here. The guard is
87
95
  * placed at the caller (not here) because validation must precede ALL writes for
88
96
  * the validate-first / write-nothing-on-bad-input invariant to hold; a guard
89
97
  * duplicated here would be redundant for that path. A FUTURE DIRECT CALLER of this
@@ -160,6 +168,11 @@ export function materializeProfile(spec) {
160
168
  // destroying anything pre-existing).
161
169
  const dirPreexisted = existsSync(dir);
162
170
  try {
171
+ // Ensure the data home (`$SIL_DATA_DIR`, 0700) exists first — its creation
172
+ // and mode are owned by credentials.ts (the data-dir owner), and this also
173
+ // re-heals it if it was deleted mid-session. Then create the per-agent leaf
174
+ // (`agents/<id>`), which is profile-store's own concern.
175
+ ensureDataDir();
163
176
  mkdirSync(dir, { recursive: true, mode: DIR_MODE });
164
177
  atomicWrite(domainSpecPath, spec.domainSpec);
165
178
  atomicWrite(intentSpecPath, spec.intentSpec);
@@ -232,8 +245,8 @@ function getAgentsRoot() {
232
245
  * `getAgentArtefactDir`. Returns `null` when valid; an `invalid_request`
233
246
  * variant naming the field otherwise. The gate is identical to
234
247
  * `materializeProfile`'s validate-first block (`AGENT_ID_RE` + non-`main`),
235
- * applied BEFORE any `join`/`read`/`rm` so a `../`, `/`, `.`, or `main` never
236
- * becomes a filesystem path segment. `getAgentArtefactDir`'s SAFETY note
248
+ * applied BEFORE any path join, read, or delete so a parent-directory traversal,
249
+ * an absolute path, a bare dot, or `main` never becomes a filesystem path segment. `getAgentArtefactDir`'s SAFETY note
237
250
  * mandates exactly this for every direct caller — list does not (it never
238
251
  * trusts a caller-supplied id; it reads only ids it discovered on disk), but
239
252
  * read and remove DO take a caller id and so call this first. */
@@ -427,10 +440,10 @@ function notFoundRead(agentId) {
427
440
  * - asserts the resolved target is strictly UNDER `getDataDir()/agents/` and
428
441
  * is NOT the `agents/` parent, so a delete can never escape the subtree or
429
442
  * wipe sibling experts;
430
- * - `rmSync(dir, { recursive, force })` the single leaf dir.
443
+ * - recursively delete the single validated leaf dir.
431
444
  *
432
445
  * Absent target → `not_found` (idempotent — a re-run after a partial host-CLI
433
- * failure is safe). A genuine `rmSync` failure (e.g. EACCES) →
446
+ * failure is safe). A genuine delete failure (e.g. EACCES) →
434
447
  * `persistence_failed` with `<dir>: <cause>`. Never throws across the boundary.
435
448
  */
436
449
  export function removeAgentArtefacts(agentId) {
@@ -439,8 +452,8 @@ export function removeAgentArtefacts(agentId) {
439
452
  return bad;
440
453
  const dir = getAgentArtefactDir(agentId);
441
454
  // Defence in depth beyond the id gate: assert the resolved path is strictly a
442
- // child of the agents root and never the root itself. A `rmSync` of the
443
- // parent would wipe every sibling expert — refuse it even if some future
455
+ // child of the agents root and never the root itself. Deleting the parent
456
+ // directory would wipe every sibling expert — refuse it even if some future
444
457
  // change to the gate let a separator-bearing id through.
445
458
  const root = getAgentsRoot();
446
459
  if (dirname(dir) !== root || dir === root) {
@@ -31,7 +31,7 @@
31
31
  * Wire contract for the sil-API identity read (a SECOND origin — sil-api, the
32
32
  * Fastify domain service — NOT sil-web; bare path, not /api/v1; see the
33
33
  * sil-whoami card). The authenticated self-read is a BODYLESS GET; the
34
- * Authorization header carries the stored access token and IS the principal —
34
+ * Authorization header carries the stored session token and IS the principal —
35
35
  * sil-api derives the user from the JWT `sub`, not a request body:
36
36
  *
37
37
  * GET <silApiUrl>/identity Authorization: Bearer <access_token>
@@ -519,7 +519,7 @@ export async function refreshStoredTokens() {
519
519
  * module's `readTokens` (so a TOCTOU on
520
520
  * the on-disk pair is observed):
521
521
  * re-read empty (TOCTOU) → must_reregister(no_stored_tokens), NO retry.
522
- * re-read ok → retry ONCE with the rotated access token:
522
+ * re-read ok → retry ONCE with the rotated session token:
523
523
  * retry still unauthorized → second_unauthorized (the rotated token is
524
524
  * structurally dead — NEVER refresh again).
525
525
  * retry otherwise → `{ result, retry }`.
@@ -40,7 +40,7 @@
40
40
  * `sil_register`; a transient/invalid must NOT (re-registering can't fix a 5xx or
41
41
  * a bad query and would derail the user).
42
42
  *
43
- * Privacy: the access token and Bearer header never reach a log line or the
43
+ * Privacy: the session token and Bearer header never reach a log line or the
44
44
  * result; logs carry only non-credential status markers (search params are not
45
45
  * credentials, but are not logged either — nothing here needs them).
46
46
  *
@@ -125,9 +125,10 @@ function registerSearch(api) {
125
125
  + " in the user's OWN country (home-country / domestic / local sellers) — set it"
126
126
  + " ONLY when the shopper asks for local/domestic shops; it nudges local shops up"
127
127
  + " the ranking but does NOT restrict results to them, so never tell the user the"
128
- + " results are all local. To actually surface local shops, ALSO issue the"
129
- + " `query` in the USER'S LANGUAGE (a Greek-language query surfaces Greek shops);"
130
- + " pass NO country — sil resolves it server-side. Requires registration (run"
128
+ + " results are all local. To surface MORE local shops you MAY also issue the"
129
+ + " `query` in that country's language (a Greek-language query surfaces Greek"
130
+ + " shops) — optional, and never an override of a language the user deliberately"
131
+ + " chose; pass NO country — sil resolves it server-side. Requires registration (run"
131
132
  + " sil_register first).",
132
133
  parameters: Type.Object({
133
134
  query: Type.Optional(Type.String({
@@ -183,9 +184,10 @@ function registerSearch(api) {
183
184
  + " nudges local shops up the ranking but does NOT restrict results to them"
184
185
  + " and does NOT guarantee every result is local — some local shops won't"
185
186
  + " be detected and some non-local shops may still appear, so never tell"
186
- + " the user the results are all local sellers. To actually surface local"
187
- + " shops, also issue the `query` in the USER'S LANGUAGE (a Greek-language"
188
- + " query surfaces Greek shops; an English query will not). You pass NO"
187
+ + " the user the results are all local sellers. To surface MORE local"
188
+ + " shops you MAY also issue the `query` in that country's language (a"
189
+ + " Greek-language query surfaces Greek shops; an English query will not)"
190
+ + " — optional, never overriding a language the user deliberately chose. You pass NO"
189
191
  + " country — sil resolves the user's country server-side from their"
190
192
  + " registered address, so do NOT call sil_whoami or pass a country. Omit"
191
193
  + " (or false) for the normal unbiased ranking.",
@@ -334,7 +336,7 @@ function mapSearchOutcome(api, outcome) {
334
336
  * classes (not-registered/401 and source/transport failure) by DISTINCT recovery
335
337
  * hints. One wrong hint = one misdirected user.
336
338
  *
337
- * Privacy + freshness: the access token and Bearer header never reach a log line
339
+ * Privacy + freshness: the session token and Bearer header never reach a log line
338
340
  * or the result; the products are always live-fetched (never cached — freshness is
339
341
  * the reason this tool exists; a cached `checkout_url`/price is a broken purchase).
340
342
  */
@@ -119,7 +119,7 @@ function registerRegister(api) {
119
119
  /**
120
120
  * `sil_whoami` — read the registered user's live identity (name + addresses)
121
121
  * from sil-api with the stored Bearer token, refreshing transparently on an
122
- * expired access token.
122
+ * expired session token.
123
123
  *
124
124
  * execute() flow (ALL I/O here; register() opens nothing, arms no timer —
125
125
  * whoami is a synchronous request/response, NOT a poll):
@@ -150,8 +150,8 @@ function registerWhoami(api) {
150
150
  name: "sil_whoami",
151
151
  label: "Who am I on sil",
152
152
  description: "Return the registered user's identity (name and addresses) from sil,"
153
- + " using the credentials stored by sil_register. If the access token has"
154
- + " expired it is refreshed transparently and the read is retried. If you"
153
+ + " using the credentials stored by sil_register. If the stored session token"
154
+ + " has expired it is refreshed transparently and the read is retried. If you"
155
155
  + " are not registered, or the session has fully expired, the result names"
156
156
  + " the recovery action (run sil_register).",
157
157
  parameters: Type.Object({}),
@@ -10,7 +10,7 @@
10
10
  * identity/voice is the host workspace `SOUL.md`, written directly via the host
11
11
  * CLI. The *wiring* half — the host `agents.list[]` entry, the enabled `sil`
12
12
  * plugin, the attached `sil` skill, the `SOUL.md` — is the host agent driving
13
- * its own `openclaw …` CLI under the bundled `skill/SKILL.md` procedure; the
13
+ * its own `openclaw …` CLI under the bundled `sil-shopping/SKILL.md` procedure; the
14
14
  * plugin never writes `~/.openclaw` (`security.noChildProcess: true`, host
15
15
  * config is outside `filesystemScope`).
16
16
  *
@@ -2,8 +2,8 @@
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.3.1",
6
- "skills": ["./skill"],
5
+ "version": "0.3.4",
6
+ "skills": ["./sil-shopping"],
7
7
  "activation": {
8
8
  "onCapabilities": ["tool"]
9
9
  },
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "security": {
53
53
  "shipsRuntimeCode": true,
54
- "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). sil_profile_materialize makes no network call and reads no token: it writes a created shopping expert's SDS behaviour artefacts (domain_spec.md + intent_spec.md + user_spec.md + playbook.md — all four required and present from creation, seeded partial then augmented every query, plus profile.json) atomically into $SIL_DATA_DIR/agents/<agentId>/ (owner-only, 0600) — the persona is the agent's host workspace SOUL.md, written by the host CLI (not this plugin, not a sil artefact), and the agent's host-config wiring is driven separately by the host CLI. sil_profile_list / sil_profile_get / sil_profile_remove are the local expert lifecycle over the same artefact store, also making no network call and reading no token: list enumerates $SIL_DATA_DIR/agents/*/profile.json read-only, get reads one expert's manifest + domain_spec/intent_spec/user_spec/playbook bodies read-only, and remove deletes exactly one validated agents/<agentId>/ leaf directory (fail-closed on a malformed/traversal id — deletes nothing) — the host-wiring half of removal is the host CLI's, not this plugin's. The PKCE verifier is held only in memory and is never written to disk. Tokens and identity PII are never logged.",
54
+ "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. sil_profile_materialize makes no network call and reads no token: it writes a created shopping expert's SDS behaviour artefacts (domain_spec.md + intent_spec.md + user_spec.md + playbook.md — all four required and present from creation, seeded partial then augmented every query, plus profile.json) into $SIL_DATA_DIR/agents/<agentId>/ (owner-only, 0600), writing each artefact atomically (tmp file → rename over target). Failure guarantee: a FRESH create that fails mid-write is torn down (no partial directory survives); a RE-MATERIALIZE over an existing expert is per-file atomic and dir-preserving (NOT a cross-file transaction) — on failure the prior expert is left intact and is never served half-refined (a missing body fails the read closed). The persona is the agent's host workspace SOUL.md, written by the host CLI (not this plugin, not a sil artefact), and the agent's host-config wiring is driven separately by the host CLI. sil_profile_list / sil_profile_get / sil_profile_remove are the local expert lifecycle over the same artefact store, also making no network call and reading no token: list enumerates $SIL_DATA_DIR/agents/*/profile.json read-only, get reads one expert's manifest + domain_spec/intent_spec/user_spec/playbook bodies read-only, and remove deletes exactly one validated agents/<agentId>/ leaf directory (fail-closed on a malformed/traversal id — deletes nothing) — the host-wiring half of removal is the host CLI's, not this plugin's. The PKCE verifier is held only in memory and is never written to disk. Tokens and identity PII are never logged.",
55
55
  "registersLongLivedService": false,
56
56
  "serviceIds": [],
57
57
  "runsTimers": true,