dsh-agent-sdk-bridge 1.2.3 → 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
  }
@@ -3947,26 +4292,24 @@ const CODEBUDDY_FETCH_TIMEOUT_MS = 3e4;
3947
4292
  const LOGIN_TIMEOUT_MS = 3e5;
3948
4293
  /** Bound for clearing stale credentials before a fresh browser login. */
3949
4294
  const LOGOUT_TIMEOUT_MS = 2e4;
3950
- const MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
3951
- /**
3952
- * The same namespace after the CLI normalises the server name.
3953
- *
3954
- * CodeBuddy rewrites every non-alphanumeric character in an MCP server name to
3955
- * `_`, so a server registered as `dsh-host` is exposed to the model as
3956
- * `mcp__dsh_host__<tool>`. Matching only the registered spelling rejected the
3957
- * host's own tools as "built-ins", which is exactly why the model fell back to
3958
- * `Bash`. The Qoder CLI keeps the hyphen, so both spellings are accepted.
3959
- */
3960
- 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, "_")}__`];
3961
4297
  /** Whether a CLI tool name belongs to this plugin's MCP server. */
3962
4298
  function isHostTool(toolName) {
3963
- return toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith(MCP_TOOL_PREFIX_SANITIZED);
4299
+ return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES$1) !== null;
3964
4300
  }
3965
- /** 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
+ */
3966
4311
  function hostToolName(toolName) {
3967
- if (toolName.startsWith(MCP_TOOL_PREFIX)) return toolName.slice(MCP_TOOL_PREFIX.length);
3968
- if (toolName.startsWith(MCP_TOOL_PREFIX_SANITIZED)) return toolName.slice(MCP_TOOL_PREFIX_SANITIZED.length);
3969
- return toolName;
4312
+ return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES$1) ?? toolName;
3970
4313
  }
3971
4314
  /**
3972
4315
  * Whether the CLI answered as the anonymous fallback.
@@ -4651,8 +4994,18 @@ var CodeBuddySession = class {
4651
4994
  session = null;
4652
4995
  mcp = null;
4653
4996
  pairing = new ToolResultPairing();
4654
- registered = /* @__PURE__ */ new Map();
4655
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;
4656
5009
  queue = null;
4657
5010
  disposed = false;
4658
5011
  abortPending = false;
@@ -4760,28 +5113,18 @@ var CodeBuddySession = class {
4760
5113
  this.toolSchemas = tools;
4761
5114
  this.registerTools();
4762
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
+ */
4763
5125
  registerTools() {
4764
- if (this.mcp === null) return;
4765
- for (const schema of this.toolSchemas) {
4766
- const hash = JSON.stringify(schema.parameters ?? {});
4767
- if (this.registered.get(schema.name) === hash) continue;
4768
- const shape = jsonSchemaToShape(schema.parameters ?? {});
4769
- try {
4770
- this.mcp.instance.registerTool(schema.name, {
4771
- description: schema.description.length > 0 ? schema.description : schema.name,
4772
- inputSchema: shape
4773
- }, async () => {
4774
- const result = await this.pairing.claim(this.toolResultTimeoutMs);
4775
- return {
4776
- content: result.content,
4777
- ...result.isError ? { isError: true } : {}
4778
- };
4779
- });
4780
- } catch {
4781
- continue;
4782
- }
4783
- this.registered.set(schema.name, hash);
4784
- }
5126
+ if (this.registry === null) return;
5127
+ this.registry.reconcile(this.toolSchemas);
4785
5128
  }
4786
5129
  /** Hand the host's tool results to parked or buffered handlers. */
4787
5130
  deliverToolResults(tail) {
@@ -4870,6 +5213,14 @@ var CodeBuddySession = class {
4870
5213
  name: MCP_SERVER_NAME,
4871
5214
  tools: []
4872
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();
4873
5224
  this.registerTools();
4874
5225
  const session = sdk.unstable_v2_createSession({
4875
5226
  environment: codeBuddyEnvironment(this.region),
@@ -5650,7 +6001,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
5650
6001
  if (!this.isSignedIn(region)) throw new Error(`${region === "cn" ? "CodeBuddy 国内版" : "CodeBuddy 国际版"}尚未登录,请先在设置 → CodeBuddy 中登录。`);
5651
6002
  const model = resolveCodeBuddyModelId(options.model, this.aliases);
5652
6003
  if (options.sessionId === void 0 || options.purpose !== void 0) {
5653
- 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);
5654
6005
  for (const chunk of await codeBuddyColdStream(region, prompt, model, options)) yield chunk;
5655
6006
  return;
5656
6007
  }
@@ -6017,12 +6368,18 @@ function minimaxCliCommand() {
6017
6368
  const HOST_TOOL_PREFIXES = [`mcp__${MINIMAX_MCP_SERVER}__`, `mcp__${MINIMAX_MCP_SERVER.replace(/[^a-zA-Z0-9]/g, "_")}__`];
6018
6369
  /** Whether a CLI tool name belongs to this plugin's MCP server. */
6019
6370
  function isHostMcpTool(name) {
6020
- return HOST_TOOL_PREFIXES.some((prefix) => name.startsWith(prefix));
6371
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) !== null;
6021
6372
  }
6022
- /** 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
+ */
6023
6381
  function hostMcpToolName(name) {
6024
- for (const prefix of HOST_TOOL_PREFIXES) if (name.startsWith(prefix)) return name.slice(prefix.length);
6025
- return name;
6382
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) ?? name;
6026
6383
  }
6027
6384
  /** Thinking-effort values an ACP config option advertises, minus `default`. */
6028
6385
  function effortValues(options) {
@@ -8386,7 +8743,7 @@ var MinimaxAdapter = class extends LlmAdapter {
8386
8743
  if (await minimaxRegionBlocked(region)) throw new Error(minimaxRegionBlockMessage(region));
8387
8744
  const model = resolveMinimaxModelId(options.model, this.aliases);
8388
8745
  if (options.sessionId === void 0 || options.purpose !== void 0) {
8389
- 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);
8390
8747
  for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk;
8391
8748
  return;
8392
8749
  }
@@ -9039,9 +9396,7 @@ async function handleApi(req, res, adapters) {
9039
9396
  const mode = parsed.mode;
9040
9397
  const result = startSetup(postBrand, mode, (code) => {
9041
9398
  if (code !== 0) return;
9042
- qoder.invalidateCatalog();
9043
- qoder.invalidateUsage();
9044
- if (mode === "logout") qoder.closeSessions();
9399
+ qoder.resetAccount();
9045
9400
  });
9046
9401
  if (!result.started) {
9047
9402
  send(res, result.reason === "busy" ? 409 : result.reason === "unsupported" ? 501 : 500, { error: result.error });