Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .agents/skills/verify-proxy-key-transport/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
name: verify-proxy-key-transport
description: Verify per-run proxy credentials through actual loopback HTTP and SSE without external providers or customer data.
---

1. Launch: use an isolated latest-main worktree and its owned locked dev environment
(`uv sync --locked --dev --extra mcp`, reusing the package download store).
The tests own a temporary loopback HTTP server; no application service,
container, database, target or external model is started.
2. Doctor: `python3 tests/ci/verify_proxy_key_transport.py --doctor` asserts that
all three product packages and the interpreter environment belong to this
worktree. Baseline `28b97543` must exist locally for historical checks.
`--types` and `--types-full` reuse the canonical root type configuration.
3. Drive: run the root service-harness inspect, verify and status commands.
The transport gate runs real sync/async HTTP and SSE requests, selected-model
and vendor tool-turn checks, credential-failure refusals and connected suites.
The identical six assertions must fail against immutable old middleware,
loaded in memory without changing the worktree. Historical infrastructure
errors, skips and incomplete regressions return2 rather than qualifying.
4. Evidence: retain source hashes, exact commands, stdout/stderr and actual exit
codes outside the task worktree. This proves local transport behavior, not
external upstream availability or deployment acceptance. The pinned personal
runner rejects existing benchmark submodule directories before execution;
report that limit, preserve the submodules, and run every exact declared
command independently. Manual results are not a successful runner receipt.
Repository protection and exact-head hosted checks remain separate.
5. Cleanup: the fixture closes and joins only its own HTTP server, and the
driver deletes only its temporary JUnit file. No credentials are required.
Preserve evidence and remove the worktree only after actual merge and
clean/pushed/inactive checks.
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,9 @@ Keep Brain local-only with ENTIRE_BRAIN_NO_EGRESS=1. Before opening or updating
a PR, update the single root CHAGELOG.md and link it from the PR description.
Keep checkpoint uploads disabled for public source; do not attach sessions
containing private work.

# Model credential binding

| Invariant | Enforcement |
| --- | --- |
| Binding a per-run proxy key retains the selected model's transport/protocol configuration and never silently dispatches with an environment key on binding failure. | `tests/ci/verify_proxy_key_transport.py`, real loopback HTTP/SSE and sync/async rejection cases; immutable historical middleware must fail all six regression assertions. |
2 changes: 2 additions & 0 deletions CHAGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ Keep proposed and unmerged changes out of released sections.

## [Unreleased]

- Proposed per-run proxy credential correction ([#1211](https://github.com/BitterSecurity/Decepticon/pull/1211)): preserve selected-model streaming, usage, token limits, retry/timeout settings, vendor protocol subclasses and HTTP transports when binding an engagement key. Refuse dispatch if an explicit key cannot be bound instead of silently using the environment account; requests without a per-run key are unchanged. No package version, publication or deployment. [Verification and compatibility](docs/verification/proxy-key-transport-20261120.md).

- Proposed CI verification correction ([#1210](https://github.com/BitterSecurity/Decepticon/pull/1210)): require every declared dependency to succeed or intentionally skip before CI OK passes. Reject abandoned, unknown and missing outcomes while preserving existing scope skips and protections. This corrects a false-positive aggregate after a hosted macOS runner could not be assigned; runner availability and actual hosted CI remain separate. [Verification](docs/verification/ci-required-terminal-results-20261120.md).

- Proposed [PR #1209](https://github.com/BitterSecurity/Decepticon/pull/1209) on the rust-anything streaming text experiment. Recorded parity held for 231 cases, while the Node native binding was slower in the local microbenchmark. See the [measured results](docs/verification/rust-anything-streaming-text-20261120.md).
Expand Down
73 changes: 73 additions & 0 deletions docs/verification/proxy-key-transport-20261120.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Per-run proxy credentials preserve selected-model behavior

## Problem and change

Rebuilding a selected model as a plain `ChatOpenAI` silently reset streaming,
streaming usage, token limits and selected timeout/retry settings. It also
discarded vendor protocol subclasses and custom HTTP transports. In a shared
server, a credential-binding error continued with the original environment
credential instead of rejecting the request.

Revalidate the selected concrete model with its original configuration and
fresh OpenAI clients. Preserve serialization-excluded configuration such as
HTTP pools, callbacks and the streaming chunk timeout. Keep the configured
proxy destination; remove a default Authorization override and update an
existing LiteLLM authentication header. Preserve provider BYOK and tracing
headers. The established temperature compatibility rule remains in place.

An explicit per-run credential that cannot be bound now refuses dispatch in
both sync and async middleware. The generic error/log does not contain the
underlying exception or credential. Requests without a per-run credential keep
their existing single-tenant behavior. This failure behavior is intentional:
multi-tenant callers must fix their credential configuration rather than
silently charge the environment account.

## Local evidence

Baseline: immutable main `28b97543aba2e80761564fdf85e8c4ba4d9f5738`.
The final verification uses an owned environment installed with
`uv sync --locked --dev --extra mcp`, reusing the download store. The driver
asserts environment ownership and all three product imports resolve to this
worktree. A shared environment was first used for compatibility measurements;
its dependency drift and foreign editable analyzer paths were identified and
those results are not the locked-environment acceptance evidence.

| Check | Actual result |
| --- | --- |
| New transport assertions against original middleware | All6 fail;0 errors/skips |
| Transport and original proxy middleware cases |16 passed |
| Connected factory, model-selection and proxy suites |902 passed;0 skips |
| Full repository Ruff |Passed |
| Full repository format check |943 files formatted |
| Changed Python files, errors-only type check |0 errors |
| Full canonical root type check, locked environment |893 files;0 errors;953 existing warnings |
| Existing CI aggregate behavior |22 real Bash fixtures pass; historical regression exits1 |

`python3 tests/ci/verify_proxy_key_transport.py --doctor` checks import ownership.
`python3 tests/ci/verify_proxy_key_transport.py` drives the connected suite.
`python3 tests/ci/verify_proxy_key_transport.py --historical` reads the immutable
old middleware into memory and must exit1 with exactly six assertion failures.
Setup, collection, skips and incomplete historical runs do not qualify.

The HTTP fixture runs real `invoke` and `ainvoke` requests against a disposable
loopback server, including SSE aggregation, token callbacks and usage. It checks
wire credentials, streaming mode, token limits, sampling, subclass behavior,
fresh client construction, custom HTTP pool identity and original-model
immutability. Two vendor tool-bound turns retain opaque synthetic protocol
blocks. Binding-failure tests assert no handler dispatch and capture the actual
logger's output. No model provider, database, remote target or real credential
is used by these tests.

## Verification limits

The pinned personal `service-harness` runner rejects the repository's existing
benchmark submodule directories before gates execute: `Submodules need an
explicit verification contract: benchmark/MHBench`. Inspect/verify exit2 and
status has no receipt. No submodule, runner, trust configuration or repository
protection was changed to work around it. All seven declared gates and their
two historical regressions were run directly with their exact argv; direct
results are not a successful personal-harness receipt.

These tests establish local HTTP/protocol behavior. They do not establish
external provider availability, end-to-end deployment acceptance, package
publication or a production rollout. No version is bumped by this change.
71 changes: 42 additions & 29 deletions packages/decepticon/decepticon/middleware/proxy_key_override.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,32 +101,37 @@ def _read_proxy_key(request: Any) -> str:


def _rekey_model(original: BaseChatModel, api_key: str) -> BaseChatModel:
"""Rebuild ``original`` against the LiteLLM proxy, authenticating with
``api_key`` instead of the env master key.
Rebuild rather than ``model_copy`` because the OpenAI client binds the API
key at ``__init__`` — a shallow copy would keep the old client (old key).
Model id, base url, timeout, retries, and the temperature gate mirror the
baked-in primary (same as ``model_override._build_proxied_llm``) so
streaming / tool calling / fallback semantics are unchanged; only the
Authorization key differs.
"""Bind fresh proxy clients while retaining the selected model's protocol.
The OpenAI clients capture credentials at construction, so a shallow model
copy would retain the previous key. Revalidate the original concrete class
with all its configuration, including fields excluded from serialization
(custom HTTP transports, callbacks and streaming timeouts). Only the bound
OpenAI clients must be recreated. Never send a virtual key to an arbitrary
model URL: the destination remains the configured proxy.
"""
if not isinstance(original, ChatOpenAI):
raise TypeError("per-run proxy credentials require an OpenAI-compatible proxy model")
proxy = LLMFactory._resolve_proxy_config()
model_id = getattr(original, "model_name", None) or getattr(original, "model", None)
if not model_id:
raise ValueError("cannot resolve model id from current model for re-key")
kwargs: dict[str, Any] = {
"model": model_id,
"base_url": proxy.url,
"api_key": SecretStr(api_key),
"timeout": proxy.timeout,
"max_retries": proxy.max_retries,
bound_clients = {"client", "async_client", "root_client", "root_async_client"}
kwargs = {
name: getattr(original, name)
for name in type(original).model_fields
if name not in bound_clients
}
if not _model_drops_temperature(str(model_id)):
temperature = getattr(original, "temperature", None)
if temperature is not None:
kwargs["temperature"] = temperature
return ChatOpenAI(**kwargs)
kwargs["openai_api_base"] = proxy.url
kwargs["openai_api_key"] = SecretStr(api_key)
# Default headers can override the client's new Authorization header. Keep
# provider BYOK and tracing headers, but replace proxy authentication only.
if original.default_headers is not None:
kwargs["default_headers"] = {
name: api_key if name.lower() == "x-litellm-api-key" else value
for name, value in original.default_headers.items()
if name.lower() != "authorization"
}
if _model_drops_temperature(original.model_name):
kwargs["temperature"] = None
return type(original).model_validate(kwargs)


class ProxyKeyOverrideMiddleware(AgentMiddleware):
Expand All @@ -149,9 +154,13 @@ def wrap_model_call(self, request, handler):
return handler(request)
try:
new_llm = _rekey_model(request.model, key)
except Exception as exc:
log.warning("proxy_key_override failed to bind: %s", exc)
return handler(request)
except Exception:
log.warning(
"proxy_key_override refused dispatch: per-run proxy credential binding failed"
)
raise RuntimeError(
"Failed to bind per-run proxy credential; model dispatch refused"
) from None
log.info("proxy_key_override active (per-run virtual key)")
return handler(request.override(model=new_llm))

Expand All @@ -162,9 +171,13 @@ async def awrap_model_call(self, request, handler):
return await handler(request)
try:
new_llm = _rekey_model(request.model, key)
except Exception as exc:
log.warning("proxy_key_override failed to bind: %s", exc)
return await handler(request)
except Exception:
log.warning(
"proxy_key_override refused dispatch: per-run proxy credential binding failed"
)
raise RuntimeError(
"Failed to bind per-run proxy credential; model dispatch refused"
) from None
log.info("proxy_key_override active (per-run virtual key)")
return await handler(request.override(model=new_llm))

Expand Down
Loading
Loading