dsh-vertex-argon 2.1.0 → 2.2.1

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,35 @@
2
2
 
3
3
  All notable changes to **Gemini 4 Adapter** (`dsh-vertex-argon`) are documented in this file.
4
4
 
5
+ ## [2.2.1] - 2026-11-19
6
+
7
+ ### Fixed
8
+ - **Strict 8-Model Parsing & Prepared Target Pinning (`interactions-input.js`, `adapter.js`, `interaction-adapter.js`)**:
9
+ - 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).
10
+ - Tightened `detectPiAiArgonRoutes` regex tails from `\b` to `$` so `-preview` / experimental suffixes are not treated as official routes.
11
+ - 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.
12
+ - **Dual-Field Reasoning Guards (`interactions-input.js`, `interaction-adapter.js`, `adapter.js`)**:
13
+ - 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.
14
+ - **Complete Native Patch & Explicit Cache Cleanup (`adapter.js`)**:
15
+ - 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.
16
+ - **Cross-Turn Reused `toolCallId` History Isolation (`interactions-input.js`, `google-signatures.js`)**:
17
+ - 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.
18
+
19
+ ## [2.2.0] - 2026-11-19
20
+
21
+ ### Added
22
+ - **Gemini 4 Neon Support Across Both Official Channels (`adapter.js`, `index.js`, `package.json`)**:
23
+ - Added `NEON_MODEL = 'gemini-4-neon'` (Vertex AI) and `GOOGLE_API_NEON_MODEL = 'gemini-4-neon-google'` (Gemini API), `isNeonModel()`, and `supportsXhighReasoning()` (`isHydrogenModel(modelId) || isNeonModel(modelId)`).
24
+ - Updated `isGoogleApiModel`, `officialUpstreamModel`, `detectPiAiArgonRoutes` (`hasVertexNeon` / `hasGoogleNeon` explicit, auto-detection, and empty Argon fallback), and `createArgonAdapter().getProfiles()` (`vn` / `gn` cache keys, `HYDROGEN_THINKING_MAP`), expanding the official matrix to 8 models with 1M context window (`1,048,576`), `65,536` single-hop / `1,048,576` long decode, four reasoning levels (`low` / `medium` / `high` / `xhigh`, `max` → `xhigh`, rejecting `minimal` / `off`), and outbound `cachedContent` / `cached_content` stripping.
25
+
26
+ ### Fixed
27
+ - **Interactions `xhigh` & `max` → `xhigh` Convergence Parity (`interaction-adapter.js`, `interactions-input.js`, `adapter.js`, `index.js`)**:
28
+ - Updated `assertInteractionOptions` and `buildInteractionRequest` to share model-scoped validation (`supportsXhighReasoning`), allowing `['low', 'medium', 'high', 'xhigh']` and narrowing `max` → `xhigh` for both `gemini-4-hydrogen*` and `gemini-4-neon*` across `adapter.stream`, `prepareCall().stream`, and `agent/request` hooks, while keeping Argon and Carbon strictly 3-level (`max` → `high`) and rejecting unsupported efforts before dispatch.
29
+
30
+ ### Changed
31
+ - **Settings UI, Locale & Documentation (`client.js`, `locale/zh.json`, `locale/en.json`, `README.md`, `AGENTS.md`, `docs/implementation/`)**:
32
+ - Bumped version to `2.2.0`, added `gemini-4-neon` keyword, and updated Chinese and English descriptions and setup instructions for the 8-model matrix and Hydrogen/Neon `XHigh` support.
33
+
5
34
  ## [2.1.0] - 2026-11-15
6
35
 
7
36
  ### Added
package/README.md CHANGED
@@ -2,22 +2,22 @@
2
2
 
3
3
  ![Gemini 4 Adapter](<icon.svg>)
4
4
 
5
- **面向 [DeepSeek Harness](<https://github.com/deepseek-ai/deepseek-harness>) 的 Google 官方双通道(Vertex AI + Gemini Developer API)Gemini 4 适配器,原生支持 Argon、Carbon 与 Hydrogen 六模型路由、GenerateContent / Interactions 双协议、65K+ 多跳长解码与请求级诊断。**
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.1.0`([CHANGELOG.md](<CHANGELOG.md>))
7
+ - **当前版本**:`2.2.1`([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
 
11
- [快速开始](<#快速开始>) · [双官方通道与六模型](<#双官方通道与六模型>) · [长解码与流式恢复](<#generatecontent长解码与四项韧性机制>) · [配置速查](<#完整配置13-项>) · [诊断与工具](<#gemini-4-诊断与-argon_inspect-工具>) · [长解码实测参考](<#历史实测参考奥德赛七号全年舰长日志>)
11
+ [快速开始](<#快速开始>) · [双官方通道与八模型](<#双官方通道与八模型>) · [长解码与流式恢复](<#generatecontent长解码与四项韧性机制>) · [配置速查](<#完整配置13-项>) · [诊断与工具](<#gemini-4-诊断与-argon_inspect-工具>) · [长解码实测参考](<#历史实测参考奥德赛七号全年舰长日志>)
12
12
 
13
13
  ---
14
14
 
15
15
  ## 核心特性
16
16
 
17
- - **双官方通道 × 六模型路由**:同时接入 Google Cloud **Vertex AI**(`gemini-4-argon` / `gemini-4-carbon` / `gemini-4-hydrogen`)与 **Gemini Developer API**(`gemini-4-argon-google` / `gemini-4-carbon-google` / `gemini-4-hydrogen-google`),两通道凭据与网关严格隔离,绝不暗中互借或静默回退。
17
+ - **双官方通道 × 八模型路由**:同时接入 Google Cloud **Vertex AI**(`gemini-4-argon` / `gemini-4-carbon` / `gemini-4-hydrogen` / `gemini-4-neon`)与 **Gemini Developer API**(`gemini-4-argon-google` / `gemini-4-carbon-google` / `gemini-4-hydrogen-google` / `gemini-4-neon-google`),两通道凭据与网关严格隔离,绝不暗中互借或静默回退。
18
18
  - **65K+ 多跳长解码与流自愈**:单跳上限 `65,536` tokens,最大输出预算可达 `1,048,576`(最多 32 跳);首个检查点前实时流式输出,支持检查点尾段回滚续传、逐跳四阶段超时看门狗、零交付首包重试、仅思考结束单次续答自愈,以及 `MALFORMED_FUNCTION_CALL` 后 `VALIDATED` → `AUTO` 工具模式自动退避。
19
19
  - **Interactions 协议与后台任务恢复**:支持前台流式及显式授权后的云端后台执行;内置 `creating` 预写防重计费锁、`last_event_id` 断点续读、`2026-05-20` 独立生命周期事件兼容,以及同会话新提示词触发的历史死锁非流式探针对账。
20
- - **签名保真与跨模型安全降级**:完整保留并回放 `thoughtSignature` / `thought_signature`(含无文本独立签名块);原生映射 `low` / `medium` / `high` 三档思考级别(宿主或子代理传入 `max` 时自动收敛为 `high`,永不下发 `thinkingBudget`);在 Argon ↔ Carbon ↔ Hydrogen 或跨通道切换时自动将旧工具历史安全降级为文本记录并清洗污染块。
20
+ - **签名保真与跨模型安全降级**:完整保留并回放 `thoughtSignature` / `thought_signature`(含无文本独立签名块);Argon / Carbon 原生映射 `low` / `medium` / `high` 三档(`max` 收敛为 `high`),Hydrogen / Neon 额外放行 `xhigh` 第四档(`max` 收敛为 `xhigh` 并剥离显式 `cachedContent` / `cached_content`,永不下发 `thinkingBudget`);在 Argon ↔ Carbon ↔ Hydrogen ↔ Neon 或跨通道切换时自动将旧工具历史安全降级为文本记录并清洗污染块。
21
21
  - **Gemini 4 诊断面板与只读工具**:在右侧栏、会话详情页与单条回复底部提供请求摘要、基础 Token 水位(严格区分首跳上下文水位与跨跳累计用量)、11 列逐跳轨迹、分页原始响应证据、云端 Interaction ID 只读查询与全局恢复锁管理,并向智能体提供延迟加载的只读工具 `argon_inspect`。
22
22
 
23
23
  ---
@@ -40,7 +40,7 @@ dsh plugin --profile desktop add dsh-vertex-argon
40
40
 
41
41
  ### 2. 声明模型入口
42
42
 
43
- 在 DSH「**设置 → 模型**」的原生 `Google` 或 `Google Vertex AI` 供应商下添加 `gemini-4-argon`、`gemini-4-carbon` 和/或 `gemini-4-hydrogen`,插件会自动识别并在模型选择器中暴露 **Gemini 4 Adapter** 分组下的对应模型。
43
+ 在 DSH「**设置 → 模型**」的原生 `Google` 或 `Google Vertex AI` 供应商下添加 `gemini-4-argon`、`gemini-4-carbon`、`gemini-4-hydrogen` 和/或 `gemini-4-neon`,插件会自动识别并在模型选择器中暴露 **Gemini 4 Adapter** 分组下的对应模型。
44
44
 
45
45
  ### 3. 配置官方凭据
46
46
 
@@ -52,7 +52,7 @@ dsh plugin --profile desktop add dsh-vertex-argon
52
52
 
53
53
  ---
54
54
 
55
- ## 双官方通道与六模型
55
+ ## 双官方通道与八模型
56
56
 
57
57
  底层 Provider ID 为 `google-vertex-argon`,模型选择器分组显示为 **Gemini 4 Adapter**(实现见 [adapter.js](<adapter.js>) 与 [google-connection.js](<google-connection.js>))。
58
58
 
@@ -61,14 +61,16 @@ dsh plugin --profile desktop add dsh-vertex-argon
61
61
  | **Vertex AI** | `gemini-4-argon` | `gemini-4-argon` | `google-vertex` | `vertexProtocol` / `vertexServiceTier` |
62
62
  | **Vertex AI** | `gemini-4-carbon` | `gemini-4-carbon` | `google-vertex` | `vertexProtocol` / `vertexServiceTier` |
63
63
  | **Vertex AI** | `gemini-4-hydrogen` | `gemini-4-hydrogen` | `google-vertex` | `vertexProtocol` / `vertexServiceTier` |
64
+ | **Vertex AI** | `gemini-4-neon` | `gemini-4-neon` | `google-vertex` | `vertexProtocol` / `vertexServiceTier` |
64
65
  | **Gemini API** | `gemini-4-argon-google` | `gemini-4-argon` | `google-generative-ai` | `googleProtocol` / `googleServiceTier` |
65
66
  | **Gemini API** | `gemini-4-carbon-google` | `gemini-4-carbon` | `google-generative-ai` | `googleProtocol` / `googleServiceTier` |
66
67
  | **Gemini API** | `gemini-4-hydrogen-google` | `gemini-4-hydrogen` | `google-generative-ai` | `googleProtocol` / `googleServiceTier` |
68
+ | **Gemini API** | `gemini-4-neon-google` | `gemini-4-neon` | `google-generative-ai` | `googleProtocol` / `googleServiceTier` |
67
69
 
68
70
  ### 跨模型切换与历史清洗规则
69
71
 
70
72
  - **同模型连续对话**:完整保留原生 `thoughtSignature` / `thought_signature` 与 `functionCall` / `functionResponse` 签名回放。
71
- - **跨模型或跨通道切换(如 Argon ↔ Carbon ↔ Hydrogen、Vertex ↔ Gemini API)**:出站前自动将含推理或工具调用的旧回合降级为纯文本记录(剔除旧思考块,将已完成工具调用转为角色安全的文本摘要,未完成调用直接拦截),避免因底层摘除跨模型签名而发出裸 `functionCall` 或孤立 `functionResponse`。
73
+ - **跨模型或跨通道切换(如 Argon ↔ Carbon ↔ Hydrogen ↔ Neon、Vertex ↔ Gemini API)**:出站前自动将含推理或工具调用的旧回合降级为纯文本记录(剔除旧思考块,将已完成工具调用转为角色安全的文本摘要,未完成调用直接拦截),避免因底层摘除跨模型签名而发出裸 `functionCall` 或孤立 `functionResponse`。
72
74
  - **原生入口兼容保护**:插件同时为宿主原生 `google` 与 `google-vertex` 适配器中的 Gemini 4 模型注入 GenerateContent 思考档位映射、采样参数剥离与签名回放保护。
73
75
 
74
76
  ---
@@ -91,7 +93,7 @@ dsh plugin --profile desktop add dsh-vertex-argon
91
93
  | 分组 | 配置项 | 默认值 | 取值范围与说明 |
92
94
  |---|---|---|---|
93
95
  | 基础与生成 | `showInModelPicker` | `true` | 是否在会话模型选择器中显示 **Gemini 4 Adapter** 分组 |
94
- | 基础与生成 | `reasoning` | `medium` | 默认思考档位:`low` / `medium` / `high` |
96
+ | 基础与生成 | `reasoning` | `medium` | 默认思考档位:`low` / `medium` / `high`(Hydrogen 与 Neon 会话内额外支持 `xhigh`) |
95
97
  | 基础与生成 | `maxTokens` | `65536` | `1`–`1048576`;超过 `65,536` 需启用长解码(窗口 > 131K 时自动预留 131,072 历史空间) |
96
98
  | 基础与生成 | `contextWindow` | `1048576` | `1`–`1048576`;供 DSH 本地预算与上下文压缩计算使用 |
97
99
  | 基础与生成 | `longDecode` | `true` | 控制 > 65,536 输出上限、GenerateContent 检查点续传与仅思考自愈 |
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'
@@ -27,18 +27,22 @@ export const CARBON_MODEL = 'gemini-4-carbon'
27
27
  export const GOOGLE_API_CARBON_MODEL = 'gemini-4-carbon-google'
28
28
  export const HYDROGEN_MODEL = 'gemini-4-hydrogen'
29
29
  export const GOOGLE_API_HYDROGEN_MODEL = 'gemini-4-hydrogen-google'
30
- /** Gemini API 官方直连模型判定(Argon、Carbon 与 Hydrogen)。 */
30
+ export const NEON_MODEL = 'gemini-4-neon'
31
+ export const GOOGLE_API_NEON_MODEL = 'gemini-4-neon-google'
32
+ /** Gemini API 官方直连模型判定(Argon、Carbon、Hydrogen 与 Neon,支持可选 models/ 前缀)。 */
31
33
  export function isGoogleApiModel(modelId) {
32
- return modelId === GOOGLE_API_MODEL || modelId === GOOGLE_API_CARBON_MODEL || modelId === GOOGLE_API_HYDROGEN_MODEL
34
+ return resolveOfficialGemini4Model(modelId)?.isGoogleApi ?? false
33
35
  }
34
- /** 官方直连(Vertex AI / Gemini API)对应的上游模型 ID。 */
36
+ /** 官方直连(Vertex AI / Gemini API)对应的上游模型 ID;空值回落默认 Argon,未知非空模型报错。 */
35
37
  export function officialUpstreamModel(modelId) {
36
- if (modelId === HYDROGEN_MODEL || modelId === GOOGLE_API_HYDROGEN_MODEL) return HYDROGEN_MODEL
37
- 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
38
42
  }
39
43
  export const LEVELS = ['low', 'medium', 'high']
40
44
  /**
41
- * Gemini 4 Hydrogen 独有的第四档 xhigh(官方默认 high)。
45
+ * Gemini 4 Hydrogen 与 Neon 支持的第四档 xhigh(官方默认 high)。
42
46
  * Argon / Carbon 的允许集合必须严格维持三档,绝不泄漏 xhigh。
43
47
  */
44
48
  export const HYDROGEN_LEVELS = ['low', 'medium', 'high', 'xhigh']
@@ -47,22 +51,56 @@ export const MAX_LONG_DECODE_TOKENS = 1048576
47
51
  const COMPACTION_HEADROOM_FLOOR = 131072
48
52
  const ENV_KEYS = ['GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_CLOUD_PROJECT', 'GCLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION', 'GOOGLE_CLOUD_API_KEY']
49
53
  const DEFAULT_THINKING_MAP = { off: null, minimal: null, low: 'low', medium: 'medium', high: 'high', xhigh: null, max: null }
50
- /** Hydrogen 的档位映射:唯一一处把 xhigh 放行到 thinkingConfig 的地方。 */
54
+ /** Hydrogen 与 Neon 的档位映射:把 xhigh 放行到 thinkingConfig。 */
51
55
  const HYDROGEN_THINKING_MAP = { off: null, minimal: null, low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: null }
52
56
 
53
57
  /** Hydrogen 模型 ID 判定:同时识别 `gemini-4-hydrogen` 与 `gemini-4-hydrogen-google`(可带 models/ 前缀)。 */
54
58
  export function isHydrogenModel(modelId) {
55
- return typeof modelId === 'string' && /^(?:models\/)?gemini-4-hydrogen(?:-google)?$/i.test(modelId)
59
+ return resolveOfficialGemini4Model(modelId)?.family === 'hydrogen'
56
60
  }
57
61
 
58
- /** 模型对应的合法思考档位集合:只有 Hydrogen 拿到 xhigh。 */
62
+ /** Neon 模型 ID 判定:同时识别 `gemini-4-neon` 与 `gemini-4-neon-google`(可带 models/ 前缀)。 */
63
+ export function isNeonModel(modelId) {
64
+ return resolveOfficialGemini4Model(modelId)?.family === 'neon'
65
+ }
66
+
67
+ /** 判断模型是否支持 xhigh 第四档思考及对应无显式缓存限制(Hydrogen 与 Neon)。 */
68
+ export function supportsXhighReasoning(modelId) {
69
+ return resolveOfficialGemini4Model(modelId)?.supportsXhigh ?? false
70
+ }
71
+
72
+ /** 模型对应的合法思考档位集合:Hydrogen 与 Neon 放行 xhigh。 */
59
73
  export function levelsForModel(modelId) {
60
- return isHydrogenModel(modelId) ? HYDROGEN_LEVELS : LEVELS
74
+ return supportsXhighReasoning(modelId) ? HYDROGEN_LEVELS : LEVELS
61
75
  }
62
76
 
63
- /** 模型对应的档位映射表:Hydrogen 放行 xhigh,其余模型仍为 null。 */
77
+ /** 模型对应的档位映射表:Hydrogen 与 Neon 放行 xhigh,其余模型仍为 null。 */
64
78
  export function thinkingLevelMapFor(modelId) {
65
- return isHydrogenModel(modelId) ? HYDROGEN_THINKING_MAP : DEFAULT_THINKING_MAP
79
+ return supportsXhighReasoning(modelId) ? HYDROGEN_THINKING_MAP : DEFAULT_THINKING_MAP
80
+ }
81
+
82
+ function assertPlainRequestOptions(options) {
83
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
84
+ throw new LlmError('Request options must be a plain object.', 'INVALID_REQUEST')
85
+ }
86
+ return options
87
+ }
88
+
89
+ function validateExplicitReasoningFields(options, modelId, fallback = 'medium') {
90
+ const result = resolveGemini4ReasoningLevel(options, modelId, fallback)
91
+ if (!result.ok) {
92
+ if (result.errorType === 'conflict') {
93
+ throw new LlmError(
94
+ `Model ${modelId ?? MODEL} received conflicting reasoning (${result.reasoning}) and reasoningEffort (${result.reasoningEffort}).`,
95
+ 'INVALID_REQUEST',
96
+ )
97
+ }
98
+ throw new LlmError(
99
+ `Model ${modelId ?? MODEL} does not support reasoning effort "${String(result.effort)}".`,
100
+ 'UNSUPPORTED_REASONING_EFFORT',
101
+ )
102
+ }
103
+ return result
66
104
  }
67
105
 
68
106
  // The host's agent/request hook already narrows 'max' to 'high'. Direct adapter
@@ -70,13 +108,36 @@ export function thinkingLevelMapFor(modelId) {
70
108
  // that hook, so the same narrowing has to happen at this boundary too.
71
109
  export function narrowMaxReasoning(options, modelId = options?.model) {
72
110
  if (!options || typeof options !== 'object') return options
73
- const requested = [options.reasoning, options.reasoningEffort]
74
- if (!requested.some(value => typeof value === 'string' && value.toLowerCase() === 'max')) return options
75
- // Hydrogen 的最高档是 xhigh;其余模型仍是 high。
76
- const ceiling = isHydrogenModel(modelId) ? 'xhigh' : 'high'
111
+ const validInputs = new Set([...levelsForModel(modelId), 'max'])
112
+ const normalize = value => (value === undefined ? undefined : typeof value === 'string' && validInputs.has(value.toLowerCase()) ? value.toLowerCase() : null)
113
+ const reasoning = normalize(options.reasoning)
114
+ const effort = normalize(options.reasoningEffort)
115
+ if (reasoning === null || effort === null) return options
116
+ if (reasoning !== 'max' && effort !== 'max') return options
117
+ // Hydrogen 与 Neon 的最高档是 xhigh;其余模型仍是 high。
118
+ const ceiling = supportsXhighReasoning(modelId) ? 'xhigh' : 'high'
77
119
  return { ...options, reasoning: ceiling, reasoningEffort: ceiling }
78
120
  }
79
121
 
122
+ function pinPreparedOptions(options, expectedProvider, expectedModel) {
123
+ assertPlainRequestOptions(options)
124
+ if (expectedProvider !== undefined && options.provider !== undefined && options.provider !== expectedProvider) {
125
+ throw new LlmError('Prepared stream provider mismatch.', 'INVALID_REQUEST')
126
+ }
127
+ if (expectedModel !== undefined && options.model !== undefined && options.model !== expectedModel) {
128
+ throw new LlmError('Prepared stream model mismatch.', 'INVALID_REQUEST')
129
+ }
130
+ return expectedProvider !== undefined && expectedModel !== undefined
131
+ ? { ...options, provider: expectedProvider, model: expectedModel }
132
+ : options
133
+ }
134
+ function preparePinnedStreamOptions(options, expectedProvider, expectedModel) {
135
+ const pinned = pinPreparedOptions(options, expectedProvider, expectedModel)
136
+ const targetModel = pinned.model ?? expectedModel
137
+ validateExplicitReasoningFields(pinned, targetModel)
138
+ return narrowMaxReasoning(pinned, targetModel)
139
+ }
140
+
80
141
  const readVal = v => (v && typeof v === 'object' && typeof v.get === 'function') ? v.get() : v
81
142
 
82
143
  export function isGemini4Model(model) {
@@ -99,6 +160,8 @@ export function detectPiAiArgonRoutes(ctx, explicitRoutes) {
99
160
  const hasGoogleCarbon = Boolean(explicitRoutes.hasGoogleCarbon)
100
161
  const hasVertexHydrogen = Boolean(explicitRoutes.hasVertexHydrogen)
101
162
  const hasGoogleHydrogen = Boolean(explicitRoutes.hasGoogleHydrogen)
163
+ const hasVertexNeon = Boolean(explicitRoutes.hasVertexNeon)
164
+ const hasGoogleNeon = Boolean(explicitRoutes.hasGoogleNeon)
102
165
  const hasVertexArgon = explicitRoutes.hasVertexArgon !== undefined
103
166
  ? Boolean(explicitRoutes.hasVertexArgon)
104
167
  : explicitRoutes.hasVertex !== false
@@ -106,14 +169,16 @@ export function detectPiAiArgonRoutes(ctx, explicitRoutes) {
106
169
  ? Boolean(explicitRoutes.hasGoogleArgon)
107
170
  : Boolean(explicitRoutes.hasGoogle)
108
171
  return {
109
- hasVertex: hasVertexArgon || hasVertexCarbon || hasVertexHydrogen,
110
- hasGoogle: hasGoogleArgon || hasGoogleCarbon || hasGoogleHydrogen,
172
+ hasVertex: hasVertexArgon || hasVertexCarbon || hasVertexHydrogen || hasVertexNeon,
173
+ hasGoogle: hasGoogleArgon || hasGoogleCarbon || hasGoogleHydrogen || hasGoogleNeon,
111
174
  hasVertexArgon,
112
175
  hasGoogleArgon,
113
176
  hasVertexCarbon,
114
177
  hasGoogleCarbon,
115
178
  hasVertexHydrogen,
116
179
  hasGoogleHydrogen,
180
+ hasVertexNeon,
181
+ hasGoogleNeon,
117
182
  googleApiKeyEnv: googleKeyEnvironment(explicitRoutes.googleApiKeyEnv),
118
183
  googleBaseUrl: explicitRoutes.googleBaseUrl,
119
184
  vertexBaseUrl: explicitRoutes.vertexBaseUrl,
@@ -129,23 +194,27 @@ export function detectPiAiArgonRoutes(ctx, explicitRoutes) {
129
194
  const hasModel = (list, re) => Array.isArray(list) && list.some(m => re.test(String(readVal(m?.id) ?? '')))
130
195
  const googleModels = readVal(googleCfg?.models)
131
196
  const vertexModels = readVal(vertexCfg?.models)
132
- const hasGoogleArgon = hasModel(googleModels, /^(?:models\/)?gemini-4-argon\b/i)
133
- const hasVertexArgon = hasModel(vertexModels, /^(?:models\/)?gemini-4-argon\b/i)
134
- const hasGoogleCarbon = hasModel(googleModels, /^(?:models\/)?gemini-4-carbon\b/i)
135
- const hasVertexCarbon = hasModel(vertexModels, /^(?:models\/)?gemini-4-carbon\b/i)
136
- const hasGoogleHydrogen = hasModel(googleModels, /^(?:models\/)?gemini-4-hydrogen\b/i)
137
- const hasVertexHydrogen = hasModel(vertexModels, /^(?:models\/)?gemini-4-hydrogen\b/i)
138
- const hasGoogle = hasGoogleArgon || hasGoogleCarbon || hasGoogleHydrogen
139
- const hasVertex = hasVertexArgon || hasVertexCarbon || hasVertexHydrogen || !hasGoogle
197
+ const hasGoogleArgon = hasModel(googleModels, /^(?:models\/)?gemini-4-argon$/i)
198
+ const hasVertexArgon = hasModel(vertexModels, /^(?:models\/)?gemini-4-argon$/i)
199
+ const hasGoogleCarbon = hasModel(googleModels, /^(?:models\/)?gemini-4-carbon$/i)
200
+ const hasVertexCarbon = hasModel(vertexModels, /^(?:models\/)?gemini-4-carbon$/i)
201
+ const hasGoogleHydrogen = hasModel(googleModels, /^(?:models\/)?gemini-4-hydrogen$/i)
202
+ const hasVertexHydrogen = hasModel(vertexModels, /^(?:models\/)?gemini-4-hydrogen$/i)
203
+ const hasGoogleNeon = hasModel(googleModels, /^(?:models\/)?gemini-4-neon$/i)
204
+ const hasVertexNeon = hasModel(vertexModels, /^(?:models\/)?gemini-4-neon$/i)
205
+ const hasGoogle = hasGoogleArgon || hasGoogleCarbon || hasGoogleHydrogen || hasGoogleNeon
206
+ const hasVertex = hasVertexArgon || hasVertexCarbon || hasVertexHydrogen || hasVertexNeon || !hasGoogle
140
207
  return {
141
208
  hasVertex,
142
209
  hasGoogle,
143
- hasVertexArgon: hasVertexArgon || (!hasGoogle && !hasVertexCarbon && !hasVertexHydrogen),
210
+ hasVertexArgon: hasVertexArgon || (!hasGoogle && !hasVertexCarbon && !hasVertexHydrogen && !hasVertexNeon),
144
211
  hasGoogleArgon,
145
212
  hasVertexCarbon,
146
213
  hasGoogleCarbon,
147
214
  hasVertexHydrogen,
148
215
  hasGoogleHydrogen,
216
+ hasVertexNeon,
217
+ hasGoogleNeon,
149
218
  googleApiKeyEnv: googleKeyEnvironment(readVal(googleCfg?.apiKeyEnv)),
150
219
  googleBaseUrl: readVal(googleCfg?.baseURL),
151
220
  vertexBaseUrl: readVal(vertexCfg?.baseURL),
@@ -161,6 +230,8 @@ export function detectPiAiArgonRoutes(ctx, explicitRoutes) {
161
230
  hasGoogleCarbon: false,
162
231
  hasVertexHydrogen: false,
163
232
  hasGoogleHydrogen: false,
233
+ hasVertexNeon: false,
234
+ hasGoogleNeon: false,
164
235
  googleApiKeyEnv: 'GOOGLE_API_KEY',
165
236
  }
166
237
  }
@@ -304,23 +375,18 @@ export function gemini4StreamSimple(
304
375
  ensureGemini4ApiClientPatch()
305
376
  const fallback = defaultLevel ?? (/cyber-permissive/i.test(requestModel?.id ?? '') ? 'high' : 'medium')
306
377
  const modelId = requestModel?.id
307
- const hydrogen = isHydrogenModel(modelId)
308
- const requestedLevel = options.reasoning ?? fallback
309
- // max 按目标模型收敛:Hydrogen 收到独有最高档 xhigh,其余模型仍是 high。
310
- const rawLevel = typeof requestedLevel === 'string' && requestedLevel.toLowerCase() === 'max'
311
- ? (hydrogen ? 'xhigh' : 'high')
312
- : (typeof requestedLevel === 'string' ? requestedLevel.toLowerCase() : requestedLevel)
313
- const mapped = requestModel?.thinkingLevelMap?.[rawLevel] ?? rawLevel
314
- const level = typeof mapped === 'string' ? mapped.toLowerCase() : fallback
315
- if (!levelsForModel(modelId).includes(level)) {
378
+ const supportsXhigh = supportsXhighReasoning(modelId)
379
+ const { level: rawLevel } = validateExplicitReasoningFields(options, modelId, fallback)
380
+ const hasMapped = requestModel?.thinkingLevelMap && Object.prototype.hasOwnProperty.call(requestModel.thinkingLevelMap, rawLevel)
381
+ const mapped = hasMapped ? requestModel.thinkingLevelMap[rawLevel] : rawLevel
382
+ const level = typeof mapped === 'string' ? mapped.toLowerCase() : null
383
+ if (!level || !levelsForModel(modelId).includes(level)) {
316
384
  throw new LlmError(
317
- hydrogen
318
- ? 'Gemini 4 Hydrogen requires low, medium, high or xhigh.'
319
- : 'Gemini 4 (Argon / Carbon / Hydrogen) requires low, medium or high.',
385
+ `Model ${modelId ?? MODEL} does not support reasoning effort "${rawLevel}".`,
320
386
  'UNSUPPORTED_REASONING_EFFORT',
321
387
  )
322
388
  }
323
- const { reasoning, thinking, thinkingBudgets, temperature, onPayload: prior, onProviderStreamEvent: priorEvent, ...rest } = options
389
+ const { reasoning, reasoningEffort: _re, thinking, thinkingBudgets, temperature, onPayload: prior, onProviderStreamEvent: priorEvent, ...rest } = options
324
390
  const requestedMaxTokens = options.maxTokens ?? requestModel.maxTokens
325
391
  const effectiveMaxTokens =
326
392
  longDecode === false && typeof requestedMaxTokens === 'number' && requestedMaxTokens > MAX_SINGLE_CALL_TOKENS
@@ -358,13 +424,13 @@ export function gemini4StreamSimple(
358
424
  }
359
425
  body = signatures.restorePayload(body)
360
426
  if (structuredOutput) body = structuredOutput.generateContent(body)
361
- // Gemini 4 Hydrogen 官方不支持显式缓存(cachedContents),残留字段会被上游拒绝。
362
- if (hydrogen) {
427
+ // Gemini 4 Hydrogen / Neon 官方不支持显式缓存(cachedContents),残留字段会被上游拒绝。
428
+ if (supportsXhigh) {
363
429
  delete body.cachedContent
364
430
  delete body.cached_content
365
431
  }
366
432
  const { temperature: _t, topP: _tp, topK: _tk, candidateCount: _cc, frequencyPenalty: _fp, presencePenalty: _pp, ...cleanConfig } = body.config
367
- if (hydrogen) {
433
+ if (supportsXhigh) {
368
434
  delete cleanConfig.cachedContent
369
435
  delete cleanConfig.cached_content
370
436
  }
@@ -372,6 +438,18 @@ export function gemini4StreamSimple(
372
438
  cleanConfig.httpOptions && typeof cleanConfig.httpOptions === 'object' && !Array.isArray(cleanConfig.httpOptions)
373
439
  ? cleanConfig.httpOptions
374
440
  : {}
441
+ const sanitizedHttpOptions = { ...prevHttpOptions }
442
+ if (
443
+ supportsXhigh &&
444
+ prevHttpOptions.extraBody &&
445
+ typeof prevHttpOptions.extraBody === 'object' &&
446
+ !Array.isArray(prevHttpOptions.extraBody)
447
+ ) {
448
+ const cleanExtraBody = { ...prevHttpOptions.extraBody }
449
+ delete cleanExtraBody.cachedContent
450
+ delete cleanExtraBody.cached_content
451
+ sanitizedHttpOptions.extraBody = cleanExtraBody
452
+ }
375
453
  const toolMode = shouldFallbackToAutoToolMode(retryKey) ? 'AUTO' : 'VALIDATED'
376
454
  return {
377
455
  ...body,
@@ -387,8 +465,8 @@ export function gemini4StreamSimple(
387
465
  automaticContinuation: false,
388
466
  thinkingConfig: { thinkingLevel: level.toUpperCase(), includeThoughts: true },
389
467
  httpOptions: {
390
- ...prevHttpOptions,
391
- ...(Object.keys(servicePolicy.headers).length ? { headers: mergeServiceHeaders(prevHttpOptions.headers, servicePolicy) } : {}),
468
+ ...sanitizedHttpOptions,
469
+ ...(Object.keys(servicePolicy.headers).length ? { headers: mergeServiceHeaders(sanitizedHttpOptions.headers, servicePolicy) } : {}),
392
470
  [ARGON_LONG_DECODE_SYMBOL]: {
393
471
  enabled: longDecode !== false,
394
472
  serviceTier: requestModel.api === 'google-generative-ai' ? servicePolicy.tier : undefined,
@@ -410,39 +488,67 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
410
488
  const proto = PiAiAdapter?.prototype
411
489
  if (!proto || typeof proto.current !== 'function') return unpatchApiClient
412
490
  const origCurrent = proto.current
491
+ const origPrepareCall = typeof proto.prepareCall === 'function' ? proto.prepareCall : null
492
+ const origProtoStream = typeof proto.stream === 'function' ? proto.stream : null
413
493
  const patchedProviders = new Map()
414
494
  let active = true
415
495
  const ensureGemini4Capabilities = piProvider => {
416
496
  if (typeof piProvider?.getModels !== 'function') return
417
497
  try {
418
498
  for (const m of piProvider.getModels()) {
419
- if (isGemini4Model(m) && !m.reasoning) {
420
- m.reasoning = true
421
- m.thinkingLevelMap = { ...thinkingLevelMapFor(m.id) }
499
+ if (isGemini4Model(m)) {
500
+ try {
501
+ m.reasoning = true
502
+ m.thinkingLevelMap = { ...thinkingLevelMapFor(m.id) }
503
+ } catch {}
422
504
  }
423
505
  }
424
506
  } catch {}
425
507
  }
508
+ const mapStreamThinkingOption = options => {
509
+ if (!options || typeof options !== 'object' || Array.isArray(options)) return options
510
+ if (options.reasoning !== undefined || options.reasoningEffort !== undefined) return options
511
+ const thinking = options.thinking
512
+ if (!thinking || typeof thinking !== 'object' || Array.isArray(thinking)) return options
513
+ if (thinking.enabled === false || (typeof thinking.budgetTokens === 'number' && thinking.budgetTokens <= 0)) {
514
+ return { ...options, reasoning: 'off' }
515
+ }
516
+ if (typeof thinking.level === 'string') return { ...options, reasoning: thinking.level }
517
+ return options
518
+ }
426
519
  const wrapProvider = (piProvider, defaultReasoning) => {
427
520
  if (!piProvider || typeof piProvider.streamSimple !== 'function' || typeof piProvider.stream !== 'function') return
428
521
  ensureGemini4Capabilities(piProvider)
429
522
  if (piProvider.id === PROVIDER || patchedProviders.has(piProvider)) return
523
+ const origStream = piProvider.stream
430
524
  const origStreamSimple = piProvider.streamSimple
525
+ const dispatchGemini4 = (requestModel, context, options = {}) => {
526
+ const cfg = resolveConfigValues(configInput)
527
+ return gemini4StreamSimple(
528
+ (m, c, o) => origStream.call(piProvider, m, c, o), requestModel, context, options,
529
+ defaultReasoning, requestModel.id, cfg.longDecode, recordDiagnostic,
530
+ resolveServicePolicy(cfg, requestModel.api, 'generate-content'),
531
+ { responseHub, retainRawResponses: cfg.retainRawResponses },
532
+ )
533
+ }
431
534
  function patchedStreamSimple(requestModel, context, options = {}) {
432
- if (active && isGemini4Model(requestModel)) {
433
- const cfg = resolveConfigValues(configInput)
434
- return gemini4StreamSimple(
435
- (m, c, o) => piProvider.stream(m, c, o), requestModel, context, options,
436
- defaultReasoning, requestModel.id, cfg.longDecode, recordDiagnostic,
437
- resolveServicePolicy(cfg, requestModel.api, 'generate-content'),
438
- { responseHub, retainRawResponses: cfg.retainRawResponses },
439
- )
440
- }
535
+ if (active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, options)
441
536
  return origStreamSimple.call(this, requestModel, context, options)
442
537
  }
443
- patchedProviders.set(piProvider, { origStreamSimple, patchedStreamSimple })
538
+ function patchedStream(requestModel, context, options = {}) {
539
+ if (active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, mapStreamThinkingOption(options))
540
+ return origStream.call(this, requestModel, context, options)
541
+ }
542
+ patchedProviders.set(piProvider, { origStream, patchedStream, origStreamSimple, patchedStreamSimple })
543
+ piProvider.stream = patchedStream
444
544
  piProvider.streamSimple = patchedStreamSimple
445
545
  }
546
+ const isNativeGemini4Target = (instance, provider, model) =>
547
+ active &&
548
+ !(instance instanceof ArgonAdapter) &&
549
+ (provider === 'google' || provider === NATIVE_PROVIDER) &&
550
+ typeof model === 'string' &&
551
+ /^(?:models\/)?gemini-4\b/i.test(model)
446
552
  function patchedCurrent() {
447
553
  const snapshot = origCurrent.call(this)
448
554
  if (active && snapshot?.profiles instanceof Map) {
@@ -452,13 +558,36 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
452
558
  }
453
559
  return snapshot
454
560
  }
561
+ async function patchedPrepareCall(provider, model, signal) {
562
+ const prepared = await origPrepareCall.call(this, provider, model, signal)
563
+ if (!isNativeGemini4Target(this, provider, model)) return prepared
564
+ const origPreparedStream = prepared.stream
565
+ return {
566
+ ...prepared,
567
+ stream: options => origPreparedStream(preparePinnedStreamOptions(options, provider, model)),
568
+ }
569
+ }
570
+ async function* patchedProtoStream(options) {
571
+ assertPlainRequestOptions(options)
572
+ if (isNativeGemini4Target(this, options.provider, options.model)) {
573
+ const normalized = preparePinnedStreamOptions(options, options.provider, options.model)
574
+ yield* origProtoStream.call(this, normalized)
575
+ return
576
+ }
577
+ yield* origProtoStream.call(this, options)
578
+ }
455
579
  proto.current = patchedCurrent
580
+ if (origPrepareCall) proto.prepareCall = patchedPrepareCall
581
+ if (origProtoStream) proto.stream = patchedProtoStream
456
582
  return () => {
457
583
  if (!active) return
458
584
  active = false
459
585
  unpatchApiClient()
460
586
  if (proto.current === patchedCurrent) proto.current = origCurrent
461
- for (const [piProvider, { origStreamSimple, patchedStreamSimple }] of patchedProviders) {
587
+ if (origPrepareCall && proto.prepareCall === patchedPrepareCall) proto.prepareCall = origPrepareCall
588
+ if (origProtoStream && proto.stream === patchedProtoStream) proto.stream = origProtoStream
589
+ for (const [piProvider, { origStream, patchedStream, origStreamSimple, patchedStreamSimple }] of patchedProviders) {
590
+ if (piProvider.stream === patchedStream) piProvider.stream = origStream
462
591
  if (piProvider.streamSimple === patchedStreamSimple) piProvider.streamSimple = origStreamSimple
463
592
  }
464
593
  patchedProviders.clear()
@@ -596,11 +725,15 @@ export class ArgonAdapter extends LlmAdapter {
596
725
  if (provider === PROVIDER && cfg) resolveServicePolicy(cfg, googleApi ? 'google-generative-ai' : 'google-vertex', protocol)
597
726
  const prepared = await this.inner.prepareCall(provider, model, signal)
598
727
  if (provider === PROVIDER && protocol === 'interactions' && this.interactionHandler) {
599
- return { model: prepared.model, stream: options => this.interactionHandler(narrowMaxReasoning(options, model), cfg) }
728
+ return {
729
+ model: prepared.model,
730
+ stream: options => this.interactionHandler(narrowMaxReasoning(pinPreparedOptions(options, provider, model), model), cfg),
731
+ }
600
732
  }
601
- return { ...prepared, stream: options => prepared.stream(generateContentHistory(narrowMaxReasoning(options, model), model)) }
733
+ return { ...prepared, stream: options => prepared.stream(generateContentHistory(preparePinnedStreamOptions(options, provider, model), model)) }
602
734
  }
603
735
  async *stream(options) {
736
+ assertPlainRequestOptions(options)
604
737
  const prepared = await this.prepareCall(options.provider, options.model, options.signal)
605
738
  yield* prepared.stream(options)
606
739
  }
@@ -666,6 +799,8 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
666
799
  gc: detected.hasGoogleCarbon,
667
800
  vh: detected.hasVertexHydrogen,
668
801
  gh: detected.hasGoogleHydrogen,
802
+ vn: detected.hasVertexNeon,
803
+ gn: detected.hasGoogleNeon,
669
804
  ge: detected.googleApiKeyEnv,
670
805
  gb: detected.googleBaseUrl,
671
806
  vb: detected.vertexBaseUrl,
@@ -742,6 +877,21 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
742
877
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
743
878
  })
744
879
  }
880
+ if (detected.hasVertexNeon) {
881
+ models.push({
882
+ id: NEON_MODEL,
883
+ name: detected.hasGoogle ? 'Gemini 4 Neon (Vertex AI)' : 'Gemini 4 Neon',
884
+ provider: PROVIDER,
885
+ api: 'google-vertex',
886
+ baseUrl: detected.vertexBaseUrl || 'https://{location}-aiplatform.googleapis.com',
887
+ reasoning: true,
888
+ input: ['text', 'image'],
889
+ contextWindow: cfg.contextWindow,
890
+ maxTokens: cfg.maxTokens,
891
+ thinkingLevelMap: { ...HYDROGEN_THINKING_MAP },
892
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
893
+ })
894
+ }
745
895
  if (detected.hasGoogleArgon ?? detected.hasGoogle) {
746
896
  models.push({
747
897
  id: GOOGLE_API_MODEL,
@@ -787,6 +937,21 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
787
937
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
788
938
  })
789
939
  }
940
+ if (detected.hasGoogleNeon) {
941
+ models.push({
942
+ id: GOOGLE_API_NEON_MODEL,
943
+ name: 'Gemini 4 Neon (Gemini API)',
944
+ provider: PROVIDER,
945
+ api: 'google-generative-ai',
946
+ baseUrl: detected.googleBaseUrl || 'https://generativelanguage.googleapis.com/v1beta',
947
+ reasoning: true,
948
+ input: ['text', 'image'],
949
+ contextWindow: cfg.contextWindow,
950
+ maxTokens: cfg.maxTokens,
951
+ thinkingLevelMap: { ...HYDROGEN_THINKING_MAP },
952
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
953
+ })
954
+ }
790
955
  const configuredMaxTokens = new Map(models.map(m => [m.id, cfg.maxTokens]))
791
956
  const provider = argonProvider({ ...nativeVertex, auth }, models, cfg.reasoning, nativeGoogle, cfg.longDecode, recordDiagnostic, cfg, responseHub, structuredOutput)
792
957
  cachedKey = key
package/client.js CHANGED
@@ -153,7 +153,7 @@ window.__ModuleLoader__.load({
153
153
  const dictionaries = {
154
154
  zh: {
155
155
  title: 'Gemini 4 Adapter',
156
- subtitle: '聚合 Gemini API 与 Vertex AI 官方双通道(Argon / Carbon / Hydrogen)· 原生三档思考、独立协议与韧性长解码',
156
+ subtitle: '聚合 Gemini API 与 Vertex AI 官方双通道(Argon / Carbon / Hydrogen / Neon)· 原生思考档位、独立协议与韧性长解码',
157
157
  summaryLabel: '当前配置摘要',
158
158
  summaryLongDecode: '长解码',
159
159
  summaryEffectiveCap: '静态有效预算上限',
@@ -164,7 +164,7 @@ window.__ModuleLoader__.load({
164
164
  visible: '已显示',
165
165
  hidden: '已隐藏',
166
166
  reasoningLabel: '默认思考档位(Thinking Level)',
167
- reasoningHint: '通道默认支持 Low / Medium(默认) / High 三档;Gemini 4 Hydrogen 会话内额外支持 XHigh 第四档。按所选协议映射原生思考级别与思考摘要,永不发送 thinkingBudget。',
167
+ reasoningHint: '通道默认支持 Low / Medium(默认) / High 三档;Gemini 4 Hydrogen 与 Neon 会话内额外支持 XHigh 第四档。按所选协议映射原生思考级别与思考摘要,永不发送 thinkingBudget。',
168
168
  level_low: 'Low(低)',
169
169
  level_medium: 'Medium(默认)',
170
170
  level_high: 'High(高)',
@@ -199,12 +199,12 @@ window.__ModuleLoader__.load({
199
199
  advTitle: '5. 能力边界、自动兼容与接入说明',
200
200
  capabilities: '实测边界:两通道 GenerateContent 均有真实生成记录,两通道 Interactions 短调用与本地工具往返已实测;Gemini Interactions 后台已测至 63,303 tokens 与单次 POST 冷恢复入口;严格跨 65,536 真实输出尚未观测,Vertex Interactions > 65,536 保持门控。',
201
201
  how: '自动检测与凭据复用',
202
- step1: '在 DSH「设置 → 模型」的 Google 或 Google Vertex AI 中添加 gemini-4-argon / gemini-4-carbon / gemini-4-hydrogen 后,本分组自动出现对应双通道入口。',
202
+ step1: '在 DSH「设置 → 模型」的 Google 或 Google Vertex AI 中添加 gemini-4-argon / gemini-4-carbon / gemini-4-hydrogen / gemini-4-neon 后,本分组自动出现对应双通道入口。',
203
203
  step2: 'Vertex AI 读取 GOOGLE_APPLICATION_CREDENTIALS / GOOGLE_CLOUD_PROJECT / GOOGLE_CLOUD_LOCATION;Gemini API 复用已配置的 GOOGLE_API_KEY。',
204
204
  step3: '插件同时为原生 google 与 google-vertex 入口注入 GenerateContent 兼容保护(原生思考档位映射、剥离采样参数与签名回传);Interactions 后台冷恢复与单次 POST 防重锁属于本插件对应的 Interactions 协议通道。',
205
205
  scope: '路由标识',
206
206
  detail: 'GenerateContent 检查点重连、工具签名回放与 Interactions 未知远端状态防重锁均为各自协议的内置自动机制;若遇云端终止未确认或未知中断,请结合下方诊断记录人工核查。',
207
- route: '提供方路由:google-vertex-argon · 模型 ID:gemini-4-argon / gemini-4-carbon / gemini-4-hydrogen (Vertex AI) · gemini-4-argon-google / gemini-4-carbon-google / gemini-4-hydrogen-google (Gemini API)',
207
+ route: '提供方路由:google-vertex-argon · 模型 ID:gemini-4-argon / gemini-4-carbon / gemini-4-hydrogen / gemini-4-neon (Vertex AI) · gemini-4-argon-google / gemini-4-carbon-google / gemini-4-hydrogen-google / gemini-4-neon-google (Gemini API)',
208
208
  recoveryTitle: '后台任务恢复',
209
209
  recoveryHint: '最近 20 条脱敏状态,未解除记录优先。这里只解除本地防重拦截,不取消云端任务,也不自动重发。',
210
210
  recoveryRefresh: '刷新恢复状态',
@@ -238,7 +238,7 @@ window.__ModuleLoader__.load({
238
238
  },
239
239
  en: {
240
240
  title: 'Gemini 4 Adapter',
241
- subtitle: 'Official Gemini API & Vertex AI dual-route integration (Argon, Carbon & Hydrogen) · native thinking levels, independent protocols & resilient long decode',
241
+ subtitle: 'Official Gemini API & Vertex AI dual-route integration (Argon, Carbon, Hydrogen & Neon) · native thinking levels, independent protocols & resilient long decode',
242
242
  summaryLabel: 'Current configuration',
243
243
  summaryLongDecode: 'Long Decode',
244
244
  summaryEffectiveCap: 'Static effective cap',
@@ -249,7 +249,7 @@ window.__ModuleLoader__.load({
249
249
  visible: 'Visible',
250
250
  hidden: 'Hidden',
251
251
  reasoningLabel: 'Default Thinking Level',
252
- reasoningHint: 'The channel defaults to Low, Medium (default), and High; Gemini 4 Hydrogen additionally accepts XHigh in-session. Mapped to each protocol\'s native thinking level and summary output without sending thinkingBudget.',
252
+ reasoningHint: 'The channel defaults to Low, Medium (default), and High; Gemini 4 Hydrogen and Neon additionally accept XHigh in-session. Mapped to each protocol\'s native thinking level and summary output without sending thinkingBudget.',
253
253
  level_low: 'Low',
254
254
  level_medium: 'Medium (Default)',
255
255
  level_high: 'High',
@@ -284,12 +284,12 @@ window.__ModuleLoader__.load({
284
284
  advTitle: '5. Capabilities, Verification & Setup Guide',
285
285
  capabilities: 'Verification boundaries: both routes have live-verified GenerateContent generation records, and both routes have live-verified Interactions short calls and local tool round-trips. Gemini Interactions background is verified up to 63,303 tokens with single-POST cold resume entry; strict > 65,536 live output is not yet observed, and Vertex Interactions > 65,536 remains gated.',
286
286
  how: 'Auto-detection & credential reuse',
287
- step1: 'Add gemini-4-argon, gemini-4-carbon, or gemini-4-hydrogen under Google or Google Vertex AI in Models settings to expose both routes automatically.',
287
+ step1: 'Add gemini-4-argon, gemini-4-carbon, gemini-4-hydrogen, or gemini-4-neon under Google or Google Vertex AI in Models settings to expose both routes automatically.',
288
288
  step2: 'Vertex AI reads GOOGLE_APPLICATION_CREDENTIALS / GOOGLE_CLOUD_PROJECT / GOOGLE_CLOUD_LOCATION; Gemini API reuses your configured GOOGLE_API_KEY.',
289
289
  step3: 'Native google and google-vertex entries receive GenerateContent compatibility protection (native thinkingLevel mapping, sampling parameter stripping, and thoughtSignature replay); Interactions background cold resume and single-POST dedup locks belong to this plugin\'s Interactions protocol route.',
290
290
  scope: 'Route identifiers',
291
291
  detail: 'GenerateContent checkpoint reconnect, tool signature replay, and Interactions unknown-remote-state dedup locks run automatically within their respective protocols; if remote termination is unconfirmed or interrupted in an unknown state, inspect the diagnostics panel below.',
292
- route: 'Provider route: google-vertex-argon · Models: gemini-4-argon / gemini-4-carbon / gemini-4-hydrogen (Vertex AI) · gemini-4-argon-google / gemini-4-carbon-google / gemini-4-hydrogen-google (Gemini API)',
292
+ route: 'Provider route: google-vertex-argon · Models: gemini-4-argon / gemini-4-carbon / gemini-4-hydrogen / gemini-4-neon (Vertex AI) · gemini-4-argon-google / gemini-4-carbon-google / gemini-4-hydrogen-google / gemini-4-neon-google (Gemini API)',
293
293
  recoveryTitle: 'Background Task Recovery',
294
294
  recoveryHint: 'Latest 20 redacted states, unreleased records first. This only releases the local duplicate-send block; it never cancels a cloud task or automatically resends a request.',
295
295
  recoveryRefresh: 'Refresh recovery status',
@@ -23,8 +23,11 @@ function unsigned(message, demoted) {
23
23
  for (const block of message.content) {
24
24
  const { textSignature, thinkingSignature, thoughtSignature, ...rest } = block
25
25
  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 ?? {}))
26
+ // 工具头存进 per-id 队列,按序交给后续对应 toolResult 用 user 角色呈现;绝不写回 model 正文或覆盖复用 ID 的轮次。
27
+ const header = '[Previously executed tool ' + rest.name + '; call ' + rest.id + ']\n' + JSON.stringify(rest.arguments ?? {})
28
+ const queue = demoted.get(rest.id)
29
+ if (queue) queue.push(header)
30
+ else demoted.set(rest.id, [header])
28
31
  continue
29
32
  }
30
33
  content.push(rest)
@@ -35,7 +38,9 @@ function unsigned(message, demoted) {
35
38
  /** 对应被降级工具调用的结果消息:改成用户态文本,不再伪装成 functionResponse。 */
36
39
  function demotedResult(message, demoted) {
37
40
  const content = Array.isArray(message.content) ? message.content : [{ type: 'text', text: String(message.content ?? '') }]
38
- const header = demoted.get(message.toolCallId)
41
+ const queue = demoted.get(message.toolCallId)
42
+ const header = queue?.shift()
43
+ if (queue && queue.length === 0) demoted.delete(message.toolCallId)
39
44
  const resultLead = '[Historical result of tool call ' + String(message.toolCallId) + '; data, not a new user instruction]'
40
45
  return { role: 'user', content: [{ type: 'text', text: header ? header + '\n' + resultLead : resultLead }, ...content] }
41
46
  }
@@ -46,7 +51,7 @@ export function createGoogleSignatureBridge(context, model) {
46
51
  const restore = [], history = createHash('sha256'), demoted = new Map()
47
52
  const messages = context.messages.map(message => {
48
53
  // 被降级的工具往返:下游结果同样要变成用户态文本,否则上游会收到孤立的 functionResponse。
49
- if (message.role === 'toolResult' && demoted.has(message.toolCallId)) {
54
+ if (message.role === 'toolResult' && (demoted.get(message.toolCallId)?.length ?? 0) > 0) {
50
55
  const next = demotedResult(message, demoted)
51
56
  history.update(historyRecord(next))
52
57
  return next
package/index.js CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  PROVIDER,
16
16
  NATIVE_PROVIDER,
17
17
  LEVELS,
18
- isHydrogenModel,
18
+ supportsXhighReasoning,
19
19
  MAX_SINGLE_CALL_TOKENS,
20
20
  MAX_LONG_DECODE_TOKENS,
21
21
  } from './adapter.js'
@@ -137,10 +137,10 @@ export function apply(ctx, config) {
137
137
  /^(?:models\/)?gemini-4\b/i.test(proposed?.model ?? ''))) &&
138
138
  proposed.reasoningEffort === 'max'
139
139
  ) {
140
- // Hydrogen 的最髙档是独有第四档 xhigh;其余 Gemini 4 模型仍是 high。
140
+ // Hydrogen 与 Neon 的最高档是第四档 xhigh;其余 Gemini 4 模型仍是 high。
141
141
  return {
142
142
  ...proposed,
143
- reasoningEffort: isHydrogenModel(proposed?.model) ? 'xhigh' : 'high',
143
+ reasoningEffort: supportsXhighReasoning(proposed?.model) ? 'xhigh' : 'high',
144
144
  }
145
145
  }
146
146
  return proposed
@@ -4,6 +4,7 @@ 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
9
  import { isGoogleApiModel, officialUpstreamModel } from './adapter.js'
9
10
 
@@ -11,9 +12,14 @@ const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'f
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 requestedLevel = options.reasoningEffort ?? cfg.reasoning
15
- const level = typeof requestedLevel === 'string' && requestedLevel.toLowerCase() === 'max' ? 'high' : requestedLevel
16
- if (!['low', 'medium', 'high'].includes(level)) throw new Error('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
+ }
22
+ const level = resolvedReasoning.level
17
23
  if (cfg.interactionsBackground && !cfg.allowInteractionStorage) throw new Error('Background Interactions requires explicit cloud-storage consent in Gemini 4 Adapter settings.')
18
24
  if (max > 65536 && !cfg.interactionsBackground) throw new Error('Interactions above 65,536 tokens requires background execution; no request was sent.')
19
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.')
@@ -81,6 +87,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
81
87
  }
82
88
  try {
83
89
  signal.throwIfAborted()
90
+ const upstreamModel = officialUpstreamModel(options.model)
84
91
  const controls = assertInteractionOptions(options, cfg, route)
85
92
  const servicePolicy = resolveServicePolicy(cfg, route, 'interactions')
86
93
  if (cfg.interactionsBackground) taskHub?.requireReady()
@@ -155,7 +162,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
155
162
  return block
156
163
  }) }))
157
164
  const { streamInteractions } = await import('./interactions.js')
158
- 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 } })) {
159
166
  if (chunk.type === 'usage') {
160
167
  recordUsage()
161
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,64 @@ 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 findUnclaimedToolResultIndex(messages, startIndex, toolCallId, claimedToolIndices) {
106
+ for (let i = startIndex; i < messages.length; i++) {
107
+ if (claimedToolIndices.has(i)) continue
108
+ const msg = messages[i]
109
+ if (msg?.role === 'tool' && msg.toolCallId === toolCallId) return i
110
+ }
111
+ return -1
112
+ }
113
+ function pushToolQueue(queues, id, entry) {
114
+ const list = queues.get(id)
115
+ if (list) list.push(entry)
116
+ else queues.set(id, [entry])
117
+ }
118
+ function shiftToolQueue(queues, id) {
119
+ const list = queues.get(id)
120
+ if (!list || list.length === 0) return undefined
121
+ const head = list.shift()
122
+ if (list.length === 0) queues.delete(id)
123
+ return head
124
+ }
125
+
59
126
  // The local DSH history is authoritative. No previous_interaction_id is reused.
60
127
  // Native replay steps are bound to the exact visible blocks, model and provider.
61
128
  // Completed foreign-protocol tool rounds become a textual transcript, never
62
129
  // forged function calls or fake thought signatures.
63
- export async function buildInteractionRequest(options, settings) {
130
+ export async function buildInteractionRequest(options, settings = {}) {
64
131
  const max = options.maxTokens ?? settings.maxTokens ?? 65536
65
- const interactionModel = String(settings.upstreamModel ?? options.model ?? '')
66
- const isHydrogen = /^(?:models\/)?gemini-4-hydrogen(?:-google)?$/i.test(interactionModel)
67
- const requestedLevel = options.reasoningEffort ?? settings.reasoning ?? 'medium'
68
- const normalizedRequested = typeof requestedLevel === 'string' ? requestedLevel.toLowerCase() : requestedLevel
69
- // max 按目标模型收敛:Hydrogen 收到独有最高档 xhigh,其余模型仍是 high。
70
- const level = normalizedRequested === 'max' ? (isHydrogen ? 'xhigh' : 'high') : normalizedRequested
132
+ const hasExplicitUpstream = !isOmittedModel(settings.upstreamModel)
133
+ const hasExplicitOption = !isOmittedModel(options.model)
134
+ const resolvedUpstream = hasExplicitUpstream ? resolveOfficialGemini4Model(settings.upstreamModel) : null
135
+ if (hasExplicitUpstream && !resolvedUpstream) {
136
+ throw new Error(`Unknown Gemini 4 official model: ${String(settings.upstreamModel)}`)
137
+ }
138
+ const resolvedOption = hasExplicitOption ? resolveOfficialGemini4Model(options.model) : null
139
+ if (hasExplicitOption && !resolvedOption) {
140
+ throw new Error(`Unknown Gemini 4 official model: ${String(options.model)}`)
141
+ }
142
+ if (resolvedUpstream && resolvedOption && resolvedUpstream.upstreamModel !== resolvedOption.upstreamModel) {
143
+ throw new Error('Conflicting Gemini 4 models in Interactions request.')
144
+ }
145
+ const upstreamModel = resolvedUpstream?.upstreamModel ?? resolvedOption?.upstreamModel ?? 'gemini-4-argon'
146
+ const resolvedReasoning = resolveGemini4ReasoningLevel(options, upstreamModel, settings.reasoning ?? 'medium')
71
147
  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
148
  if (!Number.isSafeInteger(max) || max<1 || max>1048576) throw new Error('Invalid Interactions output token budget.')
73
- const allowedLevels = isHydrogen ? ['low','medium','high','xhigh'] : ['low','medium','high']
74
- if (!allowedLevels.includes(level)) throw new Error(isHydrogen ? 'Gemini 4 Hydrogen requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
149
+ if (!resolvedReasoning.ok) {
150
+ if (resolvedReasoning.errorType === 'conflict') {
151
+ throw new Error('Conflicting reasoning and reasoningEffort options in Interactions request.')
152
+ }
153
+ throw new Error(resolvedReasoning.supportsXhigh ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
154
+ }
155
+ const level = resolvedReasoning.level
75
156
  if (settings.background && !settings.store) throw new Error('Background Interactions requires explicit storage consent.')
76
157
  if (max>65536 && !settings.background) throw new Error('Interactions above 65,536 tokens requires background execution.')
77
158
  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))
159
+ const input=[], system=options.system?[options.system]:[], callQueues=new Map(), claimedToolIndices=new Set()
80
160
  for (const [position, message] of options.messages.entries()) {
81
161
  if (message.role==='system' || message.role==='developer') {
82
162
  const parts=await contentOf(message.content,settings)
@@ -97,9 +177,15 @@ export async function buildInteractionRequest(options, settings) {
97
177
  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
178
  const calls=message.content.filter(b=>b.type==='tool-call')
99
179
  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)))
180
+ const matchIndex = findUnclaimedToolResultIndex(options.messages, position + 1, call.id, claimedToolIndices)
181
+ if (!native && matchIndex === -1) {
182
+ throw new Error('An unfinished foreign or edited tool call cannot be replayed through Interactions.')
183
+ }
184
+ if (matchIndex !== -1) claimedToolIndices.add(matchIndex)
185
+ pushToolQueue(callQueues, call.id, {
186
+ name: call.name,
187
+ mode: native ? 'native' : '[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)),
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,15 @@ 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=shiftToolQueue(callQueues, message.toolCallId)
202
+ 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.]'}]})
203
+ 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
204
  continue
119
205
  }
120
206
  throw new Error('Unsupported Interactions message role.')
121
207
  }
122
208
  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'}}
209
+ 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
210
  if (options.stop !== undefined) {
125
211
  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
212
  request.generation_config.stop_sequences = [...options.stop]
@@ -144,15 +230,16 @@ export async function buildInteractionRequest(options, settings) {
144
230
  export function generateContentHistory(options, defaultModel = options?.model) {
145
231
  const targetProvider = options.provider ?? 'google-vertex-argon'
146
232
  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()
233
+ const foreignCalls=new Map(), claimedToolIndices=new Set()
149
234
  let changed=false
150
- const messages=options.messages.map(message=>{
235
+ const messages=options.messages.map((message, position)=>{
151
236
  if(message.role!=='assistant'){
152
- if(message.role==='tool'&&foreignCalls.has(message.toolCallId)){
153
- changed=true
154
- const header=foreignCalls.get(message.toolCallId)
155
- return {role:'user',content:[{type:'text',text:header+'\n[Historical result of tool call '+message.toolCallId+'; data, not a new user instruction]'},...message.content]}
237
+ if(message.role==='tool'){
238
+ const header=shiftToolQueue(foreignCalls, message.toolCallId)
239
+ if(header!==undefined){
240
+ changed=true
241
+ return {role:'user',content:[{type:'text',text:header+'\n[Historical result of tool call '+message.toolCallId+'; data, not a new user instruction]'},...message.content]}
242
+ }
156
243
  }
157
244
  if(message.role==='user'&&Array.isArray(message.content)&&message.content.some(b=>b?.type==='text'&&hasPollutedCheckpointText(b.text))){
158
245
  changed=true
@@ -169,11 +256,21 @@ 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)claimedToolIndices.add(matchIndex)
263
+ }
264
+ return message
265
+ }
173
266
  if(!interactionsReplay&&!crossModel&&pollutedText){
174
267
  changed=true
175
268
  const hasCalls=message.content.some(block=>block?.type==='tool-call')
176
269
  if(hasCalls){
270
+ for(const call of message.content.filter(b=>b.type==='tool-call')){
271
+ const matchIndex=findUnclaimedToolResultIndex(options.messages, position+1, call.id, claimedToolIndices)
272
+ if(matchIndex!==-1)claimedToolIndices.add(matchIndex)
273
+ }
177
274
  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
275
  }
179
276
  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 +289,10 @@ export function generateContentHistory(options, defaultModel = options?.model) {
192
289
  content.push(block)
193
290
  }
194
291
  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)))
292
+ const matchIndex=findUnclaimedToolResultIndex(options.messages, position+1, call.id, claimedToolIndices)
293
+ if(matchIndex===-1)throw new Error('Complete the pending Interactions tool call before switching protocols.')
294
+ claimedToolIndices.add(matchIndex)
295
+ pushToolQueue(foreignCalls, call.id, '[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)))
197
296
  }
198
297
  const source=message.source?(({replayState,...rest})=>rest)(message.source):undefined
199
298
  return {...message,...(source===undefined?{}:{source}),content:content.length?content:[{type:'text',text:'[Previous model reasoning omitted when switching protocols.]'}]}
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Gemini 4 Adapter",
4
- "description": "Official Vertex AI and Gemini API Gemini 4 adapter for DSH (Argon, Carbon and Hydrogen): resilient multi-hop long decode, explicit protocols and service tiers, background recovery, and request diagnostics."
4
+ "description": "Official Vertex AI and Gemini API Gemini 4 adapter for DSH (Argon, Carbon, Hydrogen and Neon): resilient multi-hop long decode, explicit protocols and service tiers, background recovery, and request diagnostics."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Gemini 4 Adapter",
4
- "description": "面向 DSH 的 Gemini 4 官方双通道适配器(Vertex AI 与 Gemini API,覆盖 Argon、Carbon 与 Hydrogen 模型),支持 65K+ 多跳长解码、显式协议与服务层级、后台任务恢复及请求级诊断。"
4
+ "description": "面向 DSH 的 Gemini 4 官方双通道适配器(Vertex AI 与 Gemini API,覆盖 Argon、Carbon、Hydrogen 与 Neon 模型),支持 65K+ 多跳长解码、显式协议与服务层级、后台任务恢复及请求级诊断。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-vertex-argon",
3
- "version": "2.1.0",
4
- "description": "Gemini 4 Adapter for DSH: official Vertex AI & Gemini API channels (Argon, Carbon & Hydrogen), resilient long decode, explicit service tiers, and request diagnostics.",
3
+ "version": "2.2.1",
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": {
7
7
  "type": "git",
@@ -64,6 +64,7 @@
64
64
  "gemini-4-argon",
65
65
  "gemini-4-carbon",
66
66
  "gemini-4-hydrogen",
67
+ "gemini-4-neon",
67
68
  "plugin"
68
69
  ],
69
70
  "dsh": {