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.
@@ -0,0 +1,305 @@
1
+ /**
2
+ * OpenCode Go 模型目錄正規化與隔離快取模組(Stage 1)。
3
+ *
4
+ * 設計規則:
5
+ * - 僅處理 `/inference/go/v1/models` 的正規化與 Go 專用快取。
6
+ * - 絕不混用免費 OAuth 的 `STATIC_FREE_MODELS` 或 `~/.dsh/opencode-next.models.json`。
7
+ * - 缺欄位不冒稱支援:未明確提供的 `limit`、`capabilities`、`modalities` 一律保留 `null`。
8
+ * - 快取以 `credentialFingerprint` 隔離;換 key 或停用時清除舊快取。
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import os from 'node:os';
14
+ import { randomBytes } from 'node:crypto';
15
+
16
+ function positiveIntOrNull(value) {
17
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) return null;
18
+ return value;
19
+ }
20
+
21
+ function boolOrNull(value) {
22
+ return typeof value === 'boolean' ? value : null;
23
+ }
24
+
25
+ function normalizeStringArrayOrNull(arr) {
26
+ if (!Array.isArray(arr)) return null;
27
+ const cleaned = [];
28
+ for (const item of arr) {
29
+ if (typeof item !== 'string') continue;
30
+ const trimmed = item.trim().toLowerCase();
31
+ if (trimmed && !cleaned.includes(trimmed)) cleaned.push(trimmed);
32
+ }
33
+ return cleaned;
34
+ }
35
+
36
+ /**
37
+ * 正規化單一 Go 模型中繼資料。
38
+ * 涵蓋 `id`、`type`、`limit`、`capabilities` 與 `modalities`;缺欄位不冒稱支援。
39
+ */
40
+ export function normalizeGoModel(raw, fallbackId = null) {
41
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
42
+ const rawId = typeof raw.id === 'string' ? raw.id.trim() : (typeof fallbackId === 'string' ? fallbackId.trim() : '');
43
+ if (!rawId) return null;
44
+
45
+ const name = typeof raw.name === 'string' && raw.name.trim()
46
+ ? raw.name.trim()
47
+ : (typeof raw.display_name === 'string' && raw.display_name.trim() ? raw.display_name.trim() : rawId);
48
+
49
+ const type = typeof raw.type === 'string' && raw.type.trim()
50
+ ? raw.type.trim()
51
+ : null;
52
+
53
+ const limit = {
54
+ context: positiveIntOrNull(raw.limit?.context ?? raw.context_window ?? raw.contextWindow),
55
+ output: positiveIntOrNull(raw.limit?.output ?? raw.max_output_tokens ?? raw.max_tokens),
56
+ input: positiveIntOrNull(raw.limit?.input ?? raw.max_input_tokens)
57
+ };
58
+
59
+ const capObj = raw.capabilities && typeof raw.capabilities === 'object' && !Array.isArray(raw.capabilities)
60
+ ? raw.capabilities
61
+ : {};
62
+
63
+ const capabilities = {
64
+ reasoning: boolOrNull(capObj.reasoning ?? raw.reasoning),
65
+ toolCall: boolOrNull(capObj.toolCall ?? capObj.tool_call ?? raw.toolCall ?? raw.tool_call),
66
+ attachment: boolOrNull(capObj.attachment ?? raw.attachment),
67
+ structuredOutput: boolOrNull(capObj.structuredOutput ?? capObj.structured_output ?? raw.structuredOutput ?? raw.structured_output),
68
+ temperature: boolOrNull(capObj.temperature ?? raw.temperature)
69
+ };
70
+
71
+ const inputModalities = normalizeStringArrayOrNull(raw.modalities?.input ?? raw.inputModalities);
72
+ const outputModalities = normalizeStringArrayOrNull(raw.modalities?.output ?? raw.outputModalities);
73
+
74
+ const modalities = {
75
+ input: inputModalities,
76
+ output: outputModalities
77
+ };
78
+
79
+ return {
80
+ id: rawId,
81
+ name,
82
+ type,
83
+ limit,
84
+ capabilities,
85
+ modalities,
86
+ status: typeof raw.status === 'string' && raw.status.trim() ? raw.status.trim() : null,
87
+ ownedBy: typeof raw.owned_by === 'string' && raw.owned_by.trim()
88
+ ? raw.owned_by.trim()
89
+ : (typeof raw.provider === 'string' && raw.provider.trim() ? raw.provider.trim() : null)
90
+ };
91
+ }
92
+
93
+ /**
94
+ * 解析並正規化 `/inference/go/v1/models` 回應清單。
95
+ */
96
+ export function normalizeGoModelsPayload(payload) {
97
+ let entries = null;
98
+ let keyed = false;
99
+
100
+ if (Array.isArray(payload)) {
101
+ entries = payload;
102
+ } else if (payload && typeof payload === 'object') {
103
+ if (Array.isArray(payload.data)) {
104
+ entries = payload.data;
105
+ } else if (Array.isArray(payload.models)) {
106
+ entries = payload.models;
107
+ } else if (payload.models && typeof payload.models === 'object') {
108
+ entries = Object.entries(payload.models);
109
+ keyed = true;
110
+ }
111
+ }
112
+
113
+ if (!entries) {
114
+ throw new TypeError('Invalid OpenCode Go models payload shape.');
115
+ }
116
+
117
+ const seen = new Set();
118
+ const normalized = [];
119
+ for (const entry of entries) {
120
+ const item = keyed ? normalizeGoModel(entry[1], entry[0]) : normalizeGoModel(entry, null);
121
+ if (!item || seen.has(item.id)) continue;
122
+ seen.add(item.id);
123
+ normalized.push(item);
124
+ }
125
+ return normalized;
126
+ }
127
+
128
+ export function cloneGoModels(models) {
129
+ if (!Array.isArray(models)) return [];
130
+ return models.map((m) => ({
131
+ ...m,
132
+ limit: m.limit ? { ...m.limit } : { context: null, output: null, input: null },
133
+ capabilities: m.capabilities
134
+ ? { ...m.capabilities }
135
+ : { reasoning: null, toolCall: null, attachment: null, structuredOutput: null, temperature: null },
136
+ modalities: {
137
+ input: Array.isArray(m.modalities?.input) ? [...m.modalities.input] : null,
138
+ output: Array.isArray(m.modalities?.output) ? [...m.modalities.output] : null
139
+ }
140
+ }));
141
+ }
142
+
143
+ const INACTIVE_STATUSES = new Set(['deprecated', 'disabled', 'retired', 'inactive']);
144
+ const ELIGIBLE_CHAT_TYPES = new Set(['chat', 'chat-completions', 'text']);
145
+
146
+ function hasCatalogImageModality(inputModalities) {
147
+ if (!Array.isArray(inputModalities)) return false;
148
+ return inputModalities.some((entry) => {
149
+ if (typeof entry !== 'string') return false;
150
+ const lower = entry.trim().toLowerCase();
151
+ return lower === 'image' || lower.startsWith('image/');
152
+ });
153
+ }
154
+
155
+ /**
156
+ * 評估 Go 模型是否具備進入 DSH 正式模型選單之結構資格,並回傳不合格原因碼(單一判斷來源)。
157
+ *
158
+ * 僅限「狀態有效、type 為 chat/chat-completions/text,且具備明確 limit.context 與 limit.output」
159
+ * 的模型可入選;缺 type、缺上限、已下架/停用、非文字模型或其它協定一律僅供預覽。
160
+ */
161
+ export function classifyGoPickerModel(model) {
162
+ if (!model || typeof model !== 'object' || typeof model.id !== 'string' || !model.id.trim()) {
163
+ return { eligible: false, reasons: ['invalid-model'] };
164
+ }
165
+ const reasons = [];
166
+ if (typeof model.status === 'string' && INACTIVE_STATUSES.has(model.status.trim().toLowerCase())) {
167
+ reasons.push('inactive-status');
168
+ }
169
+ if (typeof model.type !== 'string' || !model.type.trim()) {
170
+ reasons.push('missing-type');
171
+ } else if (!ELIGIBLE_CHAT_TYPES.has(model.type.trim().toLowerCase())) {
172
+ reasons.push('unsupported-type');
173
+ }
174
+ if (
175
+ !Number.isSafeInteger(model.limit?.context) || model.limit.context <= 0
176
+ || !Number.isSafeInteger(model.limit?.output) || model.limit.output <= 0
177
+ ) {
178
+ reasons.push('missing-limits');
179
+ }
180
+ if (
181
+ (Array.isArray(model.modalities?.input) && !model.modalities.input.includes('text'))
182
+ || (Array.isArray(model.modalities?.output) && model.modalities.output.length > 0 && !model.modalities.output.includes('text'))
183
+ ) {
184
+ reasons.push('non-text-modality');
185
+ }
186
+ return {
187
+ eligible: reasons.length === 0,
188
+ reasons
189
+ };
190
+ }
191
+
192
+ /**
193
+ * 判斷 Go 模型是否可於第二階段進入 DSH 正式模型選單。
194
+ */
195
+ export function isEligibleGoPickerModel(model) {
196
+ return classifyGoPickerModel(model).eligible;
197
+ }
198
+
199
+ /**
200
+ * 判斷 Go 模型是否支援透過 `/inference/go/openai/v1/chat/completions` 接收圖片。
201
+ * 須同時滿足:進選單資格,且上游目錄宣告 `image`/`image/*` 輸入模態(不限於手動白名單,未來新模型可自動支援)。
202
+ */
203
+ export function supportsGoImageInput(model) {
204
+ if (!isEligibleGoPickerModel(model)) return false;
205
+ return hasCatalogImageModality(model.modalities?.input);
206
+ }
207
+
208
+ /**
209
+ * 轉成 DSH LlmModel 描述物件。
210
+ * 不填補預設上限;凡進選單且上游目錄宣告 `image`/`image/*` 的模型皆自動開放 `'image'` 輸入,其餘維持純文字。
211
+ */
212
+ export function toGoPickerDescriptor(provider, model) {
213
+ const inputModalities = supportsGoImageInput(model) ? ['text', 'image'] : ['text'];
214
+ return {
215
+ provider,
216
+ id: model.id,
217
+ name: model.name || model.id,
218
+ inputModalities,
219
+ context: { contextWindow: model.limit.context },
220
+ defaultMaxTokens: model.limit.output
221
+ };
222
+ }
223
+
224
+ export function defaultGoCachePath() {
225
+ return path.join(os.homedir(), '.dsh', 'opencode-go.cache.json');
226
+ }
227
+
228
+ /**
229
+ * OpenCode Go 專屬快取儲存器。
230
+ * 絕不儲存任何明文密鑰,僅記錄 `credentialFingerprint` 與正規化後的狀態預覽。
231
+ */
232
+ export class GoCacheStore {
233
+ #path;
234
+
235
+ constructor(cachePath = null) {
236
+ this.#path = typeof cachePath === 'string' && cachePath.trim()
237
+ ? cachePath.trim()
238
+ : (cachePath === null ? null : defaultGoCachePath());
239
+ }
240
+
241
+ get path() {
242
+ return this.#path;
243
+ }
244
+
245
+ read(expectedFingerprint = null) {
246
+ if (!this.#path) return null;
247
+ try {
248
+ if (!fs.existsSync(this.#path)) return null;
249
+ const parsed = JSON.parse(fs.readFileSync(this.#path, 'utf8'));
250
+ if (!parsed || parsed.version !== 1 || typeof parsed.credentialFingerprint !== 'string') {
251
+ return null;
252
+ }
253
+ if (expectedFingerprint && parsed.credentialFingerprint !== expectedFingerprint) {
254
+ return null;
255
+ }
256
+ return {
257
+ version: 1,
258
+ credentialFingerprint: parsed.credentialFingerprint,
259
+ checkedAt: Number.isFinite(parsed.checkedAt) ? parsed.checkedAt : null,
260
+ usage: parsed.usage ?? null,
261
+ previewModels: cloneGoModels(Array.isArray(parsed.previewModels) ? parsed.previewModels : [])
262
+ };
263
+ } catch {
264
+ return null;
265
+ }
266
+ }
267
+
268
+ write({ credentialFingerprint, checkedAt, usage, previewModels }) {
269
+ if (!this.#path || !credentialFingerprint) return false;
270
+ const payload = {
271
+ version: 1,
272
+ credentialFingerprint,
273
+ checkedAt: Number.isFinite(checkedAt) ? checkedAt : Date.now(),
274
+ usage: usage ?? null,
275
+ previewModels: cloneGoModels(previewModels)
276
+ };
277
+ try {
278
+ const dir = path.dirname(this.#path);
279
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
280
+ const tmp = `${this.#path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
281
+ try {
282
+ fs.writeFileSync(tmp, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
283
+ fs.renameSync(tmp, this.#path);
284
+ } finally {
285
+ try {
286
+ if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
287
+ } catch {}
288
+ }
289
+ return true;
290
+ } catch {
291
+ return false;
292
+ }
293
+ }
294
+
295
+ clear() {
296
+ if (!this.#path) return false;
297
+ try {
298
+ if (fs.existsSync(this.#path)) {
299
+ fs.rmSync(this.#path, { force: true });
300
+ return true;
301
+ }
302
+ } catch {}
303
+ return false;
304
+ }
305
+ }