haoyuan 1.0.0 → 1.1.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 +53 -13
- package/api/configs/secrets.py +27 -0
- package/api/tests/test_secrets_config.py +61 -0
- package/bin/haoyuan.js +761 -48
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -109,6 +109,37 @@ Kernel(会话 / 事件 / 工具注册 / 策略 / 模型网关 / 审批)
|
|
|
109
109
|
- Node.js 18+
|
|
110
110
|
- Windows / Linux / macOS
|
|
111
111
|
|
|
112
|
+
### npm 安装(推荐)
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
# 前提:Node.js 18+、Python 3.10+
|
|
116
|
+
npm install -g haoyuan
|
|
117
|
+
|
|
118
|
+
# 国内加速:
|
|
119
|
+
npm install -g haoyuan --registry=https://registry.npmmirror.com
|
|
120
|
+
|
|
121
|
+
# 终端对话(首次自动创建 venv、安装依赖)
|
|
122
|
+
haoyuan
|
|
123
|
+
|
|
124
|
+
# 启动服务并自动打开网页
|
|
125
|
+
haoyuan web
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
| 命令 | 作用 |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `haoyuan` | 终端对话(流式输出、工具调用、审批确认) |
|
|
131
|
+
| `haoyuan web` | 启动服务并自动打开网页 |
|
|
132
|
+
| `haoyuan web --no-open` | 启动服务但不打开浏览器 |
|
|
133
|
+
| `haoyuan --version` / `-V` | 查看版本号 |
|
|
134
|
+
| `haoyuan config` | 全局配置文件(模型 Key 等),`--open` 直接打开编辑 |
|
|
135
|
+
| `haoyuan login` / `haoyuan logout` | 账号保护开启时登录 / 清除本地令牌 |
|
|
136
|
+
| `haoyuan setup` | 仅预装依赖 |
|
|
137
|
+
| `haoyuan help` | 显示帮助 |
|
|
138
|
+
|
|
139
|
+
终端内命令:`/new` 新建会话、`/web` 在浏览器打开当前会话、`/cancel` 取消当前任务、`/exit` 退出(Ctrl+C 同样有效)。
|
|
140
|
+
|
|
141
|
+
网页默认地址 `http://127.0.0.1:8030`,端口被占用自动 +1。未配置模型 Key 时使用内置 `mock` 模型,会话、工具调用、审批与前端均可完整运行。
|
|
142
|
+
|
|
112
143
|
### Windows 一键启动
|
|
113
144
|
|
|
114
145
|
```bat
|
|
@@ -164,32 +195,41 @@ npm run dev # http://localhost:8130,被占用时自动 +1
|
|
|
164
195
|
|
|
165
196
|
### 配置模型
|
|
166
197
|
|
|
198
|
+
**全局配置文件(推荐)** —— 固定用户级路径,重装/升级不受影响:
|
|
199
|
+
|
|
167
200
|
```bash
|
|
168
|
-
|
|
201
|
+
haoyuan config # 首次运行自动创建配置文件并显示路径
|
|
202
|
+
haoyuan config --open # 直接在编辑器中打开
|
|
169
203
|
```
|
|
170
204
|
|
|
171
|
-
|
|
205
|
+
路径:`~/.config/haoyuan/config.json`(Windows 即 `C:\Users\<你>\.config\haoyuan\config.json`,可用环境变量 `HAOYUAN_CONFIG` 覆盖):
|
|
172
206
|
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
207
|
+
```json
|
|
208
|
+
{
|
|
209
|
+
"DEEPSEEK_API_KEY": "sk-...",
|
|
210
|
+
"DEEPSEEK_BASE_URL": "https://api.deepseek.com",
|
|
211
|
+
"DEEPSEEK_MODEL": "deepseek-flash",
|
|
212
|
+
"ZHIPU_API_KEY": "",
|
|
213
|
+
"MIMO_API_KEY": ""
|
|
214
|
+
}
|
|
215
|
+
```
|
|
177
216
|
|
|
178
|
-
|
|
179
|
-
ZHIPU_API_KEY = ""
|
|
217
|
+
**包内配置(可选)**:
|
|
180
218
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
MIMO_BASE_URL = "https://token-plan-cn.xiaomimimo.com/v1"
|
|
184
|
-
MIMO_MODEL = "mimo-v2.6-flash"
|
|
219
|
+
```bash
|
|
220
|
+
copy api\configs\secrets_example.py api\configs\secrets_local.py
|
|
185
221
|
```
|
|
186
222
|
|
|
187
|
-
|
|
223
|
+
编辑 `api/configs/secrets_local.py`,字段同上(Python 常量格式)。适用于源码部署;npm 全局安装时该文件位于包目录内,升级会被清除,建议优先用全局配置。
|
|
224
|
+
|
|
225
|
+
**环境变量**(优先级最高):
|
|
188
226
|
|
|
189
227
|
```powershell
|
|
190
228
|
$env:DEEPSEEK_API_KEY="sk-..."
|
|
191
229
|
```
|
|
192
230
|
|
|
231
|
+
优先级:环境变量 > 全局配置文件 > `secrets_local.py`。保存后重新运行 `haoyuan` 生效;服务健康检查 `GET /api/health` 的 `key_source` 会显示 Key 来源。
|
|
232
|
+
|
|
193
233
|
**未配置任何 Key 时自动使用本地 `mock` 模型**,完整跑通会话、工具调用、审批、事件与前端。
|
|
194
234
|
|
|
195
235
|
---
|
package/api/configs/secrets.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import json
|
|
3
4
|
import os
|
|
5
|
+
from pathlib import Path
|
|
4
6
|
|
|
5
7
|
try:
|
|
6
8
|
from configs import secrets_local as _local
|
|
@@ -8,10 +10,33 @@ except ImportError:
|
|
|
8
10
|
_local = None
|
|
9
11
|
|
|
10
12
|
|
|
13
|
+
def config_path() -> Path:
|
|
14
|
+
"""全局配置文件路径(与 opencode 类似的固定用户级路径)。"""
|
|
15
|
+
override = os.getenv("HAOYUAN_CONFIG")
|
|
16
|
+
if override:
|
|
17
|
+
return Path(override).expanduser()
|
|
18
|
+
return Path.home() / ".config" / "haoyuan" / "config.json"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _read_global_config() -> dict:
|
|
22
|
+
try:
|
|
23
|
+
with config_path().open("r", encoding="utf-8-sig") as fh:
|
|
24
|
+
data = json.load(fh)
|
|
25
|
+
return data if isinstance(data, dict) else {}
|
|
26
|
+
except Exception:
|
|
27
|
+
return {}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_GLOBAL_CONFIG = _read_global_config()
|
|
31
|
+
|
|
32
|
+
|
|
11
33
|
def _get(name: str, default: str = "") -> str:
|
|
12
34
|
env_value = os.getenv(name)
|
|
13
35
|
if env_value is not None and env_value.strip():
|
|
14
36
|
return env_value.strip()
|
|
37
|
+
global_value = _GLOBAL_CONFIG.get(name)
|
|
38
|
+
if global_value is not None and str(global_value).strip():
|
|
39
|
+
return str(global_value).strip()
|
|
15
40
|
if _local is not None:
|
|
16
41
|
local_value = getattr(_local, name, None)
|
|
17
42
|
if local_value is not None and str(local_value).strip():
|
|
@@ -41,6 +66,8 @@ def get_secret(name: str, default: str = "") -> str:
|
|
|
41
66
|
def secret_source(name: str) -> str:
|
|
42
67
|
if os.getenv(name, "").strip():
|
|
43
68
|
return "env"
|
|
69
|
+
if _GLOBAL_CONFIG.get(name) is not None and str(_GLOBAL_CONFIG.get(name) or "").strip():
|
|
70
|
+
return str(config_path())
|
|
44
71
|
if _local is not None and str(getattr(_local, name, "") or "").strip():
|
|
45
72
|
return "configs/secrets_local.py"
|
|
46
73
|
return "default"
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from configs import secrets as secrets_mod
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _reload():
|
|
12
|
+
return importlib.reload(secrets_mod)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@pytest.fixture(autouse=True)
|
|
16
|
+
def _restore_module(monkeypatch):
|
|
17
|
+
yield
|
|
18
|
+
monkeypatch.delenv("HAOYUAN_CONFIG", raising=False)
|
|
19
|
+
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
|
20
|
+
_reload()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_global_config_file_priority(tmp_path, monkeypatch):
|
|
24
|
+
cfg_file = tmp_path / "config.json"
|
|
25
|
+
cfg_file.write_text(
|
|
26
|
+
json.dumps({"DEEPSEEK_API_KEY": "sk-global-123", "DEEPSEEK_MODEL": "deepseek-flash"}),
|
|
27
|
+
encoding="utf-8",
|
|
28
|
+
)
|
|
29
|
+
monkeypatch.setenv("HAOYUAN_CONFIG", str(cfg_file))
|
|
30
|
+
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
|
31
|
+
mod = _reload()
|
|
32
|
+
assert mod.DEEPSEEK_API_KEY == "sk-global-123"
|
|
33
|
+
assert mod.secret_source("DEEPSEEK_API_KEY") == str(cfg_file)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_env_overrides_global_config(tmp_path, monkeypatch):
|
|
37
|
+
cfg_file = tmp_path / "config.json"
|
|
38
|
+
cfg_file.write_text(json.dumps({"DEEPSEEK_API_KEY": "sk-global"}), encoding="utf-8")
|
|
39
|
+
monkeypatch.setenv("HAOYUAN_CONFIG", str(cfg_file))
|
|
40
|
+
monkeypatch.setenv("DEEPSEEK_API_KEY", "sk-env")
|
|
41
|
+
mod = _reload()
|
|
42
|
+
assert mod.DEEPSEEK_API_KEY == "sk-env"
|
|
43
|
+
assert mod.secret_source("DEEPSEEK_API_KEY") == "env"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_invalid_global_config_ignored(tmp_path, monkeypatch):
|
|
47
|
+
cfg_file = tmp_path / "config.json"
|
|
48
|
+
cfg_file.write_text('{"DEEPSEEK_API_KEY": "sk-should-not-apply"', encoding="utf-8")
|
|
49
|
+
monkeypatch.setenv("HAOYUAN_CONFIG", str(cfg_file))
|
|
50
|
+
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
|
51
|
+
mod = _reload()
|
|
52
|
+
assert mod.DEEPSEEK_API_KEY != "sk-should-not-apply"
|
|
53
|
+
assert mod.secret_source("DEEPSEEK_API_KEY") != str(cfg_file)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_local_file_fallback(tmp_path, monkeypatch):
|
|
57
|
+
monkeypatch.setenv("HAOYUAN_CONFIG", str(tmp_path / "missing.json"))
|
|
58
|
+
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
|
|
59
|
+
mod = _reload()
|
|
60
|
+
assert mod.DEEPSEEK_API_KEY != "sk-from-nowhere"
|
|
61
|
+
assert mod.secret_source("DEEPSEEK_API_KEY") in {"configs/secrets_local.py", "default"}
|
package/bin/haoyuan.js
CHANGED
|
@@ -3,9 +3,18 @@
|
|
|
3
3
|
|
|
4
4
|
const { spawn, spawnSync } = require("child_process");
|
|
5
5
|
const fs = require("fs");
|
|
6
|
+
const http = require("http");
|
|
7
|
+
const os = require("os");
|
|
6
8
|
const path = require("path");
|
|
9
|
+
const readline = require("readline");
|
|
7
10
|
|
|
8
11
|
const ROOT = path.resolve(__dirname, "..");
|
|
12
|
+
let VERSION = "0.0.0";
|
|
13
|
+
try {
|
|
14
|
+
VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version || VERSION;
|
|
15
|
+
} catch {
|
|
16
|
+
/* ignore */
|
|
17
|
+
}
|
|
9
18
|
const IS_WIN = process.platform === "win32";
|
|
10
19
|
const NPM = IS_WIN ? "npm.cmd" : "npm";
|
|
11
20
|
const VENV = path.join(ROOT, "api", "env1");
|
|
@@ -16,6 +25,48 @@ const WEB = path.join(ROOT, "web");
|
|
|
16
25
|
const API = path.join(ROOT, "api");
|
|
17
26
|
const RUNTIME_FILE = path.join(API, "data", "runtime.json");
|
|
18
27
|
const DIST_INDEX = path.join(WEB, "dist", "index.html");
|
|
28
|
+
const TOKEN_FILE = path.join(API, "data", "cli-token");
|
|
29
|
+
let TOKEN = (process.env.HAOYUAN_TOKEN || "").trim();
|
|
30
|
+
if (!TOKEN) {
|
|
31
|
+
try {
|
|
32
|
+
TOKEN = fs.readFileSync(TOKEN_FILE, "utf8").trim();
|
|
33
|
+
} catch {
|
|
34
|
+
TOKEN = "";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function saveToken(token) {
|
|
39
|
+
TOKEN = token;
|
|
40
|
+
try {
|
|
41
|
+
fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true });
|
|
42
|
+
fs.writeFileSync(TOKEN_FILE, token);
|
|
43
|
+
return true;
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function clearToken() {
|
|
50
|
+
TOKEN = "";
|
|
51
|
+
try {
|
|
52
|
+
fs.unlinkSync(TOKEN_FILE);
|
|
53
|
+
} catch {
|
|
54
|
+
/* ignore */
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
59
|
+
const C = COLOR
|
|
60
|
+
? {
|
|
61
|
+
reset: "\x1b[0m",
|
|
62
|
+
dim: "\x1b[2m",
|
|
63
|
+
bold: "\x1b[1m",
|
|
64
|
+
cyan: "\x1b[36m",
|
|
65
|
+
green: "\x1b[32m",
|
|
66
|
+
red: "\x1b[31m",
|
|
67
|
+
yellow: "\x1b[33m",
|
|
68
|
+
}
|
|
69
|
+
: { reset: "", dim: "", bold: "", cyan: "", green: "", red: "", yellow: "" };
|
|
19
70
|
|
|
20
71
|
function log(msg) {
|
|
21
72
|
process.stdout.write(`[HaoYuan] ${msg}\n`);
|
|
@@ -38,8 +89,7 @@ function shellQuote(s) {
|
|
|
38
89
|
function run(cmd, args, opts = {}) {
|
|
39
90
|
const lenient = opts.lenient === true;
|
|
40
91
|
const useShell = IS_WIN && /\.(cmd|bat)$/i.test(cmd);
|
|
41
|
-
|
|
42
|
-
log(display);
|
|
92
|
+
log(`${cmd} ${args.join(" ")}`);
|
|
43
93
|
const r = spawnSync(
|
|
44
94
|
cmd,
|
|
45
95
|
useShell ? args.map(shellQuote) : args,
|
|
@@ -121,20 +171,23 @@ function readApiPort() {
|
|
|
121
171
|
}
|
|
122
172
|
}
|
|
123
173
|
|
|
174
|
+
async function healthyPort(port) {
|
|
175
|
+
if (!port) return false;
|
|
176
|
+
try {
|
|
177
|
+
const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
|
|
178
|
+
signal: AbortSignal.timeout(2000),
|
|
179
|
+
});
|
|
180
|
+
return res.ok;
|
|
181
|
+
} catch {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
124
186
|
async function waitUntilHealthy(timeoutMs = 180000) {
|
|
125
187
|
const deadline = Date.now() + timeoutMs;
|
|
126
188
|
while (Date.now() < deadline) {
|
|
127
189
|
const port = readApiPort();
|
|
128
|
-
if (port)
|
|
129
|
-
try {
|
|
130
|
-
const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
|
|
131
|
-
signal: AbortSignal.timeout(1500),
|
|
132
|
-
});
|
|
133
|
-
if (res.ok) return port;
|
|
134
|
-
} catch {
|
|
135
|
-
/* 服务未就绪,继续等待 */
|
|
136
|
-
}
|
|
137
|
-
}
|
|
190
|
+
if (await healthyPort(port)) return port;
|
|
138
191
|
await new Promise((r) => setTimeout(r, 500));
|
|
139
192
|
}
|
|
140
193
|
return 0;
|
|
@@ -169,7 +222,16 @@ function postinstall() {
|
|
|
169
222
|
}
|
|
170
223
|
}
|
|
171
224
|
|
|
172
|
-
async function
|
|
225
|
+
async function web(options = {}) {
|
|
226
|
+
const running = await healthyPort(readApiPort());
|
|
227
|
+
if (running) {
|
|
228
|
+
const url = `http://127.0.0.1:${running}`;
|
|
229
|
+
log(`服务已在运行: ${url}`);
|
|
230
|
+
if (options.noOpen) log(`(--no-open 模式,请手动打开 ${url})`);
|
|
231
|
+
else openBrowser(url);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
|
|
173
235
|
if (!fs.existsSync(PYTHON)) {
|
|
174
236
|
log("首次运行,安装后端依赖 ...");
|
|
175
237
|
setup({ build: !fs.existsSync(DIST_INDEX) });
|
|
@@ -203,44 +265,695 @@ async function start(options = {}) {
|
|
|
203
265
|
}
|
|
204
266
|
}
|
|
205
267
|
|
|
206
|
-
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
268
|
+
async function ensureServer() {
|
|
269
|
+
const running = await healthyPort(readApiPort());
|
|
270
|
+
if (running) return { port: running, child: null };
|
|
271
|
+
|
|
272
|
+
if (!fs.existsSync(PYTHON)) {
|
|
273
|
+
log("首次运行,安装后端依赖 ...");
|
|
274
|
+
setup({ build: !fs.existsSync(DIST_INDEX) });
|
|
275
|
+
}
|
|
276
|
+
if (!fs.existsSync(DIST_INDEX)) buildFrontend();
|
|
277
|
+
|
|
278
|
+
log("启动 API(端口 8030,被占用时自动顺延)...");
|
|
279
|
+
let tail = "";
|
|
280
|
+
const child = spawn(PYTHON, ["main.py"], {
|
|
281
|
+
cwd: API,
|
|
282
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
283
|
+
env: process.env,
|
|
284
|
+
});
|
|
285
|
+
const keep = (chunk) => {
|
|
286
|
+
tail = (tail + chunk.toString()).slice(-4000);
|
|
287
|
+
};
|
|
288
|
+
child.stdout.on("data", keep);
|
|
289
|
+
child.stderr.on("data", keep);
|
|
290
|
+
child.on("error", (err) => {
|
|
291
|
+
warn(`服务启动失败: ${err.message}`);
|
|
292
|
+
process.exit(1);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
const port = await waitUntilHealthy();
|
|
296
|
+
if (!port) {
|
|
297
|
+
child.kill();
|
|
298
|
+
warn("服务启动超时。服务日志:");
|
|
299
|
+
if (tail) process.stderr.write(tail + "\n");
|
|
300
|
+
process.exit(1);
|
|
301
|
+
}
|
|
302
|
+
log(`服务已就绪: http://127.0.0.1:${port}`);
|
|
303
|
+
return { port, child };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function apiHeaders() {
|
|
307
|
+
const headers = { "content-type": "application/json" };
|
|
308
|
+
if (TOKEN) {
|
|
309
|
+
headers["authorization"] = `Bearer ${TOKEN}`;
|
|
310
|
+
headers["x-haoyuan-token"] = TOKEN;
|
|
311
|
+
}
|
|
312
|
+
return headers;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function apiJson(port, method, apiPath, body) {
|
|
316
|
+
const res = await fetch(`http://127.0.0.1:${port}${apiPath}`, {
|
|
317
|
+
method,
|
|
318
|
+
headers: apiHeaders(),
|
|
319
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
320
|
+
signal: AbortSignal.timeout(30000),
|
|
321
|
+
});
|
|
322
|
+
let payload = null;
|
|
323
|
+
try {
|
|
324
|
+
payload = await res.json();
|
|
325
|
+
} catch {
|
|
326
|
+
/* ignore */
|
|
327
|
+
}
|
|
328
|
+
if (!payload || payload.code !== 200) {
|
|
329
|
+
throw new Error((payload && payload.message) || `HTTP ${res.status}`);
|
|
330
|
+
}
|
|
331
|
+
return payload.data;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function shortJson(value, limit = 120) {
|
|
335
|
+
let text;
|
|
336
|
+
try {
|
|
337
|
+
text = JSON.stringify(value);
|
|
338
|
+
} catch {
|
|
339
|
+
text = String(value);
|
|
340
|
+
}
|
|
341
|
+
if (!text) text = "";
|
|
342
|
+
return text.length > limit ? `${text.slice(0, limit)}…` : text;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function ask(rl, promptText, { mute = false } = {}) {
|
|
346
|
+
return new Promise((resolve) => {
|
|
347
|
+
if (!mute) {
|
|
348
|
+
rl.question(promptText, resolve);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
process.stdout.write(promptText);
|
|
352
|
+
const original = rl._writeToOutput;
|
|
353
|
+
rl._writeToOutput = () => {};
|
|
354
|
+
rl.question("", (answer) => {
|
|
355
|
+
rl._writeToOutput = original;
|
|
356
|
+
process.stdout.write("\n");
|
|
357
|
+
resolve(answer);
|
|
358
|
+
});
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function loginAt(port, rl) {
|
|
363
|
+
const statusRes = await fetch(`http://127.0.0.1:${port}/api/auth/status`, {
|
|
364
|
+
signal: AbortSignal.timeout(10000),
|
|
365
|
+
});
|
|
366
|
+
const status = await statusRes.json().catch(() => null);
|
|
367
|
+
const data = (status && status.data) || {};
|
|
368
|
+
if (!data.configured) {
|
|
369
|
+
log("该实例未开启账号保护,无需登录。");
|
|
370
|
+
return "";
|
|
371
|
+
}
|
|
372
|
+
const username = (await ask(rl, `用户名${data.username ? `(${data.username})` : ""}: `)).trim();
|
|
373
|
+
const password = await ask(rl, "密码: ", { mute: true });
|
|
374
|
+
const res = await fetch(`http://127.0.0.1:${port}/api/auth/login`, {
|
|
375
|
+
method: "POST",
|
|
376
|
+
headers: { "content-type": "application/json" },
|
|
377
|
+
body: JSON.stringify({ username, password }),
|
|
378
|
+
signal: AbortSignal.timeout(15000),
|
|
379
|
+
});
|
|
380
|
+
const payload = await res.json().catch(() => null);
|
|
381
|
+
if (!payload || payload.code !== 200) {
|
|
382
|
+
throw new Error((payload && payload.message) || `HTTP ${res.status}`);
|
|
383
|
+
}
|
|
384
|
+
saveToken(payload.data.token);
|
|
385
|
+
log(`已登录: ${payload.data.username || username}`);
|
|
386
|
+
return payload.data.token;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
async function loginCommand() {
|
|
390
|
+
const { port, child } = await ensureServer();
|
|
391
|
+
const rl = readline.createInterface({
|
|
392
|
+
input: process.stdin,
|
|
393
|
+
output: process.stdout,
|
|
394
|
+
terminal: process.stdin.isTTY === true,
|
|
395
|
+
});
|
|
396
|
+
try {
|
|
397
|
+
await loginAt(port, rl);
|
|
398
|
+
} catch (err) {
|
|
399
|
+
warn(`登录失败: ${err.message}`);
|
|
400
|
+
} finally {
|
|
401
|
+
try {
|
|
402
|
+
rl.close();
|
|
403
|
+
} catch {
|
|
404
|
+
/* ignore */
|
|
405
|
+
}
|
|
406
|
+
if (child) {
|
|
407
|
+
try {
|
|
408
|
+
child.kill();
|
|
409
|
+
} catch {
|
|
410
|
+
/* ignore */
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function logoutCommand() {
|
|
417
|
+
clearToken();
|
|
418
|
+
log("已清除本地 CLI 令牌。");
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const CONFIG_TEMPLATE = JSON.stringify(
|
|
422
|
+
{
|
|
423
|
+
DEEPSEEK_API_KEY: "",
|
|
424
|
+
DEEPSEEK_BASE_URL: "https://api.deepseek.com",
|
|
425
|
+
DEEPSEEK_MODEL: "deepseek-flash",
|
|
426
|
+
ZHIPU_API_KEY: "",
|
|
427
|
+
MIMO_API_KEY: "",
|
|
428
|
+
},
|
|
429
|
+
null,
|
|
430
|
+
2
|
|
431
|
+
);
|
|
432
|
+
|
|
433
|
+
function configFilePath() {
|
|
434
|
+
return process.env.HAOYUAN_CONFIG
|
|
435
|
+
? path.resolve(process.env.HAOYUAN_CONFIG)
|
|
436
|
+
: path.join(os.homedir(), ".config", "haoyuan", "config.json");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function configCommand({ open = false } = {}) {
|
|
440
|
+
const file = configFilePath();
|
|
441
|
+
let created = false;
|
|
442
|
+
if (!fs.existsSync(file)) {
|
|
443
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
444
|
+
fs.writeFileSync(file, `${CONFIG_TEMPLATE}\n`);
|
|
445
|
+
created = true;
|
|
446
|
+
}
|
|
447
|
+
log(`全局配置文件: ${file}${created ? "(已创建)" : ""}`);
|
|
448
|
+
if (open && IS_WIN) {
|
|
449
|
+
spawn("cmd", ["/c", "start", "", "notepad.exe", file], { detached: true, stdio: "ignore" }).unref();
|
|
450
|
+
} else if (open && process.platform === "darwin") {
|
|
451
|
+
spawn("open", [file], { detached: true, stdio: "ignore" }).unref();
|
|
452
|
+
} else if (open) {
|
|
453
|
+
spawn("xdg-open", [file], { detached: true, stdio: "ignore" }).unref();
|
|
454
|
+
}
|
|
455
|
+
process.stdout.write(
|
|
456
|
+
[
|
|
457
|
+
"",
|
|
458
|
+
"填写示例(JSON,优先级:环境变量 > 本文件 > api/configs/secrets_local.py):",
|
|
459
|
+
CONFIG_TEMPLATE.replace(/: "",/g, ': "",'),
|
|
460
|
+
"",
|
|
461
|
+
"保存后重新运行 haoyuan 生效。",
|
|
462
|
+
"",
|
|
463
|
+
].join("\n")
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
async function chat() {
|
|
468
|
+
const { port, child: serverChild } = await ensureServer();
|
|
469
|
+
|
|
470
|
+
const die = (msg) => {
|
|
471
|
+
if (serverChild) {
|
|
472
|
+
try {
|
|
473
|
+
serverChild.kill();
|
|
474
|
+
} catch {
|
|
475
|
+
/* ignore */
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
fail(msg);
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
const state = {
|
|
482
|
+
sessionId: "",
|
|
483
|
+
busy: false,
|
|
484
|
+
approval: null,
|
|
485
|
+
inText: false,
|
|
486
|
+
inReasoning: false,
|
|
487
|
+
streamReq: null,
|
|
488
|
+
lastEventId: 0,
|
|
489
|
+
closing: false,
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
let rl = null;
|
|
493
|
+
|
|
494
|
+
function prompt() {
|
|
495
|
+
if (state.closing) return;
|
|
496
|
+
rl.setPrompt(`${C.cyan}>${C.reset} `);
|
|
497
|
+
rl.prompt();
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function endLine() {
|
|
501
|
+
if (state.inText || state.inReasoning) {
|
|
502
|
+
process.stdout.write(`${C.reset}\n`);
|
|
503
|
+
state.inText = false;
|
|
504
|
+
state.inReasoning = false;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function shutdown(code = 0) {
|
|
509
|
+
state.closing = true;
|
|
510
|
+
closeStream();
|
|
511
|
+
try {
|
|
512
|
+
rl.close();
|
|
513
|
+
} catch {
|
|
514
|
+
/* ignore */
|
|
515
|
+
}
|
|
516
|
+
if (serverChild) {
|
|
517
|
+
try {
|
|
518
|
+
serverChild.kill();
|
|
519
|
+
} catch {
|
|
520
|
+
/* ignore */
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
process.exit(code);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function closeStream() {
|
|
527
|
+
if (state.streamReq) {
|
|
528
|
+
try {
|
|
529
|
+
state.streamReq.destroy();
|
|
530
|
+
} catch {
|
|
531
|
+
/* ignore */
|
|
532
|
+
}
|
|
533
|
+
state.streamReq = null;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function openStream() {
|
|
538
|
+
if (state.streamReq || state.closing) return;
|
|
539
|
+
const qs = `after_id=${state.lastEventId}${TOKEN ? `&token=${encodeURIComponent(TOKEN)}` : ""}`;
|
|
540
|
+
const headers = { Accept: "text/event-stream" };
|
|
541
|
+
if (TOKEN) headers["x-haoyuan-token"] = TOKEN;
|
|
542
|
+
const req = http.get(
|
|
543
|
+
{
|
|
544
|
+
host: "127.0.0.1",
|
|
545
|
+
port,
|
|
546
|
+
path: `/api/sessions/${encodeURIComponent(state.sessionId)}/stream?${qs}`,
|
|
547
|
+
headers,
|
|
548
|
+
},
|
|
549
|
+
(res) => {
|
|
550
|
+
if (res.statusCode !== 200) {
|
|
551
|
+
res.resume();
|
|
552
|
+
state.streamReq = null;
|
|
553
|
+
if (state.busy) setTimeout(openStream, 500);
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
let buf = "";
|
|
557
|
+
res.setEncoding("utf8");
|
|
558
|
+
res.on("data", (chunk) => {
|
|
559
|
+
buf += chunk;
|
|
560
|
+
let idx;
|
|
561
|
+
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
562
|
+
const block = buf.slice(0, idx);
|
|
563
|
+
buf = buf.slice(idx + 2);
|
|
564
|
+
const data = block
|
|
565
|
+
.split("\n")
|
|
566
|
+
.filter((line) => line.startsWith("data:"))
|
|
567
|
+
.map((line) => line.slice(5).trim())
|
|
568
|
+
.join("");
|
|
569
|
+
if (!data) continue;
|
|
570
|
+
let event;
|
|
571
|
+
try {
|
|
572
|
+
event = JSON.parse(data);
|
|
573
|
+
} catch {
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
handleEvent(event);
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
res.on("end", () => {
|
|
580
|
+
state.streamReq = null;
|
|
581
|
+
if (state.busy && !state.closing) setTimeout(openStream, 600);
|
|
582
|
+
});
|
|
583
|
+
res.on("error", () => {
|
|
584
|
+
state.streamReq = null;
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
);
|
|
588
|
+
req.on("error", () => {
|
|
589
|
+
state.streamReq = null;
|
|
590
|
+
if (state.busy && !state.closing) setTimeout(openStream, 800);
|
|
591
|
+
});
|
|
592
|
+
state.streamReq = req;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function handleEvent(event) {
|
|
596
|
+
if (event && event.id !== undefined) {
|
|
597
|
+
const id = Number(event.id);
|
|
598
|
+
if (Number.isFinite(id) && id > state.lastEventId) state.lastEventId = id;
|
|
599
|
+
}
|
|
600
|
+
const type = event.type || event.event;
|
|
601
|
+
const payload = event.payload || {};
|
|
602
|
+
|
|
603
|
+
if (type === "stream.end") {
|
|
604
|
+
state.streamReq = null;
|
|
605
|
+
if (state.busy) {
|
|
606
|
+
state.busy = false;
|
|
607
|
+
endLine();
|
|
608
|
+
prompt();
|
|
609
|
+
}
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
if (type === "delta") {
|
|
614
|
+
if (state.inReasoning) {
|
|
615
|
+
process.stdout.write(`${C.reset}\n`);
|
|
616
|
+
state.inReasoning = false;
|
|
617
|
+
}
|
|
618
|
+
if (!state.inText) {
|
|
619
|
+
process.stdout.write(`${C.bold}[助手]${C.reset} `);
|
|
620
|
+
state.inText = true;
|
|
621
|
+
}
|
|
622
|
+
if (payload.text) process.stdout.write(payload.text);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
if (type === "reasoning") {
|
|
627
|
+
if (payload.text) {
|
|
628
|
+
if (!state.inReasoning) {
|
|
629
|
+
process.stdout.write(`${C.dim}[思考] `);
|
|
630
|
+
state.inReasoning = true;
|
|
631
|
+
}
|
|
632
|
+
process.stdout.write(payload.text);
|
|
633
|
+
}
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
if (type === "tool.start") {
|
|
638
|
+
endLine();
|
|
639
|
+
process.stdout.write(`${C.cyan}[工具]${C.reset} ${payload.tool} ${C.dim}${shortJson(payload.args)}${C.reset}\n`);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
if (type === "tool.end") {
|
|
644
|
+
const mark = payload.ok ? `${C.green}[完成]${C.reset}` : `${C.red}[失败]${C.reset}`;
|
|
645
|
+
const ms = payload.ms != null ? ` ${C.dim}${payload.ms}ms${C.reset}` : "";
|
|
646
|
+
const detail = payload.ok ? payload.summary || "" : payload.error || "";
|
|
647
|
+
process.stdout.write(`${mark} ${payload.tool}${ms}${detail ? ` ${C.dim}${shortJson(detail, 160)}${C.reset}` : ""}\n`);
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
if (type === "approval.required") {
|
|
652
|
+
endLine();
|
|
653
|
+
state.approval = payload;
|
|
654
|
+
process.stdout.write(
|
|
655
|
+
`${C.yellow}[审批]${C.reset} ${payload.tool} 需要确认 ${C.dim}${shortJson(payload.args, 200)}${C.reset}\n`
|
|
656
|
+
);
|
|
657
|
+
if (payload.preview) {
|
|
658
|
+
process.stdout.write(`${C.dim}${shortJson(payload.preview, 400)}${C.reset}\n`);
|
|
659
|
+
}
|
|
660
|
+
rl.setPrompt(`${C.yellow}批准执行? (y/N)${C.reset} `);
|
|
661
|
+
rl.prompt();
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
if (type === "approval.resolved") {
|
|
666
|
+
state.approval = null;
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
if (type === "error") {
|
|
671
|
+
endLine();
|
|
672
|
+
process.stdout.write(`${C.red}[错误] ${payload.message || "未知错误"}${C.reset}\n`);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
if (type === "done") {
|
|
677
|
+
if (!state.inText && payload.text) {
|
|
678
|
+
process.stdout.write(`${C.bold}[助手]${C.reset} ${payload.text}\n`);
|
|
679
|
+
}
|
|
680
|
+
endLine();
|
|
681
|
+
if (state.busy) {
|
|
682
|
+
state.busy = false;
|
|
683
|
+
prompt();
|
|
684
|
+
}
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
if (type === "session.status") {
|
|
689
|
+
if (payload.status === "error" && payload.error) {
|
|
690
|
+
endLine();
|
|
691
|
+
process.stdout.write(`${C.red}[错误] ${payload.error}${C.reset}\n`);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
async function resolveApproval(approved) {
|
|
697
|
+
const approval = state.approval;
|
|
698
|
+
state.approval = null;
|
|
699
|
+
rl.setPrompt(`${C.cyan}>${C.reset} `);
|
|
700
|
+
if (!approval) return;
|
|
701
|
+
try {
|
|
702
|
+
await apiJson(port, "POST", `/api/approvals/${encodeURIComponent(approval.approval_id)}/resolve`, {
|
|
703
|
+
approved,
|
|
704
|
+
reason: approved ? "approved from CLI" : "rejected from CLI",
|
|
705
|
+
});
|
|
706
|
+
process.stdout.write(`${approved ? C.green : C.red}[${approved ? "已批准" : "已拒绝"}]${C.reset}\n`);
|
|
707
|
+
} catch (err) {
|
|
708
|
+
warn(`审批提交失败: ${err.message}`);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
async function newSession() {
|
|
713
|
+
const data = await apiJson(port, "POST", "/api/sessions", {
|
|
714
|
+
kind: "auto",
|
|
715
|
+
workspace: process.cwd(),
|
|
716
|
+
});
|
|
717
|
+
state.sessionId = data.id;
|
|
718
|
+
state.lastEventId = 0;
|
|
719
|
+
openStream();
|
|
720
|
+
return data;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async function sendMessage(text) {
|
|
724
|
+
state.busy = true;
|
|
725
|
+
try {
|
|
726
|
+
await apiJson(port, "POST", `/api/sessions/${encodeURIComponent(state.sessionId)}/messages`, {
|
|
727
|
+
content: text,
|
|
728
|
+
locale: "",
|
|
729
|
+
});
|
|
730
|
+
if (!state.streamReq) openStream();
|
|
731
|
+
} catch (err) {
|
|
732
|
+
state.busy = false;
|
|
733
|
+
warn(`发送失败: ${err.message}`);
|
|
734
|
+
prompt();
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
async function cancelRun() {
|
|
739
|
+
try {
|
|
740
|
+
await apiJson(port, "POST", `/api/sessions/${encodeURIComponent(state.sessionId)}/cancel`, {});
|
|
741
|
+
process.stdout.write(`${C.yellow}[已取消当前任务]${C.reset}\n`);
|
|
742
|
+
} catch (err) {
|
|
743
|
+
warn(`取消失败: ${err.message}`);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function chatHelp() {
|
|
227
748
|
process.stdout.write(
|
|
228
749
|
[
|
|
229
|
-
|
|
230
|
-
"",
|
|
231
|
-
"
|
|
232
|
-
"
|
|
233
|
-
"
|
|
234
|
-
" build 仅构建前端",
|
|
235
|
-
" help 显示帮助",
|
|
236
|
-
"",
|
|
237
|
-
"选项:",
|
|
238
|
-
" --no-open 启动后不自动打开浏览器",
|
|
239
|
-
" --no-build setup 时跳过前端构建(已有 dist 时自动跳过)",
|
|
750
|
+
`${C.bold}终端命令${C.reset}`,
|
|
751
|
+
" /new 新建会话",
|
|
752
|
+
" /web 在浏览器打开当前会话",
|
|
753
|
+
" /cancel 取消当前任务",
|
|
754
|
+
" /exit 退出(也可 Ctrl+C)",
|
|
240
755
|
"",
|
|
241
756
|
].join("\n")
|
|
242
757
|
);
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
async function handleLine(line) {
|
|
761
|
+
const text = line.trim();
|
|
762
|
+
if (!text) {
|
|
763
|
+
prompt();
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
if (state.approval) {
|
|
768
|
+
if (/^y(es)?$/i.test(text)) await resolveApproval(true);
|
|
769
|
+
else await resolveApproval(false);
|
|
770
|
+
prompt();
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
if (text.startsWith("/")) {
|
|
775
|
+
const cmd = text.split(/\s+/, 1)[0].toLowerCase();
|
|
776
|
+
if (cmd === "/exit" || cmd === "/quit") return shutdown(0);
|
|
777
|
+
if (cmd === "/help") {
|
|
778
|
+
chatHelp();
|
|
779
|
+
return prompt();
|
|
780
|
+
}
|
|
781
|
+
if (cmd === "/new") {
|
|
782
|
+
try {
|
|
783
|
+
const session = await newSession();
|
|
784
|
+
log(`新会话: ${session.id}${session.title ? ` · ${session.title}` : ""}`);
|
|
785
|
+
} catch (err) {
|
|
786
|
+
warn(`新建会话失败: ${err.message}`);
|
|
787
|
+
}
|
|
788
|
+
return prompt();
|
|
789
|
+
}
|
|
790
|
+
if (cmd === "/web") {
|
|
791
|
+
openBrowser(`http://127.0.0.1:${port}/#/s/${state.sessionId}`);
|
|
792
|
+
return prompt();
|
|
793
|
+
}
|
|
794
|
+
if (cmd === "/cancel") {
|
|
795
|
+
await cancelRun();
|
|
796
|
+
return prompt();
|
|
797
|
+
}
|
|
798
|
+
warn(`未知命令: ${cmd}(/help 查看帮助)`);
|
|
799
|
+
return prompt();
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
if (state.busy) {
|
|
803
|
+
await sendMessage(text);
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
await sendMessage(text);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
rl = readline.createInterface({
|
|
811
|
+
input: process.stdin,
|
|
812
|
+
output: process.stdout,
|
|
813
|
+
historySize: 300,
|
|
814
|
+
terminal: process.stdin.isTTY === true,
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
let session;
|
|
818
|
+
try {
|
|
819
|
+
session = await newSession();
|
|
820
|
+
} catch (err) {
|
|
821
|
+
if (!/auth/i.test(err.message)) die(`创建会话失败: ${err.message}`);
|
|
822
|
+
if (!process.stdin.isTTY) die(`需要登录:请先运行 haoyuan login(${err.message})`);
|
|
823
|
+
try {
|
|
824
|
+
await loginAt(port, rl);
|
|
825
|
+
session = await newSession();
|
|
826
|
+
} catch (loginErr) {
|
|
827
|
+
die(`登录失败: ${loginErr.message}`);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
const health = await fetch(`http://127.0.0.1:${port}/api/health`).then((r) => r.json());
|
|
832
|
+
const model = health && health.data ? `${health.data.default_provider}/${health.data.default_model}` : "unknown";
|
|
833
|
+
const mockHint =
|
|
834
|
+
health && health.data && health.data.default_provider === "mock"
|
|
835
|
+
? `${C.dim}提示: 未配置模型 Key,当前使用本地 mock。运行 haoyuan config 进行全局配置。${C.reset}`
|
|
836
|
+
: "";
|
|
837
|
+
|
|
838
|
+
process.stdout.write(
|
|
839
|
+
[
|
|
840
|
+
"",
|
|
841
|
+
`${C.bold}豪源 HaoYuan v${VERSION}${C.reset} · 终端对话`,
|
|
842
|
+
`${C.dim}模型 ${model} · 工作区 ${process.cwd()}${C.reset}`,
|
|
843
|
+
`${C.dim}会话 ${session.id} · 网页 /web · 帮助 /help · 退出 /exit 或 Ctrl+C${C.reset}`,
|
|
844
|
+
mockHint,
|
|
845
|
+
"",
|
|
846
|
+
]
|
|
847
|
+
.filter(Boolean)
|
|
848
|
+
.join("\n")
|
|
849
|
+
);
|
|
850
|
+
|
|
851
|
+
rl.on("line", (line) => {
|
|
852
|
+
handleLine(line).catch((err) => {
|
|
853
|
+
warn(err.message);
|
|
854
|
+
prompt();
|
|
855
|
+
});
|
|
856
|
+
});
|
|
857
|
+
|
|
858
|
+
rl.on("close", () => shutdown(0));
|
|
859
|
+
|
|
860
|
+
const onSigint = async () => {
|
|
861
|
+
if (state.busy) {
|
|
862
|
+
await cancelRun();
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
shutdown(0);
|
|
866
|
+
};
|
|
867
|
+
rl.on("SIGINT", onSigint);
|
|
868
|
+
process.on("SIGINT", onSigint);
|
|
869
|
+
process.on("SIGTERM", () => shutdown(0));
|
|
870
|
+
|
|
871
|
+
prompt();
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
function printVersion() {
|
|
875
|
+
process.stdout.write(`${VERSION}\n`);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function printHelp() {
|
|
879
|
+
process.stdout.write(
|
|
880
|
+
[
|
|
881
|
+
`豪源 HaoYuan v${VERSION}`,
|
|
882
|
+
"",
|
|
883
|
+
"用法: haoyuan [命令] [选项]",
|
|
884
|
+
"",
|
|
885
|
+
"命令:",
|
|
886
|
+
" haoyuan 终端对话(默认)",
|
|
887
|
+
" haoyuan web 启动服务并打开网页",
|
|
888
|
+
" haoyuan version 显示版本号",
|
|
889
|
+
" haoyuan config 全局配置文件(模型 Key 等),--open 直接打开编辑",
|
|
890
|
+
" haoyuan login 登录(账号保护开启时)",
|
|
891
|
+
" haoyuan logout 清除本地登录令牌",
|
|
892
|
+
" haoyuan setup 安装后端/前端依赖",
|
|
893
|
+
" haoyuan build 仅构建前端",
|
|
894
|
+
" haoyuan help 显示帮助",
|
|
895
|
+
"",
|
|
896
|
+
"选项:",
|
|
897
|
+
" -V, --version 显示版本号",
|
|
898
|
+
" --no-open web 启动后不打开浏览器",
|
|
899
|
+
" --no-build setup 时跳过前端构建",
|
|
900
|
+
"",
|
|
901
|
+
"环境变量:",
|
|
902
|
+
" HAOYUAN_TOKEN 账号保护开启后的访问令牌",
|
|
903
|
+
" HAOYUAN_PORT 后端基准端口(默认 8030)",
|
|
904
|
+
"",
|
|
905
|
+
].join("\n")
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
const argv = process.argv.slice(2);
|
|
910
|
+
const command = argv[0] || "";
|
|
911
|
+
const flags = new Set(argv.slice(1));
|
|
912
|
+
const noOpen = flags.has("--no-open");
|
|
913
|
+
const noBuild = flags.has("--no-build");
|
|
914
|
+
|
|
915
|
+
async function main() {
|
|
916
|
+
if (command === "--version" || command === "-V" || command === "-v" || command === "version") {
|
|
917
|
+
printVersion();
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
if (command === "--help" || command === "-h" || command === "help") {
|
|
921
|
+
printHelp();
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
if (command === "" || command === "chat") {
|
|
925
|
+
await chat();
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (command === "web" || command === "start" || command === "serve") {
|
|
929
|
+
await web({ noOpen });
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
if (command === "setup") {
|
|
933
|
+
setup({ build: !noBuild });
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
if (command === "login") {
|
|
937
|
+
await loginCommand();
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
if (command === "logout") {
|
|
941
|
+
logoutCommand();
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
if (command === "config") {
|
|
945
|
+
configCommand({ open: flags.has("--open") });
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
if (command === "build") {
|
|
949
|
+
buildFrontend();
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
if (command === "postinstall") {
|
|
953
|
+
postinstall();
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
fail(`未知命令: ${command}(运行 haoyuan help 查看用法)`);
|
|
246
957
|
}
|
|
958
|
+
|
|
959
|
+
main().catch((err) => fail(err.message));
|