Repository navigation
Expand file tree
/
Copy pathtitle.py
More file actions
78 lines (66 loc) · 3.49 KB
/
Copy pathtitle.py
File metadata and controls
78 lines (66 loc) · 3.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""Antigravity 透传会话标题推导 — 从请求信封的 user 文本取会话开篇意图.
客户端把用户手输回合包在 ``<USER_REQUEST>`` 壳内,壳后紧跟
``<ADDITIONAL_METADATA>``(本地时间)与 ``<USER_SETTINGS_CHANGE>``
(模式 / 权限策略)等注入块;同一请求里还会出现 ``<SYSTEM_MESSAGE>``、
``<COMPACTED_HISTORY>``(上下文压缩摘要)、sub-agent 父 prompt 等无壳文本。
标题首写胜出且没有修改入口,写错即永久占位,所以这里只认壳内文本:
其余形态一律不成题,只留原因码供 DEBUG 取证,待 wire 样本确认后再扩规则。
带 ``<COMPACTED_HISTORY>`` 的首个 user 回合整条不成题:原始首回合已不在
wire 上,其后同一 Content 里的壳只是当轮请求。
"""
from __future__ import annotations
import re
from collections.abc import Sequence
from typing import NamedTuple
# 复用 cc 路由链路的标题推导器(单一事实源:噪声剥离、豁免前缀、600 字上限)
from ..routing.executor import _derive_title_from_user_texts
# 开壳:``(?=[\s>])`` 挡住 <USER_REQUESTS> / <USER_REQUEST-X> 这类同前缀标签,
# ``[^>]*>`` 兼容带属性的变体
_USER_REQUEST_OPEN_RE = re.compile(r"\s*<USER_REQUEST(?=[\s>])[^>]*>")
_USER_REQUEST_CLOSE = "</USER_REQUEST>"
_TAG_NAME_RE = re.compile(r"^</?([A-Za-z_][A-Za-z0-9_.:-]{0,39})")
_SYSTEM_MESSAGE_MARK_RE = re.compile(r"</?SYSTEM_MESSAGE(?=[\s>/])")
# 系统提醒前缀的探测窗口:模板开头是一句裸文本说明,标签在其后出现
_SYSTEM_MESSAGE_WINDOW = 200
_COMPACTED_HISTORY_TAG = "COMPACTED_HISTORY"
class SessionTitle(NamedTuple):
"""标题推导结果:``title`` 为空时 ``skipped`` 列出各文本 part 被跳过的原因."""
title: str
skipped: tuple[str, ...] = ()
def derive_session_title(
user_texts: Sequence[str], exempt_prefixes: Sequence[str] | None = None
) -> SessionTitle:
"""从首个 user 回合的文本 part 推导会话标题(严格准入,fail-closed).
只有以 ``<USER_REQUEST>`` 开头且闭合的壳,其内文才成为候选;候选交给
``_derive_title_from_user_texts``(与 cc 路由链路同一推导器),首个有效
候选即标题。遇到 ``<COMPACTED_HISTORY>`` 块则整条不成题。
"""
candidates: list[str] = []
skipped: list[str] = []
for text in user_texts:
open_match = _USER_REQUEST_OPEN_RE.match(text)
if open_match:
close = text.rfind(_USER_REQUEST_CLOSE)
inner = text[open_match.end() : close].strip() if close >= 0 else ""
if inner:
candidates.append(inner)
continue
skipped.append("EMPTY_SHELL" if close >= 0 else "UNCLOSED_SHELL")
continue
stripped = text.lstrip()
if stripped.startswith("<"):
tag = _TAG_NAME_RE.match(stripped)
name = tag.group(1) if tag else "unparsed"
if name == _COMPACTED_HISTORY_TAG:
return SessionTitle("", ("COMPACTED_HISTORY_BLOCK",))
skipped.append(f"XML_BLOCK:{name}")
elif _SYSTEM_MESSAGE_MARK_RE.search(stripped[:_SYSTEM_MESSAGE_WINDOW]):
skipped.append("BARE_TEXT:system_message")
else:
skipped.append("BARE_TEXT")
title = _derive_title_from_user_texts(
candidates, exempt_prefixes=list(exempt_prefixes or [])
)
if not title and candidates:
skipped.append("EXEMPT_OR_SANITIZED")
return SessionTitle(title, tuple(skipped))