haoyuan 1.1.0 → 1.2.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/README.md +29 -14
- package/api/configs/models.py +12 -0
- package/api/configs/secrets.py +35 -0
- package/api/tests/test_secrets_config.py +84 -0
- package/bin/haoyuan.js +191 -19
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -128,14 +128,16 @@ haoyuan web
|
|
|
128
128
|
| 命令 | 作用 |
|
|
129
129
|
|---|---|
|
|
130
130
|
| `haoyuan` | 终端对话(流式输出、工具调用、审批确认) |
|
|
131
|
+
| `haoyuan --model x/y` | 以指定模型启动对话(如 `--model deepseek/deepseek-flash`) |
|
|
131
132
|
| `haoyuan web` | 启动服务并自动打开网页 |
|
|
132
133
|
| `haoyuan web --no-open` | 启动服务但不打开浏览器 |
|
|
133
134
|
| `haoyuan --version` / `-V` | 查看版本号 |
|
|
135
|
+
| `haoyuan config` | 全局配置文件(模型 Key 等),`--open` 直接打开编辑 |
|
|
134
136
|
| `haoyuan login` / `haoyuan logout` | 账号保护开启时登录 / 清除本地令牌 |
|
|
135
137
|
| `haoyuan setup` | 仅预装依赖 |
|
|
136
138
|
| `haoyuan help` | 显示帮助 |
|
|
137
139
|
|
|
138
|
-
终端内命令:`/new` 新建会话、`/web` 在浏览器打开当前会话、`/cancel` 取消当前任务、`/exit` 退出(Ctrl+C 同样有效)。
|
|
140
|
+
终端内命令:`/models` 查看/选择模型(序号选择,`/model x/y` 直选)、`/new` 新建会话、`/web` 在浏览器打开当前会话、`/cancel` 取消当前任务、`/exit` 退出(Ctrl+C 同样有效)。
|
|
139
141
|
|
|
140
142
|
网页默认地址 `http://127.0.0.1:8030`,端口被占用自动 +1。未配置模型 Key 时使用内置 `mock` 模型,会话、工具调用、审批与前端均可完整运行。
|
|
141
143
|
|
|
@@ -194,32 +196,45 @@ npm run dev # http://localhost:8130,被占用时自动 +1
|
|
|
194
196
|
|
|
195
197
|
### 配置模型
|
|
196
198
|
|
|
199
|
+
**全局配置文件(推荐)** —— 固定用户级路径,重装/升级不受影响:
|
|
200
|
+
|
|
197
201
|
```bash
|
|
198
|
-
|
|
202
|
+
haoyuan config # 首次运行自动创建配置文件并显示路径
|
|
203
|
+
haoyuan config --open # 直接在编辑器中打开
|
|
199
204
|
```
|
|
200
205
|
|
|
201
|
-
|
|
206
|
+
路径:`~/.config/haoyuan/config.json`(Windows 即 `C:\Users\<你>\.config\haoyuan\config.json`,可用环境变量 `HAOYUAN_CONFIG` 覆盖):
|
|
202
207
|
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
208
|
+
```json
|
|
209
|
+
{
|
|
210
|
+
"DEEPSEEK_API_KEY": "sk-...",
|
|
211
|
+
"DEEPSEEK_BASE_URL": "https://api.deepseek.com",
|
|
212
|
+
"DEEPSEEK_MODEL": "deepseek-flash",
|
|
213
|
+
"ZHIPU_API_KEY": "",
|
|
214
|
+
"MIMO_API_KEY": "",
|
|
215
|
+
"PROVIDER": "",
|
|
216
|
+
"MODEL": ""
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`PROVIDER` / `MODEL` 可锁定默认模型(如 `"MODEL": "deepseek-v4-pro"`,留空则按已配置 Key 自动选择)。
|
|
207
221
|
|
|
208
|
-
|
|
209
|
-
ZHIPU_API_KEY = ""
|
|
222
|
+
**包内配置(可选)**:
|
|
210
223
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
MIMO_BASE_URL = "https://token-plan-cn.xiaomimimo.com/v1"
|
|
214
|
-
MIMO_MODEL = "mimo-v2.6-flash"
|
|
224
|
+
```bash
|
|
225
|
+
copy api\configs\secrets_example.py api\configs\secrets_local.py
|
|
215
226
|
```
|
|
216
227
|
|
|
217
|
-
|
|
228
|
+
编辑 `api/configs/secrets_local.py`,字段同上(Python 常量格式)。适用于源码部署;npm 全局安装时该文件位于包目录内,升级会被清除,建议优先用全局配置。
|
|
229
|
+
|
|
230
|
+
**环境变量**(优先级最高):
|
|
218
231
|
|
|
219
232
|
```powershell
|
|
220
233
|
$env:DEEPSEEK_API_KEY="sk-..."
|
|
221
234
|
```
|
|
222
235
|
|
|
236
|
+
优先级:环境变量 > 全局配置文件 > `secrets_local.py`。保存后重新运行 `haoyuan` 生效;服务健康检查 `GET /api/health` 的 `key_source` 会显示 Key 来源。
|
|
237
|
+
|
|
223
238
|
**未配置任何 Key 时自动使用本地 `mock` 模型**,完整跑通会话、工具调用、审批、事件与前端。
|
|
224
239
|
|
|
225
240
|
---
|
package/api/configs/models.py
CHANGED
|
@@ -12,6 +12,7 @@ from configs.secrets import (
|
|
|
12
12
|
MIMO_MODEL,
|
|
13
13
|
ZHIPU_API_KEY,
|
|
14
14
|
ZHIPU_BASE_URL,
|
|
15
|
+
global_config,
|
|
15
16
|
)
|
|
16
17
|
|
|
17
18
|
|
|
@@ -102,6 +103,17 @@ def price_for(provider: str, model: str | None = None) -> dict[str, float]:
|
|
|
102
103
|
def auto_default() -> tuple[str, str]:
|
|
103
104
|
if os.getenv("HAOYUAN_FORCE_MOCK", "").strip().lower() in {"1", "true", "yes"}:
|
|
104
105
|
return "mock", "mock-deterministic"
|
|
106
|
+
gp = global_config("PROVIDER")
|
|
107
|
+
gm = global_config("MODEL")
|
|
108
|
+
if gp and gp != "auto" and gp in PROVIDERS:
|
|
109
|
+
conf = PROVIDERS[gp]
|
|
110
|
+
if gm and gm != "auto" and gm in conf.models:
|
|
111
|
+
return gp, gm
|
|
112
|
+
return gp, conf.default_model
|
|
113
|
+
if gm and gm != "auto":
|
|
114
|
+
for name, conf in PROVIDERS.items():
|
|
115
|
+
if gm in conf.models:
|
|
116
|
+
return name, gm
|
|
105
117
|
if DEEPSEEK_API_KEY:
|
|
106
118
|
return "deepseek", DEEPSEEK_MODEL
|
|
107
119
|
if ZHIPU_API_KEY:
|
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,41 @@ 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
|
+
|
|
33
|
+
def global_config(name: str, default: str = "") -> str:
|
|
34
|
+
value = _GLOBAL_CONFIG.get(name)
|
|
35
|
+
if value is None:
|
|
36
|
+
return default
|
|
37
|
+
text = str(value).strip()
|
|
38
|
+
return text or default
|
|
39
|
+
|
|
40
|
+
|
|
11
41
|
def _get(name: str, default: str = "") -> str:
|
|
12
42
|
env_value = os.getenv(name)
|
|
13
43
|
if env_value is not None and env_value.strip():
|
|
14
44
|
return env_value.strip()
|
|
45
|
+
global_value = _GLOBAL_CONFIG.get(name)
|
|
46
|
+
if global_value is not None and str(global_value).strip():
|
|
47
|
+
return str(global_value).strip()
|
|
15
48
|
if _local is not None:
|
|
16
49
|
local_value = getattr(_local, name, None)
|
|
17
50
|
if local_value is not None and str(local_value).strip():
|
|
@@ -41,6 +74,8 @@ def get_secret(name: str, default: str = "") -> str:
|
|
|
41
74
|
def secret_source(name: str) -> str:
|
|
42
75
|
if os.getenv(name, "").strip():
|
|
43
76
|
return "env"
|
|
77
|
+
if _GLOBAL_CONFIG.get(name) is not None and str(_GLOBAL_CONFIG.get(name) or "").strip():
|
|
78
|
+
return str(config_path())
|
|
44
79
|
if _local is not None and str(getattr(_local, name, "") or "").strip():
|
|
45
80
|
return "configs/secrets_local.py"
|
|
46
81
|
return "default"
|
|
@@ -0,0 +1,84 @@
|
|
|
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"}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_auto_default_from_global_config(tmp_path, monkeypatch):
|
|
65
|
+
import importlib
|
|
66
|
+
|
|
67
|
+
from configs import models as models_mod
|
|
68
|
+
|
|
69
|
+
cfg_file = tmp_path / "config.json"
|
|
70
|
+
cfg_file.write_text(json.dumps({"PROVIDER": "zhipu"}), encoding="utf-8")
|
|
71
|
+
monkeypatch.setenv("HAOYUAN_CONFIG", str(cfg_file))
|
|
72
|
+
monkeypatch.delenv("HAOYUAN_FORCE_MOCK", raising=False)
|
|
73
|
+
_reload()
|
|
74
|
+
models = importlib.reload(models_mod)
|
|
75
|
+
assert models.auto_default() == ("zhipu", "glm-5.3-flash")
|
|
76
|
+
|
|
77
|
+
cfg_file.write_text(json.dumps({"MODEL": "deepseek-v4-pro"}), encoding="utf-8")
|
|
78
|
+
_reload()
|
|
79
|
+
models = importlib.reload(models_mod)
|
|
80
|
+
assert models.auto_default() == ("deepseek", "deepseek-v4-pro")
|
|
81
|
+
|
|
82
|
+
monkeypatch.delenv("HAOYUAN_CONFIG")
|
|
83
|
+
_reload()
|
|
84
|
+
importlib.reload(models_mod)
|
package/bin/haoyuan.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
const { spawn, spawnSync } = require("child_process");
|
|
5
5
|
const fs = require("fs");
|
|
6
6
|
const http = require("http");
|
|
7
|
+
const os = require("os");
|
|
7
8
|
const path = require("path");
|
|
8
9
|
const readline = require("readline");
|
|
9
10
|
|
|
@@ -171,14 +172,14 @@ function readApiPort() {
|
|
|
171
172
|
}
|
|
172
173
|
|
|
173
174
|
async function healthyPort(port) {
|
|
174
|
-
if (!port) return
|
|
175
|
+
if (!port) return 0;
|
|
175
176
|
try {
|
|
176
177
|
const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
|
|
177
178
|
signal: AbortSignal.timeout(2000),
|
|
178
179
|
});
|
|
179
|
-
return res.ok;
|
|
180
|
+
return res.ok ? port : 0;
|
|
180
181
|
} catch {
|
|
181
|
-
return
|
|
182
|
+
return 0;
|
|
182
183
|
}
|
|
183
184
|
}
|
|
184
185
|
|
|
@@ -417,7 +418,55 @@ function logoutCommand() {
|
|
|
417
418
|
log("已清除本地 CLI 令牌。");
|
|
418
419
|
}
|
|
419
420
|
|
|
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
|
+
PROVIDER: "",
|
|
429
|
+
MODEL: "",
|
|
430
|
+
},
|
|
431
|
+
null,
|
|
432
|
+
2
|
|
433
|
+
);
|
|
434
|
+
|
|
435
|
+
function configFilePath() {
|
|
436
|
+
return process.env.HAOYUAN_CONFIG
|
|
437
|
+
? path.resolve(process.env.HAOYUAN_CONFIG)
|
|
438
|
+
: path.join(os.homedir(), ".config", "haoyuan", "config.json");
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function configCommand({ open = false } = {}) {
|
|
442
|
+
const file = configFilePath();
|
|
443
|
+
let created = false;
|
|
444
|
+
if (!fs.existsSync(file)) {
|
|
445
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
446
|
+
fs.writeFileSync(file, `${CONFIG_TEMPLATE}\n`);
|
|
447
|
+
created = true;
|
|
448
|
+
}
|
|
449
|
+
log(`全局配置文件: ${file}${created ? "(已创建)" : ""}`);
|
|
450
|
+
if (open && IS_WIN) {
|
|
451
|
+
spawn("cmd", ["/c", "start", "", "notepad.exe", file], { detached: true, stdio: "ignore" }).unref();
|
|
452
|
+
} else if (open && process.platform === "darwin") {
|
|
453
|
+
spawn("open", [file], { detached: true, stdio: "ignore" }).unref();
|
|
454
|
+
} else if (open) {
|
|
455
|
+
spawn("xdg-open", [file], { detached: true, stdio: "ignore" }).unref();
|
|
456
|
+
}
|
|
457
|
+
process.stdout.write(
|
|
458
|
+
[
|
|
459
|
+
"",
|
|
460
|
+
"填写示例(JSON,优先级:环境变量 > 本文件 > api/configs/secrets_local.py):",
|
|
461
|
+
CONFIG_TEMPLATE.replace(/: "",/g, ': "",'),
|
|
462
|
+
"",
|
|
463
|
+
"保存后重新运行 haoyuan 生效。",
|
|
464
|
+
"",
|
|
465
|
+
].join("\n")
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async function chat(options = {}) {
|
|
421
470
|
const { port, child: serverChild } = await ensureServer();
|
|
422
471
|
|
|
423
472
|
const die = (msg) => {
|
|
@@ -433,8 +482,10 @@ async function chat() {
|
|
|
433
482
|
|
|
434
483
|
const state = {
|
|
435
484
|
sessionId: "",
|
|
485
|
+
model: "",
|
|
436
486
|
busy: false,
|
|
437
487
|
approval: null,
|
|
488
|
+
picking: null,
|
|
438
489
|
inText: false,
|
|
439
490
|
inReasoning: false,
|
|
440
491
|
streamReq: null,
|
|
@@ -663,11 +714,20 @@ async function chat() {
|
|
|
663
714
|
}
|
|
664
715
|
|
|
665
716
|
async function newSession() {
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
717
|
+
const body = { kind: "auto", workspace: process.cwd() };
|
|
718
|
+
const wanted = (options.model || "").trim();
|
|
719
|
+
if (wanted) {
|
|
720
|
+
const slash = wanted.indexOf("/");
|
|
721
|
+
if (slash > 0) {
|
|
722
|
+
body.provider = wanted.slice(0, slash);
|
|
723
|
+
body.model = wanted.slice(slash + 1);
|
|
724
|
+
} else {
|
|
725
|
+
body.model = wanted;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
const data = await apiJson(port, "POST", "/api/sessions", body);
|
|
670
729
|
state.sessionId = data.id;
|
|
730
|
+
state.model = `${data.provider || "mock"}/${data.model || "auto"}`;
|
|
671
731
|
state.lastEventId = 0;
|
|
672
732
|
openStream();
|
|
673
733
|
return data;
|
|
@@ -701,15 +761,95 @@ async function chat() {
|
|
|
701
761
|
process.stdout.write(
|
|
702
762
|
[
|
|
703
763
|
`${C.bold}终端命令${C.reset}`,
|
|
704
|
-
" /
|
|
705
|
-
" /
|
|
706
|
-
" /
|
|
707
|
-
" /
|
|
764
|
+
" /models [x/y] 查看/选择模型(如 /model deepseek/deepseek-flash)",
|
|
765
|
+
" /new 新建会话",
|
|
766
|
+
" /web 在浏览器打开当前会话",
|
|
767
|
+
" /cancel 取消当前任务",
|
|
768
|
+
" /exit 退出(也可 Ctrl+C)",
|
|
708
769
|
"",
|
|
709
770
|
].join("\n")
|
|
710
771
|
);
|
|
711
772
|
}
|
|
712
773
|
|
|
774
|
+
function buildModelOptions(providers) {
|
|
775
|
+
const options = [{ provider: "mock", model: "mock-deterministic", configured: true }];
|
|
776
|
+
for (const p of providers || []) {
|
|
777
|
+
for (const m of p.models || []) {
|
|
778
|
+
options.push({
|
|
779
|
+
provider: p.provider,
|
|
780
|
+
model: m,
|
|
781
|
+
configured: !!p.configured,
|
|
782
|
+
default: m === p.default_model,
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
return options;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
function printModelOptions(options) {
|
|
790
|
+
process.stdout.write(`${C.bold}可用模型:${C.reset}\n`);
|
|
791
|
+
options.forEach((opt, i) => {
|
|
792
|
+
const label = `${opt.provider}/${opt.model}`;
|
|
793
|
+
const parts = [` ${i + 1}) ${label}`];
|
|
794
|
+
if (label === state.model) parts.push(`${C.green}* 当前${C.reset}`);
|
|
795
|
+
if (opt.provider === "mock") parts.push(`${C.dim}(本地调试)${C.reset}`);
|
|
796
|
+
else if (!opt.configured) parts.push(`${C.dim}(Key 未配置,选择后无法调用)${C.reset}`);
|
|
797
|
+
else if (opt.default) parts.push(`${C.dim}(该厂商默认)${C.reset}`);
|
|
798
|
+
process.stdout.write(parts.join(" ") + "\n");
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
async function setModel(opt) {
|
|
803
|
+
try {
|
|
804
|
+
await apiJson(port, "PATCH", `/api/sessions/${encodeURIComponent(state.sessionId)}`, {
|
|
805
|
+
provider: opt.provider,
|
|
806
|
+
model: opt.model,
|
|
807
|
+
});
|
|
808
|
+
state.model = `${opt.provider}/${opt.model}`;
|
|
809
|
+
process.stdout.write(`${C.green}[已切换模型] ${state.model}${C.reset}\n`);
|
|
810
|
+
} catch (err) {
|
|
811
|
+
warn(`切换失败: ${err.message}`);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async function handlePick(text) {
|
|
816
|
+
const pick = state.picking;
|
|
817
|
+
if (!text) {
|
|
818
|
+
state.picking = null;
|
|
819
|
+
process.stdout.write(`${C.dim}[已取消选择]${C.reset}\n`);
|
|
820
|
+
return prompt();
|
|
821
|
+
}
|
|
822
|
+
const idx = Number.parseInt(text, 10);
|
|
823
|
+
if (!Number.isFinite(idx) || idx < 1 || idx > pick.options.length) {
|
|
824
|
+
process.stdout.write(`${C.dim}请输入 1-${pick.options.length} 的序号,或回车取消:${C.reset} `);
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
state.picking = null;
|
|
828
|
+
await setModel(pick.options[idx - 1]);
|
|
829
|
+
return prompt();
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
async function modelsCommand(argModel) {
|
|
833
|
+
const data = await apiJson(port, "GET", "/api/models");
|
|
834
|
+
const options = buildModelOptions(data && data.providers);
|
|
835
|
+
if (argModel) {
|
|
836
|
+
const slash = argModel.indexOf("/");
|
|
837
|
+
const opt = options.find((o) =>
|
|
838
|
+
slash > 0 ? `${o.provider}/${o.model}` === argModel : o.model === argModel
|
|
839
|
+
);
|
|
840
|
+
if (!opt) {
|
|
841
|
+
warn(`未知模型: ${argModel}(/models 查看可用列表)`);
|
|
842
|
+
return prompt();
|
|
843
|
+
}
|
|
844
|
+
await setModel(opt);
|
|
845
|
+
return prompt();
|
|
846
|
+
}
|
|
847
|
+
state.picking = { options };
|
|
848
|
+
printModelOptions(options);
|
|
849
|
+
rl.setPrompt(`${C.cyan}选择序号>${C.reset} `);
|
|
850
|
+
rl.prompt();
|
|
851
|
+
}
|
|
852
|
+
|
|
713
853
|
async function handleLine(line) {
|
|
714
854
|
const text = line.trim();
|
|
715
855
|
if (!text) {
|
|
@@ -724,6 +864,11 @@ async function chat() {
|
|
|
724
864
|
return;
|
|
725
865
|
}
|
|
726
866
|
|
|
867
|
+
if (state.picking) {
|
|
868
|
+
await handlePick(text);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
|
|
727
872
|
if (text.startsWith("/")) {
|
|
728
873
|
const cmd = text.split(/\s+/, 1)[0].toLowerCase();
|
|
729
874
|
if (cmd === "/exit" || cmd === "/quit") return shutdown(0);
|
|
@@ -731,6 +876,16 @@ async function chat() {
|
|
|
731
876
|
chatHelp();
|
|
732
877
|
return prompt();
|
|
733
878
|
}
|
|
879
|
+
if (cmd === "/models" || cmd === "/model") {
|
|
880
|
+
const arg = text.slice(cmd.length).trim();
|
|
881
|
+
try {
|
|
882
|
+
await modelsCommand(arg);
|
|
883
|
+
} catch (err) {
|
|
884
|
+
warn(`获取模型失败: ${err.message}`);
|
|
885
|
+
prompt();
|
|
886
|
+
}
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
734
889
|
if (cmd === "/new") {
|
|
735
890
|
try {
|
|
736
891
|
const session = await newSession();
|
|
@@ -781,17 +936,21 @@ async function chat() {
|
|
|
781
936
|
}
|
|
782
937
|
}
|
|
783
938
|
|
|
784
|
-
const
|
|
785
|
-
|
|
939
|
+
const mockHint = state.model.startsWith("mock/")
|
|
940
|
+
? `${C.dim}提示: 未配置模型 Key,当前使用本地 mock。运行 haoyuan config 进行全局配置,/models 切换模型。${C.reset}`
|
|
941
|
+
: "";
|
|
786
942
|
|
|
787
943
|
process.stdout.write(
|
|
788
944
|
[
|
|
789
945
|
"",
|
|
790
946
|
`${C.bold}豪源 HaoYuan v${VERSION}${C.reset} · 终端对话`,
|
|
791
|
-
`${C.dim}模型 ${model} · 工作区 ${process.cwd()}${C.reset}`,
|
|
792
|
-
`${C.dim}会话 ${session.id} ·
|
|
947
|
+
`${C.dim}模型 ${state.model} · 工作区 ${process.cwd()}${C.reset}`,
|
|
948
|
+
`${C.dim}会话 ${session.id} · /models 选模型 · /web 网页 · /help 帮助 · /exit 退出${C.reset}`,
|
|
949
|
+
mockHint,
|
|
793
950
|
"",
|
|
794
|
-
]
|
|
951
|
+
]
|
|
952
|
+
.filter(Boolean)
|
|
953
|
+
.join("\n")
|
|
795
954
|
);
|
|
796
955
|
|
|
797
956
|
rl.on("line", (line) => {
|
|
@@ -832,6 +991,7 @@ function printHelp() {
|
|
|
832
991
|
" haoyuan 终端对话(默认)",
|
|
833
992
|
" haoyuan web 启动服务并打开网页",
|
|
834
993
|
" haoyuan version 显示版本号",
|
|
994
|
+
" haoyuan config 全局配置文件(模型 Key 等),--open 直接打开编辑",
|
|
835
995
|
" haoyuan login 登录(账号保护开启时)",
|
|
836
996
|
" haoyuan logout 清除本地登录令牌",
|
|
837
997
|
" haoyuan setup 安装后端/前端依赖",
|
|
@@ -840,6 +1000,7 @@ function printHelp() {
|
|
|
840
1000
|
"",
|
|
841
1001
|
"选项:",
|
|
842
1002
|
" -V, --version 显示版本号",
|
|
1003
|
+
" --model x/y 指定模型(如 --model deepseek/deepseek-flash)",
|
|
843
1004
|
" --no-open web 启动后不打开浏览器",
|
|
844
1005
|
" --no-build setup 时跳过前端构建",
|
|
845
1006
|
"",
|
|
@@ -856,6 +1017,13 @@ const command = argv[0] || "";
|
|
|
856
1017
|
const flags = new Set(argv.slice(1));
|
|
857
1018
|
const noOpen = flags.has("--no-open");
|
|
858
1019
|
const noBuild = flags.has("--no-build");
|
|
1020
|
+
let modelFlag = "";
|
|
1021
|
+
const mi = argv.indexOf("--model");
|
|
1022
|
+
if (mi >= 0 && argv[mi + 1] && !argv[mi + 1].startsWith("--")) {
|
|
1023
|
+
modelFlag = argv[mi + 1].trim();
|
|
1024
|
+
}
|
|
1025
|
+
const modelEq = argv.find((a) => a.startsWith("--model="));
|
|
1026
|
+
if (modelEq) modelFlag = modelEq.slice(8).trim();
|
|
859
1027
|
|
|
860
1028
|
async function main() {
|
|
861
1029
|
if (command === "--version" || command === "-V" || command === "-v" || command === "version") {
|
|
@@ -866,8 +1034,8 @@ async function main() {
|
|
|
866
1034
|
printHelp();
|
|
867
1035
|
return;
|
|
868
1036
|
}
|
|
869
|
-
if (command === "" || command === "chat") {
|
|
870
|
-
await chat();
|
|
1037
|
+
if (command === "" || command === "chat" || command === "--model") {
|
|
1038
|
+
await chat({ model: modelFlag });
|
|
871
1039
|
return;
|
|
872
1040
|
}
|
|
873
1041
|
if (command === "web" || command === "start" || command === "serve") {
|
|
@@ -886,6 +1054,10 @@ async function main() {
|
|
|
886
1054
|
logoutCommand();
|
|
887
1055
|
return;
|
|
888
1056
|
}
|
|
1057
|
+
if (command === "config") {
|
|
1058
|
+
configCommand({ open: flags.has("--open") });
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
889
1061
|
if (command === "build") {
|
|
890
1062
|
buildFrontend();
|
|
891
1063
|
return;
|