dsh-subagent-library 0.3.3 → 0.3.5

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";
@@ -8849,12 +9221,48 @@ async function settleStart(start, signal) {
8849
9221
  };
8850
9222
  }
8851
9223
  }
9224
+ /** DSH ≥0.2.1 replaced the subagent start seam with startActivation. Places
9225
+ * that must branch on host generation (delegate, catalog, settings API) probe
9226
+ * the same property so every branch flips together on one host. */
9227
+ function isModernSubagentHost(subagents) {
9228
+ return typeof subagents?.startActivation === "function";
9229
+ }
9230
+ /** Pass `promise` through unless `signal` aborts first. The losing side is
9231
+ * silenced: a rejection that arrives after the race was decided resolves an
9232
+ * already-detached derived promise, and the abort listener is always removed. */
9233
+ function raceAbort(promise, signal, message) {
9234
+ if (signal.aborted) return Promise.reject(new Error(message));
9235
+ return new Promise((resolve, reject) => {
9236
+ let settled = false;
9237
+ const onAbort = () => {
9238
+ if (settled) return;
9239
+ settled = true;
9240
+ signal.removeEventListener("abort", onAbort);
9241
+ reject(new Error(message));
9242
+ };
9243
+ signal.addEventListener("abort", onAbort);
9244
+ promise.then((value) => {
9245
+ if (settled) return;
9246
+ settled = true;
9247
+ signal.removeEventListener("abort", onAbort);
9248
+ resolve(value);
9249
+ }, (error) => {
9250
+ if (settled) return;
9251
+ settled = true;
9252
+ signal.removeEventListener("abort", onAbort);
9253
+ reject(error);
9254
+ });
9255
+ });
9256
+ }
8852
9257
  /** Foreground collection: await the child, dispose the run, map stop reasons.
8853
- * `run.result` rejection must still release the run (mirrors settleRun). */
8854
- async function settleForegroundRun(run) {
9258
+ * `run.result` rejection must still release the run (mirrors settleRun).
9259
+ * A ≥0.2.1 activation signal stops covering the child once the host accepts
9260
+ * it, so an abort during collection has to dispose here; hosts without
9261
+ * startActivation keep cancelling through the signal alone. */
9262
+ async function settleForegroundRun(run, signal) {
8855
9263
  let result;
8856
9264
  try {
8857
- result = await run.result;
9265
+ result = await (signal === void 0 ? run.result : raceAbort(run.result, signal, "delegate: foreground collection aborted"));
8858
9266
  } finally {
8859
9267
  await run.dispose().catch(() => {});
8860
9268
  }
@@ -9108,6 +9516,129 @@ function apply(ctx, config$1) {
9108
9516
  view
9109
9517
  };
9110
9518
  };
9519
+ /** Launcher-owned profile. Absent hosts keep the shared-file route. An
9520
+ * unsafe name is still a profile — it must not silently write its route
9521
+ * into the shared roster. */
9522
+ const currentProfile = () => {
9523
+ const name$1 = ctx.get("profileContext")?.name;
9524
+ if (typeof name$1 !== "string" || name$1 === "") return { kind: "absent" };
9525
+ const reason = profilePathProblem(name$1);
9526
+ return reason === void 0 ? {
9527
+ kind: "ready",
9528
+ name: name$1
9529
+ } : {
9530
+ kind: "unsafe",
9531
+ name: name$1,
9532
+ reason
9533
+ };
9534
+ };
9535
+ /** Provider ids registered in THIS process. Undefined when the host has no
9536
+ * `llm` service — a missing list must not be treated as "no providers",
9537
+ * or every shared route would be dropped. */
9538
+ const registeredProviderIds = () => {
9539
+ const llm = ctx.get("llm");
9540
+ if (typeof llm?.listProviders !== "function") return void 0;
9541
+ try {
9542
+ const ids = llm.listProviders().map((item) => item?.id).filter((id) => typeof id === "string" && id !== "");
9543
+ return new Set(ids);
9544
+ } catch {
9545
+ return;
9546
+ }
9547
+ };
9548
+ const emptyEffective = (lib) => ({
9549
+ subagentProvider: lib.subagentProvider,
9550
+ raw: lib.view,
9551
+ view: lib.view,
9552
+ notes: {},
9553
+ ignoredProviders: {},
9554
+ overlayErrors: {},
9555
+ overlayTexts: {}
9556
+ });
9557
+ /** Shared roster plus this profile's route. */
9558
+ const loadEffective = async () => {
9559
+ const lib = await loadLibrary();
9560
+ const state = currentProfile();
9561
+ if (state.kind === "absent") return emptyEffective(lib);
9562
+ const registered = registeredProviderIds();
9563
+ const notes = {};
9564
+ const ignoredProviders = {};
9565
+ const overlayErrors = {};
9566
+ const overlayTexts = {};
9567
+ const entries = {};
9568
+ const diagnostics = [...lib.view.diagnostics];
9569
+ if (state.kind === "unsafe") diagnostics.unshift({
9570
+ severity: "error",
9571
+ message: `${state.reason}。本 profile 不会把模型路由写进共享名册;未注册的共享 provider 仍不会被调用。`
9572
+ });
9573
+ else await deleteOrphanOverlays(lib.view.dir, lib.view.listing, lib.view.presentIds, fsPort());
9574
+ for (const [id, row] of Object.entries(lib.view.entries)) {
9575
+ let overlay = void 0;
9576
+ if (state.kind === "ready") {
9577
+ const read = await readRouteOverlay(lib.view.dir, state.name, id, fsPort());
9578
+ if (!read.ok) {
9579
+ notes[id] = "overlay-broken";
9580
+ overlayErrors[id] = read.message;
9581
+ entries[id] = {
9582
+ ...row,
9583
+ entry: stripRoute(row.entry)
9584
+ };
9585
+ diagnostics.push({
9586
+ severity: "error",
9587
+ id,
9588
+ message: read.message
9589
+ });
9590
+ continue;
9591
+ }
9592
+ if (read.overlay !== void 0 && read.boundHash !== void 0 && read.boundHash !== routeBinding(row.entry)) {
9593
+ await deleteProfileOverlay(lib.view.dir, state.name, id, fsPort());
9594
+ diagnostics.push({
9595
+ severity: "warning",
9596
+ id,
9597
+ message: `profile "${state.name}" 的路由覆盖已失效(共享名册路由已变),已忽略。`
9598
+ });
9599
+ } else {
9600
+ overlay = read.overlay;
9601
+ if (read.text !== void 0 && read.overlay !== void 0) overlayTexts[id] = read.text;
9602
+ }
9603
+ }
9604
+ const resolved = resolveEffectiveEntry(row.entry, overlay, registered);
9605
+ notes[id] = resolved.note;
9606
+ entries[id] = {
9607
+ ...row,
9608
+ entry: resolved.entry
9609
+ };
9610
+ if (resolved.note === "foreign-ignored" && row.entry.provider !== void 0) ignoredProviders[id] = row.entry.provider;
9611
+ }
9612
+ const hash = state.kind === "ready" ? hashProfileView(lib.view.hash, state.name, overlayTexts) : lib.view.hash;
9613
+ return {
9614
+ subagentProvider: lib.subagentProvider,
9615
+ raw: lib.view,
9616
+ view: {
9617
+ ...lib.view,
9618
+ entries,
9619
+ diagnostics,
9620
+ hash
9621
+ },
9622
+ ...state.kind === "ready" ? { profile: state.name } : {
9623
+ profile: state.name,
9624
+ profileProblem: state.reason
9625
+ },
9626
+ notes,
9627
+ ignoredProviders,
9628
+ overlayErrors,
9629
+ overlayTexts,
9630
+ ...registered === void 0 ? {} : { registeredProviders: [...registered] }
9631
+ };
9632
+ };
9633
+ const routeNoteText = (lib, id) => {
9634
+ const note = lib.notes[id];
9635
+ const profile = lib.profile ?? "this profile";
9636
+ if (note === "foreign-ignored") return `provider "${lib.ignoredProviders[id] ?? "?"}" is not registered in profile "${profile}"; this call uses the session model`;
9637
+ if (note === "profile") return `route is pinned to profile "${profile}"`;
9638
+ if (note === "inherit") return `profile "${profile}" inherits the session model`;
9639
+ if (note === "profile-missing") return `profile "${profile}" route provider is not registered in this profile`;
9640
+ if (note === "overlay-broken") return lib.overlayErrors[id];
9641
+ };
9111
9642
  const MAX_BODY_BYTES = 1 << 20;
9112
9643
  const readJsonBody = async (req) => {
9113
9644
  const chunks = [];
@@ -9181,10 +9712,11 @@ function apply(ctx, config$1) {
9181
9712
  };
9182
9713
  /** Wire shape of one roster row for the settings editor: the stored entry
9183
9714
  * 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, {
9715
+ const wireEntries = (lib) => Object.fromEntries(Object.entries(lib.view.entries).map(([id, row]) => [id, {
9185
9716
  ...row.entry,
9186
9717
  ...row.enabled ? {} : { enabled: false },
9187
- ...row.source === "legacy" ? { source: "legacy" } : {}
9718
+ ...row.source === "legacy" ? { source: "legacy" } : {},
9719
+ ...lib.notes[id] !== void 0 && lib.notes[id] !== "shared" ? { routeNote: lib.notes[id] } : {}
9188
9720
  }]));
9189
9721
  /** Legacy settings entries currently shadowed by a roster file — the safe
9190
9722
  * one-click cleanup set for the 0.2→0.3 transition (a legacy row WITHOUT a
@@ -9194,8 +9726,16 @@ function apply(ctx, config$1) {
9194
9726
  if (raw === void 0) return [];
9195
9727
  return Object.keys(raw).filter((id) => ENTRY_ID.test(id) && view.entries[id]?.source === "file");
9196
9728
  };
9729
+ const profileRouteWarnings = (lib) => {
9730
+ if (lib.profile === void 0) return [];
9731
+ return Object.entries(lib.ignoredProviders).map(([id, provider]) => ({
9732
+ severity: "warning",
9733
+ id,
9734
+ message: `共享名册路由 provider "${provider}" 未在当前 profile "${lib.profile}" 注册,调用将改用本会话模型。在此填写的 Provider/模型只保存到这个 profile。`
9735
+ }));
9736
+ };
9197
9737
  const wireView = async (legacySkipWarning = false, extraWarnings = []) => {
9198
- const { view } = await loadLibrary();
9738
+ const lib = await loadEffective();
9199
9739
  const diagnostics = [
9200
9740
  ...extraWarnings.map((message) => ({
9201
9741
  severity: "warning",
@@ -9205,16 +9745,18 @@ function apply(ctx, config$1) {
9205
9745
  severity: "warning",
9206
9746
  message: "设置服务只读:settings 中的旧副本未能同步移除,被删条目可能以旧副本复活"
9207
9747
  }] : [],
9208
- ...view.diagnostics
9748
+ ...profileRouteWarnings(lib),
9749
+ ...lib.view.diagnostics
9209
9750
  ];
9210
9751
  return {
9211
9752
  ok: true,
9212
9753
  writable: true,
9213
- dir: view.dir,
9214
- hash: view.hash,
9215
- entries: wireEntries(view),
9754
+ dir: lib.view.dir,
9755
+ hash: lib.view.hash,
9756
+ ...lib.profile !== void 0 ? { profile: lib.profile } : {},
9757
+ entries: wireEntries(lib),
9216
9758
  diagnostics,
9217
- legacyCount: legacyShadowedIds(view).length
9759
+ legacyCount: legacyShadowedIds(lib.view).length
9218
9760
  };
9219
9761
  };
9220
9762
  ctx.inject(["webServer"], (wctx) => {
@@ -9284,19 +9826,21 @@ function apply(ctx, config$1) {
9284
9826
  const rawHash = body["expectedHash"];
9285
9827
  const expectedHash = typeof rawHash === "string" ? rawHash : void 0;
9286
9828
  try {
9287
- const { view: current } = await loadLibrary();
9288
- if (expectedHash !== void 0 && expectedHash !== current.hash) {
9829
+ const opened = await loadEffective();
9830
+ const current = opened.raw;
9831
+ if (expectedHash !== void 0 && expectedHash !== opened.view.hash) {
9289
9832
  sendJson(res, 409, {
9290
9833
  ok: false,
9291
9834
  error: "conflict",
9292
9835
  view: {
9293
9836
  ok: true,
9294
9837
  writable: true,
9295
- dir: current.dir,
9296
- hash: current.hash,
9297
- entries: wireEntries(current),
9298
- diagnostics: current.diagnostics,
9299
- legacyCount: legacyShadowedIds(current).length
9838
+ dir: opened.view.dir,
9839
+ hash: opened.view.hash,
9840
+ ...opened.profile !== void 0 ? { profile: opened.profile } : {},
9841
+ entries: wireEntries(opened),
9842
+ diagnostics: [...profileRouteWarnings(opened), ...opened.view.diagnostics],
9843
+ legacyCount: legacyShadowedIds(opened.raw).length
9300
9844
  }
9301
9845
  });
9302
9846
  return;
@@ -9321,6 +9865,7 @@ function apply(ctx, config$1) {
9321
9865
  return;
9322
9866
  }
9323
9867
  await deleteEntryFile(current.dir, id, fsPort());
9868
+ await deleteRouteOverlays(current.dir, id, fsPort());
9324
9869
  sendJson(res, 200, await wireView(await unsetLegacy([id]) === "skipped-readonly"));
9325
9870
  return;
9326
9871
  } else if (body["op"] === "save") {
@@ -9346,6 +9891,7 @@ function apply(ctx, config$1) {
9346
9891
  }
9347
9892
  const payload = { ...value };
9348
9893
  delete payload["source"];
9894
+ delete payload["routeNote"];
9349
9895
  try {
9350
9896
  validated.set(id, parseEntryDocument(payload));
9351
9897
  } catch (error) {
@@ -9358,21 +9904,46 @@ function apply(ctx, config$1) {
9358
9904
  }
9359
9905
  }
9360
9906
  const sweepWarnings = [];
9907
+ if (isModernSubagentHost(ctx.subagents)) {
9908
+ for (const [id, doc] of validated) if (doc.entry.toolFilter !== void 0) sweepWarnings.push(`条目 "${id}" 带 toolFilter:本宿主(DSH ≥0.2.1)无法强制执行逐条目工具过滤,委派该条目会被拒绝。`);
9909
+ }
9910
+ const profileState = currentProfile();
9911
+ if (profileState.kind === "unsafe") for (const [id, doc] of validated) {
9912
+ const shown = opened.view.entries[id]?.entry ?? { description: doc.entry.description };
9913
+ if (!sameRoute(pickRoute(doc.entry), pickRoute(shown))) {
9914
+ sendJson(res, 400, {
9915
+ ok: false,
9916
+ error: "profile-path",
9917
+ message: `${profileState.reason}。不能把本 profile 的模型路由写进共享名册。`
9918
+ });
9919
+ return;
9920
+ }
9921
+ }
9361
9922
  for (const [id, doc] of validated) {
9362
9923
  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;
9924
+ const sharedDoc = profileState.kind === "absent" ? doc : {
9925
+ entry: preserveSharedRoute(doc.entry, prev?.entry),
9926
+ enabled: doc.enabled
9927
+ };
9928
+ if (prev?.source === "file" && prev.file === entryFileName(id) && serializeEntry(prev.entry, prev.enabled) === serializeEntry(sharedDoc.entry, sharedDoc.enabled)) try {
9929
+ await removeYmlSibling(current.dir, id, fsPort());
9930
+ } catch (error) {
9931
+ sweepWarnings.push(`条目 "${id}" 的同名 .yml 残留清除失败,冲突诊断会持续到清除成功:${String(error)}`);
9370
9932
  }
9371
- await writeEntryFile({
9933
+ else await writeEntryFile({
9372
9934
  dir: current.dir,
9373
9935
  id,
9374
- entry: doc.entry,
9375
- enabled: doc.enabled,
9936
+ entry: sharedDoc.entry,
9937
+ enabled: sharedDoc.enabled,
9938
+ fs: fsPort()
9939
+ });
9940
+ if (profileState.kind === "ready") await syncProfileRoute({
9941
+ dir: current.dir,
9942
+ profile: profileState.name,
9943
+ id,
9944
+ client: doc.entry,
9945
+ shown: opened.view.entries[id]?.entry ?? { description: doc.entry.description },
9946
+ shared: prev?.entry,
9376
9947
  fs: fsPort()
9377
9948
  });
9378
9949
  }
@@ -9381,6 +9952,7 @@ function apply(ctx, config$1) {
9381
9952
  if (validated.has(id)) continue;
9382
9953
  deletedIds.push(id);
9383
9954
  if (row.source === "file") await deleteEntryFile(current.dir, id, fsPort());
9955
+ await deleteRouteOverlays(current.dir, id, fsPort());
9384
9956
  }
9385
9957
  sendJson(res, 200, await wireView(await unsetLegacy(deletedIds) === "skipped-readonly", sweepWarnings));
9386
9958
  return;
@@ -9404,7 +9976,7 @@ function apply(ctx, config$1) {
9404
9976
  });
9405
9977
  ctx.tools.register(defineTool({
9406
9978
  name: "list_subagents",
9407
- description: "List the named subagents available in the subagent library: each entry shows its id, role description, provider, model, background mode and tool filter (allow/deny scoping — e.g. deny:[write, edit] marks a read-only role). Call this before delegating so you can pick a matching library_id.",
9979
+ description: "List the named subagents available in the subagent library: each entry shows its id, role description, provider, model, background mode and tool filter (allow/deny scoping — e.g. deny:[write, edit] marks a read-only role)" + (isModernSubagentHost(ctx.subagents) ? ". On this host (DSH ≥0.2.1) per-entry tool filters cannot be enforced: entries carrying toolFilter are refused at delegate time and marked as undelegable in the listing." : "") + " Call this before delegating so you can pick a matching library_id.",
9408
9980
  parameters: {},
9409
9981
  output: {
9410
9982
  schema: {
@@ -9430,15 +10002,20 @@ function apply(ctx, config$1) {
9430
10002
  isConcurrencySafe: () => true,
9431
10003
  async execute(_args, exec) {
9432
10004
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9433
- const { view } = await loadLibrary();
10005
+ const lib = await loadEffective();
10006
+ const { view } = lib;
9434
10007
  const agent = exec.agent;
10008
+ const modernCatalog = isModernSubagentHost(ctx.subagents);
9435
10009
  /** The catalog must not advertise a filter this session cannot apply:
9436
10010
  * summarize the SANITIZED filter and list what was ignored, so the model
9437
- * sees the same tool scope delegation will actually produce. */
10011
+ * sees the same tool scope delegation will actually produce. On a host
10012
+ * without filter enforcement the filter is undelegable outright, so the
10013
+ * row says so instead of advertising a scope delegation would refuse. */
9438
10014
  const filterSummary = (row) => {
9439
10015
  const entry = row.entry;
9440
10016
  if (entry.toolFilter === void 0) return void 0;
9441
10017
  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(" ");
10018
+ if (modernCatalog) return `${declared}(本宿主无法强制执行 toolFilter,委派该条目会被拒绝)`;
9442
10019
  if (agent === void 0) return declared;
9443
10020
  const { filter, dropped } = sanitizeToolFilter(ctx, entry.toolFilter, agent);
9444
10021
  const effective = filter === void 0 ? "(本会话无可应用的名单项)" : [filter.allow !== void 0 ? `allow:[${filter.allow.join(", ")}]` : "", filter.deny !== void 0 ? `deny:[${filter.deny.join(", ")}]` : ""].filter(Boolean).join(" ");
@@ -9446,6 +10023,7 @@ function apply(ctx, config$1) {
9446
10023
  };
9447
10024
  const rows = Object.entries(view.entries).map(([id, row]) => {
9448
10025
  const summary = filterSummary(row);
10026
+ const routeNote = routeNoteText(lib, id);
9449
10027
  return {
9450
10028
  id,
9451
10029
  description: row.entry.description,
@@ -9453,7 +10031,8 @@ function apply(ctx, config$1) {
9453
10031
  model: row.entry.model ?? "(session default)",
9454
10032
  backgroundMode: row.entry.backgroundMode ?? "one-shot",
9455
10033
  ...row.enabled ? {} : { enabled: false },
9456
- ...summary !== void 0 ? { toolFilter: summary } : {}
10034
+ ...summary !== void 0 ? { toolFilter: summary } : {},
10035
+ ...routeNote !== void 0 ? { routeNote } : {}
9457
10036
  };
9458
10037
  });
9459
10038
  const catalogDiagnostics = view.diagnostics.filter((item) => item.severity !== "info");
@@ -9463,7 +10042,7 @@ function apply(ctx, config$1) {
9463
10042
  }));
9464
10043
  ctx.tools.register(defineTool({
9465
10044
  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.",
10045
+ 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
10046
  parameters: {
9468
10047
  library_id: {
9469
10048
  type: "string",
@@ -9504,7 +10083,7 @@ function apply(ctx, config$1) {
9504
10083
  const dropped = Array.isArray(value.droppedTools) ? value.droppedTools.filter((name$1) => typeof name$1 === "string") : [];
9505
10084
  return [{
9506
10085
  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(";")})` : "")
10086
+ 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
10087
  }];
9509
10088
  }
9510
10089
  },
@@ -9513,7 +10092,8 @@ function apply(ctx, config$1) {
9513
10092
  if (settingsFailure !== void 0) throw new Error(settingsFailure);
9514
10093
  const parent = exec.agent;
9515
10094
  if (!parent) throw new Error("delegate tool requires a calling agent (exec.agent was undefined)");
9516
- const { subagentProvider: defaultProvider, view } = await loadLibrary();
10095
+ const lib = await loadEffective();
10096
+ const { subagentProvider: defaultProvider, view } = lib;
9517
10097
  if (!ENTRY_ID.test(args.library_id)) throw new Error(`subagent library entry id "${args.library_id}" is invalid`);
9518
10098
  const row = Object.hasOwn(view.entries, args.library_id) ? view.entries[args.library_id] : void 0;
9519
10099
  if (row === void 0) {
@@ -9521,6 +10101,12 @@ function apply(ctx, config$1) {
9521
10101
  throw new Error(`subagent library has no entry "${args.library_id}"${ids.length ? ` (available: ${ids.join(", ")})` : " (library is empty)"}`);
9522
10102
  }
9523
10103
  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`);
10104
+ const routeNote = routeNoteText(lib, args.library_id);
10105
+ if (lib.notes[args.library_id] === "overlay-broken") throw new Error(`delegate: ${routeNote ?? "profile route file is invalid"}`);
10106
+ if (lib.notes[args.library_id] === "profile-missing") {
10107
+ const available = lib.registeredProviders?.join(", ") || "none";
10108
+ 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.`);
10109
+ }
9524
10110
  const entry = row.entry;
9525
10111
  const subagentProviderName = entry.subagentProvider ?? defaultProvider;
9526
10112
  const transport = ctx.subagents.getProvider(subagentProviderName);
@@ -9531,13 +10117,17 @@ function apply(ctx, config$1) {
9531
10117
  if (maxDepth !== void 0) assertSubagentMaxDepth(maxDepth);
9532
10118
  const { filter: toolFilter, dropped, allowEmptied } = sanitizeToolFilter(ctx, entry.toolFilter, parent);
9533
10119
  const droppedTools = dropped.map((item) => item.reason === "session-local" ? `${item.name}(本会话专属工具,子代本就继承不到)` : `${item.name}(本会话不存在)`);
10120
+ const subagentHost = ctx.subagents;
10121
+ const modernHost = isModernSubagentHost(subagentHost);
10122
+ if (modernHost && entry.toolFilter !== void 0) throw new Error(`delegate: this host cannot enforce a per-child toolFilter (entry "${args.library_id}"). Remove toolFilter from the roster file, or run on a host that still accepts it.`);
9534
10123
  if (allowEmptied) throw new Error(`delegate: entry "${args.library_id}" allow list names no tool this session can apply (${droppedTools.join("; ")}) — refusing to start a child with no tools at all`);
9535
- if (!continuable) {
9536
- if (maxDepth !== void 0 && !transport.capabilities.depthLimit) throw new Error(`delegate: transport "${subagentProviderName}" cannot enforce maxDepth (no depthLimit capability)`);
10124
+ if (!continuable && maxDepth !== void 0 && !transport.capabilities.depthLimit) throw new Error(`delegate: transport "${subagentProviderName}" cannot enforce maxDepth (no depthLimit capability)`);
10125
+ if (!modernHost && !continuable) {
9537
10126
  if (entry.persona !== void 0 && !transport.capabilities.persona) throw new Error(`delegate: transport "${subagentProviderName}" cannot apply a persona (no persona capability)`);
9538
10127
  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`);
9539
10128
  if (entry.toolFilter !== void 0 && !transport.capabilities.toolFilter) throw new Error(`delegate: transport "${subagentProviderName}" cannot apply a tool filter (no toolFilter capability)`);
9540
10129
  }
10130
+ const promptText = modernHost && entry.persona !== void 0 ? `Role persona:\n${entry.persona}\n\nTask:\n${args.prompt}` : args.prompt;
9541
10131
  const agentOptions = entry.provider !== void 0 || entry.model !== void 0 || entry.maxTokens !== void 0 || entry.reasoningEffort !== void 0 ? {
9542
10132
  ...entry.provider !== void 0 ? { provider: entry.provider } : {},
9543
10133
  ...entry.model !== void 0 ? { model: entry.model } : {},
@@ -9548,24 +10138,61 @@ function apply(ctx, config$1) {
9548
10138
  label: args.description ?? args.library_id,
9549
10139
  prompt: [{
9550
10140
  type: "text",
9551
- text: args.prompt
10141
+ text: promptText
9552
10142
  }],
9553
10143
  parent,
9554
10144
  ...agentOptions !== void 0 ? { agentOptions } : {},
9555
- ...entry.persona !== void 0 ? { persona: entry.persona } : {},
9556
- ...toolFilter !== void 0 ? { toolFilter } : {},
10145
+ ...!modernHost && entry.persona !== void 0 ? { persona: entry.persona } : {},
10146
+ ...!modernHost && toolFilter !== void 0 ? { toolFilter } : {},
9557
10147
  ...maxDepth !== void 0 ? { maxDepth } : {}
9558
10148
  };
9559
- const droppedNote = droppedTools.length > 0 ? { droppedTools } : {};
10149
+ const begin = async (signal, delivery) => {
10150
+ if (subagentHost.startActivation !== void 0) {
10151
+ const { label,...task } = request;
10152
+ const started$1 = await subagentHost.startActivation({
10153
+ provider: subagentProviderName,
10154
+ label: label ?? args.library_id,
10155
+ request: task,
10156
+ signal,
10157
+ delivery
10158
+ });
10159
+ return {
10160
+ childId: started$1.childId,
10161
+ run: {
10162
+ id: started$1.childId,
10163
+ result: started$1.result,
10164
+ localAgent: void 0,
10165
+ dispose: () => started$1.dispose()
10166
+ }
10167
+ };
10168
+ }
10169
+ if (continuable) {
10170
+ if (subagentHost.startContinuable === void 0) throw new Error("delegate: this host has no startContinuable or startActivation");
10171
+ return { childId: (await subagentHost.startContinuable({
10172
+ provider: subagentProviderName,
10173
+ label: request.label ?? args.library_id,
10174
+ request,
10175
+ signal
10176
+ })).childId };
10177
+ }
10178
+ if (subagentHost.start === void 0) throw new Error("delegate: this host has no subagent start or startActivation");
10179
+ const run = await subagentHost.start(subagentProviderName, {
10180
+ ...request,
10181
+ signal
10182
+ });
10183
+ return {
10184
+ childId: run.id,
10185
+ run
10186
+ };
10187
+ };
10188
+ const droppedNote = {
10189
+ ...droppedTools.length > 0 ? { droppedTools } : {},
10190
+ ...routeNote !== void 0 && lib.notes[args.library_id] !== "profile" ? { routeNote } : {}
10191
+ };
9560
10192
  if (args.run_in_background === true || continuable) {
9561
10193
  if (continuable) return {
9562
10194
  kind: "continuable",
9563
- subagentId: (await ctx.subagents.startContinuable({
9564
- provider: subagentProviderName,
9565
- label: args.description ?? args.library_id,
9566
- request,
9567
- signal: exec.signal
9568
- })).childId,
10195
+ subagentId: (await begin(exec.signal, "parent")).childId,
9569
10196
  ...droppedNote
9570
10197
  };
9571
10198
  const jobs = ctx.get("jobs");
@@ -9575,16 +10202,23 @@ function apply(ctx, config$1) {
9575
10202
  jobId: jobs.start({
9576
10203
  kind: "subagent",
9577
10204
  label: args.description ?? args.library_id,
9578
- owner: parent,
10205
+ owner: modernHost ? parent.session.id : parent,
9579
10206
  run: () => {
9580
10207
  const controller = new AbortController();
10208
+ let accepted;
9581
10209
  return {
9582
10210
  cancel: (reason) => {
9583
10211
  controller.abort(reason ?? "background subagent task killed");
10212
+ accepted?.dispose().catch(() => {});
9584
10213
  },
9585
- done: settleStart(ctx.subagents.start(subagentProviderName, {
9586
- ...request,
9587
- signal: controller.signal
10214
+ done: settleStart(begin(controller.signal, "caller").then((started$1) => {
10215
+ if (started$1.run === void 0) throw new Error("delegate: background start returned no run");
10216
+ accepted = started$1.run;
10217
+ if (controller.signal.aborted) {
10218
+ accepted.dispose().catch(() => {});
10219
+ throw new Error("background subagent task killed");
10220
+ }
10221
+ return accepted;
9588
10222
  }), controller.signal)
9589
10223
  };
9590
10224
  }
@@ -9592,11 +10226,10 @@ function apply(ctx, config$1) {
9592
10226
  ...droppedNote
9593
10227
  };
9594
10228
  }
10229
+ const started = await begin(exec.signal, "caller");
10230
+ if (started.run === void 0) throw new Error("delegate: foreground start returned no run");
9595
10231
  return {
9596
- ...await settleForegroundRun(await ctx.subagents.start(subagentProviderName, {
9597
- ...request,
9598
- signal: exec.signal
9599
- })),
10232
+ ...await settleForegroundRun(started.run, exec.signal),
9600
10233
  ...droppedNote
9601
10234
  };
9602
10235
  }
@@ -9604,19 +10237,23 @@ function apply(ctx, config$1) {
9604
10237
  ctx.systemPrompt.section({
9605
10238
  name: "subagent-library",
9606
10239
  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."
10240
+ 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
10241
  });
9609
10242
  const commands = ctx.get("commands");
9610
10243
  if (commands !== void 0) commands.register({
9611
10244
  name: "subagent",
9612
10245
  description: "List the subagent library entries",
9613
10246
  handler: async () => {
9614
- const { view } = await loadLibrary();
10247
+ const lib = await loadEffective();
10248
+ const { view } = lib;
9615
10249
  const ids = Object.keys(view.entries);
9616
10250
  const lines = ids.map((id) => {
9617
10251
  const row = view.entries[id];
10252
+ const note = lib.notes[id];
9618
10253
  const tags = [
9619
10254
  `${row.entry.provider ?? "默认模型路由"}/${row.entry.model ?? "默认模型"}`,
10255
+ note === "foreign-ignored" || note === "inherit" ? "本 profile 会话模型" : "",
10256
+ note === "profile" ? `profile:${lib.profile}` : "",
9620
10257
  row.entry.backgroundMode === "continuable" ? "可续聊" : "",
9621
10258
  row.source === "legacy" ? "legacy" : "",
9622
10259
  row.enabled ? "" : "已停用"