dsh-vertex-argon 2.2.3 → 2.2.4

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/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  All notable changes to **Gemini 4 Adapter** (`dsh-vertex-argon`) are documented in this file.
4
4
 
5
+ ## [2.2.4] - 2026-11-19
6
+
7
+ ### Fixed
8
+ - **Google Background Interactions `longDecode: false` Clamp & `maxTokens: null` Guard (`interaction-adapter.js`, `interactions-input.js`)**:
9
+ - Clamped outbound `maxTokens` / `generation_config.max_output_tokens` to `65,536` when `longDecode === false` (including Google background Interactions where `explicitMaxTokensCap > 65536`), and rejected explicit `maxTokens: null` in both `buildInteractionRequest` and `argonProvider.streamSimple`.
10
+ - **GenerateContent `onPayload` `extraBody` Thinking Sanitization, Mandatory Output Cap & Cloned Model Ceiling Retention (`adapter.js`)**:
11
+ - Sanitized `httpOptions.extraBody` and `extraBody.generationConfig` / `generation_config` (`thinkingConfig`, `thinkingBudget`, `includeThoughts`, sampling keys) for all Gemini 4 models (plus explicit cache fields on Hydrogen/Neon), and ensured omitted `config.maxOutputTokens` after upstream `onPayload` hooks is restored to the resolved output budget.
12
+ - Preserved trusted `configured` model properties and `MAX_TOKENS_CEILING` symbols in `argonProvider.streamSimple` so JSON-cloned model descriptors cannot bypass configured caps.
13
+ - **Signed Thinking Part Boundaries & Startup Registration Rollback (`google-signatures.js`, `index.js`)**:
14
+ - Split subsequent unsigned thinking parts away from preceding signed thinking parts in `observe()` so empty signed thinking parts preserve 1:1 boundaries.
15
+ - Registered `installGemini4PiAiPatch()` disposal immediately and rolled back the lease if `ctx.llm.registerAdapter()` throws.
16
+
5
17
  ## [2.2.3] - 2026-11-19
6
18
 
7
19
  ### Fixed
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  **面向 [DeepSeek Harness](<https://github.com/deepseek-ai/deepseek-harness>) 的 Google 官方双通道(Vertex AI + Gemini Developer API)Gemini 4 适配器,原生支持 Argon、Carbon、Hydrogen 与 Neon 八模型路由、GenerateContent / Interactions 双协议、65K+ 多跳长解码与请求级诊断。**
6
6
 
7
- - **当前版本**:`2.2.3`([CHANGELOG.md](<CHANGELOG.md>))
7
+ - **当前版本**:`2.2.4`([CHANGELOG.md](<CHANGELOG.md>))
8
8
  - **npm 包名**:`dsh-vertex-argon`(保留既有包名、官方通道路由与本地存储域 ID,官方通道用户可直接原地升级;`2.0.0` 已移除 `1.6.x` 非官方反代通道)
9
9
  - **运行要求**:DSH `>=0.2.0-rc.2`,Node.js `^22.19.0 || >=24.0.0`(见 [package.json](<package.json>))
10
10
 
package/adapter.js CHANGED
@@ -412,6 +412,59 @@ function routeCeilingFor(requestModel, longDecode = true) {
412
412
  : (longDecode === false ? MAX_SINGLE_CALL_TOKENS : MAX_LONG_DECODE_TOKENS))
413
413
  }
414
414
 
415
+ function isPlainObjectRecord(value) {
416
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
417
+ const proto = Object.getPrototypeOf(value)
418
+ return proto === null || proto === Object.prototype
419
+ }
420
+
421
+ const EXTRA_BODY_STRIPPED_KEYS = [
422
+ 'thinkingConfig',
423
+ 'thinking_config',
424
+ 'thinkingBudget',
425
+ 'thinking_budget',
426
+ 'includeThoughts',
427
+ 'include_thoughts',
428
+ 'temperature',
429
+ 'topP',
430
+ 'top_p',
431
+ 'topK',
432
+ 'top_k',
433
+ 'candidateCount',
434
+ 'candidate_count',
435
+ 'frequencyPenalty',
436
+ 'frequency_penalty',
437
+ 'presencePenalty',
438
+ 'presence_penalty',
439
+ ]
440
+
441
+ function sanitizeGemini4ExtraBody(extraBody, stripExplicitCache) {
442
+ if (extraBody === undefined || extraBody === null) return extraBody
443
+ if (!isPlainObjectRecord(extraBody)) {
444
+ throw new LlmError('Gemini 4 httpOptions.extraBody must be a plain object.', 'INVALID_REQUEST')
445
+ }
446
+ const cleanExtraBody = { ...extraBody }
447
+ for (const key of EXTRA_BODY_STRIPPED_KEYS) delete cleanExtraBody[key]
448
+ if (stripExplicitCache) {
449
+ delete cleanExtraBody.cachedContent
450
+ delete cleanExtraBody.cached_content
451
+ }
452
+ for (const cfgKey of ['generationConfig', 'generation_config']) {
453
+ if (cleanExtraBody[cfgKey] === undefined || cleanExtraBody[cfgKey] === null) continue
454
+ if (!isPlainObjectRecord(cleanExtraBody[cfgKey])) {
455
+ throw new LlmError(`Gemini 4 httpOptions.extraBody.${cfgKey} must be a plain object.`, 'INVALID_REQUEST')
456
+ }
457
+ const sub = { ...cleanExtraBody[cfgKey] }
458
+ for (const key of EXTRA_BODY_STRIPPED_KEYS) delete sub[key]
459
+ if (stripExplicitCache) {
460
+ delete sub.cachedContent
461
+ delete sub.cached_content
462
+ }
463
+ cleanExtraBody[cfgKey] = sub
464
+ }
465
+ return cleanExtraBody
466
+ }
467
+
415
468
  function assertOutboundMaxOutputTokens(body, cleanConfig, extraBody, ceiling) {
416
469
  const locations = [
417
470
  cleanConfig?.maxOutputTokens,
@@ -482,7 +535,7 @@ export function gemini4StreamSimple(
482
535
  assertGemini4MaxTokens(options, requestModel, longDecode)
483
536
  const routeCeiling = routeCeilingFor(requestModel, longDecode)
484
537
  const outboundCeiling = longDecode === false ? Math.min(routeCeiling, MAX_SINGLE_CALL_TOKENS) : routeCeiling
485
- const requestedMaxTokens = options.maxTokens ?? requestModel.maxTokens
538
+ const requestedMaxTokens = options.maxTokens === undefined ? requestModel.maxTokens : options.maxTokens
486
539
  if (requestedMaxTokens !== undefined && (!Number.isSafeInteger(requestedMaxTokens) || requestedMaxTokens < 1 || requestedMaxTokens > MAX_LONG_DECODE_TOKENS)) {
487
540
  throw new LlmError('Invalid Gemini 4 maxTokens budget.', 'INVALID_REQUEST')
488
541
  }
@@ -537,32 +590,21 @@ export function gemini4StreamSimple(
537
590
  ? cleanConfig.httpOptions
538
591
  : {}
539
592
  const sanitizedHttpOptions = { ...prevHttpOptions }
540
- if (
541
- supportsXhigh &&
542
- prevHttpOptions.extraBody &&
543
- typeof prevHttpOptions.extraBody === 'object' &&
544
- !Array.isArray(prevHttpOptions.extraBody)
545
- ) {
546
- const cleanExtraBody = { ...prevHttpOptions.extraBody }
547
- delete cleanExtraBody.cachedContent
548
- delete cleanExtraBody.cached_content
549
- for (const cfgKey of ['generationConfig', 'generation_config']) {
550
- if (cleanExtraBody[cfgKey] && typeof cleanExtraBody[cfgKey] === 'object' && !Array.isArray(cleanExtraBody[cfgKey])) {
551
- const sub = { ...cleanExtraBody[cfgKey] }
552
- delete sub.cachedContent
553
- delete sub.cached_content
554
- cleanExtraBody[cfgKey] = sub
555
- }
556
- }
557
- sanitizedHttpOptions.extraBody = cleanExtraBody
593
+ if (Object.hasOwn(prevHttpOptions, 'extraBody') && prevHttpOptions.extraBody !== undefined) {
594
+ sanitizedHttpOptions.extraBody = sanitizeGemini4ExtraBody(prevHttpOptions.extraBody, supportsXhigh)
558
595
  }
559
596
  assertOutboundMaxOutputTokens(body, cleanConfig, sanitizedHttpOptions.extraBody, outboundCeiling)
597
+ const resolvedPayloadMax = cleanConfig.maxOutputTokens !== undefined
598
+ ? cleanConfig.maxOutputTokens
599
+ : (cleanConfig.max_output_tokens !== undefined ? cleanConfig.max_output_tokens : (effectiveMaxTokens ?? outboundCeiling))
600
+ delete cleanConfig.max_output_tokens
560
601
  const toolMode = shouldFallbackToAutoToolMode(retryKey) ? 'AUTO' : 'VALIDATED'
561
602
  return {
562
603
  ...body,
563
604
  model: upstreamModelId,
564
605
  config: {
565
606
  ...cleanConfig,
607
+ maxOutputTokens: resolvedPayloadMax,
566
608
  ...(cleanConfig.tools?.some(tool => tool.functionDeclarations?.length) ? {
567
609
  toolConfig: {
568
610
  ...cleanConfig.toolConfig,
@@ -814,9 +856,23 @@ export function argonProvider(nativeVertex, models, defaultLevel = undefined, na
814
856
  getModels: () => [...modelMap.values()],
815
857
  streamSimple(requestModel, context, options = {}) {
816
858
  const configured = modelMap.get(requestModel?.id)
817
- if (!configured || requestModel.provider !== PROVIDER) {
859
+ if (!configured || requestModel?.provider !== PROVIDER) {
818
860
  throw new LlmError('Gemini 4 Adapter only serves configured Gemini 4 routes.', 'UNSUPPORTED_OPTION')
819
861
  }
862
+ if (requestModel.api !== undefined && requestModel.api !== configured.api) {
863
+ throw new LlmError('Gemini 4 Adapter only serves google-vertex or google-generative-ai.', 'UNSUPPORTED_OPTION')
864
+ }
865
+ const effectiveModel = {
866
+ ...configured,
867
+ ...requestModel,
868
+ id: configured.id,
869
+ provider: PROVIDER,
870
+ api: configured.api,
871
+ maxTokens: configured.maxTokens,
872
+ thinkingLevelMap: configured.thinkingLevelMap,
873
+ [MAX_TOKENS_CEILING]: configured[MAX_TOKENS_CEILING] ?? (Number.isSafeInteger(configured.maxTokens) ? configured.maxTokens : undefined),
874
+ }
875
+ const requestedMaxTokens = options.maxTokens === undefined ? configured.maxTokens : options.maxTokens
820
876
  const { env: rawEnv, apiKey: vertexApiKey, ...restOptions } = options
821
877
  const cleanEnv = rawEnv ? { ...rawEnv } : undefined
822
878
  if (cleanEnv) {
@@ -828,9 +884,9 @@ export function argonProvider(nativeVertex, models, defaultLevel = undefined, na
828
884
  const policy = resolveServicePolicy(serviceConfig, 'google-generative-ai', 'generate-content')
829
885
  return gemini4StreamSimple(
830
886
  (m, c, o) => nativeGoogle.stream(m, c, o),
831
- requestModel,
887
+ effectiveModel,
832
888
  context,
833
- { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(apiKey ? { apiKey } : {}), maxTokens: options.maxTokens ?? configured.maxTokens },
889
+ { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(apiKey ? { apiKey } : {}), maxTokens: requestedMaxTokens },
834
890
  defaultLevel,
835
891
  officialUpstreamModel(configured.id),
836
892
  longDecode,
@@ -839,14 +895,14 @@ export function argonProvider(nativeVertex, models, defaultLevel = undefined, na
839
895
  { responseHub, retainRawResponses: serviceConfig.retainRawResponses }, structuredOutput,
840
896
  )
841
897
  }
842
- if (requestModel.api !== 'google-vertex') {
898
+ if (effectiveModel.api !== 'google-vertex') {
843
899
  throw new LlmError('Gemini 4 Adapter only serves google-vertex or google-generative-ai.', 'UNSUPPORTED_OPTION')
844
900
  }
845
901
  return gemini4StreamSimple(
846
902
  (m, c, o) => nativeVertex.stream(m, c, o),
847
- requestModel,
903
+ effectiveModel,
848
904
  context,
849
- { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(vertexApiKey ? { apiKey: vertexApiKey } : {}), maxTokens: options.maxTokens ?? configured.maxTokens },
905
+ { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(vertexApiKey ? { apiKey: vertexApiKey } : {}), maxTokens: requestedMaxTokens },
850
906
  defaultLevel,
851
907
  officialUpstreamModel(configured.id),
852
908
  longDecode,
@@ -115,7 +115,7 @@ export function createGoogleSignatureBridge(context, model) {
115
115
  const historyDigest = history.digest('hex')
116
116
  const content = [], pending = [], standalone = new Map(), usedToolIds = new Set()
117
117
  const partial = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content }
118
- let current, seen = false, bytes = 0
118
+ let current, currentSignedInThisChunk = false, seen = false, bytes = 0
119
119
  const emit = event => {
120
120
  if (pending.length >= 32768) throw failure('Google response exceeded the bounded pending event count.')
121
121
  pending.push({ ...event, partial })
@@ -136,6 +136,7 @@ export function createGoogleSignatureBridge(context, model) {
136
136
  ...(sig ? { contentSignature: sig } : {}),
137
137
  })
138
138
  current = undefined
139
+ currentSignedInThisChunk = false
139
140
  }
140
141
  const finishMessage = message => {
141
142
  close()
@@ -159,6 +160,7 @@ export function createGoogleSignatureBridge(context, model) {
159
160
  },
160
161
  observe(chunk) {
161
162
  seen = true
163
+ currentSignedInThisChunk = false
162
164
  for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {
163
165
  bytes += Buffer.byteLength(JSON.stringify(part))
164
166
  if (bytes > 64 * 1024 * 1024) throw failure('Google response exceeded the bounded signature replay buffer.')
@@ -180,7 +182,8 @@ export function createGoogleSignatureBridge(context, model) {
180
182
  const sigKey = type === 'text' ? 'textSignature' : 'thinkingSignature'
181
183
  const splitSigned = type === 'text'
182
184
  ? (Boolean(current?.textSignature) || (Boolean(sig) && part.text === ''))
183
- : (Boolean(sig) && (Boolean(current?.thinkingSignature) || part.text === ''))
185
+ : ((Boolean(sig) && (Boolean(current?.thinkingSignature) || part.text === '')) ||
186
+ (Boolean(current?.thinkingSignature) && (currentSignedInThisChunk || current.thinking === '')))
184
187
  if (!current || current.type !== type || splitSigned) {
185
188
  close(); current = type === 'text' ? { type, text: '' } : { type, thinking: '' }
186
189
  const index = start(current)
@@ -188,7 +191,10 @@ export function createGoogleSignatureBridge(context, model) {
188
191
  }
189
192
  const key = type === 'text' ? 'text' : 'thinking'
190
193
  current[key] += part.text
191
- if (sig) current[sigKey] = sig
194
+ if (sig) {
195
+ current[sigKey] = sig
196
+ if (type === 'thinking') currentSignedInThisChunk = true
197
+ }
192
198
  emit({ type: type === 'text' ? 'text_delta' : 'thinking_delta', contentIndex: content.length - 1, delta: part.text })
193
199
  }
194
200
  if (part.functionCall) {
package/index.js CHANGED
@@ -119,11 +119,17 @@ export function apply(ctx, config) {
119
119
  const recordDiagnostic = record => hub.record(record)
120
120
  const adapter = createArgonAdapter(ctx, () => config, undefined, undefined, recordDiagnostic, taskHub, responseHub)
121
121
  const unpatchPiAi = installGemini4PiAiPatch(recordDiagnostic, () => config, responseHub)
122
- const registration = ctx.llm.registerAdapter([PROVIDER], adapter)
123
- ctx.effect(() => () => {
122
+ let registration
123
+ try {
124
+ registration = ctx.llm.registerAdapter([PROVIDER], adapter)
125
+ ctx.effect(() => () => {
126
+ unpatchPiAi()
127
+ registration?.()
128
+ })
129
+ } catch (error) {
124
130
  unpatchPiAi()
125
- registration?.()
126
- })
131
+ throw error
132
+ }
127
133
  if (typeof ctx.on === 'function') {
128
134
  ctx.on('llm/stream', (options, next) => associations.stream(options, next))
129
135
  ctx.on('agent/assistant-stream', payload => associations.frame(payload))
@@ -10,9 +10,10 @@ import { isGoogleApiModel, officialUpstreamModel } from './adapter.js'
10
10
 
11
11
  const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'failed', 'cancelled', 'budget_exceeded'])
12
12
  export function assertInteractionOptions(options, cfg, route) {
13
- const max = options.maxTokens === undefined ? cfg.maxTokens : options.maxTokens
13
+ const requestedMax = options.maxTokens === undefined ? cfg.maxTokens : options.maxTokens
14
14
  const maxCeiling = cfg.explicitMaxTokensCap ?? cfg.maxTokens
15
- if (!Number.isSafeInteger(max) || max <= 0 || max > maxCeiling) throw new Error('Interactions output budget must be a positive integer within the configured effective cap.')
15
+ if (!Number.isSafeInteger(requestedMax) || requestedMax <= 0 || requestedMax > maxCeiling) throw new Error('Interactions output budget must be a positive integer within the configured effective cap.')
16
+ const max = cfg.longDecode === false ? Math.min(requestedMax, 65536) : requestedMax
16
17
  const defaultReasoning = cfg?.hasExplicitReasoning === false ? defaultReasoningForModel(options.model) : cfg.reasoning
17
18
  const resolvedReasoning = resolveGemini4ReasoningLevel(options, options.model, defaultReasoning)
18
19
  if (!resolvedReasoning.ok) {
@@ -164,7 +165,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
164
165
  return block
165
166
  }) }))
166
167
  const { streamInteractions } = await import('./interactions.js')
167
- for await (const chunk of streamInteractions({ ...options, messages, signal }, { route, upstreamModel, ...controls, serviceTier: route === 'google-generative-ai' ? servicePolicy.tier : undefined, background: cfg.interactionsBackground, store: cfg.allowInteractionStorage, transport, resolveImage, structuredOutput, onEvent: observed, onReconnectDelay: ms => { pendingBackoffMs = ms }, onTerminal: () => { complete = true }, onExit: reason => { exitReason = reason } })) {
168
+ for await (const chunk of streamInteractions({ ...options, maxTokens: controls.maxTokens, messages, signal }, { route, upstreamModel, ...controls, longDecode: cfg.longDecode, serviceTier: route === 'google-generative-ai' ? servicePolicy.tier : undefined, background: cfg.interactionsBackground, store: cfg.allowInteractionStorage, transport, resolveImage, structuredOutput, onEvent: observed, onReconnectDelay: ms => { pendingBackoffMs = ms }, onTerminal: () => { complete = true }, onExit: reason => { exitReason = reason } })) {
168
169
  if (chunk.type === 'usage') {
169
170
  recordUsage()
170
171
  // Only an observed first-hop input watermark can be normalized for the
@@ -128,7 +128,9 @@ function findUnclaimedToolResultIndex(messages, startIndex, toolCallId, claimedT
128
128
  // Completed foreign-protocol tool rounds become a textual transcript, never
129
129
  // forged function calls or fake thought signatures.
130
130
  export async function buildInteractionRequest(options, settings = {}) {
131
- const max = options.maxTokens ?? settings.maxTokens ?? 65536
131
+ const rawMax = options.maxTokens !== undefined
132
+ ? options.maxTokens
133
+ : (settings.maxTokens !== undefined ? settings.maxTokens : 65536)
132
134
  const hasExplicitUpstream = !isOmittedModel(settings.upstreamModel)
133
135
  const hasExplicitOption = !isOmittedModel(options.model)
134
136
  const resolvedUpstream = hasExplicitUpstream ? resolveOfficialGemini4Model(settings.upstreamModel) : null
@@ -145,7 +147,8 @@ export async function buildInteractionRequest(options, settings = {}) {
145
147
  const upstreamModel = resolvedUpstream?.upstreamModel ?? resolvedOption?.upstreamModel ?? 'gemini-4-argon'
146
148
  const resolvedReasoning = resolveGemini4ReasoningLevel(options, upstreamModel, settings.reasoning ?? defaultReasoningForModel(upstreamModel))
147
149
  for (const flag of [settings.background, settings.store]) if (flag !== undefined && typeof flag !== 'boolean') throw new Error('Interactions background and storage consent must be booleans.')
148
- if (!Number.isSafeInteger(max) || max<1 || max>1048576) throw new Error('Invalid Interactions output token budget.')
150
+ if (!Number.isSafeInteger(rawMax) || rawMax<1 || rawMax>1048576) throw new Error('Invalid Interactions output token budget.')
151
+ const max = settings.longDecode === false ? Math.min(rawMax, 65536) : rawMax
149
152
  if (!resolvedReasoning.ok) {
150
153
  if (resolvedReasoning.errorType === 'conflict') {
151
154
  throw new Error('Conflicting reasoning and reasoningEffort options in Interactions request.')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-vertex-argon",
3
- "version": "2.2.3",
3
+ "version": "2.2.4",
4
4
  "description": "Gemini 4 Adapter for DSH: official Vertex AI & Gemini API channels (Argon, Carbon, Hydrogen & Neon), resilient long decode, explicit service tiers, and request diagnostics.",
5
5
  "license": "MIT",
6
6
  "repository": {