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/src/adapter.ts CHANGED
@@ -23,8 +23,8 @@ import type { ResolvedConfig } from './config.ts'
23
23
  import type { Live } from './live.ts'
24
24
  import { readLive, readLiveOptional } from './live.ts'
25
25
  import { DEFAULT_MODEL_CACHE_TTL_MS, DEFAULT_FETCH_TIMEOUT_MS, QoderModelCatalog } from './models.ts'
26
- import { feedImageRefs, feedToText, imageRefs, joinFeeds, renderInitialFeed, renderRefreshed, renderUserTurn } from './render.ts'
27
- import type { Feed } from './render.ts'
26
+ import { feedImageRefs, feedToText, imageRefText, imageRefs, joinFeeds, renderInitialFeed, renderRefreshed, renderUserTurn } from './render.ts'
27
+ import type { Feed, ImagePathResolver } from './render.ts'
28
28
  import { QoderSession, QoderSessionManager, DEFAULT_MAX_SESSIONS } from './session.ts'
29
29
  import type { ChannelContent, ResolvedImages, SessionModelPolicy } from './session.ts'
30
30
  import type { UsageSnapshot } from './usage.ts'
@@ -56,6 +56,11 @@ export interface QoderAdapterOptions {
56
56
  modelCacheTtlMs?: Live<number>
57
57
  /** Request-image reader; absent → images are never forwarded as pixels. */
58
58
  readImage?: ImageRequestReader
59
+ /**
60
+ * The tool-world path of one image, for the handle text that lets the model
61
+ * edit it. Absent → an unreadable image keeps the harness placeholder.
62
+ */
63
+ imagePath?: ImagePathResolver
59
64
  /** How long an unpaired MCP tool handler waits before failing its call. */
60
65
  toolResultTimeoutMs?: Live<number>
61
66
  /** How long the inner process gets to acknowledge an abort. */
@@ -95,6 +100,13 @@ export const QODER_PROVIDER = 'qoder-cn'
95
100
  /** The international edition's route; a second adapter instance serves it. */
96
101
  export const QODER_INTL_PROVIDER = 'qoder-intl'
97
102
 
103
+ /** The window facts one live catalog entry carries. */
104
+ export type WindowFacts = {
105
+ maxInputTokens?: number
106
+ defaultContextWindow?: number
107
+ availableContextWindows?: readonly number[]
108
+ }
109
+
98
110
  /**
99
111
  * Decide the context window to report for one live model.
100
112
  *
@@ -103,6 +115,8 @@ export const QODER_INTL_PROVIDER = 'qoder-intl'
103
115
  * actually runs with. `maxInputTokens` is NOT a substitute — it is the ceiling
104
116
  * for a single request and is often lower than the session window (e.g. 180 000
105
117
  * against a 200 000 session), so falling back to it would understate capacity.
118
+ * Callers that accept a user override should validate it against
119
+ * `availableContextWindows` first — see {@link resolveDeclaredWindow}.
106
120
  *
107
121
  * @param live - the live catalog entry, when the CLI answered.
108
122
  * @param override - the user's chosen window for this model, if any.
@@ -110,7 +124,7 @@ export const QODER_INTL_PROVIDER = 'qoder-intl'
110
124
  * @returns the window in tokens.
111
125
  */
112
126
  export function pickContextWindow(
113
- live: { maxInputTokens?: number, defaultContextWindow?: number, availableContextWindows?: readonly number[] } | undefined,
127
+ live: WindowFacts | undefined,
114
128
  override: number | undefined,
115
129
  fallback: number,
116
130
  ): number {
@@ -144,16 +158,39 @@ function largestWindow(available: readonly number[] | undefined): number | undef
144
158
  * @param declared - the window this route publishes to the harness.
145
159
  * @returns the window the CLI runs with, or undefined when unknown.
146
160
  */
147
- export function cliContextWindow(
148
- live: { maxInputTokens?: number, defaultContextWindow?: number, availableContextWindows?: readonly number[] } | undefined,
149
- declared: number,
150
- ): number | undefined {
161
+ export function cliContextWindow(live: WindowFacts | undefined, declared: number): number | undefined {
151
162
  if (live === undefined) return undefined
152
163
  const available = live.availableContextWindows
153
164
  if (available !== undefined && available.includes(declared)) return declared
154
165
  return live.defaultContextWindow ?? largestWindow(available) ?? live.maxInputTokens
155
166
  }
156
167
 
168
+ /**
169
+ * The window to publish for one route, which is also the one the CLI is told
170
+ * to run with.
171
+ *
172
+ * A live entry is authoritative: the user's override counts only when the
173
+ * model advertises it. The CLI silently ignores anything else (a 1M choice on
174
+ * a 200K-only route), and dividing by it would understate every reading
175
+ * fivefold. When the catalog is momentarily unavailable, the last successful
176
+ * answer is reused instead of the static 200K default — that fallback used to
177
+ * change the denominator, and the compaction budget, mid-session: a 1M
178
+ * conversation read 1M one turn and 200K the next, and then compacted at what
179
+ * looked like 10%.
180
+ */
181
+ export function resolveDeclaredWindow(
182
+ live: WindowFacts | undefined,
183
+ override: number | undefined,
184
+ remembered: number | undefined,
185
+ fallback: number,
186
+ ): number {
187
+ if (live === undefined) return remembered ?? override ?? fallback
188
+ const available = live.availableContextWindows
189
+ const honored = override !== undefined
190
+ && (available === undefined || available.length === 0 || available.includes(override))
191
+ return pickContextWindow(live, honored ? override : undefined, remembered ?? fallback)
192
+ }
193
+
157
194
  function modelInfo(provider: string, entry: { id: string, name: string, description?: string, isVl?: boolean }): LlmModelInfo {
158
195
  return {
159
196
  provider,
@@ -237,6 +274,7 @@ export class QoderAdapter extends LlmAdapter {
237
274
  private readonly catalog: QoderModelCatalog
238
275
  private readonly usage: QoderUsage
239
276
  private readonly readImage: ImageRequestReader | undefined
277
+ private readonly imagePath: ImagePathResolver | undefined
240
278
  private readonly brand: QoderBrand
241
279
  /**
242
280
  * Memoized `Set` view of the disabled-model list.
@@ -246,6 +284,24 @@ export class QoderAdapter extends LlmAdapter {
246
284
  * hash probe instead of rebuilding a set per call, with no staleness.
247
285
  */
248
286
  private disabledCache: { source: readonly string[], set: ReadonlySet<string> } | undefined
287
+ /**
288
+ * The last window each route resolved to, plus what the model advertised.
289
+ *
290
+ * Reused only when a live entry is missing. Without it a failed refresh fell
291
+ * back to the static 200K, so a 1M session suddenly declared 200K: the ring
292
+ * denominator changed and the compaction engine budgeted against 200K,
293
+ * compacting a history that was still only ~10% of the real window.
294
+ */
295
+ private readonly knownWindows = new Map<string, { window: number, available?: readonly number[] }>()
296
+ /**
297
+ * Last verified image capability per route.
298
+ *
299
+ * A missed catalog refresh used to fall back to text-only, and DSH then
300
+ * stripped the pixels before this adapter ran: a vision model silently lost
301
+ * the image for that turn. Remembering the last answer keeps the declared
302
+ * capability stable across a transient miss.
303
+ */
304
+ private readonly knownVision = new Map<string, boolean>()
249
305
 
250
306
  constructor(options: QoderAdapterOptions = {}) {
251
307
  super()
@@ -264,6 +320,7 @@ export class QoderAdapter extends LlmAdapter {
264
320
  )
265
321
  this.usage = new QoderUsage(this.brand, options.usageCacheTtlMs)
266
322
  this.readImage = options.readImage
323
+ this.imagePath = options.imagePath
267
324
  }
268
325
 
269
326
  private get defaultMaxTokens(): number {
@@ -338,7 +395,14 @@ export class QoderAdapter extends LlmAdapter {
338
395
  * @returns live catalog entries in upstream order.
339
396
  */
340
397
  async describeCatalog(): Promise<Awaited<ReturnType<QoderModelCatalog['liveModels']>>> {
341
- return this.catalog.liveModels()
398
+ const live = await this.catalog.liveModels()
399
+ // Seed the remembered windows and capabilities here too, so the settings
400
+ // page's rows and the request path validate against the same catalog.
401
+ for (const entry of live) {
402
+ this.declaredWindow(entry.value, entry)
403
+ this.knownVision.set(entry.value, entry.isVl === true)
404
+ }
405
+ return live
342
406
  }
343
407
 
344
408
  /** Forget the cached catalog; the next read asks the CLI again. */
@@ -375,9 +439,33 @@ export class QoderAdapter extends LlmAdapter {
375
439
  return [...this.disabledModels]
376
440
  }
377
441
 
378
- /** The user's window for one model, or undefined when following upstream. */
442
+ /**
443
+ * The user's window for one model, when the provider accepts it.
444
+ *
445
+ * A stored choice the model does not advertise is not a real choice: the CLI
446
+ * ignores it and keeps its own window, so publishing it would only make the
447
+ * meter divide by a capacity the route never runs with. Until the catalog
448
+ * has answered once the choice is trusted (there is nothing to check yet).
449
+ */
379
450
  contextWindowFor(id: string): number | undefined {
380
- return this.windowOverride(id)
451
+ const override = this.windowOverride(id)
452
+ if (override === undefined) return undefined
453
+ const target = resolveQoderModelId(id, this.modelAliases)
454
+ const available = this.knownWindows.get(target)?.available
455
+ if (available === undefined || available.length === 0) return override
456
+ return available.includes(override) ? override : undefined
457
+ }
458
+
459
+ /** The window this route publishes, remembering it for catalog misses. */
460
+ private declaredWindow(id: string, live: WindowFacts | undefined): number {
461
+ const window = resolveDeclaredWindow(
462
+ live,
463
+ this.windowOverride(id),
464
+ this.knownWindows.get(id)?.window,
465
+ DEFAULT_CONTEXT_WINDOW,
466
+ )
467
+ if (live !== undefined) this.knownWindows.set(id, { window, available: live.availableContextWindows })
468
+ return window
381
469
  }
382
470
 
383
471
  /** The stored per-model window map, for rewriting the field. */
@@ -406,6 +494,8 @@ export class QoderAdapter extends LlmAdapter {
406
494
  const target = resolveQoderModelId(model, this.modelAliases)
407
495
  const live = (await this.catalog.liveModels()).find(entry => entry.value === target)
408
496
  if (live !== undefined) {
497
+ const vision = live.isVl === true
498
+ this.knownVision.set(target, vision)
409
499
  const reasoning = reasoningInfo(live.efforts, live.defaultEffort ?? this.defaultReasoningEffort, live.isReasoning)
410
500
  return {
411
501
  provider,
@@ -416,7 +506,7 @@ export class QoderAdapter extends LlmAdapter {
416
506
  // projects images to handle text for a route that omits it, so a claim
417
507
  // the CLI did not make would silently drop pixels; the reverse error
418
508
  // would send pixels to a model that cannot read them.
419
- inputModalities: live.isVl === true ? ['text' as const, 'image' as const] : ['text' as const],
509
+ inputModalities: vision ? ['text' as const, 'image' as const] : ['text' as const],
420
510
  context: {
421
511
  // The compaction engine and context meter price against the window a
422
512
  // request actually uses. Upstream reports three different numbers
@@ -425,11 +515,7 @@ export class QoderAdapter extends LlmAdapter {
425
515
  // then upstream's own session window. Reporting a window larger than
426
516
  // the session really runs with would push the auto-compaction
427
517
  // threshold past what the provider accepts.
428
- contextWindow: pickContextWindow(
429
- live,
430
- this.windowOverride(target),
431
- DEFAULT_CONTEXT_WINDOW,
432
- ),
518
+ contextWindow: this.declaredWindow(target, live),
433
519
  },
434
520
  defaultMaxTokens: live.maxOutputTokens ?? this.defaultMaxTokens,
435
521
  ...reasoning === undefined ? {} : { reasoning },
@@ -441,12 +527,17 @@ export class QoderAdapter extends LlmAdapter {
441
527
  ? QODER_MODELS.find(entry => entry.id === target)
442
528
  : undefined
443
529
  const reasoning = reasoningInfo(undefined, this.defaultReasoningEffort, true)
530
+ // The live catalog is momentarily unavailable. Reuse the last verified
531
+ // capability rather than declaring text-only, which would make the harness
532
+ // drop pixels from a vision model for this turn.
533
+ const rememberedVision = this.knownVision.get(target) === true
444
534
  return Promise.resolve({
445
535
  ...configured === undefined
446
- ? { provider, id: model, name: model, inputModalities: ['text' as const] }
536
+ ? { provider, id: model, name: model }
447
537
  : { ...modelInfo(provider, configured), id: model },
538
+ inputModalities: rememberedVision ? ['text' as const, 'image' as const] : ['text' as const],
448
539
  context: {
449
- contextWindow: this.windowOverride(target) ?? DEFAULT_CONTEXT_WINDOW,
540
+ contextWindow: this.declaredWindow(target, undefined),
450
541
  },
451
542
  defaultMaxTokens: this.defaultMaxTokens,
452
543
  ...reasoning === undefined ? {} : { reasoning },
@@ -488,7 +579,7 @@ export class QoderAdapter extends LlmAdapter {
488
579
  const model = resolveQoderModelId(options.model, this.modelAliases)
489
580
  if (options.sessionId === undefined || options.purpose !== undefined) {
490
581
  // Side channels summarise text; pixels would only cost them context.
491
- const prompt = feedToText(renderInitialFeed(options.system, options.messages))
582
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.imagePath), this.imagePath)
492
583
  + '\n(这是一次性旁路请求,直接输出下一条助手回复。)'
493
584
  // Side channels (titles, compaction summaries) reuse the main session's
494
585
  // model so dsh's recorded summarization target matches what qodercli
@@ -534,7 +625,7 @@ export class QoderAdapter extends LlmAdapter {
534
625
  session.fedMessages = options.messages
535
626
  session.fedSystem = options.system
536
627
  const feed = plan.feed === null ? null : await this.buildFeed(plan.feed, generation.vision, images)
537
- yield* session.stream(options, feed, plan.feed === null ? undefined : feedToText(plan.feed))
628
+ yield* session.stream(options, feed, plan.feed === null ? undefined : feedToText(plan.feed, this.imagePath))
538
629
  }
539
630
 
540
631
  private async *firstTurn(
@@ -554,9 +645,9 @@ export class QoderAdapter extends LlmAdapter {
554
645
  session.recordRequestInput(options.system, options.messages)
555
646
  session.fedMessages = options.messages
556
647
  session.fedSystem = options.system
557
- const feed = renderInitialFeed(options.system, options.messages)
648
+ const feed = renderInitialFeed(options.system, options.messages, this.imagePath)
558
649
  const images = await this.resolveImages(feedImageRefs(feed), vision, options.signal)
559
- yield* session.stream(options, await this.buildFeed(feed, vision, images), feedToText(feed))
650
+ yield* session.stream(options, await this.buildFeed(feed, vision, images), feedToText(feed, this.imagePath))
560
651
  }
561
652
 
562
653
  /** Image references carried by a message tail, skipping assistant content. */
@@ -604,7 +695,7 @@ export class QoderAdapter extends LlmAdapter {
604
695
  images: ResolvedImages,
605
696
  ): Promise<string | ChannelContent[]> {
606
697
  if (typeof feed === 'string') return feed
607
- if (!vision) return feedToText(feed)
698
+ if (!vision) return feedToText(feed, this.imagePath)
608
699
  const content: ChannelContent[] = []
609
700
  let pixels = 0
610
701
  for (const part of feed) {
@@ -612,11 +703,20 @@ export class QoderAdapter extends LlmAdapter {
612
703
  if (part.text.length > 0) content.push({ type: 'text', text: part.text })
613
704
  continue
614
705
  }
615
- const resolved = images.get(String(part.attachment.attachmentId))
706
+ const key = String(part.attachment.attachmentId)
707
+ const resolved = images.get(key)
708
+ const path = this.imagePath?.(part.attachment)
616
709
  if (resolved === undefined) {
617
- content.push({ type: 'text', text: `[图片附件 ${String(part.attachment.attachmentId)} 本次未能读取,请基于文字内容继续]` })
710
+ content.push({
711
+ type: 'text',
712
+ text: `[图片附件 ${key} 本次未能读取${path === undefined ? '' : `;本机文件:${path}`},请基于文字内容继续]`,
713
+ })
618
714
  continue
619
715
  }
716
+ // The pixels let the model read the image; this handle lets it find and
717
+ // edit the source file. Without it a "modify this image" turn searches
718
+ // the workspace for a file that was never there.
719
+ content.push({ type: 'text', text: imageRefText(part.attachment, path) })
620
720
  pixels += 1
621
721
  content.push({
622
722
  type: 'image',
package/src/api.ts CHANGED
@@ -45,6 +45,13 @@ export interface ModelRow {
45
45
  override?: number
46
46
  priceFactor?: number
47
47
  reasoning: boolean
48
+ /**
49
+ * Whether the provider accepts a context-budget choice for this model.
50
+ *
51
+ * Absent (Qoder, MiniMax) means the ordinary menu applies. `false` means the
52
+ * window is fixed upstream, so the page shows the value without a selector.
53
+ */
54
+ contextWindowSelectable?: boolean
48
55
  }
49
56
 
50
57
  /** The adapters the API can reach, one per provider route. */
@@ -87,6 +94,9 @@ export async function buildRows(adapter: QoderAdapter): Promise<ModelRow[]> {
87
94
  ...override === undefined ? {} : { override },
88
95
  ...priceFactor === undefined ? {} : { priceFactor },
89
96
  reasoning: entry.isReasoning !== false,
97
+ // One advertised window is a fixed window: the CLI ignores anything
98
+ // else, so the page should show the value instead of a dead selector.
99
+ contextWindowSelectable: (entry.availableContextWindows?.length ?? 0) > 1,
90
100
  }
91
101
  })
92
102
  }
@@ -98,9 +108,12 @@ export async function buildCodeBuddyRows(
98
108
  ): Promise<ModelRow[]> {
99
109
  const live = await adapter.describeCatalog(region)
100
110
  return live.map(entry => {
111
+ // Only windows the provider accepts are offered. CodeBuddy validates
112
+ // `set_config.contextWindow` against `contextWindow.supportedLengths` and
113
+ // answers anything else with `Allowed: <none>`, so a menu entry the CLI
114
+ // refuses would be a switch that does nothing upstream.
101
115
  const override = adapter.contextWindowFor(entry.id, region)
102
116
  const choices = new Set<number>(entry.contextWindows)
103
- choices.add(entry.defaultContextWindow)
104
117
  if (override !== undefined) choices.add(override)
105
118
  return {
106
119
  id: entry.id,
@@ -114,6 +127,7 @@ export async function buildCodeBuddyRows(
114
127
  ...override === undefined ? {} : { override },
115
128
  ...entry.priceFactor === undefined ? {} : { priceFactor: entry.priceFactor },
116
129
  reasoning: (entry.reasoningEfforts?.length ?? 0) > 0,
130
+ contextWindowSelectable: entry.contextWindows.length > 0,
117
131
  }
118
132
  })
119
133
  }
@@ -14,7 +14,6 @@ import type {
14
14
  GenerateOptions, LlmModelInfo, LlmProviderInfo, LlmResolvedModelInfo,
15
15
  PreparedAdapterCall, RequestMessage, StreamChunk,
16
16
  } from '@deepseek-ai/dsh-llm'
17
- import { textOnlyImageText } from '@deepseek-ai/dsh-llm'
18
17
  import type { CodeBuddyRegion } from './brand.ts'
19
18
  import { codeBuddyColdStream, CodeBuddyAccountReader, CodeBuddyAuth, CodeBuddyCatalog, CodeBuddySessionManager, CODEBUDDY_DEFAULT_CONTEXT_WINDOW, CODEBUDDY_DEFAULT_MAX_TOKENS, CODEBUDDY_CACHE_TTL_MS, CODEBUDDY_FETCH_TIMEOUT_MS } from './codebuddy.ts'
20
19
  import type { CodeBuddyModel, CodeBuddyUsageSnapshot } from './codebuddy.ts'
@@ -22,8 +21,8 @@ import { reasoningInfo, planContinuation } from './adapter.ts'
22
21
  import type { ImageRequestReader } from './adapter.ts'
23
22
  import type { Live } from './live.ts'
24
23
  import { readLive, readLiveOptional } from './live.ts'
25
- import type { Feed } from './render.ts'
26
- import { feedImageRefs, feedToText, renderInitialFeed, resolvedFeedParts } from './render.ts'
24
+ import type { Feed, ImagePathResolver } from './render.ts'
25
+ import { feedImageRefs, feedToText, imageRefText, renderInitialFeed, resolvedFeedParts } from './render.ts'
27
26
  import type { ChannelContent } from './session.ts'
28
27
 
29
28
  /** The CodeBuddy provider route. */
@@ -50,6 +49,11 @@ export interface CodeBuddyAdapterOptions {
50
49
  * store) → images degrade to their handle text instead of failing the turn.
51
50
  */
52
51
  readImage?: ImageRequestReader
52
+ /**
53
+ * The tool-world path of one image, for the handle text that lets the model
54
+ * edit it. Absent → an unreadable image keeps the harness placeholder.
55
+ */
56
+ imagePath?: ImagePathResolver
53
57
  }
54
58
 
55
59
  const NO_MODELS: readonly string[] = []
@@ -84,6 +88,8 @@ export class CodeBuddyAdapter extends LlmAdapter {
84
88
  private readonly accounts: CodeBuddyAccountReader
85
89
  private readonly auth = new CodeBuddyAuth()
86
90
  private readonly disabledCache = new Map<CodeBuddyRegion, { key: string, set: ReadonlySet<string> }>()
91
+ /** Last verified image capability, keyed `${region}:${model}`. */
92
+ private readonly knownVision = new Map<string, boolean>()
87
93
 
88
94
  constructor(options: CodeBuddyAdapterOptions = {}) {
89
95
  super()
@@ -134,7 +140,9 @@ export class CodeBuddyAdapter extends LlmAdapter {
134
140
  /** The live catalog, unfiltered (the page must show switched-off models). */
135
141
  async describeCatalog(region: CodeBuddyRegion = this.region): Promise<readonly CodeBuddyModel[]> {
136
142
  if (!this.isSignedIn(region)) return []
137
- return this.catalog.models(region)
143
+ const models = await this.catalog.models(region)
144
+ for (const model of models) this.knownVision.set(`${region}:${model.id}`, model.vision)
145
+ return models
138
146
  }
139
147
 
140
148
  /** Whether the selected (or given) region has a stored login. */
@@ -190,8 +198,16 @@ export class CodeBuddyAdapter extends LlmAdapter {
190
198
  /** Whether the resolved model accepts images (drives whether pixels are sent). */
191
199
  private async modelVision(model: string): Promise<boolean> {
192
200
  const target = resolveCodeBuddyModelId(model, this.aliases)
201
+ const key = `${this.region}:${target}`
193
202
  const live = (await this.catalog.models().catch(() => [])).find(entry => entry.id === target)
194
- return live?.vision === true
203
+ if (live !== undefined) {
204
+ this.knownVision.set(key, live.vision)
205
+ return live.vision
206
+ }
207
+ // A missed catalog read must not turn a vision model into a text-only one:
208
+ // DSH strips pixels before this adapter runs when the declared capability
209
+ // says text only.
210
+ return this.knownVision.get(key) === true
195
211
  }
196
212
 
197
213
  /**
@@ -237,7 +253,7 @@ export class CodeBuddyAdapter extends LlmAdapter {
237
253
  signal?: AbortSignal,
238
254
  ): Promise<string | ChannelContent[]> {
239
255
  if (typeof feed === 'string') return feed
240
- if (!vision) return feedToText(feed)
256
+ if (!vision) return feedToText(feed, this.options.imagePath)
241
257
  const images = await this.resolveFeedImages(feed, vision, signal)
242
258
  const parts = resolvedFeedParts(feed, images)
243
259
  if (!parts.some(part => part.type !== 'text')) return parts.map(part => part.type === 'text' ? part.text : '').join('\n\n')
@@ -247,10 +263,17 @@ export class CodeBuddyAdapter extends LlmAdapter {
247
263
  content.push({ type: 'text', text: part.text })
248
264
  continue
249
265
  }
250
- if (part.type === 'image-unreadable') {
251
- content.push({ type: 'text', text: textOnlyImageText(part.attachment) })
252
- continue
253
- }
266
+ // The pixels let the model read the image; this handle lets it find and
267
+ // edit the source file. Without it a "modify this image" turn searches
268
+ // the workspace for a file that was never there.
269
+ const path = this.options.imagePath?.(part.attachment)
270
+ content.push({
271
+ type: 'text',
272
+ text: part.type === 'image-unreadable' && path === undefined
273
+ ? `[图片附件 ${String(part.attachment.attachmentId)} 本次未能读取,请基于文字内容继续]`
274
+ : imageRefText(part.attachment, path),
275
+ })
276
+ if (part.type === 'image-unreadable') continue
254
277
  content.push({
255
278
  type: 'image',
256
279
  source: { type: 'base64', media_type: part.mediaType, data: part.data },
@@ -259,8 +282,32 @@ export class CodeBuddyAdapter extends LlmAdapter {
259
282
  return content
260
283
  }
261
284
 
285
+ /**
286
+ * The window this model actually runs with.
287
+ *
288
+ * The user's override only applies where the provider accepts one. Every
289
+ * model in the current catalog reports `supportedLengths: null`, so the CLI
290
+ * answers a `set_config.contextWindow` with `Allowed: <none>`; a stored
291
+ * override would then make DSH show a denominator the upstream never uses,
292
+ * which is exactly how the context ring drifted.
293
+ */
262
294
  contextWindowFor(id: string, region: CodeBuddyRegion = this.region): number | undefined {
263
- return this.options.modelContextWindows?.(region)[id]
295
+ const override = this.options.modelContextWindows?.(region)[id]
296
+ if (override === undefined) return undefined
297
+ const live = this.models(region).find(entry => entry.id === id)
298
+ if (live === undefined) return override
299
+ return live.contextWindows.includes(override) ? override : undefined
300
+ }
301
+
302
+ /** The catalog snapshot the adapter last read (empty before the first read). */
303
+ private models(region: CodeBuddyRegion): readonly CodeBuddyModel[] {
304
+ return this.catalog.snapshot(region)
305
+ }
306
+
307
+ /** Whether this model lets the user pick a context budget at all. */
308
+ supportsContextWindowChoice(id: string, region: CodeBuddyRegion = this.region): boolean {
309
+ const live = this.models(region).find(entry => entry.id === id)
310
+ return live !== undefined && live.contextWindows.length > 0
264
311
  }
265
312
 
266
313
  override async listModels(provider: string): Promise<readonly LlmModelInfo[]> {
@@ -273,8 +320,10 @@ export class CodeBuddyAdapter extends LlmAdapter {
273
320
 
274
321
  override async resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
275
322
  const target = resolveCodeBuddyModelId(model, this.aliases)
323
+ const key = `${this.region}:${target}`
276
324
  const live = (await this.catalog.models()).find(entry => entry.id === target)
277
325
  if (live !== undefined) {
326
+ this.knownVision.set(key, live.vision)
278
327
  const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, (live.reasoningEfforts?.length ?? 0) > 0)
279
328
  return {
280
329
  provider,
@@ -296,7 +345,7 @@ export class CodeBuddyAdapter extends LlmAdapter {
296
345
  provider,
297
346
  id: model,
298
347
  name: model,
299
- inputModalities: ['text'],
348
+ inputModalities: this.knownVision.get(key) === true ? ['text', 'image'] : ['text'],
300
349
  context: { contextWindow: this.contextWindowFor(target) ?? CODEBUDDY_DEFAULT_CONTEXT_WINDOW },
301
350
  defaultMaxTokens: readLive(this.options.defaultMaxTokens, CODEBUDDY_DEFAULT_MAX_TOKENS),
302
351
  ...reasoning === undefined ? {} : { reasoning },
@@ -321,7 +370,7 @@ export class CodeBuddyAdapter extends LlmAdapter {
321
370
  }
322
371
  const model = resolveCodeBuddyModelId(options.model, this.aliases)
323
372
  if (options.sessionId === undefined || options.purpose !== undefined) {
324
- const prompt = feedToText(renderInitialFeed(options.system, options.messages))
373
+ const prompt = feedToText(renderInitialFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath)
325
374
  + '\n(这是一次性旁路请求,直接输出下一条助手回复。)'
326
375
  for (const chunk of await codeBuddyColdStream(region, prompt, model, options)) yield chunk
327
376
  return
@@ -342,7 +391,9 @@ export class CodeBuddyAdapter extends LlmAdapter {
342
391
  yield* this.firstTurn(session, options, region, model, effort)
343
392
  return
344
393
  }
345
- session.configure(region, model, { effort, system: options.system, cwd: this.cwdOf(options) })
394
+ session.configure(region, model, {
395
+ effort, system: options.system, cwd: this.cwdOf(options), ...await this.windowOption(model),
396
+ })
346
397
  session.ensureTools(options.tools ?? [])
347
398
  session.fedMessages = options.messages
348
399
  session.fedSystem = options.system
@@ -360,19 +411,43 @@ export class CodeBuddyAdapter extends LlmAdapter {
360
411
  model: string,
361
412
  effort: string | undefined,
362
413
  ): AsyncGenerator<StreamChunk> {
363
- session.configure(region, model, { effort, system: options.system, cwd: this.cwdOf(options) })
414
+ session.configure(region, model, {
415
+ effort, system: options.system, cwd: this.cwdOf(options), ...await this.windowOption(model),
416
+ })
364
417
  session.ensureTools(options.tools ?? [])
365
418
  session.fedMessages = options.messages
366
419
  session.fedSystem = options.system
367
420
  const vision = await this.modelVision(options.model)
368
421
  const feed = await this.buildFeed(
369
- renderInitialFeed(undefined, options.messages),
422
+ renderInitialFeed(undefined, options.messages, this.options.imagePath),
370
423
  vision,
371
424
  options.signal,
372
425
  )
373
426
  yield* session.stream(options, feed)
374
427
  }
375
428
 
429
+ /**
430
+ * The context window the host and the inner session must agree on.
431
+ *
432
+ * Only a model that offers selectable budgets is configured: one fixed
433
+ * window rejects every value, so the CLI's own default already matches what
434
+ * the host shows. For a model with choices the adapter sends the picked
435
+ * value; returning to "default" sends the model's own default budget, since
436
+ * the CLI rejects a null clear (`contextWindow must be a positive safe
437
+ * integer`). The override lives for the life of the CLI process, so the
438
+ * default has to be sent explicitly to drop a previous choice.
439
+ */
440
+ private async windowOption(model: string): Promise<{ contextWindow?: number }> {
441
+ const live = (await this.catalog.models(this.region)).find(entry => entry.id === model)
442
+ if (live === undefined || live.contextWindows.length === 0) return {}
443
+ const chosen = this.options.modelContextWindows?.(this.region)[model]
444
+ return {
445
+ contextWindow: chosen !== undefined && live.contextWindows.includes(chosen)
446
+ ? chosen
447
+ : live.defaultContextWindow,
448
+ }
449
+ }
450
+
376
451
  private cwdOf(options: GenerateOptions): string | undefined {
377
452
  return (options as GenerateOptions & { cwd?: string }).cwd
378
453
  }