@linxin666/dsh-liangshen 0.3.23 → 0.4.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 (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +55 -41
  3. package/README.zh.md +54 -40
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +1380 -29
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +616 -367
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +78 -0
  11. package/lib/types/client/PluginSettingsCard.d.ts +137 -0
  12. package/lib/types/client/index.d.ts +57 -4
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +40 -1
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +103 -0
  17. package/lib/types/client/settings-form.d.ts +197 -0
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/core/lever.d.ts +6 -3
  21. package/lib/types/index.d.ts +160 -33
  22. package/lib/types/index.test.d.ts +5 -0
  23. package/package.json +27 -18
  24. package/presets/liangshen/NOTICE +4 -4
  25. package/presets/liangshen/agent.cordis.yml +168 -123
  26. package/presets/liangshen/fact-ledger.mjs +141 -0
  27. package/presets/liangshen/guard.mjs +426 -0
  28. package/presets/liangshen/minimal-prompt.mjs +73 -38
  29. package/presets/liangshen/paging.mjs +232 -0
  30. package/presets/liangshen/tool-activate.mjs +176 -0
  31. package/presets/liangshen/tool-catalog.mjs +615 -219
  32. package/presets/liangshen/working-context.mjs +222 -0
  33. package/src/announce.test.ts +248 -55
  34. package/src/client/LiangShenLever.module.css +2 -0
  35. package/src/client/LiangShenLever.tsx +41 -10
  36. package/src/client/LiangShenSettingsCard.tsx +233 -0
  37. package/src/client/PluginSettingsCard.tsx +555 -0
  38. package/src/client/index.ts +102 -5
  39. package/src/client/lever-controller.ts +76 -9
  40. package/src/client/locales.ts +79 -1
  41. package/src/client/main-session.ts +43 -0
  42. package/src/client/plugin-card-seat.ts +192 -0
  43. package/src/client/settings-card.module.css +418 -0
  44. package/src/client/settings-form.ts +442 -0
  45. package/src/composition.test.ts +294 -0
  46. package/src/composition.ts +554 -0
  47. package/src/core/lever.ts +7 -4
  48. package/src/index.test.ts +68 -1
  49. package/src/index.ts +293 -101
  50. package/tools/benchmark-live-run.mjs +193 -63
  51. package/lib/types/schema.d.ts +0 -18
  52. package/lib/types/schema.test.d.ts +0 -1
  53. package/lib/types/sync.d.ts +0 -47
  54. package/lib/types/sync.test.d.ts +0 -1
  55. package/presets/liangshen/custom-bash.mjs +0 -213
  56. package/src/schema.test.ts +0 -64
  57. package/src/schema.ts +0 -110
  58. package/src/sync.test.ts +0 -224
  59. package/src/sync.ts +0 -222
package/lib/index.js CHANGED
@@ -1,339 +1,461 @@
1
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, utimesSync } 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
- /** Copy `sourceRoot/<id>` into `targetRoot/<id>`, idempotently. */
239
- function syncOnePreset(sourceDir, targetDir) {
240
- const sourceFiles = filesUnder(sourceDir);
241
- const sourceSet = new Set(sourceFiles.map((file) => relative(sourceDir, file)));
242
- if (existsSync(targetDir) && !statSync(targetDir).isDirectory()) rmSync(targetDir, {
243
- recursive: true,
244
- force: true
245
- });
246
- if (!existsSync(targetDir)) {
247
- copyTreeSync(sourceDir, targetDir);
248
- pruneExtras(targetDir, sourceSet);
249
- return "synced";
250
- }
251
- let dirty = false;
252
- for (const file of sourceFiles) {
253
- const dest = join(targetDir, relative(sourceDir, file));
254
- if (!existsSync(dest) || !sameFile(file, dest)) {
255
- dirty = true;
256
- break;
257
- }
258
- }
259
- if (!dirty) {
260
- for (const file of filesUnder(targetDir)) if (!sourceSet.has(relative(targetDir, file))) {
261
- dirty = true;
262
- break;
263
- }
264
- }
265
- if (!dirty) return "current";
266
- pruneExtras(targetDir, sourceSet);
267
- copyTreeSync(sourceDir, targetDir);
268
- pruneExtras(targetDir, sourceSet);
269
- return "synced";
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
+ }]];
270
409
  }
271
410
  /**
272
- * Sync every preset under `sourceRoot` into `targetRoot`, then remove
273
- * target directories named in `retire` that the bundle no longer ships —
274
- * preset ids the plugin once owned and later dropped. Only those exact ids
275
- * are removed; every other target directory is left untouched.
411
+ * Apply the settings overlay to one parsed row list.
276
412
  *
277
- * Each synced (or already-current) preset is validated against the structural
278
- * `agent.cordis.yml` schema; a validation failure lands in `failed` so the
279
- * caller can surface a broken preset as a first-class result instead of a
280
- * warn-only log line.
281
- * @param sourceRoot - plugin-owned preset tree (bundled in the package).
282
- * @param targetRoot - dsh agent-presets discovery root (e.g. <home>/.dsh/.agent-presets).
283
- * @param retire - previously bundled preset ids to remove when absent from the source.
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.
419
+ * @param overrides - the operator's settings-surface choices.
420
+ * @returns a new row list with the overlay applied.
284
421
  */
285
- function syncPresetTrees(sourceRoot, targetRoot, retire = []) {
286
- const result = {
287
- synced: [],
288
- current: [],
289
- failed: [],
290
- retired: []
291
- };
292
- mkdirSync(targetRoot, { recursive: true });
293
- if (existsSync(sourceRoot)) for (const entry of readdirSync(sourceRoot)) {
294
- const source = join(sourceRoot, entry);
295
- if (!statSync(source).isDirectory()) continue;
296
- const id = basename(source);
297
- const targetDir = join(targetRoot, id);
298
- let outcome;
299
- try {
300
- outcome = syncOnePreset(source, targetDir);
301
- } catch (error) {
302
- result.failed.push({
303
- id,
304
- error: error instanceof Error ? error.message : String(error)
305
- });
306
- continue;
307
- }
308
- try {
309
- const problems = validatePresetAgentFile(targetDir);
310
- if (problems.length > 0) result.failed.push({
311
- id,
312
- error: `agent.cordis.yml failed validation: ${problems.join("; ")}`
313
- });
314
- else if (outcome === "synced") result.synced.push(id);
315
- else result.current.push(id);
316
- } catch (error) {
317
- result.failed.push({
318
- id,
319
- error: error instanceof Error ? error.message : String(error)
320
- });
321
- }
322
- }
323
- for (const id of retire) {
324
- if (existsSync(join(sourceRoot, id))) continue;
325
- const stale = join(targetRoot, id);
326
- if (existsSync(stale) && statSync(stale).isDirectory()) {
327
- rmSync(stale, {
328
- recursive: true,
329
- force: true
330
- });
331
- result.retired.push(id);
332
- }
333
- }
334
- return result;
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
436
+ }
437
+ };
438
+ });
335
439
  }
336
440
  //#endregion
441
+ //#region src/core/lever.ts
442
+ /**
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.
451
+ *
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.
455
+ */
456
+ /** The preset id this lever turns on; also the preset directory name. */
457
+ const LIANGSHEN_PRESET_ID = "liangshen";
458
+ //#endregion
337
459
  //#region src/mount-once.ts
338
460
  /**
339
461
  * Host single-instance guard shared by the plugin family. The family bundle
@@ -379,108 +501,235 @@ function mountOnce(packageName, fn) {
379
501
  /**
380
502
  * dsh-liangshen — LiangShen (梁神) agent preset plugin.
381
503
  *
382
- * Host half only: on startup it syncs the bundled `presets/` tree into the
383
- * harness-home agent-presets root (`~/.dsh/.agent-presets`), making the
384
- * LiangShen preset selectable for new sessions without copying files by hand.
385
- * The capability announcement is a system-prompt section that ships OFF by
386
- * default (`announceToAgent: false`) and can be enabled in the web settings
387
- * surface (plugin config) or the profile patch. No browser half, no routes,
388
- * 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.
389
518
  *
390
- * The preset combines a minimal persona with a staged, promoted tool surface:
391
- * the system prompt keeps a minimal persona with standing working discipline
392
- * and workspace instructions, the session's entire first user turn runs a native
393
- * foundational tool surface ([bash, str_replace_editor, exit_plan_mode, skill],
394
- * with bash-only preserved as a configuration experiment), and from the second
395
- * turn this session presents its tools in PTC mode upon successful activation,
396
- * so the wire carries the single `run_code` transport while the generated SDK
397
- * bindings and collapse rule travel in the tool list injected as a durable
398
- * message after the user's message, preserving full input and output key
399
- * parameter semantics.
519
+ * The preset combines a minimal persona with a lifetime-declared tool
520
+ * presentation: the system prompt keeps a minimal persona with standing
521
+ * working discipline and workspace instructions, and the wire runs the SDK's
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
527
+ * (default `mcp__*`) stay paged out of the executed surface through the
528
+ * host's scoped tool restriction until the preset's own `tool_activate` tool
529
+ * loads their namespace (LRU cap three), with the activation state replayed
530
+ * from the durable session event stream. The tool catalog — listing exactly
531
+ * the tools the request carries plus the paged-out namespace summaries — and a
532
+ * one-line working-context projection travel as durable user messages,
533
+ * republished only on change.
400
534
  */
401
535
  /** Stable cordis plugin name. */
402
536
  const name = "liangshen";
403
- /** Settings namespace of the plugin (the web settings surface edits it). */
404
- 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";
405
545
  /** Prompt assembly must exist before the announcement section can register. */
406
546
  const inject = ["systemPrompt"];
547
+ /** The wire presentations the preset's tool catalog accepts. */
548
+ const PRESENTATION_OPTIONS = [
549
+ "ptc",
550
+ "native",
551
+ "both"
552
+ ];
553
+ /** Sensitivity presets for the circuit breaker's adaptive thresholds. */
554
+ const SENSITIVITY_OPTIONS = [
555
+ "conservative",
556
+ "balanced",
557
+ "aggressive"
558
+ ];
407
559
  const Config = z.object({
408
- enabled: z.boolean().default(true),
409
- announceToAgent: z.boolean().default(false)
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()
410
568
  });
411
- /** Schema default, re-read for hand-built test contexts. */
412
- const DEFAULT_ANNOUNCE = false;
569
+ /** Schema defaults, re-read for hand-built test contexts. */
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」时即指本插件,请据此协作。";
413
611
  /** Order of the announcement section within the tool-guidance band. */
414
612
  const SECTION_ORDER = 150;
415
- /** Model-facing announcement: plugin presence, principle, and limits. */
416
- const LIANGSHEN_GUIDANCE = "本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」。原理:系统提示词保持极简 persona(minimal-prompt 放行该段与 plan 模式的 plan:policy),persona 内置本模式工作纪律(思维循环即断、先理解需求与方案再实现验证、YAGNI/PDCA、代码不加冗余注释),并在组装时追加工作区目录 Your working directory is <cwd>. 与 AGENTS.md 工作区指令(workspace-instructions 段,65536 字节预算,每次组装重读);工具清单由 tool-catalog 从第一条用户消息起以 user 消息注入在用户消息之后,形如 skill catalog,仅当工具集变化或该消息离开可见面(压缩、恢复)时重发;wire 上的 schema 按回合分层:首轮整个 user turn 原生呈现基础锚定工具集(默认 [bash, str_replace_editor, exit_plan_mode, skill],且保留 bash-only 配置实验),第二个回合起在 PTC 成功激活后切换为 PTC 呈现(wire 上只有 run_code,其余工具在程序里以 await tools.<name>({...}) 调用,保留完整输入输出关键参数语义而非 200 字唯一契约;缺失 code runtime 时优雅回退至原生呈现);注入消息承载 SDK 绑定、程序契约(一段程序编排多步:独立只读调用用 Promise.all 并发、ToolCallError 处理、输出自选)与「激活后只有 run_code 可直接调用」的规则。工作区子目录动态指令支持注册文件工具含 str_replace_editor 及 PTC 内子调用触达的目录(不解析任意 bash/program 代码)。文件操作受宿主沙箱约束,Windows 下 bash 为 Git Bash 子进程且状态不跨调用保留。真实推理探针通过不等于模式集成通过,更不等于统计效果提升。preset 文件由插件维护于 ~/.dsh/.agent-presets,升级插件时自动更新;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。";
417
- /** Absolute path of the bundled preset tree inside this package. */
418
- function bundledPresetsRoot() {
419
- 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
+ };
420
633
  }
421
634
  /**
422
- * Mount the plugin: sync bundled presets into the harness-home agent-presets
423
- * root, register the settings namespace (enabled / announceToAgent, live),
424
- * and announce through a system-prompt section when announceToAgent is on
425
- * (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.
426
638
  * @param ctx - host plugin context carrying systemPrompt.
427
639
  * @param config - resolved plugin config (schema defaults applied by the loader).
428
640
  */
429
641
  const apply = mountOnce("@linxin666/dsh-liangshen", applyImpl);
430
642
  function applyImpl(ctx, config) {
431
- let current = () => config ?? {};
432
- const resolve = () => ({
433
- announceToAgent: current().announceToAgent ?? DEFAULT_ANNOUNCE,
434
- enabled: current().enabled ?? true
435
- });
436
- const sync = () => {
437
- const targetRoot = join(dshHome(), ".agent-presets");
643
+ /** The live registry, or undefined on a deployment that composes none. */
644
+ const registryOf = () => {
438
645
  try {
439
- mkdirSync(targetRoot, { recursive: true });
440
- const result = syncPresetTrees(bundledPresetsRoot(), targetRoot, ["liangshen-exact"]);
441
- for (const { id, error } of result.failed) ctx.logger?.warn?.(`dsh-liangshen: preset ${id} sync failed: ${error}`);
442
- if (result.synced.length > 0) ctx.logger?.info?.(`dsh-liangshen: presets synced into ${targetRoot}: ${result.synced.join(", ")}`);
443
- if (result.retired.length > 0) ctx.logger?.info?.(`dsh-liangshen: retired stale presets from ${targetRoot}: ${result.retired.join(", ")}`);
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;
667
+ try {
668
+ await dispose();
444
669
  } catch (error) {
445
- 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)}`);
446
671
  }
447
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. */
448
701
  let disposeSection;
449
- 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 = () => {
450
709
  disposeSection?.();
451
710
  disposeSection = void 0;
452
- if (!resolve().enabled) return;
453
- sync();
454
- if (resolve().announceToAgent) disposeSection = ctx.systemPrompt.section({
711
+ const values = resolveConfig(config);
712
+ if (values.enabled && values.announceToAgent) disposeSection = ctx.systemPrompt.section({
455
713
  name: "plugin:dsh-liangshen",
456
714
  order: SECTION_ORDER,
457
715
  text: LIANGSHEN_GUIDANCE
458
716
  });
717
+ declare();
459
718
  };
460
- ctx.inject(["settings"], (settingsCtx) => {
461
- try {
462
- if (typeof settingsCtx.settings?.installSection === "function") settingsCtx.settings.installSection(ctx, LIANGSHEN_SETTINGS_NAMESPACE, Config, config ?? {}, {
463
- setSource: (source) => {
464
- current = source;
465
- refresh();
466
- },
467
- onChange: refresh
468
- });
469
- else if (typeof settingsCtx.settings?.register === "function") {
470
- const scope = settingsCtx.settings.register(LIANGSHEN_SETTINGS_NAMESPACE, Config, { base: config ?? {} });
471
- current = () => scope?.get?.() ?? config ?? {};
472
- scope?.watch?.(() => {
473
- refresh();
474
- });
475
- refresh();
476
- }
477
- } catch {}
719
+ ctx.on("loader/volatile-update", () => {
720
+ rearm();
478
721
  });
479
- refresh();
480
- ctx.effect(() => () => {
481
- disposeSection?.();
482
- disposeSection = void 0;
483
- }, "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");
484
733
  }
485
734
  //#endregion
486
- export { Config, LIANGSHEN_GUIDANCE, LIANGSHEN_SETTINGS_NAMESPACE, apply, bundledPresetsRoot, dshHome, inject, name };
735
+ export { Config, DEFAULT_CONFIG, LIANGSHEN_GUIDANCE, LIANGSHEN_SETTINGS_NAMESPACE, PRESENTATION_OPTIONS, SENSITIVITY_OPTIONS, apply, bundledPresetDir, inject, name, resolveConfig };