dsh-subagent-library 0.3.0 → 0.3.2

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
@@ -309,7 +309,7 @@ function CallId(id) {
309
309
  * @param value - the value to freeze in place.
310
310
  * @returns the same value, frozen.
311
311
  */
312
- function deepFreeze$1(value) {
312
+ function deepFreeze(value) {
313
313
  const seen = /* @__PURE__ */ new WeakSet();
314
314
  const pending = [{
315
315
  kind: "visit",
@@ -3056,7 +3056,7 @@ function failureMessageFromContent(content) {
3056
3056
  function materializePresentation(candidate) {
3057
3057
  const detached = snapshotJsonValue(candidate);
3058
3058
  if (detached === void 0) throw new TypeError("tool result must be losslessly JSON-serializable");
3059
- return deepFreeze$1(detached);
3059
+ return deepFreeze(detached);
3060
3060
  }
3061
3061
  /** Structured `{ name, code }` for a thrown HarnessError, else undefined. */
3062
3062
  function errorInfo(error) {
@@ -3604,7 +3604,7 @@ var ToolRuntime = class extends Service {
3604
3604
  if (detached === void 0) throw new TypeError("tool execution arguments must be losslessly JSON-serializable");
3605
3605
  const execution = {
3606
3606
  ...base,
3607
- arguments: deepFreeze$1(detached)
3607
+ arguments: deepFreeze(detached)
3608
3608
  };
3609
3609
  this.deferredContexts.set(execution, deferredContexts);
3610
3610
  this.contentFinalizers.set(execution, finalizerFor());
@@ -3964,7 +3964,7 @@ var ToolRuntime = class extends Service {
3964
3964
  const detached = snapshotToolValue(tool.name, candidate);
3965
3965
  const violations = validateJsonSchemaValue(tool.output.schema, detached, "value");
3966
3966
  if (violations.length > 0) throw new ToolOutputError(tool.name, violations);
3967
- const value = deepFreeze$1(detached);
3967
+ const value = deepFreeze(detached);
3968
3968
  let rendered;
3969
3969
  try {
3970
3970
  rendered = tool.output.render(exec.arguments, value);
@@ -4021,7 +4021,7 @@ var ToolRuntime = class extends Service {
4021
4021
  error: result.error,
4022
4022
  ...presentation
4023
4023
  });
4024
- return deepFreeze$1({
4024
+ return deepFreeze({
4025
4025
  ...materializePresentation({
4026
4026
  isError: false,
4027
4027
  ...presentation,
@@ -4283,7 +4283,7 @@ const allowsEval = /* @__PURE__ */ cached(() => {
4283
4283
  return false;
4284
4284
  }
4285
4285
  });
4286
- function isPlainObject$1(o) {
4286
+ function isPlainObject(o) {
4287
4287
  if (isObject(o) === false) return false;
4288
4288
  const ctor = o.constructor;
4289
4289
  if (ctor === void 0) return true;
@@ -4294,7 +4294,7 @@ function isPlainObject$1(o) {
4294
4294
  return true;
4295
4295
  }
4296
4296
  function shallowClone(o) {
4297
- if (isPlainObject$1(o)) return { ...o };
4297
+ if (isPlainObject(o)) return { ...o };
4298
4298
  if (Array.isArray(o)) return [...o];
4299
4299
  if (o instanceof Map) return new Map(o);
4300
4300
  if (o instanceof Set) return new Set(o);
@@ -4377,7 +4377,7 @@ function omit(schema, mask) {
4377
4377
  }));
4378
4378
  }
4379
4379
  function extend(schema, shape) {
4380
- 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");
4381
4381
  const checks = schema._zod.def.checks;
4382
4382
  if (checks && checks.length > 0) {
4383
4383
  const existingShape = schema._zod.def.shape;
@@ -4393,7 +4393,7 @@ function extend(schema, shape) {
4393
4393
  } }));
4394
4394
  }
4395
4395
  function safeExtend(schema, shape) {
4396
- 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");
4397
4397
  return clone(schema, mergeDefs(schema._zod.def, { get shape() {
4398
4398
  const _shape = {
4399
4399
  ...schema._zod.def.shape,
@@ -5983,7 +5983,7 @@ function mergeValues(a, b) {
5983
5983
  valid: true,
5984
5984
  data: a
5985
5985
  };
5986
- if (isPlainObject$1(a) && isPlainObject$1(b)) {
5986
+ if (isPlainObject(a) && isPlainObject(b)) {
5987
5987
  const bKeys = Object.keys(b);
5988
5988
  const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
5989
5989
  const newObj = {
@@ -8455,597 +8455,6 @@ async function settleRun(run) {
8455
8455
  return outcome;
8456
8456
  }
8457
8457
 
8458
- //#endregion
8459
- //#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
8460
- /**
8461
- * Structural secret redaction for settings values. `role('secret')` fields are
8462
- * removed from a value before it crosses a wire boundary; a sidecar records
8463
- * each schema-declared secret position and whether it currently holds a value,
8464
- * so a configuration surface can render a write-only input without ever
8465
- * receiving the secret itself.
8466
- * @module @deepseek-ai/dsh-settings/redact
8467
- */
8468
- /** Whether a value is a plain data object the walker may recurse into. */
8469
- function isRecord(value) {
8470
- return typeof value === "object" && value !== null && !Array.isArray(value);
8471
- }
8472
- function walk(node, value, path, secrets) {
8473
- if (node === void 0) return value;
8474
- if (node.meta?.role === "secret") {
8475
- secrets.push({
8476
- path,
8477
- set: value !== void 0
8478
- });
8479
- return;
8480
- }
8481
- switch (node.type) {
8482
- case "object": {
8483
- const properties = node.dict ?? {};
8484
- const source = isRecord(value) ? value : void 0;
8485
- const rebuilt = {};
8486
- if (source !== void 0) for (const [key, entry] of Object.entries(source)) {
8487
- if (key in properties) continue;
8488
- rebuilt[key] = entry;
8489
- }
8490
- for (const [key, child] of Object.entries(properties)) {
8491
- const stripped = walk(child, source?.[key], [...path, key], secrets);
8492
- if (stripped !== void 0) rebuilt[key] = stripped;
8493
- }
8494
- return source === void 0 && Object.keys(rebuilt).length === 0 ? value : rebuilt;
8495
- }
8496
- case "dict": {
8497
- if (!isRecord(value)) return value;
8498
- const rebuilt = {};
8499
- for (const [key, entry] of Object.entries(value)) {
8500
- const stripped = walk(node.inner, entry, [...path, key], secrets);
8501
- if (stripped !== void 0) rebuilt[key] = stripped;
8502
- }
8503
- return rebuilt;
8504
- }
8505
- case "array":
8506
- if (!Array.isArray(value)) return value;
8507
- return value.map((entry, index) => walk(node.inner, entry, [...path, String(index)], secrets));
8508
- default: return value;
8509
- }
8510
- }
8511
- /**
8512
- * Remove every `role('secret')` field a schema declares from a value. The
8513
- * walker follows `object`, `dict`, and `array` containers; a secret must be
8514
- * declared directly on a field reachable through those containers (a secret
8515
- * buried inside a union branch or transform is not reachable and must not be
8516
- * modeled that way). The input is never mutated.
8517
- * @param schema - live schemastery schema describing the value.
8518
- * @param value - the value to strip; `undefined` yields an empty record with
8519
- * object-property secret slots still enumerated.
8520
- * @returns the stripped detached value and the ordered secret positions.
8521
- */
8522
- function redactSecrets(schema, value) {
8523
- const secrets = [];
8524
- return {
8525
- value: walk(schema, value, [], secrets),
8526
- secrets
8527
- };
8528
- }
8529
- /**
8530
- * Service Definition for the user-settings capability seam (`ctx.settings`). Providers store one raw document of
8531
- * per-namespace sections; plugins register a namespace schema and read the
8532
- * resolved value, which layers schema defaults, the registrant's composition
8533
- * `base`, and the user document section, in that order.
8534
- * @module @deepseek-ai/dsh-settings
8535
- */
8536
- const NAMESPACE_PATTERN = /^[a-z][a-z0-9-]*$/;
8537
- /**
8538
- * Brand a raw string as a {@link SettingsNamespace}.
8539
- * @param value - candidate namespace; lowercase kebab-case, as in plugin short names.
8540
- * @returns the branded namespace.
8541
- */
8542
- function settingsNamespace(value) {
8543
- if (!NAMESPACE_PATTERN.test(value)) throw new TypeError(`settings namespace "${value}" must match ${String(NAMESPACE_PATTERN)}`);
8544
- return value;
8545
- }
8546
- /**
8547
- * Deep equality over JSON-compatible data (objects, arrays, primitives) — the
8548
- * Service Definition's single change-detection predicate, exported so the invariant
8549
- * companion checks exactly the implementation's relation.
8550
- * @param a - one JSON-compatible value.
8551
- * @param b - the other JSON-compatible value.
8552
- * @returns whether the two values are structurally equal.
8553
- */
8554
- function deepEqualJson(a, b) {
8555
- if (a === b) return true;
8556
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
8557
- if (Array.isArray(a) || Array.isArray(b)) {
8558
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
8559
- return a.every((entry, index) => deepEqualJson(entry, b[index]));
8560
- }
8561
- const left = a;
8562
- const right = b;
8563
- const keys = Object.keys(left);
8564
- if (keys.length !== Object.keys(right).length) return false;
8565
- return keys.every((key) => key in right && deepEqualJson(left[key], right[key]));
8566
- }
8567
- /**
8568
- * A write refused because the namespace moved since the caller read it. The
8569
- * Service Definition's serialized write queue orders writes; it cannot tell a fresh writer
8570
- * from one holding a stale snapshot, which is what this reports.
8571
- */
8572
- var SettingsConflictError = class extends Error {
8573
- /** Stable machine code for wire layers mapping this to their own taxonomy. */
8574
- code = "SETTINGS_CONFLICT";
8575
- /** The revision the write expected. */
8576
- expected;
8577
- /** The revision the namespace actually stands at. */
8578
- actual;
8579
- /**
8580
- * @param ns - the namespace whose write was refused.
8581
- * @param expected - the revision the caller sent.
8582
- * @param actual - the revision now stored.
8583
- */
8584
- constructor(ns, expected, actual) {
8585
- super(`settings namespace "${ns}" changed since it was read (expected revision ${String(expected)}, now ${String(actual)})`);
8586
- this.name = "SettingsConflictError";
8587
- this.expected = expected;
8588
- this.actual = actual;
8589
- }
8590
- };
8591
- /** Whether a value is a plain data object (not an array, null, or class instance). */
8592
- function isPlainObject(value) {
8593
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
8594
- const proto = Object.getPrototypeOf(value);
8595
- return proto === Object.prototype || proto === null;
8596
- }
8597
- /** Apply one path op to a detached section, returning the next section. */
8598
- function applyPathOp(section, op) {
8599
- const [head, ...rest] = op.path;
8600
- if (head === void 0) {
8601
- if (op.op === "unset") return {};
8602
- if (!isPlainObject(op.value)) throw new TypeError("settings mutate: setting the section root requires a plain object");
8603
- return { ...op.value };
8604
- }
8605
- if (rest.length === 0) {
8606
- if (op.op === "set") return {
8607
- ...section,
8608
- [head]: op.value
8609
- };
8610
- const { [head]: _removed,...kept } = section;
8611
- return kept;
8612
- }
8613
- const child = section[head];
8614
- if (!isPlainObject(child)) {
8615
- if (op.op === "unset") return section;
8616
- return {
8617
- ...section,
8618
- [head]: applyPathOp({}, {
8619
- ...op,
8620
- path: rest
8621
- })
8622
- };
8623
- }
8624
- return {
8625
- ...section,
8626
- [head]: applyPathOp(child, {
8627
- ...op,
8628
- path: rest
8629
- })
8630
- };
8631
- }
8632
- /** Human label for a value that lossless JSON cannot represent (numbers reject inline). */
8633
- function describeRejected(value) {
8634
- if (value === void 0) return "undefined";
8635
- if (typeof value === "object" && value !== null) {
8636
- const name$1 = Object.getPrototypeOf(value)?.constructor?.name;
8637
- return name$1 === void 0 || name$1 === "Object" ? "a non-plain object" : `a ${name$1}`;
8638
- }
8639
- return `a ${typeof value}`;
8640
- }
8641
- /**
8642
- * Detach and validate one write input in a single walk before persistence:
8643
- * only JSON data (plain objects, arrays, strings, finite numbers,
8644
- * booleans, `null`) may reach a provider document. `structuredClone` alone
8645
- * would admit Dates, Maps, BigInts, and cycles that YAML/JSON storage then
8646
- * silently distorts on the reload round-trip. `undefined` entries in objects
8647
- * are skipped — the same sparse-patch semantics as {@link mergeLayers} — while
8648
- * an `undefined` array entry is rejected rather than coerced.
8649
- * @param root - plain-object write input (caller-checked).
8650
- * @param reject - builds the validation error from a value label and its `$`-rooted path.
8651
- * @returns the detached JSON-compatible clone.
8652
- */
8653
- function cloneJsonShaped(root, reject) {
8654
- const visiting = /* @__PURE__ */ new WeakSet();
8655
- const clone$1 = (value, path) => {
8656
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
8657
- if (typeof value === "number") {
8658
- if (!Number.isFinite(value)) throw reject("a non-finite number", path);
8659
- return value;
8660
- }
8661
- if (Array.isArray(value)) {
8662
- if (visiting.has(value)) throw reject("a circular reference", path);
8663
- visiting.add(value);
8664
- const entries = value.map((entry, index) => clone$1(entry, `${path}[${index}]`));
8665
- visiting.delete(value);
8666
- return entries;
8667
- }
8668
- if (isPlainObject(value)) {
8669
- if (visiting.has(value)) throw reject("a circular reference", path);
8670
- visiting.add(value);
8671
- const out = {};
8672
- for (const [key, entry] of Object.entries(value)) {
8673
- if (entry === void 0) continue;
8674
- out[key] = clone$1(entry, `${path}.${key}`);
8675
- }
8676
- visiting.delete(value);
8677
- return out;
8678
- }
8679
- throw reject(describeRejected(value), path);
8680
- };
8681
- return clone$1(root, "$");
8682
- }
8683
- /**
8684
- * Layer `over` onto `under`: plain objects merge recursively, every other
8685
- * value (arrays included) replaces the lower layer wholesale. `over` never
8686
- * carries `undefined` entries — sections come from parsed documents and write
8687
- * snapshots pass {@link cloneJsonShaped}, which strips them so a sparse patch
8688
- * cannot erase lower keys.
8689
- */
8690
- function mergeLayers(under, over) {
8691
- if (over === void 0) return under;
8692
- if (!isPlainObject(under) || !isPlainObject(over)) return over;
8693
- const merged = { ...under };
8694
- for (const [key, value] of Object.entries(over)) merged[key] = key in merged ? mergeLayers(merged[key], value) : value;
8695
- return merged;
8696
- }
8697
- /** Recursively freeze one resolved value so handed-out snapshots stay immutable. */
8698
- function deepFreeze(value) {
8699
- if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
8700
- for (const entry of Object.values(value)) deepFreeze(entry);
8701
- return Object.freeze(value);
8702
- }
8703
- /**
8704
- * Abstract settings service. Providers implement raw-document storage
8705
- * (`load`/`persist`) and push external changes through {@link Settings.publish};
8706
- * the base class owns namespace registration, resolution, validation, change
8707
- * detection, and the `settings/updated` commit event.
8708
- */
8709
- var SettingsProvider = class extends Service {
8710
- registrations = /* @__PURE__ */ new Map();
8711
- /** Latest published raw document; empty until the provider's first publish. */
8712
- document = {};
8713
- /** Per-namespace write chains; settled tails, so a failure never poisons the queue. */
8714
- writeQueues = /* @__PURE__ */ new Map();
8715
- /** In-flight watcher invocation segments, drained by the dispose teardown. */
8716
- pendingTails = /* @__PURE__ */ new Set();
8717
- /** Set at service dispose: refuse new writes while queued ones drain. */
8718
- stopped = false;
8719
- /** Opaque read of {@link stopped}: control flow cannot narrow it across awaits. */
8720
- isStopped() {
8721
- return this.stopped;
8722
- }
8723
- constructor(ctx) {
8724
- super(ctx, "settings");
8725
- }
8726
- /**
8727
- * Load the provider's document once and publish it before the service
8728
- * becomes injectable, and register the write-drain teardown. Providers with
8729
- * their own init (watchers, connections) delegate here first via
8730
- * `yield* super[Service.init]()`; their disposers then run before the drain.
8731
- */
8732
- async *[Service.init]() {
8733
- yield async () => {
8734
- this.stopped = true;
8735
- await Promise.allSettled([...this.writeQueues.values(), ...this.pendingTails]);
8736
- };
8737
- this.publish(await this.load());
8738
- }
8739
- /**
8740
- * Absolute path of the provider's user-editable document, when its storage
8741
- * is one local file. Configuration surfaces use this only as availability
8742
- * metadata; the guarded open operation resolves the path again Host-side.
8743
- * Non-file providers leave it undefined and expose no open-document affordance.
8744
- * @returns the absolute local document path, or undefined for non-file storage.
8745
- */
8746
- get documentPath() {}
8747
- /**
8748
- * Prepare the provider's user-editable document for a native editor. File
8749
- * providers may materialize an absent document before returning its path;
8750
- * non-file providers return undefined.
8751
- * @returns the absolute local document path, or undefined for non-file storage.
8752
- */
8753
- prepareDocument() {
8754
- return Promise.resolve(this.documentPath);
8755
- }
8756
- /**
8757
- * Register a namespace schema and receive its owner scope. The registration
8758
- * is an effect on the calling plugin's fiber: disposing that fiber removes
8759
- * the namespace and its observers. An invalid stored section fails the
8760
- * registration itself — the earliest point where the schema can judge it.
8761
- * @param ns - unique namespace; duplicate registration fails loud.
8762
- * @param schema - schemastery schema resolving this namespace's value.
8763
- * @param options - composition `base` layer and effect timing.
8764
- * @returns the owner scope for reads, observation, and updates.
8765
- */
8766
- register(ns, schema, options) {
8767
- if (this.registrations.has(ns)) throw new Error(`settings namespace "${ns}" is already registered`);
8768
- const registration = {
8769
- ns,
8770
- schema,
8771
- base: options?.base,
8772
- applies: options?.applies ?? "live",
8773
- ...options?.validate === void 0 ? {} : { validate: options.validate },
8774
- resolved: deepFreeze(this.resolve(schema, options?.base, this.section(ns), options?.validate)),
8775
- revision: 0,
8776
- watchers: /* @__PURE__ */ new Set()
8777
- };
8778
- this.ctx.effect(() => {
8779
- this.registrations.set(ns, registration);
8780
- return () => this.registrations.delete(ns);
8781
- }, `settings.register(${JSON.stringify(String(ns))})`);
8782
- return {
8783
- get: () => registration.resolved,
8784
- watch: (callback) => {
8785
- const watcher = {
8786
- callback,
8787
- tail: Promise.resolve(),
8788
- active: true
8789
- };
8790
- registration.watchers.add(watcher);
8791
- return () => {
8792
- watcher.active = false;
8793
- registration.watchers.delete(watcher);
8794
- };
8795
- },
8796
- update: (patch) => this.update(ns, patch),
8797
- replace: (section) => this.replace(ns, section)
8798
- };
8799
- }
8800
- /**
8801
- * Describe every registered namespace for configuration surfaces, including
8802
- * the composition `base` and raw user layers so a form can mark which fields
8803
- * the user overrode (presence in `user`) and what a reset returns to.
8804
- * @param options - redaction switch; wire surfaces must redact.
8805
- * @returns one descriptor per registered namespace, in registration order.
8806
- */
8807
- describe(options) {
8808
- return [...this.registrations.values()].map((registration) => {
8809
- let user;
8810
- try {
8811
- user = this.section(registration.ns);
8812
- } catch {
8813
- user = void 0;
8814
- }
8815
- const base = registration.base === void 0 ? void 0 : structuredClone(registration.base);
8816
- const detachedUser = user === void 0 ? void 0 : structuredClone(user);
8817
- const descriptor = {
8818
- ns: registration.ns,
8819
- schema: registration.schema.toJSON(),
8820
- value: registration.resolved,
8821
- revision: registration.revision,
8822
- ...base === void 0 ? {} : { base },
8823
- ...detachedUser === void 0 ? {} : { user: detachedUser },
8824
- applies: registration.applies
8825
- };
8826
- if (options?.redactSecrets !== true) return descriptor;
8827
- const schema = registration.schema;
8828
- const redacted = redactSecrets(schema, registration.resolved);
8829
- return {
8830
- ...descriptor,
8831
- value: redacted.value,
8832
- ...base === void 0 ? {} : { base: redactSecrets(schema, base).value },
8833
- ...detachedUser === void 0 ? {} : { user: redactSecrets(schema, detachedUser).value },
8834
- secrets: redacted.secrets
8835
- };
8836
- });
8837
- }
8838
- /**
8839
- * Read one registered namespace's resolved value.
8840
- * @param ns - the namespace to read.
8841
- * @returns the resolved value, or `undefined` while unregistered.
8842
- */
8843
- get(ns) {
8844
- return this.registrations.get(ns)?.resolved;
8845
- }
8846
- /**
8847
- * Merge a patch into one registered namespace's user layer, validate the
8848
- * resolved candidate, persist through the provider, then commit and emit.
8849
- * A validation failure rejects before anything is persisted. Writes to one
8850
- * namespace are serialized: concurrent updates apply in call order, each
8851
- * merging over the previous write's committed section.
8852
- * @param ns - the registered namespace to update.
8853
- * @param patch - plain-object patch over the user section.
8854
- * @param expectedRevision - the descriptor `revision` the caller read; a
8855
- * namespace that moved past it rejects with {@link SettingsConflictError}.
8856
- */
8857
- async update(ns, patch, expectedRevision) {
8858
- return this.write(ns, patch, "merge", expectedRevision);
8859
- }
8860
- /**
8861
- * Replace one registered namespace's user section wholesale, validate,
8862
- * persist, then commit and emit. Keys absent from `section` fall back to the
8863
- * composition `base` and schema defaults — this is the removal/reset path a
8864
- * merge-only patch cannot express (`replace({})` re-inherits everything).
8865
- * @param ns - the registered namespace to replace.
8866
- * @param section - the complete next user section.
8867
- * @param expectedRevision - the descriptor `revision` the caller read; a
8868
- * namespace that moved past it rejects with {@link SettingsConflictError}.
8869
- */
8870
- async replace(ns, section, expectedRevision) {
8871
- return this.write(ns, section, "replace", expectedRevision);
8872
- }
8873
- /**
8874
- * Apply path-addressed edits to one registered namespace's user section,
8875
- * validate, persist, then commit and emit. The ops are applied to the
8876
- * section as it stands when the write reaches the front of the queue, so a
8877
- * caller never has to restate fields it did not touch — and, crucially,
8878
- * cannot delete fields it never saw. This is the write path for any caller
8879
- * holding a redacted view; `replace` remains the wholesale reset.
8880
- * @param ns - the registered namespace to edit.
8881
- * @param ops - ordered path edits; later ops observe earlier ones.
8882
- * @param expectedRevision - the descriptor `revision` the caller read; a
8883
- * namespace that moved past it rejects with {@link SettingsConflictError}.
8884
- */
8885
- async mutate(ns, ops, expectedRevision) {
8886
- if (!Array.isArray(ops)) throw new TypeError(`settings mutate for "${ns}" must be an array of path ops`);
8887
- for (const op of ops) {
8888
- if (!isPlainObject(op) || op["op"] !== "set" && op["op"] !== "unset") throw new TypeError(`settings mutate for "${ns}" ops must be {op:'set'|'unset', path}`);
8889
- 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`);
8890
- }
8891
- return this.write(ns, ops, "mutate", expectedRevision);
8892
- }
8893
- /** Validate a write, then queue it on the namespace's serialized write chain. */
8894
- write(ns, input, mode, expectedRevision) {
8895
- const verb = mode === "merge" ? "update" : mode === "replace" ? "replace" : "mutate";
8896
- const registration = this.registrations.get(ns);
8897
- if (registration === void 0) throw new Error(`settings namespace "${ns}" is not registered`);
8898
- if (this.isStopped()) throw new Error(`settings service is disposed: "${ns}" cannot be written`);
8899
- if (!this.writable) throw new Error(`settings provider is read-only: "${ns}" cannot be updated in-process`);
8900
- let payload;
8901
- if (mode === "mutate") payload = { ops: input };
8902
- else {
8903
- if (!isPlainObject(input)) throw new TypeError(`settings ${verb} for "${ns}" must be a plain object`);
8904
- payload = input;
8905
- }
8906
- const snapshot = cloneJsonShaped(payload, (label, path) => /* @__PURE__ */ new TypeError(`settings ${verb} for "${ns}" must contain only JSON-compatible data (found ${label} at ${path})`));
8907
- const run = (this.writeQueues.get(ns) ?? Promise.resolve()).catch(() => void 0).then(async () => {
8908
- if (this.isStopped()) throw new Error(`settings service was disposed before the queued "${ns}" ${verb} ran`);
8909
- if (this.registrations.get(ns) !== registration) throw new Error(`settings namespace "${ns}" registration was disposed before the queued ${verb} ran`);
8910
- const current = this.section(ns) ?? {};
8911
- if (expectedRevision !== void 0 && expectedRevision !== registration.revision) throw new SettingsConflictError(ns, expectedRevision, registration.revision);
8912
- const section = mode === "merge" ? mergeLayers(current, snapshot) : mode === "replace" ? snapshot : snapshot["ops"].reduce(applyPathOp, current);
8913
- const next = deepFreeze(this.resolve(registration.schema, registration.base, section, registration.validate));
8914
- await this.persist(ns, section);
8915
- this.document[ns] = section;
8916
- if (this.registrations.get(ns) === registration && !this.isStopped()) {
8917
- this.bumpRevision(registration, current, section);
8918
- this.commit(registration, next, "update");
8919
- }
8920
- });
8921
- this.writeQueues.set(ns, run);
8922
- return run;
8923
- }
8924
- /**
8925
- * Provider hook: commit a complete raw document observed in storage. Each
8926
- * registered namespace re-resolves; an invalid section keeps that
8927
- * namespace's last good value and warns, other namespaces still commit.
8928
- * @param doc - the detached raw document (unregistered sections preserved).
8929
- * @param source - change origin; defaults to `provider`.
8930
- */
8931
- publish(doc, source = "provider") {
8932
- const before = /* @__PURE__ */ new Map();
8933
- for (const registration of this.registrations.values()) try {
8934
- before.set(registration.ns, this.section(registration.ns));
8935
- } catch {
8936
- before.set(registration.ns, void 0);
8937
- }
8938
- this.document = doc;
8939
- for (const registration of this.registrations.values()) {
8940
- let next;
8941
- try {
8942
- next = deepFreeze(this.resolve(registration.schema, registration.base, this.section(registration.ns), registration.validate));
8943
- } catch (error) {
8944
- this.ctx.logger.warn("settings: keeping last good \"%s\" after invalid stored section", registration.ns);
8945
- this.ctx.logger.warn(error);
8946
- continue;
8947
- }
8948
- this.bumpRevision(registration, before.get(registration.ns), this.section(registration.ns));
8949
- this.commit(registration, next, source);
8950
- }
8951
- }
8952
- /** Read one namespace's raw user section, rejecting non-object sections. */
8953
- section(ns) {
8954
- const section = this.document[ns];
8955
- if (section === void 0) return void 0;
8956
- if (!isPlainObject(section)) throw new TypeError(`settings section "${ns}" must be an object of keys`);
8957
- return section;
8958
- }
8959
- /** Resolve one namespace value: schema defaults, then `base`, then the user layer. */
8960
- resolve(schema, base, section, validate) {
8961
- const value = schema(mergeLayers(base, section));
8962
- validate?.(value);
8963
- return value;
8964
- }
8965
- /**
8966
- * Advance a namespace's revision when its RAW section changed, and announce
8967
- * it. Deliberately independent of {@link commit}'s resolved-value equality:
8968
- * storing an override equal to the composition base leaves the resolved
8969
- * value alone but changes what the document says, which is exactly what a
8970
- * configuration surface must re-read.
8971
- */
8972
- bumpRevision(registration, before, after) {
8973
- if (deepEqualJson(before, after)) return;
8974
- registration.revision += 1;
8975
- this.emitDocumentUpdated(registration.ns, registration.revision);
8976
- }
8977
- /** Contained fan-out of `settings/document-updated`, mirroring {@link commit}'s. */
8978
- emitDocumentUpdated(ns, revision) {
8979
- let invariantFailure;
8980
- const args = [
8981
- "settings/document-updated",
8982
- ns,
8983
- revision
8984
- ];
8985
- for (const listener of this.ctx.events.dispatch("emit", args)) try {
8986
- const returned = listener(ns, revision);
8987
- if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
8988
- this.warnListenerFailure(ns, error);
8989
- });
8990
- } catch (error) {
8991
- if (error?.code === "INVARIANT") {
8992
- invariantFailure ??= error;
8993
- continue;
8994
- }
8995
- this.warnListenerFailure(ns, error);
8996
- }
8997
- if (invariantFailure !== void 0) throw invariantFailure;
8998
- }
8999
- /** Commit a resolved value when changed: swap, notify watchers, emit the event. */
9000
- commit(registration, next, source) {
9001
- const prev = registration.resolved;
9002
- if (deepEqualJson(next, prev)) return;
9003
- registration.resolved = next;
9004
- for (const watcher of [...registration.watchers]) {
9005
- const segment = watcher.tail.then(() => {
9006
- if (!watcher.active || this.isStopped()) return;
9007
- return watcher.callback(next, prev);
9008
- }).then(() => void 0, (error) => {
9009
- this.warnWatcherFailure(registration.ns, error);
9010
- });
9011
- watcher.tail = segment;
9012
- this.pendingTails.add(segment);
9013
- segment.then(() => this.pendingTails.delete(segment));
9014
- }
9015
- let invariantFailure;
9016
- const args = [
9017
- "settings/updated",
9018
- registration.ns,
9019
- next,
9020
- prev,
9021
- source
9022
- ];
9023
- for (const listener of this.ctx.events.dispatch("emit", args)) try {
9024
- const returned = listener(registration.ns, next, prev, source);
9025
- if (returned != null && typeof returned.then === "function") Promise.resolve(returned).then(void 0, (error) => {
9026
- this.warnListenerFailure(registration.ns, error);
9027
- });
9028
- } catch (error) {
9029
- if (error?.code === "INVARIANT") {
9030
- invariantFailure ??= error;
9031
- continue;
9032
- }
9033
- this.warnListenerFailure(registration.ns, error);
9034
- }
9035
- if (invariantFailure !== void 0) throw invariantFailure;
9036
- }
9037
- /** Contained-watcher diagnostic shared by the sync and async failure paths. */
9038
- warnWatcherFailure(ns, error) {
9039
- this.ctx.logger.warn("settings: watcher for \"%s\" failed", ns);
9040
- this.ctx.logger.warn(error);
9041
- }
9042
- /** Contained-listener diagnostic shared by the sync and async failure paths. */
9043
- warnListenerFailure(ns, error) {
9044
- this.ctx.logger.warn("settings: a settings/updated listener for \"%s\" failed", ns);
9045
- this.ctx.logger.warn(error);
9046
- }
9047
- };
9048
-
9049
8458
  //#endregion
9050
8459
  //#region src/roster.ts
9051
8460
  /** Entry ids are lowercase dns-ish labels. Also enforced for file names. */
@@ -9185,6 +8594,19 @@ const entryFileName = (id) => `${id}.yaml`;
9185
8594
  * writes and deletes must address both too — a `.yml`-only entry that
9186
8595
  * survives a delete would resurrect after every restart (SUB-ROSTER-YML-001). */
9187
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
+ }
9188
8610
  /** Atomic single-file write: temp name in the roster dir, then rename with
9189
8611
  * bounded retries (Windows AV/indexer transiently lock fresh files). */
9190
8612
  async function writeEntryFile(options) {
@@ -9204,15 +8626,7 @@ async function writeEntryFile(options) {
9204
8626
  }
9205
8627
  await wait(50 * 3 ** attempt);
9206
8628
  }
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
- }
8629
+ await removeYmlSibling(options.dir, options.id, fsp, wait);
9216
8630
  }
9217
8631
  /** Remove every on-disk spelling that can serve one id (`.yaml` AND `.yml`);
9218
8632
  * a missing file is already the desired state (SUB-ROSTER-YML-001). */
@@ -9502,34 +8916,142 @@ function sanitizeToolFilter(ctx, filter, scope) {
9502
8916
  };
9503
8917
  }
9504
8918
  function apply(ctx, config$1) {
9505
- let source;
9506
- let settingsService;
9507
- let settingsNs;
9508
- /** Non-null when the settings seam could not register this namespace (e.g. a
9509
- * hand-edited settings.yaml section fails the Config schema). Registration
9510
- * failing inside a Cordis child fiber would otherwise leave the library
9511
- * 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. */
9512
8926
  let settingsFailure;
9513
8927
  ctx.inject(["settings"], (sctx) => {
9514
- settingsService = sctx.settings;
9515
- settingsNs = settingsNamespace("subagent-library");
9516
- try {
9517
- const scope = sctx.settings.register(settingsNs, Config, { base: config$1 });
9518
- source = () => scope.get();
9519
- sctx.effect(() => () => {
9520
- source = () => config$1;
9521
- });
9522
- scope.watch(() => {});
9523
- } catch (error) {
9524
- 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;
9525
9043
  }
9526
9044
  });
9045
+ ctx.inject(["settings", "configEditor"], (ectx) => {
9046
+ const editor = ectx.configEditor;
9047
+ if (editor !== void 0) configEditorHost = editor;
9048
+ });
9527
9049
  /** Library entries restricted to schema-consistent ids: a hand-written key
9528
9050
  * like `k3_reviewer` passes z.dict (any string key) but can never be
9529
9051
  * delegated or deleted, so it is filtered out of every view. */
9530
9052
  const filterEntries = (raw) => Object.fromEntries(Object.entries(raw ?? {}).filter(([id]) => ENTRY_ID.test(id)));
9531
9053
  const resolveConfig = () => {
9532
- const base = source !== void 0 ? source() : config$1;
9054
+ const base = settings?.readConfig() ?? config$1;
9533
9055
  return {
9534
9056
  ...base,
9535
9057
  entries: filterEntries(base.entries)
@@ -9668,19 +9190,23 @@ function apply(ctx, config$1) {
9668
9190
  * one-click cleanup set for the 0.2→0.3 transition (a legacy row WITHOUT a
9669
9191
  * file is still serving and must survive). */
9670
9192
  const legacyShadowedIds = (view) => {
9671
- const svc = settingsService;
9672
- const ns = settingsNs;
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 [];
9193
+ const raw = settings?.legacyUserEntries();
9194
+ if (raw === void 0) return [];
9676
9195
  return Object.keys(raw).filter((id) => ENTRY_ID.test(id) && view.entries[id]?.source === "file");
9677
9196
  };
9678
- const wireView = async (legacySkipWarning = false) => {
9197
+ const wireView = async (legacySkipWarning = false, extraWarnings = []) => {
9679
9198
  const { view } = await loadLibrary();
9680
- const diagnostics = legacySkipWarning ? [{
9681
- severity: "warning",
9682
- message: "设置服务只读:settings 中的旧副本未能同步移除,被删条目可能以旧副本复活"
9683
- }, ...view.diagnostics] : view.diagnostics;
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
+ ];
9684
9210
  return {
9685
9211
  ok: true,
9686
9212
  writable: true,
@@ -9700,15 +9226,7 @@ function apply(ctx, config$1) {
9700
9226
  * instead of a silent false success (red team A7 / k3 #4). */
9701
9227
  const unsetLegacy = async (ids) => {
9702
9228
  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";
9229
+ return settings?.unsetEntries(ids) ?? "no-settings";
9712
9230
  };
9713
9231
  wctx.effect(() => web.register({
9714
9232
  kind: "exact",
@@ -9784,8 +9302,7 @@ function apply(ctx, config$1) {
9784
9302
  return;
9785
9303
  }
9786
9304
  if (body["op"] === "clear-legacy") {
9787
- const svc = settingsService;
9788
- if (svc !== void 0 && !svc.writable) {
9305
+ if (settings !== void 0 && !settings.isWritable()) {
9789
9306
  sendJson(res, 403, {
9790
9307
  ok: false,
9791
9308
  error: "readonly",
@@ -9840,9 +9357,17 @@ function apply(ctx, config$1) {
9840
9357
  return;
9841
9358
  }
9842
9359
  }
9360
+ const sweepWarnings = [];
9843
9361
  for (const [id, doc] of validated) {
9844
9362
  const prev = current.entries[id];
9845
- if (prev?.source === "file" && serializeEntry(prev.entry, prev.enabled) === serializeEntry(doc.entry, doc.enabled)) continue;
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
+ }
9846
9371
  await writeEntryFile({
9847
9372
  dir: current.dir,
9848
9373
  id,
@@ -9857,7 +9382,7 @@ function apply(ctx, config$1) {
9857
9382
  deletedIds.push(id);
9858
9383
  if (row.source === "file") await deleteEntryFile(current.dir, id, fsPort());
9859
9384
  }
9860
- sendJson(res, 200, await wireView(await unsetLegacy(deletedIds) === "skipped-readonly"));
9385
+ sendJson(res, 200, await wireView(await unsetLegacy(deletedIds) === "skipped-readonly", sweepWarnings));
9861
9386
  return;
9862
9387
  } else {
9863
9388
  sendJson(res, 400, {