sil-openclaw 0.2.4 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -10,6 +10,117 @@ release (`clawhub package publish --changelog`). See [README](./README.md#releas
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.3.0] - 2026-06-23
14
+
15
+ ### Added
16
+
17
+ - **Create a tailored, sil-wired shopping expert — a real OpenClaw agent that
18
+ shops its niche with no further setup.** A new agent-creation engine (the `sil`
19
+ skill drives the host's own `openclaw` CLI — the plugin never writes the host
20
+ config) materializes a dedicated shopping expert: a real `agents.list[]` entry
21
+ with the **sil plugin enabled and the sil skill attached**, the persona injected
22
+ as the agent's `SOUL.md` system framing, and the behaviour artefacts written by
23
+ the new **`sil_profile_materialize`** tool into `$SIL_DATA_DIR/agents/<agentId>/`
24
+ (`persona.md`, an optional `playbook.md` domain sub-skill, and a `profile.json`
25
+ manifest the skill reads at runtime). The engine is validate-first and
26
+ fail-closed: it checks the spec before any write (`invalid_request` — nothing
27
+ written), refuses to clobber an existing agent (`collision` — never overwrites a
28
+ persona or its wiring), and declares `created` only after the host's **own**
29
+ `openclaw config validate` returns `valid: true` (any failed step is
30
+ `persistence_failed` carrying the path + cause, nothing partial left behind).
31
+ Creating an expert is **local and offline** — no registration, no token read,
32
+ no network call; the expert registers the user later, on first shop. Host-CLI
33
+ shapes are pinned to **`alpine/openclaw:2026.6.9`** (the sil-stage host). (#27,
34
+ #30)
35
+ - **The `sil` skill now runs a brainstorm interview before creating a shopping
36
+ expert.** An open, back-and-forth interview converges five sections *with* the
37
+ user — domain framing, persona, elicitation style, answer→`sil_search`-param
38
+ mapping, and recommendation rubric — eliciting BOTH the domain's
39
+ decision-attributes AND the user's own tastes/budget/constraints, then
40
+ assembles a tailored spec the agent-creation engine materializes via
41
+ `sil_profile_materialize`. Nothing is created until the user explicitly
42
+ endorses the assembled draft (abandon-mid-flow leaves nothing written, no
43
+ teardown); a vague domain is narrowed with the user first; a name collision
44
+ offers refine-or-rename and never clobbers. The mapping targets only real
45
+ `sil_search` params (budget → `price_min`/`price_max` in minor units, "prefer
46
+ secondhand" → `condition`, niche → `query`/`category`) and leaves `ship_to`
47
+ empty so sil resolves the registered default server-side.
48
+ - **A created expert shops its niche like a trusted specialist, not a generic
49
+ clerk.** When a session opens inside a created expert, the skill loads its
50
+ `profile.json` → `persona.md` + `playbook.md` and runs a profile-driven
51
+ shop-time loop: elicit **only the missing** load-bearing attributes in the
52
+ playbook's priority order (never a fixed question battery, never re-asking what
53
+ the user already stated), map answers to real `sil_search` params (`ship_to`
54
+ left empty so the server resolves the registered default; a taste with no
55
+ matching param folds into `query`/the rubric, never an invented filter), search,
56
+ then reason over the candidates with the playbook's rubric and the persona's
57
+ hard-rules / hard-no's — presenting results **best-first as `sil_search`
58
+ returned them (never re-ranked)** and always with the domain "why". An
59
+ empty-but-servable result relaxes a constraint and explains the change; a
60
+ genuinely unservable domain gets an honest "no", never padded with junk; a
61
+ non-`ok` status follows the tool's own `recovery`, never the empty-match path.
62
+ Consumes the catalog tools **unchanged** — no new tool; the rubric is applied at
63
+ reasoning time. (#31)
64
+ - **Local expert lifecycle — list, view, and remove the shopping experts you
65
+ create.** Three new tools manage the artefact store the create-engine writes
66
+ (`$SIL_DATA_DIR/agents/<id>/`): `sil_profile_list` enumerates your experts
67
+ most-recently-created first (sourced from each `profile.json` manifest — the
68
+ authoritative "is a sil expert" signal — with one corrupt manifest isolated
69
+ in `unreadable[]`, never aborting the listing); `sil_profile_get` returns one
70
+ expert's full detail (name, persona, optional playbook, manifest path,
71
+ createdAt); and `sil_profile_remove` deletes exactly one validated expert's
72
+ behaviour-artefact directory. All three make no network call and read no
73
+ token — generic profile-less shopping is unchanged. Removal is the **artefact
74
+ half only**: the host-wiring half (`openclaw agents remove`) is host-CLI
75
+ driven and runs **first** (a failed artefact step then leaves only harmless,
76
+ list-surfaced disk cruft — never a broken-but-loading expert), and the skill
77
+ **confirms before removing**. `sil_profile_remove` is fail-closed and scoped:
78
+ a malformed/traversal/`main` id is rejected (`invalid_request`) and deletes
79
+ nothing, an absent id is `not_found` (idempotent — safe to re-run), and a
80
+ genuine filesystem failure is `persistence_failed` with the path + cause —
81
+ never a thrown error across the tool boundary. The list/view/remove flow lives
82
+ in its own progressive-disclosure reference, `references/manage_experts.md`,
83
+ which the router routes the manage intents to.
84
+ - **Refine an existing expert from what it observed in real sessions
85
+ (self-reinforcement).** A targeted-amend loop sharpens a *named* expert without
86
+ re-brainstorming it from scratch: load it with **`sil_profile_get`**, propose
87
+ concrete refinements **grounded in observed evidence** from the just-run
88
+ shopping session (a mapping that surfaced irrelevant items, a constraint the
89
+ user volunteered but the playbook never captured, a candidate they rejected —
90
+ never a generic, ungrounded "improvement"), let the user **confirm a subset**
91
+ (per-proposal accept/reject — never inferred from silence or an off-topic
92
+ answer), and persist **only** the confirmed subset by re-running
93
+ **`sil_profile_materialize`** over that one `agentId`. The re-write is per-file
94
+ atomic and dir-preserving — a failed persist leaves the prior expert intact and
95
+ never serves a half-refined one (a torn manifest reads back as not-found,
96
+ fail-closed). The improvement is **per-user and local** (written only to this
97
+ user's `$SIL_DATA_DIR` — no server endpoint, no shared or cross-user signal, no
98
+ identity round-trip) and **isolated** (touches only the named
99
+ `agents/<agentId>/`; sibling experts and generic profile-less shopping are
100
+ untouched). Adds **no new tool** — it composes the existing `sil_profile_get` +
101
+ `sil_profile_materialize`; when no observed session is available it falls back
102
+ to a guided amend and never fabricates observations. (#32)
103
+
104
+ ### Changed
105
+
106
+ - **Restructured the bundled `sil` skill to progressive disclosure
107
+ (skill-creator convention).** `skill/SKILL.md` is now a maximally-lean pure
108
+ router: frontmatter, a one-paragraph role, the three always-on behavioural
109
+ principles, a brief session-start note, and an intent→tool→reference routing
110
+ table — nothing more. The detailed procedures moved into self-contained
111
+ references loaded on demand: `references/catalog_tools_reference.md` (the four
112
+ core tools' per-tool behaviour + the shared status taxonomy),
113
+ `references/brainstorm_interview.md` (the interview),
114
+ `references/agent_creation_engine.md` (the ordered creation engine),
115
+ `references/search_param_mapping.md` (the answer→`sil_search`-param mapping),
116
+ and `references/manage_experts.md` (the list/view/remove flow), with a worked
117
+ end-to-end walkthrough under `examples/road_cycling_expert_walkthrough.md`.
118
+ The endorsement-before-engine gate now lives as the router's two-step trigger
119
+ (interview first; engine only after explicit endorsement). The
120
+ contributor-facing "adding a tool" prose — duplicated from the repo
121
+ `CLAUDE.md` and never needed at runtime — was removed from the skill entirely.
122
+ No detail is duplicated between the router and any reference.
123
+
13
124
  ## [0.2.4] - 2026-06-18
14
125
 
15
126
  ### Fixed
package/README.md CHANGED
@@ -58,7 +58,7 @@ The agent loads the bundled skill on first commerce intent and takes it from the
58
58
 
59
59
  sil is a [UCP](https://github.com/universal-commerce-protocol/ucp) (Universal Commerce Protocol) commerce service, and `sil-openclaw` wires it into your OpenClaw agent — so it can find products, compare prices and availability, pull up full detail, and surface a checkout link the moment you say *buy*. Powered by [4GPTs](https://4gpts.com).
60
60
 
61
- Today the plugin covers **identity and catalog** — registration plus search and product lookup. The rest of the UCP journey (cart, checkout, order, fulfillment) lands as those domains ship, and the same plugin grows with them.
61
+ Today the plugin covers **identity, catalog, and dedicated shopping experts** — registration, catalog search and product lookup, plus a one-conversation flow that mints a new OpenClaw agent pre-wired to shop a single niche for you. The rest of the UCP journey (cart, checkout, order, fulfillment) lands as those domains ship, and the same plugin grows with them.
62
62
 
63
63
  ---
64
64
 
@@ -94,6 +94,60 @@ agent done — here's your checkout link, ready to pay:
94
94
 
95
95
  ---
96
96
 
97
+ ## Turn your OpenClaw into a shopping expert
98
+
99
+ So far your *general* agent did the shopping. Go one step further: mint a **dedicated** OpenClaw agent that shops a single niche like a specialist — its taste, budget, and hard rules baked in once, then reused on every visit.
100
+
101
+ **TL;DR** — say *"make me a shopping expert for road-cycling gear"* and the plugin **interviews you** (the niche, your taste, your budget, the rules it must never break), then creates a real OpenClaw agent wired to sil with that persona and playbook. Open it later and it already knows your niche: it asks only what's still missing, searches sil with your constraints pre-set, and ranks results your way. **Nothing is created until you say "create it"** — and building one is local and offline, no sign-in required.
102
+
103
+ **1 — One conversation builds the expert:**
104
+
105
+ ```text
106
+ you make me a shopping expert for road-cycling gear
107
+
108
+ agent Love it — let's shape it together. Components and apparel,
109
+ or complete bikes too?
110
+
111
+ you components and apparel, I've got the frame. ~€1200 budget,
112
+ secondhand is fine, and I'm in France
113
+
114
+ agent Here's the expert I'll build:
115
+
116
+ Road-Cycling Buyer — a concise components advisor
117
+ · always flags groupset compatibility · never carbon bars
118
+ · searches secondhand to ~€1200, French shops first
119
+ · ranks compatibility → value → weight
120
+
121
+ shall I create it?
122
+
123
+ you yes, create it
124
+
125
+ agent done — "Road-Cycling Buyer" is live. Open it anytime;
126
+ it shops your niche with no further setup.
127
+ ```
128
+
129
+ **2 — The expert shops like a specialist, not a clerk:**
130
+
131
+ ```text
132
+ you (inside Road-Cycling Buyer) I need new wheels
133
+
134
+ agent what groupset are you running? — so I only show compatible builds
135
+
136
+ you Shimano 105
137
+
138
+ agent searched sil — secondhand, France-first, 105-compatible:
139
+
140
+ 1. Fulcrum Racing 4 (used) €420 Shimano HG ✓ · 1560 g
141
+ 2. DT Swiss P1800 (used) €505 Shimano HG ✓ · 1700 g
142
+
143
+ ranked compatibility → value → weight, the way you set it up.
144
+ want detail or a checkout link on either?
145
+ ```
146
+
147
+ > **You teach it once; it stays an expert.** 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.
148
+
149
+ ---
150
+
97
151
  ## Identity & authentication
98
152
 
99
153
  **sil gives your agent an identity — and the capability to use it.** One browser sign-in links your OpenClaw agent to a sil identity it holds on your behalf — your name, your saved addresses. That identity is what lets the agent *transact*: it can search, compare, and surface checkout links with any merchant that speaks [UCP](https://github.com/universal-commerce-protocol/ucp) (the Universal Commerce Protocol), all under your account, without you ever touching a store login.
@@ -120,13 +174,23 @@ Namespaced `sil_*` so they never collide with other plugins. Your agent calls th
120
174
  | `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. |
121
175
  | `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`. |
122
176
 
177
+ **Experts** — create and manage dedicated shopping agents
178
+
179
+ | Tool | What it does |
180
+ |---|---|
181
+ | `sil_profile_materialize` | Persist a created expert's behaviour artefacts — `persona.md`, an optional `playbook.md` domain sub-skill, and a `profile.json` manifest — under `$SIL_DATA_DIR/agents/<id>/`. Driven by the skill's creation engine once you endorse the draft; validate-first and fail-closed, it never clobbers an existing expert. |
182
+ | `sil_profile_list` | List the experts you've created, most-recently-made first. Takes no arguments. |
183
+ | `sil_profile_get` | Show one expert in full — `name`, `persona`, optional `playbook`, manifest path, and `createdAt`. |
184
+ | `sil_profile_remove` | Delete one expert's behaviour artefacts. Scoped and idempotent; the agent confirms with you before removing. |
185
+
123
186
  ---
124
187
 
125
188
  ## Skills
126
189
 
127
- 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 four tools work well together:
190
+ 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:
128
191
 
129
- - **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`.
192
+ - **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.
193
+ - **Interviews before it builds.** Asked for a shopping expert, it runs an open interview to shape the niche, persona, and rules *with* you — and creates nothing until you explicitly endorse the assembled draft.
130
194
  - **Recovers the right way.** Every tool reports a status; the skill follows that tool's own recovery hint — re-register, fix the query, or retry — instead of guessing a fix that won't work.
131
195
  - **Keeps prices honest.** It treats price, availability, and checkout links as point-in-time and re-checks an item right before you buy, so the link you get is the link you pay.
132
196
 
package/dist/index.js CHANGED
@@ -23,6 +23,7 @@ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
23
23
  import { applyPluginConfigOverrides, getWebUrl, getWebUrlSource, getApiUrl, getApiUrlSource, } from "./lib/config.js";
24
24
  import { registerCatalogTools } from "./tools/catalog.js";
25
25
  import { registerIdentityTools } from "./tools/identity.js";
26
+ import { registerProfileTools } from "./tools/profile.js";
26
27
  export default definePluginEntry({
27
28
  id: "sil",
28
29
  name: "sil",
@@ -32,6 +33,7 @@ export default definePluginEntry({
32
33
  applyPluginConfigOverrides(api.pluginConfig);
33
34
  registerIdentityTools(api);
34
35
  registerCatalogTools(api);
36
+ registerProfileTools(api);
35
37
  api.logger.info("sil_plugin_loaded", {
36
38
  message: "sil plugin registered.",
37
39
  api_url: getWebUrl(),
@@ -0,0 +1,426 @@
1
+ /**
2
+ * sil shopping-expert behaviour-artefact store.
3
+ *
4
+ * The agent-creation engine (the bundled `skill/SKILL.md` procedure driving
5
+ * the OpenClaw host CLI) registers the *wiring* of a new sil-wired agent into
6
+ * the host's own config — the `agents.list[]` entry, the enabled `sil` plugin,
7
+ * the attached `sil` skill. That host-config write is the host agent driving
8
+ * its own `openclaw …` CLI; the plugin never touches `~/.openclaw`.
9
+ *
10
+ * What the plugin DOES own is the agent's *behaviour* layer, materialized into
11
+ * its own disclosed `filesystemScope` — `$SIL_DATA_DIR` (the same directory
12
+ * `lib/credentials.ts` uses for tokens/identity). Per the founder steer
13
+ * (2026-06-22) the engine writes a fixed, minimal set of artefacts there that
14
+ * power the created expert's behaviour, read by the sil skill at runtime:
15
+ *
16
+ * $SIL_DATA_DIR/agents/<agentId>/
17
+ * ├─ persona.md the shopping persona/instructions (host-natural —
18
+ * │ same shape as a workspace SOUL.md; the skill copies it
19
+ * │ into the agent workspace SOUL.md and re-reads it at
20
+ * │ session start)
21
+ * ├─ playbook.md the generated domain sub-skill (host-natural — same
22
+ * │ shape as a SKILL.md body; loaded by the sil skill at
23
+ * │ session start). OPTIONAL — written only when supplied.
24
+ * └─ profile.json the strictly-typed manifest the sil skill resolves the
25
+ * artefacts from (no filesystem guessing)
26
+ *
27
+ * Store boundary: host config = wiring; `$SIL_DATA_DIR` = behaviour artefacts.
28
+ * Identity/tokens already live in `$SIL_DATA_DIR` but stay logically separate
29
+ * (no identity coupling — creating an expert reads/writes no token).
30
+ *
31
+ * Writes are atomic and all-or-nothing (Product invariant 7): a bad spec
32
+ * writes NOTHING (validate first), and a mid-write failure leaves no partial
33
+ * artefact directory behind. The atomic write mirrors `credentials.ts` —
34
+ * tmp file → write → rename over target → chmod 0600, dir 0700.
35
+ */
36
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, } from "node:fs";
37
+ import { dirname, join } from "node:path";
38
+ import { randomBytes } from "node:crypto";
39
+ import { getDataDir } from "./credentials.js";
40
+ /** Owner-only file/dir modes — the artefacts are user-scoped, like tokens. */
41
+ const FILE_MODE = 0o600;
42
+ const DIR_MODE = 0o700;
43
+ /** The sub-tree under `$SIL_DATA_DIR` that holds per-agent behaviour artefacts. */
44
+ const AGENTS_SUBDIR = "agents";
45
+ /** Artefact filenames (stable — the sil skill resolves them from profile.json,
46
+ * but the names are also documented so a human can find them). */
47
+ const PERSONA_FILE = "persona.md";
48
+ const PLAYBOOK_FILE = "playbook.md";
49
+ const PROFILE_FILE = "profile.json";
50
+ /** A host-agent id must be lower-kebab and is never `main` (host-reserved). */
51
+ const AGENT_ID_RE = /^[a-z0-9][a-z0-9-]*$/;
52
+ /** Resolve the per-agent artefact directory under the plugin's data dir. Never
53
+ * hardcoded — `getDataDir()` honors `$SIL_DATA_DIR`/`$XDG_DATA_HOME`.
54
+ *
55
+ * SAFETY: this resolver does NOT guard `agentId` — it joins it as a path segment
56
+ * verbatim. The path-traversal guard lives at the only caller, `materializeProfile`,
57
+ * which validates `agentId` against `AGENT_ID_RE` (lower-kebab, not `main`) BEFORE
58
+ * the join, so `../escape`, `a/../b`, `.`, etc. never reach here. The guard is
59
+ * placed at the caller (not here) because validation must precede ALL writes for
60
+ * the validate-first / write-nothing-on-bad-input invariant to hold; a guard
61
+ * duplicated here would be redundant for that path. A FUTURE DIRECT CALLER of this
62
+ * exported resolver would bypass the guard — re-run `AGENT_ID_RE` (or route through
63
+ * `materializeProfile`) before trusting the returned path with any filesystem op. */
64
+ export function getAgentArtefactDir(agentId) {
65
+ return join(getDataDir(), AGENTS_SUBDIR, agentId);
66
+ }
67
+ /** True when `s` is a present, non-blank string. */
68
+ function nonBlank(s) {
69
+ return typeof s === "string" && s.trim().length > 0;
70
+ }
71
+ function invalid(field, message) {
72
+ return { ok: false, kind: "invalid_request", field, message };
73
+ }
74
+ /**
75
+ * Materialize the behaviour artefacts for a created sil-wired agent.
76
+ *
77
+ * Validate-first: any invalid field returns `invalid_request` and writes
78
+ * NOTHING. On a write failure, the partial directory is removed and
79
+ * `persistence_failed` is returned with `<dir>: <cause>` — no partial artefact
80
+ * set ever survives (Product invariant 7, atomic outcome).
81
+ */
82
+ export function materializeProfile(spec) {
83
+ // --- validate-first (nothing is written until every field is good) ---
84
+ if (!nonBlank(spec.agentId)) {
85
+ return invalid("agentId", "agentId is required and must be non-empty.");
86
+ }
87
+ if (spec.agentId === "main") {
88
+ return invalid("agentId", '"main" is host-reserved and cannot be a sil expert id.');
89
+ }
90
+ if (!AGENT_ID_RE.test(spec.agentId)) {
91
+ return invalid("agentId", "agentId must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(spec.agentId));
92
+ }
93
+ if (!nonBlank(spec.name)) {
94
+ return invalid("name", "name is required and must be non-empty.");
95
+ }
96
+ if (!nonBlank(spec.persona)) {
97
+ return invalid("persona", "persona is required and must be non-empty.");
98
+ }
99
+ // playbook is optional, but if present it must be non-blank (an empty string
100
+ // would materialize a useless artefact — reject it loudly rather than write it).
101
+ if (spec.playbook !== undefined && !nonBlank(spec.playbook)) {
102
+ return invalid("playbook", "playbook, when provided, must be non-empty.");
103
+ }
104
+ const dir = getAgentArtefactDir(spec.agentId);
105
+ const personaPath = join(dir, PERSONA_FILE);
106
+ const playbookPath = spec.playbook !== undefined ? join(dir, PLAYBOOK_FILE) : undefined;
107
+ const profilePath = join(dir, PROFILE_FILE);
108
+ const manifest = {
109
+ agentId: spec.agentId,
110
+ name: spec.name,
111
+ personaPath,
112
+ ...(playbookPath ? { playbookPath } : {}),
113
+ createdAt: new Date().toISOString(),
114
+ };
115
+ // Whether the artefact directory already existed before this call. If it did,
116
+ // it is not ours to delete on failure (it may hold a prior expert's artefacts,
117
+ // or — if the path is occupied by a non-directory — a user's file). We only
118
+ // remove what THIS call created (Product invariant 7: nothing partial, without
119
+ // destroying anything pre-existing).
120
+ const dirPreexisted = existsSync(dir);
121
+ try {
122
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE });
123
+ atomicWrite(personaPath, spec.persona);
124
+ if (playbookPath && spec.playbook !== undefined) {
125
+ atomicWrite(playbookPath, spec.playbook);
126
+ }
127
+ atomicWrite(profilePath, JSON.stringify(manifest, null, 2) + "\n");
128
+ }
129
+ catch (err) {
130
+ // Leave nothing partial behind — but only tear down the dir if WE created it.
131
+ if (!dirPreexisted) {
132
+ try {
133
+ rmSync(dir, { recursive: true, force: true });
134
+ }
135
+ catch {
136
+ // Cleanup is best-effort; the original cause is what the caller needs.
137
+ }
138
+ }
139
+ const cause = err instanceof Error ? err.message : String(err);
140
+ return {
141
+ ok: false,
142
+ kind: "persistence_failed",
143
+ error: dir + ": " + cause,
144
+ message: "The shopping-expert behaviour artefacts could NOT be written to the sil"
145
+ + " data directory, so the profile did not stick. Fix the data directory"
146
+ + " (it must be writable — check permissions / free space / that"
147
+ + " $SIL_DATA_DIR is a directory), then create the expert again.",
148
+ };
149
+ }
150
+ return {
151
+ ok: true,
152
+ agentId: spec.agentId,
153
+ dir,
154
+ personaPath,
155
+ ...(playbookPath ? { playbookPath } : {}),
156
+ profilePath,
157
+ };
158
+ }
159
+ /** Atomic single-file write: tmp sibling → write → rename over target → chmod.
160
+ * Mirrors the token/identity write in `credentials.ts` so a half-written
161
+ * artefact never appears (a reader sees the old file or the new one). */
162
+ function atomicWrite(path, contents) {
163
+ const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
164
+ writeFileSync(tmp, contents, { mode: FILE_MODE });
165
+ renameSync(tmp, path);
166
+ chmodSync(path, FILE_MODE);
167
+ }
168
+ // ===========================================================================
169
+ // Local expert lifecycle — list / view / remove the artefact half.
170
+ //
171
+ // The manifest (`profile.json`) is the source of truth for "is this a sil
172
+ // expert": a directory under `agents/<id>/` with a readable profile.json IS an
173
+ // expert; a bare host `agents.list[]` entry without one is not ours to manage.
174
+ // The host-config (wiring) half of list/remove is the host agent driving its
175
+ // own `openclaw …` CLI — these primitives only ever touch `$SIL_DATA_DIR`.
176
+ //
177
+ // Each primitive returns a discriminated result and NEVER throws across the
178
+ // boundary (mirroring MaterializeResult), so one corrupt manifest or a single
179
+ // failed delete degrades only its own outcome — never the whole operation.
180
+ // ===========================================================================
181
+ /** Resolve the agents subtree root under the plugin's data dir — the parent of
182
+ * every per-agent artefact directory. The deleter asserts a target is strictly
183
+ * a child of this (and never this itself), so a delete can never reach the
184
+ * parent and wipe sibling experts. */
185
+ function getAgentsRoot() {
186
+ return join(getDataDir(), AGENTS_SUBDIR);
187
+ }
188
+ /** Re-run the writer's exact `agentId` gate at a DIRECT caller of
189
+ * `getAgentArtefactDir`. Returns `null` when valid; an `invalid_request`
190
+ * variant naming the field otherwise. The gate is identical to
191
+ * `materializeProfile`'s validate-first block (`AGENT_ID_RE` + non-`main`),
192
+ * applied BEFORE any `join`/`read`/`rm` so a `../`, `/`, `.`, or `main` never
193
+ * becomes a filesystem path segment. `getAgentArtefactDir`'s SAFETY note
194
+ * mandates exactly this for every direct caller — list does not (it never
195
+ * trusts a caller-supplied id; it reads only ids it discovered on disk), but
196
+ * read and remove DO take a caller id and so call this first. */
197
+ function rejectBadAgentId(agentId) {
198
+ if (!nonBlank(agentId)) {
199
+ return invalidAgentId("agentId is required and must be non-empty.");
200
+ }
201
+ if (agentId === "main") {
202
+ return invalidAgentId('"main" is host-reserved and is not a sil expert id.');
203
+ }
204
+ if (!AGENT_ID_RE.test(agentId)) {
205
+ return invalidAgentId("agentId must be lower-kebab (a-z, 0-9, hyphen) — got: " + JSON.stringify(agentId));
206
+ }
207
+ return null;
208
+ }
209
+ function invalidAgentId(message) {
210
+ return { ok: false, kind: "invalid_request", field: "agentId", message };
211
+ }
212
+ /** Read + parse one `agents/<id>/profile.json` into a typed manifest, or throw
213
+ * a descriptive error the caller maps to an `unreadable`/`not_found` outcome.
214
+ * A manifest whose JSON parses but is missing the required string fields is
215
+ * treated as corrupt (an interrupted or hand-edited write) — not silently
216
+ * coerced. */
217
+ function readManifestFile(profilePath) {
218
+ const raw = readFileSync(profilePath, "utf8");
219
+ const parsed = JSON.parse(raw);
220
+ if (typeof parsed !== "object" ||
221
+ parsed === null ||
222
+ typeof parsed.agentId !== "string" ||
223
+ typeof parsed.name !== "string" ||
224
+ typeof parsed.personaPath !== "string" ||
225
+ typeof parsed.createdAt !== "string") {
226
+ throw new Error("profile.json is missing required manifest fields");
227
+ }
228
+ return parsed;
229
+ }
230
+ /**
231
+ * Enumerate the materialized experts under each `$SIL_DATA_DIR/agents/<id>/`.
232
+ *
233
+ * The manifest is the source of truth — each `agents/<id>/profile.json` is read
234
+ * and parsed (no dirname guessing). Experts are returned `createdAt` DESC (the
235
+ * just-made expert first, the one the user most likely wants to act on). An
236
+ * absent/empty store yields a normal empty listing. One unreadable or corrupt
237
+ * manifest lands in `unreadable[]` and never aborts the listing — the healthy
238
+ * experts still list. Reads only; never writes, never reads a token.
239
+ */
240
+ export function listAgentProfiles() {
241
+ const root = getAgentsRoot();
242
+ if (!existsSync(root)) {
243
+ return { ok: true, experts: [], unreadable: [] };
244
+ }
245
+ const experts = [];
246
+ const unreadable = [];
247
+ let entries;
248
+ try {
249
+ entries = readdirSync(root, { withFileTypes: true });
250
+ }
251
+ catch (err) {
252
+ // The agents root exists but cannot be enumerated (e.g. EACCES). Surface it
253
+ // as a single degraded entry rather than throwing across the boundary.
254
+ unreadable.push({
255
+ agentId: AGENTS_SUBDIR,
256
+ error: errCause(err),
257
+ });
258
+ return { ok: true, experts, unreadable };
259
+ }
260
+ for (const entry of entries) {
261
+ if (!entry.isDirectory())
262
+ continue;
263
+ const agentId = entry.name;
264
+ const profilePath = join(root, agentId, PROFILE_FILE);
265
+ if (!existsSync(profilePath)) {
266
+ // A directory under agents/ with no manifest is not a (loadable) sil
267
+ // expert — report it degraded so the user sees the residue (e.g. a
268
+ // remove that cleared the manifest but left a stray file).
269
+ unreadable.push({ agentId, error: "no profile.json manifest" });
270
+ continue;
271
+ }
272
+ try {
273
+ const manifest = readManifestFile(profilePath);
274
+ experts.push({
275
+ agentId: manifest.agentId,
276
+ name: manifest.name,
277
+ hasPlaybook: manifest.playbookPath !== undefined,
278
+ createdAt: manifest.createdAt,
279
+ });
280
+ }
281
+ catch (err) {
282
+ unreadable.push({ agentId, error: errCause(err) });
283
+ }
284
+ }
285
+ // Most-recently-created first (Product Flow 1). createdAt is ISO 8601, so a
286
+ // lexical compare is also chronological; fall back to it when Date.parse is
287
+ // NaN (a corrupt-but-parseable date) so the sort is total and stable-ish.
288
+ experts.sort((a, b) => createdAtDesc(a.createdAt, b.createdAt));
289
+ return { ok: true, experts, unreadable };
290
+ }
291
+ /** Compare two ISO 8601 createdAt strings, most-recent first. */
292
+ function createdAtDesc(a, b) {
293
+ const ta = Date.parse(a);
294
+ const tb = Date.parse(b);
295
+ if (Number.isNaN(ta) || Number.isNaN(tb)) {
296
+ // Lexical fallback keeps the sort total when a timestamp is unparseable.
297
+ return a < b ? 1 : a > b ? -1 : 0;
298
+ }
299
+ return tb - ta;
300
+ }
301
+ /**
302
+ * Read one expert's full detail — the manifest PLUS the persona/playbook bodies
303
+ * from the files it points at — so the skill can render a complete view.
304
+ *
305
+ * Re-runs the writer's `agentId` gate BEFORE any `join`/read (a traversal-shaped
306
+ * id → `invalid_request`, reading nothing). An unknown id, an absent/unreadable
307
+ * manifest, or an absent persona body → `not_found` (a degraded expert is, from
308
+ * the user's view, not viewable). Never throws across the boundary; reads only.
309
+ */
310
+ export function readAgentProfile(agentId) {
311
+ const bad = rejectBadAgentId(agentId);
312
+ if (bad)
313
+ return bad;
314
+ const dir = getAgentArtefactDir(agentId);
315
+ const profilePath = join(dir, PROFILE_FILE);
316
+ if (!existsSync(profilePath)) {
317
+ return notFoundRead(agentId);
318
+ }
319
+ let manifest;
320
+ try {
321
+ manifest = readManifestFile(profilePath);
322
+ }
323
+ catch {
324
+ // A corrupt/half-written manifest is, to the viewer, an expert that cannot
325
+ // be loaded — surface not_found (the skill lists the healthy ones), never a
326
+ // raw parse error across the boundary.
327
+ return notFoundRead(agentId);
328
+ }
329
+ let persona;
330
+ try {
331
+ persona = readFileSync(manifest.personaPath, "utf8");
332
+ }
333
+ catch {
334
+ // Manifest present but its persona body is gone (a partial removal, or a
335
+ // hand-deleted file) — the expert is not viewable.
336
+ return notFoundRead(agentId);
337
+ }
338
+ let playbook;
339
+ if (manifest.playbookPath !== undefined) {
340
+ try {
341
+ playbook = readFileSync(manifest.playbookPath, "utf8");
342
+ }
343
+ catch {
344
+ // The playbook is optional detail; its absence does not make the expert
345
+ // unviewable. Render the rest without it.
346
+ playbook = undefined;
347
+ }
348
+ }
349
+ return {
350
+ ok: true,
351
+ agentId: manifest.agentId,
352
+ name: manifest.name,
353
+ persona,
354
+ ...(playbook !== undefined ? { playbook } : {}),
355
+ profilePath,
356
+ createdAt: manifest.createdAt,
357
+ };
358
+ }
359
+ function notFoundRead(agentId) {
360
+ return {
361
+ ok: false,
362
+ kind: "not_found",
363
+ agentId,
364
+ message: 'No sil expert "' + agentId + '" — list your experts to see which exist.',
365
+ };
366
+ }
367
+ /**
368
+ * Remove one expert's behaviour-artefact directory — the sil-side half of a
369
+ * clean removal (the host-wiring half is the skill's `openclaw` CLI step; the
370
+ * plugin cannot write `~/.openclaw`).
371
+ *
372
+ * Fail-closed and scoped to exactly the named expert:
373
+ * - re-runs the writer's `agentId` gate ITSELF (never trusts the caller) — a
374
+ * bad/`main`/traversal-shaped id → `invalid_request`, deletes NOTHING;
375
+ * - asserts the resolved target is strictly UNDER `getDataDir()/agents/` and
376
+ * is NOT the `agents/` parent, so a delete can never escape the subtree or
377
+ * wipe sibling experts;
378
+ * - `rmSync(dir, { recursive, force })` the single leaf dir.
379
+ *
380
+ * Absent target → `not_found` (idempotent — a re-run after a partial host-CLI
381
+ * failure is safe). A genuine `rmSync` failure (e.g. EACCES) →
382
+ * `persistence_failed` with `<dir>: <cause>`. Never throws across the boundary.
383
+ */
384
+ export function removeAgentArtefacts(agentId) {
385
+ const bad = rejectBadAgentId(agentId);
386
+ if (bad)
387
+ return bad;
388
+ const dir = getAgentArtefactDir(agentId);
389
+ // Defence in depth beyond the id gate: assert the resolved path is strictly a
390
+ // child of the agents root and never the root itself. A `rmSync` of the
391
+ // parent would wipe every sibling expert — refuse it even if some future
392
+ // change to the gate let a separator-bearing id through.
393
+ const root = getAgentsRoot();
394
+ if (dirname(dir) !== root || dir === root) {
395
+ return invalidAgentId("agentId resolves outside the agents subtree — refusing to delete: " +
396
+ JSON.stringify(agentId));
397
+ }
398
+ if (!existsSync(dir)) {
399
+ return {
400
+ ok: false,
401
+ kind: "not_found",
402
+ agentId,
403
+ message: 'No sil expert "' + agentId + '" to remove (already gone) — list your'
404
+ + " experts to see which exist. A re-run is safe (idempotent).",
405
+ };
406
+ }
407
+ try {
408
+ rmSync(dir, { recursive: true, force: true });
409
+ }
410
+ catch (err) {
411
+ return {
412
+ ok: false,
413
+ kind: "persistence_failed",
414
+ error: dir + ": " + errCause(err),
415
+ message: "The expert's behaviour artefacts could NOT be removed from the sil data"
416
+ + " directory. Fix the data directory (it must be writable — check"
417
+ + " permissions), then remove the expert again.",
418
+ recovery: "fix_data_dir",
419
+ };
420
+ }
421
+ return { ok: true, agentId };
422
+ }
423
+ /** Extract a human-readable cause from an unknown thrown value (never PII). */
424
+ function errCause(err) {
425
+ return err instanceof Error ? err.message : String(err);
426
+ }