@linxin666/dsh-liangshen 0.3.24 → 0.4.1

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 (52) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +24 -17
  3. package/README.zh.md +25 -18
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +381 -77
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +594 -428
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +27 -10
  11. package/lib/types/client/PluginSettingsCard.d.ts +4 -0
  12. package/lib/types/client/index.d.ts +32 -13
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +13 -0
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +23 -16
  17. package/lib/types/client/settings-form.d.ts +17 -17
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/index.d.ts +146 -31
  21. package/lib/types/index.test.d.ts +5 -0
  22. package/package.json +25 -20
  23. package/presets/liangshen/agent.cordis.yml +44 -10
  24. package/presets/liangshen/fact-ledger.mjs +141 -0
  25. package/presets/liangshen/guard.mjs +426 -0
  26. package/presets/liangshen/minimal-prompt.mjs +2 -2
  27. package/presets/liangshen/tool-catalog.mjs +24 -20
  28. package/presets/liangshen/working-context.mjs +10 -2
  29. package/src/announce.test.ts +248 -55
  30. package/src/client/LiangShenLever.module.css +2 -0
  31. package/src/client/LiangShenLever.tsx +37 -9
  32. package/src/client/LiangShenSettingsCard.tsx +96 -12
  33. package/src/client/PluginSettingsCard.tsx +7 -2
  34. package/src/client/index.ts +61 -23
  35. package/src/client/lever-controller.ts +76 -9
  36. package/src/client/locales.ts +30 -4
  37. package/src/client/main-session.ts +43 -0
  38. package/src/client/plugin-card-seat.ts +24 -17
  39. package/src/client/settings-form.ts +34 -31
  40. package/src/composition.test.ts +294 -0
  41. package/src/composition.ts +554 -0
  42. package/src/index.test.ts +68 -1
  43. package/src/index.ts +278 -107
  44. package/tools/benchmark-live-run.mjs +171 -32
  45. package/lib/types/schema.d.ts +0 -18
  46. package/lib/types/schema.test.d.ts +0 -1
  47. package/lib/types/sync.d.ts +0 -74
  48. package/lib/types/sync.test.d.ts +0 -1
  49. package/src/schema.test.ts +0 -64
  50. package/src/schema.ts +0 -110
  51. package/src/sync.test.ts +0 -303
  52. package/src/sync.ts +0 -324
package/lib/index.js CHANGED
@@ -1,407 +1,460 @@
1
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
2
- import { basename, dirname, isAbsolute, join, relative } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import z from "schemastery";
5
- import { homedir } from "node:os";
6
- import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
7
- //#region src/dsh-home.ts
1
+ import { fileURLToPath, pathToFileURL } from "node:url";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import { readFileSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ //#region src/composition.ts
8
6
  /**
9
- * DSH_HOME resolution shared by the plugin family's Host halves: the
10
- * environment override wins, the platform home fallback follows. Mirrors
11
- * what dsh-pet and dsh-liangshen each used to implement locally.
7
+ * The LiangShen preset's composition reader: just enough YAML to turn the
8
+ * bundled `presets/liangshen/agent.cordis.yml` — and the flat `preset.yml`
9
+ * display map beside it — into the declaration the agent-preset registry takes.
10
+ *
11
+ * Under 0.1.7 a preset is an ordinary registry declaration instead of a
12
+ * directory the harness discovers, so this plugin hands `ctx.agentPresets` the
13
+ * rows of its OWN composition. No YAML package is resolvable from this package
14
+ * and the harness's reader is not importable from here, so the subset is owned
15
+ * here; the shipped composition is the only file it must read, and tests fence
16
+ * it against that whole file. Supported: block maps and sequences, quoted and
17
+ * plain scalars, single-line flow sequences, literal and folded block scalars,
18
+ * comments, and `!!js` expressions preserved as data (`{ __jsExpr }`, the shape
19
+ * the Loader itself hands a plugin).
20
+ *
21
+ * Fail-closed: a construct outside the subset — anchors, aliases, tags other
22
+ * than `!!js`, nested flow collections, multiple documents, tabs — raises
23
+ * {@link CompositionError} rather than being guessed at, so an unreadable
24
+ * composition is refused instead of half-declared.
25
+ *
26
+ * Relative module names (`name: ./minimal-prompt.mjs`) are resolved against
27
+ * the preset directory handed to {@link readCompositionRows} and emitted as
28
+ * file URLs: the registry mounts a declaration under the DECLARING LOADER's
29
+ * base, so a relative name would otherwise be resolved outside this package.
30
+ * @module @linxin666/dsh-liangshen/composition
12
31
  */
13
- /** Expand a leading ~ (or ~user) in a path, platform-style. */
14
- function expandHome(path, home = homedir()) {
15
- const j = home.startsWith("/") ? join$1 : join;
16
- if (path === "~") return home;
17
- if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
18
- return path;
32
+ /** A construct outside the supported subset, or malformed YAML. */
33
+ var CompositionError = class extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "CompositionError";
37
+ }
38
+ };
39
+ const BLANK_OR_COMMENT_RE = /^[ \t]*(?:#.*)?$/;
40
+ const INTEGER_RE = /^[+-]?\d+$/;
41
+ const FLOAT_RE = /^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?$/;
42
+ /** The indentation width of one line (its leading spaces). */
43
+ function indentOf(line) {
44
+ const match = /^ */.exec(line);
45
+ return match === null ? 0 : match[0].length;
19
46
  }
20
47
  /**
21
- * Resolve the DSH home directory.
22
- * @param env - process environment to read DSH_HOME from.
23
- * @param home - platform home directory fallback (test seam).
24
- * @returns the absolute DSH home path.
48
+ * The indentation of one structurally significant line. A tab there is
49
+ * forbidden by YAML; block-scalar content is verbatim and never measured here.
25
50
  */
26
- function resolveDshHome(env = process.env, home = homedir()) {
27
- const isPosix = home.startsWith("/");
28
- const j = isPosix ? join$1 : join;
29
- const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
30
- const raw = env.DSH_HOME;
31
- if (raw !== void 0 && raw.trim() !== "") {
32
- const expanded = expandHome(raw.trim(), home);
33
- return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
51
+ function significantIndent(line, lineNumber) {
52
+ const leading = /^[ \t]*/.exec(line)?.[0] ?? "";
53
+ if (leading.includes(" ")) throw new CompositionError(`line ${String(lineNumber)}: tabs must not be used for indentation`);
54
+ return leading.length;
55
+ }
56
+ /** Advance past blank and comment-only lines. */
57
+ function skipInsignificant(cursor) {
58
+ while (cursor.index < cursor.lines.length && BLANK_OR_COMMENT_RE.test(cursor.lines[cursor.index] ?? "")) cursor.index += 1;
59
+ }
60
+ /** Whether a line at `indent` opens a block sequence entry. */
61
+ function isSequenceEntry(line, indent) {
62
+ if (line[indent] !== "-") return false;
63
+ return line.length === indent + 1 || line[indent + 1] === " ";
64
+ }
65
+ /** The index of the quote that closes a quoted scalar starting at index 0. */
66
+ function closingQuote(text) {
67
+ const quote = text[0];
68
+ for (let index = 1; index < text.length; index += 1) {
69
+ const char = text[index];
70
+ if (quote === "\"" && char === "\\") {
71
+ index += 1;
72
+ continue;
73
+ }
74
+ if (quote === "'" && char === "'" && text[index + 1] === "'") {
75
+ index += 1;
76
+ continue;
77
+ }
78
+ if (char === quote) return index;
34
79
  }
35
- return j(home, ".dsh");
80
+ return -1;
36
81
  }
37
- /** Resolve the DSH home directory from the live environment. */
38
- function dshHome() {
39
- return resolveDshHome();
82
+ /** Resolve one quoted scalar, or return the text unchanged when unquoted. */
83
+ function unquote(text) {
84
+ const trimmed = text.trim();
85
+ if (trimmed.startsWith("\"")) {
86
+ const end = closingQuote(trimmed);
87
+ if (end !== trimmed.length - 1) throw new CompositionError(`unterminated double-quoted scalar: ${trimmed}`);
88
+ return trimmed.slice(1, end).replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (_, escape) => {
89
+ switch (escape[0]) {
90
+ case "n": return "\n";
91
+ case "t": return " ";
92
+ case "r": return "\r";
93
+ case "0": return "\0";
94
+ case "u":
95
+ case "x": return String.fromCharCode(Number.parseInt(escape.slice(1), 16));
96
+ default: return escape;
97
+ }
98
+ });
99
+ }
100
+ if (trimmed.startsWith("'")) {
101
+ const end = closingQuote(trimmed);
102
+ if (end !== trimmed.length - 1) throw new CompositionError(`unterminated single-quoted scalar: ${trimmed}`);
103
+ return trimmed.slice(1, end).replaceAll("''", "'");
104
+ }
105
+ return trimmed;
106
+ }
107
+ /** Split one block-map line into its key and the raw text after the colon. */
108
+ function matchKeyEntry(text) {
109
+ if (text.startsWith("'") || text.startsWith("\"")) {
110
+ const end = closingQuote(text);
111
+ if (end === -1) return void 0;
112
+ const after = text.slice(end + 1).trimStart();
113
+ if (!after.startsWith(":")) return void 0;
114
+ return {
115
+ key: unquote(text.slice(0, end + 1)),
116
+ rest: after.slice(1).trim()
117
+ };
118
+ }
119
+ for (let index = 0; index < text.length; index += 1) {
120
+ const char = text[index];
121
+ if (char === "#" && index > 0 && text[index - 1] === " ") break;
122
+ if (char === ":" && (index + 1 === text.length || text[index + 1] === " ")) return {
123
+ key: text.slice(0, index),
124
+ rest: text.slice(index + 1).trim()
125
+ };
126
+ }
127
+ }
128
+ /** Resolve a plain scalar to the value YAML's JSON schema would produce. */
129
+ function plainScalar(text) {
130
+ const comment = text.indexOf(" #");
131
+ const value = (comment === -1 ? text : text.slice(0, comment)).trim();
132
+ if (value === "" || value === "~" || value === "null" || value === "Null" || value === "NULL") return null;
133
+ if (value === "true" || value === "True" || value === "TRUE") return true;
134
+ if (value === "false" || value === "False" || value === "FALSE") return false;
135
+ if (INTEGER_RE.test(value)) return Number(value);
136
+ if (FLOAT_RE.test(value)) return Number(value);
137
+ return value;
40
138
  }
41
- //#endregion
42
- //#region src/schema.ts
43
139
  /**
44
- * Structural validation for a bundled `agent.cordis.yml`.
45
- *
46
- * Deliberately dependency-free: it parses only the flat row metadata the sync
47
- * and the dsh agent-presets loader rely on. Every top-level row is written as
48
- * `- id: <id>` at column zero, with the `name`/`group`/`disabled` keys at two
49
- * spaces of indentation. Nested `config:` and `isolate:` bodies are opaque to
50
- * this validator — the dsh loader checks their semantics.
51
- *
52
- * Returns the list of problems found; an empty array means the document is
53
- * structurally valid.
140
+ * Read one single-line flow sequence (`['mcp__*']`) into its scalar items.
141
+ * Nested flow collections are outside the subset and refused.
54
142
  */
55
- /** A top-level row opener: `- id: <id>` (id may be blank for diagnostics). */
56
- const ROW_RE = /^-\s+id:\s*(.*)$/;
57
- /** Any top-level list item, for ids missing from a row opener. */
58
- const ITEM_RE = /^-\s/;
59
- /** A two-space-indented flat metadata key: ` name: <value>`. */
60
- const META_RE = /^ {2}([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/;
61
- /** The only `name` forms the dsh agent-presets loader mounts from a row. */
62
- const NAME_PREFIX_RE = /^(\.\/|@|cordis:)/;
63
- /** Strip one pair of surrounding single or double quotes from a scalar. */
64
- function unquote(value) {
65
- if (value.length >= 2) {
66
- const first = value[0];
67
- if ((first === "'" || first === "\"") && value.endsWith(first)) return value.slice(1, -1);
143
+ function flowSequence(text) {
144
+ const end = text.lastIndexOf("]");
145
+ if (end === -1) throw new CompositionError(`unterminated flow sequence: ${text}`);
146
+ const tail = text.slice(end + 1).trim();
147
+ if (tail !== "" && !tail.startsWith("#")) throw new CompositionError(`unexpected content after a flow sequence: ${tail}`);
148
+ const body = text.slice(1, end);
149
+ if (body.trim() === "") return [];
150
+ const items = [];
151
+ for (const raw of body.split(",")) {
152
+ const item = raw.trim();
153
+ if (item === "") throw new CompositionError(`empty item in a flow sequence: ${text}`);
154
+ if (item.startsWith("[") || item.startsWith("{")) throw new CompositionError(`nested flow collections are not supported: ${item}`);
155
+ items.push(inlineScalar(item));
68
156
  }
69
- return value;
157
+ return items;
158
+ }
159
+ /** Resolve the text that follows a colon or a dash on one line. */
160
+ function inlineScalar(text) {
161
+ const value = text.trim();
162
+ if (value.startsWith("!!js")) {
163
+ const expression = value.slice(4).trim();
164
+ if (expression === "") throw new CompositionError("!!js requires an expression");
165
+ return { __jsExpr: unquote(expression) };
166
+ }
167
+ if (value.startsWith("'") || value.startsWith("\"")) {
168
+ const end = closingQuote(value);
169
+ if (end === -1) throw new CompositionError(`unterminated quoted scalar: ${value}`);
170
+ const tail = value.slice(end + 1).trim();
171
+ if (tail !== "" && !tail.startsWith("#")) throw new CompositionError(`unexpected content after a quoted scalar: ${tail}`);
172
+ return unquote(value.slice(0, end + 1));
173
+ }
174
+ if (value.startsWith("[")) return flowSequence(value);
175
+ if (value.startsWith("{")) throw new CompositionError(`flow mappings are not supported: ${value}`);
176
+ if (value.startsWith("|") || value.startsWith(">")) throw new CompositionError(`block scalars need their own line: ${value}`);
177
+ if (value.startsWith("!") || value.startsWith("&") || value.startsWith("*")) throw new CompositionError(`unsupported YAML node: ${value}`);
178
+ return plainScalar(value);
70
179
  }
71
180
  /**
72
- * Validate the structural contract of an `agent.cordis.yml` document.
73
- * @param text - the raw YAML document text.
74
- * @returns a list of human-readable problems; empty means valid.
181
+ * Read one literal (`|`) or folded (`>`) block scalar, consuming its lines.
182
+ * @param cursor - line cursor positioned on the line that follows the header.
183
+ * @param parentIndent - indentation of the node that owns the scalar.
184
+ * @param header - the header text (`|-`, `>+2`, ...) possibly with a comment.
185
+ * @returns the scalar text after indentation stripping and chomping.
75
186
  */
76
- function validateAgentCordis(text) {
77
- const errors = [];
78
- const normalized = text.replace(/\r\n/g, "\n");
79
- if (normalized.trim() === "") return ["document is empty"];
80
- const seenIds = /* @__PURE__ */ new Set();
81
- const current = {
82
- id: null,
83
- name: null,
84
- group: null
85
- };
86
- const closeRow = () => {
87
- if (current.id === null) return;
88
- if (current.name === null) errors.push(`row "${current.id}": missing "name" key`);
89
- else if (!NAME_PREFIX_RE.test(current.name)) errors.push(`row "${current.id}": name "${current.name}" must start with "./", "@" or "cordis:"`);
90
- if (current.group === "true" && current.name !== "cordis:group") errors.push(`row "${current.id}": "group: true" requires name "cordis:group"`);
91
- current.name = null;
92
- current.group = null;
93
- current.id = null;
94
- };
95
- const lines = normalized.split("\n");
96
- for (let index = 0; index < lines.length; index += 1) {
97
- const lineNo = index + 1;
98
- const line = lines[index];
99
- const trimmed = line.trim();
100
- if (trimmed === "" || trimmed.startsWith("#")) continue;
101
- const row = ROW_RE.exec(line);
102
- if (row !== null) {
103
- closeRow();
104
- const id = row[1].trim();
105
- if (id === "") {
106
- errors.push(`line ${lineNo}: empty row id`);
107
- current.id = null;
108
- } else {
109
- if (seenIds.has(id)) errors.push(`line ${lineNo}: duplicate row id "${id}"`);
110
- seenIds.add(id);
111
- current.id = id;
112
- }
113
- current.name = null;
114
- current.group = null;
187
+ function blockScalar(cursor, parentIndent, header) {
188
+ const style = header[0];
189
+ const indicators = header.slice(1).split("#")[0]?.trim() ?? "";
190
+ let explicitIndent;
191
+ let chomp = "clip";
192
+ for (const char of indicators) if (char === "-") chomp = "strip";
193
+ else if (char === "+") chomp = "keep";
194
+ else if (char >= "1" && char <= "9") explicitIndent = Number(char);
195
+ else throw new CompositionError(`unsupported block scalar header: ${header}`);
196
+ const body = [];
197
+ let blockIndent;
198
+ let trailing = 0;
199
+ while (cursor.index < cursor.lines.length) {
200
+ const line = cursor.lines[cursor.index] ?? "";
201
+ if (line.trim() === "") {
202
+ body.push("");
203
+ trailing += 1;
204
+ cursor.index += 1;
115
205
  continue;
116
206
  }
117
- if (current.id === null) {
118
- if (ITEM_RE.test(line)) errors.push(`line ${lineNo}: list item does not declare an "id:"`);
119
- else if (/^\S/.test(line)) errors.push(`line ${lineNo}: content outside a "- id:" row`);
207
+ const indent = indentOf(line);
208
+ if (indent <= parentIndent) break;
209
+ if (blockIndent === void 0) blockIndent = explicitIndent === void 0 ? indent : parentIndent + explicitIndent;
210
+ if (indent < blockIndent) break;
211
+ body.push(line.slice(blockIndent));
212
+ trailing = 0;
213
+ cursor.index += 1;
214
+ }
215
+ const lines = body.slice(0, body.length - trailing);
216
+ if (style === ">") {
217
+ let folded = "";
218
+ let blank = 0;
219
+ let started = false;
220
+ for (const line of lines) {
221
+ if (line === "") {
222
+ blank += 1;
223
+ continue;
224
+ }
225
+ if (!started) {
226
+ folded = line;
227
+ started = true;
228
+ blank = 0;
229
+ continue;
230
+ }
231
+ folded += blank === 0 ? " " + line : "\n".repeat(blank) + line;
232
+ blank = 0;
233
+ }
234
+ if (chomp === "strip") return folded;
235
+ if (chomp === "keep") return folded + "\n".repeat(trailing + 1);
236
+ return folded === "" ? "" : folded + "\n";
237
+ }
238
+ const text = lines.join("\n");
239
+ if (chomp === "strip") return text;
240
+ if (chomp === "keep") return text + "\n".repeat(trailing + 1);
241
+ return text === "" ? "" : text + "\n";
242
+ }
243
+ /** Resolve the value of one entry whose line has already been consumed. */
244
+ function parseValue(cursor, parentIndent, rest) {
245
+ if (rest !== "") {
246
+ if (rest.startsWith("|") || rest.startsWith(">")) return blockScalar(cursor, parentIndent, rest);
247
+ return inlineScalar(rest);
248
+ }
249
+ skipInsignificant(cursor);
250
+ const line = cursor.lines[cursor.index];
251
+ if (line === void 0 || indentOf(line) <= parentIndent) return null;
252
+ return parseNode(cursor, parentIndent + 1);
253
+ }
254
+ /** Parse a block map whose keys sit at exactly `indent`. */
255
+ function parseMap(cursor, indent) {
256
+ const map = {};
257
+ while (true) {
258
+ skipInsignificant(cursor);
259
+ const line = cursor.lines[cursor.index];
260
+ if (line === void 0) break;
261
+ const lineIndent = significantIndent(line, cursor.index + 1);
262
+ if (lineIndent < indent) break;
263
+ if (lineIndent > indent) throw new CompositionError(`line ${String(cursor.index + 1)}: unexpected indentation`);
264
+ if (isSequenceEntry(line, indent)) break;
265
+ const entry = matchKeyEntry(line.slice(indent));
266
+ if (entry === void 0) throw new CompositionError(`line ${String(cursor.index + 1)}: expected "key: value", got "${line.trim()}"`);
267
+ if (Object.hasOwn(map, entry.key)) throw new CompositionError(`line ${String(cursor.index + 1)}: duplicate key "${entry.key}"`);
268
+ cursor.index += 1;
269
+ map[entry.key] = parseValue(cursor, indent, entry.rest);
270
+ }
271
+ return map;
272
+ }
273
+ /** Parse a block sequence whose dashes sit at exactly `indent`. */
274
+ function parseSequence(cursor, indent) {
275
+ const items = [];
276
+ while (true) {
277
+ skipInsignificant(cursor);
278
+ const line = cursor.lines[cursor.index];
279
+ if (line === void 0) break;
280
+ if (significantIndent(line, cursor.index + 1) !== indent || !isSequenceEntry(line, indent)) break;
281
+ const rest = line.slice(indent + 1);
282
+ const content = rest.trimStart();
283
+ if (content === "") {
284
+ cursor.index += 1;
285
+ skipInsignificant(cursor);
286
+ const nested = cursor.lines[cursor.index];
287
+ const nestedIndent = nested === void 0 ? -1 : significantIndent(nested, cursor.index + 1);
288
+ items.push(nestedIndent <= indent ? null : parseNode(cursor, indent + 1));
120
289
  continue;
121
290
  }
122
- const meta = META_RE.exec(line);
123
- if (meta !== null) {
124
- const value = unquote(meta[2].trim());
125
- if (meta[1] === "name") current.name = value;
126
- else if (meta[1] === "group") current.group = value;
291
+ const contentIndent = indent + 1 + (rest.length - content.length);
292
+ if (matchKeyEntry(content) !== void 0) {
293
+ cursor.lines[cursor.index] = " ".repeat(contentIndent) + content;
294
+ items.push(parseMap(cursor, contentIndent));
127
295
  continue;
128
296
  }
129
- if (/^ {2}/.test(line)) continue;
130
- errors.push(`line ${lineNo}: unexpected content in row "${current.id}"`);
297
+ cursor.index += 1;
298
+ items.push(parseValue(cursor, indent, content));
131
299
  }
132
- closeRow();
133
- return errors;
300
+ return items;
134
301
  }
135
- //#endregion
136
- //#region src/sync.ts
137
- /**
138
- * Sync every preset directory under `sourceRoot` into `targetRoot` — the
139
- * dsh agent-presets discovery root (harness-home `.agent-presets`).
140
- *
141
- * A preset is a directory holding `agent.cordis.yml`; the directory name is
142
- * the preset id. Copy is per-directory and idempotent: a preset whose target
143
- * tree is byte-identical to the source tree is skipped, otherwise the source
144
- * tree is copied and any target files the source does not contain are removed.
145
- * Directories the plugin does not own (other presets the user authored) are
146
- * never touched.
147
- *
148
- * After a preset is synced its `agent.cordis.yml` is validated against the
149
- * structural preset schema; a validation failure is reported through the
150
- * run's `failed` entries instead of being a warn-only side effect, so callers
151
- * can observe (and surface) a broken preset rather than silently shipping it.
152
- */
153
- /**
154
- * Clock/coarse-grain tolerance for the mtime fast path. When a source and a
155
- * target file share a size and a near-identical mtime we still fall through to
156
- * a byte comparison; a mtime gap beyond this simply proves the pair cannot be
157
- * byte-identical, so we skip the read.
158
- */
159
- const MTIME_TOLERANCE_MS = 1e3;
160
- function filesUnder(root) {
161
- const out = [];
162
- const walk = (dir) => {
163
- for (const entry of readdirSync(dir)) {
164
- const path = join(dir, entry);
165
- if (statSync(path).isDirectory()) walk(path);
166
- else out.push(path);
167
- }
302
+ /** Parse the block node that starts at the cursor. */
303
+ function parseNode(cursor, minIndent) {
304
+ skipInsignificant(cursor);
305
+ const line = cursor.lines[cursor.index];
306
+ if (line === void 0) return null;
307
+ const indent = significantIndent(line, cursor.index + 1);
308
+ if (indent < minIndent) return null;
309
+ return isSequenceEntry(line, indent) ? parseSequence(cursor, indent) : parseMap(cursor, indent);
310
+ }
311
+ /** Read one cordis YAML document (an entry list, or the flat map of `preset.yml`). */
312
+ function readYaml(text) {
313
+ const cursor = {
314
+ lines: (text.startsWith("") ? text.slice(1) : text).split("\n"),
315
+ index: 0
168
316
  };
169
- walk(root);
170
- return out;
317
+ const value = parseNode(cursor, 0);
318
+ skipInsignificant(cursor);
319
+ const extra = cursor.lines[cursor.index];
320
+ if (extra !== void 0) throw new CompositionError(`line ${String(cursor.index + 1)}: unexpected content "${extra.trim()}"`);
321
+ return value;
322
+ }
323
+ /** Whether a parsed value is one composition row (a map with a string `name`). */
324
+ function asRow(value, at) {
325
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new CompositionError(`${at} is not a plugin row (expected a map with a "name")`);
326
+ const row = value;
327
+ if (typeof row.name !== "string" || row.name === "") throw new CompositionError(`${at} names no plugin (a "name" string is required)`);
328
+ return row;
171
329
  }
172
330
  /**
173
- * File identity is bytes. Size and mtime are only a fast negative check: a
174
- * size mismatch or a mtime gap beyond the tolerance proves the pair cannot be
175
- * byte-identical without reading both, but an equal size and close mtime still
176
- * fall through to a byte comparison so content differences are never missed.
331
+ * Rewrite the relative module names of one row list, recursively through the
332
+ * nested entry lists of group rows, into absolute file URLs.
177
333
  */
178
- function sameFile(a, b) {
179
- const sourceStat = statSync(a);
180
- const targetStat = statSync(b);
181
- if (sourceStat.size !== targetStat.size) return false;
182
- if (Math.abs(sourceStat.mtimeMs - targetStat.mtimeMs) > MTIME_TOLERANCE_MS) return false;
183
- return readFileSync(a).equals(readFileSync(b));
334
+ function absolutizeRows(rows, baseDir, at = "row") {
335
+ return rows.map((row, index) => {
336
+ const label = `${at} ${String(index + 1)}`;
337
+ const checked = asRow(row, label);
338
+ const name = checked.name ?? "";
339
+ const out = { ...checked };
340
+ if (name.startsWith("./") || name.startsWith("../")) out.name = pathToFileURL(resolve(baseDir, name)).href;
341
+ if (checked.group === true) {
342
+ if (!Array.isArray(checked.config)) throw new CompositionError(`group ${label} must hold a list of plugin rows`);
343
+ out.config = absolutizeRows(checked.config, baseDir, `${label} group`);
344
+ }
345
+ return out;
346
+ });
184
347
  }
185
348
  /**
186
- * Remove files not in `keep` (relative paths), then remove only the
187
- * directories those removals left empty — still strictly inside `root`, so
188
- * sibling presets are never touched.
349
+ * Read the child plugin rows of one `agent.cordis.yml`.
350
+ * @param text - the raw composition document.
351
+ * @param baseDir - directory a relative row `name` resolves against (the preset's own directory).
352
+ * @returns the row list to hand the registry, relative names resolved to file URLs.
353
+ * @throws {CompositionError} on malformed YAML or a row the registry would reject.
189
354
  */
190
- function pruneExtras(root, keep) {
191
- const parents = /* @__PURE__ */ new Set();
192
- for (const file of filesUnder(root)) if (!keep.has(relative(root, file))) {
193
- parents.add(dirname(file));
194
- rmSync(file, { force: true });
355
+ function readCompositionRows(text, baseDir) {
356
+ const value = readYaml(text);
357
+ if (!Array.isArray(value)) throw new CompositionError("agent.cordis.yml must be a top-level list of plugin rows");
358
+ return absolutizeRows(value, baseDir);
359
+ }
360
+ /** Read the single-line display scalars of one `preset.yml`. */
361
+ function readPresetMetadata(text) {
362
+ const value = readYaml(text);
363
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new CompositionError("preset.yml must be a mapping");
364
+ const record = value;
365
+ const metadata = {};
366
+ for (const key of ["name", "description"]) {
367
+ const field = record[key];
368
+ if (field === void 0 || field === null) continue;
369
+ if (typeof field !== "string" || field.includes("\n")) throw new CompositionError(`preset.yml: ${key} must be a single-line string`);
370
+ metadata[key] = field;
195
371
  }
196
- for (const start of parents) {
197
- let dir = start;
198
- while (dir !== void 0 && relative(root, dir) !== "") if (existsSync(dir) && readdirSync(dir).length === 0) {
199
- rmSync(dir, {
200
- recursive: true,
201
- force: true
202
- });
203
- dir = dirname(dir);
204
- } else dir = void 0;
372
+ const order = record["order"];
373
+ if (order !== void 0 && order !== null) {
374
+ if (typeof order !== "number" || !Number.isFinite(order)) throw new CompositionError("preset.yml: order must be a number");
375
+ metadata.order = order;
205
376
  }
206
- }
207
- /** Validate the synced preset's `agent.cordis.yml` artifact on disk. */
208
- function validatePresetAgentFile(presetDir) {
209
- const agent = join(presetDir, "agent.cordis.yml");
210
- if (!existsSync(agent)) return ["agent.cordis.yml is missing from the preset tree"];
211
- return validateAgentCordis(readFileSync(agent, "utf8"));
377
+ return metadata;
212
378
  }
213
379
  /**
214
- * Copy the whole tree under `sourceDir` into `targetDir`, creating the target
215
- * directory as needed. Intentionally not `fs.cpSync` (recursive): on Node 22
216
- * for Windows, `fs.cpSync` with `recursive: true` crashes the process with a
217
- * fatal error (STATUS_STACK_BUFFER_OVERRUN / 0xC0000409, no JS exception is
218
- * thrown) whenever the source path contains non-ASCII characters such as a
219
- * CJK home directory (nodejs/node#54476, regression from nodejs/node#53614).
220
- * Since `engines` supports Node ^22.19.0, this must work on Node 22, so the
221
- * copy is done with the same per-entry primitives the rest of the module
222
- * already uses. Source mtimes are preserved to keep the `preserveTimestamps`
223
- * contract of the previous `cpSync` call.
380
+ * Build the registry declaration of one preset directory.
381
+ * @param id - preset identity the roster keys the declaration by.
382
+ * @param dir - absolute preset directory holding `agent.cordis.yml` and `preset.yml`.
383
+ * @returns the definition to submit to `ctx.agentPresets.register`.
384
+ * @throws {CompositionError} when either file is missing, unreadable, or unparsable.
224
385
  */
225
- function copyTreeSync(sourceDir, targetDir) {
226
- mkdirSync(targetDir, { recursive: true });
227
- for (const entry of readdirSync(sourceDir)) {
228
- const source = join(sourceDir, entry);
229
- const target = join(targetDir, entry);
230
- const stat = statSync(source);
231
- if (stat.isDirectory()) copyTreeSync(source, target);
232
- else {
233
- copyFileSync(source, target);
234
- utimesSync(target, stat.atime, stat.mtime);
386
+ function readPresetDefinition(id, dir) {
387
+ const read = (name) => {
388
+ try {
389
+ return readFileSync(join(dir, name), "utf8");
390
+ } catch (error) {
391
+ throw new CompositionError(`${name} is unreadable: ${error instanceof Error ? error.message : String(error)}`);
235
392
  }
236
- }
393
+ };
394
+ return {
395
+ id,
396
+ ...readPresetMetadata(read("preset.yml")),
397
+ plugins: readCompositionRows(read("agent.cordis.yml"), dir)
398
+ };
237
399
  }
238
- /**
239
- * Replace one indented `key: <value>` line inside the block of `- id: <row>`.
240
- *
241
- * Strings render single-quoted and booleans render bare: YAML reads an unquoted
242
- * `false` as a boolean, while `'false'` would be a truthy string and silently
243
- * invert the switch.
244
- */
245
- function setRowValue(text, rowId, key, value) {
246
- if (value === void 0) return text;
247
- const literal = typeof value === "boolean" ? String(value) : `'${value}'`;
248
- const rowStart = text.indexOf(`- id: ${rowId}
249
- `);
250
- if (rowStart < 0) return text;
251
- const afterRow = rowStart + `- id: ${rowId}
252
- `.length;
253
- const rest = text.slice(afterRow);
254
- const boundary = rest.search(/^\S/m);
255
- const body = boundary < 0 ? rest : rest.slice(0, boundary);
256
- const tail = boundary < 0 ? "" : rest.slice(boundary);
257
- const pattern = new RegExp(`^(\\s*)${key}:\\s*.*$`, "m");
258
- const rewritten = pattern.test(body) ? body.replace(pattern, `$1${key}: ${literal}`) : body;
259
- return text.slice(0, afterRow) + rewritten + tail;
400
+ /** The overlay table: settings field to composition row and config key. */
401
+ function overrideTargets(overrides) {
402
+ return [["tool-catalog", { ...overrides.presentation === void 0 ? {} : { presentation: overrides.presentation } }], ["guard", {
403
+ ...overrides.guardEnabled === void 0 ? {} : { enabled: overrides.guardEnabled },
404
+ ...overrides.guardSensitivity === void 0 ? {} : { sensitivity: overrides.guardSensitivity },
405
+ ...overrides.guardStallReasoningChars === void 0 ? {} : { stallReasoningChars: overrides.guardStallReasoningChars },
406
+ ...overrides.guardGlobalStallCap === void 0 ? {} : { globalStallCap: overrides.guardGlobalStallCap },
407
+ ...overrides.guardEchoFailures === void 0 ? {} : { echoFailures: overrides.guardEchoFailures }
408
+ }]];
260
409
  }
261
410
  /**
262
- * Render `agent.cordis.yml` with the settings overrides applied.
411
+ * Apply the settings overlay to one parsed row list.
263
412
  *
264
- * Rows are matched by their `- id:` marker, so the transform does not depend on
265
- * line numbers or on the values the shipped file happens to carry. A row or key
266
- * the source does not contain is left alone rather than invented: the overlay
267
- * narrows the shipped configuration, it never adds a mount the preset did not
268
- * have.
269
- * @param text - the bundled preset composition.
413
+ * Rows are addressed by their `id`, and only a row the composition actually
414
+ * carries is touched: the overlay narrows the shipped configuration, it never
415
+ * invents a mount the preset did not have. The shipped composition declares
416
+ * every key the overlay writes, so leaving a key absent only matters for a
417
+ * composition that dropped it.
418
+ * @param rows - the parsed composition rows.
270
419
  * @param overrides - the operator's settings-surface choices.
271
- * @returns the composition to write into the synced tree.
420
+ * @returns a new row list with the overlay applied.
272
421
  */
273
- function renderPresetOverrides(text, overrides) {
274
- let out = text;
275
- out = setRowValue(out, "tool-catalog", "presentation", overrides.presentation);
276
- return out;
277
- }
278
- /** Copy `sourceRoot/<id>` into `targetRoot/<id>`, idempotently. */
279
- function syncOnePreset(sourceDir, targetDir, overrides = {}) {
280
- const sourceFiles = filesUnder(sourceDir);
281
- const sourceSet = new Set(sourceFiles.map((file) => relative(sourceDir, file)));
282
- if (existsSync(targetDir) && !statSync(targetDir).isDirectory()) rmSync(targetDir, {
283
- recursive: true,
284
- force: true
285
- });
286
- const applyOverrides = () => {
287
- const agentFile = join(targetDir, "agent.cordis.yml");
288
- if (!existsSync(agentFile)) return;
289
- const rendered = renderPresetOverrides(readFileSync(agentFile, "utf8"), overrides);
290
- if (rendered !== readFileSync(agentFile, "utf8")) writeFileSync(agentFile, rendered);
291
- };
292
- if (!existsSync(targetDir)) {
293
- copyTreeSync(sourceDir, targetDir);
294
- pruneExtras(targetDir, sourceSet);
295
- applyOverrides();
296
- return "synced";
297
- }
298
- const agentEntry = join(sourceDir, "agent.cordis.yml");
299
- const expectedAgent = existsSync(agentEntry) ? Buffer.from(renderPresetOverrides(readFileSync(agentEntry, "utf8"), overrides)) : void 0;
300
- let dirty = false;
301
- for (const file of sourceFiles) {
302
- const dest = join(targetDir, relative(sourceDir, file));
303
- if (!existsSync(dest)) {
304
- dirty = true;
305
- break;
306
- }
307
- if (file === agentEntry) {
308
- if (expectedAgent === void 0 || !expectedAgent.equals(readFileSync(dest))) {
309
- dirty = true;
310
- break;
422
+ function applyPresetOverrides(rows, overrides) {
423
+ const table = overrideTargets(overrides);
424
+ return rows.map((row) => {
425
+ const target = table.find(([id]) => id === row.id);
426
+ if (target === void 0) return row;
427
+ const [, patch] = target;
428
+ if (Object.keys(patch).length === 0) return row;
429
+ const config = row.config;
430
+ if (typeof config !== "object" || config === null || Array.isArray(config)) return row;
431
+ return {
432
+ ...row,
433
+ config: {
434
+ ...config,
435
+ ...patch
311
436
  }
312
- continue;
313
- }
314
- if (!sameFile(file, dest)) {
315
- dirty = true;
316
- break;
317
- }
318
- }
319
- if (!dirty) {
320
- for (const file of filesUnder(targetDir)) if (!sourceSet.has(relative(targetDir, file))) {
321
- dirty = true;
322
- break;
323
- }
324
- }
325
- if (!dirty) {
326
- const before = readFileSync(join(targetDir, "agent.cordis.yml"), "utf8");
327
- const after = renderPresetOverrides(before, overrides);
328
- if (after !== before) {
329
- writeFileSync(join(targetDir, "agent.cordis.yml"), after);
330
- return "synced";
331
- }
332
- return "current";
333
- }
334
- pruneExtras(targetDir, sourceSet);
335
- copyTreeSync(sourceDir, targetDir);
336
- pruneExtras(targetDir, sourceSet);
337
- applyOverrides();
338
- return "synced";
437
+ };
438
+ });
339
439
  }
440
+ //#endregion
441
+ //#region src/core/lever.ts
340
442
  /**
341
- * Sync every preset under `sourceRoot` into `targetRoot`, then remove
342
- * target directories named in `retire` that the bundle no longer ships —
343
- * preset ids the plugin once owned and later dropped. Only those exact ids
344
- * are removed; every other target directory is left untouched.
443
+ * LiangShen lever logic — framework-free, no DOM, compiled by both programs.
444
+ *
445
+ * The lever is a homepage control beside the model selector: pulling it down
446
+ * turns the current session's preset into LiangShen mode, pushing it up
447
+ * restores the preset the user was on before. The facts it needs are the
448
+ * current session's preset, whether that session may still change preset at
449
+ * all, and the preset roster; the decisions are pure so they can be tested
450
+ * without the browser runtime.
345
451
  *
346
- * Each synced (or already-current) preset is validated against the structural
347
- * `agent.cordis.yml` schema; a validation failure lands in `failed` so the
348
- * caller can surface a broken preset as a first-class result instead of a
349
- * warn-only log line.
350
- * @param sourceRoot - plugin-owned preset tree (bundled in the package).
351
- * @param targetRoot - dsh agent-presets discovery root (e.g. <home>/.dsh/.agent-presets).
352
- * @param retire - previously bundled preset ids to remove when absent from the source.
452
+ * A preset is fixed once a session starts (the host refuses the switch with
453
+ * `agent-preset/locked`), so the lever is only meaningful while the session is
454
+ * blank — which is exactly the new-session screen it renders on.
353
455
  */
354
- function syncPresetTrees(sourceRoot, targetRoot, retire = [], overrides = {}) {
355
- const result = {
356
- synced: [],
357
- current: [],
358
- failed: [],
359
- retired: []
360
- };
361
- mkdirSync(targetRoot, { recursive: true });
362
- if (existsSync(sourceRoot)) for (const entry of readdirSync(sourceRoot)) {
363
- const source = join(sourceRoot, entry);
364
- if (!statSync(source).isDirectory()) continue;
365
- const id = basename(source);
366
- const targetDir = join(targetRoot, id);
367
- let outcome;
368
- try {
369
- outcome = syncOnePreset(source, targetDir, overrides);
370
- } catch (error) {
371
- result.failed.push({
372
- id,
373
- error: error instanceof Error ? error.message : String(error)
374
- });
375
- continue;
376
- }
377
- try {
378
- const problems = validatePresetAgentFile(targetDir);
379
- if (problems.length > 0) result.failed.push({
380
- id,
381
- error: `agent.cordis.yml failed validation: ${problems.join("; ")}`
382
- });
383
- else if (outcome === "synced") result.synced.push(id);
384
- else result.current.push(id);
385
- } catch (error) {
386
- result.failed.push({
387
- id,
388
- error: error instanceof Error ? error.message : String(error)
389
- });
390
- }
391
- }
392
- for (const id of retire) {
393
- if (existsSync(join(sourceRoot, id))) continue;
394
- const stale = join(targetRoot, id);
395
- if (existsSync(stale) && statSync(stale).isDirectory()) {
396
- rmSync(stale, {
397
- recursive: true,
398
- force: true
399
- });
400
- result.retired.push(id);
401
- }
402
- }
403
- return result;
404
- }
456
+ /** The preset id this lever turns on; also the preset directory name. */
457
+ const LIANGSHEN_PRESET_ID = "liangshen";
405
458
  //#endregion
406
459
  //#region src/mount-once.ts
407
460
  /**
@@ -448,21 +501,29 @@ function mountOnce(packageName, fn) {
448
501
  /**
449
502
  * dsh-liangshen — LiangShen (梁神) agent preset plugin.
450
503
  *
451
- * Host half only: on startup it syncs the bundled `presets/` tree into the
452
- * harness-home agent-presets root (`~/.dsh/.agent-presets`), making the
453
- * LiangShen preset selectable for new sessions without copying files by hand.
454
- * The capability announcement is a system-prompt section that ships OFF by
455
- * default (`announceToAgent: false`) and can be enabled in the web settings
456
- * surface (plugin config) or the profile patch. No browser half, no routes,
457
- * no agent tools — the preset itself provides the tools.
504
+ * Host half only: at activation it DECLARES the bundled LiangShen agent preset
505
+ * to the harness's agent-preset registry (`ctx.agentPresets`), reading the
506
+ * composition rows of `presets/liangshen/agent.cordis.yml` and handing the
507
+ * registry a definition whose relative module paths resolve inside the bundled
508
+ * preset directory. Declare = enabled: the registry mounts the preset's rows
509
+ * eagerly and hands back a disposer this plugin owns, so disabling the plugin
510
+ * (or the row unloading) unmounts them, and nothing is written to the harness
511
+ * home. The registration is released in `ctx.effect`; the plugin's own Config
512
+ * is the settings page the Host generates for this profile entry, and a
513
+ * settings write re-declares the preset with the new values instead of
514
+ * remounting the row. The capability announcement is a system-prompt section
515
+ * that ships OFF by default (`announceToAgent: false`) and can be enabled in
516
+ * the web settings surface (plugin config) or the profile patch. No browser
517
+ * routes, no agent tools — the preset itself provides the tools.
458
518
  *
459
519
  * The preset combines a minimal persona with a lifetime-declared tool
460
520
  * presentation: the system prompt keeps a minimal persona with standing
461
521
  * working discipline and workspace instructions, and the wire runs the SDK's
462
- * 'ptc' presentation by default — the wire collapses to the `run_code`
463
- * transport and every other tool is reached through the generated SDK,
464
- * declared once per session instead of staged across a turn boundary
465
- * ('native' and 'both' are one-line opt-outs). High-fan-out tool families
522
+ * 'both' presentation by default — the assembled native roster stays on the
523
+ * wire for ordinary work and the `run_code` transport sits co-resident for
524
+ * programmatic batch computation and wide fan-out, declared once per session
525
+ * instead of staged across a turn boundary ('native' and 'ptc' are one-line
526
+ * opt-outs). High-fan-out tool families
466
527
  * (default `mcp__*`) stay paged out of the executed surface through the
467
528
  * host's scoped tool restriction until the preset's own `tool_activate` tool
468
529
  * loads their namespace (LRU cap three), with the activation state replayed
@@ -473,8 +534,14 @@ function mountOnce(packageName, fn) {
473
534
  */
474
535
  /** Stable cordis plugin name. */
475
536
  const name = "liangshen";
476
- /** Settings namespace of the plugin (the web settings surface edits it). */
477
- const LIANGSHEN_SETTINGS_NAMESPACE = "dsh-liangshen";
537
+ /**
538
+ * Settings namespace of the plugin. Under the 0.1.7 settings contract a
539
+ * plugin's own Config IS its settings page and the namespace IS the profile
540
+ * entry id, so this is the row id the standalone bundle patch inserts; the
541
+ * aggregate install names the generated `web-ui-liangshen` row and the family
542
+ * binder resolves between the two.
543
+ */
544
+ const LIANGSHEN_SETTINGS_NAMESPACE = "liangshen";
478
545
  /** Prompt assembly must exist before the announcement section can register. */
479
546
  const inject = ["systemPrompt"];
480
547
  /** The wire presentations the preset's tool catalog accepts. */
@@ -483,87 +550,186 @@ const PRESENTATION_OPTIONS = [
483
550
  "native",
484
551
  "both"
485
552
  ];
553
+ /** Sensitivity presets for the circuit breaker's adaptive thresholds. */
554
+ const SENSITIVITY_OPTIONS = [
555
+ "conservative",
556
+ "balanced",
557
+ "aggressive"
558
+ ];
486
559
  const Config = z.object({
487
- enabled: z.boolean().default(true),
488
- announceToAgent: z.boolean().default(false),
489
- presentation: z.union([...PRESENTATION_OPTIONS]).default("ptc")
560
+ enabled: z.boolean().default(true).volatile(),
561
+ announceToAgent: z.boolean().default(false).volatile(),
562
+ presentation: z.union([...PRESENTATION_OPTIONS]).default("both").volatile(),
563
+ guardEnabled: z.boolean().default(true).volatile(),
564
+ guardSensitivity: z.union([...SENSITIVITY_OPTIONS]).default("balanced").volatile(),
565
+ guardStallReasoningChars: z.number().default(8e3).volatile(),
566
+ guardGlobalStallCap: z.number().default(4).volatile(),
567
+ guardEchoFailures: z.number().default(3).volatile()
490
568
  });
491
569
  /** Schema defaults, re-read for hand-built test contexts. */
492
- const DEFAULT_ANNOUNCE = false;
493
- const DEFAULT_PRESENTATION = "ptc";
570
+ const DEFAULT_CONFIG = {
571
+ enabled: true,
572
+ announceToAgent: false,
573
+ presentation: "both",
574
+ guardEnabled: true,
575
+ guardSensitivity: "balanced",
576
+ guardStallReasoningChars: 8e3,
577
+ guardGlobalStallCap: 4,
578
+ guardEchoFailures: 3
579
+ };
580
+ /**
581
+ * Read one activation field. The Host validates the raw profile config and
582
+ * hands volatile fields over as references, so a read goes through `get()`; a
583
+ * plain value passes through, and an absent field falls back to the schema
584
+ * default.
585
+ */
586
+ function readField(field, fallback) {
587
+ if (field === void 0 || field === null) return fallback;
588
+ const ref = field;
589
+ const value = typeof ref.get === "function" ? ref.get() : field;
590
+ return value === void 0 ? fallback : value;
591
+ }
592
+ /**
593
+ * Read the effective settings of this activation.
594
+ * @param config - the config the Host passed to the activation.
595
+ * @returns every field resolved against the schema defaults.
596
+ */
597
+ function resolveConfig(config) {
598
+ return {
599
+ enabled: readField(config?.enabled, DEFAULT_CONFIG.enabled),
600
+ announceToAgent: readField(config?.announceToAgent, DEFAULT_CONFIG.announceToAgent),
601
+ presentation: readField(config?.presentation, DEFAULT_CONFIG.presentation),
602
+ guardEnabled: readField(config?.guardEnabled, DEFAULT_CONFIG.guardEnabled),
603
+ guardSensitivity: readField(config?.guardSensitivity, DEFAULT_CONFIG.guardSensitivity),
604
+ guardStallReasoningChars: readField(config?.guardStallReasoningChars, DEFAULT_CONFIG.guardStallReasoningChars),
605
+ guardGlobalStallCap: readField(config?.guardGlobalStallCap, DEFAULT_CONFIG.guardGlobalStallCap),
606
+ guardEchoFailures: readField(config?.guardEchoFailures, DEFAULT_CONFIG.guardEchoFailures)
607
+ };
608
+ }
609
+ /** Model-facing announcement: plugin presence, principle, and limits. */
610
+ const LIANGSHEN_GUIDANCE = "本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」。原理:系统提示词保持极简 persona(minimal-prompt 放行该段与 plan 模式的 plan:policy),persona 内置本模式工作纪律(反思熔断——同一假设推演不超过两轮、缺事实立即闭合思考并调用原生检测工具;行动导向——思考只决定下一步具体操作、不在思考中预演代码实现;并发探索——多处独立检查或搜索在单轮内并发发射多个工具调用;YAGNI/PDCA——单步验证单一假设、不写冗余注释;有界收敛——不无限下钻依赖链、前置检查最多2-3轮后立即收敛并作答或编辑),并在组装时追加工作区目录行 Your working directory is <cwd>.。AGENTS.md 工作区指令默认交还宿主自身的 agent-instructions 行,以 user 角色注入,本插件不追加任何系统提示词段、也不改动 pre-step 的消息批次;可选 instructionSource: system-prompt 才由本插件在组装时读取 AGENTS.md 链并追加 workspace-instructions 段(65536 字节预算,每次组装重读)。wire 呈现由 tool-catalog 按会话一次声明,取值 'both'(默认:原生清单与 run_code 同驻,原生直调优先、run_code 用于程序化批处理与并发扇出)、'native'(组装出的原生清单)或 'ptc'(wire 收拢为唯一的 run_code),并可在插件设置界面切换(写入所声明预设的 tool-catalog 行);未挂载 code runtime 时不做声明,会话运行原生工具面。温和工具分页出厂开启(pagedToolPatterns 默认 ['mcp__*']):匹配工具在激活前被作用域级工具限制移出可见面(既不在 wire,也不在生成的 SDK 声明中),目录消息列出常驻工具签名与未激活命名空间摘要,调用 tool_activate({ namespace }) 按需激活(LRU 上限 3 个活跃命名空间,驱逐最久未用);激活状态从持久会话事件流重建,resume/压缩后自然恢复。运行时退化熔断器(guard)从事件流折叠停摆(连续零产出长思考)与空转(同参重复失败)信号,每 episode 触发一次:注入熔断消息并把推理档位临时下调一档(max→high→low,窗口 3 个请求);无信号时从不改写请求。关键事实登记簿(fact_register)让模型把硬约束/已确认决策/失败路径登记为单行事实,随 working-context 行每步投射进局部注意力窗口。working-context 插件在 pre-step 注入单行 [Working Context: ...] 就近状态投射(plan 模式、活跃命名空间、进行中 todo、登记事实,全部从事件流折叠,读不到则省略,全部为空则不注入)。历史工具结果修剪为 4096 字符阈值(head 2048 / tail 1024)。文件操作受宿主沙箱约束;shell 在每个平台都挂上游标准 Stdio 栈(POSIX 为 bash,Windows 为 pwsh),带简短描述标题卡片与确定性退出码。真实推理探针通过不等于模式集成通过,更不等于统计效果提升。预设由插件在激活时向 agent-preset registry 直接注册(不写任何预设目录),插件停用即注销;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。";
494
611
  /** Order of the announcement section within the tool-guidance band. */
495
612
  const SECTION_ORDER = 150;
496
- /** Model-facing announcement: plugin presence, principle, and limits. */
497
- const LIANGSHEN_GUIDANCE = "本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」。原理:系统提示词保持极简 persona(minimal-prompt 放行该段与 plan 模式的 plan:policy),persona 内置本模式工作纪律(反思熔断——同一假设推演不超过两轮、缺事实立即闭合思考并调用原生检测工具;行动导向——思考只决定下一步具体操作、不在思考中预演代码实现;并发探索——多处独立检查或搜索在单轮内并发发射多个工具调用;YAGNI/PDCA——单步验证单一假设、不写冗余注释),并在组装时追加工作区目录行 Your working directory is <cwd>.。AGENTS.md 工作区指令默认交还宿主自身的 agent-instructions 行,以 user 角色注入,本插件不追加任何系统提示词段、也不改动 pre-step 的消息批次;可选 instructionSource: system-prompt 才由本插件在组装时读取 AGENTS.md 链并追加 workspace-instructions 段(65536 字节预算,每次组装重读)。wire 呈现由 tool-catalog 按会话一次声明,取值 'ptc'(默认:wire 收拢为唯一的 run_code,其余工具经生成的 SDK 触达)、'native'(组装出的原生清单)或 'both'(两者同驻),并可在插件设置界面切换(同步 preset 时写入 tool-catalog 行);未挂载 code runtime 时不做声明,会话运行原生工具面。温和工具分页:匹配 pagedToolPatterns(默认 mcp__*)的工具在激活前被作用域级工具限制移出可见面(既不在 wire,也不在生成的 SDK 声明中),目录消息列出常驻工具签名与未激活命名空间摘要,调用 tool_activate({ namespace }) 按需激活(LRU 上限 3 个活跃命名空间,驱逐最久未用);激活状态从持久会话事件流重建,resume/压缩后自然恢复。working-context 插件在 pre-step 注入单行 [Working Context: ...] 就近状态投射(plan 模式、活跃命名空间、进行中 todo 标题,全部从事件流折叠,读不到则省略,全部为空则不注入)。历史工具结果修剪为 4096 字符阈值(head 1500 / tail 500)。文件操作受宿主沙箱约束;shell 在每个平台都挂上游标准 Stdio 栈(POSIX 为 bash,Windows 为 pwsh),带简短描述标题卡片与确定性退出码。真实推理探针通过不等于模式集成通过,更不等于统计效果提升。preset 文件由插件维护于 ~/.dsh/.agent-presets,升级插件时自动更新;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。";
498
- /** Absolute path of the bundled preset tree inside this package. */
499
- function bundledPresetsRoot() {
500
- return fileURLToPath(new URL("../presets/", import.meta.url));
613
+ /**
614
+ * Absolute path of the bundled LiangShen preset directory: the composition,
615
+ * the display map, and the preset-local `.mjs` plugins this plugin declares.
616
+ * @returns the preset directory as a filesystem path.
617
+ */
618
+ function bundledPresetDir() {
619
+ return fileURLToPath(new URL("../presets/liangshen/", import.meta.url));
620
+ }
621
+ /**
622
+ * Build the registry declaration of the bundled preset with the settings
623
+ * currently committed applied to the rows they shape.
624
+ * @param values - the activation's effective settings.
625
+ * @returns the definition to submit to `ctx.agentPresets.register`.
626
+ */
627
+ function declaration(values) {
628
+ const definition = readPresetDefinition(LIANGSHEN_PRESET_ID, bundledPresetDir());
629
+ return {
630
+ ...definition,
631
+ plugins: applyPresetOverrides(definition.plugins, values)
632
+ };
501
633
  }
502
634
  /**
503
- * Mount the plugin: sync bundled presets into the harness-home agent-presets
504
- * root, register the settings namespace (enabled / announceToAgent, live),
505
- * and announce through a system-prompt section when announceToAgent is on
506
- * (off by default).
635
+ * Mount the plugin: declare the bundled preset, register the announcement
636
+ * section when announceToAgent is on (off by default), and re-declare on every
637
+ * committed settings write.
507
638
  * @param ctx - host plugin context carrying systemPrompt.
508
639
  * @param config - resolved plugin config (schema defaults applied by the loader).
509
640
  */
510
641
  const apply = mountOnce("@linxin666/dsh-liangshen", applyImpl);
511
642
  function applyImpl(ctx, config) {
512
- let current = () => config ?? {};
513
- const resolve = () => ({
514
- announceToAgent: current().announceToAgent ?? DEFAULT_ANNOUNCE,
515
- enabled: current().enabled ?? true,
516
- presentation: current().presentation ?? DEFAULT_PRESENTATION
517
- });
518
- const sync = () => {
519
- const targetRoot = join(dshHome(), ".agent-presets");
643
+ /** The live registry, or undefined on a deployment that composes none. */
644
+ const registryOf = () => {
645
+ try {
646
+ return ctx.get("agentPresets");
647
+ } catch {
648
+ return;
649
+ }
650
+ };
651
+ /** Disposer of the live declaration; the declaring plugin owns it. */
652
+ let release;
653
+ /** Declaration generation: a re-arm supersedes the one it replaced. */
654
+ let generation = 0;
655
+ /** Set once the owning fiber unloads: a late re-arm must not declare again. */
656
+ let closed = false;
657
+ /** Serializes declaration work, so a settings write cannot interleave with an in-flight activation. */
658
+ let queue = Promise.resolve();
659
+ const warn = (message) => {
660
+ ctx.logger?.warn?.(`dsh-liangshen: ${message}`);
661
+ };
662
+ /** Release the live declaration, waiting for the registry to unmount its rows. */
663
+ const undeclare = async () => {
664
+ const dispose = release;
665
+ release = void 0;
666
+ if (dispose === void 0) return;
520
667
  try {
521
- mkdirSync(targetRoot, { recursive: true });
522
- const settings = resolve();
523
- const result = syncPresetTrees(bundledPresetsRoot(), targetRoot, ["liangshen-exact"], { presentation: settings.presentation });
524
- for (const { id, error } of result.failed) ctx.logger?.warn?.(`dsh-liangshen: preset ${id} sync failed: ${error}`);
525
- if (result.synced.length > 0) ctx.logger?.info?.(`dsh-liangshen: presets synced into ${targetRoot}: ${result.synced.join(", ")}`);
526
- if (result.retired.length > 0) ctx.logger?.info?.(`dsh-liangshen: retired stale presets from ${targetRoot}: ${result.retired.join(", ")}`);
668
+ await dispose();
527
669
  } catch (error) {
528
- ctx.logger?.warn?.(`dsh-liangshen: preset sync failed: ${error instanceof Error ? error.message : String(error)}`);
670
+ warn(`releasing the preset declaration failed: ${error instanceof Error ? error.message : String(error)}`);
529
671
  }
530
672
  };
673
+ /**
674
+ * Declare the preset with the settings committed right now. Queued behind any
675
+ * in-flight activation and skipped when a newer re-arm superseded it, so a
676
+ * burst of settings writes settles on the last one.
677
+ */
678
+ const declare = () => {
679
+ const target = ++generation;
680
+ queue = queue.then(async () => {
681
+ if (closed || target !== generation) return;
682
+ await undeclare();
683
+ const values = resolveConfig(config);
684
+ if (!values.enabled) return;
685
+ const registry = registryOf();
686
+ if (registry === void 0) {
687
+ warn("the agent-preset registry is unavailable; the preset is not declared");
688
+ return;
689
+ }
690
+ try {
691
+ release = await registry.register(declaration(values));
692
+ ctx.logger?.info?.(`liangshen: preset ${LIANGSHEN_PRESET_ID} declared`);
693
+ } catch (error) {
694
+ warn(`declaring the preset failed: ${error instanceof Error ? error.message : String(error)}`);
695
+ }
696
+ }).catch((error) => {
697
+ warn(`preset declaration failed: ${error instanceof Error ? error.message : String(error)}`);
698
+ });
699
+ };
700
+ /** The live announcement section, replaced on every re-arm. */
531
701
  let disposeSection;
532
- const refresh = () => {
702
+ /**
703
+ * Apply the committed settings: swap the announcement section and re-declare
704
+ * the preset. This is the edge the pre-0.1.7 settings `setSource`/`onChange`
705
+ * hooks ran on, from the settings write that the Loader now commits into this
706
+ * row's volatile references instead of remounting it.
707
+ */
708
+ const rearm = () => {
533
709
  disposeSection?.();
534
710
  disposeSection = void 0;
535
- if (!resolve().enabled) return;
536
- sync();
537
- if (resolve().announceToAgent) disposeSection = ctx.systemPrompt.section({
711
+ const values = resolveConfig(config);
712
+ if (values.enabled && values.announceToAgent) disposeSection = ctx.systemPrompt.section({
538
713
  name: "plugin:dsh-liangshen",
539
714
  order: SECTION_ORDER,
540
715
  text: LIANGSHEN_GUIDANCE
541
716
  });
717
+ declare();
542
718
  };
543
- ctx.inject(["settings"], (settingsCtx) => {
544
- try {
545
- if (typeof settingsCtx.settings?.installSection === "function") settingsCtx.settings.installSection(ctx, LIANGSHEN_SETTINGS_NAMESPACE, Config, config ?? {}, {
546
- setSource: (source) => {
547
- current = source;
548
- refresh();
549
- },
550
- onChange: refresh
551
- });
552
- else if (typeof settingsCtx.settings?.register === "function") {
553
- const scope = settingsCtx.settings.register(LIANGSHEN_SETTINGS_NAMESPACE, Config, { base: config ?? {} });
554
- current = () => scope?.get?.() ?? config ?? {};
555
- scope?.watch?.(() => {
556
- refresh();
557
- });
558
- refresh();
559
- }
560
- } catch {}
719
+ ctx.on("loader/volatile-update", () => {
720
+ rearm();
561
721
  });
562
- refresh();
563
- ctx.effect(() => () => {
564
- disposeSection?.();
565
- disposeSection = void 0;
566
- }, "dsh-liangshen: announcement");
722
+ ctx.effect(() => {
723
+ rearm();
724
+ return async () => {
725
+ disposeSection?.();
726
+ disposeSection = void 0;
727
+ closed = true;
728
+ generation += 1;
729
+ await queue;
730
+ await undeclare();
731
+ };
732
+ }, "dsh-liangshen: preset declaration and announcement");
567
733
  }
568
734
  //#endregion
569
- export { Config, LIANGSHEN_GUIDANCE, LIANGSHEN_SETTINGS_NAMESPACE, PRESENTATION_OPTIONS, apply, bundledPresetsRoot, dshHome, inject, name };
735
+ export { Config, DEFAULT_CONFIG, LIANGSHEN_GUIDANCE, LIANGSHEN_SETTINGS_NAMESPACE, PRESENTATION_OPTIONS, SENSITIVITY_OPTIONS, apply, bundledPresetDir, inject, name, resolveConfig };