dsh-subagent-library 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
  /**
@@ -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,
@@ -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);
@@ -9042,25 +9047,26 @@ var SettingsProvider = class extends Service {
9042
9047
  };
9043
9048
 
9044
9049
  //#endregion
9045
- //#region src/index.ts
9046
- const name = "subagent-library";
9047
- const inject = [
9048
- "subagents",
9049
- "tools",
9050
- "systemPrompt"
9051
- ];
9050
+ //#region src/roster.ts
9051
+ /** Entry ids are lowercase dns-ish labels. Also enforced for file names. */
9052
9052
  const ENTRY_ID = /^[a-z0-9][a-z0-9-]*$/;
9053
- const LIBRARY_SECTION_ORDER = 116.6;
9054
- /** Recursion cap applied when an entry omits maxDepth and the transport can
9055
- * enforce it — the harness itself imposes no global delegation cap
9056
- * (resolveChildDepth checks only an explicit value), and the official
9057
- * subagent tool defaults to 3 to keep chained delegation bounded. */
9058
- const DEFAULT_MAX_DEPTH = 3;
9053
+ /** NTFS single component cap is 255; `<id>.yaml` plus headroom stays far below. */
9054
+ const MAX_ID_LENGTH = 64;
9055
+ /** Windows reserved device names — `<name>.yaml` is an illegal file name. */
9056
+ const RESERVED_NAMES = new Set([
9057
+ "con",
9058
+ "prn",
9059
+ "aux",
9060
+ "nul",
9061
+ ...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),
9062
+ ...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`)
9063
+ ]);
9059
9064
  const EntrySchema = z.object({
9060
9065
  description: z.string().required(),
9061
9066
  provider: z.string(),
9062
9067
  model: z.string(),
9063
9068
  subagentProvider: z.string(),
9069
+ reasoningEffort: z.string(),
9064
9070
  maxTokens: z.natural().max(Number.MAX_SAFE_INTEGER),
9065
9071
  persona: z.string(),
9066
9072
  toolFilter: z.object({
@@ -9070,8 +9076,348 @@ const EntrySchema = z.object({
9070
9076
  maxDepth: z.natural().max(Number.MAX_SAFE_INTEGER),
9071
9077
  backgroundMode: z.union(["one-shot", "continuable"]).default("one-shot")
9072
9078
  });
9079
+ const ENTRY_KEYS = new Set([
9080
+ "description",
9081
+ "provider",
9082
+ "model",
9083
+ "subagentProvider",
9084
+ "reasoningEffort",
9085
+ "maxTokens",
9086
+ "persona",
9087
+ "toolFilter",
9088
+ "maxDepth",
9089
+ "backgroundMode"
9090
+ ]);
9091
+ /** Key under which a host/test may inject an `FsPort` on the plugin Context. */
9092
+ const kFsPort = Symbol.for("dsh-subagent-library.fs-port");
9093
+ const nodeFsPort = {
9094
+ readdir: (dir) => promises.readdir(dir),
9095
+ readFile: (path) => promises.readFile(path),
9096
+ writeFile: (path, data) => promises.writeFile(path, data, "utf8"),
9097
+ rename: (from, to) => promises.rename(from, to),
9098
+ unlink: (path) => promises.unlink(path),
9099
+ mkdir: async (dir, options) => {
9100
+ await promises.mkdir(dir, options);
9101
+ }
9102
+ };
9103
+ const isEnoent = (error) => error.code === "ENOENT";
9104
+ const defaultDelay = (ms) => new Promise((resolve) => {
9105
+ setTimeout(resolve, ms);
9106
+ });
9107
+ /** Validate one entry id; returns the error message, or undefined when valid. */
9108
+ function validateEntryId(id) {
9109
+ if (!ENTRY_ID.test(id)) return `id "${id}" must match ${String(ENTRY_ID)}`;
9110
+ if (id.length > MAX_ID_LENGTH) return `id "${id}" exceeds ${MAX_ID_LENGTH} characters`;
9111
+ if (RESERVED_NAMES.has(id)) return `id "${id}" is a reserved Windows device name and cannot be a roster file`;
9112
+ }
9113
+ /** Expand `~`, anchor relative paths at `~/.dsh`, keep absolutes as-is. */
9114
+ function resolveEntriesDir(entriesDir, home = homedir()) {
9115
+ const raw = entriesDir?.trim();
9116
+ if (raw === void 0 || raw === "") return nodePath.join(home, ".dsh", "subagents");
9117
+ const expanded = raw === "~" || raw.startsWith("~/") || raw.startsWith("~\\") ? nodePath.join(home, raw.slice(2)) : raw;
9118
+ return nodePath.isAbsolute(expanded) ? expanded : nodePath.join(home, ".dsh", expanded);
9119
+ }
9120
+ const stripBom = (text) => text.charCodeAt(0) === 65279 ? text.slice(1) : text;
9121
+ /**
9122
+ * Parse and validate one entry document (file contents or a save payload).
9123
+ * Unknown keys are LOUDLY rejected: a typo'd `backgroundmode` must not be
9124
+ * silently dropped into a default. Returns the normalized entry and the
9125
+ * enabled flag (default true).
9126
+ */
9127
+ function parseEntryDocument(raw) {
9128
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("条目内容必须是对象(字段:description / provider / model / …)");
9129
+ const record = raw;
9130
+ const unknownKeys = Object.keys(record).filter((key) => key !== "enabled" && !ENTRY_KEYS.has(key));
9131
+ if (unknownKeys.length > 0) throw new Error(`未知字段:${unknownKeys.join(", ")}(可用:${[...ENTRY_KEYS, "enabled"].join(", ")})`);
9132
+ const { enabled = true,...rest } = record;
9133
+ if (typeof enabled !== "boolean") throw new Error("enabled 必须是布尔值");
9134
+ 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"]}"`);
9135
+ const entry = EntrySchema(rest);
9136
+ if (typeof entry !== "object" || entry === null) throw new Error("条目校验失败");
9137
+ return {
9138
+ entry,
9139
+ enabled
9140
+ };
9141
+ }
9142
+ /** Canonical JSON of one entry (recursively key-sorted) — hash input. */
9143
+ function canonical(value) {
9144
+ if (Array.isArray(value)) return value.map(canonical);
9145
+ 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)]));
9146
+ return value;
9147
+ }
9148
+ function hashEntries(entries) {
9149
+ const payload = Object.keys(entries).sort().map((id) => [
9150
+ id,
9151
+ entries[id].enabled,
9152
+ canonical(entries[id].entry)
9153
+ ]);
9154
+ return createHash("sha256").update(JSON.stringify(payload)).digest("hex").slice(0, 16);
9155
+ }
9156
+ /** Serialize an entry to YAML. Defaults are omitted (`enabled: true`,
9157
+ * `backgroundMode: 'one-shot'`); output is UTF-8 without BOM, unwrapped. */
9158
+ function serializeEntry(entry, enabled = true) {
9159
+ const record = entry;
9160
+ const doc = {};
9161
+ for (const key of [
9162
+ "description",
9163
+ "provider",
9164
+ "model",
9165
+ "subagentProvider",
9166
+ "reasoningEffort",
9167
+ "maxTokens",
9168
+ "persona",
9169
+ "toolFilter",
9170
+ "maxDepth",
9171
+ "backgroundMode"
9172
+ ]) {
9173
+ const value = record[key];
9174
+ if (value === void 0) continue;
9175
+ if (key === "backgroundMode" && value === "one-shot") continue;
9176
+ doc[key] = value;
9177
+ }
9178
+ if (!enabled) doc["enabled"] = false;
9179
+ return stringify(doc, { lineWidth: 0 });
9180
+ }
9181
+ /** The CANONICAL file name for an id — always `.yaml` (SUB-ROSTER-YML-001:
9182
+ * save converges every entry onto this spelling). */
9183
+ const entryFileName = (id) => `${id}.yaml`;
9184
+ /** Every on-disk spelling that can serve one id. `loadRoster` READS both, so
9185
+ * writes and deletes must address both too — a `.yml`-only entry that
9186
+ * survives a delete would resurrect after every restart (SUB-ROSTER-YML-001). */
9187
+ const entryFileNames = (id) => [`${id}.yaml`, `${id}.yml`];
9188
+ /** Atomic single-file write: temp name in the roster dir, then rename with
9189
+ * bounded retries (Windows AV/indexer transiently lock fresh files). */
9190
+ async function writeEntryFile(options) {
9191
+ const fsp = options.fs ?? nodeFsPort;
9192
+ const wait = options.delay ?? defaultDelay;
9193
+ await fsp.mkdir(options.dir, { recursive: true });
9194
+ const target = nodePath.join(options.dir, entryFileName(options.id));
9195
+ const temp = nodePath.join(options.dir, `.${options.id}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`);
9196
+ await fsp.writeFile(temp, serializeEntry(options.entry, options.enabled ?? true));
9197
+ for (let attempt = 0;; attempt += 1) try {
9198
+ await fsp.rename(temp, target);
9199
+ break;
9200
+ } catch (error) {
9201
+ if (attempt >= 2) {
9202
+ await fsp.unlink(temp).catch(() => {});
9203
+ throw error;
9204
+ }
9205
+ await wait(50 * 3 ** attempt);
9206
+ }
9207
+ const ymlSibling = nodePath.join(options.dir, `${options.id}.yml`);
9208
+ for (let attempt = 0;; attempt += 1) try {
9209
+ await fsp.unlink(ymlSibling);
9210
+ break;
9211
+ } catch (error) {
9212
+ if (isEnoent(error)) break;
9213
+ if (attempt >= 2) throw error;
9214
+ await wait(50 * 3 ** attempt);
9215
+ }
9216
+ }
9217
+ /** Remove every on-disk spelling that can serve one id (`.yaml` AND `.yml`);
9218
+ * a missing file is already the desired state (SUB-ROSTER-YML-001). */
9219
+ async function deleteEntryFile(dir, id, fsp = nodeFsPort) {
9220
+ for (const name$1 of entryFileNames(id)) try {
9221
+ await fsp.unlink(nodePath.join(dir, name$1));
9222
+ } catch (error) {
9223
+ if (!isEnoent(error)) throw error;
9224
+ }
9225
+ }
9226
+ /**
9227
+ * Read the whole roster fresh: directory files first (sorted), then legacy
9228
+ * entries that no file shadows. Diagnostics carry every skip reason.
9229
+ */
9230
+ async function loadRoster(options) {
9231
+ const fsp = options.fs ?? nodeFsPort;
9232
+ const diagnostics = [];
9233
+ const entries = {};
9234
+ let names;
9235
+ try {
9236
+ names = (await fsp.readdir(options.dir)).slice().sort();
9237
+ } catch (error) {
9238
+ if (!isEnoent(error)) diagnostics.push({
9239
+ severity: "error",
9240
+ message: `名册目录不可读 ${options.dir}:${String(error)}`
9241
+ });
9242
+ names = [];
9243
+ }
9244
+ const owner = /* @__PURE__ */ new Map();
9245
+ /** Ids whose FILE exists but failed to load. If a legacy copy then serves
9246
+ * the same id, that fallback must be LOUD: delegate would run the stale
9247
+ * settings persona while the user believes their edit is live (A2). */
9248
+ const failedFileIds = /* @__PURE__ */ new Set();
9249
+ for (const name$1 of names) {
9250
+ const lower = name$1.toLowerCase();
9251
+ if (!lower.endsWith(".yaml") && !lower.endsWith(".yml")) continue;
9252
+ const id = lower.endsWith(".yaml") ? lower.slice(0, -5) : lower.slice(0, -4);
9253
+ if (id.startsWith("_")) continue;
9254
+ if (lower !== name$1) {
9255
+ diagnostics.push({
9256
+ severity: "warning",
9257
+ file: name$1,
9258
+ id,
9259
+ message: `文件名必须全小写,已跳过 "${name$1}"`
9260
+ });
9261
+ continue;
9262
+ }
9263
+ const idError = validateEntryId(id);
9264
+ if (idError !== void 0) {
9265
+ diagnostics.push({
9266
+ severity: "error",
9267
+ file: name$1,
9268
+ id,
9269
+ message: idError
9270
+ });
9271
+ continue;
9272
+ }
9273
+ const existing = owner.get(id);
9274
+ if (existing !== void 0) {
9275
+ diagnostics.push({
9276
+ severity: "error",
9277
+ file: name$1,
9278
+ id,
9279
+ message: `与 "${existing}" 解析出相同 id(.yaml/.yml 只能保留一个),已跳过`
9280
+ });
9281
+ continue;
9282
+ }
9283
+ owner.set(id, name$1);
9284
+ let text;
9285
+ try {
9286
+ text = (await fsp.readFile(nodePath.join(options.dir, name$1))).toString("utf8");
9287
+ } catch (error) {
9288
+ diagnostics.push({
9289
+ severity: "error",
9290
+ file: name$1,
9291
+ id,
9292
+ message: `读取失败,条目已跳过:${String(error)}`
9293
+ });
9294
+ owner.delete(id);
9295
+ failedFileIds.add(id);
9296
+ continue;
9297
+ }
9298
+ try {
9299
+ const { entry, enabled } = parseEntryDocument(parse(stripBom(text)));
9300
+ entries[id] = {
9301
+ entry,
9302
+ enabled,
9303
+ source: "file",
9304
+ file: name$1
9305
+ };
9306
+ } catch (error) {
9307
+ diagnostics.push({
9308
+ severity: "error",
9309
+ file: name$1,
9310
+ id,
9311
+ message: `解析或校验失败,条目已跳过:${String(error)}`
9312
+ });
9313
+ failedFileIds.add(id);
9314
+ }
9315
+ }
9316
+ for (const [id, entry] of Object.entries(options.legacy ?? {})) {
9317
+ if (!ENTRY_ID.test(id)) continue;
9318
+ const file = entries[id];
9319
+ if (file !== void 0) {
9320
+ diagnostics.push({
9321
+ severity: "info",
9322
+ id,
9323
+ message: `settings 中的旧条目已被名册文件 "${file.file}" 覆盖(旧条目可从 settings.yaml 删除)`
9324
+ });
9325
+ continue;
9326
+ }
9327
+ if (failedFileIds.has(id)) diagnostics.push({
9328
+ severity: "error",
9329
+ id,
9330
+ message: `名册文件损坏,当前由 settings 旧副本兜底——delegate 使用的是旧配置;修复或删除该文件后恢复文件优先`
9331
+ });
9332
+ entries[id] = {
9333
+ entry,
9334
+ enabled: true,
9335
+ source: "legacy"
9336
+ };
9337
+ }
9338
+ return {
9339
+ dir: options.dir,
9340
+ entries,
9341
+ diagnostics,
9342
+ hash: hashEntries(entries)
9343
+ };
9344
+ }
9345
+ /**
9346
+ * One-time-per-directory, per-entry idempotent migration: every legacy entry
9347
+ * that has no roster file yet (and a valid id) is written to `<id>.yaml`.
9348
+ * Legacy settings entries are intentionally KEPT (rollback copy for users
9349
+ * downgrading the plugin); re-running never duplicates or overwrites.
9350
+ */
9351
+ async function migrateLegacyEntries(options) {
9352
+ const fsp = options.fs ?? nodeFsPort;
9353
+ const diagnostics = [];
9354
+ const imported = [];
9355
+ const skipped = [];
9356
+ let names;
9357
+ try {
9358
+ names = new Set((await fsp.readdir(options.dir)).map((name$1) => name$1.toLowerCase()));
9359
+ } catch (error) {
9360
+ if (!isEnoent(error)) throw error;
9361
+ names = /* @__PURE__ */ new Set();
9362
+ }
9363
+ for (const [id, entry] of Object.entries(options.legacy)) {
9364
+ const idError = validateEntryId(id);
9365
+ if (idError !== void 0) {
9366
+ skipped.push({
9367
+ id,
9368
+ reason: idError
9369
+ });
9370
+ continue;
9371
+ }
9372
+ if (names.has(`${id}.yaml`) || names.has(`${id}.yml`)) {
9373
+ skipped.push({
9374
+ id,
9375
+ reason: "roster file already exists"
9376
+ });
9377
+ continue;
9378
+ }
9379
+ try {
9380
+ await writeEntryFile({
9381
+ dir: options.dir,
9382
+ id,
9383
+ entry,
9384
+ fs: fsp,
9385
+ delay: options.delay
9386
+ });
9387
+ names.add(`${id}.yaml`);
9388
+ imported.push(id);
9389
+ } catch (error) {
9390
+ diagnostics.push({
9391
+ severity: "error",
9392
+ id,
9393
+ message: `迁移写入失败:${String(error)}`
9394
+ });
9395
+ }
9396
+ }
9397
+ return {
9398
+ imported,
9399
+ skipped,
9400
+ diagnostics
9401
+ };
9402
+ }
9403
+
9404
+ //#endregion
9405
+ //#region src/index.ts
9406
+ const name = "subagent-library";
9407
+ const inject = [
9408
+ "subagents",
9409
+ "tools",
9410
+ "systemPrompt"
9411
+ ];
9412
+ const LIBRARY_SECTION_ORDER = 116.6;
9413
+ /** Recursion cap applied when an entry omits maxDepth and the transport can
9414
+ * enforce it — the harness itself imposes no global delegation cap
9415
+ * (resolveChildDepth checks only an explicit value), and the official
9416
+ * subagent tool defaults to 3 to keep chained delegation bounded. */
9417
+ const DEFAULT_MAX_DEPTH = 3;
9073
9418
  const Config = z.object({
9074
9419
  subagentProvider: z.string().default("spawn"),
9420
+ entriesDir: z.string(),
9075
9421
  entries: z.dict(EntrySchema).default({})
9076
9422
  });
9077
9423
  /** Render text blocks from the canonical JSON block array without trusting arbitrary values. */
@@ -9180,9 +9526,8 @@ function apply(ctx, config$1) {
9180
9526
  });
9181
9527
  /** Library entries restricted to schema-consistent ids: a hand-written key
9182
9528
  * 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)));
9529
+ * delegated or deleted, so it is filtered out of every view. */
9530
+ const filterEntries = (raw) => Object.fromEntries(Object.entries(raw ?? {}).filter(([id]) => ENTRY_ID.test(id)));
9186
9531
  const resolveConfig = () => {
9187
9532
  const base = source !== void 0 ? source() : config$1;
9188
9533
  return {
@@ -9190,6 +9535,57 @@ function apply(ctx, config$1) {
9190
9535
  entries: filterEntries(base.entries)
9191
9536
  };
9192
9537
  };
9538
+ const fsPort = () => ctx[kFsPort] ?? nodeFsPort;
9539
+ let migratedDir;
9540
+ let migrationFailure;
9541
+ /** Seed the roster directory from legacy settings entries — exactly once
9542
+ * per directory ON SUCCESS. Per-entry idempotent (existing files are never
9543
+ * touched), and legacy documents are deliberately KEPT in settings as the
9544
+ * rollback copy for users downgrading the plugin (removal planned 0.4.0).
9545
+ * A FAILED migration must NOT latch (red team A5): transient FS errors are
9546
+ * fast-fail and cheap, so every roster read retries until it succeeds —
9547
+ * otherwise a single AV-lock would silently strand entries on the legacy
9548
+ * path until 0.4 removes legacy reading. */
9549
+ const ensureMigrated = async () => {
9550
+ const legacy = resolveConfig().entries ?? {};
9551
+ if (Object.keys(legacy).length === 0) return;
9552
+ const dir = resolveEntriesDir(resolveConfig().entriesDir);
9553
+ if (migratedDir === dir) return;
9554
+ try {
9555
+ const result = await migrateLegacyEntries({
9556
+ dir,
9557
+ legacy,
9558
+ fs: fsPort()
9559
+ });
9560
+ if (result.diagnostics.length === 0) {
9561
+ migratedDir = dir;
9562
+ migrationFailure = void 0;
9563
+ } else migrationFailure = `${result.diagnostics.map((item) => item.message).join(";")}(修复后将自动重试)`;
9564
+ } catch (error) {
9565
+ migrationFailure = `${String(error)}——下次使用名册时自动重试;重启 dsh web 亦可立即重试`;
9566
+ }
9567
+ };
9568
+ /** Fresh roster view for every consumer (tools, command, settings API):
9569
+ * no cache — tens of small files read in milliseconds, and the cache layer
9570
+ * is exactly where mtime/case/rename bugs live (v0.3.0 design review). */
9571
+ const loadLibrary = async () => {
9572
+ if (settingsFailure !== void 0) throw new Error(settingsFailure);
9573
+ const cfg = resolveConfig();
9574
+ await ensureMigrated();
9575
+ const view = await loadRoster({
9576
+ dir: resolveEntriesDir(cfg.entriesDir),
9577
+ legacy: cfg.entries,
9578
+ fs: fsPort()
9579
+ });
9580
+ if (migrationFailure !== void 0) view.diagnostics.unshift({
9581
+ severity: "warning",
9582
+ message: `旧条目自动迁移未完成:${migrationFailure}`
9583
+ });
9584
+ return {
9585
+ subagentProvider: cfg.subagentProvider,
9586
+ view
9587
+ };
9588
+ };
9193
9589
  const MAX_BODY_BYTES = 1 << 20;
9194
9590
  const readJsonBody = async (req) => {
9195
9591
  const chunks = [];
@@ -9261,28 +9657,59 @@ function apply(ctx, config$1) {
9261
9657
  }
9262
9658
  return true;
9263
9659
  };
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;
9270
- };
9271
- const currentView = () => {
9660
+ /** Wire shape of one roster row for the settings editor: the stored entry
9661
+ * plus the enabled flag when false and a `source` marker for legacy rows. */
9662
+ const wireEntries = (view) => Object.fromEntries(Object.entries(view.entries).map(([id, row]) => [id, {
9663
+ ...row.entry,
9664
+ ...row.enabled ? {} : { enabled: false },
9665
+ ...row.source === "legacy" ? { source: "legacy" } : {}
9666
+ }]));
9667
+ /** Legacy settings entries currently shadowed by a roster file — the safe
9668
+ * one-click cleanup set for the 0.2→0.3 transition (a legacy row WITHOUT a
9669
+ * file is still serving and must survive). */
9670
+ const legacyShadowedIds = (view) => {
9272
9671
  const svc = settingsService;
9273
9672
  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) ?? {});
9673
+ if (svc === void 0 || ns === void 0) return [];
9674
+ const raw = (svc.describe().find((row) => row.ns === ns)?.user)?.entries;
9675
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return [];
9676
+ return Object.keys(raw).filter((id) => ENTRY_ID.test(id) && view.entries[id]?.source === "file");
9677
+ };
9678
+ const wireView = async (legacySkipWarning = false) => {
9679
+ const { view } = await loadLibrary();
9680
+ const diagnostics = legacySkipWarning ? [{
9681
+ severity: "warning",
9682
+ message: "设置服务只读:settings 中的旧副本未能同步移除,被删条目可能以旧副本复活"
9683
+ }, ...view.diagnostics] : view.diagnostics;
9278
9684
  return {
9279
- writable: svc.writable,
9280
- revision: descriptor.revision,
9281
- entries
9685
+ ok: true,
9686
+ writable: true,
9687
+ dir: view.dir,
9688
+ hash: view.hash,
9689
+ entries: wireEntries(view),
9690
+ diagnostics,
9691
+ legacyCount: legacyShadowedIds(view).length
9282
9692
  };
9283
9693
  };
9284
9694
  ctx.inject(["webServer"], (wctx) => {
9285
9695
  const web = wctx.webServer;
9696
+ /** Best-effort removal of legacy-only settings entries (the file half is
9697
+ * already gone). No expectedRevision: last-write-wins — a racing settings
9698
+ * writer must not fail a delete that mostly succeeded. Returns whether
9699
+ * the unset actually ran, so a read-only settings service can be surfaced
9700
+ * instead of a silent false success (red team A7 / k3 #4). */
9701
+ const unsetLegacy = async (ids) => {
9702
+ if (ids.length === 0) return "done";
9703
+ const svc = settingsService;
9704
+ const ns = settingsNs;
9705
+ if (svc === void 0 || ns === void 0) return "no-settings";
9706
+ if (!svc.writable) return "skipped-readonly";
9707
+ await svc.mutate(ns, ids.map((id) => ({
9708
+ op: "unset",
9709
+ path: ["entries", id]
9710
+ })));
9711
+ return "done";
9712
+ };
9286
9713
  wctx.effect(() => web.register({
9287
9714
  kind: "exact",
9288
9715
  path: "/subagent-library/api",
@@ -9296,18 +9723,15 @@ function apply(ctx, config$1) {
9296
9723
  });
9297
9724
  return;
9298
9725
  }
9299
- const view = currentView();
9300
- if (view === null) {
9301
- sendJson(res, 503, {
9726
+ try {
9727
+ sendJson(res, 200, await wireView());
9728
+ } catch (error) {
9729
+ sendJson(res, 500, {
9302
9730
  ok: false,
9303
- error: "not-ready"
9731
+ error: "roster-unreadable",
9732
+ message: String(error)
9304
9733
  });
9305
- return;
9306
9734
  }
9307
- sendJson(res, 200, {
9308
- ok: true,
9309
- ...view
9310
- });
9311
9735
  return;
9312
9736
  }
9313
9737
  if (req.method !== "POST") {
@@ -9318,6 +9742,14 @@ function apply(ctx, config$1) {
9318
9742
  return;
9319
9743
  }
9320
9744
  if (!guardWrite(req, res)) return;
9745
+ if (settingsFailure !== void 0) {
9746
+ sendJson(res, 503, {
9747
+ ok: false,
9748
+ error: "not-ready",
9749
+ message: settingsFailure
9750
+ });
9751
+ return;
9752
+ }
9321
9753
  const read = await readJsonBody(req);
9322
9754
  if (!read.ok) {
9323
9755
  if (read.error === "too-large") sendJson(res, 413, {
@@ -9331,26 +9763,38 @@ function apply(ctx, config$1) {
9331
9763
  return;
9332
9764
  }
9333
9765
  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;
9766
+ const rawHash = body["expectedHash"];
9767
+ const expectedHash = typeof rawHash === "string" ? rawHash : void 0;
9352
9768
  try {
9353
- if (body["op"] === "delete") {
9769
+ const { view: current } = await loadLibrary();
9770
+ if (expectedHash !== void 0 && expectedHash !== current.hash) {
9771
+ sendJson(res, 409, {
9772
+ ok: false,
9773
+ error: "conflict",
9774
+ view: {
9775
+ ok: true,
9776
+ writable: true,
9777
+ dir: current.dir,
9778
+ hash: current.hash,
9779
+ entries: wireEntries(current),
9780
+ diagnostics: current.diagnostics,
9781
+ legacyCount: legacyShadowedIds(current).length
9782
+ }
9783
+ });
9784
+ return;
9785
+ }
9786
+ if (body["op"] === "clear-legacy") {
9787
+ const svc = settingsService;
9788
+ if (svc !== void 0 && !svc.writable) {
9789
+ sendJson(res, 403, {
9790
+ ok: false,
9791
+ error: "readonly",
9792
+ message: "设置服务只读,无法清除旧副本"
9793
+ });
9794
+ return;
9795
+ }
9796
+ await unsetLegacy(legacyShadowedIds(current));
9797
+ } else if (body["op"] === "delete") {
9354
9798
  const id = typeof body["id"] === "string" ? body["id"] : "";
9355
9799
  if (!ENTRY_ID.test(id)) {
9356
9800
  sendJson(res, 400, {
@@ -9359,10 +9803,9 @@ function apply(ctx, config$1) {
9359
9803
  });
9360
9804
  return;
9361
9805
  }
9362
- await svc.mutate(ns, [{
9363
- op: "unset",
9364
- path: ["entries", id]
9365
- }], expectedRevision);
9806
+ await deleteEntryFile(current.dir, id, fsPort());
9807
+ sendJson(res, 200, await wireView(await unsetLegacy([id]) === "skipped-readonly"));
9808
+ return;
9366
9809
  } else if (body["op"] === "save") {
9367
9810
  const entries = body["entries"];
9368
9811
  if (typeof entries !== "object" || entries === null || Array.isArray(entries)) {
@@ -9373,24 +9816,49 @@ function apply(ctx, config$1) {
9373
9816
  return;
9374
9817
  }
9375
9818
  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`
9819
+ const validated = /* @__PURE__ */ new Map();
9820
+ for (const [id, value] of Object.entries(candidate)) {
9821
+ const idError = validateEntryId(id);
9822
+ if (idError !== void 0) {
9823
+ sendJson(res, 400, {
9824
+ ok: false,
9825
+ error: "invalid-entry-id",
9826
+ message: idError
9827
+ });
9828
+ return;
9829
+ }
9830
+ const payload = { ...value };
9831
+ delete payload["source"];
9832
+ try {
9833
+ validated.set(id, parseEntryDocument(payload));
9834
+ } catch (error) {
9835
+ sendJson(res, 400, {
9836
+ ok: false,
9837
+ error: "rejected",
9838
+ message: `条目 "${id}":${String(error)}`
9839
+ });
9840
+ return;
9841
+ }
9842
+ }
9843
+ for (const [id, doc] of validated) {
9844
+ const prev = current.entries[id];
9845
+ if (prev?.source === "file" && serializeEntry(prev.entry, prev.enabled) === serializeEntry(doc.entry, doc.enabled)) continue;
9846
+ await writeEntryFile({
9847
+ dir: current.dir,
9848
+ id,
9849
+ entry: doc.entry,
9850
+ enabled: doc.enabled,
9851
+ fs: fsPort()
9382
9852
  });
9383
- return;
9384
9853
  }
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);
9854
+ const deletedIds = [];
9855
+ for (const [id, row] of Object.entries(current.entries)) {
9856
+ if (validated.has(id)) continue;
9857
+ deletedIds.push(id);
9858
+ if (row.source === "file") await deleteEntryFile(current.dir, id, fsPort());
9859
+ }
9860
+ sendJson(res, 200, await wireView(await unsetLegacy(deletedIds) === "skipped-readonly"));
9861
+ return;
9394
9862
  } else {
9395
9863
  sendJson(res, 400, {
9396
9864
  ok: false,
@@ -9398,28 +9866,12 @@ function apply(ctx, config$1) {
9398
9866
  });
9399
9867
  return;
9400
9868
  }
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
- });
9869
+ sendJson(res, 200, await wireView());
9413
9870
  } catch (error) {
9414
- const message = String(error);
9415
- if (error.code === "SETTINGS_CONFLICT") sendJson(res, 409, {
9871
+ sendJson(res, 500, {
9416
9872
  ok: false,
9417
- error: "conflict"
9418
- });
9419
- else sendJson(res, 400, {
9420
- ok: false,
9421
- error: "rejected",
9422
- message
9873
+ error: "write-failed",
9874
+ message: String(error)
9423
9875
  });
9424
9876
  }
9425
9877
  }
@@ -9453,12 +9905,13 @@ function apply(ctx, config$1) {
9453
9905
  isConcurrencySafe: () => true,
9454
9906
  async execute(_args, exec) {
9455
9907
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9456
- const lib = resolveConfig();
9908
+ const { view } = await loadLibrary();
9457
9909
  const agent = exec.agent;
9458
9910
  /** The catalog must not advertise a filter this session cannot apply:
9459
9911
  * summarize the SANITIZED filter and list what was ignored, so the model
9460
9912
  * sees the same tool scope delegation will actually produce. */
9461
- const filterSummary = (entry) => {
9913
+ const filterSummary = (row) => {
9914
+ const entry = row.entry;
9462
9915
  if (entry.toolFilter === void 0) return void 0;
9463
9916
  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
9917
  if (agent === void 0) return declared;
@@ -9466,17 +9919,21 @@ function apply(ctx, config$1) {
9466
9919
  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
9920
  return dropped.length > 0 ? `${effective} 忽略:[${dropped.map((item) => item.name).join(", ")}]` : effective;
9468
9921
  };
9469
- return Object.entries(lib.entries).map(([id, entry]) => {
9470
- const summary = filterSummary(entry);
9922
+ const rows = Object.entries(view.entries).map(([id, row]) => {
9923
+ const summary = filterSummary(row);
9471
9924
  return {
9472
9925
  id,
9473
- description: entry.description,
9474
- provider: entry.provider ?? "(session default)",
9475
- model: entry.model ?? "(session default)",
9476
- backgroundMode: entry.backgroundMode ?? "one-shot",
9926
+ description: row.entry.description,
9927
+ provider: row.entry.provider ?? "(session default)",
9928
+ model: row.entry.model ?? "(session default)",
9929
+ backgroundMode: row.entry.backgroundMode ?? "one-shot",
9930
+ ...row.enabled ? {} : { enabled: false },
9477
9931
  ...summary !== void 0 ? { toolFilter: summary } : {}
9478
9932
  };
9479
9933
  });
9934
+ const catalogDiagnostics = view.diagnostics.filter((item) => item.severity !== "info");
9935
+ if (catalogDiagnostics.length > 0) rows.push({ diagnostics: catalogDiagnostics.map((item) => `${item.severity}${item.id !== void 0 ? ` [${item.id}]` : ""}: ${item.message}`) });
9936
+ return rows;
9480
9937
  }
9481
9938
  }));
9482
9939
  ctx.tools.register(defineTool({
@@ -9531,14 +9988,16 @@ function apply(ctx, config$1) {
9531
9988
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9532
9989
  const parent = exec.agent;
9533
9990
  if (!parent) throw new Error("delegate tool requires a calling agent (exec.agent was undefined)");
9534
- const lib = resolveConfig();
9991
+ const { subagentProvider: defaultProvider, view } = await loadLibrary();
9535
9992
  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);
9993
+ const row = Object.hasOwn(view.entries, args.library_id) ? view.entries[args.library_id] : void 0;
9994
+ if (row === void 0) {
9995
+ const ids = Object.keys(view.entries);
9539
9996
  throw new Error(`subagent library has no entry "${args.library_id}"${ids.length ? ` (available: ${ids.join(", ")})` : " (library is empty)"}`);
9540
9997
  }
9541
- const subagentProviderName = entry.subagentProvider ?? lib.subagentProvider;
9998
+ 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`);
9999
+ const entry = row.entry;
10000
+ const subagentProviderName = entry.subagentProvider ?? defaultProvider;
9542
10001
  const transport = ctx.subagents.getProvider(subagentProviderName);
9543
10002
  if (transport === void 0) throw new Error(`subagent transport provider "${subagentProviderName}" is not registered (available: ${ctx.subagents.list().join(", ") || "none"})`);
9544
10003
  const continuable = entry.backgroundMode === "continuable";
@@ -9554,9 +10013,10 @@ function apply(ctx, config$1) {
9554
10013
  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
10014
  if (entry.toolFilter !== void 0 && !transport.capabilities.toolFilter) throw new Error(`delegate: transport "${subagentProviderName}" cannot apply a tool filter (no toolFilter capability)`);
9556
10015
  }
9557
- const agentOptions = entry.provider !== void 0 || entry.model !== void 0 || entry.maxTokens !== void 0 ? {
10016
+ const agentOptions = entry.provider !== void 0 || entry.model !== void 0 || entry.maxTokens !== void 0 || entry.reasoningEffort !== void 0 ? {
9558
10017
  ...entry.provider !== void 0 ? { provider: entry.provider } : {},
9559
10018
  ...entry.model !== void 0 ? { model: entry.model } : {},
10019
+ ...entry.reasoningEffort !== void 0 ? { reasoningEffort: entry.reasoningEffort } : {},
9560
10020
  ...entry.maxTokens !== void 0 ? { maxTokens: entry.maxTokens } : {}
9561
10021
  } : void 0;
9562
10022
  const request = {
@@ -9625,15 +10085,23 @@ function apply(ctx, config$1) {
9625
10085
  if (commands !== void 0) commands.register({
9626
10086
  name: "subagent",
9627
10087
  description: "List the subagent library entries",
9628
- handler: () => {
9629
- const lib = resolveConfig();
9630
- const ids = Object.keys(lib.entries);
10088
+ handler: async () => {
10089
+ const { view } = await loadLibrary();
10090
+ const ids = Object.keys(view.entries);
10091
+ const lines = ids.map((id) => {
10092
+ const row = view.entries[id];
10093
+ const tags = [
10094
+ `${row.entry.provider ?? "默认模型路由"}/${row.entry.model ?? "默认模型"}`,
10095
+ row.entry.backgroundMode === "continuable" ? "可续聊" : "",
10096
+ row.source === "legacy" ? "legacy" : "",
10097
+ row.enabled ? "" : "已停用"
10098
+ ].filter(Boolean).join(",");
10099
+ return `- ${id}: ${row.entry.description} [${tags}]`;
10100
+ });
10101
+ const diagnosticLines = view.diagnostics.filter((item) => item.severity !== "info").map((item) => ` ! ${item.severity}${item.id !== void 0 ? ` [${item.id}]` : ""}: ${item.message}`);
9631
10102
  return {
9632
10103
  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")
10104
+ 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
10105
  };
9638
10106
  }
9639
10107
  });