opencode-next 0.0.0-stage → 1.0.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/LICENSE +22 -0
- package/README.md +339 -2
- package/README.zh-TW.md +368 -0
- package/bin/login.mjs +71 -0
- package/bin/smoke.mjs +73 -0
- package/cordis.patch.yml +9 -0
- package/lib/adapter.js +574 -0
- package/lib/bun-transport.js +413 -0
- package/lib/bun-worker.mjs +77 -0
- package/lib/catalog.js +870 -0
- package/lib/client.js +396 -0
- package/lib/config.js +200 -0
- package/lib/constants.js +161 -0
- package/lib/context-window.js +117 -0
- package/lib/device-flow.js +263 -0
- package/lib/failures.js +475 -0
- package/lib/fallback.js +229 -0
- package/lib/go/adapter.js +434 -0
- package/lib/go/catalog.js +305 -0
- package/lib/go/client.js +647 -0
- package/lib/go/credentials.js +321 -0
- package/lib/go/service.js +643 -0
- package/lib/images.js +98 -0
- package/lib/index.js +408 -0
- package/lib/picker.js +126 -0
- package/lib/probe.js +309 -0
- package/lib/status.js +440 -0
- package/lib/store.js +434 -0
- package/lib/stream.js +271 -0
- package/lib/token-manager.js +560 -0
- package/lib/ui.js +4587 -0
- package/lib/web-api.js +876 -0
- package/package.json +69 -4
package/lib/fallback.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模型備援(前三順位)。
|
|
3
|
+
*
|
|
4
|
+
* 使用者要的東西很簡單:「這個模型不行,就自動換我排的下一個」。但直接
|
|
5
|
+
* 對每個錯誤都換模型會出事,所以整個模組的核心是**一個判斷函式**:
|
|
6
|
+
* `canFallback(reason)`。
|
|
7
|
+
*
|
|
8
|
+
* 為什麼要分「模型層級」與「通道層級」:
|
|
9
|
+
*
|
|
10
|
+
* - 模型層級(400 模型下線、410 已下架、404 不存在、地區封鎖):換一個
|
|
11
|
+
* 模型真的會成功。這是備援唯一該發揮作用的情況。
|
|
12
|
+
*
|
|
13
|
+
* - 通道層級(IP 被風控、免費通道擋客戶端、授權失效、額度用盡):擋的是
|
|
14
|
+
* 「你這個人/這條網路出口」。此時換 30 個模型就是送出 30 次注定失敗的
|
|
15
|
+
* 請求,只會讓 IP 評分更差,而且真正該處理的問題(關 VPN、重新登入)
|
|
16
|
+
* 會被一句「所有模型都不可用」蓋掉。
|
|
17
|
+
*
|
|
18
|
+
* `upstream-error`(5xx)刻意**不**列入可換:免費通道是同一個閘道代理全部
|
|
19
|
+
* 模型,5xx 多半是閘道本身出問題,換模型不會好;而且這個錯誤碼已經在
|
|
20
|
+
* `SAFE_RETRY_POLICY.retryableCodes` 裡,上層會自己重試同一個模型。
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from 'node:fs';
|
|
24
|
+
import { dirname, join } from 'node:path';
|
|
25
|
+
import { homedir } from 'node:os';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 最多幾個備援順位。
|
|
29
|
+
*
|
|
30
|
+
* 原本是 3(「前三順位」),改成 1 的理由是實測:備援唯一真正有用的場景是
|
|
31
|
+
* 「單一模型下架」(410 帶 replacement),而觀察到的其餘失敗——IP 風控、
|
|
32
|
+
* 免費池縮減——都是整批一起壞。那種情況下第 2、第 3 順位不會成功,
|
|
33
|
+
* 只會多送幾個注定失敗的請求出去,在風控這件事上反而是扣分。
|
|
34
|
+
*
|
|
35
|
+
* 保留 1 個順位仍然有價值:5 個 410 下架的模型就有 5 次被救回來的機會。
|
|
36
|
+
*/
|
|
37
|
+
export const MAX_FALLBACK_MODELS = 1;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 換模型真的有用的失敗原因。
|
|
41
|
+
*
|
|
42
|
+
* 這份清單的每一項都對應「問題出在這個模型身上」,所以下一順位有機會成功。
|
|
43
|
+
*/
|
|
44
|
+
const FALLBACK_REASONS = new Set([
|
|
45
|
+
'unavailable', // 400:上游明說這個模型不可用
|
|
46
|
+
'bad-request', // 400:上游沒說原因,但實測換模型/換帳號常能過去
|
|
47
|
+
'deprecated', // 410:已下架
|
|
48
|
+
'not-found', // 404:上游沒有這個模型
|
|
49
|
+
'region-restricted', // 這個模型被地區封鎖,通道本身是好的
|
|
50
|
+
'timeout', // 首個事件超時:這個模型太慢或掛住
|
|
51
|
+
'transport' // 連線層失敗:換一個再試
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
// 刻意**不在**上面清單裡的:
|
|
55
|
+
// context-overflow —— 內容太長,換模型只會更糟(其餘模型上下文通常更小)。
|
|
56
|
+
// 正確處置是壓縮或縮短訊息,硬切到備援等於把使用者推去撞牆。
|
|
57
|
+
// network-blocked —— 擋的是整個網路出口,換誰都一樣。
|
|
58
|
+
// free-lane-blocked —— 同上,擋的是通道不是模型。
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 這個失敗能不能靠「換下一個模型」解決。
|
|
62
|
+
*
|
|
63
|
+
* @param {string|null|undefined} reason 來自 `classifyHttpFailure().reason`
|
|
64
|
+
* 或 probe 的 `reason`。未知值一律回 false。
|
|
65
|
+
*/
|
|
66
|
+
export function canFallback(reason) {
|
|
67
|
+
if (typeof reason !== 'string') return false;
|
|
68
|
+
return FALLBACK_REASONS.has(reason);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 這個 reason 屬於「通道/網路」層級,換模型無效。給 UI 與測試用。 */
|
|
72
|
+
export function isChannelLevelFailure(reason) {
|
|
73
|
+
if (typeof reason !== 'string') return false;
|
|
74
|
+
return (
|
|
75
|
+
reason === 'network-blocked'
|
|
76
|
+
|| reason === 'free-lane-blocked'
|
|
77
|
+
|| reason === 'unauthorized'
|
|
78
|
+
|| reason === 'forbidden'
|
|
79
|
+
|| reason === 'quota-exceeded'
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 把使用者設定的前三個順位整理成乾淨的清單。
|
|
85
|
+
*
|
|
86
|
+
* 去重、去空白、丟掉非字串、截到三個。這些驗證在伺服器端做,因為請求是
|
|
87
|
+
* 從瀏覽器來的,不能假設它送來的一定是三個合法 model id。
|
|
88
|
+
*/
|
|
89
|
+
export function normalizeModelList(input) {
|
|
90
|
+
if (!Array.isArray(input)) return [];
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
const out = [];
|
|
93
|
+
for (const raw of input) {
|
|
94
|
+
if (typeof raw !== 'string') continue;
|
|
95
|
+
const id = raw.trim();
|
|
96
|
+
if (id === '' || seen.has(id)) continue;
|
|
97
|
+
seen.add(id);
|
|
98
|
+
out.push(id);
|
|
99
|
+
if (out.length >= MAX_FALLBACK_MODELS) break;
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 預設存放位置;刻意與探測快取分開,語意不同不該混在同一支檔案。 */
|
|
105
|
+
export function defaultFallbackPath() {
|
|
106
|
+
const home = process.env.DSH_HOME || join(homedir(), '.dsh');
|
|
107
|
+
return join(home, 'opencode-next.fallback.json');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 備援設定的持久化。
|
|
112
|
+
*
|
|
113
|
+
* 為什麼不放進 DSH 的 plugin config:那份設定要在 DSH 的設定檔裡手改,
|
|
114
|
+
* 而使用者要的是一個畫面就能勾選、就能調整順位的開關。所以狀態存在外掛
|
|
115
|
+
* 自己的檔案,由 API 寫入,介面只是它的前端。
|
|
116
|
+
*
|
|
117
|
+
* 讀寫全程 try/catch:設定檔壞掉或沒有寫入權限時,外掛必須照常運作
|
|
118
|
+
* (退回「備援關閉」),不能因此讓推論路徑失敗。
|
|
119
|
+
*/
|
|
120
|
+
export class FallbackStore {
|
|
121
|
+
#path;
|
|
122
|
+
#state = { enabled: false, models: [] };
|
|
123
|
+
#loaded = false;
|
|
124
|
+
|
|
125
|
+
constructor({ path } = {}) {
|
|
126
|
+
this.#path = path || defaultFallbackPath();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
#load() {
|
|
130
|
+
if (this.#loaded) return;
|
|
131
|
+
this.#loaded = true;
|
|
132
|
+
try {
|
|
133
|
+
if (!existsSync(this.#path)) return;
|
|
134
|
+
const text = readFileSync(this.#path, 'utf8').replace(/^\uFEFF/, '');
|
|
135
|
+
const parsed = JSON.parse(text);
|
|
136
|
+
this.#state = {
|
|
137
|
+
enabled: parsed?.enabled === true,
|
|
138
|
+
models: normalizeModelList(parsed?.models)
|
|
139
|
+
};
|
|
140
|
+
} catch {
|
|
141
|
+
// 壞掉的設定檔等同於「沒設定過」。不覆寫它,留給使用者自己檢查。
|
|
142
|
+
this.#state = { enabled: false, models: [] };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 目前設定。回傳副本,呼叫端改不動內部狀態。 */
|
|
147
|
+
get() {
|
|
148
|
+
this.#load();
|
|
149
|
+
return { enabled: this.#state.enabled, models: [...this.#state.models] };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 更新設定。
|
|
154
|
+
*
|
|
155
|
+
* 先寫暫存檔再 rename:直接覆寫時若行程中途結束,會留下一個半截的 JSON,
|
|
156
|
+
* 下次啟動就整份設定消失。rename 在同一個磁碟區上是原子操作。
|
|
157
|
+
*/
|
|
158
|
+
set(patch = {}) {
|
|
159
|
+
this.#load();
|
|
160
|
+
const next = {
|
|
161
|
+
enabled: patch.enabled === undefined ? this.#state.enabled : patch.enabled === true,
|
|
162
|
+
models:
|
|
163
|
+
patch.models === undefined ? [...this.#state.models] : normalizeModelList(patch.models)
|
|
164
|
+
};
|
|
165
|
+
this.#state = next;
|
|
166
|
+
try {
|
|
167
|
+
mkdirSync(dirname(this.#path), { recursive: true });
|
|
168
|
+
const tmp = `${this.#path}.tmp`;
|
|
169
|
+
writeFileSync(tmp, JSON.stringify(next, null, 2), 'utf8');
|
|
170
|
+
renameSync(tmp, this.#path);
|
|
171
|
+
} catch {
|
|
172
|
+
// 寫不進去也要讓這次設定在記憶體中生效,至少本次執行期間是對的。
|
|
173
|
+
}
|
|
174
|
+
return this.get();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 依「使用者選的主模型 + 前三順位」算出實際要嘗試的順序。
|
|
180
|
+
*
|
|
181
|
+
* 規則:
|
|
182
|
+
* 1. 主模型永遠排第一(使用者這次就是要它)。
|
|
183
|
+
* 2. 備援只在使用者開啟且清單非空時才加入。
|
|
184
|
+
* 3. 只考慮 catalog 認為可用的模型;未探測或已判定不可用的都不放進來,
|
|
185
|
+
* 否則備援會把時間浪費在明知不通的模型上。
|
|
186
|
+
* 4. 去重:主模型若也在順位清單裡,不要重複嘗試。
|
|
187
|
+
* 5. 上游若明確指定替代模型(410 的 `metadata.replacement`),把它插在
|
|
188
|
+
* 使用者順位之前——那是 OpenCode 自己的建議,比我們的猜測可靠。
|
|
189
|
+
*
|
|
190
|
+
* @param {object} params
|
|
191
|
+
* @param {string} params.primary 這次請求指定的模型
|
|
192
|
+
* @param {{enabled: boolean, models: string[]}} params.settings 使用者設定
|
|
193
|
+
* @param {(id: string) => boolean|null} params.isAvailable 查詢可用性;null 代表未知
|
|
194
|
+
* @param {string|null} [params.replacement] 上游建議的替代模型
|
|
195
|
+
* @returns {string[]} 至少含 primary
|
|
196
|
+
*/
|
|
197
|
+
export function buildAttemptChain({ primary, settings, isAvailable, replacement = null }) {
|
|
198
|
+
const chain = [];
|
|
199
|
+
const seen = new Set();
|
|
200
|
+
|
|
201
|
+
const push = (id) => {
|
|
202
|
+
if (typeof id !== 'string' || id === '' || seen.has(id)) return;
|
|
203
|
+
seen.add(id);
|
|
204
|
+
chain.push(id);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
push(primary);
|
|
208
|
+
|
|
209
|
+
if (!settings?.enabled) return chain;
|
|
210
|
+
|
|
211
|
+
for (const id of settings.models || []) {
|
|
212
|
+
// 可用性未知(null)時仍然嘗試:catalog 還沒探測完就開著備援,
|
|
213
|
+
// 直接把它全部濾掉會讓「剛裝好就勾選備援」看起來完全沒作用。
|
|
214
|
+
const available = isAvailable(id);
|
|
215
|
+
if (available === false) continue;
|
|
216
|
+
push(id);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 上游的建議排在最後才加,但它其實比使用者順位更該先試。
|
|
220
|
+
// 這裡刻意不把它插到最前面:使用者排的順位是他明確表達的偏好,
|
|
221
|
+
// 靜默把它擠掉會讓人覺得設定沒生效。放在隊尾是最小驚訝的折衷——
|
|
222
|
+
// 使用者順位都失敗時,至少還有 OpenCode 自己指名的那一個。
|
|
223
|
+
if (typeof replacement === 'string') {
|
|
224
|
+
const available = isAvailable(replacement);
|
|
225
|
+
if (available !== false) push(replacement);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return chain;
|
|
229
|
+
}
|
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode Go DSH LlmAdapter 接點(Stage 2:文字串流與工具呼叫)。
|
|
3
|
+
*
|
|
4
|
+
* 設計界線:
|
|
5
|
+
* - 固定推論端點:`POST https://opencode.ai/inference/go/openai/v1/chat/completions`。
|
|
6
|
+
* - 使用 Bearer Personal API Key、外掛自己的 User-Agent、`redirect: 'manual'`。
|
|
7
|
+
* - `x-opencode-session` 必須來自 DSH 實際會話 ID;缺漏或無效時拒絕請求。
|
|
8
|
+
* - 僅做 Chat Completions 文字 SSE 與工具呼叫(工具名稱、分段參數、工具結果續輪、
|
|
9
|
+
* finish reason、取消與逾時),並啟用 `stream_options.include_usage`。
|
|
10
|
+
* - 不沿用免費通道的 CLI 身分標頭、Bun 請求改寫、工具別名或假工具;
|
|
11
|
+
* 不自動換帳號、不跨 provider 退回、不自動重送計費請求。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
DEFAULT_FIRST_EVENT_MS,
|
|
16
|
+
DEFAULT_IMAGE_MAX_BYTES,
|
|
17
|
+
DEFAULT_IMAGE_PIXEL_BUDGET,
|
|
18
|
+
DEFAULT_STREAM_IDLE_MS,
|
|
19
|
+
GO_PROVIDER,
|
|
20
|
+
GO_PROVIDER_NAME
|
|
21
|
+
} from '../constants.js';
|
|
22
|
+
import { collectImageRefs, convertMessages, convertTools } from '../client.js';
|
|
23
|
+
import { toFailure } from '../failures.js';
|
|
24
|
+
import { resolveImageDataUrls } from '../images.js';
|
|
25
|
+
import { parseOpenAiSseStream } from '../stream.js';
|
|
26
|
+
import { supportsGoImageInput, toGoPickerDescriptor } from './catalog.js';
|
|
27
|
+
import { GoClientError, postGoChatCompletions, validateGoSessionId } from './client.js';
|
|
28
|
+
import { redactSecret } from './credentials.js';
|
|
29
|
+
|
|
30
|
+
function analyzeActiveUserImages(dshMessages) {
|
|
31
|
+
const userMessages = [];
|
|
32
|
+
let activeImageBlocks = 0;
|
|
33
|
+
if (Array.isArray(dshMessages)) {
|
|
34
|
+
for (const msg of dshMessages) {
|
|
35
|
+
if (!msg || (msg.role !== 'user' && msg.role !== 'human') || !Array.isArray(msg.content)) continue;
|
|
36
|
+
userMessages.push(msg);
|
|
37
|
+
for (const block of msg.content) {
|
|
38
|
+
if (block && block.type === 'image' && block.offloaded !== true) {
|
|
39
|
+
activeImageBlocks++;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const refs = activeImageBlocks > 0 ? collectImageRefs(userMessages) : new Map();
|
|
45
|
+
let invalidImageBlocks = 0;
|
|
46
|
+
if (activeImageBlocks > 0) {
|
|
47
|
+
for (const msg of userMessages) {
|
|
48
|
+
for (const block of msg.content) {
|
|
49
|
+
if (!block || block.type !== 'image' || block.offloaded === true) continue;
|
|
50
|
+
const id = block?.attachment?.attachmentId;
|
|
51
|
+
if (typeof id !== 'string' || !id || !refs.has(id)) {
|
|
52
|
+
invalidImageBlocks++;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { activeImageBlocks, invalidImageBlocks, refs };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const GO_NO_RETRY_POLICY = Object.freeze({
|
|
61
|
+
mode: 'off',
|
|
62
|
+
maxRetries: 0,
|
|
63
|
+
retryableCodes: Object.freeze([]),
|
|
64
|
+
initialDelayMs: 0,
|
|
65
|
+
maxDelayMs: 0,
|
|
66
|
+
jitterRatio: 0
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
function toDshFailure(err, activeKey = '') {
|
|
70
|
+
const safeMsg = redactSecret(err?.message || 'OpenCode Go request failed.', activeKey);
|
|
71
|
+
const wrapped = new Error(safeMsg);
|
|
72
|
+
if (err?.status !== undefined) wrapped.status = err.status;
|
|
73
|
+
|
|
74
|
+
if (err instanceof GoClientError) {
|
|
75
|
+
let code = 'TRANSPORT';
|
|
76
|
+
if (err.category === 'invalid-key' || err.category === 'no-entitlement' || err.category === 'permission-policy') {
|
|
77
|
+
code = 'AUTH';
|
|
78
|
+
} else if (err.category === 'invalid-request') {
|
|
79
|
+
code = err.subCategory === 'model-not-eligible' ? 'MODEL_UNAVAILABLE' : 'INVALID_REQUEST';
|
|
80
|
+
} else if (err.category === 'transient') {
|
|
81
|
+
if (err.subCategory === 'quota-exceeded') code = 'QUOTA';
|
|
82
|
+
else if (err.subCategory === 'rate-limited') code = 'RATE_LIMIT';
|
|
83
|
+
else if (err.subCategory === 'timeout') code = 'TIMEOUT';
|
|
84
|
+
else if (err.subCategory === 'upstream-error') code = 'SERVER';
|
|
85
|
+
else code = 'TRANSPORT';
|
|
86
|
+
} else if (err.category === 'invalid-response' && err.subCategory === 'endpoint-not-found') {
|
|
87
|
+
code = 'SERVER';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const failure = toFailure(wrapped, {
|
|
91
|
+
code,
|
|
92
|
+
status: err.status ?? undefined,
|
|
93
|
+
reason: err.subCategory || err.category,
|
|
94
|
+
retryable: false
|
|
95
|
+
});
|
|
96
|
+
if (Number.isFinite(err.retryAfterMs)) {
|
|
97
|
+
failure.retryAfterMs = err.retryAfterMs;
|
|
98
|
+
}
|
|
99
|
+
return failure;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return toFailure(wrapped, {
|
|
103
|
+
code: 'TRANSPORT',
|
|
104
|
+
reason: 'transport',
|
|
105
|
+
retryable: false
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function createGoWatchdog(firstEventMs, idleMs, callerSignal) {
|
|
110
|
+
const controller = new AbortController();
|
|
111
|
+
let timer = null;
|
|
112
|
+
let waitingFirst = true;
|
|
113
|
+
let timeoutError = null;
|
|
114
|
+
|
|
115
|
+
const onCallerAbort = () => controller.abort(callerSignal?.reason);
|
|
116
|
+
if (callerSignal !== undefined) {
|
|
117
|
+
if (callerSignal.aborted) onCallerAbort();
|
|
118
|
+
else callerSignal.addEventListener('abort', onCallerAbort, { once: true });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const arm = () => {
|
|
122
|
+
if (timer !== null) clearTimeout(timer);
|
|
123
|
+
const limit = waitingFirst ? firstEventMs : idleMs;
|
|
124
|
+
timer = setTimeout(() => {
|
|
125
|
+
timeoutError = new Error(
|
|
126
|
+
waitingFirst
|
|
127
|
+
? `OpenCode Go stream sent no first event within ${limit}ms`
|
|
128
|
+
: `OpenCode Go stream was idle for ${limit}ms`
|
|
129
|
+
);
|
|
130
|
+
toFailure(timeoutError, { code: 'TIMEOUT', reason: 'timeout', status: undefined });
|
|
131
|
+
controller.abort(timeoutError);
|
|
132
|
+
}, limit);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
arm();
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
signal: controller.signal,
|
|
139
|
+
tick() {
|
|
140
|
+
waitingFirst = false;
|
|
141
|
+
arm();
|
|
142
|
+
},
|
|
143
|
+
timedOut: () => timeoutError !== null,
|
|
144
|
+
error: () => timeoutError ?? new Error('OpenCode Go stream aborted'),
|
|
145
|
+
dispose() {
|
|
146
|
+
if (timer !== null) clearTimeout(timer);
|
|
147
|
+
timer = null;
|
|
148
|
+
callerSignal?.removeEventListener?.('abort', onCallerAbort);
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function* withGoWatchdog(source, watchdog, activeKey, body = null) {
|
|
154
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
155
|
+
const waitAbort = () => new Promise((_, reject) => {
|
|
156
|
+
if (watchdog.signal.aborted) {
|
|
157
|
+
reject(watchdog.timedOut() ? watchdog.error() : (watchdog.signal.reason || new Error('Aborted')));
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const onAbort = () => {
|
|
161
|
+
try { body?.cancel?.().catch?.(() => {}); } catch {}
|
|
162
|
+
reject(watchdog.timedOut() ? watchdog.error() : (watchdog.signal.reason || new Error('Aborted')));
|
|
163
|
+
};
|
|
164
|
+
watchdog.signal.addEventListener('abort', onAbort, { once: true });
|
|
165
|
+
waitAbort._cleanup = () => watchdog.signal.removeEventListener('abort', onAbort);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
try {
|
|
169
|
+
for (;;) {
|
|
170
|
+
if (watchdog.timedOut()) throw watchdog.error();
|
|
171
|
+
if (watchdog.signal.aborted) throw watchdog.signal.reason || new Error('Aborted');
|
|
172
|
+
const abortRace = waitAbort();
|
|
173
|
+
let next;
|
|
174
|
+
try {
|
|
175
|
+
next = await Promise.race([iterator.next(), abortRace]);
|
|
176
|
+
} finally {
|
|
177
|
+
waitAbort._cleanup?.();
|
|
178
|
+
waitAbort._cleanup = null;
|
|
179
|
+
}
|
|
180
|
+
if (next.done === true) return;
|
|
181
|
+
watchdog.tick();
|
|
182
|
+
yield next.value;
|
|
183
|
+
}
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (watchdog.timedOut()) throw watchdog.error();
|
|
186
|
+
if (watchdog.signal.aborted) throw error;
|
|
187
|
+
if (error?.failure?.code) throw error;
|
|
188
|
+
throw toFailure(
|
|
189
|
+
new Error(redactSecret(error?.message || 'OpenCode Go stream interrupted.', activeKey)),
|
|
190
|
+
{ code: 'TRANSPORT', reason: 'transport', retryable: false }
|
|
191
|
+
);
|
|
192
|
+
} finally {
|
|
193
|
+
waitAbort._cleanup?.();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export class OpenCodeGoAdapter {
|
|
198
|
+
#service;
|
|
199
|
+
#providerId;
|
|
200
|
+
#providerName;
|
|
201
|
+
#config;
|
|
202
|
+
|
|
203
|
+
constructor(service, config = {}) {
|
|
204
|
+
this.#service = service;
|
|
205
|
+
this.#config = config || {};
|
|
206
|
+
this.#providerId = (typeof config?.providerId === 'string' && config.providerId.trim())
|
|
207
|
+
|| service?.providerId?.()
|
|
208
|
+
|| GO_PROVIDER;
|
|
209
|
+
this.#providerName = (typeof config?.providerName === 'string' && config.providerName.trim())
|
|
210
|
+
|| service?.providerName?.()
|
|
211
|
+
|| GO_PROVIDER_NAME;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
providerInfo(provider) {
|
|
215
|
+
return {
|
|
216
|
+
id: provider || this.#providerId,
|
|
217
|
+
name: this.#providerName
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 明確停用自動重試:不自動重送計費請求。
|
|
223
|
+
*/
|
|
224
|
+
providerRetryPolicy(_provider) {
|
|
225
|
+
return GO_NO_RETRY_POLICY;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
imageRequestPricing(_provider, _model) {
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* 僅列出已驗證資格且可進行文字/工具推論的 Go 模型。
|
|
234
|
+
*/
|
|
235
|
+
async listModels(provider) {
|
|
236
|
+
const models = this.#service?.getPickerModels?.() ?? [];
|
|
237
|
+
const targetProvider = provider || this.#providerId;
|
|
238
|
+
return models.map((m) => toGoPickerDescriptor(targetProvider, m));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async resolveModel(provider, modelId) {
|
|
242
|
+
const status = this.#service?.getStatus?.();
|
|
243
|
+
if (!this.#service?.isEnabled?.()) {
|
|
244
|
+
throw toFailure(new Error('OpenCode Go provider is disabled.'), {
|
|
245
|
+
code: 'MODEL_UNAVAILABLE',
|
|
246
|
+
reason: 'go-disabled',
|
|
247
|
+
retryable: false
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
if (status?.connectionState !== 'connected') {
|
|
251
|
+
throw toFailure(new Error('OpenCode Go subscription is not verified/connected.'), {
|
|
252
|
+
code: 'AUTH',
|
|
253
|
+
reason: status?.connectionState || 'unconfigured',
|
|
254
|
+
retryable: false
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
const models = this.#service?.getPickerModels?.() ?? [];
|
|
258
|
+
const found = models.find((m) => m.id === modelId);
|
|
259
|
+
if (!found) {
|
|
260
|
+
throw toFailure(new Error(`Model "${modelId}" is not available in OpenCode Go.`), {
|
|
261
|
+
code: 'MODEL_UNAVAILABLE',
|
|
262
|
+
reason: 'model-not-eligible',
|
|
263
|
+
retryable: false
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
return toGoPickerDescriptor(provider || this.#providerId, found);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async prepareCall(provider, model, signal) {
|
|
270
|
+
return {
|
|
271
|
+
model: await this.resolveModel(provider, model, signal),
|
|
272
|
+
stream: (options) => this.stream(options)
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async *stream(options = {}) {
|
|
277
|
+
let sessionId;
|
|
278
|
+
try {
|
|
279
|
+
sessionId = validateGoSessionId(options);
|
|
280
|
+
} catch (err) {
|
|
281
|
+
throw toDshFailure(err);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
let ctx;
|
|
285
|
+
try {
|
|
286
|
+
ctx = await this.#service.getInferenceContext(options.model);
|
|
287
|
+
} catch (err) {
|
|
288
|
+
throw toDshFailure(err);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const { key, model, userAgent, fetchFn } = ctx;
|
|
292
|
+
const imageSupported = supportsGoImageInput(model);
|
|
293
|
+
const { activeImageBlocks, invalidImageBlocks, refs: userImageRefs } = analyzeActiveUserImages(options.messages || []);
|
|
294
|
+
|
|
295
|
+
let imageUrls = new Map();
|
|
296
|
+
if (activeImageBlocks > 0) {
|
|
297
|
+
if (!imageSupported) {
|
|
298
|
+
throw toFailure(
|
|
299
|
+
new Error(`Model "${model.id}" on OpenCode Go does not support image input in this plugin; image request was rejected without falling back to text-only.`),
|
|
300
|
+
{
|
|
301
|
+
code: 'INVALID_REQUEST',
|
|
302
|
+
reason: 'image-unsupported',
|
|
303
|
+
retryable: false
|
|
304
|
+
}
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (invalidImageBlocks > 0 || userImageRefs.size === 0) {
|
|
309
|
+
throw toFailure(
|
|
310
|
+
new Error(`Attached image for OpenCode Go model "${model.id}" is missing a valid attachment reference; refusing to send text without the image.`),
|
|
311
|
+
{
|
|
312
|
+
code: 'INVALID_REQUEST',
|
|
313
|
+
reason: 'image-invalid',
|
|
314
|
+
retryable: false
|
|
315
|
+
}
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const attachments = this.#config.resolveAttachments?.();
|
|
320
|
+
if (!attachments) {
|
|
321
|
+
throw toFailure(
|
|
322
|
+
new Error(`OpenCode Go image input requires DSH attachments service for model "${model.id}"; refusing to silently drop attached image.`),
|
|
323
|
+
{
|
|
324
|
+
code: 'INVALID_REQUEST',
|
|
325
|
+
reason: 'attachments-unavailable',
|
|
326
|
+
retryable: false
|
|
327
|
+
}
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
imageUrls = await resolveImageDataUrls(userImageRefs, {
|
|
332
|
+
attachments,
|
|
333
|
+
pixelBudget: this.#pixelBudget(),
|
|
334
|
+
maxBytes: this.#maxImageBytes(),
|
|
335
|
+
signal: options.signal
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
for (const attachmentId of userImageRefs.keys()) {
|
|
339
|
+
const resolvedUrl = imageUrls.get(attachmentId);
|
|
340
|
+
if (typeof resolvedUrl !== 'string' || !resolvedUrl.toLowerCase().startsWith('data:image/')) {
|
|
341
|
+
throw toFailure(
|
|
342
|
+
new Error(`Could not read attached image (${attachmentId}) for OpenCode Go model "${model.id}"; refusing to send text without the image.`),
|
|
343
|
+
{
|
|
344
|
+
code: 'INVALID_REQUEST',
|
|
345
|
+
reason: 'image-unreadable',
|
|
346
|
+
retryable: false
|
|
347
|
+
}
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const userTools = convertTools(options.tools);
|
|
354
|
+
const hasUserTools = Array.isArray(userTools) && userTools.length > 0;
|
|
355
|
+
const messages = convertMessages(options.messages || [], {
|
|
356
|
+
system: options.system,
|
|
357
|
+
imageUrls,
|
|
358
|
+
imageSupported
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
const bodyPayload = {
|
|
362
|
+
model: model.id,
|
|
363
|
+
messages,
|
|
364
|
+
stream: true,
|
|
365
|
+
stream_options: { include_usage: true },
|
|
366
|
+
...(Number.isSafeInteger(options.maxTokens) && options.maxTokens > 0
|
|
367
|
+
? { max_completion_tokens: options.maxTokens }
|
|
368
|
+
: {}),
|
|
369
|
+
...(hasUserTools ? { tools: userTools } : {}),
|
|
370
|
+
...(options.temperature !== undefined ? { temperature: options.temperature } : {}),
|
|
371
|
+
...(Array.isArray(options.stop) && options.stop.length > 0 ? { stop: options.stop } : {})
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const watchdog = createGoWatchdog(this.#firstEventMs(), this.#idleMs(), options.signal);
|
|
375
|
+
|
|
376
|
+
try {
|
|
377
|
+
const res = await postGoChatCompletions({
|
|
378
|
+
key,
|
|
379
|
+
sessionId,
|
|
380
|
+
payload: bodyPayload,
|
|
381
|
+
fetchFn,
|
|
382
|
+
signal: watchdog.signal,
|
|
383
|
+
userAgent
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
const stream = withGoWatchdog(
|
|
387
|
+
parseOpenAiSseStream(res.body, { includeGoBilling: true }),
|
|
388
|
+
watchdog,
|
|
389
|
+
key,
|
|
390
|
+
res.body
|
|
391
|
+
);
|
|
392
|
+
|
|
393
|
+
for await (const chunk of stream) {
|
|
394
|
+
if (chunk.type === 'usage') {
|
|
395
|
+
this.#service?.noteBilling?.(chunk.usage);
|
|
396
|
+
}
|
|
397
|
+
yield chunk;
|
|
398
|
+
}
|
|
399
|
+
} catch (err) {
|
|
400
|
+
if (watchdog.timedOut()) throw watchdog.error();
|
|
401
|
+
if (options.signal?.aborted) throw err;
|
|
402
|
+
if (err?.failure?.code) throw err;
|
|
403
|
+
throw toDshFailure(err, key);
|
|
404
|
+
} finally {
|
|
405
|
+
watchdog.dispose();
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
#idleMs() {
|
|
410
|
+
const configured = Number(this.#config.streamIdleTimeoutMs);
|
|
411
|
+
return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_STREAM_IDLE_MS;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
#firstEventMs() {
|
|
415
|
+
const configured = Number(this.#config.firstEventTimeoutMs);
|
|
416
|
+
if (Number.isFinite(configured) && configured > 0) return configured;
|
|
417
|
+
return Math.min(DEFAULT_FIRST_EVENT_MS, this.#idleMs());
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
#pixelBudget() {
|
|
421
|
+
const configured = Number(this.#config.imagePixelBudget);
|
|
422
|
+
return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_IMAGE_PIXEL_BUDGET;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
#maxImageBytes() {
|
|
426
|
+
const configured = Number(this.#config.imageMaxBytes);
|
|
427
|
+
return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_IMAGE_MAX_BYTES;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* 僅作 adapter 層介面保留;共用的 Go service 只由外掛卸載路徑釋放。
|
|
432
|
+
*/
|
|
433
|
+
dispose() {}
|
|
434
|
+
}
|