dsh-plugin-opencode2api 1.3.5 → 1.3.7

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.
Files changed (3) hide show
  1. package/README.md +9 -1
  2. package/lib/index.js +197 -89
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  一键把 [opencode2api](https://github.com/jasonxu114514/opencode2api) 装进 DSH:自动下载对应平台的程序、生成配置、启动并常驻,并自动把「本地免费 API」注册成 DSH 的模型商(模型列表从网关动态获取)。装好后本机就有一个专属的、兼容 OpenAI 的免费 API;DSH 关闭再打开会自动重启。
4
4
 
5
+ ## 1.3.7 更新
6
+
7
+ - 修复“cloudflared 下载失败后整台设备消失”:不再先删除旧二进制,改为先写 `cloudflared.new`,校验通过后再替换;下载失败保留旧文件,下次继续用或重试。
8
+ - 修复“重启也连不上”:心跳和 20 秒隧道检查定时器现在先启动,再处理 cloudflared。即使下载/启动失败,设备也会继续心跳并显示“隧道启动中/重连中”,不会 3 分钟后直接离线。
9
+ - 增加下载与启动的并发锁:20 秒检查、60 秒心跳和手动“立即心跳”不会再同时开多个 cloudflared 下载;慢网下只保留一个下载任务。
10
+ - cloudflared 单镜像下载超时从 120 秒放宽到 240 秒,失败后退避重试(30s/60s/120s/180s),不再每 20 秒硬撞一次。
11
+ - 心跳现在在隧道未知时上报 `tunnel:false`,避免中转站把没有隧道的设备当成可用设备派请求。
12
+
5
13
  ## 1.2.2 更新
6
14
 
7
15
  - 手机原生面板与桌面设置页对齐:移除「复制接入」「复制后台」,改为「复制地址」「复制 Key」;保留「打开后台」「查看日志」「项目主页」。
@@ -63,7 +71,7 @@ Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1
63
71
 
64
72
  ### 隧道连不上怎么查(Windows 尤其看这里)
65
73
 
66
- 1. 看日志:`<DSH_HOME>\dsh-go\opencode2api\cloudflared.log`(默认 `C:\Users\你的用户名\.dsh\...`),搜索 `ERR`、`exit`、`[plugin]`。出现 `下载到的不是可执行文件` 说明镜像返回了网页,删掉同目录的 `cloudflared.exe` 让插件重下即可。
74
+ 1. 看日志:`<DSH_HOME>\dsh-go\opencode2api\cloudflared.log`(默认 `C:\Users\你的用户名\.dsh\...`),搜索 `ERR`、`exit`、`[plugin]`。1.3.7 起出现 `下载到的不是可执行文件` 不会删除旧文件,会保留并重试;也可以手动把正确的 `cloudflared.exe` 放到同目录,重启 DSH 即可。
67
75
  2. Windows Defender 有时会拦 cloudflared:在「病毒和威胁防护 → 排除项」里把插件数据目录加进去,再重新接入。
68
76
  3. 1.3.5 起,插件启动 cloudflared 后等 1.5 秒确认进程还活着;秒退会直接显示「隧道启动失败」,不再假装在线。
69
77
  4. 旧版留下的 `cloudflared.pid` 可能被别的程序复用,导致插件误以为隧道在跑。1.3.5 会核对进程名(Windows 用 `tasklist`,Linux 读 `/proc/<pid>/comm`,macOS 用 `ps`),不是 cloudflared 就忽略并重新启动。
package/lib/index.js CHANGED
@@ -13,6 +13,7 @@ const REPO = 'jasonxu114514/opencode2api'
13
13
  const API_PORT = Number(process.env.OPENCODE2API_PORT || 8080)
14
14
  const WEB_PORT = API_PORT + 1
15
15
  const DOWNLOAD_TIMEOUT_MS = 120_000
16
+ const CLOUDFLARED_TIMEOUT_MS = Number(process.env.OCP_CLOUDFLARED_TIMEOUT_MS || 240_000)
16
17
  const MIRRORS = ['', 'https://gh-proxy.com/', 'https://ghproxy.net/', 'https://ghfast.top/']
17
18
 
18
19
  const HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
@@ -333,7 +334,11 @@ let heartbeatFails = 0
333
334
  let tunnelDownStreak = 0
334
335
  let tunnelNextTry = 0
335
336
  let tunnelExits = 0
337
+ let tunnelAttemptFails = 0
336
338
  let tunnelState = { ok: false, at: 0, reason: '' }
339
+ let cloudflaredPromise = null
340
+ let startTunnelPromise = null
341
+ let checkTunnelBusy = false
337
342
 
338
343
  function readPool() {
339
344
  try {
@@ -404,39 +409,77 @@ function existingBinaryOk(file) {
404
409
 
405
410
  async function ensureCloudflared() {
406
411
  if (existingBinaryOk(CLOUDFLARED)) return
407
- // 之前下到的可能是镜像的错误网页,留着只会每次启动都失败
408
- try {
409
- if (fs.existsSync(CLOUDFLARED)) fs.unlinkSync(CLOUDFLARED)
410
- } catch {}
411
- const t = cloudflaredTarget()
412
- let lastFailure = null
413
- for (const prefix of MIRRORS) {
412
+ const staged = `${CLOUDFLARED}.new`
413
+ if (existingBinaryOk(staged)) {
414
414
  try {
415
- const body = await fetchBuffer(`${prefix}https://github.com/cloudflare/cloudflared/releases/latest/download/${t.file}`)
416
- if (t.archive) {
417
- const temp = path.join(DATA, `.cf-${Date.now()}`)
418
- fs.mkdirSync(temp, { recursive: true })
419
- const archive = path.join(temp, t.file)
420
- await fsp.writeFile(archive, body)
421
- await extract(archive, temp)
422
- const found = findFile(temp, 'cloudflared')
423
- if (!found) throw new Error('cloudflared 解压失败')
424
- await fsp.copyFile(found, CLOUDFLARED)
425
- await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
426
- } else {
427
- if (!expectedMagicOk(body)) {
428
- throw new Error(`下载到的不是可执行文件(${body.length} 字节,多半是镜像错误页)`)
429
- }
430
- await fsp.writeFile(CLOUDFLARED, body)
431
- logTunnel(`cloudflared downloaded bytes=${body.length} from=${prefix || 'github'}`)
432
- }
415
+ fs.renameSync(staged, CLOUDFLARED)
433
416
  if (!IS_WIN) fs.chmodSync(CLOUDFLARED, 0o755)
417
+ logTunnel('cloudflared staged binary promoted')
434
418
  return
435
419
  } catch (error) {
436
- lastFailure = error
420
+ throw new Error(`替换 cloudflared 失败:${error.message}`)
437
421
  }
438
422
  }
439
- throw lastFailure || new Error('cloudflared 下载失败')
423
+ if (cloudflaredPromise) return cloudflaredPromise
424
+ cloudflaredPromise = (async () => {
425
+ if (existingBinaryOk(CLOUDFLARED)) return
426
+ try {
427
+ if (fs.existsSync(CLOUDFLARED)) {
428
+ const size = fs.statSync(CLOUDFLARED).size
429
+ logTunnel(`existing cloudflared invalid (size=${size}), keeping it until replacement is verified`)
430
+ }
431
+ } catch {}
432
+ const t = cloudflaredTarget()
433
+ let lastFailure = null
434
+ for (const prefix of MIRRORS) {
435
+ let temp = null
436
+ try {
437
+ const url = `${prefix}https://github.com/cloudflare/cloudflared/releases/latest/download/${t.file}`
438
+ const body = await fetchBuffer(url, CLOUDFLARED_TIMEOUT_MS)
439
+ if (t.archive) {
440
+ temp = path.join(DATA, `.cf-${Date.now()}`)
441
+ fs.mkdirSync(temp, { recursive: true })
442
+ const archive = path.join(temp, t.file)
443
+ await fsp.writeFile(archive, body)
444
+ await extract(archive, temp)
445
+ const found = findFile(temp, 'cloudflared')
446
+ if (!found) throw new Error('cloudflared 解压失败')
447
+ if (!existingBinaryOk(found)) throw new Error('解压出的 cloudflared 校验失败')
448
+ try {
449
+ fs.renameSync(found, CLOUDFLARED)
450
+ } catch (error) {
451
+ throw new Error(`替换 cloudflared 失败:${error.message}`)
452
+ }
453
+ } else {
454
+ if (!expectedMagicOk(body)) {
455
+ throw new Error(`下载到的不是可执行文件(${body.length} 字节,多半是镜像错误页)`)
456
+ }
457
+ await fsp.writeFile(staged, body)
458
+ if (!existingBinaryOk(staged)) throw new Error('下载的 cloudflared 校验失败')
459
+ if (!IS_WIN) fs.chmodSync(staged, 0o755)
460
+ try {
461
+ fs.renameSync(staged, CLOUDFLARED)
462
+ } catch (error) {
463
+ throw new Error(`替换 cloudflared 失败:${error.message}`)
464
+ }
465
+ }
466
+ if (!IS_WIN) fs.chmodSync(CLOUDFLARED, 0o755)
467
+ logTunnel(`cloudflared downloaded bytes=${body.length} from=${prefix || 'github'}`)
468
+ return
469
+ } catch (error) {
470
+ lastFailure = error
471
+ logTunnel(`cloudflared download failed from=${prefix || 'github'}: ${error?.message || error}`)
472
+ } finally {
473
+ if (temp) await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
474
+ }
475
+ }
476
+ throw lastFailure || new Error('cloudflared 下载失败')
477
+ })()
478
+ try {
479
+ await cloudflaredPromise
480
+ } finally {
481
+ cloudflaredPromise = null
482
+ }
440
483
  }
441
484
 
442
485
  function readTunnelPid() {
@@ -513,6 +556,16 @@ function tunnelArgs(token) {
513
556
  }
514
557
 
515
558
  async function startTunnel() {
559
+ if (startTunnelPromise) return startTunnelPromise
560
+ startTunnelPromise = startTunnelInner()
561
+ try {
562
+ return await startTunnelPromise
563
+ } finally {
564
+ startTunnelPromise = null
565
+ }
566
+ }
567
+
568
+ async function startTunnelInner() {
516
569
  const pool = readPool()
517
570
  if (!pool?.tunnelToken) return false
518
571
  if (await tunnelRunningVerified()) return true
@@ -520,18 +573,31 @@ async function startTunnel() {
520
573
  logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
521
574
  try { fs.unlinkSync(TUNNEL_PID) } catch {}
522
575
  }
523
- if (!fs.existsSync(CLOUDFLARED)) await ensureCloudflared()
524
- const fd = fs.openSync(TUNNEL_LOG, 'a')
576
+ if (!existingBinaryOk(CLOUDFLARED)) await ensureCloudflared()
577
+ let fd = null
578
+ try {
579
+ fd = fs.openSync(TUNNEL_LOG, 'a')
580
+ } catch {
581
+ // Windows 上日志被杀软临时占用时也要能启动,不能因为打不开日志就整条隧道不跑
582
+ fd = null
583
+ }
525
584
  let child
526
585
  try {
527
586
  child = spawn(CLOUDFLARED, tunnelArgs(pool.tunnelToken), {
528
- stdio: ['ignore', fd, fd],
587
+ stdio: fd === null ? 'ignore' : ['ignore', fd, fd],
529
588
  detached: false,
530
589
  windowsHide: true,
531
590
  })
532
591
  tunnelChild = child
533
592
  } finally {
534
- fs.closeSync(fd)
593
+ if (fd !== null) {
594
+ try { fs.closeSync(fd) } catch {}
595
+ }
596
+ }
597
+ if (!child.pid) {
598
+ logTunnel('cloudflared spawn failed: no pid')
599
+ tunnelChild = null
600
+ return false
535
601
  }
536
602
  child.once('error', (error) => logTunnel(`spawn error: ${error?.message || error}`))
537
603
  child.once('exit', (code, signal) => {
@@ -574,9 +640,10 @@ async function stopTunnel() {
574
640
  } catch {}
575
641
  }
576
642
 
577
- export async function heartbeat() {
643
+ export async function heartbeat(options = {}) {
644
+ const startTunnelNow = options.start !== false
578
645
  const pool = readPool()
579
- if (!pool?.deviceId || !pool?.deviceSecret) return
646
+ if (!pool?.deviceId || !pool?.deviceSecret) return false
580
647
  const tunnel = await tunnelReady()
581
648
  tunnelState = {
582
649
  ok: tunnel.ok,
@@ -594,14 +661,14 @@ export async function heartbeat() {
594
661
  body: JSON.stringify({
595
662
  version: PLUGIN_VERSION,
596
663
  platform: target() ? `${target().os}/${target().arch}` : process.platform,
597
- tunnel: tunnel.known ? tunnel.ok : undefined,
664
+ tunnel: tunnel.known ? tunnel.ok : false,
598
665
  }),
599
666
  signal: AbortSignal.timeout(25000),
600
667
  })
601
668
  const data = await res.json().catch(() => ({}))
602
669
  if (res.status === 401) {
603
670
  resetPoolLocally(data.error || '设备已被移除')
604
- return
671
+ return false
605
672
  }
606
673
  if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`)
607
674
  heartbeatFails = 0
@@ -611,15 +678,17 @@ export async function heartbeat() {
611
678
  if (data.enabled === false) {
612
679
  void stopTunnel()
613
680
  poolInfo = { status: '已被管理端停用', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
614
- } else {
615
- const started = await startTunnel()
616
- if (!started) {
617
- poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: pool.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
618
- } else if (tunnel.known && !tunnel.ok) {
681
+ return false
682
+ }
683
+ if (!startTunnelNow) {
684
+ if (tunnel.known && tunnel.ok) {
685
+ poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
686
+ } else if (tunnel.known) {
619
687
  poolInfo = { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
620
688
  } else {
621
- poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
689
+ poolInfo = { status: '隧道启动中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
622
690
  }
691
+ return true
623
692
  }
624
693
  } catch (error) {
625
694
  heartbeatFails += 1
@@ -629,6 +698,37 @@ export async function heartbeat() {
629
698
  writePool(pool)
630
699
  poolInfo = { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
631
700
  }
701
+ return false
702
+ }
703
+ try {
704
+ const started = await startTunnel()
705
+ if (!started) {
706
+ poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: pool.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
707
+ return false
708
+ }
709
+ if (tunnel.known && !tunnel.ok) {
710
+ poolInfo = { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
711
+ } else {
712
+ poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
713
+ }
714
+ if (started) {
715
+ // 刚启动的隧道通常几秒内注册连接;尽快补一次心跳,避免第一次上报 false 后要等 60 秒才恢复调度
716
+ void (async () => {
717
+ for (let i = 0; i < 5; i++) {
718
+ const ready = await tunnelReady()
719
+ if (ready.known && ready.ok) {
720
+ await heartbeat({ start: false })
721
+ return
722
+ }
723
+ await sleep(1000)
724
+ }
725
+ })().catch(() => {})
726
+ }
727
+ return true
728
+ } catch (error) {
729
+ logTunnel(`heartbeat start tunnel failed: ${error?.message || error}`)
730
+ poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: pool.hostname || '', lastError: human(error) }
731
+ return false
632
732
  }
633
733
  }
634
734
 
@@ -648,38 +748,51 @@ function startPoolTimers() {
648
748
  }
649
749
 
650
750
  async function checkTunnel() {
651
- const pool = readPool()
652
- if (!pool?.tunnelToken) return
653
- if (Date.now() < tunnelNextTry) return
654
- const running = await tunnelRunningVerified()
655
- if (running) {
656
- const ready = await tunnelReady()
657
- tunnelState = {
658
- ok: ready.ok,
659
- at: Date.now(),
660
- reason: ready.known ? (ready.ok ? '' : '隧道没连上') : '隧道状态未知',
751
+ if (checkTunnelBusy) return
752
+ checkTunnelBusy = true
753
+ try {
754
+ const pool = readPool()
755
+ if (!pool?.tunnelToken) return
756
+ if (Date.now() < tunnelNextTry) return
757
+ const running = await tunnelRunningVerified()
758
+ if (running) {
759
+ const ready = await tunnelReady()
760
+ tunnelState = {
761
+ ok: ready.ok,
762
+ at: Date.now(),
763
+ reason: ready.known ? (ready.ok ? '' : '隧道没连上') : '隧道状态未知',
764
+ }
765
+ if (ready.ok) {
766
+ tunnelDownStreak = 0
767
+ tunnelAttemptFails = 0
768
+ return
769
+ }
770
+ // 进程在但一条连接都没连上:连续两次才动,别把刚起步的隧道掐掉
771
+ tunnelDownStreak += 1
772
+ if (tunnelDownStreak < 2) return
773
+ logTunnel(`tunnel unhealthy (connections=${ready.connections} known=${ready.known}), restarting`)
774
+ await stopTunnel()
775
+ } else if (tunnelRunning()) {
776
+ logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
777
+ try { fs.unlinkSync(TUNNEL_PID) } catch {}
661
778
  }
662
- if (ready.ok) {
663
- tunnelDownStreak = 0
664
- return
779
+ // 进程没了或确认不健康:重启并做指数退避,避免秒退秒起
780
+ tunnelDownStreak = 0
781
+ const started = await startTunnel().catch((error) => {
782
+ logTunnel(`restart failed: ${error?.message || error}`)
783
+ return false
784
+ })
785
+ if (started) {
786
+ tunnelAttemptFails = 0
787
+ } else {
788
+ tunnelAttemptFails += 1
789
+ tunnelState = { ok: false, at: Date.now(), reason: 'cloudflared 启动失败' }
665
790
  }
666
- // 进程在但一条连接都没连上:连续两次才动,别把刚起步的隧道掐掉
667
- tunnelDownStreak += 1
668
- if (tunnelDownStreak < 2) return
669
- logTunnel(`tunnel unhealthy (connections=${ready.connections} known=${ready.known}), restarting`)
670
- await stopTunnel()
671
- } else if (tunnelRunning()) {
672
- logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
673
- try { fs.unlinkSync(TUNNEL_PID) } catch {}
791
+ const fails = Math.max(tunnelExits, tunnelAttemptFails)
792
+ tunnelNextTry = Date.now() + Math.min(30_000 * 2 ** Math.min(fails, 3), 180_000)
793
+ } finally {
794
+ checkTunnelBusy = false
674
795
  }
675
- // 进程没了或确认不健康:重启并做指数退避,避免秒退秒起
676
- tunnelDownStreak = 0
677
- const started = await startTunnel().catch((error) => {
678
- logTunnel(`restart failed: ${error?.message || error}`)
679
- return false
680
- })
681
- if (!started) tunnelState = { ok: false, at: Date.now(), reason: 'cloudflared 启动失败' }
682
- tunnelNextTry = Date.now() + Math.min(5000 * 2 ** Math.min(tunnelExits, 5), 180000)
683
796
  }
684
797
 
685
798
  function stopPoolTimers() {
@@ -728,15 +841,15 @@ export async function joinPool(input = {}) {
728
841
  lastHeartbeat: 0,
729
842
  lastError: '',
730
843
  })
731
- await ensureCloudflared()
732
- const started = await startTunnel()
844
+ tunnelNextTry = 0
845
+ tunnelAttemptFails = 0
846
+ heartbeatFails = 0
733
847
  startPoolTimers()
734
- await heartbeat()
735
- if (!started) {
736
- poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: data.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
737
- return `设备已登记,但隧道没启动:${data.hostname || data.device_id}`
848
+ await heartbeat({ start: false })
849
+ void checkTunnel().catch((error) => logTunnel(`join background start failed: ${error?.message || error}`))
850
+ if (poolInfo.status !== '在线') {
851
+ return `设备已登记,隧道后台启动中:${data.hostname || data.device_id}`
738
852
  }
739
- poolInfo = { status: '在线', tone: 'good', hostname: data.hostname || '', lastError: '' }
740
853
  return `已接入设备池:${data.hostname || data.device_id}`
741
854
  })()
742
855
  try {
@@ -779,16 +892,11 @@ function bootPool() {
779
892
  poolInfo = { status: '未接入', tone: 'muted', hostname: '', lastError: '' }
780
893
  return
781
894
  }
782
- void (async () => {
783
- try {
784
- await ensureCloudflared()
785
- await startTunnel()
786
- startPoolTimers()
787
- await heartbeat()
788
- } catch (error) {
789
- poolInfo = { status: '接入异常', tone: 'bad', hostname: pool.hostname || '', lastError: human(error) }
790
- }
791
- })()
895
+ startPoolTimers()
896
+ void heartbeat().catch((error) => {
897
+ logTunnel(`boot heartbeat failed: ${error?.message || error}`)
898
+ poolInfo = { status: '接入异常', tone: 'bad', hostname: pool.hostname || '', lastError: human(error) }
899
+ })
792
900
  }
793
901
 
794
902
  async function buildState() {
@@ -956,9 +1064,9 @@ async function runCommand(command, args) {
956
1064
  })
957
1065
  }
958
1066
 
959
- async function fetchBuffer(url) {
1067
+ async function fetchBuffer(url, timeoutMs = DOWNLOAD_TIMEOUT_MS) {
960
1068
  const controller = new AbortController()
961
- const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)
1069
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
962
1070
  try {
963
1071
  const res = await fetch(url, { signal: controller.signal, redirect: 'follow' })
964
1072
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-opencode2api",
3
- "version": "1.3.5",
3
+ "version": "1.3.7",
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",