lingshu-skill 5.29.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 +168 -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 +532 -19
  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 +134 -43
  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 +168 -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 +532 -19
  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 +22 -7
  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 +641 -61
  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 +225 -72
  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 +31 -11
  32. package/scripts/astrbot_plugin_lingshu/engine/scripts/safety_net.py +45 -9
  33. package/scripts/cli.py +47 -18
  34. package/scripts/core.py +32 -0
  35. package/scripts/dream.py +22 -7
  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 +641 -61
  40. package/scripts/panel_icon.py +220 -0
  41. package/scripts/panel_launcher.py +114 -10
  42. package/scripts/panel_server.py +225 -72
  43. package/scripts/panel_shortcut.py +330 -0
  44. package/scripts/panel_splash.py +181 -0
  45. package/scripts/persona.py +31 -11
  46. package/scripts/safety_net.py +45 -9
@@ -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)