dsh-plugin-opencode2api 1.2.1 → 1.3.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/README.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  一键把 [opencode2api](https://github.com/jasonxu114514/opencode2api) 装进 DSH:自动下载对应平台的程序、生成配置、启动并常驻,并自动把「本地免费 API」注册成 DSH 的模型商(模型列表从网关动态获取)。装好后本机就有一个专属的、兼容 OpenAI 的免费 API;DSH 关闭再打开会自动重启。
4
4
 
5
+ ## 1.2.2 更新
6
+
7
+ - 手机原生面板与桌面设置页对齐:移除「复制接入」「复制后台」,改为「复制地址」「复制 Key」;保留「打开后台」「查看日志」「项目主页」。
8
+ - 「打开后台」在 dshGo 原生面板受平台限制:`link` 只接受 https,本地后台是 `http://127.0.0.1:8081`,因此会自动复制地址并提示粘贴到浏览器;桌面 Web UI 仍可直接打开。
9
+ - 停止/重启在 Windows 之外补充 `ss` / `netstat` 兜底,Linux/macOS/Android 按端口找进程更可靠。
10
+
5
11
  ## 1.2.1 更新
6
12
 
7
13
  - 修复停止/重启:按端口反查并终止进程(Windows `netstat` + `taskkill`,macOS/Linux/Android 用 `lsof`/`fuser`/`/proc`),不再依赖可能丢失的 pid 文件;启动改为健康检查通过才算成功,并自动接管已有健康实例。
@@ -32,13 +38,27 @@ dsh plugin --profile web add dsh-plugin-opencode2api
32
38
  | 方式 | 命令 | 前提 |
33
39
  |---|---|---|
34
40
  | GitHub | `dsh plugin --profile web add github:king-andthe-nice/dsh-plugin-opencode2api` | 能访问 GitHub |
35
- | 本地包 | `dsh plugin --profile web add ./dsh-plugin-opencode2api-1.2.1.tgz` | 有 17 KB 的 tgz |
36
- | 局域网 | `dsh plugin --profile web add http://<手机IP>:8000/dsh-plugin-opencode2api-1.2.1.tgz` | 手机先 `python3 -m http.server 8000` |
41
+ | 本地包 | `dsh plugin --profile web add ./dsh-plugin-opencode2api-1.2.2.tgz` | 有 17 KB 的 tgz |
42
+ | 局域网 | `dsh plugin --profile web add http://<手机IP>:8000/dsh-plugin-opencode2api-1.2.2.tgz` | 手机先 `python3 -m http.server 8000` |
37
43
 
38
44
  装好后引擎会自动下载程序(约 5 MB)、生成配置并在 `0.0.0.0:8080` 启动(本机和局域网都能连)。首次下载失败会每 30 秒重试。
39
45
 
40
46
  Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1:3080`)→ **设置 → 本地免费 API**,就能看到状态和操作按钮;手机 App 则在「本地API」胶囊/面板里。
41
47
 
48
+ ## 接入云端设备池(1.3.1)
49
+
50
+ 如果你有一个自己的中转站(例如本项目作者的 oc-proxy),可以把这台设备变成它的一个后端,让中转站把请求分过来。
51
+
52
+ 1. 中转站后台 → **管理 → 设备** → **生成接入码**(15 分钟有效,只能用一次);
53
+ 2. 在这台设备上打开插件:
54
+ - 手机:输入框上方「本地API」→ 面板里填前端地址和接入码 → 加入设备池;
55
+ - 桌面:设置 → 本地免费 API → **云端设备池** → 填地址和接入码 → 加入设备池;
56
+ 3. 插件会自动创建 Cloudflare 隧道、下载并启动 cloudflared、每 60 秒上报心跳。
57
+
58
+ 管理端看到设备「在线」后就会把请求分配过来。心跳超过 3 分钟没到会自动标记离线,重新上线自动恢复;长期不用时在管理端点「删除」会同时清理隧道和 DNS。
59
+
60
+ 退出:面板里点「退出设备池」,会同时从中转站删除这台设备。
61
+
42
62
  ## 使用
43
63
 
44
64
  装好后插件会自动把本地 API 注册成模型商「本地免费 API」,模型列表从 `/v1/models` 动态获取。直接在 DSH 的模型选择器里选它下面的免费模型即可,不需要手动填 URL 和 Key。
@@ -46,7 +66,7 @@ Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1
46
66
  桌面端在 **设置 → 本地免费 API** 里操作;手机端在「本地API」面板里操作。面板会显示「模型商:已自动配置」。如果没配上,点面板里的「自动配置」重试;仍然失败时再手动接入:
47
67
 
48
68
  1. 打开「本地免费 API」面板。
49
- 2. 点「复制接入」,得到:
69
+ 2. 点「复制地址」得到本机/局域网地址,点「复制 Key」得到 API Key:
50
70
 
51
71
  ```text
52
72
  本机:http://127.0.0.1:8080/v1
@@ -61,7 +81,7 @@ Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1
61
81
 
62
82
  - **启动 / 停止 / 重启 / 重装**:重装会重新下载程序。
63
83
  - **仅本机 / 开局域网**:切换监听地址(`127.0.0.1` 或 `0.0.0.0`)。
64
- - **复制地址 / 复制 Key / 复制后台信息 / 打开后台**:桌面设置页与手机面板都提供。
84
+ - **复制地址 / 复制 Key / 打开后台**:桌面设置页与手机面板都提供(手机原生面板的「打开后台」受 https 限制,会自动复制地址)。
65
85
  - **自动配置**:重新把本地 API 注册为模型商「本地免费 API」,并同步最新模型列表。
66
86
  - **运行日志**:桌面设置页可展开查看最后 40 行;手机面板新增「查看日志」,也可看数据目录里的 `opencode2api.log`。
67
87
  - 状态实时显示;进程挂掉会自动拉起。
package/lib/client.js CHANGED
@@ -21,6 +21,17 @@ window.__ModuleLoader__.load({
21
21
  .oc2a summary { user-select: none; }
22
22
  `
23
23
 
24
+ const inputStyle = {
25
+ flex: '1 1 200px',
26
+ minWidth: 140,
27
+ padding: '6px 8px',
28
+ borderRadius: 7,
29
+ border: '1px solid var(--dsw-alias-border-l1)',
30
+ background: 'var(--dsw-alias-bg-layer-2)',
31
+ color: 'var(--dsw-alias-label-primary)',
32
+ fontSize: 12,
33
+ }
34
+
24
35
  const calloutStyle = {
25
36
  border: '1px solid var(--dsw-alias-border-l1)',
26
37
  borderRadius: 9,
@@ -136,6 +147,8 @@ window.__ModuleLoader__.load({
136
147
  const [error, setError] = useState('')
137
148
  const [busy, setBusy] = useState('')
138
149
  const [copied, copy] = useCopy()
150
+ const [poolUrl, setPoolUrl] = useState('https://')
151
+ const [poolCode, setPoolCode] = useState('')
139
152
 
140
153
  const load = useCallback(async () => {
141
154
  try {
@@ -152,14 +165,14 @@ window.__ModuleLoader__.load({
152
165
  return () => clearInterval(timer)
153
166
  }, [load])
154
167
 
155
- const act = async action => {
168
+ const act = async (action, extra = {}) => {
156
169
  setBusy(action)
157
170
  setError('')
158
171
  try {
159
172
  const result = await request('/action', {
160
173
  method: 'POST',
161
174
  headers: { 'content-type': 'application/json' },
162
- body: JSON.stringify({ action }),
175
+ body: JSON.stringify({ action, ...extra }),
163
176
  })
164
177
  if (result?.state) setState(result.state)
165
178
  else void load()
@@ -377,6 +390,56 @@ window.__ModuleLoader__.load({
377
390
  '项目主页',
378
391
  ),
379
392
  ),
393
+ h(
394
+ 'div',
395
+ { style: calloutStyle },
396
+ h(
397
+ 'div',
398
+ { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 } },
399
+ h('strong', null, '云端设备池'),
400
+ h(
401
+ 'span',
402
+ { style: { fontSize: 12, color: TONE[state?.poolTone] || TONE.muted } },
403
+ state?.poolStatus || '未接入',
404
+ ),
405
+ ),
406
+ state?.poolHost
407
+ ? h('div', { style: { fontSize: 12, marginBottom: 6 } }, state.poolHost)
408
+ : null,
409
+ h(
410
+ 'div',
411
+ { style: { display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 6 } },
412
+ h('input', {
413
+ value: poolUrl,
414
+ onChange: e => setPoolUrl(e.target.value),
415
+ placeholder: 'https://oc.techpanda.qzz.io',
416
+ style: inputStyle,
417
+ }),
418
+ h('input', {
419
+ value: poolCode,
420
+ onChange: e => setPoolCode(e.target.value),
421
+ placeholder: '接入码 ocp_…',
422
+ style: inputStyle,
423
+ }),
424
+ h(
425
+ Button,
426
+ {
427
+ primary: true,
428
+ disabled: disabled || !poolCode.trim(),
429
+ onClick: () => act('joinPool', { url: poolUrl.trim(), code: poolCode.trim() }),
430
+ },
431
+ busy === 'joinPool' ? '接入中…' : '加入设备池',
432
+ ),
433
+ state?.poolHost
434
+ ? h(Button, { onClick: () => act('leavePool'), disabled }, '退出')
435
+ : null,
436
+ ),
437
+ h(
438
+ 'div',
439
+ { style: { fontSize: 11, color: TONE.muted } },
440
+ '在这台设备上自动建隧道并上报心跳;掉线后管理端会自动标记离线。',
441
+ ),
442
+ ),
380
443
  h(
381
444
  'div',
382
445
  {
package/lib/index.js CHANGED
@@ -308,9 +308,287 @@ function readJson(req) {
308
308
  })
309
309
  }
310
310
 
311
+
312
+ // ---- 云端设备池 ----
313
+ const PLUGIN_VERSION = '1.3.0'
314
+ const POOL = path.join(DATA, 'pool.json')
315
+ const CLOUDFLARED = path.join(DATA, IS_WIN ? 'cloudflared.exe' : 'cloudflared')
316
+ const TUNNEL_LOG = path.join(DATA, 'cloudflared.log')
317
+ const TUNNEL_PID = path.join(DATA, 'cloudflared.pid')
318
+
319
+ let poolInfo = { status: '未接入', tone: 'muted', hostname: '', lastError: '' }
320
+ let tunnelChild = null
321
+ let heartbeatTimer = null
322
+ let tunnelTimer = null
323
+ let joining = null
324
+
325
+ function readPool() {
326
+ try {
327
+ return JSON.parse(fs.readFileSync(POOL, 'utf8'))
328
+ } catch {
329
+ return null
330
+ }
331
+ }
332
+
333
+ function writePool(data) {
334
+ fs.mkdirSync(DATA, { recursive: true })
335
+ fs.writeFileSync(POOL, JSON.stringify(data, null, 2), { mode: 0o600 })
336
+ }
337
+
338
+ function localApiKey() {
339
+ const cfg = readConfig()
340
+ return cfg.server_keys?.[0] || ''
341
+ }
342
+
343
+ function poolSnapshot() {
344
+ const pool = readPool()
345
+ if (!pool?.deviceId) return { status: '未接入', tone: 'muted', hostname: '', lastError: '' }
346
+ const age = pool.lastHeartbeat ? Date.now() - pool.lastHeartbeat : null
347
+ if (pool.lastError) return { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
348
+ if (age === null) return { status: '等待心跳', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
349
+ if (age < 180000) return { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
350
+ return { status: '离线', tone: 'bad', hostname: pool.hostname || '', lastError: '' }
351
+ }
352
+
353
+ function cloudflaredTarget() {
354
+ const arch = process.arch === 'x64' ? 'amd64' : process.arch === 'arm64' ? 'arm64' : null
355
+ if (!arch) throw new Error('当前 CPU 架构不支持 cloudflared')
356
+ if (process.platform === 'win32') return { file: `cloudflared-windows-${arch}.exe`, archive: false }
357
+ if (process.platform === 'darwin') return { file: `cloudflared-darwin-${arch}.tgz`, archive: true }
358
+ return { file: `cloudflared-linux-${arch}`, archive: false }
359
+ }
360
+
361
+ async function ensureCloudflared() {
362
+ if (fs.existsSync(CLOUDFLARED)) return
363
+ const t = cloudflaredTarget()
364
+ let lastFailure = null
365
+ for (const prefix of MIRRORS) {
366
+ try {
367
+ const body = await fetchBuffer(`${prefix}https://github.com/cloudflare/cloudflared/releases/latest/download/${t.file}`)
368
+ if (t.archive) {
369
+ const temp = path.join(DATA, `.cf-${Date.now()}`)
370
+ fs.mkdirSync(temp, { recursive: true })
371
+ const archive = path.join(temp, t.file)
372
+ await fsp.writeFile(archive, body)
373
+ await extract(archive, temp)
374
+ const found = findFile(temp, 'cloudflared')
375
+ if (!found) throw new Error('cloudflared 解压失败')
376
+ await fsp.copyFile(found, CLOUDFLARED)
377
+ await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
378
+ } else {
379
+ await fsp.writeFile(CLOUDFLARED, body)
380
+ }
381
+ if (!IS_WIN) fs.chmodSync(CLOUDFLARED, 0o755)
382
+ return
383
+ } catch (error) {
384
+ lastFailure = error
385
+ }
386
+ }
387
+ throw lastFailure || new Error('cloudflared 下载失败')
388
+ }
389
+
390
+ function tunnelRunning() {
391
+ if (tunnelChild && tunnelChild.exitCode === null) return true
392
+ try {
393
+ const pid = Number(fs.readFileSync(TUNNEL_PID, 'utf8').trim())
394
+ if (pid && alive(pid)) return true
395
+ } catch {}
396
+ return false
397
+ }
398
+
399
+ async function startTunnel() {
400
+ const pool = readPool()
401
+ if (!pool?.tunnelToken) return false
402
+ if (tunnelRunning()) return true
403
+ if (!fs.existsSync(CLOUDFLARED)) await ensureCloudflared()
404
+ const fd = fs.openSync(TUNNEL_LOG, 'a')
405
+ try {
406
+ tunnelChild = spawn(
407
+ CLOUDFLARED,
408
+ ['tunnel', '--no-autoupdate', 'run', '--token', pool.tunnelToken],
409
+ { stdio: ['ignore', fd, fd], detached: false },
410
+ )
411
+ } finally {
412
+ fs.closeSync(fd)
413
+ }
414
+ tunnelChild.once('error', () => {})
415
+ tunnelChild.unref()
416
+ try {
417
+ fs.writeFileSync(TUNNEL_PID, String(tunnelChild.pid))
418
+ } catch {}
419
+ return true
420
+ }
421
+
422
+ function stopTunnel() {
423
+ const pids = new Set()
424
+ if (tunnelChild?.pid) pids.add(tunnelChild.pid)
425
+ try {
426
+ const filePid = Number(fs.readFileSync(TUNNEL_PID, 'utf8').trim())
427
+ if (filePid) pids.add(filePid)
428
+ } catch {}
429
+ for (const pid of pids) {
430
+ try {
431
+ process.kill(pid)
432
+ } catch {}
433
+ }
434
+ tunnelChild = null
435
+ try {
436
+ fs.unlinkSync(TUNNEL_PID)
437
+ } catch {}
438
+ }
439
+
440
+ export async function heartbeat() {
441
+ const pool = readPool()
442
+ if (!pool?.deviceId || !pool?.deviceSecret) return
443
+ try {
444
+ const res = await fetch(`${pool.url}/api/device/heartbeat`, {
445
+ method: 'POST',
446
+ headers: {
447
+ 'content-type': 'application/json',
448
+ 'x-device-id': pool.deviceId,
449
+ 'x-device-secret': pool.deviceSecret,
450
+ },
451
+ body: JSON.stringify({
452
+ version: PLUGIN_VERSION,
453
+ platform: target() ? `${target().os}/${target().arch}` : process.platform,
454
+ }),
455
+ signal: AbortSignal.timeout(15000),
456
+ })
457
+ const data = await res.json().catch(() => ({}))
458
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`)
459
+ pool.lastHeartbeat = Date.now()
460
+ pool.lastError = ''
461
+ writePool(pool)
462
+ if (data.enabled === false) {
463
+ stopTunnel()
464
+ poolInfo = { status: '已被管理端停用', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
465
+ } else {
466
+ void startTunnel()
467
+ poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
468
+ }
469
+ } catch (error) {
470
+ pool.lastError = human(error)
471
+ writePool(pool)
472
+ poolInfo = { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
473
+ }
474
+ }
475
+
476
+ function startPoolTimers() {
477
+ if (!heartbeatTimer) {
478
+ heartbeatTimer = setInterval(() => {
479
+ void heartbeat()
480
+ }, 60_000)
481
+ heartbeatTimer.unref?.()
482
+ }
483
+ if (!tunnelTimer) {
484
+ tunnelTimer = setInterval(() => {
485
+ const pool = readPool()
486
+ if (pool?.tunnelToken && !tunnelRunning()) void startTunnel().catch(() => {})
487
+ }, 45_000)
488
+ tunnelTimer.unref?.()
489
+ }
490
+ }
491
+
492
+ function stopPoolTimers() {
493
+ if (heartbeatTimer) clearInterval(heartbeatTimer)
494
+ if (tunnelTimer) clearInterval(tunnelTimer)
495
+ heartbeatTimer = null
496
+ tunnelTimer = null
497
+ }
498
+
499
+ export async function joinPool(input = {}) {
500
+ if (joining) return joining
501
+ joining = (async () => {
502
+ const url = String(input.url || '').trim().replace(/\/+$/, '')
503
+ const code = String(input.code || '').trim()
504
+ if (!/^https?:\/\//i.test(url)) throw new Error('前端地址要以 http:// 或 https:// 开头')
505
+ if (!code) throw new Error('缺少接入码')
506
+
507
+ if (!fs.existsSync(CFG)) ensureConfig()
508
+ if (!fs.existsSync(BIN)) await ensureInstalled()
509
+ if (!(await health())) await start()
510
+ const key = localApiKey()
511
+ if (!key) throw new Error('本机 API Key 还没生成,先点一次启动')
512
+
513
+ const res = await fetch(`${url}/api/device/enroll`, {
514
+ method: 'POST',
515
+ headers: { 'content-type': 'application/json' },
516
+ body: JSON.stringify({
517
+ code,
518
+ apiKey: key,
519
+ name: os.hostname().slice(0, 40) || 'device',
520
+ platform: target() ? `${target().os}/${target().arch}` : process.platform,
521
+ version: PLUGIN_VERSION,
522
+ }),
523
+ signal: AbortSignal.timeout(30000),
524
+ })
525
+ const data = await res.json().catch(() => ({}))
526
+ if (!res.ok || !data.device_id) throw new Error(data.error || `接入失败 HTTP ${res.status}`)
527
+
528
+ writePool({
529
+ url,
530
+ deviceId: data.device_id,
531
+ deviceSecret: data.device_secret,
532
+ tunnelToken: data.tunnel_token,
533
+ hostname: data.hostname || '',
534
+ joinedAt: Date.now(),
535
+ lastHeartbeat: 0,
536
+ lastError: '',
537
+ })
538
+ await ensureCloudflared()
539
+ await startTunnel()
540
+ startPoolTimers()
541
+ await heartbeat()
542
+ poolInfo = { status: '在线', tone: 'good', hostname: data.hostname || '', lastError: '' }
543
+ return `已接入设备池:${data.hostname || data.device_id}`
544
+ })()
545
+ try {
546
+ return await joining
547
+ } finally {
548
+ joining = null
549
+ }
550
+ }
551
+
552
+ export async function leavePool() {
553
+ const pool = readPool()
554
+ stopPoolTimers()
555
+ stopTunnel()
556
+ if (pool?.deviceId && pool?.deviceSecret && pool?.url) {
557
+ await fetch(`${pool.url}/api/device/leave`, {
558
+ method: 'POST',
559
+ headers: { 'x-device-id': pool.deviceId, 'x-device-secret': pool.deviceSecret },
560
+ signal: AbortSignal.timeout(15000),
561
+ }).catch(() => {})
562
+ }
563
+ try {
564
+ fs.unlinkSync(POOL)
565
+ } catch {}
566
+ poolInfo = { status: '未接入', tone: 'muted', hostname: '', lastError: '' }
567
+ return '已退出设备池'
568
+ }
569
+
570
+ function bootPool() {
571
+ const pool = readPool()
572
+ if (!pool?.deviceId) {
573
+ poolInfo = { status: '未接入', tone: 'muted', hostname: '', lastError: '' }
574
+ return
575
+ }
576
+ void (async () => {
577
+ try {
578
+ await ensureCloudflared()
579
+ await startTunnel()
580
+ startPoolTimers()
581
+ await heartbeat()
582
+ } catch (error) {
583
+ poolInfo = { status: '接入异常', tone: 'bad', hostname: pool.hostname || '', lastError: human(error) }
584
+ }
585
+ })()
586
+ }
587
+
311
588
  async function buildState() {
312
589
  const snap = await snapshot()
313
590
  const cfg = fs.existsSync(CFG) ? readConfig() : {}
591
+ const pool = poolSnapshot()
314
592
  return {
315
593
  ...snap,
316
594
  running: Boolean(await health()),
@@ -325,10 +603,14 @@ async function buildState() {
325
603
  autoError: lastAutoError,
326
604
  version: VERSION,
327
605
  time: Date.now(),
606
+ poolStatus: pool.status,
607
+ poolTone: pool.tone,
608
+ poolHost: pool.hostname,
609
+ poolError: pool.lastError,
328
610
  }
329
611
  }
330
612
 
331
- async function runAction(action) {
613
+ async function runAction(action, body = {}) {
332
614
  switch (action) {
333
615
  case 'start':
334
616
  desired = true
@@ -348,6 +630,13 @@ async function runAction(action) {
348
630
  const ok = await start()
349
631
  return ok ? (action === 'listenLocal' ? '已仅本机监听' : '已开局域网') : '切换失败'
350
632
  }
633
+ case 'joinPool':
634
+ return await joinPool(body)
635
+ case 'leavePool':
636
+ return await leavePool()
637
+ case 'poolSync':
638
+ await heartbeat()
639
+ return poolInfo.status
351
640
  case 'autoConfig':
352
641
  await autoConfigure(true)
353
642
  return autoInfo.status
@@ -406,7 +695,7 @@ async function api(req, res) {
406
695
  if (method === 'POST' && route === '/action') {
407
696
  if (!local) return send(403, { error: '仅本机可操作' })
408
697
  const body = await readJson(req)
409
- const toast = await runAction(String(body.action || ''))
698
+ const toast = await runAction(String(body.action || ''), body)
410
699
  return send(200, { ok: true, toast, state: await buildState() })
411
700
  }
412
701
  return send(404, { error: 'not found' })
@@ -574,13 +863,25 @@ function alive(pid) {
574
863
  }
575
864
  }
576
865
 
577
- function execLines(command, args) {
866
+ function execLines(command, args, timeout = 3000) {
578
867
  return new Promise((resolve) => {
579
868
  const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'ignore'] })
580
869
  let out = ''
870
+ let done = false
871
+ let timer
872
+ const finish = (value) => {
873
+ if (done) return
874
+ done = true
875
+ clearTimeout(timer)
876
+ resolve(value)
877
+ }
878
+ timer = setTimeout(() => {
879
+ try { child.kill() } catch {}
880
+ finish(out)
881
+ }, timeout)
581
882
  child.stdout?.on('data', (chunk) => { out += chunk })
582
- child.once('error', () => resolve(''))
583
- child.once('close', () => resolve(out))
883
+ child.once('error', () => finish(''))
884
+ child.once('close', () => finish(out))
584
885
  })
585
886
  }
586
887
 
@@ -633,6 +934,22 @@ async function listenerPids(port) {
633
934
  const pid = Number(line.trim())
634
935
  if (pid) found.add(pid)
635
936
  }
937
+ if (!found.size) {
938
+ const ss = await execLines('ss', ['-ltnp'])
939
+ for (const line of ss.split(/\r?\n/)) {
940
+ if (!new RegExp(`:${port}\\b`).test(line)) continue
941
+ for (const match of line.matchAll(/pid=(\d+)/g)) found.add(Number(match[1]))
942
+ }
943
+ }
944
+ if (!found.size) {
945
+ const netstat = await execLines('netstat', ['-ltnp'])
946
+ for (const line of netstat.split(/\r?\n/)) {
947
+ if (!/LISTEN/.test(line) || !new RegExp(`:${port}\\b`).test(line)) continue
948
+ const last = line.trim().split(/\s+/).pop() || ''
949
+ const pid = Number((last.match(/^(\d+)\//) || last.match(/^(\d+)$/) || [])[1])
950
+ if (pid) found.add(pid)
951
+ }
952
+ }
636
953
  if (!found.size) {
637
954
  const fuser = await execLines('fuser', ['-n', 'tcp', String(port)])
638
955
  for (const token of fuser.split(/\s+/)) {
@@ -820,6 +1137,8 @@ function registerUi(ctx) {
820
1137
  { label: '局域网', value: { $: 'data.lanUrl' } },
821
1138
  { label: '模型', value: { $: 'data.models' } },
822
1139
  { label: '模型商', value: { $: 'data.provider' }, tone: { $: 'data.providerTone' } },
1140
+ { label: '设备池', value: { $: 'data.poolStatus' }, tone: { $: 'data.poolTone' } },
1141
+ { label: '池地址', value: { $: 'data.poolHost' } },
823
1142
  { label: '平台', value: { $: 'data.platform' } },
824
1143
  ],
825
1144
  },
@@ -841,8 +1160,8 @@ function registerUi(ctx) {
841
1160
  {
842
1161
  type: 'actions',
843
1162
  items: [
844
- { label: '复制接入', action: 'copyInfo' },
845
- { label: '复制后台', action: 'copyWeb' },
1163
+ { label: '复制地址', action: 'copyBase' },
1164
+ { label: '复制Key', action: 'copyKey' },
846
1165
  { label: '自动配置', action: 'autoConfig' },
847
1166
  { label: '重装', action: 'reinstall' },
848
1167
  ],
@@ -850,7 +1169,14 @@ function registerUi(ctx) {
850
1169
  {
851
1170
  type: 'actions',
852
1171
  items: [
853
- { label: '打开后台', action: 'openWeb', style: 'primary' },
1172
+ { label: '退出设备池', action: 'leavePool' },
1173
+ { label: '立即心跳', action: 'poolSync' },
1174
+ ],
1175
+ },
1176
+ {
1177
+ type: 'actions',
1178
+ items: [
1179
+ { label: '打开后台', action: 'openWeb' },
854
1180
  { label: '查看日志', action: 'viewLog' },
855
1181
  { label: '项目主页', action: 'openHome' },
856
1182
  ],
@@ -923,22 +1249,19 @@ function registerUi(ctx) {
923
1249
  const ok = await start()
924
1250
  return { toast: ok ? '已开局域网' : '切换失败' }
925
1251
  }),
926
- copyInfo: () => {
927
- const cfg = readConfig()
928
- const key = cfg.server_keys?.[0] || ''
1252
+ copyBase: () => {
929
1253
  const lan = lanAddress()
930
1254
  const lanLine = lan ? `\n局域网:http://${lan}:${API_PORT}/v1` : ''
931
1255
  return {
932
- copy: `本机:http://127.0.0.1:${API_PORT}/v1${lanLine}\nAPI Key:${key}\n推荐模型:big-pickle`,
933
- toast: '接入信息已复制',
1256
+ copy: `本机:http://127.0.0.1:${API_PORT}/v1${lanLine}`,
1257
+ toast: 'API 地址已复制',
934
1258
  }
935
1259
  },
936
- copyWeb: () => {
1260
+ copyKey: () => {
937
1261
  const cfg = readConfig()
938
- const password = readPassword() || '(已在后台改过,请用新密码)'
939
1262
  return {
940
- copy: `后台:http://127.0.0.1:${WEB_PORT}\n账号:${cfg.webui?.username || 'admin'}\n密码:${password}`,
941
- toast: '后台信息已复制',
1263
+ copy: cfg.server_keys?.[0] || '(无 Key)',
1264
+ toast: 'API Key 已复制',
942
1265
  }
943
1266
  },
944
1267
  reinstall: () => {
@@ -958,18 +1281,22 @@ function registerUi(ctx) {
958
1281
  })()
959
1282
  return { toast: '后台重装中…' }
960
1283
  },
961
- openWeb: () => ({
962
- copy: `http://127.0.0.1:${WEB_PORT}`,
963
- open: `http://127.0.0.1:${WEB_PORT}`,
964
- toast: '后台地址已复制,可粘贴到浏览器打开',
965
- }),
1284
+ openWeb: () => {
1285
+ const url = `http://127.0.0.1:${WEB_PORT}`
1286
+ const effect = { copy: url, toast: '后台地址已复制,请粘贴到浏览器打开' }
1287
+ if (/^https:\/\//i.test(url)) {
1288
+ effect.link = url
1289
+ effect.toast = '正在打开后台'
1290
+ }
1291
+ return effect
1292
+ },
966
1293
  viewLog: () => ({
967
1294
  copy: tailLog(40) || '(暂无日志)',
968
1295
  toast: '日志已复制',
969
1296
  }),
970
1297
  openHome: () => ({
971
1298
  copy: 'https://github.com/king-andthe-nice/dsh-plugin-opencode2api',
972
- open: 'https://github.com/king-andthe-nice/dsh-plugin-opencode2api',
1299
+ link: 'https://github.com/king-andthe-nice/dsh-plugin-opencode2api',
973
1300
  toast: '项目地址已复制',
974
1301
  }),
975
1302
  autoConfig: () =>
@@ -977,6 +1304,12 @@ function registerUi(ctx) {
977
1304
  await autoConfigure(true)
978
1305
  return { toast: autoInfo.tone === 'good' ? '模型商已配置' : autoInfo.status }
979
1306
  }),
1307
+ leavePool: () => pendingWork('正在退出', async () => ({ toast: await leavePool() })),
1308
+ poolSync: () =>
1309
+ pendingWork('正在同步', async () => {
1310
+ await heartbeat()
1311
+ return { toast: poolInfo.status }
1312
+ }),
980
1313
  },
981
1314
  })
982
1315
 
@@ -1009,11 +1342,15 @@ export function apply(ctx) {
1009
1342
  const bootTimer = setTimeout(() => {
1010
1343
  void boot()
1011
1344
  }, 1500)
1345
+ const poolTimer = setTimeout(() => {
1346
+ bootPool()
1347
+ }, 2500)
1012
1348
  const watchdog = setInterval(() => {
1013
1349
  if (desired && !busy) void boot()
1014
1350
  }, 30000)
1015
1351
  return () => {
1016
1352
  clearTimeout(bootTimer)
1353
+ clearTimeout(poolTimer)
1017
1354
  clearInterval(watchdog)
1018
1355
  }
1019
1356
  }, 'opencode2api autostart')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-opencode2api",
3
- "version": "1.2.1",
3
+ "version": "1.3.1",
4
4
  "description": "Unofficial one-click installer and auto-runner for opencode2api — a local free OpenAI-compatible API gateway — inside DSH, with a desktop settings UI and a dsh-go native panel (Windows, macOS, Linux, Android).",
5
5
  "repository": {
6
6
  "type": "git",