dsh-agent-sdk-bridge 1.2.3 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -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,41 @@ 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
4295
  /**
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, "_")}__`;
4296
+ * The key this plugin's MCP server is registered under, in the CodeBuddy CLI.
4297
+ *
4298
+ * It is the CLI's own normalised spelling - `dsh_host`, not `dsh-host` - and
4299
+ * that choice is the fix for the recurring "tool went missing": the CLI builds
4300
+ * its call-time tool map from `mcp__<key>__<tool>` with the key verbatim,
4301
+ * while several of its own code paths (`parseMcpToolName`, the plugin tool
4302
+ * namer, the wire-format normaliser) rewrite every non-alphanumeric character
4303
+ * to `_`. With a hyphenated key the list showed `mcp__dsh-host__read_files`
4304
+ * while a model that emitted the normalised `mcp__dsh_host__read_files` - as
4305
+ * one did, verbatim, in a failed session - found no entry, and the CLI refused
4306
+ * the call with `Tool "..." does not exist in the current tool set.` before it
4307
+ * ever reached this server. Registering under the normalised spelling makes
4308
+ * list, lookup and normalisation one and the same name, so there is no second
4309
+ * spelling to guess.
4310
+ */
4311
+ const CODEBUDDY_MCP_SERVER_KEY = "dsh_host";
4312
+ /** Both spellings, in the order the shared stripper tries them. */
4313
+ const HOST_TOOL_PREFIXES$1 = [`mcp__${CODEBUDDY_MCP_SERVER_KEY}__`, `mcp__${MCP_SERVER_NAME}__`];
3961
4314
  /** Whether a CLI tool name belongs to this plugin's MCP server. */
3962
4315
  function isHostTool(toolName) {
3963
- return toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith(MCP_TOOL_PREFIX_SANITIZED);
4316
+ return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES$1) !== null;
3964
4317
  }
3965
- /** The host-side tool name, with the MCP namespace removed. */
4318
+ /**
4319
+ * The host-side tool name, with every MCP namespace layer removed.
4320
+ *
4321
+ * CodeBuddy qualifies an already-qualified name again, so the handler can be
4322
+ * handed `mcp__dsh_host__mcp__dsh_host__edit`. Stripping one layer produced
4323
+ * `mcp__dsh_host__edit`, a name the host does not have (its tool is `edit`), and
4324
+ * DSH answered `unknown tool "mcp__dsh_host__edit"`; the model retried the
4325
+ * doubled spelling next round and the CLI rejected it with `does not exist in
4326
+ * the current tool set`. See {@link stripMcpNamespace}.
4327
+ */
3966
4328
  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;
4329
+ return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES$1) ?? toolName;
3970
4330
  }
3971
4331
  /**
3972
4332
  * Whether the CLI answered as the anonymous fallback.
@@ -4651,8 +5011,18 @@ var CodeBuddySession = class {
4651
5011
  session = null;
4652
5012
  mcp = null;
4653
5013
  pairing = new ToolResultPairing();
4654
- registered = /* @__PURE__ */ new Map();
4655
5014
  toolSchemas = [];
5015
+ /**
5016
+ * Reconciles the live host tool list into {@link mcp}.
5017
+ *
5018
+ * Created with the MCP server, because that is what it installs into. Owned
5019
+ * here rather than inline so a tool that the host adds or withdraws during a
5020
+ * conversation is actually added or withdrawn: the MCP SDK refuses a second
5021
+ * `registerTool` for a name it already holds, so the previous
5022
+ * name→hash replay could never replace a changed schema, and `Tool "…" does
5023
+ * not exist in the current tool set.` was what the model got for its trouble.
5024
+ */
5025
+ registry = null;
4656
5026
  queue = null;
4657
5027
  disposed = false;
4658
5028
  abortPending = false;
@@ -4760,31 +5130,21 @@ var CodeBuddySession = class {
4760
5130
  this.toolSchemas = tools;
4761
5131
  this.registerTools();
4762
5132
  }
5133
+ /**
5134
+ * Reconcile this session's MCP tool set with the host's live list.
5135
+ *
5136
+ * Add, update in place, and remove: the host withdraws tools when a mode
5137
+ * changes and adds them when `ops_discover_tools` resolves a deferred one, and
5138
+ * a tool the model can still name but the server no longer holds is answered
5139
+ * with `Tool "…" does not exist in the current tool set.` — the CLI never
5140
+ * forwards it to the host, so no tool result ever comes back.
5141
+ */
4763
5142
  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
- }
5143
+ if (this.registry === null) return;
5144
+ this.registry.reconcile(this.toolSchemas);
4785
5145
  }
4786
5146
  /** Hand the host's tool results to parked or buffered handlers. */
4787
- deliverToolResults(tail) {
5147
+ deliverToolResults(tail, images) {
4788
5148
  let freshUserTurn = false;
4789
5149
  const delivered = /* @__PURE__ */ new Set();
4790
5150
  for (const message of tail) {
@@ -4794,7 +5154,7 @@ var CodeBuddySession = class {
4794
5154
  }
4795
5155
  if (message.role !== "tool") continue;
4796
5156
  delivered.add(this.pairing.deliver(String(message.toolCallId), {
4797
- content: renderCodeBuddyResult(message.content),
5157
+ content: renderCodeBuddyResult(message.content, images),
4798
5158
  isError: message.isError === true
4799
5159
  }));
4800
5160
  }
@@ -4867,15 +5227,23 @@ var CodeBuddySession = class {
4867
5227
  if (this.session !== null) return this.session;
4868
5228
  const sdk = await loadCodeBuddySdk();
4869
5229
  this.mcp ??= sdk.createSdkMcpServer({
4870
- name: MCP_SERVER_NAME,
5230
+ name: CODEBUDDY_MCP_SERVER_KEY,
4871
5231
  tools: []
4872
5232
  });
5233
+ this.registry ??= new HostToolRegistry(this.mcp.instance, () => async () => {
5234
+ const result = await this.pairing.claim(this.toolResultTimeoutMs);
5235
+ return {
5236
+ content: result.content,
5237
+ ...result.isError ? { isError: true } : {}
5238
+ };
5239
+ }, (message) => console.warn(`[dsh-agent-sdk-bridge] ${message}`));
5240
+ this.registry.prepare();
4873
5241
  this.registerTools();
4874
5242
  const session = sdk.unstable_v2_createSession({
4875
5243
  environment: codeBuddyEnvironment(this.region),
4876
5244
  sessionId: randomUUID(),
4877
5245
  model: this.model,
4878
- mcpServers: { [MCP_SERVER_NAME]: this.mcp },
5246
+ mcpServers: { [CODEBUDDY_MCP_SERVER_KEY]: this.mcp },
4879
5247
  canUseTool: this.canUseTool,
4880
5248
  tools: [],
4881
5249
  ...cliEnv(this.region),
@@ -5217,7 +5585,7 @@ var CodeBuddySession = class {
5217
5585
  }
5218
5586
  };
5219
5587
  /** Render host tool-result blocks into the MCP content the inner model reads. */
5220
- function renderCodeBuddyResult(blocks) {
5588
+ function renderCodeBuddyResult(blocks, images) {
5221
5589
  if (!Array.isArray(blocks)) return [{
5222
5590
  type: "text",
5223
5591
  text: String(blocks ?? "")
@@ -5227,11 +5595,18 @@ function renderCodeBuddyResult(blocks) {
5227
5595
  type: "text",
5228
5596
  text: block.text ?? ""
5229
5597
  });
5230
- else if (block.type === "image") content.push({
5231
- type: "text",
5232
- text: "[图片结果未转发给 CodeBuddy]"
5233
- });
5234
- else content.push({
5598
+ else if (block.type === "image" && block.attachment !== null && typeof block.attachment === "object") {
5599
+ const attachment = block.attachment;
5600
+ const resolved = images?.get(String(attachment.attachmentId));
5601
+ content.push(resolved === void 0 ? {
5602
+ type: "text",
5603
+ text: textOnlyImageText(attachment)
5604
+ } : {
5605
+ type: "image",
5606
+ data: resolved.data,
5607
+ mimeType: resolved.mediaType
5608
+ });
5609
+ } else content.push({
5235
5610
  type: "text",
5236
5611
  text: JSON.stringify(block)
5237
5612
  });
@@ -5521,10 +5896,24 @@ var CodeBuddyAdapter = class extends LlmAdapter {
5521
5896
  * prompt instead of failing the whole turn.
5522
5897
  */
5523
5898
  async resolveFeedImages(feed, vision, signal) {
5899
+ return await this.resolveImages(feedImageRefs(feed), vision, signal);
5900
+ }
5901
+ /**
5902
+ * Images carried by the messages the inner session has not seen yet.
5903
+ *
5904
+ * Tool results are included: `read_image` hands its pixels back through the
5905
+ * MCP tool result, not through the prompt text, so this tail is the only
5906
+ * place the bytes can come from.
5907
+ */
5908
+ async resolveTurnImages(tail, vision, signal) {
5909
+ const refs = tail.flatMap((message) => message.role === "assistant" ? [] : imageRefs(message.content));
5910
+ return await this.resolveImages(refs, vision, signal);
5911
+ }
5912
+ async resolveImages(refs, vision, signal) {
5524
5913
  const map = /* @__PURE__ */ new Map();
5525
5914
  const readImage = this.options.readImage;
5526
5915
  if (!vision || readImage === void 0) return map;
5527
- for (const ref of feedImageRefs(feed)) {
5916
+ for (const ref of refs) {
5528
5917
  const key = String(ref.attachmentId);
5529
5918
  if (map.has(key)) continue;
5530
5919
  try {
@@ -5650,7 +6039,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
5650
6039
  if (!this.isSignedIn(region)) throw new Error(`${region === "cn" ? "CodeBuddy 国内版" : "CodeBuddy 国际版"}尚未登录,请先在设置 → CodeBuddy 中登录。`);
5651
6040
  const model = resolveCodeBuddyModelId(options.model, this.aliases);
5652
6041
  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(这是一次性旁路请求,直接输出下一条助手回复。)";
6042
+ const prompt = feedToText(renderSideChannelFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath);
5654
6043
  for (const chunk of await codeBuddyColdStream(region, prompt, model, options)) yield chunk;
5655
6044
  return;
5656
6045
  }
@@ -5662,7 +6051,9 @@ var CodeBuddyAdapter = class extends LlmAdapter {
5662
6051
  return;
5663
6052
  }
5664
6053
  const tail = options.messages.slice(session.fedMessages.length);
5665
- session.deliverToolResults(tail);
6054
+ const vision = await this.modelVision(options.model);
6055
+ const images = await this.resolveTurnImages(tail, vision, options.signal);
6056
+ session.deliverToolResults(tail, images);
5666
6057
  const plan = planContinuation(session.fedMessages, options.messages);
5667
6058
  if (plan.rebuild) {
5668
6059
  this.sessions.dispose(sessionId);
@@ -5679,7 +6070,6 @@ var CodeBuddyAdapter = class extends LlmAdapter {
5679
6070
  session.ensureTools(options.tools ?? []);
5680
6071
  session.fedMessages = options.messages;
5681
6072
  session.fedSystem = options.system;
5682
- const vision = await this.modelVision(options.model);
5683
6073
  const feed = plan.feed === null ? null : await this.buildFeed(plan.feed, vision, options.signal);
5684
6074
  yield* session.stream(options, feed);
5685
6075
  }
@@ -6017,12 +6407,18 @@ function minimaxCliCommand() {
6017
6407
  const HOST_TOOL_PREFIXES = [`mcp__${MINIMAX_MCP_SERVER}__`, `mcp__${MINIMAX_MCP_SERVER.replace(/[^a-zA-Z0-9]/g, "_")}__`];
6018
6408
  /** Whether a CLI tool name belongs to this plugin's MCP server. */
6019
6409
  function isHostMcpTool(name) {
6020
- return HOST_TOOL_PREFIXES.some((prefix) => name.startsWith(prefix));
6410
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) !== null;
6021
6411
  }
6022
- /** The host-side name of an MCP tool, without the namespace. */
6412
+ /**
6413
+ * The host-side name of an MCP tool, without any namespace layer.
6414
+ *
6415
+ * Every layer is peeled, not just one: a model that emits an already-qualified
6416
+ * name has it qualified again by the CLI, and handing the host
6417
+ * `mcp__dsh-host__edit` made DSH answer `unknown tool` even though the tool was
6418
+ * registered under `edit`. See {@link stripMcpNamespace}.
6419
+ */
6023
6420
  function hostMcpToolName(name) {
6024
- for (const prefix of HOST_TOOL_PREFIXES) if (name.startsWith(prefix)) return name.slice(prefix.length);
6025
- return name;
6421
+ return stripMcpNamespace(name, HOST_TOOL_PREFIXES) ?? name;
6026
6422
  }
6027
6423
  /** Thinking-effort values an ACP config option advertises, minus `default`. */
6028
6424
  function effortValues(options) {
@@ -6773,8 +7169,15 @@ var EventQueue = class {
6773
7169
  });
6774
7170
  }
6775
7171
  };
6776
- /** Render a harness tool result for the MCP caller. */
6777
- function renderToolResult(content) {
7172
+ /**
7173
+ * Render a harness tool result for the MCP caller.
7174
+ *
7175
+ * A tool result can carry pixels (`read_image` returns the picture beside its
7176
+ * path envelope). The MCP result schema passes an image block straight to the
7177
+ * agent, so a resolvable attachment becomes `{type:'image'}`; one the host
7178
+ * could not read falls back to the harness handle text instead of vanishing.
7179
+ */
7180
+ function renderToolResult(content, images) {
6778
7181
  const text = (value) => {
6779
7182
  if (typeof value === "string") return value;
6780
7183
  if (value === null || value === void 0) return "";
@@ -6786,22 +7189,49 @@ function renderToolResult(content) {
6786
7189
  };
6787
7190
  if (Array.isArray(content)) {
6788
7191
  const parts = [];
7192
+ let pending = [];
7193
+ const flush = () => {
7194
+ if (pending.length === 0) return;
7195
+ parts.push({
7196
+ type: "text",
7197
+ text: pending.join("\n")
7198
+ });
7199
+ pending = [];
7200
+ };
6789
7201
  for (const block of content) {
6790
7202
  if (typeof block === "string") {
6791
- parts.push(block);
7203
+ pending.push(block);
6792
7204
  continue;
6793
7205
  }
6794
- if (block !== null && typeof block === "object" && block.type === "text") {
6795
- parts.push(text(block.text));
6796
- continue;
7206
+ if (block !== null && typeof block === "object") {
7207
+ const typed = block;
7208
+ if (typed.type === "text") {
7209
+ pending.push(text(typed.text));
7210
+ continue;
7211
+ }
7212
+ if (typed.type === "image" && typed.attachment !== null && typeof typed.attachment === "object") {
7213
+ const attachment = typed.attachment;
7214
+ const resolved = images?.get(String(attachment.attachmentId));
7215
+ flush();
7216
+ parts.push(resolved === void 0 ? {
7217
+ type: "text",
7218
+ text: textOnlyImageText(attachment)
7219
+ } : {
7220
+ type: "image",
7221
+ data: resolved.data,
7222
+ mimeType: resolved.mediaType
7223
+ });
7224
+ continue;
7225
+ }
6797
7226
  }
6798
- parts.push(text(block));
7227
+ pending.push(text(block));
6799
7228
  }
6800
- const joined = parts.join("\n").trim();
6801
- return { content: [{
7229
+ flush();
7230
+ if (parts.length === 0) return { content: [{
6802
7231
  type: "text",
6803
- text: joined === "" ? "(宿主工具没有返回内容)" : joined
7232
+ text: "(宿主工具没有返回内容)"
6804
7233
  }] };
7234
+ return { content: parts };
6805
7235
  }
6806
7236
  const joined = text(content).trim();
6807
7237
  return { content: [{
@@ -7519,7 +7949,7 @@ var MinimaxSession = class {
7519
7949
  this.bridge.setTools(tools);
7520
7950
  }
7521
7951
  /** Hand the host's tool results to parked handlers. */
7522
- deliverToolResults(tail) {
7952
+ deliverToolResults(tail, images) {
7523
7953
  let freshUserTurn = false;
7524
7954
  for (const message of tail) {
7525
7955
  if (message.role === "user") {
@@ -7533,7 +7963,7 @@ var MinimaxSession = class {
7533
7963
  clearTimeout(pending.timer);
7534
7964
  this.pending.delete(callId);
7535
7965
  pending.resolve({
7536
- ...renderToolResult(message.content),
7966
+ ...renderToolResult(message.content, images),
7537
7967
  ...message.isError === true ? { isError: true } : {}
7538
7968
  });
7539
7969
  }
@@ -8386,7 +8816,7 @@ var MinimaxAdapter = class extends LlmAdapter {
8386
8816
  if (await minimaxRegionBlocked(region)) throw new Error(minimaxRegionBlockMessage(region));
8387
8817
  const model = resolveMinimaxModelId(options.model, this.aliases);
8388
8818
  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(这是一次性旁路请求,直接输出下一条助手回复。)";
8819
+ const prompt = feedToText(renderSideChannelFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath);
8390
8820
  for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk;
8391
8821
  return;
8392
8822
  }
@@ -8398,7 +8828,9 @@ var MinimaxAdapter = class extends LlmAdapter {
8398
8828
  return;
8399
8829
  }
8400
8830
  const tail = options.messages.slice(session.fedMessages.length);
8401
- session.deliverToolResults(tail);
8831
+ const vision = await this.modelVision(model, region);
8832
+ const images = await this.resolveTurnImages(tail, vision, options.signal);
8833
+ session.deliverToolResults(tail, images);
8402
8834
  const plan = planContinuation(session.fedMessages, options.messages);
8403
8835
  if (plan.rebuild) {
8404
8836
  this.sessions.dispose(sessionId);
@@ -8425,7 +8857,6 @@ var MinimaxAdapter = class extends LlmAdapter {
8425
8857
  session.ensureTools(options.tools ?? []);
8426
8858
  session.fedMessages = options.messages;
8427
8859
  session.fedSystem = options.system;
8428
- const vision = await this.modelVision(model, region);
8429
8860
  const feed = plan.feed === null ? null : await this.buildFeed(plan.feed, vision, options.signal);
8430
8861
  yield* session.stream(options, feed);
8431
8862
  }
@@ -8464,20 +8895,7 @@ var MinimaxAdapter = class extends LlmAdapter {
8464
8895
  async buildFeed(feed, vision, signal) {
8465
8896
  if (typeof feed === "string") return feed;
8466
8897
  if (!vision) return feedToText(feed, this.options.imagePath);
8467
- const images = /* @__PURE__ */ new Map();
8468
- const readImage = this.options.readImage;
8469
- if (readImage !== void 0) for (const ref of feedImageRefs(feed)) {
8470
- const key = String(ref.attachmentId);
8471
- if (images.has(key)) continue;
8472
- try {
8473
- const image = await readImage(ref, signal);
8474
- if (image !== void 0) images.set(key, {
8475
- data: Buffer.from(image.bytes).toString("base64"),
8476
- mediaType: image.mediaType
8477
- });
8478
- } catch {}
8479
- }
8480
- const parts = resolvedFeedParts(feed, images);
8898
+ const parts = resolvedFeedParts(feed, await this.resolveImages(feedImageRefs(feed), vision, signal));
8481
8899
  if (!parts.some((part) => part.type !== "text")) return parts.map((part) => part.type === "text" ? part.text : "").join("\n\n");
8482
8900
  const content = [];
8483
8901
  for (const part of parts) {
@@ -8502,6 +8920,34 @@ var MinimaxAdapter = class extends LlmAdapter {
8502
8920
  }
8503
8921
  return content;
8504
8922
  }
8923
+ /**
8924
+ * Images carried by the messages the inner session has not seen yet.
8925
+ *
8926
+ * Tool results are included: `read_image` hands its pixels back through the
8927
+ * ACP tool result, not through the prompt text, so this tail is the only
8928
+ * place the bytes can come from.
8929
+ */
8930
+ async resolveTurnImages(tail, vision, signal) {
8931
+ const refs = tail.flatMap((message) => message.role === "assistant" ? [] : imageRefs(message.content));
8932
+ return await this.resolveImages(refs, vision, signal);
8933
+ }
8934
+ async resolveImages(refs, vision, signal) {
8935
+ const map = /* @__PURE__ */ new Map();
8936
+ const readImage = this.options.readImage;
8937
+ if (!vision || readImage === void 0) return map;
8938
+ for (const ref of refs) {
8939
+ const key = String(ref.attachmentId);
8940
+ if (map.has(key)) continue;
8941
+ try {
8942
+ const image = await readImage(ref, signal);
8943
+ if (image !== void 0) map.set(key, {
8944
+ data: Buffer.from(image.bytes).toString("base64"),
8945
+ mediaType: image.mediaType
8946
+ });
8947
+ } catch {}
8948
+ }
8949
+ return map;
8950
+ }
8505
8951
  cwdOf(options) {
8506
8952
  return options.cwd;
8507
8953
  }
@@ -9039,9 +9485,7 @@ async function handleApi(req, res, adapters) {
9039
9485
  const mode = parsed.mode;
9040
9486
  const result = startSetup(postBrand, mode, (code) => {
9041
9487
  if (code !== 0) return;
9042
- qoder.invalidateCatalog();
9043
- qoder.invalidateUsage();
9044
- if (mode === "logout") qoder.closeSessions();
9488
+ qoder.resetAccount();
9045
9489
  });
9046
9490
  if (!result.started) {
9047
9491
  send(res, result.reason === "busy" ? 409 : result.reason === "unsupported" ? 501 : 500, { error: result.error });