haoyuan 1.1.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 CHANGED
@@ -131,6 +131,7 @@ haoyuan web
131
131
  | `haoyuan web` | 启动服务并自动打开网页 |
132
132
  | `haoyuan web --no-open` | 启动服务但不打开浏览器 |
133
133
  | `haoyuan --version` / `-V` | 查看版本号 |
134
+ | `haoyuan config` | 全局配置文件(模型 Key 等),`--open` 直接打开编辑 |
134
135
  | `haoyuan login` / `haoyuan logout` | 账号保护开启时登录 / 清除本地令牌 |
135
136
  | `haoyuan setup` | 仅预装依赖 |
136
137
  | `haoyuan help` | 显示帮助 |
@@ -194,32 +195,41 @@ npm run dev # http://localhost:8130,被占用时自动 +1
194
195
 
195
196
  ### 配置模型
196
197
 
198
+ **全局配置文件(推荐)** —— 固定用户级路径,重装/升级不受影响:
199
+
197
200
  ```bash
198
- copy api\configs\secrets_example.py api\configs\secrets_local.py
201
+ haoyuan config # 首次运行自动创建配置文件并显示路径
202
+ haoyuan config --open # 直接在编辑器中打开
199
203
  ```
200
204
 
201
- 编辑 `api/configs/secrets_local.py`:
205
+ 路径:`~/.config/haoyuan/config.json`(Windows 即 `C:\Users\<你>\.config\haoyuan\config.json`,可用环境变量 `HAOYUAN_CONFIG` 覆盖):
202
206
 
203
- ```python
204
- DEEPSEEK_API_KEY = "sk-..."
205
- DEEPSEEK_BASE_URL = "https://api.deepseek.com"
206
- DEEPSEEK_MODEL = "deepseek-flash"
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
+ ```
207
216
 
208
- # 可选:智谱
209
- ZHIPU_API_KEY = ""
217
+ **包内配置(可选)**:
210
218
 
211
- # 可选:小米 MiMo(公平评测使用的模型)
212
- MIMO_API_KEY = "tp-..."
213
- MIMO_BASE_URL = "https://token-plan-cn.xiaomimimo.com/v1"
214
- MIMO_MODEL = "mimo-v2.6-flash"
219
+ ```bash
220
+ copy api\configs\secrets_example.py api\configs\secrets_local.py
215
221
  ```
216
222
 
217
- 也可以使用环境变量(优先级高于文件):
223
+ 编辑 `api/configs/secrets_local.py`,字段同上(Python 常量格式)。适用于源码部署;npm 全局安装时该文件位于包目录内,升级会被清除,建议优先用全局配置。
224
+
225
+ **环境变量**(优先级最高):
218
226
 
219
227
  ```powershell
220
228
  $env:DEEPSEEK_API_KEY="sk-..."
221
229
  ```
222
230
 
231
+ 优先级:环境变量 > 全局配置文件 > `secrets_local.py`。保存后重新运行 `haoyuan` 生效;服务健康检查 `GET /api/health` 的 `key_source` 会显示 Key 来源。
232
+
223
233
  **未配置任何 Key 时自动使用本地 `mock` 模型**,完整跑通会话、工具调用、审批、事件与前端。
224
234
 
225
235
  ---
@@ -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
@@ -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
 
@@ -417,6 +418,52 @@ function logoutCommand() {
417
418
  log("已清除本地 CLI 令牌。");
418
419
  }
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
+
420
467
  async function chat() {
421
468
  const { port, child: serverChild } = await ensureServer();
422
469
 
@@ -783,6 +830,10 @@ async function chat() {
783
830
 
784
831
  const health = await fetch(`http://127.0.0.1:${port}/api/health`).then((r) => r.json());
785
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
+ : "";
786
837
 
787
838
  process.stdout.write(
788
839
  [
@@ -790,8 +841,11 @@ async function chat() {
790
841
  `${C.bold}豪源 HaoYuan v${VERSION}${C.reset} · 终端对话`,
791
842
  `${C.dim}模型 ${model} · 工作区 ${process.cwd()}${C.reset}`,
792
843
  `${C.dim}会话 ${session.id} · 网页 /web · 帮助 /help · 退出 /exit 或 Ctrl+C${C.reset}`,
844
+ mockHint,
793
845
  "",
794
- ].join("\n")
846
+ ]
847
+ .filter(Boolean)
848
+ .join("\n")
795
849
  );
796
850
 
797
851
  rl.on("line", (line) => {
@@ -832,6 +886,7 @@ function printHelp() {
832
886
  " haoyuan 终端对话(默认)",
833
887
  " haoyuan web 启动服务并打开网页",
834
888
  " haoyuan version 显示版本号",
889
+ " haoyuan config 全局配置文件(模型 Key 等),--open 直接打开编辑",
835
890
  " haoyuan login 登录(账号保护开启时)",
836
891
  " haoyuan logout 清除本地登录令牌",
837
892
  " haoyuan setup 安装后端/前端依赖",
@@ -886,6 +941,10 @@ async function main() {
886
941
  logoutCommand();
887
942
  return;
888
943
  }
944
+ if (command === "config") {
945
+ configCommand({ open: flags.has("--open") });
946
+ return;
947
+ }
889
948
  if (command === "build") {
890
949
  buildFrontend();
891
950
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haoyuan",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "豪源 · HaoYuan — 个人指挥 AI 实现多个 AI 员工异步并行工作的 AI 工作室",
5
5
  "bin": {
6
6
  "haoyuan": "bin/haoyuan.js"