dsh-plugin-opencode2api 1.1.0 → 1.2.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,13 @@
2
2
 
3
3
  一键把 [opencode2api](https://github.com/jasonxu114514/opencode2api) 装进 DSH:自动下载对应平台的程序、生成配置、启动并常驻,并自动把「本地免费 API」注册成 DSH 的模型商(模型列表从网关动态获取)。装好后本机就有一个专属的、兼容 OpenAI 的免费 API;DSH 关闭再打开会自动重启。
4
4
 
5
+ ## 1.2.1 更新
6
+
7
+ - 修复停止/重启:按端口反查并终止进程(Windows `netstat` + `taskkill`,macOS/Linux/Android 用 `lsof`/`fuser`/`/proc`),不再依赖可能丢失的 pid 文件;启动改为健康检查通过才算成功,并自动接管已有健康实例。
8
+ - 手机面板补齐「打开后台」「查看日志」「项目主页」,与桌面设置页功能一致。
9
+ - 推荐模型改为 `big-pickle`(`deepseek-v4.1-flash-free` 更易触发上游匿名通道限流)。
10
+ - 内置 opencode2api 版本仍固定为 v1.5.1;可用环境变量 `OPENCODE2API_VERSION` 覆盖后重装。
11
+
5
12
  ## 适用平台
6
13
 
7
14
  | 平台 | 架构 | 状态 |
@@ -14,21 +21,29 @@
14
21
 
15
22
  ## 安装
16
23
 
17
- 在 DSH 的插件市场搜索 `dsh-plugin-opencode2api` 安装;或命令行:
24
+ 最方便的是 npm(已发布,国内镜像已同步):
18
25
 
19
26
  ```sh
20
- dsh plugin --profile web add github:king-andthe-nice/dsh-plugin-opencode2api
27
+ dsh plugin --profile web add dsh-plugin-opencode2api
21
28
  ```
22
29
 
23
- > npm 版发布后也可以 `dsh plugin --profile web add dsh-plugin-opencode2api`。
30
+ 其他方式:
31
+
32
+ | 方式 | 命令 | 前提 |
33
+ |---|---|---|
34
+ | 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` |
24
37
 
25
38
  装好后引擎会自动下载程序(约 5 MB)、生成配置并在 `0.0.0.0:8080` 启动(本机和局域网都能连)。首次下载失败会每 30 秒重试。
26
39
 
40
+ Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1:3080`)→ **设置 → 本地免费 API**,就能看到状态和操作按钮;手机 App 则在「本地API」胶囊/面板里。
41
+
27
42
  ## 使用
28
43
 
29
44
  装好后插件会自动把本地 API 注册成模型商「本地免费 API」,模型列表从 `/v1/models` 动态获取。直接在 DSH 的模型选择器里选它下面的免费模型即可,不需要手动填 URL 和 Key。
30
45
 
31
- 面板会显示「模型商:已自动配置」。如果没配上,点面板里的「自动配置」重试;仍然失败时再手动接入:
46
+ 桌面端在 **设置 → 本地免费 API** 里操作;手机端在「本地API」面板里操作。面板会显示「模型商:已自动配置」。如果没配上,点面板里的「自动配置」重试;仍然失败时再手动接入:
32
47
 
33
48
  1. 打开「本地免费 API」面板。
34
49
  2. 点「复制接入」,得到:
@@ -37,18 +52,36 @@ dsh plugin --profile web add github:king-andthe-nice/dsh-plugin-opencode2api
37
52
  本机:http://127.0.0.1:8080/v1
38
53
  局域网:http://<你的局域网IP>:8080/v1
39
54
  API Key:<随机生成>
40
- 推荐模型:deepseek-v4.1-flash-free
55
+ 推荐模型:big-pickle
41
56
  ```
42
57
 
43
58
  3. 在 DSH 里添加 OpenAI 兼容服务商,Base URL 填上面的地址,API Key 填生成的 Key。
44
59
 
45
- ## 面板功能
60
+ ## 功能(桌面设置页 / 手机面板)
46
61
 
47
62
  - **启动 / 停止 / 重启 / 重装**:重装会重新下载程序。
48
63
  - **仅本机 / 开局域网**:切换监听地址(`127.0.0.1` 或 `0.0.0.0`)。
49
- - **复制接入 / 复制后台**:复制 API 接入信息或管理后台地址与密码。
64
+ - **复制地址 / 复制 Key / 复制后台信息 / 打开后台**:桌面设置页与手机面板都提供。
50
65
  - **自动配置**:重新把本地 API 注册为模型商「本地免费 API」,并同步最新模型列表。
51
- - 状态条实时显示运行状态,进程挂掉会自动拉起。
66
+ - **运行日志**:桌面设置页可展开查看最后 40 行;手机面板新增「查看日志」,也可看数据目录里的 `opencode2api.log`。
67
+ - 状态实时显示;进程挂掉会自动拉起。
68
+
69
+ ## 界面说明
70
+
71
+ - **Windows / macOS / Linux(DSH Web UI)**:**设置 → 本地免费 API**,有状态、启动/停止/重启、监听切换、复制地址/Key、自动配置、重装和日志。
72
+ - **dsh-go 手机 App**:有「本地API」胶囊、状态条和原生面板。
73
+ - dsh-go 原生界面(胶囊/状态条/面板)只存在于手机 App;桌面端用的是 DSH Web UI 的设置页,不是 dsh-go 原生面板。
74
+
75
+ ### Windows 装完看不到界面?
76
+
77
+ 1. 先确认插件已装:DSH Web UI → 插件 → **已安装**,应看到 `dsh-plugin-opencode2api`。
78
+ 2. 打开 **设置 → 本地免费 API**(1.2.0 起提供桌面设置页)。1.1.0 只有手机原生面板,桌面没有界面。
79
+ 3. 如果插件市场里标着「本地开发」,说明装的是本地链接;想用 npm 版先移除再装,然后重启 DSH:
80
+
81
+ ```powershell
82
+ dsh plugin --profile web remove dsh-plugin-opencode2api
83
+ dsh plugin --profile web add dsh-plugin-opencode2api
84
+ ```
52
85
 
53
86
  ## 自动配置
54
87
 
@@ -63,7 +96,7 @@ dsh plugin --profile web add github:king-andthe-nice/dsh-plugin-opencode2api
63
96
 
64
97
  ## 管理后台
65
98
 
66
- 浏览器打开 `http://127.0.0.1:8081`(或局域网地址),账号 `admin`,初始密码见面板「复制后台」,也可在后台修改。后台可以改密码、查看请求、管理上游 Key 等。
99
+ 浏览器打开 `http://127.0.0.1:8081`(或局域网地址),账号 `admin`,初始密码见桌面设置页(仅本机显示)或 `webui-password.txt`;后台改过后以新密码为准。后台可以改密码、查看请求、管理上游 Key 等。
67
100
 
68
101
  ## 数据目录
69
102
 
package/lib/client.js ADDED
@@ -0,0 +1,468 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-plugin-opencode2api',
3
+ factory: require => {
4
+ const module = { exports: {} }
5
+ const exports = module.exports
6
+ const React = require('react')
7
+ const { createElement: h, useCallback, useEffect, useState } = React
8
+ const inject = ['slots']
9
+
10
+ const TONE = {
11
+ good: 'var(--dsw-alias-state-success-primary)',
12
+ warn: 'var(--dsw-alias-state-warning-primary)',
13
+ bad: 'var(--dsw-alias-state-error-primary)',
14
+ info: 'var(--dsw-alias-state-business-primary)',
15
+ muted: 'var(--dsw-alias-label-tertiary)',
16
+ }
17
+
18
+ const CSS = `
19
+ .oc2a button:hover:not(:disabled) { filter: brightness(1.08); }
20
+ .oc2a code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 11px; background: var(--dsw-alias-bg-layer-2); padding: 1px 4px; border-radius: 4px; }
21
+ .oc2a summary { user-select: none; }
22
+ `
23
+
24
+ const calloutStyle = {
25
+ border: '1px solid var(--dsw-alias-border-l1)',
26
+ borderRadius: 9,
27
+ padding: '9px 11px',
28
+ margin: '8px 0',
29
+ fontSize: 12,
30
+ lineHeight: 1.6,
31
+ background: 'var(--dsw-alias-bg-layer-1)',
32
+ }
33
+
34
+ async function request(path, init) {
35
+ const res = await fetch(`/api/opencode2api${path}`, init)
36
+ const text = await res.text()
37
+ let data = null
38
+ try {
39
+ data = text ? JSON.parse(text) : null
40
+ } catch {
41
+ data = null
42
+ }
43
+ if (!res.ok) throw new Error(data?.error || text || `HTTP ${res.status}`)
44
+ return data
45
+ }
46
+
47
+ function useCopy() {
48
+ const [copied, setCopied] = useState('')
49
+ const copy = useCallback(async (label, value) => {
50
+ try {
51
+ await navigator.clipboard.writeText(value)
52
+ } catch {
53
+ const area = document.createElement('textarea')
54
+ area.value = value
55
+ document.body.appendChild(area)
56
+ area.select()
57
+ try {
58
+ document.execCommand('copy')
59
+ } catch {}
60
+ area.remove()
61
+ }
62
+ setCopied(label)
63
+ setTimeout(() => setCopied(''), 1500)
64
+ }, [])
65
+ return [copied, copy]
66
+ }
67
+
68
+ function Button({ children, onClick, disabled, primary }) {
69
+ return h(
70
+ 'button',
71
+ {
72
+ type: 'button',
73
+ onClick,
74
+ disabled,
75
+ style: {
76
+ appearance: 'none',
77
+ border: primary ? 'none' : '1px solid var(--dsw-alias-border-l1)',
78
+ background: primary
79
+ ? 'var(--dsw-alias-state-business-primary)'
80
+ : 'var(--dsw-alias-bg-layer-2)',
81
+ color: primary
82
+ ? 'var(--dsw-alias-label-on-accent)'
83
+ : 'var(--dsw-alias-label-primary)',
84
+ borderRadius: 8,
85
+ padding: '7px 12px',
86
+ font: 'inherit',
87
+ fontSize: 13,
88
+ cursor: disabled ? 'not-allowed' : 'pointer',
89
+ opacity: disabled ? 0.55 : 1,
90
+ },
91
+ },
92
+ children,
93
+ )
94
+ }
95
+
96
+ function Metric({ label, value, tone }) {
97
+ return h(
98
+ 'div',
99
+ {
100
+ style: {
101
+ border: '1px solid var(--dsw-alias-border-l1)',
102
+ borderRadius: 10,
103
+ padding: '10px 12px',
104
+ background: 'var(--dsw-alias-bg-layer-1)',
105
+ minWidth: 0,
106
+ },
107
+ },
108
+ h(
109
+ 'div',
110
+ {
111
+ style: {
112
+ fontSize: 11,
113
+ color: 'var(--dsw-alias-label-tertiary)',
114
+ marginBottom: 4,
115
+ },
116
+ },
117
+ label,
118
+ ),
119
+ h(
120
+ 'div',
121
+ {
122
+ style: {
123
+ fontSize: 13,
124
+ fontWeight: 600,
125
+ color: tone || 'var(--dsw-alias-label-primary)',
126
+ overflowWrap: 'anywhere',
127
+ },
128
+ },
129
+ value,
130
+ ),
131
+ )
132
+ }
133
+
134
+ function Page() {
135
+ const [state, setState] = useState(null)
136
+ const [error, setError] = useState('')
137
+ const [busy, setBusy] = useState('')
138
+ const [copied, copy] = useCopy()
139
+
140
+ const load = useCallback(async () => {
141
+ try {
142
+ setState(await request('/state'))
143
+ setError('')
144
+ } catch (err) {
145
+ setError(String(err?.message || err))
146
+ }
147
+ }, [])
148
+
149
+ useEffect(() => {
150
+ void load()
151
+ const timer = setInterval(load, 5000)
152
+ return () => clearInterval(timer)
153
+ }, [load])
154
+
155
+ const act = async action => {
156
+ setBusy(action)
157
+ setError('')
158
+ try {
159
+ const result = await request('/action', {
160
+ method: 'POST',
161
+ headers: { 'content-type': 'application/json' },
162
+ body: JSON.stringify({ action }),
163
+ })
164
+ if (result?.state) setState(result.state)
165
+ else void load()
166
+ } catch (err) {
167
+ setError(String(err?.message || err))
168
+ } finally {
169
+ setBusy('')
170
+ }
171
+ }
172
+
173
+ const tone = state
174
+ ? TONE[state.tone] || 'var(--dsw-alias-label-secondary)'
175
+ : 'var(--dsw-alias-label-secondary)'
176
+ const running = state?.running === true
177
+ const installed = state?.installed === true
178
+ const statusText = state
179
+ ? state.state || (running ? '运行中' : installed ? '已停止' : '未安装')
180
+ : '读取中…'
181
+ const disabled = busy !== ''
182
+ const secretHidden = state?.keyHidden === true
183
+
184
+ return h(
185
+ 'div',
186
+ {
187
+ className: 'oc2a',
188
+ style: {
189
+ padding: '18px 20px 28px',
190
+ maxWidth: 820,
191
+ color: 'var(--dsw-alias-label-primary)',
192
+ },
193
+ },
194
+ h('style', null, CSS),
195
+ h(
196
+ 'div',
197
+ {
198
+ style: {
199
+ display: 'flex',
200
+ alignItems: 'center',
201
+ gap: 10,
202
+ flexWrap: 'wrap',
203
+ marginBottom: 4,
204
+ },
205
+ },
206
+ h('div', { style: { fontSize: 18, fontWeight: 700 } }, '本地免费 API'),
207
+ h(
208
+ 'span',
209
+ {
210
+ style: {
211
+ display: 'inline-flex',
212
+ alignItems: 'center',
213
+ gap: 6,
214
+ fontSize: 12,
215
+ color: tone,
216
+ },
217
+ },
218
+ h('span', {
219
+ style: {
220
+ width: 7,
221
+ height: 7,
222
+ borderRadius: 99,
223
+ background: tone,
224
+ },
225
+ }),
226
+ statusText,
227
+ ),
228
+ ),
229
+ h(
230
+ 'div',
231
+ {
232
+ style: {
233
+ fontSize: 12,
234
+ color: 'var(--dsw-alias-label-tertiary)',
235
+ marginBottom: 14,
236
+ },
237
+ },
238
+ 'opencode2api · 自动下载、启动、掉线拉起;模型商自动配置,无需手动填 URL 和 Key。',
239
+ ),
240
+ error
241
+ ? h(
242
+ 'div',
243
+ {
244
+ style: {
245
+ ...calloutStyle,
246
+ borderColor: 'var(--dsw-alias-state-error-primary)',
247
+ color: 'var(--dsw-alias-state-error-primary)',
248
+ },
249
+ },
250
+ error,
251
+ )
252
+ : null,
253
+ state?.note
254
+ ? h(
255
+ 'div',
256
+ {
257
+ style: {
258
+ ...calloutStyle,
259
+ borderColor:
260
+ state.noteTone === 'warn'
261
+ ? 'var(--dsw-alias-state-warning-primary)'
262
+ : 'var(--dsw-alias-border-l1)',
263
+ color:
264
+ state.noteTone === 'warn'
265
+ ? 'var(--dsw-alias-state-warning-primary)'
266
+ : 'var(--dsw-alias-label-secondary)',
267
+ },
268
+ },
269
+ state.note,
270
+ )
271
+ : null,
272
+ h(
273
+ 'div',
274
+ {
275
+ style: {
276
+ display: 'grid',
277
+ gridTemplateColumns:
278
+ 'repeat(auto-fit, minmax(170px, 1fr))',
279
+ gap: 10,
280
+ margin: '14px 0',
281
+ },
282
+ },
283
+ h(Metric, { label: '本机地址', value: state?.baseUrl || '—' }),
284
+ h(Metric, { label: '局域网', value: state?.lanUrl || '—' }),
285
+ h(Metric, { label: '模型数', value: state?.models || '—' }),
286
+ h(Metric, {
287
+ label: '模型商',
288
+ value: state?.provider || '—',
289
+ tone: TONE[state?.providerTone] || undefined,
290
+ }),
291
+ h(Metric, { label: '监听', value: state?.listenMode || '—' }),
292
+ h(Metric, { label: '平台', value: state?.platform || '—' }),
293
+ ),
294
+ h(
295
+ 'div',
296
+ {
297
+ style: {
298
+ display: 'flex',
299
+ flexWrap: 'wrap',
300
+ gap: 8,
301
+ marginBottom: 10,
302
+ },
303
+ },
304
+ running
305
+ ? h(Button, { onClick: () => act('stop'), disabled }, '停止')
306
+ : h(
307
+ Button,
308
+ {
309
+ primary: true,
310
+ onClick: () => act('start'),
311
+ disabled,
312
+ },
313
+ busy === 'start' ? '启动中…' : '启动',
314
+ ),
315
+ h(Button, { onClick: () => act('restart'), disabled }, '重启'),
316
+ h(Button, { onClick: () => act('listenLocal'), disabled }, '仅本机'),
317
+ h(Button, { onClick: () => act('listenLan'), disabled }, '开局域网'),
318
+ h(
319
+ Button,
320
+ { onClick: () => act('autoConfig'), disabled },
321
+ busy === 'autoConfig' ? '配置中…' : '自动配置',
322
+ ),
323
+ h(Button, { onClick: () => act('reinstall'), disabled }, '重装'),
324
+ ),
325
+ h(
326
+ 'div',
327
+ {
328
+ style: {
329
+ display: 'flex',
330
+ flexWrap: 'wrap',
331
+ gap: 8,
332
+ marginBottom: 14,
333
+ },
334
+ },
335
+ h(
336
+ Button,
337
+ {
338
+ onClick: () => void copy('本机地址', state?.baseUrl || ''),
339
+ disabled: !state?.baseUrl,
340
+ },
341
+ copied === '本机地址' ? '已复制地址' : '复制地址',
342
+ ),
343
+ h(
344
+ Button,
345
+ {
346
+ onClick: () => void copy('Key', state?.key || ''),
347
+ disabled: !state?.key,
348
+ },
349
+ secretHidden
350
+ ? 'Key 仅本机可见'
351
+ : copied === 'Key'
352
+ ? '已复制 Key'
353
+ : '复制 Key',
354
+ ),
355
+ h(
356
+ Button,
357
+ {
358
+ onClick: () =>
359
+ window.open(
360
+ state?.webUrl || 'http://127.0.0.1:8081',
361
+ '_blank',
362
+ 'noopener',
363
+ ),
364
+ },
365
+ '打开后台',
366
+ ),
367
+ h(
368
+ Button,
369
+ {
370
+ onClick: () =>
371
+ window.open(
372
+ 'https://github.com/king-andthe-nice/dsh-plugin-opencode2api',
373
+ '_blank',
374
+ 'noopener',
375
+ ),
376
+ },
377
+ '项目主页',
378
+ ),
379
+ ),
380
+ h(
381
+ 'div',
382
+ {
383
+ style: {
384
+ fontSize: 12,
385
+ color: 'var(--dsw-alias-label-tertiary)',
386
+ lineHeight: 1.7,
387
+ marginBottom: 12,
388
+ },
389
+ },
390
+ 'DSH 模型选择器里应出现「本地免费 API」。后台账号 admin,密码见 ',
391
+ h('code', null, state?.webPasswordPath || 'webui-password.txt'),
392
+ secretHidden || !state?.password
393
+ ? null
394
+ : h('span', null, ';当前密码:', h('code', null, state.password)),
395
+ ),
396
+ h(
397
+ 'details',
398
+ {
399
+ style: {
400
+ borderTop: '1px solid var(--dsw-alias-border-l1)',
401
+ paddingTop: 10,
402
+ },
403
+ },
404
+ h(
405
+ 'summary',
406
+ {
407
+ style: {
408
+ cursor: 'pointer',
409
+ fontSize: 12,
410
+ color: 'var(--dsw-alias-label-secondary)',
411
+ },
412
+ },
413
+ '运行日志',
414
+ ),
415
+ h(
416
+ 'pre',
417
+ {
418
+ style: {
419
+ margin: '8px 0 0',
420
+ padding: 10,
421
+ borderRadius: 8,
422
+ background: 'var(--dsw-alias-bg-layer-2)',
423
+ color: 'var(--dsw-alias-label-secondary)',
424
+ fontSize: 11,
425
+ lineHeight: 1.55,
426
+ whiteSpace: 'pre-wrap',
427
+ wordBreak: 'break-all',
428
+ maxHeight: 220,
429
+ overflow: 'auto',
430
+ },
431
+ },
432
+ state?.log || '暂无日志',
433
+ ),
434
+ ),
435
+ h(
436
+ 'div',
437
+ {
438
+ style: {
439
+ marginTop: 12,
440
+ fontSize: 11,
441
+ color: 'var(--dsw-alias-label-tertiary)',
442
+ },
443
+ },
444
+ '网关来自 opencode2api(GPL-3.0-or-later)官方 Release,本插件不打包、不修改它。',
445
+ ),
446
+ )
447
+ }
448
+
449
+ function apply(ctx) {
450
+ ctx.slots.inject('settings.section', () =>
451
+ ctx.slots.register(
452
+ {
453
+ name: 'settings.section',
454
+ id: 'opencode2api',
455
+ order: 36,
456
+ label: () => '本地免费 API',
457
+ },
458
+ () => h(Page),
459
+ ),
460
+ )
461
+ }
462
+
463
+ exports.apply = apply
464
+ exports.inject = inject
465
+ exports.name = 'opencode2api'
466
+ return module.exports
467
+ },
468
+ })
package/lib/index.js CHANGED
@@ -270,6 +270,151 @@ async function autoConfigure(force = false) {
270
270
  autoInfo = { status: '已自动配置', tone: 'good' }
271
271
  }
272
272
 
273
+ function tailLog(lines = 40) {
274
+ try {
275
+ const stat = fs.statSync(LOG)
276
+ const start = Math.max(0, stat.size - 32 * 1024)
277
+ const fd = fs.openSync(LOG, 'r')
278
+ const buffer = Buffer.alloc(stat.size - start)
279
+ try {
280
+ fs.readSync(fd, buffer, 0, buffer.length, start)
281
+ } finally {
282
+ fs.closeSync(fd)
283
+ }
284
+ return buffer.toString('utf8').split('\n').slice(-lines).join('\n')
285
+ } catch {
286
+ return ''
287
+ }
288
+ }
289
+
290
+ function readJson(req) {
291
+ return new Promise((resolve, reject) => {
292
+ let body = ''
293
+ req.on('data', (chunk) => {
294
+ body += chunk
295
+ if (body.length > 1024 * 1024) {
296
+ req.destroy()
297
+ reject(new Error('请求过大'))
298
+ }
299
+ })
300
+ req.on('end', () => {
301
+ try {
302
+ resolve(body ? JSON.parse(body) : {})
303
+ } catch (error) {
304
+ reject(error)
305
+ }
306
+ })
307
+ req.on('error', reject)
308
+ })
309
+ }
310
+
311
+ async function buildState() {
312
+ const snap = await snapshot()
313
+ const cfg = fs.existsSync(CFG) ? readConfig() : {}
314
+ return {
315
+ ...snap,
316
+ running: Boolean(await health()),
317
+ installed: fs.existsSync(BIN),
318
+ key: cfg.server_keys?.[0] || '',
319
+ password: readPassword(),
320
+ webPasswordPath: PASS,
321
+ apiPort: API_PORT,
322
+ webPort: WEB_PORT,
323
+ listen: cfg.listen || '',
324
+ log: tailLog(40),
325
+ autoError: lastAutoError,
326
+ version: VERSION,
327
+ time: Date.now(),
328
+ }
329
+ }
330
+
331
+ async function runAction(action) {
332
+ switch (action) {
333
+ case 'start':
334
+ desired = true
335
+ return (await start()) ? '已启动' : '启动失败,看日志'
336
+ case 'stop':
337
+ return (await stop()) ? '已停止' : '停止失败'
338
+ case 'restart': {
339
+ const ok = await restart()
340
+ if (ok) void autoConfigure().catch(() => {})
341
+ return ok ? '已重启' : '重启失败,看日志'
342
+ }
343
+ case 'listenLocal':
344
+ case 'listenLan': {
345
+ setListen(action === 'listenLocal' ? '127.0.0.1' : '0.0.0.0')
346
+ desired = true
347
+ await killProcess()
348
+ const ok = await start()
349
+ return ok ? (action === 'listenLocal' ? '已仅本机监听' : '已开局域网') : '切换失败'
350
+ }
351
+ case 'autoConfig':
352
+ await autoConfigure(true)
353
+ return autoInfo.status
354
+ case 'reinstall':
355
+ void (async () => {
356
+ busy = true
357
+ try {
358
+ desired = true
359
+ await killProcess()
360
+ await ensureInstalled(true)
361
+ await start()
362
+ lastError = ''
363
+ void autoConfigure().catch(() => {})
364
+ } catch (error) {
365
+ lastError = human(error)
366
+ } finally {
367
+ busy = false
368
+ }
369
+ })()
370
+ return '后台重装中…'
371
+ default:
372
+ throw new Error('未知操作')
373
+ }
374
+ }
375
+
376
+ async function api(req, res) {
377
+ const url = new URL(req.url ?? '/', 'http://localhost')
378
+ const route = url.pathname.replace(/^\/api\/opencode2api/, '').replace(/\/+$/, '') || '/'
379
+ const method = String(req.method ?? 'GET').toUpperCase()
380
+ const send = (status, payload) => {
381
+ res.writeHead(status, {
382
+ 'content-type': 'application/json; charset=utf-8',
383
+ 'cache-control': 'no-store',
384
+ })
385
+ res.end(JSON.stringify(payload))
386
+ }
387
+ const address = req.socket?.remoteAddress ?? ''
388
+ const local = address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
389
+ const origin = String(req.headers.origin || '')
390
+ if (origin && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/i.test(origin)) {
391
+ return send(403, { error: 'forbidden' })
392
+ }
393
+ try {
394
+ if (method === 'GET' && route === '/state') {
395
+ const state = await buildState()
396
+ if (!local) {
397
+ state.key = ''
398
+ state.password = ''
399
+ state.keyHidden = true
400
+ }
401
+ return send(200, state)
402
+ }
403
+ if (method === 'GET' && route === '/log') {
404
+ return send(200, { log: tailLog(Number(url.searchParams.get('lines')) || 120) })
405
+ }
406
+ if (method === 'POST' && route === '/action') {
407
+ if (!local) return send(403, { error: '仅本机可操作' })
408
+ const body = await readJson(req)
409
+ const toast = await runAction(String(body.action || ''))
410
+ return send(200, { ok: true, toast, state: await buildState() })
411
+ }
412
+ return send(404, { error: 'not found' })
413
+ } catch (error) {
414
+ return send(500, { error: human(error) })
415
+ }
416
+ }
417
+
273
418
  function setListen(host) {
274
419
  const cfg = readConfig()
275
420
  cfg.listen = `${host}:${API_PORT}`
@@ -429,6 +574,97 @@ function alive(pid) {
429
574
  }
430
575
  }
431
576
 
577
+ function execLines(command, args) {
578
+ return new Promise((resolve) => {
579
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'ignore'] })
580
+ let out = ''
581
+ child.stdout?.on('data', (chunk) => { out += chunk })
582
+ child.once('error', () => resolve(''))
583
+ child.once('close', () => resolve(out))
584
+ })
585
+ }
586
+
587
+ function pidsFromProc(port) {
588
+ const result = []
589
+ try {
590
+ const hex = port.toString(16).toUpperCase().padStart(4, '0')
591
+ const inodes = new Set()
592
+ for (const file of ['/proc/net/tcp', '/proc/net/tcp6']) {
593
+ for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/).slice(1)) {
594
+ const cols = line.trim().split(/\s+/)
595
+ if (cols.length < 10 || cols[3] !== '0A') continue
596
+ if (String(cols[1] || '').split(':')[1]?.toUpperCase() !== hex) continue
597
+ inodes.add(cols[9])
598
+ }
599
+ }
600
+ if (!inodes.size) return result
601
+ for (const dir of fs.readdirSync('/proc')) {
602
+ if (!/^\d+$/.test(dir)) continue
603
+ try {
604
+ for (const fd of fs.readdirSync(`/proc/${dir}/fd`)) {
605
+ let link = ''
606
+ try { link = fs.readlinkSync(`/proc/${dir}/fd/${fd}`) } catch {}
607
+ const match = /^socket:\[(\d+)\]$/.exec(link)
608
+ if (match && inodes.has(match[1])) {
609
+ result.push(Number(dir))
610
+ break
611
+ }
612
+ }
613
+ } catch {}
614
+ }
615
+ } catch {}
616
+ return result
617
+ }
618
+
619
+ async function listenerPids(port) {
620
+ const found = new Set()
621
+ if (IS_WIN) {
622
+ const text = await execLines('netstat', ['-ano', '-p', 'tcp'])
623
+ for (const line of text.split(/\r?\n/)) {
624
+ const cols = line.trim().split(/\s+/)
625
+ if (cols.length < 5 || cols[3] !== 'LISTENING') continue
626
+ if (!String(cols[1] || '').endsWith(`:${port}`)) continue
627
+ const pid = Number(cols[4])
628
+ if (pid) found.add(pid)
629
+ }
630
+ } else {
631
+ const lsof = await execLines('lsof', ['-tiTCP:' + port, '-sTCP:LISTEN'])
632
+ for (const line of lsof.split(/\r?\n/)) {
633
+ const pid = Number(line.trim())
634
+ if (pid) found.add(pid)
635
+ }
636
+ if (!found.size) {
637
+ const fuser = await execLines('fuser', ['-n', 'tcp', String(port)])
638
+ for (const token of fuser.split(/\s+/)) {
639
+ const pid = Number(token.trim())
640
+ if (pid) found.add(pid)
641
+ }
642
+ }
643
+ if (!found.size) for (const pid of pidsFromProc(port)) found.add(pid)
644
+ }
645
+ found.delete(process.pid)
646
+ return [...found]
647
+ }
648
+
649
+ async function terminatePid(pid) {
650
+ if (!pid || pid === process.pid) return
651
+ if (IS_WIN) {
652
+ await execLines('taskkill', ['/PID', String(pid), '/T', '/F'])
653
+ } else {
654
+ try { process.kill(pid, 'SIGTERM') } catch {}
655
+ for (let i = 0; i < 12 && alive(pid); i++) await sleep(250)
656
+ if (alive(pid)) {
657
+ try { process.kill(pid, 'SIGKILL') } catch {}
658
+ }
659
+ }
660
+ }
661
+
662
+ function writePid(pid) {
663
+ try {
664
+ fs.writeFileSync(PID, String(pid))
665
+ } catch {}
666
+ }
667
+
432
668
  async function health() {
433
669
  try {
434
670
  const res = await fetch(`http://127.0.0.1:${API_PORT}/healthz`, { signal: AbortSignal.timeout(1500) })
@@ -443,7 +679,12 @@ async function health() {
443
679
  async function start() {
444
680
  if (!fs.existsSync(BIN)) await ensureInstalled()
445
681
  ensureConfig()
446
- if (await portOpen()) return true
682
+ if (await health()) {
683
+ const owners = await listenerPids(API_PORT)
684
+ if (owners.length === 1) writePid(owners[0])
685
+ return true
686
+ }
687
+ if ((await portOpen()) || (await portOpen(WEB_PORT))) await killProcess()
447
688
  const fd = fs.openSync(LOG, 'a')
448
689
  let child
449
690
  try {
@@ -451,39 +692,37 @@ async function start() {
451
692
  } finally {
452
693
  fs.closeSync(fd)
453
694
  }
695
+ child.once('error', () => {})
454
696
  child.unref()
455
- try {
456
- fs.writeFileSync(PID, String(child.pid))
457
- } catch {}
458
- for (let i = 0; i < 40; i++) {
697
+ writePid(child.pid)
698
+ for (let i = 0; i < 60; i++) {
459
699
  await sleep(500)
460
- if (await portOpen()) return true
461
- if (!alive(child.pid) && i > 3) break
700
+ if (await health()) {
701
+ const owners = await listenerPids(API_PORT)
702
+ if (owners.length === 1) writePid(owners[0])
703
+ return true
704
+ }
705
+ if (i > 3 && !alive(child.pid)) break
462
706
  }
463
- return portOpen()
707
+ return Boolean(await health())
464
708
  }
465
709
 
466
710
  async function killProcess() {
711
+ const targets = new Set()
467
712
  const pid = readPid()
468
- if (pid && alive(pid)) {
469
- try {
470
- process.kill(pid, 'SIGTERM')
471
- } catch {}
472
- for (let i = 0; i < 24 && alive(pid); i++) await sleep(250)
473
- if (alive(pid)) {
474
- try {
475
- process.kill(pid, 'SIGKILL')
476
- } catch {}
477
- }
713
+ if (pid) targets.add(pid)
714
+ for (const port of [API_PORT, WEB_PORT]) {
715
+ for (const owner of await listenerPids(port)) targets.add(owner)
478
716
  }
717
+ for (const target of targets) await terminatePid(target)
479
718
  try {
480
719
  fs.unlinkSync(PID)
481
720
  } catch {}
482
- for (let i = 0; i < 12; i++) {
483
- if (!(await portOpen())) return true
721
+ for (let i = 0; i < 20; i++) {
722
+ if (!(await portOpen()) && !(await portOpen(WEB_PORT))) return true
484
723
  await sleep(250)
485
724
  }
486
- return !(await portOpen())
725
+ return !(await portOpen()) && !(await portOpen(WEB_PORT))
487
726
  }
488
727
 
489
728
  async function stop() {
@@ -608,6 +847,14 @@ function registerUi(ctx) {
608
847
  { label: '重装', action: 'reinstall' },
609
848
  ],
610
849
  },
850
+ {
851
+ type: 'actions',
852
+ items: [
853
+ { label: '打开后台', action: 'openWeb', style: 'primary' },
854
+ { label: '查看日志', action: 'viewLog' },
855
+ { label: '项目主页', action: 'openHome' },
856
+ ],
857
+ },
611
858
  { type: 'callout', text: { $: 'data.note' }, tone: { $: 'data.noteTone' } },
612
859
  ],
613
860
  }),
@@ -682,7 +929,7 @@ function registerUi(ctx) {
682
929
  const lan = lanAddress()
683
930
  const lanLine = lan ? `\n局域网:http://${lan}:${API_PORT}/v1` : ''
684
931
  return {
685
- copy: `本机:http://127.0.0.1:${API_PORT}/v1${lanLine}\nAPI Key:${key}\n推荐模型:deepseek-v4.1-flash-free`,
932
+ copy: `本机:http://127.0.0.1:${API_PORT}/v1${lanLine}\nAPI Key:${key}\n推荐模型:big-pickle`,
686
933
  toast: '接入信息已复制',
687
934
  }
688
935
  },
@@ -711,6 +958,20 @@ function registerUi(ctx) {
711
958
  })()
712
959
  return { toast: '后台重装中…' }
713
960
  },
961
+ openWeb: () => ({
962
+ copy: `http://127.0.0.1:${WEB_PORT}`,
963
+ open: `http://127.0.0.1:${WEB_PORT}`,
964
+ toast: '后台地址已复制,可粘贴到浏览器打开',
965
+ }),
966
+ viewLog: () => ({
967
+ copy: tailLog(40) || '(暂无日志)',
968
+ toast: '日志已复制',
969
+ }),
970
+ openHome: () => ({
971
+ copy: 'https://github.com/king-andthe-nice/dsh-plugin-opencode2api',
972
+ open: 'https://github.com/king-andthe-nice/dsh-plugin-opencode2api',
973
+ toast: '项目地址已复制',
974
+ }),
714
975
  autoConfig: () =>
715
976
  pendingWork('正在配置', async () => {
716
977
  await autoConfigure(true)
@@ -760,4 +1021,10 @@ export function apply(ctx) {
760
1021
  ctx.inject(['dshGo'], (ctx) => {
761
1022
  registerUi(ctx)
762
1023
  })
1024
+ ctx.inject(['webServer'], (scoped) => {
1025
+ scoped.effect(
1026
+ () => scoped.webServer.register({ kind: 'prefix', path: '/api/opencode2api', handler: api }),
1027
+ 'opencode2api: web api',
1028
+ )
1029
+ })
763
1030
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-plugin-opencode2api",
3
- "version": "1.1.0",
4
- "description": "Unofficial one-click installer and auto-runner for opencode2api — a local free OpenAI-compatible API gateway — inside DSH (Windows, macOS, Linux, Android).",
3
+ "version": "1.2.1",
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",
7
7
  "url": "git+https://github.com/king-andthe-nice/dsh-plugin-opencode2api.git"
@@ -9,7 +9,13 @@
9
9
  "homepage": "https://github.com/king-andthe-nice/dsh-plugin-opencode2api#readme",
10
10
  "license": "MIT",
11
11
  "type": "module",
12
- "main": "lib/index.js",
12
+ "main": "./lib/index.js",
13
+ "exports": {
14
+ ".": "./lib/index.js",
15
+ "./client": "./lib/client.js",
16
+ "./package.json": "./package.json",
17
+ "./cordis.patch.yml": "./cordis.patch.yml"
18
+ },
13
19
  "files": [
14
20
  "lib",
15
21
  "cordis.patch.yml",
@@ -33,6 +39,11 @@
33
39
  "dsh": {
34
40
  "bundle": {
35
41
  "patch": "./cordis.patch.yml"
42
+ },
43
+ "client": {
44
+ "platform": "web",
45
+ "immediately": true,
46
+ "inject": []
36
47
  }
37
48
  },
38
49
  "engines": {