dsh-vertex-argon 2.2.7 → 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 CHANGED
@@ -2,6 +2,18 @@
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
+
5
17
  ## [2.2.7] - 2026-11-19
6
18
 
7
19
  ### 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`([CHANGELOG.md](<CHANGELOG.md>))
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: toolMode },
624
+ functionCallingConfig: { ...cleanConfig.toolConfig?.functionCallingConfig, mode: effectiveToolMode },
618
625
  },
619
626
  } : {}),
620
627
  automaticContinuation: false,
@@ -852,13 +859,16 @@ export function resolveConfigValues(raw = {}) {
852
859
  }
853
860
  }
854
861
 
855
- function deepFreezeClone(value, seen = new WeakMap()) {
862
+ export function deepFreezeClone(value, seen = new WeakMap()) {
856
863
  if (!value || typeof value !== 'object') return value
857
864
  if (seen.has(value)) return seen.get(value)
858
865
  if (Array.isArray(value)) {
859
- const arr = []
866
+ const arr = new Array(value.length)
860
867
  seen.set(value, arr)
861
- for (const item of value) arr.push(deepFreezeClone(item, seen))
868
+ for (const key of Reflect.ownKeys(value)) {
869
+ if (key === 'length') continue
870
+ arr[key] = deepFreezeClone(value[key], seen)
871
+ }
862
872
  return Object.freeze(arr)
863
873
  }
864
874
  const copy = {}
@@ -251,6 +251,7 @@ export async function continueArgonRequestStream(apiClient, original, request, m
251
251
  let initialPrompt, initialCached
252
252
  let initialUsageLocked = false
253
253
  let thinkingDropoutHeals = 0
254
+ let anyCommittedVisibleOrTool = false
254
255
  const totals = Object.fromEntries(fields.map(key => [key, 0]))
255
256
  const billed = Object.fromEntries(fields.map(key => [key, 0]))
256
257
 
@@ -267,10 +268,22 @@ export async function continueArgonRequestStream(apiClient, original, request, m
267
268
  let blocked = false, terminal = false, streamSettled = false, usageAccounted = false
268
269
  let hopChunks = 0, hopSawThought = false, hopSawVisibleOrTool = false
269
270
  let thoughtParts = [], thoughtBytes = 0, suppressedStop = false, hopToken
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)
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))
274
287
 
275
288
  const wrap = (raw, headers, usageSnapshot, hideStop = false) => {
276
289
  let out = raw
@@ -360,8 +373,9 @@ export async function continueArgonRequestStream(apiClient, original, request, m
360
373
  }
361
374
  const candidate = raw.candidates?.[0]
362
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)))
363
377
  hopSawThought ||= parts.some(part => part.thought === true)
364
- hopSawVisibleOrTool ||= parts.some(part => part.functionCall || (!part.thought && typeof part.text === 'string' && part.text.length > 0))
378
+ hopSawVisibleOrTool ||= chunkHasVisibleOrTool
365
379
  if (hopSawVisibleOrTool) { thoughtParts = []; thoughtBytes = 0 }
366
380
  else if (enabled && thinkingDropoutHeals < MAX_THINKING_DROPOUT_HEALS) {
367
381
  for (const part of parts) if (part.thought === true || part.thoughtSignature || part.thought_signature) {
@@ -390,13 +404,14 @@ export async function continueArgonRequestStream(apiClient, original, request, m
390
404
  refreshOriginalUsage()
391
405
  const outgoing = wrap(raw, chunk.headers, latestUsage, hideStop)
392
406
  committedUsage = latestUsage ? { ...latestUsage } : undefined
407
+ anyCommittedVisibleOrTool ||= chunkHasVisibleOrTool
393
408
  hopChunks++
394
409
  yield outgoing
395
410
  continue
396
411
  }
397
412
  pendingBytes += Buffer.byteLength(JSON.stringify(raw))
398
413
  if (pendingBytes > MAX_PENDING_BYTES) throw streamError('Argon uncommitted stream exceeded the bounded checkpoint buffer.', 'ARGON_BUFFER_LIMIT')
399
- 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 })
400
415
  pendingHasContent ||= parts.some(part => typeof part.text === 'string' ? part.text.length > 0 || Boolean(part.thoughtSignature || part.thought_signature) : Object.keys(part).length > 0)
401
416
  const finalMetadata = finishReason === 'CONTINUATION' && token && token !== startToken && !pendingHasContent
402
417
  if (newCheckpoint || terminal || finalMetadata) {
@@ -408,6 +423,7 @@ export async function continueArgonRequestStream(apiClient, original, request, m
408
423
  throwIfAborted(request.abortSignal)
409
424
  const outgoing = wrap(saved.raw, saved.headers, saved.usage, saved.hideStop)
410
425
  committedUsage = saved.usage
426
+ anyCommittedVisibleOrTool ||= saved.hasVisibleOrTool
411
427
  hopChunks++
412
428
  yield outgoing
413
429
  }
@@ -438,6 +454,8 @@ export async function continueArgonRequestStream(apiClient, original, request, m
438
454
  }
439
455
  if (terminal) {
440
456
  if (!failure && canHeal()) {
457
+ const priorBilledOutput = billed.candidatesTokenCount + billed.thoughtsTokenCount
458
+ const hopOutputSpent = accountableHopOutputSpent() ?? 0
441
459
  accountUsage()
442
460
  hopTracker?.finish({ finishReason, continued: true })
443
461
  if (hop === MAX_CONTINUATION_HOPS) throw streamError('Argon continuation hop limit reached without a terminal response.', 'ARGON_HOP_LIMIT')
@@ -446,7 +464,7 @@ export async function continueArgonRequestStream(apiClient, original, request, m
446
464
  token = hopToken
447
465
  } else {
448
466
  token = undefined
449
- const remainingBudget = initialMaxOutputTokens === undefined ? undefined : initialMaxOutputTokens - (billed.candidatesTokenCount + billed.thoughtsTokenCount)
467
+ const remainingBudget = initialMaxOutputTokens === undefined ? undefined : initialMaxOutputTokens - (priorBilledOutput + hopOutputSpent)
450
468
  const withRemainingBudget = bodyObj => {
451
469
  if (remainingBudget === undefined) return bodyObj
452
470
  const updateCfg = cfgObj => {
@@ -3,6 +3,12 @@ import { createHash, randomUUID } from 'node:crypto'
3
3
  const ALLOWED_PART_KEYS = new Set(['text', 'thought', 'thoughtSignature', 'thought_signature', 'functionCall', 'function_call'])
4
4
  const ALLOWED_CALL_KEYS = new Set(['name', 'args', 'id', 'call_id'])
5
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
+ }
11
+
6
12
  const PREFIX = '{"dshGoogleSignatureOnly":'
7
13
  const base64 = value => typeof value === 'string' && value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value)
8
14
  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')
@@ -165,7 +171,7 @@ export function createGoogleSignatureBridge(context, model) {
165
171
  seen = true
166
172
  currentFromThisChunk = false
167
173
  for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {
168
- if (!part || typeof part !== 'object' || Array.isArray(part)) {
174
+ if (!isPlainRecord(part)) {
169
175
  close()
170
176
  throw failure('Google returned a malformed candidate part.')
171
177
  }
@@ -176,11 +182,11 @@ export function createGoogleSignatureBridge(context, model) {
176
182
  close()
177
183
  throw failure('Google returned an unsupported candidate part (' + unsupportedKeys.join(', ') + ') that cannot be replayed.')
178
184
  }
179
- if (part.functionCall !== undefined && (!part.functionCall || typeof part.functionCall !== 'object' || Array.isArray(part.functionCall))) {
185
+ if (part.functionCall !== undefined && !isPlainRecord(part.functionCall)) {
180
186
  close()
181
187
  throw failure('Google returned a candidate part with an invalid functionCall payload.')
182
188
  }
183
- if (part.function_call !== undefined && (!part.function_call || typeof part.function_call !== 'object' || Array.isArray(part.function_call))) {
189
+ if (part.function_call !== undefined && !isPlainRecord(part.function_call)) {
184
190
  close()
185
191
  throw failure('Google returned a candidate part with an invalid functionCall payload.')
186
192
  }
@@ -200,16 +206,16 @@ export function createGoogleSignatureBridge(context, model) {
200
206
  throw failure('Google returned a candidate part with an invalid text field.')
201
207
  }
202
208
  if (hasCall) {
203
- const invalidCallKey = Object.keys(call).filter(key => call[key] !== undefined).find(key => !ALLOWED_CALL_KEYS.has(key))
204
- if (invalidCallKey) {
209
+ const invalidCallKeys = Object.keys(call).filter(key => call[key] !== undefined && !ALLOWED_CALL_KEYS.has(key))
210
+ if (invalidCallKeys.length > 0) {
205
211
  close()
206
- throw failure('Google returned a candidate part with an unsupported functionCall field (' + invalidCallKey + ').')
212
+ throw failure('Google returned a candidate part with an unsupported functionCall field (' + JSON.stringify(invalidCallKeys[0]) + ').')
207
213
  }
208
214
  if (typeof call.name !== 'string' || !call.name) {
209
215
  close()
210
216
  throw failure('Google returned a candidate part with an invalid functionCall name.')
211
217
  }
212
- if (call.args !== undefined && (!call.args || typeof call.args !== 'object' || Array.isArray(call.args))) {
218
+ if (call.args !== undefined && !isPlainRecord(call.args)) {
213
219
  close()
214
220
  throw failure('Google returned a candidate part with an invalid functionCall args payload.')
215
221
  }
@@ -221,9 +227,9 @@ export function createGoogleSignatureBridge(context, model) {
221
227
  close()
222
228
  throw failure('Google returned a candidate part with an invalid functionCall call_id.')
223
229
  }
224
- if (call.id !== undefined && call.call_id !== undefined && call.id !== call.call_id) {
230
+ if (call.id !== undefined && call.call_id !== undefined) {
225
231
  close()
226
- throw failure('Google returned a candidate part with conflicting functionCall id and call_id.')
232
+ throw failure('Google returned a candidate part with both functionCall id and call_id fields.')
227
233
  }
228
234
  }
229
235
  if (hasText && hasCall) {
@@ -236,7 +242,7 @@ export function createGoogleSignatureBridge(context, model) {
236
242
  }
237
243
  bytes += Buffer.byteLength(JSON.stringify(part))
238
244
  if (bytes > 64 * 1024 * 1024) throw failure('Google response exceeded the bounded signature replay buffer.')
239
- // A Part may serialize the signature in either wire spelling.
245
+ // A Part may serialize the signature in either wire spelling, but never both on one Part.
240
246
  if (part.thoughtSignature !== undefined && (typeof part.thoughtSignature !== 'string' || !part.thoughtSignature)) {
241
247
  close()
242
248
  throw failure('Google returned a candidate part with an invalid thoughtSignature.')
@@ -245,9 +251,9 @@ export function createGoogleSignatureBridge(context, model) {
245
251
  close()
246
252
  throw failure('Google returned a candidate part with an invalid thoughtSignature.')
247
253
  }
248
- if (part.thoughtSignature !== undefined && part.thought_signature !== undefined && part.thoughtSignature !== part.thought_signature) {
254
+ if (part.thoughtSignature !== undefined && part.thought_signature !== undefined) {
249
255
  close()
250
- throw failure('Google returned a candidate part with conflicting thoughtSignature spellings.')
256
+ throw failure('Google returned a candidate part with both thoughtSignature and thought_signature fields.')
251
257
  }
252
258
  const sig = part.thoughtSignature ?? part.thought_signature
253
259
  const onlySignature = typeof sig === 'string' && !hasText && !hasCall
package/interactions.js CHANGED
@@ -29,7 +29,10 @@ 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, unindexedVisibleOutput=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
38
  function* appendText(state, text, reasoning=false, indexed=false) {
@@ -41,8 +44,9 @@ export async function* streamInteractions(options, settings) {
41
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* handle(event) {
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;unindexedVisibleOutput=false
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,13 +106,12 @@ 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
- const indexed=Boolean(event.event_id)
113
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)}
114
110
  if(step.type==='thought')for(const content of step.summary??[]){if(content.type==='text')yield*appendText(state,content.text,true,indexed)}
115
111
  return
116
112
  }
117
113
  if(type==='step.delta'){
118
- const state=stateFor(event.index),delta=event.delta,indexed=Boolean(event.event_id)
114
+ const state=stateFor(event.index),delta=event.delta
119
115
  if(!validObject(delta))throw protocolError('Invalid step delta.')
120
116
  if(state.kind==='user_input'){
121
117
  if(state.closed)throw protocolError('Received a delta for an already closed step.')
@@ -147,7 +143,7 @@ export async function* streamInteractions(options, settings) {
147
143
  if(state.kind==='function_call'){
148
144
  try{state.args=state.argsText?JSON.parse(state.argsText):(state.argsValue??{})}catch{state.invalidArguments=true}
149
145
  if(!validObject(state.args))state.invalidArguments=true
150
- }else yield*closeText(state)
146
+ }else yield*closeText(state, indexed)
151
147
  return
152
148
  }
153
149
  // Usage/status extensions may be added without rendering; unknown semantic
@@ -160,6 +156,18 @@ export async function* streamInteractions(options, settings) {
160
156
  }
161
157
  throw protocolError('Unknown Interactions stream event.')
162
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
+ }
163
171
  const cancel=async()=>{
164
172
  if(settings.background&&interactionId&&!terminal.has(status)&&!cancelled){
165
173
  cancelled=true // one attempt per unwind, even if confirmation fails
@@ -170,10 +178,10 @@ export async function* streamInteractions(options, settings) {
170
178
  signal?.throwIfAborted()
171
179
  const body=await buildInteractionRequest(options,settings)
172
180
  let stream=await transport.create(body,{signal})
173
- let reconnects=0,connections=1,replayingWithoutCursor=false
181
+ let reconnects=0,connections=1,replayingWithoutCursor=false,lastDropFingerprint
174
182
  const deadline=Date.now()+24*60*60*1000
175
183
  for(;;){
176
- const beforeProgress=progressVersion
184
+ const beforeProgress=progressVersion,beforeLastEventId=lastEventId
177
185
  let failure
178
186
  try{
179
187
  if(!stream?.[Symbol.asyncIterator])throw protocolError('Interactions create/get returned no event stream.')
@@ -185,7 +193,10 @@ export async function* streamInteractions(options, settings) {
185
193
  if(!failure&&completedEvent&&terminal.has(status))break
186
194
  if(failure&&!retryable(failure))throw failure
187
195
  signal?.throwIfAborted()
188
- if((!replayingWithoutCursor||lastEventId)&&progressVersion>beforeProgress)reconnects=0
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
189
200
  if(connections>=64||Date.now()>=deadline)throw Object.assign(new Error('Interactions recovery reached its connection or runtime bound.'),{code:'ARGON_INTERACTIONS_INTERRUPTED'})
190
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'})
191
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.')
@@ -196,7 +207,10 @@ export async function* streamInteractions(options, settings) {
196
207
  replayingWithoutCursor=true
197
208
  steps.clear();blocks.clear();seenEvents.clear();emittedToolIds.clear()
198
209
  blockIndex=0;bytes=0;status=undefined;usage=undefined;completedEvent=false
199
- }else replayingWithoutCursor=false
210
+ }else{
211
+ replayingWithoutCursor=false
212
+ if(indexedSnapshot)restoreSnapshot(indexedSnapshot)
213
+ }
200
214
  const delayMs=computeReconnectDelayMs(++reconnects,settings.reconnectBackoff,parseUpstreamRetryDelayMs(failure))
201
215
  await waitWithAbort(delayMs,signal)
202
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.7",
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": {