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.
Files changed (60) hide show
  1. seed/__init__.py +125 -0
  2. seed/cli.py +102 -0
  3. seed/core/__init__.py +8 -0
  4. seed/core/_session_cache.py +41 -0
  5. seed/core/agent_context.py +163 -0
  6. seed/core/agent_registry.py +180 -0
  7. seed/core/agent_runtime.py +2384 -0
  8. seed/core/chat_events.py +70 -0
  9. seed/core/commands.py +149 -0
  10. seed/core/config_plane.py +537 -0
  11. seed/core/engine.py +150 -0
  12. seed/core/env_access.py +168 -0
  13. seed/core/execution.py +148 -0
  14. seed/core/llm_exec.py +1652 -0
  15. seed/core/llm_presets.py +305 -0
  16. seed/core/llm_sess.py +1094 -0
  17. seed/core/media_store.py +84 -0
  18. seed/core/mem_bridge.py +294 -0
  19. seed/core/mem_sys.py +409 -0
  20. seed/core/model_providers.py +88 -0
  21. seed/core/models.py +211 -0
  22. seed/core/paths.py +109 -0
  23. seed/core/persistence.py +133 -0
  24. seed/core/proj_reg.py +609 -0
  25. seed/core/proj_todos.py +141 -0
  26. seed/core/projection_audit.py +317 -0
  27. seed/core/routing.py +192 -0
  28. seed/core/sess_store.py +44 -0
  29. seed/core/tool_output_cap.py +122 -0
  30. seed/core/tool_runtime.py +330 -0
  31. seed/core/trace_audit.py +123 -0
  32. seed/core/turn_loop.py +750 -0
  33. seed/core/usage_accumulator.py +72 -0
  34. seed/integrations/__init__.py +33 -0
  35. seed/integrations/agent_tools.py +160 -0
  36. seed/integrations/cron_sched.py +773 -0
  37. seed/integrations/env_config.py +77 -0
  38. seed/integrations/exec_backend.py +432 -0
  39. seed/integrations/hooks.py +61 -0
  40. seed/integrations/hooks_config.py +109 -0
  41. seed/integrations/instruction_release.py +256 -0
  42. seed/integrations/lsp_client.py +219 -0
  43. seed/integrations/lsp_config.py +99 -0
  44. seed/integrations/mcp_client.py +1283 -0
  45. seed/integrations/mcp_config.py +208 -0
  46. seed/integrations/mcp_registry.py +154 -0
  47. seed/integrations/message_api.py +16 -0
  48. seed/integrations/prompt_task.py +39 -0
  49. seed/integrations/safety.py +331 -0
  50. seed/integrations/session_title.py +211 -0
  51. seed/integrations/symbol_index.py +311 -0
  52. seed/integrations/task_runner.py +275 -0
  53. seed/integrations/webhook_auth.py +33 -0
  54. seed/integrations/webhook_dedup.py +132 -0
  55. seed/models.py +31 -0
  56. seed_kernel-1.0.11.dist-info/METADATA +17 -0
  57. seed_kernel-1.0.11.dist-info/RECORD +60 -0
  58. seed_kernel-1.0.11.dist-info/WHEEL +5 -0
  59. seed_kernel-1.0.11.dist-info/entry_points.txt +2 -0
  60. seed_kernel-1.0.11.dist-info/top_level.txt +1 -0
@@ -0,0 +1,331 @@
1
+ """
2
+ Safety — prompt-injection heuristics, output sanitization, bash policy, audit log.
3
+
4
+ Canonical implementation lives here under ``seed.integrations`` (IO / policy layer).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import logging
10
+ import os
11
+ import re
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+ from typing import List, Optional, Tuple
15
+
16
+ from seed.core.env_access import (
17
+ PROJECT_ROOT,
18
+ SAFETY_AUDIT_LOG,
19
+ SAFETY_BASH_ALLOWED_DIRS,
20
+ SAFETY_BASH_BLOCKED,
21
+ SAFETY_BASH_TIMEOUT_MAX,
22
+ SAFETY_REDACT_PII,
23
+ SAFETY_REDACT_SECRETS,
24
+ env_truthy,
25
+ pick_default,
26
+ pick_nonempty,
27
+ )
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # SafetyConfig — reads SEED_SAFETY_* (CODEAGENT_SAFETY_* deprecated alias)
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ class SafetyConfig:
37
+ """Reads safety-related env vars documented in ``config/env.example``."""
38
+
39
+ @staticmethod
40
+ def redact_secrets_enabled() -> bool:
41
+ return env_truthy(*SAFETY_REDACT_SECRETS, default="1")
42
+
43
+ @staticmethod
44
+ def redact_pii_enabled() -> bool:
45
+ return env_truthy(*SAFETY_REDACT_PII, default="0")
46
+
47
+ @staticmethod
48
+ def bash_blocked_patterns() -> List[str]:
49
+ raw = pick_default("", *SAFETY_BASH_BLOCKED) or ""
50
+ return [p.strip() for p in raw.split(",") if p.strip()]
51
+
52
+ @staticmethod
53
+ def bash_allowed_dirs() -> List[str]:
54
+ raw = (pick_default("", *SAFETY_BASH_ALLOWED_DIRS) or "").strip()
55
+ if not raw:
56
+ root = pick_nonempty(*PROJECT_ROOT)
57
+ dirs: List[str] = [root] if root else []
58
+ else:
59
+ dirs = [p.strip() for p in raw.split(";") if p.strip()]
60
+
61
+ # Web UI project workspace (external repo path) — allow bash default cwd there.
62
+ try:
63
+ from seed.core.agent_context import get_active_project_workspace_cwd
64
+
65
+ ws = (get_active_project_workspace_cwd() or "").strip()
66
+ if ws:
67
+ resolved_ws = str(Path(ws).expanduser().resolve())
68
+ covered = any(
69
+ resolved_ws.startswith(str(Path(d).expanduser().resolve()))
70
+ for d in dirs
71
+ )
72
+ if not covered:
73
+ dirs.append(resolved_ws)
74
+ except Exception:
75
+ pass
76
+
77
+ return dirs
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # Prompt injection detection
82
+ # ---------------------------------------------------------------------------
83
+
84
+ _PROMPT_INJECTION_SIGNATURES: Tuple[str, ...] = (
85
+ "ignore previous instructions",
86
+ "ignore all previous",
87
+ "disregard previous",
88
+ "you are now",
89
+ "you must ignore",
90
+ "developer mode",
91
+ "sudo mode",
92
+ "override your instructions",
93
+ "new instructions:",
94
+ "[system]",
95
+ "-----begin system-----",
96
+ "</system>",
97
+ "无需遵守",
98
+ "忽略以上",
99
+ "绕过限制",
100
+ )
101
+
102
+
103
+ def _detect_prompt_injection(text: str) -> List[str]:
104
+ """Check for known prompt injection signatures. Returns list of matched signatures."""
105
+ low = text.lower()
106
+ matches: List[str] = []
107
+ for sig in _PROMPT_INJECTION_SIGNATURES:
108
+ if sig in low:
109
+ matches.append(sig)
110
+ if len(matches) >= 3:
111
+ break
112
+ return matches
113
+
114
+
115
+ def _looks_like_tool_invocation(text: str, tool_name: str) -> bool:
116
+ """Heuristic: does the user text look like an attempt to invoke a tool directly?"""
117
+ if tool_name not in text:
118
+ return False
119
+ low = text.lower()
120
+ triggers = (
121
+ "call ",
122
+ "invoke ",
123
+ "use ",
124
+ "run ",
125
+ "execute ",
126
+ "请调用",
127
+ "请执行",
128
+ "请使用",
129
+ "调用",
130
+ "执行",
131
+ )
132
+ idx = low.find(tool_name.lower())
133
+ if idx < 0:
134
+ return False
135
+ start = max(0, idx - 40)
136
+ context = low[start:idx].strip()
137
+ for t in triggers:
138
+ if t in context:
139
+ return True
140
+ return False
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Secret / PII patterns
145
+ # ---------------------------------------------------------------------------
146
+
147
+ _SECRET_PATTERNS: Tuple[re.Pattern, ...] = (
148
+ re.compile(r'\b(?:sk|pk|ske|pke)(?:-[a-zA-Z0-9]{10,})\b'),
149
+ re.compile(
150
+ r'(?i)(?:api[_-]?key|apikey|secret[_-]?key|access[_-]?token)'
151
+ r'["\']?\s*[:=]\s*["\']?([a-zA-Z0-9_\-.]{16,})["\']?'
152
+ ),
153
+ re.compile(r'(?i)authorization:\s*bearer\s+[a-zA-Z0-9_\-.]{8,}'),
154
+ re.compile(r'\beyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\b'),
155
+ re.compile(r'(?i)(?:password|passwd|pwd)["\']?\s*[:=]\s*["\']?([^\s"\'"]{4,})["\']?'),
156
+ )
157
+
158
+ _PII_PATTERNS: Tuple[re.Pattern, ...] = (
159
+ re.compile(r'\b[1-9]\d{5}(?:19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]\b'),
160
+ re.compile(r'\b1[3-9]\d{9}\b'),
161
+ re.compile(r'\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b'),
162
+ re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b'),
163
+ )
164
+
165
+
166
+ def _redact_match(matched: str) -> str:
167
+ """Keep leading 3 chars + trailing 3 chars visible, redact the middle."""
168
+ if len(matched) <= 12:
169
+ return matched[:3] + "[REDACTED]"
170
+ return matched[:3] + "[REDACTED]" + matched[-3:]
171
+
172
+
173
+ def _redact_secrets(text: str) -> str:
174
+ """Replace known secret patterns with [REDACTED] marker."""
175
+ for pattern in _SECRET_PATTERNS:
176
+ text = pattern.sub(lambda m: _redact_match(m.group(0)), text)
177
+ return text
178
+
179
+
180
+ def _redact_pii(text: str) -> str:
181
+ """Replace PII patterns with [REDACTED] marker."""
182
+ for pattern in _PII_PATTERNS:
183
+ text = pattern.sub("[REDACTED]", text)
184
+ return text
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Output sanitization (LLM replies + tool results)
189
+ # ---------------------------------------------------------------------------
190
+
191
+
192
+ def sanitize_assistant_output(text: str) -> str:
193
+ """Sanitize LLM assistant output — redact secrets/PII if enabled."""
194
+ if not text:
195
+ return text
196
+ result = text
197
+ if SafetyConfig.redact_secrets_enabled():
198
+ result = _redact_secrets(result)
199
+ if SafetyConfig.redact_pii_enabled():
200
+ result = _redact_pii(result)
201
+ return result
202
+
203
+
204
+ def sanitize_tool_output(text: str, tool_name: Optional[str] = None) -> str:
205
+ """Sanitize tool execution output — redact secrets/PII if enabled."""
206
+ if not text:
207
+ return text
208
+ result = text
209
+ if SafetyConfig.redact_secrets_enabled():
210
+ result = _redact_secrets(result)
211
+ if SafetyConfig.redact_pii_enabled():
212
+ result = _redact_pii(result)
213
+ return result
214
+
215
+
216
+ # ---------------------------------------------------------------------------
217
+ # Bash command safety
218
+ # ---------------------------------------------------------------------------
219
+
220
+ _HARD_BLOCKED_BASH_PATTERNS: Tuple[re.Pattern, ...] = (
221
+ re.compile(r'\brm\s+(-\w*\s+)*/\s*'),
222
+ re.compile(r'\brm\s+(-\w*\s+)*--no-preserve-root\b'),
223
+ re.compile(r'\bdd\s+if='),
224
+ re.compile(r'\bmkfs\.'),
225
+ re.compile(r'\bmkswap\b'),
226
+ re.compile(r'\bformat\s+\w:'),
227
+ re.compile(r'\bfdisk\s+/dev/'),
228
+ re.compile(r'\bparted\s+/dev/'),
229
+ re.compile(r':\(\)\s*\{'),
230
+ re.compile(r'>\s*/dev/sd[a-z]'),
231
+ re.compile(r'>\s*/dev/nvme\d+n\d+'),
232
+ re.compile(r'>\s*/dev/mmcblk'),
233
+ re.compile(r'>\s*/dev/loop'),
234
+ re.compile(r'\bmv\s+(.*\s+)?/(?:etc|boot|bin|sbin|lib|lib64|usr)\b'),
235
+ re.compile(r'\bcp\s+(.*\s+)?/(?:etc|boot|bin|sbin)\b'),
236
+ re.compile(r'\bchmod\s+[-]?777\s+/\s*'),
237
+ re.compile(r'\bchown\s+.*\s+/\s*'),
238
+ re.compile(r'\bcurl\s+.*\|\s*(?:bash|sh|zsh)\b'),
239
+ re.compile(r'\bwget\s+.*\|\s*(?:bash|sh|zsh)\b'),
240
+ re.compile(r'\bcurl\s+.*\|\s*sh\b'),
241
+ re.compile(r'\bformat\s+/q?\s+[a-zA-Z]:'),
242
+ re.compile(r'\bdiskpart\b'),
243
+ re.compile(r'\breg\s+delete\s+HK'),
244
+ re.compile(r'\breg\s+add\s+HK.*/f\b'),
245
+ )
246
+
247
+
248
+ def check_bash_command(command: str, cwd: Optional[str] = None) -> Optional[str]:
249
+ """Check a shell command for safety. Returns error message string or None if safe."""
250
+ # (1) Hard-coded patterns
251
+ ext_cmd = re.sub(r"\s+-[a-zA-Z]*[if][a-zA-Z]*\s+", " ", command)
252
+ for pattern in _HARD_BLOCKED_BASH_PATTERNS:
253
+ if pattern.search(command) or pattern.search(ext_cmd):
254
+ logger.warning("Blocked dangerous bash command matching %s: %.200s", pattern.pattern, command)
255
+ return f"Error: Blocked dangerous command pattern: {pattern.pattern}"
256
+
257
+ # (2) User-configured extra patterns
258
+ for extra in SafetyConfig.bash_blocked_patterns():
259
+ try:
260
+ if re.search(extra, command, re.IGNORECASE):
261
+ logger.warning("Blocked by user safety pattern %s: %.200s", extra, command)
262
+ return f"Error: Blocked by safety pattern: {extra}"
263
+ except re.error:
264
+ if extra.lower() in command.lower():
265
+ return f"Error: Blocked by safety pattern: {extra}"
266
+
267
+ # (3) Working directory restriction
268
+ allowed = SafetyConfig.bash_allowed_dirs()
269
+ if cwd and allowed:
270
+ resolved_cwd = str(Path(cwd).resolve())
271
+ allowed_resolved = [str(Path(d).resolve()) for d in allowed]
272
+ if not any(resolved_cwd.startswith(d) for d in allowed_resolved):
273
+ logger.warning("Blocked bash command with disallowed cwd=%s (allowed=%s)", resolved_cwd, allowed_resolved)
274
+ return (
275
+ f"Error: Working directory '{resolved_cwd}' is not in the allowed list. "
276
+ f"Please use a directory under: {', '.join(allowed)}"
277
+ )
278
+
279
+ return None
280
+
281
+
282
+ def enforce_bash_timeout(requested_timeout: int) -> int:
283
+ """Clamp bash timeout to a safe upper bound."""
284
+ hard_max = int(pick_default("120", *SAFETY_BASH_TIMEOUT_MAX) or 120)
285
+ return min(requested_timeout, hard_max)
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # Audit log
290
+ # ---------------------------------------------------------------------------
291
+
292
+ _AUDIT_LOG_PATH: Optional[Path] = None
293
+
294
+
295
+ def _get_audit_log_path() -> Path:
296
+ global _AUDIT_LOG_PATH
297
+ if _AUDIT_LOG_PATH is None:
298
+ from seed.core.config_plane import project_root as _pr
299
+
300
+ root = str(_pr())
301
+ _AUDIT_LOG_PATH = Path(root) / "config" / "audit_log.jsonl"
302
+ return _AUDIT_LOG_PATH
303
+
304
+
305
+ def _log_safety_event(
306
+ event_type: str,
307
+ detail: str,
308
+ session_id: Optional[str] = None,
309
+ agent_id: Optional[str] = None,
310
+ severity: str = "info",
311
+ ) -> None:
312
+ """Append an event to the audit log (JSONL). Best-effort, never raises."""
313
+ if pick_default("0", *SAFETY_AUDIT_LOG).lower() not in ("1", "true", "yes", "on"):
314
+ return
315
+ try:
316
+ path = _get_audit_log_path()
317
+ path.parent.mkdir(parents=True, exist_ok=True)
318
+ record = {
319
+ "ts": datetime.now(timezone.utc).isoformat(),
320
+ "event_type": event_type,
321
+ "severity": severity,
322
+ "detail": detail,
323
+ }
324
+ if session_id:
325
+ record["session_id"] = session_id
326
+ if agent_id:
327
+ record["agent_id"] = agent_id
328
+ with path.open("a", encoding="utf-8") as f:
329
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
330
+ except Exception as exc:
331
+ logger.debug("Failed to write safety audit log: %s", exc)
@@ -0,0 +1,211 @@
1
+ """Use LLM to set Session.metadata['display_title'] for Web UI session list."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import re
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from seed.core import env_access as _ea
9
+ from seed.core.llm_sess import persist_chat_session
10
+ from seed.core.models import Session
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # 不把助手思维链/英文 CoT 喂给标题模型(否则会生成 “Thinking Process…” 类标题)
15
+ _THINKING_LINE = re.compile(
16
+ r"(?is)^(thinking\s*process|思考过程|思维链|chain\s*of\s*thought|<redacted_thinking|<think\b|\*\*thinking)",
17
+ )
18
+ _BULLET_ANALYZE = re.compile(r"^\s*\d+\.\s*\*\*\s*analyze\b", re.I)
19
+
20
+ # Auto-continue / strategy nudges (often injected as synthetic user messages).
21
+ # Must not drive session titles — aligned with CodeAgent ``_auto_continue_nudge`` outputs.
22
+ _AUTO_CONTINUE_NUDGE_PREFIX = "请继续完成未完成事项"
23
+ _AUTO_CONTINUE_PLAYBOOK_PREFIX = "上一段连续在"
24
+ _AUTO_CONTINUE_STRATEGY_TRIGGER = "【策略切换触发】"
25
+
26
+
27
+ def _is_user_content_session_title_nudge(content: str) -> bool:
28
+ """True if this user message is an auto-continue nudge, not real user intent."""
29
+ t = (content or "").strip()
30
+ if not t:
31
+ return False
32
+ if t.startswith(_AUTO_CONTINUE_NUDGE_PREFIX):
33
+ return True
34
+ if t.startswith(_AUTO_CONTINUE_PLAYBOOK_PREFIX):
35
+ return True
36
+ if t.startswith(_AUTO_CONTINUE_STRATEGY_TRIGGER):
37
+ return True
38
+ return False
39
+
40
+
41
+ def _skip_message_for_session_title(m: Dict[str, Any]) -> bool:
42
+ if not isinstance(m, dict) or m.get("role") != "user":
43
+ return False
44
+ if m.get("_skip_session_title") or m.get("skip_session_title"):
45
+ return True
46
+ return _is_user_content_session_title_nudge(str(m.get("content") or ""))
47
+
48
+
49
+ def _strip_assistant_noise_for_title(text: str) -> str:
50
+ t = str(text or "").strip().replace("\r\n", "\n")
51
+ if not t:
52
+ return ""
53
+ if _THINKING_LINE.search(t[:400]) or _BULLET_ANALYZE.search(t[:500]):
54
+ return ""
55
+ # 去掉常见 <think>…</think>
56
+ t = re.sub(r"(?is)<think>.*?</think>", "", t).strip()
57
+ return t
58
+
59
+
60
+ def _user_context_for_title(messages: List[Dict[str, Any]], *, max_msgs: int = 4, max_chars: int = 200) -> str:
61
+ """标题只依据用户原话,避免助手正文/思维链污染。"""
62
+ users: List[str] = []
63
+ for m in reversed(messages or []):
64
+ if not isinstance(m, dict) or m.get("role") != "user":
65
+ continue
66
+ if _skip_message_for_session_title(m):
67
+ continue
68
+ raw = str(m.get("content") or "").strip().replace("\r\n", "\n")
69
+ if not raw:
70
+ continue
71
+ if len(raw) > max_chars:
72
+ raw = raw[:max_chars] + "…"
73
+ users.append(raw)
74
+ if len(users) >= max_msgs:
75
+ break
76
+ if not users:
77
+ return ""
78
+ users.reverse()
79
+ return "\n".join(f"用户: {u}" for u in users)
80
+
81
+
82
+ def _fallback_title_from_users(messages: List[Dict[str, Any]], max_chars: int = 36) -> Optional[str]:
83
+ for m in reversed(messages or []):
84
+ if not isinstance(m, dict) or m.get("role") != "user":
85
+ continue
86
+ if _skip_message_for_session_title(m):
87
+ continue
88
+ t = str(m.get("content") or "").strip().replace("\r\n", " ")
89
+ if not t:
90
+ continue
91
+ t = re.sub(r"\s+", " ", t)
92
+ if len(t) > max_chars:
93
+ t = t[: max_chars - 1].rstrip() + "…"
94
+ return t
95
+ return None
96
+
97
+
98
+ def _title_looks_like_thinking_or_cot(title: str) -> bool:
99
+ s = (title or "").strip()
100
+ if not s:
101
+ return True
102
+ low = s.lower()
103
+ if "thinking process" in low or "analyze the" in low:
104
+ return True
105
+ if re.match(r"^\d+\.\s*\*+", s):
106
+ return True
107
+ if s.startswith("**") and "analyze" in low[:80]:
108
+ return True
109
+ return False
110
+
111
+
112
+ def _sanitize_title(raw: str, max_chars: int) -> str:
113
+ s = (raw or "").strip()
114
+ s = re.sub(r'^[\"\'「」『』【】\[\]()()]+|[\"\'「」『』【】\[\]()()]+$', "", s)
115
+ s = re.sub(r"\s+", " ", s).replace("\n", " ").strip()
116
+ if len(s) > max_chars:
117
+ s = s[: max_chars - 1].rstrip() + "…"
118
+ return s
119
+
120
+
121
+ def llm_generate_display_title(llm: Any, session: Session) -> Optional[str]:
122
+ from seed.core.llm_exec import LLMError
123
+
124
+ ctx = _user_context_for_title(session.messages or [])
125
+ if not ctx.strip():
126
+ ctx = _strip_assistant_noise_for_title(
127
+ str(
128
+ next(
129
+ (
130
+ m.get("content")
131
+ for m in reversed(session.messages or [])
132
+ if isinstance(m, dict) and m.get("role") == "assistant"
133
+ ),
134
+ "",
135
+ )
136
+ )
137
+ )
138
+ if ctx:
139
+ ctx = "助手摘要(已去思维链):\n" + ctx[:400]
140
+ if not ctx.strip():
141
+ return None
142
+ try:
143
+ max_c = int(_ea.pick_default("36", *_ea.SESSION_TITLE_MAX_CHARS))
144
+ except ValueError:
145
+ max_c = 36
146
+ max_c = max(8, min(max_c, 80))
147
+ sys_msg = (
148
+ "你是会话标题生成器。输入仅为「用户」说过的话(每行一条)。"
149
+ "请根据用户主题输出仅一行标题:简短自然,中文优先;"
150
+ "不要英文、不要模仿思考步骤、不要 “Thinking/Analyze” 等词;"
151
+ "不要引号、不要用「关于」开头、不要结尾句号,不要“会话”“聊天室”等泛词。"
152
+ )
153
+ user_msg = f"用户原话:\n{ctx}\n\n只输出一行标题,不超过{max_c}个字。"
154
+ try:
155
+ tok = int(_ea.pick_default("96", *_ea.SESSION_TITLE_MAX_TOKENS))
156
+ except ValueError:
157
+ tok = 96
158
+ tok = max(24, min(tok, 256))
159
+ try:
160
+ content, meta = llm.generate(
161
+ [
162
+ {"role": "system", "content": sys_msg},
163
+ {"role": "user", "content": user_msg},
164
+ ],
165
+ tools=None,
166
+ max_turns=1,
167
+ temperature=0.25,
168
+ max_tokens=tok,
169
+ )
170
+ except LLMError as e:
171
+ logger.warning("session title LLM failed: %s", e)
172
+ return None
173
+ if meta.get("tool_calls"):
174
+ logger.warning("session title LLM returned tool_calls, ignoring")
175
+ title = _sanitize_title(content, max_c)
176
+ if not title:
177
+ return _fallback_title_from_users(session.messages or [], max_c)
178
+ if _title_looks_like_thinking_or_cot(title):
179
+ logger.info("session title rejected as CoT-like, using user fallback")
180
+ return _fallback_title_from_users(session.messages or [], max_c)
181
+ return title
182
+
183
+
184
+ def maybe_llm_refresh_session_title(llm: Any, session: Session) -> None:
185
+ """
186
+ Writes metadata.display_title via LLM and re-persists session.
187
+
188
+ Synthetic auto-continue ``user`` messages (nudge / strategy playbook) are
189
+ excluded from title context so the model follows real user intent.
190
+
191
+ SEED_SESSION_TITLE_LLM (alias CODEAGENT_*): default 1; set 0 to disable.
192
+ SEED_SESSION_TITLE_MODE: default ``first`` (标题仅在首次成功生成后固定);
193
+ 设为 ``every`` 则每轮对话后重新提炼。
194
+ """
195
+ raw = _ea.pick_default("1", *_ea.SESSION_TITLE_LLM).lower()
196
+ if raw in ("0", "false", "no", "off"):
197
+ return
198
+ mode = _ea.pick_default("first", *_ea.SESSION_TITLE_MODE).strip().lower()
199
+ if mode not in ("first", "every"):
200
+ mode = "first"
201
+ if mode == "first" and session.metadata.get("display_title_source") == "llm":
202
+ return
203
+ title = llm_generate_display_title(llm, session)
204
+ if not title:
205
+ return
206
+ session.metadata["display_title"] = title
207
+ session.metadata["display_title_source"] = "llm"
208
+ try:
209
+ persist_chat_session(session)
210
+ except Exception:
211
+ logger.exception("persist after session title failed")