dsh-plugin-opencode2api 1.3.6 → 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 +185 -97
  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,51 +409,77 @@ function existingBinaryOk(file) {
404
409
 
405
410
  async function ensureCloudflared() {
406
411
  if (existingBinaryOk(CLOUDFLARED)) return
407
- try {
408
- if (fs.existsSync(CLOUDFLARED)) {
409
- const size = fs.statSync(CLOUDFLARED).size
410
- logTunnel(`existing cloudflared invalid (size=${size}), re-downloading`)
411
- fs.unlinkSync(CLOUDFLARED)
412
+ const staged = `${CLOUDFLARED}.new`
413
+ if (existingBinaryOk(staged)) {
414
+ try {
415
+ fs.renameSync(staged, CLOUDFLARED)
416
+ if (!IS_WIN) fs.chmodSync(CLOUDFLARED, 0o755)
417
+ logTunnel('cloudflared staged binary promoted')
418
+ return
419
+ } catch (error) {
420
+ throw new Error(`替换 cloudflared 失败:${error.message}`)
412
421
  }
413
- } catch {}
414
- const t = cloudflaredTarget()
415
- let lastFailure = null
416
- for (const prefix of MIRRORS) {
422
+ }
423
+ if (cloudflaredPromise) return cloudflaredPromise
424
+ cloudflaredPromise = (async () => {
425
+ if (existingBinaryOk(CLOUDFLARED)) return
417
426
  try {
418
- const body = await fetchBuffer(`${prefix}https://github.com/cloudflare/cloudflared/releases/latest/download/${t.file}`)
419
- if (t.archive) {
420
- const temp = path.join(DATA, `.cf-${Date.now()}`)
421
- fs.mkdirSync(temp, { recursive: true })
422
- const archive = path.join(temp, t.file)
423
- await fsp.writeFile(archive, body)
424
- await extract(archive, temp)
425
- const found = findFile(temp, 'cloudflared')
426
- if (!found) throw new Error('cloudflared 解压失败')
427
- await fsp.copyFile(found, CLOUDFLARED)
428
- await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
429
- } else {
430
- if (!expectedMagicOk(body)) {
431
- throw new Error(`下载到的不是可执行文件(${body.length} 字节,多半是镜像错误页)`)
432
- }
433
- // 先写临时文件再改名:正在运行的旧 cloudflared 不会被写坏(Windows/Linux 都安全)
434
- const temp = `${CLOUDFLARED}.new`
435
- await fsp.writeFile(temp, body)
436
- if (!IS_WIN) fs.chmodSync(temp, 0o755)
437
- try {
438
- fs.renameSync(temp, CLOUDFLARED)
439
- } catch (error) {
440
- try { fs.unlinkSync(temp) } catch {}
441
- throw error
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
+ }
442
465
  }
466
+ if (!IS_WIN) fs.chmodSync(CLOUDFLARED, 0o755)
443
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(() => {})
444
474
  }
445
- if (!IS_WIN && t.archive) fs.chmodSync(CLOUDFLARED, 0o755)
446
- return
447
- } catch (error) {
448
- lastFailure = error
449
475
  }
476
+ throw lastFailure || new Error('cloudflared 下载失败')
477
+ })()
478
+ try {
479
+ await cloudflaredPromise
480
+ } finally {
481
+ cloudflaredPromise = null
450
482
  }
451
- throw lastFailure || new Error('cloudflared 下载失败')
452
483
  }
453
484
 
454
485
  function readTunnelPid() {
@@ -525,6 +556,16 @@ function tunnelArgs(token) {
525
556
  }
526
557
 
527
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() {
528
569
  const pool = readPool()
529
570
  if (!pool?.tunnelToken) return false
530
571
  if (await tunnelRunningVerified()) return true
@@ -532,7 +573,7 @@ async function startTunnel() {
532
573
  logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
533
574
  try { fs.unlinkSync(TUNNEL_PID) } catch {}
534
575
  }
535
- if (!fs.existsSync(CLOUDFLARED)) await ensureCloudflared()
576
+ if (!existingBinaryOk(CLOUDFLARED)) await ensureCloudflared()
536
577
  let fd = null
537
578
  try {
538
579
  fd = fs.openSync(TUNNEL_LOG, 'a')
@@ -553,6 +594,11 @@ async function startTunnel() {
553
594
  try { fs.closeSync(fd) } catch {}
554
595
  }
555
596
  }
597
+ if (!child.pid) {
598
+ logTunnel('cloudflared spawn failed: no pid')
599
+ tunnelChild = null
600
+ return false
601
+ }
556
602
  child.once('error', (error) => logTunnel(`spawn error: ${error?.message || error}`))
557
603
  child.once('exit', (code, signal) => {
558
604
  tunnelExits += 1
@@ -594,9 +640,10 @@ async function stopTunnel() {
594
640
  } catch {}
595
641
  }
596
642
 
597
- export async function heartbeat() {
643
+ export async function heartbeat(options = {}) {
644
+ const startTunnelNow = options.start !== false
598
645
  const pool = readPool()
599
- if (!pool?.deviceId || !pool?.deviceSecret) return
646
+ if (!pool?.deviceId || !pool?.deviceSecret) return false
600
647
  const tunnel = await tunnelReady()
601
648
  tunnelState = {
602
649
  ok: tunnel.ok,
@@ -614,14 +661,14 @@ export async function heartbeat() {
614
661
  body: JSON.stringify({
615
662
  version: PLUGIN_VERSION,
616
663
  platform: target() ? `${target().os}/${target().arch}` : process.platform,
617
- tunnel: tunnel.known ? tunnel.ok : undefined,
664
+ tunnel: tunnel.known ? tunnel.ok : false,
618
665
  }),
619
666
  signal: AbortSignal.timeout(25000),
620
667
  })
621
668
  const data = await res.json().catch(() => ({}))
622
669
  if (res.status === 401) {
623
670
  resetPoolLocally(data.error || '设备已被移除')
624
- return
671
+ return false
625
672
  }
626
673
  if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`)
627
674
  heartbeatFails = 0
@@ -631,15 +678,17 @@ export async function heartbeat() {
631
678
  if (data.enabled === false) {
632
679
  void stopTunnel()
633
680
  poolInfo = { status: '已被管理端停用', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
634
- } else {
635
- const started = await startTunnel()
636
- if (!started) {
637
- poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: pool.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
638
- } 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) {
639
687
  poolInfo = { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
640
688
  } else {
641
- poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
689
+ poolInfo = { status: '隧道启动中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
642
690
  }
691
+ return true
643
692
  }
644
693
  } catch (error) {
645
694
  heartbeatFails += 1
@@ -649,6 +698,37 @@ export async function heartbeat() {
649
698
  writePool(pool)
650
699
  poolInfo = { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
651
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
652
732
  }
653
733
  }
654
734
 
@@ -668,38 +748,51 @@ function startPoolTimers() {
668
748
  }
669
749
 
670
750
  async function checkTunnel() {
671
- const pool = readPool()
672
- if (!pool?.tunnelToken) return
673
- if (Date.now() < tunnelNextTry) return
674
- const running = await tunnelRunningVerified()
675
- if (running) {
676
- const ready = await tunnelReady()
677
- tunnelState = {
678
- ok: ready.ok,
679
- at: Date.now(),
680
- 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 {}
681
778
  }
682
- if (ready.ok) {
683
- tunnelDownStreak = 0
684
- 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 启动失败' }
685
790
  }
686
- // 进程在但一条连接都没连上:连续两次才动,别把刚起步的隧道掐掉
687
- tunnelDownStreak += 1
688
- if (tunnelDownStreak < 2) return
689
- logTunnel(`tunnel unhealthy (connections=${ready.connections} known=${ready.known}), restarting`)
690
- await stopTunnel()
691
- } else if (tunnelRunning()) {
692
- logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
693
- 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
694
795
  }
695
- // 进程没了或确认不健康:重启并做指数退避,避免秒退秒起
696
- tunnelDownStreak = 0
697
- const started = await startTunnel().catch((error) => {
698
- logTunnel(`restart failed: ${error?.message || error}`)
699
- return false
700
- })
701
- if (!started) tunnelState = { ok: false, at: Date.now(), reason: 'cloudflared 启动失败' }
702
- tunnelNextTry = Date.now() + Math.min(5000 * 2 ** Math.min(tunnelExits, 5), 180000)
703
796
  }
704
797
 
705
798
  function stopPoolTimers() {
@@ -748,15 +841,15 @@ export async function joinPool(input = {}) {
748
841
  lastHeartbeat: 0,
749
842
  lastError: '',
750
843
  })
751
- await ensureCloudflared()
752
- const started = await startTunnel()
844
+ tunnelNextTry = 0
845
+ tunnelAttemptFails = 0
846
+ heartbeatFails = 0
753
847
  startPoolTimers()
754
- await heartbeat()
755
- if (!started) {
756
- poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: data.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
757
- 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}`
758
852
  }
759
- poolInfo = { status: '在线', tone: 'good', hostname: data.hostname || '', lastError: '' }
760
853
  return `已接入设备池:${data.hostname || data.device_id}`
761
854
  })()
762
855
  try {
@@ -799,16 +892,11 @@ function bootPool() {
799
892
  poolInfo = { status: '未接入', tone: 'muted', hostname: '', lastError: '' }
800
893
  return
801
894
  }
802
- void (async () => {
803
- try {
804
- await ensureCloudflared()
805
- await startTunnel()
806
- startPoolTimers()
807
- await heartbeat()
808
- } catch (error) {
809
- poolInfo = { status: '接入异常', tone: 'bad', hostname: pool.hostname || '', lastError: human(error) }
810
- }
811
- })()
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
+ })
812
900
  }
813
901
 
814
902
  async function buildState() {
@@ -976,9 +1064,9 @@ async function runCommand(command, args) {
976
1064
  })
977
1065
  }
978
1066
 
979
- async function fetchBuffer(url) {
1067
+ async function fetchBuffer(url, timeoutMs = DOWNLOAD_TIMEOUT_MS) {
980
1068
  const controller = new AbortController()
981
- const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)
1069
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
982
1070
  try {
983
1071
  const res = await fetch(url, { signal: controller.signal, redirect: 'follow' })
984
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.6",
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",