feat(ENG-3500): bring-your-own-LLM Tier 3 and policy options
What
ENG-3500 phase 2. This ports TS 0.9.1 (ENG-3495 BYO-LLM Tier 3) and the rest of TS 0.9.2. After it, Python matches the TS package on every shared conformance case.
Providers
create_llm_tier3_provider(complete=...)wraps any LLM call; you writecomplete, and defender handles the rest:- Prompt:
DEFAULT_TIER3_PROMPT(version"1"), byte-identical to TS. Untrusted text sits between random-id markers, and<<<look-alikes are neutralized. - Parsing: the reply must be exactly one JSON verdict. Duplicate keys and
NaNare rejected. - Refusals: a refusal, a content-filter hit or an unusable reply blocks (
refused=True). - Custom prompts: a
Tier3PromptTemplateis validated when the provider is created; a builder function also works.
- Prompt:
create_openai_compatible_tier3_provider(...)useshttpxthrough the new[llm]extra:- Transport safety: https only (plain http is allowed for loopback), credentials in the URL are rejected, and redirects are never followed.
- Retries: on 429, 5xx and network errors, only while the deadline allows.
- Errors: network error text is reduced to the error type, so no URL or key leaks into it.
- Reply handling: a leading
<think>block is stripped. Refusals,content_filter,lengthand emptychoicesall block.
Policy options (tier3={...})
allow_override, on_error, decide, timeout_ms, max_concurrency, stop_on_first_block, on_event, include_raw. They behave the same as TS. The Python-specific parts:
- Cancellation: cancelling the awaiting task cancels in-flight provider calls and raises
CancelledError. TS reports a "cancelled by caller" failure instead. - Timeouts:
timeout_mscancels an async provider at the deadline. A sync provider can't be interrupted, and the README says so. - Deadline unit:
ctx["deadline"]istime.time()seconds. TS uses epoch milliseconds. - Concurrency:
max_concurrencyapplies per event loop, so the sync API, which runs a new loop on each call, keeps working.
Per-call context and result fields
- Per-call context:
defend_tool_result(..., context={"user_goal": ..., "tool_description": ...}), also accepted per item indefend_tool_results.- What the provider gets in
ctx:tool_name(plustoolNamefor 0.8.x providers),mode,chunkanddeadline.
- What the provider gets in
- New fields on
result.tier3:reason,refused,prompt_version,override_applied,override_suppressedanddecided_by. - Redaction: provider error text in
skip_reason,noteand events is redacted. - New types:
Tier3EventandTier3DecisionInput(metadata only, never content).
JS parity helpers
utils/text.py holds JS \s and \p{Cf} (Unicode 16.0, taken from Node), UTF-16 truncation and JS typeof. tier3_input.py now uses these too.
Checks
| Check | Result |
|---|---|
| Conformance | 134/134 pass; the known-failures list is empty (it was 86) |
uv run pytest | 524 passed, ruff check clean |
| Differential fuzz vs TS (bun) | redaction, parser, marker neutralizing, tool-name sanitizing and template validation: 0 mismatches in 9,000 random cases each |
Real LLMs, tier3_only | 18/18 as expected with gpt-6-luna and gemini-3.8-flash (OpenAI-compatible provider) and claude-haiku-5-5 (create_llm_tier3_provider): 2 benign and 4 injection payloads each |
| Real LLM, cascade | ONNX Tier 2 + Claude judge: benign allowed, injection blocked, and the risky-allow_override warning fires |
The real-LLM run found one bug, now fixed with a regression test. httpx's default 5-second timeout cut off slow Gemini replies even with timeout_ms=30000. The default fails open, so those injections would have been allowed. Each request now uses the remaining deadline as its timeout.
Release
Python's release-please treats feat: as a patch, so this would ship as 0.9.1. All of TS 0.9.2 is in it, so I suggest pinning 0.9.2 with a Release-As PR after merge, so both packages carry the same version. That's your call.
š¤ Generated with Claude Code
Summary by cubic
Ports the TypeScript package's BYO-LLM Tier 3 (TS 0.9.1) and the rest of 0.9.2 to Python, so both packages now pass all 134 shared conformance cases (the known-failures list was 86).
Adds create_llm_tier3_provider(complete=...) for wrapping any LLM call and create_openai_compatible_tier3_provider(...) for OpenAI-compatible endpoints over httpx (new [llm] extra). The tier3={...} policy gains allow_override, on_error, decide, timeout_ms, max_concurrency, stop_on_first_block, on_event, and include_raw; result objects gain reason, refused, prompt_version, override_applied, override_suppressed, and decided_by. Provider error text is redacted before it reaches skip_reason, note, and events.
Behavior notes
- Cancelling the awaiting task cancels in-flight provider calls; TS reports a "cancelled by caller" failure instead.
timeout_mscancels async providers at the deadline; sync providers can't be interrupted.max_concurrencyapplies per event loop, so the sync API, which runs a new loop per call, keeps working. A caller cancelled while queued no longer releases a slot it never held.- A fail-open bug was fixed: httpx's default 5-second timeout cut off slow Gemini replies, allowing injections; requests now use the remaining deadline as their timeout.
- A refusal blocks even when the reply has no valid decision, and lone surrogates in
reason/rawbecome U+FFFD. - The OpenAI-compatible provider validates
response_format, retries, URL port, and header values (includingapi_key) at construction, keeps retry backoff inside the deadline, sends a singleAuthorizationheader, and lets httpx use its default proxy and CA settings. - Redaction was hardened: a password containing
@no longer leaks into the URL host, and unquoted or quoted Bearer/Basic values are redacted whole until whitespace, a comma, or the end, including embedded and escaped quotes.
Release
- Python's release-please treats
feat:as a patch, so pin 0.9.2 after merge to keep both packages versioned alike.