dsh-vertex-argon 1.6.1 → 1.6.3

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,35 @@
2
2
 
3
3
  All notable changes to `dsh-vertex-argon` are documented in this file.
4
4
 
5
+ ## [1.6.3] - 2026-10-28
6
+
7
+ ### Added
8
+ - **Gemini 3.8 Flash on the Antigravity Proxy (`adapter.js`, `interaction-adapter.js`, `client.js`)**:
9
+ - Added `PROXY_FLASH_MODEL = 'gemini-3.8-flash-proxy'` (`Gemini 3.8 Flash (Antigravity)`) next to `PROXY_MODEL`; both register only when `proxyEnabled || explicitRoutes.hasProxy`, share the proxy base URL and the dedicated `ANTIGRAVITY_API_KEY` / `proxyApiKey` credential, and never touch Google / Vertex credentials.
10
+ - Added `isProxyModel` / `proxyUpstreamBaseModel` / `resolveProxyUpstreamModel` as the single proxy-map; `gemini-3.8-flash-proxy` maps `low` / `medium` / `high` 1:1 to `gemini-3.8-flash-low` / `gemini-3.8-flash-medium` / `gemini-3.8-flash-high` across both GenerateContent and Interactions, while official Vertex AI and Gemini API routes keep `gemini-4-argon`.
11
+ - Inspector shows **Antigravity Proxy** for both proxy model IDs. The 16 volatile settings are unchanged.
12
+
13
+ ### Fixed
14
+ - **Cross-Model GenerateContent History Downgrade (`interactions-input.js`, `adapter.js`)**:
15
+ - `generateContentHistory(options, model)` now also downgrades history when switching between `gemini-4-argon-proxy` and `gemini-3.8-flash-proxy` (or across providers) and the message carries `reasoning` / `tool-call` blocks: thought blocks are dropped, completed tool round-trips become explicit text, unfinished calls throw, and `replayState` is stripped. pi-ai no longer emits a signature-stripped native `functionCall` or an orphan `functionResponse` after a proxy-model switch, and old reasoning is no longer replayed as public prose. Same-model history keeps native signature replay; pure-text cross-model messages still fall through to the signature bridge.
16
+
17
+ ## [1.6.2] - 2026-10-26
18
+
19
+ ### Fixed
20
+ - **Interactions `2026-05-20` Lifecycle Events, Terminal Guards & `user_input` Replay (`interactions.js`, `interaction-lifecycle.js`, `inspector-service.js`)**:
21
+ - Supported dedicated `2026-05-20` lifecycle events (`interaction.in_progress`, `interaction.requires_action`, `interaction.failed`, `interaction.cancelled`, `interaction.incomplete`, `interaction.budget_exceeded`) and `budget_exceeded` terminal mapping (`max-tokens`).
22
+ - Finalized streams at EOF when `interaction.status_update` carries `failed`, `cancelled`, or `budget_exceeded`, enforced monotonic terminal-state guards against late non-terminal notices, ignored unknown `interaction.*` notices without cancelling paid cloud tasks, and safely skipped structural `user_input` steps during replay.
23
+ - Normalized in-stream `error` event codes case-insensitively and prioritized `remote-error` over simultaneous local aborts so terminal provider errors never trigger redundant `/cancel` requests or leave `cancel-failed` locks.
24
+ - **Background Recovery Zombie-Lock Reconciliation & Conservative Error Probes (`interaction-state.js`)**:
25
+ - Reconciled historical same-session `accepted` handles via a bounded non-streaming `GET` probe when the user submits a changed prompt: automatically dropped dead records (`failed`, `cancelled`, or HTTP `404`), retained un-replayed terminal handles (`completed`, `requires_action`, `incomplete`, `budget_exceeded`) for cold resume by their original `requestKey` while releasing session-wide exclusivity for the new prompt, and kept conservative blocks when the remote task is still `in_progress` / `queued` or the probe fails with non-404 errors.
26
+ - Verified cloud state via a bounded non-streaming probe before dropping recovery handles on unrecoverable in-stream `error` frames, and hardened post-ID persistence retry on initial save failure.
27
+ - **Interactions `Retry-After` Backoff & First-Hop Input Watermark Window (`interaction-transport.js`, `interactions.js`, `interaction-adapter.js`)**:
28
+ - Extracted `Retry-After` delays from non-2xx Interactions response headers without reading error bodies, failed fast above `60s`, and recorded reconnect `backoffDelayMs` on the subsequent `interaction-resume` hop.
29
+ - Kept the first-hop input watermark window open across same-hop `function_call` steps and trailing `interaction.completed` / `interaction.requires_action` events until a second `model_output` step (64K hop boundary) begins; suppressed host `usage` chunks and kept `reportedInputTokens: null` whenever first-hop input tokens were never reported rather than leaking cumulative multi-hop inputs or fabricating `0`.
30
+ - **GenerateContent Watchdog Pseudo-Progress Hardening & Snake-Case Signature Replay (`generate-content.js`, `google-signatures.js`, `test/host-internals.mjs`)**:
31
+ - Prevented empty heartbeat frames `{}`, empty thought frames `{ thought: true, text: '' }`, nameless `{ functionCall: {} }` parts, alternating empty frames, repeated `continuationToken` / `finishReason` values, and repeated `thoughtSignature` values (deduplicated per hop via a bounded 8,192-entry `seenSignatures` set) from renewing phase timeout budgets.
32
+ - Supported snake_case `thought_signature` parts in `createGoogleSignatureBridge` and relaxed the `dshDesktopBoot` minifier identifier match in `test/host-internals.mjs` for `0.2.1-rc.3` compatibility.
33
+
5
34
  ## [1.6.1] - 2026-10-25
6
35
 
7
36
  ### Changed
package/README.md CHANGED
@@ -4,15 +4,15 @@
4
4
 
5
5
  **为 [DeepSeek Harness](<https://github.com/deepseek-ai/deepseek-harness>) 提供 Vertex AI、Gemini API、Antigravity 三路由,以及 GenerateContent / Interactions 双协议接入。**
6
6
 
7
- 工程版本 **1.6.0**;兼容 **DSH 0.2.1-rc.2 / 0.2.1-rc.3**,Node.js `^22.19.0 || >=24.0.0`。版本与依赖以 [package.json](<package.json>) 为准;历史变更见 [CHANGELOG.md](<CHANGELOG.md>)。本文说明本地工程,不代表已安装、已发布或已完成本轮云端实测。
7
+ 工程版本 **1.6.3**;兼容 **DSH 0.2.1-rc.2 / 0.2.1-rc.3**,Node.js `^22.19.0 || >=24.0.0`。版本与依赖以 [package.json](<package.json>) 为准;历史变更见 [CHANGELOG.md](<CHANGELOG.md>)。本文说明本地工程,不代表已安装、已发布或已完成本轮云端实测。
8
8
 
9
9
  [三路由与凭据](<#三路由与凭据>) · [完整配置](<#完整配置16-项>) · [流式恢复](<#generatecontent四项韧性机制>) · [Inspector](<#argon-inspectordebug-与-operations>) · [历史实测](<#历史实测奥德赛七号全年舰长日志>)
10
10
 
11
11
  ## 核心能力
12
12
 
13
- - **独立第三模型**:Antigravity 使用 `gemini-4-argon-proxy`,独立地址与专属密钥,不覆盖 Gemini API 模型。
13
+ - **独立代理模型**:Antigravity 路由下有 `gemini-4-argon-proxy` 与 `gemini-3.8-flash-proxy` 两个独立模型,共用独立地址与专属密钥,不覆盖 Gemini API 模型。
14
14
  - **GenerateContent 长解码**:单跳输出上限 `65,536`,输出预算配置最高 `1,048,576`,所有尝试共用 32 跳上限;支持检查点恢复、阶段超时、安全首包重试和仅思考结束自愈。
15
- - **Interactions 后台恢复**:显式启用后台与存储后,用 `creating` 预写锁防止未知创建被自动重发,以 `last_event_id` 续读已知任务。
15
+ - **Interactions 后台恢复与状态对账**:显式启用后台与存储后,用 `creating` 预写锁防止未知创建被自动重发,以 `last_event_id` 续读已知任务;兼容 `2026-05-20` 独立生命周期事件,并在同会话发起新提示词时自动以有界非流式探针对账历史任务(清理已 `failed` / `cancelled` / `404` 死锁,保留未回放终态句柄的同时放行新提示词)。
16
16
  - **签名保真**:保留并回放仅含 `thoughtSignature` / `thought_signature` 的空 `Part`;思考档位为 `low` / `medium` / `high`,宿主传入 `max` 时收敛为 `high`。
17
17
  - **聚焦请求诊断**:只展示请求摘要、基本 Token 水位、逐跳轨迹、原始响应和完整 JSON,不再提供费用估算、模态用量或范围概览。
18
18
 
@@ -25,8 +25,9 @@ Provider ID 保持 `google-vertex-argon`,模型位于 **Vertex Argon** 分组
25
25
  | Vertex AI | `gemini-4-argon` | `google-vertex` | `vertexProtocol` / `vertexServiceTier` |
26
26
  | Gemini Developer API | `gemini-4-argon-google` | `google-generative-ai` | `googleProtocol` / `googleServiceTier` |
27
27
  | Antigravity Proxy | `gemini-4-argon-proxy` | `google-generative-ai` | 复用 `googleProtocol` / `googleServiceTier` |
28
+ | Antigravity Proxy | `gemini-3.8-flash-proxy` | `google-generative-ai` | 同上;与 Argon 共用代理地址与专属密钥 |
28
29
 
29
- 这里的“三路由”指三个独立模型与连接目标,**并未新增第三种诊断 `route` 值**。Inspector 根据独立 `model` 显示 **Antigravity Proxy**。代理启用条件为 `proxyEnabled === true || explicitRoutes.hasProxy === true`;默认关闭,仅配置密钥不会自动开启。
30
+ 这里的“三路由”指三个连接目标、四个独立模型 ID,**并未新增第三种诊断 `route` 值**。Inspector 根据独立 `model` 显示 **Antigravity Proxy**。代理启用条件为 `proxyEnabled === true || explicitRoutes.hasProxy === true`;默认关闭,仅配置密钥不会自动开启。
30
31
 
31
32
  ### Vertex AI
32
33
 
@@ -46,7 +47,8 @@ Provider ID 保持 `google-vertex-argon`,模型位于 **Vertex Argon** 分组
46
47
  - `proxyApiKey` 先去除首尾空白;有值时使用设置值,否则只读取 `ANTIGRAVITY_API_KEY`。
47
48
  - **绝不回退到 Google/Vertex 密钥,也不把代理密钥送往 Google/Vertex。** 缺少专属密钥时应明确失败。
48
49
  - 地址和密钥使用草稿输入,失焦或点击保存后提交,重置恢复默认值。填写的 Key 保存在插件配置中,密码框仅遮挡显示;也可留空并使用 DSH 凭据中的 `ANTIGRAVITY_API_KEY`,避免直接填写配置。设置实时更新时,模型列表缓存随之失效。
49
- - 代理沿用 Google 协议与服务层级配置;具体端点是否支持所选能力仍取决于代理实现,不是新增的云端验证结论。
50
+ - 选中代理模型时,插件按推理档位(`low` / `medium` / `high`)把上游模型 ID 1:1 映射:`gemini-4-argon-proxy` → `gemini-4-argon-low`、`gemini-4-argon-medium`、`gemini-4-argon-high`;`gemini-3.8-flash-proxy` → `gemini-3.8-flash-low`、`gemini-3.8-flash-medium`、`gemini-3.8-flash-high`(官方 Vertex AI 与 Gemini API 路由保持 `gemini-4-argon`)。GenerateContent 与 Interactions 走同一份映射。代理沿用 Google 协议与服务层级配置;具体端点是否支持所选能力仍取决于代理实现,不是新增的云端验证结论。
51
+ - **两个代理模型之间切换**时,旧模型的 GenerateContent 工具历史会在出站前降级成文本记录、旧思考一并剔除;未完成的工具调用直接报错。只有与当前代理模型完全一致的历史才保留原生签名回放,避免底层按 provider/model 摘掉签名后仍发出裸 `functionCall` 或孤立 `functionResponse`。
50
52
 
51
53
  ## 完整配置:16 项
52
54
 
@@ -89,7 +91,7 @@ Vertex GenerateContent 通过 `X-Vertex-AI-LLM-Shared-Request-Type: priority`
89
91
  实现见 [generate-content.js](<generate-content.js>);精确边界见 [协议合同](<docs/implementation/DECISIONS.md>)。开启 `longDecode` 后,Vertex 使用 `v1beta1`,Gemini API / Antigravity 使用 `v1beta`。关闭长解码仅禁用多跳/检查点续传与仅思考自愈,零交付初始重试和阶段超时仍可用。
90
92
 
91
93
  1. **流内错误与服务端等待建议**:HTTP `200` 的 SSE 也可能包含顶层 `{ error }`。插件单独记录流内状态,解析 `Retry-After`、Google `details` 中的重试/配额恢复延时以及消息中的等待提示,取有效建议并加 `200ms` 余量,与本地退避共同决定等待;解析后的延时超过 `60s` 立即失败,不长期占用重试。
92
- 2. **每跳独立的阶段超时**:首包、思考、思考到可见输出的转换阶段各 `180s`,可见文本或工具流的滑动等待为 `120s`。每跳使用独立 `AbortController`;上游阻塞可终止,不把用户主动取消当作可恢复故障,也不让上一跳定时器影响下一跳。消费方暂停读取不消耗上游等待预算。
94
+ 2. **每跳独立的阶段超时**:首包、思考、思考到可见输出的转换阶段各 `180s`,可见文本或工具流的滑动等待为 `120s`。每跳使用独立 `AbortController`;仅真实进展(首次进入思考/转换阶段、非空文本、具名工具调用、本跳未见的新签名或新检查点)刷新等待预算,空帧、空思考帧、空工具对象与重复签名不续命。上游阻塞可终止,不把用户主动取消当作可恢复故障,也不让上一跳定时器影响下一跳;消费方暂停读取不消耗上游等待预算。
93
95
  3. **首包安全重试与检查点恢复**:可恢复故障发生时,若本跳尚未向调用方 `yield` 任何分片,即使没有 `continuationToken` 也可 `retry-initial`,初次尝试之外最多重试 3 次;已有分片交付但没有检查点时不得整段重试。有检查点则丢弃未提交尾段并从检查点重连,同一检查点无进展也最多重试 3 次。**首个检查点之前实时 `yield`,不把整段输出全部缓存到检查点。**
94
96
  4. **仅思考 STOP 自愈**:一跳只有思考、没有可见回答或工具调用,却以 `STOP` 结束时,最多追加一次 `thinking-dropout-heal`。有可用 token 则用 token 续写;没有则保留原思考与签名,追加 `model` 思考内容及 `user` 消息 `Continue and provide the final response or tool call.`。被安全规则阻止的回答不因此绕过限制;第二次仅思考结束不再循环。
95
97
 
@@ -116,7 +118,7 @@ billedOutputTokens, billedThoughtsTokens, billedToolTokens,
116
118
  billedPromptTokens, billedCachedTokens, billedTotalTokens
117
119
  ```
118
120
 
119
- 每跳仅保留五项 Token 计数:`promptTokens`、`cachedTokens`、`outputTokens`、`thoughtsTokens`、`totalTokens`。输入水位与跨跳累计用量分开:前者用于宿主上下文判断,后者保留各次上游尝试的观测计数,不混作上下文长度或价格。未知用量可为 `null`。
121
+ 每跳仅保留五项 Token 计数:`promptTokens`、`cachedTokens`、`outputTokens`、`thoughtsTokens`、`totalTokens`。输入水位与跨跳累计用量分开:前者采用首跳原始输入口径(Interactions 在首个 `model_output` 结束并开启下一个 `model_output` 续跳前采集,同跳 `function_call` 不提前关闭;若首跳未报告输入则保持 `null` 且不向宿主交付伪造 `0` 或跨跳累计 `usage` 分片),后者保留各次上游尝试的观测计数,不混作上下文长度或价格。
120
122
 
121
123
  ### Operations:显式操作、独立权限
122
124
 
@@ -148,7 +150,7 @@ billedPromptTokens, billedCachedTokens, billedTotalTokens
148
150
 
149
151
  ## 历史实测:奥德赛七号全年舰长日志
150
152
 
151
- > 以下是 **v1.5.0 历史云端实测**,保留用于说明长解码已有依据;**不是 v1.6.0 本轮新增 live 验证,也不能证明 Antigravity 或新增恢复分支已在云端验证**。本轮验证状态见 [验证账本](<docs/implementation/STATUS.md>)。
153
+ > 以下是 **v1.5.0 历史云端实测**,保留用于说明长解码已有依据;**不是 v1.6.3 本轮新增 live 验证,也不能证明 Antigravity 或新增恢复分支已在云端验证**。本轮验证状态见 [验证账本](<docs/implementation/STATUS.md>)。
152
154
 
153
155
  历史任务要求单回合连续输出 `DAY 001` 至 `DAY 365` 的全年日志,保持每日状态、每周维护、月末报告以及第 100/200/215/300/365 天的长期事件。原记录记载全年日志与状态台账完成;本文未重新运行或逐篇复核内容。
154
156
 
package/adapter.js CHANGED
@@ -24,6 +24,26 @@ export const NATIVE_PROVIDER = 'google-vertex'
24
24
  export const MODEL = 'gemini-4-argon'
25
25
  export const GOOGLE_API_MODEL = 'gemini-4-argon-google'
26
26
  export const PROXY_MODEL = 'gemini-4-argon-proxy'
27
+ /** Antigravity 反代暴露的 Gemini 3.8 Flash;与 Argon 共用同一份反代地址与专属密钥。 */
28
+ export const PROXY_FLASH_MODEL = 'gemini-3.8-flash-proxy'
29
+ export const FLASH_UPSTREAM_MODEL = 'gemini-3.8-flash'
30
+ export const PROXY_MODELS = Object.freeze([PROXY_MODEL, PROXY_FLASH_MODEL])
31
+ export const PROXY_MODEL_NAMES = Object.freeze({
32
+ [PROXY_MODEL]: 'Gemini 4 Argon (Antigravity)',
33
+ [PROXY_FLASH_MODEL]: 'Gemini 3.8 Flash (Antigravity)',
34
+ })
35
+ /** 反代模型判定:Argon 与 Flash 都走同一条 Antigravity 通道。 */
36
+ export function isProxyModel(modelId) {
37
+ return typeof modelId === 'string' && PROXY_MODELS.includes(modelId)
38
+ }
39
+ /** 反代模型对应的上游基础 ID;档位后缀由 resolveProxyUpstreamModel 追加。 */
40
+ export function proxyUpstreamBaseModel(modelId) {
41
+ return modelId === PROXY_FLASH_MODEL ? FLASH_UPSTREAM_MODEL : MODEL
42
+ }
43
+ /** 反代上游模型 ID:`<基础 ID>-<low|medium|high>`,与反代暴露的档位模型一一对应。 */
44
+ export function resolveProxyUpstreamModel(modelId, level) {
45
+ return `${proxyUpstreamBaseModel(modelId)}-${level}`
46
+ }
27
47
  export const PROXY_API_KEY_ENV = 'ANTIGRAVITY_API_KEY'
28
48
  export const DEFAULT_PROXY_BASE_URL = 'http://127.0.0.1:8045/v1beta'
29
49
  export const LEVELS = ['low', 'medium', 'high']
@@ -200,7 +220,7 @@ export function gemini4StreamSimple(
200
220
  const mapped = requestModel?.thinkingLevelMap?.[rawLevel] ?? rawLevel
201
221
  const level = typeof mapped === 'string' ? mapped.toLowerCase() : fallback
202
222
  if (!LEVELS.includes(level)) throw new LlmError('Gemini 4 Argon requires low, medium or high.', 'UNSUPPORTED_REASONING_EFFORT')
203
- const resolvedUpstreamModelId = requestModel?.id === PROXY_MODEL ? `${MODEL}-${level}` : upstreamModelId
223
+ const resolvedUpstreamModelId = isProxyModel(requestModel?.id) ? resolveProxyUpstreamModel(requestModel.id, level) : upstreamModelId
204
224
  const { reasoning, thinking, thinkingBudgets, temperature, onPayload: prior, onProviderStreamEvent: priorEvent, ...rest } = options
205
225
  const requestedMaxTokens = options.maxTokens ?? requestModel.maxTokens
206
226
  const effectiveMaxTokens =
@@ -409,7 +429,7 @@ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nat
409
429
  delete cleanEnv.__ANTIGRAVITY_API_KEY__
410
430
  }
411
431
  if (configured.api === 'google-generative-ai') {
412
- const proxy = configured.id === PROXY_MODEL
432
+ const proxy = isProxyModel(configured.id)
413
433
  const apiKey = proxy ? rawEnv?.__ANTIGRAVITY_API_KEY__ : rawEnv?.__GOOGLE_API_KEY__
414
434
  if (!apiKey) throw new LlmError(proxy ? 'Antigravity proxy requires its dedicated API key.' : 'Gemini API credentials are not configured.', 'MISSING_CREDENTIAL')
415
435
  return gemini4StreamSimple(
@@ -418,7 +438,7 @@ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nat
418
438
  context,
419
439
  { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(apiKey ? { apiKey } : {}), maxTokens: options.maxTokens ?? configured.maxTokens },
420
440
  defaultLevel,
421
- MODEL,
441
+ proxy ? proxyUpstreamBaseModel(configured.id) : MODEL,
422
442
  longDecode,
423
443
  recordDiagnostic,
424
444
  resolveServicePolicy(serviceConfig, 'google-generative-ai', 'generate-content'),
@@ -457,7 +477,7 @@ export class ArgonAdapter extends LlmAdapter {
457
477
  imageRequestPricing(provider, model) { return this.inner.imageRequestPricing?.(provider, model) }
458
478
  imageRequestTarget(provider, model, image) {
459
479
  const cfg = this.configSnapshot?.()
460
- const protocol = (model === GOOGLE_API_MODEL || model === PROXY_MODEL) ? cfg?.googleProtocol : cfg?.vertexProtocol
480
+ const protocol = (model === GOOGLE_API_MODEL || isProxyModel(model)) ? cfg?.googleProtocol : cfg?.vertexProtocol
461
481
  if (provider === PROVIDER && protocol === 'interactions' && this.interactionHandler) return interactionImageRequestTarget(image)
462
482
  return this.inner.imageRequestTarget(provider, model, image)
463
483
  }
@@ -468,13 +488,13 @@ export class ArgonAdapter extends LlmAdapter {
468
488
  resolveModel(provider, model, signal) { return this.inner.resolveModel(provider, model, signal) }
469
489
  async prepareCall(provider, model, signal) {
470
490
  const cfg = this.configSnapshot?.()
471
- if (provider === PROVIDER && cfg) resolveServicePolicy(cfg, (model === GOOGLE_API_MODEL || model === PROXY_MODEL) ? 'google-generative-ai' : 'google-vertex', (model === GOOGLE_API_MODEL || model === PROXY_MODEL) ? cfg.googleProtocol : cfg.vertexProtocol)
491
+ if (provider === PROVIDER && cfg) resolveServicePolicy(cfg, (model === GOOGLE_API_MODEL || isProxyModel(model)) ? 'google-generative-ai' : 'google-vertex', (model === GOOGLE_API_MODEL || isProxyModel(model)) ? cfg.googleProtocol : cfg.vertexProtocol)
472
492
  const prepared = await this.inner.prepareCall(provider, model, signal)
473
- const protocol = (model === GOOGLE_API_MODEL || model === PROXY_MODEL) ? cfg?.googleProtocol : cfg?.vertexProtocol
493
+ const protocol = (model === GOOGLE_API_MODEL || isProxyModel(model)) ? cfg?.googleProtocol : cfg?.vertexProtocol
474
494
  if (provider === PROVIDER && protocol === 'interactions' && this.interactionHandler) {
475
495
  return { model: prepared.model, stream: options => this.interactionHandler(options, cfg) }
476
496
  }
477
- return { ...prepared, stream: options => prepared.stream(generateContentHistory(options)) }
497
+ return { ...prepared, stream: options => prepared.stream(generateContentHistory(options, model)) }
478
498
  }
479
499
  async *stream(options) {
480
500
  const prepared = await this.prepareCall(options.provider, options.model, options.signal)
@@ -606,7 +626,20 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
606
626
  if (cfg.proxyEnabled || detected.hasProxy) {
607
627
  models.push({
608
628
  id: PROXY_MODEL,
609
- name: 'Gemini 4 Argon (Antigravity)',
629
+ name: PROXY_MODEL_NAMES[PROXY_MODEL],
630
+ provider: PROVIDER,
631
+ api: 'google-generative-ai',
632
+ baseUrl: cfg.proxyBaseUrl,
633
+ reasoning: true,
634
+ input: ['text', 'image'],
635
+ contextWindow: cfg.contextWindow,
636
+ maxTokens: cfg.maxTokens,
637
+ thinkingLevelMap: { ...DEFAULT_THINKING_MAP },
638
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
639
+ })
640
+ models.push({
641
+ id: PROXY_FLASH_MODEL,
642
+ name: PROXY_MODEL_NAMES[PROXY_FLASH_MODEL],
610
643
  provider: PROVIDER,
611
644
  api: 'google-generative-ai',
612
645
  baseUrl: cfg.proxyBaseUrl,
package/client.js CHANGED
@@ -531,7 +531,7 @@ window.__ModuleLoader__.load({
531
531
  inspectorTimeline: '请求列表', inspectorThinking: '思考等级', inspectorFailure: '失败类别', inspectorDuration: '耗时',
532
532
  inspectorAssociation: '关联状态', inspectorTokenWatermark: 'Token 水位', inspectorEyebrow: 'ARGON / DEBUG',
533
533
  proxyTitle: 'Antigravity 反代通道 (Antigravity Proxy)', proxyEnabled: '启用独立代理模型', proxyBaseUrl: '代理 Base URL', proxyApiKey: '代理 API Key',
534
- proxyHint: '独立模型 gemini-4-argon-proxy;共用 Gemini API 的协议与服务等级。密钥只使用此处配置或 ANTIGRAVITY_API_KEY,不复用 Google / Vertex 凭据。',
534
+ proxyHint: '独立模型 gemini-4-argon-proxy 与 gemini-3.8-flash-proxy;共用 Gemini API 的协议与服务等级。密钥只使用此处配置或 ANTIGRAVITY_API_KEY,不复用 Google / Vertex 凭据。',
535
535
  proxySaveHint: '开关点击即保存;地址和密钥在离开输入框或点击对应保存按钮时保存,不逐字提交。恢复默认值会关闭代理、恢复默认地址并清空专属密钥。',
536
536
  proxySaveBaseUrl: '保存代理地址', proxySaveApiKey: '保存代理密钥',
537
537
  })
@@ -539,7 +539,7 @@ window.__ModuleLoader__.load({
539
539
  inspectorTimeline: 'Requests', inspectorThinking: 'Thinking level', inspectorFailure: 'Failure category', inspectorDuration: 'Duration',
540
540
  inspectorAssociation: 'Association status', inspectorTokenWatermark: 'Token watermark', inspectorEyebrow: 'ARGON / DEBUG',
541
541
  proxyTitle: 'Antigravity Proxy', proxyEnabled: 'Enable the independent proxy model', proxyBaseUrl: 'Proxy Base URL', proxyApiKey: 'Proxy API Key',
542
- proxyHint: 'Independent gemini-4-argon-proxy model; shares Gemini API protocol and service tier settings. Uses only this key or ANTIGRAVITY_API_KEY, never Google / Vertex credentials.',
542
+ proxyHint: 'Independent gemini-4-argon-proxy and gemini-3.8-flash-proxy models; they share Gemini API protocol and service tier settings. Uses only this key or ANTIGRAVITY_API_KEY, never Google / Vertex credentials.',
543
543
  proxySaveHint: 'The switch saves immediately. URL and key save on blur or with their Save buttons, never on each keystroke. Reset disables the proxy, restores the default URL and clears its dedicated key.',
544
544
  proxySaveBaseUrl: 'Save proxy URL', proxySaveApiKey: 'Save proxy key',
545
545
  })
@@ -1047,7 +1047,7 @@ window.__ModuleLoader__.load({
1047
1047
  navigate()
1048
1048
  }
1049
1049
  const association = row => t(row?.association === 'linked' ? 'inspectorAssociated' : row?.association === 'unverified' ? 'inspectorUnverified' : 'inspectorUnassociated')
1050
- const routeName = record => record?.model === 'gemini-4-argon-proxy' || record?.route === 'antigravity-proxy' ? 'Antigravity Proxy' : record?.route === 'google-generative-ai' ? 'Gemini API' : record?.route === 'google-vertex' ? 'Vertex AI' : (record?.route ?? t('inspectorUnknown'))
1050
+ const routeName = record => record?.model === 'gemini-4-argon-proxy' || record?.model === 'gemini-3.8-flash-proxy' || record?.route === 'antigravity-proxy' ? 'Antigravity Proxy' : record?.route === 'google-generative-ai' ? 'Gemini API' : record?.route === 'google-vertex' ? 'Vertex AI' : (record?.route ?? t('inspectorUnknown'))
1051
1051
  const outcome = value => t(({ done: 'diagOutcome_done', 'tool-calls': 'diagOutcome_tool', 'max-tokens': 'diagOutcome_max', error: 'diagOutcome_error', aborted: 'diagOutcome_aborted' })[value] ?? 'diagOutcome_incomplete')
1052
1052
  const tone = value => value === 'done' || value === 'tool-calls' ? 'success' : value === 'error' ? 'error' : value === 'max-tokens' ? 'warn' : 'idle'
1053
1053
  const activeDetail = detail?.status === 'available' ? detail : null
@@ -132,18 +132,40 @@ function createHopWatchdog(userSignal, overrides = {}) {
132
132
  return [phase, Number.isFinite(proposed) && proposed > 0 ? proposed : fallback]
133
133
  }))
134
134
  let phase = 'initial-ttft', remaining = timeouts[phase]
135
+ let enteredThinking = false, enteredTransition = false
136
+ // Adjacent-only dedupe would let A/B/A/B alternation or a repeated two-signature
137
+ // frame look like fresh output. Remember every signature seen in this hop, with a
138
+ // bound so a hostile stream cannot grow the set without limit.
139
+ const seenSignatures = new Set()
135
140
  let timeoutError
136
141
  const userAbort = () => controller.abort(Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
137
142
  userSignal?.addEventListener('abort', userAbort, { once: true })
138
143
  if (userSignal?.aborted) userAbort()
139
144
  return {
140
145
  signal: controller.signal,
141
- update(parts) {
142
- const visible = parts.some(part => part.functionCall || (!part.thought && typeof part.text === 'string' && part.text.length > 0))
143
- if (visible || phase === 'streaming') phase = 'streaming'
144
- else if (parts.some(part => part.thought === true)) phase = 'thinking'
145
- else phase = 'transition'
146
- remaining = timeouts[phase]
146
+ update(parts, hasProgress = false) {
147
+ // A named function call or non-empty text is real output. An empty
148
+ // {} functionCall, an empty thought frame and a re-used thought signature
149
+ // are all pseudo progress that must never renew the idle budget.
150
+ const visible = parts.some(part => (part.functionCall && typeof part.functionCall === 'object' && typeof part.functionCall.name === 'string' && part.functionCall.name.length > 0) || (!part.thought && typeof part.text === 'string' && part.text.length > 0))
151
+ const anyThought = parts.some(part => part.thought === true)
152
+ const productiveThought = parts.some(part => part.thought === true && typeof part.text === 'string' && part.text.length > 0)
153
+ let newSignature = false
154
+ for (const part of parts) {
155
+ const sig = part.thoughtSignature ?? part.thought_signature
156
+ if (typeof sig === 'string' && sig.length > 0 && !seenSignatures.has(sig) && seenSignatures.size < 8192) {
157
+ seenSignatures.add(sig)
158
+ newSignature = true
159
+ }
160
+ }
161
+ const nextPhase = (visible || phase === 'streaming') ? 'streaming' : anyThought ? 'thinking' : 'transition'
162
+ phase = nextPhase
163
+ // Entering a phase counts once, so alternating empty frames cannot ping-pong
164
+ // between thinking and transition and keep resetting the budget.
165
+ const firstEntry = (nextPhase === 'thinking' && !enteredThinking) || (nextPhase === 'transition' && !enteredTransition)
166
+ if (nextPhase === 'thinking') enteredThinking = true
167
+ if (nextPhase === 'transition') enteredTransition = true
168
+ if (firstEntry || visible || productiveThought || newSignature || hasProgress) remaining = timeouts[phase]
147
169
  },
148
170
  async run(operation) {
149
171
  throwIfAborted(userSignal)
@@ -327,7 +349,6 @@ export async function continueArgonRequestStream(apiClient, original, request, m
327
349
  }
328
350
  const candidate = raw.candidates?.[0]
329
351
  const parts = candidate?.content?.parts ?? []
330
- watchdog.update(parts)
331
352
  hopSawThought ||= parts.some(part => part.thought === true)
332
353
  hopSawVisibleOrTool ||= parts.some(part => part.functionCall || (!part.thought && typeof part.text === 'string' && part.text.length > 0))
333
354
  if (hopSawVisibleOrTool) { thoughtParts = []; thoughtBytes = 0 }
@@ -343,6 +364,10 @@ export async function continueArgonRequestStream(apiClient, original, request, m
343
364
  const hasToken = typeof nextToken === 'string' && nextToken.length > 0
344
365
  if (hasToken) hopToken = nextToken
345
366
  const newCheckpoint = hasToken && nextToken !== token
367
+ // Renew the idle budget only for genuinely new progress: a repeated
368
+ // continuation token, a repeated finishReason or an empty thought frame
369
+ // must never extend a stalled hop.
370
+ watchdog.update(parts, Boolean(newCheckpoint || (candidate?.finishReason !== undefined && candidate.finishReason !== finishReason) || (!blocked && raw.promptFeedback?.blockReason)))
346
371
  if (candidate?.finishReason !== undefined) finishReason = candidate.finishReason
347
372
  blocked ||= Boolean(raw.promptFeedback?.blockReason)
348
373
  terminal ||= blocked || (finishReason !== undefined && finishReason !== 'CONTINUATION')
@@ -94,14 +94,16 @@ export function createGoogleSignatureBridge(context, model) {
94
94
  for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {
95
95
  bytes += Buffer.byteLength(JSON.stringify(part))
96
96
  if (bytes > 64 * 1024 * 1024) throw failure('Google response exceeded the bounded signature replay buffer.')
97
- const onlySignature = typeof part.thoughtSignature === 'string' && Object.keys(part).filter(key => part[key] !== undefined).every(key => key === 'thoughtSignature' || key === 'thought')
97
+ // A Part may serialize the signature in either wire spelling.
98
+ const sig = part.thoughtSignature ?? part.thought_signature
99
+ const onlySignature = typeof sig === 'string' && Object.keys(part).filter(key => part[key] !== undefined).every(key => key === 'thoughtSignature' || key === 'thought_signature' || key === 'thought')
98
100
  if (onlySignature) {
99
- if (!part.thoughtSignature || (part.thought !== undefined && typeof part.thought !== 'boolean')) throw failure('Google returned an invalid standalone signature.')
101
+ if (!sig || (part.thought !== undefined && typeof part.thought !== 'boolean')) throw failure('Google returned an invalid standalone signature.')
100
102
  bytes += 320 // Include the local versioned codec and content binding in the retention bound.
101
103
  if (bytes > 64 * 1024 * 1024) throw failure('Google signature replay metadata exceeded the bounded response buffer.')
102
104
  close()
103
105
  const block = { type: 'text', text: '' }, index = start(block)
104
- standalone.set(index, { signature: part.thoughtSignature, ...(part.thought === undefined ? {} : { thought: part.thought }) })
106
+ standalone.set(index, { signature: sig, ...(part.thought === undefined ? {} : { thought: part.thought }) })
105
107
  emit({ type: 'text_start', contentIndex: index }); emit({ type: 'text_end', contentIndex: index, content: '' })
106
108
  continue
107
109
  }
@@ -114,7 +116,7 @@ export function createGoogleSignatureBridge(context, model) {
114
116
  }
115
117
  const key = type === 'text' ? 'text' : 'thinking'
116
118
  current[key] += part.text
117
- if (part.thoughtSignature) current[type === 'text' ? 'textSignature' : 'thinkingSignature'] = part.thoughtSignature
119
+ if (sig) current[type === 'text' ? 'textSignature' : 'thinkingSignature'] = sig
118
120
  emit({ type: type === 'text' ? 'text_delta' : 'thinking_delta', contentIndex: content.length - 1, delta: part.text })
119
121
  }
120
122
  if (part.functionCall) {
@@ -122,7 +124,7 @@ export function createGoogleSignatureBridge(context, model) {
122
124
  const call = part.functionCall
123
125
  const id = call.id && !usedToolIds.has(call.id) ? call.id : 'argon_' + randomUUID().replaceAll('-', '')
124
126
  usedToolIds.add(id)
125
- const block = { type: 'toolCall', id, name: call.name || '', arguments: call.args ?? {}, ...(part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}) }
127
+ const block = { type: 'toolCall', id, name: call.name || '', arguments: call.args ?? {}, ...(sig ? { thoughtSignature: sig } : {}) }
126
128
  const index = start(block)
127
129
  emit({ type: 'toolcall_start', contentIndex: index })
128
130
  emit({ type: 'toolcall_delta', contentIndex: index, delta: JSON.stringify(block.arguments) })
@@ -87,7 +87,7 @@ export function createInspectorOperations(hub,{responseHub,query,readEvent}={})
87
87
  capture.observe('interaction-object',1,result.interaction)
88
88
  const retained=capture.finish('done')
89
89
  const status=result.interaction.status
90
- return {ok:true,queryId,capturedAt,identity:result.identity,remoteStatus:['in_progress','completed','requires_action','incomplete','failed','cancelled'].includes(status)?status:null,readOnly:true,retention:'memory-only',capture:retained}
90
+ return {ok:true,queryId,capturedAt,identity:result.identity,remoteStatus:['in_progress','completed','requires_action','incomplete','failed','cancelled','budget_exceeded'].includes(status)?status:null,readOnly:true,retention:'memory-only',capture:retained}
91
91
  }catch(error){return interactionQueryErrorResult(error,signal)}
92
92
  },
93
93
  readQueryResponse(request){return invoke('readQueryResponse',request,({queryId,...page})=>({ok:true,page:queries.read({id:queryId,sessionHash:null,...page})}))},
@@ -4,8 +4,10 @@ import { durableInteractionTransport } from './interaction-state.js'
4
4
  import { createArgonDiagnosticTracker } from './diagnostics.js'
5
5
  import { interactionExitReason } from './interaction-lifecycle.js'
6
6
  import { resolveServicePolicy } from './service-level.js'
7
+ // 循环导入:adapter.js 只在本模块的函数被调用时才读取这些绑定,函数声明本身已提升。
8
+ import { isProxyModel, resolveProxyUpstreamModel } from './adapter.js'
7
9
 
8
- const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'failed', 'cancelled'])
10
+ const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'failed', 'cancelled', 'budget_exceeded'])
9
11
  export function assertInteractionOptions(options, cfg, route) {
10
12
  const max = options.maxTokens ?? cfg.maxTokens
11
13
  if (!Number.isSafeInteger(max) || max <= 0 || max > cfg.maxTokens) throw new Error('Interactions output budget must be a positive integer within the configured effective cap.')
@@ -19,32 +21,56 @@ export function assertInteractionOptions(options, cfg, route) {
19
21
 
20
22
  export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, getRoutes, taskHub, recordDiagnostic, responseHub, structuredOutput }) {
21
23
  return async function* interactions(options, cfg) {
22
- const proxy = options.model === 'gemini-4-argon-proxy'
24
+ const proxy = isProxyModel(options.model)
23
25
  const route = proxy || options.model === 'gemini-4-argon-google' ? 'google-generative-ai' : 'google-vertex'
24
26
  const requestController = new AbortController()
25
27
  const signal = options.signal ? AbortSignal.any([options.signal, requestController.signal]) : requestController.signal
26
28
  let tracker, durable, claim, complete = false, usage, firstInput, firstCached, hopIndex = 0
27
29
  let finalOutcome = 'incomplete', finalError, exitReason = 'consumer-abandoned'
28
- let originalPromptClosed = false
30
+ let originalPromptClosed = false, firstModelOutputStopped = false, pendingBackoffMs = 0
29
31
  const modelOutputs = new Set()
30
32
  const observed = event => {
31
- if (event.event_type === 'step.start' && event.step?.type === 'model_output') modelOutputs.add(event.index)
33
+ const type = event.event_type ?? event.type
34
+ if (type === 'step.start' && event.step?.type === 'model_output') {
35
+ // The original prompt closes only when the next model_output step opens,
36
+ // which is the cross-hop (64K continuation) marker. A single-hop reply
37
+ // stops its model_output first and then reports its one and only usage on
38
+ // the following interaction.requires_action / interaction.completed; a
39
+ // function_call step of the same hop must not close it early, or that
40
+ // unique first-hop watermark would be discarded.
41
+ if (firstModelOutputStopped) originalPromptClosed = true
42
+ modelOutputs.add(event.index)
43
+ }
32
44
  const u = event.interaction?.usage ?? event.usage ?? event.metadata?.total_usage
33
45
  if (u && typeof u === 'object') {
34
46
  usage = { ...usage, ...u }
35
- if ((!originalPromptClosed || firstInput === undefined) && Number.isSafeInteger(u.total_input_tokens) && u.total_input_tokens > 0) {
36
- firstInput = u.total_input_tokens; firstCached = usage.total_cached_tokens ?? 0
47
+ // The first-hop watermark is only captured before the original prompt
48
+ // output closes; later 64K hops report cumulative inputs that must never
49
+ // overwrite it. A single-hop reply without model_output keeps it open.
50
+ if (!originalPromptClosed) {
51
+ // A legitimate zero input watermark is still a first-hop observation.
52
+ if (Number.isSafeInteger(u.total_input_tokens) && u.total_input_tokens >= 0) firstInput = u.total_input_tokens
53
+ if (firstInput !== undefined) {
54
+ if (Number.isSafeInteger(u.total_cached_tokens) && u.total_cached_tokens >= 0) firstCached = u.total_cached_tokens
55
+ else if (firstCached === undefined) firstCached = usage.total_cached_tokens ?? 0
56
+ }
37
57
  }
38
58
  }
39
- if (event.event_type === 'step.stop' && modelOutputs.has(event.index)) originalPromptClosed = true
59
+ if (type === 'step.stop' && modelOutputs.has(event.index)) firstModelOutputStopped = true
40
60
  }
41
- const recordUsage = reported => {
61
+ const recordUsage = () => {
62
+ // Only an observed first-hop input watermark may become a context value.
63
+ // Without one, later hops report cumulative inputs and a single-hop reply
64
+ // may report output tokens alone: an unknown input stays unknown instead of
65
+ // being recorded as a known zero.
66
+ const knownInitialInput = firstInput !== undefined ? firstInput + (usage?.total_tool_use_tokens ?? 0) : undefined
67
+ const knownInitialCache = firstInput !== undefined ? (firstCached ?? 0) : undefined
42
68
  tracker?.recordTokenUsage({
43
- reportedInputTokens: firstInput !== undefined ? firstInput + (usage?.total_tool_use_tokens ?? 0) : (reported ? reported.inputTokens + (reported.cacheReadTokens ?? 0) : undefined),
44
- reportedCacheTokens: firstCached ?? reported?.cacheReadTokens,
69
+ reportedInputTokens: knownInitialInput,
70
+ reportedCacheTokens: knownInitialCache,
45
71
  outputTokens: usage?.total_output_tokens,
46
72
  thoughtsTokens: usage?.total_thought_tokens,
47
- totalTokens: firstInput !== undefined && usage ? firstInput + (usage.total_output_tokens ?? 0) + (usage.total_thought_tokens ?? 0) + (usage.total_tool_use_tokens ?? 0) : reported?.totalTokens,
73
+ totalTokens: knownInitialInput !== undefined && usage ? knownInitialInput + (usage.total_output_tokens ?? 0) + (usage.total_thought_tokens ?? 0) : undefined,
48
74
  billedOutputTokens: usage?.total_output_tokens,
49
75
  billedThoughtsTokens: usage?.total_thought_tokens,
50
76
  billedToolTokens: usage?.total_tool_use_tokens ?? 0,
@@ -64,7 +90,10 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
64
90
  tracker = createArgonDiagnosticTracker({ route, model: options.model, protocol: 'interactions', background: cfg.interactionsBackground, apiVersion: connection.apiVersion, thinkingLevel: controls.reasoning.toUpperCase(), longDecode: controls.maxTokens > 65536, maxTokens: controls.maxTokens, sessionId: options.sessionId, requestedServiceTier: servicePolicy.tier }, recordDiagnostic, { responseHub, retainRawResponses: cfg.retainRawResponses })
65
91
  tracker?.setApiVersion(connection.apiVersion)
66
92
  const observe = async (operation, args, trigger) => {
67
- const hop = tracker?.beginHop({ hopIndex: ++hopIndex, trigger, usedContinuationToken: trigger !== 'interaction-create', backoffDelayMs: 0, body: operation === 'create' ? JSON.stringify(args[0]) : undefined })
93
+ // A reconnect hint observed by the stream belongs to the next resume hop.
94
+ const backoffDelayMs = trigger === 'interaction-create' ? 0 : pendingBackoffMs
95
+ pendingBackoffMs = 0
96
+ const hop = tracker?.beginHop({ hopIndex: ++hopIndex, trigger, usedContinuationToken: trigger !== 'interaction-create', backoffDelayMs, body: operation === 'create' ? JSON.stringify(args[0]) : undefined })
68
97
  let status, hopUsage
69
98
  const recordHopUsage = response => {
70
99
  const u = response?.interaction?.usage ?? response?.usage ?? response?.metadata?.total_usage
@@ -86,7 +115,10 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
86
115
  for await (const event of response) {
87
116
  tracker?.observeResponse('interaction-event', hopIndex, event)
88
117
  recordHopUsage(event)
89
- status = event.interaction?.status ?? event.status ?? status
118
+ // Dedicated 2026-05-20 terminal lifecycle events imply their own state.
119
+ const eventType = event.event_type ?? event.type
120
+ const impliedStatus = eventType === 'interaction.completed' ? 'completed' : eventType === 'interaction.requires_action' ? 'requires_action' : eventType === 'interaction.failed' ? 'failed' : eventType === 'interaction.cancelled' ? 'cancelled' : eventType === 'interaction.incomplete' ? 'incomplete' : eventType === 'interaction.budget_exceeded' ? 'budget_exceeded' : undefined
121
+ status = event.interaction?.status ?? event.status ?? impliedStatus ?? status
90
122
  hop?.onChunk({ status: 200, hasCheckpoint: Boolean(event.event_id), finishReason: terminalStates.has(status) ? status.toUpperCase() : undefined })
91
123
  yield event
92
124
  }
@@ -123,14 +155,18 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
123
155
  return block
124
156
  }) }))
125
157
  const { streamInteractions } = await import('./interactions.js')
126
- for await (const chunk of streamInteractions({ ...options, messages, signal }, { route, upstreamModel: proxy ? `gemini-4-argon-${controls.reasoning}` : 'gemini-4-argon', ...controls, serviceTier: route === 'google-generative-ai' ? servicePolicy.tier : undefined, background: cfg.interactionsBackground, store: cfg.allowInteractionStorage, transport, resolveImage, structuredOutput, onEvent: observed, onTerminal: () => { complete = true }, onExit: reason => { exitReason = reason } })) {
158
+ for await (const chunk of streamInteractions({ ...options, messages, signal }, { route, upstreamModel: proxy ? resolveProxyUpstreamModel(options.model, controls.reasoning) : 'gemini-4-argon', ...controls, serviceTier: route === 'google-generative-ai' ? servicePolicy.tier : undefined, background: cfg.interactionsBackground, store: cfg.allowInteractionStorage, transport, resolveImage, structuredOutput, onEvent: observed, onReconnectDelay: ms => { pendingBackoffMs = ms }, onTerminal: () => { complete = true }, onExit: reason => { exitReason = reason } })) {
127
159
  if (chunk.type === 'usage') {
128
- recordUsage(chunk.usage)
160
+ recordUsage()
161
+ // Only an observed first-hop input watermark can be normalized for the
162
+ // host. Without one, neither cumulative cross-hop inputs nor a missing
163
+ // single-hop input may be yielded: a fabricated zero would silently
164
+ // understate the context. The observed values survive in billed fields.
129
165
  if (firstInput !== undefined) {
130
166
  const output = (usage?.total_output_tokens ?? 0) + (usage?.total_thought_tokens ?? 0)
131
167
  yield { ...chunk, usage: { ...chunk.usage, inputTokens: Math.max(0, firstInput - (firstCached ?? 0)) + (usage?.total_tool_use_tokens ?? 0), cacheReadTokens: firstCached ?? 0, outputTokens: output, reasoningTokens: usage?.total_thought_tokens ?? 0, totalTokens: firstInput + output + (usage?.total_tool_use_tokens ?? 0) } }
132
- continue
133
168
  }
169
+ continue
134
170
  }
135
171
  if (chunk.type === 'finish') {
136
172
  complete ||= ['stop','tool-calls','max-tokens'].includes(chunk.reason.kind)
@@ -1,7 +1,24 @@
1
1
  // Local transport termination does not by itself cancel a stored cloud generation.
2
2
  export const HOST_SHUTDOWN_CODE = 'ARGON_HOST_SHUTDOWN'
3
3
 
4
+ // An in-stream error event whose code is not listed here is treated as a remote
5
+ // terminal state: the cloud task is already over, so no reconnect and no /cancel.
6
+ // 'unknown' stays recoverable because an unclassified frame proves nothing.
7
+ const RECOVERABLE_STREAM_ERROR_CODES = ['authentication', 'unavailable', 'internal', 'deadline_exceeded', 'gateway_timeout', 'resource_exhausted', 'aborted', 'unknown']
8
+
9
+ export function normalizeStreamErrorCode(code) {
10
+ return String(code ?? 'unknown').replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 64)
11
+ }
12
+
13
+ export function isRecoverableStreamErrorCode(code) {
14
+ return RECOVERABLE_STREAM_ERROR_CODES.includes(normalizeStreamErrorCode(code).toLowerCase())
15
+ }
16
+
4
17
  export function interactionExitReason(error, signal) {
18
+ // A remote terminal error outranks a simultaneous local abort: both can arrive
19
+ // on the same frame, and cancelling a task the cloud already finished would be
20
+ // wrong. The recovery handle is reconciled against the cloud instead.
21
+ if (error?.remoteTerminalError) return 'remote-error'
5
22
  if (signal?.aborted) {
6
23
  if (signal.reason?.code === HOST_SHUTDOWN_CODE) return 'host-shutdown'
7
24
  if (signal.reason?.name === 'TimeoutError') return 'read-interrupted'
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
2
  import { shared } from './runtime.js'
3
- import { HOST_SHUTDOWN_CODE, interactionExitReason, cancelsRemoteInteraction } from './interaction-lifecycle.js'
3
+ import { HOST_SHUTDOWN_CODE, interactionExitReason, cancelsRemoteInteraction, isRecoverableStreamErrorCode } from './interaction-lifecycle.js'
4
4
  const { z } = await shared('zod')
5
5
  const hash = value => createHash('sha256').update(value).digest('hex')
6
6
  const digest = z.string().regex(/^[a-f0-9]{64}$/)
@@ -97,10 +97,12 @@ export function durableInteractionTransport(base, hub, identity, { signal, onEve
97
97
  let task = hub.get(identity.key)
98
98
  if (task?.releasedAt) throw new Error('This attempt was released by the user; obtain a fresh request identity before creating another.')
99
99
  let terminal = false
100
+ let terminalStatus
100
101
  let lastEventId = task?.lastEventId ?? null
101
102
  let stopped = false
102
103
  let cancelPromise
103
- const isTerminal = status => ['completed', 'requires_action', 'incomplete', 'failed', 'cancelled'].includes(status)
104
+ let sawUnrecoverableError = false
105
+ const isTerminal = status => ['completed', 'requires_action', 'incomplete', 'failed', 'cancelled', 'budget_exceeded'].includes(status)
104
106
  async function save(stage = 'accepted') {
105
107
  task = await hub.put(identity, { stage, interactionId: task?.interactionId ?? null, lastEventId })
106
108
  }
@@ -110,8 +112,20 @@ export function durableInteractionTransport(base, hub, identity, { signal, onEve
110
112
  for await (const event of source) {
111
113
  const id = event.interaction?.id ?? event.interaction_id
112
114
  if (id && task?.interactionId && id !== task.interactionId) throw Object.assign(new Error('Interaction ID changed during recovery.'), { code: 'ARGON_INTERACTIONS_PROTOCOL' })
113
- const status = event.interaction?.status ?? event.status
114
- if (isTerminal(status)) terminal = true
115
+ // A dedicated 2026-05-20 terminal lifecycle event carries its own state.
116
+ const type = event.event_type ?? event.type
117
+ const status = event.interaction?.status ?? event.status ?? (
118
+ type === 'interaction.completed' ? 'completed' :
119
+ type === 'interaction.requires_action' ? 'requires_action' :
120
+ type === 'interaction.failed' ? 'failed' :
121
+ type === 'interaction.cancelled' ? 'cancelled' :
122
+ type === 'interaction.incomplete' ? 'incomplete' :
123
+ type === 'interaction.budget_exceeded' ? 'budget_exceeded' : undefined
124
+ )
125
+ if (isTerminal(status)) { terminal = true; terminalStatus = status }
126
+ // Only an unclassified error event claims a remote terminal state; the
127
+ // cloud task itself is re-probed before any recovery handle is dropped.
128
+ if (type === 'error' && !isRecoverableStreamErrorCode(event.error?.code)) sawUnrecoverableError = true
115
129
  if (event.event_id && event.event_id !== lastEventId) {
116
130
  lastEventId = event.event_id
117
131
  await save()
@@ -126,7 +140,7 @@ export function durableInteractionTransport(base, hub, identity, { signal, onEve
126
140
  async create(body) {
127
141
  signal?.throwIfAborted()
128
142
  if (task) {
129
- if (!task.interactionId) throw new Error('A previous background creation has an unknown outcome; refusing a duplicate billable POST. Open Vertex Argon settings > Background recovery to review and explicitly release the local block.')
143
+ if (!task.interactionId) throw new Error('A previous background creation has an unknown outcome; refusing a duplicate billable POST. Open Argon Inspector > Operations > Background Task Recovery to review and explicitly release the local block.')
130
144
  if (task.stage === 'cancel-failed') {
131
145
  await this.cancel(task.interactionId)
132
146
  throw new Error('The previous background task is now cancelled. Start the request again explicitly if still needed.')
@@ -138,6 +152,37 @@ export function durableInteractionTransport(base, hub, identity, { signal, onEve
138
152
  if (previous.releasedAt || previous.key === identity.key || previous.sessionHash !== identity.sessionHash) continue
139
153
  if (hub.isActive(previous.key) || !previous.interactionId) throw new Error('This session has an active or unknown-outcome background task; resolve it before creating another.')
140
154
  if (previous.endpointHash !== identity.endpointHash || previous.principalHash !== identity.principalHash) throw new Error('This session has an outstanding task on another route or credential; cancel it with its original configuration first.')
155
+ if (typeof base.get === 'function') {
156
+ // Reconcile the zombie lock against the cloud first: a task the provider
157
+ // already finished or dropped must not block this session forever. The
158
+ // prompt has already changed, so this old body is never replayed here.
159
+ let remote, remoteGone = false
160
+ // The probe is a final network read, so it is bounded like the
161
+ // cancellation confirmation instead of stalling the new prompt.
162
+ const probeSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(REMOTE_CANCEL_TIMEOUT_MS)]) : AbortSignal.timeout(REMOTE_CANCEL_TIMEOUT_MS)
163
+ try {
164
+ const probe = await base.get(previous.interactionId, { stream: false, signal: probeSignal })
165
+ if (probe && typeof probe === 'object' && typeof probe[Symbol.asyncIterator] !== 'function') remote = probe
166
+ else try { await probe?.return?.() } catch {}
167
+ } catch (error) {
168
+ // A 404 proves the remote task no longer exists. Every other failure
169
+ // (401/403/5xx/network) leaves cloud state unverified and keeps the lock.
170
+ if (error?.status === 404) remoteGone = true
171
+ }
172
+ if (remoteGone || (remote && ['failed', 'cancelled'].includes(remote.status))) {
173
+ // The cloud task is gone or already failed/cancelled: nothing is left
174
+ // to recover, so the dead record is dropped.
175
+ await hub.remove(previous.key)
176
+ continue
177
+ }
178
+ if (remote && isTerminal(remote.status)) {
179
+ // A completed / requires_action / incomplete / budget_exceeded task
180
+ // still owns un-replayed output. Keep its handle addressable by its own
181
+ // requestKey for a cold resume, but release the session-wide
182
+ // exclusivity so the new prompt may proceed.
183
+ continue
184
+ }
185
+ }
141
186
  throw new Error('This session has an outstanding remote task for another request; explicitly resolve it before creating another.')
142
187
  }
143
188
  // Persist intent before POST. Fetch cancellation is shielded only after dispatch,
@@ -171,11 +216,19 @@ export function durableInteractionTransport(base, hub, identity, { signal, onEve
171
216
  if (task?.interactionId) {
172
217
  // Keep a known ID recoverable even if persisting/consuming the first event failed.
173
218
  if (signal?.aborted && cancelsRemoteInteraction(interactionExitReason(signal.reason, signal))) { try { await this.cancel(task.interactionId) } catch {} }
219
+ // The remote task exists but its ID never reached an accepted record;
220
+ // retry the write once and cancel the cloud task if the disk still lags.
221
+ // A record already removed by a confirmed cancellation is not resurrected.
222
+ let persisted
223
+ try { persisted = hub.get(identity.key) } catch {}
224
+ if (persisted && persisted.interactionId !== task.interactionId) {
225
+ try { await save('accepted') } catch { try { await this.cancel(task.interactionId) } catch {} }
226
+ }
174
227
  } else if (error.requestSubmitted === false || [400, 401, 402, 403, 404, 405, 413, 415, 422, 429].includes(error.status)) {
175
228
  await hub.remove(identity.key); task = undefined
176
229
  } else {
177
230
  await save('unknown')
178
- error.message += ' Background creation outcome is unknown. Open Vertex Argon settings > Background recovery to review this record; no automatic resubmission was made.'
231
+ error.message += ' Background creation outcome is unknown. Open Argon Inspector > Operations > Background Task Recovery to review this record; no automatic resubmission was made.'
179
232
  error.code = 'ARGON_BACKGROUND_UNKNOWN'
180
233
  }
181
234
  throw error
@@ -213,7 +266,39 @@ export function durableInteractionTransport(base, hub, identity, { signal, onEve
213
266
  },
214
267
  async finish({ complete = false, reason = 'consumer-abandoned' } = {}) {
215
268
  if (stopped || !task) return
216
- if (complete && terminal) { await hub.remove(identity.key); return }
269
+ // A remote failure, cancellation or unrecoverable error stream is already
270
+ // terminal in the cloud: the local lock must go even when the local replay
271
+ // never completed. Completed, requires_action, incomplete and budget-exceeded
272
+ // results stay retained so an interrupted replay needs no new billable POST.
273
+ if ((complete && terminal) || ['failed','cancelled'].includes(terminalStatus)) { await hub.remove(identity.key); return }
274
+ // A local error frame is not proof of a remote terminal state. Verify the
275
+ // cloud task before dropping the recovery handle: a still-running task keeps
276
+ // its handle, a finished (or 404) one releases it.
277
+ if (reason === 'remote-error' || sawUnrecoverableError) {
278
+ // Without an addressable ID or a readable transport the cloud state stays
279
+ // unverified: retain the handle instead of dropping un-replayed output.
280
+ if (!task.interactionId || typeof base.get !== 'function') return
281
+ let probe
282
+ // The probe is a final network read, so it is bounded exactly like the
283
+ // cancellation confirmation instead of stalling the host turn.
284
+ try { probe = await base.get(task.interactionId, { stream: false, signal: AbortSignal.timeout(REMOTE_CANCEL_TIMEOUT_MS) }) } catch (error) {
285
+ if (error?.status === 404) await hub.remove(identity.key)
286
+ // Any other probe failure leaves cloud state unverified: keep the handle.
287
+ return
288
+ }
289
+ if (probe && typeof probe === 'object' && typeof probe[Symbol.asyncIterator] !== 'function') {
290
+ // Only a confirmed failed/cancelled cloud task proves the remote work is
291
+ // over. Completed, requires_action, incomplete, budget_exceeded, running
292
+ // and unknown states all keep their handle: an un-replayed result must
293
+ // never be discarded because of a local error frame.
294
+ if (['failed', 'cancelled'].includes(probe.status)) await hub.remove(identity.key)
295
+ return
296
+ }
297
+ // A streamed or non-object probe carries no authoritative status: close it
298
+ // and keep the handle rather than deciding on an unverified cloud state.
299
+ try { Promise.resolve(probe?.return?.()).catch(() => {}) } catch {}
300
+ return
301
+ }
217
302
  if (task.interactionId && !terminal && cancelsRemoteInteraction(reason)) await this.cancel(task.interactionId)
218
303
  // A completed remote task with an interrupted local replay is retained:
219
304
  // the next attempt can replay its missing output without another POST.
@@ -1,5 +1,6 @@
1
1
  import { shared } from './runtime.js'
2
2
  import { readBoundedJson } from './bounded-json.js'
3
+ import { parseUpstreamRetryDelayMs } from './generate-content.js'
3
4
  const { attributionHeaders } = await shared('@deepseek-ai/dsh-llm')
4
5
 
5
6
  // Raw REST avoids stale generated Interactions schemas; auth is refreshed per call.
@@ -158,7 +159,12 @@ export function createInteractionsTransport({ endpoint, getHeaders, fetchImpl =
158
159
  const message = status === 402
159
160
  ? 'Google Interactions request rejected for billing (HTTP 402 Payment Required). Check your Google prepaid credit balance and add credits if depleted. Do not retry automatically; requests cannot succeed until credits are added.'
160
161
  : 'Google Interactions request failed (HTTP ' + status + ').'
161
- throw transportError({ name: 'ApiError', code }, 'fetch', status, message)
162
+ // Only the documented bounded retry hint is read; the provider body is
163
+ // never parsed, so an echoing error body cannot reach diagnostics.
164
+ const retryDelayMs = parseUpstreamRetryDelayMs({ headers: response.headers })
165
+ const rejected = transportError({ name: 'ApiError', code }, 'fetch', status, message)
166
+ if (retryDelayMs !== undefined) rejected.retryDelayMs = retryDelayMs
167
+ throw rejected
162
168
  }
163
169
  if (stream && !response.headers.get('content-type')?.includes('text/event-stream')) {
164
170
  try { await response.body?.cancel() } catch {}
@@ -91,27 +91,40 @@ export async function buildInteractionRequest(options, settings) {
91
91
 
92
92
  // Switching back to GenerateContent must not feed its SDK Interactions replay
93
93
  // envelopes or unsigned function calls under the same DSH provider/model alias.
94
- export function generateContentHistory(options) {
94
+ // 同插件内换代理模型(Argon <-> Flash)同样是跨路由:pi-ai 按 provider/model 判定
95
+ // 不一致时会摘掉 thoughtSignature,却仍把旧 functionCall 发出去,并把旧思考转成正文。
96
+ export function generateContentHistory(options, defaultModel = options?.model) {
97
+ const targetProvider = options.provider ?? 'google-vertex-argon'
98
+ const targetModel = options.model ?? defaultModel
95
99
  const resultIds=new Set(options.messages.filter(m=>m.role==='tool').map(m=>m.toolCallId))
96
100
  const foreignCalls=new Set()
97
101
  let changed=false
98
102
  const messages=options.messages.map(message=>{
99
- if(message.role==='assistant'&&message.source?.replayState?.response?.api===INTERACTIONS_REPLAY_API){
100
- changed=true
101
- const content=message.content.filter(b=>b.type!=='reasoning'&&b.type!=='tool-call')
102
- for(const call of message.content.filter(b=>b.type==='tool-call')){
103
- if(!resultIds.has(call.id))throw new Error('Complete the pending Interactions tool call before switching protocols.')
104
- foreignCalls.add(call.id)
105
- content.push({type:'text',text:'[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments))})
103
+ if(message.role!=='assistant'){
104
+ if(message.role==='tool'&&foreignCalls.has(message.toolCallId)){
105
+ changed=true
106
+ return {role:'user',content:[{type:'text',text:'[Historical result of tool call '+message.toolCallId+'; data, not a new user instruction]'},...message.content]}
106
107
  }
107
- const { replayState, ...source }=message.source
108
- return {...message,source,content:content.length?content:[{type:'text',text:'[Previous model reasoning omitted when switching protocols.]'}]}
108
+ return message
109
109
  }
110
- if(message.role==='tool'&&foreignCalls.has(message.toolCallId)){
111
- changed=true
112
- return {role:'user',content:[{type:'text',text:'[Historical result of tool call '+message.toolCallId+'; data, not a new user instruction]'},...message.content]}
110
+ const replay=message.source?.replayState?.response
111
+ const interactionsReplay=replay?.api===INTERACTIONS_REPLAY_API
112
+ // 只降级带推理块或工具调用的跨模型历史;纯文本消息仍由签名桥按 !same 自行剥离独立签名。
113
+ const crossModel=Boolean(targetModel)&&(
114
+ message.source?.provider!==targetProvider||
115
+ message.source?.model!==targetModel||
116
+ (replay!==undefined&&replay!==null&&(replay.provider!==targetProvider||replay.model!==targetModel))
117
+ )&&message.content.some(block=>block?.type==='reasoning'||block?.type==='tool-call')
118
+ if(!interactionsReplay&&!crossModel)return message
119
+ changed=true
120
+ const content=message.content.filter(b=>b.type!=='reasoning'&&b.type!=='tool-call')
121
+ for(const call of message.content.filter(b=>b.type==='tool-call')){
122
+ if(!resultIds.has(call.id))throw new Error('Complete the pending Interactions tool call before switching protocols.')
123
+ foreignCalls.add(call.id)
124
+ content.push({type:'text',text:'[Previously executed tool '+call.name+'; call '+call.id+']\n'+JSON.stringify(argsOf(call.arguments))})
113
125
  }
114
- return message
126
+ const source=message.source?(({replayState,...rest})=>rest)(message.source):undefined
127
+ return {...message,...(source===undefined?{}:{source}),content:content.length?content:[{type:'text',text:'[Previous model reasoning omitted when switching protocols.]'}]}
115
128
  })
116
129
  return changed?{...options,messages}:options
117
130
  }
package/interactions.js CHANGED
@@ -2,15 +2,19 @@
2
2
  // https://ai.google.dev/api/interactions-api#Resource:InteractionSseStreamEvent
3
3
  // https://ai.google.dev/gemini-api/docs/long-decode#stream-long-decode
4
4
  import { buildInteractionRequest, contentHash, historyHash, INTERACTIONS_REPLAY_API } from './interactions-input.js'
5
- import { computeReconnectDelayMs, waitWithAbort } from './generate-content.js'
5
+ import { computeReconnectDelayMs, waitWithAbort, parseUpstreamRetryDelayMs, MAX_SERVER_RETRY_DELAY_MS } from './generate-content.js'
6
6
  import { fetchErrorCodes } from './diagnostics.js'
7
- import { interactionExitReason, cancelsRemoteInteraction } from './interaction-lifecycle.js'
7
+ import { interactionExitReason, cancelsRemoteInteraction, isRecoverableStreamErrorCode, normalizeStreamErrorCode } from './interaction-lifecycle.js'
8
8
  export { buildInteractionRequest } from './interactions-input.js'
9
- const terminal = new Set(['completed','requires_action','incomplete','failed','cancelled'])
9
+ const terminal = new Set(['completed','requires_action','incomplete','failed','cancelled','budget_exceeded'])
10
10
  const MAX_BYTES = 64*1024*1024
11
11
  const MAX_EVENTS = 65536
12
12
  function protocolError(message) { return Object.assign(new Error(message),{code:'ARGON_INTERACTIONS_PROTOCOL'}) }
13
- const retryable = e => e?.recoverableStreamError === true || !String(e?.code??'').startsWith('ARGON_') && (e?.status===undefined || e.status===408 || e.status===429 || e.status>=500 || (e.status>=200 && e.status<300 && ['stream','response-body'].includes(e.phase) && fetchErrorCodes(e).length>0))
13
+ const retryable = e => {
14
+ // A server asking for a longer wait than GenerateContent allows fails fast.
15
+ if(parseUpstreamRetryDelayMs(e) > MAX_SERVER_RETRY_DELAY_MS)return false
16
+ return e?.recoverableStreamError === true || !String(e?.code??'').startsWith('ARGON_') && (e?.status===undefined || e.status===408 || e.status===429 || e.status>=500 || (e.status>=200 && e.status<300 && ['stream','response-body'].includes(e.phase) && fetchErrorCodes(e).length>0))
17
+ }
14
18
  function validObject(value) { return value && typeof value==='object' && !Array.isArray(value) }
15
19
  function usageOf(raw) {
16
20
  const count=k=>Number.isSafeInteger(raw?.[k])&&raw[k]>=0?raw[k]:0
@@ -64,20 +68,44 @@ export async function* streamInteractions(options, settings) {
64
68
  if(id){if(interactionId&&interactionId!==id)throw protocolError('Interaction ID changed mid-stream.');interactionId=id}
65
69
  observeUsage(event)
66
70
  if(type==='interaction.created'||type==='interaction.status_update'||type==='interaction.completed'){
67
- status=event.interaction?.status??event.status??(type==='interaction.completed'?'completed':status)
68
- if(type==='interaction.completed')completedEvent=true
71
+ const nextStatus=event.interaction?.status??event.status??(type==='interaction.completed'?'completed':status)
72
+ // A confirmed terminal status is never rolled back by a later notice.
73
+ if(!terminal.has(status)||terminal.has(nextStatus))status=nextStatus
74
+ // A status_update carrying a failed/cancelled/over-budget state is itself the
75
+ // end of the stream: EOF must finalize it rather than retrying the hop.
76
+ // A plain completed status still waits for the dedicated completed event.
77
+ if(type==='interaction.completed'||(type==='interaction.status_update'&&['failed','cancelled','budget_exceeded'].includes(status)))completedEvent=true
78
+ return
79
+ }
80
+ // 2026-05-20 emits dedicated terminal lifecycle events instead of only
81
+ // interaction.completed; each one closes the stream on its own.
82
+ if(type==='interaction.in_progress'||type==='interaction.requires_action'||type==='interaction.failed'||type==='interaction.cancelled'||type==='interaction.incomplete'||type==='interaction.budget_exceeded'){
83
+ const implied=type.slice('interaction.'.length)
84
+ const nextStatus=event.interaction?.status??event.status??implied
85
+ // The same guard as status updates: a lifecycle notice for a task that has
86
+ // already reached a confirmed terminal state never rolls it back.
87
+ if(!terminal.has(status)||terminal.has(nextStatus))status=nextStatus
88
+ if(type!=='interaction.in_progress')completedEvent=true
69
89
  return
70
90
  }
71
91
  if(type==='error'){
72
- const code=String(event.error?.code??'unknown').replace(/[^A-Za-z0-9_.-]/g,'').slice(0,64)
92
+ const code=normalizeStreamErrorCode(event.error?.code)
73
93
  const error=protocolError('Interactions returned an error event ('+code+').')
74
94
  // Only retry the existing stored task, never create another paid task.
75
- error.recoverableStreamError=['authentication','unavailable','internal','deadline_exceeded'].includes(code)
95
+ error.recoverableStreamError=isRecoverableStreamErrorCode(code)
96
+ if(!error.recoverableStreamError){
97
+ // An unclassified error frame is not proof that the cloud task ended:
98
+ // nothing is reported as terminal until the cloud state is re-probed.
99
+ error.remoteTerminalError=true
100
+ status='failed'
101
+ }
76
102
  throw error
77
103
  }
78
104
  if(type==='step.start'){
79
105
  if(!Number.isSafeInteger(event.index)||event.index<0||event.index>4095||steps.has(event.index))throw protocolError('Invalid or duplicate step.start.')
80
106
  const step=event.step
107
+ // Replayed user-input steps are structural markers with no model output.
108
+ if(validObject(step)&&step.type==='user_input'){steps.set(event.index,{kind:'user_input',closed:false});progressVersion++;return}
81
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.')
82
110
  const state={kind:step.type,text:'',signature:step.signature,callId:step.id,name:step.name,argsValue:step.arguments,argsText:'',closed:false}
83
111
  steps.set(event.index,state);progressVersion++
@@ -88,6 +116,10 @@ export async function* streamInteractions(options, settings) {
88
116
  if(type==='step.delta'){
89
117
  const state=stateFor(event.index),delta=event.delta
90
118
  if(!validObject(delta))throw protocolError('Invalid step delta.')
119
+ if(state.kind==='user_input'){
120
+ if(state.closed)throw protocolError('Received a delta for an already closed step.')
121
+ return
122
+ }
91
123
  if(delta.type==='text_annotation_delta'&&state.kind==='model_output')return // additive citations; no DSH annotation block type
92
124
  if(delta.type==='text'&&state.kind==='model_output')yield*appendText(state,delta.text)
93
125
  else if(delta.type==='thought_summary'&&state.kind==='thought'){
@@ -110,6 +142,7 @@ export async function* streamInteractions(options, settings) {
110
142
  const state=stateFor(event.index)
111
143
  if(state.closed)throw protocolError('Duplicate step.stop without a replay cursor.')
112
144
  state.closed=true;progressVersion++
145
+ if(state.kind==='user_input')return
113
146
  if(state.kind==='function_call'){
114
147
  try{state.args=state.argsText?JSON.parse(state.argsText):(state.argsValue??{})}catch{state.invalidArguments=true}
115
148
  if(!validObject(state.args))state.invalidArguments=true
@@ -118,7 +151,12 @@ export async function* streamInteractions(options, settings) {
118
151
  }
119
152
  // Usage/status extensions may be added without rendering; unknown semantic
120
153
  // output events fail closed rather than silently losing generated content.
121
- if(typeof type==='string'&&type.startsWith('interaction.'))throw protocolError('Unknown interaction lifecycle event: '+type)
154
+ if(typeof type==='string'&&type.startsWith('interaction.')){
155
+ // Future non-content lifecycle notices and heartbeats must never abort a
156
+ // paid task; only an explicit error event is fatal. Their payload is
157
+ // unknown, so it must never overwrite an already confirmed status.
158
+ return
159
+ }
122
160
  throw protocolError('Unknown Interactions stream event.')
123
161
  }
124
162
  const cancel=async()=>{
@@ -140,9 +178,12 @@ export async function* streamInteractions(options, settings) {
140
178
  if(!stream?.[Symbol.asyncIterator])throw protocolError('Interactions create/get returned no event stream.')
141
179
  for await(const event of stream){signal?.throwIfAborted();yield*handle(event)}
142
180
  }catch(e){failure=e}
143
- signal?.throwIfAborted()
181
+ // A terminal frame or an unrecoverable failure decides the outcome before a
182
+ // simultaneous local abort: aborting must not rewrite it as a user stop and
183
+ // must not send /cancel to a remote task that already ended.
144
184
  if(!failure&&completedEvent&&terminal.has(status))break
145
185
  if(failure&&!retryable(failure))throw failure
186
+ signal?.throwIfAborted()
146
187
  if((!replayingWithoutCursor||lastEventId)&&progressVersion>beforeProgress)reconnects=0
147
188
  if(connections>=64||Date.now()>=deadline)throw Object.assign(new Error('Interactions recovery reached its connection or runtime bound.'),{code:'ARGON_INTERACTIONS_INTERRUPTED'})
148
189
  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'})
@@ -154,7 +195,11 @@ export async function* streamInteractions(options, settings) {
154
195
  steps.clear();blocks.clear();seenEvents.clear();emittedToolIds.clear()
155
196
  blockIndex=0;bytes=0;status=undefined;usage=undefined;completedEvent=false
156
197
  }else replayingWithoutCursor=false
157
- await waitWithAbort(computeReconnectDelayMs(++reconnects,settings.reconnectBackoff),signal)
198
+ const delayMs=computeReconnectDelayMs(++reconnects,settings.reconnectBackoff,parseUpstreamRetryDelayMs(failure))
199
+ await waitWithAbort(delayMs,signal)
200
+ // The transport options of get() stay byte-for-byte unchanged; hops only
201
+ // observe the suggested wait for diagnostics.
202
+ settings.onReconnectDelay?.(delayMs)
158
203
  connections++
159
204
  // Reconnect even if an early status said completed: drain the replayed
160
205
  // events through EOF before finalizing, as required by the long-decode guide.
@@ -164,7 +209,7 @@ export async function* streamInteractions(options, settings) {
164
209
  stream=(async function*(){throw e})()
165
210
  }
166
211
  }
167
- for(const state of steps.values())if(state.kind!=='function_call')yield*closeText(state)
212
+ for(const state of steps.values())if(state.kind!=='function_call'&&state.kind!=='user_input')yield*closeText(state)
168
213
  const toolStates=[...steps.values()].filter(s=>s.kind==='function_call')
169
214
  if(status==='completed'||status==='requires_action'){
170
215
  if([...steps.values()].some(state=>!state.closed))throw protocolError('Interactions completed before every step.stop was received.')
@@ -188,11 +233,12 @@ export async function* streamInteractions(options, settings) {
188
233
  const content=[...blocks.entries()].sort((a,b)=>a[0]-b[0]).map(([,block])=>block)
189
234
  const replaySteps=[]
190
235
  if(status==='completed'||status==='requires_action')for(const [,state]of [...steps.entries()].sort((a,b)=>a[0]-b[0])){
236
+ if(state.kind==='user_input')continue
191
237
  if(state.kind==='thought')replaySteps.push({type:'thought',...(state.signature?{signature:state.signature}:{}),...(state.text?{summary:[{type:'text',text:state.text}]}:{})})
192
238
  else if(state.kind==='model_output')replaySteps.push({type:'model_output',content:[{type:'text',text:state.text}]})
193
239
  else replaySteps.push({type:'function_call',id:state.callId,name:state.name,arguments:state.args})
194
240
  }
195
- const kind=status==='requires_action'||(status==='completed'&&toolStates.length)?'tool-calls':status==='completed'?'stop':status==='incomplete'?'max-tokens':status==='cancelled'?'aborted':'error'
241
+ const kind=status==='requires_action'||(status==='completed'&&toolStates.length)?'tool-calls':status==='completed'?'stop':(status==='incomplete'||status==='budget_exceeded')?'max-tokens':status==='cancelled'?'aborted':'error'
196
242
  const reason=['aborted','error'].includes(kind)?{kind,failure:{code:kind==='aborted'?'ABORTED':'ARGON_INTERACTIONS_FAILED',message:'Remote interaction '+status+'.'}}:{kind}
197
243
  finishedNormally=true
198
244
  exitReason='completed'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-vertex-argon",
3
- "version": "1.6.1",
3
+ "version": "1.6.3",
4
4
  "description": "Gemini API, Vertex AI and Antigravity Argon for DSH: resilient streaming, explicit service tiers and focused request diagnostics.",
5
5
  "license": "MIT",
6
6
  "repository": {