dsh-plugin-opencode2api 0.0.0-stage → 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/lib/index.js ADDED
@@ -0,0 +1,915 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { createHash, randomBytes } from 'node:crypto'
3
+ import fs from 'node:fs'
4
+ import fsp from 'node:fs/promises'
5
+ import { createConnection } from 'node:net'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+
9
+ export const name = 'dsh-plugin-opencode2api'
10
+
11
+ const VERSION = process.env.OPENCODE2API_VERSION || '1.5.1'
12
+ const REPO = 'jasonxu114514/opencode2api'
13
+ const API_PORT = Number(process.env.OPENCODE2API_PORT || 8080)
14
+ const WEB_PORT = API_PORT + 1
15
+ const DOWNLOAD_TIMEOUT_MS = 120_000
16
+ const MIRRORS = ['', 'https://gh-proxy.com/', 'https://ghproxy.net/', 'https://ghfast.top/']
17
+
18
+ const HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
19
+ const IS_CHECK = /dsh-go-check-/.test(HOME)
20
+ const DATA = path.join(HOME, 'dsh-go', 'opencode2api')
21
+ const IS_WIN = process.platform === 'win32'
22
+ const BIN = path.join(DATA, IS_WIN ? 'opencode2api.exe' : 'opencode2api')
23
+ const CFG = path.join(DATA, 'config.json')
24
+ const PID = path.join(DATA, 'opencode2api.pid')
25
+ const LOG = path.join(DATA, 'opencode2api.log')
26
+ const PASS = path.join(DATA, 'webui-password.txt')
27
+ const AUTO_STATE = path.join(DATA, 'auto-provider.json')
28
+ const PROVIDER_ID = 'opencode2api'
29
+ const CRED_REF = 'OPENCODE2API_API_KEY'
30
+
31
+ let desired = true
32
+ let busy = false
33
+ let installing = null
34
+ let lastError = ''
35
+ let lastAutoError = ''
36
+ let runtime = null
37
+ let autoInfo = { status: '未配置', tone: 'warn' }
38
+
39
+ function sleep(ms) {
40
+ return new Promise((resolve) => setTimeout(resolve, ms))
41
+ }
42
+
43
+ function human(error) {
44
+ const message = String(error?.message ?? error ?? '')
45
+ if (message.includes('ENOEXEC') || message.includes('ENOENT')) return '程序无法在当前平台运行,请手动安装或换平台'
46
+ if (message.includes('EACCES')) return '程序没有执行权限'
47
+ if (message.includes('sha256')) return '下载校验失败,请重试'
48
+ if (/HTTP \d+/.test(message) || message.includes('fetch')) return '下载失败,请检查网络后重试'
49
+ return message.slice(0, 60) || '操作失败'
50
+ }
51
+
52
+ function target() {
53
+ const arch = process.arch === 'x64' ? 'amd64' : process.arch === 'arm64' ? 'arm64' : null
54
+ if (!arch) return null
55
+ if (process.platform === 'win32') return { os: 'windows', arch, ext: 'zip', bin: 'opencode2api.exe' }
56
+ if (process.platform === 'darwin') return { os: 'darwin', arch, ext: 'tar.gz', bin: 'opencode2api' }
57
+ if (process.platform === 'linux') return { os: 'linux', arch, ext: 'tar.gz', bin: 'opencode2api' }
58
+ return null
59
+ }
60
+
61
+ function randomKey(length) {
62
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
63
+ const bytes = randomBytes(length)
64
+ let out = ''
65
+ for (let i = 0; i < length; i++) out += chars[bytes[i] % chars.length]
66
+ return out
67
+ }
68
+
69
+ function defaultConfig() {
70
+ return {
71
+ listen: `0.0.0.0:${API_PORT}`,
72
+ server_keys: [randomKey(32)],
73
+ zen_keys: [],
74
+ go_keys: [],
75
+ anonymous: true,
76
+ warp: { enabled: false, pool_size: 2, stack: 'ipv6', source_ipv6: '' },
77
+ proxies: ['direct'],
78
+ proxyfile: '',
79
+ upstream: {
80
+ zen: 'https://opencode.ai/zen',
81
+ go: 'https://opencode.ai/zen/go',
82
+ anonymous: 'https://opencode.ai/inference',
83
+ prompt_environment: {},
84
+ },
85
+ retry: { max_attempts: 3, timeout_seconds: 300 },
86
+ models: { refresh_seconds: 300, protocols: {}, free_only: false, active_probes: false },
87
+ performance: {
88
+ max_idle_conns: 2048,
89
+ max_idle_conns_per_host: 256,
90
+ max_conns_per_host: 0,
91
+ idle_conn_timeout_seconds: 120,
92
+ connect_timeout_seconds: 5,
93
+ failure_cooldown_seconds: 15,
94
+ attempt_timeout_seconds: 0,
95
+ first_event_timeout_seconds: 0,
96
+ max_anonymous_exits: 8,
97
+ free_tier_block_seconds: 900,
98
+ },
99
+ logging: { level: 'info', ring_size: 2000, dump_request_bodies: false },
100
+ webui: {
101
+ enabled: true,
102
+ listen: `0.0.0.0:${WEB_PORT}`,
103
+ username: 'admin',
104
+ password: randomKey(14),
105
+ session_ttl_minutes: 720,
106
+ },
107
+ prefer: 'go',
108
+ reasoning: { effort: 'high', effort_by_model: {} },
109
+ rotation: {
110
+ sota: {
111
+ alias: 'sota',
112
+ order: ['deepseek-v4.1-flash', 'glm-5.3', 'grok-4.6', 'kimi-k3', 'qwen3.8-max'],
113
+ },
114
+ sweet: { alias: 'sweet', order: [] },
115
+ first_output_seconds: 30,
116
+ },
117
+ }
118
+ }
119
+
120
+ function readConfig() {
121
+ try {
122
+ return JSON.parse(fs.readFileSync(CFG, 'utf8'))
123
+ } catch {
124
+ return defaultConfig()
125
+ }
126
+ }
127
+
128
+ function ensureConfig() {
129
+ if (!fs.existsSync(CFG)) {
130
+ const cfg = defaultConfig()
131
+ fs.mkdirSync(DATA, { recursive: true })
132
+ fs.writeFileSync(PASS, `${cfg.webui.password}\n`, { mode: 0o600 })
133
+ fs.writeFileSync(CFG, JSON.stringify(cfg, null, 2))
134
+ }
135
+ return readConfig()
136
+ }
137
+
138
+ function readPassword() {
139
+ try {
140
+ return fs.readFileSync(PASS, 'utf8').trim()
141
+ } catch {
142
+ return ''
143
+ }
144
+ }
145
+
146
+ async function fetchModels(key) {
147
+ try {
148
+ const res = await fetch(`http://127.0.0.1:${API_PORT}/v1/models`, {
149
+ headers: { authorization: `Bearer ${key}` },
150
+ signal: AbortSignal.timeout(8000),
151
+ })
152
+ if (!res.ok) return []
153
+ const body = await res.json()
154
+ const list = Array.isArray(body?.data) ? body.data : Array.isArray(body?.models) ? body.models : []
155
+ return list
156
+ .map((item) => (typeof item === 'string' ? { id: item } : item))
157
+ .filter((item) => item && typeof item.id === 'string' && item.id.length > 0)
158
+ } catch {
159
+ return []
160
+ }
161
+ }
162
+
163
+ function modelEntry(model) {
164
+ const entry = { id: model.id }
165
+ const window = model.context_length ?? model.context_window ?? model.max_input ?? model.metadata?.context_window
166
+ if (Number.isFinite(window) && window > 0) entry.contextWindow = window
167
+ const maxOut = model.max_output ?? model.metadata?.max_output
168
+ if (Number.isFinite(maxOut) && maxOut > 0) entry.maxTokens = maxOut
169
+ const modalities = model.metadata?.input_modalities ?? model.input_modalities
170
+ if (Array.isArray(modalities)) {
171
+ const input = modalities.filter((item) => item === 'text' || item === 'image')
172
+ if (input.length > 0) entry.input = input
173
+ }
174
+ const efforts = model.reasoning_efforts ?? model.compat?.supportedReasoningEfforts
175
+ if (model.reasoning === true && Array.isArray(efforts) && efforts.length > 0) {
176
+ const levels = { off: null }
177
+ for (const level of efforts) {
178
+ if (['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].includes(level)) levels[level] = level
179
+ }
180
+ if (Object.keys(levels).length > 1) entry.reasoningEfforts = levels
181
+ }
182
+ return entry
183
+ }
184
+
185
+ function autoHash(key, models) {
186
+ return createHash('sha256')
187
+ .update(JSON.stringify({ key, ids: models.map((model) => model.id) }))
188
+ .digest('hex')
189
+ .slice(0, 16)
190
+ }
191
+
192
+ function readAutoState() {
193
+ try {
194
+ return JSON.parse(fs.readFileSync(AUTO_STATE, 'utf8'))
195
+ } catch {
196
+ return null
197
+ }
198
+ }
199
+
200
+ async function autoConfigure(force = false) {
201
+ if (!runtime || IS_CHECK) return
202
+ const settings = runtime.get('settings')
203
+ const credentials = runtime.get('credentials')
204
+ if (!settings || !credentials) {
205
+ autoInfo = { status: '等待引擎', tone: 'info' }
206
+ return
207
+ }
208
+ const cfg = readConfig()
209
+ const key = cfg.server_keys?.[0]
210
+ if (!key) {
211
+ autoInfo = { status: '缺少 Key', tone: 'warn' }
212
+ return
213
+ }
214
+ const models = await fetchModels(key)
215
+ if (!models.length) {
216
+ lastAutoError = '未取到模型列表'
217
+ autoInfo = { status: '取模型失败', tone: 'warn' }
218
+ return
219
+ }
220
+ const hash = autoHash(key, models)
221
+ const state = readAutoState()
222
+ if (!force && state && state.hash === hash && state.version === VERSION) {
223
+ autoInfo = { status: '已自动配置', tone: 'good' }
224
+ return
225
+ }
226
+ let descriptor
227
+ try {
228
+ descriptor = settings.describe().find((row) => row.ns === 'llm-pi-ai')
229
+ } catch {}
230
+ if (!descriptor) {
231
+ lastAutoError = '未找到 llm-pi-ai 配置'
232
+ autoInfo = { status: '不支持自动配置', tone: 'warn' }
233
+ return
234
+ }
235
+ const entry = {
236
+ displayName: '本地免费 API',
237
+ api: 'openai-completions',
238
+ baseURL: `http://127.0.0.1:${API_PORT}/v1`,
239
+ apiKeyEnv: CRED_REF,
240
+ models: models.map(modelEntry),
241
+ }
242
+ try {
243
+ await credentials.set(CRED_REF, key)
244
+ } catch (error) {
245
+ lastAutoError = human(error)
246
+ autoInfo = { status: '写入 Key 失败', tone: 'bad' }
247
+ return
248
+ }
249
+ let failure = null
250
+ for (let attempt = 0; attempt < 2; attempt++) {
251
+ try {
252
+ const row = settings.describe().find((item) => item.ns === 'llm-pi-ai')
253
+ if (!row) throw new Error('llm-pi-ai 不存在')
254
+ await settings.update('llm-pi-ai', { providers: { [PROVIDER_ID]: entry } }, row.revision)
255
+ failure = null
256
+ break
257
+ } catch (error) {
258
+ failure = error
259
+ }
260
+ }
261
+ if (failure) {
262
+ lastAutoError = human(failure)
263
+ autoInfo = { status: '配置失败', tone: 'bad' }
264
+ return
265
+ }
266
+ try {
267
+ fs.writeFileSync(AUTO_STATE, JSON.stringify({ version: VERSION, hash }))
268
+ } catch {}
269
+ lastAutoError = ''
270
+ autoInfo = { status: '已自动配置', tone: 'good' }
271
+ }
272
+
273
+ function tailLog(lines = 40) {
274
+ try {
275
+ const stat = fs.statSync(LOG)
276
+ const start = Math.max(0, stat.size - 32 * 1024)
277
+ const fd = fs.openSync(LOG, 'r')
278
+ const buffer = Buffer.alloc(stat.size - start)
279
+ try {
280
+ fs.readSync(fd, buffer, 0, buffer.length, start)
281
+ } finally {
282
+ fs.closeSync(fd)
283
+ }
284
+ return buffer.toString('utf8').split('\n').slice(-lines).join('\n')
285
+ } catch {
286
+ return ''
287
+ }
288
+ }
289
+
290
+ function readJson(req) {
291
+ return new Promise((resolve, reject) => {
292
+ let body = ''
293
+ req.on('data', (chunk) => {
294
+ body += chunk
295
+ if (body.length > 1024 * 1024) {
296
+ req.destroy()
297
+ reject(new Error('请求过大'))
298
+ }
299
+ })
300
+ req.on('end', () => {
301
+ try {
302
+ resolve(body ? JSON.parse(body) : {})
303
+ } catch (error) {
304
+ reject(error)
305
+ }
306
+ })
307
+ req.on('error', reject)
308
+ })
309
+ }
310
+
311
+ async function buildState() {
312
+ const snap = await snapshot()
313
+ const cfg = fs.existsSync(CFG) ? readConfig() : {}
314
+ return {
315
+ ...snap,
316
+ running: Boolean(await health()),
317
+ installed: fs.existsSync(BIN),
318
+ key: cfg.server_keys?.[0] || '',
319
+ password: readPassword(),
320
+ webPasswordPath: PASS,
321
+ apiPort: API_PORT,
322
+ webPort: WEB_PORT,
323
+ listen: cfg.listen || '',
324
+ log: tailLog(40),
325
+ autoError: lastAutoError,
326
+ version: VERSION,
327
+ time: Date.now(),
328
+ }
329
+ }
330
+
331
+ async function runAction(action) {
332
+ switch (action) {
333
+ case 'start':
334
+ desired = true
335
+ await boot()
336
+ return '已启动'
337
+ case 'stop':
338
+ await stop()
339
+ return '已停止'
340
+ case 'restart':
341
+ await restart()
342
+ void autoConfigure().catch(() => {})
343
+ return '已重启'
344
+ case 'listenLocal':
345
+ case 'listenLan': {
346
+ setListen(action === 'listenLocal' ? '127.0.0.1' : '0.0.0.0')
347
+ desired = true
348
+ await killProcess()
349
+ const ok = await start()
350
+ return ok ? (action === 'listenLocal' ? '已仅本机监听' : '已开局域网') : '切换失败'
351
+ }
352
+ case 'autoConfig':
353
+ await autoConfigure(true)
354
+ return autoInfo.status
355
+ case 'reinstall':
356
+ void (async () => {
357
+ busy = true
358
+ try {
359
+ desired = true
360
+ await killProcess()
361
+ await ensureInstalled(true)
362
+ await start()
363
+ lastError = ''
364
+ void autoConfigure().catch(() => {})
365
+ } catch (error) {
366
+ lastError = human(error)
367
+ } finally {
368
+ busy = false
369
+ }
370
+ })()
371
+ return '后台重装中…'
372
+ default:
373
+ throw new Error('未知操作')
374
+ }
375
+ }
376
+
377
+ async function api(req, res) {
378
+ const url = new URL(req.url ?? '/', 'http://localhost')
379
+ const route = url.pathname.replace(/^\/api\/opencode2api/, '').replace(/\/+$/, '') || '/'
380
+ const method = String(req.method ?? 'GET').toUpperCase()
381
+ const send = (status, payload) => {
382
+ res.writeHead(status, {
383
+ 'content-type': 'application/json; charset=utf-8',
384
+ 'cache-control': 'no-store',
385
+ })
386
+ res.end(JSON.stringify(payload))
387
+ }
388
+ const address = req.socket?.remoteAddress ?? ''
389
+ const local = address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
390
+ const origin = String(req.headers.origin || '')
391
+ if (origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/i.test(origin)) {
392
+ return send(403, { error: 'forbidden' })
393
+ }
394
+ try {
395
+ if (method === 'GET' && route === '/state') {
396
+ const state = await buildState()
397
+ if (!local) {
398
+ state.key = ''
399
+ state.password = ''
400
+ state.keyHidden = true
401
+ }
402
+ return send(200, state)
403
+ }
404
+ if (method === 'GET' && route === '/log') {
405
+ return send(200, { log: tailLog(Number(url.searchParams.get('lines')) || 120) })
406
+ }
407
+ if (method === 'POST' && route === '/action') {
408
+ if (!local) return send(403, { error: '仅本机可操作' })
409
+ const body = await readJson(req)
410
+ const toast = await runAction(String(body.action || ''))
411
+ return send(200, { ok: true, toast, state: await buildState() })
412
+ }
413
+ return send(404, { error: 'not found' })
414
+ } catch (error) {
415
+ return send(500, { error: human(error) })
416
+ }
417
+ }
418
+
419
+ function setListen(host) {
420
+ const cfg = readConfig()
421
+ cfg.listen = `${host}:${API_PORT}`
422
+ cfg.webui = { ...(cfg.webui || {}), listen: `${host}:${WEB_PORT}` }
423
+ fs.writeFileSync(CFG, JSON.stringify(cfg, null, 2))
424
+ }
425
+
426
+ function lanAddress() {
427
+ try {
428
+ for (const list of Object.values(os.networkInterfaces())) {
429
+ for (const item of list || []) {
430
+ if (item && item.family === 'IPv4' && !item.internal) return item.address
431
+ }
432
+ }
433
+ } catch {}
434
+ return ''
435
+ }
436
+
437
+ function findFile(dir, filename) {
438
+ let entries
439
+ try {
440
+ entries = fs.readdirSync(dir, { withFileTypes: true })
441
+ } catch {
442
+ return null
443
+ }
444
+ for (const entry of entries) {
445
+ const full = path.join(dir, entry.name)
446
+ if (entry.isDirectory()) {
447
+ const nested = findFile(full, filename)
448
+ if (nested) return nested
449
+ } else if (entry.name === filename) {
450
+ return full
451
+ }
452
+ }
453
+ return null
454
+ }
455
+
456
+ async function runCommand(command, args) {
457
+ return new Promise((resolve, reject) => {
458
+ const child = spawn(command, args, { stdio: 'ignore' })
459
+ child.once('error', reject)
460
+ child.once('close', (code) => (code === 0 ? resolve() : reject(new Error(`${command} exit ${code}`))))
461
+ })
462
+ }
463
+
464
+ async function fetchBuffer(url) {
465
+ const controller = new AbortController()
466
+ const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)
467
+ try {
468
+ const res = await fetch(url, { signal: controller.signal, redirect: 'follow' })
469
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
470
+ return Buffer.from(await res.arrayBuffer())
471
+ } finally {
472
+ clearTimeout(timer)
473
+ }
474
+ }
475
+
476
+ async function download(relative, destination) {
477
+ let lastFailure = null
478
+ for (const prefix of MIRRORS) {
479
+ const url = `${prefix}https://github.com/${REPO}/releases/download/v${VERSION}/${relative}`
480
+ try {
481
+ const body = await fetchBuffer(url)
482
+ try {
483
+ const shaBody = await fetchBuffer(`${url}.sha256`)
484
+ const expected = shaBody.toString('utf8').trim().split(/\s+/)[0].toLowerCase()
485
+ const actual = createHash('sha256').update(body).digest('hex')
486
+ if (expected && expected !== actual) throw new Error('sha256 mismatch')
487
+ } catch (error) {
488
+ if (String(error?.message).includes('sha256')) throw error
489
+ }
490
+ await fsp.writeFile(destination, body)
491
+ return
492
+ } catch (error) {
493
+ lastFailure = error
494
+ }
495
+ }
496
+ throw lastFailure || new Error('download failed')
497
+ }
498
+
499
+ async function extract(archive, destination) {
500
+ try {
501
+ await runCommand('tar', ['-xf', archive, '-C', destination])
502
+ } catch (error) {
503
+ if (archive.endsWith('.zip') && IS_WIN) {
504
+ await runCommand('powershell', [
505
+ '-NoProfile',
506
+ '-Command',
507
+ `Expand-Archive -LiteralPath "${archive}" -DestinationPath "${destination}" -Force`,
508
+ ])
509
+ } else {
510
+ throw error
511
+ }
512
+ }
513
+ }
514
+
515
+ async function ensureInstalled(force = false) {
516
+ if (installing) return installing
517
+ installing = (async () => {
518
+ fs.mkdirSync(DATA, { recursive: true })
519
+ if (!force && fs.existsSync(BIN)) return
520
+ const plat = target()
521
+ if (!plat) throw new Error('当前平台暂不支持')
522
+ const relative = `opencode2api_v${VERSION}_${plat.os}_${plat.arch}.${plat.ext}`
523
+ const temp = path.join(DATA, `.install-${Date.now()}`)
524
+ fs.mkdirSync(temp, { recursive: true })
525
+ try {
526
+ const archive = path.join(temp, relative)
527
+ await download(relative, archive)
528
+ await extract(archive, temp)
529
+ const found = findFile(temp, plat.bin)
530
+ if (!found) throw new Error('压缩包里没有找到程序')
531
+ if (fs.existsSync(BIN)) fs.unlinkSync(BIN)
532
+ await fsp.copyFile(found, BIN)
533
+ if (!IS_WIN) fs.chmodSync(BIN, 0o755)
534
+ lastError = ''
535
+ } finally {
536
+ await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
537
+ }
538
+ })()
539
+ try {
540
+ return await installing
541
+ } finally {
542
+ installing = null
543
+ }
544
+ }
545
+
546
+ function portOpen(port = API_PORT, timeout = 800) {
547
+ return new Promise((resolve) => {
548
+ const socket = createConnection({ host: '127.0.0.1', port })
549
+ const finish = (value) => {
550
+ socket.destroy()
551
+ resolve(value)
552
+ }
553
+ socket.setTimeout(timeout)
554
+ socket.once('connect', () => finish(true))
555
+ socket.once('timeout', () => finish(false))
556
+ socket.once('error', () => finish(false))
557
+ })
558
+ }
559
+
560
+ function readPid() {
561
+ try {
562
+ return Number(fs.readFileSync(PID, 'utf8').trim()) || null
563
+ } catch {
564
+ return null
565
+ }
566
+ }
567
+
568
+ function alive(pid) {
569
+ if (!pid) return false
570
+ try {
571
+ process.kill(pid, 0)
572
+ return true
573
+ } catch {
574
+ return false
575
+ }
576
+ }
577
+
578
+ async function health() {
579
+ try {
580
+ const res = await fetch(`http://127.0.0.1:${API_PORT}/healthz`, { signal: AbortSignal.timeout(1500) })
581
+ if (!res.ok) return null
582
+ const body = await res.json()
583
+ return body && (body.status === 'ok' || body.ready === true || body.models) ? body : null
584
+ } catch {
585
+ return null
586
+ }
587
+ }
588
+
589
+ async function start() {
590
+ if (!fs.existsSync(BIN)) await ensureInstalled()
591
+ ensureConfig()
592
+ if (await portOpen()) return true
593
+ const fd = fs.openSync(LOG, 'a')
594
+ let child
595
+ try {
596
+ child = spawn(BIN, ['-config', CFG], { cwd: DATA, detached: true, stdio: ['ignore', fd, fd] })
597
+ } finally {
598
+ fs.closeSync(fd)
599
+ }
600
+ child.unref()
601
+ try {
602
+ fs.writeFileSync(PID, String(child.pid))
603
+ } catch {}
604
+ for (let i = 0; i < 40; i++) {
605
+ await sleep(500)
606
+ if (await portOpen()) return true
607
+ if (!alive(child.pid) && i > 3) break
608
+ }
609
+ return portOpen()
610
+ }
611
+
612
+ async function killProcess() {
613
+ const pid = readPid()
614
+ if (pid && alive(pid)) {
615
+ try {
616
+ process.kill(pid, 'SIGTERM')
617
+ } catch {}
618
+ for (let i = 0; i < 24 && alive(pid); i++) await sleep(250)
619
+ if (alive(pid)) {
620
+ try {
621
+ process.kill(pid, 'SIGKILL')
622
+ } catch {}
623
+ }
624
+ }
625
+ try {
626
+ fs.unlinkSync(PID)
627
+ } catch {}
628
+ for (let i = 0; i < 12; i++) {
629
+ if (!(await portOpen())) return true
630
+ await sleep(250)
631
+ }
632
+ return !(await portOpen())
633
+ }
634
+
635
+ async function stop() {
636
+ desired = false
637
+ return killProcess()
638
+ }
639
+
640
+ async function restart() {
641
+ desired = true
642
+ await killProcess()
643
+ return start()
644
+ }
645
+
646
+ async function boot() {
647
+ if (!desired) return
648
+ try {
649
+ await ensureInstalled()
650
+ await start()
651
+ lastError = ''
652
+ void autoConfigure().catch(() => {})
653
+ } catch (error) {
654
+ lastError = human(error)
655
+ }
656
+ }
657
+
658
+ async function snapshot() {
659
+ const body = await health()
660
+ const installed = fs.existsSync(BIN)
661
+ const running = Boolean(body)
662
+ let state = '未安装'
663
+ let tone = 'bad'
664
+ if (IS_CHECK) {
665
+ state = '未安装'
666
+ tone = 'muted'
667
+ } else if (busy) {
668
+ state = '处理中…'
669
+ tone = 'warn'
670
+ } else if (running) {
671
+ state = '运行中'
672
+ tone = 'good'
673
+ } else if (installed) {
674
+ state = '已停止'
675
+ tone = 'warn'
676
+ }
677
+ const models = body?.models?.total ?? body?.models ?? '—'
678
+ const plat = target()
679
+ const cfg = readConfig()
680
+ const lan = lanAddress()
681
+ return {
682
+ state,
683
+ tone,
684
+ baseUrl: `http://127.0.0.1:${API_PORT}/v1`,
685
+ webUrl: `http://127.0.0.1:${WEB_PORT}`,
686
+ lanUrl: lan ? `http://${lan}:${API_PORT}/v1` : '—',
687
+ listenMode: String(cfg.listen || '').startsWith('0.0.0.0') ? '局域网' : '仅本机',
688
+ models: String(models),
689
+ platform: plat ? `${plat.os}/${plat.arch}` : '不支持',
690
+ provider: autoInfo.status,
691
+ providerTone: autoInfo.tone,
692
+ note: lastAutoError || lastError || '后台可改密码与监听地址;重装会重新下载程序',
693
+ noteTone: lastAutoError || lastError ? 'warn' : 'info',
694
+ }
695
+ }
696
+
697
+ function pendingWork(label, work) {
698
+ return {
699
+ pending: { label, timeoutMs: 50000 },
700
+ result: async () => {
701
+ busy = true
702
+ try {
703
+ return await work()
704
+ } catch (error) {
705
+ lastError = human(error)
706
+ return { toast: '操作失败' }
707
+ } finally {
708
+ busy = false
709
+ }
710
+ },
711
+ }
712
+ }
713
+
714
+ function registerUi(ctx) {
715
+ ctx.dshGo.panel('gateway', {
716
+ view: () => ({
717
+ type: 'stack',
718
+ title: '本地免费 API',
719
+ children: [
720
+ { type: 'metric', label: '状态', value: { $: 'data.state' }, tone: { $: 'data.tone' } },
721
+ {
722
+ type: 'keyValue',
723
+ items: [
724
+ { label: 'API', value: { $: 'data.baseUrl' } },
725
+ { label: '后台', value: { $: 'data.webUrl' } },
726
+ { label: '监听', value: { $: 'data.listenMode' } },
727
+ { label: '局域网', value: { $: 'data.lanUrl' } },
728
+ { label: '模型', value: { $: 'data.models' } },
729
+ { label: '模型商', value: { $: 'data.provider' }, tone: { $: 'data.providerTone' } },
730
+ { label: '平台', value: { $: 'data.platform' } },
731
+ ],
732
+ },
733
+ {
734
+ type: 'actions',
735
+ items: [
736
+ { label: '启动', action: 'start', style: 'primary' },
737
+ { label: '停止', action: 'stop' },
738
+ { label: '重启', action: 'restart' },
739
+ ],
740
+ },
741
+ {
742
+ type: 'actions',
743
+ items: [
744
+ { label: '仅本机', action: 'listenLocal' },
745
+ { label: '开局域网', action: 'listenLan' },
746
+ ],
747
+ },
748
+ {
749
+ type: 'actions',
750
+ items: [
751
+ { label: '复制接入', action: 'copyInfo' },
752
+ { label: '复制后台', action: 'copyWeb' },
753
+ { label: '自动配置', action: 'autoConfig' },
754
+ { label: '重装', action: 'reinstall' },
755
+ ],
756
+ },
757
+ { type: 'callout', text: { $: 'data.note' }, tone: { $: 'data.noteTone' } },
758
+ ],
759
+ }),
760
+ data: (scope, emit) => {
761
+ if (IS_CHECK) {
762
+ emit({
763
+ state: '未安装',
764
+ tone: 'info',
765
+ baseUrl: `http://127.0.0.1:${API_PORT}/v1`,
766
+ webUrl: `http://127.0.0.1:${WEB_PORT}`,
767
+ lanUrl: '—',
768
+ listenMode: '局域网',
769
+ models: '—',
770
+ platform: target() ? `${target().os}/${target().arch}` : '不支持',
771
+ provider: '检查模式',
772
+ providerTone: 'info',
773
+ note: '检查模式',
774
+ noteTone: 'info',
775
+ })
776
+ return () => {}
777
+ }
778
+ let closed = false
779
+ const tick = async () => {
780
+ try {
781
+ const data = await snapshot()
782
+ if (!closed) emit(data)
783
+ } catch {}
784
+ }
785
+ void tick()
786
+ const timer = setInterval(tick, 5000)
787
+ return () => {
788
+ closed = true
789
+ clearInterval(timer)
790
+ }
791
+ },
792
+ actions: {
793
+ start: () =>
794
+ pendingWork('正在启动', async () => {
795
+ desired = true
796
+ const ok = await start()
797
+ return { toast: ok ? '已启动' : '启动失败,看日志' }
798
+ }),
799
+ stop: () =>
800
+ pendingWork('正在停止', async () => {
801
+ const ok = await stop()
802
+ return { toast: ok ? '已停止' : '停止失败' }
803
+ }),
804
+ restart: () =>
805
+ pendingWork('正在重启', async () => {
806
+ const ok = await restart()
807
+ return { toast: ok ? '已重启' : '重启失败' }
808
+ }),
809
+ listenLocal: () =>
810
+ pendingWork('正在切换', async () => {
811
+ setListen('127.0.0.1')
812
+ desired = true
813
+ await killProcess()
814
+ const ok = await start()
815
+ return { toast: ok ? '已仅本机监听' : '切换失败' }
816
+ }),
817
+ listenLan: () =>
818
+ pendingWork('正在切换', async () => {
819
+ setListen('0.0.0.0')
820
+ desired = true
821
+ await killProcess()
822
+ const ok = await start()
823
+ return { toast: ok ? '已开局域网' : '切换失败' }
824
+ }),
825
+ copyInfo: () => {
826
+ const cfg = readConfig()
827
+ const key = cfg.server_keys?.[0] || ''
828
+ const lan = lanAddress()
829
+ const lanLine = lan ? `\n局域网:http://${lan}:${API_PORT}/v1` : ''
830
+ return {
831
+ copy: `本机:http://127.0.0.1:${API_PORT}/v1${lanLine}\nAPI Key:${key}\n推荐模型:deepseek-v4.1-flash-free`,
832
+ toast: '接入信息已复制',
833
+ }
834
+ },
835
+ copyWeb: () => {
836
+ const cfg = readConfig()
837
+ const password = readPassword() || '(已在后台改过,请用新密码)'
838
+ return {
839
+ copy: `后台:http://127.0.0.1:${WEB_PORT}\n账号:${cfg.webui?.username || 'admin'}\n密码:${password}`,
840
+ toast: '后台信息已复制',
841
+ }
842
+ },
843
+ reinstall: () => {
844
+ void (async () => {
845
+ busy = true
846
+ try {
847
+ desired = true
848
+ await killProcess()
849
+ await ensureInstalled(true)
850
+ await start()
851
+ lastError = ''
852
+ } catch (error) {
853
+ lastError = human(error)
854
+ } finally {
855
+ busy = false
856
+ }
857
+ })()
858
+ return { toast: '后台重装中…' }
859
+ },
860
+ autoConfig: () =>
861
+ pendingWork('正在配置', async () => {
862
+ await autoConfigure(true)
863
+ return { toast: autoInfo.tone === 'good' ? '模型商已配置' : autoInfo.status }
864
+ }),
865
+ },
866
+ })
867
+
868
+ ctx.dshGo.strip('status', (scope, emit) => {
869
+ if (IS_CHECK) {
870
+ emit({ text: '本地 API', icon: 'server' })
871
+ return () => {}
872
+ }
873
+ let closed = false
874
+ const tick = async () => {
875
+ try {
876
+ const body = await health()
877
+ const text = body ? '本地API 运行中' : fs.existsSync(BIN) ? '本地API 已停止' : '本地API 未安装'
878
+ if (!closed) emit({ text, icon: 'server', tone: body ? 'good' : 'warn' })
879
+ } catch {}
880
+ }
881
+ void tick()
882
+ const timer = setInterval(tick, 8000)
883
+ return () => {
884
+ closed = true
885
+ clearInterval(timer)
886
+ }
887
+ })
888
+ }
889
+
890
+ export function apply(ctx) {
891
+ runtime = ctx
892
+ if (!IS_CHECK) {
893
+ ctx.effect(() => {
894
+ const bootTimer = setTimeout(() => {
895
+ void boot()
896
+ }, 1500)
897
+ const watchdog = setInterval(() => {
898
+ if (desired && !busy) void boot()
899
+ }, 30000)
900
+ return () => {
901
+ clearTimeout(bootTimer)
902
+ clearInterval(watchdog)
903
+ }
904
+ }, 'opencode2api autostart')
905
+ }
906
+ ctx.inject(['dshGo'], (ctx) => {
907
+ registerUi(ctx)
908
+ })
909
+ ctx.inject(['webServer'], (scoped) => {
910
+ scoped.effect(
911
+ () => scoped.webServer.register({ kind: 'prefix', path: '/api/opencode2api', handler: api }),
912
+ 'opencode2api: web api',
913
+ )
914
+ })
915
+ }