dsh-vertex-argon 2.2.5 → 2.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes to **Gemini 4 Adapter** (`dsh-vertex-argon`) are documented in this file.
4
4
 
5
+ ## [2.2.7] - 2026-11-19
6
+
7
+ ### Fixed
8
+ - **Same-Chunk Part Splitting & Dual-Key Field Validation (`google-signatures.js`)**:
9
+ - 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.
10
+ - 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`).
11
+ - **Unindexed Visible Interactions Frame Guard (`interactions.js`)**:
12
+ - 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`.
13
+ - **Pre-Handler Interactions Reasoning Validation & Recursive Descriptor Freeze (`adapter.js`)**:
14
+ - 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.
15
+ - Upgraded `freezeDescriptor` to recursive `deepFreezeClone` across nested objects, arrays, and symbol properties.
16
+ - **Thinking-Dropout Heal Token Budget Deduction (`generate-content.js`)**:
17
+ - 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.
18
+
19
+ ## [2.2.6] - 2026-11-19
20
+
21
+ ### Fixed
22
+ - **Fail-Closed Unsupported Part Validation (`google-signatures.js`)**:
23
+ - Validated every candidate Part inside `observe(chunk)` against the supported `pi-ai` replay contract (`text`, `thought`, `thoughtSignature` / `thought_signature`, `functionCall` / `function_call`); unrepresentable parts (`executableCode`, `codeExecutionResult`, `functionResponse`, `inlineData`, `fileData`, mixed `text + functionCall`, `functionCall` with `thought: true`, or bare `{ thought: true }`) now fail closed with `ARGON_SIGNATURE_REPLAY` instead of being silently dropped.
24
+ - **Symmetric Cross-Chunk & Same-Chunk Text/Thinking Merge (`google-signatures.js`)**:
25
+ - Made `splitSigned` symmetric between `text` and `thinking`: cross-chunk continuations from a non-empty signed block to an unsigned block merge while preserving the signature, whereas same-chunk signature boundaries, conflicting signatures (`S1` → `S2`), and explicit empty signed carriers split 1:1.
26
+ - **Immutable Deep-Frozen Model Descriptors (`adapter.js`)**:
27
+ - Added `freezeDescriptor` deep-freezing returned/registered model descriptors (`input`, `thinkingLevelMap`, `cost`, and the descriptor object itself while preserving `MAX_TOKENS_CEILING`) in both `getProfiles()` and `argonProvider()`, preventing callers from mutating cached descriptor state via `getModels()`.
28
+
5
29
  ## [2.2.5] - 2026-11-19
6
30
 
7
31
  ### 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.5`([CHANGELOG.md](<CHANGELOG.md>))
7
+ - **当前版本**:`2.2.7`([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
@@ -852,14 +852,39 @@ export function resolveConfigValues(raw = {}) {
852
852
  }
853
853
  }
854
854
 
855
+ function deepFreezeClone(value, seen = new WeakMap()) {
856
+ if (!value || typeof value !== 'object') return value
857
+ if (seen.has(value)) return seen.get(value)
858
+ if (Array.isArray(value)) {
859
+ const arr = []
860
+ seen.set(value, arr)
861
+ for (const item of value) arr.push(deepFreezeClone(item, seen))
862
+ return Object.freeze(arr)
863
+ }
864
+ const copy = {}
865
+ seen.set(value, copy)
866
+ for (const key of Object.keys(value)) {
867
+ copy[key] = deepFreezeClone(value[key], seen)
868
+ }
869
+ for (const sym of Object.getOwnPropertySymbols(value)) {
870
+ copy[sym] = deepFreezeClone(value[sym], seen)
871
+ }
872
+ return Object.freeze(copy)
873
+ }
874
+
875
+ function freezeDescriptor(descriptor) {
876
+ return deepFreezeClone(descriptor)
877
+ }
878
+
855
879
  /** Serve the official Vertex AI and Gemini API models in one plugin group. */
856
880
  export function argonProvider(nativeVertex, models, defaultLevel = undefined, nativeGoogle = googleProvider(), longDecode = true, recordDiagnostic, serviceConfig = {}, responseHub, structuredOutput) {
857
- const modelMap = new Map((Array.isArray(models) ? models : [models]).map(m => [m.id, m]))
881
+ const frozenModels = (Array.isArray(models) ? models : [models]).map(freezeDescriptor)
882
+ const modelMap = new Map(frozenModels.map(m => [m.id, m]))
858
883
  return {
859
884
  id: PROVIDER,
860
885
  name: 'Gemini 4 Adapter',
861
886
  auth: nativeVertex.auth,
862
- getModels: () => [...modelMap.values()],
887
+ getModels: () => [...frozenModels],
863
888
  streamSimple(requestModel, context, options = {}) {
864
889
  const configured = modelMap.get(requestModel?.id)
865
890
  if (!configured || requestModel?.provider !== PROVIDER) {
@@ -959,6 +984,17 @@ export class ArgonAdapter extends LlmAdapter {
959
984
  stream: options => {
960
985
  const pinned = pinPreparedOptions(options, provider, model)
961
986
  assertGemini4MaxTokens(pinned, resolvedModel, cfg?.longDecode)
987
+ const defaultReasoning = cfg?.hasExplicitReasoning === false ? defaultReasoningForModel(model) : (cfg?.reasoning ?? defaultReasoningForModel(model))
988
+ const check = resolveGemini4ReasoningLevel(pinned, model, defaultReasoning)
989
+ if (!check.ok) {
990
+ const message = check.errorType === 'conflict'
991
+ ? 'Conflicting reasoning and reasoningEffort options in Interactions request.'
992
+ : (check.supportsXhigh ? 'Gemini 4 (Hydrogen / Neon) requires low, medium, high, or xhigh thinking.' : 'Argon requires low, medium, or high thinking.')
993
+ const code = check.errorType === 'conflict' ? 'INVALID_REQUEST' : 'UNSUPPORTED_REASONING_EFFORT'
994
+ return (async function* () {
995
+ yield { type: 'finish', reason: { kind: 'error', failure: { code, message } } }
996
+ })()
997
+ }
962
998
  return this.interactionHandler(syncGemini4ReasoningOptions(pinned, model), cfg)
963
999
  },
964
1000
  }
@@ -1195,8 +1231,9 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
1195
1231
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1196
1232
  })
1197
1233
  }
1198
- for (const modelDescriptor of models) {
1199
- modelDescriptor[MAX_TOKENS_CEILING] = cfg.explicitMaxTokensCap
1234
+ for (let i = 0; i < models.length; i++) {
1235
+ models[i][MAX_TOKENS_CEILING] = cfg.explicitMaxTokensCap
1236
+ models[i] = freezeDescriptor(models[i])
1200
1237
  }
1201
1238
  const configuredMaxTokens = new Map(models.map(m => [m.id, cfg.maxTokens]))
1202
1239
  const configuredReasoning = cfg.hasExplicitReasoning ? cfg.reasoning : undefined
@@ -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) {
@@ -259,7 +267,10 @@ export async function continueArgonRequestStream(apiClient, original, request, m
259
267
  let blocked = false, terminal = false, streamSettled = false, usageAccounted = false
260
268
  let hopChunks = 0, hopSawThought = false, hopSawVisibleOrTool = false
261
269
  let thoughtParts = [], thoughtBytes = 0, suppressedStop = false, hopToken
262
- const canHeal = () => enabled && thinkingDropoutHeals < MAX_THINKING_DROPOUT_HEALS && hopSawThought && !hopSawVisibleOrTool && !blocked && finishReason === 'STOP'
270
+ const remainingHealBudget = () => initialMaxOutputTokens === undefined
271
+ ? Infinity
272
+ : initialMaxOutputTokens - (billed.candidatesTokenCount + billed.thoughtsTokenCount + (usageAccounted ? 0 : value(latestUsage, 'candidatesTokenCount') + value(latestUsage, 'thoughtsTokenCount')))
273
+ const canHeal = () => enabled && thinkingDropoutHeals < MAX_THINKING_DROPOUT_HEALS && hopSawThought && !hopSawVisibleOrTool && !blocked && finishReason === 'STOP' && (Boolean(hopToken) || remainingHealBudget() > 0)
263
274
 
264
275
  const wrap = (raw, headers, usageSnapshot, hideStop = false) => {
265
276
  let out = raw
@@ -368,13 +379,13 @@ export async function continueArgonRequestStream(apiClient, original, request, m
368
379
  // continuation token, a repeated finishReason or an empty thought frame
369
380
  // must never extend a stalled hop.
370
381
  watchdog.update(parts, Boolean(newCheckpoint || (candidate?.finishReason !== undefined && candidate.finishReason !== finishReason) || (!blocked && raw.promptFeedback?.blockReason)))
382
+ if (raw.usageMetadata && typeof raw.usageMetadata === 'object') latestUsage = readUsage(raw.usageMetadata, latestUsage)
371
383
  if (candidate?.finishReason !== undefined) finishReason = candidate.finishReason
372
384
  blocked ||= Boolean(raw.promptFeedback?.blockReason)
373
385
  terminal ||= blocked || (finishReason !== undefined && finishReason !== 'CONTINUATION')
374
386
  const hideStop = candidate?.finishReason === 'STOP' && canHeal()
375
387
  if (candidate?.finishReason !== undefined && candidate.finishReason !== 'CONTINUATION') suppressedStop = hideStop
376
388
  hopTracker?.onChunk({ status: 200, hasCheckpoint: hasToken, finishReason: candidate?.finishReason })
377
- if (raw.usageMetadata && typeof raw.usageMetadata === 'object') latestUsage = readUsage(raw.usageMetadata, latestUsage)
378
389
  if (!enabled || (!token && !newCheckpoint && !terminal && candidate?.finishReason !== 'CONTINUATION')) {
379
390
  refreshOriginalUsage()
380
391
  const outgoing = wrap(raw, chunk.headers, latestUsage, hideStop)
@@ -431,11 +442,31 @@ export async function continueArgonRequestStream(apiClient, original, request, m
431
442
  hopTracker?.finish({ finishReason, continued: true })
432
443
  if (hop === MAX_CONTINUATION_HOPS) throw streamError('Argon continuation hop limit reached without a terminal response.', 'ARGON_HOP_LIMIT')
433
444
  thinkingDropoutHeals++
434
- if (hopToken) token = hopToken
435
- else {
445
+ if (hopToken) {
446
+ token = hopToken
447
+ } else {
436
448
  token = undefined
449
+ const remainingBudget = initialMaxOutputTokens === undefined ? undefined : initialMaxOutputTokens - (billed.candidatesTokenCount + billed.thoughtsTokenCount)
450
+ const withRemainingBudget = bodyObj => {
451
+ if (remainingBudget === undefined) return bodyObj
452
+ const updateCfg = cfgObj => {
453
+ if (!cfgObj || typeof cfgObj !== 'object' || Array.isArray(cfgObj)) return cfgObj
454
+ const nextCfg = { ...cfgObj }
455
+ if ('maxOutputTokens' in nextCfg) nextCfg.maxOutputTokens = remainingBudget
456
+ if ('max_output_tokens' in nextCfg) nextCfg.max_output_tokens = remainingBudget
457
+ return nextCfg
458
+ }
459
+ return {
460
+ ...bodyObj,
461
+ ...(bodyObj.generationConfig !== undefined ? { generationConfig: updateCfg(bodyObj.generationConfig) } : {}),
462
+ ...(bodyObj.generation_config !== undefined ? { generation_config: updateCfg(bodyObj.generation_config) } : {}),
463
+ }
464
+ }
465
+ if (httpOptions.extraBody && typeof httpOptions.extraBody === 'object' && !Array.isArray(httpOptions.extraBody)) {
466
+ httpOptions.extraBody = withRemainingBudget(httpOptions.extraBody)
467
+ }
437
468
  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.' }] }] }
469
+ continuationBody = withRemainingBudget({ ...rest, contents: [...(rest.contents ?? []), { role: 'model', parts: thoughtParts }, { role: 'user', parts: [{ text: 'Continue and provide the final response or tool call.' }] }] })
439
470
  }
440
471
  retriesWithoutProgress = 0; retryAttempt = 0; delayMs = 0
441
472
  trigger = 'thinking-dropout-heal'
@@ -1,5 +1,8 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
2
 
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
+
3
6
  const PREFIX = '{"dshGoogleSignatureOnly":'
4
7
  const base64 = value => typeof value === 'string' && value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value)
5
8
  const digest = content => createHash('sha256').update(JSON.stringify(content.map(block => block.type === 'text' ? ['text', block.text] : block.type === 'thinking' ? ['thinking', block.thinking] : ['toolCall', block.id, block.name, block.arguments]))).digest('hex')
@@ -162,13 +165,97 @@ export function createGoogleSignatureBridge(context, model) {
162
165
  seen = true
163
166
  currentFromThisChunk = false
164
167
  for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {
168
+ if (!part || typeof part !== 'object' || Array.isArray(part)) {
169
+ close()
170
+ throw failure('Google returned a malformed candidate part.')
171
+ }
172
+ const definedKeys = Object.keys(part).filter(key => part[key] !== undefined)
173
+ if (definedKeys.length === 0) continue
174
+ const unsupportedKeys = definedKeys.filter(key => !ALLOWED_PART_KEYS.has(key))
175
+ if (unsupportedKeys.length > 0) {
176
+ close()
177
+ throw failure('Google returned an unsupported candidate part (' + unsupportedKeys.join(', ') + ') that cannot be replayed.')
178
+ }
179
+ if (part.functionCall !== undefined && (!part.functionCall || typeof part.functionCall !== 'object' || Array.isArray(part.functionCall))) {
180
+ close()
181
+ throw failure('Google returned a candidate part with an invalid functionCall payload.')
182
+ }
183
+ if (part.function_call !== undefined && (!part.function_call || typeof part.function_call !== 'object' || Array.isArray(part.function_call))) {
184
+ close()
185
+ throw failure('Google returned a candidate part with an invalid functionCall payload.')
186
+ }
187
+ if (part.functionCall !== undefined && part.function_call !== undefined) {
188
+ close()
189
+ throw failure('Google returned a candidate part with both functionCall and function_call fields.')
190
+ }
191
+ const call = part.functionCall ?? part.function_call
192
+ const hasText = part.text !== undefined
193
+ const hasCall = call !== undefined
194
+ if (part.thought !== undefined && typeof part.thought !== 'boolean') {
195
+ close()
196
+ throw failure('Google returned a candidate part with an invalid thought flag.')
197
+ }
198
+ if (hasText && typeof part.text !== 'string') {
199
+ close()
200
+ throw failure('Google returned a candidate part with an invalid text field.')
201
+ }
202
+ if (hasCall) {
203
+ const invalidCallKey = Object.keys(call).filter(key => call[key] !== undefined).find(key => !ALLOWED_CALL_KEYS.has(key))
204
+ if (invalidCallKey) {
205
+ close()
206
+ throw failure('Google returned a candidate part with an unsupported functionCall field (' + invalidCallKey + ').')
207
+ }
208
+ if (typeof call.name !== 'string' || !call.name) {
209
+ close()
210
+ throw failure('Google returned a candidate part with an invalid functionCall name.')
211
+ }
212
+ if (call.args !== undefined && (!call.args || typeof call.args !== 'object' || Array.isArray(call.args))) {
213
+ close()
214
+ throw failure('Google returned a candidate part with an invalid functionCall args payload.')
215
+ }
216
+ if (call.id !== undefined && (typeof call.id !== 'string' || !call.id)) {
217
+ close()
218
+ throw failure('Google returned a candidate part with an invalid functionCall id.')
219
+ }
220
+ if (call.call_id !== undefined && (typeof call.call_id !== 'string' || !call.call_id)) {
221
+ close()
222
+ throw failure('Google returned a candidate part with an invalid functionCall call_id.')
223
+ }
224
+ if (call.id !== undefined && call.call_id !== undefined && call.id !== call.call_id) {
225
+ close()
226
+ throw failure('Google returned a candidate part with conflicting functionCall id and call_id.')
227
+ }
228
+ }
229
+ if (hasText && hasCall) {
230
+ close()
231
+ throw failure('Google returned a mixed text/functionCall part that cannot be represented losslessly.')
232
+ }
233
+ if (hasCall && part.thought === true) {
234
+ close()
235
+ throw failure('Google returned a thought-flagged functionCall part that cannot be represented in replay history.')
236
+ }
165
237
  bytes += Buffer.byteLength(JSON.stringify(part))
166
238
  if (bytes > 64 * 1024 * 1024) throw failure('Google response exceeded the bounded signature replay buffer.')
167
239
  // A Part may serialize the signature in either wire spelling.
240
+ if (part.thoughtSignature !== undefined && (typeof part.thoughtSignature !== 'string' || !part.thoughtSignature)) {
241
+ close()
242
+ throw failure('Google returned a candidate part with an invalid thoughtSignature.')
243
+ }
244
+ if (part.thought_signature !== undefined && (typeof part.thought_signature !== 'string' || !part.thought_signature)) {
245
+ close()
246
+ throw failure('Google returned a candidate part with an invalid thoughtSignature.')
247
+ }
248
+ if (part.thoughtSignature !== undefined && part.thought_signature !== undefined && part.thoughtSignature !== part.thought_signature) {
249
+ close()
250
+ throw failure('Google returned a candidate part with conflicting thoughtSignature spellings.')
251
+ }
168
252
  const sig = part.thoughtSignature ?? part.thought_signature
169
- const onlySignature = typeof sig === 'string' && Object.keys(part).filter(key => part[key] !== undefined).every(key => key === 'thoughtSignature' || key === 'thought_signature' || key === 'thought')
253
+ const onlySignature = typeof sig === 'string' && !hasText && !hasCall
170
254
  if (onlySignature) {
171
- if (!sig || (part.thought !== undefined && typeof part.thought !== 'boolean')) throw failure('Google returned an invalid standalone signature.')
255
+ if (!sig) {
256
+ close()
257
+ throw failure('Google returned an invalid standalone signature.')
258
+ }
172
259
  bytes += 320 // Include the local versioned codec and content binding in the retention bound.
173
260
  if (bytes > 64 * 1024 * 1024) throw failure('Google signature replay metadata exceeded the bounded response buffer.')
174
261
  close()
@@ -177,16 +264,17 @@ export function createGoogleSignatureBridge(context, model) {
177
264
  emit({ type: 'text_start', contentIndex: index }); emit({ type: 'text_end', contentIndex: index, content: '' })
178
265
  continue
179
266
  }
180
- if (part.text !== undefined) {
267
+ if (hasText) {
181
268
  const type = part.thought === true ? 'thinking' : 'text'
182
269
  const sigKey = type === 'text' ? 'textSignature' : 'thinkingSignature'
183
- const sameChunkSigBoundary = currentFromThisChunk && (Boolean(current?.[sigKey]) || Boolean(sig))
184
- const splitSigned = type === 'text'
185
- ? (Boolean(current?.textSignature) || sameChunkSigBoundary || (Boolean(sig) && part.text === ''))
186
- : (sameChunkSigBoundary ||
187
- (Boolean(sig) && (Boolean(current?.thinkingSignature) || part.text === '')) ||
188
- (Boolean(current?.thinkingSignature) && current.thinking === ''))
189
- if (!current || current.type !== type || splitSigned) {
270
+ const curText = type === 'text' ? current?.text : current?.thinking
271
+ const curSig = current?.[sigKey]
272
+ const crossChunkSigConflict =
273
+ (Boolean(curSig) && Boolean(sig)) ||
274
+ (Boolean(curSig) && curText === '') ||
275
+ (Boolean(sig) && part.text === '')
276
+ const splitPart = currentFromThisChunk || crossChunkSigConflict
277
+ if (!current || current.type !== type || splitPart) {
190
278
  close(); current = type === 'text' ? { type, text: '' } : { type, thinking: '' }
191
279
  const index = start(current)
192
280
  emit({ type: type === 'text' ? 'text_start' : 'thinking_start', contentIndex: index })
@@ -196,18 +284,22 @@ export function createGoogleSignatureBridge(context, model) {
196
284
  currentFromThisChunk = true
197
285
  if (sig) current[sigKey] = sig
198
286
  emit({ type: type === 'text' ? 'text_delta' : 'thinking_delta', contentIndex: content.length - 1, delta: part.text })
287
+ continue
199
288
  }
200
- if (part.functionCall) {
289
+ if (hasCall) {
201
290
  close()
202
- const call = part.functionCall
203
- const id = call.id && !usedToolIds.has(call.id) ? call.id : 'argon_' + randomUUID().replaceAll('-', '')
291
+ const rawId = call.id ?? call.call_id
292
+ const id = rawId && !usedToolIds.has(rawId) ? rawId : 'argon_' + randomUUID().replaceAll('-', '')
204
293
  usedToolIds.add(id)
205
294
  const block = { type: 'toolCall', id, name: call.name || '', arguments: call.args ?? {}, ...(sig ? { thoughtSignature: sig } : {}) }
206
295
  const index = start(block)
207
296
  emit({ type: 'toolcall_start', contentIndex: index })
208
297
  emit({ type: 'toolcall_delta', contentIndex: index, delta: JSON.stringify(block.arguments) })
209
298
  emit({ type: 'toolcall_end', contentIndex: index, toolCall: block })
299
+ continue
210
300
  }
301
+ close()
302
+ throw failure('Google returned an unrepresentable candidate part.')
211
303
  }
212
304
  },
213
305
  stream(source) {
package/interactions.js CHANGED
@@ -29,16 +29,16 @@ 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
33
33
  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
34
  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) {
35
+ function* appendText(state, text, reasoning=false, indexed=false) {
36
36
  if(typeof text!=='string')throw protocolError('Interactions text delta is not a string.')
37
37
  if(!text)return
38
38
  if(state.closed)throw protocolError('Received a delta for an already closed step.')
39
39
  checkBytes(text)
40
40
  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++
41
+ state.text+=text;emitted=true;if(!indexed)unindexedVisibleOutput=true;progressVersion++
42
42
  yield{type:reasoning?'reasoning-delta':'text-delta',index:state.blockIndex,text}
43
43
  }
44
44
  function* closeText(state) {
@@ -60,7 +60,7 @@ export async function* streamInteractions(options, settings) {
60
60
  if(typeof event.event_id!=='string')throw protocolError('Invalid event ID.')
61
61
  if(seenEvents.has(event.event_id))return
62
62
  if(seenEvents.size>=MAX_EVENTS)throw protocolError('Interactions event retention limit reached.')
63
- seenEvents.add(event.event_id);lastEventId=event.event_id
63
+ seenEvents.add(event.event_id);lastEventId=event.event_id;unindexedVisibleOutput=false
64
64
  }
65
65
  settings.onEvent?.(event)
66
66
  const type=event.event_type??event.type
@@ -109,21 +109,22 @@ export async function* streamInteractions(options, settings) {
109
109
  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
110
  const state={kind:step.type,text:'',signature:step.signature,callId:step.id,name:step.name,argsValue:step.arguments,argsText:'',closed:false}
111
111
  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)}
112
+ const indexed=Boolean(event.event_id)
113
+ 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)}
114
+ if(step.type==='thought')for(const content of step.summary??[]){if(content.type==='text')yield*appendText(state,content.text,true,indexed)}
114
115
  return
115
116
  }
116
117
  if(type==='step.delta'){
117
- const state=stateFor(event.index),delta=event.delta
118
+ const state=stateFor(event.index),delta=event.delta,indexed=Boolean(event.event_id)
118
119
  if(!validObject(delta))throw protocolError('Invalid step delta.')
119
120
  if(state.kind==='user_input'){
120
121
  if(state.closed)throw protocolError('Received a delta for an already closed step.')
121
122
  return
122
123
  }
123
124
  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)
125
+ if(delta.type==='text'&&state.kind==='model_output')yield*appendText(state,delta.text,false,indexed)
125
126
  else if(delta.type==='thought_summary'&&state.kind==='thought'){
126
- if(delta.content?.type==='text')yield*appendText(state,delta.content.text,true)
127
+ if(delta.content?.type==='text')yield*appendText(state,delta.content.text,true,indexed)
127
128
  else if(delta.content!==undefined)throw protocolError('Unsupported thought summary modality.')
128
129
  }else if(delta.type==='thought_signature'&&state.kind==='thought'){
129
130
  if(typeof delta.signature!=='string')throw protocolError('Invalid thought signature.')
@@ -187,6 +188,7 @@ export async function* streamInteractions(options, settings) {
187
188
  if((!replayingWithoutCursor||lastEventId)&&progressVersion>beforeProgress)reconnects=0
188
189
  if(connections>=64||Date.now()>=deadline)throw Object.assign(new Error('Interactions recovery reached its connection or runtime bound.'),{code:'ARGON_INTERACTIONS_INTERRUPTED'})
189
190
  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'})
191
+ 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
192
  if(!lastEventId){
191
193
  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
194
  // No visible blocks or tool calls have escaped: discard cursor-free
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-vertex-argon",
3
- "version": "2.2.5",
3
+ "version": "2.2.7",
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": {