dsh-vertex-argon 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes to **Gemini 4 Adapter** (`dsh-vertex-argon`) are documented in this file.
4
4
 
5
+ ## [2.2.2] - 2026-11-19
6
+
7
+ ### Fixed
8
+ - **Hook/Adapter Dual-Field Reasoning Parity & `maxTokens` Guard (`index.js`, `adapter.js`)**:
9
+ - Added `syncGemini4ReasoningOptions` so `agent/request`, `ArgonAdapter.prepareCall().stream` (both GenerateContent and Interactions), and native `PiAiAdapter` wrappers agree on explicit `{ reasoning, reasoningEffort }` pairs (e.g., `{ reasoning: 'low', reasoningEffort: 'max' }` resolves cleanly while keeping invalid inputs rejected), and write both fields when explicit so omitted `reasoningEffort` cannot fall back to profile defaults.
10
+ - Enforced positive safe integer and declared route `maxTokens` ceiling (`<= 1,048,576`, honoring explicit route/config limits while preserving `longDecode=false` 64K clamping) in `gemini4StreamSimple`.
11
+ - **Turn-Scoped `toolCallId` Pairing & Complete Native `google`/`google-vertex` Coverage (`interactions-input.js`, `google-signatures.js`, `adapter.js`)**:
12
+ - Scoped tool-call result pairing in `buildInteractionRequest`, `generateContentHistory`, and `createGoogleSignatureBridge` strictly to `[assistantIndex + 1, nextAssistant)` turn boundaries so an interrupted prior call with a reused `toolCallId` cannot claim a subsequent turn's result, and upgraded `createGoogleSignatureBridge` to downgrade cross-model `toolCall` / `thinking` turns even without standalone codecs.
13
+ - Routed native `google` / `google-vertex` `PiAiAdapter.prototype.prepareCall` and `stream` through `generateContentHistory`, tracked modified model descriptors so `unpatch` restores original `reasoning` / `thinkingLevelMap` properties, and honored `active` inside retained prepared closures.
14
+
15
+ ## [2.2.1] - 2026-11-19
16
+
17
+ ### Fixed
18
+ - **Strict 8-Model Parsing & Prepared Target Pinning (`interactions-input.js`, `adapter.js`, `interaction-adapter.js`)**:
19
+ - Unified official 8-model parsing (`resolveOfficialGemini4Model`) across `isGoogleApiModel`, `officialUpstreamModel`, `isHydrogenModel`, `isNeonModel`, `supportsXhighReasoning`, and `buildInteractionRequest` (`models/` prefix, case-insensitive, explicit `UNKNOWN_MODEL` / `Error` rejection for unknown non-empty IDs while retaining default `'gemini-4-argon'` when omitted, and exact model resolution when `settings.upstreamModel` is omitted in Interactions).
20
+ - Tightened `detectPiAiArgonRoutes` regex tails from `\b` to `$` so `-preview` / experimental suffixes are not treated as official routes.
21
+ - Hardened `ArgonAdapter.prepareCall` to synchronously reject non-object options or mismatched `provider` / `model` (`INVALID_REQUEST`) and pin `(provider, model)` on omitted fields across both GenerateContent and Interactions branches.
22
+ - **Dual-Field Reasoning Guards (`interactions-input.js`, `interaction-adapter.js`, `adapter.js`)**:
23
+ - Added shared `resolveGemini4ReasoningLevel` so explicit `reasoning` and `reasoningEffort` are both checked at `ArgonAdapter.stream`, `prepareCall().stream`, `gemini4StreamSimple`, `assertInteractionOptions`, and `buildInteractionRequest`, rejecting explicit invalid efforts (such as `{ reasoning: 'off' }`) or conflicting non-`max` fields instead of falling back to defaults, and guarding `narrowMaxReasoning` when a sibling field is invalid.
24
+ - **Complete Native Patch & Explicit Cache Cleanup (`adapter.js`)**:
25
+ - Updated `installGemini4PiAiPatch` to apply `thinkingLevelMap` to pre-enabled `isGemini4Model` entries regardless of existing `m.reasoning`, wrap `piProvider.stream` alongside `piProvider.streamSimple`, wrap `PiAiAdapter.prototype.prepareCall` / `PiAiAdapter.prototype.stream` for native `google` / `google-vertex` Gemini 4 routes, strip `httpOptions.extraBody.cachedContent` / `cached_content` non-mutatingly on Hydrogen/Neon, and cleanly restore all patched prototypes/methods on disposal.
26
+ - **Cross-Turn Reused `toolCallId` History Isolation (`interactions-input.js`, `google-signatures.js`)**:
27
+ - Replaced global `Map` / `Set` tracking with per-`toolCallId` FIFO queues and unclaimed-after-position lookup in `buildInteractionRequest`, `generateContentHistory`, and `createGoogleSignatureBridge`, preventing earlier downgraded turns from corrupting reused native `toolCallId` turns or masking later unfinished calls.
28
+
5
29
  ## [2.2.0] - 2026-11-19
6
30
 
7
31
  ### Added
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.0`([CHANGELOG.md](<CHANGELOG.md>))
7
+ - **当前版本**:`2.2.2`([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
@@ -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 } from './interactions-input.js'
9
+ import { generateContentHistory, resolveOfficialGemini4Model, resolveGemini4ReasoningLevel } 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'
@@ -29,20 +29,16 @@ export const HYDROGEN_MODEL = 'gemini-4-hydrogen'
29
29
  export const GOOGLE_API_HYDROGEN_MODEL = 'gemini-4-hydrogen-google'
30
30
  export const NEON_MODEL = 'gemini-4-neon'
31
31
  export const GOOGLE_API_NEON_MODEL = 'gemini-4-neon-google'
32
- /** Gemini API 官方直连模型判定(Argon、Carbon、Hydrogen 与 Neon)。 */
32
+ /** Gemini API 官方直连模型判定(Argon、Carbon、Hydrogen 与 Neon,支持可选 models/ 前缀)。 */
33
33
  export function isGoogleApiModel(modelId) {
34
- return (
35
- modelId === GOOGLE_API_MODEL ||
36
- modelId === GOOGLE_API_CARBON_MODEL ||
37
- modelId === GOOGLE_API_HYDROGEN_MODEL ||
38
- modelId === GOOGLE_API_NEON_MODEL
39
- )
34
+ return resolveOfficialGemini4Model(modelId)?.isGoogleApi ?? false
40
35
  }
41
- /** 官方直连(Vertex AI / Gemini API)对应的上游模型 ID。 */
36
+ /** 官方直连(Vertex AI / Gemini API)对应的上游模型 ID;空值回落默认 Argon,未知非空模型报错。 */
42
37
  export function officialUpstreamModel(modelId) {
43
- if (modelId === NEON_MODEL || modelId === GOOGLE_API_NEON_MODEL) return NEON_MODEL
44
- if (modelId === HYDROGEN_MODEL || modelId === GOOGLE_API_HYDROGEN_MODEL) return HYDROGEN_MODEL
45
- return modelId === CARBON_MODEL || modelId === GOOGLE_API_CARBON_MODEL ? CARBON_MODEL : MODEL
38
+ if (modelId === undefined || modelId === null || modelId === '') return MODEL
39
+ const resolved = resolveOfficialGemini4Model(modelId)
40
+ if (!resolved) throw new LlmError(`Unknown Gemini 4 official model: ${String(modelId)}`, 'UNKNOWN_MODEL')
41
+ return resolved.upstreamModel
46
42
  }
47
43
  export const LEVELS = ['low', 'medium', 'high']
48
44
  /**
@@ -53,6 +49,7 @@ export const HYDROGEN_LEVELS = ['low', 'medium', 'high', 'xhigh']
53
49
  export const MAX_SINGLE_CALL_TOKENS = 65536
54
50
  export const MAX_LONG_DECODE_TOKENS = 1048576
55
51
  const COMPACTION_HEADROOM_FLOOR = 131072
52
+ const MAX_TOKENS_CEILING = Symbol('argonMaxTokensCeiling')
56
53
  const ENV_KEYS = ['GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_CLOUD_PROJECT', 'GCLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION', 'GOOGLE_CLOUD_API_KEY']
57
54
  const DEFAULT_THINKING_MAP = { off: null, minimal: null, low: 'low', medium: 'medium', high: 'high', xhigh: null, max: null }
58
55
  /** Hydrogen 与 Neon 的档位映射:把 xhigh 放行到 thinkingConfig。 */
@@ -60,17 +57,17 @@ const HYDROGEN_THINKING_MAP = { off: null, minimal: null, low: 'low', medium: 'm
60
57
 
61
58
  /** Hydrogen 模型 ID 判定:同时识别 `gemini-4-hydrogen` 与 `gemini-4-hydrogen-google`(可带 models/ 前缀)。 */
62
59
  export function isHydrogenModel(modelId) {
63
- return typeof modelId === 'string' && /^(?:models\/)?gemini-4-hydrogen(?:-google)?$/i.test(modelId)
60
+ return resolveOfficialGemini4Model(modelId)?.family === 'hydrogen'
64
61
  }
65
62
 
66
63
  /** Neon 模型 ID 判定:同时识别 `gemini-4-neon` 与 `gemini-4-neon-google`(可带 models/ 前缀)。 */
67
64
  export function isNeonModel(modelId) {
68
- return typeof modelId === 'string' && /^(?:models\/)?gemini-4-neon(?:-google)?$/i.test(modelId)
65
+ return resolveOfficialGemini4Model(modelId)?.family === 'neon'
69
66
  }
70
67
 
71
68
  /** 判断模型是否支持 xhigh 第四档思考及对应无显式缓存限制(Hydrogen 与 Neon)。 */
72
69
  export function supportsXhighReasoning(modelId) {
73
- return isHydrogenModel(modelId) || isNeonModel(modelId)
70
+ return resolveOfficialGemini4Model(modelId)?.supportsXhigh ?? false
74
71
  }
75
72
 
76
73
  /** 模型对应的合法思考档位集合:Hydrogen 与 Neon 放行 xhigh。 */
@@ -83,18 +80,73 @@ export function thinkingLevelMapFor(modelId) {
83
80
  return supportsXhighReasoning(modelId) ? HYDROGEN_THINKING_MAP : DEFAULT_THINKING_MAP
84
81
  }
85
82
 
83
+ function assertPlainRequestOptions(options) {
84
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
85
+ throw new LlmError('Request options must be a plain object.', 'INVALID_REQUEST')
86
+ }
87
+ return options
88
+ }
89
+
90
+ function validateExplicitReasoningFields(options, modelId, fallback = 'medium') {
91
+ const result = resolveGemini4ReasoningLevel(options, modelId, fallback)
92
+ if (!result.ok) {
93
+ if (result.errorType === 'conflict') {
94
+ throw new LlmError(
95
+ `Model ${modelId ?? MODEL} received conflicting reasoning (${result.reasoning}) and reasoningEffort (${result.reasoningEffort}).`,
96
+ 'INVALID_REQUEST',
97
+ )
98
+ }
99
+ throw new LlmError(
100
+ `Model ${modelId ?? MODEL} does not support reasoning effort "${String(result.effort)}".`,
101
+ 'UNSUPPORTED_REASONING_EFFORT',
102
+ )
103
+ }
104
+ return result
105
+ }
106
+
86
107
  // The host's agent/request hook already narrows 'max' to 'high'. Direct adapter
87
108
  // callers (advisor tools calling adapter.stream / prepareCall().stream) bypass
88
109
  // that hook, so the same narrowing has to happen at this boundary too.
89
110
  export function narrowMaxReasoning(options, modelId = options?.model) {
90
111
  if (!options || typeof options !== 'object') return options
91
- const requested = [options.reasoning, options.reasoningEffort]
92
- if (!requested.some(value => typeof value === 'string' && value.toLowerCase() === 'max')) return options
112
+ const validInputs = new Set([...levelsForModel(modelId), 'max'])
113
+ const normalize = value => (value === undefined ? undefined : typeof value === 'string' && validInputs.has(value.toLowerCase()) ? value.toLowerCase() : null)
114
+ const reasoning = normalize(options.reasoning)
115
+ const effort = normalize(options.reasoningEffort)
116
+ if (reasoning === null || effort === null) return options
117
+ if (reasoning !== 'max' && effort !== 'max') return options
93
118
  // Hydrogen 与 Neon 的最高档是 xhigh;其余模型仍是 high。
94
119
  const ceiling = supportsXhighReasoning(modelId) ? 'xhigh' : 'high'
95
120
  return { ...options, reasoning: ceiling, reasoningEffort: ceiling }
96
121
  }
97
122
 
123
+ export function syncGemini4ReasoningOptions(options, modelId = options?.model) {
124
+ if (!options || typeof options !== 'object' || Array.isArray(options)) return options
125
+ if (options.reasoning === undefined && options.reasoningEffort === undefined) return options
126
+ const result = resolveGemini4ReasoningLevel(options, modelId)
127
+ if (!result.ok) return options
128
+ return { ...options, reasoning: result.level, reasoningEffort: result.level }
129
+ }
130
+
131
+ function pinPreparedOptions(options, expectedProvider, expectedModel) {
132
+ assertPlainRequestOptions(options)
133
+ if (expectedProvider !== undefined && options.provider !== undefined && options.provider !== expectedProvider) {
134
+ throw new LlmError('Prepared stream provider mismatch.', 'INVALID_REQUEST')
135
+ }
136
+ if (expectedModel !== undefined && options.model !== undefined && options.model !== expectedModel) {
137
+ throw new LlmError('Prepared stream model mismatch.', 'INVALID_REQUEST')
138
+ }
139
+ return expectedProvider !== undefined && expectedModel !== undefined
140
+ ? { ...options, provider: expectedProvider, model: expectedModel }
141
+ : options
142
+ }
143
+ function preparePinnedStreamOptions(options, expectedProvider, expectedModel) {
144
+ const pinned = pinPreparedOptions(options, expectedProvider, expectedModel)
145
+ const targetModel = pinned.model ?? expectedModel
146
+ validateExplicitReasoningFields(pinned, targetModel)
147
+ return syncGemini4ReasoningOptions(pinned, targetModel)
148
+ }
149
+
98
150
  const readVal = v => (v && typeof v === 'object' && typeof v.get === 'function') ? v.get() : v
99
151
 
100
152
  export function isGemini4Model(model) {
@@ -151,14 +203,14 @@ export function detectPiAiArgonRoutes(ctx, explicitRoutes) {
151
203
  const hasModel = (list, re) => Array.isArray(list) && list.some(m => re.test(String(readVal(m?.id) ?? '')))
152
204
  const googleModels = readVal(googleCfg?.models)
153
205
  const vertexModels = readVal(vertexCfg?.models)
154
- const hasGoogleArgon = hasModel(googleModels, /^(?:models\/)?gemini-4-argon\b/i)
155
- const hasVertexArgon = hasModel(vertexModels, /^(?:models\/)?gemini-4-argon\b/i)
156
- const hasGoogleCarbon = hasModel(googleModels, /^(?:models\/)?gemini-4-carbon\b/i)
157
- const hasVertexCarbon = hasModel(vertexModels, /^(?:models\/)?gemini-4-carbon\b/i)
158
- const hasGoogleHydrogen = hasModel(googleModels, /^(?:models\/)?gemini-4-hydrogen\b/i)
159
- const hasVertexHydrogen = hasModel(vertexModels, /^(?:models\/)?gemini-4-hydrogen\b/i)
160
- const hasGoogleNeon = hasModel(googleModels, /^(?:models\/)?gemini-4-neon\b/i)
161
- const hasVertexNeon = hasModel(vertexModels, /^(?:models\/)?gemini-4-neon\b/i)
206
+ const hasGoogleArgon = hasModel(googleModels, /^(?:models\/)?gemini-4-argon$/i)
207
+ const hasVertexArgon = hasModel(vertexModels, /^(?:models\/)?gemini-4-argon$/i)
208
+ const hasGoogleCarbon = hasModel(googleModels, /^(?:models\/)?gemini-4-carbon$/i)
209
+ const hasVertexCarbon = hasModel(vertexModels, /^(?:models\/)?gemini-4-carbon$/i)
210
+ const hasGoogleHydrogen = hasModel(googleModels, /^(?:models\/)?gemini-4-hydrogen$/i)
211
+ const hasVertexHydrogen = hasModel(vertexModels, /^(?:models\/)?gemini-4-hydrogen$/i)
212
+ const hasGoogleNeon = hasModel(googleModels, /^(?:models\/)?gemini-4-neon$/i)
213
+ const hasVertexNeon = hasModel(vertexModels, /^(?:models\/)?gemini-4-neon$/i)
162
214
  const hasGoogle = hasGoogleArgon || hasGoogleCarbon || hasGoogleHydrogen || hasGoogleNeon
163
215
  const hasVertex = hasVertexArgon || hasVertexCarbon || hasVertexHydrogen || hasVertexNeon || !hasGoogle
164
216
  return {
@@ -315,6 +367,26 @@ function wrapGemini4Stream(rawStream, tracker, signal, retryKey) {
315
367
  }
316
368
  }
317
369
 
370
+ export function assertGemini4MaxTokens(options, requestModel, longDecode = true) {
371
+ if (!options || options.maxTokens === undefined) return
372
+ const routeCeiling = requestModel?.provider === PROVIDER
373
+ ? (requestModel?.[MAX_TOKENS_CEILING] ?? MAX_LONG_DECODE_TOKENS)
374
+ : (Number.isSafeInteger(requestModel?.maxTokens) && requestModel.maxTokens > 0
375
+ ? Math.min(MAX_LONG_DECODE_TOKENS, requestModel.maxTokens)
376
+ : (longDecode === false ? MAX_SINGLE_CALL_TOKENS : MAX_LONG_DECODE_TOKENS))
377
+ if (
378
+ !Number.isSafeInteger(options.maxTokens) ||
379
+ options.maxTokens < 1 ||
380
+ options.maxTokens > MAX_LONG_DECODE_TOKENS ||
381
+ options.maxTokens > routeCeiling
382
+ ) {
383
+ throw new LlmError(
384
+ `Gemini 4 maxTokens must be an integer between 1 and ${Math.min(MAX_LONG_DECODE_TOKENS, routeCeiling)}.`,
385
+ 'INVALID_REQUEST',
386
+ )
387
+ }
388
+ }
389
+
318
390
  export function gemini4StreamSimple(
319
391
  nativeStream,
320
392
  requestModel,
@@ -333,23 +405,22 @@ export function gemini4StreamSimple(
333
405
  const fallback = defaultLevel ?? (/cyber-permissive/i.test(requestModel?.id ?? '') ? 'high' : 'medium')
334
406
  const modelId = requestModel?.id
335
407
  const supportsXhigh = supportsXhighReasoning(modelId)
336
- const requestedLevel = options.reasoning ?? fallback
337
- // max 按目标模型收敛:Hydrogen 与 Neon 收到四档最高档 xhigh,Argon / Carbon 仍是 high。
338
- const rawLevel = typeof requestedLevel === 'string' && requestedLevel.toLowerCase() === 'max'
339
- ? (supportsXhigh ? 'xhigh' : 'high')
340
- : (typeof requestedLevel === 'string' ? requestedLevel.toLowerCase() : requestedLevel)
341
- const mapped = requestModel?.thinkingLevelMap?.[rawLevel] ?? rawLevel
342
- const level = typeof mapped === 'string' ? mapped.toLowerCase() : fallback
343
- if (!levelsForModel(modelId).includes(level)) {
408
+ const { level: rawLevel } = validateExplicitReasoningFields(options, modelId, fallback)
409
+ const hasMapped = requestModel?.thinkingLevelMap && Object.prototype.hasOwnProperty.call(requestModel.thinkingLevelMap, rawLevel)
410
+ const mapped = hasMapped ? requestModel.thinkingLevelMap[rawLevel] : rawLevel
411
+ const level = typeof mapped === 'string' ? mapped.toLowerCase() : null
412
+ if (!level || !levelsForModel(modelId).includes(level)) {
344
413
  throw new LlmError(
345
- supportsXhigh
346
- ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high or xhigh.'
347
- : 'Gemini 4 (Argon / Carbon) requires low, medium or high.',
414
+ `Model ${modelId ?? MODEL} does not support reasoning effort "${rawLevel}".`,
348
415
  'UNSUPPORTED_REASONING_EFFORT',
349
416
  )
350
417
  }
351
- const { reasoning, thinking, thinkingBudgets, temperature, onPayload: prior, onProviderStreamEvent: priorEvent, ...rest } = options
418
+ const { reasoning, reasoningEffort: _re, thinking, thinkingBudgets, temperature, onPayload: prior, onProviderStreamEvent: priorEvent, ...rest } = options
419
+ assertGemini4MaxTokens(options, requestModel, longDecode)
352
420
  const requestedMaxTokens = options.maxTokens ?? requestModel.maxTokens
421
+ if (requestedMaxTokens !== undefined && (!Number.isSafeInteger(requestedMaxTokens) || requestedMaxTokens < 1 || requestedMaxTokens > MAX_LONG_DECODE_TOKENS)) {
422
+ throw new LlmError('Invalid Gemini 4 maxTokens budget.', 'INVALID_REQUEST')
423
+ }
353
424
  const effectiveMaxTokens =
354
425
  longDecode === false && typeof requestedMaxTokens === 'number' && requestedMaxTokens > MAX_SINGLE_CALL_TOKENS
355
426
  ? MAX_SINGLE_CALL_TOKENS
@@ -400,6 +471,18 @@ export function gemini4StreamSimple(
400
471
  cleanConfig.httpOptions && typeof cleanConfig.httpOptions === 'object' && !Array.isArray(cleanConfig.httpOptions)
401
472
  ? cleanConfig.httpOptions
402
473
  : {}
474
+ 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
485
+ }
403
486
  const toolMode = shouldFallbackToAutoToolMode(retryKey) ? 'AUTO' : 'VALIDATED'
404
487
  return {
405
488
  ...body,
@@ -415,8 +498,8 @@ export function gemini4StreamSimple(
415
498
  automaticContinuation: false,
416
499
  thinkingConfig: { thinkingLevel: level.toUpperCase(), includeThoughts: true },
417
500
  httpOptions: {
418
- ...prevHttpOptions,
419
- ...(Object.keys(servicePolicy.headers).length ? { headers: mergeServiceHeaders(prevHttpOptions.headers, servicePolicy) } : {}),
501
+ ...sanitizedHttpOptions,
502
+ ...(Object.keys(servicePolicy.headers).length ? { headers: mergeServiceHeaders(sanitizedHttpOptions.headers, servicePolicy) } : {}),
420
503
  [ARGON_LONG_DECODE_SYMBOL]: {
421
504
  enabled: longDecode !== false,
422
505
  serviceTier: requestModel.api === 'google-generative-ai' ? servicePolicy.tier : undefined,
@@ -438,39 +521,76 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
438
521
  const proto = PiAiAdapter?.prototype
439
522
  if (!proto || typeof proto.current !== 'function') return unpatchApiClient
440
523
  const origCurrent = proto.current
524
+ const origPrepareCall = typeof proto.prepareCall === 'function' ? proto.prepareCall : null
525
+ const origProtoStream = typeof proto.stream === 'function' ? proto.stream : null
441
526
  const patchedProviders = new Map()
527
+ const patchedModels = new Map()
442
528
  let active = true
443
529
  const ensureGemini4Capabilities = piProvider => {
444
530
  if (typeof piProvider?.getModels !== 'function') return
445
531
  try {
446
532
  for (const m of piProvider.getModels()) {
447
- if (isGemini4Model(m) && !m.reasoning) {
448
- m.reasoning = true
449
- m.thinkingLevelMap = { ...thinkingLevelMapFor(m.id) }
533
+ if (isGemini4Model(m)) {
534
+ try {
535
+ if (!patchedModels.has(m)) {
536
+ patchedModels.set(m, {
537
+ hadReasoning: Object.prototype.hasOwnProperty.call(m, 'reasoning'),
538
+ reasoning: m.reasoning,
539
+ hadMap: Object.prototype.hasOwnProperty.call(m, 'thinkingLevelMap'),
540
+ thinkingLevelMap: m.thinkingLevelMap,
541
+ })
542
+ }
543
+ m.reasoning = true
544
+ m.thinkingLevelMap = { ...thinkingLevelMapFor(m.id) }
545
+ } catch {}
450
546
  }
451
547
  }
452
548
  } catch {}
453
549
  }
550
+ const mapStreamThinkingOption = options => {
551
+ if (!options || typeof options !== 'object' || Array.isArray(options)) return options
552
+ if (options.reasoning !== undefined || options.reasoningEffort !== undefined) return options
553
+ const thinking = options.thinking
554
+ if (!thinking || typeof thinking !== 'object' || Array.isArray(thinking)) return options
555
+ if (thinking.enabled === false || (typeof thinking.budgetTokens === 'number' && thinking.budgetTokens <= 0)) {
556
+ return { ...options, reasoning: 'off' }
557
+ }
558
+ if (typeof thinking.level === 'string') return { ...options, reasoning: thinking.level }
559
+ return options
560
+ }
454
561
  const wrapProvider = (piProvider, defaultReasoning) => {
455
562
  if (!piProvider || typeof piProvider.streamSimple !== 'function' || typeof piProvider.stream !== 'function') return
456
563
  ensureGemini4Capabilities(piProvider)
457
564
  if (piProvider.id === PROVIDER || patchedProviders.has(piProvider)) return
565
+ const origStream = piProvider.stream
458
566
  const origStreamSimple = piProvider.streamSimple
567
+ const dispatchGemini4 = (requestModel, context, options = {}) => {
568
+ const cfg = resolveConfigValues(configInput)
569
+ return gemini4StreamSimple(
570
+ (m, c, o) => origStream.call(piProvider, m, c, o), requestModel, context, options,
571
+ defaultReasoning, requestModel.id, cfg.longDecode, recordDiagnostic,
572
+ resolveServicePolicy(cfg, requestModel.api, 'generate-content'),
573
+ { responseHub, retainRawResponses: cfg.retainRawResponses },
574
+ )
575
+ }
459
576
  function patchedStreamSimple(requestModel, context, options = {}) {
460
- if (active && isGemini4Model(requestModel)) {
461
- const cfg = resolveConfigValues(configInput)
462
- return gemini4StreamSimple(
463
- (m, c, o) => piProvider.stream(m, c, o), requestModel, context, options,
464
- defaultReasoning, requestModel.id, cfg.longDecode, recordDiagnostic,
465
- resolveServicePolicy(cfg, requestModel.api, 'generate-content'),
466
- { responseHub, retainRawResponses: cfg.retainRawResponses },
467
- )
468
- }
577
+ if (active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, options)
469
578
  return origStreamSimple.call(this, requestModel, context, options)
470
579
  }
471
- patchedProviders.set(piProvider, { origStreamSimple, patchedStreamSimple })
580
+ function patchedStream(requestModel, context, options = {}) {
581
+ if (active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, mapStreamThinkingOption(options))
582
+ return origStream.call(this, requestModel, context, options)
583
+ }
584
+ patchedProviders.set(piProvider, { origStream, patchedStream, origStreamSimple, patchedStreamSimple })
585
+ piProvider.stream = patchedStream
472
586
  piProvider.streamSimple = patchedStreamSimple
473
587
  }
588
+ const isNativeGemini4Target = (instance, provider, model) =>
589
+ active &&
590
+ !(instance instanceof ArgonAdapter) &&
591
+ (provider === 'google' || provider === NATIVE_PROVIDER) &&
592
+ typeof model === 'string' &&
593
+ /^(?:models\/)?gemini-4\b/i.test(model)
474
594
  function patchedCurrent() {
475
595
  const snapshot = origCurrent.call(this)
476
596
  if (active && snapshot?.profiles instanceof Map) {
@@ -480,16 +600,56 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
480
600
  }
481
601
  return snapshot
482
602
  }
603
+ async function patchedPrepareCall(provider, model, signal) {
604
+ const prepared = await origPrepareCall.call(this, provider, model, signal)
605
+ if (!isNativeGemini4Target(this, provider, model)) return prepared
606
+ const origPreparedStream = prepared.stream
607
+ const resolvedModel = this.current?.()?.models?.getModel?.(provider, model)
608
+ return {
609
+ ...prepared,
610
+ stream: options => {
611
+ if (!active) return origPreparedStream(options)
612
+ const pinned = preparePinnedStreamOptions(options, provider, model)
613
+ if (resolvedModel) assertGemini4MaxTokens(pinned, resolvedModel, resolveConfigValues(configInput).longDecode)
614
+ return origPreparedStream(generateContentHistory(pinned, model))
615
+ },
616
+ }
617
+ }
618
+ async function* patchedProtoStream(options) {
619
+ if (options && typeof options === 'object' && !Array.isArray(options) && isNativeGemini4Target(this, options.provider, options.model)) {
620
+ const resolvedModel = this.current?.()?.models?.getModel?.(options.provider, options.model)
621
+ const pinned = preparePinnedStreamOptions(options, options.provider, options.model)
622
+ if (resolvedModel) assertGemini4MaxTokens(pinned, resolvedModel, resolveConfigValues(configInput).longDecode)
623
+ const normalized = generateContentHistory(pinned, options.model)
624
+ yield* origProtoStream.call(this, normalized)
625
+ return
626
+ }
627
+ yield* origProtoStream.call(this, options)
628
+ }
483
629
  proto.current = patchedCurrent
630
+ if (origPrepareCall) proto.prepareCall = patchedPrepareCall
631
+ if (origProtoStream) proto.stream = patchedProtoStream
484
632
  return () => {
485
633
  if (!active) return
486
634
  active = false
487
635
  unpatchApiClient()
488
636
  if (proto.current === patchedCurrent) proto.current = origCurrent
489
- for (const [piProvider, { origStreamSimple, patchedStreamSimple }] of patchedProviders) {
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
490
641
  if (piProvider.streamSimple === patchedStreamSimple) piProvider.streamSimple = origStreamSimple
491
642
  }
492
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()
493
653
  }
494
654
  }
495
655
 
@@ -519,16 +679,22 @@ export function resolveConfigValues(raw = {}) {
519
679
  for (const [key, val] of [['contextWindow', contextWindow], ['maxTokens', rawMaxTokens]]) {
520
680
  if (!Number.isSafeInteger(val) || val <= 0 || val > MAX_LONG_DECODE_TOKENS) throw new LlmError('Invalid Argon ' + key, 'INVALID_CONFIG')
521
681
  }
682
+ const hasExplicitMaxTokens = source?.maxTokens !== undefined && readVal(source?.maxTokens) !== undefined
522
683
  const enabledLongDecode = Boolean(longDecode)
523
684
  const capByMode = enabledLongDecode ? Math.min(rawMaxTokens, MAX_LONG_DECODE_TOKENS) : Math.min(rawMaxTokens, MAX_SINGLE_CALL_TOKENS)
524
685
  const safeCompactionCap = contextWindow > COMPACTION_HEADROOM_FLOOR ? contextWindow - COMPACTION_HEADROOM_FLOOR : contextWindow
525
686
  const maxTokens = Math.max(1, Math.min(capByMode, safeCompactionCap))
687
+ const explicitMaxTokensCap = hasExplicitMaxTokens
688
+ ? Math.max(1, Math.min(rawMaxTokens, safeCompactionCap))
689
+ : Math.max(1, Math.min(MAX_LONG_DECODE_TOKENS, safeCompactionCap))
526
690
  return {
527
691
  showInModelPicker: Boolean(showInModelPicker),
528
692
  reasoning,
529
693
  longDecode: enabledLongDecode,
530
694
  contextWindow,
531
695
  maxTokens,
696
+ hasExplicitMaxTokens,
697
+ explicitMaxTokensCap,
532
698
  googleProtocol,
533
699
  vertexProtocol,
534
700
  googleServiceTier,
@@ -624,11 +790,25 @@ export class ArgonAdapter extends LlmAdapter {
624
790
  if (provider === PROVIDER && cfg) resolveServicePolicy(cfg, googleApi ? 'google-generative-ai' : 'google-vertex', protocol)
625
791
  const prepared = await this.inner.prepareCall(provider, model, signal)
626
792
  if (provider === PROVIDER && protocol === 'interactions' && this.interactionHandler) {
627
- return { model: prepared.model, stream: options => this.interactionHandler(narrowMaxReasoning(options && typeof options === 'object' && !options.model ? { ...options, model } : options, model), cfg) }
793
+ return {
794
+ model: prepared.model,
795
+ stream: options => this.interactionHandler(syncGemini4ReasoningOptions(pinPreparedOptions(options, provider, model), model), cfg),
796
+ }
797
+ }
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
+ return {
802
+ ...prepared,
803
+ stream: options => {
804
+ const pinned = preparePinnedStreamOptions(options, provider, model)
805
+ if (provider === PROVIDER) assertGemini4MaxTokens(pinned, resolvedModel, cfg?.longDecode)
806
+ return prepared.stream(generateContentHistory(pinned, model))
807
+ },
628
808
  }
629
- return { ...prepared, stream: options => prepared.stream(generateContentHistory(narrowMaxReasoning(options, model), model)) }
630
809
  }
631
810
  async *stream(options) {
811
+ assertPlainRequestOptions(options)
632
812
  const prepared = await this.prepareCall(options.provider, options.model, options.signal)
633
813
  yield* prepared.stream(options)
634
814
  }
@@ -677,6 +857,8 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
677
857
  ld: cfg.longDecode,
678
858
  cw: cfg.contextWindow,
679
859
  mt: cfg.maxTokens,
860
+ explicitMt: cfg.hasExplicitMaxTokens,
861
+ capMt: cfg.explicitMaxTokensCap,
680
862
  visible: cfg.showInModelPicker,
681
863
  gp: cfg.googleProtocol,
682
864
  vp: cfg.vertexProtocol,
@@ -847,6 +1029,9 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
847
1029
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
848
1030
  })
849
1031
  }
1032
+ for (const modelDescriptor of models) {
1033
+ modelDescriptor[MAX_TOKENS_CEILING] = cfg.explicitMaxTokensCap
1034
+ }
850
1035
  const configuredMaxTokens = new Map(models.map(m => [m.id, cfg.maxTokens]))
851
1036
  const provider = argonProvider({ ...nativeVertex, auth }, models, cfg.reasoning, nativeGoogle, cfg.longDecode, recordDiagnostic, cfg, responseHub, structuredOutput)
852
1037
  cachedKey = key
@@ -18,13 +18,34 @@ function decode(value) {
18
18
  } catch { return null }
19
19
  }
20
20
 
21
- function unsigned(message, demoted) {
21
+ function hasFollowingAssistant(messages, position) {
22
+ for (let i = position + 1; i < messages.length; i++) {
23
+ if (messages[i]?.role === 'assistant') return true
24
+ }
25
+ return false
26
+ }
27
+
28
+ function findTurnToolResultIndex(messages, assistantIndex, toolCallId, claimedIndices) {
29
+ for (let i = assistantIndex + 1; i < messages.length; i++) {
30
+ const msg = messages[i]
31
+ if (msg.role === 'assistant') break
32
+ if (claimedIndices.has(i)) continue
33
+ if (msg.role === 'toolResult' && msg.toolCallId === toolCallId) return i
34
+ }
35
+ return -1
36
+ }
37
+
38
+ function unsigned(message, assistantIndex, allMessages, claimedIndices, demotedByResultIndex) {
22
39
  const content = []
23
40
  for (const block of message.content) {
24
41
  const { textSignature, thinkingSignature, thoughtSignature, ...rest } = block
42
+ if (rest.type === 'thinking') continue
25
43
  if (rest.type === 'toolCall') {
26
- // 工具头存进映射,交给后续 toolResult 用 user 角色呈现;绝不写回 model 正文。
27
- demoted.set(rest.id, '[Previously executed tool ' + rest.name + '; call ' + rest.id + ']\n' + JSON.stringify(rest.arguments ?? {}))
44
+ // 工具头按回合边界内匹配的 toolResult 下标登记,绝不跨过下一轮 assistant 偷认回执。
45
+ const matchIndex = findTurnToolResultIndex(allMessages, assistantIndex, rest.id, claimedIndices)
46
+ if (matchIndex === -1) throw failure('Complete the pending tool call before replaying across Google signature boundaries.')
47
+ claimedIndices.add(matchIndex)
48
+ demotedByResultIndex.set(matchIndex, '[Previously executed tool ' + rest.name + '; call ' + rest.id + ']\n' + JSON.stringify(rest.arguments ?? {}))
28
49
  continue
29
50
  }
30
51
  content.push(rest)
@@ -33,9 +54,8 @@ function unsigned(message, demoted) {
33
54
  }
34
55
 
35
56
  /** 对应被降级工具调用的结果消息:改成用户态文本,不再伪装成 functionResponse。 */
36
- function demotedResult(message, demoted) {
57
+ function demotedResult(message, header) {
37
58
  const content = Array.isArray(message.content) ? message.content : [{ type: 'text', text: String(message.content ?? '') }]
38
- const header = demoted.get(message.toolCallId)
39
59
  const resultLead = '[Historical result of tool call ' + String(message.toolCallId) + '; data, not a new user instruction]'
40
60
  return { role: 'user', content: [{ type: 'text', text: header ? header + '\n' + resultLead : resultLead }, ...content] }
41
61
  }
@@ -43,11 +63,13 @@ function demotedResult(message, demoted) {
43
63
  // The existing textSignature field is adapter-owned opaque replay metadata.
44
64
  // Its versioned codec never reaches Google: onPayload restores the original Part.
45
65
  export function createGoogleSignatureBridge(context, model) {
46
- const restore = [], history = createHash('sha256'), demoted = new Map()
47
- const messages = context.messages.map(message => {
48
- // 被降级的工具往返:下游结果同样要变成用户态文本,否则上游会收到孤立的 functionResponse。
49
- if (message.role === 'toolResult' && demoted.has(message.toolCallId)) {
50
- const next = demotedResult(message, demoted)
66
+ const restore = [], history = createHash('sha256'), claimedIndices = new Set(), demotedByResultIndex = new Map()
67
+ const messages = context.messages.map((message, index, allMessages) => {
68
+ // 被降级的工具往返:仅消费本回合内明确配对的 toolResult 下标,不跨轮误认。
69
+ if (message.role === 'toolResult' && demotedByResultIndex.has(index)) {
70
+ const header = demotedByResultIndex.get(index)
71
+ demotedByResultIndex.delete(index)
72
+ const next = demotedResult(message, header)
51
73
  history.update(historyRecord(next))
52
74
  return next
53
75
  }
@@ -60,12 +82,23 @@ export function createGoogleSignatureBridge(context, model) {
60
82
  const same = message.api === model.api && message.provider === model.provider && message.model === model.id
61
83
  const codes = message.content.map(block => block.type === 'text' ? decode(block.textSignature) : undefined)
62
84
  const hasCodes = codes.some(code => code !== undefined)
63
- const contentDigest = hasCodes ? digest(message.content) : undefined
85
+ const brokenCodec = hasCodes && (!same || codes.some((code, idx) => code !== undefined && (!code || message.content[idx].text !== '' || code.contentDigest !== digest(message.content) || code.historyDigest !== previousHistory)))
86
+ const hasForeignTurnContent = !same && message.content.some(block => block.type === 'toolCall' || block.type === 'thinking')
64
87
  let next = message
65
- if (hasCodes && (!same || codes.some((code, index) => code !== undefined && (!code || message.content[index].text !== '' || code.contentDigest !== contentDigest || code.historyDigest !== previousHistory)))) next = unsigned(message, demoted)
66
- else {
67
- const content = message.content.map((block, index) => {
68
- const code = codes[index]
88
+ if (brokenCodec || hasForeignTurnContent) {
89
+ next = unsigned(message, index, allMessages, claimedIndices, demotedByResultIndex)
90
+ } else {
91
+ for (const block of message.content) {
92
+ if (block.type === 'toolCall') {
93
+ const matchIndex = findTurnToolResultIndex(allMessages, index, block.id, claimedIndices)
94
+ if (matchIndex === -1 && hasFollowingAssistant(allMessages, index)) {
95
+ throw failure('Complete the pending tool turn before replaying Google history.')
96
+ }
97
+ if (matchIndex !== -1) claimedIndices.add(matchIndex)
98
+ }
99
+ }
100
+ const content = message.content.map((block, idx) => {
101
+ const code = codes[idx]
69
102
  if (code) {
70
103
  const carrier = Buffer.from(code.signature).toString('base64')
71
104
  restore.push({ signature: code.signature, carrier, standalone: true, ...(code.thought === undefined ? {} : { thought: code.thought }) })
package/index.js CHANGED
@@ -12,10 +12,10 @@ import {
12
12
  installGemini4PiAiPatch,
13
13
  resolveConfigValues,
14
14
  detectPiAiArgonRoutes,
15
+ syncGemini4ReasoningOptions,
15
16
  PROVIDER,
16
17
  NATIVE_PROVIDER,
17
18
  LEVELS,
18
- supportsXhighReasoning,
19
19
  MAX_SINGLE_CALL_TOKENS,
20
20
  MAX_LONG_DECODE_TOKENS,
21
21
  } from './adapter.js'
@@ -132,16 +132,11 @@ export function apply(ctx, config) {
132
132
  ctx.on('agent/request', async (_payload, next) => {
133
133
  const proposed = await next()
134
134
  if (
135
- (proposed?.provider === PROVIDER ||
136
- ((proposed?.provider === 'google' || proposed?.provider === 'google-vertex') &&
137
- /^(?:models\/)?gemini-4\b/i.test(proposed?.model ?? ''))) &&
138
- proposed.reasoningEffort === 'max'
135
+ proposed?.provider === PROVIDER ||
136
+ ((proposed?.provider === 'google' || proposed?.provider === NATIVE_PROVIDER) &&
137
+ /^(?:models\/)?gemini-4\b/i.test(proposed?.model ?? ''))
139
138
  ) {
140
- // Hydrogen 与 Neon 的最高档是第四档 xhigh;其余 Gemini 4 模型仍是 high。
141
- return {
142
- ...proposed,
143
- reasoningEffort: supportsXhighReasoning(proposed?.model) ? 'xhigh' : 'high',
144
- }
139
+ return syncGemini4ReasoningOptions(proposed, proposed?.model)
145
140
  }
146
141
  return proposed
147
142
  })
@@ -4,21 +4,22 @@ 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
8
  // 循环导入:adapter.js 只在本模块的函数被调用时才读取这些绑定,函数声明本身已提升。
8
- import { isGoogleApiModel, officialUpstreamModel, supportsXhighReasoning, levelsForModel } from './adapter.js'
9
+ import { isGoogleApiModel, officialUpstreamModel } from './adapter.js'
9
10
 
10
11
  const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'failed', 'cancelled', 'budget_exceeded'])
11
12
  export function assertInteractionOptions(options, cfg, route) {
12
13
  const max = options.maxTokens ?? cfg.maxTokens
13
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.')
14
- const xhighSupported = supportsXhighReasoning(options.model)
15
- const requestedLevel = options.reasoningEffort ?? cfg.reasoning
16
- const normalizedRequested = typeof requestedLevel === 'string' ? requestedLevel.toLowerCase() : requestedLevel
17
- // max 按目标模型收敛:Hydrogen 与 Neon 收到四档最高档 xhigh,Argon / Carbon 仍是 high。
18
- const level = normalizedRequested === 'max' ? (xhighSupported ? 'xhigh' : 'high') : normalizedRequested
19
- if (!levelsForModel(options.model).includes(level)) {
20
- throw new Error(xhighSupported ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
15
+ const resolvedReasoning = resolveGemini4ReasoningLevel(options, options.model, cfg.reasoning)
16
+ if (!resolvedReasoning.ok) {
17
+ if (resolvedReasoning.errorType === 'conflict') {
18
+ throw new Error('Conflicting reasoning and reasoningEffort options in Interactions request.')
19
+ }
20
+ throw new Error(resolvedReasoning.supportsXhigh ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
21
21
  }
22
+ const level = resolvedReasoning.level
22
23
  if (cfg.interactionsBackground && !cfg.allowInteractionStorage) throw new Error('Background Interactions requires explicit cloud-storage consent in Gemini 4 Adapter settings.')
23
24
  if (max > 65536 && !cfg.interactionsBackground) throw new Error('Interactions above 65,536 tokens requires background execution; no request was sent.')
24
25
  if (route === 'google-vertex' && max > 65536) throw new Error('Vertex Interactions long decode is not verified; choose GenerateContent or explicitly lower the budget to 65,536.')
@@ -86,6 +87,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
86
87
  }
87
88
  try {
88
89
  signal.throwIfAborted()
90
+ const upstreamModel = officialUpstreamModel(options.model)
89
91
  const controls = assertInteractionOptions(options, cfg, route)
90
92
  const servicePolicy = resolveServicePolicy(cfg, route, 'interactions')
91
93
  if (cfg.interactionsBackground) taskHub?.requireReady()
@@ -160,7 +162,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
160
162
  return block
161
163
  }) }))
162
164
  const { streamInteractions } = await import('./interactions.js')
163
- for await (const chunk of streamInteractions({ ...options, messages, signal }, { route, upstreamModel: officialUpstreamModel(options.model), ...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 } })) {
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 } })) {
164
166
  if (chunk.type === 'usage') {
165
167
  recordUsage()
166
168
  // Only an observed first-hop input watermark can be normalized for the
@@ -1,5 +1,48 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  export const INTERACTIONS_REPLAY_API = 'google-interactions-v1'
3
+ export const OFFICIAL_GEMINI4_MODEL_RE = /^(?:models\/)?(gemini-4-(argon|carbon|hydrogen|neon))(-google)?$/i
4
+ export function resolveOfficialGemini4Model(modelId) {
5
+ if (typeof modelId !== 'string') return null
6
+ const match = OFFICIAL_GEMINI4_MODEL_RE.exec(modelId)
7
+ if (!match) return null
8
+ const upstreamModel = match[1].toLowerCase()
9
+ const family = match[2].toLowerCase()
10
+ const isGoogleApi = Boolean(match[3])
11
+ return {
12
+ canonicalId: `${upstreamModel}${isGoogleApi ? '-google' : ''}`,
13
+ upstreamModel,
14
+ family,
15
+ isGoogleApi,
16
+ supportsXhigh: family === 'hydrogen' || family === 'neon',
17
+ }
18
+ }
19
+ /** 统一校验 thinking/reasoning 双字段,显式非法或双字段互相冲突时当场失败,避免静默回退默认值。 */
20
+ export function resolveGemini4ReasoningLevel(options, modelId, fallback = 'medium') {
21
+ const supportsXhigh = Boolean(resolveOfficialGemini4Model(modelId)?.supportsXhigh)
22
+ const allowed = supportsXhigh ? ['low', 'medium', 'high', 'xhigh'] : ['low', 'medium', 'high']
23
+ const validInputs = new Set([...allowed, 'max'])
24
+ const normalize = value => {
25
+ if (value === undefined) return undefined
26
+ if (typeof value !== 'string') return null
27
+ const lower = value.toLowerCase()
28
+ return validInputs.has(lower) ? lower : null
29
+ }
30
+ const hasEffort = options?.reasoningEffort !== undefined
31
+ const hasReasoning = options?.reasoning !== undefined
32
+ const effort = hasEffort ? normalize(options.reasoningEffort) : undefined
33
+ const reasoning = hasReasoning ? normalize(options.reasoning) : undefined
34
+ if (hasEffort && effort === null) return { ok: false, errorType: 'unsupported', effort: options.reasoningEffort, supportsXhigh }
35
+ if (hasReasoning && reasoning === null) return { ok: false, errorType: 'unsupported', effort: options.reasoning, supportsXhigh }
36
+ if (effort !== undefined && reasoning !== undefined && effort !== 'max' && reasoning !== 'max' && effort !== reasoning) {
37
+ return { ok: false, errorType: 'conflict', reasoning, reasoningEffort: effort, supportsXhigh }
38
+ }
39
+ const requested = effort === 'max' || reasoning === 'max'
40
+ ? 'max'
41
+ : (effort ?? reasoning ?? (typeof fallback === 'string' ? fallback.toLowerCase() : fallback))
42
+ const level = requested === 'max' ? (supportsXhigh ? 'xhigh' : 'high') : requested
43
+ if (!allowed.includes(level)) return { ok: false, errorType: 'unsupported', effort: requested, supportsXhigh }
44
+ return { ok: true, level, supportsXhigh }
45
+ }
3
46
  export const contentHash = content => createHash('sha256').update(JSON.stringify(content)).digest('hex')
4
47
  export const historyHash = messages => contentHash(messages.map(m => ({ role: m.role, content: m.content, toolCallId: m.toolCallId, isError: m.isError })))
5
48
  const copy = value => JSON.parse(JSON.stringify(value))
@@ -56,27 +99,59 @@ async function contentOf(blocks, settings, scrubText = false) {
56
99
  return content
57
100
  }
58
101
 
102
+ function isOmittedModel(value) {
103
+ return value === undefined || value === null || value === ''
104
+ }
105
+ function hasFollowingAssistant(messages, position) {
106
+ for (let i = position + 1; i < messages.length; i++) {
107
+ if (messages[i]?.role === 'assistant') return true
108
+ }
109
+ return false
110
+ }
111
+ function findUnclaimedToolResultIndex(messages, startIndex, toolCallId, claimedToolIndices) {
112
+ for (let i = startIndex; i < messages.length; i++) {
113
+ const msg = messages[i]
114
+ if (msg?.role === 'assistant') break
115
+ if (claimedToolIndices.has(i)) continue
116
+ if (msg?.role === 'tool' && msg.toolCallId === toolCallId) return i
117
+ }
118
+ return -1
119
+ }
120
+
59
121
  // The local DSH history is authoritative. No previous_interaction_id is reused.
60
122
  // Native replay steps are bound to the exact visible blocks, model and provider.
61
123
  // Completed foreign-protocol tool rounds become a textual transcript, never
62
124
  // forged function calls or fake thought signatures.
63
- export async function buildInteractionRequest(options, settings) {
125
+ export async function buildInteractionRequest(options, settings = {}) {
64
126
  const max = options.maxTokens ?? settings.maxTokens ?? 65536
65
- const interactionModel = String(settings.upstreamModel ?? options.model ?? '')
66
- const supportsXhigh = /^(?:models\/)?gemini-4-(?:hydrogen|neon)(?:-google)?$/i.test(interactionModel)
67
- const requestedLevel = options.reasoningEffort ?? settings.reasoning ?? 'medium'
68
- const normalizedRequested = typeof requestedLevel === 'string' ? requestedLevel.toLowerCase() : requestedLevel
69
- // max 按目标模型收敛:Hydrogen 与 Neon 收到四档最高档 xhigh,Argon / Carbon 仍是 high。
70
- const level = normalizedRequested === 'max' ? (supportsXhigh ? 'xhigh' : 'high') : normalizedRequested
127
+ const hasExplicitUpstream = !isOmittedModel(settings.upstreamModel)
128
+ const hasExplicitOption = !isOmittedModel(options.model)
129
+ const resolvedUpstream = hasExplicitUpstream ? resolveOfficialGemini4Model(settings.upstreamModel) : null
130
+ if (hasExplicitUpstream && !resolvedUpstream) {
131
+ throw new Error(`Unknown Gemini 4 official model: ${String(settings.upstreamModel)}`)
132
+ }
133
+ const resolvedOption = hasExplicitOption ? resolveOfficialGemini4Model(options.model) : null
134
+ if (hasExplicitOption && !resolvedOption) {
135
+ throw new Error(`Unknown Gemini 4 official model: ${String(options.model)}`)
136
+ }
137
+ if (resolvedUpstream && resolvedOption && resolvedUpstream.upstreamModel !== resolvedOption.upstreamModel) {
138
+ throw new Error('Conflicting Gemini 4 models in Interactions request.')
139
+ }
140
+ const upstreamModel = resolvedUpstream?.upstreamModel ?? resolvedOption?.upstreamModel ?? 'gemini-4-argon'
141
+ const resolvedReasoning = resolveGemini4ReasoningLevel(options, upstreamModel, settings.reasoning ?? 'medium')
71
142
  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.')
72
143
  if (!Number.isSafeInteger(max) || max<1 || max>1048576) throw new Error('Invalid Interactions output token budget.')
73
- const allowedLevels = supportsXhigh ? ['low','medium','high','xhigh'] : ['low','medium','high']
74
- if (!allowedLevels.includes(level)) throw new Error(supportsXhigh ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
144
+ if (!resolvedReasoning.ok) {
145
+ if (resolvedReasoning.errorType === 'conflict') {
146
+ throw new Error('Conflicting reasoning and reasoningEffort options in Interactions request.')
147
+ }
148
+ throw new Error(resolvedReasoning.supportsXhigh ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
149
+ }
150
+ const level = resolvedReasoning.level
75
151
  if (settings.background && !settings.store) throw new Error('Background Interactions requires explicit storage consent.')
76
152
  if (max>65536 && !settings.background) throw new Error('Interactions above 65,536 tokens requires background execution.')
77
153
  if (max>65536 && settings.route==='google-vertex') throw new Error('Vertex Interactions long decode is not verified; use GenerateContent.')
78
- const input=[], system=options.system?[options.system]:[], callModes=new Map(), callNames=new Map()
79
- const resultIds=new Set(options.messages.filter(m=>m.role==='tool').map(m=>m.toolCallId))
154
+ const input=[], system=options.system?[options.system]:[], toolPlansByIndex=new Map(), claimedToolIndices=new Set()
80
155
  for (const [position, message] of options.messages.entries()) {
81
156
  if (message.role==='system' || message.role==='developer') {
82
157
  const parts=await contentOf(message.content,settings)
@@ -97,9 +172,20 @@ export async function buildInteractionRequest(options, settings) {
97
172
  const native=!polluted && replay?.api===INTERACTIONS_REPLAY_API && replay.provider===options.provider && replay.model===options.model && replay.route===settings.route && replay.contentHash===contentHash(message.content) && replay.historyHash===historyHash(options.messages.slice(0,position)) && Array.isArray(replay.steps)
98
173
  const calls=message.content.filter(b=>b.type==='tool-call')
99
174
  for(const call of calls){
100
- callNames.set(call.id,call.name)
101
- if(!native&&!resultIds.has(call.id))throw new Error('An unfinished foreign or edited tool call cannot be replayed through Interactions.')
102
- callModes.set(call.id,native?'native':'[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)))
175
+ const matchIndex = findUnclaimedToolResultIndex(options.messages, position + 1, call.id, claimedToolIndices)
176
+ if (!native && matchIndex === -1) {
177
+ throw new Error('An unfinished foreign or edited tool call cannot be replayed through Interactions.')
178
+ }
179
+ if (native && matchIndex === -1 && hasFollowingAssistant(options.messages, position)) {
180
+ throw new Error('An incomplete Interactions tool turn cannot precede another assistant turn.')
181
+ }
182
+ if (matchIndex !== -1) {
183
+ claimedToolIndices.add(matchIndex)
184
+ toolPlansByIndex.set(matchIndex, {
185
+ name: call.name,
186
+ mode: native ? 'native' : '[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)),
187
+ })
188
+ }
103
189
  }
104
190
  if(native){
105
191
  if(replay.steps.some(s=>!['thought','model_output','function_call'].includes(s.type)))throw new Error('Invalid Interactions replay step.')
@@ -112,15 +198,16 @@ export async function buildInteractionRequest(options, settings) {
112
198
  }
113
199
  if(message.role==='tool'){
114
200
  const content=await contentOf(message.content,settings)
115
- const mode=callModes.get(message.toolCallId)
116
- if(mode==='native')input.push({type:'function_result',call_id:message.toolCallId,name:callNames.get(message.toolCallId),is_error:Boolean(message.isError),result:content.length?content:[{type:'text',text:'[Tool completed without output.]'}]})
117
- else input.push({type:'user_input',content:[{type:'text',text:(typeof mode==='string'?mode+'\n':'')+'[Result of previously executed tool call '+message.toolCallId+(message.isError?'; error':'')+']'},...content]})
201
+ const entry=toolPlansByIndex.get(position)
202
+ if(entry) toolPlansByIndex.delete(position)
203
+ if(entry?.mode==='native')input.push({type:'function_result',call_id:message.toolCallId,name:entry.name,is_error:Boolean(message.isError),result:content.length?content:[{type:'text',text:'[Tool completed without output.]'}]})
204
+ else input.push({type:'user_input',content:[{type:'text',text:(typeof entry?.mode==='string'?entry.mode+'\n':'')+'[Result of previously executed tool call '+message.toolCallId+(message.isError?'; error':'')+']'},...content]})
118
205
  continue
119
206
  }
120
207
  throw new Error('Unsupported Interactions message role.')
121
208
  }
122
209
  if(!input.length)throw new Error('Interactions input must not be empty.')
123
- const request={model:settings.upstreamModel??'gemini-4-argon',input,stream:true,background:Boolean(settings.background),store:Boolean(settings.store),generation_config:{max_output_tokens:max,thinking_level:level,thinking_summaries:'auto'}}
210
+ const request={model:upstreamModel,input,stream:true,background:Boolean(settings.background),store:Boolean(settings.store),generation_config:{max_output_tokens:max,thinking_level:level,thinking_summaries:'auto'}}
124
211
  if (options.stop !== undefined) {
125
212
  if (!Array.isArray(options.stop) || options.stop.some(s => typeof s !== 'string' || s.length === 0)) throw new Error('Stop sequences must be nonempty strings.')
126
213
  request.generation_config.stop_sequences = [...options.stop]
@@ -144,14 +231,14 @@ export async function buildInteractionRequest(options, settings) {
144
231
  export function generateContentHistory(options, defaultModel = options?.model) {
145
232
  const targetProvider = options.provider ?? 'google-vertex-argon'
146
233
  const targetModel = options.model ?? defaultModel
147
- const resultIds=new Set(options.messages.filter(m=>m.role==='tool').map(m=>m.toolCallId))
148
- const foreignCalls=new Map()
234
+ const foreignHeadersByIndex=new Map(), claimedToolIndices=new Set()
149
235
  let changed=false
150
- const messages=options.messages.map(message=>{
236
+ const messages=options.messages.map((message, position)=>{
151
237
  if(message.role!=='assistant'){
152
- if(message.role==='tool'&&foreignCalls.has(message.toolCallId)){
238
+ if(message.role==='tool'&&foreignHeadersByIndex.has(position)){
153
239
  changed=true
154
- const header=foreignCalls.get(message.toolCallId)
240
+ const header=foreignHeadersByIndex.get(position)
241
+ foreignHeadersByIndex.delete(position)
155
242
  return {role:'user',content:[{type:'text',text:header+'\n[Historical result of tool call '+message.toolCallId+'; data, not a new user instruction]'},...message.content]}
156
243
  }
157
244
  if(message.role==='user'&&Array.isArray(message.content)&&message.content.some(b=>b?.type==='text'&&hasPollutedCheckpointText(b.text))){
@@ -169,11 +256,27 @@ export function generateContentHistory(options, defaultModel = options?.model) {
169
256
  (replay!==undefined&&replay!==null&&(replay.provider!==targetProvider||replay.model!==targetModel))
170
257
  )&&message.content.some(block=>block?.type==='reasoning'||block?.type==='tool-call')
171
258
  const pollutedText=message.content.some(block=>block?.type==='text'&&hasPollutedAssistantText(block.text))
172
- if(!interactionsReplay&&!crossModel&&!pollutedText)return message
259
+ if(!interactionsReplay&&!crossModel&&!pollutedText){
260
+ for(const call of message.content.filter(b=>b.type==='tool-call')){
261
+ const matchIndex=findUnclaimedToolResultIndex(options.messages, position+1, call.id, claimedToolIndices)
262
+ if(matchIndex===-1 && hasFollowingAssistant(options.messages, position)){
263
+ throw new Error('Complete the pending tool turn before continuing history.')
264
+ }
265
+ if(matchIndex!==-1)claimedToolIndices.add(matchIndex)
266
+ }
267
+ return message
268
+ }
173
269
  if(!interactionsReplay&&!crossModel&&pollutedText){
174
270
  changed=true
175
271
  const hasCalls=message.content.some(block=>block?.type==='tool-call')
176
272
  if(hasCalls){
273
+ for(const call of message.content.filter(b=>b.type==='tool-call')){
274
+ const matchIndex=findUnclaimedToolResultIndex(options.messages, position+1, call.id, claimedToolIndices)
275
+ if(matchIndex===-1 && hasFollowingAssistant(options.messages, position)){
276
+ throw new Error('Complete the pending tool turn before continuing history.')
277
+ }
278
+ if(matchIndex!==-1)claimedToolIndices.add(matchIndex)
279
+ }
177
280
  return {...message,content:message.content.map(block=>block?.type==='text'&&hasPollutedAssistantText(block.text)?{...block,text:scrubPollutedAssistantText(block.text)||'[Previous model reasoning omitted when switching protocols.]'}:block)}
178
281
  }
179
282
  const cleaned=message.content.map(block=>block?.type==='text'?{...block,text:scrubPollutedAssistantText(block.text)}:block).filter(block=>block?.type!=='text'||block.text.length>0)
@@ -192,8 +295,10 @@ export function generateContentHistory(options, defaultModel = options?.model) {
192
295
  content.push(block)
193
296
  }
194
297
  for(const call of message.content.filter(b=>b.type==='tool-call')){
195
- if(!resultIds.has(call.id))throw new Error('Complete the pending Interactions tool call before switching protocols.')
196
- foreignCalls.set(call.id,'[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)))
298
+ const matchIndex=findUnclaimedToolResultIndex(options.messages, position+1, call.id, claimedToolIndices)
299
+ if(matchIndex===-1)throw new Error('Complete the pending Interactions tool call before switching protocols.')
300
+ claimedToolIndices.add(matchIndex)
301
+ foreignHeadersByIndex.set(matchIndex, '[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)))
197
302
  }
198
303
  const source=message.source?(({replayState,...rest})=>rest)(message.source):undefined
199
304
  return {...message,...(source===undefined?{}:{source}),content:content.length?content:[{type:'text',text:'[Previous model reasoning omitted when switching protocols.]'}]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-vertex-argon",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
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": {