lingshu-skill 5.10.0 → 5.11.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/scripts/growth.py CHANGED
@@ -19,11 +19,13 @@ import http.client
19
19
  import json
20
20
  import os
21
21
  import subprocess
22
+ import tarfile
22
23
  import re
23
24
  import shutil
24
25
  import sys
25
26
  import threading
26
27
  import time
28
+ import urllib.request
27
29
  import uuid
28
30
  from pathlib import Path
29
31
 
@@ -1178,6 +1180,13 @@ def list_skills() -> list:
1178
1180
  # base64 拉取。Gitee 匿名 API 会触发 IP 风控(403),GitHub 匿名限额 60 次/小时
1179
1181
  # 按 IP 共享易耗尽;可在 config.json 配 gitee_token / github_token 走认证
1180
1182
  # (python scripts/brain.py config set gitee_token <token>)。token 绝不写日志。
1183
+ # npm 官方发布渠道:`npm i lingshu-skill`。CDN 快、有版本号与 shasum 可校验,
1184
+ # 比 Gitee/GitHub 的 zip 下载稳(后者受匿名限额与网络波动影响)。
1185
+ NPM_PACKAGE = "lingshu-skill"
1186
+ NPM_REGISTRY = "https://registry.npmjs.org"
1187
+ NPM_META_TTL = 600 # 版本信息缓存 10 分钟,别每次点都打 registry
1188
+ NPM_MAX_BYTES = 60 * 1024 * 1024 # 包体上限(防被塞个巨大文件)
1189
+
1181
1190
  GITEE_API_BASE = "https://gitee.com/api/v5/repos/htmcwy_0/lingshu-skill"
1182
1191
  GITEE_BRANCH = "main"
1183
1192
  GITHUB_REPO = "Q2667671398/lingshu-skill"
@@ -1973,6 +1982,140 @@ def _lingshu_remote_source_locked(force: bool) -> tuple[Path | None, str, str]:
1973
1982
  return None, "none", err
1974
1983
 
1975
1984
 
1985
+ def _npm_meta_cache_path() -> Path:
1986
+ return brain.HOME / "npm-meta.json"
1987
+
1988
+
1989
+ def npm_latest(force: bool = False, timeout: int = 20) -> dict:
1990
+ """查 npm 上 lingshu-skill 的最新版本(只读,带缓存)。
1991
+
1992
+ 返回 {ok, version, tarball, shasum, unpacked, fetched_at} 或 {ok: False, error}。
1993
+ """
1994
+ cache_p = _npm_meta_cache_path()
1995
+ if not force:
1996
+ try:
1997
+ c = json.loads(cache_p.read_text(encoding="utf-8"))
1998
+ if isinstance(c, dict) and time.time() - float(c.get("fetched_at") or 0) < NPM_META_TTL:
1999
+ return {**c, "cached": True}
2000
+ except (OSError, ValueError, TypeError):
2001
+ pass
2002
+ url = f"{NPM_REGISTRY}/{NPM_PACKAGE}/latest"
2003
+ try:
2004
+ req = urllib.request.Request(url, headers={
2005
+ "User-Agent": "lingshu-skill-updater",
2006
+ "Accept": "application/json",
2007
+ })
2008
+ with urllib.request.urlopen(req, timeout=timeout) as r:
2009
+ data = json.loads(r.read().decode("utf-8", "replace"))
2010
+ dist = data.get("dist") or {}
2011
+ out = {"ok": True, "version": str(data.get("version") or ""),
2012
+ "tarball": str(dist.get("tarball") or ""),
2013
+ "shasum": str(dist.get("shasum") or ""),
2014
+ "unpacked": int(dist.get("unpackedSize") or 0),
2015
+ "fetched_at": int(time.time())}
2016
+ if not out["version"] or not out["tarball"]:
2017
+ return {"ok": False, "error": "npm 返回的版本信息不完整"}
2018
+ try:
2019
+ cache_p.parent.mkdir(parents=True, exist_ok=True)
2020
+ cache_p.write_text(json.dumps(out, ensure_ascii=False), encoding="utf-8")
2021
+ except OSError:
2022
+ pass
2023
+ return out
2024
+ except Exception as exc: # noqa: BLE001
2025
+ return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
2026
+
2027
+
2028
+ def _safe_extract_tgz(tgz_path: Path, dest: Path) -> Path:
2029
+ """解包 npm tarball,只取 package/ 下的内容,且**逐条防路径穿越**。"""
2030
+ dest.mkdir(parents=True, exist_ok=True)
2031
+ root = None
2032
+ with tarfile.open(tgz_path, "r:gz") as tf:
2033
+ for m in tf.getmembers():
2034
+ name = m.name.replace("\\", "/")
2035
+ if m.issym() or m.islnk():
2036
+ continue # 链接一律跳过(可指向包外)
2037
+ if name.startswith("/") or ".." in Path(name).parts:
2038
+ raise KeyError(f"npm 包内有可疑路径,已中止:{name}")
2039
+ if not (name == "package" or name.startswith("package/")):
2040
+ continue # 只解 package/ 前缀
2041
+ rel = name[len("package"):].lstrip("/")
2042
+ if not rel:
2043
+ continue
2044
+ target = dest / rel
2045
+ if m.isdir():
2046
+ target.mkdir(parents=True, exist_ok=True)
2047
+ continue
2048
+ if not m.isfile():
2049
+ continue
2050
+ target.parent.mkdir(parents=True, exist_ok=True)
2051
+ f = tf.extractfile(m)
2052
+ if f is None:
2053
+ continue
2054
+ with open(target, "wb") as out:
2055
+ shutil.copyfileobj(f, out)
2056
+ if root is None:
2057
+ root = dest
2058
+ return root or dest
2059
+
2060
+
2061
+ def _lingshu_npm_source(force: bool = False) -> tuple[Path, str]:
2062
+ """下载并解出 npm 版灵枢,返回 (源目录, "npm");失败抛 KeyError 带原因。"""
2063
+ meta = npm_latest(force=force)
2064
+ if not meta.get("ok"):
2065
+ raise KeyError(f"npm 版本查询失败:{meta.get('error')}")
2066
+ ver = str(meta["version"])
2067
+ dest = brain.HOME / "sources" / f"npm-{NPM_PACKAGE}-{ver}"
2068
+ if (dest / "SKILL.md").is_file():
2069
+ return dest, "npm" # 已经下过这个版本,直接复用
2070
+ tmp_dir = dest.parent / f".npm-tmp-{ver}-{uuid.uuid4().hex[:8]}"
2071
+ tgz = tmp_dir.with_suffix(".tgz")
2072
+ try:
2073
+ tmp_dir.parent.mkdir(parents=True, exist_ok=True)
2074
+ req = urllib.request.Request(meta["tarball"],
2075
+ headers={"User-Agent": "lingshu-skill-updater"})
2076
+ h = hashlib.sha1()
2077
+ got = 0
2078
+ with urllib.request.urlopen(req, timeout=60) as r, open(tgz, "wb") as out:
2079
+ while True:
2080
+ chunk = r.read(256 * 1024)
2081
+ if not chunk:
2082
+ break
2083
+ got += len(chunk)
2084
+ if got > NPM_MAX_BYTES:
2085
+ raise KeyError(f"npm 包体超过上限(>{NPM_MAX_BYTES // (1024 * 1024)}MB),已中止")
2086
+ h.update(chunk)
2087
+ out.write(chunk)
2088
+ want = str(meta.get("shasum") or "")
2089
+ if want and h.hexdigest() != want:
2090
+ raise KeyError(f"npm 包校验失败(sha1 不符):期望 {want[:12]}…,实得 {h.hexdigest()[:12]}…")
2091
+ _safe_extract_tgz(tgz, tmp_dir)
2092
+ if not (tmp_dir / "SKILL.md").is_file():
2093
+ raise KeyError("npm 包里没有 SKILL.md,可能不是灵枢技能包")
2094
+ if dest.exists():
2095
+ shutil.rmtree(dest, ignore_errors=True)
2096
+ tmp_dir.rename(dest)
2097
+ try:
2098
+ brain.log_event("update", f"已从 npm 下载灵枢 v{ver}({got // 1024} KB,sha1 校验通过)")
2099
+ except Exception:
2100
+ pass
2101
+ return dest, "npm"
2102
+ except KeyError:
2103
+ raise
2104
+ except Exception as exc: # noqa: BLE001
2105
+ raise KeyError(f"npm 下载失败:{type(exc).__name__}: {exc}") from exc
2106
+ finally:
2107
+ try:
2108
+ if tgz.is_file():
2109
+ tgz.unlink()
2110
+ except OSError:
2111
+ pass
2112
+ try:
2113
+ if tmp_dir.is_dir():
2114
+ shutil.rmtree(tmp_dir, ignore_errors=True)
2115
+ except OSError:
2116
+ pass
2117
+
2118
+
1976
2119
  def _update_check_live(name: str = "lingshu", force_pull: bool = False) -> dict:
1977
2120
  """检查本地源与全局已装副本的差异,返回「更新了什么」明细。
1978
2121
 
@@ -2131,12 +2274,24 @@ def _update_check_live(name: str = "lingshu", force_pull: bool = False) -> dict:
2131
2274
  return out
2132
2275
 
2133
2276
 
2134
- def _load_update_cache() -> dict | None:
2135
- """读「检查更新」结果缓存;文件不存在/损坏返回 None。"""
2277
+ def _load_update_cache(prefer: str | None = None) -> dict | None:
2278
+ """读「检查更新」结果缓存;文件不存在/损坏返回 None。
2279
+
2280
+ prefer 给了就做**来源一致性检查**:用户把 update_source 从 git 改成 npm 后,
2281
+ 旧的 git 结果不能冒充新来源的已是最新,否则切了源还是看到旧结论。
2282
+ """
2136
2283
  try:
2137
2284
  if not UPDATE_CACHE_FILE.is_file():
2138
2285
  return None
2139
- return _read_json(UPDATE_CACHE_FILE)
2286
+ data = _read_json(UPDATE_CACHE_FILE)
2287
+ if not isinstance(data, dict):
2288
+ return None
2289
+ pref = str(prefer or "").strip().lower()
2290
+ if pref in ("npm", "git"):
2291
+ cached_src = str(data.get("source") or "").strip().lower()
2292
+ if cached_src and cached_src != pref:
2293
+ return None # 来源换了:缓存作废,让调用方重新查
2294
+ return data
2140
2295
  except (OSError, ValueError):
2141
2296
  return None
2142
2297
 
@@ -2149,19 +2304,22 @@ def _save_update_cache(result: dict) -> None:
2149
2304
  return
2150
2305
  try:
2151
2306
  UPDATE_CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
2152
- brain.atomic_json(UPDATE_CACHE_FILE, {"ts": int(time.time()), "result": result})
2307
+ brain.atomic_json(UPDATE_CACHE_FILE, {"ts": int(time.time()),
2308
+ "source": str(result.get("source") or ""),
2309
+ "result": result})
2153
2310
  except (OSError, ValueError):
2154
2311
  pass
2155
2312
 
2156
2313
 
2157
- def update_check(name: str = "lingshu", force_pull: bool = False, auto: bool = False) -> dict:
2314
+ def update_check(name: str = "lingshu", force_pull: bool = False, auto: bool = False,
2315
+ prefer: str | None = None) -> dict:
2158
2316
  """检查更新(带缓存):auto=True 严格只读缓存绝不联网,force_pull=True 联网并刷新缓存。
2159
2317
 
2160
2318
  面板服务启动时后台用 force_pull=True 检测一次并写缓存;浏览器刷新面板
2161
2319
  用 auto=True(毫秒级返回,永不联网、永不阻塞页面),缓存不存在就返回
2162
2320
  cached=False 由前端自行降级。用户手动点「检查更新」才走 force_pull=True。
2163
2321
  """
2164
- cache = _load_update_cache()
2322
+ cache = _load_update_cache(prefer)
2165
2323
  if auto:
2166
2324
  if cache and isinstance(cache.get("result"), dict):
2167
2325
  res = dict(cache["result"])
@@ -2377,8 +2535,8 @@ def _accept_risk(name: str) -> None:
2377
2535
  pass
2378
2536
 
2379
2537
 
2380
- def resolve_source(name: str = "lingshu", force_pull: bool = False
2381
- ) -> tuple[Path, str]:
2538
+ def resolve_source(name: str = "lingshu", force_pull: bool = False,
2539
+ prefer: str | None = None) -> tuple[Path, str]:
2382
2540
  """更新源解析的单一入口:dev → remote → installed,返回 (源目录, source_kind)。
2383
2541
 
2384
2542
  - dev:本地开发目录配置(config.json 里 sources.<name> 指向含 SKILL.md 的目录,
@@ -2387,31 +2545,65 @@ def resolve_source(name: str = "lingshu", force_pull: bool = False
2387
2545
  拉取失败抛出带原因的 KeyError。
2388
2546
  - installed:已安装本地版本(唯一保底,永远可解析)。
2389
2547
 
2548
+ `prefer`:显式指定远程源("npm" / "git")。给了就**跳过 dev 判断**——
2549
+ 面板「从 npm 更新」与排障命令需要它,否则开发仓库里永远被 dev 抢先。
2550
+
2390
2551
  update_check / install_skill / apply 流程统一从这里拿源,不再各写一套交织判断。
2391
2552
  """
2392
2553
  name = _require_slug(name)
2393
- # 1) 本地开发目录配置
2554
+ _prefer_in = str(prefer or "").strip().lower()
2555
+ if _prefer_in not in ("npm", "git"):
2556
+ _prefer_in = ""
2557
+ # 1) 本地开发目录配置(显式指定远程源时跳过,避免 dev 把 npm/git 抢掉)
2394
2558
  try:
2395
2559
  cfg = _read_json(brain.HOME / "config.json")
2396
2560
  dev = str((cfg.get("sources") or {}).get(name) or "").strip()
2397
- if dev and (Path(dev).expanduser() / "SKILL.md").is_file():
2561
+ if (not _prefer_in and dev
2562
+ and (Path(dev).expanduser() / "SKILL.md").is_file()):
2398
2563
  return Path(dev).expanduser(), "dev"
2399
2564
  except (OSError, ValueError, AttributeError):
2400
2565
  pass
2401
2566
  # 2) 面板跑在开发仓库里:自身目录即源(且不是已装副本自己比自己)
2402
2567
  try:
2403
2568
  self_dir = Path(__file__).resolve().parent.parent
2404
- if ((self_dir / "SKILL.md").is_file() and _is_lingshu(name, {}, None)
2569
+ if (not _prefer_in
2570
+ and (self_dir / "SKILL.md").is_file() and _is_lingshu(name, {}, None)
2405
2571
  and self_dir.resolve() != _find_installed(name).resolve()):
2406
2572
  return self_dir, "dev"
2407
2573
  except (OSError, ValueError, KeyError):
2408
2574
  pass
2409
2575
  # 3) 远程拉取(灵枢本体专属能力)
2576
+ # 优先 **npm**:官方发布渠道、CDN 快、有版本号与 shasum 可校验;
2577
+ # Gitee/GitHub 的 zip 下载受匿名限额与网络波动影响(历史上"远程拉取失败"多卡在这)。
2410
2578
  if _is_lingshu(name, {}, None):
2579
+ _prefer = "auto"
2580
+ if _prefer_in:
2581
+ _prefer = _prefer_in # 显式参数优先于配置
2582
+ else:
2583
+ try:
2584
+ _prefer = str((_read_json(brain.HOME / "config.json")
2585
+ .get("update_source") or "auto")).strip().lower()
2586
+ except (OSError, ValueError, AttributeError):
2587
+ _prefer = "auto"
2588
+ if _prefer not in ("auto", "npm", "git"):
2589
+ _prefer = "auto"
2590
+ _npm_err = None
2591
+ if _prefer in ("auto", "npm"):
2592
+ try:
2593
+ _dir, _kind = _lingshu_npm_source(force=force_pull)
2594
+ return _dir, _kind
2595
+ except KeyError as e:
2596
+ _npm_err = str(e)
2597
+ if _prefer == "npm":
2598
+ raise KeyError(f"npm 下载失败:{_npm_err}") from e
2411
2599
  remote, source, err = _lingshu_remote_source(force=force_pull)
2412
2600
  if remote is not None:
2413
2601
  return remote, source if source in ("gitee", "github") else "remote"
2414
- raise KeyError(f"远程拉取更新源失败(Gitee/GitHub 均不可用):{err}")
2602
+ _parts = []
2603
+ if _npm_err:
2604
+ _parts.append(f"npm:{_npm_err}")
2605
+ _parts.append(f"Gitee/GitHub:{err}")
2606
+ raise KeyError("远程拉取更新源失败(" + ";".join(_parts) + ")")
2415
2607
  # 4) 已安装本地版本兜底
2416
2608
  installed = _find_installed(name)
2417
2609
  if (installed / "SKILL.md").is_file():
@@ -737,17 +737,34 @@ class Handler(BaseHTTPRequestHandler):
737
737
  qs = parse_qs(url.query)
738
738
  auto = (qs.get("auto") or ["0"])[0] in ("1", "true", "yes")
739
739
  refresh = (qs.get("refresh") or ["0"])[0] in ("1", "true", "yes")
740
+ src_pref = (qs.get("source") or [""])[0].strip().lower()
741
+ if src_pref not in ("npm", "git"):
742
+ src_pref = ""
740
743
  res = growth.update_check("lingshu", force_pull=refresh, auto=auto)
741
744
  # 透出源类型(dev/remote/installed/none)与源目标路径,供前端确认框展示。
742
745
  # 注意:这里不能再 force_pull=refresh——update_check 刚拉过一遍远程并写了
743
746
  # 缓存,再来一遍等于把整条 Gitee/GitHub 拉取链路跑两次,手动检查必然超时。
744
747
  if isinstance(res, dict) and res.get("cached") is not False:
745
748
  try:
746
- src, kind = growth.resolve_source("lingshu", force_pull=False)
749
+ src, kind = growth.resolve_source("lingshu", force_pull=False,
750
+ prefer=(src_pref or None))
747
751
  res["source_kind"] = kind
752
+ res["source"] = kind
748
753
  res["target_path"] = str(src)
749
- except Exception:
754
+ except Exception as exc: # noqa: BLE001
750
755
  res.setdefault("source_kind", res.get("source", "none"))
756
+ res["source_error"] = str(exc)[:200]
757
+ # 手动检查时附带 npm 版本信息(走缓存,不打二次网络):前端能显示
758
+ # "npm 最新 vX(~N KB)",让用户知道这个下载方式可用、多大。
759
+ if isinstance(res, dict) and refresh and not auto:
760
+ try:
761
+ nm = growth.npm_latest(force=False)
762
+ if nm.get("ok"):
763
+ res["npm"] = {"version": nm.get("version"),
764
+ "unpacked": nm.get("unpacked"),
765
+ "cached": bool(nm.get("cached"))}
766
+ except Exception:
767
+ pass
751
768
  self._json(res)
752
769
  return
753
770
  if path == "/api/workspace":
@@ -1634,14 +1651,29 @@ def _api_skill(self, path, data):
1634
1651
  data.get("append"), data.get("description"))
1635
1652
  self._json({"ok": True, "skill": res, "workspace": workspace()})
1636
1653
  elif act == "install":
1637
- # 面板安装忽略 from_dir:本地 CLI 才能指外部目录,防远程乱指
1638
- res = growth.install_skill(data.get("name", ""),
1654
+ # 面板安装忽略前端传的 from_dir:本地 CLI 才能指外部目录,防远程乱指。
1655
+ # 但允许传**下载源枚举**(npm/git):目录由服务端自己 resolve,客户端拿不到路径控制权。
1656
+ _name = data.get("name", "")
1657
+ _src_pref = str(data.get("source") or "").strip().lower()
1658
+ _from = None
1659
+ if _src_pref in ("npm", "git") and _name:
1660
+ try:
1661
+ _dir, _kind = growth.resolve_source(_name, force_pull=True,
1662
+ prefer=_src_pref)
1663
+ _from = str(_dir)
1664
+ except KeyError as exc:
1665
+ self._json({"error": f"{_src_pref} 下载源不可用:{exc}"}, 502)
1666
+ return
1667
+ res = growth.install_skill(_name,
1639
1668
  bool(data.get("force")),
1640
- None,
1669
+ _from,
1641
1670
  accept_risk=bool(data.get("yes")))
1671
+ if isinstance(res, dict):
1672
+ res.setdefault("source", _src_pref or "auto")
1642
1673
  # 面板触发的更新/安装要留痕(特别是本体 lingshu):事后能查谁在何时更新到什么状态
1643
- brain.log_event("panel", f"安装/更新技能 {data.get('name', '')} "
1644
- f"(force={bool(data.get('force'))}) → {res.get('state')}")
1674
+ brain.log_event("panel", f"安装/更新技能 {_name} "
1675
+ f"(源={_src_pref or 'auto'}, force={bool(data.get('force'))}) "
1676
+ f"→ {res.get('state')}")
1645
1677
  self._json({"ok": True, "result": res, "workspace": workspace()})
1646
1678
  return
1647
1679
  elif act == "uninstall":
@@ -76,6 +76,9 @@ CONFIG_SCHEMA: list[dict[str, Any]] = [
76
76
  "hint": "送进 rerank 的候选条数,越大越准也越慢"},
77
77
 
78
78
  # —— 面板与宿主 ——
79
+ {"key": "update_source", "group": "自动更新与备份", "label": "更新下载源",
80
+ "kind": "enum", "options": ["auto", "npm", "git"],
81
+ "hint": "auto=npm 优先(失败退回 Gitee/GitHub);npm=只走 npm 官方包;git=只走 Gitee/GitHub"},
79
82
  {"key": "panel_idle_minutes", "group": "面板与宿主", "label": "空闲自动退出(分钟)",
80
83
  "kind": "int", "min": 0, "max": 1440, "step": 5,
81
84
  "hint": "关掉网页后,多少分钟没请求就自动退出服务(默认 1);0=永不退出(需重启面板生效)"},
@@ -27,24 +27,51 @@ def enabled() -> bool:
27
27
  return bool(_cfg().get("auto_update"))
28
28
 
29
29
 
30
- def check(force_pull: bool = False) -> dict:
31
- """查有没有新版本(只读)。"""
30
+ def _normalize(res: dict) -> dict:
31
+ """把 growth.update_check 的字段名补成调用方好用的别名,**不改原字段**。
32
+
33
+ 历史坑:run() 判断的是 `update_available`,而 update_check 返回的是 `outdated`,
34
+ 于是自动更新永远走"已是最新"分支——功能等于没接上。
35
+ """
36
+ if not isinstance(res, dict):
37
+ return res
38
+ if "update_available" not in res:
39
+ res["update_available"] = bool(res.get("outdated"))
40
+ res.setdefault("current", res.get("installed_version"))
41
+ res.setdefault("latest", res.get("source_version") or res.get("version"))
42
+ return res
43
+
44
+
45
+ def check(force_pull: bool = False, source: str | None = None) -> dict:
46
+ """查有没有新版本(只读)。`source` 可强制 "npm" / "git"。"""
32
47
  import growth
33
48
  try:
34
- return growth.update_check("lingshu", force_pull=force_pull)
49
+ if source:
50
+ # 强制指定源时先把它解析出来(顺带把"能不能拿到"这件事暴露给调用方)
51
+ src, kind = growth.resolve_source("lingshu", force_pull=force_pull,
52
+ prefer=source)
53
+ res = growth.update_check("lingshu", force_pull=force_pull,
54
+ prefer=source)
55
+ if isinstance(res, dict):
56
+ res["source"] = kind
57
+ res["source_kind"] = kind
58
+ res["target_path"] = str(src)
59
+ return _normalize(res)
60
+ return _normalize(growth.update_check("lingshu", force_pull=force_pull,
61
+ prefer=source))
35
62
  except Exception as exc: # noqa: BLE001
36
63
  core.log_event("update", f"检查更新失败:{exc}", level="warn")
37
64
  return {"ok": False, "error": str(exc)}
38
65
 
39
66
 
40
- def run(force: bool = False) -> dict:
41
- """执行一次自动更新(含更新前备份)。返回结果字典。"""
67
+ def run(force: bool = False, source: str | None = None) -> dict:
68
+ """执行一次自动更新(含更新前备份)。`source` 可强制 "npm" / "git"。"""
42
69
  if core.READONLY:
43
70
  return {"ok": False, "reason": "记忆库只读,跳过自动更新"}
44
71
  if not force and not enabled():
45
72
  return {"ok": False, "skipped": True, "reason": "auto_update 未开启"}
46
73
 
47
- chk = check(force_pull=True)
74
+ chk = check(force_pull=True, source=source)
48
75
  if not chk or not chk.get("update_available"):
49
76
  return {"ok": True, "skipped": True,
50
77
  "reason": "已是最新", "current": chk.get("current"),
@@ -67,15 +94,17 @@ def run(force: bool = False) -> dict:
67
94
  # ② 原子更新
68
95
  try:
69
96
  import growth
70
- src, kind = growth.resolve_source("lingshu", force_pull=False)
97
+ src, kind = growth.resolve_source("lingshu", force_pull=False,
98
+ prefer=source)
71
99
  res = growth.install_skill("lingshu", force=True, from_dir=str(src))
72
100
  except Exception as exc: # noqa: BLE001
73
101
  core.log_event("update", f"自动更新失败:{exc}", level="error")
74
102
  return {"ok": False, "reason": f"更新失败(已回滚):{exc}", "backup": bak}
75
103
 
76
- core.log_event("update", f"自动更新完成:{chk.get('current')} → {chk.get('latest')};"
77
- f"更新前备份 {bak}")
104
+ core.log_event("update", f"自动更新完成(来源 {chk.get('source') or 'auto'}):"
105
+ f"{chk.get('current')} → {chk.get('latest')};更新前备份 {bak}")
78
106
  return {"ok": True, "updated": True, "backup": bak,
107
+ "source": chk.get("source") or "auto",
79
108
  "from": chk.get("current"), "to": chk.get("latest"),
80
109
  "detail": res if isinstance(res, dict) else str(res),
81
110
  "at": int(time.time())}