coding-proxy 0.6.0__py3-none-any.whl → 0.6.1__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.
@@ -379,25 +379,44 @@ def reset(
379
379
  def session_bind(
380
380
  key: str = typer.Option(..., "--key", "-k", help="Session key"),
381
381
  vendor: str = typer.Option(
382
- ..., "--vendor", "-v", help="绑定 vendor(逗号分隔多个)"
382
+ None, "--vendor", "-v", help="绑定 vendor(逗号分隔多个,与 --model 可组合)"
383
+ ),
384
+ model: str = typer.Option(
385
+ None,
386
+ "--model",
387
+ "-m",
388
+ help="绑定模型(须在 config 的 bindable_models 清单内,与 --vendor 可组合)",
383
389
  ),
384
390
  port: int = typer.Option(3392, "--port", "-p", help="代理服务端口"),
385
391
  ) -> None:
386
- """为指定 Session 绑定 vendor 优先级."""
392
+ """为指定 Session 绑定 vendor 优先级与可选的会话级模型覆盖."""
387
393
  import httpx as _httpx
388
394
 
389
- vendors = [v.strip() for v in vendor.split(",") if v.strip()]
395
+ if not vendor and not model:
396
+ console.print("[red]至少提供 --vendor 或 --model 之一[/red]")
397
+ raise typer.Exit(1)
398
+
399
+ payload: dict = {"session_key": key}
400
+ if vendor:
401
+ payload["vendors"] = [v.strip() for v in vendor.split(",") if v.strip()]
402
+ if model:
403
+ payload["model"] = model
390
404
  try:
391
405
  resp = _httpx.put(
392
406
  f"http://127.0.0.1:{port}/api/session-vendor",
393
- json={"session_key": key, "vendors": vendors},
407
+ json=payload,
394
408
  timeout=5,
395
409
  )
396
410
  if resp.status_code == 200:
397
411
  data = resp.json()
412
+ parts = []
413
+ if data.get("model"):
414
+ parts.append(f"model={data['model']}")
415
+ if data.get("vendors"):
416
+ parts.append(" → ".join(data["vendors"]))
398
417
  console.print(
399
418
  f"[green]绑定成功:[/] session [cyan]{key[:16]}…[/cyan] → "
400
- + " → ".join(data.get("vendors", vendors))
419
+ + " ".join(parts)
401
420
  )
402
421
  else:
403
422
  try:
@@ -456,7 +475,11 @@ def session_list(
456
475
  for b in bindings:
457
476
  key = b.get("session_key", "?")
458
477
  vendors = b.get("vendors", [])
459
- console.print(f" [cyan]{key[:24]}…[/cyan] → " + " → ".join(vendors))
478
+ model = b.get("model")
479
+ model_part = f"model={model} " if model else ""
480
+ console.print(
481
+ f" [cyan]{key[:24]}…[/cyan] → {model_part}" + " → ".join(vendors)
482
+ )
460
483
  else:
461
484
  console.print(f"[red]查询失败: {resp.status_code} {resp.text}[/red]")
462
485
  except _httpx.ConnectError:
@@ -719,6 +719,21 @@ native_api:
719
719
  # 未配置时(默认),所有 Session 使用全局 tiers 顺序。
720
720
  session_policies:
721
721
  policies: []
722
+ # 可绑定模型清单 —— Dashboard「Model Bind」下拉选项与 API 校验的唯一来源。
723
+ # label / model 清单内唯一;tiers 为随绑定重排的 vendor 优先级(空 = 不改顺序)。
724
+ # 跨系列原生模型名(如 glm-5.3)需配套 identity model_mapping 规则
725
+ # (pattern 与 target 同名),防 ModelMapper default 静默改写。
726
+ bindable_models:
727
+ - label: "Opus 4.6"
728
+ model: "claude-opus-4.6"
729
+ - label: "Sonnet 4.6"
730
+ model: "claude-sonnet-4.6"
731
+ - label: "Haiku 4.5"
732
+ model: "claude-haiku-4.5"
733
+ # 跨系列示例:
734
+ # - label: "GLM 5.3"
735
+ # model: "glm-5.3"
736
+ # tiers: ["zhipu"]
722
737
  # 标题前缀 → 供应商自动绑定。
723
738
  # 当 Session 标题以指定前缀开头时,自动将该 Session 绑定到对应供应商。
724
739
  # 匹配规则按列表顺序求值,首次匹配生效。
@@ -44,12 +44,50 @@ class SessionPolicy(BaseModel):
44
44
  default_factory=list,
45
45
  description="覆盖全局 tier 顺序的供应商优先级列表",
46
46
  )
47
+ model: str | None = Field(
48
+ default=None,
49
+ min_length=1,
50
+ description=(
51
+ "会话级模型覆盖:非空时该 Session 的后续请求体 model 字段"
52
+ "统一改写为此值(shadow copy,逐请求生效,在途请求不受影响)。"
53
+ ),
54
+ )
55
+
56
+ @field_validator("model", mode="before")
57
+ @classmethod
58
+ def _empty_model_to_none(cls, value: object) -> object:
59
+ """空串/纯空白归一为未设置(Config 页 text 控件清空后保存 '' 的恢复路径)."""
60
+ if isinstance(value, str) and not value.strip():
61
+ return None
62
+ return value
63
+
47
64
  quota: SessionQuotaConfig | None = Field(
48
65
  default=None,
49
66
  description="Per-session 资源配额(预留)",
50
67
  )
51
68
 
52
69
 
70
+ class BindableModel(BaseModel):
71
+ """可绑定模型清单条目 — Dashboard Model Bind 下拉选项的唯一来源."""
72
+
73
+ label: str = Field(
74
+ min_length=1,
75
+ description="UI 显示名(清单内唯一)",
76
+ )
77
+ model: str = Field(
78
+ min_length=1,
79
+ description="覆盖目标模型名(清单内唯一)",
80
+ )
81
+ tiers: list[str] = Field(
82
+ default_factory=list,
83
+ description=(
84
+ "随绑定重排的 vendor 优先级列表(空 = 仅覆盖模型、不改 vendor 顺序)。"
85
+ "跨系列原生模型名(如 glm-5.3)需配套 identity model_mapping 规则,"
86
+ "防 ModelMapper default 静默改写。"
87
+ ),
88
+ )
89
+
90
+
53
91
  class TitleVendorBinding(BaseModel):
54
92
  """标题前缀 → 供应商自动绑定规则."""
55
93
 
@@ -73,6 +111,32 @@ class SessionPoliciesConfig(BaseModel):
73
111
  default_factory=list,
74
112
  description="Session 路由策略列表,按定义顺序求值,首次匹配生效",
75
113
  )
114
+ bindable_models: list[BindableModel] = Field(
115
+ default_factory=list,
116
+ description=(
117
+ "可绑定模型清单(Model Bind 下拉选项的唯一来源)。"
118
+ "API 只允许绑定清单内的模型;跨系列原生模型名需配套 identity "
119
+ "model_mapping 规则。label 与 model 在清单内必须唯一。"
120
+ ),
121
+ )
122
+
123
+ @field_validator("bindable_models", mode="after")
124
+ @classmethod
125
+ def _validate_bindable_models(
126
+ cls, value: list[BindableModel]
127
+ ) -> list[BindableModel]:
128
+ """校验 label / model 清单内唯一,防 UI 选项与 API 校验歧义."""
129
+ seen_labels: set[str] = set()
130
+ seen_models: set[str] = set()
131
+ for item in value:
132
+ if item.label in seen_labels:
133
+ raise ValueError(f"duplicate bindable_models label: {item.label}")
134
+ if item.model in seen_models:
135
+ raise ValueError(f"duplicate bindable_models model: {item.model}")
136
+ seen_labels.add(item.label)
137
+ seen_models.add(item.model)
138
+ return value
139
+
76
140
  title_vendor_bindings: list[TitleVendorBinding] = Field(
77
141
  default_factory=list,
78
142
  description=(
@@ -530,6 +530,37 @@ REGISTRY += [
530
530
  "命中后使用的 vendor 优先级",
531
531
  enum=list(_VENDOR_TYPES),
532
532
  ),
533
+ _f(
534
+ "session_policies.policies.*.model",
535
+ "Model",
536
+ "text",
537
+ "会话级模型覆盖:非空时该 Session 的请求统一改写为此模型",
538
+ ),
539
+ _f(
540
+ "session_policies.bindable_models",
541
+ "Model List",
542
+ "list_section",
543
+ "可绑定模型清单,Model Bind 下拉选项的唯一来源",
544
+ ),
545
+ _f(
546
+ "session_policies.bindable_models.*.label",
547
+ "Label",
548
+ "text",
549
+ "UI 显示名,清单内唯一",
550
+ ),
551
+ _f(
552
+ "session_policies.bindable_models.*.model",
553
+ "Model",
554
+ "text",
555
+ "覆盖目标模型名,清单内唯一",
556
+ ),
557
+ _f(
558
+ "session_policies.bindable_models.*.tiers",
559
+ "Tiers",
560
+ "list",
561
+ "随绑定重排的 vendor 优先级,空则不改顺序",
562
+ enum=list(_VENDOR_TYPES),
563
+ ),
533
564
  _f(
534
565
  "session_policies.title_vendor_bindings",
535
566
  "Title Bindings",
@@ -6,6 +6,7 @@
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
+ import html
9
10
  import json
10
11
  import logging
11
12
  import re
@@ -37,7 +38,7 @@ from .rate_limit import (
37
38
  parse_rate_limit_headers,
38
39
  )
39
40
  from .session_manager import RouteSessionManager
40
- from .session_policy import SessionPolicyResolver
41
+ from .session_policy import SessionPolicy, SessionPolicyResolver
41
42
  from .tier import VendorTier
42
43
  from .usage_parser import (
43
44
  build_usage_evidence_records,
@@ -77,6 +78,8 @@ def _log_unexpected(scope: str, tier_name: str, exc: BaseException) -> None:
77
78
  _SESSION_TITLE_MAX_LEN = 600
78
79
  # 回退标题截取长度 — 工具结果等非用户直接输入的摘要上限。
79
80
  _FALLBACK_TITLE_MAX_LEN = 80
81
+ # 注入式载荷标题截取长度 — 家族标签 + 载荷合计上限,保持列表可扫读。
82
+ _INJECTED_PAYLOAD_TITLE_MAX_LEN = 160
80
83
 
81
84
  # Claude Code 注入的"噪声"标签 — 系统级上下文,不应进入 Session 标题。
82
85
  # 这些标签由 CC harness 在首个 user 消息 content 中拼接,高度同质,
@@ -85,7 +88,7 @@ _NOISE_TAG_PATTERN = re.compile(
85
88
  r"<(?P<tag>system-reminder|user-preferences|"
86
89
  r"local-command-stdout|local-command-stderr|"
87
90
  r"bash-input|bash-stdout|bash-stderr|"
88
- r"ide_selection|stdin|system_instruction|session|"
91
+ r"ide_selection|ide_opened_file|stdin|system_instruction|session|"
89
92
  r"artifactMetadata|thinking)\b[^>]*>"
90
93
  r".*?</(?P=tag)>",
91
94
  flags=re.DOTALL | re.IGNORECASE,
@@ -105,6 +108,12 @@ _CMD_WRAPPER_PATTERN = re.compile(
105
108
  r"<command-[\w-]+>.*?</command-[\w-]+>", flags=re.DOTALL
106
109
  )
107
110
 
111
+ # <pasted_content> 仅剥外壳标签保留内容 — 粘贴体本身是真实用户输入。
112
+ _PASTED_CONTENT_WRAPPER = re.compile(r"</?pasted_content\b[^>]*>", re.IGNORECASE)
113
+
114
+ # [Image #N] 粘贴图片占位符 — 剥离后保留周边真实文本。
115
+ _IMAGE_PLACEHOLDER_PATTERN = re.compile(r"\[Image #\d+\]\s*", re.IGNORECASE)
116
+
108
117
  # 空白折叠
109
118
  _WHITESPACE_PATTERN = re.compile(r"\s+")
110
119
 
@@ -137,6 +146,8 @@ def _sanitize_user_text(raw: str) -> str:
137
146
  # 阶段二: 通用噪声剥离
138
147
  cleaned = _NOISE_TAG_PATTERN.sub("", raw)
139
148
  cleaned = _CMD_WRAPPER_PATTERN.sub("", cleaned)
149
+ cleaned = _PASTED_CONTENT_WRAPPER.sub("", cleaned)
150
+ cleaned = _IMAGE_PLACEHOLDER_PATTERN.sub("", cleaned)
140
151
  cleaned = _WHITESPACE_PATTERN.sub(" ", cleaned).strip()
141
152
  if cleaned:
142
153
  return cleaned
@@ -165,6 +176,200 @@ def _sanitize_user_text(raw: str) -> str:
165
176
  # ─────────────────────────────────────────────────────────────────
166
177
 
167
178
 
179
+ # ── 注入式 Prompt(agent-as-tool 模板)载荷提取 ──────────────────
180
+ #
181
+ # Agent harness(记忆压缩器、会话命名器等)以子会话形式调用模型,首条 user
182
+ # 消息是固定话术模板(如 "You are a memory relevance compressor..."),
183
+ # 模板头无区分度,真实业务载荷内嵌在 "User query:" 等分隔符之后。
184
+ # 家族表按序匹配:(opener, 家族标签, 载荷分隔符, 尾部样板截断);
185
+ # 命中后剥模板头截载荷,产出 "[家族标签] 载荷" 形式标题。
186
+ _INJECTED_PROMPT_FAMILIES: tuple[
187
+ tuple[re.Pattern[str], str, re.Pattern[str], re.Pattern[str] | None, bool], ...
188
+ ] = (
189
+ (
190
+ re.compile(r"(?i)^you are a memory relevance compressor\b"),
191
+ "[记忆压缩]",
192
+ re.compile(r"(?i)\bUser query\s*[::]\s*"),
193
+ re.compile(r"(?i)\bRetrieved\s+\S+\s+context fragments\b"),
194
+ False,
195
+ ),
196
+ (
197
+ re.compile(r"(?i)^Name this chat\b"),
198
+ "[会话命名]",
199
+ re.compile(r"(?i)\bFirst request\s*[::]\s*"),
200
+ re.compile(r"(?i)\bThis is a naming-only task\b"),
201
+ False,
202
+ ),
203
+ (
204
+ re.compile(r"(?i)^Generate a short git branch name\b"),
205
+ "[分支命名]",
206
+ re.compile(r"(?i)\bUser request\s*[::]\s*"),
207
+ None,
208
+ False,
209
+ ),
210
+ (
211
+ re.compile(r"(?i)^Use the \S+ tool to run exactly this one command\b"),
212
+ "[单命令]",
213
+ re.compile(r"(?i)(?:\band nothing else|The command is)\s*[::]\s*"),
214
+ None,
215
+ False,
216
+ ),
217
+ # 通用兜底:其余 "You are ..." 注入式模板。分隔符要求句界锚定(防止真实
218
+ # persona 消息中句中的 "task:"/"query:" 误截断);无分隔符时按真实输入
219
+ # 处理(fallback_real_input=True),避免误伤手打 "You are ..." 的用户消息。
220
+ (
221
+ re.compile(r"(?i)^you are\b"),
222
+ "[注入任务]",
223
+ re.compile(
224
+ r"(?i)(?:^|(?<=[.。!?\n]))\s*(?:User query|User request|First request)\s*[::]\s*"
225
+ ),
226
+ re.compile(r"(?i)\bRetrieved\s+\S+\s+context fragments\b"),
227
+ True,
228
+ ),
229
+ )
230
+
231
+
232
+ # task-notification 载荷凝缩:注入载荷常为 harness 的任务通知 XML 块,
233
+ # 其中的 <summary> 行(如 Agent "xx" finished)才是可扫读标识;
234
+ # 无 summary 时整块剥离后取残余文本。
235
+ _TASK_SUMMARY_PATTERN = re.compile(r"<summary>\s*(.*?)\s*</summary>", re.DOTALL)
236
+ _TASK_NOTIFICATION_BLOCK = re.compile(
237
+ r"<task-notification\b[^>]*>.*?</task-notification>", re.DOTALL | re.IGNORECASE
238
+ )
239
+ # 未闭合的 <task-notification ...> 开标签兜底(块正则不生效时剥开头标签)。
240
+ _NOTIFICATION_OPEN_TAG = re.compile(r"<task-notification\b[^>]*>", re.IGNORECASE)
241
+ # 已知元数据标签:成对剥除时连同内文一起移除(id/路径/状态无扫读价值),
242
+ # 避免剥壳留内文产生孤立 id 残段。
243
+ _NOTIFICATION_ID_PAIRS = re.compile(
244
+ r"<(?P<tag>task-id|tool-use-id|output-file|status|event|note)\b[^>]*>"
245
+ r".*?</(?P=tag)>",
246
+ re.DOTALL | re.IGNORECASE,
247
+ )
248
+ # 未成对的残余元数据标签(截断形态)与 summary 外壳:剥标签本身、保留 summary 内文。
249
+ _NOTIFICATION_ID_TAGS = re.compile(
250
+ r"</?(?:task-id|tool-use-id|output-file|status|event|note|summary)\b[^>]*/?>",
251
+ re.IGNORECASE,
252
+ )
253
+ # 实体转义形态的通知标记(&lt;task-notification / &gt;task-notification):
254
+ # 仅命中时才对载荷做全量实体解码(legacy 无分号实体随之解码,属可接受代价),
255
+ # 其余载荷只做下方安全五元组的定向解码,避免 &not→¬ 类改写真实业务文本。
256
+ _ESCAPED_NOTIFICATION_MARK = re.compile(
257
+ r"&(?:lt|gt|quot);/?(?:task-notification)", re.IGNORECASE
258
+ )
259
+ _SAFE_ENTITIES_MAP = {
260
+ "&lt;": "<",
261
+ "&gt;": ">",
262
+ "&amp;": "&",
263
+ "&quot;": '"',
264
+ "&#39;": "'",
265
+ }
266
+ _SAFE_ENTITY_PATTERN = re.compile(
267
+ "|".join(re.escape(k) for k in _SAFE_ENTITIES_MAP), re.IGNORECASE
268
+ )
269
+
270
+
271
+ def _condense_notification_payload(payload: str) -> str:
272
+ """注入载荷为任务通知 XML 块时凝缩为可读文本,否则原样返回.
273
+
274
+ ``<summary>`` 提取限定在 task-notification 块内(载荷正文自身出现的
275
+ ``<summary>`` 字面量不触发凝缩);块未闭合时退化为剥标签取残余文本。
276
+ """
277
+ if "<task-notification" not in payload.lower():
278
+ return payload
279
+ block = _TASK_NOTIFICATION_BLOCK.search(payload)
280
+ if block:
281
+ m = _TASK_SUMMARY_PATTERN.search(block.group(0))
282
+ if m and m.group(1).strip():
283
+ return m.group(1).strip()
284
+ # 未闭合/无 summary 兜底:成对元数据标签连同内文剥除,summary 剥壳保内文,
285
+ # 使残余文本与闭合块路径口径一致(无孤立 id 残段、无残留标签)。
286
+ stripped = _TASK_NOTIFICATION_BLOCK.sub(" ", payload)
287
+ stripped = _NOTIFICATION_OPEN_TAG.sub(" ", stripped)
288
+ stripped = _NOTIFICATION_ID_PAIRS.sub(" ", stripped)
289
+ stripped = _NOTIFICATION_ID_TAGS.sub(" ", stripped)
290
+ return _WHITESPACE_PATTERN.sub(" ", stripped).strip()
291
+
292
+
293
+ def _extract_injected_prompt_title(cleaned: str) -> str | None:
294
+ """注入式 Prompt 载荷标题提取.
295
+
296
+ Returns:
297
+ ``None`` — 非注入式消息(调用方按真实用户输入处理);
298
+ ``""`` — 命中注入家族但无载荷(模板全同质、无区分度,调用方应跳过该条);
299
+ ``str`` — ``[家族标签] 载荷`` 形式的标题。
300
+ """
301
+ for opener, tag, delim, tail, fallback_real_input in _INJECTED_PROMPT_FAMILIES:
302
+ if not opener.search(cleaned):
303
+ continue
304
+ m = delim.search(cleaned)
305
+ if not m:
306
+ # 具名家族模板高度特异,无载荷即整条跳过;通用家族 opener 宽松,
307
+ # 无载荷时按真实输入处理以免误伤手打 "You are ..." 的用户消息。
308
+ return None if fallback_real_input else ""
309
+ payload = cleaned[m.end() :]
310
+ if tail:
311
+ t = tail.search(payload)
312
+ if t:
313
+ payload = payload[: t.start()]
314
+ # 实体解码分两档:转义形态的通知 XML 全量解码(先于凝缩守卫,转义形态
315
+ # 需还原为字面标签才能被识别);其余载荷仅定向解码带分号的安全实体
316
+ # (&lt;/&gt;/&amp;/&quot;/&#39;),避免 html.unescape 的 HTML5 legacy
317
+ # 无分号规则(&not→¬ 等)改写真实业务文本。
318
+ has_escaped_notification = bool(_ESCAPED_NOTIFICATION_MARK.search(payload))
319
+ if has_escaped_notification:
320
+ payload = html.unescape(payload)
321
+ payload = _condense_notification_payload(payload)
322
+ if not has_escaped_notification:
323
+ payload = _SAFE_ENTITY_PATTERN.sub(
324
+ lambda m: _SAFE_ENTITIES_MAP[m.group(0).lower()], payload
325
+ )
326
+ payload = _WHITESPACE_PATTERN.sub(" ", payload).strip()
327
+ if not payload:
328
+ return ""
329
+ return f"{tag} {payload}"[:_INJECTED_PAYLOAD_TITLE_MAX_LEN]
330
+ return None
331
+
332
+
333
+ def _derive_title_from_user_texts(
334
+ texts, exempt_prefixes: list[str] | None = None
335
+ ) -> str:
336
+ """从一批用户原始文本推导标题 — 供请求路径与历史回填共用.
337
+
338
+ 逐条清洗 → 豁免前缀跳过 → 注入式载荷提取 → 首条真实输入。
339
+ 豁免前缀同时作用于清洗文本与派生的注入式标题(豁免家族标签时
340
+ 跳过该条继续查找,而非丢弃整个 Level 1)。
341
+ 全部跳过时返回空串(调用方按无候选处理)。
342
+ """
343
+ prefixes = [p for p in (exempt_prefixes or []) if p]
344
+
345
+ def _exempt(candidate: str) -> bool:
346
+ if any(candidate.startswith(p) for p in prefixes):
347
+ logger.debug(
348
+ "Title candidate skipped by exempt prefix (snippet=%r)",
349
+ candidate[:60],
350
+ )
351
+ return True
352
+ return False
353
+
354
+ for raw in texts:
355
+ cleaned = _sanitize_user_text(raw)
356
+ if not cleaned:
357
+ continue
358
+ # 整条消息即 harness 固定话术:背景任务通知 / 会话续接摘要,无区分度。
359
+ if cleaned.startswith("<task-notification") or cleaned.startswith(
360
+ "This session is being continued"
361
+ ):
362
+ continue
363
+ if _exempt(cleaned):
364
+ continue
365
+ injected = _extract_injected_prompt_title(cleaned)
366
+ if injected is None:
367
+ return cleaned[:_SESSION_TITLE_MAX_LEN]
368
+ if injected and not _exempt(injected):
369
+ return injected
370
+ return ""
371
+
372
+
168
373
  def _extract_title_from_user_text(
169
374
  messages: list[CanonicalMessagePart],
170
375
  exempt_prefixes: list[str] | None = None,
@@ -174,22 +379,15 @@ def _extract_title_from_user_text(
174
379
  ``exempt_prefixes`` 非空时,清洗后文本以任一前缀开头则跳过该输入、继续向后
175
380
  查找——用于过滤注入式 Prompt,避免其被误用作 Session 标题。匹配作用于
176
381
  ``_sanitize_user_text`` 清洗后的纯文本(而非带 XML 标签的原始 raw)。
382
+ 注入式模板消息(agent-as-tool 话术)经 ``_extract_injected_prompt_title``
383
+ 剥离模板头、截取业务载荷;无载荷则跳过该条继续查找。
177
384
  """
178
- for part in messages:
179
- if part.role != "user" or part.type != CanonicalPartType.TEXT:
180
- continue
181
- cleaned = _sanitize_user_text(part.text)
182
- if not cleaned:
183
- continue
184
- if exempt_prefixes and any(cleaned.startswith(p) for p in exempt_prefixes):
185
- logger.debug(
186
- "Title candidate skipped by exempt prefix %r (snippet=%r)",
187
- next(p for p in exempt_prefixes if cleaned.startswith(p)),
188
- cleaned[:60],
189
- )
190
- continue
191
- return cleaned[:_SESSION_TITLE_MAX_LEN]
192
- return ""
385
+ texts = [
386
+ part.text
387
+ for part in messages
388
+ if part.role == "user" and part.type == CanonicalPartType.TEXT
389
+ ]
390
+ return _derive_title_from_user_texts(texts, exempt_prefixes=exempt_prefixes)
193
391
 
194
392
 
195
393
  def _extract_title_from_tool_results(messages: list[CanonicalMessagePart]) -> str:
@@ -722,13 +920,17 @@ class _RouteExecutor:
722
920
 
723
921
  # ── 公开执行入口 ──────────────────────────────────────
724
922
 
725
- def _resolve_effective_tiers(self, session_key: str) -> list[VendorTier]:
923
+ def _resolve_effective_tiers(
924
+ self, session_key: str, policy: SessionPolicy | None = None
925
+ ) -> list[VendorTier]:
726
926
  """根据 Session Policy 解析生效的 tier 顺序.
727
927
 
728
928
  策略指定的 vendor 按其顺序排列在头部,未提及的保持在末尾。
729
- 无策略时返回全局默认顺序。
929
+ 无策略时返回全局默认顺序。policy 可由调用方预先 resolve 传入,
930
+ 与会话级模型覆盖共用同一次解析(避免双重 resolve 的竞态窗口)。
730
931
  """
731
- policy = self._policy_resolver.resolve(session_key)
932
+ if policy is None:
933
+ policy = self._policy_resolver.resolve(session_key)
732
934
  if not policy or not policy.tiers:
733
935
  return self._tiers
734
936
 
@@ -746,6 +948,44 @@ class _RouteExecutor:
746
948
  seen.add(tier.name)
747
949
  return ordered
748
950
 
951
+ _MODEL_FALLBACK_REASONS = frozenset({"default"})
952
+
953
+ @classmethod
954
+ def _log_model_drift(
955
+ cls,
956
+ bound_model: str | None,
957
+ tier: VendorTier,
958
+ model_served: str,
959
+ ) -> None:
960
+ """会话模型覆盖生效但实际 served 模型偏离预期时告警.
961
+
962
+ 两类触发:served 既非绑定名也非接单 vendor 映射预期(failover 接单 /
963
+ 上游换名),或绑定名命中映射 default 回退被改写(缺显式规则)。
964
+ 配置内等价映射(如 claude 档位名 → glm 档位名)属预期行为,不告警。
965
+ """
966
+ if not bound_model:
967
+ return
968
+ expected, reason = tier.vendor.map_model_with_reason(bound_model)
969
+ if model_served not in (bound_model, expected):
970
+ logger.warning(
971
+ "Session model drift: bound=%s but tier %s served %s "
972
+ "(its model mapping expected %s — failover takeover or "
973
+ "unexpected upstream substitution)",
974
+ bound_model,
975
+ tier.name,
976
+ model_served,
977
+ expected,
978
+ )
979
+ elif reason in cls._MODEL_FALLBACK_REASONS and model_served != bound_model:
980
+ logger.warning(
981
+ "Session model drift: bound=%s hit model_mapping default fallback "
982
+ "on tier %s and was rewritten to %s — add an identity mapping "
983
+ "rule (pattern=target) for this model",
984
+ bound_model,
985
+ tier.name,
986
+ model_served,
987
+ )
988
+
749
989
  def _extract_session_title(self, request: CanonicalRequest) -> str:
750
990
  """封装模块级标题提取,注入实例持有的豁免前缀名单.
751
991
 
@@ -767,6 +1007,10 @@ class _RouteExecutor:
767
1007
  """
768
1008
  if not title or not self._title_vendor_bindings:
769
1009
  return
1010
+ # 已有运行时绑定(手动 Vendor/Model Bind)时跳过,防自动绑定整条覆盖;
1011
+ # compat TTL 过期导致长会话被重新判定为新会话时同样受此保护。
1012
+ if self._policy_resolver.get_runtime_binding(session_key) is not None:
1013
+ return
770
1014
  for binding in self._title_vendor_bindings:
771
1015
  if title.startswith(binding.prefix):
772
1016
  self._policy_resolver.upsert(session_key, [binding.vendor])
@@ -885,7 +1129,20 @@ class _RouteExecutor:
885
1129
  canonical_request.session_key, title
886
1130
  )
887
1131
  incompatible_reasons: list[str] = []
888
- effective_tiers = self._resolve_effective_tiers(canonical_request.session_key)
1132
+ session_policy = self._policy_resolver.resolve(canonical_request.session_key)
1133
+ client_model = str(body.get("model", "unknown"))
1134
+ bound_model = session_policy.model if session_policy else None
1135
+ if bound_model and bound_model != client_model:
1136
+ logger.info(
1137
+ "Session model override active: session=%s client_model=%s → bound_model=%s",
1138
+ canonical_request.session_key[:12],
1139
+ client_model,
1140
+ bound_model,
1141
+ )
1142
+ body = {**body, "model": bound_model}
1143
+ effective_tiers = self._resolve_effective_tiers(
1144
+ canonical_request.session_key, policy=session_policy
1145
+ )
889
1146
  last_idx = len(effective_tiers) - 1
890
1147
 
891
1148
  for i, tier in enumerate(effective_tiers):
@@ -942,6 +1199,7 @@ class _RouteExecutor:
942
1199
  duration = int((time.monotonic() - start) * 1000)
943
1200
  model = body.get("model", "unknown")
944
1201
  model_served = usage.get("model_served") or tier.vendor.map_model(model)
1202
+ self._log_model_drift(bound_model, tier, model_served)
945
1203
  if failed_tier_name is not None:
946
1204
  logger.info(
947
1205
  "Tier %s stream succeeded (took over from failed tier: %s)",
@@ -1066,7 +1324,20 @@ class _RouteExecutor:
1066
1324
  canonical_request.session_key, title
1067
1325
  )
1068
1326
  incompatible_reasons: list[str] = []
1069
- effective_tiers = self._resolve_effective_tiers(canonical_request.session_key)
1327
+ session_policy = self._policy_resolver.resolve(canonical_request.session_key)
1328
+ client_model = str(body.get("model", "unknown"))
1329
+ bound_model = session_policy.model if session_policy else None
1330
+ if bound_model and bound_model != client_model:
1331
+ logger.info(
1332
+ "Session model override active: session=%s client_model=%s → bound_model=%s",
1333
+ canonical_request.session_key[:12],
1334
+ client_model,
1335
+ bound_model,
1336
+ )
1337
+ body = {**body, "model": bound_model}
1338
+ effective_tiers = self._resolve_effective_tiers(
1339
+ canonical_request.session_key, policy=session_policy
1340
+ )
1070
1341
  last_idx = len(effective_tiers) - 1
1071
1342
 
1072
1343
  for i, tier in enumerate(effective_tiers):
@@ -1096,6 +1367,7 @@ class _RouteExecutor:
1096
1367
  duration = int((time.monotonic() - start) * 1000)
1097
1368
  model = body.get("model", "unknown")
1098
1369
  model_served = resp.model_served or tier.vendor.map_model(model)
1370
+ self._log_model_drift(bound_model, tier, model_served)
1099
1371
  if failed_tier_name is not None:
1100
1372
  logger.info(
1101
1373
  "Tier %s message succeeded (took over from failed tier: %s)",
@@ -50,9 +50,18 @@ class ModelMapper:
50
50
  def map(
51
51
  self, model: str, vendor: str = "fallback", default: str | None = None
52
52
  ) -> str:
53
- """将源模型名映射为目标模型名.
53
+ """将源模型名映射为目标模型名(见 map_with_reason)."""
54
+ return self.map_with_reason(model, vendor, default)[0]
55
+
56
+ def map_with_reason(
57
+ self, model: str, vendor: str = "fallback", default: str | None = None
58
+ ) -> tuple[str, str]:
59
+ """将源模型名映射为目标模型名并返回命中原因.
54
60
 
55
61
  优先级:精确匹配 > 通配符/正则匹配 > default/_DEFAULT_TARGET。
62
+ 返回 (target, reason),reason ∈ {"exact", "pattern", "default"};
63
+ "default" 表示未命中任何显式规则、走了回退目标(会话级模型覆盖的
64
+ 漂移告警据此区分「配置内等价映射」与「缺规则被静默改写」)。
56
65
  """
57
66
  display_name = vendor.strip().lower()
58
67
  match_key = self._normalize_vendor(vendor)
@@ -62,7 +71,7 @@ class ModelMapper:
62
71
  continue
63
72
  if not rule.is_regex and "*" not in rule.pattern:
64
73
  if rule.pattern == model:
65
- return rule.target
74
+ return rule.target, "exact"
66
75
 
67
76
  # 2. 通配符/正则匹配
68
77
  for rule in self._rules:
@@ -71,10 +80,10 @@ class ModelMapper:
71
80
  if rule.is_regex:
72
81
  compiled = self._compiled[rule.pattern]
73
82
  if compiled.fullmatch(model):
74
- return rule.target
83
+ return rule.target, "pattern"
75
84
  elif "*" in rule.pattern:
76
85
  if fnmatch.fnmatch(model, rule.pattern):
77
- return rule.target
86
+ return rule.target, "pattern"
78
87
 
79
88
  # 3. 默认值
80
89
  fallback_target = default or _DEFAULT_TARGET
@@ -84,4 +93,4 @@ class ModelMapper:
84
93
  fallback_target,
85
94
  display_name,
86
95
  )
87
- return fallback_target
96
+ return fallback_target, "default"