dsh-plugin-opencode2api 0.0.0-stage → 1.1.0
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/LICENSE +21 -0
- package/README.md +112 -2
- package/THIRD_PARTY_NOTICES.md +38 -0
- package/cordis.patch.yml +4 -0
- package/lib/index.js +763 -0
- package/package.json +87 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-plugin-opencode2api contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,113 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-plugin-opencode2api · 本地免费 API
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
一键把 [opencode2api](https://github.com/jasonxu114514/opencode2api) 装进 DSH:自动下载对应平台的程序、生成配置、启动并常驻,并自动把「本地免费 API」注册成 DSH 的模型商(模型列表从网关动态获取)。装好后本机就有一个专属的、兼容 OpenAI 的免费 API;DSH 关闭再打开会自动重启。
|
|
4
|
+
|
|
5
|
+
## 适用平台
|
|
6
|
+
|
|
7
|
+
| 平台 | 架构 | 状态 |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| Windows 10/11 | x64 / arm64 | 支持 |
|
|
10
|
+
| macOS | Intel / Apple Silicon | 支持 |
|
|
11
|
+
| Linux | x64 / arm64 | 支持 |
|
|
12
|
+
| Android(DSH Go,proot) | arm64 | 支持 |
|
|
13
|
+
| iOS | — | 暂不支持(App 沙箱不能运行外部程序) |
|
|
14
|
+
|
|
15
|
+
## 安装
|
|
16
|
+
|
|
17
|
+
在 DSH 的插件市场搜索 `dsh-plugin-opencode2api` 安装;或命令行:
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
dsh plugin --profile web add github:king-andthe-nice/dsh-plugin-opencode2api
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
> npm 版发布后也可以 `dsh plugin --profile web add dsh-plugin-opencode2api`。
|
|
24
|
+
|
|
25
|
+
装好后引擎会自动下载程序(约 5 MB)、生成配置并在 `0.0.0.0:8080` 启动(本机和局域网都能连)。首次下载失败会每 30 秒重试。
|
|
26
|
+
|
|
27
|
+
## 使用
|
|
28
|
+
|
|
29
|
+
装好后插件会自动把本地 API 注册成模型商「本地免费 API」,模型列表从 `/v1/models` 动态获取。直接在 DSH 的模型选择器里选它下面的免费模型即可,不需要手动填 URL 和 Key。
|
|
30
|
+
|
|
31
|
+
面板会显示「模型商:已自动配置」。如果没配上,点面板里的「自动配置」重试;仍然失败时再手动接入:
|
|
32
|
+
|
|
33
|
+
1. 打开「本地免费 API」面板。
|
|
34
|
+
2. 点「复制接入」,得到:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
本机:http://127.0.0.1:8080/v1
|
|
38
|
+
局域网:http://<你的局域网IP>:8080/v1
|
|
39
|
+
API Key:<随机生成>
|
|
40
|
+
推荐模型:deepseek-v4.1-flash-free
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
3. 在 DSH 里添加 OpenAI 兼容服务商,Base URL 填上面的地址,API Key 填生成的 Key。
|
|
44
|
+
|
|
45
|
+
## 面板功能
|
|
46
|
+
|
|
47
|
+
- **启动 / 停止 / 重启 / 重装**:重装会重新下载程序。
|
|
48
|
+
- **仅本机 / 开局域网**:切换监听地址(`127.0.0.1` 或 `0.0.0.0`)。
|
|
49
|
+
- **复制接入 / 复制后台**:复制 API 接入信息或管理后台地址与密码。
|
|
50
|
+
- **自动配置**:重新把本地 API 注册为模型商「本地免费 API」,并同步最新模型列表。
|
|
51
|
+
- 状态条实时显示运行状态,进程挂掉会自动拉起。
|
|
52
|
+
|
|
53
|
+
## 自动配置
|
|
54
|
+
|
|
55
|
+
网关就绪后,插件会:
|
|
56
|
+
|
|
57
|
+
- 把 `http://127.0.0.1:8080/v1` 注册为 `llm-pi-ai` 的提供方 `opencode2api`,显示名「本地免费 API」;
|
|
58
|
+
- 把本地 API Key 写入 DSH 凭据 `OPENCODE2API_API_KEY`(不写进配置文件);
|
|
59
|
+
- 从 `/v1/models` 读取模型,写入上下文窗口、输出上限、图片输入和推理档位;
|
|
60
|
+
- 模型列表变化时自动更新,没变化不重复写。
|
|
61
|
+
|
|
62
|
+
不想自动配置时,在 DSH 的「设置 → 模型」里删掉「本地免费 API」即可;插件不会再加回来,除非模型列表变化或你点「自动配置」。
|
|
63
|
+
|
|
64
|
+
## 管理后台
|
|
65
|
+
|
|
66
|
+
浏览器打开 `http://127.0.0.1:8081`(或局域网地址),账号 `admin`,初始密码见面板「复制后台」,也可在后台修改。后台可以改密码、查看请求、管理上游 Key 等。
|
|
67
|
+
|
|
68
|
+
## 数据目录
|
|
69
|
+
|
|
70
|
+
```text
|
|
71
|
+
$DSH_HOME/dsh-go/opencode2api/ # 默认 ~/.dsh/dsh-go/opencode2api/
|
|
72
|
+
├── opencode2api # 程序
|
|
73
|
+
├── config.json # 网关配置(监听、Key、匿名开关等)
|
|
74
|
+
├── webui-password.txt # 后台初始密码(后台改过后会失效)
|
|
75
|
+
├── auto-provider.json # 自动配置状态(模型列表指纹)
|
|
76
|
+
└── opencode2api.log # 运行日志
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## 配置说明
|
|
80
|
+
|
|
81
|
+
本插件为了开箱即用,默认开启匿名免费通道,并生成随机 `server_keys` 保护 `/v1/*`。注意:上游 opencode2api 本身默认**关闭**匿名,且明确提示匿名流量可能被大量拦截。想更稳可以:
|
|
82
|
+
|
|
83
|
+
- 在后台填入自己的 Zen / Go Key(`zen_keys` / `go_keys`),或
|
|
84
|
+
- 关闭匿名,只用自己的 Key。
|
|
85
|
+
|
|
86
|
+
匿名通道由上游提供,可能被限流或拦截,仅供个人轻量使用;请遵守 OpenCode 与各模型服务的条款。
|
|
87
|
+
|
|
88
|
+
## 卸载
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
dsh plugin --profile web remove dsh-plugin-opencode2api
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
卸载不会删除 `$DSH_HOME/dsh-go/opencode2api/`;需要时手动删除该目录。
|
|
95
|
+
|
|
96
|
+
## 能力与风险
|
|
97
|
+
|
|
98
|
+
插件会读写本地文件、下载并运行外部程序、访问网络。请只从可信来源安装;公开分发代理免费模型时,请遵守上游服务条款。
|
|
99
|
+
|
|
100
|
+
## 出处与许可
|
|
101
|
+
|
|
102
|
+
本插件是 [opencode2api](https://github.com/jasonxu114514/opencode2api) 的**非官方**安装器,与作者无隶属关系。
|
|
103
|
+
|
|
104
|
+
- opencode2api:**GPL-3.0-or-later**,源码与许可证见[上游仓库](https://github.com/jasonxu114514/opencode2api)。
|
|
105
|
+
- 本插件**不打包、不修改** opencode2api;安装时从上游 GitHub Releases 下载官方原版二进制,以独立进程运行。
|
|
106
|
+
- 本插件自身代码:**MIT**(见 `LICENSE`)。
|
|
107
|
+
- 上游程序按“无担保”提供;匿名通道可能被上游限流或拦截,长期使用建议在后台填入自己的 Zen / Go Key,并遵守 OpenCode 与各模型服务的条款。
|
|
108
|
+
|
|
109
|
+
详见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Third-party notices / 第三方说明
|
|
2
|
+
|
|
3
|
+
## opencode2api
|
|
4
|
+
|
|
5
|
+
This plugin is an **unofficial** installer and process manager for **opencode2api**.
|
|
6
|
+
|
|
7
|
+
- Project: https://github.com/jasonxu114514/opencode2api
|
|
8
|
+
- Author: jasonxu114514 and contributors
|
|
9
|
+
- License: **GPL-3.0-or-later** — https://github.com/jasonxu114514/opencode2api/blob/main/LICENSE
|
|
10
|
+
- Source code: https://github.com/jasonxu114514/opencode2api
|
|
11
|
+
|
|
12
|
+
### What this plugin does with it
|
|
13
|
+
|
|
14
|
+
- It does **not** bundle, vendor, or modify opencode2api.
|
|
15
|
+
- At install time it downloads the unmodified official release binary from the
|
|
16
|
+
project's GitHub Releases (with public mirrors as fallback) and runs it as a
|
|
17
|
+
separate process.
|
|
18
|
+
- The downloaded program remains under GPL-3.0-or-later and is provided
|
|
19
|
+
**without warranty** by its authors.
|
|
20
|
+
- This plugin's own code is MIT (see `LICENSE`).
|
|
21
|
+
|
|
22
|
+
Because the binary is fetched from the copyright holder's official release rather
|
|
23
|
+
than redistributed by this plugin, the plugin does not need to relicense its own
|
|
24
|
+
code under the GPL. If you fork this plugin and **bundle** the binary, you must
|
|
25
|
+
comply with GPL-3.0-or-later (include the license text and the corresponding
|
|
26
|
+
source).
|
|
27
|
+
|
|
28
|
+
### Affiliation
|
|
29
|
+
|
|
30
|
+
This plugin is **not affiliated with or endorsed by** the opencode2api author.
|
|
31
|
+
"opencode2api" is used descriptively to identify the upstream project.
|
|
32
|
+
|
|
33
|
+
## Model providers
|
|
34
|
+
|
|
35
|
+
opencode2api can proxy OpenCode Zen / Zen Go and an anonymous free channel. Your
|
|
36
|
+
use of those services is subject to their own terms and quotas. This plugin does
|
|
37
|
+
not grant any rights to those services, and anonymous traffic may be limited or
|
|
38
|
+
blocked upstream. Prefer supplying your own Zen / Go key.
|
package/cordis.patch.yml
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,763 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import fsp from 'node:fs/promises'
|
|
5
|
+
import { createConnection } from 'node:net'
|
|
6
|
+
import os from 'node:os'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
|
|
9
|
+
export const name = 'dsh-plugin-opencode2api'
|
|
10
|
+
|
|
11
|
+
const VERSION = process.env.OPENCODE2API_VERSION || '1.5.1'
|
|
12
|
+
const REPO = 'jasonxu114514/opencode2api'
|
|
13
|
+
const API_PORT = Number(process.env.OPENCODE2API_PORT || 8080)
|
|
14
|
+
const WEB_PORT = API_PORT + 1
|
|
15
|
+
const DOWNLOAD_TIMEOUT_MS = 120_000
|
|
16
|
+
const MIRRORS = ['', 'https://gh-proxy.com/', 'https://ghproxy.net/', 'https://ghfast.top/']
|
|
17
|
+
|
|
18
|
+
const HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
19
|
+
const IS_CHECK = /dsh-go-check-/.test(HOME)
|
|
20
|
+
const DATA = path.join(HOME, 'dsh-go', 'opencode2api')
|
|
21
|
+
const IS_WIN = process.platform === 'win32'
|
|
22
|
+
const BIN = path.join(DATA, IS_WIN ? 'opencode2api.exe' : 'opencode2api')
|
|
23
|
+
const CFG = path.join(DATA, 'config.json')
|
|
24
|
+
const PID = path.join(DATA, 'opencode2api.pid')
|
|
25
|
+
const LOG = path.join(DATA, 'opencode2api.log')
|
|
26
|
+
const PASS = path.join(DATA, 'webui-password.txt')
|
|
27
|
+
const AUTO_STATE = path.join(DATA, 'auto-provider.json')
|
|
28
|
+
const PROVIDER_ID = 'opencode2api'
|
|
29
|
+
const CRED_REF = 'OPENCODE2API_API_KEY'
|
|
30
|
+
|
|
31
|
+
let desired = true
|
|
32
|
+
let busy = false
|
|
33
|
+
let installing = null
|
|
34
|
+
let lastError = ''
|
|
35
|
+
let lastAutoError = ''
|
|
36
|
+
let runtime = null
|
|
37
|
+
let autoInfo = { status: '未配置', tone: 'warn' }
|
|
38
|
+
|
|
39
|
+
function sleep(ms) {
|
|
40
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function human(error) {
|
|
44
|
+
const message = String(error?.message ?? error ?? '')
|
|
45
|
+
if (message.includes('ENOEXEC') || message.includes('ENOENT')) return '程序无法在当前平台运行,请手动安装或换平台'
|
|
46
|
+
if (message.includes('EACCES')) return '程序没有执行权限'
|
|
47
|
+
if (message.includes('sha256')) return '下载校验失败,请重试'
|
|
48
|
+
if (/HTTP \d+/.test(message) || message.includes('fetch')) return '下载失败,请检查网络后重试'
|
|
49
|
+
return message.slice(0, 60) || '操作失败'
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function target() {
|
|
53
|
+
const arch = process.arch === 'x64' ? 'amd64' : process.arch === 'arm64' ? 'arm64' : null
|
|
54
|
+
if (!arch) return null
|
|
55
|
+
if (process.platform === 'win32') return { os: 'windows', arch, ext: 'zip', bin: 'opencode2api.exe' }
|
|
56
|
+
if (process.platform === 'darwin') return { os: 'darwin', arch, ext: 'tar.gz', bin: 'opencode2api' }
|
|
57
|
+
if (process.platform === 'linux') return { os: 'linux', arch, ext: 'tar.gz', bin: 'opencode2api' }
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function randomKey(length) {
|
|
62
|
+
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
|
|
63
|
+
const bytes = randomBytes(length)
|
|
64
|
+
let out = ''
|
|
65
|
+
for (let i = 0; i < length; i++) out += chars[bytes[i] % chars.length]
|
|
66
|
+
return out
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function defaultConfig() {
|
|
70
|
+
return {
|
|
71
|
+
listen: `0.0.0.0:${API_PORT}`,
|
|
72
|
+
server_keys: [randomKey(32)],
|
|
73
|
+
zen_keys: [],
|
|
74
|
+
go_keys: [],
|
|
75
|
+
anonymous: true,
|
|
76
|
+
warp: { enabled: false, pool_size: 2, stack: 'ipv6', source_ipv6: '' },
|
|
77
|
+
proxies: ['direct'],
|
|
78
|
+
proxyfile: '',
|
|
79
|
+
upstream: {
|
|
80
|
+
zen: 'https://opencode.ai/zen',
|
|
81
|
+
go: 'https://opencode.ai/zen/go',
|
|
82
|
+
anonymous: 'https://opencode.ai/inference',
|
|
83
|
+
prompt_environment: {},
|
|
84
|
+
},
|
|
85
|
+
retry: { max_attempts: 3, timeout_seconds: 300 },
|
|
86
|
+
models: { refresh_seconds: 300, protocols: {}, free_only: false, active_probes: false },
|
|
87
|
+
performance: {
|
|
88
|
+
max_idle_conns: 2048,
|
|
89
|
+
max_idle_conns_per_host: 256,
|
|
90
|
+
max_conns_per_host: 0,
|
|
91
|
+
idle_conn_timeout_seconds: 120,
|
|
92
|
+
connect_timeout_seconds: 5,
|
|
93
|
+
failure_cooldown_seconds: 15,
|
|
94
|
+
attempt_timeout_seconds: 0,
|
|
95
|
+
first_event_timeout_seconds: 0,
|
|
96
|
+
max_anonymous_exits: 8,
|
|
97
|
+
free_tier_block_seconds: 900,
|
|
98
|
+
},
|
|
99
|
+
logging: { level: 'info', ring_size: 2000, dump_request_bodies: false },
|
|
100
|
+
webui: {
|
|
101
|
+
enabled: true,
|
|
102
|
+
listen: `0.0.0.0:${WEB_PORT}`,
|
|
103
|
+
username: 'admin',
|
|
104
|
+
password: randomKey(14),
|
|
105
|
+
session_ttl_minutes: 720,
|
|
106
|
+
},
|
|
107
|
+
prefer: 'go',
|
|
108
|
+
reasoning: { effort: 'high', effort_by_model: {} },
|
|
109
|
+
rotation: {
|
|
110
|
+
sota: {
|
|
111
|
+
alias: 'sota',
|
|
112
|
+
order: ['deepseek-v4.1-flash', 'glm-5.3', 'grok-4.6', 'kimi-k3', 'qwen3.8-max'],
|
|
113
|
+
},
|
|
114
|
+
sweet: { alias: 'sweet', order: [] },
|
|
115
|
+
first_output_seconds: 30,
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function readConfig() {
|
|
121
|
+
try {
|
|
122
|
+
return JSON.parse(fs.readFileSync(CFG, 'utf8'))
|
|
123
|
+
} catch {
|
|
124
|
+
return defaultConfig()
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function ensureConfig() {
|
|
129
|
+
if (!fs.existsSync(CFG)) {
|
|
130
|
+
const cfg = defaultConfig()
|
|
131
|
+
fs.mkdirSync(DATA, { recursive: true })
|
|
132
|
+
fs.writeFileSync(PASS, `${cfg.webui.password}\n`, { mode: 0o600 })
|
|
133
|
+
fs.writeFileSync(CFG, JSON.stringify(cfg, null, 2))
|
|
134
|
+
}
|
|
135
|
+
return readConfig()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function readPassword() {
|
|
139
|
+
try {
|
|
140
|
+
return fs.readFileSync(PASS, 'utf8').trim()
|
|
141
|
+
} catch {
|
|
142
|
+
return ''
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function fetchModels(key) {
|
|
147
|
+
try {
|
|
148
|
+
const res = await fetch(`http://127.0.0.1:${API_PORT}/v1/models`, {
|
|
149
|
+
headers: { authorization: `Bearer ${key}` },
|
|
150
|
+
signal: AbortSignal.timeout(8000),
|
|
151
|
+
})
|
|
152
|
+
if (!res.ok) return []
|
|
153
|
+
const body = await res.json()
|
|
154
|
+
const list = Array.isArray(body?.data) ? body.data : Array.isArray(body?.models) ? body.models : []
|
|
155
|
+
return list
|
|
156
|
+
.map((item) => (typeof item === 'string' ? { id: item } : item))
|
|
157
|
+
.filter((item) => item && typeof item.id === 'string' && item.id.length > 0)
|
|
158
|
+
} catch {
|
|
159
|
+
return []
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function modelEntry(model) {
|
|
164
|
+
const entry = { id: model.id }
|
|
165
|
+
const window = model.context_length ?? model.context_window ?? model.max_input ?? model.metadata?.context_window
|
|
166
|
+
if (Number.isFinite(window) && window > 0) entry.contextWindow = window
|
|
167
|
+
const maxOut = model.max_output ?? model.metadata?.max_output
|
|
168
|
+
if (Number.isFinite(maxOut) && maxOut > 0) entry.maxTokens = maxOut
|
|
169
|
+
const modalities = model.metadata?.input_modalities ?? model.input_modalities
|
|
170
|
+
if (Array.isArray(modalities)) {
|
|
171
|
+
const input = modalities.filter((item) => item === 'text' || item === 'image')
|
|
172
|
+
if (input.length > 0) entry.input = input
|
|
173
|
+
}
|
|
174
|
+
const efforts = model.reasoning_efforts ?? model.compat?.supportedReasoningEfforts
|
|
175
|
+
if (model.reasoning === true && Array.isArray(efforts) && efforts.length > 0) {
|
|
176
|
+
const levels = { off: null }
|
|
177
|
+
for (const level of efforts) {
|
|
178
|
+
if (['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].includes(level)) levels[level] = level
|
|
179
|
+
}
|
|
180
|
+
if (Object.keys(levels).length > 1) entry.reasoningEfforts = levels
|
|
181
|
+
}
|
|
182
|
+
return entry
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function autoHash(key, models) {
|
|
186
|
+
return createHash('sha256')
|
|
187
|
+
.update(JSON.stringify({ key, ids: models.map((model) => model.id) }))
|
|
188
|
+
.digest('hex')
|
|
189
|
+
.slice(0, 16)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function readAutoState() {
|
|
193
|
+
try {
|
|
194
|
+
return JSON.parse(fs.readFileSync(AUTO_STATE, 'utf8'))
|
|
195
|
+
} catch {
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function autoConfigure(force = false) {
|
|
201
|
+
if (!runtime || IS_CHECK) return
|
|
202
|
+
const settings = runtime.get('settings')
|
|
203
|
+
const credentials = runtime.get('credentials')
|
|
204
|
+
if (!settings || !credentials) {
|
|
205
|
+
autoInfo = { status: '等待引擎', tone: 'info' }
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
const cfg = readConfig()
|
|
209
|
+
const key = cfg.server_keys?.[0]
|
|
210
|
+
if (!key) {
|
|
211
|
+
autoInfo = { status: '缺少 Key', tone: 'warn' }
|
|
212
|
+
return
|
|
213
|
+
}
|
|
214
|
+
const models = await fetchModels(key)
|
|
215
|
+
if (!models.length) {
|
|
216
|
+
lastAutoError = '未取到模型列表'
|
|
217
|
+
autoInfo = { status: '取模型失败', tone: 'warn' }
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
const hash = autoHash(key, models)
|
|
221
|
+
const state = readAutoState()
|
|
222
|
+
if (!force && state && state.hash === hash && state.version === VERSION) {
|
|
223
|
+
autoInfo = { status: '已自动配置', tone: 'good' }
|
|
224
|
+
return
|
|
225
|
+
}
|
|
226
|
+
let descriptor
|
|
227
|
+
try {
|
|
228
|
+
descriptor = settings.describe().find((row) => row.ns === 'llm-pi-ai')
|
|
229
|
+
} catch {}
|
|
230
|
+
if (!descriptor) {
|
|
231
|
+
lastAutoError = '未找到 llm-pi-ai 配置'
|
|
232
|
+
autoInfo = { status: '不支持自动配置', tone: 'warn' }
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
const entry = {
|
|
236
|
+
displayName: '本地免费 API',
|
|
237
|
+
api: 'openai-completions',
|
|
238
|
+
baseURL: `http://127.0.0.1:${API_PORT}/v1`,
|
|
239
|
+
apiKeyEnv: CRED_REF,
|
|
240
|
+
models: models.map(modelEntry),
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
await credentials.set(CRED_REF, key)
|
|
244
|
+
} catch (error) {
|
|
245
|
+
lastAutoError = human(error)
|
|
246
|
+
autoInfo = { status: '写入 Key 失败', tone: 'bad' }
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
let failure = null
|
|
250
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
251
|
+
try {
|
|
252
|
+
const row = settings.describe().find((item) => item.ns === 'llm-pi-ai')
|
|
253
|
+
if (!row) throw new Error('llm-pi-ai 不存在')
|
|
254
|
+
await settings.update('llm-pi-ai', { providers: { [PROVIDER_ID]: entry } }, row.revision)
|
|
255
|
+
failure = null
|
|
256
|
+
break
|
|
257
|
+
} catch (error) {
|
|
258
|
+
failure = error
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (failure) {
|
|
262
|
+
lastAutoError = human(failure)
|
|
263
|
+
autoInfo = { status: '配置失败', tone: 'bad' }
|
|
264
|
+
return
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
fs.writeFileSync(AUTO_STATE, JSON.stringify({ version: VERSION, hash }))
|
|
268
|
+
} catch {}
|
|
269
|
+
lastAutoError = ''
|
|
270
|
+
autoInfo = { status: '已自动配置', tone: 'good' }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function setListen(host) {
|
|
274
|
+
const cfg = readConfig()
|
|
275
|
+
cfg.listen = `${host}:${API_PORT}`
|
|
276
|
+
cfg.webui = { ...(cfg.webui || {}), listen: `${host}:${WEB_PORT}` }
|
|
277
|
+
fs.writeFileSync(CFG, JSON.stringify(cfg, null, 2))
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function lanAddress() {
|
|
281
|
+
try {
|
|
282
|
+
for (const list of Object.values(os.networkInterfaces())) {
|
|
283
|
+
for (const item of list || []) {
|
|
284
|
+
if (item && item.family === 'IPv4' && !item.internal) return item.address
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
} catch {}
|
|
288
|
+
return ''
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function findFile(dir, filename) {
|
|
292
|
+
let entries
|
|
293
|
+
try {
|
|
294
|
+
entries = fs.readdirSync(dir, { withFileTypes: true })
|
|
295
|
+
} catch {
|
|
296
|
+
return null
|
|
297
|
+
}
|
|
298
|
+
for (const entry of entries) {
|
|
299
|
+
const full = path.join(dir, entry.name)
|
|
300
|
+
if (entry.isDirectory()) {
|
|
301
|
+
const nested = findFile(full, filename)
|
|
302
|
+
if (nested) return nested
|
|
303
|
+
} else if (entry.name === filename) {
|
|
304
|
+
return full
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return null
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function runCommand(command, args) {
|
|
311
|
+
return new Promise((resolve, reject) => {
|
|
312
|
+
const child = spawn(command, args, { stdio: 'ignore' })
|
|
313
|
+
child.once('error', reject)
|
|
314
|
+
child.once('close', (code) => (code === 0 ? resolve() : reject(new Error(`${command} exit ${code}`))))
|
|
315
|
+
})
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function fetchBuffer(url) {
|
|
319
|
+
const controller = new AbortController()
|
|
320
|
+
const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)
|
|
321
|
+
try {
|
|
322
|
+
const res = await fetch(url, { signal: controller.signal, redirect: 'follow' })
|
|
323
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
|
324
|
+
return Buffer.from(await res.arrayBuffer())
|
|
325
|
+
} finally {
|
|
326
|
+
clearTimeout(timer)
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function download(relative, destination) {
|
|
331
|
+
let lastFailure = null
|
|
332
|
+
for (const prefix of MIRRORS) {
|
|
333
|
+
const url = `${prefix}https://github.com/${REPO}/releases/download/v${VERSION}/${relative}`
|
|
334
|
+
try {
|
|
335
|
+
const body = await fetchBuffer(url)
|
|
336
|
+
try {
|
|
337
|
+
const shaBody = await fetchBuffer(`${url}.sha256`)
|
|
338
|
+
const expected = shaBody.toString('utf8').trim().split(/\s+/)[0].toLowerCase()
|
|
339
|
+
const actual = createHash('sha256').update(body).digest('hex')
|
|
340
|
+
if (expected && expected !== actual) throw new Error('sha256 mismatch')
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (String(error?.message).includes('sha256')) throw error
|
|
343
|
+
}
|
|
344
|
+
await fsp.writeFile(destination, body)
|
|
345
|
+
return
|
|
346
|
+
} catch (error) {
|
|
347
|
+
lastFailure = error
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
throw lastFailure || new Error('download failed')
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async function extract(archive, destination) {
|
|
354
|
+
try {
|
|
355
|
+
await runCommand('tar', ['-xf', archive, '-C', destination])
|
|
356
|
+
} catch (error) {
|
|
357
|
+
if (archive.endsWith('.zip') && IS_WIN) {
|
|
358
|
+
await runCommand('powershell', [
|
|
359
|
+
'-NoProfile',
|
|
360
|
+
'-Command',
|
|
361
|
+
`Expand-Archive -LiteralPath "${archive}" -DestinationPath "${destination}" -Force`,
|
|
362
|
+
])
|
|
363
|
+
} else {
|
|
364
|
+
throw error
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function ensureInstalled(force = false) {
|
|
370
|
+
if (installing) return installing
|
|
371
|
+
installing = (async () => {
|
|
372
|
+
fs.mkdirSync(DATA, { recursive: true })
|
|
373
|
+
if (!force && fs.existsSync(BIN)) return
|
|
374
|
+
const plat = target()
|
|
375
|
+
if (!plat) throw new Error('当前平台暂不支持')
|
|
376
|
+
const relative = `opencode2api_v${VERSION}_${plat.os}_${plat.arch}.${plat.ext}`
|
|
377
|
+
const temp = path.join(DATA, `.install-${Date.now()}`)
|
|
378
|
+
fs.mkdirSync(temp, { recursive: true })
|
|
379
|
+
try {
|
|
380
|
+
const archive = path.join(temp, relative)
|
|
381
|
+
await download(relative, archive)
|
|
382
|
+
await extract(archive, temp)
|
|
383
|
+
const found = findFile(temp, plat.bin)
|
|
384
|
+
if (!found) throw new Error('压缩包里没有找到程序')
|
|
385
|
+
if (fs.existsSync(BIN)) fs.unlinkSync(BIN)
|
|
386
|
+
await fsp.copyFile(found, BIN)
|
|
387
|
+
if (!IS_WIN) fs.chmodSync(BIN, 0o755)
|
|
388
|
+
lastError = ''
|
|
389
|
+
} finally {
|
|
390
|
+
await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
|
|
391
|
+
}
|
|
392
|
+
})()
|
|
393
|
+
try {
|
|
394
|
+
return await installing
|
|
395
|
+
} finally {
|
|
396
|
+
installing = null
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function portOpen(port = API_PORT, timeout = 800) {
|
|
401
|
+
return new Promise((resolve) => {
|
|
402
|
+
const socket = createConnection({ host: '127.0.0.1', port })
|
|
403
|
+
const finish = (value) => {
|
|
404
|
+
socket.destroy()
|
|
405
|
+
resolve(value)
|
|
406
|
+
}
|
|
407
|
+
socket.setTimeout(timeout)
|
|
408
|
+
socket.once('connect', () => finish(true))
|
|
409
|
+
socket.once('timeout', () => finish(false))
|
|
410
|
+
socket.once('error', () => finish(false))
|
|
411
|
+
})
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function readPid() {
|
|
415
|
+
try {
|
|
416
|
+
return Number(fs.readFileSync(PID, 'utf8').trim()) || null
|
|
417
|
+
} catch {
|
|
418
|
+
return null
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function alive(pid) {
|
|
423
|
+
if (!pid) return false
|
|
424
|
+
try {
|
|
425
|
+
process.kill(pid, 0)
|
|
426
|
+
return true
|
|
427
|
+
} catch {
|
|
428
|
+
return false
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async function health() {
|
|
433
|
+
try {
|
|
434
|
+
const res = await fetch(`http://127.0.0.1:${API_PORT}/healthz`, { signal: AbortSignal.timeout(1500) })
|
|
435
|
+
if (!res.ok) return null
|
|
436
|
+
const body = await res.json()
|
|
437
|
+
return body && (body.status === 'ok' || body.ready === true || body.models) ? body : null
|
|
438
|
+
} catch {
|
|
439
|
+
return null
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function start() {
|
|
444
|
+
if (!fs.existsSync(BIN)) await ensureInstalled()
|
|
445
|
+
ensureConfig()
|
|
446
|
+
if (await portOpen()) return true
|
|
447
|
+
const fd = fs.openSync(LOG, 'a')
|
|
448
|
+
let child
|
|
449
|
+
try {
|
|
450
|
+
child = spawn(BIN, ['-config', CFG], { cwd: DATA, detached: true, stdio: ['ignore', fd, fd] })
|
|
451
|
+
} finally {
|
|
452
|
+
fs.closeSync(fd)
|
|
453
|
+
}
|
|
454
|
+
child.unref()
|
|
455
|
+
try {
|
|
456
|
+
fs.writeFileSync(PID, String(child.pid))
|
|
457
|
+
} catch {}
|
|
458
|
+
for (let i = 0; i < 40; i++) {
|
|
459
|
+
await sleep(500)
|
|
460
|
+
if (await portOpen()) return true
|
|
461
|
+
if (!alive(child.pid) && i > 3) break
|
|
462
|
+
}
|
|
463
|
+
return portOpen()
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async function killProcess() {
|
|
467
|
+
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
|
+
}
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
fs.unlinkSync(PID)
|
|
481
|
+
} catch {}
|
|
482
|
+
for (let i = 0; i < 12; i++) {
|
|
483
|
+
if (!(await portOpen())) return true
|
|
484
|
+
await sleep(250)
|
|
485
|
+
}
|
|
486
|
+
return !(await portOpen())
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async function stop() {
|
|
490
|
+
desired = false
|
|
491
|
+
return killProcess()
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
async function restart() {
|
|
495
|
+
desired = true
|
|
496
|
+
await killProcess()
|
|
497
|
+
return start()
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async function boot() {
|
|
501
|
+
if (!desired) return
|
|
502
|
+
try {
|
|
503
|
+
await ensureInstalled()
|
|
504
|
+
await start()
|
|
505
|
+
lastError = ''
|
|
506
|
+
void autoConfigure().catch(() => {})
|
|
507
|
+
} catch (error) {
|
|
508
|
+
lastError = human(error)
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
async function snapshot() {
|
|
513
|
+
const body = await health()
|
|
514
|
+
const installed = fs.existsSync(BIN)
|
|
515
|
+
const running = Boolean(body)
|
|
516
|
+
let state = '未安装'
|
|
517
|
+
let tone = 'bad'
|
|
518
|
+
if (IS_CHECK) {
|
|
519
|
+
state = '未安装'
|
|
520
|
+
tone = 'muted'
|
|
521
|
+
} else if (busy) {
|
|
522
|
+
state = '处理中…'
|
|
523
|
+
tone = 'warn'
|
|
524
|
+
} else if (running) {
|
|
525
|
+
state = '运行中'
|
|
526
|
+
tone = 'good'
|
|
527
|
+
} else if (installed) {
|
|
528
|
+
state = '已停止'
|
|
529
|
+
tone = 'warn'
|
|
530
|
+
}
|
|
531
|
+
const models = body?.models?.total ?? body?.models ?? '—'
|
|
532
|
+
const plat = target()
|
|
533
|
+
const cfg = readConfig()
|
|
534
|
+
const lan = lanAddress()
|
|
535
|
+
return {
|
|
536
|
+
state,
|
|
537
|
+
tone,
|
|
538
|
+
baseUrl: `http://127.0.0.1:${API_PORT}/v1`,
|
|
539
|
+
webUrl: `http://127.0.0.1:${WEB_PORT}`,
|
|
540
|
+
lanUrl: lan ? `http://${lan}:${API_PORT}/v1` : '—',
|
|
541
|
+
listenMode: String(cfg.listen || '').startsWith('0.0.0.0') ? '局域网' : '仅本机',
|
|
542
|
+
models: String(models),
|
|
543
|
+
platform: plat ? `${plat.os}/${plat.arch}` : '不支持',
|
|
544
|
+
provider: autoInfo.status,
|
|
545
|
+
providerTone: autoInfo.tone,
|
|
546
|
+
note: lastAutoError || lastError || '后台可改密码与监听地址;重装会重新下载程序',
|
|
547
|
+
noteTone: lastAutoError || lastError ? 'warn' : 'info',
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function pendingWork(label, work) {
|
|
552
|
+
return {
|
|
553
|
+
pending: { label, timeoutMs: 50000 },
|
|
554
|
+
result: async () => {
|
|
555
|
+
busy = true
|
|
556
|
+
try {
|
|
557
|
+
return await work()
|
|
558
|
+
} catch (error) {
|
|
559
|
+
lastError = human(error)
|
|
560
|
+
return { toast: '操作失败' }
|
|
561
|
+
} finally {
|
|
562
|
+
busy = false
|
|
563
|
+
}
|
|
564
|
+
},
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function registerUi(ctx) {
|
|
569
|
+
ctx.dshGo.panel('gateway', {
|
|
570
|
+
view: () => ({
|
|
571
|
+
type: 'stack',
|
|
572
|
+
title: '本地免费 API',
|
|
573
|
+
children: [
|
|
574
|
+
{ type: 'metric', label: '状态', value: { $: 'data.state' }, tone: { $: 'data.tone' } },
|
|
575
|
+
{
|
|
576
|
+
type: 'keyValue',
|
|
577
|
+
items: [
|
|
578
|
+
{ label: 'API', value: { $: 'data.baseUrl' } },
|
|
579
|
+
{ label: '后台', value: { $: 'data.webUrl' } },
|
|
580
|
+
{ label: '监听', value: { $: 'data.listenMode' } },
|
|
581
|
+
{ label: '局域网', value: { $: 'data.lanUrl' } },
|
|
582
|
+
{ label: '模型', value: { $: 'data.models' } },
|
|
583
|
+
{ label: '模型商', value: { $: 'data.provider' }, tone: { $: 'data.providerTone' } },
|
|
584
|
+
{ label: '平台', value: { $: 'data.platform' } },
|
|
585
|
+
],
|
|
586
|
+
},
|
|
587
|
+
{
|
|
588
|
+
type: 'actions',
|
|
589
|
+
items: [
|
|
590
|
+
{ label: '启动', action: 'start', style: 'primary' },
|
|
591
|
+
{ label: '停止', action: 'stop' },
|
|
592
|
+
{ label: '重启', action: 'restart' },
|
|
593
|
+
],
|
|
594
|
+
},
|
|
595
|
+
{
|
|
596
|
+
type: 'actions',
|
|
597
|
+
items: [
|
|
598
|
+
{ label: '仅本机', action: 'listenLocal' },
|
|
599
|
+
{ label: '开局域网', action: 'listenLan' },
|
|
600
|
+
],
|
|
601
|
+
},
|
|
602
|
+
{
|
|
603
|
+
type: 'actions',
|
|
604
|
+
items: [
|
|
605
|
+
{ label: '复制接入', action: 'copyInfo' },
|
|
606
|
+
{ label: '复制后台', action: 'copyWeb' },
|
|
607
|
+
{ label: '自动配置', action: 'autoConfig' },
|
|
608
|
+
{ label: '重装', action: 'reinstall' },
|
|
609
|
+
],
|
|
610
|
+
},
|
|
611
|
+
{ type: 'callout', text: { $: 'data.note' }, tone: { $: 'data.noteTone' } },
|
|
612
|
+
],
|
|
613
|
+
}),
|
|
614
|
+
data: (scope, emit) => {
|
|
615
|
+
if (IS_CHECK) {
|
|
616
|
+
emit({
|
|
617
|
+
state: '未安装',
|
|
618
|
+
tone: 'info',
|
|
619
|
+
baseUrl: `http://127.0.0.1:${API_PORT}/v1`,
|
|
620
|
+
webUrl: `http://127.0.0.1:${WEB_PORT}`,
|
|
621
|
+
lanUrl: '—',
|
|
622
|
+
listenMode: '局域网',
|
|
623
|
+
models: '—',
|
|
624
|
+
platform: target() ? `${target().os}/${target().arch}` : '不支持',
|
|
625
|
+
provider: '检查模式',
|
|
626
|
+
providerTone: 'info',
|
|
627
|
+
note: '检查模式',
|
|
628
|
+
noteTone: 'info',
|
|
629
|
+
})
|
|
630
|
+
return () => {}
|
|
631
|
+
}
|
|
632
|
+
let closed = false
|
|
633
|
+
const tick = async () => {
|
|
634
|
+
try {
|
|
635
|
+
const data = await snapshot()
|
|
636
|
+
if (!closed) emit(data)
|
|
637
|
+
} catch {}
|
|
638
|
+
}
|
|
639
|
+
void tick()
|
|
640
|
+
const timer = setInterval(tick, 5000)
|
|
641
|
+
return () => {
|
|
642
|
+
closed = true
|
|
643
|
+
clearInterval(timer)
|
|
644
|
+
}
|
|
645
|
+
},
|
|
646
|
+
actions: {
|
|
647
|
+
start: () =>
|
|
648
|
+
pendingWork('正在启动', async () => {
|
|
649
|
+
desired = true
|
|
650
|
+
const ok = await start()
|
|
651
|
+
return { toast: ok ? '已启动' : '启动失败,看日志' }
|
|
652
|
+
}),
|
|
653
|
+
stop: () =>
|
|
654
|
+
pendingWork('正在停止', async () => {
|
|
655
|
+
const ok = await stop()
|
|
656
|
+
return { toast: ok ? '已停止' : '停止失败' }
|
|
657
|
+
}),
|
|
658
|
+
restart: () =>
|
|
659
|
+
pendingWork('正在重启', async () => {
|
|
660
|
+
const ok = await restart()
|
|
661
|
+
return { toast: ok ? '已重启' : '重启失败' }
|
|
662
|
+
}),
|
|
663
|
+
listenLocal: () =>
|
|
664
|
+
pendingWork('正在切换', async () => {
|
|
665
|
+
setListen('127.0.0.1')
|
|
666
|
+
desired = true
|
|
667
|
+
await killProcess()
|
|
668
|
+
const ok = await start()
|
|
669
|
+
return { toast: ok ? '已仅本机监听' : '切换失败' }
|
|
670
|
+
}),
|
|
671
|
+
listenLan: () =>
|
|
672
|
+
pendingWork('正在切换', async () => {
|
|
673
|
+
setListen('0.0.0.0')
|
|
674
|
+
desired = true
|
|
675
|
+
await killProcess()
|
|
676
|
+
const ok = await start()
|
|
677
|
+
return { toast: ok ? '已开局域网' : '切换失败' }
|
|
678
|
+
}),
|
|
679
|
+
copyInfo: () => {
|
|
680
|
+
const cfg = readConfig()
|
|
681
|
+
const key = cfg.server_keys?.[0] || ''
|
|
682
|
+
const lan = lanAddress()
|
|
683
|
+
const lanLine = lan ? `\n局域网:http://${lan}:${API_PORT}/v1` : ''
|
|
684
|
+
return {
|
|
685
|
+
copy: `本机:http://127.0.0.1:${API_PORT}/v1${lanLine}\nAPI Key:${key}\n推荐模型:deepseek-v4.1-flash-free`,
|
|
686
|
+
toast: '接入信息已复制',
|
|
687
|
+
}
|
|
688
|
+
},
|
|
689
|
+
copyWeb: () => {
|
|
690
|
+
const cfg = readConfig()
|
|
691
|
+
const password = readPassword() || '(已在后台改过,请用新密码)'
|
|
692
|
+
return {
|
|
693
|
+
copy: `后台:http://127.0.0.1:${WEB_PORT}\n账号:${cfg.webui?.username || 'admin'}\n密码:${password}`,
|
|
694
|
+
toast: '后台信息已复制',
|
|
695
|
+
}
|
|
696
|
+
},
|
|
697
|
+
reinstall: () => {
|
|
698
|
+
void (async () => {
|
|
699
|
+
busy = true
|
|
700
|
+
try {
|
|
701
|
+
desired = true
|
|
702
|
+
await killProcess()
|
|
703
|
+
await ensureInstalled(true)
|
|
704
|
+
await start()
|
|
705
|
+
lastError = ''
|
|
706
|
+
} catch (error) {
|
|
707
|
+
lastError = human(error)
|
|
708
|
+
} finally {
|
|
709
|
+
busy = false
|
|
710
|
+
}
|
|
711
|
+
})()
|
|
712
|
+
return { toast: '后台重装中…' }
|
|
713
|
+
},
|
|
714
|
+
autoConfig: () =>
|
|
715
|
+
pendingWork('正在配置', async () => {
|
|
716
|
+
await autoConfigure(true)
|
|
717
|
+
return { toast: autoInfo.tone === 'good' ? '模型商已配置' : autoInfo.status }
|
|
718
|
+
}),
|
|
719
|
+
},
|
|
720
|
+
})
|
|
721
|
+
|
|
722
|
+
ctx.dshGo.strip('status', (scope, emit) => {
|
|
723
|
+
if (IS_CHECK) {
|
|
724
|
+
emit({ text: '本地 API', icon: 'server' })
|
|
725
|
+
return () => {}
|
|
726
|
+
}
|
|
727
|
+
let closed = false
|
|
728
|
+
const tick = async () => {
|
|
729
|
+
try {
|
|
730
|
+
const body = await health()
|
|
731
|
+
const text = body ? '本地API 运行中' : fs.existsSync(BIN) ? '本地API 已停止' : '本地API 未安装'
|
|
732
|
+
if (!closed) emit({ text, icon: 'server', tone: body ? 'good' : 'warn' })
|
|
733
|
+
} catch {}
|
|
734
|
+
}
|
|
735
|
+
void tick()
|
|
736
|
+
const timer = setInterval(tick, 8000)
|
|
737
|
+
return () => {
|
|
738
|
+
closed = true
|
|
739
|
+
clearInterval(timer)
|
|
740
|
+
}
|
|
741
|
+
})
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
export function apply(ctx) {
|
|
745
|
+
runtime = ctx
|
|
746
|
+
if (!IS_CHECK) {
|
|
747
|
+
ctx.effect(() => {
|
|
748
|
+
const bootTimer = setTimeout(() => {
|
|
749
|
+
void boot()
|
|
750
|
+
}, 1500)
|
|
751
|
+
const watchdog = setInterval(() => {
|
|
752
|
+
if (desired && !busy) void boot()
|
|
753
|
+
}, 30000)
|
|
754
|
+
return () => {
|
|
755
|
+
clearTimeout(bootTimer)
|
|
756
|
+
clearInterval(watchdog)
|
|
757
|
+
}
|
|
758
|
+
}, 'opencode2api autostart')
|
|
759
|
+
}
|
|
760
|
+
ctx.inject(['dshGo'], (ctx) => {
|
|
761
|
+
registerUi(ctx)
|
|
762
|
+
})
|
|
763
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,89 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-opencode2api",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
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).",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/king-andthe-nice/dsh-plugin-opencode2api.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://github.com/king-andthe-nice/dsh-plugin-opencode2api#readme",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "lib/index.js",
|
|
13
|
+
"files": [
|
|
14
|
+
"lib",
|
|
15
|
+
"cordis.patch.yml",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE",
|
|
18
|
+
"THIRD_PARTY_NOTICES.md"
|
|
19
|
+
],
|
|
20
|
+
"keywords": [
|
|
21
|
+
"dsh-plugin",
|
|
22
|
+
"dsh-go",
|
|
23
|
+
"opencode",
|
|
24
|
+
"opencode2api",
|
|
25
|
+
"gateway",
|
|
26
|
+
"openai-compatible",
|
|
27
|
+
"free-api"
|
|
28
|
+
],
|
|
29
|
+
"private": false,
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"dsh": {
|
|
34
|
+
"bundle": {
|
|
35
|
+
"patch": "./cordis.patch.yml"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"engines": {
|
|
39
|
+
"dsh": ">=0.2.1-rc.2 <0.3.0-0"
|
|
40
|
+
},
|
|
41
|
+
"dshGo": {
|
|
42
|
+
"v": 1,
|
|
43
|
+
"title": {
|
|
44
|
+
"zh": "本地免费 API",
|
|
45
|
+
"en": "Local Free API"
|
|
46
|
+
},
|
|
47
|
+
"icon": "server",
|
|
48
|
+
"contributes": {
|
|
49
|
+
"composer.actions": [
|
|
50
|
+
{
|
|
51
|
+
"id": "open-gateway",
|
|
52
|
+
"label": {
|
|
53
|
+
"zh": "本地API",
|
|
54
|
+
"en": "Local API"
|
|
55
|
+
},
|
|
56
|
+
"icon": "server",
|
|
57
|
+
"effect": [
|
|
58
|
+
{
|
|
59
|
+
"type": "open",
|
|
60
|
+
"page": "panel:gateway"
|
|
61
|
+
}
|
|
62
|
+
]
|
|
63
|
+
}
|
|
64
|
+
],
|
|
65
|
+
"composer.strip": [
|
|
66
|
+
{
|
|
67
|
+
"id": "status",
|
|
68
|
+
"icon": "server",
|
|
69
|
+
"panel": "gateway"
|
|
70
|
+
}
|
|
71
|
+
],
|
|
72
|
+
"panels": [
|
|
73
|
+
{
|
|
74
|
+
"id": "gateway",
|
|
75
|
+
"title": {
|
|
76
|
+
"zh": "本地免费 API",
|
|
77
|
+
"en": "Local Free API"
|
|
78
|
+
},
|
|
79
|
+
"icon": "server",
|
|
80
|
+
"placement": [
|
|
81
|
+
"session.tab",
|
|
82
|
+
"features",
|
|
83
|
+
"plugin"
|
|
84
|
+
]
|
|
85
|
+
}
|
|
86
|
+
]
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|