dsh-agent-sdk-bridge 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -764,6 +764,28 @@ function resetSdk(brand) {
764
764
  forced.add(brand);
765
765
  }
766
766
  /**
767
+ * Drop the loaded generation and stop the daemon it started.
768
+ *
769
+ * A daemon loads the CLI's credentials when it initializes, and those
770
+ * credentials are not part of the configuration signature: signing in as
771
+ * another account leaves the daemon answering as the account it started with.
772
+ * Shutting it down and forcing a new instance makes the next query read the
773
+ * credentials that are on disk now.
774
+ *
775
+ * The generation is dropped synchronously, so a read that starts as soon as the
776
+ * sign-in helper exits already gets the new instance; the old daemon is stopped
777
+ * in the background because no caller can wait on the shutdown.
778
+ *
779
+ * @param brand - which edition's daemon to replace.
780
+ */
781
+ function discardSdk(brand) {
782
+ const generation = generations.get(brand);
783
+ generations.delete(brand);
784
+ forced.add(brand);
785
+ if (generation === void 0) return;
786
+ generation.module.then((sdk) => sdk.shutdownDaemon()).catch(() => void 0);
787
+ }
788
+ /**
767
789
  * Whether an error is the SDK's daemon refusing a different configuration.
768
790
  *
769
791
  * @param error - whatever a query threw.
@@ -869,6 +891,19 @@ const DEFAULT_FETCH_TIMEOUT_MS = 2e4;
869
891
  * the requesting catalog's TTL, so normal freshness is unchanged.
870
892
  */
871
893
  const sharedSnapshots = /* @__PURE__ */ new Map();
894
+ /**
895
+ * Brands whose CLI has answered a catalogue read successfully at least once.
896
+ *
897
+ * An empty answer is the account speaking — signed out, or a plan with no
898
+ * official models — and it must not be confused with a read that never
899
+ * happened. Deliberately NOT cleared by {@link QoderModelCatalog.invalidate}:
900
+ * a sign-out drops the catalogue, and the next read may fail outright (the CLI
901
+ * was just re-authenticated, the network hiccuped), which would otherwise look
902
+ * like "never reachable" and republish the static plan to an account with
903
+ * nothing. Any successful read counts, including one whose models are all
904
+ * switched off upstream: the plan only ever stands in for silence.
905
+ */
906
+ const answeredCatalogs = /* @__PURE__ */ new Set();
872
907
  /** Cached live CLI catalog with a static fallback. */
873
908
  var QoderModelCatalog = class {
874
909
  brand;
@@ -879,6 +914,12 @@ var QoderModelCatalog = class {
879
914
  /** Why the last refresh failed, for the settings page's guidance. */
880
915
  failure;
881
916
  /**
917
+ * Bumped by {@link invalidate}. A fetch that started before a sign-in carries
918
+ * the previous account's entries, so it must not republish them after the
919
+ * cache was dropped for that account change.
920
+ */
921
+ epoch = 0;
922
+ /**
882
923
  * @param brand - which edition's CLI answers.
883
924
  * @param ttlMs - how long a fetched catalog stays fresh before a re-fetch.
884
925
  * Read per use, so a settings edit takes effect on the next read.
@@ -898,17 +939,30 @@ var QoderModelCatalog = class {
898
939
  */
899
940
  async liveModels() {
900
941
  const ttlMs = readLive(this.ttlMs, DEFAULT_MODEL_CACHE_TTL_MS);
942
+ const epoch = this.epoch;
901
943
  const fresh = (snapshot) => snapshot !== void 0 && Date.now() - snapshot.at < ttlMs;
902
944
  const cached = this.cached ?? sharedSnapshots.get(this.brand);
903
945
  if (fresh(cached) && cached !== void 0) {
904
946
  this.cached = cached;
905
947
  return officialOnly(cached.models);
906
948
  }
907
- this.inflight ??= this.fetch().finally(() => {
908
- this.inflight = void 0;
909
- });
949
+ let entry = this.inflight;
950
+ if (entry === void 0 || entry.epoch !== epoch) {
951
+ const promise = this.fetch();
952
+ entry = {
953
+ epoch,
954
+ promise
955
+ };
956
+ this.inflight = entry;
957
+ const settled = entry;
958
+ const clear = () => {
959
+ if (this.inflight === settled) this.inflight = void 0;
960
+ };
961
+ promise.then(clear, clear);
962
+ }
910
963
  try {
911
- const models = await this.inflight;
964
+ const models = await entry.promise;
965
+ if (epoch !== this.epoch) return officialOnly(models);
912
966
  const snapshot = {
913
967
  at: Date.now(),
914
968
  models
@@ -916,10 +970,11 @@ var QoderModelCatalog = class {
916
970
  this.cached = snapshot;
917
971
  sharedSnapshots.set(this.brand, snapshot);
918
972
  this.failure = void 0;
973
+ answeredCatalogs.add(this.brand);
919
974
  return officialOnly(models);
920
975
  } catch (error) {
921
976
  const detail = error instanceof Error ? error.message : String(error);
922
- this.failure = cliFailureText(detail, this.brand);
977
+ if (epoch === this.epoch) this.failure = cliFailureText(detail, this.brand);
923
978
  return officialOnly((this.cached ?? sharedSnapshots.get(this.brand))?.models ?? []);
924
979
  }
925
980
  }
@@ -947,16 +1002,24 @@ var QoderModelCatalog = class {
947
1002
  * is installed at all, and which account is signed in — and an empty answer is
948
1003
  * cached like any other. So after the setup helper has run, the page's next
949
1004
  * read must not be served from a snapshot taken before that login existed.
1005
+ *
1006
+ * The remembered empty answer is deliberately kept: it says the account has
1007
+ * nothing, which a later failed read must not turn back into the static plan.
950
1008
  */
951
1009
  invalidate() {
952
1010
  this.cached = void 0;
953
1011
  sharedSnapshots.delete(this.brand);
954
1012
  this.failure = void 0;
1013
+ this.epoch += 1;
1014
+ this.inflight = void 0;
955
1015
  }
956
- /** dsh catalog entries: the enabled live list, or the static fallback. */
1016
+ /** dsh catalog entries: the enabled live list, or the fallback {@link emptyCatalogFallback} allows. */
957
1017
  async models() {
958
1018
  const live = (await this.liveModels()).filter((model) => model.isEnabled !== false);
959
- if (live.length === 0) return brandProfile(this.brand).staticCatalog ? QODER_MODELS : [];
1019
+ if (live.length === 0) return emptyCatalogFallback(this.brand, {
1020
+ cliInstalled: resolveQoderCli(this.brand) !== void 0,
1021
+ answered: answeredCatalogs.has(this.brand)
1022
+ });
960
1023
  return live.map((model) => ({
961
1024
  id: model.value,
962
1025
  name: model.displayName.length > 0 ? model.displayName : model.value,
@@ -1000,6 +1063,30 @@ var QoderModelCatalog = class {
1000
1063
  }
1001
1064
  };
1002
1065
  /**
1066
+ * What the picker may show when the live catalogue came back empty.
1067
+ *
1068
+ * The captured CN plan is a stand-in for exactly one situation: this edition's
1069
+ * CLI is installed, and the catalogue could not be read because the CLI or the
1070
+ * network was unavailable. Two cases must stay empty:
1071
+ *
1072
+ * - The CLI answered. That is the account speaking — signed out, or a plan
1073
+ * with no official models — and publishing the plan here is what put every
1074
+ * Qoder CN model back into the picker after a sign-out, where selecting one
1075
+ * could only fail. `getAvailableModels()` answers a *successful* empty list
1076
+ * while signed out (its `cache` and `live` strategies included, even with a
1077
+ * populated `~/.qoder-cn/.models`), so this is the ordinary sign-out path,
1078
+ * not an edge case.
1079
+ * - The CLI is not installed at all, so none of those models could run.
1080
+ *
1081
+ * @param brand - which edition's catalogue is empty.
1082
+ * @param state - whether that edition's CLI is on the machine, and whether a
1083
+ * successful read has ever produced an answer.
1084
+ */
1085
+ function emptyCatalogFallback(brand, state) {
1086
+ if (!state.cliInstalled || state.answered) return [];
1087
+ return brandProfile(brand).staticCatalog ? QODER_MODELS : [];
1088
+ }
1089
+ /**
1003
1090
  * Keep only the subscription's official models.
1004
1091
  *
1005
1092
  * The CLI also returns models the account added itself (`source` is `user` or
@@ -1310,6 +1397,23 @@ const BACKEND_ROLE = [
1310
1397
  "不要复述对话,不要解释你的角色。"
1311
1398
  ].join("\n");
1312
1399
  /**
1400
+ * Preamble for a side-channel call whose last user message *is* the task.
1401
+ *
1402
+ * Compaction and session titles are not "what would the assistant say next":
1403
+ * DSH appends an instruction as the final user message — compaction sends
1404
+ * `Condense the conversation ABOVE into a structured checkpoint…` — and
1405
+ * expects exactly that to be carried out. Rendering such a request with
1406
+ * {@link BACKEND_ROLE} buried the instruction inside "background" and then
1407
+ * closed with "output the next assistant reply", so a compaction run dutifully
1408
+ * reproduced the previous assistant message instead of summarising. The
1409
+ * transcript then showed the last reply restated where the checkpoint belonged.
1410
+ */
1411
+ const SIDE_CHANNEL_ROLE = [
1412
+ "你在为一个编码 agent(宿主)充当 LLM API 后端。",
1413
+ "这一次不是继续对话:最后一条用户消息就是你要执行的任务,请直接完成它。",
1414
+ "不要把最后一条消息当成新的聊天内容来回应,也不要复述对话或解释你的角色。"
1415
+ ].join("\n");
1416
+ /**
1313
1417
  * Join feed sections into one feed. While no section carries an image the
1314
1418
  * result is the historical text shape, sections separated by a blank line;
1315
1419
  * the first image turns the whole feed into parts, with the text around it
@@ -1462,6 +1566,32 @@ function feedWideCharCount(feed) {
1462
1566
  return feed.reduce((total, part) => total + (part.type === "text" ? countWideChars(part.text) : 0), 0);
1463
1567
  }
1464
1568
  /**
1569
+ * Compose the feed for a one-shot side-channel request (compaction, a session
1570
+ * title): its last user message is the instruction to carry out, not a turn to
1571
+ * continue.
1572
+ *
1573
+ * The history is still rendered, because compaction must see the conversation
1574
+ * it is condensing, but the role preamble and the closing line both name the
1575
+ * trailing instruction as the task. See {@link SIDE_CHANNEL_ROLE} for the
1576
+ * misread this replaces.
1577
+ */
1578
+ function renderSideChannelFeed(system, messages, imagePath) {
1579
+ const history = [];
1580
+ for (const message of messages) {
1581
+ const entry = renderMessage(message, imagePath);
1582
+ if (feedToText(entry, imagePath).length > 0) history.push(entry);
1583
+ }
1584
+ const sections = [SIDE_CHANNEL_ROLE];
1585
+ if (system !== void 0 && system.length > 0) sections.push(`---- 宿主系统提示(作为你的行为准则) ----\n${system}`);
1586
+ const first = history[0];
1587
+ if (first !== void 0) {
1588
+ sections.push(label("---- 宿主对话记录 ----\n", first));
1589
+ sections.push(...history.slice(1));
1590
+ }
1591
+ sections.push("---- 以上是背景。请执行最后一条用户消息给出的任务。 ----");
1592
+ return joinFeeds(sections);
1593
+ }
1594
+ /**
1465
1595
  * Compose the first feed for a fresh session: backend role, the host system
1466
1596
  * prompt, and the existing conversation as compact context. Messages of the
1467
1597
  * current turn keep their image references; earlier ones are handles.
@@ -1571,6 +1701,56 @@ function jsonSchemaToShape(parameters) {
1571
1701
  return shape;
1572
1702
  }
1573
1703
  //#endregion
1704
+ //#region src/mcp-naming.ts
1705
+ /**
1706
+ * MCP tool-name namespacing, shared by every CLI backend this bridge drives.
1707
+ *
1708
+ * Each backend reaches the host's tools over an in-process MCP server, so the
1709
+ * name a model emits is namespaced (`mcp__dsh-host__ops_bash`) while the host
1710
+ * dispatches on the bare name (`ops_bash`). Two things make that translation
1711
+ * less trivial than it looks, and both are the same bug in different clothes:
1712
+ *
1713
+ * - **Spelling.** CodeBuddy rewrites a server name's non-alphanumeric characters
1714
+ * to `_`, so `dsh-host` is exposed as `mcp__dsh_host__…`; the Qoder CLI keeps
1715
+ * the hyphen. A handler must accept both.
1716
+ * - **Depth.** A model occasionally emits an already-qualified name, and the CLI
1717
+ * then qualifies it again. Peeling exactly one layer handed the host
1718
+ * `mcp__dsh_host__edit` — a name it does not have — so DSH answered
1719
+ * `unknown tool "mcp__dsh_host__edit"`; the model then retried the doubled
1720
+ * spelling and the CLI refused it with its own
1721
+ * `does not exist in the current tool set.` Two error messages, one cause:
1722
+ * a prefix peeled once instead of exhaustively.
1723
+ *
1724
+ * This module exists so all three backends peel the same way, rather than each
1725
+ * carrying its own one-layer `slice`.
1726
+ *
1727
+ * @module dsh-agent-sdk-bridge/mcp-naming
1728
+ */
1729
+ /** How many prefix layers a single name may carry before the walk gives up. */
1730
+ const MAX_NAMESPACE_LAYERS = 8;
1731
+ /**
1732
+ * Peel every matching namespace layer off a tool name.
1733
+ *
1734
+ * @param name - the tool name as the CLI's `tool_use` block carried it.
1735
+ * @param prefixes - the namespaced spellings that belong to one server, in
1736
+ * either spelling the backends produce. Longest first is not required; the
1737
+ * walk re-checks the whole list after each peel.
1738
+ * @returns the bare host tool name, or null when no prefix matched at all (or
1739
+ * the name was nothing but namespaces).
1740
+ */
1741
+ function stripMcpNamespace(name, prefixes) {
1742
+ const usable = prefixes.filter((prefix) => prefix.length > 0);
1743
+ let current = name;
1744
+ let stripped = false;
1745
+ for (let layer = 0; layer < MAX_NAMESPACE_LAYERS; layer++) {
1746
+ const found = usable.find((prefix) => current.startsWith(prefix));
1747
+ if (found === void 0) return stripped && current.length > 0 ? current : null;
1748
+ current = current.slice(found.length);
1749
+ stripped = true;
1750
+ }
1751
+ return usable.some((prefix) => current.startsWith(prefix)) || current.length === 0 ? null : stripped ? current : null;
1752
+ }
1753
+ //#endregion
1574
1754
  //#region src/session.ts
1575
1755
  /**
1576
1756
  * One long-lived inner Qoder CLI session per host session id: a channel-fed
@@ -1584,7 +1764,7 @@ function jsonSchemaToShape(parameters) {
1584
1764
  /** MCP server name this adapter exposes host tools under. */
1585
1765
  const MCP_SERVER_NAME = "dsh-host";
1586
1766
  /** Prefix qodercli uses for this server's tools inside `canUseTool`. */
1587
- const MCP_TOOL_PREFIX$1 = `mcp__${MCP_SERVER_NAME}__`;
1767
+ const MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
1588
1768
  /**
1589
1769
  * How long a handler the CLI never announced waits for a result before failing.
1590
1770
  *
@@ -1597,6 +1777,128 @@ const DEFAULT_TOOL_RESULT_TIMEOUT_MS = 12e4;
1597
1777
  const DEFAULT_ABORT_GRACE_MS = 5e3;
1598
1778
  /** Inner turns allowed for one side-channel (title, compaction) request. */
1599
1779
  const DEFAULT_COLD_MAX_TURNS = 4;
1780
+ /**
1781
+ * Keeps one in-process MCP server's tool set equal to the host's live set.
1782
+ *
1783
+ * The host's tool list is not fixed for a session's lifetime: `dsh-ops` adds
1784
+ * and withdraws tools as a session's mode changes and as `ops_discover_tools`
1785
+ * pulls a deferred capability in, and DSH republishes that change to the model
1786
+ * as `tool-addition` / `tool-removal` blocks. The MCP SDK, however, refuses a
1787
+ * second `registerTool` for a name it already holds ("Tool X is already
1788
+ * registered") and offers no unregister of its own, so a naive replay leaves a
1789
+ * changed schema at its old definition and can never take a withdrawn tool back
1790
+ * out. The model then calls a name the server does not have, and CodeBuddy
1791
+ * answers it with `Tool "…" does not exist in the current tool set.` instead of
1792
+ * a host result — the "tool went missing mid-conversation" symptom.
1793
+ *
1794
+ * This wrapper therefore reconciles by name: register what is new, `update()`
1795
+ * what changed, and `remove()` what the host withdrew. The call handler is built
1796
+ * per registered tool and answers through the session's tool-result pairing, so
1797
+ * a tool re-registered after a mode change still collects its own result.
1798
+ */
1799
+ var HostToolRegistry = class {
1800
+ host;
1801
+ handlerFor;
1802
+ onProblem;
1803
+ /** What this registry has actually installed, by tool name, with its schema hash. */
1804
+ installed = /* @__PURE__ */ new Map();
1805
+ constructor(host, handlerFor, onProblem = () => {}) {
1806
+ this.host = host;
1807
+ this.handlerFor = handlerFor;
1808
+ this.onProblem = onProblem;
1809
+ }
1810
+ /**
1811
+ * Declare the tools capability before the transport connects.
1812
+ *
1813
+ * Must run before `connect()`, because the SDK refuses a capability change
1814
+ * afterwards. Without it a session whose first turn published no host tools
1815
+ * connects with no tools capability, and every tool the host offers later can
1816
+ * only throw — see {@link ToolRegistryHost.setToolRequestHandlers}.
1817
+ */
1818
+ prepare() {
1819
+ try {
1820
+ this.host.setToolRequestHandlers?.();
1821
+ } catch (error) {
1822
+ this.onProblem(`MCP tools 能力未能在连接前声明:${errorText(error)}`);
1823
+ }
1824
+ }
1825
+ /**
1826
+ * Make the installed tool set match `tools` exactly.
1827
+ *
1828
+ * @param tools - the host's live tool schemas, in the order the host published them.
1829
+ * @returns whether anything was added, changed or removed.
1830
+ */
1831
+ reconcile(tools) {
1832
+ const wanted = /* @__PURE__ */ new Map();
1833
+ for (const schema of tools) {
1834
+ const hash = JSON.stringify([schema.description, schema.parameters ?? {}]);
1835
+ wanted.set(schema.name, {
1836
+ hash,
1837
+ schema
1838
+ });
1839
+ }
1840
+ let changed = false;
1841
+ for (const [name, entry] of [...this.installed.entries()]) {
1842
+ if (wanted.has(name)) continue;
1843
+ try {
1844
+ entry.handle.remove();
1845
+ } catch (error) {
1846
+ this.onProblem(`工具 ${name} 无法从 MCP 注销:${errorText(error)}`);
1847
+ }
1848
+ this.installed.delete(name);
1849
+ changed = true;
1850
+ }
1851
+ for (const [name, { hash, schema }] of wanted) {
1852
+ const existing = this.installed.get(name);
1853
+ if (existing !== void 0 && existing.hash === hash) continue;
1854
+ const description = schema.description.length > 0 ? schema.description : name;
1855
+ const inputSchema = jsonSchemaToShape(schema.parameters ?? {});
1856
+ if (existing !== void 0) try {
1857
+ existing.handle.update({
1858
+ description,
1859
+ paramsSchema: inputSchema
1860
+ });
1861
+ this.installed.set(name, {
1862
+ hash,
1863
+ handle: existing.handle
1864
+ });
1865
+ changed = true;
1866
+ continue;
1867
+ } catch (error) {
1868
+ this.onProblem(`工具 ${name} 的 schema 更新失败,改为重新注册:${errorText(error)}`);
1869
+ try {
1870
+ existing.handle.remove();
1871
+ } catch {}
1872
+ this.installed.delete(name);
1873
+ }
1874
+ try {
1875
+ const handle = this.host.registerTool(name, {
1876
+ description,
1877
+ inputSchema
1878
+ }, this.handlerFor(name));
1879
+ this.installed.set(name, {
1880
+ hash,
1881
+ handle
1882
+ });
1883
+ changed = true;
1884
+ } catch (error) {
1885
+ this.onProblem(`宿主工具 ${name} 未能注册进 MCP server:${errorText(error)}`);
1886
+ }
1887
+ }
1888
+ if (changed) try {
1889
+ this.host.sendToolListChanged?.();
1890
+ } catch {}
1891
+ return changed;
1892
+ }
1893
+ /** Names currently installed, for diagnostics and tests. */
1894
+ names() {
1895
+ return [...this.installed.keys()];
1896
+ }
1897
+ };
1898
+ /** One error's message, for the diagnostics above. */
1899
+ function errorText(error) {
1900
+ return error instanceof Error ? error.message : String(error);
1901
+ }
1600
1902
  /** Minimal push-only async channel feeding the SDK's streaming-input mode. */
1601
1903
  function createChannel() {
1602
1904
  const queue = [];
@@ -1751,15 +2053,16 @@ function meteredUsage(real, reasoning) {
1751
2053
  }
1752
2054
  /**
1753
2055
  * The host tool runtime dispatches by the bare host name; the inner model
1754
- * only ever sees the namespaced MCP form, so strip the prefix on the way out.
2056
+ * only ever sees the namespaced MCP form, so strip every prefix layer on the
2057
+ * way out. See {@link stripMcpNamespace} for why one layer is not enough.
1755
2058
  */
1756
2059
  function hostToolName$1(name) {
1757
- return name.startsWith(MCP_TOOL_PREFIX$1) ? name.slice(MCP_TOOL_PREFIX$1.length) : name;
2060
+ return stripMcpNamespace(name, [MCP_TOOL_PREFIX]) ?? name;
1758
2061
  }
1759
2062
  /** Deny native tools, allow this adapter's MCP tools. */
1760
2063
  async function gateTools(toolName, _input, options) {
1761
2064
  const echo = options.toolUseID !== void 0 ? { toolUseID: options.toolUseID } : {};
1762
- if (toolName.startsWith(MCP_TOOL_PREFIX$1)) return {
2065
+ if (toolName.startsWith(MCP_TOOL_PREFIX)) return {
1763
2066
  behavior: "allow",
1764
2067
  ...echo
1765
2068
  };
@@ -2102,7 +2405,22 @@ var QoderSession = class {
2102
2405
  name: MCP_SERVER_NAME,
2103
2406
  tools: []
2104
2407
  });
2105
- registered = /* @__PURE__ */ new Map();
2408
+ /**
2409
+ * Reconciles the live host tool list into {@link mcp}.
2410
+ *
2411
+ * The session outlives the host's tool list: `dsh-ops` publishes a different
2412
+ * set per mode and `ops_discover_tools` adds capabilities mid-conversation.
2413
+ * Installing only what is new left the server unable to ever replace a
2414
+ * changed schema (the MCP SDK refuses a duplicate name), so this owns the
2415
+ * add/update/remove bookkeeping instead of a name→hash map.
2416
+ */
2417
+ registry = new HostToolRegistry(this.mcp.instance, () => async (_args) => {
2418
+ const result = await this.pairing.claim(this.toolResultTimeoutMs);
2419
+ return {
2420
+ content: result.content,
2421
+ ...result.isError ? { isError: true } : {}
2422
+ };
2423
+ }, (message) => console.warn(`[dsh-agent-sdk-bridge] ${message}`));
2106
2424
  queue = null;
2107
2425
  model;
2108
2426
  reasoningEffort;
@@ -2201,6 +2519,7 @@ var QoderSession = class {
2201
2519
  if (isDaemonConflict(error)) resetSdk(this.brand);
2202
2520
  }
2203
2521
  const sdk = await loadSdk(this.brand);
2522
+ this.registry.prepare();
2204
2523
  const q = sdk.query({
2205
2524
  prompt: this.channel,
2206
2525
  options: {
@@ -2255,7 +2574,7 @@ var QoderSession = class {
2255
2574
  * per call, in execution order, before dispatching the MCP message).
2256
2575
  */
2257
2576
  canUseTool = (toolName, _input, options) => {
2258
- if (toolName.startsWith(MCP_TOOL_PREFIX$1)) {
2577
+ if (toolName.startsWith(MCP_TOOL_PREFIX)) {
2259
2578
  if (options.toolUseID !== void 0) this.pairing.announce(options.toolUseID);
2260
2579
  return Promise.resolve({
2261
2580
  behavior: "allow",
@@ -2268,28 +2587,19 @@ var QoderSession = class {
2268
2587
  ...options.toolUseID === void 0 ? {} : { toolUseID: options.toolUseID }
2269
2588
  });
2270
2589
  };
2271
- /** Register any host tools whose schema this session's MCP server lacks. */
2590
+ /**
2591
+ * Make this session's MCP tool set match the host's live tool list.
2592
+ *
2593
+ * The host adds and withdraws tools during a conversation (`dsh-ops` mode
2594
+ * switches, `ops_discover_tools`), so this reconciles rather than only adds:
2595
+ * a tool that appears mid-session is registered, a changed schema is updated
2596
+ * in place, and a withdrawn tool is removed. See {@link HostToolRegistry} for
2597
+ * the failure this prevents — the model calling a name the MCP server no
2598
+ * longer had, which the CLI answers with `Tool "…" does not exist in the
2599
+ * current tool set.` instead of a host result.
2600
+ */
2272
2601
  ensureTools(tools) {
2273
- for (const schema of tools) {
2274
- const hash = JSON.stringify(schema.parameters ?? {});
2275
- if (this.registered.get(schema.name) === hash) continue;
2276
- const shape = jsonSchemaToShape(schema.parameters ?? {});
2277
- try {
2278
- this.mcp.instance.registerTool(schema.name, {
2279
- description: schema.description.length > 0 ? schema.description : schema.name,
2280
- inputSchema: shape
2281
- }, async (args) => {
2282
- const result = await this.pairing.claim(this.toolResultTimeoutMs);
2283
- return {
2284
- content: result.content,
2285
- ...result.isError ? { isError: true } : {}
2286
- };
2287
- });
2288
- } catch {
2289
- continue;
2290
- }
2291
- this.registered.set(schema.name, hash);
2292
- }
2602
+ this.registry.reconcile(tools);
2293
2603
  }
2294
2604
  /**
2295
2605
  * Deliver host tool results to parked or buffered handlers, keyed by call id,
@@ -3020,6 +3330,12 @@ var QoderUsage = class {
3020
3330
  cached;
3021
3331
  inflight;
3022
3332
  /**
3333
+ * Bumped by {@link invalidate}. A fetch that started before a sign-in may
3334
+ * still resolve with the previous account's numbers, so it must neither be
3335
+ * shared with later readers nor written back to the cache.
3336
+ */
3337
+ epoch = 0;
3338
+ /**
3023
3339
  * @param brand - which edition's CLI answers.
3024
3340
  * @param ttlMs - how long a reading stays fresh; read per use.
3025
3341
  * @param timeoutMs - how long one round trip may take.
@@ -3041,17 +3357,31 @@ var QoderUsage = class {
3041
3357
  return this.missingCli();
3042
3358
  }
3043
3359
  const ttlMs = readLive(this.ttlMs, DEFAULT_USAGE_CACHE_TTL_MS);
3360
+ const epoch = this.epoch;
3044
3361
  if (!fresh && this.cached !== void 0 && Date.now() - this.cached.at < ttlMs) return this.cached;
3045
- this.inflight ??= this.fetch().finally(() => {
3046
- this.inflight = void 0;
3047
- });
3048
- const snapshot = await this.inflight;
3049
- this.cached = snapshot;
3362
+ let entry = this.inflight;
3363
+ if (entry === void 0 || entry.epoch !== epoch) {
3364
+ const promise = this.fetch();
3365
+ entry = {
3366
+ epoch,
3367
+ promise
3368
+ };
3369
+ this.inflight = entry;
3370
+ const settled = entry;
3371
+ const clear = () => {
3372
+ if (this.inflight === settled) this.inflight = void 0;
3373
+ };
3374
+ promise.then(clear, clear);
3375
+ }
3376
+ const snapshot = await entry.promise;
3377
+ if (epoch === this.epoch) this.cached = snapshot;
3050
3378
  return snapshot;
3051
3379
  }
3052
- /** Drop the cached reading. */
3380
+ /** Drop the cached reading, including any fetch that started before now. */
3053
3381
  invalidate() {
3054
3382
  this.cached = void 0;
3383
+ this.epoch += 1;
3384
+ this.inflight = void 0;
3055
3385
  }
3056
3386
  /** The reading for a machine whose CLI is not installed. */
3057
3387
  missingCli() {
@@ -3436,6 +3766,21 @@ var QoderAdapter = class extends LlmAdapter {
3436
3766
  invalidateUsage() {
3437
3767
  this.usage.invalidate();
3438
3768
  }
3769
+ /**
3770
+ * Forget everything that was read under the account that just left.
3771
+ *
3772
+ * Signing in or out replaces the credentials on disk, but the SDK daemon and
3773
+ * every warm session loaded the old ones when they started, and the catalog
3774
+ * and quota caches describe that same old account. Signing out has to drop
3775
+ * the sessions; signing in has to drop all four, or the page keeps showing
3776
+ * the previous account until the process restarts.
3777
+ */
3778
+ resetAccount() {
3779
+ this.catalog.invalidate();
3780
+ this.usage.invalidate();
3781
+ this.sessions.closeAll();
3782
+ discardSdk(this.brand);
3783
+ }
3439
3784
  /** Whether the user switched one model off. */
3440
3785
  isModelDisabled(id) {
3441
3786
  return this.disabledModels.has(id);
@@ -3543,7 +3888,7 @@ var QoderAdapter = class extends LlmAdapter {
3543
3888
  async *dispatch(options, generation) {
3544
3889
  const model = resolveQoderModelId(options.model, this.modelAliases);
3545
3890
  if (options.sessionId === void 0 || options.purpose !== void 0) {
3546
- const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.imagePath), this.imagePath) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
3891
+ const prompt = feedToText(renderSideChannelFeed(options.system, options.messages, this.imagePath), this.imagePath);
3547
3892
  yield* this.sessions.coldStream(options, prompt, model);
3548
3893
  return;
3549
3894
  }
@@ -3725,6 +4070,23 @@ function planContinuation(previous, current) {
3725
4070
  * @module dsh-agent-sdk-bridge/codebuddy-state
3726
4071
  */
3727
4072
  /**
4073
+ * A stored account reading with its credential removed.
4074
+ *
4075
+ * The CLI's `accountInfo()` answer carries a bearer token, and older versions
4076
+ * persisted that object whole — a second copy of the credential in a file that
4077
+ * gets backed up and pasted into bug reports, one the plugin never read. A
4078
+ * region holds exactly one credential, in `token`.
4079
+ */
4080
+ function withoutCredential(account) {
4081
+ if (account === void 0) return void 0;
4082
+ const clean = {};
4083
+ for (const [key, value] of Object.entries(account)) {
4084
+ if (/token|secret|credential|password|cookie/i.test(key)) continue;
4085
+ clean[key] = value;
4086
+ }
4087
+ return clean;
4088
+ }
4089
+ /**
3728
4090
  * The default file path.
3729
4091
  *
3730
4092
  * `DSH_HOME` is honoured so a desktop profile and a web profile keep separate
@@ -3769,13 +4131,46 @@ var CodeBuddyStateStore = class {
3769
4131
  this.loaded = true;
3770
4132
  try {
3771
4133
  const parsed = JSON.parse(readFileSync(this.file, "utf8"));
3772
- if (parsed.version === 1 && parsed.regions !== null && typeof parsed.regions === "object") this.state = {
3773
- version: 1,
3774
- regions: parsed.regions
3775
- };
4134
+ if (parsed.version === 1 && parsed.regions !== null && typeof parsed.regions === "object") {
4135
+ this.state = {
4136
+ version: 1,
4137
+ regions: parsed.regions
4138
+ };
4139
+ this.recoverLostTokens();
4140
+ }
3776
4141
  } catch {}
3777
4142
  return this.state;
3778
4143
  }
4144
+ /**
4145
+ * Lift a credential the old layout hid inside the account object.
4146
+ *
4147
+ * The CLI's `accountInfo()` answer carries a bearer token of its own, and an
4148
+ * earlier version persisted that whole object here. When the top-level
4149
+ * `token` was later dropped — which any quota failure used to do, because
4150
+ * expiry was *guessed* from the error text — the region read as signed out
4151
+ * even though a working credential still sat in the file, and nothing could
4152
+ * recover it without a fresh browser login. This picks the copy back up.
4153
+ *
4154
+ * {@link persist} no longer stores a token inside the account, so this runs
4155
+ * only over files written by those older versions.
4156
+ */
4157
+ recoverLostTokens() {
4158
+ let recovered = false;
4159
+ for (const [key, saved] of Object.entries(this.state.regions)) {
4160
+ const region = key;
4161
+ const hidden = (saved?.account)?.token;
4162
+ if (saved === void 0 || saved.token !== void 0) continue;
4163
+ if (typeof hidden !== "string" || hidden.length === 0) continue;
4164
+ this.state.regions[region] = {
4165
+ ...saved,
4166
+ token: hidden,
4167
+ signedIn: true,
4168
+ account: withoutCredential(saved.account)
4169
+ };
4170
+ recovered = true;
4171
+ }
4172
+ if (recovered) this.persist();
4173
+ }
3779
4174
  region(region) {
3780
4175
  return this.ensureLoaded().regions[region];
3781
4176
  }
@@ -3807,6 +4202,7 @@ var CodeBuddyStateStore = class {
3807
4202
  const next = { ...state.regions[region] };
3808
4203
  for (const [key, value] of Object.entries(patch)) if (value === void 0) delete next[key];
3809
4204
  else next[key] = value;
4205
+ if (next.account !== void 0) next.account = withoutCredential(next.account);
3810
4206
  state.regions[region] = next;
3811
4207
  this.persist();
3812
4208
  }
@@ -3896,26 +4292,24 @@ const CODEBUDDY_FETCH_TIMEOUT_MS = 3e4;
3896
4292
  const LOGIN_TIMEOUT_MS = 3e5;
3897
4293
  /** Bound for clearing stale credentials before a fresh browser login. */
3898
4294
  const LOGOUT_TIMEOUT_MS = 2e4;
3899
- const MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
3900
- /**
3901
- * The same namespace after the CLI normalises the server name.
3902
- *
3903
- * CodeBuddy rewrites every non-alphanumeric character in an MCP server name to
3904
- * `_`, so a server registered as `dsh-host` is exposed to the model as
3905
- * `mcp__dsh_host__<tool>`. Matching only the registered spelling rejected the
3906
- * host's own tools as "built-ins", which is exactly why the model fell back to
3907
- * `Bash`. The Qoder CLI keeps the hyphen, so both spellings are accepted.
3908
- */
3909
- const MCP_TOOL_PREFIX_SANITIZED = `mcp__${MCP_SERVER_NAME.replace(/[^a-zA-Z0-9]/g, "_")}__`;
4295
+ /** Both spellings, in the order the shared stripper tries them. */
4296
+ const HOST_TOOL_PREFIXES$1 = [`mcp__${MCP_SERVER_NAME}__`, `mcp__${MCP_SERVER_NAME.replace(/[^a-zA-Z0-9]/g, "_")}__`];
3910
4297
  /** Whether a CLI tool name belongs to this plugin's MCP server. */
3911
4298
  function isHostTool(toolName) {
3912
- return toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith(MCP_TOOL_PREFIX_SANITIZED);
4299
+ return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES$1) !== null;
3913
4300
  }
3914
- /** The host-side tool name, with the MCP namespace removed. */
4301
+ /**
4302
+ * The host-side tool name, with every MCP namespace layer removed.
4303
+ *
4304
+ * CodeBuddy qualifies an already-qualified name again, so the handler can be
4305
+ * handed `mcp__dsh_host__mcp__dsh_host__edit`. Stripping one layer produced
4306
+ * `mcp__dsh_host__edit`, a name the host does not have (its tool is `edit`), and
4307
+ * DSH answered `unknown tool "mcp__dsh_host__edit"`; the model retried the
4308
+ * doubled spelling next round and the CLI rejected it with `does not exist in
4309
+ * the current tool set`. See {@link stripMcpNamespace}.
4310
+ */
3915
4311
  function hostToolName(toolName) {
3916
- if (toolName.startsWith(MCP_TOOL_PREFIX)) return toolName.slice(MCP_TOOL_PREFIX.length);
3917
- if (toolName.startsWith(MCP_TOOL_PREFIX_SANITIZED)) return toolName.slice(MCP_TOOL_PREFIX_SANITIZED.length);
3918
- return toolName;
4312
+ return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES$1) ?? toolName;
3919
4313
  }
3920
4314
  /**
3921
4315
  * Whether the CLI answered as the anonymous fallback.
@@ -3964,11 +4358,24 @@ function tokenFor(region) {
3964
4358
  * pins the environment, so a fresh process always reads the right catalog.
3965
4359
  */
3966
4360
  function cliEnv(region) {
3967
- const env = { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) };
4361
+ const env = cliDirEnv(region);
3968
4362
  const token = tokenFor(region);
3969
4363
  if (token !== void 0) env.CODEBUDDY_AUTH_TOKEN = token;
3970
4364
  return { env };
3971
4365
  }
4366
+ /**
4367
+ * The region's own CLI directory, with no credential attached.
4368
+ *
4369
+ * The login, logout and silent-token calls need this and nothing else: they
4370
+ * must not carry a bearer token (login starts fresh, logout clears), but they
4371
+ * absolutely must be scoped to one region. Without it they acted on the CLI's
4372
+ * default `~/.codebuddy`, which both regions share — so signing in for one
4373
+ * region overwrote the other's login, and `logout` for the region the page was
4374
+ * showing left the credential of the other one standing.
4375
+ */
4376
+ function cliDirEnv(region) {
4377
+ return { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) };
4378
+ }
3972
4379
  /** Remember a bearer token in memory and on disk. */
3973
4380
  function rememberBearerToken(region, token, user) {
3974
4381
  if (token.length === 0) return;
@@ -4165,10 +4572,6 @@ var CodeBuddyAccountReader = class {
4165
4572
  }
4166
4573
  async fetch(region) {
4167
4574
  const at = Date.now();
4168
- if (tokenFor(region) === void 0) return {
4169
- at,
4170
- error: `${region === "cn" ? "CodeBuddy 国内版" : "CodeBuddy 国际版"}尚未登录,请在页面顶部选择该区域并登录。`
4171
- };
4172
4575
  try {
4173
4576
  const account = await readAccount(region, readLive(this.timeoutMs, CODEBUDDY_FETCH_TIMEOUT_MS));
4174
4577
  if (isUnauthenticatedAccount(account)) {
@@ -4204,7 +4607,7 @@ var CodeBuddyAccountReader = class {
4204
4607
  };
4205
4608
  } catch (quotaError) {
4206
4609
  const message = quotaError instanceof Error ? quotaError.message : String(quotaError);
4207
- if (isExpiredToken(message)) forgetToken(region);
4610
+ if (isCredentialRejected(quotaError)) forgetToken(region);
4208
4611
  else codeBuddyState.patch(region, {
4209
4612
  quota: void 0,
4210
4613
  quotaError: message
@@ -4242,7 +4645,7 @@ async function readAccount(region, timeoutMs) {
4242
4645
  });
4243
4646
  try {
4244
4647
  await withTimeout$1(q.connect(), timeoutMs);
4245
- return await withTimeout$1(q.accountInfo(), timeoutMs);
4648
+ return withoutCredential(await withTimeout$1(q.accountInfo(), timeoutMs)) ?? {};
4246
4649
  } finally {
4247
4650
  await q.return().catch(() => void 0);
4248
4651
  }
@@ -4329,15 +4732,21 @@ function formatLocalTime(date) {
4329
4732
  /**
4330
4733
  * A bearer token for the region, from a recent login or a silent SDK read.
4331
4734
  *
4332
- * `authenticate` returns the CLI's existing account token without opening a
4333
- * browser when the region is already signed in, so this stays a read. When it
4334
- * is not signed in the call times out; callers treat that as "log in first".
4735
+ * The silent read is the documented behaviour of `authenticate` — return the
4736
+ * CLI's existing token instead of opening a browser when the region is signed
4737
+ * in — but it did not work as measured: on a machine with a live CodeBuddy
4738
+ * login it timed out for both regions, each in the shared default directory and
4739
+ * in both per-region directories. So treat it as best effort, and never as a
4740
+ * place to recover from: the copy this plugin saved is the only credential a
4741
+ * session can count on, which is why dropping it used to read as "not signed
4742
+ * in" even while the account still worked.
4335
4743
  */
4336
4744
  async function readBearerToken(region) {
4337
4745
  const cached = tokenFor(region);
4338
4746
  if (cached !== void 0) return cached;
4339
4747
  const result = await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_authenticate({
4340
4748
  environment: codeBuddyEnvironment(region),
4749
+ env: cliDirEnv(region),
4341
4750
  timeout: 3e3,
4342
4751
  onAuthUrl: () => {}
4343
4752
  }), 6e3);
@@ -4393,7 +4802,7 @@ async function fetchCodeBuddyQuota(region, token, fetchImpl = fetch) {
4393
4802
  });
4394
4803
  const text = await response.text();
4395
4804
  if (!response.ok) {
4396
- if (response.status === 401 || response.status === 403) throw new Error("CodeBuddy 登录已过期,请重新登录");
4805
+ if (response.status === 401 || response.status === 403) throw new CredentialRejectedError("CodeBuddy 登录已过期,请重新登录");
4397
4806
  const detail = text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 160);
4398
4807
  throw new Error(`CodeBuddy 额度接口返回 HTTP ${response.status}${detail === "" ? "" : `:${detail}`}`);
4399
4808
  }
@@ -4405,9 +4814,31 @@ async function fetchCodeBuddyQuota(region, token, fetchImpl = fetch) {
4405
4814
  }
4406
4815
  return parseCodeBuddyQuota(payload);
4407
4816
  }
4408
- /** Whether a quota failure means the stored credential is no longer usable. */
4409
- function isExpiredToken(message) {
4410
- return /401|403|登录已过期|unauthor|token/i.test(message);
4817
+ /**
4818
+ * The credential this region holds was rejected by the endpoint.
4819
+ *
4820
+ * Thrown where the rejection is *known* — an explicit HTTP 401/403 — rather
4821
+ * than inferred from the error text. Inferring it was the bug: the loose
4822
+ * matcher below used to treat any failure whose message happened to contain
4823
+ * "token", "401" inside a number, or an HTML body mentioning a token, as an
4824
+ * expired login. It then dropped a working credential, and because a missing
4825
+ * local token reads as "signed out", the page showed an account as not signed
4826
+ * in while the CLI still had a usable login.
4827
+ */
4828
+ var CredentialRejectedError = class extends Error {};
4829
+ /**
4830
+ * Whether a quota failure genuinely means the credential no longer works.
4831
+ *
4832
+ * The typed error carries the CLI's own expiry sentence, which is also matched
4833
+ * here because the message is ours, fixed, and not derived from server text.
4834
+ * Everything else — a 5xx, a bad payload, a timeout, an unreachable endpoint —
4835
+ * leaves the credential alone.
4836
+ *
4837
+ * @param error - whatever quota reading threw.
4838
+ */
4839
+ function isCredentialRejected(error) {
4840
+ if (error instanceof CredentialRejectedError) return true;
4841
+ return (error instanceof Error ? error.message : String(error)) === "CodeBuddy 登录已过期,请重新登录";
4411
4842
  }
4412
4843
  /** Read quota, retrying once with a fresh token after an auth failure. */
4413
4844
  async function readQuotaWithToken(region) {
@@ -4417,7 +4848,7 @@ async function readQuotaWithToken(region) {
4417
4848
  try {
4418
4849
  return await fetchCodeBuddyQuota(region, token);
4419
4850
  } catch (error) {
4420
- if (!isExpiredToken(error instanceof Error ? error.message : String(error))) throw error;
4851
+ if (!isCredentialRejected(error)) throw error;
4421
4852
  forgetToken(region);
4422
4853
  return await fetchCodeBuddyQuota(region, await readBearerToken(region).catch((renewError) => {
4423
4854
  throw new Error(authErrorText(region, renewError));
@@ -4466,7 +4897,10 @@ var CodeBuddyAuth = class {
4466
4897
  async logout(region) {
4467
4898
  let failure;
4468
4899
  try {
4469
- await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), CODEBUDDY_FETCH_TIMEOUT_MS);
4900
+ await withTimeout$1((await loadCodeBuddySdk()).unstable_v2_logout({
4901
+ environment: codeBuddyEnvironment(region),
4902
+ env: cliDirEnv(region)
4903
+ }), CODEBUDDY_FETCH_TIMEOUT_MS);
4470
4904
  } catch (error) {
4471
4905
  failure = error instanceof Error ? error.message : String(error);
4472
4906
  }
@@ -4487,11 +4921,15 @@ var CodeBuddyAuth = class {
4487
4921
  const { region } = status;
4488
4922
  try {
4489
4923
  const sdk = await loadCodeBuddySdk();
4490
- await withTimeout$1(sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
4924
+ await withTimeout$1(sdk.unstable_v2_logout({
4925
+ environment: codeBuddyEnvironment(region),
4926
+ env: cliDirEnv(region)
4927
+ }), LOGOUT_TIMEOUT_MS).catch(() => void 0);
4491
4928
  if (!this.current(run)) return;
4492
4929
  bearerTokens.delete(region);
4493
4930
  const result = await sdk.unstable_v2_authenticate({
4494
4931
  environment: codeBuddyEnvironment(region),
4932
+ env: cliDirEnv(region),
4495
4933
  timeout: LOGIN_TIMEOUT_MS,
4496
4934
  onAuthUrl: (state) => {
4497
4935
  status.url = state.authUrl;
@@ -4556,8 +4994,18 @@ var CodeBuddySession = class {
4556
4994
  session = null;
4557
4995
  mcp = null;
4558
4996
  pairing = new ToolResultPairing();
4559
- registered = /* @__PURE__ */ new Map();
4560
4997
  toolSchemas = [];
4998
+ /**
4999
+ * Reconciles the live host tool list into {@link mcp}.
5000
+ *
5001
+ * Created with the MCP server, because that is what it installs into. Owned
5002
+ * here rather than inline so a tool that the host adds or withdraws during a
5003
+ * conversation is actually added or withdrawn: the MCP SDK refuses a second
5004
+ * `registerTool` for a name it already holds, so the previous
5005
+ * name→hash replay could never replace a changed schema, and `Tool "…" does
5006
+ * not exist in the current tool set.` was what the model got for its trouble.
5007
+ */
5008
+ registry = null;
4561
5009
  queue = null;
4562
5010
  disposed = false;
4563
5011
  abortPending = false;
@@ -4632,12 +5080,14 @@ var CodeBuddySession = class {
4632
5080
  * compacts (and the gateway rejects) anything past 276K — while the host,
4633
5081
  * told 1M, keeps showing and feeding a larger history. Replaying that history
4634
5082
  * then collapses to a summary. Applying the same number the host divides by
4635
- * keeps the two in step; models that expose no choice reject it and keep
4636
- * their default.
5083
+ * keeps the two in step; the adapter therefore sends a window for every model
5084
+ * it knows about, not only the ones that advertise a choice — the mainland
5085
+ * catalog declares no lengths anywhere and its physical `maxInputTokens` is a
5086
+ * provider number the CLI is free to ignore when left to itself.
4637
5087
  *
4638
- * The CLI refuses to clear the override (`contextWindow must be a positive
4639
- * safe integer`), so the adapter sends the model's default instead when the
4640
- * page returns to "default".
5088
+ * A rejected value keeps the CLI on its own default, which is the one case
5089
+ * where the two denominators can still disagree; it is reported nowhere, so
5090
+ * the host's figure stays the visible contract.
4641
5091
  */
4642
5092
  async applyContextWindow(session) {
4643
5093
  const window = this.contextWindow;
@@ -4663,28 +5113,18 @@ var CodeBuddySession = class {
4663
5113
  this.toolSchemas = tools;
4664
5114
  this.registerTools();
4665
5115
  }
5116
+ /**
5117
+ * Reconcile this session's MCP tool set with the host's live list.
5118
+ *
5119
+ * Add, update in place, and remove: the host withdraws tools when a mode
5120
+ * changes and adds them when `ops_discover_tools` resolves a deferred one, and
5121
+ * a tool the model can still name but the server no longer holds is answered
5122
+ * with `Tool "…" does not exist in the current tool set.` — the CLI never
5123
+ * forwards it to the host, so no tool result ever comes back.
5124
+ */
4666
5125
  registerTools() {
4667
- if (this.mcp === null) return;
4668
- for (const schema of this.toolSchemas) {
4669
- const hash = JSON.stringify(schema.parameters ?? {});
4670
- if (this.registered.get(schema.name) === hash) continue;
4671
- const shape = jsonSchemaToShape(schema.parameters ?? {});
4672
- try {
4673
- this.mcp.instance.registerTool(schema.name, {
4674
- description: schema.description.length > 0 ? schema.description : schema.name,
4675
- inputSchema: shape
4676
- }, async () => {
4677
- const result = await this.pairing.claim(this.toolResultTimeoutMs);
4678
- return {
4679
- content: result.content,
4680
- ...result.isError ? { isError: true } : {}
4681
- };
4682
- });
4683
- } catch {
4684
- continue;
4685
- }
4686
- this.registered.set(schema.name, hash);
4687
- }
5126
+ if (this.registry === null) return;
5127
+ this.registry.reconcile(this.toolSchemas);
4688
5128
  }
4689
5129
  /** Hand the host's tool results to parked or buffered handlers. */
4690
5130
  deliverToolResults(tail) {
@@ -4773,6 +5213,14 @@ var CodeBuddySession = class {
4773
5213
  name: MCP_SERVER_NAME,
4774
5214
  tools: []
4775
5215
  });
5216
+ this.registry ??= new HostToolRegistry(this.mcp.instance, () => async () => {
5217
+ const result = await this.pairing.claim(this.toolResultTimeoutMs);
5218
+ return {
5219
+ content: result.content,
5220
+ ...result.isError ? { isError: true } : {}
5221
+ };
5222
+ }, (message) => console.warn(`[dsh-agent-sdk-bridge] ${message}`));
5223
+ this.registry.prepare();
4776
5224
  this.registerTools();
4777
5225
  const session = sdk.unstable_v2_createSession({
4778
5226
  environment: codeBuddyEnvironment(this.region),
@@ -5553,7 +6001,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
5553
6001
  if (!this.isSignedIn(region)) throw new Error(`${region === "cn" ? "CodeBuddy 国内版" : "CodeBuddy 国际版"}尚未登录,请先在设置 → CodeBuddy 中登录。`);
5554
6002
  const model = resolveCodeBuddyModelId(options.model, this.aliases);
5555
6003
  if (options.sessionId === void 0 || options.purpose !== void 0) {
5556
- const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
6004
+ const prompt = feedToText(renderSideChannelFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath);
5557
6005
  for (const chunk of await codeBuddyColdStream(region, prompt, model, options)) yield chunk;
5558
6006
  return;
5559
6007
  }
@@ -5920,12 +6368,18 @@ function minimaxCliCommand() {
5920
6368
  const HOST_TOOL_PREFIXES = [`mcp__${MINIMAX_MCP_SERVER}__`, `mcp__${MINIMAX_MCP_SERVER.replace(/[^a-zA-Z0-9]/g, "_")}__`];
5921
6369
  /** Whether a CLI tool name belongs to this plugin's MCP server. */
5922
6370
  function isHostMcpTool(name) {
5923
- return HOST_TOOL_PREFIXES.some((prefix) => name.startsWith(prefix));
6371
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) !== null;
5924
6372
  }
5925
- /** The host-side name of an MCP tool, without the namespace. */
6373
+ /**
6374
+ * The host-side name of an MCP tool, without any namespace layer.
6375
+ *
6376
+ * Every layer is peeled, not just one: a model that emits an already-qualified
6377
+ * name has it qualified again by the CLI, and handing the host
6378
+ * `mcp__dsh-host__edit` made DSH answer `unknown tool` even though the tool was
6379
+ * registered under `edit`. See {@link stripMcpNamespace}.
6380
+ */
5926
6381
  function hostMcpToolName(name) {
5927
- for (const prefix of HOST_TOOL_PREFIXES) if (name.startsWith(prefix)) return name.slice(prefix.length);
5928
- return name;
6382
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) ?? name;
5929
6383
  }
5930
6384
  /** Thinking-effort values an ACP config option advertises, minus `default`. */
5931
6385
  function effortValues(options) {
@@ -8289,7 +8743,7 @@ var MinimaxAdapter = class extends LlmAdapter {
8289
8743
  if (await minimaxRegionBlocked(region)) throw new Error(minimaxRegionBlockMessage(region));
8290
8744
  const model = resolveMinimaxModelId(options.model, this.aliases);
8291
8745
  if (options.sessionId === void 0 || options.purpose !== void 0) {
8292
- const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
8746
+ const prompt = feedToText(renderSideChannelFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath);
8293
8747
  for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk;
8294
8748
  return;
8295
8749
  }
@@ -8942,9 +9396,7 @@ async function handleApi(req, res, adapters) {
8942
9396
  const mode = parsed.mode;
8943
9397
  const result = startSetup(postBrand, mode, (code) => {
8944
9398
  if (code !== 0) return;
8945
- qoder.invalidateCatalog();
8946
- qoder.invalidateUsage();
8947
- if (mode === "logout") qoder.closeSessions();
9399
+ qoder.resetAccount();
8948
9400
  });
8949
9401
  if (!result.started) {
8950
9402
  send(res, result.reason === "busy" ? 409 : result.reason === "unsupported" ? 501 : 500, { error: result.error });