coderouter-cli 2.6.0__py3-none-any.whl → 2.7.0__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.
@@ -35,6 +35,7 @@ from collections.abc import AsyncIterator
35
35
  from typing import Any
36
36
 
37
37
  import httpx
38
+ from pydantic import ValidationError
38
39
 
39
40
  from coderouter.adapters.base import (
40
41
  AdapterError,
@@ -68,6 +69,26 @@ _RETRYABLE_STATUSES = {404, 408, 425, 429, 500, 502, 503, 504}
68
69
  _DEFAULT_ANTHROPIC_VERSION = "2023-06-01"
69
70
 
70
71
 
72
+ def anthropic_messages_url(base_url: str) -> str:
73
+ """Resolve the ``/v1/messages`` endpoint URL from a ``base_url``.
74
+
75
+ ``base_url`` may be given with or without a trailing ``/v1`` — users
76
+ may point it at either ``https://api.anthropic.com`` or
77
+ ``https://api.anthropic.com/v1`` (LM Studio and similar servers
78
+ commonly advertise the latter). We normalize by stripping a trailing
79
+ ``/v1`` so appending ``/v1/messages`` always yields a valid,
80
+ non-duplicated URL.
81
+
82
+ Shared by :class:`AnthropicAdapter` and the continuous-probe guard so
83
+ both hit the exact same endpoint (see bug H4: a mismatch made the
84
+ probe target ``/v1/v1/messages`` and 404 on healthy backends).
85
+ """
86
+ base = base_url.rstrip("/")
87
+ if base.endswith("/v1"):
88
+ base = base[: -len("/v1")]
89
+ return f"{base}/v1/messages"
90
+
91
+
71
92
  class AnthropicAdapter(BaseAdapter):
72
93
  """Native Anthropic Messages API adapter (passthrough).
73
94
 
@@ -87,15 +108,10 @@ class AnthropicAdapter(BaseAdapter):
87
108
 
88
109
  ``base_url`` may be given with or without a trailing ``/v1`` —
89
110
  we normalize by stripping it so appending ``/v1/messages``
90
- always yields a valid URL.
111
+ always yields a valid URL. Delegates to the shared
112
+ :func:`anthropic_messages_url` helper.
91
113
  """
92
- base = str(self.config.base_url).rstrip("/")
93
- # Users may point base_url at either `https://api.anthropic.com`
94
- # or `https://api.anthropic.com/v1`. We normalize to the former so
95
- # we can always append /v1/messages.
96
- if base.endswith("/v1"):
97
- base = base[: -len("/v1")]
98
- return f"{base}/v1/messages"
114
+ return anthropic_messages_url(str(self.config.base_url))
99
115
 
100
116
  def _headers(self, request: AnthropicRequest | None = None) -> dict[str, str]:
101
117
  """Build Anthropic-native HTTP headers, including beta-header forwarding.
@@ -161,21 +177,21 @@ class AnthropicAdapter(BaseAdapter):
161
177
  that auth works and the endpoint is reachable.
162
178
  """
163
179
  try:
164
- async with httpx.AsyncClient(timeout=5.0) as client:
165
- resp = await client.post(
166
- self._url(),
167
- headers=self._headers(),
168
- json={
169
- "model": self.config.model,
170
- "max_tokens": 1,
171
- "messages": [{"role": "user", "content": "ping"}],
172
- },
173
- )
174
- # 200 is clearly healthy. 4xx auth errors indicate the
175
- # endpoint is reachable even if the key is bad — still a
176
- # "the server answered" signal for healthcheck purposes.
177
- # 5xx is upstream trouble.
178
- return resp.status_code < 500
180
+ resp = await self.client().post(
181
+ self._url(),
182
+ headers=self._headers(),
183
+ json={
184
+ "model": self.config.model,
185
+ "max_tokens": 1,
186
+ "messages": [{"role": "user", "content": "ping"}],
187
+ },
188
+ timeout=5.0,
189
+ )
190
+ # 200 is clearly healthy. 4xx auth errors indicate the
191
+ # endpoint is reachable even if the key is bad — still a
192
+ # "the server answered" signal for healthcheck purposes.
193
+ # 5xx is upstream trouble.
194
+ return resp.status_code < 500
179
195
  except httpx.HTTPError:
180
196
  return False
181
197
 
@@ -331,8 +347,9 @@ class AnthropicAdapter(BaseAdapter):
331
347
  timeout = self.effective_timeout(overrides)
332
348
 
333
349
  try:
334
- async with httpx.AsyncClient(timeout=timeout) as client:
335
- resp = await client.post(url, json=payload, headers=self._headers(request))
350
+ resp = await self.client().post(
351
+ url, json=payload, headers=self._headers(request), timeout=timeout
352
+ )
336
353
  except httpx.TimeoutException as exc:
337
354
  raise AdapterError(
338
355
  f"timeout contacting {url}", provider=self.name, retryable=True
@@ -394,7 +411,22 @@ class AnthropicAdapter(BaseAdapter):
394
411
  # (future additions like thinking blocks) pass through via
395
412
  # extra="allow" on AnthropicResponse.
396
413
  data["coderouter_provider"] = self.name
397
- return AnthropicResponse.model_validate(data)
414
+ # M6: guard the model validation. A 200 body that isn't a valid
415
+ # Anthropic Messages response (missing ``content``/``id``, an
416
+ # error envelope returned with a 200, etc.) would otherwise raise
417
+ # a bare pydantic ValidationError that escapes the engine's
418
+ # AdapterError-based retry/fallback path. Convert to a retryable
419
+ # AdapterError so the chain can fall through (mirrors the
420
+ # invalid-JSON branch above, but retryable — a malformed shape is
421
+ # usually transient upstream noise rather than a config fault).
422
+ try:
423
+ return AnthropicResponse.model_validate(data)
424
+ except ValidationError as exc:
425
+ raise AdapterError(
426
+ f"malformed response shape from upstream: {exc}",
427
+ provider=self.name,
428
+ retryable=True,
429
+ ) from exc
398
430
 
399
431
  async def stream_anthropic(
400
432
  self,
@@ -424,10 +456,14 @@ class AnthropicAdapter(BaseAdapter):
424
456
  logged_flag: list[bool] = [False]
425
457
 
426
458
  try:
427
- async with (
428
- httpx.AsyncClient(timeout=timeout) as client,
429
- client.stream("POST", url, json=payload, headers=self._headers(request)) as resp,
430
- ):
459
+ # H3: stream over the shared client (pool / keep-alive / TLS
460
+ # reuse). Only the ``stream(...)`` context is scoped here; the
461
+ # client persists and is closed via ``aclose`` on shutdown. The
462
+ # ``async with`` releases the response's borrowed connection even
463
+ # if the caller abandons this generator mid-stream — no GC leak.
464
+ async with self.client().stream(
465
+ "POST", url, json=payload, headers=self._headers(request), timeout=timeout
466
+ ) as resp:
431
467
  if resp.status_code >= 400:
432
468
  body = await resp.aread()
433
469
  raise AdapterError(
@@ -11,6 +11,7 @@ from abc import ABC, abstractmethod
11
11
  from collections.abc import AsyncIterator
12
12
  from typing import Any, Literal
13
13
 
14
+ import httpx
14
15
  from pydantic import BaseModel, ConfigDict, Field
15
16
 
16
17
  from coderouter.config.schemas import ProviderConfig
@@ -164,17 +165,59 @@ class BaseAdapter(ABC):
164
165
  def __init__(self, config: ProviderConfig) -> None:
165
166
  """Bind the adapter to a :class:`ProviderConfig`.
166
167
 
167
- Subclasses do not need to override this; HTTP clients are
168
- constructed lazily inside :meth:`generate` / :meth:`stream` so
169
- each call can honor a per-call timeout override.
168
+ Subclasses do not need to override this. A single shared
169
+ :class:`httpx.AsyncClient` is created lazily on first use (see
170
+ :meth:`client`) and reused across every call on this adapter so
171
+ the connection pool, HTTP keep-alive, and TLS session are all
172
+ reused. Per-call timeouts are still honored by passing
173
+ ``timeout=`` to ``client.post`` / ``client.stream`` — they do
174
+ NOT require a fresh client.
170
175
  """
171
176
  self.config = config
177
+ # Shared client, created lazily inside the running event loop the
178
+ # first time an adapter method needs it (see ``client``). Kept as
179
+ # ``None`` until then so constructing an adapter has no I/O cost and
180
+ # is safe outside an event loop (e.g. at import / config time).
181
+ self._client: httpx.AsyncClient | None = None
172
182
 
173
183
  @property
174
184
  def name(self) -> str:
175
185
  """Shortcut for ``self.config.name`` — used in log trails and errors."""
176
186
  return self.config.name
177
187
 
188
+ # ---- H3: shared HTTP client (connection-pool / keep-alive reuse) ----
189
+ def client(self) -> httpx.AsyncClient:
190
+ """Return the shared :class:`httpx.AsyncClient`, creating it lazily.
191
+
192
+ The client is created on first use so construction happens inside
193
+ the running event loop and carries no I/O cost at adapter-build
194
+ time. Subsequent calls return the same instance, which is what
195
+ lets httpx reuse pooled connections, keep-alive, and the TLS
196
+ session across requests.
197
+
198
+ No default timeout is baked in here: every call site passes an
199
+ explicit per-call ``timeout=`` (resolved from the active profile
200
+ via :meth:`effective_timeout`), so leaving the client timeout
201
+ unset avoids a surprising default clamping long-running calls.
202
+ """
203
+ if self._client is None:
204
+ self._client = httpx.AsyncClient(timeout=None)
205
+ return self._client
206
+
207
+ async def aclose(self) -> None:
208
+ """Close the shared HTTP client and drop the reference.
209
+
210
+ Idempotent: safe to call when no client was ever created, and
211
+ safe to call more than once. Invoked from the app lifespan
212
+ shutdown path so pooled connections are released cleanly rather
213
+ than left to garbage collection. After ``aclose`` a later call
214
+ re-creates the client on demand via :meth:`client`.
215
+ """
216
+ client = self._client
217
+ self._client = None
218
+ if client is not None:
219
+ await client.aclose()
220
+
178
221
  # ---- v0.6-B override resolution helpers -----------------------------
179
222
  def effective_timeout(self, overrides: ProviderCallOverrides | None) -> float:
180
223
  """Profile override wins when set; else provider default."""
@@ -19,6 +19,7 @@ from collections.abc import AsyncIterator
19
19
  from typing import Any
20
20
 
21
21
  import httpx
22
+ from pydantic import ValidationError
22
23
 
23
24
  from coderouter.adapters.base import (
24
25
  AdapterError,
@@ -197,9 +198,8 @@ class OpenAICompatAdapter(BaseAdapter):
197
198
  base = str(self.config.base_url).rstrip("/")
198
199
  url = f"{base}/models"
199
200
  try:
200
- async with httpx.AsyncClient(timeout=5.0) as client:
201
- resp = await client.get(url, headers=self._headers())
202
- return resp.status_code < 500
201
+ resp = await self.client().get(url, headers=self._headers(), timeout=5.0)
202
+ return resp.status_code < 500
203
203
  except httpx.HTTPError:
204
204
  return False
205
205
 
@@ -221,8 +221,9 @@ class OpenAICompatAdapter(BaseAdapter):
221
221
  payload = self._payload(request, stream=False, overrides=overrides)
222
222
  timeout = self.effective_timeout(overrides)
223
223
  try:
224
- async with httpx.AsyncClient(timeout=timeout) as client:
225
- resp = await client.post(url, json=payload, headers=self._headers())
224
+ resp = await self.client().post(
225
+ url, json=payload, headers=self._headers(), timeout=timeout
226
+ )
226
227
  except httpx.TimeoutException as exc:
227
228
  raise AdapterError(
228
229
  f"timeout contacting {url}", provider=self.name, retryable=True
@@ -287,7 +288,22 @@ class OpenAICompatAdapter(BaseAdapter):
287
288
 
288
289
  # Tag the response with which provider answered
289
290
  data.setdefault("object", "chat.completion")
290
- return ChatResponse(coderouter_provider=self.name, **data)
291
+ # M6: a syntactically valid JSON body may still not be a valid
292
+ # Chat Completions response (e.g. an OpenAI-compat server that
293
+ # returns ``{"error": ...}`` with a 200, or omits ``choices``).
294
+ # pydantic raises ValidationError here; if left uncaught it would
295
+ # propagate past the engine's AdapterError-based retry/fallback
296
+ # logic. Convert to a retryable AdapterError so the chain can fall
297
+ # through to the next provider (mirrors the invalid-JSON branch,
298
+ # but retryable since a malformed shape is often transient).
299
+ try:
300
+ return ChatResponse(coderouter_provider=self.name, **data)
301
+ except ValidationError as exc:
302
+ raise AdapterError(
303
+ f"malformed response shape from upstream: {exc}",
304
+ provider=self.name,
305
+ retryable=True,
306
+ ) from exc
291
307
 
292
308
  async def stream(
293
309
  self,
@@ -312,6 +328,10 @@ class OpenAICompatAdapter(BaseAdapter):
312
328
  # produce dozens of duplicate log lines.
313
329
  strip_reasoning = not self.config.capabilities.reasoning_passthrough
314
330
  reasoning_logged = False
331
+ # M6: one-shot dedupe flag for the malformed-chunk warning. A single
332
+ # broken stream can emit many non-conforming chunks; we skip each one
333
+ # but log only on the first to avoid a log flood.
334
+ malformed_chunk_logged = False
315
335
 
316
336
  # v1.0-A: stateful output_filters chain for the duration of this
317
337
  # stream. Handles `<think>...</think>` / stop markers that split
@@ -325,10 +345,16 @@ class OpenAICompatAdapter(BaseAdapter):
325
345
  # seen chunk's id/model so the flush emission looks native.
326
346
  last_chunk_template: dict[str, Any] | None = None
327
347
  try:
328
- async with (
329
- httpx.AsyncClient(timeout=timeout) as client,
330
- client.stream("POST", url, json=payload, headers=self._headers()) as resp,
331
- ):
348
+ # H3: stream over the shared client so the connection pool /
349
+ # keep-alive / TLS session are reused. Only the ``stream(...)``
350
+ # context is entered here — the client itself outlives the
351
+ # stream and is closed via ``aclose`` on app shutdown. The
352
+ # ``async with`` guarantees the response (and its borrowed
353
+ # connection) is released even if the consumer abandons this
354
+ # generator mid-stream, so no connection leaks on GC.
355
+ async with self.client().stream(
356
+ "POST", url, json=payload, headers=self._headers(), timeout=timeout
357
+ ) as resp:
332
358
  if resp.status_code >= 400:
333
359
  body = await resp.aread()
334
360
  raise AdapterError(
@@ -375,7 +401,23 @@ class OpenAICompatAdapter(BaseAdapter):
375
401
  if isinstance(content, str) and content:
376
402
  delta["content"] = filter_chain.feed(content)
377
403
  last_chunk_template = payload_obj
378
- yield StreamChunk(**payload_obj)
404
+ # M6: a chunk may be valid JSON yet not a valid
405
+ # StreamChunk (e.g. a mid-stream ``{"error": ...}``
406
+ # frame, or a chunk missing required fields). Rather
407
+ # than let the ValidationError abort the whole stream
408
+ # (bypassing the engine's AdapterError handling), skip
409
+ # the bad chunk and keep consuming. Warn once per stream.
410
+ try:
411
+ chunk = StreamChunk(**payload_obj)
412
+ except ValidationError as exc:
413
+ if not malformed_chunk_logged:
414
+ logger.warning(
415
+ "malformed-stream-chunk",
416
+ extra={"provider": self.name, "error": str(exc)},
417
+ )
418
+ malformed_chunk_logged = True
419
+ continue
420
+ yield chunk
379
421
 
380
422
  # v1.0-A: flush the chain at end-of-stream. If filters held
381
423
  # back a partial-tag suffix that turned out NOT to be a tag,
@@ -706,6 +706,63 @@ class FallbackChain(BaseModel):
706
706
  ),
707
707
  )
708
708
 
709
+ @model_validator(mode="after")
710
+ def _check_context_budget_thresholds_ordered(self) -> FallbackChain:
711
+ """v2.0-F (mE): cross-field sanity of the context-budget ratios.
712
+
713
+ The three ratios describe a strict staircase: a warning fires
714
+ first, then trimming kicks in at a higher usage, and trimming
715
+ reclaims space down to a target below the trim point. If they are
716
+ mis-ordered the guard is either a dead knob (warn above trim never
717
+ fires) or an infinite trim loop (target >= trim never converges).
718
+ Same fast-fail philosophy as ``_check_default_profile_exists`` —
719
+ surface the mistake at load with a concrete pointer to the fix
720
+ rather than at the first request that trips the guard.
721
+
722
+ Required invariants:
723
+ * ``context_budget_warn_threshold`` <= ``context_budget_trim_threshold``
724
+ * ``context_budget_trim_target`` < ``context_budget_trim_threshold``
725
+ """
726
+ if self.context_budget_warn_threshold > self.context_budget_trim_threshold:
727
+ raise ValueError(
728
+ f"profile {self.name!r}: context_budget_warn_threshold "
729
+ f"({self.context_budget_warn_threshold}) must be <= "
730
+ f"context_budget_trim_threshold "
731
+ f"({self.context_budget_trim_threshold}) — the warning has to "
732
+ f"fire at or before trimming, otherwise it can never fire. "
733
+ f"Lower warn_threshold or raise trim_threshold."
734
+ )
735
+ if self.context_budget_trim_target >= self.context_budget_trim_threshold:
736
+ raise ValueError(
737
+ f"profile {self.name!r}: context_budget_trim_target "
738
+ f"({self.context_budget_trim_target}) must be < "
739
+ f"context_budget_trim_threshold "
740
+ f"({self.context_budget_trim_threshold}) — trimming must "
741
+ f"reclaim space *below* the trigger point, otherwise trim "
742
+ f"never converges. Lower trim_target below trim_threshold."
743
+ )
744
+ return self
745
+
746
+ @model_validator(mode="after")
747
+ def _check_recovery_probe_interval_ordered(self) -> FallbackChain:
748
+ """v2.0-J (mE): the recovery-probe backoff floor must not exceed its cap.
749
+
750
+ ``recovery_probe_initial_s`` is the first probe interval and each
751
+ failed probe doubles it up to ``recovery_probe_max_s``. When the
752
+ initial interval already exceeds the max, the exponential-backoff
753
+ ceiling is below its own floor — a nonsensical configuration that
754
+ the backoff loop would silently clamp. Surface it at load instead.
755
+ """
756
+ if self.recovery_probe_initial_s > self.recovery_probe_max_s:
757
+ raise ValueError(
758
+ f"profile {self.name!r}: recovery_probe_initial_s "
759
+ f"({self.recovery_probe_initial_s}) must be <= "
760
+ f"recovery_probe_max_s ({self.recovery_probe_max_s}) — the "
761
+ f"initial probe interval cannot exceed the backoff ceiling. "
762
+ f"Lower recovery_probe_initial_s or raise recovery_probe_max_s."
763
+ )
764
+ return self
765
+
709
766
 
710
767
  # ---------------------------------------------------------------------------
711
768
  # v1.6-A: auto_router — declarative request-body classifier
@@ -720,6 +777,14 @@ class RuleMatcher(BaseModel):
720
777
  adding a new optional field — the single-field invariant enforces
721
778
  discriminated-union semantics without pydantic's tagged-union syntax.
722
779
 
780
+ Boolean matchers (``has_image`` / ``has_tools``) only carry meaning at
781
+ ``True``: the runtime evaluator matches with ``is True`` (see
782
+ ``coderouter.routing.auto_router._match_rule``), so a ``False`` value
783
+ would construct without error yet never match anything — a dead rule
784
+ that silently shadows nothing and confuses operators. ``_exactly_one``
785
+ therefore rejects ``False`` for these fields at load (``None`` remains
786
+ the "unset" sentinel).
787
+
723
788
  Variants (v1.6-A):
724
789
 
725
790
  - ``has_image: True`` — any ``image_url`` / ``image`` /
@@ -822,8 +887,29 @@ class RuleMatcher(BaseModel):
822
887
  "cjk_ratio_min",
823
888
  )
824
889
 
890
+ # Boolean matcher fields carry meaning only at ``True`` — the runtime
891
+ # evaluator uses ``is True`` — so a ``False`` value is a dead rule that
892
+ # never matches. ``_exactly_one`` rejects it explicitly (see below).
893
+ _BOOL_MATCHER_FIELDS: tuple[str, ...] = ("has_image", "has_tools")
894
+
825
895
  @model_validator(mode="after")
826
896
  def _exactly_one(self) -> Self:
897
+ # Reject the dead-rule shape first so the error names the specific
898
+ # field the operator got wrong, rather than the generic
899
+ # "exactly one" message (``False`` counts as "set" below).
900
+ false_bools = [
901
+ name
902
+ for name in self._BOOL_MATCHER_FIELDS
903
+ if getattr(self, name) is False
904
+ ]
905
+ if false_bools:
906
+ raise ValueError(
907
+ f"RuleMatcher boolean matcher(s) set to False: {false_bools}. "
908
+ f"These matchers are evaluated with ``is True``, so a False "
909
+ f"value is a dead rule that never matches (it would silently "
910
+ f"shadow nothing). Use True to match, or omit the field "
911
+ f"(leave it None) to not use this matcher."
912
+ )
827
913
  set_fields = [
828
914
  name for name in self._MATCHER_FIELDS if getattr(self, name) is not None
829
915
  ]
@@ -1391,6 +1477,74 @@ class CodeRouterConfig(BaseModel):
1391
1477
  )
1392
1478
  return self
1393
1479
 
1480
+ @model_validator(mode="after")
1481
+ def _check_names_unique(self) -> CodeRouterConfig:
1482
+ """mE: provider and profile names must each be unique.
1483
+
1484
+ ``provider_by_name`` / ``profile_by_name`` return the *first*
1485
+ match, so a duplicate name silently shadows every later entry with
1486
+ the same key — the operator's second ``local:`` block is loaded,
1487
+ validated, and then never reachable. Reject duplicates at load with
1488
+ the offending names, matching the fast-fail philosophy of the other
1489
+ ``_check_*`` validators.
1490
+ """
1491
+ seen_p: set[str] = set()
1492
+ dup_p: list[str] = []
1493
+ for p in self.providers:
1494
+ if p.name in seen_p and p.name not in dup_p:
1495
+ dup_p.append(p.name)
1496
+ seen_p.add(p.name)
1497
+ if dup_p:
1498
+ raise ValueError(
1499
+ f"duplicate provider name(s): {sorted(dup_p)}. Provider names "
1500
+ f"must be unique — a duplicate silently shadows the later "
1501
+ f"entry (provider_by_name returns the first match). Rename or "
1502
+ f"remove the duplicate(s)."
1503
+ )
1504
+
1505
+ seen_f: set[str] = set()
1506
+ dup_f: list[str] = []
1507
+ for prof in self.profiles:
1508
+ if prof.name in seen_f and prof.name not in dup_f:
1509
+ dup_f.append(prof.name)
1510
+ seen_f.add(prof.name)
1511
+ if dup_f:
1512
+ raise ValueError(
1513
+ f"duplicate profile name(s): {sorted(dup_f)}. Profile names "
1514
+ f"must be unique — a duplicate silently shadows the later "
1515
+ f"entry (profile_by_name returns the first match). Rename or "
1516
+ f"remove the duplicate(s)."
1517
+ )
1518
+ return self
1519
+
1520
+ @model_validator(mode="after")
1521
+ def _check_profile_providers_exist(self) -> CodeRouterConfig:
1522
+ """mE: every provider named in a profile chain must be declared.
1523
+
1524
+ Previously a typo in ``profiles[].providers`` was tolerated at load
1525
+ and only surfaced at runtime as a ``skip-unknown-provider`` warning;
1526
+ if *every* entry in a chain was typo'd the profile silently had no
1527
+ usable providers and only failed once fully drained. Rejecting at
1528
+ load — same philosophy as ``_check_default_profile_exists`` and
1529
+ ``_check_mode_alias_targets_exist`` — turns a silent-until-drained
1530
+ misconfig into a startup error naming the profile and the bad
1531
+ provider(s).
1532
+ """
1533
+ names = {p.name for p in self.providers}
1534
+ errors: list[str] = []
1535
+ for prof in self.profiles:
1536
+ missing = [name for name in prof.providers if name not in names]
1537
+ if missing:
1538
+ errors.append(f"{prof.name!r} -> {missing}")
1539
+ if errors:
1540
+ raise ValueError(
1541
+ f"profile(s) reference undeclared provider(s): "
1542
+ f"{'; '.join(errors)}. known providers={sorted(names)}. "
1543
+ f"Fix the typo in profiles[].providers or add the missing "
1544
+ f"provider(s)."
1545
+ )
1546
+ return self
1547
+
1394
1548
  def provider_by_name(self, name: str) -> ProviderConfig:
1395
1549
  """Look up a provider config by name. Raises KeyError if not found."""
1396
1550
  for p in self.providers:
@@ -339,33 +339,128 @@ def _compute_preserve_set(
339
339
  return preserved
340
340
 
341
341
 
342
+ def _group_removable_units(
343
+ messages: list[Any],
344
+ removable: list[int],
345
+ ) -> list[list[int]]:
346
+ """Group removable message indices into atomic tool-pair units.
347
+
348
+ ``removable`` is the sorted list of indices eligible for removal
349
+ (i.e. not in the preserve set). A tool_use assistant message and the
350
+ user message carrying its matching tool_result must be removed
351
+ together so we never leave an orphaned tool_use or tool_result in the
352
+ trimmed history (Anthropic rejects both with a 400). Because the
353
+ preserve-set computation already keeps pairs atomic, both halves of a
354
+ pair are always either both preserved or both removable — here we just
355
+ coalesce the removable halves into a single unit so the incremental
356
+ loop drops them in one step.
357
+
358
+ Returns a list of units (each a sorted list of indices), ordered by
359
+ the position of the unit's earliest message so the caller can peel
360
+ them off the front oldest-first.
361
+ """
362
+ removable_set = set(removable)
363
+
364
+ # Map every tool_use_id to the indices of the message(s) that emit the
365
+ # tool_use and the message that carries the matching tool_result.
366
+ partner: dict[int, set[int]] = {idx: set() for idx in removable}
367
+ use_index: dict[str, int] = {}
368
+ result_index: dict[str, int] = {}
369
+ for idx in removable:
370
+ for tid in _extract_tool_use_ids(messages[idx]):
371
+ use_index[tid] = idx
372
+ for tid in _extract_tool_result_ids(messages[idx]):
373
+ result_index[tid] = idx
374
+ for tid, use_idx in use_index.items():
375
+ res_idx = result_index.get(tid)
376
+ if res_idx is not None and res_idx in removable_set:
377
+ partner[use_idx].add(res_idx)
378
+ partner[res_idx].add(use_idx)
379
+
380
+ # Union-find style grouping over the partner graph.
381
+ seen: set[int] = set()
382
+ units: list[list[int]] = []
383
+ for idx in removable:
384
+ if idx in seen:
385
+ continue
386
+ stack = [idx]
387
+ group: set[int] = set()
388
+ while stack:
389
+ cur = stack.pop()
390
+ if cur in group:
391
+ continue
392
+ group.add(cur)
393
+ seen.add(cur)
394
+ stack.extend(p for p in partner[cur] if p not in group)
395
+ units.append(sorted(group))
396
+
397
+ units.sort(key=lambda unit: unit[0])
398
+ return units
399
+
400
+
401
+ def _normalize_head(messages: list[Any]) -> list[Any]:
402
+ """Drop leading messages until the first is a clean ``user`` message.
403
+
404
+ Anthropic requires the first message to be a ``user`` message, and a
405
+ leading user message must not open with a dangling ``tool_result``
406
+ (its ``tool_use`` was trimmed away). We therefore drop from the front
407
+ any assistant message and any user message that contains a
408
+ tool_result, stopping at the first ``user`` message with no
409
+ tool_result block.
410
+ """
411
+ start = 0
412
+ n = len(messages)
413
+ while start < n:
414
+ msg = messages[start]
415
+ role = msg.role if hasattr(msg, "role") else (
416
+ msg.get("role") if isinstance(msg, dict) else None
417
+ )
418
+ if role == "user" and not _has_tool_result(msg):
419
+ break
420
+ start += 1
421
+ return messages[start:]
422
+
423
+
342
424
  def _do_trim(
343
425
  messages: list[Any],
344
426
  system: Any,
345
427
  target_tokens: int,
346
428
  preserve_last_n: int,
347
429
  ) -> list[Any]:
348
- """Core trim loop. Reduces preserve_last_n if needed (floor: 2)."""
349
- current_preserve = preserve_last_n
350
-
351
- while current_preserve >= 2:
352
- preserved_indices = _compute_preserve_set(messages, current_preserve)
353
- # Keep only preserved messages (maintain order)
354
- trimmed = [messages[i] for i in sorted(preserved_indices)]
355
-
356
- estimated = estimate_tokens_from_anthropic_request(
357
- system=system,
358
- messages=trimmed,
359
- )
430
+ """Incrementally drop oldest messages until under ``target_tokens``.
431
+
432
+ Unlike the previous implementation (which deleted every non-preserved
433
+ message in one shot the moment the threshold was crossed), this peels
434
+ messages off the front one atomic unit at a time and re-estimates
435
+ after each removal, stopping as soon as the estimate is at or below
436
+ the target. The preserve set (last N messages + their tool pairs) is a
437
+ hard floor that is never removed. After trimming, the head is
438
+ normalized so the first surviving message is a ``user`` message
439
+ without a leading ``tool_result`` (avoids upstream 400s). Bug H5.
440
+ """
441
+ if not messages:
442
+ return messages
443
+
444
+ already = estimate_tokens_from_anthropic_request(system=system, messages=messages)
445
+ if already <= target_tokens:
446
+ # Nothing to do — return the input unchanged.
447
+ return messages
448
+
449
+ preserved_indices = _compute_preserve_set(messages, preserve_last_n)
450
+ removable = [i for i in range(len(messages)) if i not in preserved_indices]
451
+ units = _group_removable_units(messages, removable)
452
+
453
+ # Indices we have decided to drop; peel atomic units from the front.
454
+ dropped: set[int] = set()
455
+ for unit in units:
456
+ kept = [messages[i] for i in range(len(messages)) if i not in dropped]
457
+ estimated = estimate_tokens_from_anthropic_request(system=system, messages=kept)
360
458
  if estimated <= target_tokens:
361
- return trimmed
362
-
363
- # Still over target — reduce preserve count and retry
364
- current_preserve -= 1
459
+ break
460
+ dropped.update(unit)
365
461
 
366
- # Floor reached return with minimum preservation (last 2)
367
- preserved_indices = _compute_preserve_set(messages, 2)
368
- return [messages[i] for i in sorted(preserved_indices)]
462
+ trimmed = [messages[i] for i in range(len(messages)) if i not in dropped]
463
+ return _normalize_head(trimmed)
369
464
 
370
465
 
371
466
  __all__ = [