lingshu-skill 0.0.0-stage → 3.82.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/CHANGELOG.md +2605 -0
- package/LICENSE +21 -0
- package/README.md +698 -3
- package/SKILL-lite.md +45 -0
- package/SKILL-tiny.md +37 -0
- package/SKILL.md +379 -0
- package/assets/panel.html +5616 -0
- package/cordis-plugin/lingshu-cron/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-cron/index.js +4 -0
- package/cordis-plugin/lingshu-cron/package.json +34 -0
- package/cordis-plugin/lingshu-cron/plugin.js +1040 -0
- package/cordis-plugin/lingshu-guard/plugin.js +473 -0
- package/cordis-plugin/lingshu-im/plugin.js +635 -0
- package/cordis-plugin/lingshu-startup/README.md +123 -0
- package/cordis-plugin/lingshu-startup/cordis.patch.yml +3 -0
- package/cordis-plugin/lingshu-startup/index.js +4 -0
- package/cordis-plugin/lingshu-startup/package.json +25 -0
- package/cordis-plugin/lingshu-startup/plugin.js +352 -0
- package/cordis.patch.yml +3 -0
- package/docs/commands.md +243 -0
- package/docs/mechanics.md +610 -0
- package/docs/models.md +52 -0
- package/docs/npm-/345/217/221/345/270/203/350/257/264/346/230/216.md +49 -0
- package/docs/panel-api.md +198 -0
- package/docs/recovery.md +90 -0
- package/docs/tgz-/345/256/211/350/243/205/350/257/264/346/230/216.md +53 -0
- package/docs//350/277/233/345/261/225/344/270/216/345/276/205/345/212/236.md +804 -0
- package/index.js +102 -0
- package/package.json +52 -6
- package/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/_smoke_v299.py +31 -0
- package/scripts/_sync_trae_cn.py +34 -0
- package/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +53 -0
- package/scripts/astrbot_plugin_lingshu/PATCH_NOTES.md +28 -0
- package/scripts/astrbot_plugin_lingshu/README.md +58 -0
- package/scripts/astrbot_plugin_lingshu/_conf_schema.json +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +2605 -0
- package/scripts/astrbot_plugin_lingshu/engine/README.md +698 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +379 -0
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +5616 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +243 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/models.md +52 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/panel-api.md +198 -0
- package/scripts/astrbot_plugin_lingshu/engine/docs/recovery.md +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/assembler.py +197 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/behavior_baseline.py +280 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bench.py +192 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_pressure_sync.py +55 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_tag.py +215 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/checkpoint.py +165 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +4867 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/context_ab.py +260 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2028 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +1137 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +1180 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/failures.py +107 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/fallback_embed.py +114 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +4745 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth_parts.py +263 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/insights.py +131 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +92 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_dialogue.py +242 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_embed.py +159 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_lesson.py +160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +210 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_topic.py +177 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +4417 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/npm_prepack.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +115 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_cloud.py +609 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +2703 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panels.py +591 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2309 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/retriever.py +195 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/safety.py +368 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +736 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_rag.py +228 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_summary.py +123 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +252 -0
- package/scripts/astrbot_plugin_lingshu/main.py +703 -0
- package/scripts/astrbot_plugin_lingshu/make_checksums.py +87 -0
- package/scripts/astrbot_plugin_lingshu/metadata.yaml +7 -0
- package/scripts/behavior_baseline.py +280 -0
- package/scripts/bench.py +192 -0
- package/scripts/brain.py +46 -0
- package/scripts/check_pressure_sync.py +55 -0
- package/scripts/check_tag.py +215 -0
- package/scripts/check_version.py +265 -0
- package/scripts/checkpoint.py +165 -0
- package/scripts/cli.py +4867 -0
- package/scripts/context_ab.py +260 -0
- package/scripts/core.py +2028 -0
- package/scripts/dream.py +1137 -0
- package/scripts/emotion.py +1180 -0
- package/scripts/failures.py +107 -0
- package/scripts/fallback_embed.py +114 -0
- package/scripts/growth.py +4745 -0
- package/scripts/growth_parts.py +263 -0
- package/scripts/hooks/pre-commit +18 -0
- package/scripts/hooks/pre-push +20 -0
- package/scripts/insights.py +131 -0
- package/scripts/make_dsh_tgz.py +92 -0
- package/scripts/make_manifest.py +254 -0
- package/scripts/make_plugin_zip.py +88 -0
- package/scripts/mem_dialogue.py +242 -0
- package/scripts/mem_embed.py +159 -0
- package/scripts/mem_lesson.py +160 -0
- package/scripts/mem_score.py +210 -0
- package/scripts/mem_topic.py +177 -0
- package/scripts/memory.py +4417 -0
- package/scripts/npm_prepack.py +31 -0
- package/scripts/panel_build.py +115 -0
- package/scripts/panel_cloud.py +609 -0
- package/scripts/panel_server.py +2703 -0
- package/scripts/panels.py +591 -0
- package/scripts/persona.py +2309 -0
- package/scripts/recreate_push.ps1 +117 -0
- package/scripts/retriever.py +195 -0
- package/scripts/run_tests.py +91 -0
- package/scripts/safety.py +368 -0
- package/scripts/session_import.py +736 -0
- package/scripts/session_rag.py +228 -0
- package/scripts/session_summary.py +123 -0
- package/scripts/summarizer.py +252 -0
- package/scripts/sync_engine.py +139 -0
- package/scripts/update_dsh_copy.ps1 +107 -0
- package/start-panel.bat +60 -0
|
@@ -0,0 +1,2703 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""灵枢 本地可视化面板(仅监听 127.0.0.1)"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import hmac
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import secrets
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
import urllib.request
|
|
18
|
+
import webbrowser
|
|
19
|
+
import zipfile
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from urllib.parse import parse_qs, urlparse
|
|
24
|
+
|
|
25
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
26
|
+
import brain # noqa: E402
|
|
27
|
+
import growth # noqa: E402
|
|
28
|
+
import panels # noqa: E402 自定义面板管理(目录扫描/激活/zip 安装/市场)
|
|
29
|
+
import panel_cloud # noqa: E402 云端面板市场(Gitee/GitHub 仓库托管)
|
|
30
|
+
|
|
31
|
+
ASSETS = Path(__file__).resolve().parent.parent / "assets"
|
|
32
|
+
|
|
33
|
+
# 只读门控名单:这些 POST 端点会写数据目录,数据目录不可写时统一 403
|
|
34
|
+
_WRITE_ENDPOINTS = {
|
|
35
|
+
"/api/remember", "/api/persona", "/api/persona/state",
|
|
36
|
+
"/api/persona/edit", "/api/persona/mind", "/api/persona/interview",
|
|
37
|
+
"/api/persona/self", "/api/persona/rollback", "/api/persona/changes-viewed",
|
|
38
|
+
"/api/persona/suggest",
|
|
39
|
+
"/api/persona/snapshots/rollback", # 自动快照按 version 回滚(persona_snapshots.jsonl)
|
|
40
|
+
"/api/memory", "/api/memory/review", "/api/knowledge", "/api/knowledge/review",
|
|
41
|
+
"/api/note", "/api/skill",
|
|
42
|
+
"/api/skill/self-review", "/api/skill/dsh-repair",
|
|
43
|
+
"/api/skill/dsh-force-update",
|
|
44
|
+
"/api/evolve", "/api/dream", "/api/dream/auto",
|
|
45
|
+
"/api/dream/apply", "/api/dream/draft", "/api/memory/bulk",
|
|
46
|
+
"/api/emotion", "/api/mode", "/api/link",
|
|
47
|
+
"/api/mind/weigh", "/api/diagnostics/fix-links", "/api/seed",
|
|
48
|
+
"/api/forget", "/api/daily", "/api/dream/instruction", "/api/logs",
|
|
49
|
+
"/api/memory/dust",
|
|
50
|
+
"/api/memory/purge",
|
|
51
|
+
"/api/memory/boost",
|
|
52
|
+
"/api/memory/rebuild-embeds",
|
|
53
|
+
# 自定义面板管理:activate/delete/install 等都写数据目录
|
|
54
|
+
"/api/panels", "/api/panels/scaffold",
|
|
55
|
+
# 拓展商店:导出内置宿主适配插件(写 extensions/installed/)
|
|
56
|
+
"/api/extensions",
|
|
57
|
+
# 云端面板市场:发布/下载/配置(token 写 config.json)
|
|
58
|
+
"/api/panels/cloud",
|
|
59
|
+
# Ollama 扩展:下载写 zip / 安装写程序目录与 config.json / setup 一键全流程
|
|
60
|
+
"/api/extensions/ollama/download", "/api/extensions/ollama/install",
|
|
61
|
+
"/api/extensions/ollama/enable", "/api/extensions/ollama/setup",
|
|
62
|
+
# 数据目录迁移:写指针文件 + 复制数据(迁移目标在数据目录之外,单独放行只读门控)
|
|
63
|
+
"/api/home/migrate",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
# 本机随机 token:页面加载时注入,之后每个 API 请求都要带上。
|
|
67
|
+
# 注意:token 会随首页响应下发,本机进程 GET / 即可提取,所以它防的不是本机进程,
|
|
68
|
+
# 而是浏览器上下文里的误用(恶意网页跨站调用本机端口);跨站防护主要靠 Host/Origin 校验。
|
|
69
|
+
TOKEN = os.environ.get("LINGSHU_PANEL_TOKEN") or secrets.token_urlsafe(24)
|
|
70
|
+
# 环境变量给了空串/空白时不能退化成空 token(否则任何请求都能过鉴权)——直接拒启
|
|
71
|
+
if not TOKEN.strip():
|
|
72
|
+
print("[面板] LINGSHU_PANEL_TOKEN 为空,拒绝启动(空 token 等于不设防)", file=sys.stderr)
|
|
73
|
+
raise SystemExit(2)
|
|
74
|
+
TOKEN = TOKEN.strip()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _int_param(url, key: str, default: int, low: int, high: int) -> int:
|
|
78
|
+
try:
|
|
79
|
+
val = int((parse_qs(url.query).get(key) or [default])[0])
|
|
80
|
+
except (TypeError, ValueError):
|
|
81
|
+
val = default
|
|
82
|
+
return max(low, min(high, val))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def memory_view(m: dict) -> dict:
|
|
86
|
+
out = dict(m)
|
|
87
|
+
out["retention"] = round(brain.retention(m), 3)
|
|
88
|
+
out["display"] = brain.display_text(m)
|
|
89
|
+
out["created_text"] = brain.fmt_time(m.get("created", 0))
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _repo_version() -> str:
|
|
94
|
+
"""本服务代码副本的版本号:优先仓库 manifest.json,退一步读 SKILL.md 的 version。
|
|
95
|
+
|
|
96
|
+
面板如今也随 AstrBot 插件发布(engine/scripts/panel_server.py + engine/assets/panel.html),
|
|
97
|
+
但插件里没有 manifest.json —— 只读 manifest 会让插件版面板的「代码版本」永远空着。
|
|
98
|
+
SKILL.md 一定随副本走,用它兜底;两处都没有才返回空串(页面照常显示,不报错)。
|
|
99
|
+
"""
|
|
100
|
+
root = ASSETS.parent
|
|
101
|
+
try:
|
|
102
|
+
mf = root / "manifest.json"
|
|
103
|
+
import json as _json
|
|
104
|
+
v = str(_json.loads(mf.read_text(encoding="utf-8-sig")).get("version", "") or "")
|
|
105
|
+
if v:
|
|
106
|
+
return v
|
|
107
|
+
except Exception:
|
|
108
|
+
pass
|
|
109
|
+
try:
|
|
110
|
+
import re as _re
|
|
111
|
+
m = _re.search(r"^version:\s*([0-9][0-9a-zA-Z.\-]*)",
|
|
112
|
+
(root / "SKILL.md").read_text(encoding="utf-8-sig"),
|
|
113
|
+
_re.MULTILINE)
|
|
114
|
+
return m.group(1) if m else ""
|
|
115
|
+
except Exception:
|
|
116
|
+
return ""
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def overview() -> dict:
|
|
120
|
+
# 逐条 try/except 降级:单条坏记忆/坏文件不能让整个 overview 500(面板全页挂掉)
|
|
121
|
+
def _safe(label: str, fn, default):
|
|
122
|
+
try:
|
|
123
|
+
return fn()
|
|
124
|
+
except Exception as exc:
|
|
125
|
+
brain.log_event("panel", f"overview {label} 降级:{exc}", level="warn")
|
|
126
|
+
return default
|
|
127
|
+
|
|
128
|
+
records = brain.load_all() + brain.load_archive()
|
|
129
|
+
ordered = sorted(records, key=lambda m: _created_key(m), reverse=True)
|
|
130
|
+
memories = []
|
|
131
|
+
for m in ordered[:80]:
|
|
132
|
+
try:
|
|
133
|
+
memories.append(memory_view(m))
|
|
134
|
+
except Exception as exc:
|
|
135
|
+
brain.log_event("panel", f"overview 跳过坏记忆 {m.get('id')}: {exc}", level="warn")
|
|
136
|
+
dreams = []
|
|
137
|
+
ddir = brain.HOME / "dreams"
|
|
138
|
+
if ddir.exists():
|
|
139
|
+
for f in sorted(ddir.glob("*.md"), reverse=True)[:12]:
|
|
140
|
+
try:
|
|
141
|
+
dreams.append({"name": f.name, "mtime": brain.fmt_time(int(f.stat().st_mtime)),
|
|
142
|
+
"content": f.read_text(encoding="utf-8")[:3000]})
|
|
143
|
+
except (OSError, ValueError):
|
|
144
|
+
continue
|
|
145
|
+
st = _safe("stats", brain.stats, {}) or {}
|
|
146
|
+
return {
|
|
147
|
+
"stats": st,
|
|
148
|
+
# 层分布统计条用:各层记忆数(含归档),纯计数不做降级分支
|
|
149
|
+
"layer_counts": {"hippo": st.get("hippo", 0), "cortex": st.get("cortex", 0),
|
|
150
|
+
"dust": st.get("dust", 0), "archive": st.get("archive", 0)},
|
|
151
|
+
"persona": _safe("persona", lambda: _persona_view(), {}),
|
|
152
|
+
"memories": memories,
|
|
153
|
+
"dreams": dreams,
|
|
154
|
+
"pending": _safe("pending", brain.load_dream_pending, []),
|
|
155
|
+
"mind": _safe("mind", brain.mind_state, {}),
|
|
156
|
+
"mood": _safe("mood", brain.mood_now, {}),
|
|
157
|
+
"emotion_arc": _safe("emotion_arc", lambda: brain.emotion_arc(7), []),
|
|
158
|
+
"desires": _safe("desires", brain.desire_state, {}),
|
|
159
|
+
"emotion_groups": _safe("emotion_groups", lambda: brain.EMOTION_GROUPS, {}),
|
|
160
|
+
"desire_defs": _safe("desire_defs", lambda: brain.DESIRES, {}),
|
|
161
|
+
"rationality": _safe("rationality", brain.rationality, {}),
|
|
162
|
+
"emotion_cfg": _safe("emotion_cfg", brain.emotion_cfg, {}),
|
|
163
|
+
"daily_state": _safe("daily_state", brain._daily_state, {}),
|
|
164
|
+
"last_self_review": load_config_last_review(),
|
|
165
|
+
"onboarding": _safe("onboarding", brain.onboarding_state, {}),
|
|
166
|
+
"readonly": bool(brain.READONLY),
|
|
167
|
+
"model_tier": brain.model_tier(),
|
|
168
|
+
"mode": _safe("mode", lambda: str(brain.load_config().get("mode", "auto") or "auto").lower(), "auto"),
|
|
169
|
+
"review_counts": _safe("review_counts", brain.review_counts, {}),
|
|
170
|
+
"persona_drift": _safe("persona_drift", lambda: brain.persona_drift(7), []),
|
|
171
|
+
"emotion_alerts": _safe("emotion_alerts", lambda: brain.emotion_checks_recent(10), []),
|
|
172
|
+
"dream_draft": _safe("dream_draft", brain.load_dream_draft, None),
|
|
173
|
+
"mode_detail": _safe("mode_detail", lambda: brain.resolve_mode_detail(""), {}),
|
|
174
|
+
"log_summary": _safe("log_summary", _log_summary, {"warn": 0, "error": 0}),
|
|
175
|
+
# #24 当前写入者:锁文件里记的 pid/主机,多机共享记忆库时能看见另一台
|
|
176
|
+
"writers": _safe("writers", brain.lock_writers, []),
|
|
177
|
+
# #19 梦抽检样本(最近一次合并前后对照,未复核时面板亮提示)
|
|
178
|
+
"dream_verify": _safe("dream_verify", brain.load_verify_sample, None),
|
|
179
|
+
# 水位卡数据:唯一数据源 memory._water_level(与 status --json / cron 同口径)
|
|
180
|
+
"water": _safe("water", brain._water_level, None),
|
|
181
|
+
# 来源自检(v3.01 C-②):报告本服务跑的是哪份代码。
|
|
182
|
+
# 用户常在系统里装了多份灵枢副本(老 clone / pip 装的旧版),
|
|
183
|
+
# 打开的面板可能不是仓库最新这份——前端据此亮"代码版本错位"提示。
|
|
184
|
+
"source": {
|
|
185
|
+
"script_dir": str(Path(__file__).resolve().parent),
|
|
186
|
+
"version": _repo_version(),
|
|
187
|
+
},
|
|
188
|
+
"home": str(brain.HOME),
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _persona_view() -> dict:
|
|
193
|
+
"""完整人格 + 回归后的 state(energy/closeness 读时向基线懒回归,不写盘)。"""
|
|
194
|
+
p = brain.load_persona()
|
|
195
|
+
st = p.get("state") or {}
|
|
196
|
+
if st:
|
|
197
|
+
p["state"] = brain._state_regress(st)
|
|
198
|
+
return p
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _created_key(m: dict):
|
|
202
|
+
"""排序键:created 可能是坏类型(手改/LLM 产出),坏值沉底不抛异常。"""
|
|
203
|
+
try:
|
|
204
|
+
return float(m.get("created", 0) or 0)
|
|
205
|
+
except (TypeError, ValueError):
|
|
206
|
+
return 0.0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _imp_key(m: dict) -> float:
|
|
210
|
+
"""importance 安全转 float:坏值(None/非数字字符串/list 等)沉底为 0。"""
|
|
211
|
+
try:
|
|
212
|
+
return float(m.get("importance") or 0)
|
|
213
|
+
except (TypeError, ValueError):
|
|
214
|
+
return 0.0
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _to_num(v, default=None):
|
|
218
|
+
"""把请求里的值安全转 float:失败返回 default(默认 None,调用方据此走 400)。"""
|
|
219
|
+
try:
|
|
220
|
+
return float(v)
|
|
221
|
+
except (TypeError, ValueError):
|
|
222
|
+
return default
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _to_int(v, default=None):
|
|
226
|
+
"""把请求里的值安全转 int:失败返回 default(默认 None,调用方据此走 400)。"""
|
|
227
|
+
try:
|
|
228
|
+
return int(v)
|
|
229
|
+
except (TypeError, ValueError):
|
|
230
|
+
return default
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _log_summary() -> dict:
|
|
234
|
+
"""最近 200 条里 error / warn(不含 error)各自多少条,一次读取避免重复解析。"""
|
|
235
|
+
recent = brain.read_logs(200, level=None)
|
|
236
|
+
errs = sum(1 for r in recent if r.get("level") == "error")
|
|
237
|
+
warns = sum(1 for r in recent if r.get("level") == "warn")
|
|
238
|
+
return {"warn": warns, "error": errs}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def load_config_last_review() -> float:
|
|
242
|
+
try:
|
|
243
|
+
return float(brain.load_config().get("last_self_review", 0) or 0)
|
|
244
|
+
except Exception:
|
|
245
|
+
return 0
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def filtered_memories(url) -> list:
|
|
249
|
+
"""组合筛选:层 + 关键词 + 标签 + 情绪 + 重要性区间 + 时间范围 + 排序。
|
|
250
|
+
|
|
251
|
+
面板的搜索框只做字面过滤;真正的模糊回忆走 /api/search(recall)。
|
|
252
|
+
"""
|
|
253
|
+
qs = parse_qs(url.query)
|
|
254
|
+
|
|
255
|
+
def one(key: str, default: str = "") -> str:
|
|
256
|
+
return (qs.get(key) or [default])[0]
|
|
257
|
+
|
|
258
|
+
layer = one("layer").strip()
|
|
259
|
+
tag = one("tag").strip().lower()
|
|
260
|
+
emotion = one("emotion").strip().lower()
|
|
261
|
+
text = one("q").strip().lower()
|
|
262
|
+
sort = one("sort", "created")
|
|
263
|
+
# pending=1:只看待审核的记忆(概览页「待审核」区块跳转过来就是带这个参数)
|
|
264
|
+
only_pending = one("pending", "") == "1"
|
|
265
|
+
limit = _int_param(url, "limit", 200, 1, 500)
|
|
266
|
+
|
|
267
|
+
def num(key: str, default: float) -> float:
|
|
268
|
+
try:
|
|
269
|
+
return float(one(key, str(default)) or default)
|
|
270
|
+
except (TypeError, ValueError):
|
|
271
|
+
return default
|
|
272
|
+
|
|
273
|
+
imp_min, imp_max = num("imp_min", 0.0), num("imp_max", 1.0)
|
|
274
|
+
# 兼容「1–10 分」输入:大于 1 视为十分制
|
|
275
|
+
if imp_min > 1:
|
|
276
|
+
imp_min /= 10
|
|
277
|
+
if imp_max > 1:
|
|
278
|
+
imp_max /= 10
|
|
279
|
+
|
|
280
|
+
days = _int_param(url, "days", 0, 0, 36500)
|
|
281
|
+
since = brain.now_ts() - days * 86400 if days else 0
|
|
282
|
+
|
|
283
|
+
rows = []
|
|
284
|
+
for m in brain.load_all() + brain.load_archive():
|
|
285
|
+
if layer and m.get("layer") != layer:
|
|
286
|
+
continue
|
|
287
|
+
if only_pending and m.get("review") != "pending":
|
|
288
|
+
continue
|
|
289
|
+
if tag and tag not in [str(t).lower() for t in (m.get("tags") or [])]:
|
|
290
|
+
continue
|
|
291
|
+
if emotion and emotion not in str(m.get("emotion") or "").lower():
|
|
292
|
+
continue
|
|
293
|
+
if text:
|
|
294
|
+
blob = " ".join([str(m.get("text", "")),
|
|
295
|
+
" ".join(str(t) for t in (m.get("tags") or [])),
|
|
296
|
+
" ".join(str(e) for e in (m.get("entities") or []))]).lower()
|
|
297
|
+
if text not in blob:
|
|
298
|
+
continue
|
|
299
|
+
imp = _imp_key(m)
|
|
300
|
+
if imp < imp_min or imp > imp_max:
|
|
301
|
+
continue
|
|
302
|
+
if since and _created_key(m) < since:
|
|
303
|
+
continue
|
|
304
|
+
rows.append(m)
|
|
305
|
+
|
|
306
|
+
if sort == "importance":
|
|
307
|
+
rows.sort(key=_imp_key, reverse=True)
|
|
308
|
+
elif sort == "retention":
|
|
309
|
+
rows.sort(key=lambda m: brain.retention(m), reverse=True)
|
|
310
|
+
else:
|
|
311
|
+
rows.sort(key=_created_key, reverse=True)
|
|
312
|
+
return [memory_view(m) for m in rows[:limit]]
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def workspace() -> dict:
|
|
316
|
+
"""工作台数据汇总。任何一块读取失败都降级成空值并记日志——
|
|
317
|
+
否则一个坏掉的 knowledge/notes 文件会让所有写接口在写成功之后报 400,
|
|
318
|
+
前端以为失败又重试,等于重复写入。"""
|
|
319
|
+
out: dict = {}
|
|
320
|
+
errors: list = []
|
|
321
|
+
|
|
322
|
+
def safe(label, fn, fallback):
|
|
323
|
+
try:
|
|
324
|
+
out[label] = fn()
|
|
325
|
+
except Exception as exc: # noqa: BLE001 —— 单块失败不影响其它块
|
|
326
|
+
out[label] = fallback
|
|
327
|
+
errors.append({"label": label, "type": type(exc).__name__})
|
|
328
|
+
brain.log_event("panel", f"workspace 读取 {label} 失败:{exc}", level="error")
|
|
329
|
+
|
|
330
|
+
safe("status", growth.growth_status, {})
|
|
331
|
+
safe("knowledge", lambda: growth.list_knowledge(limit=100), [])
|
|
332
|
+
safe("knowledge_stats", growth.knowledge_stats, {})
|
|
333
|
+
safe("tidy", growth.tidy_state, {})
|
|
334
|
+
safe("notes", lambda: growth.list_notes(limit=100), [])
|
|
335
|
+
safe("note_stats", growth.note_stats, {})
|
|
336
|
+
safe("skills", growth.list_skills, [])
|
|
337
|
+
safe("skill_roots", growth.skill_roots, [])
|
|
338
|
+
safe("skill_scan", growth.scan_skills, [])
|
|
339
|
+
safe("dsh_plugins", growth.list_dsh_plugins, [])
|
|
340
|
+
safe("evolution", lambda: growth.load_evolution(limit=30), [])
|
|
341
|
+
safe("onboarding", brain.onboarding_state, {})
|
|
342
|
+
safe("pending_knowledge", growth.knowledge_pending, [])
|
|
343
|
+
out["readonly"] = bool(brain.READONLY)
|
|
344
|
+
out["model_tier"] = brain.model_tier()
|
|
345
|
+
if errors:
|
|
346
|
+
# 只回标签和异常类型;完整的异常全文已在 log_event 里,别把本机路径/堆栈塞进 HTTP 响应
|
|
347
|
+
out["workspace_errors"] = errors
|
|
348
|
+
return out
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _bad_list(data: dict, *keys) -> str | None:
|
|
352
|
+
"""这些字段必须是数组(前端传字符串会被当成字符列表逐字拆开)。"""
|
|
353
|
+
for key in keys:
|
|
354
|
+
val = data.get(key)
|
|
355
|
+
if val is not None and not isinstance(val, list):
|
|
356
|
+
return f"{key} 必须是数组"
|
|
357
|
+
return None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
# 这些写端点里有只读 action:只读模式下按 action 放行(skill 的 list/check/show、
|
|
361
|
+
# emotion 的 now/check),别把纯查询按钮也一刀切 403
|
|
362
|
+
_READONLY_ACTIONS = {
|
|
363
|
+
"/api/skill": {"", "list", "check", "show", "roots", "scan", "use"},
|
|
364
|
+
"/api/emotion": {"", "now", "check"},
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _readonly_allowed(path: str, data: dict) -> bool:
|
|
369
|
+
if path == "/api/daily" and bool(data.get("dry_run")):
|
|
370
|
+
return True
|
|
371
|
+
if path == "/api/skill/self-review":
|
|
372
|
+
return True
|
|
373
|
+
allowed = _READONLY_ACTIONS.get(path)
|
|
374
|
+
if allowed is None:
|
|
375
|
+
return False
|
|
376
|
+
return str(data.get("action") or "") in allowed
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
# --------------------------------------------------------------- 数据目录(查看 / 迁移)
|
|
380
|
+
|
|
381
|
+
_PTR_FILE = Path.home() / ".brain-memory" / ".home"
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _dir_size(p: Path) -> int:
|
|
385
|
+
"""目录体积(字节):只统计普通文件,符号链接/不可读项跳过。"""
|
|
386
|
+
total = 0
|
|
387
|
+
try:
|
|
388
|
+
for f in p.rglob("*"):
|
|
389
|
+
try:
|
|
390
|
+
if f.is_file() and not f.is_symlink():
|
|
391
|
+
total += f.stat().st_size
|
|
392
|
+
except OSError:
|
|
393
|
+
pass
|
|
394
|
+
except OSError:
|
|
395
|
+
pass
|
|
396
|
+
return total
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _home_info() -> dict:
|
|
400
|
+
ptr_active = False
|
|
401
|
+
try:
|
|
402
|
+
ptr_active = _PTR_FILE.is_file() and bool(_PTR_FILE.read_text(encoding="utf-8").strip())
|
|
403
|
+
except OSError:
|
|
404
|
+
pass
|
|
405
|
+
env_set = bool(os.environ.get("BRAIN_MEMORY_HOME"))
|
|
406
|
+
return {
|
|
407
|
+
"home": str(brain.HOME),
|
|
408
|
+
"default_home": str(Path.home() / ".brain-memory"),
|
|
409
|
+
"via_env": env_set, # 环境变量指定(优先级最高,面板改不了它)
|
|
410
|
+
"via_pointer": ptr_active, # 指针文件指定(面板可改)
|
|
411
|
+
"size_bytes": _dir_size(brain.HOME),
|
|
412
|
+
"readonly": bool(brain.READONLY),
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _migrate_home(target_raw: str) -> dict:
|
|
417
|
+
"""把数据目录迁移到 target:整目录复制(旧目录保留不动)+ 写指针文件。
|
|
418
|
+
|
|
419
|
+
进程内的 brain.HOME 不切换——本进程的各模块已各自复制了 HOME,运行中切换
|
|
420
|
+
会造成新旧两处混写;正确姿势是迁完提示用户重启面板/会话。指针文件对
|
|
421
|
+
下一次进程生效,环境变量 BRAIN_MEMORY_HOME 仍优先。
|
|
422
|
+
"""
|
|
423
|
+
target = Path(target_raw).expanduser().resolve()
|
|
424
|
+
if not str(target.name).strip() or target_raw.strip() in ("", "/", "\\"):
|
|
425
|
+
raise ValueError("目标目录不能为空")
|
|
426
|
+
if target == brain.HOME.resolve():
|
|
427
|
+
raise ValueError("目标目录与当前数据目录相同")
|
|
428
|
+
if target.exists() and any(target.iterdir()):
|
|
429
|
+
raise ValueError("目标目录已存在且非空——请选一个空目录(或先手动清理)")
|
|
430
|
+
# 计划写指针的位置必须可写:指针文件永远在默认位置 ~/.brain-memory/ 下
|
|
431
|
+
_PTR_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
432
|
+
# 复制数据(目标已确保不存在或为空)
|
|
433
|
+
shutil.copytree(brain.HOME, target, symlinks=True, dirs_exist_ok=True)
|
|
434
|
+
_PTR_FILE.write_text(str(target) + "\n", encoding="utf-8")
|
|
435
|
+
return {
|
|
436
|
+
"ok": True,
|
|
437
|
+
"from": str(brain.HOME),
|
|
438
|
+
"to": str(target),
|
|
439
|
+
"pointer": str(_PTR_FILE),
|
|
440
|
+
"note": "迁移完成。重启面板/新会话后生效;旧目录原样保留,确认无误后可自行删除。",
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
class Handler(BaseHTTPRequestHandler):
|
|
446
|
+
server_version = "LingShuPanel/1.0"
|
|
447
|
+
|
|
448
|
+
def setup(self):
|
|
449
|
+
super().setup()
|
|
450
|
+
# 慢/坏客户端最多等 30 秒:没有这个,不读完请求体的连接能让线程永久挂住
|
|
451
|
+
# (类属性 timeout 在 Python 3.13 的 BaseHTTPRequestHandler 上不生效,必须在 socket 上设置)
|
|
452
|
+
self.connection.settimeout(30)
|
|
453
|
+
|
|
454
|
+
def log_message(self, fmt, *args):
|
|
455
|
+
pass
|
|
456
|
+
|
|
457
|
+
def handle_one_request(self):
|
|
458
|
+
# 客户端刷新/关页面会把连接掐断(WinError 10053/10054),响应写不出去是正常现象,
|
|
459
|
+
# 静默收尾即可——不让 ConnectionAbortedError 刷满控制台
|
|
460
|
+
try:
|
|
461
|
+
super().handle_one_request()
|
|
462
|
+
except (ConnectionAbortedError, ConnectionResetError, BrokenPipeError, TimeoutError):
|
|
463
|
+
self.close_connection = True
|
|
464
|
+
|
|
465
|
+
# -------------------------------------------------- helpers
|
|
466
|
+
def _send(self, code: int, body: bytes, ctype: str = "application/json; charset=utf-8"):
|
|
467
|
+
# 客户端刷新/关页面会立刻掐断连接,此时 send_response/write 都会抛
|
|
468
|
+
# ConnectionAbortedError(WinError 10053)/BrokenPipeError。这是常态,不是故障:
|
|
469
|
+
# 整个响应写出过程兜底吞掉并标记关闭连接,绝不打印 traceback(否则控制台被刷屏)。
|
|
470
|
+
try:
|
|
471
|
+
self.send_response(code)
|
|
472
|
+
self.send_header("Content-Type", ctype)
|
|
473
|
+
self.send_header("Content-Length", str(len(body)))
|
|
474
|
+
self.send_header("Cache-Control", "no-store")
|
|
475
|
+
self.send_header("X-Content-Type-Options", "nosniff") # 防止把响应当 HTML 解析
|
|
476
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
477
|
+
# 页面有内联 <script>/<style>,明确放开;其余资源只能同源,禁止外链脚本/图片域名
|
|
478
|
+
self.send_header("Content-Security-Policy",
|
|
479
|
+
"default-src 'self'; script-src 'unsafe-inline'; "
|
|
480
|
+
"style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "
|
|
481
|
+
"frame-ancestors 'none'") # 防恶意网页 iframe 嵌入面板(点击劫持)
|
|
482
|
+
self.end_headers()
|
|
483
|
+
if body:
|
|
484
|
+
self.wfile.write(body)
|
|
485
|
+
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, TimeoutError):
|
|
486
|
+
self.close_connection = True
|
|
487
|
+
except OSError as exc:
|
|
488
|
+
# 其余 OSError(如 10054 被对端重置)同样是客户端侧问题,静默收尾
|
|
489
|
+
self.close_connection = True
|
|
490
|
+
brain.log_event("panel", f"响应写出失败(客户端已断开):{exc}", level="info")
|
|
491
|
+
|
|
492
|
+
def _json(self, obj, code: int = 200):
|
|
493
|
+
self._send(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"))
|
|
494
|
+
|
|
495
|
+
def _log_write_failure(self, label: str, exc: Exception, code: int) -> None:
|
|
496
|
+
"""写接口的文件系统异常(占用/权限/冲突)落到运行日志,面板「日志」页可溯源。
|
|
497
|
+
|
|
498
|
+
str(exc) 含本机路径——日志里要全貌,HTTP 响应里只给通用文案。
|
|
499
|
+
日志本身绝不当崩溃源:写失败降级为 stderr,不影响错误响应的返回。
|
|
500
|
+
"""
|
|
501
|
+
try:
|
|
502
|
+
brain.log_event("panel", f"POST {getattr(self, 'path', '?')} {label}",
|
|
503
|
+
level="warn", detail=str(exc)[:300], code=code)
|
|
504
|
+
except Exception:
|
|
505
|
+
print(f"[面板] {label}: {exc}", file=sys.stderr)
|
|
506
|
+
|
|
507
|
+
def _body(self):
|
|
508
|
+
"""读并解析 JSON 请求体。
|
|
509
|
+
|
|
510
|
+
返回 dict = 正常;返回 None = 已经回了错误响应(调用方直接 return),
|
|
511
|
+
绝不再把"解析失败"当成空对象放过去——否则非法请求会被当成合法空操作。
|
|
512
|
+
"""
|
|
513
|
+
try:
|
|
514
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
515
|
+
except ValueError:
|
|
516
|
+
length = 0
|
|
517
|
+
if length <= 0: # 负的 Content-Length 视为空请求体
|
|
518
|
+
return {}
|
|
519
|
+
if length > 2_000_000:
|
|
520
|
+
self._json({"error": "请求体过大"}, 413)
|
|
521
|
+
self.close_connection = True
|
|
522
|
+
return None
|
|
523
|
+
try:
|
|
524
|
+
raw = self.rfile.read(length).decode("utf-8-sig")
|
|
525
|
+
except Exception:
|
|
526
|
+
self._json({"error": "无法读取请求体"}, 400)
|
|
527
|
+
return None
|
|
528
|
+
if not raw.strip():
|
|
529
|
+
return {}
|
|
530
|
+
try:
|
|
531
|
+
obj = json.loads(raw)
|
|
532
|
+
except Exception:
|
|
533
|
+
self._json({"error": "请求体不是合法 JSON"}, 400)
|
|
534
|
+
return None
|
|
535
|
+
if not isinstance(obj, dict):
|
|
536
|
+
self._json({"error": "请求体必须是 JSON 对象"}, 400)
|
|
537
|
+
return None
|
|
538
|
+
return obj
|
|
539
|
+
|
|
540
|
+
def _origin_ok(self) -> bool:
|
|
541
|
+
"""只接受本机页面的请求,挡住跨站表单与 DNS rebinding。
|
|
542
|
+
|
|
543
|
+
Host 必须是 127.0.0.1/localhost——否则恶意域名解析到 127.0.0.1 后,
|
|
544
|
+
浏览器会把它当成同源,从而读走全部记忆。
|
|
545
|
+
"""
|
|
546
|
+
host = (self.headers.get("Host") or "").strip().lower()
|
|
547
|
+
if host.startswith("["): # IPv6:[::1]:8765
|
|
548
|
+
host = host.split("]")[0] + "]"
|
|
549
|
+
else:
|
|
550
|
+
host = host.split(":")[0]
|
|
551
|
+
if host not in ("127.0.0.1", "localhost", "[::1]", "::1"):
|
|
552
|
+
return False
|
|
553
|
+
origin = self.headers.get("Origin")
|
|
554
|
+
if not origin:
|
|
555
|
+
return True
|
|
556
|
+
return origin in (f"http://{self.headers.get('Host', '')}",
|
|
557
|
+
f"http://127.0.0.1:{self.server.server_port}",
|
|
558
|
+
f"http://localhost:{self.server.server_port}")
|
|
559
|
+
|
|
560
|
+
def _token_ok(self) -> bool:
|
|
561
|
+
"""所有 API 请求必须带正确 token(页面注入,非浏览器可借机偷读)。
|
|
562
|
+
|
|
563
|
+
正式 token(TOKEN)只随内置首页/默认面板下发;第三方 iframe 面板用
|
|
564
|
+
「当日滚动派生 token」:由主 TOKEN 对日期做 HMAC 派生,逐日失效,
|
|
565
|
+
泄露面被限制在当天且不进浏览器历史的是完整长期凭据。
|
|
566
|
+
"""
|
|
567
|
+
got = ""
|
|
568
|
+
auth = self.headers.get("Authorization") or ""
|
|
569
|
+
if auth.lower().startswith("bearer "):
|
|
570
|
+
got = auth[7:].strip()
|
|
571
|
+
if hmac.compare_digest(got.encode("utf-8"), TOKEN.encode("utf-8")):
|
|
572
|
+
return True
|
|
573
|
+
# 派生 iframe token:SHA256(TOKEN || YYYY-MM-DD) 前 32 位,逐日轮换
|
|
574
|
+
day = time.strftime("%Y-%m-%d", time.localtime())
|
|
575
|
+
digest = hashlib.sha256((TOKEN + "|" + day).encode("utf-8")).hexdigest()[:32]
|
|
576
|
+
# encode 成 bytes 再比:非 ASCII header(恶意/异常客户端)直接传 str 会让
|
|
577
|
+
# compare_digest 抛 TypeError,且 do_POST 的鉴权调用不在 try 里,会断连
|
|
578
|
+
return hmac.compare_digest(got.encode("utf-8"), digest.encode("utf-8"))
|
|
579
|
+
|
|
580
|
+
# -------------------------------------------------- routes
|
|
581
|
+
def do_GET(self):
|
|
582
|
+
# 与 do_POST 对齐的兜底:任意一条数据损坏都不能让整个接口断连无响应
|
|
583
|
+
try:
|
|
584
|
+
self._route_get()
|
|
585
|
+
except FileExistsError as exc:
|
|
586
|
+
print(f"[面板] 文件已存在: {exc}", file=sys.stderr)
|
|
587
|
+
self._json({"error": "同名文件已存在"}, 409)
|
|
588
|
+
except PermissionError as exc:
|
|
589
|
+
print(f"[面板] 文件被占用: {exc}", file=sys.stderr)
|
|
590
|
+
self._json({"error": "文件被占用或没有写入权限"}, 400)
|
|
591
|
+
except (ValueError, KeyError) as exc:
|
|
592
|
+
self._json({"error": str(exc)}, 400)
|
|
593
|
+
except Exception:
|
|
594
|
+
import traceback
|
|
595
|
+
# 不再 print_exc 刷控制台:完整堆栈进运行日志(面板「日志」页可看)
|
|
596
|
+
brain.log_event("panel", "GET 接口内部错误", level="error",
|
|
597
|
+
trace=traceback.format_exc()[-800:])
|
|
598
|
+
self._json({"error": "面板内部错误,详情见运行日志"}, 500)
|
|
599
|
+
|
|
600
|
+
def _route_get(self):
|
|
601
|
+
# Host/Origin 校验必须前置:任何 GET 响应都可能含 TOKEN(首页/面板 HTML),
|
|
602
|
+
# 校验放后面就等于先让恶意站点的 DNS rebinding 请求拿到 token 再 403
|
|
603
|
+
if not self._origin_ok():
|
|
604
|
+
self._json({"error": "forbidden"}, 403)
|
|
605
|
+
return
|
|
606
|
+
url = urlparse(self.path)
|
|
607
|
+
path = url.path
|
|
608
|
+
if path in ("/", "/index.html"):
|
|
609
|
+
# 始终下发内置默认面板作为「外壳」:外壳启动时拉 /api/panels,若激活了
|
|
610
|
+
# 自定义面板就用 iframe 热加载它(as_page=1 注入 token)——这样
|
|
611
|
+
# 「面板管理」按钮永远可用、iframe 崩了只崩自身、出错自动回退默认。
|
|
612
|
+
html = ASSETS / "panel.html"
|
|
613
|
+
if not html.exists():
|
|
614
|
+
self._send(404, b"panel.html missing", "text/plain; charset=utf-8")
|
|
615
|
+
return
|
|
616
|
+
content = html.read_bytes().decode("utf-8")
|
|
617
|
+
active = panels._active_name()
|
|
618
|
+
# 注入激活面板名(default/None 都算默认):外壳据此决定是否挂 iframe
|
|
619
|
+
active_js = json.dumps({"panel": active or "default"}, ensure_ascii=False)
|
|
620
|
+
content = content.replace("</head>",
|
|
621
|
+
f'<script>window.__LINGSHU_ACTIVE__ = {active_js};</script>\n</head>', 1)
|
|
622
|
+
# 注入随机 token:页面里每个 API 请求都会带上,杜绝无 Origin 直连偷读
|
|
623
|
+
content = content.replace("/*__PANEL_TOKEN__*/", TOKEN)
|
|
624
|
+
self._send(200, content.encode("utf-8"), "text/html; charset=utf-8")
|
|
625
|
+
return
|
|
626
|
+
if path == "/favicon.ico":
|
|
627
|
+
# 浏览器自动请求,返回透明 1x1 PNG,避免控制台刷 404
|
|
628
|
+
self._send(200, bytes.fromhex(
|
|
629
|
+
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
|
|
630
|
+
"0000000d4944415478da63fcffff3f030005fe02fea72d1e480000000049454e44ae426082"),
|
|
631
|
+
"image/png")
|
|
632
|
+
return
|
|
633
|
+
# 读取接口同样要校验来源 + token:记忆是隐私数据,不能被任意页面/进程读走
|
|
634
|
+
if path.startswith("/api/") and (not self._origin_ok() or not self._token_ok()):
|
|
635
|
+
self._json({"error": "forbidden"}, 403)
|
|
636
|
+
return
|
|
637
|
+
if path == "/api/overview":
|
|
638
|
+
self._json(overview())
|
|
639
|
+
return
|
|
640
|
+
if path == "/api/insights":
|
|
641
|
+
# v3.36 运行洞察:一次聚合上下文账单 / 原文库 / 收尾 / 鉴权 / 嵌入。
|
|
642
|
+
# light=1 时跳过最重的上下文账单(面板定时刷新用)。
|
|
643
|
+
try:
|
|
644
|
+
import insights
|
|
645
|
+
qs = parse_qs(url.query)
|
|
646
|
+
light = (qs.get("light") or ["0"])[0] in ("1", "true", "yes")
|
|
647
|
+
self._json(insights.build(light=light))
|
|
648
|
+
except Exception as exc: # noqa: BLE001
|
|
649
|
+
self._json({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, 500)
|
|
650
|
+
return
|
|
651
|
+
if path == "/api/self-update":
|
|
652
|
+
# auto=1:面板打开时的自动检查,只读缓存、绝不联网(毫秒返回,不会卡页面)
|
|
653
|
+
# refresh=1:用户手动点「检查更新」,真拉远程源并刷新缓存
|
|
654
|
+
qs = parse_qs(url.query)
|
|
655
|
+
auto = (qs.get("auto") or ["0"])[0] in ("1", "true", "yes")
|
|
656
|
+
refresh = (qs.get("refresh") or ["0"])[0] in ("1", "true", "yes")
|
|
657
|
+
res = growth.update_check("lingshu", force_pull=refresh, auto=auto)
|
|
658
|
+
# 透出源类型(dev/remote/installed/none)与源目标路径,供前端确认框展示。
|
|
659
|
+
# 注意:这里不能再 force_pull=refresh——update_check 刚拉过一遍远程并写了
|
|
660
|
+
# 缓存,再来一遍等于把整条 Gitee/GitHub 拉取链路跑两次,手动检查必然超时。
|
|
661
|
+
if isinstance(res, dict) and res.get("cached") is not False:
|
|
662
|
+
try:
|
|
663
|
+
src, kind = growth.resolve_source("lingshu", force_pull=False)
|
|
664
|
+
res["source_kind"] = kind
|
|
665
|
+
res["target_path"] = str(src)
|
|
666
|
+
except Exception:
|
|
667
|
+
res.setdefault("source_kind", res.get("source", "none"))
|
|
668
|
+
self._json(res)
|
|
669
|
+
return
|
|
670
|
+
if path == "/api/workspace":
|
|
671
|
+
self._json(workspace())
|
|
672
|
+
return
|
|
673
|
+
if path == "/api/growth/review":
|
|
674
|
+
days = _int_param(url, "days", 7, 1, 365)
|
|
675
|
+
self._json(growth.growth_review(days))
|
|
676
|
+
return
|
|
677
|
+
if path == "/api/workspace/search":
|
|
678
|
+
q = (parse_qs(url.query).get("q") or [""])[0]
|
|
679
|
+
scope = (parse_qs(url.query).get("scope") or ["knowledge"])[0]
|
|
680
|
+
if scope == "notes":
|
|
681
|
+
rows = [{"note": r, "score": s} for r, s in growth.search_notes(q, 30)]
|
|
682
|
+
else:
|
|
683
|
+
rows = [{"knowledge": r, "score": s} for r, s in growth.search_knowledge(q, 30)]
|
|
684
|
+
self._json(rows)
|
|
685
|
+
return
|
|
686
|
+
if path == "/api/search":
|
|
687
|
+
q = (parse_qs(url.query).get("q") or [""])[0]
|
|
688
|
+
k = _int_param(url, "k", 12, 1, 100)
|
|
689
|
+
mode = (parse_qs(url.query).get("mode") or ["auto"])[0]
|
|
690
|
+
if mode not in ("fast", "deep", "auto"):
|
|
691
|
+
mode = "auto"
|
|
692
|
+
results = brain.recall(q, k=k, strengthen=False, mode=mode)
|
|
693
|
+
self._json([{"memory": memory_view(m), "score": s, "parts": p} for m, s, p in results])
|
|
694
|
+
return
|
|
695
|
+
if path == "/api/memories":
|
|
696
|
+
self._json(filtered_memories(url))
|
|
697
|
+
return
|
|
698
|
+
if path == "/api/inject-preview":
|
|
699
|
+
q = (parse_qs(url.query).get("q") or [""])[0]
|
|
700
|
+
try:
|
|
701
|
+
packet = brain.build_injection(q)
|
|
702
|
+
except Exception as exc:
|
|
703
|
+
self._json({"error": f"生成注入包失败:{exc}"}, 500)
|
|
704
|
+
return
|
|
705
|
+
self._json({"packet": packet})
|
|
706
|
+
return
|
|
707
|
+
if path == "/api/conflicts":
|
|
708
|
+
limit = _int_param(url, "limit", 50, 1, 200)
|
|
709
|
+
self._json({"conflicts": brain.detect_conflicts(limit)})
|
|
710
|
+
return
|
|
711
|
+
if path == "/api/graph":
|
|
712
|
+
limit = _int_param(url, "limit", 300, 10, 800)
|
|
713
|
+
self._json(brain.assoc_graph(limit))
|
|
714
|
+
return
|
|
715
|
+
if path == "/api/diagnostics":
|
|
716
|
+
# 自诊断:死链 / 冲突未裁决 / 数据膨胀 / 淡忘可逆状态 / 来源归属完整率
|
|
717
|
+
self._json(brain.diagnose())
|
|
718
|
+
return
|
|
719
|
+
if path == "/api/home":
|
|
720
|
+
# 数据目录信息:当前位置、是否指针生效、默认位置、当前库体积(面板设置卡片用)
|
|
721
|
+
self._json(_home_info())
|
|
722
|
+
return
|
|
723
|
+
if path == "/api/assoc":
|
|
724
|
+
mid = (parse_qs(url.query).get("id") or [""])[0]
|
|
725
|
+
self._json({"id": mid, "neighbors": brain.assoc_of(mid)})
|
|
726
|
+
return
|
|
727
|
+
if path == "/api/mode/explain":
|
|
728
|
+
q = (parse_qs(url.query).get("q") or [""])[0]
|
|
729
|
+
self._json(brain.resolve_mode_detail(q))
|
|
730
|
+
return
|
|
731
|
+
if path == "/api/entity":
|
|
732
|
+
# 实体档案卡:name 必须非空且别太长(塞进 URL/存储都安全),limit 用现有风格夹取
|
|
733
|
+
name = (parse_qs(url.query).get("name") or [""])[0].strip()
|
|
734
|
+
if not name or len(name) > 64:
|
|
735
|
+
self._json({"error": "参数 name 必须为 1~64 字符"}, 400)
|
|
736
|
+
return
|
|
737
|
+
limit = _int_param(url, "limit", 20, 1, 100)
|
|
738
|
+
self._json(brain.entity_profile(name, limit))
|
|
739
|
+
return
|
|
740
|
+
if path == "/api/persona/diff":
|
|
741
|
+
self._json(brain.persona_diff())
|
|
742
|
+
return
|
|
743
|
+
if path == "/api/persona/snapshots":
|
|
744
|
+
limit = _int_param(url, "limit", 50, 1, 200)
|
|
745
|
+
self._json(brain.list_persona_snapshots(limit=limit))
|
|
746
|
+
return
|
|
747
|
+
if path == "/api/persona/changes":
|
|
748
|
+
# 人格变更时间线(v3.01「先生效后告知」流):未读 AI 改动 + 全量 history + 漂移度
|
|
749
|
+
days = _int_param(url, "days", 7, 1, 90)
|
|
750
|
+
self._json({
|
|
751
|
+
"unviewed": brain.ai_persona_changes(days),
|
|
752
|
+
"history": brain.persona_history(50),
|
|
753
|
+
"drift": brain.persona_drift(days),
|
|
754
|
+
})
|
|
755
|
+
return
|
|
756
|
+
if path == "/api/persona/suggest":
|
|
757
|
+
# 画像候选(persona_pending.jsonl):待确认特征 + 证据链
|
|
758
|
+
self._json({"suggestions": brain.persona_suggest_list()})
|
|
759
|
+
return
|
|
760
|
+
if path == "/api/growth/timeline":
|
|
761
|
+
# 五-G:成长时间线——性格跳变 / 成形时刻 / 被纠正节点(纯展示,零风险)
|
|
762
|
+
days = _int_param(url, "days", 365, 1, 3650)
|
|
763
|
+
limit = _int_param(url, "limit", 60, 1, 300)
|
|
764
|
+
self._json(brain.growth_timeline(days, limit))
|
|
765
|
+
return
|
|
766
|
+
if path == "/api/logs":
|
|
767
|
+
limit = _int_param(url, "limit", 200, 1, 2000)
|
|
768
|
+
level = (parse_qs(url.query).get("level") or [""])[0] or None
|
|
769
|
+
if level == "all":
|
|
770
|
+
level = None
|
|
771
|
+
self._json({"logs": brain.read_logs(limit, level=level)})
|
|
772
|
+
return
|
|
773
|
+
if path == "/api/panels":
|
|
774
|
+
self._json(panels.list_panels())
|
|
775
|
+
return
|
|
776
|
+
if path == "/api/extensions":
|
|
777
|
+
# 拓展商店清单:内置宿主适配插件 + 自定义已装拓展
|
|
778
|
+
self._json(panels.list_extensions())
|
|
779
|
+
return
|
|
780
|
+
if path == "/api/extensions/ollama/status":
|
|
781
|
+
# Ollama 扩展状态:安装/服务/模型/配置 + 下载安装进度(轮询用)
|
|
782
|
+
# 顺带触发一次自动探测接管(后台线程、幂等、失败静默):
|
|
783
|
+
# 本机已有 Ollama 在跑 → 无感接入 + 自动拉模型,用户无感知
|
|
784
|
+
_ollama_auto_probe_async()
|
|
785
|
+
self._json(ollama_status())
|
|
786
|
+
return
|
|
787
|
+
if path == "/api/panels/market":
|
|
788
|
+
# 本机市场目录扫描(无云端):列出市场面板 + zip 安装包
|
|
789
|
+
self._json(panels.list_market())
|
|
790
|
+
return
|
|
791
|
+
if path == "/api/panels/cloud":
|
|
792
|
+
# 云端市场目录清单:优先 Gitee,失败试 GitHub,再失败降级提示(不挂页面)
|
|
793
|
+
force = (parse_qs(url.query).get("force") or ["0"])[0] == "1"
|
|
794
|
+
try:
|
|
795
|
+
self._json(panel_cloud.cloud_list(force=force))
|
|
796
|
+
except Exception as exc: # noqa: BLE001
|
|
797
|
+
self._json({"panels": [], "errors": [str(exc)], "offline": True,
|
|
798
|
+
"status": panel_cloud.status()}, 200)
|
|
799
|
+
return
|
|
800
|
+
if path == "/api/panels/cloud/shot":
|
|
801
|
+
# 云端面板截图代理:前端 <img> 走本机端点,避免跨域;白名单+大小校验在模块里
|
|
802
|
+
qs = parse_qs(url.query)
|
|
803
|
+
sname = (qs.get("name") or [""])[0]
|
|
804
|
+
sext = (qs.get("ext") or [".png"])[0].lower()
|
|
805
|
+
try:
|
|
806
|
+
body, _ = (lambda b: (b, ""))(panel_cloud.cloud_shot(sname, sext))
|
|
807
|
+
except FileNotFoundError as exc:
|
|
808
|
+
self._json({"error": str(exc)}, 404)
|
|
809
|
+
return
|
|
810
|
+
except ValueError as exc:
|
|
811
|
+
self._json({"error": str(exc)}, 400)
|
|
812
|
+
return
|
|
813
|
+
except Exception as exc: # noqa: BLE001
|
|
814
|
+
self._json({"error": f"截图拉取失败:{exc}"}, 502)
|
|
815
|
+
return
|
|
816
|
+
ctype = {".png": "image/png", ".jpg": "image/jpeg",
|
|
817
|
+
".jpeg": "image/jpeg", ".webp": "image/webp"}.get(sext, "image/png")
|
|
818
|
+
self._send(200, body, ctype + "; cache-control=max-age=3600")
|
|
819
|
+
return
|
|
820
|
+
if path == "/api/panels/file":
|
|
821
|
+
# 面板静态文件:面板名过正则、相对路径规范化限死在面板目录内、扩展名白名单。
|
|
822
|
+
# as_page=1 时对 HTML 注入 token(替换 /*__PANEL_TOKEN__*/),iframe 里的
|
|
823
|
+
# 自定义面板页面靠它自取 token 调统一 API——与首页下发逻辑同源同法。
|
|
824
|
+
qs = parse_qs(url.query)
|
|
825
|
+
pname = (qs.get("panel") or [""])[0]
|
|
826
|
+
rel = (qs.get("path") or qs.get("p") or [""])[0]
|
|
827
|
+
as_page = (qs.get("as_page") or ["0"])[0] in ("1", "true", "yes")
|
|
828
|
+
try:
|
|
829
|
+
body, ctype = panels.read_panel_file(pname, rel)
|
|
830
|
+
except PermissionError as exc:
|
|
831
|
+
self._json({"error": str(exc)}, 403)
|
|
832
|
+
return
|
|
833
|
+
except FileNotFoundError as exc:
|
|
834
|
+
self._json({"error": str(exc)}, 404)
|
|
835
|
+
return
|
|
836
|
+
except ValueError as exc:
|
|
837
|
+
self._json({"error": str(exc)}, 400)
|
|
838
|
+
return
|
|
839
|
+
if as_page and "html" in ctype:
|
|
840
|
+
try:
|
|
841
|
+
text = body.decode("utf-8")
|
|
842
|
+
# 安全:只有内置默认面板才注入主 TOKEN。第三方(非内置)面板
|
|
843
|
+
# 一旦不可信,主 TOKEN 注入即可带出全部记忆——第三方面板想调
|
|
844
|
+
# API 可通过 Bearer header 携带「当日派生 token」(见 _token_ok,
|
|
845
|
+
# 逐日轮换、非 query 传参),服务端不主动下发长期主 TOKEN。
|
|
846
|
+
if pname == panels.DEFAULT_NAME:
|
|
847
|
+
text = text.replace("/*__PANEL_TOKEN__*/", TOKEN)
|
|
848
|
+
if "PANEL_TOKEN" not in text:
|
|
849
|
+
# 面板作者没写占位符时补进 <head>:保证 api() helper 能拿到 token
|
|
850
|
+
text = text.replace("<head>", '<head>\n<script>const PANEL_TOKEN="' + TOKEN + '";</script>', 1)
|
|
851
|
+
body = text.encode("utf-8")
|
|
852
|
+
except UnicodeDecodeError:
|
|
853
|
+
pass # 非 UTF-8 HTML:原样下发,面板作者自己修
|
|
854
|
+
self._send(200, body, ctype)
|
|
855
|
+
return
|
|
856
|
+
self._json({"error": "not found"}, 404)
|
|
857
|
+
|
|
858
|
+
def do_POST(self):
|
|
859
|
+
if not self._origin_ok() or not self._token_ok():
|
|
860
|
+
# 拒绝前没读请求体:keep-alive 连接里残留的 body 会被下一轮当成请求行解析,
|
|
861
|
+
# 造成连接错乱——断开连接最干净
|
|
862
|
+
self.close_connection = True
|
|
863
|
+
self._json({"error": "forbidden"}, 403)
|
|
864
|
+
return
|
|
865
|
+
path = urlparse(self.path).path
|
|
866
|
+
data = self._body()
|
|
867
|
+
if data is None:
|
|
868
|
+
return
|
|
869
|
+
# 只读门控:写接口在数据目录不可写时直接 403(展示/预览接口放行)
|
|
870
|
+
# 自愈合(v3.76 收紧):面板是长驻进程,启动那一下探测失败可能只是杀软/
|
|
871
|
+
# 索引器短暂占用——**自动降级**的只读可在写请求到来时复探自愈,不用重启。
|
|
872
|
+
# 但**用户显式强制只读**(--ro / BRAIN_MEMORY_READONLY=1,READONLY_FORCED=True)
|
|
873
|
+
# 绝不能被自愈:那等于静默违反用户的只读承诺(原来这里不区分,强制只读也
|
|
874
|
+
# 被摘掉)。强制只读时连复探都不做——探针本身会往 HOME 写文件。
|
|
875
|
+
if (brain.READONLY and not brain.READONLY_FORCED
|
|
876
|
+
and path in _WRITE_ENDPOINTS and not _readonly_allowed(path, data)):
|
|
877
|
+
try:
|
|
878
|
+
if brain._home_writable(max_attempts=3):
|
|
879
|
+
brain.READONLY = False
|
|
880
|
+
brain._sync_state()
|
|
881
|
+
except Exception:
|
|
882
|
+
pass
|
|
883
|
+
if brain.READONLY and path in _WRITE_ENDPOINTS and not _readonly_allowed(path, data):
|
|
884
|
+
self.close_connection = True
|
|
885
|
+
self._json({"error": "readonly", "message": "数据目录当前只读,写操作已被禁用。"}, 403)
|
|
886
|
+
return
|
|
887
|
+
try:
|
|
888
|
+
# 分发表:路由 -> 处理方法(分支体已拆到 _api_* 方法)
|
|
889
|
+
handler = _POST_ROUTES.get(path)
|
|
890
|
+
if handler is not None:
|
|
891
|
+
handler(self, path, data)
|
|
892
|
+
else:
|
|
893
|
+
self._json({"error": "not found"}, 404)
|
|
894
|
+
except FileExistsError as exc:
|
|
895
|
+
# 已有同名技能/扩展/笔记:409 冲突比 500 内部错误更符合事实,前端也能直接提示
|
|
896
|
+
# 系统异常的 str() 含本机路径,只回通用文案,细节进运行日志(面板「日志」页可溯源)
|
|
897
|
+
self._log_write_failure("文件已存在", exc, 409)
|
|
898
|
+
self._json({"error": "同名文件已存在"}, 409)
|
|
899
|
+
except PermissionError as exc:
|
|
900
|
+
# 文件被占用 / 无写权限:str() 也含路径,运行日志留全貌,响应只给通用文案
|
|
901
|
+
# —— 不落日志的话,用户只看到一条 400,谁占了文件、占的是哪个文件完全无从排查
|
|
902
|
+
self._log_write_failure("文件被占用或无写权限", exc, 400)
|
|
903
|
+
# WinError 5 的 str() 通常带"拒绝访问"——那是权限问题,重试没用;
|
|
904
|
+
# 其余多为短暂占用(读句柄/杀软扫描),提示稍后重试
|
|
905
|
+
msg = str(exc)
|
|
906
|
+
self._json({"error": "没有写入权限,请检查记忆库文件夹权限"
|
|
907
|
+
if ("拒绝访问" in msg or "Access is denied" in msg or "denied" in msg.lower())
|
|
908
|
+
else "文件被占用,请稍后重试"}, 400)
|
|
909
|
+
except (ValueError, KeyError) as exc:
|
|
910
|
+
# 业务异常 / 参数错:消息本身就是给用户看的,直接回显。
|
|
911
|
+
# KeyError 的 str() 自带英文引号("'没有这个技能'"),剥掉再给前端
|
|
912
|
+
self._json({"error": str(exc).strip("'\"")}, 400)
|
|
913
|
+
except Exception: # 含 TypeError/AttributeError 等服务端编程错误:日志留全栈,响应只给通用文案,避免回显本机路径
|
|
914
|
+
import traceback
|
|
915
|
+
# 不 print_exc:堆栈进运行日志,控制台不再刷 Traceback
|
|
916
|
+
brain.log_event("panel", "POST 接口内部错误", level="error",
|
|
917
|
+
trace=traceback.format_exc()[-800:])
|
|
918
|
+
self._json({"error": "面板内部错误,详情见运行日志"}, 500)
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
# POST 分发表:路由 -> Handler 处理方法(参数统一为 handler(self, path, data))。
|
|
924
|
+
# 定义在所有 _api_* 处理函数之后(模块级查表发生在运行时,不在导入期)。
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
def _api_home_migrate(self, path, data):
|
|
928
|
+
# 数据目录迁移:整库复制到新位置 + 写指针文件(重启后生效)
|
|
929
|
+
target = str(data.get("target") or "").strip()
|
|
930
|
+
if not target:
|
|
931
|
+
self._json({"error": "缺少 target(目标目录绝对路径)"}, 400)
|
|
932
|
+
return
|
|
933
|
+
if brain.READONLY:
|
|
934
|
+
self._json({"error": "当前数据目录只读,无法迁移"}, 403)
|
|
935
|
+
return
|
|
936
|
+
try:
|
|
937
|
+
self._json(_migrate_home(target))
|
|
938
|
+
except ValueError as e:
|
|
939
|
+
self._json({"error": str(e)}, 400)
|
|
940
|
+
except OSError as e:
|
|
941
|
+
self._json({"error": f"迁移失败:{e}"}, 500)
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def _api_remember(self, path, data):
|
|
946
|
+
text = (data.get("text") or "").strip()
|
|
947
|
+
if not text:
|
|
948
|
+
self._json({"error": "内容为空"}, 400)
|
|
949
|
+
return
|
|
950
|
+
tags = data.get("tags") or []
|
|
951
|
+
entities = data.get("entities") or []
|
|
952
|
+
if not isinstance(tags, list) or not isinstance(entities, list):
|
|
953
|
+
self._json({"error": "tags / entities 必须是数组"}, 400)
|
|
954
|
+
return
|
|
955
|
+
rec, how = brain.remember(
|
|
956
|
+
text,
|
|
957
|
+
kind=data.get("kind", "fact"),
|
|
958
|
+
importance=data.get("importance"),
|
|
959
|
+
tags=tags,
|
|
960
|
+
entities=entities,
|
|
961
|
+
source="user",
|
|
962
|
+
emotion=(data.get("emotion") or None),
|
|
963
|
+
project=data.get("project"),
|
|
964
|
+
session=data.get("session"),
|
|
965
|
+
)
|
|
966
|
+
self._json({"ok": True, "how": how, "memory": memory_view(rec)})
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def _api_persona_update(self, path, data):
|
|
971
|
+
updates = data.get("updates") or {}
|
|
972
|
+
rejected = brain.update_persona(updates, why="面板编辑")
|
|
973
|
+
self._json({"ok": True, "rejected": rejected, "persona": brain.load_persona()})
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def _api_persona_changes_viewed(self, path, data):
|
|
978
|
+
# 用户点了「AI 近期改过人格」通知去查看:标记已读,通知消失
|
|
979
|
+
self._json(brain.mark_persona_changes_viewed())
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def _api_persona_suggest(self, path, data):
|
|
983
|
+
# 画像候选操作(v3.01):scan=归纳一轮新候选;adopt/discard=按序号(1 起)采纳或忽略
|
|
984
|
+
action = str(data.get("action") or "").strip()
|
|
985
|
+
if action == "scan":
|
|
986
|
+
days = _to_int(data.get("days"), 3)
|
|
987
|
+
try:
|
|
988
|
+
added = brain.persona_suggest_scan(days if days and days > 0 else 3)
|
|
989
|
+
except PermissionError as exc:
|
|
990
|
+
self._json({"error": str(exc)}, 403)
|
|
991
|
+
return
|
|
992
|
+
self._json({"ok": True, "added": added})
|
|
993
|
+
return
|
|
994
|
+
idx = _to_int(data.get("index"), 0)
|
|
995
|
+
if action not in ("adopt", "discard") or idx < 1:
|
|
996
|
+
self._json({"error": "action 必须是 scan/adopt/discard;adopt/discard 需 index>=1(先 GET /api/persona/suggest 看序号)"}, 400)
|
|
997
|
+
return
|
|
998
|
+
try:
|
|
999
|
+
r = brain.persona_suggest_adopt(idx) if action == "adopt" else brain.persona_suggest_discard(idx)
|
|
1000
|
+
except (ValueError, PermissionError) as exc:
|
|
1001
|
+
self._json({"error": str(exc)}, 400)
|
|
1002
|
+
return
|
|
1003
|
+
self._json({"ok": True, **r})
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
def _api_persona_state(self, path, data):
|
|
1008
|
+
# 读-改-写整段加锁:否则和 CLI/做梦的并发人格写入互相覆盖
|
|
1009
|
+
with brain._locked(brain.HOME / "persona.json"):
|
|
1010
|
+
p = brain.load_persona()
|
|
1011
|
+
st = p.setdefault("state", {})
|
|
1012
|
+
# 先按时间结算衰减(精力回升/亲密回淡),再叠加面板新值,口径与读路径一致
|
|
1013
|
+
regressed = brain._state_regress(st)
|
|
1014
|
+
st.update(regressed)
|
|
1015
|
+
for key in ("mood", "mood_note"):
|
|
1016
|
+
if key in data:
|
|
1017
|
+
st[key] = data[key]
|
|
1018
|
+
for key in ("energy", "closeness"):
|
|
1019
|
+
if key in data:
|
|
1020
|
+
v = _to_int(data[key])
|
|
1021
|
+
if v is None:
|
|
1022
|
+
self._json({"error": f"{key} 必须是数字"}, 400)
|
|
1023
|
+
return
|
|
1024
|
+
st[key] = max(0, min(100, v))
|
|
1025
|
+
st["updated"] = brain.now_ts()
|
|
1026
|
+
p.setdefault("history", []).append({
|
|
1027
|
+
"ts": brain.now_ts(), "field": "state", "from": None,
|
|
1028
|
+
"to": {k: data[k] for k in ("mood", "mood_note", "energy", "closeness") if k in data},
|
|
1029
|
+
"why": "面板编辑",
|
|
1030
|
+
})
|
|
1031
|
+
brain.save_persona(p)
|
|
1032
|
+
self._json({"ok": True, "persona": p})
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
|
|
1036
|
+
def _api_persona_edit(self, path, data):
|
|
1037
|
+
# 类型防御:dict 字段传字符串、list 字段传对象都会在 edit_persona 里 500,
|
|
1038
|
+
# 这里先校验给 400;字符串的 likes 等按逗号拆开(容错前端/脚本的手填输入)
|
|
1039
|
+
def _as_dict(key):
|
|
1040
|
+
v = data.get(key)
|
|
1041
|
+
if v in (None, "", {}, []):
|
|
1042
|
+
return None
|
|
1043
|
+
if isinstance(v, dict):
|
|
1044
|
+
return v or None
|
|
1045
|
+
raise ValueError(f"{key} 必须是对象(键值对)")
|
|
1046
|
+
|
|
1047
|
+
def _as_list(key):
|
|
1048
|
+
v = data.get(key)
|
|
1049
|
+
if v in (None, "", [], {}):
|
|
1050
|
+
return None
|
|
1051
|
+
if isinstance(v, list):
|
|
1052
|
+
return [str(x).strip() for x in v if str(x).strip()] or None
|
|
1053
|
+
if isinstance(v, str):
|
|
1054
|
+
parts = [s.strip() for s in v.replace(",", ",").split(",")]
|
|
1055
|
+
return [s for s in parts if s] or None
|
|
1056
|
+
raise ValueError(f"{key} 必须是列表或逗号分隔的字符串")
|
|
1057
|
+
|
|
1058
|
+
try:
|
|
1059
|
+
p = brain.edit_persona(
|
|
1060
|
+
identity=_as_dict("identity"),
|
|
1061
|
+
traits=_as_dict("traits"),
|
|
1062
|
+
drives=_as_dict("drives"),
|
|
1063
|
+
style=_as_list("style"),
|
|
1064
|
+
values=_as_list("values"),
|
|
1065
|
+
likes=_as_list("likes"),
|
|
1066
|
+
dislikes=_as_list("dislikes"),
|
|
1067
|
+
background=_as_list("background"),
|
|
1068
|
+
why=data.get("why") or "面板编辑",
|
|
1069
|
+
)
|
|
1070
|
+
except ValueError as exc:
|
|
1071
|
+
self._json({"error": str(exc)}, 400)
|
|
1072
|
+
return
|
|
1073
|
+
self._json({"ok": True, "persona": p, "onboarding": brain.onboarding_state()})
|
|
1074
|
+
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def _api_persona_mind(self, path, data):
|
|
1078
|
+
if data.get("mode") == "tune":
|
|
1079
|
+
cur, rsn = _to_int(data.get("curiosity")), _to_int(data.get("reason"))
|
|
1080
|
+
if cur is None or rsn is None:
|
|
1081
|
+
self._json({"error": "curiosity / reason 必须是数字"}, 400)
|
|
1082
|
+
return
|
|
1083
|
+
dr = brain.mind_tune(cur, rsn,
|
|
1084
|
+
why=data.get("why") or "面板调节")
|
|
1085
|
+
else:
|
|
1086
|
+
dr = brain.mind_set(data.get("curiosity"), data.get("reason"), why="面板设定")
|
|
1087
|
+
self._json({"ok": True, "drives": dr, "mind": brain.mind_state(),
|
|
1088
|
+
"persona": brain.load_persona()})
|
|
1089
|
+
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
def _api_mind_weigh(self, path, data):
|
|
1093
|
+
r = brain.mind_weigh(data.get("topic", ""), data.get("benefit", 5),
|
|
1094
|
+
data.get("cost", 5), data.get("confidence", 0.6),
|
|
1095
|
+
data.get("urgency", 0.5))
|
|
1096
|
+
self._json({"ok": True, "result": r})
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
def _api_emotion(self, path, data):
|
|
1101
|
+
act = data.get("action", "now")
|
|
1102
|
+
if act == "check":
|
|
1103
|
+
r = brain.emotion_consistency_check(data.get("text", ""))
|
|
1104
|
+
self._json({"ok": True, "result": r,
|
|
1105
|
+
"alerts": brain.emotion_checks_recent(10)})
|
|
1106
|
+
return
|
|
1107
|
+
if act == "feel":
|
|
1108
|
+
intensity = _to_num(data.get("intensity"), 0.6)
|
|
1109
|
+
if intensity is None:
|
|
1110
|
+
self._json({"error": "intensity 必须是数字"}, 400)
|
|
1111
|
+
return
|
|
1112
|
+
brain.feel(data.get("emotion", ""), intensity,
|
|
1113
|
+
why=data.get("why", ""), about=data.get("about", ""),
|
|
1114
|
+
decay_hours=data.get("decay_hours"))
|
|
1115
|
+
self._json({"ok": True, "mood": brain.mood_now(),
|
|
1116
|
+
"rationality": brain.rationality(),
|
|
1117
|
+
"emotion_arc": brain.emotion_arc(7),
|
|
1118
|
+
"desires": brain.desire_state()})
|
|
1119
|
+
return
|
|
1120
|
+
if act == "evaluate":
|
|
1121
|
+
r = brain.emotion_evaluate(data.get("event", ""), data.get("polarity", "auto"),
|
|
1122
|
+
data.get("importance", 0.6),
|
|
1123
|
+
why=data.get("why", ""), about=data.get("about", ""))
|
|
1124
|
+
self._json({"ok": True, "result": r, "mood": brain.mood_now(),
|
|
1125
|
+
"rationality": brain.rationality(),
|
|
1126
|
+
"emotion_arc": brain.emotion_arc(7),
|
|
1127
|
+
"desires": brain.desire_state()})
|
|
1128
|
+
return
|
|
1129
|
+
if act == "mirror":
|
|
1130
|
+
r = brain.emotion_mirror(data.get("emotion", ""), data.get("intensity", 0.5))
|
|
1131
|
+
self._json({"ok": True, "result": r, "mood": brain.mood_now(),
|
|
1132
|
+
"rationality": brain.rationality(),
|
|
1133
|
+
"emotion_arc": brain.emotion_arc(7),
|
|
1134
|
+
"desires": brain.desire_state()})
|
|
1135
|
+
return
|
|
1136
|
+
if act == "config":
|
|
1137
|
+
updates = {}
|
|
1138
|
+
if data.get("empathy"):
|
|
1139
|
+
updates["empathy"] = {"level": data["empathy"]}
|
|
1140
|
+
if data.get("gain") is not None:
|
|
1141
|
+
gain = _to_num(data["gain"], 0.5)
|
|
1142
|
+
if gain is None:
|
|
1143
|
+
self._json({"error": "gain 必须是数字"}, 400)
|
|
1144
|
+
return
|
|
1145
|
+
updates["empathy"] = dict(updates.get("empathy", {}),
|
|
1146
|
+
gain=max(0.0, min(1.0, gain)))
|
|
1147
|
+
if data.get("max_intensity") is not None:
|
|
1148
|
+
mi = _to_num(data["max_intensity"], 0.5)
|
|
1149
|
+
if mi is None:
|
|
1150
|
+
self._json({"error": "max_intensity 必须是数字"}, 400)
|
|
1151
|
+
return
|
|
1152
|
+
updates["empathy"] = dict(updates.get("empathy", {}),
|
|
1153
|
+
max_intensity=max(0.0, min(1.0, mi)))
|
|
1154
|
+
if data.get("suppressed") is not None:
|
|
1155
|
+
updates["suppressed"] = data.get("suppressed") or []
|
|
1156
|
+
if data.get("notes") is not None:
|
|
1157
|
+
updates["notes"] = data.get("notes")
|
|
1158
|
+
cfg = brain.save_emotion_cfg(updates)
|
|
1159
|
+
self._json({"ok": True, "emotion_cfg": cfg, "mood": brain.mood_now(),
|
|
1160
|
+
"rationality": brain.rationality()})
|
|
1161
|
+
return
|
|
1162
|
+
if act == "desire":
|
|
1163
|
+
amount = _to_num(data.get("amount"), 15)
|
|
1164
|
+
if amount is None:
|
|
1165
|
+
self._json({"error": "amount 必须是数字"}, 400)
|
|
1166
|
+
return
|
|
1167
|
+
brain.desire_satisfy(data.get("emotion", ""), amount)
|
|
1168
|
+
self._json({"ok": True, "mood": brain.mood_now(),
|
|
1169
|
+
"rationality": brain.rationality(),
|
|
1170
|
+
"emotion_arc": brain.emotion_arc(7),
|
|
1171
|
+
"desires": brain.desire_state()})
|
|
1172
|
+
return
|
|
1173
|
+
# 走到这里只允许 now(或缺省不传)→ 返回当前心情快照;拼错/未知 action 明确报错,
|
|
1174
|
+
# 别"假成功"让人以为写进去了
|
|
1175
|
+
if act not in ("", "now"):
|
|
1176
|
+
self._json({"error": f"未知操作:{act}"}, 400)
|
|
1177
|
+
return
|
|
1178
|
+
self._json({"ok": True, "mood": brain.mood_now(),
|
|
1179
|
+
"rationality": brain.rationality(),
|
|
1180
|
+
"emotion_arc": brain.emotion_arc(7),
|
|
1181
|
+
"desires": brain.desire_state()})
|
|
1182
|
+
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def _api_link(self, path, data):
|
|
1186
|
+
act = data.get("action", "link")
|
|
1187
|
+
if act == "link":
|
|
1188
|
+
weight = _to_num(data.get("weight", 1.0), 1.0)
|
|
1189
|
+
if weight is None:
|
|
1190
|
+
self._json({"error": "weight 必须是数字"}, 400)
|
|
1191
|
+
return
|
|
1192
|
+
r = brain.link_memory(data.get("a", ""), data.get("b", ""),
|
|
1193
|
+
data.get("relation", "相关"),
|
|
1194
|
+
weight, data.get("why", ""))
|
|
1195
|
+
elif act == "unlink":
|
|
1196
|
+
r = {"ok": brain.unlink_memory(data.get("a", ""), data.get("b", ""))}
|
|
1197
|
+
elif act == "auto":
|
|
1198
|
+
r = brain.assoc_auto(dry_run=bool(data.get("dry_run")))
|
|
1199
|
+
else:
|
|
1200
|
+
self._json({"error": "未知操作"}, 400)
|
|
1201
|
+
return
|
|
1202
|
+
self._json({"ok": True, "result": r, "graph": brain.assoc_graph()})
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
def _api_daily(self, path, data):
|
|
1207
|
+
dry = bool(data.get("dry_run"))
|
|
1208
|
+
# 真跑会整理/归档记忆:必须显式 confirm,避免空 body 的误触/重放直接写盘
|
|
1209
|
+
if not dry and data.get("confirm") is not True:
|
|
1210
|
+
self._json({"error": "真跑每日整理需要显式传 confirm: true(或用 dry_run 先预演)"}, 400)
|
|
1211
|
+
return
|
|
1212
|
+
r = brain.daily(dry_run=dry, force=bool(data.get("force")))
|
|
1213
|
+
self._json({"ok": True, "result": r, "overview": overview() if not dry else None,
|
|
1214
|
+
"workspace": workspace() if not dry else None})
|
|
1215
|
+
|
|
1216
|
+
|
|
1217
|
+
|
|
1218
|
+
def _api_skill_self_review(self, path, data):
|
|
1219
|
+
r = growth.self_review(force=bool(data.get("force")),
|
|
1220
|
+
days=_to_int(data.get("days", 3) or 3, 3) or 3)
|
|
1221
|
+
self._json({"ok": True, "result": r})
|
|
1222
|
+
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
def _api_seed(self, path, data):
|
|
1226
|
+
self._json({"error": "人格不再由预写种子生成,请用 /api/persona/edit"}, 410)
|
|
1227
|
+
|
|
1228
|
+
|
|
1229
|
+
|
|
1230
|
+
def _api_dream(self, path, data):
|
|
1231
|
+
# 做梦会重放/巩固/遗忘记忆:必须显式 confirm,空 body 不触发真实写盘
|
|
1232
|
+
if data.get("confirm") is not True:
|
|
1233
|
+
self._json({"error": "开始做梦需要显式传 confirm: true"}, 400)
|
|
1234
|
+
return
|
|
1235
|
+
report = brain.dream(trigger="panel")
|
|
1236
|
+
self._json({"ok": True, "report": report, "overview": overview()})
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
|
|
1240
|
+
def _api_dream_auto(self, path, data):
|
|
1241
|
+
# 一键自动做梦:机器重放 → 启发式压缩 → 直接沉淀(不需要再人工审核
|
|
1242
|
+
# pending)。产出照旧标 review="pending",仍可在记忆页复核。
|
|
1243
|
+
if data.get("confirm") is not True:
|
|
1244
|
+
self._json({"error": "自动做梦需要显式传 confirm: true"}, 400)
|
|
1245
|
+
return
|
|
1246
|
+
if brain.READONLY:
|
|
1247
|
+
self._json({"error": "记忆库当前只读,无法自动做梦沉淀"}, 403)
|
|
1248
|
+
return
|
|
1249
|
+
r = brain.auto_dream(trigger="panel")
|
|
1250
|
+
self._json({"ok": True, "result": r, "overview": overview()})
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
def _api_dream_instruction(self, path, data):
|
|
1255
|
+
# 生成给 AI 的深度做梦指令:面板拿到现成文本,一键复制发给 AI,
|
|
1256
|
+
# AI 读 pending.json → 压缩成 apply.json → dream --apply。
|
|
1257
|
+
# AI 产出的记忆仍标待审核,人工在记忆页过目——这道闸不绕开。
|
|
1258
|
+
# 「现在做梦」按钮已改为 auto_dream(直接沉淀、不留 pending),
|
|
1259
|
+
# 所以这里没有 pending 时就先跑一次深度做梦把碎片攒成任务。
|
|
1260
|
+
if brain.READONLY:
|
|
1261
|
+
self._json({"error": "记忆库当前只读,无法生成做梦任务"}, 403)
|
|
1262
|
+
return
|
|
1263
|
+
pend = brain.load_dream_pending()
|
|
1264
|
+
if not pend:
|
|
1265
|
+
brain.dream(trigger="panel")
|
|
1266
|
+
pend = brain.load_dream_pending()
|
|
1267
|
+
if not pend:
|
|
1268
|
+
self._json({"error": "梦很安静:没有可整理的记忆碎片"}, 400)
|
|
1269
|
+
return
|
|
1270
|
+
c = len(pend.get("clusters") or [])
|
|
1271
|
+
instr = (
|
|
1272
|
+
f"请帮我完成一次深度做梦整理(任务 {pend.get('task_id')}):\n"
|
|
1273
|
+
f"1. 运行 `python scripts/brain.py dream` 查看 {c} 组碎片(或直接读 "
|
|
1274
|
+
f"{(brain.HOME / 'dreams' / 'pending.json')});\n"
|
|
1275
|
+
"2. 把每组碎片压缩成更抽象、更持久的长期记忆(不要逐条复述原文),"
|
|
1276
|
+
"按 pending.json 里的 apply_schema 填写 memories / persona_updates / forget;\n"
|
|
1277
|
+
"3. 把结果写成 apply.json 并执行 `python scripts/brain.py dream --apply apply.json`。\n"
|
|
1278
|
+
"注意:不要编造记忆里没有的细节;人格 traits 改动只给小幅增量;"
|
|
1279
|
+
"产出会进入待审核,用户会在面板记忆页复核。"
|
|
1280
|
+
)
|
|
1281
|
+
self._json({"ok": True, "instruction": instr, "task_id": pend.get("task_id"),
|
|
1282
|
+
"clusters": c})
|
|
1283
|
+
|
|
1284
|
+
|
|
1285
|
+
|
|
1286
|
+
def _api_dream_apply(self, path, data):
|
|
1287
|
+
result = data.get("result") or {}
|
|
1288
|
+
if isinstance(result, str):
|
|
1289
|
+
result = json.loads(result)
|
|
1290
|
+
applied = brain.apply_dream(result)
|
|
1291
|
+
self._json({"ok": True, "applied": applied, "overview": overview()})
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
|
|
1295
|
+
def _api_dream_draft(self, path, data):
|
|
1296
|
+
draft = data.get("draft")
|
|
1297
|
+
if draft is None:
|
|
1298
|
+
brain.clear_dream_draft() # 传 null = 清空草稿
|
|
1299
|
+
self._json({"ok": True, "draft": None})
|
|
1300
|
+
return
|
|
1301
|
+
if isinstance(draft, str):
|
|
1302
|
+
try:
|
|
1303
|
+
draft = json.loads(draft) # 允许前端直接传 JSON 文本
|
|
1304
|
+
except json.JSONDecodeError as exc:
|
|
1305
|
+
self._json({"error": f"草稿 JSON 解析失败:{exc}"}, 400)
|
|
1306
|
+
return
|
|
1307
|
+
if not isinstance(draft, dict):
|
|
1308
|
+
self._json({"error": "草稿必须是 JSON 对象"}, 400)
|
|
1309
|
+
return
|
|
1310
|
+
brain.save_dream_draft(draft)
|
|
1311
|
+
self._json({"ok": True, "draft": brain.load_dream_draft()})
|
|
1312
|
+
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
def _api_memory_edit(self, path, data):
|
|
1316
|
+
mid = data.get("id")
|
|
1317
|
+
# 读-改-写整体加锁:save_all 是整库快照覆写,不加锁会覆盖掉并发写入
|
|
1318
|
+
with brain._locked(brain.HOME / "hippocampus.jsonl"):
|
|
1319
|
+
records = brain.load_all()
|
|
1320
|
+
target = next((m for m in records if m["id"] == mid), None)
|
|
1321
|
+
if not target:
|
|
1322
|
+
self._json({"error": "没有这条记忆"}, 404)
|
|
1323
|
+
return
|
|
1324
|
+
for key in ("text", "gist", "pinned"):
|
|
1325
|
+
if key in data:
|
|
1326
|
+
target[key] = data[key]
|
|
1327
|
+
if "kind" in data:
|
|
1328
|
+
kind = str(data["kind"] or "").strip()
|
|
1329
|
+
if kind not in brain.KINDS: # 白名单:防恶意/手滑写入怪异类型
|
|
1330
|
+
self._json({"error": f"kind 只能是:{'、'.join(brain.KINDS)}"}, 400)
|
|
1331
|
+
return
|
|
1332
|
+
target["kind"] = kind
|
|
1333
|
+
if "importance" in data:
|
|
1334
|
+
imp = _to_num(data["importance"])
|
|
1335
|
+
if imp is None:
|
|
1336
|
+
self._json({"error": "importance 必须是数字"}, 400)
|
|
1337
|
+
return
|
|
1338
|
+
target["importance"] = round(max(0.0, min(1.0, imp / 10 if imp > 1 else imp)), 3)
|
|
1339
|
+
if "tags" in data:
|
|
1340
|
+
tags = data["tags"]
|
|
1341
|
+
if not isinstance(tags, list):
|
|
1342
|
+
self._json({"error": "tags 必须是数组"}, 400)
|
|
1343
|
+
return
|
|
1344
|
+
target["tags"] = [str(t).strip() for t in tags if str(t).strip()]
|
|
1345
|
+
brain.save_all(records)
|
|
1346
|
+
self._json({"ok": True, "memory": memory_view(target)})
|
|
1347
|
+
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
def _api_forget(self, path, data):
|
|
1351
|
+
ok = brain.forget(data.get("id", ""))
|
|
1352
|
+
self._json({"ok": ok})
|
|
1353
|
+
|
|
1354
|
+
|
|
1355
|
+
|
|
1356
|
+
def _api_diag_fix_links(self, path, data):
|
|
1357
|
+
# 自诊断配套的一键修复:摘除断链引用(只清链不删记忆,零数据损失)
|
|
1358
|
+
self._json(brain.fix_dead_links())
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
def _api_memory_dust(self, path, data):
|
|
1363
|
+
# 淡忘可逆通道:fold 折叠(原文收起)/ unfold 解压还原 / revive 彻底复活
|
|
1364
|
+
act = data.get("action", "fold")
|
|
1365
|
+
mid = data.get("id", "")
|
|
1366
|
+
if act == "fold":
|
|
1367
|
+
m = brain.fold(mid)
|
|
1368
|
+
elif act == "unfold":
|
|
1369
|
+
m = brain.unfold(mid)
|
|
1370
|
+
elif act == "revive":
|
|
1371
|
+
layer = data.get("layer") or "cortex"
|
|
1372
|
+
m = brain.revive(mid, layer=layer)
|
|
1373
|
+
else:
|
|
1374
|
+
self._json({"error": "action 只能是 fold / unfold / revive"}, 400)
|
|
1375
|
+
return
|
|
1376
|
+
self._json({"ok": True, "action": act, "memory": memory_view(m)})
|
|
1377
|
+
|
|
1378
|
+
|
|
1379
|
+
|
|
1380
|
+
def _api_memory_purge(self, path, data):
|
|
1381
|
+
# #34 物理删除:双重确认在 memory.purge 内强制校验(dust 冷静期 7 天 + confirm=id 前 8 位)
|
|
1382
|
+
try:
|
|
1383
|
+
result = brain.purge(str(data.get("id", "")), str(data.get("confirm", "")))
|
|
1384
|
+
except PermissionError as exc:
|
|
1385
|
+
self._json({"error": str(exc)}, 403)
|
|
1386
|
+
return
|
|
1387
|
+
except ValueError as exc:
|
|
1388
|
+
self._json({"error": str(exc)}, 400)
|
|
1389
|
+
return
|
|
1390
|
+
self._json({"ok": True, **result})
|
|
1391
|
+
|
|
1392
|
+
|
|
1393
|
+
|
|
1394
|
+
def _api_knowledge(self, path, data):
|
|
1395
|
+
act = data.get("action", "add")
|
|
1396
|
+
if act in ("add", "update"):
|
|
1397
|
+
bad = _bad_list(data, "points", "tags", "entities")
|
|
1398
|
+
if bad:
|
|
1399
|
+
self._json({"error": bad}, 400)
|
|
1400
|
+
return
|
|
1401
|
+
if act == "add":
|
|
1402
|
+
# 面板是本机人工操作 → source=user 直接 confirmed;
|
|
1403
|
+
# 前端若标明 AI 产出(source=ai)则落为待审核,走 review 流程。
|
|
1404
|
+
rec, how = growth.add_knowledge(
|
|
1405
|
+
data.get("title", ""), data.get("body", ""), data.get("topic", ""),
|
|
1406
|
+
data.get("points"), data.get("tags"), data.get("entities"),
|
|
1407
|
+
source=data.get("source", "user"))
|
|
1408
|
+
self._json({"ok": True, "how": how, "knowledge": rec, "workspace": workspace()})
|
|
1409
|
+
elif act == "update":
|
|
1410
|
+
rec = growth.update_knowledge(
|
|
1411
|
+
data.get("id", ""), title=data.get("title"), topic=data.get("topic"),
|
|
1412
|
+
body=data.get("body"), points=data.get("points"),
|
|
1413
|
+
tags=data.get("tags"), entities=data.get("entities"),
|
|
1414
|
+
pinned=data.get("pinned"))
|
|
1415
|
+
self._json({"ok": True, "knowledge": rec, "workspace": workspace()})
|
|
1416
|
+
elif act == "delete":
|
|
1417
|
+
self._json({"ok": growth.delete_knowledge(data.get("id", "")), "workspace": workspace()})
|
|
1418
|
+
elif act == "review":
|
|
1419
|
+
rec = growth.set_knowledge_status(data.get("id", ""), "confirmed")
|
|
1420
|
+
self._json({"ok": bool(rec), "knowledge": rec, "workspace": workspace()})
|
|
1421
|
+
elif act == "discard":
|
|
1422
|
+
rec = growth.set_knowledge_status(data.get("id", ""), "discarded")
|
|
1423
|
+
self._json({"ok": bool(rec), "knowledge": rec, "workspace": workspace()})
|
|
1424
|
+
elif act == "verify":
|
|
1425
|
+
# 记一次验证:证据等级自动+1(E0→E4 封顶),验证过的结论检索时优先
|
|
1426
|
+
try:
|
|
1427
|
+
rec = growth.knowledge_verify(data.get("id", ""),
|
|
1428
|
+
note=str(data.get("note") or ""),
|
|
1429
|
+
level=data.get("level"))
|
|
1430
|
+
except (KeyError, ValueError) as exc:
|
|
1431
|
+
self._json({"error": str(exc)}, 400)
|
|
1432
|
+
return
|
|
1433
|
+
self._json({"ok": True, "knowledge": rec, "workspace": workspace()})
|
|
1434
|
+
elif act == "tidy":
|
|
1435
|
+
self._json({"ok": True, "report": growth.tidy_knowledge(), "workspace": workspace()})
|
|
1436
|
+
elif act == "tidy/apply":
|
|
1437
|
+
result = data.get("result") or {}
|
|
1438
|
+
if isinstance(result, str):
|
|
1439
|
+
result = json.loads(result)
|
|
1440
|
+
self._json({"ok": True, "applied": growth.apply_tidy(result), "workspace": workspace()})
|
|
1441
|
+
else:
|
|
1442
|
+
self._json({"error": "未知操作"}, 400)
|
|
1443
|
+
|
|
1444
|
+
|
|
1445
|
+
|
|
1446
|
+
def _api_note(self, path, data):
|
|
1447
|
+
act = data.get("action", "write")
|
|
1448
|
+
if act in ("write", "update"):
|
|
1449
|
+
bad = _bad_list(data, "tags", "memory_ids")
|
|
1450
|
+
if bad:
|
|
1451
|
+
self._json({"error": bad}, 400)
|
|
1452
|
+
return
|
|
1453
|
+
if act == "write":
|
|
1454
|
+
rec, how = growth.write_note(
|
|
1455
|
+
data.get("type", "journal"), data.get("title", ""), data.get("body", ""),
|
|
1456
|
+
data.get("mood", ""), data.get("tags"), data.get("memory_ids"),
|
|
1457
|
+
append_same_day=bool(data.get("append", True)))
|
|
1458
|
+
self._json({"ok": True, "how": how, "note": rec, "workspace": workspace()})
|
|
1459
|
+
elif act == "update":
|
|
1460
|
+
rec = growth.update_note(data.get("id", ""), title=data.get("title"),
|
|
1461
|
+
body=data.get("body"), mood=data.get("mood"),
|
|
1462
|
+
tags=data.get("tags"))
|
|
1463
|
+
self._json({"ok": True, "note": rec, "workspace": workspace()})
|
|
1464
|
+
elif act == "delete":
|
|
1465
|
+
self._json({"ok": growth.delete_note(data.get("id", "")), "workspace": workspace()})
|
|
1466
|
+
else:
|
|
1467
|
+
self._json({"error": "未知操作"}, 400)
|
|
1468
|
+
|
|
1469
|
+
|
|
1470
|
+
|
|
1471
|
+
def _api_skill(self, path, data):
|
|
1472
|
+
act = data.get("action", "list")
|
|
1473
|
+
if act == "new":
|
|
1474
|
+
res = growth.create_skill(data.get("name", ""), data.get("description", ""),
|
|
1475
|
+
data.get("body", ""), bool(data.get("force")))
|
|
1476
|
+
self._json({"ok": True, "skill": res, "workspace": workspace()})
|
|
1477
|
+
elif act == "edit":
|
|
1478
|
+
res = growth.edit_skill(data.get("name", ""), data.get("body"),
|
|
1479
|
+
data.get("append"), data.get("description"))
|
|
1480
|
+
self._json({"ok": True, "skill": res, "workspace": workspace()})
|
|
1481
|
+
elif act == "install":
|
|
1482
|
+
# 面板安装忽略 from_dir:本地 CLI 才能指外部目录,防远程乱指
|
|
1483
|
+
res = growth.install_skill(data.get("name", ""),
|
|
1484
|
+
bool(data.get("force")),
|
|
1485
|
+
None,
|
|
1486
|
+
accept_risk=bool(data.get("yes")))
|
|
1487
|
+
# 面板触发的更新/安装要留痕(特别是本体 lingshu):事后能查谁在何时更新到什么状态
|
|
1488
|
+
brain.log_event("panel", f"安装/更新技能 {data.get('name', '')} "
|
|
1489
|
+
f"(force={bool(data.get('force'))}) → {res.get('state')}")
|
|
1490
|
+
self._json({"ok": True, "result": res, "workspace": workspace()})
|
|
1491
|
+
return
|
|
1492
|
+
elif act == "uninstall":
|
|
1493
|
+
# 会删全局技能目录里的东西,记一笔日志,事后能查是谁在面板上删的;
|
|
1494
|
+
# managed_only 只允许卸载灵枢装过的技能,防止误删用户其他全局插件
|
|
1495
|
+
res = growth.uninstall_skill(data.get("name", ""), managed_only=True)
|
|
1496
|
+
brain.log_event("panel", f"卸载技能 {data.get('name', '')} → {res.get('state')}")
|
|
1497
|
+
self._json({"ok": True, "result": res,
|
|
1498
|
+
"workspace": workspace()})
|
|
1499
|
+
elif act == "delete":
|
|
1500
|
+
ok = growth.remove_skill(data.get("name", ""))
|
|
1501
|
+
brain.log_event("panel", f"删除自建技能 {data.get('name', '')} → {ok}")
|
|
1502
|
+
self._json({"ok": ok, "workspace": workspace()})
|
|
1503
|
+
elif act == "check":
|
|
1504
|
+
self._json({"ok": True, "checks": growth.check_skill(data.get("name"))})
|
|
1505
|
+
elif act == "show":
|
|
1506
|
+
self._json({"ok": True, "skill": growth.read_skill(data.get("name", ""))})
|
|
1507
|
+
elif act == "list":
|
|
1508
|
+
self._json({"ok": True, "skills": growth.list_skills(), "workspace": workspace()})
|
|
1509
|
+
elif act == "roots":
|
|
1510
|
+
self._json({"ok": True, "roots": growth.skill_roots(),
|
|
1511
|
+
"workspace": workspace()})
|
|
1512
|
+
elif act == "root_add":
|
|
1513
|
+
res = growth.add_skill_root(data.get("path", ""))
|
|
1514
|
+
self._json({"ok": True, "result": res, "workspace": workspace()})
|
|
1515
|
+
elif act == "root_rm":
|
|
1516
|
+
res = growth.remove_skill_root(data.get("path", ""))
|
|
1517
|
+
self._json({"ok": True, "result": res, "workspace": workspace()})
|
|
1518
|
+
elif act == "scan":
|
|
1519
|
+
rows = growth.scan_skills(data.get("root") or None)
|
|
1520
|
+
self._json({"ok": True, "skills": rows, "workspace": workspace()})
|
|
1521
|
+
elif act == "use":
|
|
1522
|
+
# 只读取正文给前端预览(不自动全局化),便于面板里看外部技能内容
|
|
1523
|
+
res = growth.use_skill(data.get("name", ""),
|
|
1524
|
+
int(data.get("chars") or 6000),
|
|
1525
|
+
root=data.get("root") or None)
|
|
1526
|
+
self._json({"ok": True, "skill": res})
|
|
1527
|
+
elif act == "borrow":
|
|
1528
|
+
res = growth.borrow_skill(data.get("name", ""),
|
|
1529
|
+
data.get("as_name", ""),
|
|
1530
|
+
data.get("note", ""),
|
|
1531
|
+
bool(data.get("force")),
|
|
1532
|
+
root=data.get("root") or None)
|
|
1533
|
+
self._json({"ok": True, "skill": res, "workspace": workspace()})
|
|
1534
|
+
else:
|
|
1535
|
+
self._json({"error": "未知操作"}, 400)
|
|
1536
|
+
|
|
1537
|
+
|
|
1538
|
+
|
|
1539
|
+
def _api_skill_dsh_repair(self, path, data):
|
|
1540
|
+
"""修复 DSH 里残缺的 lingshu-skill 副本(空壳目录 + 被移除的声明)。"""
|
|
1541
|
+
profile = data.get("profile") or None
|
|
1542
|
+
res = growth.repair_dsh_lingshu_copy(profile)
|
|
1543
|
+
brain.log_event("panel",
|
|
1544
|
+
f"DSH 副本修复请求 profile={profile or 'all'} → "
|
|
1545
|
+
f"repaired={res.get('repaired')} errors={res.get('errors')}")
|
|
1546
|
+
self._json({"ok": bool(res.get("ok")), "result": res,
|
|
1547
|
+
"workspace": workspace()})
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
def _kill_lingshu_children() -> list:
|
|
1551
|
+
"""杀掉占用灵枢文件的 python 后台子进程(命令行含 brain.py / lingshu)。
|
|
1552
|
+
|
|
1553
|
+
DSH 运行时 pnpm 无法 rename 被占用的目录,强制更新前先停掉这些子进程。
|
|
1554
|
+
排除面板自身进程;单条失败不影响其余,异常静默记日志。
|
|
1555
|
+
返回 [{pid, cmd}](cmd 为截断摘要)。
|
|
1556
|
+
"""
|
|
1557
|
+
me = os.getpid()
|
|
1558
|
+
procs = [] # (pid, cmdline)
|
|
1559
|
+
try:
|
|
1560
|
+
p = subprocess.run(
|
|
1561
|
+
["wmic", "process", "where",
|
|
1562
|
+
"name='python.exe' and commandline like '%brain.py%'",
|
|
1563
|
+
"get", "processid,commandline", "/format:list"],
|
|
1564
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30)
|
|
1565
|
+
cur = {}
|
|
1566
|
+
for line in (p.stdout or "").splitlines():
|
|
1567
|
+
line = line.strip()
|
|
1568
|
+
if "=" in line:
|
|
1569
|
+
k, _, v = line.partition("=")
|
|
1570
|
+
cur[k.strip().lower()] = v.strip()
|
|
1571
|
+
elif not line and cur:
|
|
1572
|
+
procs.append((int(cur.get("processid", "0") or 0),
|
|
1573
|
+
cur.get("commandline", "")))
|
|
1574
|
+
cur = {}
|
|
1575
|
+
if cur:
|
|
1576
|
+
procs.append((int(cur.get("processid", "0") or 0),
|
|
1577
|
+
cur.get("commandline", "")))
|
|
1578
|
+
except Exception as e:
|
|
1579
|
+
brain.log_event("panel", f"wmic 枚举灵枢子进程失败,改用 PowerShell:{e}", level="warn")
|
|
1580
|
+
procs = []
|
|
1581
|
+
try:
|
|
1582
|
+
ps = ("Get-CimInstance Win32_Process -Filter \"Name='python.exe'\" | "
|
|
1583
|
+
"Where-Object {$_.CommandLine -like '*brain.py*'} | "
|
|
1584
|
+
"Select-Object ProcessId,CommandLine | ConvertTo-Json")
|
|
1585
|
+
p = subprocess.run(["powershell", "-NoProfile", "-Command", ps],
|
|
1586
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60)
|
|
1587
|
+
out = (p.stdout or "").strip()
|
|
1588
|
+
if out:
|
|
1589
|
+
items = json.loads(out)
|
|
1590
|
+
if isinstance(items, dict):
|
|
1591
|
+
items = [items]
|
|
1592
|
+
for it in items:
|
|
1593
|
+
try:
|
|
1594
|
+
procs.append((int(it.get("ProcessId") or 0),
|
|
1595
|
+
str(it.get("CommandLine") or "")))
|
|
1596
|
+
except (TypeError, ValueError):
|
|
1597
|
+
continue
|
|
1598
|
+
except Exception as e2:
|
|
1599
|
+
brain.log_event("panel", f"PowerShell 枚举灵枢子进程也失败:{e2}", level="warn")
|
|
1600
|
+
killed = []
|
|
1601
|
+
for pid, cmd in procs:
|
|
1602
|
+
if not pid or pid == me:
|
|
1603
|
+
continue
|
|
1604
|
+
low = (cmd or "").lower()
|
|
1605
|
+
if "brain.py" not in low and "lingshu" not in low:
|
|
1606
|
+
continue
|
|
1607
|
+
try:
|
|
1608
|
+
r = subprocess.run(["taskkill", "/PID", str(pid), "/F", "/T"],
|
|
1609
|
+
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30)
|
|
1610
|
+
if r.returncode == 0:
|
|
1611
|
+
killed.append({"pid": pid, "cmd": (cmd or "")[:120]})
|
|
1612
|
+
else:
|
|
1613
|
+
brain.log_event("panel", f"taskkill {pid} 失败:{(r.stderr or r.stdout or '').strip()[:120]}",
|
|
1614
|
+
level="warn")
|
|
1615
|
+
except Exception as e:
|
|
1616
|
+
brain.log_event("panel", f"taskkill {pid} 异常:{e}", level="warn")
|
|
1617
|
+
if killed:
|
|
1618
|
+
brain.log_event("panel",
|
|
1619
|
+
f"强制更新前停止灵枢子进程 {len(killed)} 个:"
|
|
1620
|
+
+ ", ".join(str(k['pid']) for k in killed))
|
|
1621
|
+
return killed
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
def _api_skill_dsh_force_update(self, path, data):
|
|
1625
|
+
"""强制在线更新 DSH 副本:停灵枢子进程 → 拉最新源 → 原地覆盖所有 DSH profile。"""
|
|
1626
|
+
import traceback
|
|
1627
|
+
killed, profiles, install_res = [], [], None
|
|
1628
|
+
try:
|
|
1629
|
+
# a) 先检查是否真的需要更新:所有副本已最新就免杀进程
|
|
1630
|
+
try:
|
|
1631
|
+
chk = growth.update_check("lingshu", force_pull=False, auto=True)
|
|
1632
|
+
except Exception:
|
|
1633
|
+
chk = {}
|
|
1634
|
+
src_ver = str(chk.get("source_version") or chk.get("version") or "")
|
|
1635
|
+
states = growth.dsh_lingshu_copy_state()
|
|
1636
|
+
need = any(
|
|
1637
|
+
(c["state"] != "ok" and c["state"] != "not_installed")
|
|
1638
|
+
or (src_ver and c.get("version") and str(c["version"]) != src_ver)
|
|
1639
|
+
for c in states)
|
|
1640
|
+
if not need:
|
|
1641
|
+
self._json({"ok": True, "killed": [], "profiles": [],
|
|
1642
|
+
"note": "所有 DSH 副本已是最新,无需更新"})
|
|
1643
|
+
return
|
|
1644
|
+
# b) 停掉占用文件的灵枢 python 子进程
|
|
1645
|
+
killed = _kill_lingshu_children()
|
|
1646
|
+
# c) 走既有安装链路拉最新版到本地全局副本(远程源由 install_skill 内部解析)
|
|
1647
|
+
install_res = growth.install_skill("lingshu", True, None, accept_risk=True)
|
|
1648
|
+
brain.log_event("panel", f"DSH 强制更新:全局副本安装 → {install_res.get('state')}")
|
|
1649
|
+
# d) 对每个有 lingshu 目录的 profile 强制覆盖(内容不一致才写)
|
|
1650
|
+
before = {c["profile"]: c["state"] for c in states}
|
|
1651
|
+
rep = growth.repair_dsh_lingshu_copy(None, force=True)
|
|
1652
|
+
after_states = {c["profile"]: c for c in growth.dsh_lingshu_copy_state()}
|
|
1653
|
+
for prof in (rep.get("repaired") or []) + [e["profile"] for e in (rep.get("errors") or [])]:
|
|
1654
|
+
if prof in profiles:
|
|
1655
|
+
continue
|
|
1656
|
+
a = after_states.get(prof) or {}
|
|
1657
|
+
profiles.append({
|
|
1658
|
+
"profile": prof,
|
|
1659
|
+
"state_before": before.get(prof),
|
|
1660
|
+
"state_after": a.get("state"),
|
|
1661
|
+
"updated_files": (rep.get("updated_files") or {}).get(prof, 0),
|
|
1662
|
+
})
|
|
1663
|
+
brain.log_event("panel", f"DSH 副本强制更新完成:killed={len(killed)} "
|
|
1664
|
+
f"profiles={[(p['profile'], p['state_after']) for p in profiles]}")
|
|
1665
|
+
self._json({"ok": bool(rep.get("ok")), "killed": killed,
|
|
1666
|
+
"profiles": profiles,
|
|
1667
|
+
"install": {"state": install_res.get("state")},
|
|
1668
|
+
"note": "已原地更新 DSH 副本,重启 DSH 生效"})
|
|
1669
|
+
except Exception as e:
|
|
1670
|
+
brain.log_event("panel", "DSH 副本强制更新失败:"
|
|
1671
|
+
+ traceback.format_exc()[-500:], level="warn")
|
|
1672
|
+
self._json({"ok": False, "error": str(e), "killed": killed,
|
|
1673
|
+
"profiles": profiles}, 500)
|
|
1674
|
+
|
|
1675
|
+
|
|
1676
|
+
|
|
1677
|
+
def _api_evolve(self, path, data):
|
|
1678
|
+
row = growth.log_evolution(data.get("kind", "self"), data.get("title", ""),
|
|
1679
|
+
data.get("detail", ""), data.get("refs") or [])
|
|
1680
|
+
self._json({"ok": True, "evolution": row, "workspace": workspace()})
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
|
|
1684
|
+
def _api_persona_interview(self, path, data):
|
|
1685
|
+
p = brain.persona_interview(data.get("name", ""), data.get("traits", ""),
|
|
1686
|
+
data.get("style", ""), data.get("values", ""),
|
|
1687
|
+
data.get("callme", ""), data.get("self_name", ""),
|
|
1688
|
+
bool(data.get("unsure")))
|
|
1689
|
+
self._json({"ok": True, "persona": p, "onboarding": brain.onboarding_state()})
|
|
1690
|
+
|
|
1691
|
+
|
|
1692
|
+
|
|
1693
|
+
def _api_persona_self(self, path, data):
|
|
1694
|
+
p = brain.persona_self_author(data.get("name", ""), data.get("traits", ""),
|
|
1695
|
+
data.get("likes", ""), data.get("dislikes", ""),
|
|
1696
|
+
data.get("habits", ""), data.get("insights", ""),
|
|
1697
|
+
data.get("style", ""), data.get("values", ""),
|
|
1698
|
+
data.get("callme", ""), data.get("self_name", ""))
|
|
1699
|
+
self._json({"ok": True, "persona": p, "onboarding": brain.onboarding_state()})
|
|
1700
|
+
|
|
1701
|
+
|
|
1702
|
+
|
|
1703
|
+
def _api_persona_rollback(self, path, data):
|
|
1704
|
+
idx = _to_int(data.get("index"))
|
|
1705
|
+
if idx is None:
|
|
1706
|
+
self._json({"error": "index 必须是数字"}, 400)
|
|
1707
|
+
return
|
|
1708
|
+
try:
|
|
1709
|
+
p = brain.persona_rollback(idx)
|
|
1710
|
+
except (ValueError, IndexError) as exc:
|
|
1711
|
+
self._json({"error": str(exc)}, 400)
|
|
1712
|
+
return
|
|
1713
|
+
self._json({"ok": True, "persona": p})
|
|
1714
|
+
|
|
1715
|
+
|
|
1716
|
+
def _api_persona_snapshot_rollback(self, path, data):
|
|
1717
|
+
"""按自动快照 version 回滚 persona.json(回滚前自动再存一份"回滚前"快照,可再回回)。"""
|
|
1718
|
+
version = _to_int(data.get("version"))
|
|
1719
|
+
if version is None or version <= 0:
|
|
1720
|
+
self._json({"error": "version 必须是正整数"}, 400)
|
|
1721
|
+
return
|
|
1722
|
+
p = brain.rollback_persona_snapshot(int(version))
|
|
1723
|
+
if p is None:
|
|
1724
|
+
self._json({"error": f"找不到快照 version={version},或快照文件损坏"}, 404)
|
|
1725
|
+
return
|
|
1726
|
+
self._json({"ok": True, "persona": p, "rolled_back_to": int(version)})
|
|
1727
|
+
|
|
1728
|
+
|
|
1729
|
+
|
|
1730
|
+
def _api_memory_review(self, path, data):
|
|
1731
|
+
mid, act = data.get("id", ""), data.get("action", "")
|
|
1732
|
+
if act not in ("confirm", "discard"):
|
|
1733
|
+
self._json({"error": "action 只能是 confirm / discard"}, 400)
|
|
1734
|
+
return
|
|
1735
|
+
try:
|
|
1736
|
+
r = brain.set_memory_review(mid, act)
|
|
1737
|
+
except (ValueError, PermissionError) as exc:
|
|
1738
|
+
self._json({"error": str(exc)}, 400)
|
|
1739
|
+
return
|
|
1740
|
+
self._json({"ok": True, "memory": r, "review_counts": brain.review_counts()})
|
|
1741
|
+
|
|
1742
|
+
|
|
1743
|
+
|
|
1744
|
+
def _api_memory_bulk(self, path, data):
|
|
1745
|
+
try:
|
|
1746
|
+
r = brain.bulk_memory_action(data.get("ids") or [],
|
|
1747
|
+
data.get("action", ""), data.get("value"))
|
|
1748
|
+
except (ValueError, PermissionError) as exc:
|
|
1749
|
+
self._json({"error": str(exc)}, 400)
|
|
1750
|
+
return
|
|
1751
|
+
self._json({"ok": True, "result": r, "review_counts": r.get("review_counts")})
|
|
1752
|
+
|
|
1753
|
+
|
|
1754
|
+
|
|
1755
|
+
def _api_memory_boost(self, path, data):
|
|
1756
|
+
"""遗忘纠正:把一条记忆的稳定度×1.5、刷新访问时间。"""
|
|
1757
|
+
mid = str(data.get("id") or "")
|
|
1758
|
+
if not mid:
|
|
1759
|
+
self._json({"error": "缺记忆 id"}, 400)
|
|
1760
|
+
return
|
|
1761
|
+
try:
|
|
1762
|
+
r = brain.boost(mid)
|
|
1763
|
+
except LookupError:
|
|
1764
|
+
self._json({"error": "找不到这条记忆(可能已删除或已归档)"}, 400)
|
|
1765
|
+
return
|
|
1766
|
+
except PermissionError:
|
|
1767
|
+
self._json({"error": "只读模式不能纠正遗忘"}, 403)
|
|
1768
|
+
return
|
|
1769
|
+
self._json({"ok": True, "result": r})
|
|
1770
|
+
|
|
1771
|
+
|
|
1772
|
+
def _api_memory_rebuild_embeds(self, path, data):
|
|
1773
|
+
"""一键重建全库 embedding 向量(force=true 全量重算,false 只补缺失/模型不符)。"""
|
|
1774
|
+
force = bool(data.get("force"))
|
|
1775
|
+
try:
|
|
1776
|
+
r = brain.memory.rebuild_embeddings(force=force)
|
|
1777
|
+
except PermissionError:
|
|
1778
|
+
self._json({"error": "当前数据目录只读,无法重建 embedding"}, 403)
|
|
1779
|
+
return
|
|
1780
|
+
except RuntimeError as exc:
|
|
1781
|
+
self._json({"error": str(exc)}, 502)
|
|
1782
|
+
return
|
|
1783
|
+
self._json({"ok": True, "result": r})
|
|
1784
|
+
|
|
1785
|
+
|
|
1786
|
+
def _api_mode(self, path, data):
|
|
1787
|
+
mode = str(data.get("mode", "") or "").lower()
|
|
1788
|
+
if mode not in ("work", "human", "auto"):
|
|
1789
|
+
self._json({"error": "mode 只能是 work / human / auto"}, 400)
|
|
1790
|
+
return
|
|
1791
|
+
brain.config_set("mode", mode)
|
|
1792
|
+
self._json({"ok": True, "mode": mode})
|
|
1793
|
+
|
|
1794
|
+
|
|
1795
|
+
|
|
1796
|
+
def _api_logs_post(self, path, data):
|
|
1797
|
+
act = str(data.get("action") or "clear")
|
|
1798
|
+
if act == "clear":
|
|
1799
|
+
n = brain.clear_logs()
|
|
1800
|
+
self._json({"ok": True, "cleared": n,
|
|
1801
|
+
"logs": brain.read_logs(200)})
|
|
1802
|
+
return
|
|
1803
|
+
if act == "delete":
|
|
1804
|
+
n = brain.clear_logs(ts=data.get("ts"), kind=data.get("kind"),
|
|
1805
|
+
msg=data.get("msg"))
|
|
1806
|
+
self._json({"ok": True, "deleted": n,
|
|
1807
|
+
"logs": brain.read_logs(200)})
|
|
1808
|
+
return
|
|
1809
|
+
self._json({"error": "action 只能是 clear / delete"}, 400)
|
|
1810
|
+
|
|
1811
|
+
|
|
1812
|
+
|
|
1813
|
+
def _api_panels(self, path, data):
|
|
1814
|
+
# 自定义面板管理:全部转发给 panels.py,统一中文错误消息回给前端
|
|
1815
|
+
act = str(data.get("action") or "")
|
|
1816
|
+
try:
|
|
1817
|
+
if act == "activate":
|
|
1818
|
+
pname = str(data.get("name") or "")
|
|
1819
|
+
panels.activate(pname)
|
|
1820
|
+
self._json({"ok": True, "active": panels._active_name() or "default"})
|
|
1821
|
+
return
|
|
1822
|
+
if act == "deactivate":
|
|
1823
|
+
panels.deactivate()
|
|
1824
|
+
self._json({"ok": True, "active": "default"})
|
|
1825
|
+
return
|
|
1826
|
+
if act == "delete":
|
|
1827
|
+
# source: installed=已安装目录 / market=市场目录
|
|
1828
|
+
panels.delete(str(data.get("name") or ""),
|
|
1829
|
+
str(data.get("source") or "installed"))
|
|
1830
|
+
self._json({"ok": True})
|
|
1831
|
+
return
|
|
1832
|
+
if act == "open-folder":
|
|
1833
|
+
p = panels.open_folder(str(data.get("which") or "installed"))
|
|
1834
|
+
self._json({"ok": True, "path": p})
|
|
1835
|
+
return
|
|
1836
|
+
if act == "upload":
|
|
1837
|
+
# 上传 = 把已安装面板剪切移动到市场目录;同名冲突 → 409
|
|
1838
|
+
r = panels.upload(str(data.get("name") or ""))
|
|
1839
|
+
self._json(r)
|
|
1840
|
+
return
|
|
1841
|
+
if act == "install":
|
|
1842
|
+
# 从市场安装(市场源复制保留);zip 形式现场解压校验
|
|
1843
|
+
r = panels.install(str(data.get("name") or ""))
|
|
1844
|
+
self._json(r)
|
|
1845
|
+
return
|
|
1846
|
+
self._json({"error": "action 只能是 activate / deactivate / delete / "
|
|
1847
|
+
"open-folder / upload / install"}, 400)
|
|
1848
|
+
except FileExistsError as exc:
|
|
1849
|
+
self._json({"error": f"{exc}(请改个名字后重试)"}, 409)
|
|
1850
|
+
except ValueError as exc:
|
|
1851
|
+
self._json({"error": str(exc)}, 400)
|
|
1852
|
+
except PermissionError as exc:
|
|
1853
|
+
self._json({"error": str(exc)}, 403)
|
|
1854
|
+
except Exception as exc:
|
|
1855
|
+
self._log_write_failure(f"panels {act}", exc, 500)
|
|
1856
|
+
self._json({"error": "面板操作失败,详情见运行日志"}, 500)
|
|
1857
|
+
|
|
1858
|
+
|
|
1859
|
+
|
|
1860
|
+
def _api_extensions(self, path, data):
|
|
1861
|
+
# 拓展商店操作:install=导出内置适配插件到 extensions/installed/
|
|
1862
|
+
act = str(data.get("action") or "")
|
|
1863
|
+
try:
|
|
1864
|
+
if act == "install":
|
|
1865
|
+
r = panels.export_extension(str(data.get("id") or ""))
|
|
1866
|
+
brain.log_event("panel", f"导出拓展 {r.get('id')} → {r.get('installed_dir')}")
|
|
1867
|
+
self._json(r)
|
|
1868
|
+
return
|
|
1869
|
+
if act == "open-folder":
|
|
1870
|
+
p = panels.open_folder("extensions")
|
|
1871
|
+
self._json({"ok": True, "path": p})
|
|
1872
|
+
return
|
|
1873
|
+
if act == "cloud-download":
|
|
1874
|
+
# 从云端商店拉 extensions/<id>.zip 单独下载安装(不拉整个仓库)
|
|
1875
|
+
r = panel_cloud.cloud_extension_download(str(data.get("id") or ""))
|
|
1876
|
+
brain.log_event("panel", f"云端下载拓展 {r.get('id')}")
|
|
1877
|
+
self._json(r)
|
|
1878
|
+
return
|
|
1879
|
+
self._json({"error": "action 只能是 install / cloud-download / open-folder"}, 400)
|
|
1880
|
+
except FileExistsError as exc:
|
|
1881
|
+
self._json({"error": str(exc)}, 409)
|
|
1882
|
+
except ValueError as exc:
|
|
1883
|
+
self._json({"error": str(exc)}, 400)
|
|
1884
|
+
except PermissionError as exc:
|
|
1885
|
+
self._json({"error": str(exc)}, 403)
|
|
1886
|
+
except Exception as exc:
|
|
1887
|
+
self._log_write_failure(f"extensions {act}", exc, 500)
|
|
1888
|
+
self._json({"error": "拓展操作失败,详情见运行日志"}, 500)
|
|
1889
|
+
|
|
1890
|
+
|
|
1891
|
+
|
|
1892
|
+
def _api_panels_cloud(self, path, data):
|
|
1893
|
+
# 云端市场操作:publish=发布到云端(可带截图 base64)、
|
|
1894
|
+
# download=从云端装到本机、save-config=配置 Gitee/GitHub 仓库与 token
|
|
1895
|
+
act = str(data.get("action") or "")
|
|
1896
|
+
try:
|
|
1897
|
+
if act == "publish":
|
|
1898
|
+
pname = str(data.get("name") or "")
|
|
1899
|
+
shot_b64 = str(data.get("screenshot") or "")
|
|
1900
|
+
shot = None
|
|
1901
|
+
ext = ".png"
|
|
1902
|
+
if shot_b64:
|
|
1903
|
+
if "," in shot_b64: # data:image/png;base64,xxx 前缀剥掉
|
|
1904
|
+
head, shot_b64 = shot_b64.split(",", 1)
|
|
1905
|
+
for e in (".png", ".jpg", ".jpeg", ".webp"):
|
|
1906
|
+
if e in head:
|
|
1907
|
+
ext = e
|
|
1908
|
+
break
|
|
1909
|
+
import base64 as _b64
|
|
1910
|
+
shot = _b64.b64decode(shot_b64)
|
|
1911
|
+
r = panel_cloud.cloud_publish(pname, shot, ext)
|
|
1912
|
+
self._json(r)
|
|
1913
|
+
return
|
|
1914
|
+
if act == "download":
|
|
1915
|
+
r = panel_cloud.cloud_download(str(data.get("name") or ""))
|
|
1916
|
+
self._json(r)
|
|
1917
|
+
return
|
|
1918
|
+
if act == "clear-config":
|
|
1919
|
+
r = panel_cloud.set_config(gitee_repo="", gitee_token="",
|
|
1920
|
+
github_repo="", github_token="")
|
|
1921
|
+
self._json(r)
|
|
1922
|
+
return
|
|
1923
|
+
if act == "save-config":
|
|
1924
|
+
r = panel_cloud.set_config(
|
|
1925
|
+
gitee_repo=str(data.get("gitee_repo") or ""),
|
|
1926
|
+
gitee_token=str(data.get("gitee_token") or ""),
|
|
1927
|
+
github_repo=str(data.get("github_repo") or ""),
|
|
1928
|
+
github_token=str(data.get("github_token") or ""),
|
|
1929
|
+
branch=str(data.get("branch") or ""))
|
|
1930
|
+
self._json(r)
|
|
1931
|
+
return
|
|
1932
|
+
self._json({"error": "action 只能是 publish / download / save-config / clear-config"}, 400)
|
|
1933
|
+
except ValueError as exc:
|
|
1934
|
+
self._json({"error": str(exc)}, 400)
|
|
1935
|
+
except PermissionError as exc:
|
|
1936
|
+
self._json({"error": str(exc)}, 403)
|
|
1937
|
+
except Exception as exc: # noqa: BLE001
|
|
1938
|
+
self._log_write_failure(f"panels cloud {act}", exc, 502)
|
|
1939
|
+
self._json({"error": str(exc) or "云端操作失败,详情见运行日志"}, 502)
|
|
1940
|
+
|
|
1941
|
+
|
|
1942
|
+
|
|
1943
|
+
def _api_panels_scaffold(self, path, data):
|
|
1944
|
+
# 生成最小面板骨架:方便 AI/用户起步(AI 创建自定义面板的落地入口)
|
|
1945
|
+
pname = str(data.get("name") or "").strip()
|
|
1946
|
+
ptitle = str(data.get("title") or "").strip()
|
|
1947
|
+
try:
|
|
1948
|
+
self._json(panels.scaffold(pname, ptitle))
|
|
1949
|
+
except FileExistsError as exc:
|
|
1950
|
+
self._json({"error": str(exc)}, 409)
|
|
1951
|
+
except ValueError as exc:
|
|
1952
|
+
self._json({"error": str(exc)}, 400)
|
|
1953
|
+
return
|
|
1954
|
+
|
|
1955
|
+
|
|
1956
|
+
# --------------------------------------------------------------- 扩展:Ollama 一键安装
|
|
1957
|
+
# 下载 URL 固定常量:绝不接受前端传入 URL,避免被当成任意下载代理滥用
|
|
1958
|
+
_OLLAMA_URL = "https://ollama.com/download/ollama-windows-amd64.zip"
|
|
1959
|
+
_OLLAMA_INSTALL_DIR = Path(os.environ.get("LOCALAPPDATA")
|
|
1960
|
+
or str(Path.home() / "AppData/Local")) / "Programs/Ollama"
|
|
1961
|
+
_OLLAMA_PORT = 11434
|
|
1962
|
+
_OLLAMA_MODEL = "nomic-embed-text"
|
|
1963
|
+
# 探测用地址写死 127.0.0.1,不要用 localhost:Windows 上 localhost 先解析成 ::1、
|
|
1964
|
+
# 失败再试 IPv4,端口没人听时每次探测要等满两倍超时才返回(实测 4.0s vs 2.0s)。
|
|
1965
|
+
# 面板打开「本地能力」页的第一屏就卡在这上面,所以这里只要 1 秒。
|
|
1966
|
+
_OLLAMA_PROBE_URL = f"http://127.0.0.1:{_OLLAMA_PORT}/api/tags"
|
|
1967
|
+
_OLLAMA_PROBE_TIMEOUT = 1.0
|
|
1968
|
+
|
|
1969
|
+
|
|
1970
|
+
def _ollama_state_path() -> Path:
|
|
1971
|
+
return brain.HOME / "downloads" / "ollama_state.json"
|
|
1972
|
+
|
|
1973
|
+
|
|
1974
|
+
def _ollama_zip_path() -> Path:
|
|
1975
|
+
return brain.HOME / "downloads" / "ollama-windows-amd64.zip"
|
|
1976
|
+
|
|
1977
|
+
|
|
1978
|
+
_OLLAMA_STATE_LOCK = threading.Lock() # state 文件多线程读写互斥(setup/download/probe/status 三处同时碰)
|
|
1979
|
+
_OLLAMA_DOWNLOAD_LOCK = threading.Lock() # 下载 zip 互斥:sync + async 不能同时写同一个文件
|
|
1980
|
+
|
|
1981
|
+
|
|
1982
|
+
# Ollama zip SHA256 清单(键 = 文件名,值 = 官方 hex)。ollama.com 版本更新后哈希会变,
|
|
1983
|
+
# 键匹配不上时不阻断(只 warn + 沿用启发式校验);键匹配上则必须严格比对。
|
|
1984
|
+
# 占位空 dict:官方发布页(github.com/ollama/ollama/releases)未公开稳定 sha256 清单,
|
|
1985
|
+
# 待维护者从 release 页核实后填入,如 "ollama-windows-amd64.zip": "<64位hex>"。
|
|
1986
|
+
_OLLAMA_ZIP_SHA256: dict = {}
|
|
1987
|
+
|
|
1988
|
+
_OLLAMA_ZIP_NAME = Path(_OLLAMA_URL).name
|
|
1989
|
+
|
|
1990
|
+
|
|
1991
|
+
def _ollama_validate_zip(path: Path) -> None:
|
|
1992
|
+
"""下载后校验:先比对 SHA256(清单里有该文件名时),再做启发式校验
|
|
1993
|
+
(拒绝半截 / 非 zip / 不含 ollama.exe 的归档)。"""
|
|
1994
|
+
expected = _OLLAMA_ZIP_SHA256.get(_OLLAMA_ZIP_NAME)
|
|
1995
|
+
if expected:
|
|
1996
|
+
h = hashlib.sha256()
|
|
1997
|
+
with open(path, "rb") as f:
|
|
1998
|
+
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
|
1999
|
+
h.update(chunk)
|
|
2000
|
+
actual = h.hexdigest()
|
|
2001
|
+
if actual.lower() != str(expected).lower():
|
|
2002
|
+
raise RuntimeError(f"zip SHA256 校验失败:期望 {expected},实际 {actual}")
|
|
2003
|
+
else:
|
|
2004
|
+
brain.log_event("ollama", f"{_OLLAMA_ZIP_NAME} 不在 SHA256 清单中,仅做启发式校验", level="warn")
|
|
2005
|
+
try:
|
|
2006
|
+
with zipfile.ZipFile(path) as zf:
|
|
2007
|
+
bad = zf.testzip()
|
|
2008
|
+
if bad is not None:
|
|
2009
|
+
raise RuntimeError(f"zip 内部成员损坏:{bad}")
|
|
2010
|
+
names = zf.namelist()
|
|
2011
|
+
exe_names = [n for n in names
|
|
2012
|
+
if n.lower().endswith("ollama.exe") and not n.endswith("/")]
|
|
2013
|
+
if not exe_names:
|
|
2014
|
+
raise RuntimeError("zip 内未找到 ollama.exe(可能非官方归档或已损坏)")
|
|
2015
|
+
# 顺手再扫一遍 zip slip(_ollama_safe_extractall 里也会扫,这里早失败早报警)
|
|
2016
|
+
dest_r = path.parent.resolve()
|
|
2017
|
+
for member in names:
|
|
2018
|
+
try:
|
|
2019
|
+
if not (path.parent / member).resolve().is_relative_to(dest_r):
|
|
2020
|
+
raise RuntimeError(f"zip 含越界路径:{member}")
|
|
2021
|
+
except RuntimeError:
|
|
2022
|
+
raise
|
|
2023
|
+
except Exception as exc:
|
|
2024
|
+
raise RuntimeError(f"zip 成员解析失败:{member}") from exc
|
|
2025
|
+
except RuntimeError:
|
|
2026
|
+
raise
|
|
2027
|
+
except zipfile.BadZipFile as exc:
|
|
2028
|
+
raise RuntimeError(f"zip 文件损坏:{exc}") from exc
|
|
2029
|
+
|
|
2030
|
+
|
|
2031
|
+
def _ollama_state_write(stage: str, **extra) -> None:
|
|
2032
|
+
"""分阶段状态落盘:前端轮询 /api/extensions/ollama/status 时读这份。
|
|
2033
|
+
阶段名(状态机):idle → downloading(带 percent) → downloaded
|
|
2034
|
+
→ extracting → starting → pulling → done;任何一步失败 → error(带 detail)。
|
|
2035
|
+
加锁防止 setup 并发时 write 半截 JSON 被 read 读到。"""
|
|
2036
|
+
try:
|
|
2037
|
+
with _OLLAMA_STATE_LOCK:
|
|
2038
|
+
p = _ollama_state_path()
|
|
2039
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
2040
|
+
payload = {"stage": stage, "ts": time.time()}
|
|
2041
|
+
payload.update(extra)
|
|
2042
|
+
brain.atomic_json(p, payload)
|
|
2043
|
+
except OSError:
|
|
2044
|
+
pass # 状态文件写失败只影响进度展示,不中断安装流程
|
|
2045
|
+
|
|
2046
|
+
|
|
2047
|
+
def _ollama_state_read() -> dict:
|
|
2048
|
+
try:
|
|
2049
|
+
with _OLLAMA_STATE_LOCK:
|
|
2050
|
+
obj = json.loads(_ollama_state_path().read_text(encoding="utf-8"))
|
|
2051
|
+
return obj if isinstance(obj, dict) else {}
|
|
2052
|
+
except (OSError, ValueError):
|
|
2053
|
+
return {}
|
|
2054
|
+
|
|
2055
|
+
|
|
2056
|
+
def _ollama_registry_dirs() -> list[Path]:
|
|
2057
|
+
"""从 Windows 注册表读 Ollama 的安装目录(Inno Setup 卸载项)。
|
|
2058
|
+
|
|
2059
|
+
Ollama 官方安装器(OllamaSetup.exe,含 /DIR=D:\\xxx 自定义盘符)用 Inno Setup,
|
|
2060
|
+
会把 InstallLocation / UninstallString 写进卸载注册表。这是发现"装在别的硬盘"
|
|
2061
|
+
最可靠的来源——官方 install.ps1 自己也用 Find-InnoSetupInstall 找它。
|
|
2062
|
+
非 Windows 或无 winreg 时静默返回空列表,不影响其它平台。
|
|
2063
|
+
"""
|
|
2064
|
+
out: list[Path] = []
|
|
2065
|
+
if os.name != "nt":
|
|
2066
|
+
return out
|
|
2067
|
+
try:
|
|
2068
|
+
import winreg # stdlib,仅 Windows
|
|
2069
|
+
except ImportError:
|
|
2070
|
+
return out
|
|
2071
|
+
roots = [
|
|
2072
|
+
(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Uninstall"),
|
|
2073
|
+
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\Uninstall"),
|
|
2074
|
+
(winreg.HKEY_LOCAL_MACHINE, r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"),
|
|
2075
|
+
]
|
|
2076
|
+
for hive, sub in roots:
|
|
2077
|
+
try:
|
|
2078
|
+
key = winreg.OpenKey(hive, sub)
|
|
2079
|
+
except OSError:
|
|
2080
|
+
continue
|
|
2081
|
+
i = 0
|
|
2082
|
+
while True:
|
|
2083
|
+
try:
|
|
2084
|
+
child_name = winreg.EnumKey(key, i)
|
|
2085
|
+
except OSError:
|
|
2086
|
+
break
|
|
2087
|
+
i += 1
|
|
2088
|
+
try:
|
|
2089
|
+
child = winreg.OpenKey(key, child_name)
|
|
2090
|
+
try:
|
|
2091
|
+
display, _ = winreg.QueryValueEx(child, "DisplayName")
|
|
2092
|
+
except OSError:
|
|
2093
|
+
continue
|
|
2094
|
+
if "ollama" not in str(display).lower():
|
|
2095
|
+
continue
|
|
2096
|
+
# 优先 InstallLocation;没有就从 UninstallString 里的 unins000.exe 反推目录
|
|
2097
|
+
loc = ""
|
|
2098
|
+
try:
|
|
2099
|
+
loc, _ = winreg.QueryValueEx(child, "InstallLocation")
|
|
2100
|
+
except OSError:
|
|
2101
|
+
pass
|
|
2102
|
+
if not loc:
|
|
2103
|
+
try:
|
|
2104
|
+
uninst, _ = winreg.QueryValueEx(child, "UninstallString")
|
|
2105
|
+
uninst = str(uninst).strip().strip('"')
|
|
2106
|
+
if uninst:
|
|
2107
|
+
loc = str(Path(uninst).parent)
|
|
2108
|
+
except OSError:
|
|
2109
|
+
pass
|
|
2110
|
+
if loc:
|
|
2111
|
+
p = Path(loc.strip().strip('"'))
|
|
2112
|
+
if p.is_dir():
|
|
2113
|
+
out.append(p)
|
|
2114
|
+
except OSError:
|
|
2115
|
+
continue
|
|
2116
|
+
finally:
|
|
2117
|
+
try:
|
|
2118
|
+
winreg.CloseKey(child)
|
|
2119
|
+
except Exception:
|
|
2120
|
+
pass
|
|
2121
|
+
try:
|
|
2122
|
+
winreg.CloseKey(key)
|
|
2123
|
+
except Exception:
|
|
2124
|
+
pass
|
|
2125
|
+
return out
|
|
2126
|
+
|
|
2127
|
+
|
|
2128
|
+
def _ollama_candidate_dirs() -> list[Path]:
|
|
2129
|
+
"""所有可能的 ollama.exe 所在目录,按可信度排序(去重)。"""
|
|
2130
|
+
dirs: list[Path] = []
|
|
2131
|
+
# 1) 显式环境变量(用户/安装脚本指定的自定义位置,最高优先级)
|
|
2132
|
+
env_dir = os.environ.get("OLLAMA_INSTALL_DIR")
|
|
2133
|
+
if env_dir and Path(env_dir).is_dir():
|
|
2134
|
+
dirs.append(Path(env_dir))
|
|
2135
|
+
# 2) 注册表 Inno Setup(能找到 /DIR= 自定义盘符的安装)
|
|
2136
|
+
dirs.extend(_ollama_registry_dirs())
|
|
2137
|
+
# 3) 默认安装目录
|
|
2138
|
+
dirs.append(_OLLAMA_INSTALL_DIR)
|
|
2139
|
+
# 4) 常见非默认位置兜底(用户手动搬过、注册表又没写的情况)
|
|
2140
|
+
for base in (Path("C:\\"), Path("D:\\"), Path("E:\\")):
|
|
2141
|
+
for rel in ("Ollama", "Program Files\\Ollama", "Program Files (x86)\\Ollama"):
|
|
2142
|
+
dirs.append(base / rel)
|
|
2143
|
+
# 去重保序
|
|
2144
|
+
seen: set[str] = set()
|
|
2145
|
+
uniq: list[Path] = []
|
|
2146
|
+
for d in dirs:
|
|
2147
|
+
k = str(d).lower().rstrip("\\/")
|
|
2148
|
+
if k and k not in seen:
|
|
2149
|
+
seen.add(k)
|
|
2150
|
+
uniq.append(d)
|
|
2151
|
+
return uniq
|
|
2152
|
+
|
|
2153
|
+
|
|
2154
|
+
def _ollama_exe() -> Path | None:
|
|
2155
|
+
"""找 ollama.exe(多来源,兼容装在别的硬盘)。
|
|
2156
|
+
|
|
2157
|
+
优先级:PATH(where.exe)→ OLLAMA_INSTALL_DIR 环境变量 → 注册表 Inno Setup
|
|
2158
|
+
→ 默认目录 → 常见非默认路径。原来只查 PATH + 默认目录,装在 D:/E: 盘且没进
|
|
2159
|
+
PATH 时就误报"未安装",即使用户已经装好了。
|
|
2160
|
+
"""
|
|
2161
|
+
try:
|
|
2162
|
+
out = subprocess.run(["where.exe", "ollama"], capture_output=True,
|
|
2163
|
+
text=True, encoding="utf-8", errors="replace", timeout=5).stdout.strip()
|
|
2164
|
+
first = out.splitlines()[0].strip() if out else ""
|
|
2165
|
+
if first.lower().endswith(".exe") and Path(first).is_file():
|
|
2166
|
+
return Path(first)
|
|
2167
|
+
except Exception:
|
|
2168
|
+
pass
|
|
2169
|
+
for d in _ollama_candidate_dirs():
|
|
2170
|
+
exe = d / "ollama.exe"
|
|
2171
|
+
if exe.is_file():
|
|
2172
|
+
return exe
|
|
2173
|
+
return None
|
|
2174
|
+
|
|
2175
|
+
|
|
2176
|
+
def _ollama_probe() -> tuple[bool, set]:
|
|
2177
|
+
"""一次探测 11434:返回 (服务是否在跑, 已拉取的模型名集合)。
|
|
2178
|
+
|
|
2179
|
+
只发一次 HTTP:以前 status 里 serving / model_ready 各探一次、外加一个独立
|
|
2180
|
+
`/api/tags` 读取,本地没起 Ollama 时三连超时,面板「本地能力」要等 8 秒才出结果。
|
|
2181
|
+
连接失败和“起来了但没模型”必须区分开,所以用返回值而不是空列表表达。
|
|
2182
|
+
"""
|
|
2183
|
+
try:
|
|
2184
|
+
with urllib.request.urlopen(_OLLAMA_PROBE_URL,
|
|
2185
|
+
timeout=_OLLAMA_PROBE_TIMEOUT) as resp:
|
|
2186
|
+
if resp.status != 200:
|
|
2187
|
+
return False, set()
|
|
2188
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
2189
|
+
names = {str(m.get("name") or "") for m in data.get("models") or []}
|
|
2190
|
+
return True, names
|
|
2191
|
+
except Exception:
|
|
2192
|
+
return False, set()
|
|
2193
|
+
|
|
2194
|
+
|
|
2195
|
+
def _ollama_serving() -> bool:
|
|
2196
|
+
"""11434 是否已有服务在跑(1 秒超时)。"""
|
|
2197
|
+
return _ollama_probe()[0]
|
|
2198
|
+
|
|
2199
|
+
|
|
2200
|
+
def _ollama_tags() -> list:
|
|
2201
|
+
try:
|
|
2202
|
+
with urllib.request.urlopen(_OLLAMA_PROBE_URL,
|
|
2203
|
+
timeout=_OLLAMA_PROBE_TIMEOUT) as resp:
|
|
2204
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
2205
|
+
return [str(m.get("name") or "") for m in data.get("models") or []]
|
|
2206
|
+
except Exception:
|
|
2207
|
+
return []
|
|
2208
|
+
|
|
2209
|
+
|
|
2210
|
+
def _ollama_model_names() -> set:
|
|
2211
|
+
"""已拉取的模型名集合(精确匹配,避免子串误判)。"""
|
|
2212
|
+
return _ollama_probe()[1]
|
|
2213
|
+
|
|
2214
|
+
|
|
2215
|
+
def _ollama_safe_extractall(zf: zipfile.ZipFile, dest: Path) -> None:
|
|
2216
|
+
"""解压 zip 到 dest,拒绝 zip slip(成员名含 ../ 或绝对路径一律抛异常)。
|
|
2217
|
+
照搬 growth.py 同款防护逻辑。"""
|
|
2218
|
+
dest_r = dest.resolve()
|
|
2219
|
+
for member in zf.namelist():
|
|
2220
|
+
try:
|
|
2221
|
+
p = (dest / member).resolve()
|
|
2222
|
+
except Exception as exc:
|
|
2223
|
+
raise RuntimeError(f"zip 归档含非法成员名:{member}") from exc
|
|
2224
|
+
if not p.is_relative_to(dest_r):
|
|
2225
|
+
raise RuntimeError(f"zip 归档含越界路径成员:{member}")
|
|
2226
|
+
zf.extractall(dest)
|
|
2227
|
+
|
|
2228
|
+
|
|
2229
|
+
def _ollama_embed_configured() -> bool:
|
|
2230
|
+
try:
|
|
2231
|
+
embed = brain.load_config().get("embed") or {}
|
|
2232
|
+
return ("11434" in str(embed.get("url") or "")
|
|
2233
|
+
and str(embed.get("model") or "") == _OLLAMA_MODEL)
|
|
2234
|
+
except Exception:
|
|
2235
|
+
return False
|
|
2236
|
+
|
|
2237
|
+
|
|
2238
|
+
def _fallback_embed_enabled() -> bool:
|
|
2239
|
+
try:
|
|
2240
|
+
import fallback_embed
|
|
2241
|
+
return fallback_embed.cfg() is not None
|
|
2242
|
+
except Exception:
|
|
2243
|
+
return False
|
|
2244
|
+
|
|
2245
|
+
|
|
2246
|
+
def ollama_status() -> dict:
|
|
2247
|
+
"""状态汇总(GET):installed/serving/model_ready/embed_configured + 下载安装进度。
|
|
2248
|
+
附带降级向量兜底(fallback_embed)开关状态:无 Ollama 时语义召回靠它兜底。"""
|
|
2249
|
+
state = _ollama_state_read()
|
|
2250
|
+
# 只探一次 11434:serving 与 model_ready 共用同一次结果(见 _ollama_probe)
|
|
2251
|
+
serving, models = _ollama_probe()
|
|
2252
|
+
exe = _ollama_exe()
|
|
2253
|
+
# v3.65:`ollama list` 里是 `nomic-embed-text:latest`,而 _OLLAMA_MODEL 不带 tag,
|
|
2254
|
+
# 精确匹配永远 False。比较时去掉 :tag 后缀(无 tag 视为 :latest)。
|
|
2255
|
+
def _bare(name: str) -> str:
|
|
2256
|
+
return name.split(":", 1)[0] if name else ""
|
|
2257
|
+
model_ready = any(_bare(m) == _bare(_OLLAMA_MODEL) for m in models)
|
|
2258
|
+
st = {
|
|
2259
|
+
"ok": True,
|
|
2260
|
+
"installed": exe is not None,
|
|
2261
|
+
"exe_path": str(exe) if exe else "", # v3.65:让用户看到"在哪发现的",便于核对非默认盘
|
|
2262
|
+
"serving": serving,
|
|
2263
|
+
"model_ready": model_ready,
|
|
2264
|
+
"embed_configured": _ollama_embed_configured(),
|
|
2265
|
+
"zip_exists": _ollama_zip_path().is_file(),
|
|
2266
|
+
"stage": str(state.get("stage") or "idle"),
|
|
2267
|
+
"percent": int(state.get("percent") or 0),
|
|
2268
|
+
"detail": str(state.get("detail") or ""),
|
|
2269
|
+
}
|
|
2270
|
+
st["fallback_enabled"] = _fallback_embed_enabled()
|
|
2271
|
+
# 语义召回综合状态:Ollama 就绪(服务+模型+已接入)或降级兜底开启,都算可用
|
|
2272
|
+
st["semantic_ready"] = (
|
|
2273
|
+
st["serving"] and st["model_ready"] and st["embed_configured"]
|
|
2274
|
+
) or st["fallback_enabled"]
|
|
2275
|
+
return st
|
|
2276
|
+
|
|
2277
|
+
|
|
2278
|
+
def _api_ollama_enable(self, path, data):
|
|
2279
|
+
"""自动探测接管:Ollama 已在跑但没接入灵枢时,一键写好 embed 配置。
|
|
2280
|
+
模型没拉则先拉(同步,拉模型耗时可观但属于用户显式点按钮)。"""
|
|
2281
|
+
try:
|
|
2282
|
+
if not _ollama_serving():
|
|
2283
|
+
self._json({"ok": False, "error": "Ollama 服务未运行(11434 无响应)"}, 400)
|
|
2284
|
+
return
|
|
2285
|
+
# v3.65:去掉 :tag 比较,避免 `nomic-embed-text:latest` 被误判成没拉
|
|
2286
|
+
if not any(m.split(":", 1)[0] == _OLLAMA_MODEL.split(":", 1)[0]
|
|
2287
|
+
for m in _ollama_model_names()):
|
|
2288
|
+
if not _ollama_pull_model():
|
|
2289
|
+
self._json({"ok": False, "error": f"模型 {_OLLAMA_MODEL} 拉取失败"}, 502)
|
|
2290
|
+
return
|
|
2291
|
+
cfg = brain.load_config()
|
|
2292
|
+
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2293
|
+
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2294
|
+
embed["model"] = _OLLAMA_MODEL
|
|
2295
|
+
cfg["embed"] = embed
|
|
2296
|
+
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2297
|
+
self._json({"ok": True, "stage": "done"})
|
|
2298
|
+
except Exception as exc:
|
|
2299
|
+
self._log_write_failure("ollama enable", exc, 500)
|
|
2300
|
+
self._json({"ok": False, "error": "接入失败,详情见运行日志"}, 500)
|
|
2301
|
+
|
|
2302
|
+
|
|
2303
|
+
def _api_ollama_setup(self, path, data):
|
|
2304
|
+
"""一键开启向量记忆(v2.99 ②):串联「已装跳过 → 未装复用 download/install
|
|
2305
|
+
→ 起 serve → 拉模型 → 写 embed 配置」。所有长耗时步骤都丢进后台线程,
|
|
2306
|
+
HTTP 只负责启动任务并立即返回(前端轮询 status 看进度,规避 15s 超时)。"""
|
|
2307
|
+
try:
|
|
2308
|
+
# 幂等:上一轮流水线还在飞就直接拒绝,避免两个线程同时 pull/写 config
|
|
2309
|
+
stage = str(_ollama_state_read().get("stage") or "idle")
|
|
2310
|
+
if stage in ("downloading", "extracting", "starting", "pulling"):
|
|
2311
|
+
self._json({"ok": True, "already": True, "stage": stage})
|
|
2312
|
+
return
|
|
2313
|
+
threading.Thread(target=_ollama_setup_async,
|
|
2314
|
+
name="ollama-setup", daemon=True).start()
|
|
2315
|
+
self._json({"ok": True, "stage": "started"})
|
|
2316
|
+
except Exception as exc:
|
|
2317
|
+
self._log_write_failure("ollama setup", exc, 500)
|
|
2318
|
+
self._json({"ok": False, "error": "一键任务启动失败,详情见运行日志"}, 500)
|
|
2319
|
+
|
|
2320
|
+
|
|
2321
|
+
def _ollama_setup_async() -> None:
|
|
2322
|
+
"""一键流水线(后台线程):每一步前先探测,能用现成的绝不重复折腾。"""
|
|
2323
|
+
try:
|
|
2324
|
+
# ① 已装 Ollama → 跳过下载/解压;未装但 zip 已在 → 只解压;都没有 → 先下载
|
|
2325
|
+
if _ollama_exe() is None:
|
|
2326
|
+
zip_path = _ollama_zip_path()
|
|
2327
|
+
if not zip_path.is_file():
|
|
2328
|
+
_ollama_state_write("downloading", percent=0, detail="下载 Ollama(约1GB)")
|
|
2329
|
+
_ollama_download_sync()
|
|
2330
|
+
if not _ollama_zip_path().is_file():
|
|
2331
|
+
_ollama_state_write("error", detail="Ollama 下载失败(网络问题),降级向量兜底仍在生效")
|
|
2332
|
+
return
|
|
2333
|
+
_ollama_state_write("extracting", detail="解压到程序目录")
|
|
2334
|
+
_OLLAMA_INSTALL_DIR.mkdir(parents=True, exist_ok=True)
|
|
2335
|
+
with zipfile.ZipFile(_ollama_zip_path()) as zf:
|
|
2336
|
+
_ollama_safe_extractall(zf, _OLLAMA_INSTALL_DIR)
|
|
2337
|
+
if _ollama_exe() is None:
|
|
2338
|
+
_ollama_state_write("error", detail="解压后找不到 ollama.exe")
|
|
2339
|
+
return
|
|
2340
|
+
# ② 确保 serve 在跑(已在跑则 _ollama_start_serve 直接返回 True)
|
|
2341
|
+
_ollama_state_write("starting", detail="启动 ollama serve")
|
|
2342
|
+
if not _ollama_start_serve():
|
|
2343
|
+
_ollama_state_write("error", detail="ollama serve 启动失败(可稍后在面板重试)")
|
|
2344
|
+
return
|
|
2345
|
+
# ③ 拉模型(tags 里已有 → 跳过,避免重复下载)
|
|
2346
|
+
if _OLLAMA_MODEL not in _ollama_model_names():
|
|
2347
|
+
_ollama_state_write("pulling", detail=f"拉取模型 {_OLLAMA_MODEL}(首次较慢)")
|
|
2348
|
+
if not _ollama_pull_model():
|
|
2349
|
+
_ollama_state_write("error", detail=f"模型 {_OLLAMA_MODEL} 拉取失败(网络或磁盘问题)")
|
|
2350
|
+
return
|
|
2351
|
+
# ④ 写 embed 配置启用向量(与 enable/install 同款读-改-写)
|
|
2352
|
+
cfg = brain.load_config()
|
|
2353
|
+
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2354
|
+
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2355
|
+
embed["model"] = _OLLAMA_MODEL
|
|
2356
|
+
cfg["embed"] = embed
|
|
2357
|
+
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2358
|
+
_ollama_state_write("done", percent=100, detail="语义召回已就绪(真模型向量)")
|
|
2359
|
+
except Exception as exc:
|
|
2360
|
+
_ollama_state_write("error", detail=f"一键流程失败:{exc}")
|
|
2361
|
+
|
|
2362
|
+
|
|
2363
|
+
def _ollama_download(dest: Path, on_progress=None) -> None:
|
|
2364
|
+
"""共享下载实现:流式分块写盘 + 进度回调 + 下载完立即校验(坏的就删掉防误装)。
|
|
2365
|
+
on_progress(percent, got_mb) 由调用方决定进度去向(sync 写 state、async 也写 state)。
|
|
2366
|
+
异常时删掉半截文件并 raise,调用方负责状态落盘与锁。"""
|
|
2367
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
2368
|
+
req = urllib.request.Request(_OLLAMA_URL,
|
|
2369
|
+
headers={"User-Agent": "lingshu-panel"})
|
|
2370
|
+
try:
|
|
2371
|
+
with urllib.request.urlopen(req, timeout=60) as resp, open(dest, "wb") as f:
|
|
2372
|
+
total = int(resp.headers.get("Content-Length") or 0)
|
|
2373
|
+
got = 0
|
|
2374
|
+
while True:
|
|
2375
|
+
chunk = resp.read(1024 * 256)
|
|
2376
|
+
if not chunk:
|
|
2377
|
+
break
|
|
2378
|
+
f.write(chunk)
|
|
2379
|
+
got += len(chunk)
|
|
2380
|
+
pct = int(got * 100 / total) if total > 0 else 0
|
|
2381
|
+
if on_progress:
|
|
2382
|
+
on_progress(pct, got // (1024 * 1024))
|
|
2383
|
+
_ollama_validate_zip(dest) # 下载完立即校验(坏的就删掉防误装)
|
|
2384
|
+
except Exception:
|
|
2385
|
+
try:
|
|
2386
|
+
dest.unlink(missing_ok=True) # 半截 zip / 校验失败 → 删掉防误装
|
|
2387
|
+
except OSError:
|
|
2388
|
+
pass
|
|
2389
|
+
raise
|
|
2390
|
+
|
|
2391
|
+
|
|
2392
|
+
def _ollama_download_run(quiet_busy: bool = False) -> None:
|
|
2393
|
+
"""下载主流程(#5 重构:sync/async 共用,不再两份重复代码)。
|
|
2394
|
+
持 _OLLAMA_DOWNLOAD_LOCK 防两个线程同时写同一个 zip;
|
|
2395
|
+
锁被占用时 quiet_busy=True(setup 线程里静默退出),
|
|
2396
|
+
False(面板触发)写状态提示等待复用现有 zip。
|
|
2397
|
+
在调用者所在线程内阻塞执行——调用方决定是否丢进后台线程。"""
|
|
2398
|
+
dest = _ollama_zip_path()
|
|
2399
|
+
if not _OLLAMA_DOWNLOAD_LOCK.acquire(blocking=False):
|
|
2400
|
+
if quiet_busy:
|
|
2401
|
+
return # 另一个线程在下,不重复下载
|
|
2402
|
+
_ollama_state_write("downloading", detail="已有下载在进行中,等待复用现有 zip")
|
|
2403
|
+
return
|
|
2404
|
+
try:
|
|
2405
|
+
_ollama_download(dest, on_progress=lambda pct, mb: _ollama_state_write(
|
|
2406
|
+
"downloading", percent=pct, detail=f"{mb}MB"))
|
|
2407
|
+
_ollama_state_write("downloaded", percent=100, detail=str(dest))
|
|
2408
|
+
except Exception as exc:
|
|
2409
|
+
_ollama_state_write("error", detail=f"下载失败:{exc}")
|
|
2410
|
+
finally:
|
|
2411
|
+
_OLLAMA_DOWNLOAD_LOCK.release()
|
|
2412
|
+
|
|
2413
|
+
|
|
2414
|
+
def _ollama_download_sync() -> None:
|
|
2415
|
+
"""同步下载 zip(只在 setup 后台线程里调)。"""
|
|
2416
|
+
_ollama_download_run(quiet_busy=True)
|
|
2417
|
+
|
|
2418
|
+
|
|
2419
|
+
def _ollama_download_async() -> None:
|
|
2420
|
+
"""后台线程流式下载 zip,进度写状态文件(约 1GB,绝不阻塞 HTTP 线程)。"""
|
|
2421
|
+
threading.Thread(target=_ollama_download_run, name="ollama-download",
|
|
2422
|
+
daemon=True).start()
|
|
2423
|
+
|
|
2424
|
+
|
|
2425
|
+
# --------------------------------------------------------------- ① 自动探测接管
|
|
2426
|
+
# 面板启动/状态轮询时静默探测 127.0.0.1:11434:本机已有 Ollama 在跑 → 无感接入;
|
|
2427
|
+
# 在跑但模型没拉 → 后台自动 pull(只拉一次);探测失败(没装/没跑)→ 静默退出,
|
|
2428
|
+
# 降级向量兜底照常工作,绝不弹窗、绝不阻塞、绝不报错打扰用户。
|
|
2429
|
+
_AUTO_PROBE_STATE = {"pulled": False, "lock": threading.Lock()}
|
|
2430
|
+
|
|
2431
|
+
|
|
2432
|
+
def _ollama_auto_probe() -> None:
|
|
2433
|
+
"""一次探测接管(探测 + 后台 pull + 写 config)。任何异常吞掉,不留痕也不崩。"""
|
|
2434
|
+
if not _AUTO_PROBE_STATE["lock"].acquire(blocking=False):
|
|
2435
|
+
return # 已有探测在飞:不重复,也不排队
|
|
2436
|
+
try:
|
|
2437
|
+
if not _ollama_serving():
|
|
2438
|
+
return # 没装/没跑:静默退出,降级向量兜底照常
|
|
2439
|
+
# 服务在跑但灵枢还没接入 → 接管写配置
|
|
2440
|
+
if not _ollama_embed_configured():
|
|
2441
|
+
if _OLLAMA_MODEL in _ollama_model_names():
|
|
2442
|
+
cfg = brain.load_config()
|
|
2443
|
+
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2444
|
+
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2445
|
+
embed["model"] = _OLLAMA_MODEL
|
|
2446
|
+
cfg["embed"] = embed
|
|
2447
|
+
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2448
|
+
return
|
|
2449
|
+
# 模型没拉:整个生命周期只自动 pull 一次(避免反复打扰/重复下载)
|
|
2450
|
+
if _AUTO_PROBE_STATE["pulled"]:
|
|
2451
|
+
return
|
|
2452
|
+
_AUTO_PROBE_STATE["pulled"] = True
|
|
2453
|
+
if _ollama_pull_model():
|
|
2454
|
+
cfg = brain.load_config()
|
|
2455
|
+
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2456
|
+
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2457
|
+
embed["model"] = _OLLAMA_MODEL
|
|
2458
|
+
cfg["embed"] = embed
|
|
2459
|
+
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2460
|
+
except Exception:
|
|
2461
|
+
pass # 探测接管是锦上添花:任何失败都静默,降级兜底照常
|
|
2462
|
+
finally:
|
|
2463
|
+
_AUTO_PROBE_STATE["lock"].release()
|
|
2464
|
+
|
|
2465
|
+
|
|
2466
|
+
def _ollama_auto_probe_async() -> None:
|
|
2467
|
+
"""后台线程跑探测:绝不阻塞 HTTP 请求(探测失败还会等 2s 网络超时)。"""
|
|
2468
|
+
try:
|
|
2469
|
+
threading.Thread(target=_ollama_auto_probe,
|
|
2470
|
+
name="ollama-auto-probe", daemon=True).start()
|
|
2471
|
+
except Exception:
|
|
2472
|
+
pass
|
|
2473
|
+
|
|
2474
|
+
|
|
2475
|
+
def _ollama_start_serve() -> bool:
|
|
2476
|
+
"""启动 ollama serve(DETACHED);端口已被占用(服务已在跑)则直接算成功。"""
|
|
2477
|
+
if _ollama_serving():
|
|
2478
|
+
return True
|
|
2479
|
+
exe = _ollama_exe()
|
|
2480
|
+
if exe is None:
|
|
2481
|
+
return False
|
|
2482
|
+
# DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP:脱离面板进程,面板关了它也不死
|
|
2483
|
+
flags = 0x00000008 | 0x00000200
|
|
2484
|
+
subprocess.Popen([str(exe), "serve"], creationflags=flags,
|
|
2485
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
2486
|
+
stdin=subprocess.DEVNULL, close_fds=True)
|
|
2487
|
+
for _ in range(20): # 最多等 10 秒,轮询 tags 而不是死等固定时间
|
|
2488
|
+
if _ollama_serving():
|
|
2489
|
+
return True
|
|
2490
|
+
time.sleep(0.5)
|
|
2491
|
+
return False
|
|
2492
|
+
|
|
2493
|
+
|
|
2494
|
+
def _ollama_pull_model() -> bool:
|
|
2495
|
+
"""ollama pull nomic-embed-text(首次下载模型可能要几分钟,超时 600s)。
|
|
2496
|
+
CREATE_NO_WINDOW:面板进程拉模型不弹黑窗(Windows 控制台程序默认会开窗)。"""
|
|
2497
|
+
try:
|
|
2498
|
+
exe = _ollama_exe()
|
|
2499
|
+
if exe is None:
|
|
2500
|
+
return False
|
|
2501
|
+
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
|
|
2502
|
+
r = subprocess.run([str(exe), "pull", _OLLAMA_MODEL], capture_output=True,
|
|
2503
|
+
text=True, encoding="utf-8", errors="replace", timeout=600, creationflags=flags)
|
|
2504
|
+
return r.returncode == 0
|
|
2505
|
+
except Exception:
|
|
2506
|
+
return False
|
|
2507
|
+
|
|
2508
|
+
|
|
2509
|
+
def _ollama_install_async() -> None:
|
|
2510
|
+
"""后台安装流水线:解压 → 起 serve → 拉模型 → 写 embed 配置 → done。"""
|
|
2511
|
+
try:
|
|
2512
|
+
zip_path = _ollama_zip_path()
|
|
2513
|
+
if not zip_path.is_file():
|
|
2514
|
+
_ollama_state_write("error", detail="zip 不存在,请先下载")
|
|
2515
|
+
return
|
|
2516
|
+
_ollama_state_write("extracting", detail="解压到程序目录")
|
|
2517
|
+
_OLLAMA_INSTALL_DIR.mkdir(parents=True, exist_ok=True)
|
|
2518
|
+
with zipfile.ZipFile(zip_path) as zf:
|
|
2519
|
+
_ollama_safe_extractall(zf, _OLLAMA_INSTALL_DIR)
|
|
2520
|
+
if _ollama_exe() is None:
|
|
2521
|
+
_ollama_state_write("error", detail="解压后找不到 ollama.exe")
|
|
2522
|
+
return
|
|
2523
|
+
_ollama_state_write("starting", detail="启动 ollama serve")
|
|
2524
|
+
if not _ollama_start_serve():
|
|
2525
|
+
_ollama_state_write("error", detail="ollama serve 启动失败(进程异常,可稍后手动重试)")
|
|
2526
|
+
return
|
|
2527
|
+
_ollama_state_write("pulling", detail=f"拉取模型 {_OLLAMA_MODEL}(首次较慢)")
|
|
2528
|
+
if not _ollama_pull_model():
|
|
2529
|
+
_ollama_state_write("error", detail=f"模型 {_OLLAMA_MODEL} 拉取失败(网络或磁盘问题)")
|
|
2530
|
+
return
|
|
2531
|
+
# 写 embed 配置:config_set 是扁平键,embed 是嵌套对象,读-改-写整段 config.json
|
|
2532
|
+
cfg = brain.load_config()
|
|
2533
|
+
embed = cfg.get("embed") if isinstance(cfg.get("embed"), dict) else {}
|
|
2534
|
+
embed["url"] = f"http://localhost:{_OLLAMA_PORT}/api/embeddings"
|
|
2535
|
+
embed["model"] = _OLLAMA_MODEL
|
|
2536
|
+
cfg["embed"] = embed
|
|
2537
|
+
brain.atomic_json(brain.HOME / "config.json", cfg)
|
|
2538
|
+
_ollama_state_write("done", percent=100, detail="语义召回已就绪")
|
|
2539
|
+
except Exception as exc:
|
|
2540
|
+
_ollama_state_write("error", detail=f"安装失败:{exc}")
|
|
2541
|
+
|
|
2542
|
+
|
|
2543
|
+
def _api_ollama_status(self, path, data):
|
|
2544
|
+
self._json(ollama_status())
|
|
2545
|
+
|
|
2546
|
+
|
|
2547
|
+
def _api_ollama_download(self, path, data):
|
|
2548
|
+
try:
|
|
2549
|
+
if _ollama_serving():
|
|
2550
|
+
# 服务已在跑就不必再折腾 zip:跳到安装/配置阶段
|
|
2551
|
+
self._json({"ok": True, "skipped": True, "stage": "serving"})
|
|
2552
|
+
return
|
|
2553
|
+
if _ollama_zip_path().is_file():
|
|
2554
|
+
self._json({"ok": True, "skipped": True, "stage": "downloaded"})
|
|
2555
|
+
return
|
|
2556
|
+
if _ollama_state_read().get("stage") == "downloading":
|
|
2557
|
+
self._json({"ok": True, "skipped": True, "stage": "downloading"})
|
|
2558
|
+
return
|
|
2559
|
+
threading.Thread(target=_ollama_download_async,
|
|
2560
|
+
name="ollama-download", daemon=True).start()
|
|
2561
|
+
self._json({"ok": True, "stage": "downloading"})
|
|
2562
|
+
except Exception as exc:
|
|
2563
|
+
self._log_write_failure("ollama download", exc, 500)
|
|
2564
|
+
self._json({"ok": False, "error": "下载任务启动失败,详情见运行日志"}, 500)
|
|
2565
|
+
|
|
2566
|
+
|
|
2567
|
+
def _api_ollama_install(self, path, data):
|
|
2568
|
+
try:
|
|
2569
|
+
if not _ollama_zip_path().is_file() and _ollama_exe() is None:
|
|
2570
|
+
self._json({"ok": False, "error": "尚未下载 Ollama,请先点「下载安装」"}, 400)
|
|
2571
|
+
return
|
|
2572
|
+
threading.Thread(target=_ollama_install_async,
|
|
2573
|
+
name="ollama-install", daemon=True).start()
|
|
2574
|
+
self._json({"ok": True, "stage": "extracting"})
|
|
2575
|
+
except Exception as exc:
|
|
2576
|
+
self._log_write_failure("ollama install", exc, 500)
|
|
2577
|
+
self._json({"ok": False, "error": "安装任务启动失败,详情见运行日志"}, 500)
|
|
2578
|
+
|
|
2579
|
+
|
|
2580
|
+
# POST 分发表:路由 -> Handler 处理方法(参数统一为 handler(self, path, data))
|
|
2581
|
+
# 按路由家族分组:首页/记忆写入 → 人格/心智/情绪 → 关联/整理/模式 → 做梦
|
|
2582
|
+
# → 记忆管理/知识/笔记 → 技能/种子 → 日志 → 面板与拓展商店 → 扩展(Ollama)
|
|
2583
|
+
_POST_ROUTES = {
|
|
2584
|
+
# 首页与记忆写入
|
|
2585
|
+
"/api/home/migrate": _api_home_migrate,
|
|
2586
|
+
"/api/remember": _api_remember,
|
|
2587
|
+
# 人格 / 心智 / 情绪
|
|
2588
|
+
"/api/persona": _api_persona_update,
|
|
2589
|
+
"/api/persona/changes-viewed": _api_persona_changes_viewed,
|
|
2590
|
+
"/api/persona/suggest": _api_persona_suggest,
|
|
2591
|
+
"/api/persona/state": _api_persona_state,
|
|
2592
|
+
"/api/persona/edit": _api_persona_edit,
|
|
2593
|
+
"/api/persona/mind": _api_persona_mind,
|
|
2594
|
+
"/api/persona/interview": _api_persona_interview,
|
|
2595
|
+
"/api/persona/self": _api_persona_self,
|
|
2596
|
+
"/api/persona/rollback": _api_persona_rollback,
|
|
2597
|
+
"/api/persona/snapshots/rollback": _api_persona_snapshot_rollback,
|
|
2598
|
+
"/api/mind/weigh": _api_mind_weigh,
|
|
2599
|
+
"/api/emotion": _api_emotion,
|
|
2600
|
+
# 关联 / 整理 / 模式
|
|
2601
|
+
"/api/link": _api_link,
|
|
2602
|
+
"/api/daily": _api_daily,
|
|
2603
|
+
"/api/evolve": _api_evolve,
|
|
2604
|
+
"/api/mode": _api_mode,
|
|
2605
|
+
# 做梦
|
|
2606
|
+
"/api/dream": _api_dream,
|
|
2607
|
+
"/api/dream/auto": _api_dream_auto,
|
|
2608
|
+
"/api/dream/instruction": _api_dream_instruction,
|
|
2609
|
+
"/api/dream/apply": _api_dream_apply,
|
|
2610
|
+
"/api/dream/draft": _api_dream_draft,
|
|
2611
|
+
# 记忆管理 / 知识 / 笔记
|
|
2612
|
+
"/api/memory": _api_memory_edit,
|
|
2613
|
+
"/api/forget": _api_forget,
|
|
2614
|
+
"/api/diagnostics/fix-links": _api_diag_fix_links,
|
|
2615
|
+
"/api/memory/dust": _api_memory_dust,
|
|
2616
|
+
"/api/memory/purge": _api_memory_purge,
|
|
2617
|
+
"/api/memory/review": _api_memory_review,
|
|
2618
|
+
"/api/memory/bulk": _api_memory_bulk,
|
|
2619
|
+
"/api/memory/boost": _api_memory_boost,
|
|
2620
|
+
"/api/memory/rebuild-embeds": _api_memory_rebuild_embeds,
|
|
2621
|
+
"/api/knowledge": _api_knowledge,
|
|
2622
|
+
"/api/note": _api_note,
|
|
2623
|
+
# 技能 / 种子
|
|
2624
|
+
"/api/skill": _api_skill,
|
|
2625
|
+
"/api/skill/self-review": _api_skill_self_review,
|
|
2626
|
+
"/api/skill/dsh-repair": _api_skill_dsh_repair,
|
|
2627
|
+
"/api/skill/dsh-force-update": _api_skill_dsh_force_update,
|
|
2628
|
+
"/api/seed": _api_seed,
|
|
2629
|
+
# 日志
|
|
2630
|
+
"/api/logs": _api_logs_post,
|
|
2631
|
+
# 面板与拓展商店
|
|
2632
|
+
"/api/panels": _api_panels,
|
|
2633
|
+
"/api/panels/cloud": _api_panels_cloud,
|
|
2634
|
+
"/api/panels/scaffold": _api_panels_scaffold,
|
|
2635
|
+
"/api/extensions": _api_extensions,
|
|
2636
|
+
# 扩展:Ollama 一键下载/安装(下载 URL 固定在服务端,不接受外部传入)
|
|
2637
|
+
"/api/extensions/ollama/status": _api_ollama_status,
|
|
2638
|
+
"/api/extensions/ollama/download": _api_ollama_download,
|
|
2639
|
+
"/api/extensions/ollama/install": _api_ollama_install,
|
|
2640
|
+
"/api/extensions/ollama/enable": _api_ollama_enable,
|
|
2641
|
+
"/api/extensions/ollama/setup": _api_ollama_setup,
|
|
2642
|
+
}
|
|
2643
|
+
|
|
2644
|
+
|
|
2645
|
+
def _startup_update_check() -> None:
|
|
2646
|
+
"""服务启动时后台检测一次更新并写入缓存(失败静默,不影响面板启动)。
|
|
2647
|
+
|
|
2648
|
+
浏览器刷新面板只读这份缓存,绝不联网——只有重启面板服务才会真正
|
|
2649
|
+
拉远程源检测最新版本。
|
|
2650
|
+
"""
|
|
2651
|
+
def _job():
|
|
2652
|
+
import traceback
|
|
2653
|
+
try:
|
|
2654
|
+
# auto=False 才能真正走 _update_check_live 联网检测并写缓存;
|
|
2655
|
+
# auto=True 只在读缓存模式,会被 early-return 拦截
|
|
2656
|
+
growth.update_check("lingshu", force_pull=True, auto=False)
|
|
2657
|
+
except Exception:
|
|
2658
|
+
try:
|
|
2659
|
+
brain.log_event("panel", "启动时更新检测失败", level="warn",
|
|
2660
|
+
trace=traceback.format_exc()[-500:])
|
|
2661
|
+
except Exception:
|
|
2662
|
+
pass
|
|
2663
|
+
threading.Thread(target=_job, name="startup-update-check", daemon=True).start()
|
|
2664
|
+
|
|
2665
|
+
|
|
2666
|
+
def serve(port: int = 8765, open_browser: bool = True) -> None:
|
|
2667
|
+
brain.ensure_home()
|
|
2668
|
+
brain._resolve_readonly(False) # 面板也要探测只读:数据目录不可写时 POST 写接口返回 403
|
|
2669
|
+
_startup_update_check()
|
|
2670
|
+
# ① 自动探测接管(启动即探一次,后台线程、失败静默):本机已有 Ollama 在跑
|
|
2671
|
+
# → 无感接入 embed 配置;模型没拉 → 后台自动 pull(整个生命周期只一次)。
|
|
2672
|
+
_ollama_auto_probe_async()
|
|
2673
|
+
try:
|
|
2674
|
+
httpd = ThreadingHTTPServer(("127.0.0.1", port), Handler)
|
|
2675
|
+
except OSError as exc:
|
|
2676
|
+
print(f"[错误] 端口 {port} 被占用或不可用:{exc}", file=sys.stderr)
|
|
2677
|
+
print("换一个端口试试:python scripts/panel_server.py --port 8766", file=sys.stderr)
|
|
2678
|
+
raise SystemExit(1) from exc
|
|
2679
|
+
httpd.daemon_threads = True # 退出时不等挂住的请求线程,防止 Ctrl+C 后进程残留
|
|
2680
|
+
url = f"http://127.0.0.1:{port}"
|
|
2681
|
+
print(f"灵枢 · 记忆面板:{url}")
|
|
2682
|
+
print(f"记忆库:{brain.HOME}")
|
|
2683
|
+
print("Ctrl+C 停止")
|
|
2684
|
+
if open_browser:
|
|
2685
|
+
threading.Timer(0.8, lambda: webbrowser.open(url)).start()
|
|
2686
|
+
try:
|
|
2687
|
+
httpd.serve_forever()
|
|
2688
|
+
except KeyboardInterrupt:
|
|
2689
|
+
print("\n已停止")
|
|
2690
|
+
finally:
|
|
2691
|
+
httpd.server_close()
|
|
2692
|
+
|
|
2693
|
+
|
|
2694
|
+
if __name__ == "__main__":
|
|
2695
|
+
import argparse
|
|
2696
|
+
ap = argparse.ArgumentParser()
|
|
2697
|
+
ap.add_argument("--port", type=int, default=8765)
|
|
2698
|
+
ap.add_argument("--no-browser", action="store_true")
|
|
2699
|
+
ap.add_argument("--home", help="测试用:指定数据目录(透传给 brain,不影响正式数据)")
|
|
2700
|
+
a = ap.parse_args()
|
|
2701
|
+
if a.home:
|
|
2702
|
+
brain._override_home(["--home", a.home])
|
|
2703
|
+
serve(a.port, not a.no_browser)
|