dsh-vertex-argon 2.2.1 → 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,16 @@
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
+
5
15
  ## [2.2.1] - 2026-11-19
6
16
 
7
17
  ### Fixed
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  **面向 [DeepSeek Harness](<https://github.com/deepseek-ai/deepseek-harness>) 的 Google 官方双通道(Vertex AI + Gemini Developer API)Gemini 4 适配器,原生支持 Argon、Carbon、Hydrogen 与 Neon 八模型路由、GenerateContent / Interactions 双协议、65K+ 多跳长解码与请求级诊断。**
6
6
 
7
- - **当前版本**:`2.2.1`([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
@@ -49,6 +49,7 @@ export const HYDROGEN_LEVELS = ['low', 'medium', 'high', 'xhigh']
49
49
  export const MAX_SINGLE_CALL_TOKENS = 65536
50
50
  export const MAX_LONG_DECODE_TOKENS = 1048576
51
51
  const COMPACTION_HEADROOM_FLOOR = 131072
52
+ const MAX_TOKENS_CEILING = Symbol('argonMaxTokensCeiling')
52
53
  const ENV_KEYS = ['GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_CLOUD_PROJECT', 'GCLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION', 'GOOGLE_CLOUD_API_KEY']
53
54
  const DEFAULT_THINKING_MAP = { off: null, minimal: null, low: 'low', medium: 'medium', high: 'high', xhigh: null, max: null }
54
55
  /** Hydrogen 与 Neon 的档位映射:把 xhigh 放行到 thinkingConfig。 */
@@ -119,6 +120,14 @@ export function narrowMaxReasoning(options, modelId = options?.model) {
119
120
  return { ...options, reasoning: ceiling, reasoningEffort: ceiling }
120
121
  }
121
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
+
122
131
  function pinPreparedOptions(options, expectedProvider, expectedModel) {
123
132
  assertPlainRequestOptions(options)
124
133
  if (expectedProvider !== undefined && options.provider !== undefined && options.provider !== expectedProvider) {
@@ -135,7 +144,7 @@ function preparePinnedStreamOptions(options, expectedProvider, expectedModel) {
135
144
  const pinned = pinPreparedOptions(options, expectedProvider, expectedModel)
136
145
  const targetModel = pinned.model ?? expectedModel
137
146
  validateExplicitReasoningFields(pinned, targetModel)
138
- return narrowMaxReasoning(pinned, targetModel)
147
+ return syncGemini4ReasoningOptions(pinned, targetModel)
139
148
  }
140
149
 
141
150
  const readVal = v => (v && typeof v === 'object' && typeof v.get === 'function') ? v.get() : v
@@ -358,6 +367,26 @@ function wrapGemini4Stream(rawStream, tracker, signal, retryKey) {
358
367
  }
359
368
  }
360
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
+
361
390
  export function gemini4StreamSimple(
362
391
  nativeStream,
363
392
  requestModel,
@@ -387,7 +416,11 @@ export function gemini4StreamSimple(
387
416
  )
388
417
  }
389
418
  const { reasoning, reasoningEffort: _re, thinking, thinkingBudgets, temperature, onPayload: prior, onProviderStreamEvent: priorEvent, ...rest } = options
419
+ assertGemini4MaxTokens(options, requestModel, longDecode)
390
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
+ }
391
424
  const effectiveMaxTokens =
392
425
  longDecode === false && typeof requestedMaxTokens === 'number' && requestedMaxTokens > MAX_SINGLE_CALL_TOKENS
393
426
  ? MAX_SINGLE_CALL_TOKENS
@@ -491,6 +524,7 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
491
524
  const origPrepareCall = typeof proto.prepareCall === 'function' ? proto.prepareCall : null
492
525
  const origProtoStream = typeof proto.stream === 'function' ? proto.stream : null
493
526
  const patchedProviders = new Map()
527
+ const patchedModels = new Map()
494
528
  let active = true
495
529
  const ensureGemini4Capabilities = piProvider => {
496
530
  if (typeof piProvider?.getModels !== 'function') return
@@ -498,6 +532,14 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
498
532
  for (const m of piProvider.getModels()) {
499
533
  if (isGemini4Model(m)) {
500
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
+ }
501
543
  m.reasoning = true
502
544
  m.thinkingLevelMap = { ...thinkingLevelMapFor(m.id) }
503
545
  } catch {}
@@ -562,15 +604,23 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
562
604
  const prepared = await origPrepareCall.call(this, provider, model, signal)
563
605
  if (!isNativeGemini4Target(this, provider, model)) return prepared
564
606
  const origPreparedStream = prepared.stream
607
+ const resolvedModel = this.current?.()?.models?.getModel?.(provider, model)
565
608
  return {
566
609
  ...prepared,
567
- stream: options => origPreparedStream(preparePinnedStreamOptions(options, provider, model)),
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
+ },
568
616
  }
569
617
  }
570
618
  async function* patchedProtoStream(options) {
571
- assertPlainRequestOptions(options)
572
- if (isNativeGemini4Target(this, options.provider, options.model)) {
573
- const normalized = preparePinnedStreamOptions(options, options.provider, options.model)
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)
574
624
  yield* origProtoStream.call(this, normalized)
575
625
  return
576
626
  }
@@ -591,6 +641,15 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
591
641
  if (piProvider.streamSimple === patchedStreamSimple) piProvider.streamSimple = origStreamSimple
592
642
  }
593
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()
594
653
  }
595
654
  }
596
655
 
@@ -620,16 +679,22 @@ export function resolveConfigValues(raw = {}) {
620
679
  for (const [key, val] of [['contextWindow', contextWindow], ['maxTokens', rawMaxTokens]]) {
621
680
  if (!Number.isSafeInteger(val) || val <= 0 || val > MAX_LONG_DECODE_TOKENS) throw new LlmError('Invalid Argon ' + key, 'INVALID_CONFIG')
622
681
  }
682
+ const hasExplicitMaxTokens = source?.maxTokens !== undefined && readVal(source?.maxTokens) !== undefined
623
683
  const enabledLongDecode = Boolean(longDecode)
624
684
  const capByMode = enabledLongDecode ? Math.min(rawMaxTokens, MAX_LONG_DECODE_TOKENS) : Math.min(rawMaxTokens, MAX_SINGLE_CALL_TOKENS)
625
685
  const safeCompactionCap = contextWindow > COMPACTION_HEADROOM_FLOOR ? contextWindow - COMPACTION_HEADROOM_FLOOR : contextWindow
626
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))
627
690
  return {
628
691
  showInModelPicker: Boolean(showInModelPicker),
629
692
  reasoning,
630
693
  longDecode: enabledLongDecode,
631
694
  contextWindow,
632
695
  maxTokens,
696
+ hasExplicitMaxTokens,
697
+ explicitMaxTokensCap,
633
698
  googleProtocol,
634
699
  vertexProtocol,
635
700
  googleServiceTier,
@@ -727,10 +792,20 @@ export class ArgonAdapter extends LlmAdapter {
727
792
  if (provider === PROVIDER && protocol === 'interactions' && this.interactionHandler) {
728
793
  return {
729
794
  model: prepared.model,
730
- stream: options => this.interactionHandler(narrowMaxReasoning(pinPreparedOptions(options, provider, model), model), cfg),
795
+ stream: options => this.interactionHandler(syncGemini4ReasoningOptions(pinPreparedOptions(options, provider, model), model), cfg),
731
796
  }
732
797
  }
733
- return { ...prepared, stream: options => prepared.stream(generateContentHistory(preparePinnedStreamOptions(options, provider, model), model)) }
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
+ },
808
+ }
734
809
  }
735
810
  async *stream(options) {
736
811
  assertPlainRequestOptions(options)
@@ -782,6 +857,8 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
782
857
  ld: cfg.longDecode,
783
858
  cw: cfg.contextWindow,
784
859
  mt: cfg.maxTokens,
860
+ explicitMt: cfg.hasExplicitMaxTokens,
861
+ capMt: cfg.explicitMaxTokensCap,
785
862
  visible: cfg.showInModelPicker,
786
863
  gp: cfg.googleProtocol,
787
864
  vp: cfg.vertexProtocol,
@@ -952,6 +1029,9 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
952
1029
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
953
1030
  })
954
1031
  }
1032
+ for (const modelDescriptor of models) {
1033
+ modelDescriptor[MAX_TOKENS_CEILING] = cfg.explicitMaxTokensCap
1034
+ }
955
1035
  const configuredMaxTokens = new Map(models.map(m => [m.id, cfg.maxTokens]))
956
1036
  const provider = argonProvider({ ...nativeVertex, auth }, models, cfg.reasoning, nativeGoogle, cfg.longDecode, recordDiagnostic, cfg, responseHub, structuredOutput)
957
1037
  cachedKey = key
@@ -18,16 +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
- // 工具头存进 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])
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 ?? {}))
31
49
  continue
32
50
  }
33
51
  content.push(rest)
@@ -36,11 +54,8 @@ function unsigned(message, demoted) {
36
54
  }
37
55
 
38
56
  /** 对应被降级工具调用的结果消息:改成用户态文本,不再伪装成 functionResponse。 */
39
- function demotedResult(message, demoted) {
57
+ function demotedResult(message, header) {
40
58
  const content = Array.isArray(message.content) ? message.content : [{ type: 'text', text: String(message.content ?? '') }]
41
- const queue = demoted.get(message.toolCallId)
42
- const header = queue?.shift()
43
- if (queue && queue.length === 0) demoted.delete(message.toolCallId)
44
59
  const resultLead = '[Historical result of tool call ' + String(message.toolCallId) + '; data, not a new user instruction]'
45
60
  return { role: 'user', content: [{ type: 'text', text: header ? header + '\n' + resultLead : resultLead }, ...content] }
46
61
  }
@@ -48,11 +63,13 @@ function demotedResult(message, demoted) {
48
63
  // The existing textSignature field is adapter-owned opaque replay metadata.
49
64
  // Its versioned codec never reaches Google: onPayload restores the original Part.
50
65
  export function createGoogleSignatureBridge(context, model) {
51
- const restore = [], history = createHash('sha256'), demoted = new Map()
52
- const messages = context.messages.map(message => {
53
- // 被降级的工具往返:下游结果同样要变成用户态文本,否则上游会收到孤立的 functionResponse。
54
- if (message.role === 'toolResult' && (demoted.get(message.toolCallId)?.length ?? 0) > 0) {
55
- 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)
56
73
  history.update(historyRecord(next))
57
74
  return next
58
75
  }
@@ -65,12 +82,23 @@ export function createGoogleSignatureBridge(context, model) {
65
82
  const same = message.api === model.api && message.provider === model.provider && message.model === model.id
66
83
  const codes = message.content.map(block => block.type === 'text' ? decode(block.textSignature) : undefined)
67
84
  const hasCodes = codes.some(code => code !== undefined)
68
- 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')
69
87
  let next = message
70
- if (hasCodes && (!same || codes.some((code, index) => code !== undefined && (!code || message.content[index].text !== '' || code.contentDigest !== contentDigest || code.historyDigest !== previousHistory)))) next = unsigned(message, demoted)
71
- else {
72
- const content = message.content.map((block, index) => {
73
- 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]
74
102
  if (code) {
75
103
  const carrier = Buffer.from(code.signature).toString('base64')
76
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
  })
@@ -102,26 +102,21 @@ async function contentOf(blocks, settings, scrubText = false) {
102
102
  function isOmittedModel(value) {
103
103
  return value === undefined || value === null || value === ''
104
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
+ }
105
111
  function findUnclaimedToolResultIndex(messages, startIndex, toolCallId, claimedToolIndices) {
106
112
  for (let i = startIndex; i < messages.length; i++) {
107
- if (claimedToolIndices.has(i)) continue
108
113
  const msg = messages[i]
114
+ if (msg?.role === 'assistant') break
115
+ if (claimedToolIndices.has(i)) continue
109
116
  if (msg?.role === 'tool' && msg.toolCallId === toolCallId) return i
110
117
  }
111
118
  return -1
112
119
  }
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
120
 
126
121
  // The local DSH history is authoritative. No previous_interaction_id is reused.
127
122
  // Native replay steps are bound to the exact visible blocks, model and provider.
@@ -156,7 +151,7 @@ export async function buildInteractionRequest(options, settings = {}) {
156
151
  if (settings.background && !settings.store) throw new Error('Background Interactions requires explicit storage consent.')
157
152
  if (max>65536 && !settings.background) throw new Error('Interactions above 65,536 tokens requires background execution.')
158
153
  if (max>65536 && settings.route==='google-vertex') throw new Error('Vertex Interactions long decode is not verified; use GenerateContent.')
159
- const input=[], system=options.system?[options.system]:[], callQueues=new Map(), claimedToolIndices=new Set()
154
+ const input=[], system=options.system?[options.system]:[], toolPlansByIndex=new Map(), claimedToolIndices=new Set()
160
155
  for (const [position, message] of options.messages.entries()) {
161
156
  if (message.role==='system' || message.role==='developer') {
162
157
  const parts=await contentOf(message.content,settings)
@@ -181,11 +176,16 @@ export async function buildInteractionRequest(options, settings = {}) {
181
176
  if (!native && matchIndex === -1) {
182
177
  throw new Error('An unfinished foreign or edited tool call cannot be replayed through Interactions.')
183
178
  }
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
- })
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
+ }
189
189
  }
190
190
  if(native){
191
191
  if(replay.steps.some(s=>!['thought','model_output','function_call'].includes(s.type)))throw new Error('Invalid Interactions replay step.')
@@ -198,7 +198,8 @@ export async function buildInteractionRequest(options, settings = {}) {
198
198
  }
199
199
  if(message.role==='tool'){
200
200
  const content=await contentOf(message.content,settings)
201
- const entry=shiftToolQueue(callQueues, message.toolCallId)
201
+ const entry=toolPlansByIndex.get(position)
202
+ if(entry) toolPlansByIndex.delete(position)
202
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.]'}]})
203
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]})
204
205
  continue
@@ -230,16 +231,15 @@ export async function buildInteractionRequest(options, settings = {}) {
230
231
  export function generateContentHistory(options, defaultModel = options?.model) {
231
232
  const targetProvider = options.provider ?? 'google-vertex-argon'
232
233
  const targetModel = options.model ?? defaultModel
233
- const foreignCalls=new Map(), claimedToolIndices=new Set()
234
+ const foreignHeadersByIndex=new Map(), claimedToolIndices=new Set()
234
235
  let changed=false
235
236
  const messages=options.messages.map((message, position)=>{
236
237
  if(message.role!=='assistant'){
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
- }
238
+ if(message.role==='tool'&&foreignHeadersByIndex.has(position)){
239
+ changed=true
240
+ const header=foreignHeadersByIndex.get(position)
241
+ foreignHeadersByIndex.delete(position)
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]}
243
243
  }
244
244
  if(message.role==='user'&&Array.isArray(message.content)&&message.content.some(b=>b?.type==='text'&&hasPollutedCheckpointText(b.text))){
245
245
  changed=true
@@ -259,6 +259,9 @@ export function generateContentHistory(options, defaultModel = options?.model) {
259
259
  if(!interactionsReplay&&!crossModel&&!pollutedText){
260
260
  for(const call of message.content.filter(b=>b.type==='tool-call')){
261
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
+ }
262
265
  if(matchIndex!==-1)claimedToolIndices.add(matchIndex)
263
266
  }
264
267
  return message
@@ -269,6 +272,9 @@ export function generateContentHistory(options, defaultModel = options?.model) {
269
272
  if(hasCalls){
270
273
  for(const call of message.content.filter(b=>b.type==='tool-call')){
271
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
+ }
272
278
  if(matchIndex!==-1)claimedToolIndices.add(matchIndex)
273
279
  }
274
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)}
@@ -292,7 +298,7 @@ export function generateContentHistory(options, defaultModel = options?.model) {
292
298
  const matchIndex=findUnclaimedToolResultIndex(options.messages, position+1, call.id, claimedToolIndices)
293
299
  if(matchIndex===-1)throw new Error('Complete the pending Interactions tool call before switching protocols.')
294
300
  claimedToolIndices.add(matchIndex)
295
- pushToolQueue(foreignCalls, call.id, '[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)))
301
+ foreignHeadersByIndex.set(matchIndex, '[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments)))
296
302
  }
297
303
  const source=message.source?(({replayState,...rest})=>rest)(message.source):undefined
298
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.1",
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": {