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,2384 @@
1
+ """LLM + tool registry: OpenAI-style multi-turn tool loop."""
2
+ from __future__ import annotations
3
+
4
+
5
+ from datetime import datetime, timezone
6
+ import json
7
+ import logging
8
+ import re
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
11
+
12
+ from seed.core.chat_events import is_chat_cancelled
13
+
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def _message_ts() -> str:
19
+ return datetime.now(timezone.utc).isoformat()
20
+
21
+
22
+ _COMPACT_BLOCK = re.compile(
23
+ r"\n<<<(?:SEED_COMPACT|CODEAGENT_COMPACT)>>>\n.*?\n<<<END_(?:SEED_COMPACT|CODEAGENT_COMPACT)>>>\n",
24
+ re.DOTALL,
25
+ )
26
+
27
+
28
+ # Grouping of tool names into "failure domains". When a loop ends with a streak
29
+ # of same-domain errors, the outer server loop can use this to switch strategy
30
+ # instead of naively replaying "please continue".
31
+ _FAILURE_DOMAIN_PREFIXES: Tuple[str, ...] = (
32
+ "browser_",
33
+ "bash",
34
+ "file_",
35
+ "web_",
36
+ )
37
+
38
+
39
+ def _classify_failure_domain(name: str) -> Optional[str]:
40
+ if not name:
41
+ return None
42
+ for p in _FAILURE_DOMAIN_PREFIXES:
43
+ if name.startswith(p):
44
+ return p
45
+ return None
46
+
47
+
48
+ def _is_tool_error_payload(payload: str) -> bool:
49
+ """Heuristic: did this tool result represent a failure the model should
50
+ NOT blindly retry with the same parameters?
51
+
52
+ We match:
53
+ - ``error:`` / ``Error:`` prefix produced by our executor wrappers
54
+ - raw Python exceptions that still made it through: ``Tool '...' execution error: ...``
55
+ - CDP timeouts that surface as normal tool strings containing
56
+ ``CDP timeout`` / ``timeout calling``
57
+ """
58
+ if not isinstance(payload, str):
59
+ return False
60
+ s = payload.lstrip()
61
+ if not s:
62
+ return False
63
+ low = s[:512].lower()
64
+ if low.startswith("error:"):
65
+ return True
66
+ if "execution error" in low:
67
+ return True
68
+ if "cdp timeout" in low or "timeout calling" in low:
69
+ return True
70
+ return False
71
+
72
+
73
+ def _detect_failure_streak(
74
+ outcomes: List[Tuple[str, bool, str]],
75
+ *,
76
+ min_streak: int = 3,
77
+ ) -> Optional[Dict[str, Any]]:
78
+ """Return info about a tail streak of same-domain errors, or ``None``.
79
+
80
+ ``outcomes``: list of ``(tool_name, is_error, payload_excerpt)`` in call order.
81
+ """
82
+ if not outcomes:
83
+ return None
84
+ tail: List[Tuple[str, str]] = []
85
+ for name, is_err, msg in reversed(outcomes):
86
+ if is_err:
87
+ tail.append((name, msg))
88
+ else:
89
+ break
90
+ if len(tail) < min_streak:
91
+ return None
92
+ domains = {_classify_failure_domain(n) for n, _ in tail}
93
+ if len(domains) != 1:
94
+ return None
95
+ dom = next(iter(domains))
96
+ if dom is None:
97
+ return None
98
+ tail.reverse()
99
+ return {
100
+ "domain": dom,
101
+ "streak": len(tail),
102
+ "recent_errors": [
103
+ {"tool": n, "error": (m or "")[:400]} for n, m in tail[-min_streak * 2 :]
104
+ ],
105
+ }
106
+
107
+
108
+
109
+
110
+
111
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
112
+
113
+ from seed.core.tool_runtime import ToolRegistry
114
+
115
+
116
+ def _consecutive_error_tail_count(outcomes: List[Tuple[str, bool, str]]) -> int:
117
+ n = 0
118
+ for _name, is_err, _msg in reversed(outcomes):
119
+ if is_err:
120
+ n += 1
121
+ else:
122
+ break
123
+ return n
124
+
125
+
126
+ def _last_consecutive_error_block(
127
+ outcomes: List[Tuple[str, bool, str]], k: int
128
+ ) -> List[Tuple[str, str]]:
129
+ """Most recent ``k`` outcomes among the trailing error run (newest last)."""
130
+ buf: List[Tuple[str, str]] = []
131
+ for name, is_err, msg in reversed(outcomes):
132
+ if not is_err:
133
+ break
134
+ buf.append((name or "", (msg or "")[:500]))
135
+ if len(buf) >= k:
136
+ break
137
+ buf.reverse()
138
+ return buf
139
+
140
+
141
+ def _format_tool_error_streak_nudge(block: List[Tuple[str, str]]) -> str:
142
+ lines = [
143
+ "[CodeAgent] 已连续多次工具调用返回错误。请阅读下列摘要,**换一种策略**"
144
+ "(换工具、换参数、或先排查环境),不要重复同一失败路径。",
145
+ "",
146
+ "最近错误摘要:",
147
+ ]
148
+ for i, (name, excerpt) in enumerate(block, 1):
149
+ lines.append(f"{i}. `{name}`: {excerpt[:320]}{'…' if len(excerpt) > 320 else ''}")
150
+ return "\n".join(lines)
151
+
152
+
153
+ def format_tool_segment_summary(
154
+ tools_used: List[str],
155
+ tool_trace: List[Dict[str, str]],
156
+ *,
157
+ max_trace: int = 8,
158
+ ) -> str:
159
+ """工具链调用摘要已禁用。保留签名兼容,始终返回空字符串。"""
160
+ _ = tools_used, tool_trace, max_trace # 标记参数已用(避免 lint warning)
161
+ return ""
162
+
163
+
164
+ DEFAULT_SYSTEM = """你是 CodeAgent:谨慎的编程与系统助手(此为配置缺失时的后备 system)。
165
+
166
+ 工具纪律:
167
+ - 问候、闲聊、致谢或无需文件/命令/搜索的一般问答:**只用自然语言回复,不要调工具**。
168
+ - 仅在用户明确需要执行时调用工具:读写文件、运行命令、搜索/代码分析、`calculate` 等。
169
+ - 若信息不足:先简短回答,**最多提一个**澄清问题,不要用工具瞎试。
170
+
171
+ 合法调用工具后,用简短文字向用户归纳结果。"""
172
+
173
+
174
+ def registry_to_openai_tools(
175
+ registry: ToolRegistry,
176
+ *,
177
+ include_names: Optional[Sequence[str]] = None,
178
+ exclude_prefixes: Optional[Sequence[str]] = None,
179
+ ) -> List[Dict[str, Any]]:
180
+ """Build Chat Completions ``tools`` payload from a ``ToolRegistry``."""
181
+ tools: List[Dict[str, Any]] = []
182
+ include_set = {n for n in (include_names or []) if n}
183
+ # Stable ordering matters for cache-prefix reuse (e.g. DeepSeek KV cache).
184
+ # Sort by tool name so plugin load order does not perturb the tools schema.
185
+ for tool in sorted(registry.list_all(), key=lambda t: (t.name or "")):
186
+ if include_set and tool.name not in include_set:
187
+ continue
188
+ if exclude_prefixes and any(
189
+ tool.name.startswith(p) for p in exclude_prefixes if p
190
+ ):
191
+ continue
192
+ props: Dict[str, Any] = {}
193
+ required: List[str] = []
194
+ for pname, pdef in (tool.parameters or {}).items():
195
+ props[pname] = {
196
+ "type": pdef.get("type", "string"),
197
+ "description": pdef.get("description", ""),
198
+ }
199
+ if pdef.get("required"):
200
+ required.append(pname)
201
+ tools.append(
202
+ {
203
+ "type": "function",
204
+ "function": {
205
+ "name": tool.name,
206
+ "description": tool.description or "",
207
+ "parameters": {
208
+ "type": "object",
209
+ "properties": props,
210
+ "required": required,
211
+ },
212
+ },
213
+ }
214
+ )
215
+ return tools
216
+
217
+
218
+
219
+
220
+ import re
221
+
222
+ # Chain-of-thought / reasoning markup (Qwen, DeepSeek, some proxies). Stripped
223
+ # before persisting assistant content so history does not reinforce repetition.
224
+ _THINK_BLOCK_RE = re.compile(
225
+ r"(?:"
226
+ r"<\s*think\s*>[\s\S]*?<\s*/\s*think\s*>"
227
+ r"|"
228
+ r"<\s*redacted_thinking\s*>[\s\S]*?<\s*/\s*redacted_thinking\s*>"
229
+ r")",
230
+ re.IGNORECASE,
231
+ )
232
+ _THINK_CLOSE_RE = re.compile(r"<\s*/\s*(?:think|redacted_thinking)\s*>", re.IGNORECASE)
233
+ _THINK_OPEN_RE = re.compile(r"<\s*(?:think|redacted_thinking)\s*>", re.IGNORECASE)
234
+ _HARMONY_CHANNEL_RE = re.compile(
235
+ r"<\|(?:start|channel|message|end|constrain|return)\|>",
236
+ re.IGNORECASE,
237
+ )
238
+
239
+
240
+ def _strip_think_markup(text: str) -> str:
241
+ """Remove <think>...</think> chain-of-thought from assistant content.
242
+
243
+ Handles three forms we have seen in the wild:
244
+ - balanced ``<think>...</think>``
245
+ - dangling ``</think>`` only (upstream stripped opening tag but left body)
246
+ - dangling ``<think>`` only (stream truncated before closing tag)
247
+ """
248
+ if not text:
249
+ return text
250
+ t = _THINK_BLOCK_RE.sub("", text)
251
+ # Dangling closing tag: treat everything up to and including it as thought.
252
+ m_close = _THINK_CLOSE_RE.search(t)
253
+ if m_close:
254
+ t = t[m_close.end():]
255
+ # Dangling opening tag: treat everything from it to end as thought.
256
+ m_open = _THINK_OPEN_RE.search(t)
257
+ if m_open:
258
+ t = t[:m_open.start()]
259
+ t = _HARMONY_CHANNEL_RE.sub("", t)
260
+ return t
261
+
262
+
263
+ # ---------------------------------------------------------------------------
264
+ # Bare chain-of-thought detection.
265
+ #
266
+ # Some local stacks (sglang without --reasoning-parser, plain vLLM, certain
267
+ # Ollama builds) stream Qwen3 / DeepSeek-R1 "thinking tokens" straight into
268
+ # ``content`` with NO ``<think>`` markup at all. The model then sees these
269
+ # prose thought monologues in its own history and produces more of them,
270
+ # which looks to the user like infinite repetition / "表演思考".
271
+ #
272
+ # Observed pathological prefixes (20k+ char bodies):
273
+ # "Here's a thinking process that leads to the suggested response: ..."
274
+ # "The user wants to confirm if ..."
275
+ # "User says ... I need to clarify ... Plan: 1. ... 2. ..."
276
+ # "用户纠正了我对...的理解。用户指出:1. ..."
277
+ # "我需要重新调整...的定义 ... **修正后的...**:"
278
+ #
279
+ # We can't strip partial CoT (no anchor), so we detect the whole-message
280
+ # pattern and redact it to an empty string. Upstream callers see assistant
281
+ # content=""/None and must either produce real output or call a tool.
282
+ # ---------------------------------------------------------------------------
283
+
284
+ # Strong CoT opener signals (single hit is enough when combined with length).
285
+ _BARE_COT_STRONG_OPENERS = (
286
+ # English (gpt-oss / R1-distill / Qwen3-Thinking leak)
287
+ "here's a thinking process",
288
+ "here is a thinking process",
289
+ "here is my thinking process",
290
+ "here's my thinking",
291
+ "let me think step by step",
292
+ "let me analyze this",
293
+ "let me analyze the user",
294
+ "let me analyze what",
295
+ "let me break this down",
296
+ "let me think through this",
297
+ "okay, let me think",
298
+ "okay, so the user",
299
+ "ok, so the user",
300
+ "the user wants to",
301
+ "the user is asking",
302
+ "the user says",
303
+ "the user's comment",
304
+ "the user's feedback",
305
+ "the user's question",
306
+ "the user is essentially",
307
+ "user wants to confirm",
308
+ "user says",
309
+ "user states",
310
+ "i need to clarify",
311
+ "i need to analyze",
312
+ "i need to understand",
313
+ "i need to figure out",
314
+ "first, i need to",
315
+ "first, let me",
316
+ "my plan is",
317
+ "plan:\n1.",
318
+ "plan:\n- ",
319
+ "plan:\n* ",
320
+ "step 1:",
321
+ "step 1.",
322
+ # Chinese CoT (observed in ae507677 / f7de03f6)
323
+ "用户纠正了我",
324
+ "用户指出:",
325
+ "用户指出:",
326
+ "用户说的是",
327
+ "用户的意思是",
328
+ "用户想要确认",
329
+ "用户想让我",
330
+ "用户希望我",
331
+ "用户的核心需求",
332
+ "我需要重新调整",
333
+ "我需要分析一下",
334
+ "我需要澄清",
335
+ "我需要先",
336
+ "我需要弄清楚",
337
+ "让我想一想",
338
+ "让我分析一下",
339
+ "让我思考一下",
340
+ "让我先",
341
+ "好的,让我",
342
+ "好的,我来思考",
343
+ "好,我来想一下",
344
+ "我的失误",
345
+ "修正后的",
346
+ "修正版分析",
347
+ "修正后角色定位",
348
+ "思考过程:",
349
+ "思维过程:",
350
+ "分析用户的",
351
+ "分析一下用户",
352
+ )
353
+
354
+ # Structural markers that amplify suspicion. Any single hit in the opening
355
+ # of the body is enough to classify a CoT-prefixed message as a monologue.
356
+ _BARE_COT_STRUCTURE_MARKERS = (
357
+ re.compile(r"(?im)^\s*(?:plan|steps?|thinking)\s*[::]\s*$"),
358
+ re.compile(r"(?im)^\s*\d+\.\s+\*\*(?:analyze|evaluate|identify|determine|check|confirm|verify|explain|clarify)\b"),
359
+ re.compile(r"(?im)^\s*\*\*(?:analyze|evaluate|identify|determine)\s"),
360
+ re.compile(r"(?im)^\s*\d+\.\s+\*\*\s*(?:分析|评估|识别|确认|澄清|思考|判断|检查)"),
361
+ re.compile(r"(?im)^\s*\*\s+\*\*(?:user|agent|model)'s?\s"),
362
+ # Enumerated self-quote of user statements ("用户指出:" followed by "1. ... 2. ...").
363
+ re.compile(r"(?s)用户(?:指出|说的是|的意思|想要|希望)[::].{0,30}\n\s*\d+\."),
364
+ # Self-plan heading in English ("Plan:\n1." or "Steps:\n1.")
365
+ re.compile(r"(?im)^\s*(?:plan|steps?|outline)\s*[::]\s*\n\s*\d+\."),
366
+ # Two or more "Let me ..." / "I need to ..." / "First, I ..." in a row
367
+ # strongly signal a monologue.
368
+ re.compile(r"(?is)\blet me\b.{1,200}\b(?:let me|i need to|first,? i|then i|next,? i)\b"),
369
+ re.compile(r"(?is)我需要.{1,200}(?:我需要|首先|然后|接下来|让我)"),
370
+ re.compile(r"(?is)用户.{1,300}\b(?:我需要|我应该|我必须|我来|让我)"),
371
+ )
372
+
373
+
374
+ def _is_bare_chain_of_thought(text: str) -> bool:
375
+ """Heuristic: does this assistant content look like raw chain-of-thought
376
+ leaked into the message body (without any ``<think>`` markup)?
377
+
378
+ Design goals:
379
+ - Extremely high precision on multi-kilobyte CoT dumps like
380
+ "Here's a thinking process that leads to the suggested response: ..."
381
+ - Near-zero false positives on real answers. A real answer might start
382
+ with "我需要" once, but will not also contain the Plan/Step/Analyze
383
+ skeleton *and* be >1200 chars.
384
+
385
+ We require BOTH:
386
+ 1. The opening (first 400 chars, lower-cased) hits a strong CoT phrase.
387
+ 2. Either (a) the body is long (>1200 chars) OR (b) there is at least one
388
+ structural marker (numbered analyze/evaluate/identify skeleton).
389
+ """
390
+ if not text:
391
+ return False
392
+ body = text.strip()
393
+ if len(body) < 400:
394
+ # Short replies are almost never full CoT dumps; leave them alone.
395
+ return False
396
+ head = body[:400].lower()
397
+ strong = False
398
+ for needle in _BARE_COT_STRONG_OPENERS:
399
+ if needle in head:
400
+ strong = True
401
+ break
402
+ if not strong:
403
+ return False
404
+ # Length alone is sufficient once we're past the soft threshold, because
405
+ # the opener already matched and real answers rarely exceed ~600 chars
406
+ # while still opening with "Let me analyze" / "我需要" / "The user wants".
407
+ if len(body) > 600:
408
+ return True
409
+ for rx in _BARE_COT_STRUCTURE_MARKERS:
410
+ if rx.search(body[:2000]):
411
+ return True
412
+ return False
413
+
414
+
415
+ def scrub_bare_cot_from_assistant_text(text: str) -> str:
416
+ """If the content is a bare CoT monologue, redact to empty so it doesn't
417
+ pollute the next turn's context. Otherwise return as-is.
418
+
419
+ This runs AFTER ``_strip_think_markup`` in the assistant-content pipeline,
420
+ so by the time we get here we are looking at markup-free prose.
421
+ """
422
+ if not text:
423
+ return text
424
+ if _is_bare_chain_of_thought(text):
425
+ return ""
426
+ return text
427
+
428
+
429
+
430
+
431
+
432
+ import json
433
+ import os
434
+ import re
435
+ from typing import Any, Dict, List, Optional
436
+
437
+ from seed.core import env_access as _ea
438
+ from seed.core.llm_exec import LLMAPIExecutor
439
+
440
+ _COMPACT_BLOCK = re.compile(
441
+ r"\n<<<(?:SEED_COMPACT|CODEAGENT_COMPACT)>>>\n.*?\n<<<END_(?:SEED_COMPACT|CODEAGENT_COMPACT)>>>\n",
442
+ re.DOTALL,
443
+ )
444
+
445
+
446
+ def _clean_invalid_tool_call_arguments(messages: List[Dict[str, Any]]) -> None:
447
+ """In-place: strip tool_calls whose ``function.arguments`` is not valid JSON.
448
+
449
+ Historical self-heal for sessions that were saved *before* llm_exec started
450
+ validating LLM tool_call arguments. When a streaming response was truncated
451
+ (network blip, token limit, mid-arg server drop), the accumulated
452
+ ``function.arguments`` was often ``""`` or partial JSON. Persisting that
453
+ poisons the conversation: the next LLM call rejects the whole request with
454
+ ``HTTP 400 invalid function arguments json string``.
455
+
456
+ For each assistant message we drop the malformed entries. If the assistant
457
+ message has no remaining tool_calls after the sweep but does have text, we
458
+ keep the message as plain text. If the message was *only* a malformed
459
+ tool_call (no content / whitespace-only content), we remove the message
460
+ entirely so we don't leave a content-less assistant turn.
461
+
462
+ This is best-effort: it only inspects a message's *own* tool_calls. Tool
463
+ responses (role=tool) for the dropped ids become orphaned; the
464
+ ``_clean_orphaned_tool_calls`` pass that follows will deal with them.
465
+ """
466
+ if not messages:
467
+ return
468
+ for m in messages:
469
+ if not isinstance(m, dict) or m.get("role") != "assistant":
470
+ continue
471
+ raw_tc = m.get("tool_calls")
472
+ if not raw_tc or not isinstance(raw_tc, list):
473
+ continue
474
+ kept: List[Dict[str, Any]] = []
475
+ dropped_ids: List[str] = []
476
+ for tc in raw_tc:
477
+ if not isinstance(tc, dict):
478
+ continue
479
+ fn = tc.get("function") or {}
480
+ if not isinstance(fn, dict):
481
+ continue
482
+ args = fn.get("arguments")
483
+ if not isinstance(args, str) or not args.strip():
484
+ dropped_ids.append(str(tc.get("id") or "?"))
485
+ continue
486
+ try:
487
+ json.loads(args)
488
+ except (json.JSONDecodeError, TypeError, ValueError):
489
+ dropped_ids.append(str(tc.get("id") or "?"))
490
+ continue
491
+ kept.append(tc)
492
+ if dropped_ids:
493
+ logger.warning(
494
+ "Stripped %d tool_call(s) with invalid JSON arguments "
495
+ "(likely from prior streaming truncation): %s",
496
+ len(dropped_ids), dropped_ids[:5],
497
+ )
498
+ if kept:
499
+ m["tool_calls"] = kept
500
+ else:
501
+ m.pop("tool_calls", None)
502
+ # If the message was only a broken tool_call with no text content,
503
+ # drop the empty assistant turn entirely.
504
+ if not str(m.get("content") or "").strip():
505
+ # Mark for removal: tag with sentinel, sweeper removes.
506
+ m["_invalid_tc_drop_turn"] = True
507
+
508
+
509
+ def _sweep_empty_invalid_tc_turns(messages: List[Dict[str, Any]]) -> None:
510
+ """In-place: remove assistant turns tagged by ``_clean_invalid_tool_call_arguments``
511
+ that have no text content left (only had malformed tool_calls)."""
512
+ if not messages:
513
+ return
514
+ i = 0
515
+ while i < len(messages):
516
+ m = messages[i]
517
+ if (
518
+ isinstance(m, dict)
519
+ and m.get("_invalid_tc_drop_turn")
520
+ ):
521
+ messages.pop(i)
522
+ continue
523
+ i += 1
524
+
525
+
526
+ def _clean_orphaned_tool_calls(messages: List[Dict[str, Any]]) -> None:
527
+ """In-place: remove assistant tool_calls that lack matching tool responses.
528
+
529
+ When the tool loop is interrupted mid-execution (crash, disconnect, restart),
530
+ the messages list may end with an assistant message containing ``tool_calls``
531
+ but no corresponding ``tool`` role responses. DeepSeek (and other strict
532
+ OpenAI-compatible APIs) reject such incomplete histories with HTTP 400.
533
+
534
+ This function scans backwards for orphaned tool_calls and either:
535
+ - strips ``tool_calls`` from the assistant message (if it has text content)
536
+ - removes the entire message (if content is empty or whitespace-only)
537
+ """
538
+ if not messages:
539
+ return
540
+ i = len(messages) - 1
541
+ while i >= 0:
542
+ msg = messages[i]
543
+ if not isinstance(msg, dict) or msg.get("role") != "assistant":
544
+ i -= 1
545
+ continue
546
+ raw_tc = msg.get("tool_calls")
547
+ if not raw_tc:
548
+ i -= 1
549
+ continue
550
+ # Collect tool_call_ids from this assistant message
551
+ call_ids = set()
552
+ for tc in raw_tc:
553
+ if isinstance(tc, dict):
554
+ tid = (tc.get("id") or "").strip()
555
+ if tid:
556
+ call_ids.add(tid)
557
+ if not call_ids:
558
+ i -= 1
559
+ continue
560
+ # Check messages after this position for matching tool responses
561
+ following = messages[i + 1:]
562
+ responded_ids = set()
563
+ for fm in following:
564
+ if isinstance(fm, dict) and fm.get("role") == "tool":
565
+ tid = (fm.get("tool_call_id") or "").strip()
566
+ if tid in call_ids:
567
+ responded_ids.add(tid)
568
+ missing = call_ids - responded_ids
569
+ if missing:
570
+ content = msg.get("content") or ""
571
+ if content.strip():
572
+ # Keep assistant message as regular text, drop tool_calls
573
+ del msg["tool_calls"]
574
+ logger.warning(
575
+ "Cleaned orphaned tool_calls from assistant msg "
576
+ "(missing %d tool response(s)): %s",
577
+ len(missing), sorted(missing)[:3],
578
+ )
579
+ else:
580
+ # No text content → remove the entire orphaned message
581
+ messages.pop(i)
582
+ logger.warning(
583
+ "Removed empty assistant msg with orphaned tool_calls "
584
+ "(missing %d tool response(s)): %s",
585
+ len(missing), sorted(missing)[:3],
586
+ )
587
+ i -= 1
588
+
589
+
590
+ def _clean_orphaned_tool_results(messages: List[Dict[str, Any]]) -> None:
591
+ """In-place: remove ``tool`` messages whose ``tool_call_id`` is unmatched.
592
+
593
+ ``_clean_invalid_tool_call_arguments`` can strip malformed ``tool_calls`` from
594
+ an assistant turn while leaving its ``tool`` responses in place. Strict
595
+ providers (MiniMax, DeepSeek, …) then reject the next request with HTTP 400
596
+ ``tool result's tool id … not found``.
597
+ """
598
+ if not messages:
599
+ return
600
+ valid_ids: set[str] = set()
601
+ for msg in messages:
602
+ if not isinstance(msg, dict) or msg.get("role") != "assistant":
603
+ continue
604
+ for tc in msg.get("tool_calls") or []:
605
+ if not isinstance(tc, dict):
606
+ continue
607
+ tid = (tc.get("id") or "").strip()
608
+ if tid:
609
+ valid_ids.add(tid)
610
+ i = 0
611
+ while i < len(messages):
612
+ msg = messages[i]
613
+ if not isinstance(msg, dict) or msg.get("role") != "tool":
614
+ i += 1
615
+ continue
616
+ tid = (msg.get("tool_call_id") or "").strip()
617
+ if tid and tid not in valid_ids:
618
+ logger.warning(
619
+ "Removing orphaned tool result (tool_call_id=%r has no assistant tool_call)",
620
+ tid,
621
+ )
622
+ messages.pop(i)
623
+ continue
624
+ i += 1
625
+
626
+
627
+ _AUTO_CONTINUE_NUDGE_PREFIXES = (
628
+ "请继续完成未完成事项",
629
+ "上一段连续在",
630
+ )
631
+
632
+ _EPHEMERAL_MESSAGE_KEYS = (
633
+ "_source_idx",
634
+ "_auto_continue_nudge",
635
+ "_streaming",
636
+ )
637
+
638
+
639
+ def _is_auto_continue_nudge_message(message: Dict[str, Any]) -> bool:
640
+ if message.get("_auto_continue_nudge"):
641
+ return True
642
+ if message.get("role") != "user":
643
+ return False
644
+ content = message.get("content")
645
+ if not isinstance(content, str):
646
+ return False
647
+ return any(content.startswith(prefix) for prefix in _AUTO_CONTINUE_NUDGE_PREFIXES)
648
+
649
+
650
+ def _user_round_indices(body: List[Dict[str, Any]]) -> List[int]:
651
+ """User-started blocks, excluding auto-continue nudge injections."""
652
+ return [
653
+ i
654
+ for i, m in enumerate(body)
655
+ if isinstance(m, dict)
656
+ and m.get("role") == "user"
657
+ and not _is_auto_continue_nudge_message(m)
658
+ ]
659
+
660
+
661
+ def strip_ephemeral_message_fields(messages: List[Dict[str, Any]]) -> None:
662
+ """Remove in-memory-only metadata before LLM/tool persistence."""
663
+ for message in messages:
664
+ if not isinstance(message, dict):
665
+ continue
666
+ for key in _EPHEMERAL_MESSAGE_KEYS:
667
+ message.pop(key, None)
668
+
669
+
670
+ def persist_compact_summary(
671
+ full_messages: List[Dict[str, Any]],
672
+ compact_result: Optional[Dict[str, Any]],
673
+ ) -> bool:
674
+ """Write compact summary onto the correct message in persisted history."""
675
+ if not compact_result or not full_messages:
676
+ return False
677
+ summary = compact_result.get("compact_summary")
678
+ if not isinstance(summary, str) or not summary.strip():
679
+ return False
680
+ raw_idx = compact_result.get("boundary_source_idx", compact_result.get("boundary_idx"))
681
+ try:
682
+ idx = int(raw_idx)
683
+ except (TypeError, ValueError):
684
+ return False
685
+ if 0 <= idx < len(full_messages):
686
+ full_messages[idx]["_compact_summary"] = summary.strip()
687
+ return True
688
+ return False
689
+
690
+
691
+ def build_api_projection_messages(
692
+ full_messages: List[Dict[str, Any]],
693
+ *,
694
+ skills_suffix: Optional[str] = None,
695
+ cursor: Optional[Dict[str, Any]] = None,
696
+ ) -> List[Dict[str, Any]]:
697
+ """
698
+ Deep-copy ``full_messages`` and apply in-memory-only shaping for the LLM:
699
+ optional skills suffix on ``system``.
700
+
701
+ **链式摘要重建**:扫描 ``_compact_summary`` 字段(见 ``maybe_compact_context_messages``),
702
+ 找到最新的边界消息,将其之前的所有消息替换为 ``<<<SEED_COMPACT>>>`` 块注入 system prompt,
703
+ 从而避免每轮用全部原始消息做投影。
704
+
705
+ **会话游标**(``cursor`` 参数):
706
+ - None / ``{"mode": "tail"}``:默认行为,从末尾向后取全部消息
707
+ (由上层 ``maybe_compact_context_messages`` 负责压缩控制)
708
+ - ``{"mode": "head", "from_idx": N}``:从 ``full_messages[N]`` 开始投影(回滚模式),
709
+ 此时跳过链式摘要重建(因为用户想从头看原始消息)
710
+
711
+ Pass the result to ``maybe_compact_context_messages`` / ``run_llm_tool_loop``;
712
+ do not replace persisted ``Session.messages`` with this list.
713
+ """
714
+ import copy as _copy
715
+
716
+ api = _copy.deepcopy(full_messages)
717
+ for i, message in enumerate(api):
718
+ if isinstance(message, dict):
719
+ message["_source_idx"] = i
720
+
721
+ # ── 会话游标 ──
722
+ _cursor = cursor or {}
723
+ _cursor_mode = _cursor.get("mode", "tail")
724
+ if _cursor_mode == "head":
725
+ from_idx = int(_cursor.get("from_idx", 0))
726
+ if from_idx > 0 and from_idx < len(api):
727
+ has_sys = bool(api and api[0].get("role") == "system")
728
+ if has_sys and from_idx > 0:
729
+ # 保留 system,从 from_idx 开始取消息
730
+ api = [api[0]] + api[from_idx:]
731
+ else:
732
+ api = api[from_idx:]
733
+ # head 模式下跳过链式摘要重建(用户想从该点重新开始)
734
+ elif _cursor_mode == "tail":
735
+ # ── 链式摘要重建:扫描 _compact_summary,取最晚一条 ──
736
+ _last_bound_idx: int | None = None
737
+ _last_summary: str | None = None
738
+ for i, m in enumerate(api):
739
+ cs = m.get("_compact_summary")
740
+ if isinstance(cs, str) and cs.strip():
741
+ _last_bound_idx = i
742
+ _last_summary = cs.strip()
743
+
744
+ if _last_bound_idx is not None and _last_summary and _last_bound_idx > 0:
745
+ if api and api[0].get("role") == "system":
746
+ sys_msg = api[0]
747
+ base = strip_compact_block_from_system(str(sys_msg.get("content") or ""))
748
+ block = (
749
+ "\n\n<<<SEED_COMPACT>>>\n"
750
+ "## Earlier conversation (compressed)\n"
751
+ f"{_last_summary}\n"
752
+ "<<<END_SEED_COMPACT>>>\n"
753
+ )
754
+ sys_msg["content"] = base + block
755
+ # 保留 system + 边界消息及之后的所有消息
756
+ api = [sys_msg] + api[_last_bound_idx:]
757
+
758
+ if skills_suffix and api and api[0].get("role") == "system":
759
+ api[0]["content"] = str(api[0].get("content") or "").rstrip() + skills_suffix
760
+ # Hard cap on conversation history by user-rounds (opt-in via
761
+ # SEED_CHAT_USER_ROUNDS; 0 = disabled). Bounds prompt growth even when the
762
+ # API-token-driven compaction is unavailable (CLI / task / cron paths).
763
+ # Trimming happens on a user-message boundary; orphan tool_calls/results
764
+ # left behind are removed by the cleaning passes below.
765
+ _max_user_rounds = _ea.pick_int(0, *_ea.CHAT_USER_ROUNDS)
766
+ if _max_user_rounds > 0:
767
+ api = trim_messages_by_user_rounds(api, _max_user_rounds)
768
+ # Drop tool_calls with invalid JSON arguments first (historical self-heal
769
+ # for sessions saved before llm_exec started validating them), then remove
770
+ # assistant turns that became empty as a result, then clean orphans.
771
+ _clean_invalid_tool_call_arguments(api)
772
+ _sweep_empty_invalid_tc_turns(api)
773
+ _clean_orphaned_tool_calls(api)
774
+ _clean_orphaned_tool_results(api)
775
+ return api
776
+
777
+
778
+ def merge_llm_tail_into_full(
779
+ full_messages: List[Dict[str, Any]],
780
+ api_messages: List[Dict[str, Any]],
781
+ n_before_llm: int,
782
+ ) -> List[Dict[str, Any]]:
783
+ """Append messages produced during ``run_llm_tool_loop`` (``api_messages[n_before_llm:]``) onto ``full_messages``."""
784
+ if n_before_llm < 0:
785
+ n_before_llm = 0
786
+ tail = [
787
+ message
788
+ for message in api_messages[n_before_llm:]
789
+ if not (isinstance(message, dict) and _is_auto_continue_nudge_message(message))
790
+ ]
791
+ if tail:
792
+ # If the last message in full is a streaming placeholder and tail starts
793
+ # with an assistant message, replace the placeholder to avoid duplicate.
794
+ if (full_messages
795
+ and full_messages[-1].get("_streaming")
796
+ and tail[0].get("role") == "assistant"):
797
+ persisted = dict(tail[0])
798
+ strip_ephemeral_message_fields([persisted])
799
+ if "ts" not in persisted or not persisted["ts"]:
800
+ persisted["ts"] = datetime.now(timezone.utc).isoformat()
801
+ full_messages[-1] = persisted
802
+ tail = tail[1:]
803
+ if tail:
804
+ persisted_tail = []
805
+ for message in tail:
806
+ if not isinstance(message, dict):
807
+ persisted_tail.append(message)
808
+ continue
809
+ copied = dict(message)
810
+ strip_ephemeral_message_fields([copied])
811
+ # 确保每条消息都带时间戳,刷新后历史时间显示
812
+ if "ts" not in copied or not copied["ts"]:
813
+ copied["ts"] = datetime.now(timezone.utc).isoformat()
814
+ persisted_tail.append(copied)
815
+ full_messages.extend(persisted_tail)
816
+ return tail
817
+
818
+
819
+ def trim_messages_by_user_rounds(
820
+ messages: List[Dict[str, Any]],
821
+ max_user_rounds: int,
822
+ ) -> List[Dict[str, Any]]:
823
+ """
824
+ Keep the system message (if present) and the last N user-started conversation blocks.
825
+ Prevents unbounded growth of `messages` when tool outputs are large.
826
+ """
827
+ if max_user_rounds <= 0 or len(messages) <= 2:
828
+ return messages
829
+ has_system = bool(messages and messages[0].get("role") == "system")
830
+ body_start = 1 if has_system else 0
831
+ body = messages[body_start:]
832
+ # 包括所有 role=user 的消息作为轮次边界(含 _auto_continue_nudge),
833
+ # 让自主模式的分块渐进压缩能按 chunk 边界切分。
834
+ user_idx = [
835
+ i for i, m in enumerate(body)
836
+ if isinstance(m, dict) and m.get("role") == "user"
837
+ ]
838
+ if len(user_idx) <= max_user_rounds:
839
+ return messages
840
+ cut = user_idx[len(user_idx) - max_user_rounds]
841
+ trimmed = body[cut:]
842
+ if has_system:
843
+ return [messages[0]] + trimmed
844
+ return trimmed
845
+
846
+
847
+ def strip_compact_block_from_system(system_text: str) -> str:
848
+ """Remove a previously injected compact summary from system prompt text."""
849
+ return _COMPACT_BLOCK.sub("\n", system_text).strip()
850
+
851
+
852
+ def _context_compact_enabled() -> bool:
853
+ return _ea.pick_default("", *_ea.CONTEXT_COMPACT).lower() in (
854
+ "1",
855
+ "true",
856
+ "yes",
857
+ "on",
858
+ )
859
+
860
+
861
+ def _context_compact_mid_loop_enabled() -> bool:
862
+ if not _context_compact_enabled():
863
+ return False
864
+ return _ea.pick_default("0", *_ea.CONTEXT_COMPACT_MID_LOOP).lower() in (
865
+ "1",
866
+ "true",
867
+ "yes",
868
+ "on",
869
+ )
870
+
871
+
872
+ def _context_compact_adaptive_keep_enabled() -> bool:
873
+ return _ea.pick_default("0", *_ea.CONTEXT_COMPACT_ADAPTIVE_KEEP).lower() in (
874
+ "1",
875
+ "true",
876
+ "yes",
877
+ "on",
878
+ )
879
+
880
+
881
+ def _api_prompt_tokens(
882
+ messages: List[Dict[str, Any]],
883
+ *,
884
+ api_prompt_tokens: Optional[int] = None,
885
+ meta: Optional[Dict[str, Any]] = None,
886
+ ) -> int:
887
+ """LLM API ``usage.prompt_tokens`` only — no local message estimation."""
888
+ _ = messages # signature kept for call-site clarity
889
+ if api_prompt_tokens is not None and int(api_prompt_tokens) > 0:
890
+ return int(api_prompt_tokens)
891
+ if isinstance(meta, dict):
892
+ usage = meta.get("usage")
893
+ if isinstance(usage, dict):
894
+ pt = usage.get("prompt_tokens")
895
+ if isinstance(pt, (int, float)) and int(pt) > 0:
896
+ return int(pt)
897
+ return 0
898
+
899
+
900
+ def resolve_compact_trigger_tokens(
901
+ *,
902
+ persisted: Optional[Dict[str, Any]] = None,
903
+ loop_meta: Optional[Dict[str, Any]] = None,
904
+ api_prompt_tokens: Optional[int] = None,
905
+ ) -> int:
906
+ """Best-effort compact trigger size from API usage (never local estimation).
907
+
908
+ Takes the maximum of explicit ``api_prompt_tokens``, persisted session
909
+ ``context_usage`` (``peak_prompt_tokens`` / ``prompt_tokens``), and the
910
+ in-flight ``loop_meta.peak_prompt_tokens``.
911
+ """
912
+ candidates: List[int] = []
913
+ if api_prompt_tokens is not None:
914
+ try:
915
+ pt = int(api_prompt_tokens)
916
+ if pt > 0:
917
+ candidates.append(pt)
918
+ except (TypeError, ValueError):
919
+ pass
920
+ if isinstance(persisted, dict):
921
+ for key in ("peak_prompt_tokens", "prompt_tokens"):
922
+ raw = persisted.get(key)
923
+ if isinstance(raw, (int, float)) and int(raw) > 0:
924
+ candidates.append(int(raw))
925
+ if isinstance(loop_meta, dict):
926
+ raw = loop_meta.get("peak_prompt_tokens")
927
+ if isinstance(raw, (int, float)) and int(raw) > 0:
928
+ candidates.append(int(raw))
929
+ return max(candidates) if candidates else 0
930
+
931
+
932
+ def _record_peak_prompt_tokens(loop_meta: Dict[str, Any], meta: Optional[Dict[str, Any]]) -> None:
933
+ if not isinstance(meta, dict):
934
+ return
935
+ usage = meta.get("usage")
936
+ if not isinstance(usage, dict):
937
+ return
938
+ pt = usage.get("prompt_tokens")
939
+ if not isinstance(pt, (int, float)) or int(pt) <= 0:
940
+ return
941
+ prev = int(loop_meta.get("peak_prompt_tokens") or 0)
942
+ loop_meta["peak_prompt_tokens"] = max(prev, int(pt))
943
+
944
+
945
+ # Runtime override for compact min tokens (set via API, not persisted)
946
+ _compact_min_tokens_override: Optional[int] = None
947
+
948
+ def set_compact_min_tokens(val: int) -> None:
949
+ """Set runtime override for compact min tokens (0 = disable)."""
950
+ global _compact_min_tokens_override
951
+ _compact_min_tokens_override = max(0, int(val))
952
+
953
+ def _get_compact_min_tokens() -> int:
954
+ """Get compact trigger threshold in tokens (default: 30000).
955
+
956
+ Priority: runtime override > env var > default 30000.
957
+ """
958
+ global _compact_min_tokens_override
959
+ if _compact_min_tokens_override is not None:
960
+ return _compact_min_tokens_override
961
+ tok = _ea.pick_nonempty(*_ea.CONTEXT_COMPACT_MIN_TOKENS)
962
+ if tok:
963
+ return max(1000, int(tok))
964
+ return 30000
965
+
966
+
967
+ # Known model context windows (beyond MiniMax catalog)
968
+ _KNOWN_CONTEXT_WINDOWS: Dict[str, int] = {
969
+ "deepseek": 128_000,
970
+ "gpt-4": 128_000,
971
+ "gpt-3.5": 16_000,
972
+ "claude": 200_000,
973
+ "gemini": 1_000_000,
974
+ "qwen": 128_000,
975
+ "glm": 128_000,
976
+ "yi": 128_000,
977
+ "moonshot": 128_000,
978
+ "baichuan": 128_000,
979
+ "mistral": 128_000,
980
+ "llama": 128_000,
981
+ }
982
+
983
+
984
+ def _resolve_context_limit(model_name: Optional[str] = None) -> int:
985
+ """Resolve the model's context window limit in tokens.
986
+
987
+ Priority:
988
+ 1. SEED_LLM_CONTEXT_SIZE env override
989
+ 2. MINIMAX_CONTEXT_WINDOWS lookup by model name
990
+ 3. _KNOWN_CONTEXT_WINDOWS prefix match
991
+ 4. Fallback: min_tok * 10 (legacy behavior)
992
+ """
993
+ override = _ea.pick_nonempty("SEED_LLM_CONTEXT_SIZE")
994
+ if override:
995
+ return max(1000, int(override))
996
+ if model_name:
997
+ try:
998
+ from seed.core.llm_exec import MINIMAX_CONTEXT_WINDOWS
999
+ _mn = str(model_name).strip().lower()
1000
+ # Try exact match first
1001
+ ctx = MINIMAX_CONTEXT_WINDOWS.get(_mn, 0)
1002
+ if ctx <= 0:
1003
+ for _key, _val in MINIMAX_CONTEXT_WINDOWS.items():
1004
+ if _mn == _key.lower() or _mn.startswith(_key.lower()):
1005
+ ctx = _val
1006
+ break
1007
+ if ctx > 0:
1008
+ logger.info("[CTX_LIMIT] model=%s resolved=%s (minimax)", model_name, ctx)
1009
+ return ctx
1010
+ # Try known model prefixes (including after provider/ prefix)
1011
+ _match_names = [_mn]
1012
+ if "/" in _mn:
1013
+ _match_names.append(_mn.split("/", 1)[1])
1014
+ for _prefix, _ctx in _KNOWN_CONTEXT_WINDOWS.items():
1015
+ for _n in _match_names:
1016
+ if _n.startswith(_prefix):
1017
+ logger.info("[CTX_LIMIT] model=%s resolved=%s (known=%s)", model_name, _ctx, _prefix)
1018
+ return _ctx
1019
+ logger.info("[CTX_LIMIT] model=%s not found in any catalog, fallback", model_name)
1020
+ except Exception as e:
1021
+ logger.info("[CTX_LIMIT] lookup failed: %s", e)
1022
+ min_tok = _get_compact_min_tokens()
1023
+ _fallback = min_tok * 10
1024
+ logger.info("[CTX_LIMIT] fallback min_tok=%s context_limit=%s", min_tok, _fallback)
1025
+ return _fallback
1026
+
1027
+
1028
+ def estimate_context_usage(
1029
+ messages: List[Dict[str, Any]],
1030
+ model_name: Optional[str] = None,
1031
+ ) -> Dict[str, int]:
1032
+ """Context usage metadata for Web UI (prompt_tokens filled only from API)."""
1033
+ context_limit = _resolve_context_limit(model_name)
1034
+ return {
1035
+ "prompt_tokens": 0,
1036
+ "context_limit": context_limit,
1037
+ "message_count": len(messages),
1038
+ "compact_min_tokens": _get_compact_min_tokens(),
1039
+ }
1040
+
1041
+
1042
+ def build_context_usage_snapshot(
1043
+ messages: List[Dict[str, Any]],
1044
+ meta: Optional[Dict[str, Any]] = None,
1045
+ model_name: Optional[str] = None,
1046
+ ) -> Dict[str, Any]:
1047
+ """Context bar for Web UI — API ``usage.prompt_tokens`` only."""
1048
+ snap: Dict[str, Any] = dict(estimate_context_usage(messages, model_name=model_name))
1049
+ pt = _api_prompt_tokens(messages, meta=meta)
1050
+ if pt > 0:
1051
+ snap["prompt_tokens"] = pt
1052
+ snap["source"] = "api"
1053
+ if isinstance(meta, dict):
1054
+ usage = meta.get("usage")
1055
+ if isinstance(usage, dict):
1056
+ snap["completion_tokens"] = int(usage.get("completion_tokens") or 0)
1057
+ return snap
1058
+
1059
+
1060
+ def build_context_usage_from_run(
1061
+ messages: List[Dict[str, Any]],
1062
+ *,
1063
+ loop_meta: Optional[Dict[str, Any]] = None,
1064
+ last_meta: Optional[Dict[str, Any]] = None,
1065
+ model_name: Optional[str] = None,
1066
+ ) -> Dict[str, Any]:
1067
+ """Context snapshot for persistence — always prefer ``peak_prompt_tokens`` from the run."""
1068
+ peak = 0
1069
+ if isinstance(loop_meta, dict):
1070
+ peak = int(loop_meta.get("peak_prompt_tokens") or 0)
1071
+ meta_for_snap: Optional[Dict[str, Any]] = None
1072
+ usage: Dict[str, Any] = {}
1073
+ if isinstance(last_meta, dict) and isinstance(last_meta.get("usage"), dict):
1074
+ usage.update(last_meta["usage"])
1075
+ if peak > 0:
1076
+ usage["prompt_tokens"] = max(int(usage.get("prompt_tokens") or 0), peak)
1077
+ if usage:
1078
+ meta_for_snap = {"usage": usage}
1079
+ snap = build_context_usage_snapshot(messages, meta_for_snap, model_name=model_name)
1080
+ snap["compact_min_tokens"] = _get_compact_min_tokens()
1081
+ if peak > int(snap.get("prompt_tokens") or 0):
1082
+ snap["prompt_tokens"] = peak
1083
+ snap["source"] = "api"
1084
+ if peak > 0:
1085
+ snap["peak_prompt_tokens"] = peak
1086
+ return snap
1087
+
1088
+
1089
+ def apply_context_usage_metadata(
1090
+ metadata: Dict[str, Any],
1091
+ snap: Dict[str, Any],
1092
+ *,
1093
+ updated_at: str = "",
1094
+ ) -> None:
1095
+ """Write API-only context bar values into session metadata (for page refresh)."""
1096
+ pt = int(snap.get("prompt_tokens") or 0)
1097
+ peak = int(snap.get("peak_prompt_tokens") or pt)
1098
+ best = max(pt, peak)
1099
+ metadata["context_usage"] = {
1100
+ "prompt_tokens": best,
1101
+ "peak_prompt_tokens": peak if peak > 0 else best,
1102
+ "context_limit": int(snap.get("context_limit") or 0),
1103
+ "message_count": int(snap.get("message_count") or 0),
1104
+ "compact_min_tokens": int(snap.get("compact_min_tokens") or _get_compact_min_tokens()),
1105
+ "updated_at": updated_at,
1106
+ }
1107
+ if snap.get("source"):
1108
+ metadata["context_usage"]["source"] = snap["source"]
1109
+
1110
+
1111
+ def _format_transcript_for_summary(chunks: List[Dict[str, Any]], max_chars: int) -> str:
1112
+ from seed.core.llm_exec import msg_text_to_str
1113
+
1114
+ lines: List[str] = []
1115
+ for m in chunks:
1116
+ role = m.get("role", "?")
1117
+ content = m.get("content")
1118
+ if content is None and m.get("tool_calls"):
1119
+ content = json.dumps(m.get("tool_calls"), ensure_ascii=False)[:2000]
1120
+ text = msg_text_to_str(content).strip()
1121
+ if len(text) > 8000:
1122
+ text = text[:4000] + "\n...[mid omitted]...\n" + text[-4000:]
1123
+ lines.append(f"### {role}\n{text}\n")
1124
+ blob = "\n".join(lines)
1125
+ if len(blob) <= max_chars:
1126
+ return blob
1127
+ head = max_chars // 2
1128
+ tail = max_chars - head
1129
+ return (
1130
+ blob[:head]
1131
+ + "\n\n...[transcript truncated for summarizer input]...\n\n"
1132
+ + blob[-tail:]
1133
+ )
1134
+
1135
+
1136
+ def _get_compact_recent_max_chars() -> int:
1137
+ """Character budget for the post-compact recent tail (0 disables)."""
1138
+ raw = _ea.pick_default("120000", *_ea.CONTEXT_COMPACT_RECENT_MAX_CHARS)
1139
+ try:
1140
+ return max(0, int(raw))
1141
+ except (TypeError, ValueError):
1142
+ return 120000
1143
+
1144
+
1145
+ def _messages_visible_chars(messages: List[Dict[str, Any]]) -> int:
1146
+ from seed.core.llm_exec import msg_text_to_str
1147
+
1148
+ total = 0
1149
+ for message in messages:
1150
+ if not isinstance(message, dict):
1151
+ continue
1152
+ total += len(str(message.get("role") or ""))
1153
+ total += len(msg_text_to_str(message.get("content")))
1154
+ if message.get("tool_calls"):
1155
+ try:
1156
+ total += len(json.dumps(message.get("tool_calls"), ensure_ascii=False))
1157
+ except Exception:
1158
+ total += len(str(message.get("tool_calls")))
1159
+ return total
1160
+
1161
+
1162
+ def _compact_recent_message_for_projection(
1163
+ message: Dict[str, Any],
1164
+ *,
1165
+ max_content_chars: int,
1166
+ ) -> bool:
1167
+ """Shrink one oversized recent-tail message in the API projection only."""
1168
+ from seed.core.llm_exec import msg_text_to_str
1169
+
1170
+ content = msg_text_to_str(message.get("content"))
1171
+ if len(content) <= max_content_chars:
1172
+ return False
1173
+
1174
+ head_chars = max(1000, max_content_chars // 2)
1175
+ tail_chars = max(1000, max_content_chars - head_chars)
1176
+ if head_chars + tail_chars >= len(content):
1177
+ return False
1178
+
1179
+ role = str(message.get("role") or "?")
1180
+ name = str(message.get("name") or message.get("tool") or "").strip()
1181
+ title = f"Role: {role}" + (f"\nName: {name}" if name else "")
1182
+ replacement = (
1183
+ "[Recent message compacted in API projection; persisted history keeps the full original]\n"
1184
+ f"{title}\n"
1185
+ f"Original content chars: {len(content)}\n"
1186
+ "Reason: recent tail exceeded SEED_CONTEXT_COMPACT_RECENT_MAX_CHARS.\n\n"
1187
+ "Head excerpt:\n"
1188
+ f"{content[:head_chars].rstrip()}\n\n"
1189
+ "...[middle omitted from projection]...\n\n"
1190
+ "Tail excerpt:\n"
1191
+ f"{content[-tail_chars:].lstrip()}"
1192
+ )
1193
+ message["content"] = replacement
1194
+ message["_recent_tail_compacted"] = True
1195
+ return True
1196
+
1197
+
1198
+ def _compact_recent_tail_for_projection(
1199
+ recent: List[Dict[str, Any]],
1200
+ *,
1201
+ max_chars: int,
1202
+ ) -> Dict[str, int]:
1203
+ """Apply role-prioritized recent-tail shrinking to projection messages."""
1204
+ before = _messages_visible_chars(recent)
1205
+ if max_chars <= 0 or before <= max_chars:
1206
+ return {"before": before, "after": before, "count": 0}
1207
+
1208
+ latest_user_idx = -1
1209
+ for i, message in enumerate(recent):
1210
+ if isinstance(message, dict) and message.get("role") == "user":
1211
+ latest_user_idx = i
1212
+
1213
+ def _indices_for_role(role: str, *, include_latest_user: bool = True) -> List[int]:
1214
+ idxs: List[int] = []
1215
+ for i, message in enumerate(recent):
1216
+ if not isinstance(message, dict) or message.get("role") != role:
1217
+ continue
1218
+ if role == "user" and not include_latest_user and i == latest_user_idx:
1219
+ continue
1220
+ idxs.append(i)
1221
+ return sorted(
1222
+ idxs,
1223
+ key=lambda idx: len(str(recent[idx].get("content") or "")),
1224
+ reverse=True,
1225
+ )
1226
+
1227
+ compacted = 0
1228
+ # Keep the latest user instruction as raw as possible; compact it only if
1229
+ # tool/assistant/older-user shrinking still cannot satisfy the budget.
1230
+ passes = [
1231
+ (_indices_for_role("tool"), 12000),
1232
+ (_indices_for_role("assistant"), 16000),
1233
+ (_indices_for_role("user", include_latest_user=False), 24000),
1234
+ ([latest_user_idx] if latest_user_idx >= 0 else [], 32000),
1235
+ ]
1236
+ for indices, per_message_max in passes:
1237
+ if _messages_visible_chars(recent) <= max_chars:
1238
+ break
1239
+ for idx in indices:
1240
+ if idx < 0 or idx >= len(recent):
1241
+ continue
1242
+ if _messages_visible_chars(recent) <= max_chars:
1243
+ break
1244
+ target_chars = min(per_message_max, max(1000, max_chars // 2))
1245
+ if _compact_recent_message_for_projection(
1246
+ recent[idx],
1247
+ max_content_chars=target_chars,
1248
+ ):
1249
+ compacted += 1
1250
+
1251
+ after = _messages_visible_chars(recent)
1252
+ return {"before": before, "after": after, "count": compacted}
1253
+
1254
+
1255
+
1256
+ def _get_compact_summarizer_max_tokens() -> int:
1257
+ """Completion budget for compact summarizer calls (independent of ``SEED_LLM_MAX_TOKENS``)."""
1258
+ raw = _ea.pick_default("4096", *_ea.CONTEXT_COMPACT_SUMMARIZER_MAX_TOKENS)
1259
+ try:
1260
+ return max(256, min(int(raw), 65536))
1261
+ except (TypeError, ValueError):
1262
+ return 4096
1263
+
1264
+
1265
+ def _default_compact_summarizer_system_prompt(sum_max_tok: int) -> str:
1266
+ return (
1267
+ "You compress prior agent chat for continuation. "
1268
+ "Output structured bullet points in the same language as the transcript. "
1269
+ "Preserve continuation-critical state: user goals, current task status, "
1270
+ "files changed or inspected, shell commands, test results, error messages, "
1271
+ "tool names used, decisions already made, blockers, and unresolved questions. "
1272
+ "Prefer concise summaries, but do not make them so short that the next agent "
1273
+ "would need to rediscover important context. "
1274
+ "Do not invent facts.\n\n"
1275
+ "TRANSIENT-FACT RULE (CRITICAL): Any runtime state that can change "
1276
+ "silently — e.g. process PIDs, listening ports, 'running/stopped' "
1277
+ "status, temp files, cwd, currently-open sessions — MUST be written "
1278
+ "as a snapshot, not as a lasting fact. Format such lines like:\n"
1279
+ " - 『截至压缩时』PID 26364 监听 3001(需重新核对)\n"
1280
+ " - 『As of compression』port 3000 was listening on PID 18064 (re-verify before use)\n"
1281
+ "Never write an unqualified 'PID X is running' / 'port Y is up' — "
1282
+ "the downstream agent will treat that as current truth and skip "
1283
+ "re-checking, which causes wrong conclusions when the process has "
1284
+ "since died.\n\n"
1285
+ "LENGTH POLICY: The hard generation budget is "
1286
+ f"{sum_max_tok} tokens, configured by SEED_CONTEXT_COMPACT_SUMMARIZER_MAX_TOKENS. "
1287
+ "Stay concise by default, but use the available budget when needed to preserve "
1288
+ "critical continuation state."
1289
+ )
1290
+
1291
+
1292
+ def _compact_summarizer_system_prompt(sum_max_tok: int) -> str:
1293
+ """Load optional ``SEED_CONTEXT_COMPACT_SUMMARIZER_PROMPT_FILE`` or use the default."""
1294
+ raw = _ea.pick_nonempty(*_ea.CONTEXT_COMPACT_SUMMARIZER_PROMPT_FILE)
1295
+ if raw:
1296
+ try:
1297
+ path = Path(raw).expanduser()
1298
+ if path.is_file():
1299
+ text = path.read_text(encoding="utf-8").strip()
1300
+ if text:
1301
+ return text.replace("{sum_max_tok}", str(sum_max_tok))
1302
+ except Exception:
1303
+ logger.debug("compact summarizer prompt file read failed", exc_info=True)
1304
+ return _default_compact_summarizer_system_prompt(sum_max_tok)
1305
+
1306
+
1307
+ def _recent_tool_char_ratio(messages: List[Dict[str, Any]]) -> float:
1308
+ from seed.core.llm_exec import msg_text_to_str
1309
+
1310
+ total = 0
1311
+ tool_chars = 0
1312
+ for message in messages:
1313
+ if not isinstance(message, dict):
1314
+ continue
1315
+ role = str(message.get("role") or "")
1316
+ chars = len(msg_text_to_str(message.get("content")))
1317
+ if message.get("tool_calls"):
1318
+ try:
1319
+ chars += len(json.dumps(message.get("tool_calls"), ensure_ascii=False))
1320
+ except Exception:
1321
+ chars += len(str(message.get("tool_calls")))
1322
+ total += chars
1323
+ if role == "tool":
1324
+ tool_chars += chars
1325
+ if total <= 0:
1326
+ return 0.0
1327
+ return tool_chars / total
1328
+
1329
+
1330
+ def effective_keep_user_rounds(
1331
+ default_keep: int,
1332
+ *,
1333
+ trigger_tokens: int,
1334
+ min_tokens: int,
1335
+ recent_tool_char_ratio: float,
1336
+ ) -> tuple[int, str]:
1337
+ """Rule-based keep adjustment (never LLM). Returns ``(keep, reason)``."""
1338
+ keep = max(1, int(default_keep))
1339
+ reasons: List[str] = []
1340
+ if not _context_compact_adaptive_keep_enabled():
1341
+ return keep, ""
1342
+ if trigger_tokens >= int(min_tokens * 1.5):
1343
+ new_keep = max(1, keep - 1)
1344
+ if new_keep < keep:
1345
+ keep = new_keep
1346
+ reasons.append("trigger>=1.5x_min")
1347
+ if recent_tool_char_ratio >= 0.75:
1348
+ new_keep = max(1, keep - 1)
1349
+ if new_keep < keep:
1350
+ keep = new_keep
1351
+ reasons.append("tool_ratio>=0.75")
1352
+ return keep, ",".join(reasons)
1353
+
1354
+
1355
+ def _coalesce_llm_visible_text(
1356
+ content: str,
1357
+ meta: Optional[Dict[str, Any]],
1358
+ *,
1359
+ max_chars: int = 12000,
1360
+ ) -> str:
1361
+ """Prefer assistant content; fall back to reasoning when thinking models emit CoT only."""
1362
+ text = (content or "").strip()
1363
+ if text:
1364
+ return text[:max_chars] if len(text) > max_chars else text
1365
+ if not isinstance(meta, dict):
1366
+ return ""
1367
+ for key in ("reasoning_content", "reasoning"):
1368
+ rc = meta.get(key)
1369
+ if isinstance(rc, str) and rc.strip():
1370
+ text = rc.strip()
1371
+ if len(text) > max_chars:
1372
+ head = max_chars // 2
1373
+ tail = max_chars - head
1374
+ marker = "\n\n...[reasoning truncated for compact summary]...\n\n"
1375
+ text = text[:head] + marker + text[-tail:]
1376
+ return text
1377
+ return ""
1378
+
1379
+
1380
+ def _summarizer_llm(fallback: LLMAPIExecutor) -> LLMAPIExecutor:
1381
+ """If ``SEED_CONTEXT_COMPACT_SUMMARIZER_*`` (alias ``CODEAGENT_*``) are set, create a
1382
+ dedicated summarizer executor; otherwise return the fallback (main LLM).
1383
+
1384
+ Inherits API key and auth scheme from the main LLM (fallback) so the
1385
+ summarizer can authenticate even when ``SEED_LLM_API_KEY`` is not set
1386
+ as an environment variable (e.g. credentials come from a preset)."""
1387
+ url = _ea.pick_nonempty(*_ea.CONTEXT_COMPACT_SUMMARIZER_BASEURL)
1388
+ mod = _ea.pick_nonempty(*_ea.CONTEXT_COMPACT_SUMMARIZER_MODEL)
1389
+ max_tok = _get_compact_summarizer_max_tokens()
1390
+ if url and mod:
1391
+ from seed.core.llm_exec import get_llm_executor
1392
+
1393
+ return get_llm_executor(
1394
+ baseURL=url,
1395
+ model=mod,
1396
+ api_key=fallback.api_key,
1397
+ auth_scheme=fallback.auth_scheme,
1398
+ max_tokens=max_tok,
1399
+ )
1400
+ return fallback
1401
+
1402
+
1403
+
1404
+
1405
+ import os
1406
+
1407
+
1408
+
1409
+ def default_system_prompt() -> str:
1410
+ """Explicit env override, else config plane (if resolvable), else built-in default."""
1411
+ explicit = _ea.pick_nonempty(*_ea.SYSTEM_PROMPT)
1412
+ if explicit.strip():
1413
+ return explicit.strip()
1414
+ try:
1415
+ from seed.core.config_plane import build_system_prompt
1416
+
1417
+ base = build_system_prompt()
1418
+ # Multi-agent core memory (persona/memory.md) — best-effort append.
1419
+ try:
1420
+ from seed.core.paths import agent_id_default, agent_persona_memory_path
1421
+
1422
+ aid = agent_id_default()
1423
+ p = agent_persona_memory_path(aid)
1424
+ if p.is_file():
1425
+ try:
1426
+ text = p.read_text(encoding="utf-8").strip()
1427
+ except OSError:
1428
+ text = ""
1429
+ if text:
1430
+ max_chars = int(
1431
+ _ea.pick_nonempty(*_ea.PERSONA_MEMORY_MAX_CHARS) or "4000"
1432
+ )
1433
+ max_chars = max(200, min(max_chars, 50_000))
1434
+ if len(text) > max_chars:
1435
+ text = text[: max_chars - 20].rstrip() + "\n…[已截断]"
1436
+ base = (
1437
+ base.rstrip()
1438
+ + "\n\n---\n"
1439
+ + f"## Persona core memory (`agents/{aid}/persona/memory.md`)\n\n"
1440
+ + text
1441
+ + "\n"
1442
+ )
1443
+ except Exception:
1444
+ pass
1445
+ return base
1446
+ except Exception:
1447
+ return DEFAULT_SYSTEM
1448
+
1449
+
1450
+
1451
+ import logging
1452
+ import os
1453
+ from typing import Any, Dict, List
1454
+
1455
+ from seed.core.chat_events import emit_chat_event
1456
+ from seed.core.llm_exec import LLMAPIExecutor, LLMError
1457
+
1458
+
1459
+ logger = logging.getLogger(__name__)
1460
+
1461
+
1462
+ def maybe_compact_context_messages(
1463
+ messages: List[Dict[str, Any]],
1464
+ llm: LLMAPIExecutor,
1465
+ *,
1466
+ api_prompt_tokens: Optional[int] = None,
1467
+ persisted_context_usage: Optional[Dict[str, Any]] = None,
1468
+ loop_meta: Optional[Dict[str, Any]] = None,
1469
+ ) -> Optional[Dict[str, Any]]:
1470
+ """
1471
+ If enabled and the message tail (excluding system) exceeds a token threshold,
1472
+ summarize older turns into the system prompt and drop older raw messages —
1473
+ keeps the last ``KEEP_USER_ROUNDS`` (default 3) verbatim.
1474
+
1475
+ **链式摘要**:将压缩结果写入 ``old[-1][\"_compact_summary\"]``(边界消息),
1476
+ 下一轮压缩时检测已有摘要并叠加(而非全量重算)。
1477
+ 返回压缩信息字典(供调用者写回持久化消息),或 ``None``(未触发压缩)。
1478
+
1479
+ Args:
1480
+ api_prompt_tokens: Explicit trigger token count (e.g. current segment peak).
1481
+ persisted_context_usage: Session ``metadata.context_usage`` dict.
1482
+ loop_meta: In-flight tool-loop meta (``peak_prompt_tokens``).
1483
+
1484
+ Compact triggers when ``resolve_compact_trigger_tokens(...)`` exceeds
1485
+ ``SEED_CONTEXT_COMPACT_MIN_TOKENS``. No local message estimation.
1486
+
1487
+ Env (``CODEAGENT_*`` aliases still honored):
1488
+ SEED_CONTEXT_COMPACT=1
1489
+ SEED_CONTEXT_COMPACT_KEEP_USER_ROUNDS (default 3) — full turns to preserve
1490
+ SEED_CONTEXT_COMPACT_RECENT_MAX_CHARS (default 120000) — recent tail projection budget
1491
+ SEED_CONTEXT_COMPACT_SUMMARIZER_BASEURL — dedicated summarizer URL (optional)
1492
+ SEED_CONTEXT_COMPACT_SUMMARIZER_MODEL — dedicated summarizer model (optional)
1493
+ SEED_CONTEXT_SUMMARIZER_MAX_INPUT (default 120000) — cap for summarizer input chars
1494
+ """
1495
+ if not _context_compact_enabled():
1496
+ return None
1497
+ if not messages:
1498
+ return None
1499
+ has_system = messages[0].get("role") == "system"
1500
+ body_start = 1 if has_system else 0
1501
+ if body_start and len(messages) < 3:
1502
+ return None
1503
+
1504
+ min_tokens = _get_compact_min_tokens()
1505
+ if min_tokens <= 0:
1506
+ return None
1507
+ keep_rounds = int(_ea.pick_default("3", *_ea.CONTEXT_COMPACT_KEEP_USER_ROUNDS))
1508
+ recent_max_chars = _get_compact_recent_max_chars()
1509
+ max_in = int(_ea.pick_default("120000", *_ea.CONTEXT_SUMMARIZER_MAX_INPUT))
1510
+ if keep_rounds < 1:
1511
+ return None
1512
+
1513
+ cur_tokens = resolve_compact_trigger_tokens(
1514
+ persisted=persisted_context_usage,
1515
+ loop_meta=loop_meta,
1516
+ api_prompt_tokens=api_prompt_tokens,
1517
+ )
1518
+ if cur_tokens <= 0:
1519
+ return None
1520
+ try:
1521
+ warn_ratio = float(_ea.pick_default("0.85", *_ea.CONTEXT_COMPACT_WARN_RATIO) or 0.85)
1522
+ except Exception:
1523
+ warn_ratio = 0.85
1524
+ warn_ratio = max(0.1, min(warn_ratio, 0.99))
1525
+ if cur_tokens >= int(min_tokens * warn_ratio):
1526
+ _warn_model = getattr(llm, "model", None)
1527
+ emit_chat_event(
1528
+ {
1529
+ "type": "context_usage",
1530
+ "prompt_tokens": int(cur_tokens),
1531
+ "compact_min_tokens": int(min_tokens),
1532
+ "context_limit": int(_resolve_context_limit(_warn_model)),
1533
+ "warn_ratio": warn_ratio,
1534
+ "message_count": int(len(messages)),
1535
+ }
1536
+ )
1537
+
1538
+ body = messages[body_start:]
1539
+ # 包括所有 role=user 的消息作为轮次边界(含 _auto_continue_nudge),
1540
+ # 让自主模式的分块渐进压缩能按 chunk 边界切分。
1541
+ user_idx = [
1542
+ i for i, m in enumerate(body)
1543
+ if isinstance(m, dict) and m.get("role") == "user"
1544
+ ]
1545
+
1546
+ if cur_tokens < min_tokens:
1547
+ return None
1548
+
1549
+ if len(user_idx) <= keep_rounds:
1550
+ base_keep = max(1, len(user_idx) - 1)
1551
+ else:
1552
+ base_keep = keep_rounds
1553
+
1554
+ recent_preview = body[user_idx[len(user_idx) - base_keep] :] if user_idx else body
1555
+ tool_ratio = _recent_tool_char_ratio(recent_preview)
1556
+ effective_keep, adaptive_reason = effective_keep_user_rounds(
1557
+ base_keep,
1558
+ trigger_tokens=cur_tokens,
1559
+ min_tokens=min_tokens,
1560
+ recent_tool_char_ratio=tool_ratio,
1561
+ )
1562
+
1563
+ cut = user_idx[len(user_idx) - effective_keep]
1564
+ old = body[:cut]
1565
+ recent = body[cut:]
1566
+ if not old:
1567
+ recent_stats = _compact_recent_tail_for_projection(
1568
+ recent,
1569
+ max_chars=recent_max_chars,
1570
+ )
1571
+ if recent_stats["count"] > 0:
1572
+ messages[:] = ([messages[0]] if has_system else []) + recent
1573
+ emit_chat_event(
1574
+ {
1575
+ "type": "context_recent_tail_compact",
1576
+ "compacted_messages": int(recent_stats["count"]),
1577
+ "recent_chars_before": int(recent_stats["before"]),
1578
+ "recent_chars_after": int(recent_stats["after"]),
1579
+ "recent_max_chars": int(recent_max_chars),
1580
+ "prompt_tokens_before": int(cur_tokens),
1581
+ }
1582
+ )
1583
+ return None
1584
+
1585
+ # ── 增量摘要检测 ──
1586
+ # 检查 old 中的消息是否已有之前写的 _compact_summary,取最晚的一条
1587
+ _prior_summary: str | None = None
1588
+ for m in old:
1589
+ cs = m.get("_compact_summary")
1590
+ if isinstance(cs, str) and cs.strip():
1591
+ _prior_summary = cs.strip()
1592
+
1593
+ # 构建 transcript:如有旧摘要,拼在前面
1594
+ transcript = _format_transcript_for_summary(old, max_in)
1595
+ if _prior_summary:
1596
+ transcript = (
1597
+ "[Previous compact summary]\n"
1598
+ + _prior_summary
1599
+ + "\n\n[New messages since last compact]\n"
1600
+ + transcript
1601
+ )
1602
+
1603
+ sum_max_tok = _get_compact_summarizer_max_tokens()
1604
+
1605
+ sum_messages: List[Dict[str, Any]] = [
1606
+ {
1607
+ "role": "system",
1608
+ "content": _compact_summarizer_system_prompt(sum_max_tok),
1609
+ },
1610
+ {
1611
+ "role": "user",
1612
+ "content": "Transcript to compress:\n\n" + transcript,
1613
+ },
1614
+ ]
1615
+ if is_chat_cancelled():
1616
+ return None
1617
+
1618
+ summarizer = _summarizer_llm(llm)
1619
+ try:
1620
+ from seed.core.projection_audit import persist_llm_projection_audit
1621
+
1622
+ persist_llm_projection_audit(
1623
+ sum_messages,
1624
+ kind="compact_summarizer",
1625
+ round_index=0,
1626
+ tools=[],
1627
+ extra={"trigger": "maybe_compact_context_messages"},
1628
+ )
1629
+ except Exception:
1630
+ logger.debug("compact summarizer projection audit failed", exc_info=True)
1631
+ try:
1632
+ summary, _meta = summarizer.generate(
1633
+ sum_messages,
1634
+ tools=None,
1635
+ enable_thinking=False,
1636
+ max_tokens=sum_max_tok,
1637
+ )
1638
+ except LLMError as e:
1639
+ logger.warning("Context compact skipped (summarizer LLM error): %s", e)
1640
+ return None
1641
+
1642
+ summary = _coalesce_llm_visible_text(summary or "", _meta)
1643
+ if not summary:
1644
+ logger.warning(
1645
+ "Context compact skipped (empty summary; cur_tokens=%s min_tokens=%s "
1646
+ "transcript_chars=%s max_tokens=%s model=%s)",
1647
+ cur_tokens,
1648
+ min_tokens,
1649
+ len(transcript),
1650
+ sum_max_tok,
1651
+ getattr(summarizer, "model", "?"),
1652
+ )
1653
+ return None
1654
+
1655
+ # ── 链式:与旧摘要叠加(如有) ──
1656
+ combined = summary
1657
+ if _prior_summary:
1658
+ combined = _prior_summary + "\n\n[continued]\n\n" + summary
1659
+ # 记录压缩发生的时间,后续只读不改
1660
+ _compact_ts = datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
1661
+ combined = f"### 📅 摘要生成时间: {_compact_ts}\n\n" + combined
1662
+
1663
+ boundary_message = old[-1]
1664
+ boundary_source_idx = boundary_message.get("_source_idx")
1665
+ if boundary_source_idx is None:
1666
+ boundary_source_idx = body_start + cut - 1
1667
+ else:
1668
+ try:
1669
+ boundary_source_idx = int(boundary_source_idx)
1670
+ except (TypeError, ValueError):
1671
+ boundary_source_idx = body_start + cut - 1
1672
+
1673
+ # 写入 _compact_summary 到边界消息(old 中最后一条,投影副本)
1674
+ boundary_message["_compact_summary"] = combined
1675
+
1676
+ sys_msg = messages[0]
1677
+ base = strip_compact_block_from_system(str(sys_msg.get("content") or ""))
1678
+ block = (
1679
+ "\n\n<<<SEED_COMPACT>>>\n"
1680
+ "## Earlier conversation (compressed)\n"
1681
+ f"{combined}\n"
1682
+ "<<<END_SEED_COMPACT>>>\n"
1683
+ )
1684
+ sys_msg["content"] = base + block
1685
+ recent_stats = _compact_recent_tail_for_projection(
1686
+ recent,
1687
+ max_chars=recent_max_chars,
1688
+ )
1689
+ messages[:] = [sys_msg] + recent
1690
+ emit_chat_event(
1691
+ {
1692
+ "type": "context_compact",
1693
+ "dropped_messages": int(len(old)),
1694
+ "kept_user_rounds": int(effective_keep),
1695
+ "effective_keep_user_rounds": int(effective_keep),
1696
+ "adaptive_keep_reason": adaptive_reason,
1697
+ "summary_chars": int(len(combined)),
1698
+ "recent_compacted_messages": int(recent_stats["count"]),
1699
+ "recent_chars_before": int(recent_stats["before"]),
1700
+ "recent_chars_after": int(recent_stats["after"]),
1701
+ "recent_max_chars": int(recent_max_chars),
1702
+ "compact_min_tokens": int(min_tokens),
1703
+ "prompt_tokens_before": int(cur_tokens),
1704
+ "update_agent_state_hint": True,
1705
+ }
1706
+ )
1707
+ logger.info(
1708
+ "Context compact: dropped %s messages, kept %s user rounds verbatim",
1709
+ len(old),
1710
+ effective_keep,
1711
+ )
1712
+
1713
+ # ── 返回压缩信息供调用者写回 chat_sess.messages ──
1714
+ return {
1715
+ "boundary_idx": body_start + cut - 1,
1716
+ "boundary_source_idx": boundary_source_idx,
1717
+ "compact_summary": combined,
1718
+ "dropped_count": len(old),
1719
+ "effective_keep_user_rounds": int(effective_keep),
1720
+ "adaptive_keep_reason": adaptive_reason,
1721
+ }
1722
+
1723
+
1724
+ def try_mid_loop_compact_if_needed(
1725
+ messages: List[Dict[str, Any]],
1726
+ llm: LLMAPIExecutor,
1727
+ *,
1728
+ loop_meta: Dict[str, Any],
1729
+ ) -> Optional[Dict[str, Any]]:
1730
+ """Compact during a tool loop when peak prompt tokens exceed the threshold."""
1731
+ if not _context_compact_mid_loop_enabled():
1732
+ return None
1733
+ min_tokens = _get_compact_min_tokens()
1734
+ if min_tokens <= 0:
1735
+ return None
1736
+ peak = int(loop_meta.get("peak_prompt_tokens") or 0)
1737
+ if peak < min_tokens:
1738
+ return None
1739
+ result = maybe_compact_context_messages(
1740
+ messages,
1741
+ llm,
1742
+ api_prompt_tokens=peak,
1743
+ loop_meta=loop_meta,
1744
+ )
1745
+ if result is not None:
1746
+ loop_meta["peak_prompt_tokens"] = 0
1747
+ loop_meta["compact_count"] = int(loop_meta.get("compact_count") or 0) + 1
1748
+ return result
1749
+
1750
+
1751
+ def _truncate_tool_output(text: str, *, tool_name: str = "tool") -> str:
1752
+ from seed.core.tool_output_cap import cap_tool_output_for_context
1753
+
1754
+ return cap_tool_output_for_context(text, tool_name=tool_name)
1755
+
1756
+
1757
+ """OpenAI-style chat completions loop with tool execution."""
1758
+
1759
+
1760
+ import asyncio
1761
+ import contextlib
1762
+ import json
1763
+ import logging
1764
+ import uuid
1765
+ from typing import Any, Callable, Dict, List, Optional, Tuple
1766
+
1767
+ from seed.core.chat_events import emit_chat_event
1768
+ from seed.core.llm_exec import LLMAPIExecutor
1769
+ from seed.core.tool_runtime import ToolExecutor, ToolRegistry
1770
+
1771
+ logger = logging.getLogger(__name__)
1772
+
1773
+
1774
+ def _stream_llm_round(
1775
+ llm: LLMAPIExecutor,
1776
+ messages: List[Dict[str, Any]],
1777
+ tool_schema: Optional[List[Dict[str, Any]]],
1778
+ on_text_delta: Optional[Callable[[str], None]],
1779
+ on_reasoning_delta: Optional[Callable[[str], None]],
1780
+ *,
1781
+ enable_thinking: Optional[bool] = None,
1782
+ reasoning_effort: Optional[str] = None,
1783
+ ) -> Tuple[str, List[Dict[str, Any]], Dict[str, Any]]:
1784
+ """Run one LLM round with per-token streaming (called in a thread).
1785
+
1786
+ ``on_text_delta`` receives the **cumulative** text (full round text so far)
1787
+ so the frontend can compute the delta internally.
1788
+ """
1789
+ full_text = ""
1790
+ tool_calls: List[Dict[str, Any]] = []
1791
+ metadata: Dict[str, Any] = {}
1792
+
1793
+ for event in llm.generate_stream(
1794
+ messages,
1795
+ tools=tool_schema,
1796
+ enable_thinking=enable_thinking,
1797
+ reasoning_effort=reasoning_effort,
1798
+ ):
1799
+ if is_chat_cancelled():
1800
+ break
1801
+ et = event.get("type")
1802
+ if et == "delta":
1803
+ text = event.get("text", "")
1804
+ full_text += text
1805
+ if on_text_delta:
1806
+ try:
1807
+ on_text_delta(full_text)
1808
+ except Exception:
1809
+ pass
1810
+ elif et == "reasoning_delta":
1811
+ text = event.get("text", "")
1812
+ if on_reasoning_delta:
1813
+ try:
1814
+ on_reasoning_delta(text)
1815
+ except Exception:
1816
+ pass
1817
+ elif et == "done":
1818
+ tool_calls = event.get("tool_calls") or []
1819
+ metadata = event.get("metadata", {})
1820
+ break
1821
+
1822
+ try:
1823
+ from seed.core.usage_accumulator import record_round_usage
1824
+
1825
+ record_round_usage(metadata)
1826
+ except Exception:
1827
+ pass
1828
+
1829
+ return full_text, tool_calls, metadata
1830
+
1831
+
1832
+ def _emit_context_usage_snapshot(
1833
+ messages: List[Dict[str, Any]],
1834
+ meta: Optional[Dict[str, Any]] = None,
1835
+ model_name: Optional[str] = None,
1836
+ *,
1837
+ loop_meta: Optional[Dict[str, Any]] = None,
1838
+ ) -> None:
1839
+ """Push in-flight context size to Web UI (tool-loop rounds)."""
1840
+ try:
1841
+ snap = build_context_usage_from_run(
1842
+ messages,
1843
+ loop_meta=loop_meta,
1844
+ last_meta=meta,
1845
+ model_name=model_name,
1846
+ )
1847
+ emit_chat_event({"type": "context_usage", **snap})
1848
+ except Exception:
1849
+ logger.debug("context_usage snapshot emit failed", exc_info=True)
1850
+
1851
+
1852
+ async def _execute_tool_with_cancel(
1853
+ executor: ToolExecutor,
1854
+ tool_name: str,
1855
+ args_obj: Dict[str, Any],
1856
+ ) -> str:
1857
+ """Run one tool, polling cancel so stop requests are not blocked until tool returns."""
1858
+ if is_chat_cancelled():
1859
+ return f"Error executing tool {tool_name!r}: cancelled by user"
1860
+
1861
+ exec_task = asyncio.create_task(
1862
+ executor.execute_with_validation_async(tool_name, args_obj)
1863
+ )
1864
+ try:
1865
+ while not exec_task.done():
1866
+ if is_chat_cancelled():
1867
+ exec_task.cancel()
1868
+ with contextlib.suppress(asyncio.CancelledError):
1869
+ await exec_task
1870
+ return f"Error executing tool {tool_name!r}: cancelled by user"
1871
+ await asyncio.sleep(0.2)
1872
+ result = await exec_task
1873
+ except asyncio.CancelledError:
1874
+ return f"Error executing tool {tool_name!r}: cancelled by user"
1875
+ except Exception as e:
1876
+ logger.exception("tool %s failed", tool_name)
1877
+ return f"Error executing tool {tool_name!r}: {e}"
1878
+
1879
+ out = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)
1880
+ return out
1881
+
1882
+
1883
+ async def run_llm_tool_loop(
1884
+ llm: LLMAPIExecutor,
1885
+ executor: ToolExecutor,
1886
+ *,
1887
+ messages: List[Dict[str, Any]],
1888
+ registry: ToolRegistry,
1889
+ max_tool_rounds: int = 16,
1890
+ on_round_persist: Optional[Callable[[List[Dict[str, str]], List[str]], None]] = None,
1891
+ on_text_delta: Optional[Callable[[str], None]] = None,
1892
+ on_reasoning_delta: Optional[Callable[[str], None]] = None,
1893
+ on_check_pending_messages: Optional[Callable[[], List[Dict[str, Any]]]] = None,
1894
+ on_compact: Optional[Callable[[Optional[Dict[str, Any]]], None]] = None,
1895
+ enable_thinking: Optional[bool] = None,
1896
+ reasoning_effort: Optional[str] = None,
1897
+ ) -> Tuple[str, Dict[str, Any], List[str], List[Dict[str, str]], Dict[str, Any]]:
1898
+ tools_used: List[str] = []
1899
+ tool_trace: List[Dict[str, str]] = []
1900
+ loop_meta: Dict[str, Any] = {"rounds": 0, "stopped_reason": None}
1901
+ _model_name: Optional[str] = getattr(llm, "model", None)
1902
+
1903
+ oai_tools = registry_to_openai_tools(registry)
1904
+ tool_schema = oai_tools if oai_tools else None
1905
+
1906
+ last_meta: Dict[str, Any] = {}
1907
+
1908
+ try:
1909
+ for round_i in range(max(1, int(max_tool_rounds))):
1910
+ loop_meta["rounds"] = round_i + 1
1911
+
1912
+ # ── 停止信号检查 ──
1913
+ if is_chat_cancelled():
1914
+ loop_meta["stopped_reason"] = "cancelled"
1915
+ reply = ""
1916
+ for m in reversed(messages):
1917
+ if isinstance(m, dict) and m.get("role") == "assistant":
1918
+ c = m.get("content")
1919
+ reply = c if isinstance(c, str) else str(c or "")
1920
+ break
1921
+ return reply, last_meta, tools_used, tool_trace, loop_meta
1922
+
1923
+ # ── 运行时消息注入:第二个用户消息在工具链中间到达 ──
1924
+ if on_check_pending_messages:
1925
+ try:
1926
+ pending = on_check_pending_messages()
1927
+ except Exception:
1928
+ logger.exception("check_pending_messages failed")
1929
+ pending = []
1930
+ if pending:
1931
+ messages.extend(pending)
1932
+ # 不直接 return,而是 continue 让下一轮循环重新调用 LLM
1933
+ # 处理新注入的用户消息,避免 pending 消息被忽略
1934
+ continue
1935
+
1936
+ _audit_path = None
1937
+ try:
1938
+ from seed.core.projection_audit import persist_llm_projection_audit
1939
+
1940
+ _audit_path = persist_llm_projection_audit(
1941
+ messages,
1942
+ kind="chat",
1943
+ round_index=round_i + 1,
1944
+ tools=tool_schema,
1945
+ extra={"max_tool_rounds": int(max_tool_rounds)},
1946
+ )
1947
+ except Exception:
1948
+ logger.debug("chat projection audit failed", exc_info=True)
1949
+ try:
1950
+ from seed.core.trace_audit import append_trace_event
1951
+
1952
+ append_trace_event(
1953
+ "llm_request",
1954
+ round=round_i + 1,
1955
+ audit_file=_audit_path.name if _audit_path else "",
1956
+ message_count=len(messages),
1957
+ tools_count=len(tool_schema or []),
1958
+ max_tool_rounds=int(max_tool_rounds),
1959
+ )
1960
+ except Exception:
1961
+ logger.debug("trace llm_request failed", exc_info=True)
1962
+
1963
+ # --- Streaming LLM round (per-token) ---
1964
+ content, tool_calls, meta = await asyncio.to_thread(
1965
+ _stream_llm_round,
1966
+ llm,
1967
+ messages,
1968
+ tool_schema,
1969
+ on_text_delta,
1970
+ on_reasoning_delta,
1971
+ enable_thinking=enable_thinking,
1972
+ reasoning_effort=reasoning_effort,
1973
+ )
1974
+ last_meta = meta or {}
1975
+ _record_peak_prompt_tokens(loop_meta, last_meta)
1976
+ try:
1977
+ from seed.core.projection_audit import append_projection_audit_usage
1978
+
1979
+ _usage = last_meta.get("usage") if isinstance(last_meta, dict) else None
1980
+ append_projection_audit_usage(
1981
+ _audit_path,
1982
+ _usage if isinstance(_usage, dict) else None,
1983
+ meta={
1984
+ "tool_calls": int(len(tool_calls or [])),
1985
+ "finish_reason": str(last_meta.get("finish_reason") or ""),
1986
+ },
1987
+ )
1988
+ except Exception:
1989
+ logger.debug("chat projection audit usage append failed", exc_info=True)
1990
+ try:
1991
+ from seed.core.trace_audit import append_trace_event
1992
+
1993
+ _usage_for_trace = last_meta.get("usage") if isinstance(last_meta, dict) else None
1994
+ append_trace_event(
1995
+ "llm_response",
1996
+ round=round_i + 1,
1997
+ audit_file=_audit_path.name if _audit_path else "",
1998
+ usage=_usage_for_trace if isinstance(_usage_for_trace, dict) else {},
1999
+ tool_calls=int(len(tool_calls or [])),
2000
+ finish_reason=str(last_meta.get("finish_reason") or ""),
2001
+ )
2002
+ except Exception:
2003
+ logger.debug("trace llm_response failed", exc_info=True)
2004
+
2005
+ assistant_msg: Dict[str, Any] = {"role": "assistant", "content": content}
2006
+ rc = last_meta.get("reasoning_content")
2007
+ if rc is not None:
2008
+ assistant_msg["reasoning_content"] = rc
2009
+ if tool_calls:
2010
+ assistant_msg["tool_calls"] = tool_calls
2011
+ messages.append(assistant_msg)
2012
+
2013
+ _compact_result = await asyncio.to_thread(
2014
+ try_mid_loop_compact_if_needed,
2015
+ messages,
2016
+ llm,
2017
+ loop_meta=loop_meta,
2018
+ )
2019
+ if _compact_result is not None and on_compact:
2020
+ try:
2021
+ on_compact(_compact_result)
2022
+ except Exception:
2023
+ logger.exception("on_compact callback failed")
2024
+
2025
+ if not tool_calls:
2026
+ _emit_context_usage_snapshot(
2027
+ messages, last_meta, model_name=_model_name, loop_meta=loop_meta
2028
+ )
2029
+ if on_round_persist:
2030
+ try:
2031
+ on_round_persist(list(tool_trace), list(tools_used))
2032
+ except Exception:
2033
+ pass
2034
+ loop_meta["stopped_reason"] = "no_tool_calls"
2035
+ return content, last_meta, tools_used, tool_trace, loop_meta
2036
+
2037
+ _emit_context_usage_snapshot(
2038
+ messages, last_meta, model_name=_model_name, loop_meta=loop_meta
2039
+ )
2040
+
2041
+ for tc in tool_calls:
2042
+ if is_chat_cancelled():
2043
+ loop_meta["stopped_reason"] = "cancelled"
2044
+ reply = ""
2045
+ for m in reversed(messages):
2046
+ if isinstance(m, dict) and m.get("role") == "assistant":
2047
+ c = m.get("content")
2048
+ reply = c if isinstance(c, str) else str(c or "")
2049
+ break
2050
+ return reply, last_meta, tools_used, tool_trace, loop_meta
2051
+
2052
+ fn = (tc.get("function") or {}) if isinstance(tc, dict) else {}
2053
+ name = (fn.get("name") or "").strip()
2054
+ raw_args = fn.get("arguments") if isinstance(fn.get("arguments"), str) else "{}"
2055
+ if not isinstance(raw_args, str):
2056
+ raw_args = json.dumps(raw_args or {}, ensure_ascii=False)
2057
+ tid = str(tc.get("id") or "")
2058
+ tools_used.append(name)
2059
+ row: Dict[str, str] = {"name": name, "arguments": raw_args}
2060
+ tool_trace.append(row)
2061
+
2062
+ event_id = str(uuid.uuid4())
2063
+ emit_chat_event(
2064
+ {
2065
+ "type": "tool_start",
2066
+ "event_id": event_id,
2067
+ "tool": name,
2068
+ "arguments": raw_args,
2069
+ }
2070
+ )
2071
+ try:
2072
+ from seed.core.trace_audit import append_trace_event
2073
+
2074
+ append_trace_event(
2075
+ "tool_start",
2076
+ round=round_i + 1,
2077
+ event_id=event_id,
2078
+ tool_call_id=tid,
2079
+ tool=name,
2080
+ arguments=raw_args,
2081
+ )
2082
+ except Exception:
2083
+ logger.debug("trace tool_start failed", exc_info=True)
2084
+ try:
2085
+ try:
2086
+ args_obj = json.loads(raw_args) if raw_args.strip() else {}
2087
+ except json.JSONDecodeError:
2088
+ args_obj = {}
2089
+ out = await _execute_tool_with_cancel(executor, name, args_obj)
2090
+ except Exception as e:
2091
+ logger.exception("tool %s failed", name)
2092
+ out = f"Error executing tool {name!r}: {e}"
2093
+
2094
+ if is_chat_cancelled() and "cancelled by user" in out:
2095
+ loop_meta["stopped_reason"] = "cancelled"
2096
+
2097
+ out = _truncate_tool_output(out, tool_name=name)
2098
+
2099
+ snippet = out if len(out) <= 4000 else out[:4000] + "…"
2100
+ row["result"] = snippet
2101
+
2102
+ if out:
2103
+ chunk = 8000
2104
+ for i in range(0, len(out), chunk):
2105
+ emit_chat_event(
2106
+ {
2107
+ "type": "tool_output",
2108
+ "event_id": event_id,
2109
+ "tool": name,
2110
+ "text": out[i : i + chunk],
2111
+ }
2112
+ )
2113
+ emit_chat_event(
2114
+ {
2115
+ "type": "tool_end",
2116
+ "event_id": event_id,
2117
+ "tool": name,
2118
+ "arguments": raw_args,
2119
+ "result": snippet,
2120
+ }
2121
+ )
2122
+ try:
2123
+ from seed.core.trace_audit import append_trace_event
2124
+
2125
+ append_trace_event(
2126
+ "tool_end",
2127
+ round=round_i + 1,
2128
+ event_id=event_id,
2129
+ tool_call_id=tid,
2130
+ tool=name,
2131
+ result_chars=len(out or ""),
2132
+ result_preview=snippet,
2133
+ cancelled=bool(loop_meta.get("stopped_reason") == "cancelled"),
2134
+ )
2135
+ except Exception:
2136
+ logger.debug("trace tool_end failed", exc_info=True)
2137
+
2138
+ messages.append(
2139
+ {
2140
+ "role": "tool",
2141
+ "tool_call_id": tid,
2142
+ "name": name,
2143
+ "content": out,
2144
+ }
2145
+ )
2146
+
2147
+ if on_round_persist:
2148
+ try:
2149
+ on_round_persist(list(tool_trace), list(tools_used))
2150
+ except Exception:
2151
+ pass
2152
+
2153
+ if loop_meta.get("stopped_reason") == "cancelled":
2154
+ reply = ""
2155
+ for m in reversed(messages):
2156
+ if isinstance(m, dict) and m.get("role") == "assistant":
2157
+ c = m.get("content")
2158
+ reply = c if isinstance(c, str) else str(c or "")
2159
+ break
2160
+ return reply, last_meta, tools_used, tool_trace, loop_meta
2161
+
2162
+ loop_meta["stopped_reason"] = "max_tool_rounds"
2163
+ reply = ""
2164
+ if on_round_persist:
2165
+ try:
2166
+ on_round_persist(list(tool_trace), list(tools_used))
2167
+ except Exception:
2168
+ pass
2169
+ for m in reversed(messages):
2170
+ if isinstance(m, dict) and m.get("role") == "assistant":
2171
+ c = m.get("content")
2172
+ reply = c if isinstance(c, str) else str(c or "")
2173
+ break
2174
+ return reply, last_meta, tools_used, tool_trace, loop_meta
2175
+ finally:
2176
+ try:
2177
+ from seed.integrations.hooks import dispatch_hooks
2178
+
2179
+ dispatch_hooks(
2180
+ "turn_end",
2181
+ {
2182
+ "stopped_reason": loop_meta.get("stopped_reason"),
2183
+ "tools_used": list(tools_used),
2184
+ "rounds": loop_meta.get("rounds"),
2185
+ },
2186
+ )
2187
+ except Exception:
2188
+ pass
2189
+
2190
+
2191
+
2192
+ import json
2193
+ import os
2194
+ import re
2195
+ import uuid
2196
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
2197
+
2198
+ from seed.core import env_access as _ea
2199
+ from seed.core.tool_runtime import ToolRegistry
2200
+
2201
+ _TOOL_CALL_WRAPPER_RE = re.compile(
2202
+ r"<tool_call>\s*[\s\S]*?</tool_call>", re.IGNORECASE
2203
+ )
2204
+ _FUNCTION_BLOCK_RE = re.compile(
2205
+ r"<\s*function\s*=\s*(\w+)>\s*([\s\S]*?)</\s*function\s*>",
2206
+ re.IGNORECASE,
2207
+ )
2208
+ _PARAMETER_RE = re.compile(
2209
+ r"<\s*parameter\s*=\s*(\w+)>\s*([\s\S]*?)\s*</\s*parameter\s*>",
2210
+ re.IGNORECASE,
2211
+ )
2212
+ _JSON_FENCE_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)```", re.IGNORECASE)
2213
+ _ORPHAN_TOOL_CLOSE_RE = re.compile(
2214
+ r"</\s*(?:parameter|function|tool_call)\s*>",
2215
+ re.IGNORECASE,
2216
+ )
2217
+ _LOOSE_TOOL_OPEN_RE = re.compile(
2218
+ r"<\s*tool_call\s*>",
2219
+ re.IGNORECASE,
2220
+ )
2221
+ _LOOSE_FUNCTION_OPEN_RE = re.compile(
2222
+ r"<\s*function\s*=\s*\w+\s*>",
2223
+ re.IGNORECASE,
2224
+ )
2225
+ _LOOSE_PARAMETER_OPEN_RE = re.compile(
2226
+ r"<\s*parameter\s*=\s*\w+\s*>",
2227
+ re.IGNORECASE,
2228
+ )
2229
+
2230
+
2231
+ def strip_inline_tool_markup_from_assistant_text(text: str) -> str:
2232
+ """Remove Qwen-style pseudo-tool XML from assistant content before storing.
2233
+
2234
+ Also strips orphan closing tags (e.g. ``</tool_call>``) left when HTML/Markdown
2235
+ sanitizers remove unknown opening tags, and stray opening tags without pairs.
2236
+ Additionally strips ``<think>...</think>`` chain-of-thought so it is not
2237
+ replayed into the next turn and cause self-reinforcing repetition.
2238
+ """
2239
+ if not text:
2240
+ return ""
2241
+ t = _strip_think_markup(text)
2242
+ t = _TOOL_CALL_WRAPPER_RE.sub("", t)
2243
+ t = _FUNCTION_BLOCK_RE.sub("", t)
2244
+ t = _PARAMETER_RE.sub("", t)
2245
+ t = _ORPHAN_TOOL_CLOSE_RE.sub("", t)
2246
+ t = _LOOSE_TOOL_OPEN_RE.sub("", t)
2247
+ t = _LOOSE_FUNCTION_OPEN_RE.sub("", t)
2248
+ t = _LOOSE_PARAMETER_OPEN_RE.sub("", t)
2249
+ t = re.sub(r"\n{3,}", "\n\n", t).strip()
2250
+ # Final pass: redact bare chain-of-thought (no <think> markup at all,
2251
+ # just prose like "Here's a thinking process..." or "用户纠正了我...").
2252
+ # Required after markup strip because the markup pass is a no-op on these
2253
+ # leaks yet they still pollute history and re-trigger the model.
2254
+ t = scrub_bare_cot_from_assistant_text(t)
2255
+ return t
2256
+
2257
+
2258
+ def parse_inline_qwen_tool_calls(text: str) -> List[Dict[str, Any]]:
2259
+ """
2260
+ Parse tool calls that some models emit inside plain text, e.g.:
2261
+
2262
+ <tool_call>
2263
+ <function=example_tool_name>
2264
+ <parameter=body>...</parameter>
2265
+ </function>
2266
+ </tool_call>
2267
+
2268
+ Returns OpenAI-shaped tool_call dicts (ids are synthetic).
2269
+ """
2270
+ if not text or not re.search(r"<\s*function\s*=", text, re.IGNORECASE):
2271
+ return []
2272
+ out: List[Dict[str, Any]] = []
2273
+ for m in _FUNCTION_BLOCK_RE.finditer(text):
2274
+ name, inner = m.group(1), m.group(2)
2275
+ args: Dict[str, str] = {}
2276
+ for pm in _PARAMETER_RE.finditer(inner):
2277
+ k, v = pm.group(1), pm.group(2).strip()
2278
+ args[k] = v
2279
+ if not name:
2280
+ continue
2281
+ out.append(
2282
+ {
2283
+ "id": f"call_inline_{uuid.uuid4().hex[:16]}",
2284
+ "type": "function",
2285
+ "function": {
2286
+ "name": name,
2287
+ "arguments": json.dumps(args, ensure_ascii=False),
2288
+ },
2289
+ }
2290
+ )
2291
+ return out
2292
+
2293
+
2294
+ def parse_inline_json_tool_calls(text: str) -> Tuple[List[Dict[str, Any]], List[str]]:
2295
+ """
2296
+ Parse ```json ... ``` blocks that look like
2297
+ {"name": "tool", "arguments": {...}} or a list of such dicts.
2298
+ Returns (openai-shaped tool_calls, raw fence strings to strip from transcript).
2299
+ """
2300
+ out: List[Dict[str, Any]] = []
2301
+ consumed_fences: List[str] = []
2302
+ if not text or "```" not in text:
2303
+ return out, consumed_fences
2304
+ for m in _JSON_FENCE_RE.finditer(text):
2305
+ raw_inner = (m.group(1) or "").strip()
2306
+ if not raw_inner or '"' not in raw_inner:
2307
+ continue
2308
+ try:
2309
+ obj = json.loads(raw_inner)
2310
+ except (json.JSONDecodeError, TypeError, ValueError):
2311
+ continue
2312
+ items: List[Dict[str, Any]] = []
2313
+ if isinstance(obj, dict):
2314
+ items = [obj]
2315
+ elif isinstance(obj, list):
2316
+ items = [x for x in obj if isinstance(x, dict)]
2317
+ batch: List[Dict[str, Any]] = []
2318
+ for item in items:
2319
+ name = item.get("name") or item.get("tool")
2320
+ if not name or not isinstance(name, str):
2321
+ continue
2322
+ args = item.get("arguments")
2323
+ if args is None:
2324
+ args = item.get("args") or item.get("parameters")
2325
+ if isinstance(args, str):
2326
+ try:
2327
+ args = json.loads(args)
2328
+ except (json.JSONDecodeError, TypeError, ValueError):
2329
+ args = {}
2330
+ if not isinstance(args, dict):
2331
+ args = {}
2332
+ if not args:
2333
+ args = {
2334
+ k: v
2335
+ for k, v in item.items()
2336
+ if k
2337
+ not in ("name", "tool", "type", "id", "arguments", "args", "parameters")
2338
+ }
2339
+ batch.append(
2340
+ {
2341
+ "id": f"call_inline_{uuid.uuid4().hex[:16]}",
2342
+ "type": "function",
2343
+ "function": {
2344
+ "name": name.strip(),
2345
+ "arguments": json.dumps(args, ensure_ascii=False),
2346
+ },
2347
+ }
2348
+ )
2349
+ if batch:
2350
+ out.extend(batch)
2351
+ consumed_fences.append(m.group(0))
2352
+ return out, consumed_fences
2353
+
2354
+
2355
+ def _strip_json_fences_once_each(text: str, fences: List[str]) -> str:
2356
+ t = text
2357
+ for f in fences:
2358
+ if f in t:
2359
+ t = t.replace(f, "", 1)
2360
+ return t.strip()
2361
+
2362
+
2363
+ def _inline_tool_parse_enabled() -> bool:
2364
+ return _ea.pick_default("1", *_ea.INLINE_TOOL_PARSE).lower() not in (
2365
+ "0",
2366
+ "false",
2367
+ "no",
2368
+ )
2369
+
2370
+
2371
+ def _allowed_tool_names_for_loop(
2372
+ registry: ToolRegistry,
2373
+ exclude_prefixes: Optional[Sequence[str]],
2374
+ ) -> set:
2375
+ names = {t.name for t in registry.list_all()}
2376
+ if exclude_prefixes:
2377
+ names = {
2378
+ n
2379
+ for n in names
2380
+ if not any(n.startswith(p) for p in exclude_prefixes if p)
2381
+ }
2382
+ return names
2383
+
2384
+