haoyuan 0.0.4 → 0.0.6

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.
@@ -6,7 +6,7 @@ from pathlib import Path
6
6
  from configs.models import auto_default
7
7
 
8
8
  APP_NAME = "HaoYuan"
9
- APP_VERSION = "0.0.4"
9
+ APP_VERSION = "0.0.6"
10
10
  SERVER_HOST = os.getenv("HAOYUAN_HOST", "127.0.0.1")
11
11
  SERVER_PORT = int(os.getenv("HAOYUAN_PORT", "8030"))
12
12
  prefix = "/api"
@@ -4,6 +4,7 @@ import base64
4
4
  import hashlib
5
5
  import hmac
6
6
  import json
7
+ import os
7
8
  import secrets
8
9
  import threading
9
10
  import time
@@ -25,6 +26,38 @@ DEFAULT_MAX_FAILURES = 5
25
26
  MAX_FAILURES_LIMIT = 20
26
27
  LOCK_SECONDS = 5 * 60
27
28
  STATE_PATH = DATA_DIR / "user_account.json"
29
+ CLI_SECRET_PATH = DATA_DIR / "cli-secret"
30
+
31
+ _cli_secret_value: str | None = None
32
+ _cli_secret_lock = threading.Lock()
33
+
34
+
35
+ def cli_secret() -> str:
36
+ """本机 CLI 的免登录密钥:只写入本地数据目录,由同机 `haoyuan` 读取后随请求发送。"""
37
+ global _cli_secret_value
38
+ if _cli_secret_value is not None:
39
+ return _cli_secret_value
40
+ with _cli_secret_lock:
41
+ if _cli_secret_value is not None:
42
+ return _cli_secret_value
43
+ try:
44
+ value = ""
45
+ if CLI_SECRET_PATH.is_file():
46
+ value = CLI_SECRET_PATH.read_text(encoding="utf-8").strip()
47
+ if not value:
48
+ value = secrets.token_hex(32)
49
+ CLI_SECRET_PATH.parent.mkdir(parents=True, exist_ok=True)
50
+ temp = CLI_SECRET_PATH.with_suffix(".tmp")
51
+ temp.write_text(value, encoding="utf-8")
52
+ temp.replace(CLI_SECRET_PATH)
53
+ try:
54
+ os.chmod(CLI_SECRET_PATH, 0o600)
55
+ except OSError:
56
+ pass
57
+ _cli_secret_value = value
58
+ except OSError:
59
+ _cli_secret_value = ""
60
+ return _cli_secret_value
28
61
 
29
62
 
30
63
  def _now() -> str:
@@ -261,6 +294,8 @@ class AuthGateMiddleware:
261
294
  def __init__(self, app, state_path: str):
262
295
  self.app = app
263
296
  self.store = AuthStore(Path(state_path))
297
+ # 启动时即生成本机 CLI 免登录密钥,避免 CLI 首个请求早于文件生成
298
+ cli_secret()
264
299
 
265
300
  async def __call__(self, scope, receive, send):
266
301
  if scope["type"] not in {"http", "websocket"}:
@@ -278,6 +313,10 @@ class AuthGateMiddleware:
278
313
  for key, value in scope.get("headers", [])
279
314
  }
280
315
  query = parse_qs(scope.get("query_string", b"").decode("latin-1"))
316
+ cli = headers.get("x-haoyuan-cli-secret", "").strip()
317
+ expected = cli_secret()
318
+ if cli and expected and hmac.compare_digest(cli, expected):
319
+ return await self.app(scope, receive, send)
281
320
  token = _token_from_headers(headers, query)
282
321
  if token and self.store.verify_token(token):
283
322
  return await self.app(scope, receive, send)
@@ -533,6 +572,7 @@ def build_router(store: AuthStore) -> APIRouter:
533
572
  def register(ctx) -> None:
534
573
  store = AuthStore(STATE_PATH)
535
574
  store.ensure()
575
+ cli_secret()
536
576
  ctx.add_router(build_router(store))
537
577
  ctx.add_middleware(AuthGateMiddleware, state_path=str(STATE_PATH))
538
578
 
package/bin/haoyuan.js CHANGED
@@ -26,6 +26,7 @@ const API = path.join(ROOT, "api");
26
26
  const RUNTIME_FILE = path.join(API, "data", "runtime.json");
27
27
  const DIST_INDEX = path.join(WEB, "dist", "index.html");
28
28
  const TOKEN_FILE = path.join(API, "data", "cli-token");
29
+ const CLI_SECRET_FILE = path.join(API, "data", "cli-secret");
29
30
  let TOKEN = (process.env.HAOYUAN_TOKEN || "").trim();
30
31
  if (!TOKEN) {
31
32
  try {
@@ -55,6 +56,14 @@ function clearToken() {
55
56
  }
56
57
  }
57
58
 
59
+ function cliSecret() {
60
+ try {
61
+ return fs.readFileSync(CLI_SECRET_FILE, "utf8").trim();
62
+ } catch {
63
+ return "";
64
+ }
65
+ }
66
+
58
67
  const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
59
68
  const C = COLOR
60
69
  ? {
@@ -89,12 +98,11 @@ function shellQuote(s) {
89
98
  function run(cmd, args, opts = {}) {
90
99
  const lenient = opts.lenient === true;
91
100
  const useShell = IS_WIN && /\.(cmd|bat)$/i.test(cmd);
101
+ const cwd = opts.cwd || ROOT;
92
102
  log(`${cmd} ${args.join(" ")}`);
93
- const r = spawnSync(
94
- cmd,
95
- useShell ? args.map(shellQuote) : args,
96
- { stdio: "inherit", cwd: ROOT, shell: useShell }
97
- );
103
+ const r = useShell
104
+ ? spawnSync([cmd, ...args.map(shellQuote)].join(" "), { stdio: "inherit", cwd, shell: true })
105
+ : spawnSync(cmd, args, { stdio: "inherit", cwd });
98
106
  if (r.error) {
99
107
  if (lenient) {
100
108
  warn(`跳过(${r.error.message})`);
@@ -251,6 +259,37 @@ async function healthyPort(port) {
251
259
  }
252
260
  }
253
261
 
262
+ function stopLocalServer(port) {
263
+ if (!port) return false;
264
+ try {
265
+ if (IS_WIN) {
266
+ const r = spawnSync("netstat", ["-ano", "-p", "TCP"], { encoding: "utf8" });
267
+ const pids = new Set();
268
+ for (const line of (r.stdout || "").split(/\r?\n/)) {
269
+ if (!/LISTENING/i.test(line)) continue;
270
+ const cols = line.trim().split(/\s+/);
271
+ if (!cols[1] || !cols[1].endsWith(`:${port}`)) continue;
272
+ const pid = cols[cols.length - 1];
273
+ if (/^\d+$/.test(pid) && pid !== "0") pids.add(pid);
274
+ }
275
+ for (const pid of pids) {
276
+ log(`停止正在运行的豪源服务(端口 ${port},PID ${pid})...`);
277
+ spawnSync("taskkill", ["/PID", pid, "/F"], { stdio: "ignore" });
278
+ }
279
+ return pids.size > 0;
280
+ }
281
+ const r = spawnSync("lsof", ["-ti", `tcp:${port}`], { encoding: "utf8" });
282
+ const pids = (r.stdout || "").split(/\s+/).filter((pid) => /^\d+$/.test(pid));
283
+ for (const pid of pids) {
284
+ log(`停止正在运行的豪源服务(端口 ${port},PID ${pid})...`);
285
+ spawnSync("kill", ["-TERM", pid], { stdio: "ignore" });
286
+ }
287
+ return pids.length > 0;
288
+ } catch {
289
+ return false;
290
+ }
291
+ }
292
+
254
293
  async function waitUntilHealthy(timeoutMs = 180000) {
255
294
  const deadline = Date.now() + timeoutMs;
256
295
  while (Date.now() < deadline) {
@@ -369,6 +408,8 @@ async function ensureServer() {
369
408
 
370
409
  function apiHeaders() {
371
410
  const headers = { "content-type": "application/json" };
411
+ const secret = cliSecret();
412
+ if (secret) headers["x-haoyuan-cli-secret"] = secret;
372
413
  if (TOKEN) {
373
414
  headers["authorization"] = `Bearer ${TOKEN}`;
374
415
  headers["x-haoyuan-token"] = TOKEN;
@@ -626,6 +667,8 @@ async function chat(options = {}) {
626
667
  if (state.streamReq || state.closing) return;
627
668
  const qs = `after_id=${state.lastEventId}${TOKEN ? `&token=${encodeURIComponent(TOKEN)}` : ""}`;
628
669
  const headers = { Accept: "text/event-stream" };
670
+ const secret = cliSecret();
671
+ if (secret) headers["x-haoyuan-cli-secret"] = secret;
629
672
  if (TOKEN) headers["x-haoyuan-token"] = TOKEN;
630
673
  const req = http.get(
631
674
  {
@@ -704,7 +747,7 @@ async function chat(options = {}) {
704
747
  state.inReasoning = false;
705
748
  }
706
749
  if (!state.inText) {
707
- process.stdout.write(`${C.bold}[助手]${C.reset} `);
750
+ process.stdout.write(`${C.bold}[HaoYuan]${C.reset} `);
708
751
  state.inText = true;
709
752
  }
710
753
  if (payload.text) process.stdout.write(payload.text);
@@ -763,7 +806,7 @@ async function chat(options = {}) {
763
806
 
764
807
  if (type === "done") {
765
808
  if (!state.inText && payload.text) {
766
- process.stdout.write(`${C.bold}[助手]${C.reset} ${payload.text}\n`);
809
+ process.stdout.write(`${C.bold}[HaoYuan]${C.reset} ${payload.text}\n`);
767
810
  }
768
811
  endLine();
769
812
  if (state.busy) {
@@ -1102,11 +1145,9 @@ function compareVersions(a, b) {
1102
1145
  function npmCapture(args) {
1103
1146
  const full = [...args, ...npmRegistryArgs()];
1104
1147
  const useShell = IS_WIN && /\.(cmd|bat)$/i.test(NPM);
1105
- const r = spawnSync(NPM, useShell ? full.map(shellQuote) : full, {
1106
- cwd: ROOT,
1107
- encoding: "utf8",
1108
- shell: useShell,
1109
- });
1148
+ const r = useShell
1149
+ ? spawnSync([NPM, ...full.map(shellQuote)].join(" "), { cwd: ROOT, encoding: "utf8", shell: true })
1150
+ : spawnSync(NPM, full, { cwd: ROOT, encoding: "utf8" });
1110
1151
  if (r.error) return { ok: false, error: r.error.message };
1111
1152
  if (r.status !== 0) {
1112
1153
  const detail = (r.stderr || r.stdout || "").trim();
@@ -1132,10 +1173,24 @@ async function upgradeCommand() {
1132
1173
  return;
1133
1174
  }
1134
1175
 
1176
+ // Windows 下 npm 会重命名当前包目录;若服务正在运行或 cwd 在包内会 EBUSY,先停服务并在用户目录执行
1177
+ const port = readApiPort();
1178
+ if (port && (await healthyPort(port))) {
1179
+ stopLocalServer(port);
1180
+ await new Promise((resolve) => setTimeout(resolve, 800));
1181
+ }
1182
+
1135
1183
  log(`开始升级 v${VERSION} → v${latest} ...`);
1136
- const ok = run(NPM, ["install", "-g", `haoyuan@${latest}`, ...npmRegistryArgs()], { lenient: true });
1184
+ const installArgs = ["install", "-g", `haoyuan@${latest}`, ...npmRegistryArgs()];
1185
+ let ok = run(NPM, installArgs, { lenient: true, cwd: os.homedir() });
1186
+ if (!ok && IS_WIN) {
1187
+ await new Promise((resolve) => setTimeout(resolve, 1500));
1188
+ ok = run(NPM, installArgs, { lenient: true, cwd: os.homedir() });
1189
+ }
1137
1190
  if (!ok) {
1138
- fail("升级失败。若提示权限不足,请用管理员权限运行,或手动执行: npm install -g haoyuan@latest");
1191
+ fail(
1192
+ "升级失败:请完全退出正在运行的豪源(关闭所有 haoyuan 窗口/服务),在用户目录(如 C:\\Users\\你的用户名)下执行 npm install -g haoyuan@latest;权限不足请用管理员终端。"
1193
+ );
1139
1194
  }
1140
1195
  log(`升级完成:v${VERSION} → v${latest}`);
1141
1196
  log("请重新运行 haoyuan 以使用新版本。");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haoyuan",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "description": "豪源 · HaoYuan — 个人指挥 AI 实现多个 AI 员工异步并行工作的 AI 工作室",
5
5
  "bin": {
6
6
  "haoyuan": "bin/haoyuan.js"
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "haoyuan-web",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "haoyuan-web",
9
- "version": "0.0.4",
9
+ "version": "0.0.6",
10
10
  "dependencies": {
11
11
  "dompurify": "^3.2.4",
12
12
  "marked": "^15.0.7",
package/web/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haoyuan-web",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {