dsh-vertex-argon 1.1.4 → 1.2.0

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/README.md CHANGED
@@ -12,9 +12,9 @@
12
12
 
13
13
  ---
14
14
 
15
- `dsh-vertex-argon` 为 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH) 提供完整的 **Gemini 4 Argon** 接入支持,自动聚合 **Google Vertex AI**(服务账号 / ADC)与 **Google Gemini Developer API**(AI Studio API Key)双通道,修复内置 `pi-ai` 适配器误传 `thinkingBudget` 导致的 `HTTP 400` 报错,完整打通原生三档思考、思维链(Thought Summaries)与带签名的多轮工具调用。
15
+ `dsh-vertex-argon` 为 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH) 提供完整的 **Gemini 4 Argon** 接入支持,自动聚合 **Google Vertex AI**(服务账号 / ADC)与 **Google Gemini Developer API**(AI Studio API Key)双通道,修复内置 `pi-ai` 适配器误传 `thinkingBudget` 导致的 `HTTP 400` 报错,完整打通原生三档思考、思维链(Thought Summaries)、`v1beta1` **Long Decode 跨段长生成自动续传**与带签名的多轮工具调用。
16
16
 
17
- Current release: **[1.1.3](https://github.com/higekibaka/dsh-vertex-argon)** · [npm](https://www.npmjs.com/package/dsh-vertex-argon)
17
+ Current release: **[1.2.0](https://github.com/higekibaka/dsh-vertex-argon)** · [npm](https://www.npmjs.com/package/dsh-vertex-argon)
18
18
 
19
19
  ---
20
20
 
@@ -25,6 +25,7 @@ Current release: **[1.1.3](https://github.com/higekibaka/dsh-vertex-argon)** ·
25
25
  | **思考控制参数** | 误判为旧模型并发送 `thinkingBudget: -1`,触发云端 `HTTP 400` | 原生发送 `thinkingLevel: "LOW" \| "MEDIUM" \| "HIGH"`,绝不传 `thinkingBudget` |
26
26
  | **思维链(思考摘要)** | 手动新增模型默认无 `reasoning` 标记,不请求摘要 | 固定开启 `includeThoughts: true`,流式解析 `thought: true` 实时展示思维链 |
27
27
  | **多轮工具调用回传** | 路由切换或签名不对齐时易丢失上下文 | 保持 `provider` / `model` 与 `thoughtSignature` 签名全链路一致 |
28
+ | **Long Decode 长生成** | Vertex 硬编码 `v1` 且锁死 64K,遇 `CONTINUATION` 直接抛错断流 | 自动切换 `v1beta1` 跨 64K 分段续传(最高 512K)、断流检查点恢复,按首跳输入上报水位防误压缩 |
28
29
  | **采样参数净化** | 可能携带被 Argon 拒绝或忽略的采样字段 | 自动剥离 `temperature`、`topP`、`topK` 等无效采样参数 |
29
30
  | **通道管理与设置** | 需手改 `cordis.patch.yml` 并反复排查校验报错 | 自动检测双通道 + 内置 **设置 → Vertex Argon** 图形化实时调节页面 |
30
31
 
@@ -40,7 +41,8 @@ flowchart TD
40
41
  V --> P["onPayload 请求级净化与注入"]
41
42
  G --> P
42
43
  P --> T["注入 thinkingLevel: LOW / MEDIUM / HIGH 与 includeThoughts: true<br/>剔除 thinkingBudget 与 temperature / topP / topK"]
43
- T --> S["Google GenAI Stream 响应"]
44
+ T --> L["v1beta1 Long Decode 续传引擎<br/>自动处理 CONTINUATION 跨段续接、断流检查点恢复与首跳输入计量"]
45
+ L --> S["Google GenAI Stream 响应"]
44
46
  S --> R1["thought: true → DSH 思维链面板"]
45
47
  S --> R2["functionCall + thoughtSignature → 原生工具卡片与多轮签名回放"]
46
48
  ```
@@ -102,11 +104,59 @@ dsh plugin --profile web add dsh-vertex-argon
102
104
  |---|---|---|---|
103
105
  | `showInModelPicker` | `true` | `true` / `false` | 是否在会话模型选择器中显示 `Vertex Argon` 分组(隐藏不影响已打开会话) |
104
106
  | `reasoning` | `medium` | `low` / `medium` / `high` | 默认思考档位,分别映射为原生 `LOW` / `MEDIUM` / `HIGH` |
105
- | `maxTokens` | `65536` | `1` – `65536` | 单次流式请求最大输出上限(含思考与正文 token,官方单次流式上限为 `65,536`) |
107
+ | `longDecode` | `true` | `true` / `false` | 是否启用 `v1beta1` Long Decode 跨段自动续传(含断流检查点恢复与首跳输入防误压缩) |
108
+ | `maxTokens` | `65536` | `1` – `524288` | 最大输出预算(默认 `65,536`;开启 `longDecode` 后最高可设为 `524,288` 跨 64K 分段续传) |
106
109
  | `contextWindow` | `1048576` | `1` – `1048576` | 输入、思考与输出共享的总上下文窗口(官方上限为 `1,048,576`) |
107
110
 
108
111
  ---
109
112
 
113
+ ## ⚠️ 与 `billion-context` 配合使用的兼容性说明
114
+
115
+ 在 `billion-context`(`0.1.196` / `0.1.197`)下启用 Google 通道代理时,存在两个属于代理侧处理链路的已知兼容性问题(均已向上游提交 Issue 并有对应修复 PR 跟进):
116
+
117
+ ### 1. Vertex AI 工具续答 `HTTP 400`(`user.parts` 顺序校验)
118
+
119
+ 工具执行完毕后,若 `billion-context` 向最后一条 `user` 消息追加压缩提醒(nudge),会形成 `[functionResponse, text]` 的数组顺序,触发 Vertex AI 报错:
120
+
121
+ > `HTTP 400: Requests ending with a model turn are not supported.`
122
+
123
+ - **根因说明**:报错文案具有一定误导性——实际请求仍以 `user` 角色结尾且工具结果完好,触发校验的真正原因是同一条 `user` 消息内的 **`parts` 排列顺序**(与 `dsh-vertex-argon` 的 `thinkingLevel` 或思考摘要配置无关)。
124
+ - **端点对照**:
125
+
126
+ | 最后一条 `user` 消息的 `parts` 顺序 | Google Vertex AI | Google Gemini Developer API |
127
+ |---|---|---|
128
+ | `[functionResponse]`(无追加提醒) | `200 OK`,正常续答 | `200 OK`,正常续答 |
129
+ | `[functionResponse, text]`(工具结果后追加提醒) | **`400 Bad Request`** | 未复现该顺序 `400` |
130
+ | `[text, functionResponse]`(普通文本置于工具结果前) | `200 OK`,正常续答 | `200 OK`,正常续答 |
131
+
132
+ - **修复归属**:`dsh-vertex-argon` 的 `onPayload` 钩子运行在 `billion-context` 介入之前,无法在前置阶段调整代理后续注入的提醒顺序;该问题需由 `billion-context` 在 Google 请求转换与提醒注入阶段(`coreToGoogle` / `appendGoogleNudge`)统一处理。
133
+ - 上游跟踪:[Issue #3159](https://github.com/ranxianglei/billion-context/issues/3159) · [PR #3167](https://github.com/ranxianglei/billion-context/pull/3167)
134
+
135
+ ### 2. 流式响应中独立 `thoughtSignature` 片段被过滤
136
+
137
+ 在完整 `billion-context` 流式处理链路中,Vertex AI 与 Gemini Developer API 返回的思考摘要文本(`thought: true`)均可完整保留,但**不携带文本的独立 `{ thoughtSignature: "..." }` SSE 片段**会被当前的 [Google loop adapter](https://github.com/ranxianglei/billion-context/blob/master/src/loop/adapter-google.ts) 跳过。
138
+
139
+ - **实际影响边界**:
140
+ - **工具调用签名(必需)**:绑定在 `functionCall` 上的签名若缺失会导致下一轮请求直接报 `400`;该类签名在正常工具调用中可随工具块保留。
141
+ - **独立输出签名(非严格校验)**:根据 [Google 官方文档](https://ai.google.dev/gemini-api/docs/generate-content/thought-signatures),非 `functionCall` 的独立签名用于跨轮次延续推理状态,缺失不会触发服务端 `400` 报错,但可能对长链路推理连贯性产生潜在影响。
142
+ - 上游跟踪:[Issue #3158](https://github.com/ranxianglei/billion-context/issues/3158) · [PR #3162](https://github.com/ranxianglei/billion-context/pull/3162)
143
+
144
+ ### 3. 上游修复合入前的临时规避方式
145
+
146
+ 在等待上游合并发版期间,若需在开启 `billion-context` 的环境中稳定使用 Vertex AI,可在生效的 `billion-context` 配置中对目标上游设置路由级透传(仅跳过该路由的代理改写与压缩,不影响其他通道):
147
+
148
+ ```json
149
+ {
150
+ "providers": {
151
+ "https://aiplatform.googleapis.com": { "passthrough": true }
152
+ }
153
+ }
154
+ ```
155
+
156
+ > **提示**:若使用区域级 Vertex 端点(如 `https://us-central1-aiplatform.googleapis.com`)或 Gemini Developer API(`https://generativelanguage.googleapis.com`),请按实际请求的域名填写。仅关闭 `compress.injectNudge` 无法规避独立签名片段丢失;设置 `passthrough: true` 后该路由将直接透传,不再执行 `billion-context` 上下文压缩。
157
+
158
+ ---
159
+
110
160
  ## ❓ 常见问题
111
161
 
112
162
  - **为什么极简问题有时候不显示思维链文本?**
package/adapter.js CHANGED
@@ -7,14 +7,21 @@ const { PiAiAdapter } = await shared('@deepseek-ai/dsh-llm-pi-ai')
7
7
  const { launchEnvironmentOf } = await shared('@deepseek-ai/dsh-launch-environment')
8
8
  const { googleVertexProvider } = await shared('@earendil-works/pi-ai/providers/google-vertex')
9
9
  const { googleProvider } = await shared('@earendil-works/pi-ai/providers/google')
10
+ const { GoogleGenAI } = await shared('@google/genai')
10
11
 
11
12
  export const PROVIDER = 'google-vertex-argon'
12
13
  export const NATIVE_PROVIDER = 'google-vertex'
13
14
  export const MODEL = 'gemini-4-argon'
14
15
  export const GOOGLE_API_MODEL = 'gemini-4-argon-google'
15
16
  export const LEVELS = ['low', 'medium', 'high']
17
+ export const MAX_SINGLE_CALL_TOKENS = 65536
18
+ export const MAX_LONG_DECODE_TOKENS = 524288
19
+ export const MAX_CONTINUATION_HOPS = 32
20
+ const MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS = 3
21
+ const COMPACTION_HEADROOM_FLOOR = 131072
16
22
  const ENV_KEYS = ['GOOGLE_APPLICATION_CREDENTIALS', 'GOOGLE_CLOUD_PROJECT', 'GCLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION', 'GOOGLE_CLOUD_API_KEY']
17
23
  const DEFAULT_THINKING_MAP = { off: null, minimal: null, low: 'low', medium: 'medium', high: 'high', xhigh: null, max: null }
24
+ const ARGON_LONG_DECODE_SYMBOL = Symbol.for('dsh.vertexArgon.longDecode')
18
25
 
19
26
  const readVal = v => (v && typeof v === 'object' && typeof v.get === 'function') ? v.get() : v
20
27
 
@@ -61,6 +68,282 @@ export function detectPiAiArgonRoutes(ctx, explicitRoutes) {
61
68
 
62
69
  const TRANSIENT_GEMINI_STOP_RE = /(?:Unhandled stop reason:\s*(?:MALFORMED_RESPONSE|MALFORMED_FUNCTION_CALL|UNEXPECTED_TOOL_CALL|TOO_MANY_TOOL_CALLS)|Provider stopped with:\s*(?:MALFORMED_RESPONSE|MALFORMED_FUNCTION_CALL|UNEXPECTED_TOOL_CALL|OTHER|FINISH_REASON_UNSPECIFIED))/i
63
70
 
71
+ function isEmptyPlaceholderPart(part) {
72
+ return Boolean(
73
+ part &&
74
+ typeof part === 'object' &&
75
+ part.text === '' &&
76
+ !part.thought &&
77
+ !part.thoughtSignature &&
78
+ !part.functionCall,
79
+ )
80
+ }
81
+
82
+ function hasMeaningfulPart(parts) {
83
+ return Array.isArray(parts) && parts.some(p =>
84
+ p &&
85
+ typeof p === 'object' &&
86
+ (p.thought || p.thoughtSignature || p.functionCall || (typeof p.text === 'string' && p.text.length > 0)),
87
+ )
88
+ }
89
+
90
+ function isAbortedError(err, signal) {
91
+ return Boolean(signal?.aborted) || (err instanceof Error && err.name === 'AbortError')
92
+ }
93
+
94
+ function isInitialApiRejection(err, receivedAnyChunk) {
95
+ return Boolean(
96
+ !receivedAnyChunk &&
97
+ err instanceof Error &&
98
+ (err.name === 'ApiError' || ('status' in err && typeof err.status === 'number')),
99
+ )
100
+ }
101
+
102
+ async function continueArgonRequestStream(apiClient, origRequestStream, request, meta) {
103
+ const { [ARGON_LONG_DECODE_SYMBOL]: _, ...restHttpOptions } = request?.httpOptions ?? {}
104
+ const enableContinuation = meta?.enabled !== false
105
+ if (
106
+ enableContinuation &&
107
+ typeof apiClient?.isVertexAI === 'function' &&
108
+ apiClient.isVertexAI() &&
109
+ !restHttpOptions.apiVersion &&
110
+ apiClient?.clientOptions?.httpOptions?.apiVersion === 'v1'
111
+ ) {
112
+ restHttpOptions.apiVersion = 'v1beta1'
113
+ }
114
+ const hopHttpOptions = Object.keys(restHttpOptions).length > 0 ? restHttpOptions : undefined
115
+ const firstReq = { ...request, httpOptions: hopHttpOptions }
116
+ const firstStream = await origRequestStream.call(apiClient, firstReq)
117
+ if (!enableContinuation) return firstStream
118
+
119
+ return (async function* () {
120
+ let baseBodyObj
121
+ let resumeToken
122
+ let reconnectsWithoutProgress = 0
123
+ let lastError
124
+ let hopCount = 0
125
+ let initialPromptTokens
126
+ let initialCachedTokens
127
+ let completedCandidatesTokens = 0
128
+ let completedThoughtsTokens = 0
129
+ let completedToolUsePromptTokens = 0
130
+ let completedBilledPromptTokens = 0
131
+ let completedBilledCachedTokens = 0
132
+ let completedBilledTotalTokens = 0
133
+ let openHop = async () => firstStream
134
+
135
+ while (true) {
136
+ hopCount += 1
137
+ const hopStartToken = resumeToken
138
+ let hopToken
139
+ let hopFinishReason
140
+ let hopHasPromptFeedback = false
141
+ let hopHasYieldedContent = false
142
+ let hopReceivedAnyChunk = false
143
+ let hopUsage
144
+ let hopError
145
+
146
+ try {
147
+ for await (const httpChunk of await openHop()) {
148
+ const raw = await httpChunk.json()
149
+ if (!raw || typeof raw !== 'object') {
150
+ yield { headers: httpChunk.headers, json: async () => raw }
151
+ continue
152
+ }
153
+ hopReceivedAnyChunk = true
154
+ if (raw.promptFeedback !== undefined && raw.promptFeedback !== null) {
155
+ hopHasPromptFeedback = true
156
+ }
157
+ let outRaw = raw
158
+ const candidate = Array.isArray(raw.candidates) ? raw.candidates[0] : undefined
159
+ if (candidate && typeof candidate === 'object') {
160
+ if (typeof candidate.continuationToken === 'string' && candidate.continuationToken.length > 0) {
161
+ hopToken = candidate.continuationToken
162
+ } else if (candidate.finishReason !== undefined && candidate.finishReason !== 'CONTINUATION') {
163
+ hopToken = undefined
164
+ }
165
+ if (candidate.finishReason !== undefined) {
166
+ hopFinishReason = candidate.finishReason
167
+ }
168
+ if (hasMeaningfulPart(candidate.content?.parts)) {
169
+ hopHasYieldedContent = true
170
+ }
171
+ const canContinueHop =
172
+ !hopHasPromptFeedback &&
173
+ Boolean(hopToken) &&
174
+ hopToken !== hopStartToken &&
175
+ hopCount < MAX_CONTINUATION_HOPS
176
+ if (candidate.finishReason === 'CONTINUATION' && canContinueHop) {
177
+ const nextCandidate = { ...candidate }
178
+ delete nextCandidate.finishReason
179
+ if (Array.isArray(nextCandidate.content?.parts)) {
180
+ const filteredParts = nextCandidate.content.parts.filter(p => !isEmptyPlaceholderPart(p))
181
+ nextCandidate.content = { ...nextCandidate.content, parts: filteredParts }
182
+ }
183
+ const nextCandidates = [...raw.candidates]
184
+ nextCandidates[0] = nextCandidate
185
+ outRaw = { ...outRaw, candidates: nextCandidates }
186
+ }
187
+ }
188
+ if (raw.usageMetadata && typeof raw.usageMetadata === 'object') {
189
+ const prompt = raw.usageMetadata.promptTokenCount ?? 0
190
+ const cached = raw.usageMetadata.cachedContentTokenCount ?? 0
191
+ const candidates = raw.usageMetadata.candidatesTokenCount ?? 0
192
+ const thoughts = raw.usageMetadata.thoughtsTokenCount ?? 0
193
+ const toolUsePrompt = raw.usageMetadata.toolUsePromptTokenCount ?? 0
194
+ const total = raw.usageMetadata.totalTokenCount ?? (prompt + candidates + thoughts + toolUsePrompt)
195
+ if (initialPromptTokens === undefined) initialPromptTokens = prompt
196
+ if (initialCachedTokens === undefined) initialCachedTokens = cached
197
+ hopUsage = { prompt, cached, candidates, thoughts, toolUsePrompt, total }
198
+ if (hopCount === 1) {
199
+ outRaw = {
200
+ ...outRaw,
201
+ usageMetadata: {
202
+ ...raw.usageMetadata,
203
+ initialPromptTokenCount: initialPromptTokens,
204
+ },
205
+ }
206
+ } else {
207
+ const mergedCandidates = completedCandidatesTokens + candidates
208
+ const mergedThoughts = completedThoughtsTokens + thoughts
209
+ const mergedToolUsePrompt = completedToolUsePromptTokens + toolUsePrompt
210
+ const mergedTotal = initialPromptTokens + mergedCandidates + mergedThoughts + mergedToolUsePrompt
211
+ outRaw = {
212
+ ...outRaw,
213
+ usageMetadata: {
214
+ ...raw.usageMetadata,
215
+ promptTokenCount: initialPromptTokens,
216
+ ...(initialCachedTokens > 0 || raw.usageMetadata.cachedContentTokenCount !== undefined
217
+ ? { cachedContentTokenCount: initialCachedTokens }
218
+ : {}),
219
+ candidatesTokenCount: mergedCandidates,
220
+ ...(mergedThoughts > 0 || raw.usageMetadata.thoughtsTokenCount !== undefined
221
+ ? { thoughtsTokenCount: mergedThoughts }
222
+ : {}),
223
+ ...(mergedToolUsePrompt > 0 || raw.usageMetadata.toolUsePromptTokenCount !== undefined
224
+ ? { toolUsePromptTokenCount: mergedToolUsePrompt }
225
+ : {}),
226
+ totalTokenCount: mergedTotal,
227
+ initialPromptTokenCount: initialPromptTokens,
228
+ billedPromptTokenCount: completedBilledPromptTokens + prompt,
229
+ billedCachedContentTokenCount: completedBilledCachedTokens + cached,
230
+ billedTotalTokenCount: completedBilledTotalTokens + total,
231
+ },
232
+ }
233
+ }
234
+ }
235
+ yield { headers: httpChunk.headers, json: async () => outRaw }
236
+ }
237
+ } catch (error) {
238
+ hopError = { error }
239
+ }
240
+
241
+ if (hopUsage) {
242
+ completedCandidatesTokens += hopUsage.candidates
243
+ completedThoughtsTokens += hopUsage.thoughts
244
+ completedToolUsePromptTokens += hopUsage.toolUsePrompt
245
+ completedBilledPromptTokens += hopUsage.prompt
246
+ completedBilledCachedTokens += hopUsage.cached
247
+ completedBilledTotalTokens += hopUsage.total
248
+ }
249
+
250
+ if (
251
+ hopError &&
252
+ (isAbortedError(hopError.error, request?.abortSignal) ||
253
+ isInitialApiRejection(hopError.error, hopReceivedAnyChunk))
254
+ ) {
255
+ throw hopError.error
256
+ }
257
+
258
+ const hasNewToken = Boolean(hopToken) && hopToken !== hopStartToken
259
+ const madeProgress = hopHasYieldedContent || hasNewToken
260
+ if (hopError) lastError = hopError
261
+ else if (madeProgress) lastError = undefined
262
+
263
+ if (hopCount >= MAX_CONTINUATION_HOPS || hopHasPromptFeedback) {
264
+ resumeToken = undefined
265
+ } else if (hopFinishReason !== undefined) {
266
+ if (hopFinishReason === 'CONTINUATION' && hasNewToken) {
267
+ resumeToken = hopToken
268
+ reconnectsWithoutProgress = 0
269
+ } else {
270
+ resumeToken = undefined
271
+ reconnectsWithoutProgress = 0
272
+ }
273
+ } else if (hasNewToken) {
274
+ resumeToken = hopToken
275
+ reconnectsWithoutProgress = 0
276
+ } else if (!hopHasYieldedContent && hopStartToken && reconnectsWithoutProgress < MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS) {
277
+ resumeToken = hopStartToken
278
+ reconnectsWithoutProgress += 1
279
+ } else {
280
+ resumeToken = undefined
281
+ }
282
+
283
+ const canResume =
284
+ Boolean(resumeToken) &&
285
+ !hopHasPromptFeedback &&
286
+ (hopFinishReason === 'CONTINUATION' || hopFinishReason === undefined)
287
+
288
+ if (canResume) {
289
+ if (!baseBodyObj) baseBodyObj = JSON.parse(request.body)
290
+ const nextReq = {
291
+ ...request,
292
+ body: JSON.stringify({ ...baseBodyObj, continuationToken: resumeToken }),
293
+ httpOptions: hopHttpOptions,
294
+ }
295
+ openHop = () => origRequestStream.call(apiClient, nextReq)
296
+ continue
297
+ }
298
+
299
+ if (hopError) throw hopError.error
300
+ if (hopFinishReason === undefined && !hopHasPromptFeedback && lastError) throw lastError.error
301
+ return
302
+ }
303
+ })()
304
+ }
305
+
306
+ let apiClientProtoRef = null
307
+ let origApiClientRequestStream = null
308
+
309
+ function getApiClientPrototype() {
310
+ if (apiClientProtoRef) return apiClientProtoRef
311
+ try {
312
+ const probe = new GoogleGenAI({ apiKey: 'argon-probe' })
313
+ if (probe?.apiClient) {
314
+ apiClientProtoRef = Object.getPrototypeOf(probe.apiClient)
315
+ }
316
+ } catch {}
317
+ return apiClientProtoRef
318
+ }
319
+
320
+ export function ensureGemini4ApiClientPatch() {
321
+ const proto = getApiClientPrototype()
322
+ if (!proto || typeof proto.requestStream !== 'function') return () => {}
323
+ if (origApiClientRequestStream) {
324
+ return () => {
325
+ if (proto.requestStream !== origApiClientRequestStream && origApiClientRequestStream) {
326
+ proto.requestStream = origApiClientRequestStream
327
+ origApiClientRequestStream = null
328
+ }
329
+ }
330
+ }
331
+ const orig = proto.requestStream
332
+ origApiClientRequestStream = orig
333
+ function patchedRequestStream(request) {
334
+ const meta = request?.httpOptions?.[ARGON_LONG_DECODE_SYMBOL]
335
+ if (!meta) return orig.call(this, request)
336
+ return continueArgonRequestStream(this, orig, request, meta)
337
+ }
338
+ proto.requestStream = patchedRequestStream
339
+ return () => {
340
+ if (proto.requestStream === patchedRequestStream) {
341
+ proto.requestStream = orig
342
+ }
343
+ origApiClientRequestStream = null
344
+ }
345
+ }
346
+
64
347
  function wrapGemini4Stream(rawStream) {
65
348
  if (!rawStream || typeof rawStream[Symbol.asyncIterator] !== 'function') return rawStream
66
349
  return {
@@ -82,16 +365,30 @@ function wrapGemini4Stream(rawStream) {
82
365
  }
83
366
  }
84
367
 
85
- export function gemini4StreamSimple(nativeStream, requestModel, context, options = {}, defaultLevel = 'medium', upstreamModelId = requestModel.id) {
368
+ export function gemini4StreamSimple(
369
+ nativeStream,
370
+ requestModel,
371
+ context,
372
+ options = {},
373
+ defaultLevel = 'medium',
374
+ upstreamModelId = requestModel.id,
375
+ longDecode = true,
376
+ ) {
377
+ ensureGemini4ApiClientPatch()
86
378
  const fallback = defaultLevel ?? (/cyber-permissive/i.test(requestModel?.id ?? '') ? 'high' : 'medium')
87
379
  const rawLevel = options.reasoning ?? fallback
88
380
  const mapped = requestModel?.thinkingLevelMap?.[rawLevel] ?? rawLevel
89
381
  const level = typeof mapped === 'string' ? mapped.toLowerCase() : fallback
90
382
  if (!LEVELS.includes(level)) throw new LlmError('Gemini 4 Argon requires low, medium or high.', 'UNSUPPORTED_REASONING_EFFORT')
91
383
  const { reasoning, thinking, thinkingBudgets, temperature, onPayload: prior, ...rest } = options
384
+ const requestedMaxTokens = options.maxTokens ?? requestModel.maxTokens
385
+ const effectiveMaxTokens =
386
+ longDecode === false && typeof requestedMaxTokens === 'number' && requestedMaxTokens > MAX_SINGLE_CALL_TOKENS
387
+ ? MAX_SINGLE_CALL_TOKENS
388
+ : requestedMaxTokens
92
389
  return wrapGemini4Stream(nativeStream(requestModel, context, {
93
390
  ...rest,
94
- maxTokens: options.maxTokens ?? requestModel.maxTokens,
391
+ maxTokens: effectiveMaxTokens,
95
392
  async onPayload(payload, payloadModel) {
96
393
  const replacement = await prior?.(payload, payloadModel)
97
394
  const body = replacement === undefined ? payload : replacement
@@ -102,18 +399,31 @@ export function gemini4StreamSimple(nativeStream, requestModel, context, options
102
399
  throw new LlmError('Gemini 4 Argon received an incompatible model payload.', 'INVALID_REQUEST')
103
400
  }
104
401
  const { temperature: _t, topP: _tp, topK: _tk, candidateCount: _cc, frequencyPenalty: _fp, presencePenalty: _pp, ...cleanConfig } = body.config
402
+ const prevHttpOptions =
403
+ cleanConfig.httpOptions && typeof cleanConfig.httpOptions === 'object' && !Array.isArray(cleanConfig.httpOptions)
404
+ ? cleanConfig.httpOptions
405
+ : {}
105
406
  return {
106
407
  ...body,
107
408
  model: upstreamModelId,
108
- config: { ...cleanConfig, thinkingConfig: { thinkingLevel: level.toUpperCase(), includeThoughts: true } },
409
+ config: {
410
+ ...cleanConfig,
411
+ automaticContinuation: false,
412
+ thinkingConfig: { thinkingLevel: level.toUpperCase(), includeThoughts: true },
413
+ httpOptions: {
414
+ ...prevHttpOptions,
415
+ [ARGON_LONG_DECODE_SYMBOL]: { enabled: longDecode !== false },
416
+ },
417
+ },
109
418
  }
110
419
  },
111
420
  }))
112
421
  }
113
422
 
114
423
  export function installGemini4PiAiPatch() {
424
+ const unpatchApiClient = ensureGemini4ApiClientPatch()
115
425
  const proto = PiAiAdapter?.prototype
116
- if (!proto || typeof proto.current !== 'function') return () => {}
426
+ if (!proto || typeof proto.current !== 'function') return unpatchApiClient
117
427
  const origCurrent = proto.current
118
428
  const patchedProviders = new Map()
119
429
  const ensureGemini4Capabilities = piProvider => {
@@ -135,7 +445,7 @@ export function installGemini4PiAiPatch() {
135
445
  patchedProviders.set(piProvider, origStreamSimple)
136
446
  piProvider.streamSimple = function (requestModel, context, options = {}) {
137
447
  if (isGemini4Model(requestModel)) {
138
- return gemini4StreamSimple((m, c, o) => piProvider.stream(m, c, o), requestModel, context, options, defaultReasoning, requestModel.id)
448
+ return gemini4StreamSimple((m, c, o) => piProvider.stream(m, c, o), requestModel, context, options, defaultReasoning, requestModel.id, true)
139
449
  }
140
450
  return origStreamSimple.call(this, requestModel, context, options)
141
451
  }
@@ -151,6 +461,7 @@ export function installGemini4PiAiPatch() {
151
461
  }
152
462
  proto.current = patchedCurrent
153
463
  return () => {
464
+ unpatchApiClient()
154
465
  if (proto.current === patchedCurrent) proto.current = origCurrent
155
466
  for (const [piProvider, origStreamSimple] of patchedProviders.entries()) {
156
467
  piProvider.streamSimple = origStreamSimple
@@ -163,15 +474,21 @@ export function resolveConfigValues(raw = {}) {
163
474
  const source = typeof raw === 'function' ? raw() : raw
164
475
  const showInModelPicker = readVal(source?.showInModelPicker) ?? true
165
476
  const reasoning = readVal(source?.reasoning) ?? 'medium'
477
+ const longDecode = readVal(source?.longDecode) ?? true
166
478
  const contextWindow = readVal(source?.contextWindow) ?? 1048576
167
- const maxTokens = readVal(source?.maxTokens) ?? 65536
479
+ const rawMaxTokens = readVal(source?.maxTokens) ?? MAX_SINGLE_CALL_TOKENS
168
480
  if (!LEVELS.includes(reasoning)) throw new LlmError('Invalid default Argon effort.', 'INVALID_CONFIG')
169
- for (const [key, val] of [['contextWindow', contextWindow], ['maxTokens', maxTokens]]) {
481
+ for (const [key, val] of [['contextWindow', contextWindow], ['maxTokens', rawMaxTokens]]) {
170
482
  if (!Number.isSafeInteger(val) || val <= 0) throw new LlmError('Invalid Argon ' + key, 'INVALID_CONFIG')
171
483
  }
484
+ const enabledLongDecode = Boolean(longDecode)
485
+ const capByMode = enabledLongDecode ? Math.min(rawMaxTokens, MAX_LONG_DECODE_TOKENS) : Math.min(rawMaxTokens, MAX_SINGLE_CALL_TOKENS)
486
+ const safeCompactionCap = contextWindow > COMPACTION_HEADROOM_FLOOR ? contextWindow - COMPACTION_HEADROOM_FLOOR : contextWindow
487
+ const maxTokens = Math.max(1, Math.min(capByMode, safeCompactionCap))
172
488
  return {
173
489
  showInModelPicker: Boolean(showInModelPicker),
174
490
  reasoning,
491
+ longDecode: enabledLongDecode,
175
492
  contextWindow,
176
493
  maxTokens,
177
494
  routes: source?.routes,
@@ -179,7 +496,7 @@ export function resolveConfigValues(raw = {}) {
179
496
  }
180
497
 
181
498
  /** Serve both Vertex AI Argon and Gemini API (google) Argon under the unified plugin group. */
182
- export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nativeGoogle = googleProvider()) {
499
+ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nativeGoogle = googleProvider(), longDecode = true) {
183
500
  const modelMap = new Map((Array.isArray(models) ? models : [models]).map(m => [m.id, m]))
184
501
  return {
185
502
  id: PROVIDER,
@@ -204,6 +521,7 @@ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nat
204
521
  { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), ...(apiKey ? { apiKey } : {}), maxTokens: options.maxTokens ?? configured.maxTokens },
205
522
  defaultLevel,
206
523
  MODEL,
524
+ longDecode,
207
525
  )
208
526
  }
209
527
  if (requestModel.api !== 'google-vertex') {
@@ -216,6 +534,7 @@ export function argonProvider(nativeVertex, models, defaultLevel = 'medium', nat
216
534
  { ...restOptions, ...(cleanEnv ? { env: cleanEnv } : {}), maxTokens: options.maxTokens ?? configured.maxTokens },
217
535
  defaultLevel,
218
536
  MODEL,
537
+ longDecode,
219
538
  )
220
539
  },
221
540
  }
@@ -263,6 +582,7 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
263
582
  const detected = detectPiAiArgonRoutes(ctx, cfg.routes)
264
583
  const key = JSON.stringify({
265
584
  r: cfg.reasoning,
585
+ ld: cfg.longDecode,
266
586
  cw: cfg.contextWindow,
267
587
  mt: cfg.maxTokens,
268
588
  v: detected.hasVertex,
@@ -329,14 +649,14 @@ export function createArgonAdapter(ctx, configInput, nativeVertex = googleVertex
329
649
  })
330
650
  }
331
651
  const configuredMaxTokens = new Map(models.map(m => [m.id, cfg.maxTokens]))
332
- const provider = argonProvider({ ...nativeVertex, auth }, models, cfg.reasoning, nativeGoogle)
652
+ const provider = argonProvider({ ...nativeVertex, auth }, models, cfg.reasoning, nativeGoogle, cfg.longDecode)
333
653
  cachedKey = key
334
654
  cachedProfiles = new Map([[PROVIDER, {
335
655
  provider: PROVIDER,
336
656
  displayName: 'Vertex Argon',
337
657
  piProvider: provider,
338
658
  reasoning: cfg.reasoning,
339
- streamIdleTimeoutMs: 300000,
659
+ streamIdleTimeoutMs: cfg.longDecode ? 600000 : 300000,
340
660
  maxRequestImageBytes: 20 * 1024 * 1024,
341
661
  requestImagePixelBudget: 2048 * 2048,
342
662
  requestImageMaxBytes: 1024 * 1024,
package/client.js CHANGED
@@ -7,7 +7,7 @@ window.__ModuleLoader__.load({
7
7
  const dictionaries = {
8
8
  zh: {
9
9
  title: 'Vertex Argon',
10
- subtitle: '自动聚合 Vertex AI 与 Gemini API 的 Argon 通道 · 原生三档思考与工具签名回传',
10
+ subtitle: '自动聚合 Vertex AI 与 Gemini API 的 Argon 通道 · 原生三档思考、Long Decode 自动续传与工具签名回传',
11
11
  show: '在模型选择器中显示 Vertex Argon 分组',
12
12
  showHint: '控制是否在会话模型选择器中列出 Vertex Argon 分组下的模型。正在使用该模型的会话不受隐藏影响。',
13
13
  visible: '已显示',
@@ -17,8 +17,12 @@ window.__ModuleLoader__.load({
17
17
  level_low: 'Low(低)',
18
18
  level_medium: 'Medium(默认)',
19
19
  level_high: 'High(高)',
20
- maxTokensLabel: '单次流式最大输出(Max Output Tokens)',
21
- maxTokensHint: '官方单次流式请求上限为 65,536 tokens(含思考与正文输出),这是上限而非固定消耗。',
20
+ longDecodeLabel: '长生成自动续传(Long Decode Continuation)',
21
+ longDecodeHint: '开启后自动走 v1beta1 端点并处理 CONTINUATION 令牌与断流检查点恢复;多段续传时按首跳输入上报上下文水位,避免误触发自动压缩。',
22
+ longDecodeOn: '已开启',
23
+ longDecodeOff: '已关闭',
24
+ maxTokensLabel: '最大输出预算(Max Output Tokens)',
25
+ maxTokensHint: '默认 65,536 tokens(单次流式上限);开启 Long Decode 后最高可设为 524,288 tokens(跨 64K 分段自动续传,与输入共享 1M 总窗口)。',
22
26
  contextWindowLabel: '共享上下文窗口(Context Window)',
23
27
  contextWindowHint: '官方总窗口为 1,048,576 tokens,由输入、思考和输出共同共享。',
24
28
  resetDefaults: '恢复官方默认配置',
@@ -29,15 +33,15 @@ window.__ModuleLoader__.load({
29
33
  unavailable: '当前连接无法修改宿主设置。',
30
34
  how: '自动检测与使用方法',
31
35
  step1: '自动检测:只要在 DSH「设置 → 模型」的 Google(Gemini API)或 Google Vertex AI 中添加了 gemini-4-argon,本插件分组下就会自动出现对应的「Gemini 4 Argon (Vertex AI)」与「Gemini 4 Argon (Gemini API)」。',
32
- step2: '凭据复用:Vertex AI 通道自动读取 Windows 环境变量(GOOGLE_APPLICATION_CREDENTIALS / GOOGLE_CLOUD_PROJECT / GOOGLE_CLOUD_LOCATION);Gemini API 通道自动复用 Google 提供商配置的 GOOGLE_API_KEY。',
36
+ step2: '凭据复用:Vertex AI 通道自动读取环境变量(GOOGLE_APPLICATION_CREDENTIALS / GOOGLE_CLOUD_PROJECT / GOOGLE_CLOUD_LOCATION);Gemini API 通道自动复用 Google 提供商配置的 GOOGLE_API_KEY。',
33
37
  step3: '在会话模型选择器中选择 Vertex Argon 分组下的对应模型,即可正常切换 Low / Medium / High 三档并查看思维链与工具调用卡片。',
34
38
  scope: '通道特性与双保险',
35
- detail: '本插件不仅在 Vertex Argon 分组下提供完整支持 thought: true 思考摘要与 thoughtSignature 签名回传的模型入口,还同时为原生的 google 与 google-vertex 路由注入了 Gemini 4 thinkingLevel 兼容补丁,即使误选原分组条目也不会再报 thinkingBudget 400 错误。',
39
+ detail: '本插件不仅提供完整支持 thought: true 思考摘要、thoughtSignature 签名回传与 v1beta1 Long Decode 自动续传的模型入口,还同时为原生的 google 与 google-vertex 路由注入了 Gemini 4 兼容补丁。',
36
40
  route: '提供方路由:google-vertex-argon · 模型 ID:gemini-4-argon (Vertex AI) / gemini-4-argon-google (Gemini API)',
37
41
  },
38
42
  en: {
39
43
  title: 'Vertex Argon',
40
- subtitle: 'Auto-detected Vertex AI & Gemini API Argon routes · native thinking levels & signed tool replay',
44
+ subtitle: 'Auto-detected Vertex AI & Gemini API Argon routes · native thinking levels, Long Decode continuation & signed tool replay',
41
45
  show: 'Show Vertex Argon group in the model picker',
42
46
  showHint: 'Controls whether Vertex Argon models appear in the model picker. Active conversations are unaffected.',
43
47
  visible: 'Visible',
@@ -47,8 +51,12 @@ window.__ModuleLoader__.load({
47
51
  level_low: 'Low',
48
52
  level_medium: 'Medium (Default)',
49
53
  level_high: 'High',
50
- maxTokensLabel: 'Single-Request Max Output Tokens',
51
- maxTokensHint: 'Official per-request streaming cap is 65,536 tokens (thinking + response combined).',
54
+ longDecodeLabel: 'Long Decode Automatic Continuation',
55
+ longDecodeHint: 'Routes Vertex AI via v1beta1 and automatically resumes CONTINUATION tokens and mid-stream checkpoints while preserving first-hop prompt token accounting for compaction.',
56
+ longDecodeOn: 'Enabled',
57
+ longDecodeOff: 'Disabled',
58
+ maxTokensLabel: 'Max Output Budget (Max Output Tokens)',
59
+ maxTokensHint: 'Defaults to 65,536 tokens (single-request streaming cap). With Long Decode enabled, up to 524,288 tokens can be generated across 64K continuation hops.',
52
60
  contextWindowLabel: 'Shared Context Window',
53
61
  contextWindowHint: 'Official 1,048,576-token window shared across input, thinking, and output tokens.',
54
62
  resetDefaults: 'Restore Official Defaults',
@@ -62,7 +70,7 @@ window.__ModuleLoader__.load({
62
70
  step2: 'Credential reuse: Vertex AI uses GOOGLE_APPLICATION_CREDENTIALS / GOOGLE_CLOUD_PROJECT / GOOGLE_CLOUD_LOCATION; Gemini API reuses your configured GOOGLE_API_KEY.',
63
71
  step3: 'Select either model under Vertex Argon in the model picker for full Low / Medium / High thinking summaries and tool calls.',
64
72
  scope: 'Scope & fallback protection',
65
- detail: 'In addition to the dedicated Vertex Argon group, this plugin patches native google and google-vertex Gemini 4 requests so selecting the original entries also sends thinkingLevel instead of thinkingBudget.',
73
+ detail: 'In addition to the dedicated Vertex Argon group with Long Decode continuation, this plugin patches native google and google-vertex Gemini 4 requests so selecting the original entries also sends thinkingLevel instead of thinkingBudget.',
66
74
  route: 'Provider route: google-vertex-argon · Models: gemini-4-argon (Vertex AI) / gemini-4-argon-google (Gemini API)',
67
75
  },
68
76
  }
@@ -130,6 +138,7 @@ window.__ModuleLoader__.load({
130
138
  const val = state.value || {}
131
139
  const visible = val.showInModelPicker !== false
132
140
  const reasoning = val.reasoning || 'medium'
141
+ const longDecode = val.longDecode !== false
133
142
  const maxTokens = val.maxTokens || 65536
134
143
  const contextWindow = val.contextWindow || 1048576
135
144
  const disabled = pending || state.status !== 'ready' || !state.writable
@@ -148,14 +157,18 @@ window.__ModuleLoader__.load({
148
157
  try {
149
158
  const ok1 = await form.set('showInModelPicker', true)
150
159
  const ok2 = await form.set('reasoning', 'medium')
151
- const ok3 = await form.set('maxTokens', 65536)
152
- const ok4 = await form.set('contextWindow', 1048576)
153
- setNotice(ok1 && ok2 && ok3 && ok4 ? 'saved' : 'error')
160
+ const ok3 = await form.set('longDecode', true)
161
+ const ok4 = await form.set('maxTokens', 65536)
162
+ const ok5 = await form.set('contextWindow', 1048576)
163
+ setNotice(ok1 && ok2 && ok3 && ok4 && ok5 ? 'saved' : 'error')
154
164
  } catch { setNotice('error') }
155
165
  finally { setPending(false) }
156
166
  }
157
167
 
158
168
  const fmt = n => Number(n).toLocaleString()
169
+ const maxTokenCaps = longDecode
170
+ ? [8192, 16384, 32768, 65536, 131072, 262144, 524288]
171
+ : [8192, 16384, 32768, 65536]
159
172
 
160
173
  return h('section', { className: 'local-vertex-argon', 'aria-label': t('title') },
161
174
  h('style', null,
@@ -203,9 +216,19 @@ window.__ModuleLoader__.load({
203
216
  ),
204
217
  h('div', { className: 'card' },
205
218
  h('div', { className: 'row' },
219
+ h('strong', { id: 'vertex-argon-longdecode-label' }, t('longDecodeLabel')),
220
+ h('button', {
221
+ type: 'button', role: 'switch', 'aria-checked': longDecode,
222
+ 'aria-labelledby': 'vertex-argon-longdecode-label',
223
+ 'aria-describedby': 'vertex-argon-longdecode-hint',
224
+ disabled, onClick: () => updateField('longDecode', !longDecode),
225
+ }, t(pending ? 'saving' : longDecode ? 'longDecodeOn' : 'longDecodeOff')),
226
+ ),
227
+ h('p', { className: 'muted', id: 'vertex-argon-longdecode-hint' }, t('longDecodeHint')),
228
+ h('div', { className: 'row', style: { marginTop: '16px' } },
206
229
  h('strong', null, t('maxTokensLabel') + ' (' + fmt(maxTokens) + ')'),
207
230
  h('div', { className: 'group', role: 'group', 'aria-label': t('maxTokensLabel') },
208
- ...[8192, 16384, 32768, 65536].map(cap =>
231
+ ...maxTokenCaps.map(cap =>
209
232
  h('button', {
210
233
  key: cap, type: 'button', 'aria-pressed': maxTokens === cap,
211
234
  disabled, onClick: () => updateField('maxTokens', cap),
package/index.js CHANGED
@@ -1,14 +1,25 @@
1
1
  import { shared } from './runtime.js'
2
2
  const { default: z } = await shared('@deepseek-ai/schemastery')
3
- import { createArgonAdapter, installGemini4PiAiPatch, resolveConfigValues, detectPiAiArgonRoutes, PROVIDER, NATIVE_PROVIDER, LEVELS } from './adapter.js'
3
+ import {
4
+ createArgonAdapter,
5
+ installGemini4PiAiPatch,
6
+ resolveConfigValues,
7
+ detectPiAiArgonRoutes,
8
+ PROVIDER,
9
+ NATIVE_PROVIDER,
10
+ LEVELS,
11
+ MAX_SINGLE_CALL_TOKENS,
12
+ MAX_LONG_DECODE_TOKENS,
13
+ } from './adapter.js'
4
14
 
5
15
  export const name = 'local-vertex-argon'
6
16
  export const inject = ['llm']
7
17
  export const Config = z.object({
8
18
  showInModelPicker: z.boolean().default(true).volatile(),
9
19
  reasoning: z.union(LEVELS).default('medium').volatile(),
20
+ longDecode: z.boolean().default(true).volatile(),
10
21
  contextWindow: z.number().step(1).min(1).max(1048576).default(1048576).volatile(),
11
- maxTokens: z.number().step(1).min(1).max(65536).default(65536).volatile(),
22
+ maxTokens: z.number().step(1).min(1).max(MAX_LONG_DECODE_TOKENS).default(MAX_SINGLE_CALL_TOKENS).volatile(),
12
23
  })
13
24
 
14
25
  export function apply(ctx, config) {
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Vertex Argon",
4
- "description": "Native Low / Medium / High thinking levels, thought summaries, signed tool replay, and dedicated settings page."
4
+ "description": "Native Low / Medium / High thinking levels, thought summaries, Long Decode continuation, signed tool replay, and dedicated settings page."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Vertex Argon",
4
- "description": "原生 Low / Medium / High 三档思考、思考摘要与工具调用签名回传;含专属设置页。"
4
+ "description": "原生 Low / Medium / High 三档思考、思考摘要、Long Decode 跨段自动续传与工具调用签名回传;含专属设置页。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-vertex-argon",
3
- "version": "1.1.4",
4
- "description": "Google Vertex AI & Gemini API Argon plugin for DeepSeek Harness — native Low/Medium/High thinking levels, thought summaries, signed tool-call replay, and dedicated Settings UI.",
3
+ "version": "1.2.0",
4
+ "description": "Google Vertex AI & Gemini API Argon plugin for DeepSeek Harness — native Low/Medium/High thinking levels, v1beta1 Long Decode continuation, thought summaries, signed tool-call replay, and dedicated Settings UI.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
package/runtime.js CHANGED
@@ -2,21 +2,48 @@ import { createRequire, findPackageJSON } from 'node:module'
2
2
  import { pathToFileURL } from 'node:url'
3
3
  import { dirname, resolve } from 'node:path'
4
4
 
5
+ function findPiAiManifest(host) {
6
+ for (const anchor of [import.meta.url, host].filter(Boolean)) {
7
+ try {
8
+ const direct = findPackageJSON('@earendil-works/pi-ai', anchor)
9
+ if (direct) return direct
10
+ } catch {}
11
+ try {
12
+ const llmPi = findPackageJSON('@deepseek-ai/dsh-llm-pi-ai', anchor)
13
+ if (llmPi) {
14
+ const nested = findPackageJSON('@earendil-works/pi-ai', pathToFileURL(llmPi))
15
+ if (nested) return nested
16
+ }
17
+ } catch {}
18
+ }
19
+ return undefined
20
+ }
21
+
5
22
  // DSH desktop hosts plugins outside its ASAR dependency tree. Resolve shared
6
23
  // services from the running host entry, never install a second service copy.
7
24
  export async function shared(specifier) {
8
25
  try { return await import(specifier) }
9
26
  catch (error) {
10
- if (error.code !== 'ERR_MODULE_NOT_FOUND' || !process.argv[1]) throw error
11
- const host = pathToFileURL(process.argv[1])
12
- const require = createRequire(host)
27
+ if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error
28
+ const host = process.argv[1] ? pathToFileURL(process.argv[1]) : undefined
13
29
  let target
14
30
  if (specifier.startsWith('@earendil-works/pi-ai/providers/')) {
15
31
  const sub = specifier.slice('@earendil-works/pi-ai/providers/'.length)
16
- const manifest = findPackageJSON('@earendil-works/pi-ai', host)
32
+ const manifest = findPiAiManifest(host)
17
33
  if (!manifest) throw error
18
34
  target = resolve(dirname(manifest), 'dist/providers/' + sub + '.js')
19
- } else target = require.resolve(specifier)
35
+ } else if (specifier === '@google/genai') {
36
+ const piManifest = findPiAiManifest(host)
37
+ const anchor = piManifest ? pathToFileURL(piManifest) : host
38
+ if (!anchor) throw error
39
+ const manifest = findPackageJSON('@google/genai', anchor)
40
+ if (!manifest) throw error
41
+ target = resolve(dirname(manifest), 'dist/node/index.mjs')
42
+ } else {
43
+ if (!host) throw error
44
+ const require = createRequire(host)
45
+ target = require.resolve(specifier)
46
+ }
20
47
  return import(pathToFileURL(target).href)
21
48
  }
22
49
  }