seed-kernel 1.0.11__py3-none-any.whl
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.
- seed/__init__.py +125 -0
- seed/cli.py +102 -0
- seed/core/__init__.py +8 -0
- seed/core/_session_cache.py +41 -0
- seed/core/agent_context.py +163 -0
- seed/core/agent_registry.py +180 -0
- seed/core/agent_runtime.py +2384 -0
- seed/core/chat_events.py +70 -0
- seed/core/commands.py +149 -0
- seed/core/config_plane.py +537 -0
- seed/core/engine.py +150 -0
- seed/core/env_access.py +168 -0
- seed/core/execution.py +148 -0
- seed/core/llm_exec.py +1652 -0
- seed/core/llm_presets.py +305 -0
- seed/core/llm_sess.py +1094 -0
- seed/core/media_store.py +84 -0
- seed/core/mem_bridge.py +294 -0
- seed/core/mem_sys.py +409 -0
- seed/core/model_providers.py +88 -0
- seed/core/models.py +211 -0
- seed/core/paths.py +109 -0
- seed/core/persistence.py +133 -0
- seed/core/proj_reg.py +609 -0
- seed/core/proj_todos.py +141 -0
- seed/core/projection_audit.py +317 -0
- seed/core/routing.py +192 -0
- seed/core/sess_store.py +44 -0
- seed/core/tool_output_cap.py +122 -0
- seed/core/tool_runtime.py +330 -0
- seed/core/trace_audit.py +123 -0
- seed/core/turn_loop.py +750 -0
- seed/core/usage_accumulator.py +72 -0
- seed/integrations/__init__.py +33 -0
- seed/integrations/agent_tools.py +160 -0
- seed/integrations/cron_sched.py +773 -0
- seed/integrations/env_config.py +77 -0
- seed/integrations/exec_backend.py +432 -0
- seed/integrations/hooks.py +61 -0
- seed/integrations/hooks_config.py +109 -0
- seed/integrations/instruction_release.py +256 -0
- seed/integrations/lsp_client.py +219 -0
- seed/integrations/lsp_config.py +99 -0
- seed/integrations/mcp_client.py +1283 -0
- seed/integrations/mcp_config.py +208 -0
- seed/integrations/mcp_registry.py +154 -0
- seed/integrations/message_api.py +16 -0
- seed/integrations/prompt_task.py +39 -0
- seed/integrations/safety.py +331 -0
- seed/integrations/session_title.py +211 -0
- seed/integrations/symbol_index.py +311 -0
- seed/integrations/task_runner.py +275 -0
- seed/integrations/webhook_auth.py +33 -0
- seed/integrations/webhook_dedup.py +132 -0
- seed/models.py +31 -0
- seed_kernel-1.0.11.dist-info/METADATA +17 -0
- seed_kernel-1.0.11.dist-info/RECORD +60 -0
- seed_kernel-1.0.11.dist-info/WHEEL +5 -0
- seed_kernel-1.0.11.dist-info/entry_points.txt +2 -0
- seed_kernel-1.0.11.dist-info/top_level.txt +1 -0
seed/core/llm_sess.py
ADDED
|
@@ -0,0 +1,1094 @@
|
|
|
1
|
+
"""Chat session persistence — uses models.Session (same shape as TurnLoopEngine).
|
|
2
|
+
|
|
3
|
+
存储策略:
|
|
4
|
+
- 无项目关联的会话 → agents/<agent_id>/sessions/<id>.json
|
|
5
|
+
- 有项目关联的会话 → agents/<agent_id>/projects-data/<project-id>/sessions/<id>.json
|
|
6
|
+
|
|
7
|
+
旧布局 ``sessions/llm_sessions/`` 可用 ``migrate_legacy_agent_sessions()`` 一次性迁移;未迁移前仍只读回退。
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
import contextlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import shutil
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Dict, List, Optional
|
|
19
|
+
|
|
20
|
+
from seed.core import env_access as _ea
|
|
21
|
+
from seed.core.models import Session
|
|
22
|
+
from seed.core.paths import agent_home, agent_id_default, agent_project_data_subdir
|
|
23
|
+
from seed.core.proj_reg import (
|
|
24
|
+
UNASSIGNED_PROJECT_ID,
|
|
25
|
+
get_session_meta,
|
|
26
|
+
list_project_session_ids,
|
|
27
|
+
list_project_sessions_meta,
|
|
28
|
+
list_projects,
|
|
29
|
+
list_unassigned_session_ids,
|
|
30
|
+
register_session,
|
|
31
|
+
unregister_session,
|
|
32
|
+
update_session_meta,
|
|
33
|
+
)
|
|
34
|
+
from seed.core.sess_store import SessionStore
|
|
35
|
+
|
|
36
|
+
_SAFE_RE = re.compile(r"[^a-zA-Z0-9._-]+")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def agent_sessions_dir(agent_id: Optional[str] = None) -> Path:
|
|
40
|
+
"""
|
|
41
|
+
Agent chat session storage root (non-project sessions).
|
|
42
|
+
|
|
43
|
+
Priority:
|
|
44
|
+
- ``SEED_AGENT_SESSIONS_DIR`` / ``SEED_LLM_SESSIONS_DIR`` (explicit override)
|
|
45
|
+
- ``agents/<agent_id>/sessions`` under the multi-agent layout.
|
|
46
|
+
"""
|
|
47
|
+
raw = _ea.pick_nonempty(*_ea.AGENT_CHAT_SESSIONS_DIR)
|
|
48
|
+
if raw:
|
|
49
|
+
return Path(raw).expanduser().resolve()
|
|
50
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
51
|
+
d = (agent_home(aid) / "sessions").resolve()
|
|
52
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
return d
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _legacy_llm_sessions_subdir(agent_id: Optional[str] = None) -> Path:
|
|
57
|
+
"""Pre-migration layout: ``agents/<id>/sessions/llm_sessions`` (read + list fallback)."""
|
|
58
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
59
|
+
return (agent_home(aid) / "sessions" / "llm_sessions").resolve()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _default_session_search_dirs(agent_id: Optional[str] = None) -> List[Path]:
|
|
63
|
+
"""Directories to scan for non-project session JSON (new first, then legacy)."""
|
|
64
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
65
|
+
primary = agent_sessions_dir(aid)
|
|
66
|
+
legacy = _legacy_llm_sessions_subdir(aid)
|
|
67
|
+
out: List[Path] = [primary]
|
|
68
|
+
if legacy != primary and legacy.is_dir():
|
|
69
|
+
out.append(legacy)
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _remove_legacy_session_copy(handle: str, agent_id: Optional[str] = None) -> None:
|
|
74
|
+
"""After persist to the new layout, drop duplicate JSON under ``sessions/llm_sessions/``."""
|
|
75
|
+
slug = _safe_session_filename(handle)
|
|
76
|
+
legacy = _legacy_llm_sessions_subdir(agent_id) / f"{slug}.json"
|
|
77
|
+
if not legacy.is_file():
|
|
78
|
+
return
|
|
79
|
+
primary = agent_sessions_dir(agent_id) / f"{slug}.json"
|
|
80
|
+
if primary.is_file() and primary.resolve() != legacy.resolve():
|
|
81
|
+
with contextlib.suppress(OSError):
|
|
82
|
+
legacy.unlink()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
_LEGACY_SUBDIRS = ("archived", "attachments", "_artifacts", "_user_inputs")
|
|
86
|
+
_OBSOLETE_SUBDIRS = ("_transcript",) # removed JSONL ledger
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _merge_tree_into_primary(src: Path, dest: Path, *, dry_run: bool) -> int:
|
|
90
|
+
"""Merge ``src`` into ``dest`` (files only; newer mtime wins on name clash). Returns move count."""
|
|
91
|
+
if not src.is_dir():
|
|
92
|
+
return 0
|
|
93
|
+
n = 0
|
|
94
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
for root, _dirs, files in os.walk(src):
|
|
96
|
+
root_p = Path(root)
|
|
97
|
+
rel = root_p.relative_to(src)
|
|
98
|
+
out_dir = dest / rel
|
|
99
|
+
if not dry_run:
|
|
100
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
for name in files:
|
|
102
|
+
s = root_p / name
|
|
103
|
+
d = out_dir / name
|
|
104
|
+
if d.is_file():
|
|
105
|
+
if s.stat().st_mtime > d.stat().st_mtime:
|
|
106
|
+
if not dry_run:
|
|
107
|
+
d.unlink()
|
|
108
|
+
shutil.move(str(s), str(d))
|
|
109
|
+
n += 1
|
|
110
|
+
continue
|
|
111
|
+
if not dry_run:
|
|
112
|
+
shutil.move(str(s), str(d))
|
|
113
|
+
n += 1
|
|
114
|
+
return n
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def migrate_legacy_agent_sessions(
|
|
118
|
+
agent_id: Optional[str] = None,
|
|
119
|
+
*,
|
|
120
|
+
dry_run: bool = False,
|
|
121
|
+
remove_jsonl_ledger: bool = True,
|
|
122
|
+
) -> Dict[str, Any]:
|
|
123
|
+
"""
|
|
124
|
+
Move ``agents/<id>/sessions/llm_sessions/`` → flat ``agents/<id>/sessions/``.
|
|
125
|
+
|
|
126
|
+
- Session ``*.json`` and subdirs ``archived``, ``attachments``, ``_artifacts``, ``_user_inputs``
|
|
127
|
+
- Drops obsolete ``_transcript/`` JSONL (feature removed)
|
|
128
|
+
- Removes empty legacy directory when done
|
|
129
|
+
"""
|
|
130
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
131
|
+
primary = agent_sessions_dir(aid)
|
|
132
|
+
legacy = _legacy_llm_sessions_subdir(aid)
|
|
133
|
+
stats: Dict[str, Any] = {
|
|
134
|
+
"agent_id": aid,
|
|
135
|
+
"dry_run": dry_run,
|
|
136
|
+
"legacy_dir": str(legacy),
|
|
137
|
+
"primary_dir": str(primary),
|
|
138
|
+
"moved_json": 0,
|
|
139
|
+
"skipped_json": 0,
|
|
140
|
+
"merged_files": 0,
|
|
141
|
+
"removed_subdirs": [],
|
|
142
|
+
"legacy_removed": False,
|
|
143
|
+
}
|
|
144
|
+
if not legacy.is_dir():
|
|
145
|
+
return stats
|
|
146
|
+
|
|
147
|
+
for path in sorted(legacy.glob("*.json")):
|
|
148
|
+
dest = primary / path.name
|
|
149
|
+
if dest.is_file():
|
|
150
|
+
stats["skipped_json"] += 1
|
|
151
|
+
if not dry_run and path.stat().st_mtime > dest.stat().st_mtime:
|
|
152
|
+
dest.unlink()
|
|
153
|
+
shutil.move(str(path), str(dest))
|
|
154
|
+
stats["moved_json"] += 1
|
|
155
|
+
stats["skipped_json"] -= 1
|
|
156
|
+
continue
|
|
157
|
+
if not dry_run:
|
|
158
|
+
shutil.move(str(path), str(dest))
|
|
159
|
+
stats["moved_json"] += 1
|
|
160
|
+
|
|
161
|
+
for name in _LEGACY_SUBDIRS:
|
|
162
|
+
src = legacy / name
|
|
163
|
+
if src.is_dir():
|
|
164
|
+
n = _merge_tree_into_primary(src, primary / name, dry_run=dry_run)
|
|
165
|
+
stats["merged_files"] += n
|
|
166
|
+
if not dry_run:
|
|
167
|
+
shutil.rmtree(src, ignore_errors=True)
|
|
168
|
+
|
|
169
|
+
if remove_jsonl_ledger:
|
|
170
|
+
for base in (legacy, primary):
|
|
171
|
+
for name in _OBSOLETE_SUBDIRS:
|
|
172
|
+
p = base / name
|
|
173
|
+
if p.is_dir():
|
|
174
|
+
stats["removed_subdirs"].append(str(p))
|
|
175
|
+
if not dry_run:
|
|
176
|
+
shutil.rmtree(p, ignore_errors=True)
|
|
177
|
+
|
|
178
|
+
if not dry_run and legacy.is_dir():
|
|
179
|
+
with contextlib.suppress(OSError):
|
|
180
|
+
shutil.rmtree(legacy, ignore_errors=True)
|
|
181
|
+
stats["legacy_removed"] = not legacy.exists()
|
|
182
|
+
return stats
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _project_sessions_dir(project_id: str, agent_id: Optional[str] = None) -> Path:
|
|
186
|
+
"""项目关联会话的存储目录。"""
|
|
187
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
188
|
+
return agent_project_data_subdir(aid, project_id, "sessions")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _safe_session_filename(session_id: str) -> str:
|
|
192
|
+
s = _SAFE_RE.sub("_", session_id).strip("._-") or "session"
|
|
193
|
+
return s[:128]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _session_store(agent_id: Optional[str] = None) -> SessionStore:
|
|
197
|
+
return SessionStore(str(agent_sessions_dir(agent_id)))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _project_session_store(project_id: str, agent_id: Optional[str] = None) -> SessionStore:
|
|
201
|
+
"""创建指向项目会话目录的 SessionStore。"""
|
|
202
|
+
return SessionStore(str(_project_sessions_dir(project_id, agent_id)))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _resolve_session_store(session: Session, agent_id: Optional[str] = None) -> SessionStore:
|
|
206
|
+
"""根据 session 的 metadata.project_id 解析正确的 SessionStore。"""
|
|
207
|
+
pid = ""
|
|
208
|
+
if isinstance(session.metadata, dict):
|
|
209
|
+
pid = str(session.metadata.get("project_id") or "").strip()
|
|
210
|
+
if pid:
|
|
211
|
+
return _project_session_store(pid, agent_id)
|
|
212
|
+
return _session_store(agent_id)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _session_from_stored_json(data: Dict[str, Any], slug: str, handle: str) -> Session:
|
|
216
|
+
"""Build ``models_pkg.Session`` from on-disk JSON (no ``SessionStore._dict_to_session``).
|
|
217
|
+
|
|
218
|
+
Web UI session history only needs ``messages``; ``turns`` are omitted to avoid brittle deserialization.
|
|
219
|
+
"""
|
|
220
|
+
msgs = data.get("messages")
|
|
221
|
+
if not isinstance(msgs, list):
|
|
222
|
+
msgs = []
|
|
223
|
+
dict_msgs = [m for m in msgs if isinstance(m, dict)]
|
|
224
|
+
dict_msgs = _scrub_history_for_model(dict_msgs)
|
|
225
|
+
|
|
226
|
+
sess_id = str(data.get("id") or slug)
|
|
227
|
+
sid = data.get("session_id") or data.get("name") or handle
|
|
228
|
+
name = str(data.get("name") or (sid if isinstance(sid, str) else handle))
|
|
229
|
+
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
|
|
230
|
+
meta = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
|
|
231
|
+
ca = str(data.get("created_at") or "")
|
|
232
|
+
ua = str(data.get("updated_at") or ca)
|
|
233
|
+
|
|
234
|
+
return Session(
|
|
235
|
+
id=sess_id,
|
|
236
|
+
name=name,
|
|
237
|
+
created_at=ca,
|
|
238
|
+
updated_at=ua,
|
|
239
|
+
messages=list(dict_msgs),
|
|
240
|
+
turns=[],
|
|
241
|
+
config=dict(cfg),
|
|
242
|
+
metadata=dict(meta),
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _scrub_history_for_model(msgs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
247
|
+
"""Strip <think>/chain-of-thought markup from assistant content before it is
|
|
248
|
+
replayed to the model.
|
|
249
|
+
|
|
250
|
+
We keep the JSON on disk untouched (that is the forensic ground truth) but
|
|
251
|
+
never let stray chain-of-thought leak back into the next turn's context,
|
|
252
|
+
because that caused self-reinforcing exploratory repetition (same file
|
|
253
|
+
sliced 5 different ways, same port re-queried, etc.).
|
|
254
|
+
"""
|
|
255
|
+
try:
|
|
256
|
+
from seed.core.agent_runtime import strip_inline_tool_markup_from_assistant_text as _strip
|
|
257
|
+
except Exception: # pragma: no cover - defensive; runtime always has this
|
|
258
|
+
return msgs
|
|
259
|
+
out: List[Dict[str, Any]] = []
|
|
260
|
+
for m in msgs:
|
|
261
|
+
if not isinstance(m, dict):
|
|
262
|
+
out.append(m)
|
|
263
|
+
continue
|
|
264
|
+
if m.get("role") != "assistant":
|
|
265
|
+
out.append(m)
|
|
266
|
+
continue
|
|
267
|
+
c = m.get("content")
|
|
268
|
+
if isinstance(c, str) and c:
|
|
269
|
+
cleaned = _strip(c)
|
|
270
|
+
if cleaned != c:
|
|
271
|
+
m = {**m, "content": cleaned}
|
|
272
|
+
out.append(m)
|
|
273
|
+
return out
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _try_load_from_store(store: SessionStore, handle: str) -> Optional[Session]:
|
|
277
|
+
"""尝试从指定的 SessionStore 加载会话。"""
|
|
278
|
+
slug = _safe_session_filename(handle)
|
|
279
|
+
path = store.base_path / f"{slug}.json"
|
|
280
|
+
if not path.is_file():
|
|
281
|
+
return None
|
|
282
|
+
try:
|
|
283
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
284
|
+
except (json.JSONDecodeError, OSError):
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
msgs = data.get("messages")
|
|
288
|
+
if not isinstance(msgs, list):
|
|
289
|
+
return None
|
|
290
|
+
|
|
291
|
+
if data.get("id") and all(isinstance(m, dict) for m in msgs):
|
|
292
|
+
return _session_from_stored_json(data, slug, handle)
|
|
293
|
+
|
|
294
|
+
return None
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def load_chat_session_from_disk(
|
|
298
|
+
handle: str,
|
|
299
|
+
agent_id: Optional[str] = None,
|
|
300
|
+
project_id: Optional[str] = None,
|
|
301
|
+
) -> Optional[Session]:
|
|
302
|
+
"""
|
|
303
|
+
Load Session JSON from disk.
|
|
304
|
+
|
|
305
|
+
查找顺序(v2):
|
|
306
|
+
1. 如果指定了 project_id → 先从 registry 定位,再从项目会话目录加载
|
|
307
|
+
2. 如果没找到或没指定 → 从 registry 搜索所有项目
|
|
308
|
+
3. 回退:从默认 agent sessions 目录扫描(兼容旧数据/未注册会话)
|
|
309
|
+
|
|
310
|
+
``handle`` is the user-visible key (CLI --session or browser session_id).
|
|
311
|
+
"""
|
|
312
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
313
|
+
pid = (project_id or "").strip() if project_id else ""
|
|
314
|
+
|
|
315
|
+
# 优先从 registry 定位
|
|
316
|
+
reg_path = _session_file_path_from_registry(handle, aid, pid)
|
|
317
|
+
if reg_path is not None:
|
|
318
|
+
store = SessionStore(str(reg_path.parent))
|
|
319
|
+
found = _try_load_from_store(store, handle)
|
|
320
|
+
if found is not None:
|
|
321
|
+
return found
|
|
322
|
+
|
|
323
|
+
# 如果指定了项目,直接查项目目录
|
|
324
|
+
if pid:
|
|
325
|
+
pstore = _project_session_store(pid, aid)
|
|
326
|
+
found = _try_load_from_store(pstore, handle)
|
|
327
|
+
if found is not None:
|
|
328
|
+
return found
|
|
329
|
+
|
|
330
|
+
# 回退:默认目录
|
|
331
|
+
for d in _default_session_search_dirs(aid):
|
|
332
|
+
found = _try_load_from_store(SessionStore(str(d)), handle)
|
|
333
|
+
if found is not None:
|
|
334
|
+
return found
|
|
335
|
+
|
|
336
|
+
# 回退:搜索所有项目目录
|
|
337
|
+
if not pid:
|
|
338
|
+
for proj in list_projects(aid):
|
|
339
|
+
pstore = _project_session_store(proj["id"], aid)
|
|
340
|
+
found = _try_load_from_store(pstore, handle)
|
|
341
|
+
if found is not None:
|
|
342
|
+
return found
|
|
343
|
+
|
|
344
|
+
return None
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _scan_session_dir(
|
|
348
|
+
d: Path,
|
|
349
|
+
*,
|
|
350
|
+
limit: int,
|
|
351
|
+
filter_by_project: bool,
|
|
352
|
+
filter_project_id: str,
|
|
353
|
+
) -> List[Dict[str, Any]]:
|
|
354
|
+
"""扫描单个目录的会话 JSON,返回元信息列表。"""
|
|
355
|
+
if not d.is_dir():
|
|
356
|
+
return []
|
|
357
|
+
rows: List[Dict[str, Any]] = []
|
|
358
|
+
for path in sorted(d.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True):
|
|
359
|
+
if len(rows) >= limit:
|
|
360
|
+
break
|
|
361
|
+
try:
|
|
362
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
363
|
+
except (json.JSONDecodeError, OSError):
|
|
364
|
+
continue
|
|
365
|
+
msgs = data.get("messages")
|
|
366
|
+
n_msg = _count_user_messages(msgs)
|
|
367
|
+
name = data.get("name")
|
|
368
|
+
sid = str(name).strip() if isinstance(name, str) and name.strip() else path.stem
|
|
369
|
+
meta = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
|
|
370
|
+
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
|
|
371
|
+
sess_proj = str(meta.get("project_id") or "").strip()
|
|
372
|
+
if filter_by_project:
|
|
373
|
+
want = (filter_project_id or "").strip()
|
|
374
|
+
if want:
|
|
375
|
+
if sess_proj != want:
|
|
376
|
+
continue
|
|
377
|
+
else:
|
|
378
|
+
if sess_proj:
|
|
379
|
+
continue
|
|
380
|
+
preview = ""
|
|
381
|
+
if isinstance(msgs, list):
|
|
382
|
+
for m in reversed(msgs):
|
|
383
|
+
if isinstance(m, dict) and m.get("role") == "user":
|
|
384
|
+
preview = str(m.get("content") or "")[:120]
|
|
385
|
+
break
|
|
386
|
+
display_title = _session_display_title(preview, meta)
|
|
387
|
+
channel = _infer_channel(sid, meta, cfg)
|
|
388
|
+
rows.append(
|
|
389
|
+
{
|
|
390
|
+
"session_id": sid,
|
|
391
|
+
"file_id": str(data.get("id") or path.stem),
|
|
392
|
+
"updated_at": str(data.get("updated_at") or ""),
|
|
393
|
+
"message_count": n_msg,
|
|
394
|
+
"preview": preview,
|
|
395
|
+
"display_title": display_title,
|
|
396
|
+
"channel": channel,
|
|
397
|
+
"project_id": sess_proj,
|
|
398
|
+
}
|
|
399
|
+
)
|
|
400
|
+
return rows
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _merge_session_meta_rows(rows: List[Dict[str, Any]], *, limit: int) -> List[Dict[str, Any]]:
|
|
404
|
+
"""Dedupe by session_id; keep row with newer updated_at."""
|
|
405
|
+
by_sid: Dict[str, Dict[str, Any]] = {}
|
|
406
|
+
for row in rows:
|
|
407
|
+
sid = str(row.get("session_id") or "").strip()
|
|
408
|
+
if not sid:
|
|
409
|
+
continue
|
|
410
|
+
prev = by_sid.get(sid)
|
|
411
|
+
if prev is None or str(row.get("updated_at") or "") >= str(prev.get("updated_at") or ""):
|
|
412
|
+
by_sid[sid] = row
|
|
413
|
+
merged = list(by_sid.values())
|
|
414
|
+
merged.sort(key=lambda r: r.get("updated_at", ""), reverse=True)
|
|
415
|
+
return merged[:limit]
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _scan_default_agent_session_dirs(
|
|
419
|
+
agent_id: str,
|
|
420
|
+
*,
|
|
421
|
+
limit: int,
|
|
422
|
+
filter_by_project: bool,
|
|
423
|
+
filter_project_id: str,
|
|
424
|
+
) -> List[Dict[str, Any]]:
|
|
425
|
+
rows: List[Dict[str, Any]] = []
|
|
426
|
+
for d in _default_session_search_dirs(agent_id):
|
|
427
|
+
if len(rows) >= limit:
|
|
428
|
+
break
|
|
429
|
+
rows.extend(
|
|
430
|
+
_scan_session_dir(
|
|
431
|
+
d,
|
|
432
|
+
limit=limit,
|
|
433
|
+
filter_by_project=filter_by_project,
|
|
434
|
+
filter_project_id=filter_project_id,
|
|
435
|
+
)
|
|
436
|
+
)
|
|
437
|
+
return _merge_session_meta_rows(rows, limit=limit)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _session_file_path_from_registry(
|
|
441
|
+
session_id: str,
|
|
442
|
+
agent_id: str,
|
|
443
|
+
project_id: str = "",
|
|
444
|
+
) -> Optional[Path]:
|
|
445
|
+
"""根据 registry 中的会话注册信息,返回会话文件路径。
|
|
446
|
+
|
|
447
|
+
优先从 registry 定位,回退到目录扫描。
|
|
448
|
+
"""
|
|
449
|
+
slug = _safe_session_filename(session_id)
|
|
450
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
451
|
+
pid = (project_id or "").strip()
|
|
452
|
+
|
|
453
|
+
# 如果指定了 project_id,先查该项目的注册列表
|
|
454
|
+
if pid:
|
|
455
|
+
registered = list_project_session_ids(aid, pid)
|
|
456
|
+
if session_id in registered:
|
|
457
|
+
p = _project_sessions_dir(pid, aid) / f"{slug}.json"
|
|
458
|
+
if p.is_file():
|
|
459
|
+
return p
|
|
460
|
+
# 注册了但文件不存在,也尝试直接读目录
|
|
461
|
+
p = _project_sessions_dir(pid, aid) / f"{slug}.json"
|
|
462
|
+
if p.is_file():
|
|
463
|
+
return p
|
|
464
|
+
return None
|
|
465
|
+
|
|
466
|
+
# 无 project_id:扫描所有项目注册表
|
|
467
|
+
for proj in list_projects(aid):
|
|
468
|
+
registered = list_project_session_ids(aid, proj["id"])
|
|
469
|
+
if session_id in registered:
|
|
470
|
+
p = _project_sessions_dir(proj["id"], aid) / f"{slug}.json"
|
|
471
|
+
if p.is_file():
|
|
472
|
+
return p
|
|
473
|
+
return None
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _load_session_json(
|
|
477
|
+
path: Path,
|
|
478
|
+
) -> Optional[Dict[str, Any]]:
|
|
479
|
+
"""安全加载会话 JSON 文件。"""
|
|
480
|
+
try:
|
|
481
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
482
|
+
except (json.JSONDecodeError, OSError):
|
|
483
|
+
return None
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _session_meta_from_json(
|
|
487
|
+
path: Path,
|
|
488
|
+
data: Optional[Dict[str, Any]] = None,
|
|
489
|
+
) -> Optional[Dict[str, Any]]:
|
|
490
|
+
"""从 JSON 数据提取会话元信息行。"""
|
|
491
|
+
if data is None:
|
|
492
|
+
data = _load_session_json(path)
|
|
493
|
+
if data is None:
|
|
494
|
+
return None
|
|
495
|
+
msgs = data.get("messages")
|
|
496
|
+
n_msg = _count_user_messages(msgs)
|
|
497
|
+
name = data.get("name")
|
|
498
|
+
sid = str(name).strip() if isinstance(name, str) and name.strip() else path.stem
|
|
499
|
+
meta = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
|
|
500
|
+
cfg = data.get("config") if isinstance(data.get("config"), dict) else {}
|
|
501
|
+
preview = ""
|
|
502
|
+
if isinstance(msgs, list):
|
|
503
|
+
for m in reversed(msgs):
|
|
504
|
+
if isinstance(m, dict) and m.get("role") == "user":
|
|
505
|
+
preview = str(m.get("content") or "")[:120]
|
|
506
|
+
break
|
|
507
|
+
display_title = _session_display_title(preview, meta)
|
|
508
|
+
channel = _infer_channel(sid, meta, cfg)
|
|
509
|
+
context_usage = meta.get("context_usage")
|
|
510
|
+
return {
|
|
511
|
+
"session_id": sid,
|
|
512
|
+
"file_id": str(data.get("id") or path.stem),
|
|
513
|
+
"updated_at": str(data.get("updated_at") or ""),
|
|
514
|
+
"message_count": n_msg,
|
|
515
|
+
"preview": preview,
|
|
516
|
+
"display_title": display_title,
|
|
517
|
+
"channel": channel,
|
|
518
|
+
"context_usage": context_usage,
|
|
519
|
+
"project_id": str(meta.get("project_id") or "").strip(),
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def list_stored_sessions_meta(
|
|
524
|
+
*,
|
|
525
|
+
limit: int = 100,
|
|
526
|
+
agent_id: Optional[str] = None,
|
|
527
|
+
filter_by_project: bool = False,
|
|
528
|
+
filter_project_id: str = "",
|
|
529
|
+
) -> List[Dict[str, Any]]:
|
|
530
|
+
"""
|
|
531
|
+
Recent chat sessions from disk (for Web UI / tooling).
|
|
532
|
+
|
|
533
|
+
查询策略(v4):
|
|
534
|
+
- 所有会话都通过 registry 管理(含虚拟项目 __unassigned__)
|
|
535
|
+
- 优先从 registry 缓存读取元信息(无需加载 JSON 文件)
|
|
536
|
+
- 缓存缺失时回退加载 JSON 文件并自动补全缓存
|
|
537
|
+
|
|
538
|
+
When ``filter_by_project`` is True:
|
|
539
|
+
- If ``filter_project_id`` is set → list sessions for that project from registry cache
|
|
540
|
+
- If ``filter_project_id`` is empty → list sessions under virtual __unassigned__ project
|
|
541
|
+
When ``filter_by_project`` is False:
|
|
542
|
+
- List all sessions from all projects (including __unassigned__)
|
|
543
|
+
"""
|
|
544
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
545
|
+
lim = max(1, min(int(limit), 500))
|
|
546
|
+
|
|
547
|
+
if filter_by_project:
|
|
548
|
+
want = (filter_project_id or "").strip()
|
|
549
|
+
if want:
|
|
550
|
+
return _list_sessions_for_project_from_cache(aid, want, lim)
|
|
551
|
+
# 未分类 = 虚拟项目 __unassigned__
|
|
552
|
+
return _list_sessions_for_project_from_cache(aid, UNASSIGNED_PROJECT_ID, lim)
|
|
553
|
+
|
|
554
|
+
# 全部会话:所有项目(含虚拟项目)
|
|
555
|
+
rows: List[Dict[str, Any]] = []
|
|
556
|
+
seen_sids: set[str] = set()
|
|
557
|
+
|
|
558
|
+
for proj in list_projects(aid):
|
|
559
|
+
if len(rows) >= lim:
|
|
560
|
+
break
|
|
561
|
+
for sid, cached_meta in list_project_sessions_meta(aid, proj["id"]).items():
|
|
562
|
+
if len(rows) >= lim:
|
|
563
|
+
break
|
|
564
|
+
if sid in seen_sids:
|
|
565
|
+
continue
|
|
566
|
+
seen_sids.add(sid)
|
|
567
|
+
row = _meta_row_from_cache(sid, cached_meta, proj["id"])
|
|
568
|
+
if row is not None:
|
|
569
|
+
rows.append(row)
|
|
570
|
+
|
|
571
|
+
rows.sort(key=lambda r: r.get("updated_at", ""), reverse=True)
|
|
572
|
+
return rows[:lim]
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _meta_row_from_cache(
|
|
576
|
+
session_id: str,
|
|
577
|
+
cached_meta: Dict[str, Any],
|
|
578
|
+
project_id: str,
|
|
579
|
+
) -> Optional[Dict[str, Any]]:
|
|
580
|
+
"""从 registry 缓存构建会话元信息行。缓存缺失时回退加载 JSON。"""
|
|
581
|
+
if cached_meta and cached_meta.get("display_title"):
|
|
582
|
+
return {
|
|
583
|
+
"session_id": session_id,
|
|
584
|
+
"file_id": session_id,
|
|
585
|
+
"updated_at": str(cached_meta.get("updated_at") or ""),
|
|
586
|
+
"message_count": int(cached_meta.get("message_count") or 0),
|
|
587
|
+
"preview": str(cached_meta.get("preview") or "")[:120],
|
|
588
|
+
"display_title": str(cached_meta.get("display_title") or "未命名对话")[:80],
|
|
589
|
+
"channel": str(cached_meta.get("channel") or "Web 聊天")[:48],
|
|
590
|
+
"context_usage": cached_meta.get("context_usage"),
|
|
591
|
+
"project_id": project_id,
|
|
592
|
+
}
|
|
593
|
+
# 缓存缺失,回退加载 JSON
|
|
594
|
+
meta = _load_session_meta_by_id(session_id, None, project_id)
|
|
595
|
+
if meta is not None:
|
|
596
|
+
# 尝试更新缓存
|
|
597
|
+
try:
|
|
598
|
+
from seed.core.proj_reg import update_session_meta
|
|
599
|
+
update_session_meta(
|
|
600
|
+
agent_id_default(), project_id, session_id,
|
|
601
|
+
{
|
|
602
|
+
"display_title": meta.get("display_title", ""),
|
|
603
|
+
"updated_at": meta.get("updated_at", ""),
|
|
604
|
+
"message_count": meta.get("message_count", 0),
|
|
605
|
+
"preview": meta.get("preview", ""),
|
|
606
|
+
"channel": meta.get("channel", ""),
|
|
607
|
+
},
|
|
608
|
+
)
|
|
609
|
+
except Exception:
|
|
610
|
+
pass
|
|
611
|
+
return meta
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _list_sessions_for_project_from_cache(
|
|
615
|
+
agent_id: str, project_id: str, limit: int,
|
|
616
|
+
) -> List[Dict[str, Any]]:
|
|
617
|
+
"""从 registry 缓存列出项目下的会话(无需加载 JSON 文件)。"""
|
|
618
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
619
|
+
pid = (project_id or "").strip()
|
|
620
|
+
rows: List[Dict[str, Any]] = []
|
|
621
|
+
for sid, cached_meta in list_project_sessions_meta(aid, pid).items():
|
|
622
|
+
if len(rows) >= limit:
|
|
623
|
+
break
|
|
624
|
+
row = _meta_row_from_cache(sid, cached_meta, pid)
|
|
625
|
+
if row is not None:
|
|
626
|
+
rows.append(row)
|
|
627
|
+
rows.sort(key=lambda r: r.get("updated_at", ""), reverse=True)
|
|
628
|
+
return rows[:limit]
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _list_unassigned_sessions(
|
|
632
|
+
agent_id: str, limit: int,
|
|
633
|
+
exclude_sids: Optional[set[str]] = None,
|
|
634
|
+
) -> List[Dict[str, Any]]:
|
|
635
|
+
"""列出未注册到任何项目的会话(回退扫描目录)。"""
|
|
636
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
637
|
+
assigned = list_unassigned_session_ids(aid)
|
|
638
|
+
exclude = set(exclude_sids or [])
|
|
639
|
+
exclude.update(assigned)
|
|
640
|
+
|
|
641
|
+
rows: List[Dict[str, Any]] = []
|
|
642
|
+
for d in _default_session_search_dirs(aid):
|
|
643
|
+
if len(rows) >= limit:
|
|
644
|
+
break
|
|
645
|
+
for path in sorted(d.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True):
|
|
646
|
+
if len(rows) >= limit:
|
|
647
|
+
break
|
|
648
|
+
data = _load_session_json(path)
|
|
649
|
+
if data is None:
|
|
650
|
+
continue
|
|
651
|
+
name = data.get("name")
|
|
652
|
+
sid = str(name).strip() if isinstance(name, str) and name.strip() else path.stem
|
|
653
|
+
if sid in exclude:
|
|
654
|
+
continue
|
|
655
|
+
meta = _session_meta_from_json(path, data)
|
|
656
|
+
if meta is not None:
|
|
657
|
+
rows.append(meta)
|
|
658
|
+
rows.sort(key=lambda r: r.get("updated_at", ""), reverse=True)
|
|
659
|
+
return rows[:limit]
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _load_session_meta_by_id(
|
|
663
|
+
session_id: str, agent_id: str, project_id: str = "",
|
|
664
|
+
) -> Optional[Dict[str, Any]]:
|
|
665
|
+
"""按 session_id 和 project_id 加载会话元信息。"""
|
|
666
|
+
path = _session_file_path_from_registry(session_id, agent_id, project_id)
|
|
667
|
+
if path is not None:
|
|
668
|
+
return _session_meta_from_json(path)
|
|
669
|
+
# 回退:直接扫描目录
|
|
670
|
+
slug = _safe_session_filename(session_id)
|
|
671
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
672
|
+
pid = (project_id or "").strip()
|
|
673
|
+
if pid:
|
|
674
|
+
p = _project_sessions_dir(pid, aid) / f"{slug}.json"
|
|
675
|
+
if p.is_file():
|
|
676
|
+
return _session_meta_from_json(p)
|
|
677
|
+
for d in _default_session_search_dirs(aid):
|
|
678
|
+
p = d / f"{slug}.json"
|
|
679
|
+
if p.is_file():
|
|
680
|
+
return _session_meta_from_json(p)
|
|
681
|
+
return None
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def list_stored_session_ids(
|
|
685
|
+
agent_id: Optional[str] = None,
|
|
686
|
+
project_id: Optional[str] = None,
|
|
687
|
+
) -> List[str]:
|
|
688
|
+
"""列出会话 ID。
|
|
689
|
+
|
|
690
|
+
如果指定 project_id,则从 registry 读取该项目的会话列表。
|
|
691
|
+
否则扫描所有目录(兼容旧数据)。
|
|
692
|
+
"""
|
|
693
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
694
|
+
pid = (project_id or "").strip() if project_id else ""
|
|
695
|
+
|
|
696
|
+
if pid:
|
|
697
|
+
return list_project_session_ids(aid, pid)
|
|
698
|
+
|
|
699
|
+
# 全部会话:从 registry 收集 + 扫描未注册的
|
|
700
|
+
seen: set[str] = set()
|
|
701
|
+
result: List[str] = []
|
|
702
|
+
|
|
703
|
+
for proj in list_projects(aid):
|
|
704
|
+
for sid in list_project_session_ids(aid, proj["id"]):
|
|
705
|
+
if sid not in seen:
|
|
706
|
+
seen.add(sid)
|
|
707
|
+
result.append(sid)
|
|
708
|
+
|
|
709
|
+
# 回退扫描未注册的
|
|
710
|
+
for d in _default_session_search_dirs(aid):
|
|
711
|
+
if d.is_dir():
|
|
712
|
+
for path in sorted(d.glob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True):
|
|
713
|
+
try:
|
|
714
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
715
|
+
name = data.get("name")
|
|
716
|
+
sid = data.get("session_id")
|
|
717
|
+
oid = data.get("id")
|
|
718
|
+
if isinstance(name, str) and name.strip():
|
|
719
|
+
key = name.strip()
|
|
720
|
+
elif isinstance(sid, str) and sid.strip():
|
|
721
|
+
key = sid.strip()
|
|
722
|
+
elif isinstance(oid, str) and oid.strip():
|
|
723
|
+
key = oid.strip()
|
|
724
|
+
else:
|
|
725
|
+
key = path.stem
|
|
726
|
+
except (json.JSONDecodeError, OSError):
|
|
727
|
+
key = path.stem
|
|
728
|
+
if key in seen:
|
|
729
|
+
continue
|
|
730
|
+
seen.add(key)
|
|
731
|
+
result.append(key)
|
|
732
|
+
return result
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def _strip_non_leading_system(msgs: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
736
|
+
"""Drop system roles after index 0 — strict chat servers allow only one leading system."""
|
|
737
|
+
if not msgs:
|
|
738
|
+
return msgs
|
|
739
|
+
out: List[Dict[str, Any]] = [msgs[0]]
|
|
740
|
+
for m in msgs[1:]:
|
|
741
|
+
if isinstance(m, dict) and m.get("role") == "system":
|
|
742
|
+
continue
|
|
743
|
+
out.append(m)
|
|
744
|
+
return out
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def merge_fresh_system(
|
|
748
|
+
loaded: List[Dict[str, Any]],
|
|
749
|
+
fresh_system: str,
|
|
750
|
+
) -> List[Dict[str, Any]]:
|
|
751
|
+
"""Use latest config/system text while restoring message tail."""
|
|
752
|
+
if not loaded:
|
|
753
|
+
return [{"role": "system", "content": fresh_system}]
|
|
754
|
+
loaded = _strip_non_leading_system(loaded)
|
|
755
|
+
if loaded and loaded[0].get("role") == "system":
|
|
756
|
+
return [{"role": "system", "content": fresh_system}] + loaded[1:]
|
|
757
|
+
return [{"role": "system", "content": fresh_system}] + loaded
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def load_or_create_chat_session(
|
|
761
|
+
handle: str,
|
|
762
|
+
agent_id: Optional[str] = None,
|
|
763
|
+
project_id: Optional[str] = None,
|
|
764
|
+
) -> Session:
|
|
765
|
+
found = load_chat_session_from_disk(handle, agent_id, project_id)
|
|
766
|
+
if found is not None:
|
|
767
|
+
# 🐛 修复:如果传入了 project_id 但会话 metadata 中缺少或不同,
|
|
768
|
+
# 则更新 project_id,确保后续 persist 存到正确的项目目录。
|
|
769
|
+
if project_id:
|
|
770
|
+
md = found.metadata
|
|
771
|
+
if not isinstance(md, dict):
|
|
772
|
+
md = {}
|
|
773
|
+
cur_pid = str(md.get("project_id") or "").strip()
|
|
774
|
+
if cur_pid != project_id:
|
|
775
|
+
md["project_id"] = project_id
|
|
776
|
+
found.metadata = md
|
|
777
|
+
return found
|
|
778
|
+
sess = Session.for_llm_handle(handle, _safe_session_filename(handle))
|
|
779
|
+
if project_id:
|
|
780
|
+
if not isinstance(sess.metadata, dict):
|
|
781
|
+
sess.metadata = {}
|
|
782
|
+
sess.metadata["project_id"] = project_id
|
|
783
|
+
return sess
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def read_stored_session_project_id(handle: str, agent_id: Optional[str] = None) -> str:
|
|
787
|
+
s = load_chat_session_from_disk(handle, agent_id)
|
|
788
|
+
if s is None:
|
|
789
|
+
return ""
|
|
790
|
+
md = s.metadata if isinstance(s.metadata, dict) else {}
|
|
791
|
+
return str(md.get("project_id") or "").strip()
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def _extract_session_meta(session: Session) -> Dict[str, Any]:
|
|
795
|
+
"""从 Session 对象提取用于 registry 缓存的元信息。"""
|
|
796
|
+
handle = str(session.name or session.id or "").strip()
|
|
797
|
+
meta: Dict[str, Any] = {
|
|
798
|
+
"updated_at": str(session.updated_at or ""),
|
|
799
|
+
"message_count": _count_user_messages(session.messages),
|
|
800
|
+
}
|
|
801
|
+
if isinstance(session.metadata, dict):
|
|
802
|
+
dt = session.metadata.get("display_title")
|
|
803
|
+
if isinstance(dt, str) and dt.strip():
|
|
804
|
+
meta["display_title"] = dt.strip()[:80]
|
|
805
|
+
channel = session.metadata.get("channel") or session.metadata.get("source")
|
|
806
|
+
if isinstance(channel, str) and channel.strip():
|
|
807
|
+
meta["channel"] = channel.strip()[:48]
|
|
808
|
+
cu = session.metadata.get("context_usage")
|
|
809
|
+
if isinstance(cu, dict) and cu:
|
|
810
|
+
meta["context_usage"] = cu
|
|
811
|
+
if not meta.get("display_title"):
|
|
812
|
+
# 从最后一条 user 消息提取预览
|
|
813
|
+
preview = ""
|
|
814
|
+
if isinstance(session.messages, list):
|
|
815
|
+
for m in reversed(session.messages):
|
|
816
|
+
if isinstance(m, dict) and m.get("role") == "user":
|
|
817
|
+
preview = str(m.get("content") or "")[:120]
|
|
818
|
+
break
|
|
819
|
+
meta["preview"] = preview
|
|
820
|
+
meta["display_title"] = _session_display_title(preview, session.metadata if isinstance(session.metadata, dict) else {})
|
|
821
|
+
else:
|
|
822
|
+
# 也尝试提取 preview
|
|
823
|
+
if isinstance(session.messages, list):
|
|
824
|
+
for m in reversed(session.messages):
|
|
825
|
+
if isinstance(m, dict) and m.get("role") == "user":
|
|
826
|
+
meta["preview"] = str(m.get("content") or "")[:120]
|
|
827
|
+
break
|
|
828
|
+
return meta
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def persist_chat_session(session: Session, agent_id: Optional[str] = None) -> Path:
|
|
832
|
+
"""持久化会话。
|
|
833
|
+
|
|
834
|
+
根据 session.metadata.project_id 自动路由到:
|
|
835
|
+
- 有项目 → projects-data/<project-id>/sessions/
|
|
836
|
+
- 无项目 → agents/<id>/sessions/
|
|
837
|
+
|
|
838
|
+
写入后将会话 ID 及元信息缓存到项目 registry 中(如有 project_id)。
|
|
839
|
+
"""
|
|
840
|
+
session.touch_updated()
|
|
841
|
+
store = _resolve_session_store(session, agent_id)
|
|
842
|
+
store.save_session(session)
|
|
843
|
+
out = store.base_path / f"{session.id}.json"
|
|
844
|
+
handle = str(session.name or session.id or "").strip()
|
|
845
|
+
if handle:
|
|
846
|
+
_remove_legacy_session_copy(handle, agent_id)
|
|
847
|
+
# 注册到项目 registry 并缓存元信息
|
|
848
|
+
# 无 project_id 的会话暂不注册(等发消息时 project_id 设好后再注册)
|
|
849
|
+
pid = ""
|
|
850
|
+
if isinstance(session.metadata, dict):
|
|
851
|
+
pid = str(session.metadata.get("project_id") or "").strip()
|
|
852
|
+
if pid and handle:
|
|
853
|
+
sess_meta = _extract_session_meta(session)
|
|
854
|
+
register_session(agent_id or agent_id_default(), pid, handle, sess_meta)
|
|
855
|
+
return out
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def _session_json_path(handle: str) -> Path:
|
|
859
|
+
slug = _safe_session_filename(handle)
|
|
860
|
+
return agent_sessions_dir() / f"{slug}.json"
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
def _find_session_file(
|
|
864
|
+
handle: str,
|
|
865
|
+
agent_id: Optional[str] = None,
|
|
866
|
+
project_id: Optional[str] = None,
|
|
867
|
+
) -> Optional[Path]:
|
|
868
|
+
"""查找会话文件路径,优先项目目录。"""
|
|
869
|
+
slug = _safe_session_filename(handle)
|
|
870
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
871
|
+
|
|
872
|
+
pid = (project_id or "").strip() if project_id else ""
|
|
873
|
+
if pid:
|
|
874
|
+
pdir = _project_sessions_dir(pid, aid)
|
|
875
|
+
pp = pdir / f"{slug}.json"
|
|
876
|
+
if pp.is_file():
|
|
877
|
+
return pp
|
|
878
|
+
|
|
879
|
+
for d in _default_session_search_dirs(aid):
|
|
880
|
+
p = d / f"{slug}.json"
|
|
881
|
+
if p.is_file():
|
|
882
|
+
return p
|
|
883
|
+
return None
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def delete_stored_session(
|
|
887
|
+
handle: str,
|
|
888
|
+
agent_id: Optional[str] = None,
|
|
889
|
+
project_id: Optional[str] = None,
|
|
890
|
+
) -> bool:
|
|
891
|
+
"""Remove persisted chat session JSON for this session id.
|
|
892
|
+
|
|
893
|
+
同时从项目 registry 中注销该会话。
|
|
894
|
+
|
|
895
|
+
Bug fix: 当 project_id 为空时,会话可能同时存在于主目录(stub, 298B)
|
|
896
|
+
和 projects-data/<pid>/sessions/(真实数据)中。此函数会一并清理干净。
|
|
897
|
+
"""
|
|
898
|
+
from seed.core.proj_reg import list_projects, unregister_session
|
|
899
|
+
|
|
900
|
+
aid = (agent_id or "").strip() or agent_id_default()
|
|
901
|
+
pid = (project_id or "").strip() if project_id else ""
|
|
902
|
+
slug = _safe_session_filename(handle)
|
|
903
|
+
deleted_any = False
|
|
904
|
+
|
|
905
|
+
# ── 策略:始终查找并删除所有副本(主目录 + 项目目录) ──
|
|
906
|
+
|
|
907
|
+
# 1) 如果指定了 project_id:只删该项目
|
|
908
|
+
if pid:
|
|
909
|
+
path = _find_session_file(handle, aid, project_id)
|
|
910
|
+
if path is not None:
|
|
911
|
+
try:
|
|
912
|
+
path.unlink()
|
|
913
|
+
deleted_any = True
|
|
914
|
+
except OSError:
|
|
915
|
+
return False
|
|
916
|
+
# 即使文件不存在也要清理 registry(孤儿注册清理)
|
|
917
|
+
if handle:
|
|
918
|
+
unregister_session(aid, pid, handle)
|
|
919
|
+
deleted_any = True
|
|
920
|
+
# 清理 artifacts 和 attachments
|
|
921
|
+
sess_root = agent_sessions_dir(aid)
|
|
922
|
+
for subdir in ("_artifacts", "attachments"):
|
|
923
|
+
target = sess_root / subdir / handle
|
|
924
|
+
if target.is_dir():
|
|
925
|
+
try:
|
|
926
|
+
shutil.rmtree(target)
|
|
927
|
+
deleted_any = True
|
|
928
|
+
except OSError:
|
|
929
|
+
pass
|
|
930
|
+
return deleted_any
|
|
931
|
+
|
|
932
|
+
# 2) 未指定 project_id:遍历 registry 查找会话所属的项目
|
|
933
|
+
for proj in list_projects(aid):
|
|
934
|
+
proj_pid = str(proj.get("id") or "").strip()
|
|
935
|
+
if not proj_pid:
|
|
936
|
+
continue
|
|
937
|
+
registered = proj.get("sessions", {})
|
|
938
|
+
if handle not in registered:
|
|
939
|
+
continue
|
|
940
|
+
# 删除项目目录下的真实文件
|
|
941
|
+
p = _project_sessions_dir(proj_pid, aid) / f"{slug}.json"
|
|
942
|
+
if p.is_file():
|
|
943
|
+
try:
|
|
944
|
+
p.unlink()
|
|
945
|
+
deleted_any = True
|
|
946
|
+
except OSError:
|
|
947
|
+
pass
|
|
948
|
+
# 注销 registry
|
|
949
|
+
unregister_session(aid, proj_pid, handle)
|
|
950
|
+
deleted_any = True
|
|
951
|
+
break # 一个会话只属于一个项目
|
|
952
|
+
|
|
953
|
+
# 3) 清理主目录的 stub(无论上面是否找到项目)
|
|
954
|
+
for d in _default_session_search_dirs(aid):
|
|
955
|
+
stub = d / f"{slug}.json"
|
|
956
|
+
if stub.is_file():
|
|
957
|
+
try:
|
|
958
|
+
stub.unlink()
|
|
959
|
+
deleted_any = True
|
|
960
|
+
except OSError:
|
|
961
|
+
pass
|
|
962
|
+
|
|
963
|
+
# 4) 清理关联的 artifacts 和 attachments(使用原始 session_id 作为子目录名)
|
|
964
|
+
sess_root = agent_sessions_dir(aid)
|
|
965
|
+
for subdir in ("_artifacts", "attachments"):
|
|
966
|
+
target = sess_root / subdir / handle
|
|
967
|
+
if target.is_dir():
|
|
968
|
+
try:
|
|
969
|
+
shutil.rmtree(target)
|
|
970
|
+
deleted_any = True
|
|
971
|
+
except OSError:
|
|
972
|
+
pass
|
|
973
|
+
|
|
974
|
+
return deleted_any
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def archive_stored_llm_session(
|
|
978
|
+
handle: str,
|
|
979
|
+
agent_id: Optional[str] = None,
|
|
980
|
+
project_id: Optional[str] = None,
|
|
981
|
+
) -> bool:
|
|
982
|
+
"""Move session JSON to ``archived/`` under its storage directory."""
|
|
983
|
+
path = _find_session_file(handle, agent_id, project_id)
|
|
984
|
+
if path is None:
|
|
985
|
+
return False
|
|
986
|
+
arch = path.parent / "archived"
|
|
987
|
+
try:
|
|
988
|
+
arch.mkdir(parents=True, exist_ok=True)
|
|
989
|
+
dest = arch / path.name
|
|
990
|
+
if dest.is_file():
|
|
991
|
+
dest.unlink()
|
|
992
|
+
path.replace(dest)
|
|
993
|
+
except OSError:
|
|
994
|
+
return False
|
|
995
|
+
return True
|
|
996
|
+
|
|
997
|
+
|
|
998
|
+
def rename_stored_llm_session(
|
|
999
|
+
handle: str,
|
|
1000
|
+
new_title: str,
|
|
1001
|
+
agent_id: Optional[str] = None,
|
|
1002
|
+
project_id: Optional[str] = None,
|
|
1003
|
+
) -> bool:
|
|
1004
|
+
"""Update display_title in session metadata and persist."""
|
|
1005
|
+
sess = load_chat_session_from_disk(handle, agent_id, project_id)
|
|
1006
|
+
if sess is None:
|
|
1007
|
+
return False
|
|
1008
|
+
if not isinstance(sess.metadata, dict):
|
|
1009
|
+
sess.metadata = {}
|
|
1010
|
+
sess.metadata["display_title"] = (new_title or "").strip()[:80] or "未命名对话"
|
|
1011
|
+
sess.metadata["display_title_source"] = "manual"
|
|
1012
|
+
try:
|
|
1013
|
+
persist_chat_session(sess, agent_id)
|
|
1014
|
+
except OSError:
|
|
1015
|
+
return False
|
|
1016
|
+
return True
|
|
1017
|
+
|
|
1018
|
+
|
|
1019
|
+
def save_session_messages(
|
|
1020
|
+
session_id: str,
|
|
1021
|
+
messages: List[Dict[str, Any]],
|
|
1022
|
+
agent_id: Optional[str] = None,
|
|
1023
|
+
project_id: Optional[str] = None,
|
|
1024
|
+
) -> Path:
|
|
1025
|
+
"""Upsert Session.messages and persist."""
|
|
1026
|
+
sess = load_chat_session_from_disk(session_id, agent_id, project_id)
|
|
1027
|
+
if sess is None:
|
|
1028
|
+
sess = Session.for_llm_handle(session_id, _safe_session_filename(session_id))
|
|
1029
|
+
if project_id:
|
|
1030
|
+
if not isinstance(sess.metadata, dict):
|
|
1031
|
+
sess.metadata = {}
|
|
1032
|
+
sess.metadata["project_id"] = project_id
|
|
1033
|
+
sess.messages = messages
|
|
1034
|
+
return persist_chat_session(sess, agent_id)
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
def load_session_messages(
|
|
1038
|
+
session_id: str,
|
|
1039
|
+
agent_id: Optional[str] = None,
|
|
1040
|
+
project_id: Optional[str] = None,
|
|
1041
|
+
) -> Optional[List[Dict[str, Any]]]:
|
|
1042
|
+
sess = load_chat_session_from_disk(session_id, agent_id, project_id)
|
|
1043
|
+
if sess is None:
|
|
1044
|
+
return None
|
|
1045
|
+
return sess.messages
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
def _looks_like_cot_title(s: str) -> bool:
|
|
1049
|
+
"""已写入 metadata 但实为思维链/英文 CoT 的标题,列表展示时回退到用户预览。"""
|
|
1050
|
+
t = (s or "").strip()
|
|
1051
|
+
if not t:
|
|
1052
|
+
return True
|
|
1053
|
+
low = t.lower()
|
|
1054
|
+
if "thinking process" in low or "analyze the" in low:
|
|
1055
|
+
return True
|
|
1056
|
+
if re.match(r"^\d+\.\s*\*+", t):
|
|
1057
|
+
return True
|
|
1058
|
+
if t.startswith("**") and "analyze" in low[:80]:
|
|
1059
|
+
return True
|
|
1060
|
+
return False
|
|
1061
|
+
|
|
1062
|
+
|
|
1063
|
+
def _session_display_title(preview: str, metadata: Dict[str, Any]) -> str:
|
|
1064
|
+
dt = metadata.get("display_title")
|
|
1065
|
+
if isinstance(dt, str) and dt.strip():
|
|
1066
|
+
cand = dt.strip()[:80]
|
|
1067
|
+
if not _looks_like_cot_title(cand):
|
|
1068
|
+
return cand
|
|
1069
|
+
line = (preview or "").strip().replace("\n", " ")
|
|
1070
|
+
if line:
|
|
1071
|
+
return (line[:40] + "…") if len(line) > 40 else line
|
|
1072
|
+
return "未命名对话"
|
|
1073
|
+
|
|
1074
|
+
|
|
1075
|
+
def _infer_channel(session_id: str, metadata: Dict[str, Any], config: Dict[str, Any]) -> str:
|
|
1076
|
+
ch = metadata.get("channel")
|
|
1077
|
+
if isinstance(ch, str) and ch.strip():
|
|
1078
|
+
return ch.strip()[:48]
|
|
1079
|
+
src = metadata.get("source")
|
|
1080
|
+
if isinstance(src, str) and src.strip():
|
|
1081
|
+
return src.strip()[:48]
|
|
1082
|
+
sid = (session_id or "").lower()
|
|
1083
|
+
cfg_kind = (config.get("kind") or "") if isinstance(config, dict) else ""
|
|
1084
|
+
if cfg_kind == "webhook" or "webhook" in sid:
|
|
1085
|
+
return "Webhook"
|
|
1086
|
+
return "Web 聊天"
|
|
1087
|
+
|
|
1088
|
+
|
|
1089
|
+
def _count_user_messages(msgs: Any) -> int:
|
|
1090
|
+
if not isinstance(msgs, list):
|
|
1091
|
+
return 0
|
|
1092
|
+
return sum(1 for m in msgs if isinstance(m, dict) and m.get("role") == "user")
|
|
1093
|
+
|
|
1094
|
+
|