dsh-vertex-argon 1.6.1 → 1.6.2
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 +17 -0
- package/README.md +6 -6
- package/generate-content.js +32 -7
- package/google-signatures.js +7 -5
- package/inspector-service.js +1 -1
- package/interaction-adapter.js +49 -15
- package/interaction-lifecycle.js +17 -0
- package/interaction-state.js +92 -7
- package/interaction-transport.js +7 -1
- package/interactions.js +59 -13
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `dsh-vertex-argon` are documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.6.2] - 2026-10-26
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- **Interactions `2026-05-20` Lifecycle Events, Terminal Guards & `user_input` Replay (`interactions.js`, `interaction-lifecycle.js`, `inspector-service.js`)**:
|
|
9
|
+
- 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`).
|
|
10
|
+
- 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.
|
|
11
|
+
- 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.
|
|
12
|
+
- **Background Recovery Zombie-Lock Reconciliation & Conservative Error Probes (`interaction-state.js`)**:
|
|
13
|
+
- 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.
|
|
14
|
+
- 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.
|
|
15
|
+
- **Interactions `Retry-After` Backoff & First-Hop Input Watermark Window (`interaction-transport.js`, `interactions.js`, `interaction-adapter.js`)**:
|
|
16
|
+
- 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.
|
|
17
|
+
- 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`.
|
|
18
|
+
- **GenerateContent Watchdog Pseudo-Progress Hardening & Snake-Case Signature Replay (`generate-content.js`, `google-signatures.js`, `test/host-internals.mjs`)**:
|
|
19
|
+
- 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.
|
|
20
|
+
- 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.
|
|
21
|
+
|
|
5
22
|
## [1.6.1] - 2026-10-25
|
|
6
23
|
|
|
7
24
|
### Changed
|
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
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.
|
|
7
|
+
工程版本 **1.6.2**;兼容 **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
|
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
- **独立第三模型**:Antigravity 使用 `gemini-4-argon-proxy`,独立地址与专属密钥,不覆盖 Gemini API 模型。
|
|
14
14
|
- **GenerateContent 长解码**:单跳输出上限 `65,536`,输出预算配置最高 `1,048,576`,所有尝试共用 32 跳上限;支持检查点恢复、阶段超时、安全首包重试和仅思考结束自愈。
|
|
15
|
-
- **Interactions
|
|
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
|
|
|
@@ -46,7 +46,7 @@ Provider ID 保持 `google-vertex-argon`,模型位于 **Vertex Argon** 分组
|
|
|
46
46
|
- `proxyApiKey` 先去除首尾空白;有值时使用设置值,否则只读取 `ANTIGRAVITY_API_KEY`。
|
|
47
47
|
- **绝不回退到 Google/Vertex 密钥,也不把代理密钥送往 Google/Vertex。** 缺少专属密钥时应明确失败。
|
|
48
48
|
- 地址和密钥使用草稿输入,失焦或点击保存后提交,重置恢复默认值。填写的 Key 保存在插件配置中,密码框仅遮挡显示;也可留空并使用 DSH 凭据中的 `ANTIGRAVITY_API_KEY`,避免直接填写配置。设置实时更新时,模型列表缓存随之失效。
|
|
49
|
-
-
|
|
49
|
+
- 选中 `gemini-4-argon-proxy` 时,插件按推理档位(`low` / `medium` / `high`)将上游模型 ID 1:1 映射为 `gemini-4-argon-low`、`gemini-4-argon-medium`、`gemini-4-argon-high`(官方 Vertex AI 与 Gemini API 路由保持 `gemini-4-argon`)。代理沿用 Google 协议与服务层级配置;具体端点是否支持所选能力仍取决于代理实现,不是新增的云端验证结论。
|
|
50
50
|
|
|
51
51
|
## 完整配置:16 项
|
|
52
52
|
|
|
@@ -89,7 +89,7 @@ Vertex GenerateContent 通过 `X-Vertex-AI-LLM-Shared-Request-Type: priority`
|
|
|
89
89
|
实现见 [generate-content.js](<generate-content.js>);精确边界见 [协议合同](<docs/implementation/DECISIONS.md>)。开启 `longDecode` 后,Vertex 使用 `v1beta1`,Gemini API / Antigravity 使用 `v1beta`。关闭长解码仅禁用多跳/检查点续传与仅思考自愈,零交付初始重试和阶段超时仍可用。
|
|
90
90
|
|
|
91
91
|
1. **流内错误与服务端等待建议**:HTTP `200` 的 SSE 也可能包含顶层 `{ error }`。插件单独记录流内状态,解析 `Retry-After`、Google `details` 中的重试/配额恢复延时以及消息中的等待提示,取有效建议并加 `200ms` 余量,与本地退避共同决定等待;解析后的延时超过 `60s` 立即失败,不长期占用重试。
|
|
92
|
-
2. **每跳独立的阶段超时**:首包、思考、思考到可见输出的转换阶段各 `180s`,可见文本或工具流的滑动等待为 `120s`。每跳使用独立 `AbortController
|
|
92
|
+
2. **每跳独立的阶段超时**:首包、思考、思考到可见输出的转换阶段各 `180s`,可见文本或工具流的滑动等待为 `120s`。每跳使用独立 `AbortController`;仅真实进展(首次进入思考/转换阶段、非空文本、具名工具调用、本跳未见的新签名或新检查点)刷新等待预算,空帧、空思考帧、空工具对象与重复签名不续命。上游阻塞可终止,不把用户主动取消当作可恢复故障,也不让上一跳定时器影响下一跳;消费方暂停读取不消耗上游等待预算。
|
|
93
93
|
3. **首包安全重试与检查点恢复**:可恢复故障发生时,若本跳尚未向调用方 `yield` 任何分片,即使没有 `continuationToken` 也可 `retry-initial`,初次尝试之外最多重试 3 次;已有分片交付但没有检查点时不得整段重试。有检查点则丢弃未提交尾段并从检查点重连,同一检查点无进展也最多重试 3 次。**首个检查点之前实时 `yield`,不把整段输出全部缓存到检查点。**
|
|
94
94
|
4. **仅思考 STOP 自愈**:一跳只有思考、没有可见回答或工具调用,却以 `STOP` 结束时,最多追加一次 `thinking-dropout-heal`。有可用 token 则用 token 续写;没有则保留原思考与签名,追加 `model` 思考内容及 `user` 消息 `Continue and provide the final response or tool call.`。被安全规则阻止的回答不因此绕过限制;第二次仅思考结束不再循环。
|
|
95
95
|
|
|
@@ -116,7 +116,7 @@ billedOutputTokens, billedThoughtsTokens, billedToolTokens,
|
|
|
116
116
|
billedPromptTokens, billedCachedTokens, billedTotalTokens
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
-
每跳仅保留五项 Token 计数:`promptTokens`、`cachedTokens`、`outputTokens`、`thoughtsTokens`、`totalTokens
|
|
119
|
+
每跳仅保留五项 Token 计数:`promptTokens`、`cachedTokens`、`outputTokens`、`thoughtsTokens`、`totalTokens`。输入水位与跨跳累计用量分开:前者采用首跳原始输入口径(Interactions 在首个 `model_output` 结束并开启下一个 `model_output` 续跳前采集,同跳 `function_call` 不提前关闭;若首跳未报告输入则保持 `null` 且不向宿主交付伪造 `0` 或跨跳累计 `usage` 分片),后者保留各次上游尝试的观测计数,不混作上下文长度或价格。
|
|
120
120
|
|
|
121
121
|
### Operations:显式操作、独立权限
|
|
122
122
|
|
|
@@ -148,7 +148,7 @@ billedPromptTokens, billedCachedTokens, billedTotalTokens
|
|
|
148
148
|
|
|
149
149
|
## 历史实测:奥德赛七号全年舰长日志
|
|
150
150
|
|
|
151
|
-
> 以下是 **v1.5.0 历史云端实测**,保留用于说明长解码已有依据;**不是 v1.6.
|
|
151
|
+
> 以下是 **v1.5.0 历史云端实测**,保留用于说明长解码已有依据;**不是 v1.6.2 本轮新增 live 验证,也不能证明 Antigravity 或新增恢复分支已在云端验证**。本轮验证状态见 [验证账本](<docs/implementation/STATUS.md>)。
|
|
152
152
|
|
|
153
153
|
历史任务要求单回合连续输出 `DAY 001` 至 `DAY 365` 的全年日志,保持每日状态、每周维护、月末报告以及第 100/200/215/300/365 天的长期事件。原记录记载全年日志与状态台账完成;本文未重新运行或逐篇复核内容。
|
|
154
154
|
|
package/generate-content.js
CHANGED
|
@@ -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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
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')
|
package/google-signatures.js
CHANGED
|
@@ -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
|
-
|
|
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 (!
|
|
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:
|
|
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 (
|
|
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 ?? {}, ...(
|
|
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) })
|
package/inspector-service.js
CHANGED
|
@@ -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})}))},
|
package/interaction-adapter.js
CHANGED
|
@@ -5,7 +5,7 @@ import { createArgonDiagnosticTracker } from './diagnostics.js'
|
|
|
5
5
|
import { interactionExitReason } from './interaction-lifecycle.js'
|
|
6
6
|
import { resolveServicePolicy } from './service-level.js'
|
|
7
7
|
|
|
8
|
-
const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'failed', 'cancelled'])
|
|
8
|
+
const terminalStates = new Set(['completed', 'requires_action', 'incomplete', 'failed', 'cancelled', 'budget_exceeded'])
|
|
9
9
|
export function assertInteractionOptions(options, cfg, route) {
|
|
10
10
|
const max = options.maxTokens ?? cfg.maxTokens
|
|
11
11
|
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.')
|
|
@@ -25,26 +25,50 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
|
|
|
25
25
|
const signal = options.signal ? AbortSignal.any([options.signal, requestController.signal]) : requestController.signal
|
|
26
26
|
let tracker, durable, claim, complete = false, usage, firstInput, firstCached, hopIndex = 0
|
|
27
27
|
let finalOutcome = 'incomplete', finalError, exitReason = 'consumer-abandoned'
|
|
28
|
-
let originalPromptClosed = false
|
|
28
|
+
let originalPromptClosed = false, firstModelOutputStopped = false, pendingBackoffMs = 0
|
|
29
29
|
const modelOutputs = new Set()
|
|
30
30
|
const observed = event => {
|
|
31
|
-
|
|
31
|
+
const type = event.event_type ?? event.type
|
|
32
|
+
if (type === 'step.start' && event.step?.type === 'model_output') {
|
|
33
|
+
// The original prompt closes only when the next model_output step opens,
|
|
34
|
+
// which is the cross-hop (64K continuation) marker. A single-hop reply
|
|
35
|
+
// stops its model_output first and then reports its one and only usage on
|
|
36
|
+
// the following interaction.requires_action / interaction.completed; a
|
|
37
|
+
// function_call step of the same hop must not close it early, or that
|
|
38
|
+
// unique first-hop watermark would be discarded.
|
|
39
|
+
if (firstModelOutputStopped) originalPromptClosed = true
|
|
40
|
+
modelOutputs.add(event.index)
|
|
41
|
+
}
|
|
32
42
|
const u = event.interaction?.usage ?? event.usage ?? event.metadata?.total_usage
|
|
33
43
|
if (u && typeof u === 'object') {
|
|
34
44
|
usage = { ...usage, ...u }
|
|
35
|
-
|
|
36
|
-
|
|
45
|
+
// The first-hop watermark is only captured before the original prompt
|
|
46
|
+
// output closes; later 64K hops report cumulative inputs that must never
|
|
47
|
+
// overwrite it. A single-hop reply without model_output keeps it open.
|
|
48
|
+
if (!originalPromptClosed) {
|
|
49
|
+
// A legitimate zero input watermark is still a first-hop observation.
|
|
50
|
+
if (Number.isSafeInteger(u.total_input_tokens) && u.total_input_tokens >= 0) firstInput = u.total_input_tokens
|
|
51
|
+
if (firstInput !== undefined) {
|
|
52
|
+
if (Number.isSafeInteger(u.total_cached_tokens) && u.total_cached_tokens >= 0) firstCached = u.total_cached_tokens
|
|
53
|
+
else if (firstCached === undefined) firstCached = usage.total_cached_tokens ?? 0
|
|
54
|
+
}
|
|
37
55
|
}
|
|
38
56
|
}
|
|
39
|
-
if (
|
|
57
|
+
if (type === 'step.stop' && modelOutputs.has(event.index)) firstModelOutputStopped = true
|
|
40
58
|
}
|
|
41
|
-
const recordUsage =
|
|
59
|
+
const recordUsage = () => {
|
|
60
|
+
// Only an observed first-hop input watermark may become a context value.
|
|
61
|
+
// Without one, later hops report cumulative inputs and a single-hop reply
|
|
62
|
+
// may report output tokens alone: an unknown input stays unknown instead of
|
|
63
|
+
// being recorded as a known zero.
|
|
64
|
+
const knownInitialInput = firstInput !== undefined ? firstInput + (usage?.total_tool_use_tokens ?? 0) : undefined
|
|
65
|
+
const knownInitialCache = firstInput !== undefined ? (firstCached ?? 0) : undefined
|
|
42
66
|
tracker?.recordTokenUsage({
|
|
43
|
-
reportedInputTokens:
|
|
44
|
-
reportedCacheTokens:
|
|
67
|
+
reportedInputTokens: knownInitialInput,
|
|
68
|
+
reportedCacheTokens: knownInitialCache,
|
|
45
69
|
outputTokens: usage?.total_output_tokens,
|
|
46
70
|
thoughtsTokens: usage?.total_thought_tokens,
|
|
47
|
-
totalTokens:
|
|
71
|
+
totalTokens: knownInitialInput !== undefined && usage ? knownInitialInput + (usage.total_output_tokens ?? 0) + (usage.total_thought_tokens ?? 0) : undefined,
|
|
48
72
|
billedOutputTokens: usage?.total_output_tokens,
|
|
49
73
|
billedThoughtsTokens: usage?.total_thought_tokens,
|
|
50
74
|
billedToolTokens: usage?.total_tool_use_tokens ?? 0,
|
|
@@ -64,7 +88,10 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
|
|
|
64
88
|
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
89
|
tracker?.setApiVersion(connection.apiVersion)
|
|
66
90
|
const observe = async (operation, args, trigger) => {
|
|
67
|
-
|
|
91
|
+
// A reconnect hint observed by the stream belongs to the next resume hop.
|
|
92
|
+
const backoffDelayMs = trigger === 'interaction-create' ? 0 : pendingBackoffMs
|
|
93
|
+
pendingBackoffMs = 0
|
|
94
|
+
const hop = tracker?.beginHop({ hopIndex: ++hopIndex, trigger, usedContinuationToken: trigger !== 'interaction-create', backoffDelayMs, body: operation === 'create' ? JSON.stringify(args[0]) : undefined })
|
|
68
95
|
let status, hopUsage
|
|
69
96
|
const recordHopUsage = response => {
|
|
70
97
|
const u = response?.interaction?.usage ?? response?.usage ?? response?.metadata?.total_usage
|
|
@@ -86,7 +113,10 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
|
|
|
86
113
|
for await (const event of response) {
|
|
87
114
|
tracker?.observeResponse('interaction-event', hopIndex, event)
|
|
88
115
|
recordHopUsage(event)
|
|
89
|
-
|
|
116
|
+
// Dedicated 2026-05-20 terminal lifecycle events imply their own state.
|
|
117
|
+
const eventType = event.event_type ?? event.type
|
|
118
|
+
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
|
|
119
|
+
status = event.interaction?.status ?? event.status ?? impliedStatus ?? status
|
|
90
120
|
hop?.onChunk({ status: 200, hasCheckpoint: Boolean(event.event_id), finishReason: terminalStates.has(status) ? status.toUpperCase() : undefined })
|
|
91
121
|
yield event
|
|
92
122
|
}
|
|
@@ -123,14 +153,18 @@ export function createInteractionsHandler({ ctx, GoogleGenAI, resolveSecret, get
|
|
|
123
153
|
return block
|
|
124
154
|
}) }))
|
|
125
155
|
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 } })) {
|
|
156
|
+
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, onReconnectDelay: ms => { pendingBackoffMs = ms }, onTerminal: () => { complete = true }, onExit: reason => { exitReason = reason } })) {
|
|
127
157
|
if (chunk.type === 'usage') {
|
|
128
|
-
recordUsage(
|
|
158
|
+
recordUsage()
|
|
159
|
+
// Only an observed first-hop input watermark can be normalized for the
|
|
160
|
+
// host. Without one, neither cumulative cross-hop inputs nor a missing
|
|
161
|
+
// single-hop input may be yielded: a fabricated zero would silently
|
|
162
|
+
// understate the context. The observed values survive in billed fields.
|
|
129
163
|
if (firstInput !== undefined) {
|
|
130
164
|
const output = (usage?.total_output_tokens ?? 0) + (usage?.total_thought_tokens ?? 0)
|
|
131
165
|
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
166
|
}
|
|
167
|
+
continue
|
|
134
168
|
}
|
|
135
169
|
if (chunk.type === 'finish') {
|
|
136
170
|
complete ||= ['stop','tool-calls','max-tokens'].includes(chunk.reason.kind)
|
package/interaction-lifecycle.js
CHANGED
|
@@ -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'
|
package/interaction-state.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
114
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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.
|
package/interaction-transport.js
CHANGED
|
@@ -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
|
-
|
|
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 {}
|
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 =>
|
|
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
|
-
|
|
68
|
-
|
|
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=
|
|
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=
|
|
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.'))
|
|
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
|
-
|
|
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
|
-
|
|
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