opencode-next 0.0.0-stage → 1.0.1
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 +359 -2
- package/README.zh-TW.md +388 -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
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode Go 訂閱資格驗證與目錄預覽服務(Stage 1)。
|
|
3
|
+
*
|
|
4
|
+
* 職責:
|
|
5
|
+
* - 協調獨立 Go 憑證解析與官方唯讀端點(`/usage` → `/models`)。
|
|
6
|
+
* - 強制隔離快取與世代檢查,防止換 key 或停用時舊的非同步請求回寫狀態。
|
|
7
|
+
* - 在 Stage 1 僅對設定頁提供模型預覽(`previewModels`),正式選單(`getPickerModels()`)
|
|
8
|
+
* 在 Stage 2 推論完成前保持為空陣列。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { GO_CREDENTIAL_ENV_VAR, GO_PROVIDER, GO_PROVIDER_NAME } from '../constants.js';
|
|
12
|
+
import { defaultGoPickerPath, PickerStore } from '../picker.js';
|
|
13
|
+
import {
|
|
14
|
+
clearGoCredential,
|
|
15
|
+
describeGoCredential,
|
|
16
|
+
getDshCredentialCapabilities,
|
|
17
|
+
redactSecret,
|
|
18
|
+
resolveGoCredential,
|
|
19
|
+
saveGoCredential
|
|
20
|
+
} from './credentials.js';
|
|
21
|
+
import { classifyGoPickerModel, cloneGoModels, GoCacheStore, isEligibleGoPickerModel, supportsGoImageInput } from './catalog.js';
|
|
22
|
+
import { fetchGoModels, fetchGoUsage, GoClientError } from './client.js';
|
|
23
|
+
|
|
24
|
+
function mapErrorToState(err) {
|
|
25
|
+
const category = err?.category || 'transient';
|
|
26
|
+
switch (category) {
|
|
27
|
+
case 'invalid-key':
|
|
28
|
+
return 'invalid-key';
|
|
29
|
+
case 'no-entitlement':
|
|
30
|
+
return 'no-entitlement';
|
|
31
|
+
case 'permission-policy':
|
|
32
|
+
return 'permission-policy';
|
|
33
|
+
case 'redirect-blocked':
|
|
34
|
+
case 'invalid-destination':
|
|
35
|
+
return 'redirect-blocked';
|
|
36
|
+
case 'invalid-response':
|
|
37
|
+
return 'invalid-response';
|
|
38
|
+
case 'transient':
|
|
39
|
+
return err?.subCategory === 'rate-limited' ? 'rate-limited' : 'transient-error';
|
|
40
|
+
case 'aborted':
|
|
41
|
+
return 'unconfigured';
|
|
42
|
+
default:
|
|
43
|
+
return 'transient-error';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createGoService({
|
|
48
|
+
ctx = null,
|
|
49
|
+
config = {},
|
|
50
|
+
version = '0.0.0',
|
|
51
|
+
fetchFn = globalThis.fetch,
|
|
52
|
+
env = process.env,
|
|
53
|
+
cacheStore = undefined,
|
|
54
|
+
pickerStore = undefined
|
|
55
|
+
} = {}) {
|
|
56
|
+
let enabled = config?.enabled === true;
|
|
57
|
+
const providerId = (typeof config?.providerId === 'string' && config.providerId.trim()) || GO_PROVIDER;
|
|
58
|
+
const providerName = (typeof config?.providerName === 'string' && config.providerName.trim()) || GO_PROVIDER_NAME;
|
|
59
|
+
const credentialRef = (typeof config?.credentialRef === 'string' && config.credentialRef.trim()) || GO_CREDENTIAL_ENV_VAR;
|
|
60
|
+
const userAgent = `opencode-next/${version || '0.0.0'} (opencode-go)`;
|
|
61
|
+
|
|
62
|
+
const store = cacheStore !== undefined
|
|
63
|
+
? cacheStore
|
|
64
|
+
: new GoCacheStore(config?.cachePath === null ? null : (config?.cachePath || undefined));
|
|
65
|
+
const picker = pickerStore !== undefined
|
|
66
|
+
? pickerStore
|
|
67
|
+
: new PickerStore({ path: config?.pickerPath === null ? null : (config?.pickerPath || defaultGoPickerPath()) });
|
|
68
|
+
|
|
69
|
+
let generation = 0;
|
|
70
|
+
let disposed = false;
|
|
71
|
+
let activeController = null;
|
|
72
|
+
let inFlight = null;
|
|
73
|
+
let activeFingerprint = null;
|
|
74
|
+
|
|
75
|
+
let connectionState = enabled ? 'unconfigured' : 'disabled';
|
|
76
|
+
let usage = null;
|
|
77
|
+
let previewModels = [];
|
|
78
|
+
let checkedAt = null;
|
|
79
|
+
let lastError = null;
|
|
80
|
+
const initialCapabilities = getDshCredentialCapabilities(ctx);
|
|
81
|
+
let lastBilling = null;
|
|
82
|
+
let lastCredentialMeta = describeGoCredential({
|
|
83
|
+
present: false,
|
|
84
|
+
source: null,
|
|
85
|
+
ref: credentialRef,
|
|
86
|
+
fingerprint: null,
|
|
87
|
+
dshCredentialsAvailable: Boolean(initialCapabilities.service),
|
|
88
|
+
canSave: initialCapabilities.canSet,
|
|
89
|
+
canClear: initialCapabilities.canUnset
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
const resetCachedState = ({ nextState } = {}) => {
|
|
93
|
+
generation++;
|
|
94
|
+
if (activeController) {
|
|
95
|
+
try { activeController.abort(); } catch {}
|
|
96
|
+
activeController = null;
|
|
97
|
+
}
|
|
98
|
+
inFlight = null;
|
|
99
|
+
activeFingerprint = null;
|
|
100
|
+
usage = null;
|
|
101
|
+
previewModels = [];
|
|
102
|
+
checkedAt = null;
|
|
103
|
+
lastError = null;
|
|
104
|
+
lastBilling = null;
|
|
105
|
+
connectionState = nextState ?? (enabled ? 'unconfigured' : 'disabled');
|
|
106
|
+
store?.clear?.();
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 僅從本機解析憑證與恢復相符指紋的快取,不發起網路請求。
|
|
111
|
+
*/
|
|
112
|
+
const init = async () => {
|
|
113
|
+
if (disposed || !enabled) {
|
|
114
|
+
if (!disposed && !enabled) connectionState = 'disabled';
|
|
115
|
+
return getStatus();
|
|
116
|
+
}
|
|
117
|
+
const myGen = ++generation;
|
|
118
|
+
const cred = await resolveGoCredential({ ctx, credentialRef, env });
|
|
119
|
+
|
|
120
|
+
// 非同步憑證解析期間若已 clear()、setEnabled(false)、dispose() 或有更新的操作,
|
|
121
|
+
// 過期操作不可改動狀態、憑證中繼資料或快取。
|
|
122
|
+
if (disposed || !enabled || myGen !== generation) {
|
|
123
|
+
return getStatus();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
lastCredentialMeta = describeGoCredential(cred);
|
|
127
|
+
|
|
128
|
+
if (!cred.present) {
|
|
129
|
+
activeFingerprint = null;
|
|
130
|
+
usage = null;
|
|
131
|
+
previewModels = [];
|
|
132
|
+
checkedAt = null;
|
|
133
|
+
lastError = cred.error
|
|
134
|
+
? {
|
|
135
|
+
category: 'invalid-key',
|
|
136
|
+
subCategory: cred.error,
|
|
137
|
+
status: null,
|
|
138
|
+
retryable: false,
|
|
139
|
+
retryAfterMs: null,
|
|
140
|
+
message: cred.message
|
|
141
|
+
}
|
|
142
|
+
: null;
|
|
143
|
+
connectionState = cred.error ? 'invalid-key' : 'unconfigured';
|
|
144
|
+
store?.clear?.();
|
|
145
|
+
return getStatus();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
activeFingerprint = cred.fingerprint;
|
|
149
|
+
const cached = store?.read?.(cred.fingerprint) ?? null;
|
|
150
|
+
if (cached) {
|
|
151
|
+
usage = cached.usage ? structuredClone(cached.usage) : null;
|
|
152
|
+
previewModels = cloneGoModels(cached.previewModels);
|
|
153
|
+
checkedAt = cached.checkedAt;
|
|
154
|
+
connectionState = 'connected';
|
|
155
|
+
lastError = null;
|
|
156
|
+
} else {
|
|
157
|
+
store?.clear?.();
|
|
158
|
+
connectionState = 'unconfigured';
|
|
159
|
+
}
|
|
160
|
+
return getStatus();
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 解析憑證並依序查詢 `/usage` 與 `/models`。
|
|
165
|
+
*/
|
|
166
|
+
const refresh = async (_opts = {}) => {
|
|
167
|
+
if (disposed || !enabled) {
|
|
168
|
+
resetCachedState({ nextState: 'disabled' });
|
|
169
|
+
return getStatus();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (activeController) {
|
|
173
|
+
try { activeController.abort(); } catch {}
|
|
174
|
+
activeController = null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const myGen = ++generation;
|
|
178
|
+
const cred = await resolveGoCredential({ ctx, credentialRef, env });
|
|
179
|
+
|
|
180
|
+
// 非同步憑證解析期間若已發生清除、停用、處置或較新的 refresh(),
|
|
181
|
+
// 過期操作不可更新狀態、不可送出 HTTP,也不可覆寫快取。
|
|
182
|
+
if (disposed || !enabled || myGen !== generation) {
|
|
183
|
+
return getStatus();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
lastCredentialMeta = describeGoCredential(cred);
|
|
187
|
+
|
|
188
|
+
if (!cred.present) {
|
|
189
|
+
const nextState = cred.error ? 'invalid-key' : 'unconfigured';
|
|
190
|
+
// 保留 myGen,避免把 resetCachedState 內再加世代的行為影響其他追蹤
|
|
191
|
+
activeFingerprint = null;
|
|
192
|
+
usage = null;
|
|
193
|
+
previewModels = [];
|
|
194
|
+
checkedAt = null;
|
|
195
|
+
lastError = cred.error
|
|
196
|
+
? {
|
|
197
|
+
category: 'invalid-key',
|
|
198
|
+
subCategory: cred.error,
|
|
199
|
+
status: null,
|
|
200
|
+
retryable: false,
|
|
201
|
+
retryAfterMs: null,
|
|
202
|
+
message: cred.message
|
|
203
|
+
}
|
|
204
|
+
: null;
|
|
205
|
+
connectionState = nextState;
|
|
206
|
+
store?.clear?.();
|
|
207
|
+
return getStatus();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// 換 key 時立即清除舊快取(不遞增 generation,因為 myGen 已是最新世代)。
|
|
211
|
+
if (activeFingerprint && activeFingerprint !== cred.fingerprint) {
|
|
212
|
+
usage = null;
|
|
213
|
+
previewModels = [];
|
|
214
|
+
checkedAt = null;
|
|
215
|
+
lastError = null;
|
|
216
|
+
store?.clear?.();
|
|
217
|
+
}
|
|
218
|
+
activeFingerprint = cred.fingerprint;
|
|
219
|
+
|
|
220
|
+
const myFingerprint = cred.fingerprint;
|
|
221
|
+
const controller = new AbortController();
|
|
222
|
+
activeController = controller;
|
|
223
|
+
connectionState = 'checking';
|
|
224
|
+
lastError = null;
|
|
225
|
+
|
|
226
|
+
const isStillCurrent = () => (
|
|
227
|
+
!disposed
|
|
228
|
+
&& enabled
|
|
229
|
+
&& myGen === generation
|
|
230
|
+
&& activeFingerprint === myFingerprint
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
const run = (async () => {
|
|
234
|
+
try {
|
|
235
|
+
const nextUsage = await fetchGoUsage({
|
|
236
|
+
key: cred.key,
|
|
237
|
+
fetchFn,
|
|
238
|
+
signal: controller.signal,
|
|
239
|
+
userAgent
|
|
240
|
+
});
|
|
241
|
+
if (!isStillCurrent()) return getStatus();
|
|
242
|
+
|
|
243
|
+
const nextModels = await fetchGoModels({
|
|
244
|
+
key: cred.key,
|
|
245
|
+
fetchFn,
|
|
246
|
+
signal: controller.signal,
|
|
247
|
+
userAgent
|
|
248
|
+
});
|
|
249
|
+
if (!isStillCurrent()) return getStatus();
|
|
250
|
+
|
|
251
|
+
const now = Date.now();
|
|
252
|
+
usage = nextUsage;
|
|
253
|
+
previewModels = cloneGoModels(nextModels);
|
|
254
|
+
checkedAt = now;
|
|
255
|
+
connectionState = 'connected';
|
|
256
|
+
lastError = null;
|
|
257
|
+
store?.write?.({
|
|
258
|
+
credentialFingerprint: myFingerprint,
|
|
259
|
+
checkedAt: now,
|
|
260
|
+
usage: nextUsage,
|
|
261
|
+
previewModels
|
|
262
|
+
});
|
|
263
|
+
return getStatus();
|
|
264
|
+
} catch (err) {
|
|
265
|
+
// 若在非同步期間已被換 key、停用或清除,嚴禁舊請求回寫任何狀態或快取。
|
|
266
|
+
if (!isStillCurrent()) return getStatus();
|
|
267
|
+
|
|
268
|
+
const normalizedErr = err instanceof GoClientError
|
|
269
|
+
? err
|
|
270
|
+
: new GoClientError(redactSecret(err?.message || 'OpenCode Go verification failed.', cred.key), {
|
|
271
|
+
category: 'transient',
|
|
272
|
+
retryable: true
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
const nextState = mapErrorToState(normalizedErr);
|
|
276
|
+
// 資格失效、無效 key 或非合約回應時清除舊模型預覽與用量,避免殘留已連線狀態。
|
|
277
|
+
if (
|
|
278
|
+
nextState === 'invalid-key'
|
|
279
|
+
|| nextState === 'no-entitlement'
|
|
280
|
+
|| nextState === 'permission-policy'
|
|
281
|
+
|| nextState === 'invalid-response'
|
|
282
|
+
) {
|
|
283
|
+
usage = null;
|
|
284
|
+
previewModels = [];
|
|
285
|
+
checkedAt = null;
|
|
286
|
+
store?.clear?.();
|
|
287
|
+
} else {
|
|
288
|
+
// 暫時性失敗絕不把用量偽裝成 0%。
|
|
289
|
+
usage = null;
|
|
290
|
+
}
|
|
291
|
+
connectionState = nextState;
|
|
292
|
+
lastError = {
|
|
293
|
+
category: normalizedErr.category,
|
|
294
|
+
subCategory: normalizedErr.subCategory ?? null,
|
|
295
|
+
status: normalizedErr.status ?? null,
|
|
296
|
+
retryable: Boolean(normalizedErr.retryable),
|
|
297
|
+
retryAfterMs: Number.isFinite(normalizedErr.retryAfterMs) ? normalizedErr.retryAfterMs : null,
|
|
298
|
+
message: redactSecret(normalizedErr.message, cred.key)
|
|
299
|
+
};
|
|
300
|
+
return getStatus();
|
|
301
|
+
} finally {
|
|
302
|
+
if (activeController === controller) activeController = null;
|
|
303
|
+
if (inFlight?.generation === myGen) inFlight = null;
|
|
304
|
+
}
|
|
305
|
+
})();
|
|
306
|
+
|
|
307
|
+
inFlight = { promise: run, generation: myGen, fingerprint: myFingerprint };
|
|
308
|
+
return run;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
const clear = () => {
|
|
312
|
+
const caps = getDshCredentialCapabilities(ctx);
|
|
313
|
+
resetCachedState({ nextState: enabled ? 'unconfigured' : 'disabled' });
|
|
314
|
+
lastCredentialMeta = describeGoCredential({
|
|
315
|
+
present: false,
|
|
316
|
+
source: null,
|
|
317
|
+
ref: credentialRef,
|
|
318
|
+
fingerprint: null,
|
|
319
|
+
dshCredentialsAvailable: Boolean(caps.service) || lastCredentialMeta.dshCredentialsAvailable,
|
|
320
|
+
canSave: caps.canSet,
|
|
321
|
+
canClear: caps.canUnset
|
|
322
|
+
});
|
|
323
|
+
return getStatus();
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
const setEnabled = (nextEnabled) => {
|
|
327
|
+
enabled = nextEnabled === true;
|
|
328
|
+
if (!enabled) {
|
|
329
|
+
const caps = getDshCredentialCapabilities(ctx);
|
|
330
|
+
resetCachedState({ nextState: 'disabled' });
|
|
331
|
+
lastCredentialMeta = describeGoCredential({
|
|
332
|
+
present: false,
|
|
333
|
+
source: null,
|
|
334
|
+
ref: credentialRef,
|
|
335
|
+
fingerprint: null,
|
|
336
|
+
dshCredentialsAvailable: Boolean(caps.service) || lastCredentialMeta.dshCredentialsAvailable,
|
|
337
|
+
canSave: caps.canSet,
|
|
338
|
+
canClear: caps.canUnset
|
|
339
|
+
});
|
|
340
|
+
} else if (connectionState === 'disabled') {
|
|
341
|
+
connectionState = 'unconfigured';
|
|
342
|
+
}
|
|
343
|
+
return getStatus();
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* 僅從本機重新解析 Go 憑證(含 DSH 憑證服務與環境變數),不發起任何網路請求。
|
|
348
|
+
*/
|
|
349
|
+
const syncCredential = async () => {
|
|
350
|
+
if (disposed) {
|
|
351
|
+
return getStatus();
|
|
352
|
+
}
|
|
353
|
+
const myGen = ++generation;
|
|
354
|
+
const cred = await resolveGoCredential({ ctx, credentialRef, env });
|
|
355
|
+
if (disposed || myGen !== generation) {
|
|
356
|
+
return getStatus();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
lastCredentialMeta = describeGoCredential(cred);
|
|
360
|
+
if (!enabled) {
|
|
361
|
+
activeFingerprint = null;
|
|
362
|
+
usage = null;
|
|
363
|
+
previewModels = [];
|
|
364
|
+
checkedAt = null;
|
|
365
|
+
lastError = null;
|
|
366
|
+
lastBilling = null;
|
|
367
|
+
connectionState = 'disabled';
|
|
368
|
+
return getStatus();
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (!cred.present) {
|
|
372
|
+
activeFingerprint = null;
|
|
373
|
+
usage = null;
|
|
374
|
+
previewModels = [];
|
|
375
|
+
checkedAt = null;
|
|
376
|
+
lastError = cred.error
|
|
377
|
+
? {
|
|
378
|
+
category: 'invalid-key',
|
|
379
|
+
subCategory: cred.error,
|
|
380
|
+
status: null,
|
|
381
|
+
retryable: false,
|
|
382
|
+
retryAfterMs: null,
|
|
383
|
+
message: cred.message
|
|
384
|
+
}
|
|
385
|
+
: null;
|
|
386
|
+
connectionState = cred.error ? 'invalid-key' : 'unconfigured';
|
|
387
|
+
store?.clear?.();
|
|
388
|
+
return getStatus();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
activeFingerprint = cred.fingerprint;
|
|
392
|
+
const cached = store?.read?.(cred.fingerprint) ?? null;
|
|
393
|
+
if (cached) {
|
|
394
|
+
usage = cached.usage ? structuredClone(cached.usage) : null;
|
|
395
|
+
previewModels = cloneGoModels(cached.previewModels);
|
|
396
|
+
checkedAt = cached.checkedAt;
|
|
397
|
+
connectionState = 'connected';
|
|
398
|
+
lastError = null;
|
|
399
|
+
} else {
|
|
400
|
+
store?.clear?.();
|
|
401
|
+
connectionState = 'unconfigured';
|
|
402
|
+
}
|
|
403
|
+
return getStatus();
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* 透過 DSH 憑證服務儲存 OpenCode Go Personal API Key,寫入後僅重新解析本機憑證,不自動發起推論。
|
|
408
|
+
*/
|
|
409
|
+
const saveCredential = async (rawKey) => {
|
|
410
|
+
if (disposed) {
|
|
411
|
+
return {
|
|
412
|
+
ok: false,
|
|
413
|
+
error: 'disposed',
|
|
414
|
+
message: 'OpenCode Go service is disposed.',
|
|
415
|
+
status: getStatus()
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
const res = await saveGoCredential({ ctx, credentialRef, key: rawKey });
|
|
419
|
+
if (!res.ok) {
|
|
420
|
+
return {
|
|
421
|
+
ok: false,
|
|
422
|
+
error: res.error,
|
|
423
|
+
message: res.message,
|
|
424
|
+
status: getStatus()
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
resetCachedState({ nextState: enabled ? 'unconfigured' : 'disabled' });
|
|
428
|
+
await syncCredential();
|
|
429
|
+
return {
|
|
430
|
+
ok: true,
|
|
431
|
+
status: getStatus()
|
|
432
|
+
};
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* 透過 DSH 憑證服務清除已儲存的 OpenCode Go API Key,清除後重新解析本機憑證(可退回環境變數)。
|
|
437
|
+
*/
|
|
438
|
+
const clearCredential = async () => {
|
|
439
|
+
if (disposed) {
|
|
440
|
+
return {
|
|
441
|
+
ok: false,
|
|
442
|
+
error: 'disposed',
|
|
443
|
+
message: 'OpenCode Go service is disposed.',
|
|
444
|
+
status: getStatus()
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
const res = await clearGoCredential({ ctx, credentialRef });
|
|
448
|
+
if (!res.ok) {
|
|
449
|
+
return {
|
|
450
|
+
ok: false,
|
|
451
|
+
error: res.error,
|
|
452
|
+
message: res.message,
|
|
453
|
+
status: getStatus()
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
resetCachedState({ nextState: enabled ? 'unconfigured' : 'disabled' });
|
|
457
|
+
await syncCredential();
|
|
458
|
+
return {
|
|
459
|
+
ok: true,
|
|
460
|
+
status: getStatus()
|
|
461
|
+
};
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const dispose = () => {
|
|
465
|
+
disposed = true;
|
|
466
|
+
generation++;
|
|
467
|
+
if (activeController) {
|
|
468
|
+
try { activeController.abort(); } catch {}
|
|
469
|
+
activeController = null;
|
|
470
|
+
}
|
|
471
|
+
inFlight = null;
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
const getPreviewModels = () => cloneGoModels(previewModels);
|
|
475
|
+
|
|
476
|
+
const isPublishedGoPickerModel = (m) => {
|
|
477
|
+
if (!isEligibleGoPickerModel(m)) return false;
|
|
478
|
+
const p = picker.get();
|
|
479
|
+
if (p.mode !== 'manual') return true;
|
|
480
|
+
return p.shown.includes(m.id);
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Stage 2:僅在已啟用且資格驗證連線通過時,發布已驗證且勾選的 Go 文字模型至正式選單。
|
|
485
|
+
*/
|
|
486
|
+
const getPickerModels = () => {
|
|
487
|
+
if (disposed || !enabled || connectionState !== 'connected') {
|
|
488
|
+
return [];
|
|
489
|
+
}
|
|
490
|
+
return cloneGoModels(previewModels.filter(isPublishedGoPickerModel));
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
const pickerState = () => picker.get();
|
|
494
|
+
|
|
495
|
+
const setPickerShown = (modelId, shown) => {
|
|
496
|
+
const id = typeof modelId === 'string' ? modelId.trim() : '';
|
|
497
|
+
const target = previewModels.find((m) => m.id === id);
|
|
498
|
+
if (!target || !isEligibleGoPickerModel(target)) return null;
|
|
499
|
+
const cur = picker.get();
|
|
500
|
+
const set = new Set(
|
|
501
|
+
cur.mode === 'manual'
|
|
502
|
+
? cur.shown
|
|
503
|
+
: previewModels.filter(isEligibleGoPickerModel).map((m) => m.id)
|
|
504
|
+
);
|
|
505
|
+
if (shown) set.add(id);
|
|
506
|
+
else set.delete(id);
|
|
507
|
+
return picker.set({ mode: 'manual', shown: [...set] });
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
const resetPicker = () => picker.set({ mode: 'auto', shown: [] });
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* 解析本次推論所需之已驗證憑證與合格模型(僅供 Go adapter 內部使用)。
|
|
514
|
+
*/
|
|
515
|
+
const getInferenceContext = async (modelId) => {
|
|
516
|
+
if (disposed || !enabled) {
|
|
517
|
+
throw new GoClientError('OpenCode Go provider is disabled.', {
|
|
518
|
+
category: 'invalid-request',
|
|
519
|
+
subCategory: 'go-disabled',
|
|
520
|
+
retryable: false
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
if (connectionState !== 'connected') {
|
|
524
|
+
throw new GoClientError('OpenCode Go subscription is not verified/connected.', {
|
|
525
|
+
category: connectionState === 'no-entitlement' ? 'no-entitlement' : 'invalid-key',
|
|
526
|
+
subCategory: connectionState,
|
|
527
|
+
retryable: false
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
const eligible = previewModels.find((m) => m.id === modelId && isEligibleGoPickerModel(m));
|
|
531
|
+
if (!eligible) {
|
|
532
|
+
throw new GoClientError(`Model "${modelId}" is not an eligible OpenCode Go text model.`, {
|
|
533
|
+
category: 'invalid-request',
|
|
534
|
+
subCategory: 'model-not-eligible',
|
|
535
|
+
retryable: false
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const cred = await resolveGoCredential({ ctx, credentialRef, env });
|
|
540
|
+
if (disposed || !enabled || connectionState !== 'connected') {
|
|
541
|
+
throw new GoClientError('OpenCode Go connection was invalidated during credential resolution.', {
|
|
542
|
+
category: 'invalid-key',
|
|
543
|
+
subCategory: 'credential-invalidated',
|
|
544
|
+
retryable: false
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
if (!cred.present) {
|
|
548
|
+
throw new GoClientError(cred.message || 'Missing OpenCode Go API key.', {
|
|
549
|
+
category: 'invalid-key',
|
|
550
|
+
subCategory: cred.error || 'missing-key',
|
|
551
|
+
retryable: false
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
if (activeFingerprint && cred.fingerprint !== activeFingerprint) {
|
|
555
|
+
throw new GoClientError('OpenCode Go API key changed; re-verify subscription before inference.', {
|
|
556
|
+
category: 'invalid-key',
|
|
557
|
+
subCategory: 'credential-changed',
|
|
558
|
+
retryable: false
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
return {
|
|
563
|
+
key: cred.key,
|
|
564
|
+
model: cloneGoModels([eligible])[0],
|
|
565
|
+
userAgent,
|
|
566
|
+
fetchFn
|
|
567
|
+
};
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
const noteBilling = (usageChunk) => {
|
|
571
|
+
if (!usageChunk || typeof usageChunk !== 'object') return;
|
|
572
|
+
lastBilling = {
|
|
573
|
+
cost: typeof usageChunk.cost === 'number' && Number.isFinite(usageChunk.cost) ? usageChunk.cost : null,
|
|
574
|
+
billingSource: typeof usageChunk.opencode?.billing_source === 'string'
|
|
575
|
+
? usageChunk.opencode.billing_source
|
|
576
|
+
: null,
|
|
577
|
+
allowance: typeof usageChunk.opencode?.allowance === 'number' && Number.isFinite(usageChunk.opencode.allowance)
|
|
578
|
+
? usageChunk.opencode.allowance
|
|
579
|
+
: null,
|
|
580
|
+
recordedAt: Date.now()
|
|
581
|
+
};
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
const getStatus = () => {
|
|
585
|
+
const pickerModels = getPickerModels();
|
|
586
|
+
const published = !disposed && enabled && connectionState === 'connected';
|
|
587
|
+
const currentPicker = picker.get();
|
|
588
|
+
const annotatedPreview = cloneGoModels(previewModels).map((m) => {
|
|
589
|
+
const classification = classifyGoPickerModel(m);
|
|
590
|
+
const isSelected = currentPicker.mode !== 'manual' || currentPicker.shown.includes(m.id);
|
|
591
|
+
return {
|
|
592
|
+
...m,
|
|
593
|
+
pickerEligible: classification.eligible,
|
|
594
|
+
pickerPublished: published && classification.eligible && isSelected,
|
|
595
|
+
pickerImageSupported: Boolean(published && supportsGoImageInput(m)),
|
|
596
|
+
pickerReasons: classification.reasons
|
|
597
|
+
};
|
|
598
|
+
});
|
|
599
|
+
const liveCaps = getDshCredentialCapabilities(ctx);
|
|
600
|
+
return {
|
|
601
|
+
enabled,
|
|
602
|
+
providerId,
|
|
603
|
+
providerName,
|
|
604
|
+
connectionState,
|
|
605
|
+
inferenceSupported: true,
|
|
606
|
+
pickerPublishedCount: pickerModels.length,
|
|
607
|
+
picker: currentPicker,
|
|
608
|
+
credential: {
|
|
609
|
+
...lastCredentialMeta,
|
|
610
|
+
dshCredentialsAvailable: Boolean(liveCaps.service) || lastCredentialMeta.dshCredentialsAvailable,
|
|
611
|
+
canSave: liveCaps.canSet || lastCredentialMeta.canSave,
|
|
612
|
+
canClear: liveCaps.canUnset || lastCredentialMeta.canClear
|
|
613
|
+
},
|
|
614
|
+
usage: usage ? structuredClone(usage) : null,
|
|
615
|
+
lastBilling: lastBilling ? { ...lastBilling } : null,
|
|
616
|
+
previewModels: annotatedPreview,
|
|
617
|
+
checkedAt,
|
|
618
|
+
error: lastError ? { ...lastError } : null
|
|
619
|
+
};
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
return {
|
|
623
|
+
init,
|
|
624
|
+
refresh,
|
|
625
|
+
clear,
|
|
626
|
+
syncCredential,
|
|
627
|
+
saveCredential,
|
|
628
|
+
clearCredential,
|
|
629
|
+
setEnabled,
|
|
630
|
+
dispose,
|
|
631
|
+
isEnabled: () => enabled,
|
|
632
|
+
providerId: () => providerId,
|
|
633
|
+
providerName: () => providerName,
|
|
634
|
+
getPreviewModels,
|
|
635
|
+
getPickerModels,
|
|
636
|
+
pickerState,
|
|
637
|
+
setPickerShown,
|
|
638
|
+
resetPicker,
|
|
639
|
+
getInferenceContext,
|
|
640
|
+
noteBilling,
|
|
641
|
+
getStatus
|
|
642
|
+
};
|
|
643
|
+
}
|