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/lib/images.js ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 圖片投影:把 DSH 的 image 區塊變成 OpenAI 相容端點吃得下的 data URI。
3
+ *
4
+ * 這個模組刻意不 import 任何 `@deepseek-ai/*` 套件。attachment service 是宿主注入
5
+ * 的服務(服務名 `attachments`),型別上跟本檔宣告的 duck type 相同即可;真的去
6
+ * import 會讓外掛在沒有該套件的 profile 上直接載入失敗。
7
+ */
8
+
9
+ /**
10
+ * 依像素預算算出請求時的目標尺寸與位元組上限。
11
+ *
12
+ * 這必須是**純函式且確定**:attachment service 會用「附件 id + target」算 variant id
13
+ * 做快取。同一張圖每次都得到同一個 target,才會命中同一份請求版本位元組。
14
+ */
15
+ export function requestImageTarget(ref, pixelBudget, maxBytes) {
16
+ const width = Number(ref?.width);
17
+ const height = Number(ref?.height);
18
+ const budget = Number(pixelBudget) > 0 ? Math.floor(Number(pixelBudget)) : 0;
19
+ const limit = Number(maxBytes) > 0 ? Math.floor(Number(maxBytes)) : 0;
20
+
21
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {
22
+ return undefined;
23
+ }
24
+ const pixels = width * height;
25
+ if (budget <= 0 || pixels <= budget) {
26
+ return { width, height, maxBytes: limit > 0 ? limit : Math.max(1, Number(ref?.bytes) || 1) };
27
+ }
28
+ const scale = Math.sqrt(budget / pixels);
29
+ return {
30
+ width: Math.max(1, Math.floor(width * scale)),
31
+ height: Math.max(1, Math.floor(height * scale)),
32
+ maxBytes: limit > 0 ? limit : Math.max(1, Number(ref?.bytes) || 1)
33
+ };
34
+ }
35
+
36
+ function dataUrl(mediaType, data) {
37
+ const type = typeof mediaType === 'string' && mediaType !== '' ? mediaType : 'image/png';
38
+ return `data:${type};base64,${Buffer.from(data).toString('base64')}`;
39
+ }
40
+
41
+ /**
42
+ * 讀出一張請求版本圖片。
43
+ *
44
+ * 先走 `readImageRequest`(會依 target 縮放並快取);服務不支援投影時退回原圖。
45
+ * 兩條路都失敗就回傳 undefined——圖片解析失敗絕不能讓整個請求掛掉,呼叫端會把它
46
+ * 換成佔位文字,模型至少知道漏了哪一份附件。
47
+ */
48
+ async function readOne(attachments, ref, target, signal) {
49
+ if (typeof attachments?.readImageRequest === 'function' && target !== undefined) {
50
+ try {
51
+ const projected = await attachments.readImageRequest(ref, target, signal);
52
+ if (projected && projected.data) {
53
+ return dataUrl(projected.mediaType ?? projected.attachment?.mediaType, projected.data);
54
+ }
55
+ } catch (error) {
56
+ if (signal?.aborted) throw error;
57
+ // 投影不支援或編碼失敗:退回原圖。
58
+ }
59
+ }
60
+ if (typeof attachments?.readImage === 'function') {
61
+ try {
62
+ const original = await attachments.readImage(ref, signal);
63
+ if (original && original.data) {
64
+ return dataUrl(original.ref?.mediaType ?? ref.mediaType, original.data);
65
+ }
66
+ } catch (error) {
67
+ if (signal?.aborted) throw error;
68
+ }
69
+ }
70
+ return undefined;
71
+ }
72
+
73
+ /**
74
+ * 把一批附件參照讀成 `Map<attachmentId, dataURI>`。
75
+ *
76
+ * @param refs `collectImageRefs()` 的結果。
77
+ * @param options `attachments`:attachment service(可能是 undefined);`pixelBudget`
78
+ * 與 `maxBytes`:投影預算;`signal`:取消訊號。
79
+ */
80
+ export async function resolveImageDataUrls(refs, options = {}) {
81
+ const urls = new Map();
82
+ if (!(refs instanceof Map) || refs.size === 0) return urls;
83
+
84
+ const attachments = options.attachments;
85
+ if (attachments === undefined || attachments === null) return urls;
86
+
87
+ const signal = options.signal;
88
+ const pixelBudget = options.pixelBudget;
89
+ const maxBytes = options.maxBytes;
90
+
91
+ for (const [attachmentId, ref] of refs) {
92
+ signal?.throwIfAborted?.();
93
+ const target = requestImageTarget(ref, pixelBudget, maxBytes);
94
+ const url = await readOne(attachments, ref, target, signal);
95
+ if (typeof url === 'string' && url !== '') urls.set(attachmentId, url);
96
+ }
97
+ return urls;
98
+ }
package/lib/index.js ADDED
@@ -0,0 +1,408 @@
1
+ import { copyFileSync, existsSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { Config, resolveConfig } from './config.js';
5
+ import { ModelCatalog } from './catalog.js';
6
+ import { TokenManager } from './token-manager.js';
7
+ import { AutoSwitchStore } from './store.js';
8
+ import { ContextWindowStore } from './context-window.js';
9
+ import { OpenCodeOAuthAdapter } from './adapter.js';
10
+ import { FallbackStore } from './fallback.js';
11
+ import { PickerStore } from './picker.js';
12
+ import { probeModels } from './probe.js';
13
+ import { createStatusReporter } from './status.js';
14
+ import { registerWebApi } from './web-api.js';
15
+ import { PROVIDER, PROVIDER_NAME, GO_PROVIDER, GO_PROVIDER_NAME } from './constants.js';
16
+ import { installedBunPath } from './bun-transport.js';
17
+ import { createGoService } from './go/service.js';
18
+ import { OpenCodeGoAdapter } from './go/adapter.js';
19
+
20
+ export const name = 'opencode-next';
21
+ export const inject = ['llm'];
22
+ export { Config };
23
+
24
+ /**
25
+ * Applies the opencode-next Cordis plugin into the DSH host runtime.
26
+ *
27
+ * Model discovery is fully automatic and runs on two cadences:
28
+ * - a light catalog poll (default 15 min) that notices newly published free
29
+ * models as soon as OpenCode lists them;
30
+ * - a full availability probe (default 6 h) that re-verifies every candidate
31
+ * so retired models disappear from the picker.
32
+ *
33
+ * Note: named exports only, no `export default`, so the loader's
34
+ * `unwrapExports` cannot collapse this namespace into a default export and
35
+ * hide `name` / `Config` / `apply`.
36
+ */
37
+ function migrateLegacyStateFiles() {
38
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh');
39
+ const suffixes = ['accounts.json', 'models.json', 'picker.json', 'go-picker.json', 'context.json', 'token.json'];
40
+ for (const suffix of suffixes) {
41
+ const legacy = join(home, `opencode-oauth.${suffix}`);
42
+ const next = join(home, `opencode-next.${suffix}`);
43
+ try {
44
+ if (!existsSync(next) && existsSync(legacy)) {
45
+ copyFileSync(legacy, next);
46
+ }
47
+ } catch {
48
+ // 遷移失敗不阻擋外掛啟動
49
+ }
50
+ }
51
+ }
52
+
53
+ export function apply(ctx, config) {
54
+ const resolved = resolveConfig(config);
55
+ if (!config?.probeCachePath && !config?.credentialPath) {
56
+ migrateLegacyStateFiles();
57
+ }
58
+ // Node fetch is rejected with 429 even when the request shape is valid.
59
+ // A missing plugin config must not silently select that path when Bun exists.
60
+ if (config?.bunTransport?.enabled !== false) {
61
+ const bunPath = installedBunPath(resolved.bunTransport?.bunPath);
62
+ if (bunPath) {
63
+ resolved.bunTransport = {
64
+ ...resolved.bunTransport,
65
+ enabled: true,
66
+ bunPath: resolved.bunTransport?.bunPath || bunPath
67
+ };
68
+ }
69
+ }
70
+ const tokenManager = new TokenManager(resolved.credentialPath || undefined);
71
+ const contextWindowStore = new ContextWindowStore();
72
+ // 勾選名單與備援設定一樣存在外掛自己的檔案裡:使用者要的是「一個畫面
73
+ // 就能勾選」的清單,而不是得手改 DSH 設定檔的 plugin config。
74
+ const pickerStore = new PickerStore();
75
+ const catalog = new ModelCatalog({
76
+ probeCachePath: resolved.probeCachePath || undefined,
77
+ contextStore: contextWindowStore,
78
+ pickerStore
79
+ });
80
+
81
+ /**
82
+ * attachment service 是**延遲解析**而且允許缺席的。
83
+ *
84
+ * core 的 provider 也是用 `ctx.get('attachments')` 在請求當下取服務,而不是硬寫進
85
+ * `inject`。這樣做有兩個好處:沒有掛 attachment 服務的 profile 仍然載得進本外掛
86
+ * (圖片退化成佔位文字,其他功能照常),而且服務晚於本外掛載入時也拿得到。
87
+ */
88
+ const resolveAttachments = () => {
89
+ try {
90
+ return ctx.get?.('attachments');
91
+ } catch {
92
+ return undefined;
93
+ }
94
+ };
95
+
96
+ // 備援順位存在外掛自己的檔案裡,而不是 DSH 的 plugin config:使用者要的是
97
+ // 一個在設定頁就能勾選、就能調順序的開關,而 plugin config 得手動改設定檔。
98
+ // 建在這裡(而不是 web-api 裡)是因為 adapter 讀它、API 寫它,必須是同一份
99
+ // 記憶體狀態,否則改完要重啟才生效。
100
+ const fallbackStore = new FallbackStore();
101
+ const autoSwitchStore = new AutoSwitchStore({ defaultEnabled: resolved.autoSwitchAccounts });
102
+
103
+ const adapter = new OpenCodeOAuthAdapter(catalog, tokenManager, {
104
+ ...resolved,
105
+ resolveAttachments,
106
+ fallback: fallbackStore,
107
+ autoSwitch: autoSwitchStore
108
+ });
109
+
110
+ const providerId = resolved.providerId || PROVIDER;
111
+ ctx.llm.registerAdapter([providerId], adapter);
112
+
113
+ const goConfig = resolved.goSubscription || {};
114
+ const goProviderId = (goConfig.providerId && goConfig.providerId !== providerId)
115
+ ? goConfig.providerId
116
+ : GO_PROVIDER;
117
+ const goService = createGoService({
118
+ ctx,
119
+ config: {
120
+ ...goConfig,
121
+ providerId: goProviderId,
122
+ providerName: goConfig.providerName || GO_PROVIDER_NAME
123
+ }
124
+ });
125
+ let goAdapter = null;
126
+ if (goConfig.enabled === true) {
127
+ goAdapter = new OpenCodeGoAdapter(goService, {
128
+ providerId: goProviderId,
129
+ providerName: goConfig.providerName || GO_PROVIDER_NAME,
130
+ streamIdleTimeoutMs: resolved.streamIdleTimeoutMs,
131
+ resolveAttachments,
132
+ imagePixelBudget: resolved.imagePixelBudget,
133
+ imageMaxBytes: resolved.imageMaxBytes
134
+ });
135
+ ctx.llm.registerAdapter([goProviderId], goAdapter);
136
+ }
137
+
138
+ const notifyAdaptersUpdated = () => {
139
+ if (typeof ctx.emit === 'function') {
140
+ try {
141
+ ctx.emit('llm/adapters-updated');
142
+ } catch (err) {
143
+ ctx.logger?.warn?.(`[opencode-next] Could not emit adapters-updated: ${err.message}`);
144
+ }
145
+ }
146
+ };
147
+
148
+ /**
149
+ * 設定頁(狀態頁)的宿主端。
150
+ *
151
+ * 這裡刻意「註冊失敗不影響 provider」:模型能不能用遠比設定頁出不出的來重要,
152
+ * 所以整段包了 try/catch。web server 不存在(例如 headless profile)時,
153
+ * registerWebApi 內部的 ctx.inject(['webServer']) 本來就會安靜地不掛路由。
154
+ */
155
+ try {
156
+ const statusReporter = createStatusReporter({
157
+ tokenManager,
158
+ catalog,
159
+ fallback: fallbackStore,
160
+ autoSwitch: autoSwitchStore,
161
+ go: goService,
162
+ config: {
163
+ providerId,
164
+ providerName: resolved.providerName || PROVIDER_NAME,
165
+ autoDetectModels: resolved.autoDetectModels,
166
+ probeIntervalMs: resolved.probeIntervalMs,
167
+ catalogPollMs: resolved.catalogPollMs,
168
+ imagePixelBudget: resolved.imagePixelBudget,
169
+ imageMaxBytes: resolved.imageMaxBytes
170
+ }
171
+ });
172
+
173
+ registerWebApi(ctx, {
174
+ tokenManager,
175
+ catalog,
176
+ statusReporter,
177
+ fallback: fallbackStore,
178
+ autoSwitch: autoSwitchStore,
179
+ contextWindowStore,
180
+ goService,
181
+ onAdaptersUpdated: notifyAdaptersUpdated,
182
+ config: {
183
+ credentialPath: resolved.credentialPath || undefined,
184
+ inferenceUrl: resolved.inferenceUrl,
185
+ bunTransport: resolved.bunTransport
186
+ }
187
+ });
188
+ } catch (err) {
189
+ ctx.logger?.warn?.(
190
+ `[opencode-next] Settings page unavailable: ${err?.message ?? err}`
191
+ );
192
+ }
193
+
194
+ ctx.logger?.info?.(
195
+ `[opencode-next] Registered provider "${providerId}" (${catalog.getModels().length} models); inference transport: ${resolved.bunTransport?.enabled ? 'bun' : 'node'}.`
196
+ );
197
+ if (goAdapter) {
198
+ ctx.logger?.info?.(
199
+ `[opencode-next] Registered OpenCode Go provider "${goProviderId}" (${goService.getPickerModels().length} picker models; text/tools).`
200
+ );
201
+ }
202
+
203
+ let probeTimer = null;
204
+ let pollTimer = null;
205
+ let disposed = false;
206
+
207
+ const log = (level, message) => ctx.logger?.[level]?.(`[opencode-next] ${message}`);
208
+
209
+ /** Describes which candidates a probe left hidden, for the log. */
210
+ const describeHidden = () => {
211
+ const hidden = catalog.getCandidates().filter((m) => !catalog.isAvailable(m.id)).map((m) => m.id);
212
+ if (hidden.length > 0) log('info', `Hidden (not serving): ${hidden.join(', ')}`);
213
+ };
214
+
215
+ /**
216
+ * Full verification sweep: re-fetches the catalog, probes every candidate,
217
+ * and republishes the model list.
218
+ */
219
+ const runFullProbe = async (reason) => {
220
+ if (disposed) return;
221
+
222
+ await catalog.init();
223
+
224
+ if (!resolved.autoDetectModels) {
225
+ log('info', `Catalog: ${catalog.getCandidates().length} free candidates (auto-detect disabled).`);
226
+ notifyAdaptersUpdated();
227
+ return;
228
+ }
229
+
230
+ // A fresh cached result is good enough on restart — but only if the
231
+ // catalog has not gained models since. New candidates must still be
232
+ // probed right away, otherwise a model published today would stay hidden
233
+ // until the next scheduled poll.
234
+ const unseen = catalog.unseenCandidates();
235
+ const cacheFresh = reason !== 'manual' && catalog.isProbeFresh(resolved.probeIntervalMs);
236
+
237
+ if (cacheFresh && unseen.length === 0) {
238
+ const s = catalog.availabilitySummary();
239
+ log('info', `Availability cache is fresh: ${s.available}/${s.candidates} free models available.`);
240
+ notifyAdaptersUpdated();
241
+ return;
242
+ }
243
+
244
+ const incremental = cacheFresh && unseen.length > 0;
245
+ if (incremental) {
246
+ log('info', `Catalog has ${unseen.length} unverified free model(s): ${unseen.join(', ')}`);
247
+ }
248
+
249
+ let token;
250
+ try {
251
+ token = await tokenManager.getValidToken();
252
+ } catch (err) {
253
+ // No credential yet: keep the known list so the picker still renders and
254
+ // retry on the next interval, or as soon as the user signs in.
255
+ log('warn', `Skipping availability probe (${reason}): ${err.message}`);
256
+ notifyAdaptersUpdated();
257
+ return;
258
+ }
259
+
260
+ try {
261
+ const outcome = await catalog.refreshAvailability(token, probeModels, {
262
+ inferenceUrl: resolved.inferenceUrl,
263
+ bunTransport: resolved.bunTransport,
264
+ incremental,
265
+ onProgress: (done, total) => {
266
+ if (done === total || done % 10 === 0) log('info', `Probing models: ${done}/${total}`);
267
+ }
268
+ });
269
+
270
+ if (!outcome.applied) {
271
+ log(
272
+ 'warn',
273
+ `Availability probe inconclusive (${reason}): the free lane did not route the request (status ${outcome.results?.[0]?.status ?? 'unknown'}). Keeping the previous model list.`
274
+ );
275
+ notifyAdaptersUpdated();
276
+ return;
277
+ }
278
+
279
+ const s = catalog.availabilitySummary();
280
+ if (incremental) {
281
+ log(
282
+ 'info',
283
+ `Verified ${outcome.tested} new free model(s) (${reason}): ${outcome.added?.length ? outcome.added.join(', ') : 'none serving yet'}.`
284
+ );
285
+ } else {
286
+ log('info', `Availability updated (${reason}): ${s.available}/${s.candidates} free models responding.`);
287
+ }
288
+ describeHidden();
289
+ notifyAdaptersUpdated();
290
+ } catch (err) {
291
+ log('warn', `Availability probe failed (${reason}): ${err.message}`);
292
+ notifyAdaptersUpdated();
293
+ }
294
+ };
295
+
296
+ /**
297
+ * Light poll: re-fetches the catalog and, when new free models appear,
298
+ * probes only those and adds them to the picker. Cheap enough to run often.
299
+ */
300
+ const pollForNewModels = async () => {
301
+ if (disposed || !resolved.autoDetectModels) return;
302
+
303
+ try {
304
+ const { added, removed } = await catalog.refreshCatalog();
305
+
306
+ if (added.length === 0 && removed.length === 0) return;
307
+
308
+ if (added.length > 0) log('info', `Catalog gained ${added.length} free candidate(s): ${added.join(', ')}`);
309
+ if (removed.length > 0) log('info', `Catalog dropped ${removed.length} free candidate(s): ${removed.join(', ')}`);
310
+
311
+ // 發現新候選模型時只更新候選目錄,不自動發起探測。
312
+ // 避免背景未經許可發送請求消耗使用者的每日額度。
313
+ describeHidden();
314
+ notifyAdaptersUpdated();
315
+ } catch (err) {
316
+ log('warn', `Catalog poll failed: ${err.message}`);
317
+ }
318
+ };
319
+
320
+ const startTimers = () => {
321
+ if (disposed) return;
322
+
323
+ if (resolved.autoDetectModels && !pollTimer && resolved.catalogPollMs > 0) {
324
+ pollTimer = setInterval(
325
+ () => void pollForNewModels(),
326
+ Math.max(60_000, resolved.catalogPollMs)
327
+ );
328
+ pollTimer.unref?.();
329
+ }
330
+ };
331
+
332
+ // 僅在背景載入本機快取與靜態目錄,完全取消開機自動探測與定時自動探測。
333
+ //
334
+ // 理由:OpenCode 免費通道每日額度極為有限(約數十次),若每次開機或每隔數小時
335
+ // 就在背景對 46 個模型全量探測,會在幾秒內將使用者的每日全量額度消耗殆盡。
336
+ // 改為「手動一鍵探測」模式,由使用者決定何時發起探測。
337
+ void catalog.init()
338
+ .then(() => {
339
+ notifyAdaptersUpdated();
340
+ startTimers();
341
+ })
342
+ .catch((err) => {
343
+ log('warn', `Startup catalog init failed: ${err.message}`);
344
+ startTimers();
345
+ });
346
+
347
+ const runGoStartupSync = () => {
348
+ if (disposed) return;
349
+ if (goAdapter) {
350
+ void goService.init()
351
+ .then((status) => {
352
+ if (disposed) return;
353
+ notifyAdaptersUpdated();
354
+ if (status?.credential?.present) {
355
+ return goService.refresh({ reason: 'startup' })
356
+ .then(() => {
357
+ if (!disposed) notifyAdaptersUpdated();
358
+ });
359
+ }
360
+ })
361
+ .catch((err) => {
362
+ log('warn', `OpenCode Go startup init/refresh failed: ${err?.message ?? err}`);
363
+ });
364
+ } else if (ctx.get?.('credentials') ?? ctx.credentials) {
365
+ void goService.syncCredential?.()
366
+ .catch((err) => {
367
+ log('warn', `OpenCode Go credential sync failed: ${err?.message ?? err}`);
368
+ });
369
+ }
370
+ };
371
+
372
+ runGoStartupSync();
373
+
374
+ // DSH 的 credentials 服務可能在 opencode-next 之後才完成註冊;
375
+ // 監聽注入就緒事件,一掛載就重新解析憑證並自動載入 Go 模型。
376
+ if (typeof ctx.inject === 'function') {
377
+ try {
378
+ ctx.inject(['credentials'], () => {
379
+ runGoStartupSync();
380
+ });
381
+ } catch {
382
+ // 測試替身或無 inject 支援時忽略
383
+ }
384
+ }
385
+
386
+ if (typeof ctx.on === 'function') {
387
+ ctx.on('dispose', () => {
388
+ disposed = true;
389
+ if (probeTimer) clearInterval(probeTimer);
390
+ if (pollTimer) clearInterval(pollTimer);
391
+ adapter.dispose?.();
392
+ goAdapter?.dispose?.();
393
+ goService.dispose?.();
394
+ });
395
+ }
396
+ }
397
+
398
+ export {
399
+ TokenManager,
400
+ ModelCatalog,
401
+ OpenCodeOAuthAdapter,
402
+ OpenCodeGoAdapter,
403
+ createGoService,
404
+ PROVIDER,
405
+ PROVIDER_NAME,
406
+ GO_PROVIDER,
407
+ GO_PROVIDER_NAME
408
+ };
package/lib/picker.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * 模型勾選(選擇器顯示名單)。
3
+ *
4
+ * 使用者的需求:「不要把所有模型永遠全部塞進選擇器」。做法是讓設定頁的
5
+ * 模型表格每一列都有勾選框,勾了的才會出現在宿主的模型選擇器。
6
+ *
7
+ * 兩種模式:
8
+ *
9
+ * - `auto`(初始狀態):行為跟以前完全一樣——探測判定可用就顯示,
10
+ * 新模型由探測流程自行決定。此時勾選框只是狀態的展示,不參與決策。
11
+ *
12
+ * - `manual`:使用者動過勾選之後就進入這個模式。此時顯示名單完全由
13
+ * 勾選決定,之後新探測通過的模型不會再自動加入。
14
+ *
15
+ * 手動模式的第一次勾選,要把「當下 auto 模式會顯示的名單」整份快照進
16
+ * shown:這樣使用者看到的勾選狀態不會因為切模式而跳動,只是從今以後新
17
+ * 模型不再自動加入。快照由 catalog 負責(它才知道 auto 名單),儲存本身
18
+ * 不負責。
19
+ */
20
+
21
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
22
+ import { dirname, join } from 'node:path';
23
+ import { homedir } from 'node:os';
24
+
25
+ /** 預設存放位置;刻意與探測快取、備援設定分開,語意不同不該混在同一支檔案。 */
26
+ export function defaultPickerPath() {
27
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh');
28
+ return join(home, 'opencode-next.picker.json');
29
+ }
30
+
31
+ /** OpenCode Go 訂閱模型勾選名單存放位置。 */
32
+ export function defaultGoPickerPath() {
33
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh');
34
+ return join(home, 'opencode-next.go-picker.json');
35
+ }
36
+
37
+ /**
38
+ * 把請求帶來的 shown 清單整理成乾淨的陣列。
39
+ *
40
+ * 驗證在伺服器端做,不信任瀏覽器送來的內容:去空白、去重、丟掉非字串。
41
+ * 沒有設上限的上限(500):目錄裡的免費模型量級是數十個,500 足夠容納
42
+ * 任何合理的勾選,又足以檔掉惡意的巨型清單。
43
+ */
44
+ export function normalizeShownList(input) {
45
+ if (!Array.isArray(input)) return [];
46
+ const seen = new Set();
47
+ const out = [];
48
+ for (const raw of input) {
49
+ if (typeof raw !== 'string') continue;
50
+ const id = raw.trim();
51
+ if (id === '' || seen.has(id)) continue;
52
+ seen.add(id);
53
+ out.push(id);
54
+ if (out.length >= 500) break;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * 勾選名單的持久化。
61
+ *
62
+ * 為什麼不放進 DSH 的 plugin config:那份設定要在 DSH 的設定檔裡手改,
63
+ * 而使用者要的是一個畫面就能勾選的清單。所以狀態存在外掛自己的檔案,
64
+ * 由 API 寫入,介面只是它的前端。
65
+ *
66
+ * 壞掉的設定檔等同於「沒勾選過」,退回 auto 模式照常運作,不自動覆寫。
67
+ */
68
+ export class PickerStore {
69
+ #path;
70
+ #state = { mode: 'auto', shown: [] };
71
+ #loaded = false;
72
+
73
+ constructor({ path } = {}) {
74
+ this.#path = path === undefined ? defaultPickerPath() : path;
75
+ }
76
+
77
+ #load() {
78
+ if (this.#loaded) return;
79
+ this.#loaded = true;
80
+ if (!this.#path) return;
81
+ try {
82
+ if (!existsSync(this.#path)) return;
83
+ const text = readFileSync(this.#path, 'utf8').replace(/^\uFEFF/, '');
84
+ const parsed = JSON.parse(text);
85
+ this.#state = {
86
+ mode: parsed?.mode === 'manual' ? 'manual' : 'auto',
87
+ shown: normalizeShownList(parsed?.shown)
88
+ };
89
+ } catch {
90
+ this.#state = { mode: 'auto', shown: [] };
91
+ }
92
+ }
93
+
94
+ /** 目前設定。回傳副本,呼叫端改不動內部狀態。 */
95
+ get() {
96
+ this.#load();
97
+ return { mode: this.#state.mode, shown: [...this.#state.shown] };
98
+ }
99
+
100
+ /**
101
+ * 更新設定。
102
+ *
103
+ * 先寫暫存檔再 rename:直接覆寫時若行程中途結束,會留下一個半截的
104
+ * JSON,下次啟動就整份勾選消失。rename 在同一個磁碟區上是原子操作。
105
+ */
106
+ set({ mode, shown } = {}) {
107
+ this.#load();
108
+ const next = {
109
+ mode: mode === 'manual' ? 'manual' : 'auto',
110
+ shown: shown === undefined
111
+ ? [...this.#state.shown]
112
+ : normalizeShownList(shown)
113
+ };
114
+ this.#state = next;
115
+ if (!this.#path) return this.get();
116
+ try {
117
+ mkdirSync(dirname(this.#path), { recursive: true });
118
+ const temporary = `${this.#path}.tmp`;
119
+ writeFileSync(temporary, JSON.stringify({ version: 1, ...next }, null, 2), 'utf8');
120
+ renameSync(temporary, this.#path);
121
+ } catch {
122
+ // 寫不進去也要讓這次設定在記憶體中生效,至少本次執行期間是對的。
123
+ }
124
+ return this.get();
125
+ }
126
+ }