dsh-plugin-opencode2api 1.2.2 → 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
@@ -45,6 +45,20 @@ 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.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
+
48
62
  ## 使用
49
63
 
50
64
  装好后插件会自动把本地 API 注册成模型商「本地免费 API」,模型列表从 `/v1/models` 动态获取。直接在 DSH 的模型选择器里选它下面的免费模型即可,不需要手动填 URL 和 Key。
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' })
@@ -848,6 +1137,8 @@ function registerUi(ctx) {
848
1137
  { label: '局域网', value: { $: 'data.lanUrl' } },
849
1138
  { label: '模型', value: { $: 'data.models' } },
850
1139
  { label: '模型商', value: { $: 'data.provider' }, tone: { $: 'data.providerTone' } },
1140
+ { label: '设备池', value: { $: 'data.poolStatus' }, tone: { $: 'data.poolTone' } },
1141
+ { label: '池地址', value: { $: 'data.poolHost' } },
851
1142
  { label: '平台', value: { $: 'data.platform' } },
852
1143
  ],
853
1144
  },
@@ -875,6 +1166,13 @@ function registerUi(ctx) {
875
1166
  { label: '重装', action: 'reinstall' },
876
1167
  ],
877
1168
  },
1169
+ {
1170
+ type: 'actions',
1171
+ items: [
1172
+ { label: '退出设备池', action: 'leavePool' },
1173
+ { label: '立即心跳', action: 'poolSync' },
1174
+ ],
1175
+ },
878
1176
  {
879
1177
  type: 'actions',
880
1178
  items: [
@@ -1006,6 +1304,12 @@ function registerUi(ctx) {
1006
1304
  await autoConfigure(true)
1007
1305
  return { toast: autoInfo.tone === 'good' ? '模型商已配置' : autoInfo.status }
1008
1306
  }),
1307
+ leavePool: () => pendingWork('正在退出', async () => ({ toast: await leavePool() })),
1308
+ poolSync: () =>
1309
+ pendingWork('正在同步', async () => {
1310
+ await heartbeat()
1311
+ return { toast: poolInfo.status }
1312
+ }),
1009
1313
  },
1010
1314
  })
1011
1315
 
@@ -1038,11 +1342,15 @@ export function apply(ctx) {
1038
1342
  const bootTimer = setTimeout(() => {
1039
1343
  void boot()
1040
1344
  }, 1500)
1345
+ const poolTimer = setTimeout(() => {
1346
+ bootPool()
1347
+ }, 2500)
1041
1348
  const watchdog = setInterval(() => {
1042
1349
  if (desired && !busy) void boot()
1043
1350
  }, 30000)
1044
1351
  return () => {
1045
1352
  clearTimeout(bootTimer)
1353
+ clearTimeout(poolTimer)
1046
1354
  clearInterval(watchdog)
1047
1355
  }
1048
1356
  }, 'opencode2api autostart')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-opencode2api",
3
- "version": "1.2.2",
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",