lingshu-skill 5.30.0 → 5.31.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +1 -1
  3. package/SKILL-lite.md +1 -1
  4. package/SKILL-tiny.md +1 -1
  5. package/SKILL.md +341 -405
  6. package/assets/panel.html +490 -18
  7. package/cordis-plugin/lingshu-cron/plugin.js +195 -29
  8. package/docs//344/275/277/347/224/250/346/214/207/345/215/227.md +229 -0
  9. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +73 -31
  10. package/docs//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
  11. package/package.json +1 -1
  12. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +20 -17
  13. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +79 -0
  14. package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
  15. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
  16. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
  17. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +341 -405
  18. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +490 -18
  19. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +47 -18
  20. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +32 -0
  21. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +7 -1
  22. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +14 -6
  23. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +27 -5
  24. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +15 -0
  25. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +462 -14
  26. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_icon.py +220 -0
  27. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_launcher.py +114 -10
  28. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +165 -41
  29. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_shortcut.py +330 -0
  30. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_splash.py +181 -0
  31. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +19 -5
  32. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +29 -3
  33. package/scripts/cli.py +47 -18
  34. package/scripts/core.py +32 -0
  35. package/scripts/dream.py +7 -1
  36. package/scripts/emotion.py +14 -6
  37. package/scripts/growth.py +27 -5
  38. package/scripts/mem_dialogue.py +15 -0
  39. package/scripts/memory.py +462 -14
  40. package/scripts/panel_icon.py +220 -0
  41. package/scripts/panel_launcher.py +114 -10
  42. package/scripts/panel_server.py +165 -41
  43. package/scripts/panel_shortcut.py +330 -0
  44. package/scripts/panel_splash.py +181 -0
  45. package/scripts/persona.py +19 -5
  46. package/scripts/safety_net.py +29 -3
@@ -0,0 +1,220 @@
1
+ # -*- coding: utf-8 -*-
2
+ """自定义桌面快捷方式图标:选图 → 转多尺寸 .ico → 写进 .lnk。
3
+
4
+ 调研结论(为什么这么做):
5
+
6
+ 1. **.lnk 存的不是图标本身,而是一个「IconLocation」字符串**
7
+ (`C:\\path\\x.ico,0` 或 `C:\\path\\app.exe,3`)。所以换图标 = 生成一个 .ico 文件 +
8
+ 改这一个字段。不能把图片直接塞进 .lnk。
9
+
10
+ 2. **.ico 必须是多尺寸的**。Windows 在不同位置取不同尺寸:任务栏 32、桌面大图标 48/
11
+ 96、Alt+Tab 与高分屏 256。只放一张 256 的话,小尺寸会被临时缩放,糊成一团。
12
+ 灵枢原来那个 lingshu.ico 就是 7 档(16/24/32/48/64/128/256),这里对齐它。
13
+
14
+ 3. **改完要让资源管理器重新读**。Explorer 会缓存图标,光改 .lnk 常常「没反应」。
15
+ 标准做法是 `SHChangeNotify(SHCNE_ASSOCCHANGED)` + 通知 shell 刷新;
16
+ 更狠的是删 IconCache.db(要重启 explorer,代价大,不做)。
17
+
18
+ 4. **图片转 ico 用 Pillow**(本机 12.3 可用)。没有 Pillow 时降级:只接受已经是
19
+ .ico 的文件,并如实告诉用户「要 PNG 转 ICO 需要 Pillow」。
20
+
21
+ 安全边界沿用 panel_shortcut 的那套:只写 IconLocation,写前备份 .lnk,
22
+ 写后逐字段核对其它字段没被破坏,坏了立刻还原。
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import base64
27
+ import io
28
+ import subprocess
29
+ from pathlib import Path
30
+
31
+ # 与 lingshu.ico 对齐的尺寸档位
32
+ ICO_SIZES = [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
33
+ # 支持的输入格式
34
+ INPUT_EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif", ".ico")
35
+
36
+
37
+ class IconError(RuntimeError):
38
+ """图标相关操作失败。"""
39
+
40
+
41
+ def _data_dir() -> Path:
42
+ d = Path.home() / ".brain-memory"
43
+ try:
44
+ d.mkdir(parents=True, exist_ok=True)
45
+ except OSError:
46
+ pass
47
+ return d
48
+
49
+
50
+ def default_icon() -> Path:
51
+ return _data_dir() / "lingshu.ico"
52
+
53
+
54
+ def custom_icon() -> Path:
55
+ """用户自定义图标的落地位置(固定名,方便来回替换且不堆垃圾)。"""
56
+ return _data_dir() / "lingshu-custom.ico"
57
+
58
+
59
+ def pillow_available() -> bool:
60
+ try:
61
+ import PIL # noqa: F401
62
+ return True
63
+ except Exception:
64
+ return False
65
+
66
+
67
+ # ---------------------------------------------------------------- 选文件(原生对话框)
68
+
69
+ _PS_PICK = r"""
70
+ $ErrorActionPreference='Stop'
71
+ Add-Type -AssemblyName System.Windows.Forms | Out-Null
72
+ $d = New-Object System.Windows.Forms.OpenFileDialog
73
+ $d.Title = '选择图标图片(建议正方形,≥256×256)'
74
+ $d.Filter = '图片或图标|*.png;*.jpg;*.jpeg;*.bmp;*.webp;*.gif;*.ico|所有文件|*.*'
75
+ $d.CheckFileExists = $true
76
+ $d.Multiselect = $false
77
+ if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
78
+ Write-Output $d.FileName
79
+ }
80
+ """
81
+
82
+
83
+ def pick_image_file() -> str | None:
84
+ """弹出 Windows 原生文件选择框,返回选中的路径(取消则 None)。
85
+
86
+ 为什么由服务端弹框而不是网页 `<input type=file>`:
87
+ 面板跑在本机 `127.0.0.1`,浏览器出于安全**不会**把真实路径交给页面。
88
+ 而写 .lnk 需要真实路径,所以这个框必须在服务端弹。
89
+ `-STA` 是 WinForms 对话框的硬要求。
90
+ """
91
+ blob_src = _PS_PICK
92
+ blob = base64.b64encode(blob_src.encode("utf-16-le")).decode("ascii")
93
+ try:
94
+ r = subprocess.run(
95
+ ["powershell", "-STA", "-NoProfile", "-NonInteractive",
96
+ "-EncodedCommand", blob],
97
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
98
+ timeout=180, # 用户可能慢慢挑,给足时间
99
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
100
+ except subprocess.TimeoutExpired as exc:
101
+ raise IconError("选择文件超时(3 分钟)") from exc
102
+ except (OSError, subprocess.SubprocessError) as exc:
103
+ raise IconError(f"打开文件选择框失败:{exc}") from exc
104
+ out = (r.stdout or "").strip()
105
+ return out or None
106
+
107
+
108
+ # ---------------------------------------------------------------- 图片 → 多尺寸 ico
109
+
110
+ def to_ico(src: str | Path, dst: str | Path | None = None) -> Path:
111
+ """把图片转成多尺寸 .ico。已经是 .ico 且含足够尺寸时直接复制。"""
112
+ src = Path(src)
113
+ if not src.is_file():
114
+ raise IconError(f"文件不存在:{src}")
115
+ if src.suffix.lower() not in INPUT_EXTS:
116
+ raise IconError(f"不支持的文件类型「{src.suffix}」,"
117
+ f"可用:{'、'.join(INPUT_EXTS)}")
118
+ out = Path(dst) if dst else custom_icon()
119
+ out.parent.mkdir(parents=True, exist_ok=True)
120
+
121
+ # 已经是 .ico:直接拿来用(但它可能只有单尺寸,下面会检查)
122
+ if src.suffix.lower() == ".ico":
123
+ try:
124
+ sizes = _ico_sizes(src)
125
+ except Exception:
126
+ sizes = []
127
+ if len(sizes) >= 4:
128
+ out.write_bytes(src.read_bytes())
129
+ return out
130
+ # 尺寸太少 → 用 Pillow 重新打包(借它的第一帧当源)
131
+ if not pillow_available():
132
+ out.write_bytes(src.read_bytes())
133
+ return out
134
+
135
+ if not pillow_available():
136
+ raise IconError("要把 PNG/JPG 转成图标需要 Pillow(pip install pillow);"
137
+ "或者你直接准备一个 .ico 文件再选。")
138
+ from PIL import Image
139
+ try:
140
+ im = Image.open(src)
141
+ im.load()
142
+ except Exception as exc:
143
+ raise IconError(f"读不了这张图:{exc}") from exc
144
+
145
+ # 统一成正方形 RGBA:非正方形先裁中心,避免被拉变形
146
+ im = im.convert("RGBA")
147
+ w, h = im.size
148
+ if w != h:
149
+ side = min(w, h)
150
+ left = (w - side) // 2
151
+ top = (h - side) // 2
152
+ im = im.crop((left, top, left + side, top + side))
153
+ if im.size[0] < 256:
154
+ # 小图直接放大到 256,让最大档不虚(放大会略软,但比"没有大图标"好)
155
+ im = im.resize((256, 256), Image.LANCZOS)
156
+ try:
157
+ im.save(out, format="ICO", sizes=ICO_SIZES)
158
+ except Exception as exc:
159
+ raise IconError(f"生成 .ico 失败:{exc}") from exc
160
+ if not out.is_file() or out.stat().st_size == 0:
161
+ raise IconError("生成的 .ico 是空的,请换一张图片试试")
162
+ return out
163
+
164
+
165
+ def _ico_sizes(p: Path) -> list[tuple[int, int]]:
166
+ """读 .ico 里有哪些尺寸(纯标准库,不依赖 Pillow 做判断)。"""
167
+ import struct
168
+ b = p.read_bytes()
169
+ if len(b) < 6:
170
+ return []
171
+ _res, typ, n = struct.unpack("<HHH", b[:6])
172
+ if typ != 1:
173
+ return []
174
+ out = []
175
+ for i in range(n):
176
+ off = 6 + i * 16
177
+ if off + 16 > len(b):
178
+ break
179
+ w, h = struct.unpack("<BB", b[off:off + 2])
180
+ out.append((w or 256, h or 256))
181
+ return out
182
+
183
+
184
+ def ico_info(p: str | Path) -> dict:
185
+ p = Path(p)
186
+ if not p.is_file():
187
+ return {"exists": False}
188
+ try:
189
+ sizes = _ico_sizes(p)
190
+ except Exception:
191
+ sizes = []
192
+ return {
193
+ "exists": True,
194
+ "path": str(p),
195
+ "bytes": p.stat().st_size,
196
+ "sizes": sorted({s[0] for s in sizes}),
197
+ }
198
+
199
+
200
+ def preview_data_url(p: str | Path, size: int = 64) -> str:
201
+ """把 .ico 转成 PNG data URL,供网页 `<img>` 直接显示(无需额外鉴权)。
202
+
203
+ 网页 `<img src>` 带不了 Authorization 头,所以走 data URL 最省事。
204
+ """
205
+ p = Path(p)
206
+ if not p.is_file():
207
+ return ""
208
+ if not pillow_available():
209
+ return ""
210
+ from PIL import Image
211
+ try:
212
+ im = Image.open(p)
213
+ im = im.convert("RGBA")
214
+ im = im.copy()
215
+ im.thumbnail((size, size), Image.LANCZOS)
216
+ buf = io.BytesIO()
217
+ im.save(buf, format="PNG")
218
+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
219
+ except Exception:
220
+ return ""
@@ -140,20 +140,41 @@ def _port_occupied(port: int) -> bool:
140
140
  pass
141
141
 
142
142
 
143
+ def _port_bindable(port: int) -> bool:
144
+ """端口现在能不能被我们 bind(瞬时判断,不发任何 HTTP 请求)。
145
+
146
+ 为什么不用 `_ping` 来判断"有没有在跑":本机实测——**连接一个没有监听的本地端口
147
+ 不是立刻 ECONNREFUSED,而是一直挂到超时**(安全软件/防火墙丢 SYN)。
148
+ 于是 `_ping` 每次都烧满 1.5s、`_looks_like_panel` 烧 2s,启动前那套
149
+ "先探测三轮再起服务"白白花掉 **7.1 秒**(实测 8.3s 里的大头)。
150
+ bind 探测是纯本地内核操作,几毫秒返回。
151
+
152
+ 注意**不设 SO_REUSEADDR**:Windows 上设了它可以让两个 socket 绑同一端口,
153
+ 那样探测就永远"成功",等于没测。
154
+ """
155
+ import socket
156
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
157
+ try:
158
+ s.bind(("127.0.0.1", port))
159
+ return True
160
+ except OSError:
161
+ return False
162
+ finally:
163
+ try:
164
+ s.close()
165
+ except Exception:
166
+ pass
167
+
168
+
143
169
  def main() -> int:
144
170
  port = _port()
145
171
  url = f"http://127.0.0.1:{port}"
146
172
 
147
- info = _wait_for_app(port, tries=3, gap=0.2)
148
- if info and info.get("app") == "lingshu-panel":
149
- # 已经在跑:只把浏览器叫到前面来,不起第二个进程
150
- _open_browser(url)
151
- return 0
152
- if _port_occupied(port):
153
- # 竞态:连点时端口可能刚被**同伴**抢到,而我们第一轮探测太早没看到。
154
- # 先多等一会儿再看——只有确认不是我们自己的面板,才报"被别的程序占用"。
155
- again = _wait_for_app(port, tries=12, gap=0.3)
156
- if again and again.get("app") == "lingshu-panel":
173
+ # 一次性、瞬时地判断端口状态;只有确实有人在听时,才去做(较贵的)HTTP 探测。
174
+ if not _port_bindable(port):
175
+ info = _wait_for_app(port, tries=8, gap=0.25)
176
+ if info and info.get("app") == "lingshu-panel":
177
+ # 已经在跑:只把浏览器叫到前面来,不起第二个进程
157
178
  _open_browser(url)
158
179
  return 0
159
180
  _msgbox(
@@ -167,6 +188,89 @@ def main() -> int:
167
188
  # 起服务(serve 内部带空闲自退 + 打开浏览器)
168
189
  # 竞态下 bind 失败是预期行为(另一个同伴刚抢到),让 serve 别往 stderr 吐假警报。
169
190
  os.environ["LINGSHU_QUIET_PORT"] = "1"
191
+
192
+ # ---------------------------------------------------------------- 立刻给反馈
193
+ # 从这里到浏览器出画面还有好几秒(进程创建 + 导入 + 绑端口 + 浏览器渲染),
194
+ # 全程没有可见输出 → 用户以为没点上。所以**秒开一枚启动光晕**,服务就绪即关。
195
+ # tkinter 跑在主线程,真正的服务启动放后台线程(Windows 上 tkinter 必须占主线程)。
196
+ splash = None
197
+ if os.environ.get("LINGSHU_NO_SPLASH", "").strip() not in ("1", "true", "yes"):
198
+ try:
199
+ import panel_splash
200
+ if panel_splash.available():
201
+ splash = panel_splash.Splash("正在唤醒记忆…")
202
+ except Exception:
203
+ splash = None # 拿不到就不装,退化成原来的静默启动
204
+
205
+ import threading
206
+ state = {"ready": False, "err": None, "serving": False}
207
+
208
+ def _boot():
209
+ """后台线程:起服务。成功后会一直阻塞在 serve_forever(预期行为)。"""
210
+ try:
211
+ import panel_server
212
+ panel_server.serve(port, open_browser=False) # 浏览器由主线程开,顺序可控
213
+ state["serving"] = True
214
+ except (SystemExit, OSError) as exc:
215
+ state["err"] = exc
216
+ except Exception as exc: # noqa: BLE001
217
+ state["err"] = exc
218
+
219
+ if splash is not None:
220
+ th = threading.Thread(target=_boot, name="panel-boot", daemon=True)
221
+ th.start()
222
+
223
+ def _watch():
224
+ """轮询:服务通了就关光晕 + 开浏览器。"""
225
+ if state["err"] is not None:
226
+ splash.close()
227
+ return
228
+ info2 = _ping(port, timeout=0.6)
229
+ if info2 and info2.get("app") == "lingshu-panel":
230
+ splash.set_text("已就绪 · 正在打开面板…")
231
+ splash.close()
232
+ _open_browser(url)
233
+ return
234
+ if splash.root is not None and not splash._closed:
235
+ splash.root.after(140, _watch)
236
+
237
+ # 超时兜底:9 秒还没通就换文案,17 秒仍未通就关窗——不许永久挂在屏幕上
238
+ def _slow_note():
239
+ if not splash._closed:
240
+ splash.set_text("启动比预期慢,仍在尝试…")
241
+
242
+ def _hard_stop():
243
+ splash.close()
244
+
245
+ if splash.root is not None:
246
+ splash.root.after(9000, _slow_note)
247
+ splash.root.after(17000, _hard_stop)
248
+ splash.root.after(140, _watch)
249
+ splash.run() # 主线程跑界面直到 close()
250
+
251
+ # 光晕关掉后:服务线程若已失败,按原来的方式报错(不能静默退出)
252
+ if state["err"] is not None:
253
+ exc = state["err"]
254
+ again = _wait_for_app(port, tries=10, gap=0.35)
255
+ if again and again.get("app") == "lingshu-panel":
256
+ _open_browser(url)
257
+ return 0
258
+ if _port_occupied(port):
259
+ _msgbox(
260
+ f"端口 {port} 已被别的程序占用,面板起不来。\n\n"
261
+ f"两种办法:\n"
262
+ f" 1) 关掉占用该端口的程序;\n"
263
+ f" 2) 用 brain.py config set panel_port 8766 换个端口。",
264
+ "灵枢面板 · 端口被占用")
265
+ return 1
266
+ _msgbox(f"面板启动失败:\n{type(exc).__name__}: {exc}", "灵枢面板 · 启动失败")
267
+ return int(getattr(exc, "code", 1) or 2)
268
+ # 正常路径:服务在后台线程里继续跑,主线程到此结束(daemon 线程随之结束前
269
+ # 需要保持进程活着——所以这里改为阻塞等待该线程)。
270
+ th.join()
271
+ return 0
272
+
273
+ # ---- 没有 tkinter:退回原来的同步启动(行为与旧版一致)----
170
274
  try:
171
275
  import panel_server
172
276
  panel_server.serve(port, open_browser=True)
@@ -65,6 +65,10 @@ _WRITE_ENDPOINTS = {
65
65
  "/api/extensions/ollama/enable", "/api/extensions/ollama/setup",
66
66
  # 数据目录迁移:写指针文件 + 复制数据(迁移目标在数据目录之外,单独放行只读门控)
67
67
  "/api/home/migrate",
68
+ # 面板快捷方式的全局热键:写桌面 .lnk 的 Hotkey 字段(在数据目录之外,单独放行)
69
+ "/api/panel-shortcut",
70
+ # 自定义快捷方式图标:生成 .ico + 写 .lnk 的 IconLocation(同样在数据目录之外)
71
+ "/api/panel-icon",
68
72
  }
69
73
 
70
74
  # 本机随机 token:页面加载时注入,之后每个 API 请求都要带上。
@@ -270,9 +274,13 @@ def _doctor_history(days: int = 30) -> list:
270
274
  date_str = datetime.fromtimestamp(ts, tz=timezone(timedelta(hours=8))).strftime("%m-%d")
271
275
  if date_str not in by_day:
272
276
  by_day[date_str] = {"date": date_str, "passes": 0, "warns": 0, "fails": 0}
273
- by_day[date_str]["passes"] += row.get("passes", 0)
274
- by_day[date_str]["warns"] += row.get("warns", 0)
275
- by_day[date_str]["fails"] += row.get("fails", 0)
277
+ # 字段名以 doctor-history 写入端为准(pass/warn/fail);旧记录用
278
+ # passes/warns/fails,两者都认,避免历史数据整段消失。
279
+ # 原来只读 passes/warns/fails,而 growth.record_doctor_run 写的是
280
+ # pass/warn/fail → 那一半记录恒贡献 0,折线图永远平。
281
+ by_day[date_str]["passes"] += row.get("pass", row.get("passes", 0)) or 0
282
+ by_day[date_str]["warns"] += row.get("warn", row.get("warns", 0)) or 0
283
+ by_day[date_str]["fails"] += row.get("fail", row.get("fails", 0)) or 0
276
284
  out = []
277
285
  for d in sorted(by_day):
278
286
  r = by_day[d]
@@ -282,46 +290,33 @@ def _doctor_history(days: int = 30) -> list:
282
290
 
283
291
 
284
292
  def _health_score() -> int:
285
- """灵枢健康度:0-100,按最近 7 天 doctor FAIL/WARN + failures.jsonl 条数加权扣分。
286
293
 
287
- 扣分规则:
288
- - 最近 7 天 doctor FAIL 总数 × 10(一次 FAIL 扣 10)
289
- - 最近 7 天 doctor WARN 总数 × 3(一次 WARN 扣 3)
290
- - 最近 7 天 failures.jsonl 条数 × 1(一条被吞异常扣 1)
291
- 从 100 往下扣,下限 0。无历史 → 100。
294
+ """灵枢健康度:0-100。**委托给 growth.health_score(),不在这里另算一套。**
295
+
296
+
297
+
298
+ 原来这里有自己的公式(100 - fails*10 - warns*3 - fbcnt),而 growth.health_score
299
+
300
+ 用的是 100 - fail*10 - warn*3 - failures_7d//5 → 面板 footer 与 stage/doctor 对
301
+
302
+ 同一份数据给出两个不同分数,被吞异常越多差得越大。同一指标只能有一个口径。
303
+
304
+
305
+
306
+ 历史记录字段名也一并由 growth 侧统一(pass/warn/fail),它自己会取最近一次体检。
307
+
292
308
  """
293
- import time as _t
294
- from datetime import datetime, timezone, timedelta
295
- cutoff = _t.time() - 7 * 86400
296
- fails = warns = 0
297
- dh = brain.HOME / "doctor-history.jsonl"
298
- if dh.exists():
299
- for line in dh.read_text(encoding="utf-8").splitlines():
300
- if not line.strip():
301
- continue
302
- try:
303
- row = json.loads(line)
304
- except json.JSONDecodeError:
305
- continue
306
- if row.get("ts", 0) < cutoff:
307
- continue
308
- fails += row.get("fails", 0)
309
- warns += row.get("warns", 0)
310
- # failures.jsonl 条数
311
- fb = brain.HOME / "failures.jsonl"
312
- fbcnt = 0
313
- if fb.exists():
314
- for line in fb.read_text(encoding="utf-8").splitlines():
315
- if not line.strip():
316
- continue
317
- try:
318
- row = json.loads(line)
319
- except json.JSONDecodeError:
320
- continue
321
- if row.get("ts", 0) >= cutoff:
322
- fbcnt += 1
323
- score = max(0, 100 - fails * 10 - warns * 3 - fbcnt)
324
- return score
309
+
310
+ try:
311
+
312
+ import growth as _growth
313
+
314
+ return int(_growth.health_score().get("score", 100))
315
+
316
+ except Exception:
317
+
318
+ return 100
319
+
325
320
 
326
321
 
327
322
  def _created_key(m: dict):
@@ -951,6 +946,43 @@ class Handler(BaseHTTPRequestHandler):
951
946
  # 数据目录信息:当前位置、是否指针生效、默认位置、当前库体积(面板设置卡片用)
952
947
  self._json(_home_info())
953
948
  return
949
+ if path == "/api/panel-icon":
950
+ # 图标状态:当前 IconLocation、是否自定义、预览(PNG data URL)
951
+ try:
952
+ import panel_icon, panel_shortcut
953
+ sc = panel_shortcut.read_shortcut()
954
+ cur = str(sc.get("icon") or "")
955
+ icon_path = cur.rsplit(",", 1)[0] if cur else ""
956
+ dflt = panel_icon.default_icon()
957
+ using_custom = False
958
+ if icon_path:
959
+ try:
960
+ using_custom = Path(icon_path).resolve() != dflt.resolve()
961
+ except OSError:
962
+ using_custom = icon_path != str(dflt)
963
+ self._json({
964
+ "ok": True,
965
+ "icon": cur,
966
+ "icon_path": icon_path,
967
+ "using_custom": using_custom,
968
+ "preview": panel_icon.preview_data_url(icon_path) if icon_path else "",
969
+ "default_preview": panel_icon.preview_data_url(dflt),
970
+ "pillow": panel_icon.pillow_available(),
971
+ "custom_path": str(panel_icon.custom_icon()),
972
+ "intact": sc.get("intact", False),
973
+ })
974
+ except Exception as exc: # noqa: BLE001
975
+ self._json({"ok": False,
976
+ "error": f"{type(exc).__name__}: {exc}"}, 500)
977
+ return
978
+ if path == "/api/panel-shortcut":
979
+ # 桌面快捷方式的全局热键(GET 读当前值;写入走 POST)
980
+ try:
981
+ import panel_shortcut
982
+ self._json(panel_shortcut.read_shortcut())
983
+ except Exception as exc: # noqa: BLE001
984
+ self._json({"ok": False, "error": f"{type(exc).__name__}: {exc}"})
985
+ return
954
986
  if path == "/api/assoc":
955
987
  mid = (parse_qs(url.query).get("id") or [""])[0]
956
988
  self._json({"id": mid, "neighbors": brain.assoc_of(mid)})
@@ -1179,6 +1211,96 @@ class Handler(BaseHTTPRequestHandler):
1179
1211
  # 定义在所有 _api_* 处理函数之后(模块级查表发生在运行时,不在导入期)。
1180
1212
 
1181
1213
 
1214
+ def _api_panel_icon(self, path, data):
1215
+ """自定义快捷方式图标:选图 → 转多尺寸 ico → 写 .lnk 的 IconLocation。"""
1216
+ try:
1217
+ import panel_icon, panel_shortcut
1218
+ except Exception as exc: # noqa: BLE001
1219
+ self._json({"ok": False, "error": f"加载图标模块失败:{exc}"}, 500)
1220
+ return
1221
+ action = str(data.get("action") or "").strip()
1222
+ try:
1223
+ if action == "pick":
1224
+ # 服务端弹原生文件框(浏览器拿不到真实路径)。可能等用户选很久,
1225
+ # 前端为此把超时放宽到 200 秒。
1226
+ chosen = panel_icon.pick_image_file()
1227
+ if not chosen:
1228
+ self._json({"ok": False, "cancelled": True,
1229
+ "error": "没有选择文件"})
1230
+ return
1231
+ ico = panel_icon.to_ico(chosen)
1232
+ res = panel_shortcut.set_icon_location(f"{ico},0")
1233
+ res.update({"ok": True, "source": chosen,
1234
+ "sizes": panel_icon.ico_info(ico).get("sizes", []),
1235
+ "preview": panel_icon.preview_data_url(ico)})
1236
+ brain.log_event("panel", f"快捷方式图标已更换:{chosen}")
1237
+ self._json(res)
1238
+ return
1239
+ if action == "set":
1240
+ src = str(data.get("path") or "").strip()
1241
+ if not src:
1242
+ self._json({"ok": False, "error": "缺少 path"}, 400)
1243
+ return
1244
+ ico = panel_icon.to_ico(src)
1245
+ res = panel_shortcut.set_icon_location(f"{ico},0")
1246
+ res.update({"ok": True, "source": src,
1247
+ "sizes": panel_icon.ico_info(ico).get("sizes", []),
1248
+ "preview": panel_icon.preview_data_url(ico)})
1249
+ brain.log_event("panel", f"快捷方式图标已更换:{src}")
1250
+ self._json(res)
1251
+ return
1252
+ if action == "reset":
1253
+ dflt = panel_icon.default_icon()
1254
+ if not dflt.is_file():
1255
+ self._json({"ok": False,
1256
+ "error": f"默认图标不存在:{dflt}"}, 404)
1257
+ return
1258
+ res = panel_shortcut.set_icon_location(f"{dflt},0")
1259
+ res.update({"ok": True, "preview": panel_icon.preview_data_url(dflt)})
1260
+ brain.log_event("panel", "快捷方式图标已恢复默认")
1261
+ self._json(res)
1262
+ return
1263
+ self._json({"ok": False, "error": "未知 action(pick / set / reset)"}, 400)
1264
+ except (panel_icon.IconError, panel_shortcut.ShortcutError) as exc:
1265
+ self._json({"ok": False, "error": str(exc)}, 400)
1266
+ except Exception as exc: # noqa: BLE001
1267
+ self._log_write_failure("设置快捷方式图标", exc, 500)
1268
+ self._json({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, 500)
1269
+
1270
+
1271
+ def _api_panel_shortcut(self, path, data):
1272
+ """设置桌面快捷方式的全局快捷键(写 .lnk 的 Hotkey 字段)。
1273
+
1274
+ 为什么放面板里而不是让用户自己去属性里改:Windows 快捷方式的"快捷键"输入框
1275
+ 不接受回车确认、也不校验组合是否合法,很容易设成抢普通打字的状态。
1276
+ 这里做格式校验 + 写后回读校验,只动 Hotkey,不碰 TargetPath/Arguments。
1277
+ """
1278
+ try:
1279
+ import panel_shortcut
1280
+ except Exception as exc: # noqa: BLE001
1281
+ self._json({"ok": False, "error": f"加载 panel_shortcut 失败:{exc}"}, 500)
1282
+ return
1283
+ hotkey = str(data.get("hotkey") or "")
1284
+ action = str(data.get("action") or "").strip()
1285
+ try:
1286
+ if action == "repair":
1287
+ # 把被写坏的 .lnk 按灵枢标准值重建(目标/参数/图标/窗口样式)
1288
+ res = panel_shortcut.repair_shortcut()
1289
+ brain.log_event("panel", f"修复桌面快捷方式:intact={res.get('intact')}")
1290
+ self._json(res)
1291
+ return
1292
+ res = panel_shortcut.set_hotkey(hotkey)
1293
+ except panel_shortcut.ShortcutError as exc:
1294
+ self._json({"ok": False, "error": str(exc)}, 400)
1295
+ return
1296
+ except Exception as exc: # noqa: BLE001
1297
+ self._log_write_failure("设置面板快捷键", exc, 500)
1298
+ self._json({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, 500)
1299
+ return
1300
+ brain.log_event("panel", f"面板快捷键 -> {res.get('applied') or '(清除)'}")
1301
+ self._json(res)
1302
+
1303
+
1182
1304
  def _api_home_migrate(self, path, data):
1183
1305
  # 数据目录迁移:整库复制到新位置 + 写指针文件(重启后生效)
1184
1306
  target = str(data.get("target") or "").strip()
@@ -2915,6 +3037,8 @@ def _api_ollama_install(self, path, data):
2915
3037
  _POST_ROUTES = {
2916
3038
  # 首页与记忆写入
2917
3039
  "/api/home/migrate": _api_home_migrate,
3040
+ "/api/panel-shortcut": _api_panel_shortcut,
3041
+ "/api/panel-icon": _api_panel_icon,
2918
3042
  "/api/remember": _api_remember,
2919
3043
  # 数据页
2920
3044
  "/api/data/backup": _api_data_backup,