dsh-vertex-argon 2.2.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 +14 -0
- package/README.md +1 -1
- package/adapter.js +160 -55
- package/google-signatures.js +9 -4
- package/interaction-adapter.js +11 -9
- package/interactions-input.js +127 -28
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
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
|
+
|
|
5
19
|
## [2.2.0] - 2026-11-19
|
|
6
20
|
|
|
7
21
|
### Added
|
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
**面向 [DeepSeek Harness](<https://github.com/deepseek-ai/deepseek-harness>) 的 Google 官方双通道(Vertex AI + Gemini Developer API)Gemini 4 适配器,原生支持 Argon、Carbon、Hydrogen 与 Neon 八模型路由、GenerateContent / Interactions 双协议、65K+ 多跳长解码与请求级诊断。**
|
|
6
6
|
|
|
7
|
-
- **当前版本**:`2.2.
|
|
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
|
|
package/adapter.js
CHANGED
|
@@ -6,7 +6,7 @@ import { createArgonDiagnosticTracker } from './diagnostics.js'
|
|
|
6
6
|
import { createInteractionsHandler } from './interaction-adapter.js'
|
|
7
7
|
import { interactionImageRequestTarget } from './interaction-image.js'
|
|
8
8
|
import { SERVICE_TIERS, resolveServicePolicy, mergeServiceHeaders } from './service-level.js'
|
|
9
|
-
import { generateContentHistory } from './interactions-input.js'
|
|
9
|
+
import { generateContentHistory, resolveOfficialGemini4Model, resolveGemini4ReasoningLevel } from './interactions-input.js'
|
|
10
10
|
import { createGoogleSignatureBridge } from './google-signatures.js'
|
|
11
11
|
import { createInteractionQuery } from './interaction-query.js'
|
|
12
12
|
import { assertPreparedStructuredOutput } from './structured-output.js'
|
|
@@ -29,20 +29,16 @@ export const HYDROGEN_MODEL = 'gemini-4-hydrogen'
|
|
|
29
29
|
export const GOOGLE_API_HYDROGEN_MODEL = 'gemini-4-hydrogen-google'
|
|
30
30
|
export const NEON_MODEL = 'gemini-4-neon'
|
|
31
31
|
export const GOOGLE_API_NEON_MODEL = 'gemini-4-neon-google'
|
|
32
|
-
/** Gemini API 官方直连模型判定(Argon、Carbon、Hydrogen 与 Neon
|
|
32
|
+
/** Gemini API 官方直连模型判定(Argon、Carbon、Hydrogen 与 Neon,支持可选 models/ 前缀)。 */
|
|
33
33
|
export function isGoogleApiModel(modelId) {
|
|
34
|
-
return (
|
|
35
|
-
modelId === GOOGLE_API_MODEL ||
|
|
36
|
-
modelId === GOOGLE_API_CARBON_MODEL ||
|
|
37
|
-
modelId === GOOGLE_API_HYDROGEN_MODEL ||
|
|
38
|
-
modelId === GOOGLE_API_NEON_MODEL
|
|
39
|
-
)
|
|
34
|
+
return resolveOfficialGemini4Model(modelId)?.isGoogleApi ?? false
|
|
40
35
|
}
|
|
41
|
-
/** 官方直连(Vertex AI / Gemini API)对应的上游模型 ID
|
|
36
|
+
/** 官方直连(Vertex AI / Gemini API)对应的上游模型 ID;空值回落默认 Argon,未知非空模型报错。 */
|
|
42
37
|
export function officialUpstreamModel(modelId) {
|
|
43
|
-
if (modelId ===
|
|
44
|
-
|
|
45
|
-
|
|
38
|
+
if (modelId === undefined || modelId === null || modelId === '') return MODEL
|
|
39
|
+
const resolved = resolveOfficialGemini4Model(modelId)
|
|
40
|
+
if (!resolved) throw new LlmError(`Unknown Gemini 4 official model: ${String(modelId)}`, 'UNKNOWN_MODEL')
|
|
41
|
+
return resolved.upstreamModel
|
|
46
42
|
}
|
|
47
43
|
export const LEVELS = ['low', 'medium', 'high']
|
|
48
44
|
/**
|
|
@@ -60,17 +56,17 @@ const HYDROGEN_THINKING_MAP = { off: null, minimal: null, low: 'low', medium: 'm
|
|
|
60
56
|
|
|
61
57
|
/** Hydrogen 模型 ID 判定:同时识别 `gemini-4-hydrogen` 与 `gemini-4-hydrogen-google`(可带 models/ 前缀)。 */
|
|
62
58
|
export function isHydrogenModel(modelId) {
|
|
63
|
-
return
|
|
59
|
+
return resolveOfficialGemini4Model(modelId)?.family === 'hydrogen'
|
|
64
60
|
}
|
|
65
61
|
|
|
66
62
|
/** Neon 模型 ID 判定:同时识别 `gemini-4-neon` 与 `gemini-4-neon-google`(可带 models/ 前缀)。 */
|
|
67
63
|
export function isNeonModel(modelId) {
|
|
68
|
-
return
|
|
64
|
+
return resolveOfficialGemini4Model(modelId)?.family === 'neon'
|
|
69
65
|
}
|
|
70
66
|
|
|
71
67
|
/** 判断模型是否支持 xhigh 第四档思考及对应无显式缓存限制(Hydrogen 与 Neon)。 */
|
|
72
68
|
export function supportsXhighReasoning(modelId) {
|
|
73
|
-
return
|
|
69
|
+
return resolveOfficialGemini4Model(modelId)?.supportsXhigh ?? false
|
|
74
70
|
}
|
|
75
71
|
|
|
76
72
|
/** 模型对应的合法思考档位集合:Hydrogen 与 Neon 放行 xhigh。 */
|
|
@@ -83,18 +79,65 @@ export function thinkingLevelMapFor(modelId) {
|
|
|
83
79
|
return supportsXhighReasoning(modelId) ? HYDROGEN_THINKING_MAP : DEFAULT_THINKING_MAP
|
|
84
80
|
}
|
|
85
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
|
|
104
|
+
}
|
|
105
|
+
|
|
86
106
|
// The host's agent/request hook already narrows 'max' to 'high'. Direct adapter
|
|
87
107
|
// callers (advisor tools calling adapter.stream / prepareCall().stream) bypass
|
|
88
108
|
// that hook, so the same narrowing has to happen at this boundary too.
|
|
89
109
|
export function narrowMaxReasoning(options, modelId = options?.model) {
|
|
90
110
|
if (!options || typeof options !== 'object') return options
|
|
91
|
-
const
|
|
92
|
-
|
|
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
|
|
93
117
|
// Hydrogen 与 Neon 的最高档是 xhigh;其余模型仍是 high。
|
|
94
118
|
const ceiling = supportsXhighReasoning(modelId) ? 'xhigh' : 'high'
|
|
95
119
|
return { ...options, reasoning: ceiling, reasoningEffort: ceiling }
|
|
96
120
|
}
|
|
97
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
|
+
|
|
98
141
|
const readVal = v => (v && typeof v === 'object' && typeof v.get === 'function') ? v.get() : v
|
|
99
142
|
|
|
100
143
|
export function isGemini4Model(model) {
|
|
@@ -151,14 +194,14 @@ export function detectPiAiArgonRoutes(ctx, explicitRoutes) {
|
|
|
151
194
|
const hasModel = (list, re) => Array.isArray(list) && list.some(m => re.test(String(readVal(m?.id) ?? '')))
|
|
152
195
|
const googleModels = readVal(googleCfg?.models)
|
|
153
196
|
const vertexModels = readVal(vertexCfg?.models)
|
|
154
|
-
const hasGoogleArgon = hasModel(googleModels, /^(?:models\/)?gemini-4-argon
|
|
155
|
-
const hasVertexArgon = hasModel(vertexModels, /^(?:models\/)?gemini-4-argon
|
|
156
|
-
const hasGoogleCarbon = hasModel(googleModels, /^(?:models\/)?gemini-4-carbon
|
|
157
|
-
const hasVertexCarbon = hasModel(vertexModels, /^(?:models\/)?gemini-4-carbon
|
|
158
|
-
const hasGoogleHydrogen = hasModel(googleModels, /^(?:models\/)?gemini-4-hydrogen
|
|
159
|
-
const hasVertexHydrogen = hasModel(vertexModels, /^(?:models\/)?gemini-4-hydrogen
|
|
160
|
-
const hasGoogleNeon = hasModel(googleModels, /^(?:models\/)?gemini-4-neon
|
|
161
|
-
const hasVertexNeon = hasModel(vertexModels, /^(?:models\/)?gemini-4-neon
|
|
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)
|
|
162
205
|
const hasGoogle = hasGoogleArgon || hasGoogleCarbon || hasGoogleHydrogen || hasGoogleNeon
|
|
163
206
|
const hasVertex = hasVertexArgon || hasVertexCarbon || hasVertexHydrogen || hasVertexNeon || !hasGoogle
|
|
164
207
|
return {
|
|
@@ -333,22 +376,17 @@ export function gemini4StreamSimple(
|
|
|
333
376
|
const fallback = defaultLevel ?? (/cyber-permissive/i.test(requestModel?.id ?? '') ? 'high' : 'medium')
|
|
334
377
|
const modelId = requestModel?.id
|
|
335
378
|
const supportsXhigh = supportsXhighReasoning(modelId)
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
const
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
const mapped = requestModel?.thinkingLevelMap?.[rawLevel] ?? rawLevel
|
|
342
|
-
const level = typeof mapped === 'string' ? mapped.toLowerCase() : fallback
|
|
343
|
-
if (!levelsForModel(modelId).includes(level)) {
|
|
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)) {
|
|
344
384
|
throw new LlmError(
|
|
345
|
-
|
|
346
|
-
? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high or xhigh.'
|
|
347
|
-
: 'Gemini 4 (Argon / Carbon) requires low, medium or high.',
|
|
385
|
+
`Model ${modelId ?? MODEL} does not support reasoning effort "${rawLevel}".`,
|
|
348
386
|
'UNSUPPORTED_REASONING_EFFORT',
|
|
349
387
|
)
|
|
350
388
|
}
|
|
351
|
-
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
|
|
352
390
|
const requestedMaxTokens = options.maxTokens ?? requestModel.maxTokens
|
|
353
391
|
const effectiveMaxTokens =
|
|
354
392
|
longDecode === false && typeof requestedMaxTokens === 'number' && requestedMaxTokens > MAX_SINGLE_CALL_TOKENS
|
|
@@ -400,6 +438,18 @@ export function gemini4StreamSimple(
|
|
|
400
438
|
cleanConfig.httpOptions && typeof cleanConfig.httpOptions === 'object' && !Array.isArray(cleanConfig.httpOptions)
|
|
401
439
|
? cleanConfig.httpOptions
|
|
402
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
|
+
}
|
|
403
453
|
const toolMode = shouldFallbackToAutoToolMode(retryKey) ? 'AUTO' : 'VALIDATED'
|
|
404
454
|
return {
|
|
405
455
|
...body,
|
|
@@ -415,8 +465,8 @@ export function gemini4StreamSimple(
|
|
|
415
465
|
automaticContinuation: false,
|
|
416
466
|
thinkingConfig: { thinkingLevel: level.toUpperCase(), includeThoughts: true },
|
|
417
467
|
httpOptions: {
|
|
418
|
-
...
|
|
419
|
-
...(Object.keys(servicePolicy.headers).length ? { headers: mergeServiceHeaders(
|
|
468
|
+
...sanitizedHttpOptions,
|
|
469
|
+
...(Object.keys(servicePolicy.headers).length ? { headers: mergeServiceHeaders(sanitizedHttpOptions.headers, servicePolicy) } : {}),
|
|
420
470
|
[ARGON_LONG_DECODE_SYMBOL]: {
|
|
421
471
|
enabled: longDecode !== false,
|
|
422
472
|
serviceTier: requestModel.api === 'google-generative-ai' ? servicePolicy.tier : undefined,
|
|
@@ -438,39 +488,67 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
|
|
|
438
488
|
const proto = PiAiAdapter?.prototype
|
|
439
489
|
if (!proto || typeof proto.current !== 'function') return unpatchApiClient
|
|
440
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
|
|
441
493
|
const patchedProviders = new Map()
|
|
442
494
|
let active = true
|
|
443
495
|
const ensureGemini4Capabilities = piProvider => {
|
|
444
496
|
if (typeof piProvider?.getModels !== 'function') return
|
|
445
497
|
try {
|
|
446
498
|
for (const m of piProvider.getModels()) {
|
|
447
|
-
if (isGemini4Model(m)
|
|
448
|
-
|
|
449
|
-
|
|
499
|
+
if (isGemini4Model(m)) {
|
|
500
|
+
try {
|
|
501
|
+
m.reasoning = true
|
|
502
|
+
m.thinkingLevelMap = { ...thinkingLevelMapFor(m.id) }
|
|
503
|
+
} catch {}
|
|
450
504
|
}
|
|
451
505
|
}
|
|
452
506
|
} catch {}
|
|
453
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
|
+
}
|
|
454
519
|
const wrapProvider = (piProvider, defaultReasoning) => {
|
|
455
520
|
if (!piProvider || typeof piProvider.streamSimple !== 'function' || typeof piProvider.stream !== 'function') return
|
|
456
521
|
ensureGemini4Capabilities(piProvider)
|
|
457
522
|
if (piProvider.id === PROVIDER || patchedProviders.has(piProvider)) return
|
|
523
|
+
const origStream = piProvider.stream
|
|
458
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
|
+
}
|
|
459
534
|
function patchedStreamSimple(requestModel, context, options = {}) {
|
|
460
|
-
if (active && isGemini4Model(requestModel))
|
|
461
|
-
const cfg = resolveConfigValues(configInput)
|
|
462
|
-
return gemini4StreamSimple(
|
|
463
|
-
(m, c, o) => piProvider.stream(m, c, o), requestModel, context, options,
|
|
464
|
-
defaultReasoning, requestModel.id, cfg.longDecode, recordDiagnostic,
|
|
465
|
-
resolveServicePolicy(cfg, requestModel.api, 'generate-content'),
|
|
466
|
-
{ responseHub, retainRawResponses: cfg.retainRawResponses },
|
|
467
|
-
)
|
|
468
|
-
}
|
|
535
|
+
if (active && isGemini4Model(requestModel)) return dispatchGemini4(requestModel, context, options)
|
|
469
536
|
return origStreamSimple.call(this, requestModel, context, options)
|
|
470
537
|
}
|
|
471
|
-
|
|
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
|
|
472
544
|
piProvider.streamSimple = patchedStreamSimple
|
|
473
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)
|
|
474
552
|
function patchedCurrent() {
|
|
475
553
|
const snapshot = origCurrent.call(this)
|
|
476
554
|
if (active && snapshot?.profiles instanceof Map) {
|
|
@@ -480,13 +558,36 @@ export function installGemini4PiAiPatch(recordDiagnostic, configInput = {}, resp
|
|
|
480
558
|
}
|
|
481
559
|
return snapshot
|
|
482
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
|
+
}
|
|
483
579
|
proto.current = patchedCurrent
|
|
580
|
+
if (origPrepareCall) proto.prepareCall = patchedPrepareCall
|
|
581
|
+
if (origProtoStream) proto.stream = patchedProtoStream
|
|
484
582
|
return () => {
|
|
485
583
|
if (!active) return
|
|
486
584
|
active = false
|
|
487
585
|
unpatchApiClient()
|
|
488
586
|
if (proto.current === patchedCurrent) proto.current = origCurrent
|
|
489
|
-
|
|
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
|
|
490
591
|
if (piProvider.streamSimple === patchedStreamSimple) piProvider.streamSimple = origStreamSimple
|
|
491
592
|
}
|
|
492
593
|
patchedProviders.clear()
|
|
@@ -624,11 +725,15 @@ export class ArgonAdapter extends LlmAdapter {
|
|
|
624
725
|
if (provider === PROVIDER && cfg) resolveServicePolicy(cfg, googleApi ? 'google-generative-ai' : 'google-vertex', protocol)
|
|
625
726
|
const prepared = await this.inner.prepareCall(provider, model, signal)
|
|
626
727
|
if (provider === PROVIDER && protocol === 'interactions' && this.interactionHandler) {
|
|
627
|
-
return {
|
|
728
|
+
return {
|
|
729
|
+
model: prepared.model,
|
|
730
|
+
stream: options => this.interactionHandler(narrowMaxReasoning(pinPreparedOptions(options, provider, model), model), cfg),
|
|
731
|
+
}
|
|
628
732
|
}
|
|
629
|
-
return { ...prepared, stream: options => prepared.stream(generateContentHistory(
|
|
733
|
+
return { ...prepared, stream: options => prepared.stream(generateContentHistory(preparePinnedStreamOptions(options, provider, model), model)) }
|
|
630
734
|
}
|
|
631
735
|
async *stream(options) {
|
|
736
|
+
assertPlainRequestOptions(options)
|
|
632
737
|
const prepared = await this.prepareCall(options.provider, options.model, options.signal)
|
|
633
738
|
yield* prepared.stream(options)
|
|
634
739
|
}
|
package/google-signatures.js
CHANGED
|
@@ -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
|
-
//
|
|
27
|
-
|
|
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
|
|
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.
|
|
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/interaction-adapter.js
CHANGED
|
@@ -4,21 +4,22 @@ import { durableInteractionTransport } from './interaction-state.js'
|
|
|
4
4
|
import { createArgonDiagnosticTracker } from './diagnostics.js'
|
|
5
5
|
import { interactionExitReason } from './interaction-lifecycle.js'
|
|
6
6
|
import { resolveServicePolicy } from './service-level.js'
|
|
7
|
+
import { resolveGemini4ReasoningLevel } from './interactions-input.js'
|
|
7
8
|
// 循环导入:adapter.js 只在本模块的函数被调用时才读取这些绑定,函数声明本身已提升。
|
|
8
|
-
import { isGoogleApiModel, officialUpstreamModel
|
|
9
|
+
import { isGoogleApiModel, officialUpstreamModel } from './adapter.js'
|
|
9
10
|
|
|
10
11
|
const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'failed', 'cancelled', 'budget_exceeded'])
|
|
11
12
|
export function assertInteractionOptions(options, cfg, route) {
|
|
12
13
|
const max = options.maxTokens ?? cfg.maxTokens
|
|
13
14
|
if (!Number.isSafeInteger(max) || max <= 0 || max > cfg.maxTokens) throw new Error('Interactions output budget must be a positive integer within the configured effective cap.')
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
throw new Error(xhighSupported ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
|
|
15
|
+
const resolvedReasoning = resolveGemini4ReasoningLevel(options, options.model, cfg.reasoning)
|
|
16
|
+
if (!resolvedReasoning.ok) {
|
|
17
|
+
if (resolvedReasoning.errorType === 'conflict') {
|
|
18
|
+
throw new Error('Conflicting reasoning and reasoningEffort options in Interactions request.')
|
|
19
|
+
}
|
|
20
|
+
throw new Error(resolvedReasoning.supportsXhigh ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
|
|
21
21
|
}
|
|
22
|
+
const level = resolvedReasoning.level
|
|
22
23
|
if (cfg.interactionsBackground && !cfg.allowInteractionStorage) throw new Error('Background Interactions requires explicit cloud-storage consent in Gemini 4 Adapter settings.')
|
|
23
24
|
if (max > 65536 && !cfg.interactionsBackground) throw new Error('Interactions above 65,536 tokens requires background execution; no request was sent.')
|
|
24
25
|
if (route === 'google-vertex' && max > 65536) throw new Error('Vertex Interactions long decode is not verified; choose GenerateContent or explicitly lower the budget to 65,536.')
|
|
@@ -86,6 +87,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
|
|
|
86
87
|
}
|
|
87
88
|
try {
|
|
88
89
|
signal.throwIfAborted()
|
|
90
|
+
const upstreamModel = officialUpstreamModel(options.model)
|
|
89
91
|
const controls = assertInteractionOptions(options, cfg, route)
|
|
90
92
|
const servicePolicy = resolveServicePolicy(cfg, route, 'interactions')
|
|
91
93
|
if (cfg.interactionsBackground) taskHub?.requireReady()
|
|
@@ -160,7 +162,7 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
|
|
|
160
162
|
return block
|
|
161
163
|
}) }))
|
|
162
164
|
const { streamInteractions } = await import('./interactions.js')
|
|
163
|
-
for await (const chunk of streamInteractions({ ...options, messages, signal }, { route, upstreamModel
|
|
165
|
+
for await (const chunk of streamInteractions({ ...options, messages, signal }, { route, upstreamModel, ...controls, serviceTier: route === 'google-generative-ai' ? servicePolicy.tier : undefined, background: cfg.interactionsBackground, store: cfg.allowInteractionStorage, transport, resolveImage, structuredOutput, onEvent: observed, onReconnectDelay: ms => { pendingBackoffMs = ms }, onTerminal: () => { complete = true }, onExit: reason => { exitReason = reason } })) {
|
|
164
166
|
if (chunk.type === 'usage') {
|
|
165
167
|
recordUsage()
|
|
166
168
|
// Only an observed first-hop input watermark can be normalized for the
|
package/interactions-input.js
CHANGED
|
@@ -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
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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
|
-
|
|
74
|
-
|
|
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]:[],
|
|
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
|
-
|
|
101
|
-
if(!native
|
|
102
|
-
|
|
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
|
|
116
|
-
if(mode==='native')input.push({type:'function_result',call_id:message.toolCallId,name:
|
|
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:
|
|
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
|
|
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'
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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)
|
|
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
|
-
|
|
196
|
-
|
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-vertex-argon",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.1",
|
|
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": {
|