dsh-vertex-argon 2.2.6 → 2.2.8
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 +26 -0
- package/README.md +1 -1
- package/adapter.js +41 -14
- package/generate-content.js +56 -7
- package/google-signatures.js +59 -10
- package/interactions.js +37 -21
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,32 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to **Gemini 4 Adapter** (`dsh-vertex-argon`) are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [2.2.8] - 2026-11-19
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- **Strict Candidate Part Prototype, Empty-Key & Same-Part Dual Signature Rejection (`google-signatures.js`)**:
|
|
9
|
+
- Rejected dual `thoughtSignature` + `thought_signature` and dual `id` + `call_id` unconditionally even when values match, checked invalid call keys by array length (catching `""` keys), and enforced plain-object (`Object.prototype` / `null`) checks on parts, `functionCall` payloads, and `call.args`.
|
|
10
|
+
- **Indexed Snapshot Rollback for Unindexed Interactions Deltas (`interactions.js`)**:
|
|
11
|
+
- Captured an indexed state snapshot after each event carrying a valid `event_id` and restored it before reconnecting with `last_event_id`, preventing un-indexed `function_call` argument deltas prior to a stream drop from duplicating on replay while preserving cursorless retry bounds.
|
|
12
|
+
- **Request-Wide Committed Prefix & Accountable Budget Guards on Thinking-Dropout Heal (`generate-content.js`)**:
|
|
13
|
+
- Tracked request-wide `anyCommittedVisibleOrTool` across hops so synthetic (`!hopToken`) `thinking-dropout-heal` never replays without prior committed text/tool calls, and required accountable non-null output token usage before consuming remaining `maxOutputTokens` on synthetic heal.
|
|
14
|
+
- **Array Sparse-Hole / Symbol Deep-Freeze & Explicit `functionCallingConfig.mode` Preservation (`adapter.js`)**:
|
|
15
|
+
- Updated `deepFreezeClone` to preserve sparse array holes, custom array properties, and array Symbol keys via `new Array(length)` + `Reflect.ownKeys`, and preserved caller-specified `functionCallingConfig.mode` (such as `'NONE'` and `'ANY'`) instead of overwriting with `'VALIDATED'`.
|
|
16
|
+
|
|
17
|
+
## [2.2.7] - 2026-11-19
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
- **Same-Chunk Part Splitting & Dual-Key Field Validation (`google-signatures.js`)**:
|
|
21
|
+
- Split subsequent `text` / `thinking` parts within the same candidate `parts` array even when neither carries a `thoughtSignature`, aligning streaming and non-streaming block counts 1:1.
|
|
22
|
+
- Enforced strict individual validation on `thoughtSignature` / `thought_signature` and `functionCall` / `function_call` (rejecting empty/`null`/conflicting dual spellings, missing or empty `functionCall.name`, unsupported keys outside `name`/`args`/`id`/`call_id`, non-plain-object `args`, and conflicting `id`/`call_id`).
|
|
23
|
+
- **Unindexed Visible Interactions Frame Guard (`interactions.js`)**:
|
|
24
|
+
- Tracked un-indexed visible output (`unindexedVisibleOutput`) even after an earlier `event_id`, failing closed instead of replaying from an older cursor unless a subsequent `event_id` advances `lastEventId`.
|
|
25
|
+
- **Pre-Handler Interactions Reasoning Validation & Recursive Descriptor Freeze (`adapter.js`)**:
|
|
26
|
+
- Validated `resolveGemini4ReasoningLevel` inside `ArgonAdapter.prepareCall` before invoking custom `interactionHandler` instances, returning an in-band `{ type: 'finish', reason: { kind: 'error' } }` frame on invalid or conflicting options.
|
|
27
|
+
- Upgraded `freezeDescriptor` to recursive `deepFreezeClone` across nested objects, arrays, and symbol properties.
|
|
28
|
+
- **Thinking-Dropout Heal Token Budget Deduction (`generate-content.js`)**:
|
|
29
|
+
- Evaluated Hop 1 usage before deciding `hideStop` / `canHeal()` and deducted Hop 1 spent candidate + thought tokens from `maxOutputTokens` / `max_output_tokens` across both `request.body` and cloned `httpOptions.extraBody` on synthetic (`!hopToken`) replay hops (refusing synthetic healing when no budget remains), while leaving checkpointed `hopToken` requests untouched.
|
|
30
|
+
|
|
5
31
|
## [2.2.6] - 2026-11-19
|
|
6
32
|
|
|
7
33
|
### 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.
|
|
7
|
+
- **当前版本**:`2.2.8`([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
|
@@ -605,6 +605,13 @@ export function gemini4StreamSimple(
|
|
|
605
605
|
: (cleanConfig.max_output_tokens !== undefined ? cleanConfig.max_output_tokens : (effectiveMaxTokens ?? outboundCeiling))
|
|
606
606
|
delete cleanConfig.max_output_tokens
|
|
607
607
|
const toolMode = shouldFallbackToAutoToolMode(retryKey) ? 'AUTO' : 'VALIDATED'
|
|
608
|
+
const rawExistingMode = cleanConfig.toolConfig?.functionCallingConfig?.mode
|
|
609
|
+
const existingModeUpper = typeof rawExistingMode === 'string' ? rawExistingMode.trim().toUpperCase() : ''
|
|
610
|
+
const preserveCallerMode =
|
|
611
|
+
existingModeUpper === 'NONE' ||
|
|
612
|
+
existingModeUpper === 'ANY' ||
|
|
613
|
+
(existingModeUpper !== '' && existingModeUpper !== 'VALIDATED')
|
|
614
|
+
const effectiveToolMode = preserveCallerMode ? rawExistingMode : toolMode
|
|
608
615
|
return {
|
|
609
616
|
...body,
|
|
610
617
|
model: upstreamModelId,
|
|
@@ -614,7 +621,7 @@ export function gemini4StreamSimple(
|
|
|
614
621
|
...(cleanConfig.tools?.some(tool => tool.functionDeclarations?.length) ? {
|
|
615
622
|
toolConfig: {
|
|
616
623
|
...cleanConfig.toolConfig,
|
|
617
|
-
functionCallingConfig: { ...cleanConfig.toolConfig?.functionCallingConfig, mode:
|
|
624
|
+
functionCallingConfig: { ...cleanConfig.toolConfig?.functionCallingConfig, mode: effectiveToolMode },
|
|
618
625
|
},
|
|
619
626
|
} : {}),
|
|
620
627
|
automaticContinuation: false,
|
|
@@ -852,24 +859,33 @@ export function resolveConfigValues(raw = {}) {
|
|
|
852
859
|
}
|
|
853
860
|
}
|
|
854
861
|
|
|
855
|
-
function
|
|
856
|
-
if (!
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
862
|
+
export function deepFreezeClone(value, seen = new WeakMap()) {
|
|
863
|
+
if (!value || typeof value !== 'object') return value
|
|
864
|
+
if (seen.has(value)) return seen.get(value)
|
|
865
|
+
if (Array.isArray(value)) {
|
|
866
|
+
const arr = new Array(value.length)
|
|
867
|
+
seen.set(value, arr)
|
|
868
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
869
|
+
if (key === 'length') continue
|
|
870
|
+
arr[key] = deepFreezeClone(value[key], seen)
|
|
871
|
+
}
|
|
872
|
+
return Object.freeze(arr)
|
|
866
873
|
}
|
|
867
|
-
|
|
868
|
-
|
|
874
|
+
const copy = {}
|
|
875
|
+
seen.set(value, copy)
|
|
876
|
+
for (const key of Object.keys(value)) {
|
|
877
|
+
copy[key] = deepFreezeClone(value[key], seen)
|
|
878
|
+
}
|
|
879
|
+
for (const sym of Object.getOwnPropertySymbols(value)) {
|
|
880
|
+
copy[sym] = deepFreezeClone(value[sym], seen)
|
|
869
881
|
}
|
|
870
882
|
return Object.freeze(copy)
|
|
871
883
|
}
|
|
872
884
|
|
|
885
|
+
function freezeDescriptor(descriptor) {
|
|
886
|
+
return deepFreezeClone(descriptor)
|
|
887
|
+
}
|
|
888
|
+
|
|
873
889
|
/** Serve the official Vertex AI and Gemini API models in one plugin group. */
|
|
874
890
|
export function argonProvider(nativeVertex, models, defaultLevel = undefined, nativeGoogle = googleProvider(), longDecode = true, recordDiagnostic, serviceConfig = {}, responseHub, structuredOutput) {
|
|
875
891
|
const frozenModels = (Array.isArray(models) ? models : [models]).map(freezeDescriptor)
|
|
@@ -978,6 +994,17 @@ export class ArgonAdapter extends LlmAdapter {
|
|
|
978
994
|
stream: options => {
|
|
979
995
|
const pinned = pinPreparedOptions(options, provider, model)
|
|
980
996
|
assertGemini4MaxTokens(pinned, resolvedModel, cfg?.longDecode)
|
|
997
|
+
const defaultReasoning = cfg?.hasExplicitReasoning === false ? defaultReasoningForModel(model) : (cfg?.reasoning ?? defaultReasoningForModel(model))
|
|
998
|
+
const check = resolveGemini4ReasoningLevel(pinned, model, defaultReasoning)
|
|
999
|
+
if (!check.ok) {
|
|
1000
|
+
const message = check.errorType === 'conflict'
|
|
1001
|
+
? 'Conflicting reasoning and reasoningEffort options in Interactions request.'
|
|
1002
|
+
: (check.supportsXhigh ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
|
|
1003
|
+
const code = check.errorType === 'conflict' ? 'INVALID_REQUEST' : 'UNSUPPORTED_REASONING_EFFORT'
|
|
1004
|
+
return (async function* () {
|
|
1005
|
+
yield { type: 'finish', reason: { kind: 'error', failure: { code, message } } }
|
|
1006
|
+
})()
|
|
1007
|
+
}
|
|
981
1008
|
return this.interactionHandler(syncGemini4ReasoningOptions(pinned, model), cfg)
|
|
982
1009
|
},
|
|
983
1010
|
}
|
package/generate-content.js
CHANGED
|
@@ -222,6 +222,14 @@ export async function continueArgonRequestStream(apiClient, original, request, m
|
|
|
222
222
|
return (async function* () {
|
|
223
223
|
const baseBody = JSON.parse(request.body)
|
|
224
224
|
let initialBody = request.body
|
|
225
|
+
const readMaxBudget = obj => {
|
|
226
|
+
for (const cfgObj of [obj?.generationConfig, obj?.generation_config]) {
|
|
227
|
+
const val = cfgObj?.maxOutputTokens ?? cfgObj?.max_output_tokens
|
|
228
|
+
if (Number.isSafeInteger(val) && val > 0) return val
|
|
229
|
+
}
|
|
230
|
+
return undefined
|
|
231
|
+
}
|
|
232
|
+
const initialMaxOutputTokens = readMaxBudget(httpOptions.extraBody) ?? readMaxBudget(baseBody)
|
|
225
233
|
// Google documents a top-level service_tier. Apply after SDK conversion so
|
|
226
234
|
// older converters cannot silently discard it; every hop uses this snapshot.
|
|
227
235
|
if (!apiClient.isVertexAI?.() && meta.serviceTier !== undefined) {
|
|
@@ -243,6 +251,7 @@ export async function continueArgonRequestStream(apiClient, original, request, m
|
|
|
243
251
|
let initialPrompt, initialCached
|
|
244
252
|
let initialUsageLocked = false
|
|
245
253
|
let thinkingDropoutHeals = 0
|
|
254
|
+
let anyCommittedVisibleOrTool = false
|
|
246
255
|
const totals = Object.fromEntries(fields.map(key => [key, 0]))
|
|
247
256
|
const billed = Object.fromEntries(fields.map(key => [key, 0]))
|
|
248
257
|
|
|
@@ -259,7 +268,22 @@ export async function continueArgonRequestStream(apiClient, original, request, m
|
|
|
259
268
|
let blocked = false, terminal = false, streamSettled = false, usageAccounted = false
|
|
260
269
|
let hopChunks = 0, hopSawThought = false, hopSawVisibleOrTool = false
|
|
261
270
|
let thoughtParts = [], thoughtBytes = 0, suppressedStop = false, hopToken
|
|
262
|
-
const
|
|
271
|
+
const accountableHopOutputSpent = () => {
|
|
272
|
+
if (!latestUsage || latestUsage.candidatesTokenCount === null || latestUsage.thoughtsTokenCount === null || latestUsage.totalTokenCount === null) return null
|
|
273
|
+
const explicitThoughts = Number.isSafeInteger(latestUsage.thoughtsTokenCount)
|
|
274
|
+
const derivedFromTotal = Number.isSafeInteger(latestUsage.totalTokenCount) && Number.isSafeInteger(latestUsage.promptTokenCount)
|
|
275
|
+
? Math.max(0, latestUsage.totalTokenCount - latestUsage.promptTokenCount - value(latestUsage, 'toolUsePromptTokenCount'))
|
|
276
|
+
: null
|
|
277
|
+
if (!explicitThoughts && derivedFromTotal === null) return null
|
|
278
|
+
return Math.max(value(latestUsage, 'candidatesTokenCount') + value(latestUsage, 'thoughtsTokenCount'), derivedFromTotal ?? 0)
|
|
279
|
+
}
|
|
280
|
+
const remainingHealBudget = () => {
|
|
281
|
+
if (initialMaxOutputTokens === undefined) return Infinity
|
|
282
|
+
const currentHopSpent = usageAccounted ? 0 : accountableHopOutputSpent()
|
|
283
|
+
if (currentHopSpent === null) return 0
|
|
284
|
+
return initialMaxOutputTokens - (billed.candidatesTokenCount + billed.thoughtsTokenCount + currentHopSpent)
|
|
285
|
+
}
|
|
286
|
+
const canHeal = () => enabled && thinkingDropoutHeals < MAX_THINKING_DROPOUT_HEALS && hopSawThought && !hopSawVisibleOrTool && !blocked && finishReason === 'STOP' && (Boolean(hopToken) || (!anyCommittedVisibleOrTool && !startToken && remainingHealBudget() > 0))
|
|
263
287
|
|
|
264
288
|
const wrap = (raw, headers, usageSnapshot, hideStop = false) => {
|
|
265
289
|
let out = raw
|
|
@@ -349,8 +373,9 @@ export async function continueArgonRequestStream(apiClient, original, request, m
|
|
|
349
373
|
}
|
|
350
374
|
const candidate = raw.candidates?.[0]
|
|
351
375
|
const parts = candidate?.content?.parts ?? []
|
|
376
|
+
const chunkHasVisibleOrTool = parts.some(part => Boolean(part.functionCall || part.function_call || (!part.thought && typeof part.text === 'string' && part.text.length > 0)))
|
|
352
377
|
hopSawThought ||= parts.some(part => part.thought === true)
|
|
353
|
-
hopSawVisibleOrTool ||=
|
|
378
|
+
hopSawVisibleOrTool ||= chunkHasVisibleOrTool
|
|
354
379
|
if (hopSawVisibleOrTool) { thoughtParts = []; thoughtBytes = 0 }
|
|
355
380
|
else if (enabled && thinkingDropoutHeals < MAX_THINKING_DROPOUT_HEALS) {
|
|
356
381
|
for (const part of parts) if (part.thought === true || part.thoughtSignature || part.thought_signature) {
|
|
@@ -368,24 +393,25 @@ export async function continueArgonRequestStream(apiClient, original, request, m
|
|
|
368
393
|
// continuation token, a repeated finishReason or an empty thought frame
|
|
369
394
|
// must never extend a stalled hop.
|
|
370
395
|
watchdog.update(parts, Boolean(newCheckpoint || (candidate?.finishReason !== undefined && candidate.finishReason !== finishReason) || (!blocked && raw.promptFeedback?.blockReason)))
|
|
396
|
+
if (raw.usageMetadata && typeof raw.usageMetadata === 'object') latestUsage = readUsage(raw.usageMetadata, latestUsage)
|
|
371
397
|
if (candidate?.finishReason !== undefined) finishReason = candidate.finishReason
|
|
372
398
|
blocked ||= Boolean(raw.promptFeedback?.blockReason)
|
|
373
399
|
terminal ||= blocked || (finishReason !== undefined && finishReason !== 'CONTINUATION')
|
|
374
400
|
const hideStop = candidate?.finishReason === 'STOP' && canHeal()
|
|
375
401
|
if (candidate?.finishReason !== undefined && candidate.finishReason !== 'CONTINUATION') suppressedStop = hideStop
|
|
376
402
|
hopTracker?.onChunk({ status: 200, hasCheckpoint: hasToken, finishReason: candidate?.finishReason })
|
|
377
|
-
if (raw.usageMetadata && typeof raw.usageMetadata === 'object') latestUsage = readUsage(raw.usageMetadata, latestUsage)
|
|
378
403
|
if (!enabled || (!token && !newCheckpoint && !terminal && candidate?.finishReason !== 'CONTINUATION')) {
|
|
379
404
|
refreshOriginalUsage()
|
|
380
405
|
const outgoing = wrap(raw, chunk.headers, latestUsage, hideStop)
|
|
381
406
|
committedUsage = latestUsage ? { ...latestUsage } : undefined
|
|
407
|
+
anyCommittedVisibleOrTool ||= chunkHasVisibleOrTool
|
|
382
408
|
hopChunks++
|
|
383
409
|
yield outgoing
|
|
384
410
|
continue
|
|
385
411
|
}
|
|
386
412
|
pendingBytes += Buffer.byteLength(JSON.stringify(raw))
|
|
387
413
|
if (pendingBytes > MAX_PENDING_BYTES) throw streamError('Argon uncommitted stream exceeded the bounded checkpoint buffer.', 'ARGON_BUFFER_LIMIT')
|
|
388
|
-
pending.push({ raw, headers: chunk.headers, usage: latestUsage ? { ...latestUsage } : undefined, hideStop })
|
|
414
|
+
pending.push({ raw, headers: chunk.headers, usage: latestUsage ? { ...latestUsage } : undefined, hideStop, hasVisibleOrTool: chunkHasVisibleOrTool })
|
|
389
415
|
pendingHasContent ||= parts.some(part => typeof part.text === 'string' ? part.text.length > 0 || Boolean(part.thoughtSignature || part.thought_signature) : Object.keys(part).length > 0)
|
|
390
416
|
const finalMetadata = finishReason === 'CONTINUATION' && token && token !== startToken && !pendingHasContent
|
|
391
417
|
if (newCheckpoint || terminal || finalMetadata) {
|
|
@@ -397,6 +423,7 @@ export async function continueArgonRequestStream(apiClient, original, request, m
|
|
|
397
423
|
throwIfAborted(request.abortSignal)
|
|
398
424
|
const outgoing = wrap(saved.raw, saved.headers, saved.usage, saved.hideStop)
|
|
399
425
|
committedUsage = saved.usage
|
|
426
|
+
anyCommittedVisibleOrTool ||= saved.hasVisibleOrTool
|
|
400
427
|
hopChunks++
|
|
401
428
|
yield outgoing
|
|
402
429
|
}
|
|
@@ -427,15 +454,37 @@ export async function continueArgonRequestStream(apiClient, original, request, m
|
|
|
427
454
|
}
|
|
428
455
|
if (terminal) {
|
|
429
456
|
if (!failure && canHeal()) {
|
|
457
|
+
const priorBilledOutput = billed.candidatesTokenCount + billed.thoughtsTokenCount
|
|
458
|
+
const hopOutputSpent = accountableHopOutputSpent() ?? 0
|
|
430
459
|
accountUsage()
|
|
431
460
|
hopTracker?.finish({ finishReason, continued: true })
|
|
432
461
|
if (hop === MAX_CONTINUATION_HOPS) throw streamError('Argon continuation hop limit reached without a terminal response.', 'ARGON_HOP_LIMIT')
|
|
433
462
|
thinkingDropoutHeals++
|
|
434
|
-
if (hopToken)
|
|
435
|
-
|
|
463
|
+
if (hopToken) {
|
|
464
|
+
token = hopToken
|
|
465
|
+
} else {
|
|
436
466
|
token = undefined
|
|
467
|
+
const remainingBudget = initialMaxOutputTokens === undefined ? undefined : initialMaxOutputTokens - (priorBilledOutput + hopOutputSpent)
|
|
468
|
+
const withRemainingBudget = bodyObj => {
|
|
469
|
+
if (remainingBudget === undefined) return bodyObj
|
|
470
|
+
const updateCfg = cfgObj => {
|
|
471
|
+
if (!cfgObj || typeof cfgObj !== 'object' || Array.isArray(cfgObj)) return cfgObj
|
|
472
|
+
const nextCfg = { ...cfgObj }
|
|
473
|
+
if ('maxOutputTokens' in nextCfg) nextCfg.maxOutputTokens = remainingBudget
|
|
474
|
+
if ('max_output_tokens' in nextCfg) nextCfg.max_output_tokens = remainingBudget
|
|
475
|
+
return nextCfg
|
|
476
|
+
}
|
|
477
|
+
return {
|
|
478
|
+
...bodyObj,
|
|
479
|
+
...(bodyObj.generationConfig !== undefined ? { generationConfig: updateCfg(bodyObj.generationConfig) } : {}),
|
|
480
|
+
...(bodyObj.generation_config !== undefined ? { generation_config: updateCfg(bodyObj.generation_config) } : {}),
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
if (httpOptions.extraBody && typeof httpOptions.extraBody === 'object' && !Array.isArray(httpOptions.extraBody)) {
|
|
484
|
+
httpOptions.extraBody = withRemainingBudget(httpOptions.extraBody)
|
|
485
|
+
}
|
|
437
486
|
const { continuationToken: ignored, ...rest } = continuationBody
|
|
438
|
-
continuationBody = { ...rest, contents: [...(rest.contents ?? []), { role: 'model', parts: thoughtParts }, { role: 'user', parts: [{ text: 'Continue and provide the final response or tool call.' }] }] }
|
|
487
|
+
continuationBody = withRemainingBudget({ ...rest, contents: [...(rest.contents ?? []), { role: 'model', parts: thoughtParts }, { role: 'user', parts: [{ text: 'Continue and provide the final response or tool call.' }] }] })
|
|
439
488
|
}
|
|
440
489
|
retriesWithoutProgress = 0; retryAttempt = 0; delayMs = 0
|
|
441
490
|
trigger = 'thinking-dropout-heal'
|
package/google-signatures.js
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto'
|
|
2
2
|
|
|
3
3
|
const ALLOWED_PART_KEYS = new Set(['text', 'thought', 'thoughtSignature', 'thought_signature', 'functionCall', 'function_call'])
|
|
4
|
+
const ALLOWED_CALL_KEYS = new Set(['name', 'args', 'id', 'call_id'])
|
|
5
|
+
|
|
6
|
+
function isPlainRecord(value) {
|
|
7
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return false
|
|
8
|
+
const proto = Object.getPrototypeOf(value)
|
|
9
|
+
return proto === Object.prototype || proto === null
|
|
10
|
+
}
|
|
4
11
|
|
|
5
12
|
const PREFIX = '{"dshGoogleSignatureOnly":'
|
|
6
13
|
const base64 = value => typeof value === 'string' && value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value)
|
|
@@ -164,7 +171,7 @@ export function createGoogleSignatureBridge(context, model) {
|
|
|
164
171
|
seen = true
|
|
165
172
|
currentFromThisChunk = false
|
|
166
173
|
for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {
|
|
167
|
-
if (!
|
|
174
|
+
if (!isPlainRecord(part)) {
|
|
168
175
|
close()
|
|
169
176
|
throw failure('Google returned a malformed candidate part.')
|
|
170
177
|
}
|
|
@@ -175,6 +182,18 @@ export function createGoogleSignatureBridge(context, model) {
|
|
|
175
182
|
close()
|
|
176
183
|
throw failure('Google returned an unsupported candidate part (' + unsupportedKeys.join(', ') + ') that cannot be replayed.')
|
|
177
184
|
}
|
|
185
|
+
if (part.functionCall !== undefined && !isPlainRecord(part.functionCall)) {
|
|
186
|
+
close()
|
|
187
|
+
throw failure('Google returned a candidate part with an invalid functionCall payload.')
|
|
188
|
+
}
|
|
189
|
+
if (part.function_call !== undefined && !isPlainRecord(part.function_call)) {
|
|
190
|
+
close()
|
|
191
|
+
throw failure('Google returned a candidate part with an invalid functionCall payload.')
|
|
192
|
+
}
|
|
193
|
+
if (part.functionCall !== undefined && part.function_call !== undefined) {
|
|
194
|
+
close()
|
|
195
|
+
throw failure('Google returned a candidate part with both functionCall and function_call fields.')
|
|
196
|
+
}
|
|
178
197
|
const call = part.functionCall ?? part.function_call
|
|
179
198
|
const hasText = part.text !== undefined
|
|
180
199
|
const hasCall = call !== undefined
|
|
@@ -186,9 +205,32 @@ export function createGoogleSignatureBridge(context, model) {
|
|
|
186
205
|
close()
|
|
187
206
|
throw failure('Google returned a candidate part with an invalid text field.')
|
|
188
207
|
}
|
|
189
|
-
if (hasCall
|
|
190
|
-
|
|
191
|
-
|
|
208
|
+
if (hasCall) {
|
|
209
|
+
const invalidCallKeys = Object.keys(call).filter(key => call[key] !== undefined && !ALLOWED_CALL_KEYS.has(key))
|
|
210
|
+
if (invalidCallKeys.length > 0) {
|
|
211
|
+
close()
|
|
212
|
+
throw failure('Google returned a candidate part with an unsupported functionCall field (' + JSON.stringify(invalidCallKeys[0]) + ').')
|
|
213
|
+
}
|
|
214
|
+
if (typeof call.name !== 'string' || !call.name) {
|
|
215
|
+
close()
|
|
216
|
+
throw failure('Google returned a candidate part with an invalid functionCall name.')
|
|
217
|
+
}
|
|
218
|
+
if (call.args !== undefined && !isPlainRecord(call.args)) {
|
|
219
|
+
close()
|
|
220
|
+
throw failure('Google returned a candidate part with an invalid functionCall args payload.')
|
|
221
|
+
}
|
|
222
|
+
if (call.id !== undefined && (typeof call.id !== 'string' || !call.id)) {
|
|
223
|
+
close()
|
|
224
|
+
throw failure('Google returned a candidate part with an invalid functionCall id.')
|
|
225
|
+
}
|
|
226
|
+
if (call.call_id !== undefined && (typeof call.call_id !== 'string' || !call.call_id)) {
|
|
227
|
+
close()
|
|
228
|
+
throw failure('Google returned a candidate part with an invalid functionCall call_id.')
|
|
229
|
+
}
|
|
230
|
+
if (call.id !== undefined && call.call_id !== undefined) {
|
|
231
|
+
close()
|
|
232
|
+
throw failure('Google returned a candidate part with both functionCall id and call_id fields.')
|
|
233
|
+
}
|
|
192
234
|
}
|
|
193
235
|
if (hasText && hasCall) {
|
|
194
236
|
close()
|
|
@@ -200,12 +242,20 @@ export function createGoogleSignatureBridge(context, model) {
|
|
|
200
242
|
}
|
|
201
243
|
bytes += Buffer.byteLength(JSON.stringify(part))
|
|
202
244
|
if (bytes > 64 * 1024 * 1024) throw failure('Google response exceeded the bounded signature replay buffer.')
|
|
203
|
-
// A Part may serialize the signature in either wire spelling.
|
|
204
|
-
|
|
205
|
-
|
|
245
|
+
// A Part may serialize the signature in either wire spelling, but never both on one Part.
|
|
246
|
+
if (part.thoughtSignature !== undefined && (typeof part.thoughtSignature !== 'string' || !part.thoughtSignature)) {
|
|
247
|
+
close()
|
|
248
|
+
throw failure('Google returned a candidate part with an invalid thoughtSignature.')
|
|
249
|
+
}
|
|
250
|
+
if (part.thought_signature !== undefined && (typeof part.thought_signature !== 'string' || !part.thought_signature)) {
|
|
206
251
|
close()
|
|
207
252
|
throw failure('Google returned a candidate part with an invalid thoughtSignature.')
|
|
208
253
|
}
|
|
254
|
+
if (part.thoughtSignature !== undefined && part.thought_signature !== undefined) {
|
|
255
|
+
close()
|
|
256
|
+
throw failure('Google returned a candidate part with both thoughtSignature and thought_signature fields.')
|
|
257
|
+
}
|
|
258
|
+
const sig = part.thoughtSignature ?? part.thought_signature
|
|
209
259
|
const onlySignature = typeof sig === 'string' && !hasText && !hasCall
|
|
210
260
|
if (onlySignature) {
|
|
211
261
|
if (!sig) {
|
|
@@ -225,13 +275,12 @@ export function createGoogleSignatureBridge(context, model) {
|
|
|
225
275
|
const sigKey = type === 'text' ? 'textSignature' : 'thinkingSignature'
|
|
226
276
|
const curText = type === 'text' ? current?.text : current?.thinking
|
|
227
277
|
const curSig = current?.[sigKey]
|
|
228
|
-
const sameChunkSigBoundary = currentFromThisChunk && (Boolean(curSig) || Boolean(sig))
|
|
229
278
|
const crossChunkSigConflict =
|
|
230
279
|
(Boolean(curSig) && Boolean(sig)) ||
|
|
231
280
|
(Boolean(curSig) && curText === '') ||
|
|
232
281
|
(Boolean(sig) && part.text === '')
|
|
233
|
-
const
|
|
234
|
-
if (!current || current.type !== type ||
|
|
282
|
+
const splitPart = currentFromThisChunk || crossChunkSigConflict
|
|
283
|
+
if (!current || current.type !== type || splitPart) {
|
|
235
284
|
close(); current = type === 'text' ? { type, text: '' } : { type, thinking: '' }
|
|
236
285
|
const index = start(current)
|
|
237
286
|
emit({ type: type === 'text' ? 'text_start' : 'thinking_start', contentIndex: index })
|
package/interactions.js
CHANGED
|
@@ -29,20 +29,24 @@ export async function* streamInteractions(options, settings) {
|
|
|
29
29
|
const signal=options.signal, transport=settings.transport
|
|
30
30
|
const steps=new Map(), blocks=new Map(), seenEvents=new Set(), emittedToolIds=new Set()
|
|
31
31
|
let exitReason='consumer-abandoned'
|
|
32
|
-
let blockIndex=0, bytes=0, interactionId, lastEventId, status, usage, cancelled=false, finishedNormally=false, emitted=false, completedEvent=false, progressVersion=0
|
|
32
|
+
let blockIndex=0, bytes=0, interactionId, lastEventId, status, usage, cancelled=false, finishedNormally=false, emitted=false, unindexedVisibleOutput=false, completedEvent=false, progressVersion=0, indexedSnapshot
|
|
33
|
+
const cloneStepState=state=>({...state,...(state.argsValue!==undefined?{argsValue:structuredClone(state.argsValue)}:{}),...(state.args!==undefined?{args:structuredClone(state.args)}:{})})
|
|
34
|
+
const captureSnapshot=()=>({steps:new Map([...steps.entries()].map(([k,v])=>[k,cloneStepState(v)])),blocks:new Map([...blocks.entries()].map(([k,v])=>[k,structuredClone(v)])),blockIndex,bytes,status,usage:usage?structuredClone(usage):undefined,completedEvent})
|
|
35
|
+
const restoreSnapshot=snap=>{steps.clear();for(const[k,v]of snap.steps.entries())steps.set(k,cloneStepState(v));blocks.clear();for(const[k,v]of snap.blocks.entries())blocks.set(k,structuredClone(v));blockIndex=snap.blockIndex;bytes=snap.bytes;status=snap.status;usage=snap.usage?structuredClone(snap.usage):undefined;completedEvent=snap.completedEvent}
|
|
33
36
|
const observeUsage=event=>{const u=event.interaction?.usage??event.usage??event.metadata?.total_usage;if(validObject(u)){const before=(usage?.total_output_tokens??0)+(usage?.total_thought_tokens??0);usage={...usage,...u};if((usage.total_output_tokens??0)+(usage.total_thought_tokens??0)>before)progressVersion++}}
|
|
34
37
|
const checkBytes=text=>{bytes+=Buffer.byteLength(text??'');if(bytes>MAX_BYTES)throw protocolError('Interactions output exceeded the bounded response buffer.')}
|
|
35
|
-
function* appendText(state, text, reasoning=false) {
|
|
38
|
+
function* appendText(state, text, reasoning=false, indexed=false) {
|
|
36
39
|
if(typeof text!=='string')throw protocolError('Interactions text delta is not a string.')
|
|
37
40
|
if(!text)return
|
|
38
41
|
if(state.closed)throw protocolError('Received a delta for an already closed step.')
|
|
39
42
|
checkBytes(text)
|
|
40
43
|
if(state.blockIndex===undefined){state.blockIndex=blockIndex++;yield{type:'block-start',index:state.blockIndex,blockType:reasoning?'reasoning':'text'}}
|
|
41
|
-
state.text+=text;emitted=true;progressVersion++
|
|
44
|
+
state.text+=text;emitted=true;if(!indexed)unindexedVisibleOutput=true;progressVersion++
|
|
42
45
|
yield{type:reasoning?'reasoning-delta':'text-delta',index:state.blockIndex,text}
|
|
43
46
|
}
|
|
44
|
-
function* closeText(state) {
|
|
47
|
+
function* closeText(state, indexed=true) {
|
|
45
48
|
if(state.blockIndex!==undefined&&!state.blockClosed){
|
|
49
|
+
if(!indexed)unindexedVisibleOutput=true
|
|
46
50
|
const block={type:state.kind==='thought'?'reasoning':'text',text:state.text}
|
|
47
51
|
state.blockClosed=true;blocks.set(state.blockIndex,block)
|
|
48
52
|
yield{type:'block-end',index:state.blockIndex,block}
|
|
@@ -54,14 +58,7 @@ export async function* streamInteractions(options, settings) {
|
|
|
54
58
|
if(!state)throw protocolError('Interactions delta arrived before its step.start.')
|
|
55
59
|
return state
|
|
56
60
|
}
|
|
57
|
-
function*
|
|
58
|
-
if(!validObject(event))throw protocolError('Invalid Interactions event.')
|
|
59
|
-
if(event.event_id){
|
|
60
|
-
if(typeof event.event_id!=='string')throw protocolError('Invalid event ID.')
|
|
61
|
-
if(seenEvents.has(event.event_id))return
|
|
62
|
-
if(seenEvents.size>=MAX_EVENTS)throw protocolError('Interactions event retention limit reached.')
|
|
63
|
-
seenEvents.add(event.event_id);lastEventId=event.event_id
|
|
64
|
-
}
|
|
61
|
+
function* handleBody(event, indexed) {
|
|
65
62
|
settings.onEvent?.(event)
|
|
66
63
|
const type=event.event_type??event.type
|
|
67
64
|
const id=event.interaction?.id??event.interaction_id
|
|
@@ -109,8 +106,8 @@ export async function* streamInteractions(options, settings) {
|
|
|
109
106
|
if(!validObject(step)||!['thought','model_output','function_call'].includes(step.type))throw protocolError('Unsupported Interactions step type; this adapter executes only DSH-declared local tools.')
|
|
110
107
|
const state={kind:step.type,text:'',signature:step.signature,callId:step.id,name:step.name,argsValue:step.arguments,argsText:'',closed:false}
|
|
111
108
|
steps.set(event.index,state);progressVersion++
|
|
112
|
-
if(step.type==='model_output')for(const content of step.content??[]){if(content.type!=='text')throw protocolError('Unsupported output modality.');yield*appendText(state,content.text)}
|
|
113
|
-
if(step.type==='thought')for(const content of step.summary??[]){if(content.type==='text')yield*appendText(state,content.text,true)}
|
|
109
|
+
if(step.type==='model_output')for(const content of step.content??[]){if(content.type!=='text')throw protocolError('Unsupported output modality.');yield*appendText(state,content.text,false,indexed)}
|
|
110
|
+
if(step.type==='thought')for(const content of step.summary??[]){if(content.type==='text')yield*appendText(state,content.text,true,indexed)}
|
|
114
111
|
return
|
|
115
112
|
}
|
|
116
113
|
if(type==='step.delta'){
|
|
@@ -121,9 +118,9 @@ export async function* streamInteractions(options, settings) {
|
|
|
121
118
|
return
|
|
122
119
|
}
|
|
123
120
|
if(delta.type==='text_annotation_delta'&&state.kind==='model_output')return // additive citations; no DSH annotation block type
|
|
124
|
-
if(delta.type==='text'&&state.kind==='model_output')yield*appendText(state,delta.text)
|
|
121
|
+
if(delta.type==='text'&&state.kind==='model_output')yield*appendText(state,delta.text,false,indexed)
|
|
125
122
|
else if(delta.type==='thought_summary'&&state.kind==='thought'){
|
|
126
|
-
if(delta.content?.type==='text')yield*appendText(state,delta.content.text,true)
|
|
123
|
+
if(delta.content?.type==='text')yield*appendText(state,delta.content.text,true,indexed)
|
|
127
124
|
else if(delta.content!==undefined)throw protocolError('Unsupported thought summary modality.')
|
|
128
125
|
}else if(delta.type==='thought_signature'&&state.kind==='thought'){
|
|
129
126
|
if(typeof delta.signature!=='string')throw protocolError('Invalid thought signature.')
|
|
@@ -146,7 +143,7 @@ export async function* streamInteractions(options, settings) {
|
|
|
146
143
|
if(state.kind==='function_call'){
|
|
147
144
|
try{state.args=state.argsText?JSON.parse(state.argsText):(state.argsValue??{})}catch{state.invalidArguments=true}
|
|
148
145
|
if(!validObject(state.args))state.invalidArguments=true
|
|
149
|
-
}else yield*closeText(state)
|
|
146
|
+
}else yield*closeText(state, indexed)
|
|
150
147
|
return
|
|
151
148
|
}
|
|
152
149
|
// Usage/status extensions may be added without rendering; unknown semantic
|
|
@@ -159,6 +156,18 @@ export async function* streamInteractions(options, settings) {
|
|
|
159
156
|
}
|
|
160
157
|
throw protocolError('Unknown Interactions stream event.')
|
|
161
158
|
}
|
|
159
|
+
function* handle(event) {
|
|
160
|
+
if(!validObject(event))throw protocolError('Invalid Interactions event.')
|
|
161
|
+
const indexed=Boolean(event.event_id)
|
|
162
|
+
if(indexed){
|
|
163
|
+
if(typeof event.event_id!=='string')throw protocolError('Invalid event ID.')
|
|
164
|
+
if(seenEvents.has(event.event_id))return
|
|
165
|
+
if(seenEvents.size>=MAX_EVENTS)throw protocolError('Interactions event retention limit reached.')
|
|
166
|
+
seenEvents.add(event.event_id);lastEventId=event.event_id;unindexedVisibleOutput=false
|
|
167
|
+
}
|
|
168
|
+
yield*handleBody(event, indexed)
|
|
169
|
+
if(indexed)indexedSnapshot=captureSnapshot()
|
|
170
|
+
}
|
|
162
171
|
const cancel=async()=>{
|
|
163
172
|
if(settings.background&&interactionId&&!terminal.has(status)&&!cancelled){
|
|
164
173
|
cancelled=true // one attempt per unwind, even if confirmation fails
|
|
@@ -169,10 +178,10 @@ export async function* streamInteractions(options, settings) {
|
|
|
169
178
|
signal?.throwIfAborted()
|
|
170
179
|
const body=await buildInteractionRequest(options,settings)
|
|
171
180
|
let stream=await transport.create(body,{signal})
|
|
172
|
-
let reconnects=0,connections=1,replayingWithoutCursor=false
|
|
181
|
+
let reconnects=0,connections=1,replayingWithoutCursor=false,lastDropFingerprint
|
|
173
182
|
const deadline=Date.now()+24*60*60*1000
|
|
174
183
|
for(;;){
|
|
175
|
-
const beforeProgress=progressVersion
|
|
184
|
+
const beforeProgress=progressVersion,beforeLastEventId=lastEventId
|
|
176
185
|
let failure
|
|
177
186
|
try{
|
|
178
187
|
if(!stream?.[Symbol.asyncIterator])throw protocolError('Interactions create/get returned no event stream.')
|
|
@@ -184,9 +193,13 @@ export async function* streamInteractions(options, settings) {
|
|
|
184
193
|
if(!failure&&completedEvent&&terminal.has(status))break
|
|
185
194
|
if(failure&&!retryable(failure))throw failure
|
|
186
195
|
signal?.throwIfAborted()
|
|
187
|
-
|
|
196
|
+
const attemptFingerprint=JSON.stringify({lastEventId,status,usage,steps:[...steps.entries()].sort((a,b)=>a[0]-b[0])})
|
|
197
|
+
const madeProgress=lastEventId!==beforeLastEventId||((!replayingWithoutCursor||Boolean(lastEventId))&&progressVersion>beforeProgress&&attemptFingerprint!==lastDropFingerprint)
|
|
198
|
+
if(madeProgress)reconnects=0
|
|
199
|
+
lastDropFingerprint=attemptFingerprint
|
|
188
200
|
if(connections>=64||Date.now()>=deadline)throw Object.assign(new Error('Interactions recovery reached its connection or runtime bound.'),{code:'ARGON_INTERACTIONS_INTERRUPTED'})
|
|
189
201
|
if(!settings.store||!interactionId||reconnects>=3)throw failure??Object.assign(new Error('Interactions stream ended without a terminal status or safe recovery cursor.'),{code:'ARGON_INTERACTIONS_INTERRUPTED'})
|
|
202
|
+
if(unindexedVisibleOutput)throw protocolError('The stored Interactions read stream omitted event_id on a visible output frame; refusing unsafe replay. The remote task will be explicitly terminated, not resubmitted.')
|
|
190
203
|
if(!lastEventId){
|
|
191
204
|
if(emitted)throw protocolError('The stored Interactions read stream omitted event_id after visible output; refusing unsafe replay. The remote task will be explicitly terminated, not resubmitted.')
|
|
192
205
|
// No visible blocks or tool calls have escaped: discard cursor-free
|
|
@@ -194,7 +207,10 @@ export async function* streamInteractions(options, settings) {
|
|
|
194
207
|
replayingWithoutCursor=true
|
|
195
208
|
steps.clear();blocks.clear();seenEvents.clear();emittedToolIds.clear()
|
|
196
209
|
blockIndex=0;bytes=0;status=undefined;usage=undefined;completedEvent=false
|
|
197
|
-
}else
|
|
210
|
+
}else{
|
|
211
|
+
replayingWithoutCursor=false
|
|
212
|
+
if(indexedSnapshot)restoreSnapshot(indexedSnapshot)
|
|
213
|
+
}
|
|
198
214
|
const delayMs=computeReconnectDelayMs(++reconnects,settings.reconnectBackoff,parseUpstreamRetryDelayMs(failure))
|
|
199
215
|
await waitWithAbort(delayMs,signal)
|
|
200
216
|
// The transport options of get() stay byte-for-byte unchanged; hops only
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-vertex-argon",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.8",
|
|
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": {
|