dsh-agent-sdk-bridge 1.1.5 → 1.1.7

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
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, ToolCallId, fileHandleText, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, textOnlyImageText } from "@deepseek-ai/dsh-llm";
2
+ import { CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, ToolCallId, fileHandleText, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, requestImageHandleText, textOnlyImageText } from "@deepseek-ai/dsh-llm";
3
3
  import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import * as path from "node:path";
@@ -917,6 +917,22 @@ var TurnOutputAccounting = class {
917
917
  * @module dsh-llm-qoder/render
918
918
  */
919
919
  /**
920
+ * Model-facing handle for one image.
921
+ *
922
+ * The host's native adapters use the same text: it names the attachment, its
923
+ * pixel size and media type, and the read-only normalized copy on disk, and it
924
+ * tells the model to copy that file to a writable path before editing. Pixels
925
+ * alone let a model describe an image but not process it — without this path
926
+ * the model goes looking through the workspace for a file that was never there.
927
+ */
928
+ function imageRefText(ref, path) {
929
+ if (path === void 0) return `[图片附件 ${String(ref.attachmentId)}(${ref.width}×${ref.height}px,${ref.mediaType})]`;
930
+ return requestImageHandleText(ref, {
931
+ width: ref.width,
932
+ height: ref.height
933
+ }, { readonlyPath: path });
934
+ }
935
+ /**
920
936
  * Image references in block order, skipping occurrences the surface already
921
937
  * offloaded: an offload is a durable fact the harness renders as path-bearing
922
938
  * placeholder text on every route, so re-sending those pixels would undo it.
@@ -927,7 +943,7 @@ function imageRefs(blocks) {
927
943
  return refs;
928
944
  }
929
945
  /** Render one content-block list as plain text; non-text blocks get handles. */
930
- function renderBlocks(blocks) {
946
+ function renderBlocks(blocks, imagePath) {
931
947
  const parts = [];
932
948
  for (const block of blocks) switch (block.type) {
933
949
  case "text":
@@ -935,7 +951,7 @@ function renderBlocks(blocks) {
935
951
  break;
936
952
  case "reasoning": break;
937
953
  case "image":
938
- parts.push(block.offloaded === true ? offloadedImageText(block.attachment) : textOnlyImageText(block.attachment));
954
+ parts.push(block.offloaded === true ? offloadedImageText(block.attachment) : imageRefText(block.attachment, imagePath?.(block.attachment)));
939
955
  break;
940
956
  case "file":
941
957
  parts.push(fileHandleText(block.attachment, void 0));
@@ -967,8 +983,8 @@ function roleTag(message) {
967
983
  * Render one request message with its role tag. A request-only user input has
968
984
  * no durable identity or source, so it reads exactly like a user message.
969
985
  */
970
- function renderMessage(message) {
971
- return `[${roleTag(message)}] ${renderBlocks(message.content)}`;
986
+ function renderMessage(message, imagePath) {
987
+ return `[${roleTag(message)}] ${renderBlocks(message.content, imagePath)}`;
972
988
  }
973
989
  /** Preamble establishing the inner model's role as this agent's LLM backend. */
974
990
  const BACKEND_ROLE = [
@@ -1066,9 +1082,13 @@ function feedImageRefs(feed) {
1066
1082
  return feed.filter((part) => part.type === "image").map((part) => part.attachment);
1067
1083
  }
1068
1084
  /** Flatten a feed back to text, replacing images with the harness handle text. */
1069
- function feedToText(feed) {
1085
+ function feedToText(feed, imagePath) {
1070
1086
  if (typeof feed === "string") return feed;
1071
- return feed.map((part) => part.type === "text" ? part.text : textOnlyImageText(part.attachment)).filter((text) => text.length > 0).join("\n\n");
1087
+ return feed.map((part) => {
1088
+ if (part.type === "text") return part.text;
1089
+ const path = imagePath?.(part.attachment);
1090
+ return path === void 0 ? textOnlyImageText(part.attachment) : imageRefText(part.attachment, path);
1091
+ }).filter((text) => text.length > 0).join("\n\n");
1072
1092
  }
1073
1093
  /**
1074
1094
  * Split a feed into text and resolved images for providers with a vision API.
@@ -1102,6 +1122,7 @@ function resolvedFeedParts(feed, images) {
1102
1122
  attachment: part.attachment
1103
1123
  } : {
1104
1124
  type: "image",
1125
+ attachment: part.attachment,
1105
1126
  data: resolved.data,
1106
1127
  mediaType: resolved.mediaType
1107
1128
  });
@@ -1128,12 +1149,12 @@ function feedWideCharCount(feed) {
1128
1149
  * prompt, and the existing conversation as compact context. Messages of the
1129
1150
  * current turn keep their image references; earlier ones are handles.
1130
1151
  */
1131
- function renderInitialFeed(system, messages) {
1152
+ function renderInitialFeed(system, messages, imagePath) {
1132
1153
  const from = currentTurnStart(messages);
1133
1154
  const history = [];
1134
1155
  for (const [index, message] of messages.entries()) {
1135
- const entry = index >= from && imageRefs(message.content).length > 0 ? label(`[${roleTag(message)}] `, blockParts(message.content)) : renderMessage(message);
1136
- if (feedToText(entry).length > 0) history.push(entry);
1156
+ const entry = index >= from && imageRefs(message.content).length > 0 ? label(`[${roleTag(message)}] `, blockParts(message.content)) : renderMessage(message, imagePath);
1157
+ if (feedToText(entry, imagePath).length > 0) history.push(entry);
1137
1158
  }
1138
1159
  const sections = [BACKEND_ROLE];
1139
1160
  if (system !== void 0 && system.length > 0) sections.push(`---- 宿主系统提示(作为你的行为准则) ----\n${system}`);
@@ -2762,6 +2783,8 @@ const QODER_INTL_PROVIDER = "qoder-intl";
2762
2783
  * actually runs with. `maxInputTokens` is NOT a substitute — it is the ceiling
2763
2784
  * for a single request and is often lower than the session window (e.g. 180 000
2764
2785
  * against a 200 000 session), so falling back to it would understate capacity.
2786
+ * Callers that accept a user override should validate it against
2787
+ * `availableContextWindows` first — see {@link resolveDeclaredWindow}.
2765
2788
  *
2766
2789
  * @param live - the live catalog entry, when the CLI answered.
2767
2790
  * @param override - the user's chosen window for this model, if any.
@@ -2800,6 +2823,24 @@ function cliContextWindow(live, declared) {
2800
2823
  if (available !== void 0 && available.includes(declared)) return declared;
2801
2824
  return live.defaultContextWindow ?? largestWindow(available) ?? live.maxInputTokens;
2802
2825
  }
2826
+ /**
2827
+ * The window to publish for one route, which is also the one the CLI is told
2828
+ * to run with.
2829
+ *
2830
+ * A live entry is authoritative: the user's override counts only when the
2831
+ * model advertises it. The CLI silently ignores anything else (a 1M choice on
2832
+ * a 200K-only route), and dividing by it would understate every reading
2833
+ * fivefold. When the catalog is momentarily unavailable, the last successful
2834
+ * answer is reused instead of the static 200K default — that fallback used to
2835
+ * change the denominator, and the compaction budget, mid-session: a 1M
2836
+ * conversation read 1M one turn and 200K the next, and then compacted at what
2837
+ * looked like 10%.
2838
+ */
2839
+ function resolveDeclaredWindow(live, override, remembered, fallback) {
2840
+ if (live === void 0) return remembered ?? override ?? fallback;
2841
+ const available = live.availableContextWindows;
2842
+ return pickContextWindow(live, override !== void 0 && (available === void 0 || available.length === 0 || available.includes(override)) ? override : void 0, remembered ?? fallback);
2843
+ }
2803
2844
  function modelInfo$2(provider, entry) {
2804
2845
  return {
2805
2846
  provider,
@@ -2863,6 +2904,7 @@ var QoderAdapter = class extends LlmAdapter {
2863
2904
  catalog;
2864
2905
  usage;
2865
2906
  readImage;
2907
+ imagePath;
2866
2908
  brand;
2867
2909
  /**
2868
2910
  * Memoized `Set` view of the disabled-model list.
@@ -2872,6 +2914,24 @@ var QoderAdapter = class extends LlmAdapter {
2872
2914
  * hash probe instead of rebuilding a set per call, with no staleness.
2873
2915
  */
2874
2916
  disabledCache;
2917
+ /**
2918
+ * The last window each route resolved to, plus what the model advertised.
2919
+ *
2920
+ * Reused only when a live entry is missing. Without it a failed refresh fell
2921
+ * back to the static 200K, so a 1M session suddenly declared 200K: the ring
2922
+ * denominator changed and the compaction engine budgeted against 200K,
2923
+ * compacting a history that was still only ~10% of the real window.
2924
+ */
2925
+ knownWindows = /* @__PURE__ */ new Map();
2926
+ /**
2927
+ * Last verified image capability per route.
2928
+ *
2929
+ * A missed catalog refresh used to fall back to text-only, and DSH then
2930
+ * stripped the pixels before this adapter ran: a vision model silently lost
2931
+ * the image for that turn. Remembering the last answer keeps the declared
2932
+ * capability stable across a transient miss.
2933
+ */
2934
+ knownVision = /* @__PURE__ */ new Map();
2875
2935
  constructor(options = {}) {
2876
2936
  super();
2877
2937
  this.options = options;
@@ -2885,6 +2945,7 @@ var QoderAdapter = class extends LlmAdapter {
2885
2945
  this.catalog = new QoderModelCatalog(this.brand, options.modelCacheTtlMs ?? 3e5, options.catalogFetchTimeoutMs ?? 2e4);
2886
2946
  this.usage = new QoderUsage(this.brand, options.usageCacheTtlMs);
2887
2947
  this.readImage = options.readImage;
2948
+ this.imagePath = options.imagePath;
2888
2949
  }
2889
2950
  get defaultMaxTokens() {
2890
2951
  return readLive(this.options.defaultMaxTokens, DEFAULT_MAX_TOKENS);
@@ -2948,7 +3009,12 @@ var QoderAdapter = class extends LlmAdapter {
2948
3009
  * @returns live catalog entries in upstream order.
2949
3010
  */
2950
3011
  async describeCatalog() {
2951
- return this.catalog.liveModels();
3012
+ const live = await this.catalog.liveModels();
3013
+ for (const entry of live) {
3014
+ this.declaredWindow(entry.value, entry);
3015
+ this.knownVision.set(entry.value, entry.isVl === true);
3016
+ }
3017
+ return live;
2952
3018
  }
2953
3019
  /** Forget the cached catalog; the next read asks the CLI again. */
2954
3020
  invalidateCatalog() {
@@ -2978,9 +3044,30 @@ var QoderAdapter = class extends LlmAdapter {
2978
3044
  disabledModelIds() {
2979
3045
  return [...this.disabledModels];
2980
3046
  }
2981
- /** The user's window for one model, or undefined when following upstream. */
3047
+ /**
3048
+ * The user's window for one model, when the provider accepts it.
3049
+ *
3050
+ * A stored choice the model does not advertise is not a real choice: the CLI
3051
+ * ignores it and keeps its own window, so publishing it would only make the
3052
+ * meter divide by a capacity the route never runs with. Until the catalog
3053
+ * has answered once the choice is trusted (there is nothing to check yet).
3054
+ */
2982
3055
  contextWindowFor(id) {
2983
- return this.windowOverride(id);
3056
+ const override = this.windowOverride(id);
3057
+ if (override === void 0) return void 0;
3058
+ const target = resolveQoderModelId(id, this.modelAliases);
3059
+ const available = this.knownWindows.get(target)?.available;
3060
+ if (available === void 0 || available.length === 0) return override;
3061
+ return available.includes(override) ? override : void 0;
3062
+ }
3063
+ /** The window this route publishes, remembering it for catalog misses. */
3064
+ declaredWindow(id, live) {
3065
+ const window = resolveDeclaredWindow(live, this.windowOverride(id), this.knownWindows.get(id)?.window, DEFAULT_CONTEXT_WINDOW);
3066
+ if (live !== void 0) this.knownWindows.set(id, {
3067
+ window,
3068
+ available: live.availableContextWindows
3069
+ });
3070
+ return window;
2984
3071
  }
2985
3072
  /** The stored per-model window map, for rewriting the field. */
2986
3073
  modelWindowChoices() {
@@ -2993,31 +3080,34 @@ var QoderAdapter = class extends LlmAdapter {
2993
3080
  const target = resolveQoderModelId(model, this.modelAliases);
2994
3081
  const live = (await this.catalog.liveModels()).find((entry) => entry.value === target);
2995
3082
  if (live !== void 0) {
3083
+ const vision = live.isVl === true;
3084
+ this.knownVision.set(target, vision);
2996
3085
  const reasoning = reasoningInfo(live.efforts, live.defaultEffort ?? this.defaultReasoningEffort, live.isReasoning);
2997
3086
  return {
2998
3087
  provider,
2999
3088
  id: model,
3000
3089
  name: live.displayName.length > 0 ? live.displayName : live.value,
3001
3090
  ...live.description.length > 0 ? { description: live.description } : {},
3002
- inputModalities: live.isVl === true ? ["text", "image"] : ["text"],
3003
- context: { contextWindow: pickContextWindow(live, this.windowOverride(target), DEFAULT_CONTEXT_WINDOW) },
3091
+ inputModalities: vision ? ["text", "image"] : ["text"],
3092
+ context: { contextWindow: this.declaredWindow(target, live) },
3004
3093
  defaultMaxTokens: live.maxOutputTokens ?? this.defaultMaxTokens,
3005
3094
  ...reasoning === void 0 ? {} : { reasoning }
3006
3095
  };
3007
3096
  }
3008
3097
  const configured = brandProfile(this.brand).staticCatalog ? QODER_MODELS.find((entry) => entry.id === target) : void 0;
3009
3098
  const reasoning = reasoningInfo(void 0, this.defaultReasoningEffort, true);
3099
+ const rememberedVision = this.knownVision.get(target) === true;
3010
3100
  return Promise.resolve({
3011
3101
  ...configured === void 0 ? {
3012
3102
  provider,
3013
3103
  id: model,
3014
- name: model,
3015
- inputModalities: ["text"]
3104
+ name: model
3016
3105
  } : {
3017
3106
  ...modelInfo$2(provider, configured),
3018
3107
  id: model
3019
3108
  },
3020
- context: { contextWindow: this.windowOverride(target) ?? 2e5 },
3109
+ inputModalities: rememberedVision ? ["text", "image"] : ["text"],
3110
+ context: { contextWindow: this.declaredWindow(target, void 0) },
3021
3111
  defaultMaxTokens: this.defaultMaxTokens,
3022
3112
  ...reasoning === void 0 ? {} : { reasoning }
3023
3113
  });
@@ -3053,7 +3143,7 @@ var QoderAdapter = class extends LlmAdapter {
3053
3143
  async *dispatch(options, generation) {
3054
3144
  const model = resolveQoderModelId(options.model, this.modelAliases);
3055
3145
  if (options.sessionId === void 0 || options.purpose !== void 0) {
3056
- const prompt = feedToText(renderInitialFeed(options.system, options.messages)) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
3146
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.imagePath), this.imagePath) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
3057
3147
  yield* this.sessions.coldStream(options, prompt, model);
3058
3148
  return;
3059
3149
  }
@@ -3085,7 +3175,7 @@ var QoderAdapter = class extends LlmAdapter {
3085
3175
  session.fedMessages = options.messages;
3086
3176
  session.fedSystem = options.system;
3087
3177
  const feed = plan.feed === null ? null : await this.buildFeed(plan.feed, generation.vision, images);
3088
- yield* session.stream(options, feed, plan.feed === null ? void 0 : feedToText(plan.feed));
3178
+ yield* session.stream(options, feed, plan.feed === null ? void 0 : feedToText(plan.feed, this.imagePath));
3089
3179
  }
3090
3180
  async *firstTurn(session, options, model, policy, vision) {
3091
3181
  session.setModel(model, policy);
@@ -3096,9 +3186,9 @@ var QoderAdapter = class extends LlmAdapter {
3096
3186
  session.recordRequestInput(options.system, options.messages);
3097
3187
  session.fedMessages = options.messages;
3098
3188
  session.fedSystem = options.system;
3099
- const feed = renderInitialFeed(options.system, options.messages);
3189
+ const feed = renderInitialFeed(options.system, options.messages, this.imagePath);
3100
3190
  const images = await this.resolveImages(feedImageRefs(feed), vision, options.signal);
3101
- yield* session.stream(options, await this.buildFeed(feed, vision, images), feedToText(feed));
3191
+ yield* session.stream(options, await this.buildFeed(feed, vision, images), feedToText(feed, this.imagePath));
3102
3192
  }
3103
3193
  /** Image references carried by a message tail, skipping assistant content. */
3104
3194
  async resolveTurnImages(tail, vision, signal) {
@@ -3130,7 +3220,7 @@ var QoderAdapter = class extends LlmAdapter {
3130
3220
  */
3131
3221
  async buildFeed(feed, vision, images) {
3132
3222
  if (typeof feed === "string") return feed;
3133
- if (!vision) return feedToText(feed);
3223
+ if (!vision) return feedToText(feed, this.imagePath);
3134
3224
  const content = [];
3135
3225
  let pixels = 0;
3136
3226
  for (const part of feed) {
@@ -3141,14 +3231,20 @@ var QoderAdapter = class extends LlmAdapter {
3141
3231
  });
3142
3232
  continue;
3143
3233
  }
3144
- const resolved = images.get(String(part.attachment.attachmentId));
3234
+ const key = String(part.attachment.attachmentId);
3235
+ const resolved = images.get(key);
3236
+ const path = this.imagePath?.(part.attachment);
3145
3237
  if (resolved === void 0) {
3146
3238
  content.push({
3147
3239
  type: "text",
3148
- text: `[图片附件 ${String(part.attachment.attachmentId)} 本次未能读取,请基于文字内容继续]`
3240
+ text: `[图片附件 ${key} 本次未能读取${path === void 0 ? "" : `;本机文件:${path}`},请基于文字内容继续]`
3149
3241
  });
3150
3242
  continue;
3151
3243
  }
3244
+ content.push({
3245
+ type: "text",
3246
+ text: imageRefText(part.attachment, path)
3247
+ });
3152
3248
  pixels += 1;
3153
3249
  content.push({
3154
3250
  type: "image",
@@ -3488,7 +3584,6 @@ function priceFactorOf$1(model) {
3488
3584
  function toCodeBuddyModel(model) {
3489
3585
  const windows = new Set(model.contextWindow?.supportedLengths ?? []);
3490
3586
  const declared = model.contextWindow?.defaultLength ?? model.maxInputTokens ?? model.maxAllowedSize ?? 2e5;
3491
- windows.add(declared);
3492
3587
  return {
3493
3588
  id: model.id,
3494
3589
  name: model.name ?? model.id,
@@ -3558,6 +3653,15 @@ var CodeBuddyCatalog = class {
3558
3653
  this.ttlMs = ttlMs;
3559
3654
  this.timeoutMs = timeoutMs;
3560
3655
  }
3656
+ /**
3657
+ * The last catalog read for a region, without fetching.
3658
+ *
3659
+ * Callers that must answer synchronously (deciding whether a model exposes a
3660
+ * context-budget choice) use this instead of awaiting a refresh.
3661
+ */
3662
+ snapshot(requested) {
3663
+ return this.snapshots.get(requested ?? readLive(this.region, "global"))?.models ?? [];
3664
+ }
3561
3665
  /** Models for one region; a failed refresh keeps the last good list. */
3562
3666
  async models(requested) {
3563
3667
  const region = requested ?? readLive(this.region, "global");
@@ -4084,6 +4188,10 @@ var CodeBuddySession = class {
4084
4188
  effort;
4085
4189
  systemPrompt;
4086
4190
  cwd;
4191
+ /** Context budget the host shows for this session, when a model offers one. */
4192
+ contextWindow;
4193
+ /** Budget already pushed to the CLI, keyed by model and value. */
4194
+ appliedWindow;
4087
4195
  /** Host messages already fed to the inner session, for continuation planning. */
4088
4196
  fedMessages;
4089
4197
  /** Host system prompt last applied; informational for the adapter. */
@@ -4101,6 +4209,34 @@ var CodeBuddySession = class {
4101
4209
  this.effort = options.effort;
4102
4210
  this.systemPrompt = options.system;
4103
4211
  if (options.cwd !== void 0) this.cwd = options.cwd;
4212
+ if (options.contextWindow !== void 0) this.contextWindow = options.contextWindow;
4213
+ }
4214
+ /**
4215
+ * Push the host-visible context window into the inner session.
4216
+ *
4217
+ * The CLI resolves its own budget (`override > model default > physical
4218
+ * limit`) and both its compaction trigger and the upstream gateway enforce
4219
+ * that budget. A global-catalog model such as `deepseek-v4.1-flash` declares
4220
+ * `supportedLengths [300K, 1M]` with a 300K default, so a session left alone
4221
+ * compacts (and the gateway rejects) anything past 276K — while the host,
4222
+ * told 1M, keeps showing and feeding a larger history. Replaying that history
4223
+ * then collapses to a summary. Applying the same number the host divides by
4224
+ * keeps the two in step; models that expose no choice reject it and keep
4225
+ * their default.
4226
+ *
4227
+ * The CLI refuses to clear the override (`contextWindow must be a positive
4228
+ * safe integer`), so the adapter sends the model's default instead when the
4229
+ * page returns to "default".
4230
+ */
4231
+ async applyContextWindow(session) {
4232
+ const window = this.contextWindow;
4233
+ if (window === void 0) return;
4234
+ const key = `${this.model}:${window}`;
4235
+ if (this.appliedWindow === key) return;
4236
+ this.appliedWindow = key;
4237
+ try {
4238
+ await session.setConfig({ contextWindow: window });
4239
+ } catch {}
4104
4240
  }
4105
4241
  /**
4106
4242
  * Remember the host tools and register them with this session's MCP server.
@@ -4179,6 +4315,7 @@ var CodeBuddySession = class {
4179
4315
  signal?.addEventListener("abort", onAbort, { once: true });
4180
4316
  try {
4181
4317
  await session.setModel(this.model);
4318
+ await this.applyContextWindow(session);
4182
4319
  if (feed !== null && feed.length > 0) {
4183
4320
  const content = typeof feed === "string" ? feed : feed.filter((block) => block.type !== "text" || block.text.length > 0);
4184
4321
  if (content.length > 0) {
@@ -4770,6 +4907,8 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4770
4907
  accounts;
4771
4908
  auth = new CodeBuddyAuth();
4772
4909
  disabledCache = /* @__PURE__ */ new Map();
4910
+ /** Last verified image capability, keyed `${region}:${model}`. */
4911
+ knownVision = /* @__PURE__ */ new Map();
4773
4912
  constructor(options = {}) {
4774
4913
  super();
4775
4914
  this.options = options;
@@ -4810,7 +4949,9 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4810
4949
  /** The live catalog, unfiltered (the page must show switched-off models). */
4811
4950
  async describeCatalog(region = this.region) {
4812
4951
  if (!this.isSignedIn(region)) return [];
4813
- return this.catalog.models(region);
4952
+ const models = await this.catalog.models(region);
4953
+ for (const model of models) this.knownVision.set(`${region}:${model.id}`, model.vision);
4954
+ return models;
4814
4955
  }
4815
4956
  /** Whether the selected (or given) region has a stored login. */
4816
4957
  isSignedIn(region = this.region) {
@@ -4856,7 +4997,13 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4856
4997
  /** Whether the resolved model accepts images (drives whether pixels are sent). */
4857
4998
  async modelVision(model) {
4858
4999
  const target = resolveCodeBuddyModelId(model, this.aliases);
4859
- return (await this.catalog.models().catch(() => [])).find((entry) => entry.id === target)?.vision === true;
5000
+ const key = `${this.region}:${target}`;
5001
+ const live = (await this.catalog.models().catch(() => [])).find((entry) => entry.id === target);
5002
+ if (live !== void 0) {
5003
+ this.knownVision.set(key, live.vision);
5004
+ return live.vision;
5005
+ }
5006
+ return this.knownVision.get(key) === true;
4860
5007
  }
4861
5008
  /**
4862
5009
  * Resolve a feed's images into base64 for the CLI's vision blocks.
@@ -4891,7 +5038,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4891
5038
  */
4892
5039
  async buildFeed(feed, vision, signal) {
4893
5040
  if (typeof feed === "string") return feed;
4894
- if (!vision) return feedToText(feed);
5041
+ if (!vision) return feedToText(feed, this.options.imagePath);
4895
5042
  const parts = resolvedFeedParts(feed, await this.resolveFeedImages(feed, vision, signal));
4896
5043
  if (!parts.some((part) => part.type !== "text")) return parts.map((part) => part.type === "text" ? part.text : "").join("\n\n");
4897
5044
  const content = [];
@@ -4903,13 +5050,12 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4903
5050
  });
4904
5051
  continue;
4905
5052
  }
4906
- if (part.type === "image-unreadable") {
4907
- content.push({
4908
- type: "text",
4909
- text: textOnlyImageText(part.attachment)
4910
- });
4911
- continue;
4912
- }
5053
+ const path = this.options.imagePath?.(part.attachment);
5054
+ content.push({
5055
+ type: "text",
5056
+ text: part.type === "image-unreadable" && path === void 0 ? `[图片附件 ${String(part.attachment.attachmentId)} 本次未能读取,请基于文字内容继续]` : imageRefText(part.attachment, path)
5057
+ });
5058
+ if (part.type === "image-unreadable") continue;
4913
5059
  content.push({
4914
5060
  type: "image",
4915
5061
  source: {
@@ -4921,8 +5067,30 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4921
5067
  }
4922
5068
  return content;
4923
5069
  }
5070
+ /**
5071
+ * The window this model actually runs with.
5072
+ *
5073
+ * The user's override only applies where the provider accepts one. Every
5074
+ * model in the current catalog reports `supportedLengths: null`, so the CLI
5075
+ * answers a `set_config.contextWindow` with `Allowed: <none>`; a stored
5076
+ * override would then make DSH show a denominator the upstream never uses,
5077
+ * which is exactly how the context ring drifted.
5078
+ */
4924
5079
  contextWindowFor(id, region = this.region) {
4925
- return this.options.modelContextWindows?.(region)[id];
5080
+ const override = this.options.modelContextWindows?.(region)[id];
5081
+ if (override === void 0) return void 0;
5082
+ const live = this.models(region).find((entry) => entry.id === id);
5083
+ if (live === void 0) return override;
5084
+ return live.contextWindows.includes(override) ? override : void 0;
5085
+ }
5086
+ /** The catalog snapshot the adapter last read (empty before the first read). */
5087
+ models(region) {
5088
+ return this.catalog.snapshot(region);
5089
+ }
5090
+ /** Whether this model lets the user pick a context budget at all. */
5091
+ supportsContextWindowChoice(id, region = this.region) {
5092
+ const live = this.models(region).find((entry) => entry.id === id);
5093
+ return live !== void 0 && live.contextWindows.length > 0;
4926
5094
  }
4927
5095
  async listModels(provider) {
4928
5096
  const region = this.region;
@@ -4933,8 +5101,10 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4933
5101
  }
4934
5102
  async resolveModel(provider, model) {
4935
5103
  const target = resolveCodeBuddyModelId(model, this.aliases);
5104
+ const key = `${this.region}:${target}`;
4936
5105
  const live = (await this.catalog.models()).find((entry) => entry.id === target);
4937
5106
  if (live !== void 0) {
5107
+ this.knownVision.set(key, live.vision);
4938
5108
  const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, (live.reasoningEfforts?.length ?? 0) > 0);
4939
5109
  return {
4940
5110
  provider,
@@ -4952,7 +5122,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4952
5122
  provider,
4953
5123
  id: model,
4954
5124
  name: model,
4955
- inputModalities: ["text"],
5125
+ inputModalities: this.knownVision.get(key) === true ? ["text", "image"] : ["text"],
4956
5126
  context: { contextWindow: this.contextWindowFor(target) ?? 2e5 },
4957
5127
  defaultMaxTokens: readLive(this.options.defaultMaxTokens, CODEBUDDY_DEFAULT_MAX_TOKENS),
4958
5128
  ...reasoning === void 0 ? {} : { reasoning }
@@ -4972,7 +5142,7 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4972
5142
  if (!this.isSignedIn(region)) throw new Error(`${region === "cn" ? "CodeBuddy 国内版" : "CodeBuddy 国际版"}尚未登录,请先在设置 → CodeBuddy 中登录。`);
4973
5143
  const model = resolveCodeBuddyModelId(options.model, this.aliases);
4974
5144
  if (options.sessionId === void 0 || options.purpose !== void 0) {
4975
- const prompt = feedToText(renderInitialFeed(options.system, options.messages)) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
5145
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
4976
5146
  for (const chunk of await codeBuddyColdStream(region, prompt, model, options)) yield chunk;
4977
5147
  return;
4978
5148
  }
@@ -4995,7 +5165,8 @@ var CodeBuddyAdapter = class extends LlmAdapter {
4995
5165
  session.configure(region, model, {
4996
5166
  effort,
4997
5167
  system: options.system,
4998
- cwd: this.cwdOf(options)
5168
+ cwd: this.cwdOf(options),
5169
+ ...await this.windowOption(model)
4999
5170
  });
5000
5171
  session.ensureTools(options.tools ?? []);
5001
5172
  session.fedMessages = options.messages;
@@ -5008,15 +5179,33 @@ var CodeBuddyAdapter = class extends LlmAdapter {
5008
5179
  session.configure(region, model, {
5009
5180
  effort,
5010
5181
  system: options.system,
5011
- cwd: this.cwdOf(options)
5182
+ cwd: this.cwdOf(options),
5183
+ ...await this.windowOption(model)
5012
5184
  });
5013
5185
  session.ensureTools(options.tools ?? []);
5014
5186
  session.fedMessages = options.messages;
5015
5187
  session.fedSystem = options.system;
5016
5188
  const vision = await this.modelVision(options.model);
5017
- const feed = await this.buildFeed(renderInitialFeed(void 0, options.messages), vision, options.signal);
5189
+ const feed = await this.buildFeed(renderInitialFeed(void 0, options.messages, this.options.imagePath), vision, options.signal);
5018
5190
  yield* session.stream(options, feed);
5019
5191
  }
5192
+ /**
5193
+ * The context window the host and the inner session must agree on.
5194
+ *
5195
+ * Only a model that offers selectable budgets is configured: one fixed
5196
+ * window rejects every value, so the CLI's own default already matches what
5197
+ * the host shows. For a model with choices the adapter sends the picked
5198
+ * value; returning to "default" sends the model's own default budget, since
5199
+ * the CLI rejects a null clear (`contextWindow must be a positive safe
5200
+ * integer`). The override lives for the life of the CLI process, so the
5201
+ * default has to be sent explicitly to drop a previous choice.
5202
+ */
5203
+ async windowOption(model) {
5204
+ const live = (await this.catalog.models(this.region)).find((entry) => entry.id === model);
5205
+ if (live === void 0 || live.contextWindows.length === 0) return {};
5206
+ const chosen = this.options.modelContextWindows?.(this.region)[model];
5207
+ return { contextWindow: chosen !== void 0 && live.contextWindows.includes(chosen) ? chosen : live.defaultContextWindow };
5208
+ }
5020
5209
  cwdOf(options) {
5021
5210
  return options.cwd;
5022
5211
  }
@@ -7502,6 +7691,8 @@ var MinimaxAdapter = class extends LlmAdapter {
7502
7691
  auth = new MinimaxAuth();
7503
7692
  mcpServer = new MinimaxMcpServer();
7504
7693
  disabledCache = /* @__PURE__ */ new Map();
7694
+ /** Last verified image capability, keyed `${region}:${model}`. */
7695
+ knownVision = /* @__PURE__ */ new Map();
7505
7696
  constructor(options = {}) {
7506
7697
  super();
7507
7698
  this.options = options;
@@ -7542,7 +7733,9 @@ var MinimaxAdapter = class extends LlmAdapter {
7542
7733
  async describeCatalog(region = this.region) {
7543
7734
  if (!this.isSignedIn(region)) return [];
7544
7735
  if (await minimaxRegionBlocked(region)) return [];
7545
- return this.catalog.models(region);
7736
+ const models = await this.catalog.models(region);
7737
+ for (const model of models) this.knownVision.set(`${region}:${model.id}`, model.vision);
7738
+ return models;
7546
7739
  }
7547
7740
  /** Whether the region's endpoints are refusing this machine's network. */
7548
7741
  regionBlocked(region = this.region) {
@@ -7634,8 +7827,10 @@ var MinimaxAdapter = class extends LlmAdapter {
7634
7827
  async resolveModel(provider, model) {
7635
7828
  const region = this.region;
7636
7829
  const target = resolveMinimaxModelId(model, this.aliases);
7830
+ const key = `${region}:${target}`;
7637
7831
  const live = (await this.catalog.models(region)).find((entry) => entry.id === target);
7638
7832
  if (live !== void 0) {
7833
+ this.knownVision.set(key, live.vision);
7639
7834
  const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, live.reasoning);
7640
7835
  return {
7641
7836
  provider,
@@ -7653,7 +7848,7 @@ var MinimaxAdapter = class extends LlmAdapter {
7653
7848
  provider,
7654
7849
  id: model,
7655
7850
  name: model,
7656
- inputModalities: ["text"],
7851
+ inputModalities: this.knownVision.get(key) === true ? ["text", "image"] : ["text"],
7657
7852
  context: { contextWindow: this.contextWindowFor(target, region) ?? 512e3 },
7658
7853
  defaultMaxTokens: readLive(this.options.defaultMaxTokens, MINIMAX_DEFAULT_MAX_TOKENS),
7659
7854
  ...reasoning === void 0 ? {} : { reasoning }
@@ -7674,7 +7869,7 @@ var MinimaxAdapter = class extends LlmAdapter {
7674
7869
  if (await minimaxRegionBlocked(region)) throw new Error(minimaxRegionBlockMessage(region));
7675
7870
  const model = resolveMinimaxModelId(options.model, this.aliases);
7676
7871
  if (options.sessionId === void 0 || options.purpose !== void 0) {
7677
- const prompt = feedToText(renderInitialFeed(options.system, options.messages)) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
7872
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath) + "\n(这是一次性旁路请求,直接输出下一条助手回复。)";
7678
7873
  for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk;
7679
7874
  return;
7680
7875
  }
@@ -7727,13 +7922,19 @@ var MinimaxAdapter = class extends LlmAdapter {
7727
7922
  session.fedMessages = options.messages;
7728
7923
  session.fedSystem = options.system;
7729
7924
  const vision = await this.modelVision(model, region);
7730
- const feed = await this.buildFeed(renderInitialFeed(void 0, options.messages), vision, options.signal);
7925
+ const feed = await this.buildFeed(renderInitialFeed(void 0, options.messages, this.options.imagePath), vision, options.signal);
7731
7926
  yield* session.stream(options, feed);
7732
7927
  }
7733
7928
  /** Whether the resolved model accepts images (drives whether pixels are sent). */
7734
7929
  async modelVision(model, region) {
7735
7930
  const target = resolveMinimaxModelId(model, this.aliases);
7736
- return (await this.catalog.models(region).catch(() => [])).find((entry) => entry.id === target)?.vision === true;
7931
+ const key = `${region}:${target}`;
7932
+ const live = (await this.catalog.models(region).catch(() => [])).find((entry) => entry.id === target);
7933
+ if (live !== void 0) {
7934
+ this.knownVision.set(key, live.vision);
7935
+ return live.vision;
7936
+ }
7937
+ return this.knownVision.get(key) === true;
7737
7938
  }
7738
7939
  /**
7739
7940
  * Turn a feed into what one ACP prompt carries.
@@ -7745,7 +7946,7 @@ var MinimaxAdapter = class extends LlmAdapter {
7745
7946
  */
7746
7947
  async buildFeed(feed, vision, signal) {
7747
7948
  if (typeof feed === "string") return feed;
7748
- if (!vision) return feedToText(feed);
7949
+ if (!vision) return feedToText(feed, this.options.imagePath);
7749
7950
  const images = /* @__PURE__ */ new Map();
7750
7951
  const readImage = this.options.readImage;
7751
7952
  if (readImage !== void 0) for (const ref of feedImageRefs(feed)) {
@@ -7770,13 +7971,12 @@ var MinimaxAdapter = class extends LlmAdapter {
7770
7971
  });
7771
7972
  continue;
7772
7973
  }
7773
- if (part.type === "image-unreadable") {
7774
- content.push({
7775
- type: "text",
7776
- text: textOnlyImageText(part.attachment)
7777
- });
7778
- continue;
7779
- }
7974
+ const path = this.options.imagePath?.(part.attachment);
7975
+ content.push({
7976
+ type: "text",
7977
+ text: part.type === "image-unreadable" && path === void 0 ? `[图片附件 ${String(part.attachment.attachmentId)} 本次未能读取,请基于文字内容继续]` : imageRefText(part.attachment, path)
7978
+ });
7979
+ if (part.type === "image-unreadable") continue;
7780
7980
  content.push({
7781
7981
  type: "image",
7782
7982
  data: part.data,
@@ -8009,7 +8209,8 @@ async function buildRows(adapter) {
8009
8209
  defaultContextWindow: upstream,
8010
8210
  ...override === void 0 ? {} : { override },
8011
8211
  ...priceFactor === void 0 ? {} : { priceFactor },
8012
- reasoning: entry.isReasoning !== false
8212
+ reasoning: entry.isReasoning !== false,
8213
+ contextWindowSelectable: (entry.availableContextWindows?.length ?? 0) > 1
8013
8214
  };
8014
8215
  });
8015
8216
  }
@@ -8018,7 +8219,6 @@ async function buildCodeBuddyRows(adapter, region) {
8018
8219
  return (await adapter.describeCatalog(region)).map((entry) => {
8019
8220
  const override = adapter.contextWindowFor(entry.id, region);
8020
8221
  const choices = new Set(entry.contextWindows);
8021
- choices.add(entry.defaultContextWindow);
8022
8222
  if (override !== void 0) choices.add(override);
8023
8223
  return {
8024
8224
  id: entry.id,
@@ -8031,7 +8231,8 @@ async function buildCodeBuddyRows(adapter, region) {
8031
8231
  defaultContextWindow: entry.defaultContextWindow,
8032
8232
  ...override === void 0 ? {} : { override },
8033
8233
  ...entry.priceFactor === void 0 ? {} : { priceFactor: entry.priceFactor },
8034
- reasoning: (entry.reasoningEfforts?.length ?? 0) > 0
8234
+ reasoning: (entry.reasoningEfforts?.length ?? 0) > 0,
8235
+ contextWindowSelectable: entry.contextWindows.length > 0
8035
8236
  };
8036
8237
  });
8037
8238
  }
@@ -8612,6 +8813,7 @@ const Config = Config$1;
8612
8813
  function apply(ctx, config) {
8613
8814
  const live = liveConfig(config);
8614
8815
  let attachments;
8816
+ let filesystem;
8615
8817
  /**
8616
8818
  * Everything both editions share.
8617
8819
  *
@@ -8641,6 +8843,18 @@ function apply(ctx, config) {
8641
8843
  bytes: image.data,
8642
8844
  mediaType: image.mediaType
8643
8845
  }));
8846
+ },
8847
+ /**
8848
+ * Where the model can find the image on disk. Pixels let it describe the
8849
+ * picture; this path lets a "modify and save it" turn act on the file
8850
+ * instead of searching the workspace for something that was never there.
8851
+ */
8852
+ imagePath: (ref) => {
8853
+ const store = attachments;
8854
+ if (store === void 0) return void 0;
8855
+ const hostPath = store.imageHostPath(ref);
8856
+ if (hostPath === void 0) return void 0;
8857
+ return filesystem?.processPathFromHostPath?.(hostPath) ?? hostPath;
8644
8858
  }
8645
8859
  };
8646
8860
  /**
@@ -8680,7 +8894,8 @@ function apply(ctx, config) {
8680
8894
  disabledModels: (region) => region === "cn" ? live.codebuddyCnDisabledModels() : live.codebuddyGlobalDisabledModels(),
8681
8895
  modelContextWindows: (region) => region === "cn" ? live.codebuddyCnModelContextWindows() : live.codebuddyGlobalModelContextWindows(),
8682
8896
  modelAliases: live.codebuddyModelAliases,
8683
- readImage: shared.readImage
8897
+ readImage: shared.readImage,
8898
+ imagePath: shared.imagePath
8684
8899
  }),
8685
8900
  minimax: new MinimaxAdapter({
8686
8901
  maxSessions: live.maxSessions,
@@ -8695,7 +8910,8 @@ function apply(ctx, config) {
8695
8910
  disabledModels: (region) => region === "cn" ? live.minimaxCnDisabledModels() : live.minimaxGlobalDisabledModels(),
8696
8911
  modelContextWindows: (region) => region === "cn" ? live.minimaxCnModelContextWindows() : live.minimaxGlobalModelContextWindows(),
8697
8912
  modelAliases: live.minimaxModelAliases,
8698
- readImage: shared.readImage
8913
+ readImage: shared.readImage,
8914
+ imagePath: shared.imagePath
8699
8915
  })
8700
8916
  };
8701
8917
  ctx.inject(["attachments"], (scope) => {
@@ -8704,6 +8920,12 @@ function apply(ctx, config) {
8704
8920
  attachments = void 0;
8705
8921
  }, "llm-qoder-cn.attachments");
8706
8922
  });
8923
+ ctx.inject(["fs"], (scope) => {
8924
+ filesystem = scope.fs;
8925
+ scope.effect(() => () => {
8926
+ filesystem = void 0;
8927
+ }, "llm-qoder-cn.fs");
8928
+ });
8707
8929
  const routes = {};
8708
8930
  let directory;
8709
8931
  const enabled = (id) => {