dsh-vertex-argon 2.2.2 → 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,31 @@
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
+
17
+ ## [2.2.3] - 2026-11-19
18
+
19
+ ### Fixed
20
+ - **Signature Part Boundary Preservation (`google-signatures.js`)**:
21
+ - Split consecutive signed parts (`text` / `thinking`) and signed empty-text parts in `observe()` so distinct signatures and original wire Part boundaries round-trip 1:1 without merging.
22
+ - **Outbound Payload Cap Enforcement & Full `1,048,576` Long-Decode Headroom (`adapter.js`)**:
23
+ - Enforced the resolved route/mode `maxOutputTokens` ceiling after `onPayload` transforms (including `httpOptions.extraBody` and `config.maxOutputTokens` / `max_output_tokens`) and separated host compaction headroom (`contextWindow - 131,072`) from the protocol ceiling (`1,048,576`) so explicit `1,048,576` long-decode budgets are reachable.
24
+ - **Eager Interactions Budget/Option Validation & Model-Aware Defaults (`adapter.js`, `interaction-adapter.js`, `interactions-input.js`)**:
25
+ - Validated `maxTokens` (including `null` and configured caps) and explicit conflicting dual reasoning fields synchronously in `ArgonAdapter.prepareCall` before entering the Interactions async generator.
26
+ - Added `defaultReasoningForModel` (`'high'` for Hydrogen / Neon when user config omits `reasoning`, keeping `'medium'` for Argon / Carbon and channel-level UI defaults).
27
+ - **Overlapping `installGemini4PiAiPatch` / `ensureGemini4ApiClientPatch` Safety (`adapter.js`)**:
28
+ - Managed active installers via an ordered owner stack + shared first-touch model state and reference-counted `ApiClient.prototype.requestStream` leases so out-of-order disposal preserves remaining active patches and restores original properties cleanly when the last installer unmounts.
29
+
5
30
  ## [2.2.2] - 2026-11-19
6
31
 
7
32
  ### 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.2`([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
 
@@ -93,8 +93,8 @@ dsh plugin --profile desktop add dsh-vertex-argon
93
93
  | 分组 | 配置项 | 默认值 | 取值范围与说明 |
94
94
  |---|---|---|---|
95
95
  | 基础与生成 | `showInModelPicker` | `true` | 是否在会话模型选择器中显示 **Gemini 4 Adapter** 分组 |
96
- | 基础与生成 | `reasoning` | `medium` | 默认思考档位:`low` / `medium` / `high`(Hydrogen 与 Neon 会话内额外支持 `xhigh`) |
97
- | 基础与生成 | `maxTokens` | `65536` | `1`–`1048576`;超过 `65,536` 需启用长解码(窗口 > 131K 时自动预留 131,072 历史空间) |
96
+ | 基础与生成 | `reasoning` | `medium`(UI 设置页)/ 未配置时 Hydrogen 与 Neon 模型默认 `high` | 默认思考档位:`low` / `medium` / `high`(Hydrogen 与 Neon 会话内额外支持 `xhigh`) |
97
+ | 基础与生成 | `maxTokens` | `65536` | `1`–`1048576`;超过 `65,536` 需启用长解码;协议请求上限支持至 `1,048,576`(`configuredMaxTokens` 仍为宿主压缩预留 `131,072` 空间) |
98
98
  | 基础与生成 | `contextWindow` | `1048576` | `1`–`1048576`;供 DSH 本地预算与上下文压缩计算使用 |
99
99
  | 基础与生成 | `longDecode` | `true` | 控制 > 65,536 输出上限、GenerateContent 检查点续传与仅思考自愈 |
100
100
  | 协议与服务层级 | `googleProtocol` | `generate-content` | `generate-content` / `interactions`(仅作用于 Gemini API) |
package/adapter.js CHANGED
@@ -6,7 +6,7 @@ import { createArgonDiagnosticTracker } from './diagnostics.js'
6
6
  import { createInteractionsHandler } from './interaction-adapter.js'
7
7
  import { interactionImageRequestTarget } from './interaction-image.js'
8
8
  import { SERVICE_TIERS, resolveServicePolicy, mergeServiceHeaders } from './service-level.js'
9
- import { generateContentHistory, resolveOfficialGemini4Model, resolveGemini4ReasoningLevel } from './interactions-input.js'
9
+ import { generateContentHistory, resolveOfficialGemini4Model, resolveGemini4ReasoningLevel, defaultReasoningForModel } from './interactions-input.js'
10
10
  import { createGoogleSignatureBridge } from './google-signatures.js'
11
11
  import { createInteractionQuery } from './interaction-query.js'
12
12
  import { assertPreparedStructuredOutput } from './structured-output.js'
@@ -277,6 +277,7 @@ function clearAutoToolModeFallback(key) {
277
277
 
278
278
  let apiClientProtoRef = null
279
279
  let apiClientPatch = null
280
+ const apiClientLeases = new Set()
280
281
 
281
282
  function getApiClientPrototype() {
282
283
  if (apiClientProtoRef) return apiClientProtoRef
@@ -289,29 +290,65 @@ function getApiClientPrototype() {
289
290
  return apiClientProtoRef
290
291
  }
291
292
 
292
- export function ensureGemini4ApiClientPatch() {
293
+ function isGemini4ApiClientPatched() {
294
+ return Boolean(apiClientPatch?.isActive?.())
295
+ }
296
+
297
+ export function ensureGemini4ApiClientPatch({ lease = false } = {}) {
293
298
  const proto = getApiClientPrototype()
294
299
  if (!proto || typeof proto.requestStream !== 'function') return () => {}
295
- if (apiClientPatch) return apiClientPatch.dispose
300
+ if (apiClientPatch && apiClientPatch.isActive()) {
301
+ const patch = apiClientPatch
302
+ if (lease) {
303
+ const token = Symbol('argonApiClientLease')
304
+ apiClientLeases.add(token)
305
+ return () => {
306
+ if (!apiClientLeases.delete(token)) return
307
+ patch.maybeDispose()
308
+ }
309
+ }
310
+ return patch.disposeUnowned
311
+ }
296
312
  const orig = proto.requestStream
297
313
  let active = true
314
+ let unowned = !lease
315
+ const token = lease ? Symbol('argonApiClientLease') : null
316
+ if (token) apiClientLeases.add(token)
298
317
  function patchedRequestStream(request) {
299
318
  const meta = request?.httpOptions?.[ARGON_LONG_DECODE_SYMBOL]
300
319
  if (!active || !meta) return orig.call(this, request)
301
320
  return continueArgonRequestStream(this, orig, request, meta)
302
321
  }
322
+ const deactivate = () => {
323
+ if (!active) return
324
+ active = false
325
+ unowned = false
326
+ apiClientLeases.clear()
327
+ // A later wrapper belongs to its installer, even when it delegates to us.
328
+ if (proto.requestStream === patchedRequestStream) proto.requestStream = orig
329
+ if (apiClientPatch === patch) apiClientPatch = null
330
+ }
303
331
  const patch = {
304
- dispose() {
332
+ isActive: () => active,
333
+ disposeUnowned() {
334
+ if (!active) return
335
+ unowned = false
336
+ if (apiClientLeases.size === 0) deactivate()
337
+ },
338
+ maybeDispose() {
305
339
  if (!active) return
306
- active = false
307
- // A later wrapper belongs to its installer, even when it delegates to us.
308
- if (proto.requestStream === patchedRequestStream) proto.requestStream = orig
309
- if (apiClientPatch === patch) apiClientPatch = null
340
+ if (!unowned && apiClientLeases.size === 0) deactivate()
310
341
  },
311
342
  }
312
343
  proto.requestStream = patchedRequestStream
313
344
  apiClientPatch = patch
314
- return patch.dispose
345
+ if (lease) {
346
+ return () => {
347
+ if (!apiClientLeases.delete(token)) return
348
+ patch.maybeDispose()
349
+ }
350
+ }
351
+ return patch.disposeUnowned
315
352
  }
316
353
 
317
354
  function wrapGemini4Stream(rawStream, tracker, signal, retryKey) {
@@ -367,13 +404,92 @@ function wrapGemini4Stream(rawStream, tracker, signal, retryKey) {
367
404
  }
368
405
  }
369
406
 
370
- export function assertGemini4MaxTokens(options, requestModel, longDecode = true) {
371
- if (!options || options.maxTokens === undefined) return
372
- const routeCeiling = requestModel?.provider === PROVIDER
407
+ function routeCeilingFor(requestModel, longDecode = true) {
408
+ return requestModel?.provider === PROVIDER
373
409
  ? (requestModel?.[MAX_TOKENS_CEILING] ?? MAX_LONG_DECODE_TOKENS)
374
410
  : (Number.isSafeInteger(requestModel?.maxTokens) && requestModel.maxTokens > 0
375
411
  ? Math.min(MAX_LONG_DECODE_TOKENS, requestModel.maxTokens)
376
412
  : (longDecode === false ? MAX_SINGLE_CALL_TOKENS : MAX_LONG_DECODE_TOKENS))
413
+ }
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
+
468
+ function assertOutboundMaxOutputTokens(body, cleanConfig, extraBody, ceiling) {
469
+ const locations = [
470
+ cleanConfig?.maxOutputTokens,
471
+ cleanConfig?.max_output_tokens,
472
+ body?.maxOutputTokens,
473
+ body?.max_output_tokens,
474
+ body?.generationConfig?.maxOutputTokens,
475
+ body?.generationConfig?.max_output_tokens,
476
+ extraBody?.maxOutputTokens,
477
+ extraBody?.max_output_tokens,
478
+ extraBody?.generationConfig?.maxOutputTokens,
479
+ extraBody?.generationConfig?.max_output_tokens,
480
+ extraBody?.generation_config?.maxOutputTokens,
481
+ extraBody?.generation_config?.max_output_tokens,
482
+ ]
483
+ for (const val of locations) {
484
+ if (val !== undefined && (!Number.isSafeInteger(val) || val < 1 || val > ceiling)) {
485
+ throw new LlmError(`Gemini 4 payload maxOutputTokens must be an integer between 1 and ${ceiling}.`, 'INVALID_REQUEST')
486
+ }
487
+ }
488
+ }
489
+
490
+ export function assertGemini4MaxTokens(options, requestModel, longDecode = true) {
491
+ if (!options || options.maxTokens === undefined) return
492
+ const routeCeiling = routeCeilingFor(requestModel, longDecode)
377
493
  if (
378
494
  !Number.isSafeInteger(options.maxTokens) ||
379
495
  options.maxTokens < 1 ||
@@ -392,7 +508,7 @@ export function gemini4StreamSimple(
392
508
  requestModel,
393
509
  context,
394
510
  options = {},
395
- defaultLevel = 'medium',
511
+ defaultLevel = undefined,
396
512
  upstreamModelId = requestModel.id,
397
513
  longDecode = true,
398
514
  recordDiagnostic,
@@ -401,8 +517,8 @@ export function gemini4StreamSimple(
401
517
  structuredOutput,
402
518
  ) {
403
519
  assertPreparedStructuredOutput(structuredOutput)
404
- ensureGemini4ApiClientPatch()
405
- const fallback = defaultLevel ?? (/cyber-permissive/i.test(requestModel?.id ?? '') ? 'high' : 'medium')
520
+ if (!isGemini4ApiClientPatched()) ensureGemini4ApiClientPatch()
521
+ const fallback = defaultLevel ?? defaultReasoningForModel(requestModel?.id)
406
522
  const modelId = requestModel?.id
407
523
  const supportsXhigh = supportsXhighReasoning(modelId)
408
524
  const { level: rawLevel } = validateExplicitReasoningFields(options, modelId, fallback)
@@ -417,7 +533,9 @@ export function gemini4StreamSimple(
417
533
  }
418
534
  const { reasoning, reasoningEffort: _re, thinking, thinkingBudgets, temperature, onPayload: prior, onProviderStreamEvent: priorEvent, ...rest } = options
419
535
  assertGemini4MaxTokens(options, requestModel, longDecode)
420
- const requestedMaxTokens = options.maxTokens ?? requestModel.maxTokens
536
+ const routeCeiling = routeCeilingFor(requestModel, longDecode)
537
+ const outboundCeiling = longDecode === false ? Math.min(routeCeiling, MAX_SINGLE_CALL_TOKENS) : routeCeiling
538
+ const requestedMaxTokens = options.maxTokens === undefined ? requestModel.maxTokens : options.maxTokens
421
539
  if (requestedMaxTokens !== undefined && (!Number.isSafeInteger(requestedMaxTokens) || requestedMaxTokens < 1 || requestedMaxTokens > MAX_LONG_DECODE_TOKENS)) {
422
540
  throw new LlmError('Invalid Gemini 4 maxTokens budget.', 'INVALID_REQUEST')
423
541
  }
@@ -472,23 +590,21 @@ export function gemini4StreamSimple(
472
590
  ? cleanConfig.httpOptions
473
591
  : {}
474
592
  const sanitizedHttpOptions = { ...prevHttpOptions }
475
- if (
476
- supportsXhigh &&
477
- prevHttpOptions.extraBody &&
478
- typeof prevHttpOptions.extraBody === 'object' &&
479
- !Array.isArray(prevHttpOptions.extraBody)
480
- ) {
481
- const cleanExtraBody = { ...prevHttpOptions.extraBody }
482
- delete cleanExtraBody.cachedContent
483
- delete cleanExtraBody.cached_content
484
- sanitizedHttpOptions.extraBody = cleanExtraBody
593
+ if (Object.hasOwn(prevHttpOptions, 'extraBody') && prevHttpOptions.extraBody !== undefined) {
594
+ sanitizedHttpOptions.extraBody = sanitizeGemini4ExtraBody(prevHttpOptions.extraBody, supportsXhigh)
485
595
  }
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
486
601
  const toolMode = shouldFallbackToAutoToolMode(retryKey) ? 'AUTO' : 'VALIDATED'
487
602
  return {
488
603
  ...body,
489
604
  model: upstreamModelId,
490
605
  config: {
491
606
  ...cleanConfig,
607
+ maxOutputTokens: resolvedPayloadMax,
492
608
  ...(cleanConfig.tools?.some(tool => tool.functionDeclarations?.length) ? {
493
609
  toolConfig: {
494
610
  ...cleanConfig.toolConfig,
@@ -516,16 +632,25 @@ export function gemini4StreamSimple(
516
632
  )
517
633
  }
518
634
 
635
+ let activePiAiPatchGeneration = null
636
+
519
637
  export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, responseHub) {
520
- const unpatchApiClient = ensureGemini4ApiClientPatch()
638
+ const unpatchApiClient = ensureGemini4ApiClientPatch({ lease: true })
521
639
  const proto = PiAiAdapter?.prototype
522
640
  if (!proto || typeof proto.current !== 'function') return unpatchApiClient
641
+ const owner = { recordDiagnostic, configInput, responseHub }
642
+ if (activePiAiPatchGeneration && activePiAiPatchGeneration.active) {
643
+ const existing = activePiAiPatchGeneration
644
+ existing.owners.push(owner)
645
+ return () => existing.removeOwner(owner, unpatchApiClient)
646
+ }
523
647
  const origCurrent = proto.current
524
648
  const origPrepareCall = typeof proto.prepareCall === 'function' ? proto.prepareCall : null
525
649
  const origProtoStream = typeof proto.stream === 'function' ? proto.stream : null
526
650
  const patchedProviders = new Map()
527
651
  const patchedModels = new Map()
528
- let active = true
652
+ const owners = [owner]
653
+ const currentOwner = () => owners.at(-1)
529
654
  const ensureGemini4Capabilities = piProvider => {
530
655
  if (typeof piProvider?.getModels !== 'function') return
531
656
  try {
@@ -565,20 +690,21 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
565
690
  const origStream = piProvider.stream
566
691
  const origStreamSimple = piProvider.streamSimple
567
692
  const dispatchGemini4 = (requestModel, context, options = {}) => {
568
- const cfg = resolveConfigValues(configInput)
693
+ const activeOwner = currentOwner()
694
+ const cfg = resolveConfigValues(activeOwner?.configInput)
569
695
  return gemini4StreamSimple(
570
696
  (m, c, o) => origStream.call(piProvider, m, c, o), requestModel, context, options,
571
- defaultReasoning, requestModel.id, cfg.longDecode, recordDiagnostic,
697
+ defaultReasoning, requestModel.id, cfg.longDecode, activeOwner?.recordDiagnostic,
572
698
  resolveServicePolicy(cfg, requestModel.api, 'generate-content'),
573
- { responseHub, retainRawResponses: cfg.retainRawResponses },
699
+ { responseHub: activeOwner?.responseHub, retainRawResponses: cfg.retainRawResponses },
574
700
  )
575
701
  }
576
702
  function patchedStreamSimple(requestModel, context, options = {}) {
577
- if (active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, options)
703
+ if (gen.active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, options)
578
704
  return origStreamSimple.call(this, requestModel, context, options)
579
705
  }
580
706
  function patchedStream(requestModel, context, options = {}) {
581
- if (active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, mapStreamThinkingOption(options))
707
+ if (gen.active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, mapStreamThinkingOption(options))
582
708
  return origStream.call(this, requestModel, context, options)
583
709
  }
584
710
  patchedProviders.set(piProvider, { origStream, patchedStream, origStreamSimple, patchedStreamSimple })
@@ -586,14 +712,14 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
586
712
  piProvider.streamSimple = patchedStreamSimple
587
713
  }
588
714
  const isNativeGemini4Target = (instance, provider, model) =>
589
- active &&
715
+ gen.active &&
590
716
  !(instance instanceof ArgonAdapter) &&
591
717
  (provider === 'google' || provider === NATIVE_PROVIDER) &&
592
718
  typeof model === 'string' &&
593
719
  /^(?:models\/)?gemini-4\b/i.test(model)
594
720
  function patchedCurrent() {
595
721
  const snapshot = origCurrent.call(this)
596
- if (active && snapshot?.profiles instanceof Map) {
722
+ if (gen.active && snapshot?.profiles instanceof Map) {
597
723
  for (const profile of snapshot.profiles.values()) {
598
724
  if (profile?.piProvider) wrapProvider(profile.piProvider, profile.reasoning)
599
725
  }
@@ -608,9 +734,9 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
608
734
  return {
609
735
  ...prepared,
610
736
  stream: options => {
611
- if (!active) return origPreparedStream(options)
737
+ if (!gen.active) return origPreparedStream(options)
612
738
  const pinned = preparePinnedStreamOptions(options, provider, model)
613
- if (resolvedModel) assertGemini4MaxTokens(pinned, resolvedModel, resolveConfigValues(configInput).longDecode)
739
+ if (resolvedModel) assertGemini4MaxTokens(pinned, resolvedModel, resolveConfigValues(currentOwner()?.configInput).longDecode)
614
740
  return origPreparedStream(generateContentHistory(pinned, model))
615
741
  },
616
742
  }
@@ -619,44 +745,56 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
619
745
  if (options && typeof options === 'object' && !Array.isArray(options) && isNativeGemini4Target(this, options.provider, options.model)) {
620
746
  const resolvedModel = this.current?.()?.models?.getModel?.(options.provider, options.model)
621
747
  const pinned = preparePinnedStreamOptions(options, options.provider, options.model)
622
- if (resolvedModel) assertGemini4MaxTokens(pinned, resolvedModel, resolveConfigValues(configInput).longDecode)
748
+ if (resolvedModel) assertGemini4MaxTokens(pinned, resolvedModel, resolveConfigValues(currentOwner()?.configInput).longDecode)
623
749
  const normalized = generateContentHistory(pinned, options.model)
624
750
  yield* origProtoStream.call(this, normalized)
625
751
  return
626
752
  }
627
753
  yield* origProtoStream.call(this, options)
628
754
  }
755
+ const gen = {
756
+ active: true,
757
+ owners,
758
+ removeOwner(targetOwner, ownerApiUnpatch) {
759
+ const idx = owners.indexOf(targetOwner)
760
+ if (idx === -1) return
761
+ owners.splice(idx, 1)
762
+ ownerApiUnpatch()
763
+ if (owners.length > 0 || !gen.active) return
764
+ gen.active = false
765
+ if (activePiAiPatchGeneration === gen) activePiAiPatchGeneration = null
766
+ if (proto.current === patchedCurrent) proto.current = origCurrent
767
+ if (origPrepareCall && proto.prepareCall === patchedPrepareCall) proto.prepareCall = origPrepareCall
768
+ if (origProtoStream && proto.stream === patchedProtoStream) proto.stream = origProtoStream
769
+ for (const [piProvider, { origStream, patchedStream, origStreamSimple, patchedStreamSimple }] of patchedProviders) {
770
+ if (piProvider.stream === patchedStream) piProvider.stream = origStream
771
+ if (piProvider.streamSimple === patchedStreamSimple) piProvider.streamSimple = origStreamSimple
772
+ }
773
+ patchedProviders.clear()
774
+ for (const [m, saved] of patchedModels) {
775
+ try {
776
+ if (saved.hadReasoning) m.reasoning = saved.reasoning
777
+ else delete m.reasoning
778
+ if (saved.hadMap) m.thinkingLevelMap = saved.thinkingLevelMap
779
+ else delete m.thinkingLevelMap
780
+ } catch {}
781
+ }
782
+ patchedModels.clear()
783
+ },
784
+ }
785
+ activePiAiPatchGeneration = gen
629
786
  proto.current = patchedCurrent
630
787
  if (origPrepareCall) proto.prepareCall = patchedPrepareCall
631
788
  if (origProtoStream) proto.stream = patchedProtoStream
632
- return () => {
633
- if (!active) return
634
- active = false
635
- unpatchApiClient()
636
- if (proto.current === patchedCurrent) proto.current = origCurrent
637
- if (origPrepareCall && proto.prepareCall === patchedPrepareCall) proto.prepareCall = origPrepareCall
638
- if (origProtoStream && proto.stream === patchedProtoStream) proto.stream = origProtoStream
639
- for (const [piProvider, { origStream, patchedStream, origStreamSimple, patchedStreamSimple }] of patchedProviders) {
640
- if (piProvider.stream === patchedStream) piProvider.stream = origStream
641
- if (piProvider.streamSimple === patchedStreamSimple) piProvider.streamSimple = origStreamSimple
642
- }
643
- patchedProviders.clear()
644
- for (const [m, saved] of patchedModels) {
645
- try {
646
- if (saved.hadReasoning) m.reasoning = saved.reasoning
647
- else delete m.reasoning
648
- if (saved.hadMap) m.thinkingLevelMap = saved.thinkingLevelMap
649
- else delete m.thinkingLevelMap
650
- } catch {}
651
- }
652
- patchedModels.clear()
653
- }
789
+ return () => gen.removeOwner(owner, unpatchApiClient)
654
790
  }
655
791
 
656
792
  export function resolveConfigValues(raw = {}) {
657
793
  const source = typeof raw === 'function' ? raw() : raw
658
794
  const showInModelPicker = readVal(source?.showInModelPicker) ?? true
659
- const reasoning = readVal(source?.reasoning) ?? 'medium'
795
+ const rawReasoning = readVal(source?.reasoning)
796
+ const hasExplicitReasoning = rawReasoning !== undefined
797
+ const reasoning = rawReasoning ?? 'medium'
660
798
  const longDecode = readVal(source?.longDecode) ?? true
661
799
  const contextWindow = readVal(source?.contextWindow) ?? 1048576
662
800
  const rawMaxTokens = readVal(source?.maxTokens) ?? MAX_SINGLE_CALL_TOKENS
@@ -685,11 +823,12 @@ export function resolveConfigValues(raw = {}) {
685
823
  const safeCompactionCap = contextWindow > COMPACTION_HEADROOM_FLOOR ? contextWindow - COMPACTION_HEADROOM_FLOOR : contextWindow
686
824
  const maxTokens = Math.max(1, Math.min(capByMode, safeCompactionCap))
687
825
  const explicitMaxTokensCap = hasExplicitMaxTokens
688
- ? Math.max(1, Math.min(rawMaxTokens, safeCompactionCap))
689
- : Math.max(1, Math.min(MAX_LONG_DECODE_TOKENS, safeCompactionCap))
826
+ ? Math.max(1, Math.min(rawMaxTokens, contextWindow, MAX_LONG_DECODE_TOKENS))
827
+ : Math.max(1, Math.min(MAX_LONG_DECODE_TOKENS, contextWindow))
690
828
  return {
691
829
  showInModelPicker: Boolean(showInModelPicker),
692
830
  reasoning,
831
+ hasExplicitReasoning,
693
832
  longDecode: enabledLongDecode,
694
833
  contextWindow,
695
834
  maxTokens,
@@ -708,7 +847,7 @@ export function resolveConfigValues(raw = {}) {
708
847
  }
709
848
 
710
849
  /** Serve the official Vertex AI and Gemini API models in one plugin group. */
711
- export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nativeGoogle = googleProvider(), longDecode = true, recordDiagnostic, serviceConfig = {}, responseHub, structuredOutput) {
850
+ export function argonProvider(nativeVertex, models, defaultLevel = undefined, nativeGoogle = googleProvider(), longDecode = true, recordDiagnostic, serviceConfig = {}, responseHub, structuredOutput) {
712
851
  const modelMap = new Map((Array.isArray(models) ? models : [models]).map(m => [m.id, m]))
713
852
  return {
714
853
  id: PROVIDER,
@@ -717,9 +856,23 @@ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nat
717
856
  getModels: () => [...modelMap.values()],
718
857
  streamSimple(requestModel, context, options = {}) {
719
858
  const configured = modelMap.get(requestModel?.id)
720
- if (!configured || requestModel.provider !== PROVIDER) {
859
+ if (!configured || requestModel?.provider !== PROVIDER) {
721
860
  throw new LlmError('Gemini 4 Adapter only serves configured Gemini 4 routes.', 'UNSUPPORTED_OPTION')
722
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
723
876
  const { env: rawEnv, apiKey: vertexApiKey, ...restOptions } = options
724
877
  const cleanEnv = rawEnv ? { ...rawEnv } : undefined
725
878
  if (cleanEnv) {
@@ -731,9 +884,9 @@ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nat
731
884
  const policy = resolveServicePolicy(serviceConfig, 'google-generative-ai', 'generate-content')
732
885
  return gemini4StreamSimple(
733
886
  (m, c, o) => nativeGoogle.stream(m, c, o),
734
- requestModel,
887
+ effectiveModel,
735
888
  context,
736
- { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(apiKey ? { apiKey } : {}), maxTokens: options.maxTokens ?? configured.maxTokens },
889
+ { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(apiKey ? { apiKey } : {}), maxTokens: requestedMaxTokens },
737
890
  defaultLevel,
738
891
  officialUpstreamModel(configured.id),
739
892
  longDecode,
@@ -742,14 +895,14 @@ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nat
742
895
  { responseHub, retainRawResponses: serviceConfig.retainRawResponses }, structuredOutput,
743
896
  )
744
897
  }
745
- if (requestModel.api !== 'google-vertex') {
898
+ if (effectiveModel.api !== 'google-vertex') {
746
899
  throw new LlmError('Gemini 4 Adapter only serves google-vertex or google-generative-ai.', 'UNSUPPORTED_OPTION')
747
900
  }
748
901
  return gemini4StreamSimple(
749
902
  (m, c, o) => nativeVertex.stream(m, c, o),
750
- requestModel,
903
+ effectiveModel,
751
904
  context,
752
- { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(vertexApiKey ? { apiKey: vertexApiKey } : {}), maxTokens: options.maxTokens ?? configured.maxTokens },
905
+ { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(vertexApiKey ? { apiKey: vertexApiKey } : {}), maxTokens: requestedMaxTokens },
753
906
  defaultLevel,
754
907
  officialUpstreamModel(configured.id),
755
908
  longDecode,
@@ -789,15 +942,19 @@ export class ArgonAdapter extends LlmAdapter {
789
942
  const protocol = googleApi ? cfg?.googleProtocol : cfg?.vertexProtocol
790
943
  if (provider === PROVIDER && cfg) resolveServicePolicy(cfg, googleApi ? 'google-generative-ai' : 'google-vertex', protocol)
791
944
  const prepared = await this.inner.prepareCall(provider, model, signal)
945
+ const resolvedModel = provider === PROVIDER
946
+ ? (this.inner.current?.()?.models?.getModel?.(provider, model) ?? (cfg ? { provider, id: model, [MAX_TOKENS_CEILING]: cfg.explicitMaxTokensCap } : undefined))
947
+ : undefined
792
948
  if (provider === PROVIDER && protocol === 'interactions' && this.interactionHandler) {
793
949
  return {
794
950
  model: prepared.model,
795
- stream: options => this.interactionHandler(syncGemini4ReasoningOptions(pinPreparedOptions(options, provider, model), model), cfg),
951
+ stream: options => {
952
+ const pinned = pinPreparedOptions(options, provider, model)
953
+ assertGemini4MaxTokens(pinned, resolvedModel, cfg?.longDecode)
954
+ return this.interactionHandler(syncGemini4ReasoningOptions(pinned, model), cfg)
955
+ },
796
956
  }
797
957
  }
798
- const resolvedModel = provider === PROVIDER
799
- ? (this.inner.current?.()?.models?.getModel?.(provider, model) ?? (cfg ? { provider, id: model, [MAX_TOKENS_CEILING]: cfg.explicitMaxTokensCap } : undefined))
800
- : undefined
801
958
  return {
802
959
  ...prepared,
803
960
  stream: options => {
@@ -854,6 +1011,7 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
854
1011
  const detected = detectPiAiArgonRoutes(ctx, cfg.routes)
855
1012
  const key = JSON.stringify({
856
1013
  r: cfg.reasoning,
1014
+ explicitR: cfg.hasExplicitReasoning,
857
1015
  ld: cfg.longDecode,
858
1016
  cw: cfg.contextWindow,
859
1017
  mt: cfg.maxTokens,
@@ -1033,13 +1191,14 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
1033
1191
  modelDescriptor[MAX_TOKENS_CEILING] = cfg.explicitMaxTokensCap
1034
1192
  }
1035
1193
  const configuredMaxTokens = new Map(models.map(m => [m.id, cfg.maxTokens]))
1036
- const provider = argonProvider({ ...nativeVertex, auth }, models, cfg.reasoning, nativeGoogle, cfg.longDecode, recordDiagnostic, cfg, responseHub, structuredOutput)
1194
+ const configuredReasoning = cfg.hasExplicitReasoning ? cfg.reasoning : undefined
1195
+ const provider = argonProvider({ ...nativeVertex, auth }, models, configuredReasoning, nativeGoogle, cfg.longDecode, recordDiagnostic, cfg, responseHub, structuredOutput)
1037
1196
  cachedKey = key
1038
1197
  cachedProfiles = new Map([[PROVIDER, {
1039
1198
  provider: PROVIDER,
1040
1199
  displayName: 'Gemini 4 Adapter',
1041
1200
  piProvider: provider,
1042
- reasoning: cfg.reasoning,
1201
+ reasoning: configuredReasoning,
1043
1202
  streamIdleTimeoutMs: cfg.longDecode ? STREAM_READ_TIMEOUT_MS + 60000 : STREAM_READ_TIMEOUT_MS,
1044
1203
  maxRequestImageBytes: 20 * 1024 * 1024,
1045
1204
  requestImagePixelBudget: 2048 * 2048,
@@ -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 })
@@ -128,8 +128,15 @@ export function createGoogleSignatureBridge(context, model) {
128
128
  const close = () => {
129
129
  if (!current) return
130
130
  const index = content.length - 1
131
- emit({ type: current.type === 'text' ? 'text_end' : 'thinking_end', contentIndex: index, content: current.type === 'text' ? current.text : current.thinking })
131
+ const sig = current.type === 'text' ? current.textSignature : current.thinkingSignature
132
+ emit({
133
+ type: current.type === 'text' ? 'text_end' : 'thinking_end',
134
+ contentIndex: index,
135
+ content: current.type === 'text' ? current.text : current.thinking,
136
+ ...(sig ? { contentSignature: sig } : {}),
137
+ })
132
138
  current = undefined
139
+ currentSignedInThisChunk = false
133
140
  }
134
141
  const finishMessage = message => {
135
142
  close()
@@ -153,6 +160,7 @@ export function createGoogleSignatureBridge(context, model) {
153
160
  },
154
161
  observe(chunk) {
155
162
  seen = true
163
+ currentSignedInThisChunk = false
156
164
  for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {
157
165
  bytes += Buffer.byteLength(JSON.stringify(part))
158
166
  if (bytes > 64 * 1024 * 1024) throw failure('Google response exceeded the bounded signature replay buffer.')
@@ -171,14 +179,22 @@ export function createGoogleSignatureBridge(context, model) {
171
179
  }
172
180
  if (part.text !== undefined) {
173
181
  const type = part.thought === true ? 'thinking' : 'text'
174
- if (!current || current.type !== type) {
182
+ const sigKey = type === 'text' ? 'textSignature' : 'thinkingSignature'
183
+ const splitSigned = type === 'text'
184
+ ? (Boolean(current?.textSignature) || (Boolean(sig) && part.text === ''))
185
+ : ((Boolean(sig) && (Boolean(current?.thinkingSignature) || part.text === '')) ||
186
+ (Boolean(current?.thinkingSignature) && (currentSignedInThisChunk || current.thinking === '')))
187
+ if (!current || current.type !== type || splitSigned) {
175
188
  close(); current = type === 'text' ? { type, text: '' } : { type, thinking: '' }
176
189
  const index = start(current)
177
190
  emit({ type: type === 'text' ? 'text_start' : 'thinking_start', contentIndex: index })
178
191
  }
179
192
  const key = type === 'text' ? 'text' : 'thinking'
180
193
  current[key] += part.text
181
- if (sig) current[type === 'text' ? 'textSignature' : 'thinkingSignature'] = sig
194
+ if (sig) {
195
+ current[sigKey] = sig
196
+ if (type === 'thinking') currentSignedInThisChunk = true
197
+ }
182
198
  emit({ type: type === 'text' ? 'text_delta' : 'thinking_delta', contentIndex: content.length - 1, delta: part.text })
183
199
  }
184
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))
@@ -4,15 +4,18 @@ import { durableInteractionTransport } from './interaction-state.js'
4
4
  import { createArgonDiagnosticTracker } from './diagnostics.js'
5
5
  import { interactionExitReason } from './interaction-lifecycle.js'
6
6
  import { resolveServicePolicy } from './service-level.js'
7
- import { resolveGemini4ReasoningLevel } from './interactions-input.js'
7
+ import { resolveGemini4ReasoningLevel, defaultReasoningForModel } from './interactions-input.js'
8
8
  // 循环导入:adapter.js 只在本模块的函数被调用时才读取这些绑定,函数声明本身已提升。
9
9
  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 ?? cfg.maxTokens
14
- if (!Number.isSafeInteger(max) || max <= 0 || max > cfg.maxTokens) throw new Error('Interactions output budget must be a positive integer within the configured effective cap.')
15
- const resolvedReasoning = resolveGemini4ReasoningLevel(options, options.model, cfg.reasoning)
13
+ const requestedMax = options.maxTokens === undefined ? cfg.maxTokens : options.maxTokens
14
+ const maxCeiling = cfg.explicitMaxTokensCap ?? cfg.maxTokens
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
17
+ const defaultReasoning = cfg?.hasExplicitReasoning === false ? defaultReasoningForModel(options.model) : cfg.reasoning
18
+ const resolvedReasoning = resolveGemini4ReasoningLevel(options, options.model, defaultReasoning)
16
19
  if (!resolvedReasoning.ok) {
17
20
  if (resolvedReasoning.errorType === 'conflict') {
18
21
  throw new Error('Conflicting reasoning and reasoningEffort options in Interactions request.')
@@ -162,7 +165,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
162
165
  return block
163
166
  }) }))
164
167
  const { streamInteractions } = await import('./interactions.js')
165
- 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 } })) {
166
169
  if (chunk.type === 'usage') {
167
170
  recordUsage()
168
171
  // Only an observed first-hop input watermark can be normalized for the
@@ -16,8 +16,13 @@ export function resolveOfficialGemini4Model(modelId) {
16
16
  supportsXhigh: family === 'hydrogen' || family === 'neon',
17
17
  }
18
18
  }
19
+ export function defaultReasoningForModel(modelId) {
20
+ const official = resolveOfficialGemini4Model(modelId)
21
+ if (official) return official.supportsXhigh ? 'high' : 'medium'
22
+ return /cyber-permissive/i.test(String(modelId ?? '')) ? 'high' : 'medium'
23
+ }
19
24
  /** 统一校验 thinking/reasoning 双字段,显式非法或双字段互相冲突时当场失败,避免静默回退默认值。 */
20
- export function resolveGemini4ReasoningLevel(options, modelId, fallback = 'medium') {
25
+ export function resolveGemini4ReasoningLevel(options, modelId, fallback = defaultReasoningForModel(modelId)) {
21
26
  const supportsXhigh = Boolean(resolveOfficialGemini4Model(modelId)?.supportsXhigh)
22
27
  const allowed = supportsXhigh ? ['low', 'medium', 'high', 'xhigh'] : ['low', 'medium', 'high']
23
28
  const validInputs = new Set([...allowed, 'max'])
@@ -123,7 +128,9 @@ function findUnclaimedToolResultIndex(messages, startIndex, toolCallId, claimedT
123
128
  // Completed foreign-protocol tool rounds become a textual transcript, never
124
129
  // forged function calls or fake thought signatures.
125
130
  export async function buildInteractionRequest(options, settings = {}) {
126
- const max = options.maxTokens ?? settings.maxTokens ?? 65536
131
+ const rawMax = options.maxTokens !== undefined
132
+ ? options.maxTokens
133
+ : (settings.maxTokens !== undefined ? settings.maxTokens : 65536)
127
134
  const hasExplicitUpstream = !isOmittedModel(settings.upstreamModel)
128
135
  const hasExplicitOption = !isOmittedModel(options.model)
129
136
  const resolvedUpstream = hasExplicitUpstream ? resolveOfficialGemini4Model(settings.upstreamModel) : null
@@ -138,9 +145,10 @@ export async function buildInteractionRequest(options, settings = {}) {
138
145
  throw new Error('Conflicting Gemini 4 models in Interactions request.')
139
146
  }
140
147
  const upstreamModel = resolvedUpstream?.upstreamModel ?? resolvedOption?.upstreamModel ?? 'gemini-4-argon'
141
- const resolvedReasoning = resolveGemini4ReasoningLevel(options, upstreamModel, settings.reasoning ?? 'medium')
148
+ const resolvedReasoning = resolveGemini4ReasoningLevel(options, upstreamModel, settings.reasoning ?? defaultReasoningForModel(upstreamModel))
142
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.')
143
- 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
144
152
  if (!resolvedReasoning.ok) {
145
153
  if (resolvedReasoning.errorType === 'conflict') {
146
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.2",
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": {