dsh-subagent-library 0.3.2 → 0.3.4

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
@@ -8509,8 +8509,8 @@ const nodeFsPort = {
8509
8509
  await promises.mkdir(dir, options);
8510
8510
  }
8511
8511
  };
8512
- const isEnoent = (error) => error.code === "ENOENT";
8513
- const defaultDelay = (ms) => new Promise((resolve) => {
8512
+ const isEnoent$1 = (error) => error.code === "ENOENT";
8513
+ const defaultDelay$1 = (ms) => new Promise((resolve) => {
8514
8514
  setTimeout(resolve, ms);
8515
8515
  });
8516
8516
  /** Validate one entry id; returns the error message, or undefined when valid. */
@@ -8596,13 +8596,13 @@ const entryFileName = (id) => `${id}.yaml`;
8596
8596
  const entryFileNames = (id) => [`${id}.yaml`, `${id}.yml`];
8597
8597
  /** Remove a same-id `.yml` sibling (the failed-convergence residue), with
8598
8598
  * bounded retries for transient Windows locks; ENOENT = already clean. */
8599
- async function removeYmlSibling(dir, id, fsp = nodeFsPort, delay = defaultDelay) {
8599
+ async function removeYmlSibling(dir, id, fsp = nodeFsPort, delay = defaultDelay$1) {
8600
8600
  const ymlSibling = nodePath.join(dir, `${id}.yml`);
8601
8601
  for (let attempt = 0;; attempt += 1) try {
8602
8602
  await fsp.unlink(ymlSibling);
8603
8603
  return;
8604
8604
  } catch (error) {
8605
- if (isEnoent(error)) return;
8605
+ if (isEnoent$1(error)) return;
8606
8606
  if (attempt >= 2) throw error;
8607
8607
  await delay(50 * 3 ** attempt);
8608
8608
  }
@@ -8611,7 +8611,7 @@ async function removeYmlSibling(dir, id, fsp = nodeFsPort, delay = defaultDelay)
8611
8611
  * bounded retries (Windows AV/indexer transiently lock fresh files). */
8612
8612
  async function writeEntryFile(options) {
8613
8613
  const fsp = options.fs ?? nodeFsPort;
8614
- const wait = options.delay ?? defaultDelay;
8614
+ const wait = options.delay ?? defaultDelay$1;
8615
8615
  await fsp.mkdir(options.dir, { recursive: true });
8616
8616
  const target = nodePath.join(options.dir, entryFileName(options.id));
8617
8617
  const temp = nodePath.join(options.dir, `.${options.id}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`);
@@ -8634,7 +8634,7 @@ async function deleteEntryFile(dir, id, fsp = nodeFsPort) {
8634
8634
  for (const name$1 of entryFileNames(id)) try {
8635
8635
  await fsp.unlink(nodePath.join(dir, name$1));
8636
8636
  } catch (error) {
8637
- if (!isEnoent(error)) throw error;
8637
+ if (!isEnoent$1(error)) throw error;
8638
8638
  }
8639
8639
  }
8640
8640
  /**
@@ -8646,15 +8646,24 @@ async function loadRoster(options) {
8646
8646
  const diagnostics = [];
8647
8647
  const entries = {};
8648
8648
  let names;
8649
+ let listing;
8649
8650
  try {
8650
8651
  names = (await fsp.readdir(options.dir)).slice().sort();
8652
+ listing = "ok";
8651
8653
  } catch (error) {
8652
- if (!isEnoent(error)) diagnostics.push({
8653
- severity: "error",
8654
- message: `名册目录不可读 ${options.dir}:${String(error)}`
8655
- });
8654
+ if (isEnoent$1(error)) listing = "missing";
8655
+ else {
8656
+ listing = "unreadable";
8657
+ diagnostics.push({
8658
+ severity: "error",
8659
+ message: `名册目录不可读 ${options.dir}:${String(error)}`
8660
+ });
8661
+ }
8656
8662
  names = [];
8657
8663
  }
8664
+ /** Every roster id the listing named, before read/parse. A failed file is
8665
+ * still present — overlay cleanup must not treat it as deleted. */
8666
+ const presentIds = /* @__PURE__ */ new Set();
8658
8667
  const owner = /* @__PURE__ */ new Map();
8659
8668
  /** Ids whose FILE exists but failed to load. If a legacy copy then serves
8660
8669
  * the same id, that fallback must be LOUD: delegate would run the stale
@@ -8665,6 +8674,7 @@ async function loadRoster(options) {
8665
8674
  if (!lower.endsWith(".yaml") && !lower.endsWith(".yml")) continue;
8666
8675
  const id = lower.endsWith(".yaml") ? lower.slice(0, -5) : lower.slice(0, -4);
8667
8676
  if (id.startsWith("_")) continue;
8677
+ presentIds.add(id);
8668
8678
  if (lower !== name$1) {
8669
8679
  diagnostics.push({
8670
8680
  severity: "warning",
@@ -8753,7 +8763,9 @@ async function loadRoster(options) {
8753
8763
  dir: options.dir,
8754
8764
  entries,
8755
8765
  diagnostics,
8756
- hash: hashEntries(entries)
8766
+ hash: hashEntries(entries),
8767
+ listing,
8768
+ presentIds
8757
8769
  };
8758
8770
  }
8759
8771
  /**
@@ -8771,7 +8783,7 @@ async function migrateLegacyEntries(options) {
8771
8783
  try {
8772
8784
  names = new Set((await fsp.readdir(options.dir)).map((name$1) => name$1.toLowerCase()));
8773
8785
  } catch (error) {
8774
- if (!isEnoent(error)) throw error;
8786
+ if (!isEnoent$1(error)) throw error;
8775
8787
  names = /* @__PURE__ */ new Set();
8776
8788
  }
8777
8789
  for (const [id, entry] of Object.entries(options.legacy)) {
@@ -8815,6 +8827,366 @@ async function migrateLegacyEntries(options) {
8815
8827
  };
8816
8828
  }
8817
8829
 
8830
+ //#endregion
8831
+ //#region src/profile-route.ts
8832
+ /** Route fields that name an LLM, not the subagent transport. */
8833
+ const ROUTE_KEYS = [
8834
+ "provider",
8835
+ "model",
8836
+ "reasoningEffort",
8837
+ "maxTokens"
8838
+ ];
8839
+ /** Directory under the roster that holds per-profile route files. */
8840
+ const PROFILE_ROUTES_DIR = "_profiles";
8841
+ const EFFORT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
8842
+ const BOUND_HASH = /^[a-f0-9]{16}$/;
8843
+ /** Windows reserved device names. The stem before the first dot is what the OS checks. */
8844
+ const RESERVED_BASENAMES = new Set([
8845
+ "con",
8846
+ "prn",
8847
+ "aux",
8848
+ "nul",
8849
+ ...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),
8850
+ ...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`)
8851
+ ]);
8852
+ const isEnoent = (error) => error.code === "ENOENT";
8853
+ const isNotDir = (error) => error.code === "ENOTDIR";
8854
+ const defaultDelay = (ms) => new Promise((resolve) => {
8855
+ setTimeout(resolve, ms);
8856
+ });
8857
+ /**
8858
+ * Why this profile name cannot be a route-overlay directory, or undefined when
8859
+ * it can. Matches the host's profile-name rules (empty, slashes, `.`, `..`,
8860
+ * `node_modules` are invalid) and also rejects Windows path-segment traps
8861
+ * (reserved device names, trailing dot/space, `|?*` and controls). A legal
8862
+ * host name such as `my profile` is safe. An unsafe name must not fall back
8863
+ * to writing this profile's route into the shared roster file.
8864
+ */
8865
+ function profilePathProblem(name$1) {
8866
+ if (name$1 === "" || name$1.includes("/") || name$1.includes("\\") || name$1 === "." || name$1 === ".." || name$1 === "node_modules") return `profile name ${JSON.stringify(name$1)} is not a usable directory name`;
8867
+ if (name$1.length > 200) return `profile name ${JSON.stringify(name$1)} is too long to store a route file`;
8868
+ if (/[<>:"|?*]/.test(name$1) || [...name$1].some((char) => char.charCodeAt(0) < 32)) return `profile name ${JSON.stringify(name$1)} contains characters that cannot be a directory`;
8869
+ if (name$1.endsWith(".") || name$1.endsWith(" ")) return `profile name ${JSON.stringify(name$1)} cannot end with a dot or space`;
8870
+ const stem = name$1.split(".")[0]?.toLowerCase() ?? "";
8871
+ if (RESERVED_BASENAMES.has(stem)) return `profile name ${JSON.stringify(name$1)} is a reserved device name`;
8872
+ }
8873
+ /** Profile names that are safe as a single path segment under `_profiles/`. */
8874
+ function isSafeProfileName(name$1) {
8875
+ return profilePathProblem(name$1) === void 0;
8876
+ }
8877
+ /** Stable id of the shared file's route. An overlay is bound to this value. */
8878
+ function routeBinding(entry) {
8879
+ return createHash("sha256").update(JSON.stringify(pickRoute(entry ?? {}))).digest("hex").slice(0, 16);
8880
+ }
8881
+ /**
8882
+ * Settings-page conflict hash. Includes this profile's overlays so two editors
8883
+ * of the same profile cannot silently overwrite each other's route, while a
8884
+ * route saved on another profile does not change this hash.
8885
+ */
8886
+ function hashProfileView(sharedHash, profile, overlays) {
8887
+ const payload = Object.keys(overlays).sort().map((id) => [id, overlays[id]]);
8888
+ return createHash("sha256").update(JSON.stringify([
8889
+ sharedHash,
8890
+ profile,
8891
+ payload
8892
+ ])).digest("hex").slice(0, 16);
8893
+ }
8894
+ function overlayDirectory(rosterDir, profile) {
8895
+ if (!isSafeProfileName(profile)) throw new Error(`unsafe profile name "${profile}"`);
8896
+ return nodePath.join(rosterDir, PROFILE_ROUTES_DIR, profile);
8897
+ }
8898
+ function pickRoute(entry) {
8899
+ const record = entry;
8900
+ const route = {};
8901
+ const provider = record["provider"];
8902
+ const model = record["model"];
8903
+ const reasoningEffort = record["reasoningEffort"];
8904
+ const maxTokens = record["maxTokens"];
8905
+ if (typeof provider === "string" && provider !== "") route.provider = provider;
8906
+ if (typeof model === "string" && model !== "") route.model = model;
8907
+ if (typeof reasoningEffort === "string" && reasoningEffort !== "") route.reasoningEffort = reasoningEffort;
8908
+ if (typeof maxTokens === "number") route.maxTokens = maxTokens;
8909
+ return route;
8910
+ }
8911
+ function hasRoute(route) {
8912
+ return route.provider !== void 0 || route.model !== void 0 || route.reasoningEffort !== void 0 || route.maxTokens !== void 0;
8913
+ }
8914
+ function sameRoute(left, right) {
8915
+ return left.provider === right.provider && left.model === right.model && left.reasoningEffort === right.reasoningEffort && left.maxTokens === right.maxTokens;
8916
+ }
8917
+ /** Drop LLM route fields. Identity, transport, and tool scope stay. */
8918
+ function stripRoute(entry) {
8919
+ const next = { ...entry };
8920
+ delete next.provider;
8921
+ delete next.model;
8922
+ delete next.reasoningEffort;
8923
+ delete next.maxTokens;
8924
+ return next;
8925
+ }
8926
+ function withRoute(entry, route) {
8927
+ const next = stripRoute(entry);
8928
+ if (route.provider !== void 0) next.provider = route.provider;
8929
+ if (route.model !== void 0) next.model = route.model;
8930
+ if (route.reasoningEffort !== void 0) next.reasoningEffort = route.reasoningEffort;
8931
+ if (route.maxTokens !== void 0) next.maxTokens = route.maxTokens;
8932
+ return next;
8933
+ }
8934
+ /**
8935
+ * Shared-file body for a profile-scoped save: keep this profile's identity
8936
+ * edit, but do not overwrite another profile's authored route.
8937
+ */
8938
+ function preserveSharedRoute(incoming, previous) {
8939
+ return withRoute(stripRoute(incoming), pickRoute(previous ?? {}));
8940
+ }
8941
+ function isInherit(overlay) {
8942
+ return overlay.inherit === true;
8943
+ }
8944
+ /**
8945
+ * Resolve the route this profile should actually call.
8946
+ * `registered === undefined` means the host exposed no provider list, so a
8947
+ * shared route cannot be classified as foreign and is left unchanged.
8948
+ */
8949
+ function resolveEffectiveEntry(entry, overlay, registered) {
8950
+ if (overlay !== void 0 && isInherit(overlay)) return {
8951
+ entry: stripRoute(entry),
8952
+ note: "inherit"
8953
+ };
8954
+ if (overlay !== void 0 && hasRoute(overlay)) {
8955
+ const next = withRoute(entry, overlay);
8956
+ if (overlay.provider !== void 0 && registered !== void 0 && !registered.has(overlay.provider)) return {
8957
+ entry: next,
8958
+ note: "profile-missing"
8959
+ };
8960
+ return {
8961
+ entry: next,
8962
+ note: "profile"
8963
+ };
8964
+ }
8965
+ if (entry.provider !== void 0 && entry.provider !== "" && registered !== void 0 && !registered.has(entry.provider)) return {
8966
+ entry: stripRoute(entry),
8967
+ note: "foreign-ignored"
8968
+ };
8969
+ return {
8970
+ entry,
8971
+ note: "shared"
8972
+ };
8973
+ }
8974
+ /** Parse an overlay file, including the optional shared-route binding. */
8975
+ function parseOverlayDocument(raw) {
8976
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("profile route must be an object");
8977
+ const record = { ...raw };
8978
+ const bound = record["boundHash"];
8979
+ delete record["boundHash"];
8980
+ if (bound !== void 0 && (typeof bound !== "string" || !BOUND_HASH.test(bound))) throw new Error("boundHash must be 16 hex characters");
8981
+ return {
8982
+ overlay: parseRouteOverlay(record),
8983
+ ...typeof bound === "string" ? { boundHash: bound } : {}
8984
+ };
8985
+ }
8986
+ function parseRouteOverlay(raw) {
8987
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("profile route must be an object");
8988
+ const record = raw;
8989
+ const allowed = new Set(["inherit", ...ROUTE_KEYS]);
8990
+ const unknown$1 = Object.keys(record).filter((key) => !allowed.has(key));
8991
+ if (unknown$1.length > 0) throw new Error(`unknown route fields: ${unknown$1.join(", ")}`);
8992
+ if (record["inherit"] === true) {
8993
+ if (Object.keys(record).filter((key) => key !== "inherit").length > 0) throw new Error("inherit: true cannot be combined with route fields");
8994
+ return { inherit: true };
8995
+ }
8996
+ if ("inherit" in record) throw new Error("inherit must be true when present");
8997
+ const route = {};
8998
+ if ("provider" in record) {
8999
+ if (typeof record["provider"] !== "string" || record["provider"] === "") throw new Error("provider must be a non-empty string");
9000
+ route.provider = record["provider"];
9001
+ }
9002
+ if ("model" in record) {
9003
+ if (typeof record["model"] !== "string" || record["model"] === "") throw new Error("model must be a non-empty string");
9004
+ route.model = record["model"];
9005
+ }
9006
+ if ("reasoningEffort" in record) {
9007
+ if (typeof record["reasoningEffort"] !== "string" || !EFFORT_ID.test(record["reasoningEffort"])) throw new Error("reasoningEffort must be an effort id");
9008
+ route.reasoningEffort = record["reasoningEffort"];
9009
+ }
9010
+ if ("maxTokens" in record) {
9011
+ const maxTokens = record["maxTokens"];
9012
+ if (typeof maxTokens !== "number" || !Number.isSafeInteger(maxTokens) || maxTokens < 1) throw new Error("maxTokens must be a positive integer");
9013
+ route.maxTokens = maxTokens;
9014
+ }
9015
+ if (!hasRoute(route)) throw new Error("profile route is empty");
9016
+ return route;
9017
+ }
9018
+ function serializeRouteOverlay(overlay, boundHash) {
9019
+ const doc = isInherit(overlay) ? { inherit: true } : {};
9020
+ if (!isInherit(overlay)) for (const key of ROUTE_KEYS) {
9021
+ const value = overlay[key];
9022
+ if (value !== void 0) doc[key] = value;
9023
+ }
9024
+ if (boundHash !== void 0) doc["boundHash"] = boundHash;
9025
+ return stringify(doc, { lineWidth: 0 });
9026
+ }
9027
+ async function atomicWrite(dir, fileName, text, fsp, delay) {
9028
+ await fsp.mkdir(dir, { recursive: true });
9029
+ const target = nodePath.join(dir, fileName);
9030
+ const temp = nodePath.join(dir, `.${fileName}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`);
9031
+ await fsp.writeFile(temp, text);
9032
+ for (let attempt = 0;; attempt += 1) try {
9033
+ await fsp.rename(temp, target);
9034
+ return;
9035
+ } catch (error) {
9036
+ if (attempt >= 2) {
9037
+ await fsp.unlink(temp).catch(() => {});
9038
+ throw error;
9039
+ }
9040
+ await delay(50 * 3 ** attempt);
9041
+ }
9042
+ }
9043
+ /** Read one profile's route file. A missing file is "no overlay", not an error. */
9044
+ async function readRouteOverlay(rosterDir, profile, id, fsp = nodeFsPort) {
9045
+ let dir;
9046
+ try {
9047
+ dir = overlayDirectory(rosterDir, profile);
9048
+ } catch (error) {
9049
+ return {
9050
+ ok: false,
9051
+ message: String(error)
9052
+ };
9053
+ }
9054
+ let text;
9055
+ let used;
9056
+ for (const name$1 of entryFileNames(id)) try {
9057
+ text = (await fsp.readFile(nodePath.join(dir, name$1))).toString("utf8");
9058
+ used = name$1;
9059
+ break;
9060
+ } catch (error) {
9061
+ if (!isEnoent(error)) return {
9062
+ ok: false,
9063
+ message: `profile route unreadable (${profile}/${name$1}): ${String(error)}`
9064
+ };
9065
+ }
9066
+ if (text === void 0 || used === void 0) return { ok: true };
9067
+ try {
9068
+ const stripped = text.charCodeAt(0) === 65279 ? text.slice(1) : text;
9069
+ const parsed = parseOverlayDocument(parse(stripped));
9070
+ return {
9071
+ ok: true,
9072
+ overlay: parsed.overlay,
9073
+ boundHash: parsed.boundHash,
9074
+ text: stripped
9075
+ };
9076
+ } catch (error) {
9077
+ return {
9078
+ ok: false,
9079
+ message: `profile route ${profile}/${used} is invalid: ${String(error)}`
9080
+ };
9081
+ }
9082
+ }
9083
+ async function writeRouteOverlay(rosterDir, profile, id, overlay, fsp = nodeFsPort, delay = defaultDelay, boundHash) {
9084
+ const dir = overlayDirectory(rosterDir, profile);
9085
+ await atomicWrite(dir, `${id}.yaml`, serializeRouteOverlay(overlay, boundHash), fsp, delay);
9086
+ const yml = nodePath.join(dir, `${id}.yml`);
9087
+ try {
9088
+ await fsp.unlink(yml);
9089
+ } catch (error) {
9090
+ if (!isEnoent(error)) throw error;
9091
+ }
9092
+ }
9093
+ async function deleteProfileOverlay(rosterDir, profile, id, fsp = nodeFsPort) {
9094
+ const dir = overlayDirectory(rosterDir, profile);
9095
+ for (const name$1 of entryFileNames(id)) try {
9096
+ await fsp.unlink(nodePath.join(dir, name$1));
9097
+ } catch (error) {
9098
+ if (!isEnoent(error) && !isNotDir(error)) throw error;
9099
+ }
9100
+ }
9101
+ /**
9102
+ * Remove every profile's route file for one entry. Deleting the shared entry
9103
+ * must not leave a stale overlay that reappears if the id is created again.
9104
+ */
9105
+ async function deleteRouteOverlays(rosterDir, id, fsp = nodeFsPort) {
9106
+ const root = nodePath.join(rosterDir, PROFILE_ROUTES_DIR);
9107
+ let names;
9108
+ try {
9109
+ names = await fsp.readdir(root);
9110
+ } catch (error) {
9111
+ if (isEnoent(error) || isNotDir(error)) return;
9112
+ throw error;
9113
+ }
9114
+ for (const profile of names) {
9115
+ if (!isSafeProfileName(profile)) continue;
9116
+ await deleteProfileOverlay(rosterDir, profile, id, fsp);
9117
+ }
9118
+ }
9119
+ /**
9120
+ * Persist a route edit relative to the route the settings page displayed.
9121
+ * An echoed empty route — the page hid a provider this profile does not
9122
+ * have — is not an edit and must not become `inherit: true`.
9123
+ * @returns whether an overlay file was written.
9124
+ */
9125
+ async function syncProfileRoute(options) {
9126
+ const fsp = options.fs ?? nodeFsPort;
9127
+ const clientRoute = pickRoute(options.client);
9128
+ if (sameRoute(clientRoute, pickRoute(options.shown))) return false;
9129
+ await writeRouteOverlay(options.dir, options.profile, options.id, hasRoute(clientRoute) ? clientRoute : { inherit: true }, fsp, defaultDelay, routeBinding(options.shared));
9130
+ return true;
9131
+ }
9132
+ /**
9133
+ * Both roster spellings are confirmed missing. Any other outcome — the file
9134
+ * exists, or the check itself failed — is not absence. A read/parse/permission
9135
+ * error must not be turned into a delete (SUB-PROFILE-SEC-001).
9136
+ */
9137
+ async function sharedEntryConfirmedAbsent(rosterDir, id, fsp) {
9138
+ for (const name$1 of entryFileNames(id)) try {
9139
+ await fsp.readFile(nodePath.join(rosterDir, name$1));
9140
+ return false;
9141
+ } catch (error) {
9142
+ if (!isEnoent(error)) return false;
9143
+ }
9144
+ return true;
9145
+ }
9146
+ /**
9147
+ * Drop overlay files only when this read proved the shared entry is gone.
9148
+ *
9149
+ * A successful directory listing plus a per-id ENOENT re-check is the only
9150
+ * read-time signal. `unreadable` / `missing` listings, a file that was listed
9151
+ * but failed to read or parse, and any non-ENOENT re-check keep every
9152
+ * profile's overlay bytes. Explicit entry deletion still uses
9153
+ * {@link deleteRouteOverlays}; this function is not that path.
9154
+ */
9155
+ async function deleteOrphanOverlays(rosterDir, listing, presentIds, fsp = nodeFsPort) {
9156
+ if (listing !== "ok") return;
9157
+ const root = nodePath.join(rosterDir, PROFILE_ROUTES_DIR);
9158
+ let profiles;
9159
+ try {
9160
+ profiles = await fsp.readdir(root);
9161
+ } catch (error) {
9162
+ if (isEnoent(error) || isNotDir(error)) return;
9163
+ return;
9164
+ }
9165
+ for (const profile of profiles) {
9166
+ if (!isSafeProfileName(profile)) continue;
9167
+ const dir = overlayDirectory(rosterDir, profile);
9168
+ let names;
9169
+ try {
9170
+ names = await fsp.readdir(dir);
9171
+ } catch (error) {
9172
+ if (isEnoent(error) || isNotDir(error)) continue;
9173
+ continue;
9174
+ }
9175
+ for (const name$1 of names) {
9176
+ const lower = name$1.toLowerCase();
9177
+ if (!lower.endsWith(".yaml") && !lower.endsWith(".yml")) continue;
9178
+ const id = lower.endsWith(".yaml") ? lower.slice(0, -5) : lower.slice(0, -4);
9179
+ if (presentIds.has(id)) continue;
9180
+ if (!await sharedEntryConfirmedAbsent(rosterDir, id, fsp)) continue;
9181
+ try {
9182
+ await fsp.unlink(nodePath.join(dir, name$1));
9183
+ } catch (error) {
9184
+ if (!isEnoent(error)) throw error;
9185
+ }
9186
+ }
9187
+ }
9188
+ }
9189
+
8818
9190
  //#endregion
8819
9191
  //#region src/index.ts
8820
9192
  const name = "subagent-library";
@@ -9108,6 +9480,129 @@ function apply(ctx, config$1) {
9108
9480
  view
9109
9481
  };
9110
9482
  };
9483
+ /** Launcher-owned profile. Absent hosts keep the shared-file route. An
9484
+ * unsafe name is still a profile — it must not silently write its route
9485
+ * into the shared roster. */
9486
+ const currentProfile = () => {
9487
+ const name$1 = ctx.get("profileContext")?.name;
9488
+ if (typeof name$1 !== "string" || name$1 === "") return { kind: "absent" };
9489
+ const reason = profilePathProblem(name$1);
9490
+ return reason === void 0 ? {
9491
+ kind: "ready",
9492
+ name: name$1
9493
+ } : {
9494
+ kind: "unsafe",
9495
+ name: name$1,
9496
+ reason
9497
+ };
9498
+ };
9499
+ /** Provider ids registered in THIS process. Undefined when the host has no
9500
+ * `llm` service — a missing list must not be treated as "no providers",
9501
+ * or every shared route would be dropped. */
9502
+ const registeredProviderIds = () => {
9503
+ const llm = ctx.get("llm");
9504
+ if (typeof llm?.listProviders !== "function") return void 0;
9505
+ try {
9506
+ const ids = llm.listProviders().map((item) => item?.id).filter((id) => typeof id === "string" && id !== "");
9507
+ return new Set(ids);
9508
+ } catch {
9509
+ return;
9510
+ }
9511
+ };
9512
+ const emptyEffective = (lib) => ({
9513
+ subagentProvider: lib.subagentProvider,
9514
+ raw: lib.view,
9515
+ view: lib.view,
9516
+ notes: {},
9517
+ ignoredProviders: {},
9518
+ overlayErrors: {},
9519
+ overlayTexts: {}
9520
+ });
9521
+ /** Shared roster plus this profile's route. */
9522
+ const loadEffective = async () => {
9523
+ const lib = await loadLibrary();
9524
+ const state = currentProfile();
9525
+ if (state.kind === "absent") return emptyEffective(lib);
9526
+ const registered = registeredProviderIds();
9527
+ const notes = {};
9528
+ const ignoredProviders = {};
9529
+ const overlayErrors = {};
9530
+ const overlayTexts = {};
9531
+ const entries = {};
9532
+ const diagnostics = [...lib.view.diagnostics];
9533
+ if (state.kind === "unsafe") diagnostics.unshift({
9534
+ severity: "error",
9535
+ message: `${state.reason}。本 profile 不会把模型路由写进共享名册;未注册的共享 provider 仍不会被调用。`
9536
+ });
9537
+ else await deleteOrphanOverlays(lib.view.dir, lib.view.listing, lib.view.presentIds, fsPort());
9538
+ for (const [id, row] of Object.entries(lib.view.entries)) {
9539
+ let overlay = void 0;
9540
+ if (state.kind === "ready") {
9541
+ const read = await readRouteOverlay(lib.view.dir, state.name, id, fsPort());
9542
+ if (!read.ok) {
9543
+ notes[id] = "overlay-broken";
9544
+ overlayErrors[id] = read.message;
9545
+ entries[id] = {
9546
+ ...row,
9547
+ entry: stripRoute(row.entry)
9548
+ };
9549
+ diagnostics.push({
9550
+ severity: "error",
9551
+ id,
9552
+ message: read.message
9553
+ });
9554
+ continue;
9555
+ }
9556
+ if (read.overlay !== void 0 && read.boundHash !== void 0 && read.boundHash !== routeBinding(row.entry)) {
9557
+ await deleteProfileOverlay(lib.view.dir, state.name, id, fsPort());
9558
+ diagnostics.push({
9559
+ severity: "warning",
9560
+ id,
9561
+ message: `profile "${state.name}" 的路由覆盖已失效(共享名册路由已变),已忽略。`
9562
+ });
9563
+ } else {
9564
+ overlay = read.overlay;
9565
+ if (read.text !== void 0 && read.overlay !== void 0) overlayTexts[id] = read.text;
9566
+ }
9567
+ }
9568
+ const resolved = resolveEffectiveEntry(row.entry, overlay, registered);
9569
+ notes[id] = resolved.note;
9570
+ entries[id] = {
9571
+ ...row,
9572
+ entry: resolved.entry
9573
+ };
9574
+ if (resolved.note === "foreign-ignored" && row.entry.provider !== void 0) ignoredProviders[id] = row.entry.provider;
9575
+ }
9576
+ const hash = state.kind === "ready" ? hashProfileView(lib.view.hash, state.name, overlayTexts) : lib.view.hash;
9577
+ return {
9578
+ subagentProvider: lib.subagentProvider,
9579
+ raw: lib.view,
9580
+ view: {
9581
+ ...lib.view,
9582
+ entries,
9583
+ diagnostics,
9584
+ hash
9585
+ },
9586
+ ...state.kind === "ready" ? { profile: state.name } : {
9587
+ profile: state.name,
9588
+ profileProblem: state.reason
9589
+ },
9590
+ notes,
9591
+ ignoredProviders,
9592
+ overlayErrors,
9593
+ overlayTexts,
9594
+ ...registered === void 0 ? {} : { registeredProviders: [...registered] }
9595
+ };
9596
+ };
9597
+ const routeNoteText = (lib, id) => {
9598
+ const note = lib.notes[id];
9599
+ const profile = lib.profile ?? "this profile";
9600
+ if (note === "foreign-ignored") return `provider "${lib.ignoredProviders[id] ?? "?"}" is not registered in profile "${profile}"; this call uses the session model`;
9601
+ if (note === "profile") return `route is pinned to profile "${profile}"`;
9602
+ if (note === "inherit") return `profile "${profile}" inherits the session model`;
9603
+ if (note === "profile-missing") return `profile "${profile}" route provider is not registered in this profile`;
9604
+ if (note === "overlay-broken") return lib.overlayErrors[id];
9605
+ };
9111
9606
  const MAX_BODY_BYTES = 1 << 20;
9112
9607
  const readJsonBody = async (req) => {
9113
9608
  const chunks = [];
@@ -9181,10 +9676,11 @@ function apply(ctx, config$1) {
9181
9676
  };
9182
9677
  /** Wire shape of one roster row for the settings editor: the stored entry
9183
9678
  * 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, {
9679
+ const wireEntries = (lib) => Object.fromEntries(Object.entries(lib.view.entries).map(([id, row]) => [id, {
9185
9680
  ...row.entry,
9186
9681
  ...row.enabled ? {} : { enabled: false },
9187
- ...row.source === "legacy" ? { source: "legacy" } : {}
9682
+ ...row.source === "legacy" ? { source: "legacy" } : {},
9683
+ ...lib.notes[id] !== void 0 && lib.notes[id] !== "shared" ? { routeNote: lib.notes[id] } : {}
9188
9684
  }]));
9189
9685
  /** Legacy settings entries currently shadowed by a roster file — the safe
9190
9686
  * one-click cleanup set for the 0.2→0.3 transition (a legacy row WITHOUT a
@@ -9194,8 +9690,16 @@ function apply(ctx, config$1) {
9194
9690
  if (raw === void 0) return [];
9195
9691
  return Object.keys(raw).filter((id) => ENTRY_ID.test(id) && view.entries[id]?.source === "file");
9196
9692
  };
9693
+ const profileRouteWarnings = (lib) => {
9694
+ if (lib.profile === void 0) return [];
9695
+ return Object.entries(lib.ignoredProviders).map(([id, provider]) => ({
9696
+ severity: "warning",
9697
+ id,
9698
+ message: `共享名册路由 provider "${provider}" 未在当前 profile "${lib.profile}" 注册,调用将改用本会话模型。在此填写的 Provider/模型只保存到这个 profile。`
9699
+ }));
9700
+ };
9197
9701
  const wireView = async (legacySkipWarning = false, extraWarnings = []) => {
9198
- const { view } = await loadLibrary();
9702
+ const lib = await loadEffective();
9199
9703
  const diagnostics = [
9200
9704
  ...extraWarnings.map((message) => ({
9201
9705
  severity: "warning",
@@ -9205,16 +9709,18 @@ function apply(ctx, config$1) {
9205
9709
  severity: "warning",
9206
9710
  message: "设置服务只读:settings 中的旧副本未能同步移除,被删条目可能以旧副本复活"
9207
9711
  }] : [],
9208
- ...view.diagnostics
9712
+ ...profileRouteWarnings(lib),
9713
+ ...lib.view.diagnostics
9209
9714
  ];
9210
9715
  return {
9211
9716
  ok: true,
9212
9717
  writable: true,
9213
- dir: view.dir,
9214
- hash: view.hash,
9215
- entries: wireEntries(view),
9718
+ dir: lib.view.dir,
9719
+ hash: lib.view.hash,
9720
+ ...lib.profile !== void 0 ? { profile: lib.profile } : {},
9721
+ entries: wireEntries(lib),
9216
9722
  diagnostics,
9217
- legacyCount: legacyShadowedIds(view).length
9723
+ legacyCount: legacyShadowedIds(lib.view).length
9218
9724
  };
9219
9725
  };
9220
9726
  ctx.inject(["webServer"], (wctx) => {
@@ -9284,19 +9790,21 @@ function apply(ctx, config$1) {
9284
9790
  const rawHash = body["expectedHash"];
9285
9791
  const expectedHash = typeof rawHash === "string" ? rawHash : void 0;
9286
9792
  try {
9287
- const { view: current } = await loadLibrary();
9288
- if (expectedHash !== void 0 && expectedHash !== current.hash) {
9793
+ const opened = await loadEffective();
9794
+ const current = opened.raw;
9795
+ if (expectedHash !== void 0 && expectedHash !== opened.view.hash) {
9289
9796
  sendJson(res, 409, {
9290
9797
  ok: false,
9291
9798
  error: "conflict",
9292
9799
  view: {
9293
9800
  ok: true,
9294
9801
  writable: true,
9295
- dir: current.dir,
9296
- hash: current.hash,
9297
- entries: wireEntries(current),
9298
- diagnostics: current.diagnostics,
9299
- legacyCount: legacyShadowedIds(current).length
9802
+ dir: opened.view.dir,
9803
+ hash: opened.view.hash,
9804
+ ...opened.profile !== void 0 ? { profile: opened.profile } : {},
9805
+ entries: wireEntries(opened),
9806
+ diagnostics: [...profileRouteWarnings(opened), ...opened.view.diagnostics],
9807
+ legacyCount: legacyShadowedIds(opened.raw).length
9300
9808
  }
9301
9809
  });
9302
9810
  return;
@@ -9321,6 +9829,7 @@ function apply(ctx, config$1) {
9321
9829
  return;
9322
9830
  }
9323
9831
  await deleteEntryFile(current.dir, id, fsPort());
9832
+ await deleteRouteOverlays(current.dir, id, fsPort());
9324
9833
  sendJson(res, 200, await wireView(await unsetLegacy([id]) === "skipped-readonly"));
9325
9834
  return;
9326
9835
  } else if (body["op"] === "save") {
@@ -9346,6 +9855,7 @@ function apply(ctx, config$1) {
9346
9855
  }
9347
9856
  const payload = { ...value };
9348
9857
  delete payload["source"];
9858
+ delete payload["routeNote"];
9349
9859
  try {
9350
9860
  validated.set(id, parseEntryDocument(payload));
9351
9861
  } catch (error) {
@@ -9358,21 +9868,43 @@ function apply(ctx, config$1) {
9358
9868
  }
9359
9869
  }
9360
9870
  const sweepWarnings = [];
9871
+ const profileState = currentProfile();
9872
+ if (profileState.kind === "unsafe") for (const [id, doc] of validated) {
9873
+ const shown = opened.view.entries[id]?.entry ?? { description: doc.entry.description };
9874
+ if (!sameRoute(pickRoute(doc.entry), pickRoute(shown))) {
9875
+ sendJson(res, 400, {
9876
+ ok: false,
9877
+ error: "profile-path",
9878
+ message: `${profileState.reason}。不能把本 profile 的模型路由写进共享名册。`
9879
+ });
9880
+ return;
9881
+ }
9882
+ }
9361
9883
  for (const [id, doc] of validated) {
9362
9884
  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;
9885
+ const sharedDoc = profileState.kind === "absent" ? doc : {
9886
+ entry: preserveSharedRoute(doc.entry, prev?.entry),
9887
+ enabled: doc.enabled
9888
+ };
9889
+ if (prev?.source === "file" && prev.file === entryFileName(id) && serializeEntry(prev.entry, prev.enabled) === serializeEntry(sharedDoc.entry, sharedDoc.enabled)) try {
9890
+ await removeYmlSibling(current.dir, id, fsPort());
9891
+ } catch (error) {
9892
+ sweepWarnings.push(`条目 "${id}" 的同名 .yml 残留清除失败,冲突诊断会持续到清除成功:${String(error)}`);
9370
9893
  }
9371
- await writeEntryFile({
9894
+ else await writeEntryFile({
9372
9895
  dir: current.dir,
9373
9896
  id,
9374
- entry: doc.entry,
9375
- enabled: doc.enabled,
9897
+ entry: sharedDoc.entry,
9898
+ enabled: sharedDoc.enabled,
9899
+ fs: fsPort()
9900
+ });
9901
+ if (profileState.kind === "ready") await syncProfileRoute({
9902
+ dir: current.dir,
9903
+ profile: profileState.name,
9904
+ id,
9905
+ client: doc.entry,
9906
+ shown: opened.view.entries[id]?.entry ?? { description: doc.entry.description },
9907
+ shared: prev?.entry,
9376
9908
  fs: fsPort()
9377
9909
  });
9378
9910
  }
@@ -9381,6 +9913,7 @@ function apply(ctx, config$1) {
9381
9913
  if (validated.has(id)) continue;
9382
9914
  deletedIds.push(id);
9383
9915
  if (row.source === "file") await deleteEntryFile(current.dir, id, fsPort());
9916
+ await deleteRouteOverlays(current.dir, id, fsPort());
9384
9917
  }
9385
9918
  sendJson(res, 200, await wireView(await unsetLegacy(deletedIds) === "skipped-readonly", sweepWarnings));
9386
9919
  return;
@@ -9430,7 +9963,8 @@ function apply(ctx, config$1) {
9430
9963
  isConcurrencySafe: () => true,
9431
9964
  async execute(_args, exec) {
9432
9965
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9433
- const { view } = await loadLibrary();
9966
+ const lib = await loadEffective();
9967
+ const { view } = lib;
9434
9968
  const agent = exec.agent;
9435
9969
  /** The catalog must not advertise a filter this session cannot apply:
9436
9970
  * summarize the SANITIZED filter and list what was ignored, so the model
@@ -9446,6 +9980,7 @@ function apply(ctx, config$1) {
9446
9980
  };
9447
9981
  const rows = Object.entries(view.entries).map(([id, row]) => {
9448
9982
  const summary = filterSummary(row);
9983
+ const routeNote = routeNoteText(lib, id);
9449
9984
  return {
9450
9985
  id,
9451
9986
  description: row.entry.description,
@@ -9453,7 +9988,8 @@ function apply(ctx, config$1) {
9453
9988
  model: row.entry.model ?? "(session default)",
9454
9989
  backgroundMode: row.entry.backgroundMode ?? "one-shot",
9455
9990
  ...row.enabled ? {} : { enabled: false },
9456
- ...summary !== void 0 ? { toolFilter: summary } : {}
9991
+ ...summary !== void 0 ? { toolFilter: summary } : {},
9992
+ ...routeNote !== void 0 ? { routeNote } : {}
9457
9993
  };
9458
9994
  });
9459
9995
  const catalogDiagnostics = view.diagnostics.filter((item) => item.severity !== "info");
@@ -9463,7 +9999,7 @@ function apply(ctx, config$1) {
9463
9999
  }));
9464
10000
  ctx.tools.register(defineTool({
9465
10001
  name: "delegate",
9466
- description: "Delegate a task to a named subagent from the subagent library (see list_subagents for available entries and their roles). The child runs on the entry's configured model with its role persona and tool scope. Prefer this over ad-hoc subagent calls when a library entry matches the task.",
10002
+ description: "Delegate a task to a named subagent from the subagent library (see list_subagents for available entries and their roles). The child runs on the entry's model when that provider is registered in this profile; a provider that exists only in another profile is not used, and the child inherits this session's model instead. Prefer this over ad-hoc subagent calls when a library entry matches the task.",
9467
10003
  parameters: {
9468
10004
  library_id: {
9469
10005
  type: "string",
@@ -9504,7 +10040,7 @@ function apply(ctx, config$1) {
9504
10040
  const dropped = Array.isArray(value.droppedTools) ? value.droppedTools.filter((name$1) => typeof name$1 === "string") : [];
9505
10041
  return [{
9506
10042
  type: "text",
9507
- text: (value.kind === "background" ? `started background subagent task ${value.jobId}` : value.kind === "continuable" ? `started subagent ${value.subagentId}` : value.kind === "foreground" ? outputValueText(value.output ?? []) : JSON.stringify(value)) + (dropped.length > 0 ? `\n(已忽略本会话不可用的工具名:${dropped.join(";")})` : "")
10043
+ text: (value.kind === "background" ? `started background subagent task ${value.jobId}` : value.kind === "continuable" ? `started subagent ${value.subagentId}` : value.kind === "foreground" ? outputValueText(value.output ?? []) : JSON.stringify(value)) + (typeof value.routeNote === "string" && value.routeNote !== "" ? `\n(${value.routeNote})` : "") + (dropped.length > 0 ? `\n(已忽略本会话不可用的工具名:${dropped.join(";")})` : "")
9508
10044
  }];
9509
10045
  }
9510
10046
  },
@@ -9513,7 +10049,8 @@ function apply(ctx, config$1) {
9513
10049
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9514
10050
  const parent = exec.agent;
9515
10051
  if (!parent) throw new Error("delegate tool requires a calling agent (exec.agent was undefined)");
9516
- const { subagentProvider: defaultProvider, view } = await loadLibrary();
10052
+ const lib = await loadEffective();
10053
+ const { subagentProvider: defaultProvider, view } = lib;
9517
10054
  if (!ENTRY_ID.test(args.library_id)) throw new Error(`subagent library entry id "${args.library_id}" is invalid`);
9518
10055
  const row = Object.hasOwn(view.entries, args.library_id) ? view.entries[args.library_id] : void 0;
9519
10056
  if (row === void 0) {
@@ -9521,6 +10058,12 @@ function apply(ctx, config$1) {
9521
10058
  throw new Error(`subagent library has no entry "${args.library_id}"${ids.length ? ` (available: ${ids.join(", ")})` : " (library is empty)"}`);
9522
10059
  }
9523
10060
  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`);
10061
+ const routeNote = routeNoteText(lib, args.library_id);
10062
+ if (lib.notes[args.library_id] === "overlay-broken") throw new Error(`delegate: ${routeNote ?? "profile route file is invalid"}`);
10063
+ if (lib.notes[args.library_id] === "profile-missing") {
10064
+ const available = lib.registeredProviders?.join(", ") || "none";
10065
+ throw new Error(`delegate: profile "${lib.profile}" route for "${args.library_id}" uses provider "${row.entry.provider}", which is not registered in this profile (available: ${available}). Clear Provider on this profile's settings page to use the session model, or set a provider this profile has.`);
10066
+ }
9524
10067
  const entry = row.entry;
9525
10068
  const subagentProviderName = entry.subagentProvider ?? defaultProvider;
9526
10069
  const transport = ctx.subagents.getProvider(subagentProviderName);
@@ -9556,7 +10099,10 @@ function apply(ctx, config$1) {
9556
10099
  ...toolFilter !== void 0 ? { toolFilter } : {},
9557
10100
  ...maxDepth !== void 0 ? { maxDepth } : {}
9558
10101
  };
9559
- const droppedNote = droppedTools.length > 0 ? { droppedTools } : {};
10102
+ const droppedNote = {
10103
+ ...droppedTools.length > 0 ? { droppedTools } : {},
10104
+ ...routeNote !== void 0 && lib.notes[args.library_id] !== "profile" ? { routeNote } : {}
10105
+ };
9560
10106
  if (args.run_in_background === true || continuable) {
9561
10107
  if (continuable) return {
9562
10108
  kind: "continuable",
@@ -9604,19 +10150,23 @@ function apply(ctx, config$1) {
9604
10150
  ctx.systemPrompt.section({
9605
10151
  name: "subagent-library",
9606
10152
  order: LIBRARY_SECTION_ORDER,
9607
- text: (context) => ctx.tools.get("list_subagents", context.scope) === void 0 ? "" : "Use list_subagents to see the named subagents in the library, then delegate with the delegate tool (library_id + prompt). Library entries run on a fixed model with a role persona; prefer them over ad-hoc subagent calls when an entry matches the task."
10153
+ text: (context) => ctx.tools.get("list_subagents", context.scope) === void 0 ? "" : "Use list_subagents to see the named subagents in the library, then delegate with the delegate tool (library_id + prompt). Library entries run on a fixed model with a role persona; prefer them over ad-hoc subagent calls when an entry matches the task. A roster provider that is not registered in this profile is not called — the child inherits this session's model unless this profile has its own route."
9608
10154
  });
9609
10155
  const commands = ctx.get("commands");
9610
10156
  if (commands !== void 0) commands.register({
9611
10157
  name: "subagent",
9612
10158
  description: "List the subagent library entries",
9613
10159
  handler: async () => {
9614
- const { view } = await loadLibrary();
10160
+ const lib = await loadEffective();
10161
+ const { view } = lib;
9615
10162
  const ids = Object.keys(view.entries);
9616
10163
  const lines = ids.map((id) => {
9617
10164
  const row = view.entries[id];
10165
+ const note = lib.notes[id];
9618
10166
  const tags = [
9619
10167
  `${row.entry.provider ?? "默认模型路由"}/${row.entry.model ?? "默认模型"}`,
10168
+ note === "foreign-ignored" || note === "inherit" ? "本 profile 会话模型" : "",
10169
+ note === "profile" ? `profile:${lib.profile}` : "",
9620
10170
  row.entry.backgroundMode === "continuable" ? "可续聊" : "",
9621
10171
  row.source === "legacy" ? "legacy" : "",
9622
10172
  row.enabled ? "" : "已停用"