sil-openclaw 0.4.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +33 -45
  3. package/dist/gateway/search-results.js +11 -7
  4. package/dist/index.js +24 -24
  5. package/dist/lib/allowlist-script.js +13 -0
  6. package/dist/lib/artifacts.js +30 -0
  7. package/dist/lib/credentials.js +2 -3
  8. package/dist/lib/host-wiring.js +44 -15
  9. package/dist/lib/pkce.js +3 -3
  10. package/dist/lib/search-results-log.js +23 -0
  11. package/dist/lib/search-results-store.js +4 -4
  12. package/dist/lib/shopping-call.js +143 -0
  13. package/dist/lib/sil-client.js +185 -1046
  14. package/dist/lib/tool-result.js +10 -3
  15. package/dist/tools/catalog.js +311 -1197
  16. package/dist/tools/doctor.js +25 -63
  17. package/dist/tools/identity.js +110 -245
  18. package/openclaw.plugin.json +14 -11
  19. package/package.json +7 -6
  20. package/schema/PROVENANCE.md +15 -0
  21. package/schema/shopping-brief-create-request.schema.json +98 -0
  22. package/schema/shopping-brief-create-response.schema.json +24 -0
  23. package/schema/shopping-brief-edit-request.schema.json +125 -0
  24. package/schema/shopping-brief-edit-response.schema.json +24 -0
  25. package/schema/shopping-brief-read-request.schema.json +15 -0
  26. package/schema/shopping-brief-read-response.schema.json +235 -0
  27. package/schema/shopping-domain-create-request.schema.json +160 -0
  28. package/schema/shopping-domain-create-response.schema.json +60 -0
  29. package/schema/shopping-domain-get-request.schema.json +18 -0
  30. package/schema/shopping-domain-get-response.schema.json +307 -0
  31. package/schema/shopping-domain-search-request.schema.json +18 -0
  32. package/schema/shopping-domain-search-response.schema.json +92 -0
  33. package/schema/shopping-offers-request.schema.json +31 -0
  34. package/schema/shopping-offers-response.schema.json +172 -0
  35. package/schema/shopping-product-get-request.schema.json +24 -0
  36. package/schema/shopping-product-get-response.schema.json +121 -0
  37. package/schema/shopping-profile-edit-request.schema.json +97 -0
  38. package/schema/shopping-profile-edit-response.schema.json +17 -0
  39. package/schema/shopping-search-request.schema.json +106 -0
  40. package/schema/shopping-search-response.schema.json +182 -0
  41. package/schema/shopping-seller-get-request.schema.json +24 -0
  42. package/schema/shopping-seller-get-response.schema.json +342 -0
  43. package/scripts/allowlist-openclaw.mjs +4 -5
  44. package/sil-shopping/SKILL.md +196 -97
  45. package/sil-shopping/references/mint.md +190 -0
  46. package/dist/lib/bind-channel.js +0 -10
  47. package/dist/lib/creation-entrypoint.js +0 -111
  48. package/dist/lib/derive-agent-id.js +0 -36
  49. package/dist/lib/profile-store.js +0 -568
  50. package/dist/tools/profile.js +0 -300
  51. package/scripts/create-shopper.mjs +0 -677
  52. package/sil-shopping/examples/multi_domain_shopper_walkthrough.md +0 -65
  53. package/sil-shopping/references/agent_creation_engine.md +0 -223
  54. package/sil-shopping/references/fill_and_feedback.md +0 -102
  55. package/sil-shopping/references/method_and_prds.md +0 -143
  56. package/sil-shopping/references/setup_onboarding.md +0 -64
  57. package/sil-shopping/references/shop_loop.md +0 -118
@@ -1,677 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Operator bin: create the user's ONE sil-wired shopper in a single atomic run.
4
- *
5
- * This is Change 3 of the onboarding-ux plan — it collapses the nine-step,
6
- * agent-driven host-CLI choreography (`agent_creation_engine.md`) into ONE shipped
7
- * package `bin`, a sibling of `scripts/allowlist-openclaw.mjs`. Like that bin it is
8
- * a standalone operator script — NOT the plugin process — that drives the host
9
- * `openclaw` CLI via `execFileSync`.
10
- *
11
- * It runs POST-endorsement: the interview (`agent_creation_engine.md` Part 1) owns the
12
- * consent gate; this bin executes an already-assembled, already-endorsed spec
13
- * non-interactively. It never prompts, never re-runs the interview.
14
- *
15
- * Input — ONE JSON object `{ name, workspace, persona, userSpec, channel? }`,
16
- * read from stdin (primary) or `--spec <path>` (fallback). Passing multiline
17
- * persona/userSpec as JSON dodges shell-arg escaping. Unparseable/blank input →
18
- * `invalid_request`, nothing attempted. There is NO `agentId` input — it is derived
19
- * from `name` (`deriveAgentId`), so the user never invents an id; a stray `agentId`
20
- * key is ignored. `channel` is OPTIONAL — the current-channel override for the
21
- * step-10 bind; absent/blank is fail-open, never invalid_request.
22
- *
23
- * Choreography (validate-first, then atomic, fail-closed):
24
- * 1. validate the spec + derive the id — bad/blank field ⇒ invalid_request, nothing
25
- * attempted; then agentId = deriveAgentId(name) (lower-kebab; empty/`main` slug ⇒
26
- * the silent `sil-shopper` fallback — the postcondition guarantees a conforming id)
27
- * 2. resolve the host config — none ⇒ persistence_failed (precondition), nothing written
28
- * 3. singleton + agentId pre-flight — a shopper OR the agentId already exists ⇒ collision;
29
- * an INCONCLUSIVE read (degraded store / CLI error) fails closed — never fabricates
30
- * a "no shopper" verdict, never proceeds to `agents add`
31
- * 4. snapshot openclaw.json — the whole-file teardown anchor, taken BEFORE step 5
32
- * 5. openclaw agents add — create the real agents.list entry + workspace bootstrap
33
- * 6. write <workspace>/SOUL.md — the persona (atomic tmp→rename); never a sil artefact
34
- * 7. materializeProfile — REUSED; SETUP-ONLY { name, userSpec } ⇒ shared
35
- * user_spec.md (its frontmatter carries the name);
36
- * NO manifest, no domain minted at create
37
- * 8. attach the sil skill + enable the sil plugin (config set)
38
- * 9. sil-openclaw-allowlist — REUSED whole; additive/idempotent/atomic three-surface
39
- * trust merge (plugins.allow + tools.alsoAllow + plugins.entries.sil)
40
- * 10. bind the current channel — FAIL-OPEN convenience, NOT fail-closed: resolve the channel
41
- * (spec.channel > OPENCLAW_MCP_MESSAGE_CHANNEL), bind + VERIFY
42
- * from the JSON verdict (never the exit code), keep a verified
43
- * route, revert an unverifiable one; an undetermined/unverifiable
44
- * channel degrades to a manual-bind hint — it NEVER fails creation
45
- * 11. openclaw config validate — success keys off `.valid`, never an `ok` field
46
- * 12. one { status, … } JSON result; exit 0 ONLY on `created`.
47
- *
48
- * Teardown on ANY failure after step 5 = whole-file snapshot-restore of
49
- * openclaw.json (reverses the agents.list entry + skill + plugin + trust in ONE
50
- * atomic op, superseding the allowlist bin's inner `.bak`), plus removal of the
51
- * workspace dir (only if WE created it) and the singleton shopper dir (only if it
52
- * did not pre-exist — the singleton pre-flight guarantees it was ours). This
53
- * returns the host to its EXACT pre-run state, so a co-installed `klodi` that was
54
- * trusted pre-run stays trusted. A teardown that CANNOT fully revert is a distinct,
55
- * LOUDER outcome (`teardown_failed`) that names the residue — never a green-washed
56
- * `persistence_failed`.
57
- *
58
- * The step-10 channel bind is the ONE step that never routes into teardown: it is
59
- * fail-open by design (a convenience, not a precondition), so it self-reverts a bad
60
- * bind in place and continues. Because a VERIFIED route lives in openclaw.json, the
61
- * step-4 snapshot restore reverses it FOR FREE if any earlier-or-later step then
62
- * fails — no `agents unbind`, no bind-specific teardown code.
63
- *
64
- * Outcome taxonomy (four terminal, + the louder teardown_failed), in sil's
65
- * `snake_case_marker` NDJSON style (no api.logger outside the gateway). No PII, no
66
- * secrets — the persona/userSpec text is NEVER logged:
67
- * - created (info, stdout) — carries name + agentId + workspace [+ warnings]
68
- * - invalid_request (error, stderr) — bad/blank spec; nothing attempted; names the field
69
- * - collision (error, stderr) — singleton / agentId clash; nothing written
70
- * - persistence_failed (error, stderr) — a step failed after writes began; teardown fully
71
- * reverted; nothing partial; names path + cause
72
- * - teardown_failed (error, stderr) — teardown could NOT fully revert; names the residue
73
- *
74
- * All real write/merge logic lives in the typed libs (`materializeProfile` from
75
- * `dist/lib/profile-store.js`, the `sil-openclaw-allowlist` bin). This shell is
76
- * thin choreography + teardown only — it re-implements none of it.
77
- */
78
-
79
- import { execFileSync } from "node:child_process";
80
- import { existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
81
- import { homedir } from "node:os";
82
- import { basename, dirname, join, resolve } from "node:path";
83
- import { randomBytes } from "node:crypto";
84
- import { fileURLToPath } from "node:url";
85
-
86
- import {
87
- materializeProfile,
88
- readShopperIdentity,
89
- getShopperArtefactDir,
90
- } from "../dist/lib/profile-store.js";
91
- import { resolveBindChannel } from "../dist/lib/bind-channel.js";
92
- import { deriveAgentId } from "../dist/lib/derive-agent-id.js";
93
-
94
- const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
95
- /** The sibling operator bin that performs the additive, self-validating trust merge. */
96
- const ALLOWLIST_BIN = resolve(ROOT, "scripts", "allowlist-openclaw.mjs");
97
- /** The shipped plugin manifest — the single source of truth for sil's facts (id,
98
- * skill name), read the same way `scripts/allowlist-openclaw.mjs` reads it. */
99
- const MANIFEST_PATH = resolve(ROOT, "openclaw.plugin.json");
100
-
101
- /** The sil creed appended to every shopper's SOUL.md after its persona — a soul, not a
102
- * rulebook. It carries the mantra (explore first), the loop in three lines, and the one
103
- * distinction that matters (the catalog is where you buy, the web is where you learn),
104
- * so the shopper's character carries the method. The mechanics live in the attached
105
- * sil-shopping skill; this is the philosophy the model weights as identity. */
106
- const SOUL_SIL_RULES =
107
- "\n## The sil way\n\n"
108
- + "You are a spec-driven shopper, and your mantra is **explore first**: before you buy"
109
- + " in a niche, you learn how it is really bought.\n\n"
110
- + "The loop, in three lines:\n"
111
- + "1. **Learn the domain** — the first time you shop a niche, explore it on the web,"
112
- + " research how it is bought, and remember what you find (`sil_learn`).\n"
113
- + "2. **Know the person** — reuse the sizes, tastes, and limits you already hold; ask"
114
- + " only what you genuinely cannot infer.\n"
115
- + "3. **Find the thing** — search the sil catalog, weigh what comes back against what"
116
- + " you learned, and say why your pick fits.\n\n"
117
- + "The **sil catalog is where you buy; the open web is where you learn.** Research a"
118
- + " niche freely and often, but the products you recommend always come from the"
119
- + " catalog. Keep what you learn so tomorrow's shop starts smarter than today's.\n";
120
-
121
- const CREATED_EVENT = "sil_shopper_created";
122
- const FAILED_EVENT = "sil_shopper_create_failed";
123
-
124
- /** Emit one structured NDJSON line in sil's marker style: `{event, level, ...}`. */
125
- function logMarker(stream, level, event, fields) {
126
- stream.write(JSON.stringify({ event, level, ...fields }) + "\n");
127
- }
128
-
129
- /** Terminal success emit — one `created` object on stdout, exit 0. */
130
- function emitCreated(fields) {
131
- logMarker(process.stdout, "info", CREATED_EVENT, { status: "created", ...fields });
132
- process.exit(0);
133
- }
134
-
135
- /** Terminal failure emit — one object on stderr carrying the taxonomy `status`,
136
- * exit 1. Never carries persona/userSpec text. */
137
- function emitFailure(status, fields) {
138
- logMarker(process.stderr, "error", FAILED_EVENT, { status, ...fields });
139
- process.exit(1);
140
- }
141
-
142
- /** True when `s` is a present, non-blank string. */
143
- function nonBlank(s) {
144
- return typeof s === "string" && s.trim().length > 0;
145
- }
146
-
147
- /** Human-readable cause from an unknown thrown value (never PII). */
148
- function errCause(err) {
149
- return err instanceof Error ? err.message : String(err);
150
- }
151
-
152
- /** Atomic single-file write: tmp sibling → write → rename over target, preserving
153
- * the given mode. A reader sees the old file or the new one, never a half-written
154
- * one (mirrors `allowlist-openclaw.mjs` / `profile-store.ts`). */
155
- function atomicWrite(path, contents, mode) {
156
- const tmp = path + "." + randomBytes(6).toString("hex") + ".tmp";
157
- writeFileSync(tmp, contents, mode !== undefined ? { mode } : undefined);
158
- renameSync(tmp, path);
159
- }
160
-
161
- /** Resolve the host config path by precedence (first existing wins) — identical to
162
- * `allowlist-openclaw.mjs` so every subprocess agrees on ONE config file. Returns
163
- * the resolved path, or null if none exists (caller fails closed). */
164
- function resolveConfigPath() {
165
- const candidates = [];
166
- if (process.env["OPENCLAW_CONFIG_PATH"]) {
167
- candidates.push(process.env["OPENCLAW_CONFIG_PATH"]);
168
- }
169
- if (process.env["OPENCLAW_STATE_DIR"]) {
170
- candidates.push(join(process.env["OPENCLAW_STATE_DIR"], "openclaw.json"));
171
- }
172
- candidates.push(join(homedir(), ".openclaw", "openclaw.json"));
173
- for (const candidate of candidates) {
174
- if (existsSync(candidate)) return candidate;
175
- }
176
- return null;
177
- }
178
-
179
- /** Read the raw spec text — `--spec <path>` if present, else stdin (fd 0). Returns
180
- * `{ raw }` or `{ error }` (a structured cause, never the spec contents). */
181
- function readSpecRaw() {
182
- const argv = process.argv.slice(2);
183
- const specIdx = argv.indexOf("--spec");
184
- if (specIdx >= 0) {
185
- const path = argv[specIdx + 1];
186
- if (!path) return { error: "--spec requires a file path argument" };
187
- try {
188
- return { raw: readFileSync(path, "utf8") };
189
- } catch (err) {
190
- return { error: "could not read --spec file: " + errCause(err) };
191
- }
192
- }
193
- try {
194
- return { raw: readFileSync(0, "utf8") };
195
- } catch (err) {
196
- return { error: "could not read the spec from stdin: " + errCause(err) };
197
- }
198
- }
199
-
200
- /** Validate the endorsed spec — deterministic field order (name → workspace →
201
- * persona → userSpec). Returns `{ field, message }` on the FIRST bad field, or null
202
- * when the whole spec is good. Writes/attempts nothing. `agentId` is NOT a spec field
203
- * — it is derived from `name` (`deriveAgentId`) after validate; a stray `agentId` key
204
- * is ignored. `channel` is deliberately NOT validated: it is an optional fail-open
205
- * convenience, so an absent/blank/malformed channel is never invalid_request — it
206
- * folds to `null` in `resolveBindChannel` and degrades to a manual-bind hint at step 10. */
207
- function validateSpec(spec) {
208
- if (typeof spec !== "object" || spec === null || Array.isArray(spec)) {
209
- return {
210
- field: "spec",
211
- message: "spec must be a JSON object with { name, workspace, persona, userSpec, channel? }.",
212
- };
213
- }
214
- if (!nonBlank(spec.name)) {
215
- return { field: "name", message: "name is required and must be non-empty." };
216
- }
217
- if (!nonBlank(spec.workspace)) {
218
- return { field: "workspace", message: "workspace is required and must be non-empty." };
219
- }
220
- if (!nonBlank(spec.persona)) {
221
- return { field: "persona", message: "persona is required and must be non-empty." };
222
- }
223
- if (!nonBlank(spec.userSpec)) {
224
- return { field: "userSpec", message: "userSpec is required and must be non-empty." };
225
- }
226
- return null;
227
- }
228
-
229
- /** Run `openclaw <args>` pinned to the resolved config. Returns
230
- * `{ ok, stdout, stderr, code }` — never throws across the boundary. */
231
- function runOpenclaw(args, configPath) {
232
- try {
233
- const stdout = execFileSync("openclaw", args, {
234
- env: { ...process.env, OPENCLAW_CONFIG_PATH: configPath },
235
- encoding: "utf8",
236
- stdio: ["ignore", "pipe", "pipe"],
237
- });
238
- return { ok: true, stdout, stderr: "", code: 0 };
239
- } catch (err) {
240
- return {
241
- ok: false,
242
- stdout: typeof err?.stdout === "string" ? err.stdout : "",
243
- stderr: typeof err?.stderr === "string" ? err.stderr : "",
244
- code: err?.code,
245
- };
246
- }
247
- }
248
-
249
- /** Read + parse the host config JSON, or null on any read/parse failure. */
250
- function readConfig(configPath) {
251
- try {
252
- return JSON.parse(readFileSync(configPath, "utf8"));
253
- } catch {
254
- return null;
255
- }
256
- }
257
-
258
- /** Resolve the sil SKILL's published name to attach at `agents.list[i].skills`,
259
- * single-sourced from the shipped manifest (mirrors `allowlist-openclaw.mjs`'s
260
- * `readSilFacts`). A skill attaches by its PUBLISHED name = the skill-dir basename
261
- * = `basename(openclaw.plugin.json#skills[0])` (`sil-shopping`) — NOT the plugin id
262
- * (`sil`), which is the tools/trust key. The per-agent attach is the ONLY skill
263
- * surface (no global skill allow-list), so the plugin id here loads no skill at
264
- * all. Fail-closed: an unreadable manifest or a blank/absent `skills[0]` returns
265
- * `{ error }` so the create errors rather than attaching `[""]`. */
266
- function readSkillAttachName() {
267
- let manifest;
268
- try {
269
- manifest = JSON.parse(readFileSync(MANIFEST_PATH, "utf8"));
270
- } catch (err) {
271
- return { error: "the shipped manifest " + MANIFEST_PATH + " is not readable/parseable JSON: " + errCause(err) };
272
- }
273
- const ref = Array.isArray(manifest.skills) ? manifest.skills[0] : undefined;
274
- if (!nonBlank(ref)) {
275
- return { error: "the shipped manifest " + MANIFEST_PATH + " declares no skills[0] — cannot resolve the sil skill name to attach" };
276
- }
277
- const name = basename(ref);
278
- if (!nonBlank(name)) {
279
- return { error: "the shipped manifest skills[0] " + JSON.stringify(ref) + " has no usable basename" };
280
- }
281
- return { name };
282
- }
283
-
284
- /** The agentId path-segment ids already registered in the host config's
285
- * `agents.list` — the authoritative, shim-independent clash source. */
286
- function existingAgentIds(config) {
287
- const list = Array.isArray(config?.agents?.list) ? config.agents.list : [];
288
- return list.map((a) => a?.id).filter((id) => typeof id === "string");
289
- }
290
-
291
- /** The index of `agentId` in `agents.list`, or -1 (used to target the skill attach). */
292
- function agentIndex(config, agentId) {
293
- const list = Array.isArray(config?.agents?.list) ? config.agents.list : [];
294
- return list.findIndex((a) => a?.id === agentId);
295
- }
296
-
297
- /** True iff `openclaw config validate --json` reported `{valid:true}`. The host
298
- * writes its verdict to stdout even on a non-zero exit, so read stdout, never the
299
- * exit code (fail closed if it is not JSON). */
300
- function configValidates(stdout) {
301
- try {
302
- const verdict = JSON.parse(stdout);
303
- return verdict !== null && verdict.valid === true;
304
- } catch {
305
- return false;
306
- }
307
- }
308
-
309
- /** True iff `openclaw agents bind --json` reported the channel APPLIED — landed in
310
- * `added` or `updated`, with an EMPTY `conflicts`. `agents bind` exits 0 even on a
311
- * conflict or an empty `--bind`, so the JSON verdict — never the exit code — is the
312
- * source of truth (the same discipline the bin applies to `config validate.valid`). */
313
- function bindApplied(stdout) {
314
- let v;
315
- try {
316
- v = JSON.parse(stdout);
317
- } catch {
318
- return false;
319
- }
320
- if (v === null || typeof v !== "object") return false;
321
- const added = Array.isArray(v.added) ? v.added : [];
322
- const updated = Array.isArray(v.updated) ? v.updated : [];
323
- const conflicts = Array.isArray(v.conflicts) ? v.conflicts : [];
324
- return (added.length > 0 || updated.length > 0) && conflicts.length === 0;
325
- }
326
-
327
- /** True iff the `openclaw agents bindings --json` read-back (an ARRAY of
328
- * `{agentId, match:{channel}}`) actually shows the route `<channel> → <agentId>`.
329
- * This is the honesty rail: a bind is only "verified" once the read-back proves the
330
- * write stuck — issuing the write is not the same as the next message reaching it. */
331
- function bindingPresent(stdout, agentId, channel) {
332
- let v;
333
- try {
334
- v = JSON.parse(stdout);
335
- } catch {
336
- return false;
337
- }
338
- if (!Array.isArray(v)) return false;
339
- return v.some((b) => b?.agentId === agentId && b?.match?.channel === channel);
340
- }
341
-
342
- /** The fail-open manual-bind hint appended to `created` warnings when the channel
343
- * could not be auto-routed (undetermined) or the bind could not be verified. It
344
- * states the shopper WAS created, names the one-command manual bind, and never
345
- * implies a broken create — a convenience that didn't fire, not an error. */
346
- function manualBindHint(agentId, channel) {
347
- const target = channel ? `the "${channel}" channel` : "the current channel";
348
- return (
349
- `the shopper "${agentId}" was created but ${target} was not auto-routed to it. `
350
- + `To route it manually, run: openclaw agents bind --agent ${agentId} --bind <channel> `
351
- + `(or switch in-chat with /agent ${agentId}). The shopper is fully created and ready.`
352
- );
353
- }
354
-
355
- /**
356
- * Whole-file snapshot-restore teardown. Reverses everything this run created and
357
- * returns the residue it could NOT revert (empty ⇒ clean, host at exact pre-run
358
- * state). Each step is best-effort/idempotent so one failure never aborts the rest.
359
- */
360
- function teardown({ configPath, snapshot, mode, bakPreexisted, workspace, workspacePreexisted, shopperDirPreexisted }) {
361
- const residue = [];
362
-
363
- // 1. Restore openclaw.json to its exact pre-run bytes — reverses the agents.list
364
- // entry, the skill attach, the plugin enable, AND the trust merge in one op.
365
- if (snapshot !== null && configPath) {
366
- try {
367
- atomicWrite(configPath, snapshot, mode);
368
- } catch (err) {
369
- residue.push({ path: configPath, cause: "could not restore openclaw.json: " + errCause(err) });
370
- }
371
- // Remove the allowlist bin's inner `.bak` if it did not pre-exist this run.
372
- const bakPath = configPath + ".bak";
373
- if (!bakPreexisted && existsSync(bakPath)) {
374
- try {
375
- rmSync(bakPath, { force: true });
376
- } catch {
377
- // A lingering .bak is cosmetic — not host state; do not escalate to residue.
378
- }
379
- }
380
- }
381
-
382
- // 2. Remove the workspace dir ONLY if WE created it (never a pre-existing one).
383
- if (workspace && !workspacePreexisted) {
384
- try {
385
- rmSync(workspace, { recursive: true, force: true });
386
- } catch (err) {
387
- residue.push({ path: workspace, cause: "could not remove the workspace dir: " + errCause(err) });
388
- }
389
- }
390
-
391
- // 3. Remove the singleton shopper dir ONLY if it did not pre-exist (the singleton
392
- // pre-flight guarantees it was ours this run).
393
- // KNOWN GAP (narrow): this keys on WHOLE-DIR pre-existence, not on the leaf we
394
- // wrote. If `shopper/` pre-existed but held no readable user_spec.md, the
395
- // singleton read passes ("no shopper") yet `shopperDirPreexisted` is true, so a
396
- // post-materialize failure leaves THIS run's user_spec.md un-removed and does NOT
397
- // surface as residue → `teardown_failed`. Extremely narrow (normal operation
398
- // never leaves an empty `shopper/`). To close it, key this removal on "we wrote
399
- // user_spec.md this run".
400
- if (!shopperDirPreexisted) {
401
- const shopperDir = getShopperArtefactDir();
402
- try {
403
- rmSync(shopperDir, { recursive: true, force: true });
404
- } catch (err) {
405
- residue.push({ path: shopperDir, cause: "could not remove the shopper dir: " + errCause(err) });
406
- }
407
- }
408
-
409
- return residue;
410
- }
411
-
412
- function main() {
413
- // --- 1. Read + validate the endorsed spec (validate-first, nothing attempted) ---
414
- const specRaw = readSpecRaw();
415
- if (specRaw.error) {
416
- emitFailure("invalid_request", { field: "spec", cause: specRaw.error });
417
- }
418
- let spec;
419
- try {
420
- spec = JSON.parse(specRaw.raw);
421
- } catch (err) {
422
- emitFailure("invalid_request", {
423
- field: "spec",
424
- cause: "the spec is not valid JSON: " + errCause(err),
425
- });
426
- }
427
- const bad = validateSpec(spec);
428
- if (bad) {
429
- emitFailure("invalid_request", { field: bad.field, cause: bad.message });
430
- }
431
- const { name, workspace, persona, userSpec, channel } = spec;
432
- // Derive the host id from the ONE friendly name — the user never invents an id.
433
- // The lib's postcondition guarantees a conforming lower-kebab id, never `main`
434
- // (empty/`main` slug ⇒ silent `sil-shopper`), so no runtime re-validation here.
435
- const agentId = deriveAgentId(name);
436
-
437
- // --- 2. Resolve the host config (precondition — nothing written yet) ---
438
- const configPath = resolveConfigPath();
439
- if (configPath === null) {
440
- emitFailure("persistence_failed", {
441
- path: null,
442
- cause:
443
- "no OpenClaw config found at OPENCLAW_CONFIG_PATH, $OPENCLAW_STATE_DIR/openclaw.json, or "
444
- + "~/.openclaw/openclaw.json — start the OpenClaw gateway once so it writes its base config, then re-run",
445
- });
446
- }
447
- const preConfig = readConfig(configPath);
448
- if (preConfig === null) {
449
- emitFailure("persistence_failed", {
450
- path: configPath,
451
- cause: "the host openclaw.json is not readable/parseable JSON — fix it, then re-run",
452
- });
453
- }
454
-
455
- // --- 2b. Resolve the sil skill's published name to attach (shipped manifest is the
456
- // single source of truth) — a packaging defect fails closed BEFORE any host
457
- // write, so nothing is attempted. Reused at step 8. ---
458
- const skill = readSkillAttachName();
459
- if (skill.error) {
460
- emitFailure("persistence_failed", { path: MANIFEST_PATH, cause: skill.error });
461
- }
462
- const skillAttachName = skill.name;
463
-
464
- // --- 3. Singleton + agentId pre-flight (nothing written; inconclusive → fail closed) ---
465
- // The sil artefact store is the source of truth for "a shopper exists": user_spec.md
466
- // present + its frontmatter `name` reads (frontmatter-as-truth, no manifest).
467
- const overview = readShopperIdentity();
468
- if (Array.isArray(overview.unreadable) && overview.unreadable.length > 0) {
469
- // A degraded store is INCONCLUSIVE — never fabricate a "no shopper" verdict.
470
- emitFailure("persistence_failed", {
471
- path: getShopperArtefactDir(),
472
- cause: "the sil shopper store is degraded (" + overview.unreadable.map((u) => u.error).join("; ")
473
- + ") — cannot confirm the singleton; failing closed",
474
- });
475
- }
476
- if (nonBlank(overview.name)) {
477
- emitFailure("collision", {
478
- cause:
479
- "a shopper already exists — a user has exactly ONE shopper. Shop a new niche (it lazily mints a"
480
- + " domain on the spot) or refine the existing shopper; never mint a second shopper.",
481
- });
482
- }
483
- // Run the host-native agent list (ordered before the add) — a CLI error is
484
- // inconclusive and fails closed; the config file is the authoritative clash source.
485
- const listRes = runOpenclaw(["agents", "list", "--json"], configPath);
486
- if (!listRes.ok) {
487
- emitFailure("persistence_failed", {
488
- path: configPath,
489
- cause: "could not list host agents (`openclaw agents list --json` failed) — failing closed",
490
- });
491
- }
492
- if (existingAgentIds(preConfig).includes(agentId)) {
493
- emitFailure("collision", {
494
- cause: "the agentId " + JSON.stringify(agentId)
495
- + " already exists in the host agents.list — refusing to overwrite an existing agent's persona or wiring.",
496
- });
497
- }
498
-
499
- // --- 4. Snapshot openclaw.json (the teardown anchor) BEFORE the first mutation ---
500
- const snapshot = readFileSync(configPath, "utf8");
501
- const mode = statSync(configPath).mode & 0o777;
502
- const bakPreexisted = existsSync(configPath + ".bak");
503
- const workspacePreexisted = existsSync(workspace);
504
- const shopperDirPreexisted = existsSync(getShopperArtefactDir());
505
- const teardownCtx = {
506
- configPath,
507
- snapshot,
508
- mode,
509
- bakPreexisted,
510
- workspace,
511
- workspacePreexisted,
512
- shopperDirPreexisted,
513
- };
514
-
515
- /** Unwind everything and emit the honest terminal outcome: persistence_failed
516
- * when teardown fully reverted, the LOUDER teardown_failed when it could not. */
517
- const failAndTeardown = (path, cause) => {
518
- const residue = teardown(teardownCtx);
519
- if (residue.length > 0) {
520
- emitFailure("teardown_failed", {
521
- path,
522
- cause,
523
- residue,
524
- note: "teardown could NOT fully revert — the host was NOT returned to its pre-run state; the residue above remains",
525
- });
526
- }
527
- emitFailure("persistence_failed", { path, cause });
528
- };
529
-
530
- // --- 5. Create the host agent shell (workspace bootstrap: SOUL.md, AGENTS.md, …) ---
531
- const addRes = runOpenclaw(
532
- ["agents", "add", agentId, "--workspace", workspace, "--non-interactive", "--json"],
533
- configPath,
534
- );
535
- if (!addRes.ok) {
536
- failAndTeardown(configPath, "`openclaw agents add` failed: " + (addRes.stderr || "non-zero exit"));
537
- }
538
-
539
- // --- 6. Write the persona + standing sil rules into the workspace SOUL.md ---
540
- // The endorsed persona, then SOUL_SIL_RULES — the identity-level restatement of the
541
- // shopping contract, so the shopper's tool discipline is anchored in its soul, not the
542
- // skill alone (host CLI has no SOUL.md writer, so the bin does it).
543
- const soulPath = join(workspace, "SOUL.md");
544
- try {
545
- atomicWrite(soulPath, (persona.endsWith("\n") ? persona : persona + "\n") + SOUL_SIL_RULES);
546
- } catch (err) {
547
- failAndTeardown(soulPath, "could not write SOUL.md: " + errCause(err));
548
- }
549
-
550
- // --- 7. Materialize the shared user spec — REUSED lib; NO domain at create ---
551
- const mat = materializeProfile({ name, userSpec });
552
- if (!mat.ok) {
553
- const path = mat.kind === "persistence_failed" ? (mat.error?.split(":")[0] ?? getShopperArtefactDir()) : getShopperArtefactDir();
554
- failAndTeardown(path, "sil_profile_materialize " + mat.kind + ": " + (mat.message ?? mat.error ?? "failed"));
555
- }
556
-
557
- // --- 8. Attach the sil skill + enable the sil plugin (value-mode, --strict-json) ---
558
- const postAddConfig = readConfig(configPath);
559
- const idx = agentIndex(postAddConfig, agentId);
560
- if (idx < 0) {
561
- failAndTeardown(configPath, "the created agent " + JSON.stringify(agentId) + " is not in agents.list after `openclaw agents add`");
562
- }
563
- // Attach the skill by its PUBLISHED name (`sil-shopping`), NOT the plugin id
564
- // (`sil`) — a skill and the plugin are two distinct host keys, and the per-agent
565
- // attach is the only skill surface, so the plugin id here would load no skill.
566
- const skillRes = runOpenclaw(
567
- ["config", "set", `agents.list[${idx}].skills`, JSON.stringify([skillAttachName]), "--strict-json"],
568
- configPath,
569
- );
570
- if (!skillRes.ok) {
571
- failAndTeardown(configPath, "attaching the sil skill failed: " + (skillRes.stderr || "non-zero exit"));
572
- }
573
- // No per-agent `tools.deny` is set: the shopper inherits the host's default toolset
574
- // untouched. A deny of the fs-mutators is inert here — codex brings its OWN shell
575
- // (surfaced as `bash`), which the deny cannot name and which reads the shopper's
576
- // skill files anyway, and an open shell writes files regardless of any fs-mutator
577
- // deny. The shell stays open by design (trusted single-operator posture); persistence
578
- // is steered through the sil tools by the skill, not enforced by tool policy.
579
- const enableRes = runOpenclaw(
580
- ["config", "set", "plugins.entries.sil.enabled", "true", "--strict-json"],
581
- configPath,
582
- );
583
- if (!enableRes.ok) {
584
- failAndTeardown(configPath, "enabling the sil plugin failed: " + (enableRes.stderr || "non-zero exit"));
585
- }
586
-
587
- // --- 9. Admit sil at the three allow surfaces — REUSED whole allowlist bin ---
588
- let allowlistOk = true;
589
- let allowlistCause = "";
590
- try {
591
- execFileSync(process.execPath, [ALLOWLIST_BIN], {
592
- env: { ...process.env, OPENCLAW_CONFIG_PATH: configPath },
593
- encoding: "utf8",
594
- stdio: ["ignore", "pipe", "pipe"],
595
- });
596
- } catch (err) {
597
- allowlistOk = false;
598
- allowlistCause = typeof err?.stderr === "string" && err.stderr.trim().length > 0
599
- ? err.stderr.trim()
600
- : "non-zero exit";
601
- }
602
- if (!allowlistOk) {
603
- // A failed admission leaves the sil_* tools filtered — NEVER a green `created`.
604
- failAndTeardown(configPath, "the sil-openclaw-allowlist admission helper failed: " + allowlistCause);
605
- }
606
-
607
- // --- 10. Bind the current channel to the new shopper (FAIL-OPEN convenience) ---
608
- // Route the channel the user is talking on to the new shopper by default, so their
609
- // next message reaches it with no manual bind. This step NEVER fails creation: an
610
- // undetermined channel, a conflict (already owned by another agent — no auto-steal),
611
- // or an unverifiable bind all degrade to a manual-bind hint. The bind lands in
612
- // openclaw.json `bindings[]`, so a VERIFIED route is reversed for free by the
613
- // step-4 snapshot if a later step tears the whole create down.
614
- const bindWarnings = [];
615
- // The channel the route was VERIFIED-bound to (null ⇒ nothing bound). It rides in
616
- // `created` as the honesty rail: a bound channel is named ONLY when the read-back +
617
- // config validate confirm it — issuing the write is never enough.
618
- let boundChannel = null;
619
- const channelToBind = resolveBindChannel({
620
- specChannel: channel,
621
- envChannel: process.env["OPENCLAW_MCP_MESSAGE_CHANNEL"],
622
- });
623
- if (channelToBind === null) {
624
- bindWarnings.push(manualBindHint(agentId, null));
625
- } else {
626
- // Snapshot BEFORE the bind so an unverifiable write reverts to a valid config —
627
- // never falling through to the fail-closed step-11 validate (which would tear
628
- // down a fully-created shopper over a convenience shortfall).
629
- const bindSnapshot = readFileSync(configPath, "utf8");
630
- const bindRes = runOpenclaw(["agents", "bind", "--agent", agentId, "--bind", channelToBind, "--json"], configPath);
631
- const readBack = runOpenclaw(["agents", "bindings", "--agent", agentId, "--json"], configPath);
632
- const bindValidateRes = runOpenclaw(["config", "validate", "--json"], configPath);
633
- const verified =
634
- bindRes.ok
635
- && bindApplied(bindRes.stdout)
636
- && readBack.ok
637
- && bindingPresent(readBack.stdout, agentId, channelToBind)
638
- && configValidates(bindValidateRes.stdout);
639
- if (verified) {
640
- boundChannel = channelToBind;
641
- } else {
642
- // Revert JUST the route (config back to its pre-bind valid state) and degrade
643
- // to the manual-bind hint. A failed revert is still fail-open: a well-formed
644
- // bind is validation-safe, so step 11 certifies the config either way.
645
- try {
646
- atomicWrite(configPath, bindSnapshot, mode);
647
- } catch {
648
- // best-effort — never escalate a convenience revert into a torn-down create
649
- }
650
- bindWarnings.push(manualBindHint(agentId, channelToBind));
651
- }
652
- }
653
-
654
- // --- 11. Validate with the host's OWN check — success keys off `.valid` ---
655
- // The shim/host writes its structured verdict to stdout even on a non-zero exit,
656
- // so read stdout regardless of the exit code (fail closed if it is not JSON).
657
- const validateRes = runOpenclaw(["config", "validate", "--json"], configPath);
658
- let verdict = null;
659
- try {
660
- verdict = JSON.parse(validateRes.stdout);
661
- } catch {
662
- verdict = null;
663
- }
664
- if (verdict === null || verdict.valid !== true) {
665
- const issues = verdict && verdict.issues !== undefined ? JSON.stringify(verdict.issues) : undefined;
666
- const cause = verdict && (verdict.error || verdict.message)
667
- ? String(verdict.error || verdict.message)
668
- : "`openclaw config validate` did not return valid: true";
669
- failAndTeardown(configPath, issues ? cause + " — issues: " + issues : cause);
670
- }
671
-
672
- // --- 12. Declare created — carry the identity + the bound channel (honesty rail) ---
673
- const warnings = [...bindWarnings];
674
- emitCreated({ name, agentId, workspace, boundChannel, warnings });
675
- }
676
-
677
- main();