dsh-plugin-opencode2api 1.3.3 → 1.3.4

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 +5 -1
  2. package/lib/index.js +102 -16
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -45,7 +45,7 @@ dsh plugin --profile web add dsh-plugin-opencode2api
45
45
 
46
46
  Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1:3080`)→ **设置 → 本地免费 API**,就能看到状态和操作按钮;手机 App 则在「本地API」胶囊/面板里。
47
47
 
48
- ## 接入云端设备池(1.3.3)
48
+ ## 接入云端设备池(1.3.4)
49
49
 
50
50
  如果你有一个自己的中转站(例如本项目作者的 oc-proxy),可以把这台设备变成它的一个后端,让中转站把请求分过来。
51
51
 
@@ -55,6 +55,10 @@ Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1
55
55
  - 桌面:设置 → 本地免费 API → **云端设备池** → 粘入接入码 → 加入设备池(服务器地址已默认填好,需要换服才展开「自定义服务器地址」);
56
56
  3. 插件会自动创建 Cloudflare 隧道、下载并启动 cloudflared、每 60 秒上报心跳。
57
57
 
58
+ 隧道固定走 `--protocol http2 --edge-ip-version 4`:手机网络经常把 QUIC 的 UDP 7844 掐掉,走 QUIC 会一直「握手超时」然后反复重连;换成 TCP 的 http2 稳很多。
59
+
60
+ 插件每 20 秒检查一次隧道真实连接数(cloudflared 的 `/ready`,只认已注册的连接):进程还在但一条都没连上就会重启,并且带指数退避,不会秒退秒起。心跳会把这个状态一起上报,中转站据此停止往断隧道的设备派请求。
61
+
58
62
  管理端看到设备「在线」后就会把请求分配过来。心跳超过 3 分钟没到会自动标记离线,重新上线自动恢复;长期不用时在管理端点「删除」会同时清理隧道和 DNS。
59
63
 
60
64
  退出:面板里点「退出设备池」,会同时从中转站删除这台设备。
package/lib/index.js CHANGED
@@ -310,17 +310,29 @@ function readJson(req) {
310
310
 
311
311
 
312
312
  // ---- 云端设备池 ----
313
- const PLUGIN_VERSION = '1.3.0'
313
+ const PLUGIN_VERSION = (() => {
314
+ try {
315
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
316
+ return String(pkg.version || '1.3.4')
317
+ } catch {
318
+ return '1.3.4'
319
+ }
320
+ })()
314
321
  const POOL = path.join(DATA, 'pool.json')
315
322
  const CLOUDFLARED = path.join(DATA, IS_WIN ? 'cloudflared.exe' : 'cloudflared')
316
323
  const TUNNEL_LOG = path.join(DATA, 'cloudflared.log')
317
324
  const TUNNEL_PID = path.join(DATA, 'cloudflared.pid')
325
+ const METRICS_PORT = Number(process.env.OCP_TUNNEL_METRICS_PORT || 20241)
318
326
 
319
327
  let poolInfo = { status: '未接入', tone: 'muted', hostname: '', lastError: '' }
320
328
  let tunnelChild = null
321
329
  let heartbeatTimer = null
322
330
  let tunnelTimer = null
323
331
  let joining = null
332
+ let heartbeatFails = 0
333
+ let tunnelDownStreak = 0
334
+ let tunnelNextTry = 0
335
+ let tunnelExits = 0
324
336
 
325
337
  function readPool() {
326
338
  try {
@@ -346,7 +358,10 @@ function poolSnapshot() {
346
358
  const age = pool.lastHeartbeat ? Date.now() - pool.lastHeartbeat : null
347
359
  if (pool.lastError) return { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
348
360
  if (age === null) return { status: '等待心跳', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
349
- if (age < 180000) return { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
361
+ if (age < 180000) {
362
+ if (!tunnelRunning()) return { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
363
+ return { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
364
+ }
350
365
  return { status: '离线', tone: 'bad', hostname: pool.hostname || '', lastError: '' }
351
366
  }
352
367
 
@@ -396,6 +411,35 @@ function tunnelRunning() {
396
411
  return false
397
412
  }
398
413
 
414
+ async function tunnelReady() {
415
+ try {
416
+ const res = await fetch(`http://127.0.0.1:${METRICS_PORT}/ready`, {
417
+ signal: AbortSignal.timeout(2500),
418
+ })
419
+ if (!res.ok) return { known: true, ok: false, connections: 0 }
420
+ const body = await res.json().catch(() => null)
421
+ const conn = Number(body?.readyConnections) || 0
422
+ return { known: true, ok: conn > 0, connections: conn }
423
+ } catch {
424
+ return { known: false, ok: false, connections: 0 }
425
+ }
426
+ }
427
+
428
+ function logTunnel(message) {
429
+ try {
430
+ fs.appendFileSync(TUNNEL_LOG, `${new Date().toISOString()} [plugin] ${message}\n`)
431
+ } catch {}
432
+ }
433
+
434
+ function tunnelArgs(token) {
435
+ const args = ['tunnel', '--no-autoupdate']
436
+ // 手机网络对 UDP 7844 很不友好,强制走 TCP/http2,省得 QUIC 一直握手失败
437
+ args.push('--protocol', 'http2', '--edge-ip-version', '4')
438
+ args.push('--metrics', `127.0.0.1:${METRICS_PORT}`)
439
+ args.push('run', '--token', token)
440
+ return args
441
+ }
442
+
399
443
  async function startTunnel() {
400
444
  const pool = readPool()
401
445
  if (!pool?.tunnelToken) return false
@@ -403,19 +447,23 @@ async function startTunnel() {
403
447
  if (!fs.existsSync(CLOUDFLARED)) await ensureCloudflared()
404
448
  const fd = fs.openSync(TUNNEL_LOG, 'a')
405
449
  try {
406
- tunnelChild = spawn(
407
- CLOUDFLARED,
408
- ['tunnel', '--no-autoupdate', 'run', '--token', pool.tunnelToken],
409
- { stdio: ['ignore', fd, fd], detached: false },
410
- )
450
+ tunnelChild = spawn(CLOUDFLARED, tunnelArgs(pool.tunnelToken), {
451
+ stdio: ['ignore', fd, fd],
452
+ detached: false,
453
+ })
411
454
  } finally {
412
455
  fs.closeSync(fd)
413
456
  }
414
- tunnelChild.once('error', () => {})
457
+ tunnelChild.once('error', (error) => logTunnel(`spawn error: ${error?.message || error}`))
458
+ tunnelChild.once('exit', (code, signal) => {
459
+ tunnelExits += 1
460
+ logTunnel(`cloudflared exit code=${code} signal=${signal || ''} total=${tunnelExits}`)
461
+ })
415
462
  tunnelChild.unref()
416
463
  try {
417
464
  fs.writeFileSync(TUNNEL_PID, String(tunnelChild.pid))
418
465
  } catch {}
466
+ logTunnel(`cloudflared started pid=${tunnelChild.pid} protocol=http2 edge=4 metrics=${METRICS_PORT}`)
419
467
  return true
420
468
  }
421
469
 
@@ -432,6 +480,7 @@ function stopTunnel() {
432
480
  } catch {}
433
481
  }
434
482
  tunnelChild = null
483
+ tunnelDownStreak = 0
435
484
  try {
436
485
  fs.unlinkSync(TUNNEL_PID)
437
486
  } catch {}
@@ -440,6 +489,7 @@ function stopTunnel() {
440
489
  export async function heartbeat() {
441
490
  const pool = readPool()
442
491
  if (!pool?.deviceId || !pool?.deviceSecret) return
492
+ const tunnel = await tunnelReady()
443
493
  try {
444
494
  const res = await fetch(`${pool.url}/api/device/heartbeat`, {
445
495
  method: 'POST',
@@ -451,8 +501,9 @@ export async function heartbeat() {
451
501
  body: JSON.stringify({
452
502
  version: PLUGIN_VERSION,
453
503
  platform: target() ? `${target().os}/${target().arch}` : process.platform,
504
+ tunnel: tunnel.known ? tunnel.ok : undefined,
454
505
  }),
455
- signal: AbortSignal.timeout(15000),
506
+ signal: AbortSignal.timeout(25000),
456
507
  })
457
508
  const data = await res.json().catch(() => ({}))
458
509
  if (res.status === 401) {
@@ -460,6 +511,7 @@ export async function heartbeat() {
460
511
  return
461
512
  }
462
513
  if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`)
514
+ heartbeatFails = 0
463
515
  pool.lastHeartbeat = Date.now()
464
516
  pool.lastError = ''
465
517
  writePool(pool)
@@ -468,12 +520,20 @@ export async function heartbeat() {
468
520
  poolInfo = { status: '已被管理端停用', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
469
521
  } else {
470
522
  void startTunnel()
471
- poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
523
+ if (tunnel.known && !tunnel.ok) {
524
+ poolInfo = { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
525
+ } else {
526
+ poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
527
+ }
472
528
  }
473
529
  } catch (error) {
474
- pool.lastError = human(error)
475
- writePool(pool)
476
- poolInfo = { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
530
+ heartbeatFails += 1
531
+ // 单次网络抖动不算掉线,连续两次失败才改状态,避免面板来回跳
532
+ if (heartbeatFails >= 2) {
533
+ pool.lastError = human(error)
534
+ writePool(pool)
535
+ poolInfo = { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
536
+ }
477
537
  }
478
538
  }
479
539
 
@@ -486,13 +546,39 @@ function startPoolTimers() {
486
546
  }
487
547
  if (!tunnelTimer) {
488
548
  tunnelTimer = setInterval(() => {
489
- const pool = readPool()
490
- if (pool?.tunnelToken && !tunnelRunning()) void startTunnel().catch(() => {})
491
- }, 45_000)
549
+ void checkTunnel()
550
+ }, 20_000)
492
551
  tunnelTimer.unref?.()
493
552
  }
494
553
  }
495
554
 
555
+ async function checkTunnel() {
556
+ const pool = readPool()
557
+ if (!pool?.tunnelToken) return
558
+ if (Date.now() < tunnelNextTry) return
559
+ const alive = tunnelRunning()
560
+ if (alive) {
561
+ const ready = await tunnelReady()
562
+ if (ready.ok) {
563
+ tunnelDownStreak = 0
564
+ return
565
+ }
566
+ // 进程在但一条连接都没连上:连续两次才动,别把刚起步的隧道掐掉
567
+ tunnelDownStreak += 1
568
+ if (tunnelDownStreak < 2) return
569
+ logTunnel(`tunnel unhealthy (connections=${ready.connections} known=${ready.known}), restarting`)
570
+ stopTunnel()
571
+ }
572
+ // 进程没了或确认不健康:重启并做指数退避,避免秒退秒起
573
+ tunnelDownStreak = 0
574
+ try {
575
+ await startTunnel()
576
+ } catch (error) {
577
+ logTunnel(`restart failed: ${error?.message || error}`)
578
+ }
579
+ tunnelNextTry = Date.now() + Math.min(5000 * 2 ** Math.min(tunnelExits, 5), 180000)
580
+ }
581
+
496
582
  function stopPoolTimers() {
497
583
  if (heartbeatTimer) clearInterval(heartbeatTimer)
498
584
  if (tunnelTimer) clearInterval(tunnelTimer)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-opencode2api",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
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",