dsh-subagent-library 0.2.8 → 0.3.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.
package/lib/index.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { createRequire } from "node:module";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { Context, Service } from "@deepseek-ai/cordis";
4
+ import * as nodePath from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { promises } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { parse, stringify } from "yaml";
4
9
 
5
10
  //#region node_modules/.pnpm/@deepseek-ai+dsh-scope@0.1.0-rc.6_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-invariants_6f3351786c779449c277f079a737f571/node_modules/@deepseek-ai/dsh-scope/lib/index.js
6
11
  /**
@@ -304,7 +309,7 @@ function CallId(id) {
304
309
  * @param value - the value to freeze in place.
305
310
  * @returns the same value, frozen.
306
311
  */
307
- function deepFreeze$1(value) {
312
+ function deepFreeze(value) {
308
313
  const seen = /* @__PURE__ */ new WeakSet();
309
314
  const pending = [{
310
315
  kind: "visit",
@@ -3051,7 +3056,7 @@ function failureMessageFromContent(content) {
3051
3056
  function materializePresentation(candidate) {
3052
3057
  const detached = snapshotJsonValue(candidate);
3053
3058
  if (detached === void 0) throw new TypeError("tool result must be losslessly JSON-serializable");
3054
- return deepFreeze$1(detached);
3059
+ return deepFreeze(detached);
3055
3060
  }
3056
3061
  /** Structured `{ name, code }` for a thrown HarnessError, else undefined. */
3057
3062
  function errorInfo(error) {
@@ -3599,7 +3604,7 @@ var ToolRuntime = class extends Service {
3599
3604
  if (detached === void 0) throw new TypeError("tool execution arguments must be losslessly JSON-serializable");
3600
3605
  const execution = {
3601
3606
  ...base,
3602
- arguments: deepFreeze$1(detached)
3607
+ arguments: deepFreeze(detached)
3603
3608
  };
3604
3609
  this.deferredContexts.set(execution, deferredContexts);
3605
3610
  this.contentFinalizers.set(execution, finalizerFor());
@@ -3959,7 +3964,7 @@ var ToolRuntime = class extends Service {
3959
3964
  const detached = snapshotToolValue(tool.name, candidate);
3960
3965
  const violations = validateJsonSchemaValue(tool.output.schema, detached, "value");
3961
3966
  if (violations.length > 0) throw new ToolOutputError(tool.name, violations);
3962
- const value = deepFreeze$1(detached);
3967
+ const value = deepFreeze(detached);
3963
3968
  let rendered;
3964
3969
  try {
3965
3970
  rendered = tool.output.render(exec.arguments, value);
@@ -4016,7 +4021,7 @@ var ToolRuntime = class extends Service {
4016
4021
  error: result.error,
4017
4022
  ...presentation
4018
4023
  });
4019
- return deepFreeze$1({
4024
+ return deepFreeze({
4020
4025
  ...materializePresentation({
4021
4026
  isError: false,
4022
4027
  ...presentation,
@@ -4278,7 +4283,7 @@ const allowsEval = /* @__PURE__ */ cached(() => {
4278
4283
  return false;
4279
4284
  }
4280
4285
  });
4281
- function isPlainObject$1(o) {
4286
+ function isPlainObject(o) {
4282
4287
  if (isObject(o) === false) return false;
4283
4288
  const ctor = o.constructor;
4284
4289
  if (ctor === void 0) return true;
@@ -4289,7 +4294,7 @@ function isPlainObject$1(o) {
4289
4294
  return true;
4290
4295
  }
4291
4296
  function shallowClone(o) {
4292
- if (isPlainObject$1(o)) return { ...o };
4297
+ if (isPlainObject(o)) return { ...o };
4293
4298
  if (Array.isArray(o)) return [...o];
4294
4299
  if (o instanceof Map) return new Map(o);
4295
4300
  if (o instanceof Set) return new Set(o);
@@ -4372,7 +4377,7 @@ function omit(schema, mask) {
4372
4377
  }));
4373
4378
  }
4374
4379
  function extend(schema, shape) {
4375
- if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
4380
+ if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
4376
4381
  const checks = schema._zod.def.checks;
4377
4382
  if (checks && checks.length > 0) {
4378
4383
  const existingShape = schema._zod.def.shape;
@@ -4388,7 +4393,7 @@ function extend(schema, shape) {
4388
4393
  } }));
4389
4394
  }
4390
4395
  function safeExtend(schema, shape) {
4391
- if (!isPlainObject$1(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
4396
+ if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
4392
4397
  return clone(schema, mergeDefs(schema._zod.def, { get shape() {
4393
4398
  const _shape = {
4394
4399
  ...schema._zod.def.shape,
@@ -4585,7 +4590,7 @@ const _parse = (_Err) => (schema, value, _ctx, _params) => {
4585
4590
  }
4586
4591
  return result.value;
4587
4592
  };
4588
- const parse$1 = /* @__PURE__ */ _parse($ZodRealError);
4593
+ const parse$2 = /* @__PURE__ */ _parse($ZodRealError);
4589
4594
  const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
4590
4595
  const ctx = _ctx ? {
4591
4596
  ..._ctx,
@@ -5978,7 +5983,7 @@ function mergeValues(a, b) {
5978
5983
  valid: true,
5979
5984
  data: a
5980
5985
  };
5981
- if (isPlainObject$1(a) && isPlainObject$1(b)) {
5986
+ if (isPlainObject(a) && isPlainObject(b)) {
5982
5987
  const bKeys = Object.keys(b);
5983
5988
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
5984
5989
  const newObj = {
@@ -7468,7 +7473,7 @@ const ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer, { Par
7468
7473
 
7469
7474
  //#endregion
7470
7475
  //#region node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js
7471
- const parse = /* @__PURE__ */ _parse(ZodRealError);
7476
+ const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
7472
7477
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
7473
7478
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
7474
7479
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -7529,7 +7534,7 @@ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
7529
7534
  inst.def = def;
7530
7535
  inst.type = def.type;
7531
7536
  Object.defineProperty(inst, "_def", { value: def });
7532
- inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
7537
+ inst.parse = (data, params) => parse$1(inst, data, params, { callee: inst.parse });
7533
7538
  inst.safeParse = (data, params) => safeParse(inst, data, params);
7534
7539
  inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
7535
7540
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
@@ -8451,595 +8456,364 @@ async function settleRun(run) {
8451
8456
  }
8452
8457
 
8453
8458
  //#endregion
8454
- //#region node_modules/.pnpm/@deepseek-ai+dsh-settings@0.1.0-rc.6_@deepseek-ai+cordis@4.0.1_@deepseek-ai+dsh-brand@0_52495af71738a1095726249ceff4fd7b/node_modules/@deepseek-ai/dsh-settings/lib/index.js
8455
- /**
8456
- * Structural secret redaction for settings values. `role('secret')` fields are
8457
- * removed from a value before it crosses a wire boundary; a sidecar records
8458
- * each schema-declared secret position and whether it currently holds a value,
8459
- * so a configuration surface can render a write-only input without ever
8460
- * receiving the secret itself.
8461
- * @module @deepseek-ai/dsh-settings/redact
8462
- */
8463
- /** Whether a value is a plain data object the walker may recurse into. */
8464
- function isRecord(value) {
8465
- return typeof value === "object" && value !== null && !Array.isArray(value);
8466
- }
8467
- function walk(node, value, path, secrets) {
8468
- if (node === void 0) return value;
8469
- if (node.meta?.role === "secret") {
8470
- secrets.push({
8471
- path,
8472
- set: value !== void 0
8473
- });
8474
- return;
8475
- }
8476
- switch (node.type) {
8477
- case "object": {
8478
- const properties = node.dict ?? {};
8479
- const source = isRecord(value) ? value : void 0;
8480
- const rebuilt = {};
8481
- if (source !== void 0) for (const [key, entry] of Object.entries(source)) {
8482
- if (key in properties) continue;
8483
- rebuilt[key] = entry;
8484
- }
8485
- for (const [key, child] of Object.entries(properties)) {
8486
- const stripped = walk(child, source?.[key], [...path, key], secrets);
8487
- if (stripped !== void 0) rebuilt[key] = stripped;
8488
- }
8489
- return source === void 0 && Object.keys(rebuilt).length === 0 ? value : rebuilt;
8490
- }
8491
- case "dict": {
8492
- if (!isRecord(value)) return value;
8493
- const rebuilt = {};
8494
- for (const [key, entry] of Object.entries(value)) {
8495
- const stripped = walk(node.inner, entry, [...path, key], secrets);
8496
- if (stripped !== void 0) rebuilt[key] = stripped;
8497
- }
8498
- return rebuilt;
8499
- }
8500
- case "array":
8501
- if (!Array.isArray(value)) return value;
8502
- return value.map((entry, index) => walk(node.inner, entry, [...path, String(index)], secrets));
8503
- default: return value;
8459
+ //#region src/roster.ts
8460
+ /** Entry ids are lowercase dns-ish labels. Also enforced for file names. */
8461
+ const ENTRY_ID = /^[a-z0-9][a-z0-9-]*$/;
8462
+ /** NTFS single component cap is 255; `<id>.yaml` plus headroom stays far below. */
8463
+ const MAX_ID_LENGTH = 64;
8464
+ /** Windows reserved device names — `<name>.yaml` is an illegal file name. */
8465
+ const RESERVED_NAMES = new Set([
8466
+ "con",
8467
+ "prn",
8468
+ "aux",
8469
+ "nul",
8470
+ ...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),
8471
+ ...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`)
8472
+ ]);
8473
+ const EntrySchema = z.object({
8474
+ description: z.string().required(),
8475
+ provider: z.string(),
8476
+ model: z.string(),
8477
+ subagentProvider: z.string(),
8478
+ reasoningEffort: z.string(),
8479
+ maxTokens: z.natural().max(Number.MAX_SAFE_INTEGER),
8480
+ persona: z.string(),
8481
+ toolFilter: z.object({
8482
+ allow: z.array(z.string()).default(void 0),
8483
+ deny: z.array(z.string()).default(void 0)
8484
+ }).default(void 0),
8485
+ maxDepth: z.natural().max(Number.MAX_SAFE_INTEGER),
8486
+ backgroundMode: z.union(["one-shot", "continuable"]).default("one-shot")
8487
+ });
8488
+ const ENTRY_KEYS = new Set([
8489
+ "description",
8490
+ "provider",
8491
+ "model",
8492
+ "subagentProvider",
8493
+ "reasoningEffort",
8494
+ "maxTokens",
8495
+ "persona",
8496
+ "toolFilter",
8497
+ "maxDepth",
8498
+ "backgroundMode"
8499
+ ]);
8500
+ /** Key under which a host/test may inject an `FsPort` on the plugin Context. */
8501
+ const kFsPort = Symbol.for("dsh-subagent-library.fs-port");
8502
+ const nodeFsPort = {
8503
+ readdir: (dir) => promises.readdir(dir),
8504
+ readFile: (path) => promises.readFile(path),
8505
+ writeFile: (path, data) => promises.writeFile(path, data, "utf8"),
8506
+ rename: (from, to) => promises.rename(from, to),
8507
+ unlink: (path) => promises.unlink(path),
8508
+ mkdir: async (dir, options) => {
8509
+ await promises.mkdir(dir, options);
8504
8510
  }
8505
- }
8511
+ };
8512
+ const isEnoent = (error) => error.code === "ENOENT";
8513
+ const defaultDelay = (ms) => new Promise((resolve) => {
8514
+ setTimeout(resolve, ms);
8515
+ });
8516
+ /** Validate one entry id; returns the error message, or undefined when valid. */
8517
+ function validateEntryId(id) {
8518
+ if (!ENTRY_ID.test(id)) return `id "${id}" must match ${String(ENTRY_ID)}`;
8519
+ if (id.length > MAX_ID_LENGTH) return `id "${id}" exceeds ${MAX_ID_LENGTH} characters`;
8520
+ if (RESERVED_NAMES.has(id)) return `id "${id}" is a reserved Windows device name and cannot be a roster file`;
8521
+ }
8522
+ /** Expand `~`, anchor relative paths at `~/.dsh`, keep absolutes as-is. */
8523
+ function resolveEntriesDir(entriesDir, home = homedir()) {
8524
+ const raw = entriesDir?.trim();
8525
+ if (raw === void 0 || raw === "") return nodePath.join(home, ".dsh", "subagents");
8526
+ const expanded = raw === "~" || raw.startsWith("~/") || raw.startsWith("~\\") ? nodePath.join(home, raw.slice(2)) : raw;
8527
+ return nodePath.isAbsolute(expanded) ? expanded : nodePath.join(home, ".dsh", expanded);
8528
+ }
8529
+ const stripBom = (text) => text.charCodeAt(0) === 65279 ? text.slice(1) : text;
8506
8530
  /**
8507
- * Remove every `role('secret')` field a schema declares from a value. The
8508
- * walker follows `object`, `dict`, and `array` containers; a secret must be
8509
- * declared directly on a field reachable through those containers (a secret
8510
- * buried inside a union branch or transform is not reachable and must not be
8511
- * modeled that way). The input is never mutated.
8512
- * @param schema - live schemastery schema describing the value.
8513
- * @param value - the value to strip; `undefined` yields an empty record with
8514
- * object-property secret slots still enumerated.
8515
- * @returns the stripped detached value and the ordered secret positions.
8531
+ * Parse and validate one entry document (file contents or a save payload).
8532
+ * Unknown keys are LOUDLY rejected: a typo'd `backgroundmode` must not be
8533
+ * silently dropped into a default. Returns the normalized entry and the
8534
+ * enabled flag (default true).
8516
8535
  */
8517
- function redactSecrets(schema, value) {
8518
- const secrets = [];
8536
+ function parseEntryDocument(raw) {
8537
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("条目内容必须是对象(字段:description / provider / model / …)");
8538
+ const record = raw;
8539
+ const unknownKeys = Object.keys(record).filter((key) => key !== "enabled" && !ENTRY_KEYS.has(key));
8540
+ if (unknownKeys.length > 0) throw new Error(`未知字段:${unknownKeys.join(", ")}(可用:${[...ENTRY_KEYS, "enabled"].join(", ")})`);
8541
+ const { enabled = true,...rest } = record;
8542
+ if (typeof enabled !== "boolean") throw new Error("enabled 必须是布尔值");
8543
+ if (typeof record["reasoningEffort"] === "string" && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(record["reasoningEffort"])) throw new Error(`reasoningEffort 须为 effort id(如 max / high / medium / low),收到 "${record["reasoningEffort"]}"`);
8544
+ const entry = EntrySchema(rest);
8545
+ if (typeof entry !== "object" || entry === null) throw new Error("条目校验失败");
8519
8546
  return {
8520
- value: walk(schema, value, [], secrets),
8521
- secrets
8547
+ entry,
8548
+ enabled
8522
8549
  };
8523
8550
  }
8524
- /**
8525
- * Service Definition for the user-settings capability seam (`ctx.settings`). Providers store one raw document of
8526
- * per-namespace sections; plugins register a namespace schema and read the
8527
- * resolved value, which layers schema defaults, the registrant's composition
8528
- * `base`, and the user document section, in that order.
8529
- * @module @deepseek-ai/dsh-settings
8530
- */
8531
- const NAMESPACE_PATTERN = /^[a-z][a-z0-9-]*$/;
8532
- /**
8533
- * Brand a raw string as a {@link SettingsNamespace}.
8534
- * @param value - candidate namespace; lowercase kebab-case, as in plugin short names.
8535
- * @returns the branded namespace.
8536
- */
8537
- function settingsNamespace(value) {
8538
- if (!NAMESPACE_PATTERN.test(value)) throw new TypeError(`settings namespace "${value}" must match ${String(NAMESPACE_PATTERN)}`);
8551
+ /** Canonical JSON of one entry (recursively key-sorted) — hash input. */
8552
+ function canonical(value) {
8553
+ if (Array.isArray(value)) return value.map(canonical);
8554
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, canonical(item)]));
8539
8555
  return value;
8540
8556
  }
8541
- /**
8542
- * Deep equality over JSON-compatible data (objects, arrays, primitives) — the
8543
- * Service Definition's single change-detection predicate, exported so the invariant
8544
- * companion checks exactly the implementation's relation.
8545
- * @param a - one JSON-compatible value.
8546
- * @param b - the other JSON-compatible value.
8547
- * @returns whether the two values are structurally equal.
8548
- */
8549
- function deepEqualJson(a, b) {
8550
- if (a === b) return true;
8551
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
8552
- if (Array.isArray(a) || Array.isArray(b)) {
8553
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
8554
- return a.every((entry, index) => deepEqualJson(entry, b[index]));
8555
- }
8556
- const left = a;
8557
- const right = b;
8558
- const keys = Object.keys(left);
8559
- if (keys.length !== Object.keys(right).length) return false;
8560
- return keys.every((key) => key in right && deepEqualJson(left[key], right[key]));
8561
- }
8562
- /**
8563
- * A write refused because the namespace moved since the caller read it. The
8564
- * Service Definition's serialized write queue orders writes; it cannot tell a fresh writer
8565
- * from one holding a stale snapshot, which is what this reports.
8566
- */
8567
- var SettingsConflictError = class extends Error {
8568
- /** Stable machine code for wire layers mapping this to their own taxonomy. */
8569
- code = "SETTINGS_CONFLICT";
8570
- /** The revision the write expected. */
8571
- expected;
8572
- /** The revision the namespace actually stands at. */
8573
- actual;
8574
- /**
8575
- * @param ns - the namespace whose write was refused.
8576
- * @param expected - the revision the caller sent.
8577
- * @param actual - the revision now stored.
8578
- */
8579
- constructor(ns, expected, actual) {
8580
- super(`settings namespace "${ns}" changed since it was read (expected revision ${String(expected)}, now ${String(actual)})`);
8581
- this.name = "SettingsConflictError";
8582
- this.expected = expected;
8583
- this.actual = actual;
8584
- }
8585
- };
8586
- /** Whether a value is a plain data object (not an array, null, or class instance). */
8587
- function isPlainObject(value) {
8588
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
8589
- const proto = Object.getPrototypeOf(value);
8590
- return proto === Object.prototype || proto === null;
8591
- }
8592
- /** Apply one path op to a detached section, returning the next section. */
8593
- function applyPathOp(section, op) {
8594
- const [head, ...rest] = op.path;
8595
- if (head === void 0) {
8596
- if (op.op === "unset") return {};
8597
- if (!isPlainObject(op.value)) throw new TypeError("settings mutate: setting the section root requires a plain object");
8598
- return { ...op.value };
8599
- }
8600
- if (rest.length === 0) {
8601
- if (op.op === "set") return {
8602
- ...section,
8603
- [head]: op.value
8604
- };
8605
- const { [head]: _removed,...kept } = section;
8606
- return kept;
8607
- }
8608
- const child = section[head];
8609
- if (!isPlainObject(child)) {
8610
- if (op.op === "unset") return section;
8611
- return {
8612
- ...section,
8613
- [head]: applyPathOp({}, {
8614
- ...op,
8615
- path: rest
8616
- })
8617
- };
8557
+ function hashEntries(entries) {
8558
+ const payload = Object.keys(entries).sort().map((id) => [
8559
+ id,
8560
+ entries[id].enabled,
8561
+ canonical(entries[id].entry)
8562
+ ]);
8563
+ return createHash("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 16);
8564
+ }
8565
+ /** Serialize an entry to YAML. Defaults are omitted (`enabled: true`,
8566
+ * `backgroundMode: 'one-shot'`); output is UTF-8 without BOM, unwrapped. */
8567
+ function serializeEntry(entry, enabled = true) {
8568
+ const record = entry;
8569
+ const doc = {};
8570
+ for (const key of [
8571
+ "description",
8572
+ "provider",
8573
+ "model",
8574
+ "subagentProvider",
8575
+ "reasoningEffort",
8576
+ "maxTokens",
8577
+ "persona",
8578
+ "toolFilter",
8579
+ "maxDepth",
8580
+ "backgroundMode"
8581
+ ]) {
8582
+ const value = record[key];
8583
+ if (value === void 0) continue;
8584
+ if (key === "backgroundMode" && value === "one-shot") continue;
8585
+ doc[key] = value;
8586
+ }
8587
+ if (!enabled) doc["enabled"] = false;
8588
+ return stringify(doc, { lineWidth: 0 });
8589
+ }
8590
+ /** The CANONICAL file name for an id — always `.yaml` (SUB-ROSTER-YML-001:
8591
+ * save converges every entry onto this spelling). */
8592
+ const entryFileName = (id) => `${id}.yaml`;
8593
+ /** Every on-disk spelling that can serve one id. `loadRoster` READS both, so
8594
+ * writes and deletes must address both too — a `.yml`-only entry that
8595
+ * survives a delete would resurrect after every restart (SUB-ROSTER-YML-001). */
8596
+ const entryFileNames = (id) => [`${id}.yaml`, `${id}.yml`];
8597
+ /** Remove a same-id `.yml` sibling (the failed-convergence residue), with
8598
+ * bounded retries for transient Windows locks; ENOENT = already clean. */
8599
+ async function removeYmlSibling(dir, id, fsp = nodeFsPort, delay = defaultDelay) {
8600
+ const ymlSibling = nodePath.join(dir, `${id}.yml`);
8601
+ for (let attempt = 0;; attempt += 1) try {
8602
+ await fsp.unlink(ymlSibling);
8603
+ return;
8604
+ } catch (error) {
8605
+ if (isEnoent(error)) return;
8606
+ if (attempt >= 2) throw error;
8607
+ await delay(50 * 3 ** attempt);
8608
+ }
8609
+ }
8610
+ /** Atomic single-file write: temp name in the roster dir, then rename with
8611
+ * bounded retries (Windows AV/indexer transiently lock fresh files). */
8612
+ async function writeEntryFile(options) {
8613
+ const fsp = options.fs ?? nodeFsPort;
8614
+ const wait = options.delay ?? defaultDelay;
8615
+ await fsp.mkdir(options.dir, { recursive: true });
8616
+ const target = nodePath.join(options.dir, entryFileName(options.id));
8617
+ const temp = nodePath.join(options.dir, `.${options.id}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`);
8618
+ await fsp.writeFile(temp, serializeEntry(options.entry, options.enabled ?? true));
8619
+ for (let attempt = 0;; attempt += 1) try {
8620
+ await fsp.rename(temp, target);
8621
+ break;
8622
+ } catch (error) {
8623
+ if (attempt >= 2) {
8624
+ await fsp.unlink(temp).catch(() => {});
8625
+ throw error;
8626
+ }
8627
+ await wait(50 * 3 ** attempt);
8618
8628
  }
8619
- return {
8620
- ...section,
8621
- [head]: applyPathOp(child, {
8622
- ...op,
8623
- path: rest
8624
- })
8625
- };
8629
+ await removeYmlSibling(options.dir, options.id, fsp, wait);
8626
8630
  }
8627
- /** Human label for a value that lossless JSON cannot represent (numbers reject inline). */
8628
- function describeRejected(value) {
8629
- if (value === void 0) return "undefined";
8630
- if (typeof value === "object" && value !== null) {
8631
- const name$1 = Object.getPrototypeOf(value)?.constructor?.name;
8632
- return name$1 === void 0 || name$1 === "Object" ? "a non-plain object" : `a ${name$1}`;
8631
+ /** Remove every on-disk spelling that can serve one id (`.yaml` AND `.yml`);
8632
+ * a missing file is already the desired state (SUB-ROSTER-YML-001). */
8633
+ async function deleteEntryFile(dir, id, fsp = nodeFsPort) {
8634
+ for (const name$1 of entryFileNames(id)) try {
8635
+ await fsp.unlink(nodePath.join(dir, name$1));
8636
+ } catch (error) {
8637
+ if (!isEnoent(error)) throw error;
8633
8638
  }
8634
- return `a ${typeof value}`;
8635
8639
  }
8636
8640
  /**
8637
- * Detach and validate one write input in a single walk before persistence:
8638
- * only JSON data (plain objects, arrays, strings, finite numbers,
8639
- * booleans, `null`) may reach a provider document. `structuredClone` alone
8640
- * would admit Dates, Maps, BigInts, and cycles that YAML/JSON storage then
8641
- * silently distorts on the reload round-trip. `undefined` entries in objects
8642
- * are skipped — the same sparse-patch semantics as {@link mergeLayers} — while
8643
- * an `undefined` array entry is rejected rather than coerced.
8644
- * @param root - plain-object write input (caller-checked).
8645
- * @param reject - builds the validation error from a value label and its `$`-rooted path.
8646
- * @returns the detached JSON-compatible clone.
8641
+ * Read the whole roster fresh: directory files first (sorted), then legacy
8642
+ * entries that no file shadows. Diagnostics carry every skip reason.
8647
8643
  */
8648
- function cloneJsonShaped(root, reject) {
8649
- const visiting = /* @__PURE__ */ new WeakSet();
8650
- const clone$1 = (value, path) => {
8651
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
8652
- if (typeof value === "number") {
8653
- if (!Number.isFinite(value)) throw reject("a non-finite number", path);
8654
- return value;
8644
+ async function loadRoster(options) {
8645
+ const fsp = options.fs ?? nodeFsPort;
8646
+ const diagnostics = [];
8647
+ const entries = {};
8648
+ let names;
8649
+ try {
8650
+ names = (await fsp.readdir(options.dir)).slice().sort();
8651
+ } catch (error) {
8652
+ if (!isEnoent(error)) diagnostics.push({
8653
+ severity: "error",
8654
+ message: `名册目录不可读 ${options.dir}:${String(error)}`
8655
+ });
8656
+ names = [];
8657
+ }
8658
+ const owner = /* @__PURE__ */ new Map();
8659
+ /** Ids whose FILE exists but failed to load. If a legacy copy then serves
8660
+ * the same id, that fallback must be LOUD: delegate would run the stale
8661
+ * settings persona while the user believes their edit is live (A2). */
8662
+ const failedFileIds = /* @__PURE__ */ new Set();
8663
+ for (const name$1 of names) {
8664
+ const lower = name$1.toLowerCase();
8665
+ if (!lower.endsWith(".yaml") && !lower.endsWith(".yml")) continue;
8666
+ const id = lower.endsWith(".yaml") ? lower.slice(0, -5) : lower.slice(0, -4);
8667
+ if (id.startsWith("_")) continue;
8668
+ if (lower !== name$1) {
8669
+ diagnostics.push({
8670
+ severity: "warning",
8671
+ file: name$1,
8672
+ id,
8673
+ message: `文件名必须全小写,已跳过 "${name$1}"`
8674
+ });
8675
+ continue;
8655
8676
  }
8656
- if (Array.isArray(value)) {
8657
- if (visiting.has(value)) throw reject("a circular reference", path);
8658
- visiting.add(value);
8659
- const entries = value.map((entry, index) => clone$1(entry, `${path}[${index}]`));
8660
- visiting.delete(value);
8661
- return entries;
8662
- }
8663
- if (isPlainObject(value)) {
8664
- if (visiting.has(value)) throw reject("a circular reference", path);
8665
- visiting.add(value);
8666
- const out = {};
8667
- for (const [key, entry] of Object.entries(value)) {
8668
- if (entry === void 0) continue;
8669
- out[key] = clone$1(entry, `${path}.${key}`);
8670
- }
8671
- visiting.delete(value);
8672
- return out;
8677
+ const idError = validateEntryId(id);
8678
+ if (idError !== void 0) {
8679
+ diagnostics.push({
8680
+ severity: "error",
8681
+ file: name$1,
8682
+ id,
8683
+ message: idError
8684
+ });
8685
+ continue;
8673
8686
  }
8674
- throw reject(describeRejected(value), path);
8675
- };
8676
- return clone$1(root, "$");
8677
- }
8678
- /**
8679
- * Layer `over` onto `under`: plain objects merge recursively, every other
8680
- * value (arrays included) replaces the lower layer wholesale. `over` never
8681
- * carries `undefined` entries — sections come from parsed documents and write
8682
- * snapshots pass {@link cloneJsonShaped}, which strips them so a sparse patch
8683
- * cannot erase lower keys.
8684
- */
8685
- function mergeLayers(under, over) {
8686
- if (over === void 0) return under;
8687
- if (!isPlainObject(under) || !isPlainObject(over)) return over;
8688
- const merged = { ...under };
8689
- for (const [key, value] of Object.entries(over)) merged[key] = key in merged ? mergeLayers(merged[key], value) : value;
8690
- return merged;
8691
- }
8692
- /** Recursively freeze one resolved value so handed-out snapshots stay immutable. */
8693
- function deepFreeze(value) {
8694
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
8695
- for (const entry of Object.values(value)) deepFreeze(entry);
8696
- return Object.freeze(value);
8697
- }
8698
- /**
8699
- * Abstract settings service. Providers implement raw-document storage
8700
- * (`load`/`persist`) and push external changes through {@link Settings.publish};
8701
- * the base class owns namespace registration, resolution, validation, change
8702
- * detection, and the `settings/updated` commit event.
8703
- */
8704
- var SettingsProvider = class extends Service {
8705
- registrations = /* @__PURE__ */ new Map();
8706
- /** Latest published raw document; empty until the provider's first publish. */
8707
- document = {};
8708
- /** Per-namespace write chains; settled tails, so a failure never poisons the queue. */
8709
- writeQueues = /* @__PURE__ */ new Map();
8710
- /** In-flight watcher invocation segments, drained by the dispose teardown. */
8711
- pendingTails = /* @__PURE__ */ new Set();
8712
- /** Set at service dispose: refuse new writes while queued ones drain. */
8713
- stopped = false;
8714
- /** Opaque read of {@link stopped}: control flow cannot narrow it across awaits. */
8715
- isStopped() {
8716
- return this.stopped;
8717
- }
8718
- constructor(ctx) {
8719
- super(ctx, "settings");
8720
- }
8721
- /**
8722
- * Load the provider's document once and publish it before the service
8723
- * becomes injectable, and register the write-drain teardown. Providers with
8724
- * their own init (watchers, connections) delegate here first via
8725
- * `yield* super[Service.init]()`; their disposers then run before the drain.
8726
- */
8727
- async *[Service.init]() {
8728
- yield async () => {
8729
- this.stopped = true;
8730
- await Promise.allSettled([...this.writeQueues.values(), ...this.pendingTails]);
8731
- };
8732
- this.publish(await this.load());
8733
- }
8734
- /**
8735
- * Absolute path of the provider's user-editable document, when its storage
8736
- * is one local file. Configuration surfaces use this only as availability
8737
- * metadata; the guarded open operation resolves the path again Host-side.
8738
- * Non-file providers leave it undefined and expose no open-document affordance.
8739
- * @returns the absolute local document path, or undefined for non-file storage.
8740
- */
8741
- get documentPath() {}
8742
- /**
8743
- * Prepare the provider's user-editable document for a native editor. File
8744
- * providers may materialize an absent document before returning its path;
8745
- * non-file providers return undefined.
8746
- * @returns the absolute local document path, or undefined for non-file storage.
8747
- */
8748
- prepareDocument() {
8749
- return Promise.resolve(this.documentPath);
8750
- }
8751
- /**
8752
- * Register a namespace schema and receive its owner scope. The registration
8753
- * is an effect on the calling plugin's fiber: disposing that fiber removes
8754
- * the namespace and its observers. An invalid stored section fails the
8755
- * registration itself — the earliest point where the schema can judge it.
8756
- * @param ns - unique namespace; duplicate registration fails loud.
8757
- * @param schema - schemastery schema resolving this namespace's value.
8758
- * @param options - composition `base` layer and effect timing.
8759
- * @returns the owner scope for reads, observation, and updates.
8760
- */
8761
- register(ns, schema, options) {
8762
- if (this.registrations.has(ns)) throw new Error(`settings namespace "${ns}" is already registered`);
8763
- const registration = {
8764
- ns,
8765
- schema,
8766
- base: options?.base,
8767
- applies: options?.applies ?? "live",
8768
- ...options?.validate === void 0 ? {} : { validate: options.validate },
8769
- resolved: deepFreeze(this.resolve(schema, options?.base, this.section(ns), options?.validate)),
8770
- revision: 0,
8771
- watchers: /* @__PURE__ */ new Set()
8772
- };
8773
- this.ctx.effect(() => {
8774
- this.registrations.set(ns, registration);
8775
- return () => this.registrations.delete(ns);
8776
- }, `settings.register(${JSON.stringify(String(ns))})`);
8777
- return {
8778
- get: () => registration.resolved,
8779
- watch: (callback) => {
8780
- const watcher = {
8781
- callback,
8782
- tail: Promise.resolve(),
8783
- active: true
8784
- };
8785
- registration.watchers.add(watcher);
8786
- return () => {
8787
- watcher.active = false;
8788
- registration.watchers.delete(watcher);
8789
- };
8790
- },
8791
- update: (patch) => this.update(ns, patch),
8792
- replace: (section) => this.replace(ns, section)
8793
- };
8794
- }
8795
- /**
8796
- * Describe every registered namespace for configuration surfaces, including
8797
- * the composition `base` and raw user layers so a form can mark which fields
8798
- * the user overrode (presence in `user`) and what a reset returns to.
8799
- * @param options - redaction switch; wire surfaces must redact.
8800
- * @returns one descriptor per registered namespace, in registration order.
8801
- */
8802
- describe(options) {
8803
- return [...this.registrations.values()].map((registration) => {
8804
- let user;
8805
- try {
8806
- user = this.section(registration.ns);
8807
- } catch {
8808
- user = void 0;
8809
- }
8810
- const base = registration.base === void 0 ? void 0 : structuredClone(registration.base);
8811
- const detachedUser = user === void 0 ? void 0 : structuredClone(user);
8812
- const descriptor = {
8813
- ns: registration.ns,
8814
- schema: registration.schema.toJSON(),
8815
- value: registration.resolved,
8816
- revision: registration.revision,
8817
- ...base === void 0 ? {} : { base },
8818
- ...detachedUser === void 0 ? {} : { user: detachedUser },
8819
- applies: registration.applies
8820
- };
8821
- if (options?.redactSecrets !== true) return descriptor;
8822
- const schema = registration.schema;
8823
- const redacted = redactSecrets(schema, registration.resolved);
8824
- return {
8825
- ...descriptor,
8826
- value: redacted.value,
8827
- ...base === void 0 ? {} : { base: redactSecrets(schema, base).value },
8828
- ...detachedUser === void 0 ? {} : { user: redactSecrets(schema, detachedUser).value },
8829
- secrets: redacted.secrets
8687
+ const existing = owner.get(id);
8688
+ if (existing !== void 0) {
8689
+ diagnostics.push({
8690
+ severity: "error",
8691
+ file: name$1,
8692
+ id,
8693
+ message: `与 "${existing}" 解析出相同 id(.yaml/.yml 只能保留一个),已跳过`
8694
+ });
8695
+ continue;
8696
+ }
8697
+ owner.set(id, name$1);
8698
+ let text;
8699
+ try {
8700
+ text = (await fsp.readFile(nodePath.join(options.dir, name$1))).toString("utf8");
8701
+ } catch (error) {
8702
+ diagnostics.push({
8703
+ severity: "error",
8704
+ file: name$1,
8705
+ id,
8706
+ message: `读取失败,条目已跳过:${String(error)}`
8707
+ });
8708
+ owner.delete(id);
8709
+ failedFileIds.add(id);
8710
+ continue;
8711
+ }
8712
+ try {
8713
+ const { entry, enabled } = parseEntryDocument(parse(stripBom(text)));
8714
+ entries[id] = {
8715
+ entry,
8716
+ enabled,
8717
+ source: "file",
8718
+ file: name$1
8830
8719
  };
8831
- });
8832
- }
8833
- /**
8834
- * Read one registered namespace's resolved value.
8835
- * @param ns - the namespace to read.
8836
- * @returns the resolved value, or `undefined` while unregistered.
8837
- */
8838
- get(ns) {
8839
- return this.registrations.get(ns)?.resolved;
8840
- }
8841
- /**
8842
- * Merge a patch into one registered namespace's user layer, validate the
8843
- * resolved candidate, persist through the provider, then commit and emit.
8844
- * A validation failure rejects before anything is persisted. Writes to one
8845
- * namespace are serialized: concurrent updates apply in call order, each
8846
- * merging over the previous write's committed section.
8847
- * @param ns - the registered namespace to update.
8848
- * @param patch - plain-object patch over the user section.
8849
- * @param expectedRevision - the descriptor `revision` the caller read; a
8850
- * namespace that moved past it rejects with {@link SettingsConflictError}.
8851
- */
8852
- async update(ns, patch, expectedRevision) {
8853
- return this.write(ns, patch, "merge", expectedRevision);
8854
- }
8855
- /**
8856
- * Replace one registered namespace's user section wholesale, validate,
8857
- * persist, then commit and emit. Keys absent from `section` fall back to the
8858
- * composition `base` and schema defaults — this is the removal/reset path a
8859
- * merge-only patch cannot express (`replace({})` re-inherits everything).
8860
- * @param ns - the registered namespace to replace.
8861
- * @param section - the complete next user section.
8862
- * @param expectedRevision - the descriptor `revision` the caller read; a
8863
- * namespace that moved past it rejects with {@link SettingsConflictError}.
8864
- */
8865
- async replace(ns, section, expectedRevision) {
8866
- return this.write(ns, section, "replace", expectedRevision);
8720
+ } catch (error) {
8721
+ diagnostics.push({
8722
+ severity: "error",
8723
+ file: name$1,
8724
+ id,
8725
+ message: `解析或校验失败,条目已跳过:${String(error)}`
8726
+ });
8727
+ failedFileIds.add(id);
8728
+ }
8867
8729
  }
8868
- /**
8869
- * Apply path-addressed edits to one registered namespace's user section,
8870
- * validate, persist, then commit and emit. The ops are applied to the
8871
- * section as it stands when the write reaches the front of the queue, so a
8872
- * caller never has to restate fields it did not touch — and, crucially,
8873
- * cannot delete fields it never saw. This is the write path for any caller
8874
- * holding a redacted view; `replace` remains the wholesale reset.
8875
- * @param ns - the registered namespace to edit.
8876
- * @param ops - ordered path edits; later ops observe earlier ones.
8877
- * @param expectedRevision - the descriptor `revision` the caller read; a
8878
- * namespace that moved past it rejects with {@link SettingsConflictError}.
8879
- */
8880
- async mutate(ns, ops, expectedRevision) {
8881
- if (!Array.isArray(ops)) throw new TypeError(`settings mutate for "${ns}" must be an array of path ops`);
8882
- for (const op of ops) {
8883
- if (!isPlainObject(op) || op["op"] !== "set" && op["op"] !== "unset") throw new TypeError(`settings mutate for "${ns}" ops must be {op:'set'|'unset', path}`);
8884
- if (!Array.isArray(op["path"]) || op["path"].some((part) => typeof part !== "string")) throw new TypeError(`settings mutate for "${ns}" op paths must be arrays of strings`);
8885
- }
8886
- return this.write(ns, ops, "mutate", expectedRevision);
8887
- }
8888
- /** Validate a write, then queue it on the namespace's serialized write chain. */
8889
- write(ns, input, mode, expectedRevision) {
8890
- const verb = mode === "merge" ? "update" : mode === "replace" ? "replace" : "mutate";
8891
- const registration = this.registrations.get(ns);
8892
- if (registration === void 0) throw new Error(`settings namespace "${ns}" is not registered`);
8893
- if (this.isStopped()) throw new Error(`settings service is disposed: "${ns}" cannot be written`);
8894
- if (!this.writable) throw new Error(`settings provider is read-only: "${ns}" cannot be updated in-process`);
8895
- let payload;
8896
- if (mode === "mutate") payload = { ops: input };
8897
- else {
8898
- if (!isPlainObject(input)) throw new TypeError(`settings ${verb} for "${ns}" must be a plain object`);
8899
- payload = input;
8900
- }
8901
- const snapshot = cloneJsonShaped(payload, (label, path) => /* @__PURE__ */ new TypeError(`settings ${verb} for "${ns}" must contain only JSON-compatible data (found ${label} at ${path})`));
8902
- const run = (this.writeQueues.get(ns) ?? Promise.resolve()).catch(() => void 0).then(async () => {
8903
- if (this.isStopped()) throw new Error(`settings service was disposed before the queued "${ns}" ${verb} ran`);
8904
- if (this.registrations.get(ns) !== registration) throw new Error(`settings namespace "${ns}" registration was disposed before the queued ${verb} ran`);
8905
- const current = this.section(ns) ?? {};
8906
- if (expectedRevision !== void 0 && expectedRevision !== registration.revision) throw new SettingsConflictError(ns, expectedRevision, registration.revision);
8907
- const section = mode === "merge" ? mergeLayers(current, snapshot) : mode === "replace" ? snapshot : snapshot["ops"].reduce(applyPathOp, current);
8908
- const next = deepFreeze(this.resolve(registration.schema, registration.base, section, registration.validate));
8909
- await this.persist(ns, section);
8910
- this.document[ns] = section;
8911
- if (this.registrations.get(ns) === registration && !this.isStopped()) {
8912
- this.bumpRevision(registration, current, section);
8913
- this.commit(registration, next, "update");
8914
- }
8730
+ for (const [id, entry] of Object.entries(options.legacy ?? {})) {
8731
+ if (!ENTRY_ID.test(id)) continue;
8732
+ const file = entries[id];
8733
+ if (file !== void 0) {
8734
+ diagnostics.push({
8735
+ severity: "info",
8736
+ id,
8737
+ message: `settings 中的旧条目已被名册文件 "${file.file}" 覆盖(旧条目可从 settings.yaml 删除)`
8738
+ });
8739
+ continue;
8740
+ }
8741
+ if (failedFileIds.has(id)) diagnostics.push({
8742
+ severity: "error",
8743
+ id,
8744
+ message: `名册文件损坏,当前由 settings 旧副本兜底——delegate 使用的是旧配置;修复或删除该文件后恢复文件优先`
8915
8745
  });
8916
- this.writeQueues.set(ns, run);
8917
- return run;
8746
+ entries[id] = {
8747
+ entry,
8748
+ enabled: true,
8749
+ source: "legacy"
8750
+ };
8918
8751
  }
8919
- /**
8920
- * Provider hook: commit a complete raw document observed in storage. Each
8921
- * registered namespace re-resolves; an invalid section keeps that
8922
- * namespace's last good value and warns, other namespaces still commit.
8923
- * @param doc - the detached raw document (unregistered sections preserved).
8924
- * @param source - change origin; defaults to `provider`.
8925
- */
8926
- publish(doc, source = "provider") {
8927
- const before = /* @__PURE__ */ new Map();
8928
- for (const registration of this.registrations.values()) try {
8929
- before.set(registration.ns, this.section(registration.ns));
8930
- } catch {
8931
- before.set(registration.ns, void 0);
8752
+ return {
8753
+ dir: options.dir,
8754
+ entries,
8755
+ diagnostics,
8756
+ hash: hashEntries(entries)
8757
+ };
8758
+ }
8759
+ /**
8760
+ * One-time-per-directory, per-entry idempotent migration: every legacy entry
8761
+ * that has no roster file yet (and a valid id) is written to `<id>.yaml`.
8762
+ * Legacy settings entries are intentionally KEPT (rollback copy for users
8763
+ * downgrading the plugin); re-running never duplicates or overwrites.
8764
+ */
8765
+ async function migrateLegacyEntries(options) {
8766
+ const fsp = options.fs ?? nodeFsPort;
8767
+ const diagnostics = [];
8768
+ const imported = [];
8769
+ const skipped = [];
8770
+ let names;
8771
+ try {
8772
+ names = new Set((await fsp.readdir(options.dir)).map((name$1) => name$1.toLowerCase()));
8773
+ } catch (error) {
8774
+ if (!isEnoent(error)) throw error;
8775
+ names = /* @__PURE__ */ new Set();
8776
+ }
8777
+ for (const [id, entry] of Object.entries(options.legacy)) {
8778
+ const idError = validateEntryId(id);
8779
+ if (idError !== void 0) {
8780
+ skipped.push({
8781
+ id,
8782
+ reason: idError
8783
+ });
8784
+ continue;
8932
8785
  }
8933
- this.document = doc;
8934
- for (const registration of this.registrations.values()) {
8935
- let next;
8936
- try {
8937
- next = deepFreeze(this.resolve(registration.schema, registration.base, this.section(registration.ns), registration.validate));
8938
- } catch (error) {
8939
- this.ctx.logger.warn("settings: keeping last good \"%s\" after invalid stored section", registration.ns);
8940
- this.ctx.logger.warn(error);
8941
- continue;
8942
- }
8943
- this.bumpRevision(registration, before.get(registration.ns), this.section(registration.ns));
8944
- this.commit(registration, next, source);
8786
+ if (names.has(`${id}.yaml`) || names.has(`${id}.yml`)) {
8787
+ skipped.push({
8788
+ id,
8789
+ reason: "roster file already exists"
8790
+ });
8791
+ continue;
8945
8792
  }
8946
- }
8947
- /** Read one namespace's raw user section, rejecting non-object sections. */
8948
- section(ns) {
8949
- const section = this.document[ns];
8950
- if (section === void 0) return void 0;
8951
- if (!isPlainObject(section)) throw new TypeError(`settings section "${ns}" must be an object of keys`);
8952
- return section;
8953
- }
8954
- /** Resolve one namespace value: schema defaults, then `base`, then the user layer. */
8955
- resolve(schema, base, section, validate) {
8956
- const value = schema(mergeLayers(base, section));
8957
- validate?.(value);
8958
- return value;
8959
- }
8960
- /**
8961
- * Advance a namespace's revision when its RAW section changed, and announce
8962
- * it. Deliberately independent of {@link commit}'s resolved-value equality:
8963
- * storing an override equal to the composition base leaves the resolved
8964
- * value alone but changes what the document says, which is exactly what a
8965
- * configuration surface must re-read.
8966
- */
8967
- bumpRevision(registration, before, after) {
8968
- if (deepEqualJson(before, after)) return;
8969
- registration.revision += 1;
8970
- this.emitDocumentUpdated(registration.ns, registration.revision);
8971
- }
8972
- /** Contained fan-out of `settings/document-updated`, mirroring {@link commit}'s. */
8973
- emitDocumentUpdated(ns, revision) {
8974
- let invariantFailure;
8975
- const args = [
8976
- "settings/document-updated",
8977
- ns,
8978
- revision
8979
- ];
8980
- for (const listener of this.ctx.events.dispatch("emit", args)) try {
8981
- const returned = listener(ns, revision);
8982
- if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
8983
- this.warnListenerFailure(ns, error);
8793
+ try {
8794
+ await writeEntryFile({
8795
+ dir: options.dir,
8796
+ id,
8797
+ entry,
8798
+ fs: fsp,
8799
+ delay: options.delay
8984
8800
  });
8801
+ names.add(`${id}.yaml`);
8802
+ imported.push(id);
8985
8803
  } catch (error) {
8986
- if (error?.code === "INVARIANT") {
8987
- invariantFailure ??= error;
8988
- continue;
8989
- }
8990
- this.warnListenerFailure(ns, error);
8991
- }
8992
- if (invariantFailure !== void 0) throw invariantFailure;
8993
- }
8994
- /** Commit a resolved value when changed: swap, notify watchers, emit the event. */
8995
- commit(registration, next, source) {
8996
- const prev = registration.resolved;
8997
- if (deepEqualJson(next, prev)) return;
8998
- registration.resolved = next;
8999
- for (const watcher of [...registration.watchers]) {
9000
- const segment = watcher.tail.then(() => {
9001
- if (!watcher.active || this.isStopped()) return;
9002
- return watcher.callback(next, prev);
9003
- }).then(() => void 0, (error) => {
9004
- this.warnWatcherFailure(registration.ns, error);
9005
- });
9006
- watcher.tail = segment;
9007
- this.pendingTails.add(segment);
9008
- segment.then(() => this.pendingTails.delete(segment));
9009
- }
9010
- let invariantFailure;
9011
- const args = [
9012
- "settings/updated",
9013
- registration.ns,
9014
- next,
9015
- prev,
9016
- source
9017
- ];
9018
- for (const listener of this.ctx.events.dispatch("emit", args)) try {
9019
- const returned = listener(registration.ns, next, prev, source);
9020
- if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
9021
- this.warnListenerFailure(registration.ns, error);
8804
+ diagnostics.push({
8805
+ severity: "error",
8806
+ id,
8807
+ message: `迁移写入失败:${String(error)}`
9022
8808
  });
9023
- } catch (error) {
9024
- if (error?.code === "INVARIANT") {
9025
- invariantFailure ??= error;
9026
- continue;
9027
- }
9028
- this.warnListenerFailure(registration.ns, error);
9029
8809
  }
9030
- if (invariantFailure !== void 0) throw invariantFailure;
9031
- }
9032
- /** Contained-watcher diagnostic shared by the sync and async failure paths. */
9033
- warnWatcherFailure(ns, error) {
9034
- this.ctx.logger.warn("settings: watcher for \"%s\" failed", ns);
9035
- this.ctx.logger.warn(error);
9036
8810
  }
9037
- /** Contained-listener diagnostic shared by the sync and async failure paths. */
9038
- warnListenerFailure(ns, error) {
9039
- this.ctx.logger.warn("settings: a settings/updated listener for \"%s\" failed", ns);
9040
- this.ctx.logger.warn(error);
9041
- }
9042
- };
8811
+ return {
8812
+ imported,
8813
+ skipped,
8814
+ diagnostics
8815
+ };
8816
+ }
9043
8817
 
9044
8818
  //#endregion
9045
8819
  //#region src/index.ts
@@ -9049,29 +8823,15 @@ const inject = [
9049
8823
  "tools",
9050
8824
  "systemPrompt"
9051
8825
  ];
9052
- const ENTRY_ID = /^[a-z0-9][a-z0-9-]*$/;
9053
8826
  const LIBRARY_SECTION_ORDER = 116.6;
9054
8827
  /** Recursion cap applied when an entry omits maxDepth and the transport can
9055
8828
  * enforce it — the harness itself imposes no global delegation cap
9056
8829
  * (resolveChildDepth checks only an explicit value), and the official
9057
8830
  * subagent tool defaults to 3 to keep chained delegation bounded. */
9058
8831
  const DEFAULT_MAX_DEPTH = 3;
9059
- const EntrySchema = z.object({
9060
- description: z.string().required(),
9061
- provider: z.string(),
9062
- model: z.string(),
9063
- subagentProvider: z.string(),
9064
- maxTokens: z.natural().max(Number.MAX_SAFE_INTEGER),
9065
- persona: z.string(),
9066
- toolFilter: z.object({
9067
- allow: z.array(z.string()).default(void 0),
9068
- deny: z.array(z.string()).default(void 0)
9069
- }).default(void 0),
9070
- maxDepth: z.natural().max(Number.MAX_SAFE_INTEGER),
9071
- backgroundMode: z.union(["one-shot", "continuable"]).default("one-shot")
9072
- });
9073
8832
  const Config = z.object({
9074
8833
  subagentProvider: z.string().default("spawn"),
8834
+ entriesDir: z.string(),
9075
8835
  entries: z.dict(EntrySchema).default({})
9076
8836
  });
9077
8837
  /** Render text blocks from the canonical JSON block array without trusting arbitrary values. */
@@ -9156,40 +8916,198 @@ function sanitizeToolFilter(ctx, filter, scope) {
9156
8916
  };
9157
8917
  }
9158
8918
  function apply(ctx, config$1) {
9159
- let source;
9160
- let settingsService;
9161
- let settingsNs;
9162
- /** Non-null when the settings seam could not register this namespace (e.g. a
9163
- * hand-edited settings.yaml section fails the Config schema). Registration
9164
- * failing inside a Cordis child fiber would otherwise leave the library
9165
- * silently empty; surface the cause through every consumer instead. */
8919
+ const SETTINGS_NS = "subagent-library";
8920
+ let configEditorHost;
8921
+ let settings;
8922
+ /** Non-null when the settings seam could not initialize (e.g. a hand-edited
8923
+ * stored section fails the Config schema on the legacy register path).
8924
+ * Failures surface through every consumer instead of leaving the library
8925
+ * silently degraded. */
9166
8926
  let settingsFailure;
9167
8927
  ctx.inject(["settings"], (sctx) => {
9168
- settingsService = sctx.settings;
9169
- settingsNs = settingsNamespace("subagent-library");
9170
- try {
9171
- const scope = sctx.settings.register(settingsNs, Config, { base: config$1 });
9172
- source = () => scope.get();
9173
- sctx.effect(() => () => {
9174
- source = () => config$1;
9175
- });
9176
- scope.watch(() => {});
9177
- } catch (error) {
9178
- settingsFailure = `subagent-library 设置段注册失败:${String(error)}。请检查 $DSH_HOME/settings.yaml 的 subagent-library 段(常见:description 缺失、entries 写成数组、YAML 布尔/字符串误写)。`;
8928
+ /** Structural view covering both host generations (type deps stay pinned
8929
+ * to 0.1.0-rc.6, so nothing here can rely on their static types). */
8930
+ const svc = sctx.settings;
8931
+ if (typeof svc?.register === "function") {
8932
+ try {
8933
+ const scope = svc.register(SETTINGS_NS, Config, { base: config$1 });
8934
+ const legacyRaw = () => {
8935
+ try {
8936
+ return (svc.describe?.().find((candidate) => String(candidate.ns) === SETTINGS_NS))?.user ?? void 0;
8937
+ } catch {
8938
+ return;
8939
+ }
8940
+ };
8941
+ settings = {
8942
+ readConfig: () => scope.get(),
8943
+ legacyUserEntries: () => legacyRaw()?.entries,
8944
+ unsetEntries: async (ids) => {
8945
+ if (ids.length === 0) return "done";
8946
+ if (typeof svc.mutate !== "function") return "no-settings";
8947
+ if (svc.writable === false) return "skipped-readonly";
8948
+ await svc.mutate(SETTINGS_NS, ids.map((id) => ({
8949
+ op: "unset",
8950
+ path: ["entries", id]
8951
+ })));
8952
+ return "done";
8953
+ },
8954
+ isWritable: () => svc.writable !== false
8955
+ };
8956
+ } catch (error) {
8957
+ settingsFailure = `subagent-library 设置段注册失败:${String(error)}。请检查存储的 subagent-library 配置段(常见:description 缺失、entries 写成数组、YAML 布尔/字符串误写)。`;
8958
+ }
8959
+ return;
8960
+ }
8961
+ if (typeof svc?.register !== "function") {
8962
+ /** Resolved schema defaults, computed once. Used to RESTORE effective
8963
+ * defaults in the apply()-closure when a raw patch `next` drops keys —
8964
+ * the ConfigEditor raw layer does NOT carry schema defaults
8965
+ * (e.g. `subagentProvider: 'spawn'`), and a wholesale overwrite of the
8966
+ * resolved config with raw values silently removed them, breaking
8967
+ * delegation with "provider not registered"
8968
+ * (SUB-COMPAT-017-004). Defaults are restored in the closure ONLY —
8969
+ * never written back into the raw patch. */
8970
+ let schemaDefaultsCache;
8971
+ const schemaDefaults = () => {
8972
+ if (schemaDefaultsCache === void 0) try {
8973
+ schemaDefaultsCache = Config({});
8974
+ } catch {
8975
+ schemaDefaultsCache = {
8976
+ subagentProvider: "spawn",
8977
+ entries: {}
8978
+ };
8979
+ }
8980
+ const cached$1 = schemaDefaultsCache;
8981
+ return {
8982
+ ...cached$1,
8983
+ entries: { ...cached$1["entries"] ?? {} }
8984
+ };
8985
+ };
8986
+ /** Reflect a reconciled RAW config into the apply()-closure, re-resolving
8987
+ * schema defaults for keys the raw layer dropped. The Loader reconcile
8988
+ * may restart this plugin asynchronously, but the in-flight HTTP
8989
+ * response and later reads must not lose defaults in the meantime. */
8990
+ const applyReconciled = (next) => {
8991
+ const target = config$1;
8992
+ const defaults = schemaDefaults();
8993
+ const keys = new Set([
8994
+ ...Object.keys(defaults),
8995
+ ...Object.keys(target),
8996
+ ...Object.keys(next)
8997
+ ]);
8998
+ for (const key of keys) {
8999
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
9000
+ if (Object.hasOwn(next, key)) target[key] = next[key];
9001
+ else if (defaults[key] !== void 0) target[key] = defaults[key];
9002
+ else if (key in target) delete target[key];
9003
+ }
9004
+ };
9005
+ settings = {
9006
+ readConfig: () => config$1,
9007
+ legacyUserEntries: () => config$1.entries ?? void 0,
9008
+ unsetEntries: async (ids) => {
9009
+ if (ids.length === 0) return "done";
9010
+ const editor = configEditorHost;
9011
+ if (editor === void 0) return "no-settings";
9012
+ if (svc.writable === false) return "skipped-readonly";
9013
+ const entry = editor.entries?.().find((row) => {
9014
+ const id = row.options?.id ?? row.id;
9015
+ return String(id ?? "") === SETTINGS_NS;
9016
+ });
9017
+ if (entry === void 0) return "no-settings";
9018
+ let applied;
9019
+ await editor.edit(entry, (current) => {
9020
+ const patchEntries = typeof current["entries"] === "object" && current["entries"] !== null ? { ...current["entries"] } : {};
9021
+ const merged = {
9022
+ ...config$1.entries ?? {},
9023
+ ...patchEntries
9024
+ };
9025
+ let changed = false;
9026
+ for (const id of ids) if (Object.hasOwn(merged, id)) {
9027
+ delete merged[id];
9028
+ changed = true;
9029
+ }
9030
+ const next = changed ? {
9031
+ ...current,
9032
+ entries: merged
9033
+ } : { ...current };
9034
+ applied = next;
9035
+ return next;
9036
+ });
9037
+ if (applied !== void 0) applyReconciled(applied);
9038
+ return "done";
9039
+ },
9040
+ isWritable: () => svc.writable !== false
9041
+ };
9042
+ return;
9179
9043
  }
9180
9044
  });
9045
+ ctx.inject(["settings", "configEditor"], (ectx) => {
9046
+ const editor = ectx.configEditor;
9047
+ if (editor !== void 0) configEditorHost = editor;
9048
+ });
9181
9049
  /** Library entries restricted to schema-consistent ids: a hand-written key
9182
9050
  * like `k3_reviewer` passes z.dict (any string key) but can never be
9183
- * delegated or deleted, so it is filtered out of every view. Saving any
9184
- * entry then replaces the document and drops the orphaned key. */
9185
- const filterEntries = (raw) => Object.fromEntries(Object.entries(raw).filter(([id]) => ENTRY_ID.test(id)));
9051
+ * delegated or deleted, so it is filtered out of every view. */
9052
+ const filterEntries = (raw) => Object.fromEntries(Object.entries(raw ?? {}).filter(([id]) => ENTRY_ID.test(id)));
9186
9053
  const resolveConfig = () => {
9187
- const base = source !== void 0 ? source() : config$1;
9054
+ const base = settings?.readConfig() ?? config$1;
9188
9055
  return {
9189
9056
  ...base,
9190
9057
  entries: filterEntries(base.entries)
9191
9058
  };
9192
9059
  };
9060
+ const fsPort = () => ctx[kFsPort] ?? nodeFsPort;
9061
+ let migratedDir;
9062
+ let migrationFailure;
9063
+ /** Seed the roster directory from legacy settings entries — exactly once
9064
+ * per directory ON SUCCESS. Per-entry idempotent (existing files are never
9065
+ * touched), and legacy documents are deliberately KEPT in settings as the
9066
+ * rollback copy for users downgrading the plugin (removal planned 0.4.0).
9067
+ * A FAILED migration must NOT latch (red team A5): transient FS errors are
9068
+ * fast-fail and cheap, so every roster read retries until it succeeds —
9069
+ * otherwise a single AV-lock would silently strand entries on the legacy
9070
+ * path until 0.4 removes legacy reading. */
9071
+ const ensureMigrated = async () => {
9072
+ const legacy = resolveConfig().entries ?? {};
9073
+ if (Object.keys(legacy).length === 0) return;
9074
+ const dir = resolveEntriesDir(resolveConfig().entriesDir);
9075
+ if (migratedDir === dir) return;
9076
+ try {
9077
+ const result = await migrateLegacyEntries({
9078
+ dir,
9079
+ legacy,
9080
+ fs: fsPort()
9081
+ });
9082
+ if (result.diagnostics.length === 0) {
9083
+ migratedDir = dir;
9084
+ migrationFailure = void 0;
9085
+ } else migrationFailure = `${result.diagnostics.map((item) => item.message).join(";")}(修复后将自动重试)`;
9086
+ } catch (error) {
9087
+ migrationFailure = `${String(error)}——下次使用名册时自动重试;重启 dsh web 亦可立即重试`;
9088
+ }
9089
+ };
9090
+ /** Fresh roster view for every consumer (tools, command, settings API):
9091
+ * no cache — tens of small files read in milliseconds, and the cache layer
9092
+ * is exactly where mtime/case/rename bugs live (v0.3.0 design review). */
9093
+ const loadLibrary = async () => {
9094
+ if (settingsFailure !== void 0) throw new Error(settingsFailure);
9095
+ const cfg = resolveConfig();
9096
+ await ensureMigrated();
9097
+ const view = await loadRoster({
9098
+ dir: resolveEntriesDir(cfg.entriesDir),
9099
+ legacy: cfg.entries,
9100
+ fs: fsPort()
9101
+ });
9102
+ if (migrationFailure !== void 0) view.diagnostics.unshift({
9103
+ severity: "warning",
9104
+ message: `旧条目自动迁移未完成:${migrationFailure}`
9105
+ });
9106
+ return {
9107
+ subagentProvider: cfg.subagentProvider,
9108
+ view
9109
+ };
9110
+ };
9193
9111
  const MAX_BODY_BYTES = 1 << 20;
9194
9112
  const readJsonBody = async (req) => {
9195
9113
  const chunks = [];
@@ -9261,28 +9179,55 @@ function apply(ctx, config$1) {
9261
9179
  }
9262
9180
  return true;
9263
9181
  };
9264
- /** Raw `entries` map from one descriptor layer; arrays and non-objects are
9265
- * rejected so a damaged document cannot masquerade as the library. */
9266
- const entriesOf = (section) => {
9267
- if (typeof section !== "object" || section === null || Array.isArray(section)) return void 0;
9268
- const entries = section.entries;
9269
- return typeof entries === "object" && entries !== null && !Array.isArray(entries) ? entries : void 0;
9182
+ /** Wire shape of one roster row for the settings editor: the stored entry
9183
+ * plus the enabled flag when false and a `source` marker for legacy rows. */
9184
+ const wireEntries = (view) => Object.fromEntries(Object.entries(view.entries).map(([id, row]) => [id, {
9185
+ ...row.entry,
9186
+ ...row.enabled ? {} : { enabled: false },
9187
+ ...row.source === "legacy" ? { source: "legacy" } : {}
9188
+ }]));
9189
+ /** Legacy settings entries currently shadowed by a roster file — the safe
9190
+ * one-click cleanup set for the 0.2→0.3 transition (a legacy row WITHOUT a
9191
+ * file is still serving and must survive). */
9192
+ const legacyShadowedIds = (view) => {
9193
+ const raw = settings?.legacyUserEntries();
9194
+ if (raw === void 0) return [];
9195
+ return Object.keys(raw).filter((id) => ENTRY_ID.test(id) && view.entries[id]?.source === "file");
9270
9196
  };
9271
- const currentView = () => {
9272
- const svc = settingsService;
9273
- const ns = settingsNs;
9274
- if (svc === void 0 || ns === void 0) return null;
9275
- const descriptor = svc.describe().find((candidate) => candidate.ns === ns);
9276
- if (descriptor === void 0) return null;
9277
- const entries = filterEntries(entriesOf(descriptor.user) ?? entriesOf(descriptor.value) ?? {});
9197
+ const wireView = async (legacySkipWarning = false, extraWarnings = []) => {
9198
+ const { view } = await loadLibrary();
9199
+ const diagnostics = [
9200
+ ...extraWarnings.map((message) => ({
9201
+ severity: "warning",
9202
+ message
9203
+ })),
9204
+ ...legacySkipWarning ? [{
9205
+ severity: "warning",
9206
+ message: "设置服务只读:settings 中的旧副本未能同步移除,被删条目可能以旧副本复活"
9207
+ }] : [],
9208
+ ...view.diagnostics
9209
+ ];
9278
9210
  return {
9279
- writable: svc.writable,
9280
- revision: descriptor.revision,
9281
- entries
9211
+ ok: true,
9212
+ writable: true,
9213
+ dir: view.dir,
9214
+ hash: view.hash,
9215
+ entries: wireEntries(view),
9216
+ diagnostics,
9217
+ legacyCount: legacyShadowedIds(view).length
9282
9218
  };
9283
9219
  };
9284
9220
  ctx.inject(["webServer"], (wctx) => {
9285
9221
  const web = wctx.webServer;
9222
+ /** Best-effort removal of legacy-only settings entries (the file half is
9223
+ * already gone). No expectedRevision: last-write-wins — a racing settings
9224
+ * writer must not fail a delete that mostly succeeded. Returns whether
9225
+ * the unset actually ran, so a read-only settings service can be surfaced
9226
+ * instead of a silent false success (red team A7 / k3 #4). */
9227
+ const unsetLegacy = async (ids) => {
9228
+ if (ids.length === 0) return "done";
9229
+ return settings?.unsetEntries(ids) ?? "no-settings";
9230
+ };
9286
9231
  wctx.effect(() => web.register({
9287
9232
  kind: "exact",
9288
9233
  path: "/subagent-library/api",
@@ -9296,18 +9241,15 @@ function apply(ctx, config$1) {
9296
9241
  });
9297
9242
  return;
9298
9243
  }
9299
- const view = currentView();
9300
- if (view === null) {
9301
- sendJson(res, 503, {
9244
+ try {
9245
+ sendJson(res, 200, await wireView());
9246
+ } catch (error) {
9247
+ sendJson(res, 500, {
9302
9248
  ok: false,
9303
- error: "not-ready"
9249
+ error: "roster-unreadable",
9250
+ message: String(error)
9304
9251
  });
9305
- return;
9306
9252
  }
9307
- sendJson(res, 200, {
9308
- ok: true,
9309
- ...view
9310
- });
9311
9253
  return;
9312
9254
  }
9313
9255
  if (req.method !== "POST") {
@@ -9318,6 +9260,14 @@ function apply(ctx, config$1) {
9318
9260
  return;
9319
9261
  }
9320
9262
  if (!guardWrite(req, res)) return;
9263
+ if (settingsFailure !== void 0) {
9264
+ sendJson(res, 503, {
9265
+ ok: false,
9266
+ error: "not-ready",
9267
+ message: settingsFailure
9268
+ });
9269
+ return;
9270
+ }
9321
9271
  const read = await readJsonBody(req);
9322
9272
  if (!read.ok) {
9323
9273
  if (read.error === "too-large") sendJson(res, 413, {
@@ -9331,26 +9281,37 @@ function apply(ctx, config$1) {
9331
9281
  return;
9332
9282
  }
9333
9283
  const body = read.body;
9334
- const svc = settingsService;
9335
- const ns = settingsNs;
9336
- if (svc === void 0 || ns === void 0) {
9337
- sendJson(res, 503, {
9338
- ok: false,
9339
- error: "not-ready"
9340
- });
9341
- return;
9342
- }
9343
- if (!svc.writable) {
9344
- sendJson(res, 403, {
9345
- ok: false,
9346
- error: "readonly"
9347
- });
9348
- return;
9349
- }
9350
- const rawRevision = body["expectedRevision"];
9351
- const expectedRevision = typeof rawRevision === "number" && Number.isInteger(rawRevision) ? rawRevision : void 0;
9284
+ const rawHash = body["expectedHash"];
9285
+ const expectedHash = typeof rawHash === "string" ? rawHash : void 0;
9352
9286
  try {
9353
- if (body["op"] === "delete") {
9287
+ const { view: current } = await loadLibrary();
9288
+ if (expectedHash !== void 0 && expectedHash !== current.hash) {
9289
+ sendJson(res, 409, {
9290
+ ok: false,
9291
+ error: "conflict",
9292
+ view: {
9293
+ ok: true,
9294
+ writable: true,
9295
+ dir: current.dir,
9296
+ hash: current.hash,
9297
+ entries: wireEntries(current),
9298
+ diagnostics: current.diagnostics,
9299
+ legacyCount: legacyShadowedIds(current).length
9300
+ }
9301
+ });
9302
+ return;
9303
+ }
9304
+ if (body["op"] === "clear-legacy") {
9305
+ if (settings !== void 0 && !settings.isWritable()) {
9306
+ sendJson(res, 403, {
9307
+ ok: false,
9308
+ error: "readonly",
9309
+ message: "设置服务只读,无法清除旧副本"
9310
+ });
9311
+ return;
9312
+ }
9313
+ await unsetLegacy(legacyShadowedIds(current));
9314
+ } else if (body["op"] === "delete") {
9354
9315
  const id = typeof body["id"] === "string" ? body["id"] : "";
9355
9316
  if (!ENTRY_ID.test(id)) {
9356
9317
  sendJson(res, 400, {
@@ -9359,10 +9320,9 @@ function apply(ctx, config$1) {
9359
9320
  });
9360
9321
  return;
9361
9322
  }
9362
- await svc.mutate(ns, [{
9363
- op: "unset",
9364
- path: ["entries", id]
9365
- }], expectedRevision);
9323
+ await deleteEntryFile(current.dir, id, fsPort());
9324
+ sendJson(res, 200, await wireView(await unsetLegacy([id]) === "skipped-readonly"));
9325
+ return;
9366
9326
  } else if (body["op"] === "save") {
9367
9327
  const entries = body["entries"];
9368
9328
  if (typeof entries !== "object" || entries === null || Array.isArray(entries)) {
@@ -9373,24 +9333,57 @@ function apply(ctx, config$1) {
9373
9333
  return;
9374
9334
  }
9375
9335
  const candidate = entries;
9376
- const badKey = Object.keys(candidate).find((key) => !ENTRY_ID.test(key));
9377
- if (badKey !== void 0) {
9378
- sendJson(res, 400, {
9379
- ok: false,
9380
- error: "invalid-entry-id",
9381
- message: `entry id "${badKey}" is invalid`
9336
+ const validated = /* @__PURE__ */ new Map();
9337
+ for (const [id, value] of Object.entries(candidate)) {
9338
+ const idError = validateEntryId(id);
9339
+ if (idError !== void 0) {
9340
+ sendJson(res, 400, {
9341
+ ok: false,
9342
+ error: "invalid-entry-id",
9343
+ message: idError
9344
+ });
9345
+ return;
9346
+ }
9347
+ const payload = { ...value };
9348
+ delete payload["source"];
9349
+ try {
9350
+ validated.set(id, parseEntryDocument(payload));
9351
+ } catch (error) {
9352
+ sendJson(res, 400, {
9353
+ ok: false,
9354
+ error: "rejected",
9355
+ message: `条目 "${id}":${String(error)}`
9356
+ });
9357
+ return;
9358
+ }
9359
+ }
9360
+ const sweepWarnings = [];
9361
+ for (const [id, doc] of validated) {
9362
+ const prev = current.entries[id];
9363
+ if (prev?.source === "file" && prev.file === entryFileName(id) && serializeEntry(prev.entry, prev.enabled) === serializeEntry(doc.entry, doc.enabled)) {
9364
+ try {
9365
+ await removeYmlSibling(current.dir, id, fsPort());
9366
+ } catch (error) {
9367
+ sweepWarnings.push(`条目 "${id}" 的同名 .yml 残留清除失败,冲突诊断会持续到清除成功:${String(error)}`);
9368
+ }
9369
+ continue;
9370
+ }
9371
+ await writeEntryFile({
9372
+ dir: current.dir,
9373
+ id,
9374
+ entry: doc.entry,
9375
+ enabled: doc.enabled,
9376
+ fs: fsPort()
9382
9377
  });
9383
- return;
9384
9378
  }
9385
- Config({
9386
- ...config$1,
9387
- entries: candidate
9388
- });
9389
- const userSection = svc.describe().find((row) => row.ns === ns)?.user ?? {};
9390
- await svc.replace(ns, {
9391
- ...userSection,
9392
- entries: candidate
9393
- }, expectedRevision);
9379
+ const deletedIds = [];
9380
+ for (const [id, row] of Object.entries(current.entries)) {
9381
+ if (validated.has(id)) continue;
9382
+ deletedIds.push(id);
9383
+ if (row.source === "file") await deleteEntryFile(current.dir, id, fsPort());
9384
+ }
9385
+ sendJson(res, 200, await wireView(await unsetLegacy(deletedIds) === "skipped-readonly", sweepWarnings));
9386
+ return;
9394
9387
  } else {
9395
9388
  sendJson(res, 400, {
9396
9389
  ok: false,
@@ -9398,28 +9391,12 @@ function apply(ctx, config$1) {
9398
9391
  });
9399
9392
  return;
9400
9393
  }
9401
- const view = currentView();
9402
- if (view === null) {
9403
- sendJson(res, 503, {
9404
- ok: false,
9405
- error: "not-ready"
9406
- });
9407
- return;
9408
- }
9409
- sendJson(res, 200, {
9410
- ok: true,
9411
- ...view
9412
- });
9394
+ sendJson(res, 200, await wireView());
9413
9395
  } catch (error) {
9414
- const message = String(error);
9415
- if (error.code === "SETTINGS_CONFLICT") sendJson(res, 409, {
9396
+ sendJson(res, 500, {
9416
9397
  ok: false,
9417
- error: "conflict"
9418
- });
9419
- else sendJson(res, 400, {
9420
- ok: false,
9421
- error: "rejected",
9422
- message
9398
+ error: "write-failed",
9399
+ message: String(error)
9423
9400
  });
9424
9401
  }
9425
9402
  }
@@ -9453,12 +9430,13 @@ function apply(ctx, config$1) {
9453
9430
  isConcurrencySafe: () => true,
9454
9431
  async execute(_args, exec) {
9455
9432
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9456
- const lib = resolveConfig();
9433
+ const { view } = await loadLibrary();
9457
9434
  const agent = exec.agent;
9458
9435
  /** The catalog must not advertise a filter this session cannot apply:
9459
9436
  * summarize the SANITIZED filter and list what was ignored, so the model
9460
9437
  * sees the same tool scope delegation will actually produce. */
9461
- const filterSummary = (entry) => {
9438
+ const filterSummary = (row) => {
9439
+ const entry = row.entry;
9462
9440
  if (entry.toolFilter === void 0) return void 0;
9463
9441
  const declared = [entry.toolFilter.allow !== void 0 ? `allow:[${entry.toolFilter.allow.join(", ")}]` : "", entry.toolFilter.deny !== void 0 ? `deny:[${entry.toolFilter.deny.join(", ")}]` : ""].filter(Boolean).join(" ");
9464
9442
  if (agent === void 0) return declared;
@@ -9466,17 +9444,21 @@ function apply(ctx, config$1) {
9466
9444
  const effective = filter === void 0 ? "(本会话无可应用的名单项)" : [filter.allow !== void 0 ? `allow:[${filter.allow.join(", ")}]` : "", filter.deny !== void 0 ? `deny:[${filter.deny.join(", ")}]` : ""].filter(Boolean).join(" ");
9467
9445
  return dropped.length > 0 ? `${effective} 忽略:[${dropped.map((item) => item.name).join(", ")}]` : effective;
9468
9446
  };
9469
- return Object.entries(lib.entries).map(([id, entry]) => {
9470
- const summary = filterSummary(entry);
9447
+ const rows = Object.entries(view.entries).map(([id, row]) => {
9448
+ const summary = filterSummary(row);
9471
9449
  return {
9472
9450
  id,
9473
- description: entry.description,
9474
- provider: entry.provider ?? "(session default)",
9475
- model: entry.model ?? "(session default)",
9476
- backgroundMode: entry.backgroundMode ?? "one-shot",
9451
+ description: row.entry.description,
9452
+ provider: row.entry.provider ?? "(session default)",
9453
+ model: row.entry.model ?? "(session default)",
9454
+ backgroundMode: row.entry.backgroundMode ?? "one-shot",
9455
+ ...row.enabled ? {} : { enabled: false },
9477
9456
  ...summary !== void 0 ? { toolFilter: summary } : {}
9478
9457
  };
9479
9458
  });
9459
+ const catalogDiagnostics = view.diagnostics.filter((item) => item.severity !== "info");
9460
+ if (catalogDiagnostics.length > 0) rows.push({ diagnostics: catalogDiagnostics.map((item) => `${item.severity}${item.id !== void 0 ? ` [${item.id}]` : ""}: ${item.message}`) });
9461
+ return rows;
9480
9462
  }
9481
9463
  }));
9482
9464
  ctx.tools.register(defineTool({
@@ -9531,14 +9513,16 @@ function apply(ctx, config$1) {
9531
9513
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9532
9514
  const parent = exec.agent;
9533
9515
  if (!parent) throw new Error("delegate tool requires a calling agent (exec.agent was undefined)");
9534
- const lib = resolveConfig();
9516
+ const { subagentProvider: defaultProvider, view } = await loadLibrary();
9535
9517
  if (!ENTRY_ID.test(args.library_id)) throw new Error(`subagent library entry id "${args.library_id}" is invalid`);
9536
- const entry = Object.hasOwn(lib.entries, args.library_id) ? lib.entries[args.library_id] : void 0;
9537
- if (entry === void 0) {
9538
- const ids = Object.keys(lib.entries);
9518
+ const row = Object.hasOwn(view.entries, args.library_id) ? view.entries[args.library_id] : void 0;
9519
+ if (row === void 0) {
9520
+ const ids = Object.keys(view.entries);
9539
9521
  throw new Error(`subagent library has no entry "${args.library_id}"${ids.length ? ` (available: ${ids.join(", ")})` : " (library is empty)"}`);
9540
9522
  }
9541
- const subagentProviderName = entry.subagentProvider ?? lib.subagentProvider;
9523
+ if (!row.enabled) throw new Error(`delegate: entry "${args.library_id}" is disabled — remove "enabled: false" in its roster file (or re-enable it on the settings page) to delegate to it again`);
9524
+ const entry = row.entry;
9525
+ const subagentProviderName = entry.subagentProvider ?? defaultProvider;
9542
9526
  const transport = ctx.subagents.getProvider(subagentProviderName);
9543
9527
  if (transport === void 0) throw new Error(`subagent transport provider "${subagentProviderName}" is not registered (available: ${ctx.subagents.list().join(", ") || "none"})`);
9544
9528
  const continuable = entry.backgroundMode === "continuable";
@@ -9554,9 +9538,10 @@ function apply(ctx, config$1) {
9554
9538
  if (entry.toolFilter !== void 0 && entry.toolFilter.allow === void 0 && entry.toolFilter.deny === void 0) throw new Error(`delegate: entry "${args.library_id}" names a toolFilter with neither allow nor deny`);
9555
9539
  if (entry.toolFilter !== void 0 && !transport.capabilities.toolFilter) throw new Error(`delegate: transport "${subagentProviderName}" cannot apply a tool filter (no toolFilter capability)`);
9556
9540
  }
9557
- const agentOptions = entry.provider !== void 0 || entry.model !== void 0 || entry.maxTokens !== void 0 ? {
9541
+ const agentOptions = entry.provider !== void 0 || entry.model !== void 0 || entry.maxTokens !== void 0 || entry.reasoningEffort !== void 0 ? {
9558
9542
  ...entry.provider !== void 0 ? { provider: entry.provider } : {},
9559
9543
  ...entry.model !== void 0 ? { model: entry.model } : {},
9544
+ ...entry.reasoningEffort !== void 0 ? { reasoningEffort: entry.reasoningEffort } : {},
9560
9545
  ...entry.maxTokens !== void 0 ? { maxTokens: entry.maxTokens } : {}
9561
9546
  } : void 0;
9562
9547
  const request = {
@@ -9625,15 +9610,23 @@ function apply(ctx, config$1) {
9625
9610
  if (commands !== void 0) commands.register({
9626
9611
  name: "subagent",
9627
9612
  description: "List the subagent library entries",
9628
- handler: () => {
9629
- const lib = resolveConfig();
9630
- const ids = Object.keys(lib.entries);
9613
+ handler: async () => {
9614
+ const { view } = await loadLibrary();
9615
+ const ids = Object.keys(view.entries);
9616
+ const lines = ids.map((id) => {
9617
+ const row = view.entries[id];
9618
+ const tags = [
9619
+ `${row.entry.provider ?? "默认模型路由"}/${row.entry.model ?? "默认模型"}`,
9620
+ row.entry.backgroundMode === "continuable" ? "可续聊" : "",
9621
+ row.source === "legacy" ? "legacy" : "",
9622
+ row.enabled ? "" : "已停用"
9623
+ ].filter(Boolean).join(",");
9624
+ return `- ${id}: ${row.entry.description} [${tags}]`;
9625
+ });
9626
+ const diagnosticLines = view.diagnostics.filter((item) => item.severity !== "info").map((item) => ` ! ${item.severity}${item.id !== void 0 ? ` [${item.id}]` : ""}: ${item.message}`);
9631
9627
  return {
9632
9628
  kind: "success",
9633
- text: ids.length === 0 ? "子代理库为空。在 settings.yaml 的 subagent-library.entries 下添加条目(id / description / provider / model / subagentProvider / persona / toolFilter / maxDepth / backgroundMode)。" : `子代理库(${ids.length} 个):\n` + ids.map((id) => {
9634
- const entry = lib.entries[id];
9635
- return `- ${id}: ${entry.description} [${entry.provider ?? "默认模型路由"}/${entry.model ?? "默认模型"}${entry.backgroundMode === "continuable" ? ",可续聊" : ""}]`;
9636
- }).join("\n")
9629
+ text: ids.length === 0 && view.diagnostics.length === 0 ? `子代理库为空。在名册目录放置 <id>.yaml 文件(默认 ~/.dsh/subagents/,可用 subagent-library.entriesDir 配置),或在设置页添加。` : `子代理库(${ids.length} 个,目录 ${view.dir}):\n` + [...lines, ...diagnosticLines].join("\n")
9637
9630
  };
9638
9631
  }
9639
9632
  });