Skip to content

feat: serve OSA from the Claude Platform on AWS and retire the OpenRouter platform route - #395

Merged
neuromechanist merged 15 commits into
developfrom
feature/issue-360-epic-anthropic-platform
Sep 17, 2026
Merged

neuromechanist merged 15 commits into
developfrom
feature/issue-360-epic-anthropic-platform

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #360. Also closes #350, #390.

Serves every platform-funded OSA request from the Claude Platform on AWS (the
Anthropic-operated Messages API billed through AWS Marketplace, not Amazon
Bedrock) and retires OpenRouter as a platform route. OpenRouter survives as a
BYOK option only, so a user who brings their own key keeps arbitrary models.

Five phase branches plus six follow-up fixes, each reviewed and merged into this
epic branch on its own PR. Merge this one with a regular merge, not a squash,
so the phase history survives on develop.

What changed

Phase 1, Anthropic LLM service (#361, PR #365)
src/core/services/anthropic_llm.py on langchain-anthropic, with extended
thinking, prompt caching (four breakpoints: system prompt, tools, preloaded
documents, conversation), and a warning when no cache breakpoint lands.
src/core/services/llm.py keeps only the LangFuse configuration.

Phase 2, key and model policy (#362, PR #368)
Two offered models and no others: claude-haiku-4-5 (default, thinking budget
2048) and claude-sonnet-5 (adaptive thinking). Legacy aliases normalize to
those. All eight community configs migrated; bare first-party model ids now pass
config and widget validation, which previously required an OpenRouter
provider/model slash. Cache-read and cache-write tokens are priced separately
(0.1x and 1.25x) from the per-TTL keys langchain-anthropic actually populates.

Phase 3, widget and deployment (#363, PR #381)
Widget model menu, an Anthropic BYOK key field, .env.example and
deploy/docker-compose.yml brought in line, and cross-language drift tests so
the widget's model list and the Cloudflare worker's header allowlist cannot
silently diverge from Python.

Phase 4, inline citations (#364, PR #383) — closes #350
Native Anthropic search_result blocks, so a citation points at the exact span
of the retrieved document that produced the sentence rather than at a URL the
model chose to mention. citations: list[CitationInfo] on AskResponse and
ChatResponse, a citation SSE event arriving at the end of the span it
annotates, and widget rendering. Citability is gated per request on the provider,
so the OpenRouter BYOK path is byte-for-byte unchanged and falls back to a
prompt rule. Discovery-only tools stay uncitable, enforced by a test that reads
each tool's own description rather than a hand-maintained list.

Phase 5, documentation is
OpenScience-Collective/documentation#37 (PR #38 there), not in this diff.

Follow-up fixes on this branch

Issue PR Fix
#384 #385 CLI accepts and saves an Anthropic key at every entry point
#386 #387 FAQ generation runs on the Claude Platform, not OpenRouter
— #388 Cap a FAQ answer's citable text; verify streamed citations live
#390 #391 osa validate tests a community's Anthropic key, not just OpenRouter
— #392 Model-override docs in Claude Platform terms
#393 #394 X-OpenAI-API-Key bypassed server auth but was never used as a key, so the request was served on the platform's key

Two problems found during the epic are filed rather than fixed, both deliberately:
#382 (preloaded documents stay in the system prompt and so cannot be cited,
1 or 2 documents per community against 13 to 46 reachable through the citable
retrieval tool) and #389 (the widget linkifies any bare [n], so a bracketed
number in the model's own prose can collide with a live marker; the fix changes
the marker syntax across the API surface).

Also fixed along the way: escapeHtml in the widget did not escape quotes while
its output was interpolated into href/title/value attributes, reachable in
Phase 4 from cited_text, a verbatim span of a community document. Reproduced in
happy-dom before fixing.

Testing

2158 passed, 20 skipped, 1 failed

The single failure is a known local-only one, test_version_shows_version,
where Rich's ANSI styling breaks a substring assertion; both CI Test jobs pass.
ruff check and ruff format --check clean. Live paid calls against the
platform endpoint exercised thinking, caching, and streamed citations at each
phase, since two payload-shape bugs in this epic were shapes the real API
produces and no hand-built test fixture did.

claude-review fails on this PR as it does on every PR, tracked as #357.

Deploy notes

~/osa/.env on hedtools already carries the six ANTHROPIC_* variables
(appended 2026-09-17, backup at ~/osa/.env.bak-2026-09-17-0337); they are inert
until this image lands. At deploy time, flip DEFAULT_MODEL and TEST_MODEL to
claude-haiku-4-5 and prune the dead pre-migration variables. Deferring the
flip is safe because every community config sets default_model explicitly and
_select_model prefers it.

* feat: add Anthropic Claude Platform LLM service (issue #361 phase 1)

Add src/core/services/anthropic_llm.py: server-mode (AWS Claude Platform)
and BYOK (first-party API) credential handling, per-model thinking policy
for claude-haiku-4-5 and claude-sonnet-5, and a CachingChatAnthropic
subclass that applies prompt-cache breakpoints via ChatAnthropic's
_get_request_payload funnel so caching survives tool binding and
streaming. Does not change request routing or default_model; wiring
this into agents/routers is phase 2.

* feat: add Anthropic Claude Platform settings and model pricing

Add anthropic_base_url, anthropic_workspace_id,
anthropic_thinking_budget_tokens, anthropic_max_output_tokens, and
anthropic_cache_ttl to Settings for the Claude Platform on AWS.
default_model / default_model_provider are unchanged (phase 2 flips
routing). Add first-party pricing entries claude-haiku-4-5 and
claude-sonnet-5 to MODEL_PRICING; existing OpenRouter-format entries
are kept for BYOK requests.

* test: add unit and integration tests for Anthropic LLM service

Unit tests (tests/test_core/test_anthropic_llm.py): normalize_model,
default_thinking, _validate_thinking, create_anthropic_llm credential
and thinking/temperature/caching selection, and CachingChatAnthropic
payload shape (system cache_control, trailing breakpoint, marker count
within Anthropic's limit of 4, caching preserved through bind_tools,
and a plain ChatAnthropic control case with no cache_control). No
mocks: all assertions run against real constructed objects and real
_get_request_payload output.

Integration tests (tests/test_integration/test_anthropic_platform.py):
real calls against the Claude Platform on AWS for Haiku default
thinking (including a tool-call round trip) and Sonnet adaptive
thinking. Skips on missing credentials via Settings rather than
os.getenv, since ANTHROPIC_API_KEY here is only available through
Settings' .env loading and is never exported to the process
environment.

* fix: correct Anthropic caching, thinking, and server-mode config bugs

- Stop mutating caller-owned system message blocks when placing the
  system prompt cache breakpoint; langchain_anthropic reuses the
  caller's own dict objects for list-content system messages, so the
  previous in-place assignment leaked one instance's cache TTL into a
  later request built from the same SystemMessage.
- Make explicit thinking=None actually disable thinking on
  adaptive-default models (claude-sonnet-5) by sending
  {"type": "disabled"} instead of omitting the key, since an omitted
  key defaults to adaptive thinking on that generation. Budget-style
  models keep the existing omit-the-key behavior.
- Raise RuntimeError at construction time when ANTHROPIC_BASE_URL is
  set without ANTHROPIC_WORKSPACE_ID, instead of failing later with an
  opaque 4xx from the AWS endpoint, which requires the
  anthropic-workspace-id header.
- Add module logging: warn when the parent's cache_control kwarg
  silently fails to land on any message block (a permanent, invisible
  caching no-op otherwise), and warn if a system cache breakpoint
  cannot be placed because the last system block is not a dict.
- Validate cache_ttl on CachingChatAnthropic itself via a pydantic
  field validator, so the invariant holds even when the class is
  constructed directly instead of through create_anthropic_llm.
- Include the offending thinking "type" value in the non-adaptive
  validation error message, matching the adaptive branch.
- Document the prompt-cache breakpoint budget (at most 2 markers added
  per call, out of Anthropic's 4-marker limit) on CachingChatAnthropic
  for Phase 2's benefit.

Not run against a live endpoint yet; verified via
tests/test_core/test_anthropic_llm.py in a follow-up commit.

* docs: correct stale and imprecise Anthropic provider comments

- Module docstring: restate the env var requirements precisely now
  that a base URL without a workspace id is rejected at construction
  time; only ANTHROPIC_API_KEY is strictly required.
- Temperature-forwarding comment: attribute the rules correctly.
  claude-sonnet-5 rejects any non-default temperature/top_p/top_k
  unconditionally, independent of thinking state; claude-haiku-4-5
  accepts temperature except while extended thinking is on.
- anthropic_workspace_id field description: it identifies a Claude
  Platform on AWS workspace (format wrkspc_...); AWS Marketplace is
  only the billing channel, not the resource itself.
- Integration test docstring: narrow the claim about the old LiteLLM
  wrapper. Its public invoke()/bind_tools() path would have worked;
  the actual breakage was _generate()/_agenerate() delegating to
  self.llm._generate(), which a RunnableBinding does not expose.

* test: add and fix unit tests for Anthropic caching, thinking, and config fixes

- Replace a tautological base_url assertion with a comparison against a
  real no-argument ChatAnthropic instance.
- Add a source-introspection guard that fails loudly if a
  langchain-anthropic upgrade stops calling _get_request_payload from
  _generate/_stream/_agenerate/_astream, since every caching test here
  calls that method directly and would stay green regardless.
- Cover the list-form system content branch: breakpoint lands on the
  last block only, an already-marked list is not double-marked, and
  the caller's SystemMessage is left unmutated (locks in the fix-1
  mutation bug).
- Add a distinct-value test proving anthropic_thinking_budget_tokens
  is read from settings rather than the module's own default constant
  (both happen to be 2048, which the previous tests never exercised).
- Lock DEFAULT_THINKING_BUDGET_TOKENS and Settings' field default
  together with an explicit equality assertion.
- Exercise the thinking-budget-vs-max_tokens conflict through the
  public create_anthropic_llm() entry point.
- Cover explicit thinking=None on claude-sonnet-5 (must send
  {"type": "disabled"}) and rename the misleading with_thinking_off
  local variable now that "off" for sonnet-5 is an explicit value, not
  an omitted key.
- Cover base_url-without-workspace_id raising RuntimeError, and
  workspace_id-without-base_url still constructing.
- Assert the non-default cache TTL on the trailing message block, not
  only the system block.
- Add direct-construction tests for CachingChatAnthropic's cache_ttl
  field validator (valid and invalid TTLs).

All 56 tests pass; ruff check and format clean.

* test: add live prompt-caching integration test

Add a test that two sequential calls sharing a large, unique system
prefix (repeated text comfortably above Haiku's ~4096-token minimum
cacheable prefix) produce a non-zero cache_read on the second call's
usage_metadata. No unit test can prove caching actually works on the
wire, only that a cache_control marker is present in the outgoing
payload. Verified manually that the test fails (cache_read == 0) when
enable_caching=False, and that the first call's cache_read is 0 with a
fresh unique run marker, so the pass is not vacuous.

* ci: run Anthropic integration tests when credentials are configured

The integration-tests job only checked and exported
OPENROUTER_API_KEY, so tests/test_integration/test_anthropic_platform.py
could never run in CI; it silently skipped every time (Settings finds
no ANTHROPIC_API_KEY). Add a parallel check step for the three
Anthropic env vars with its own has_anthropic_key output and warning,
and a step that runs just the Anthropic integration test module when
that check passes. Existing OpenRouter steps are unchanged.

Secrets (ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL, ANTHROPIC_WORKSPACE_ID)
still need to be added to the repository by the owner; until then this
job continues to warn and skip, same as it does today for OpenRouter.

* fix: target the langchain-anthropic version CI and production install

CI and the deployment image both install with uv pip install --system,
which ignores uv.lock and resolved langchain-anthropic 1.7.2 while the
lockfile pinned 1.3.1. The caching override was therefore written and
verified against a version that never reaches production.

On 1.7.2 the library forwards a top-level cache_control kwarg straight
to the direct Anthropic API, which attaches the breakpoint to the last
cacheable block itself, and only expands the kwarg into block-level
markers for transports that cannot take the parameter. Caching still
works, verified against the live endpoint, but the payload shape differs.

Raise the floor to 1.7.2 so the lockfile matches what is deployed, accept
either breakpoint shape in the no-op warning and in the tests, and count a
top-level parameter as one marker against the Anthropic limit of four.
…ion (#368)

* feat: resolve Anthropic/OpenRouter provider and key per request

Adds ByokCredential/resolve_byok (src/api/security.py) so a caller can bring
an Anthropic or OpenRouter key, preferring Anthropic when both headers are
sent. Replaces _select_api_key with _resolve_provider/ProviderChoice in the
community router: BYOK wins, then a community-funded key (Anthropic env var
checked before OpenRouter's), then the platform key, preferring the Claude
Platform on AWS over OpenRouter. _select_model becomes provider-aware: the
Anthropic path normalizes any requested/default model against the two
offered Claude models and returns 400 (naming them) for anything else;
the OpenRouter path keeps its existing BYOK-gated custom-model behavior,
with a fallback to OpenRouter's own default when a resolved default_model
is a bare first-party id (no longer a valid OpenRouter slug post-migration).
create_community_assistant now builds the model via create_anthropic_llm or
create_openrouter_llm depending on the resolved provider; the ask/chat
endpoints and their streaming helpers accept the new X-Anthropic-API-Key
header alongside X-OpenRouter-Key.

Also lands the content-shape fix this phase depends on: langchain-anthropic
returns a list of typed content blocks (not a plain string) whenever
thinking is enabled or tools are bound. src/agents/content.py adds
extract_text/classify_content_blocks; _extract_agent_result and both
streaming on_chat_model_stream handlers use them instead of str(content) /
`+=`, which previously stringified the block list into answers or raised
TypeError. Thinking blocks now emit a content-free `thinking` SSE event
(a liveness signal only) instead of leaking reasoning or crashing the
stream. The streaming token-usage extraction also now carries the
cache_read/cache_creation breakdown through for cache-aware cost (next
commit).

Deletes src/api/routers/chat.py: verified unimported, unregistered in
main.py, and uncovered by any test, so it carried the same content-shape
bug as genuinely dead code.

Tested manually end to end against the real Claude Platform on AWS via
/hed/ask (non-streaming and streaming): clean answers, no stringified
block-list artifacts, and `thinking` events carrying no reasoning text.

* feat: default communities and platform to the Claude Platform on AWS

Every src/assistants/*/config.yaml now sets default_model to the
first-party claude-haiku-4-5 id and drops default_model_provider (an
OpenRouter-only routing hint no longer applicable); metabci moves off
deepseek/deepseek-v3.2. src/api/config.py's default_model/test_model follow
the same default, with default_model_provider/test_model_provider now
documented as OpenRouter-BYOK-only.

CommunityConfig gains anthropic_api_key_env_var (ANTHROPIC_API_KEY_* only,
same validation style as openrouter_api_key_env_var) so a community can
fund its own Anthropic usage; the OpenRouter field keeps working for
communities that still fund themselves that way.
_MODEL_ID_PATTERN now accepts a bare first-party id (no provider prefix)
alongside the existing provider/model-name form.
validate_expensive_model_without_byok's BYOK bypass now also checks
anthropic_api_key_env_var, and its guidance mentions the Anthropic offering
as a cost-capped alternative to OpenRouter BYOK.

* feat: price prompt-cache reads and writes separately in cost estimates

extract_token_usage now returns a TokenUsage namedtuple that also carries
cache_read_tokens/cache_creation_tokens, summed from each AIMessage's
usage_metadata["input_token_details"] (langchain-anthropic's input_tokens
already includes both, so this only breaks out the existing total, it
does not change it). estimate_cost gains matching cache_read_tokens/
cache_creation_tokens parameters (default 0, so existing callers are
unaffected): ordinary input prices at 1x, a cache write at 1.25x, and a
cache read at 0.1x, mirroring Anthropic's own cache economics. The
community router's callers (src/api/routers/community.py, updated in the
prior commit) already carry the cache breakdown through from both the
non-streaming and streaming paths.

* feat: send Anthropic BYOK header from the CLI when configured

OSAClient sends X-Anthropic-API-Key (preferred) or X-OpenRouter-Key,
matching the server's own resolve_byok preference. Adds
get_effective_anthropic_key() (ANTHROPIC_API_KEY env > credentials.yaml,
which already had the field) alongside the existing OpenRouter-only
get_effective_config(), left unchanged so its behavior and tests keep
working. The ask/chat commands resolve both keys and pass whichever are
set; _check_api_key now accepts either.

* test: cover provider resolution, content shape, and cache-aware cost

test_authorization.py is reworked around _resolve_provider/ProviderChoice
and the provider-aware _select_model: each BYOK header alone, both
together (Anthropic wins), community key (Anthropic env var checked
before OpenRouter's), platform key (Anthropic preferred over OpenRouter),
unauthorized origin, and nothing configured; an unoffered model on a
platform key returns 400 naming the offered models, the same model with
OpenRouter BYOK is allowed, a legacy anthropic/claude-haiku-4.5 default
still resolves, and a bare default_model on the OpenRouter path falls
back to OpenRouter's own default instead of forwarding an invalid slug.
test_community_router.py and test_cost_protection.py needed no changes
(neither depends on OpenRouter-specific shapes). test_community.py adds
coverage for anthropic_api_key_env_var and the relaxed model-id pattern.

Adds tests/test_agents/test_content.py for extract_text/
classify_content_blocks: a list of thinking and text blocks yields only
the text, a thinking block classifies as a content-free signal, and a
plain string still works untouched.

test_db.py and test_cost.py cover the cache-aware token/cost plumbing:
extract_token_usage's cache_read/cache_creation breakdown, and
estimate_cost pricing identical token counts cheaper when mostly a cache
read than when all fresh (and more expensive when writing a cache entry).

test_client.py/test_config.py cover the CLI's Anthropic-preferred BYOK
header and get_effective_anthropic_key.

Adds tests/test_integration/test_anthropic_router.py (llm + integration,
skipped when Settings().anthropic_api_key is falsy): a real /hed/ask
request, non-streaming and streamed, against the live Claude Platform on
AWS, asserting a real answer with no stringified block-list artifacts and
that `thinking` SSE events never carry reasoning text.

* fix: keep the model the same when an OpenRouter key funds the request

A bare first-party default such as claude-haiku-4-5 is not a valid
OpenRouter slug, so an OpenRouter-funded request with no explicit model
had nothing routable to use. Falling back to the factory default meant
such a request silently answered with a different model family than the
community configured, decided only by which key paid for it. The four
communities that fund themselves through openrouter_api_key_env_var
would have had their implicit default become a non-Claude model.

OpenRouter serves the same Claude models under creator/model slugs, so
map across instead: claude-haiku-4-5 resolves to
anthropic/claude-haiku-4.5, and a caller may also name an offered model
by its first-party id. A default that is neither an offered model nor an
OpenRouter slug still falls back, but now logs an error rather than
substituting silently. A test asserts the mapping stays in step with
OFFERED_MODELS so adding a model cannot skip it.

* fix: price prompt-cache writes correctly and surface extraction failures

langchain-anthropic zeroes input_token_details["cache_creation"] whenever
Anthropic's per-TTL breakdown is present (the normal shape once a
cache_control marker is sent, which CachingChatAnthropic always does) and
moves the real count under ephemeral_5m_input_tokens/ephemeral_1h_input_tokens.
Both extractors read the generic key only, so cache writes read as 0 and
were priced at 1x instead of 1.25x. Add a shared
resolve_cache_creation_tokens() helper in src/metrics/db.py that mirrors
langchain's own precedence (TTL-specific sum first, generic key as
fallback) and use it from both extract_token_usage (src/metrics/db.py) and
_extract_token_usage (src/api/routers/community.py).

Also raise _extract_token_usage's catch-all from DEBUG to WARNING: this
repo's default level is INFO, so a genuine extraction bug was silently
showing up as a free request on the dashboard instead of a visible log
line. Still swallows and returns zeros so a stream is never broken by a
metrics problem.

* fix: keep legacy model aliases on their own family over OpenRouter

to_openrouter_model() only recognizes the two canonical first-party ids,
so the bare legacy aliases in MODEL_ALIASES (claude-haiku-4.5,
claude-sonnet-4.5) returned None and fell through to the OpenRouter
emergency default -- the exact model-family substitution the previous
commit set out to eliminate. _select_model now canonicalizes through
normalize_model() before mapping to an OpenRouter slug (via a small
_to_openrouter_model_via_canonical() helper), falling back to the raw
value only when normalize_model() raises.

Also:
- Add anthropic/claude-sonnet-5 to MODEL_PRICING (src/metrics/cost.py) at
  the same rate as the first-party claude-sonnet-5 entry: a community
  whose default resolves to that OpenRouter slug was otherwise blocked
  with a 403 as "not in the approved pricing list".
- Name the community in _select_model's unmappable-default log line
  (message and extra={"community_id": ...}), matching _resolve_provider's
  existing pattern, so a misconfigured default is actionable from logs.
- Note in a comment that the cache multipliers are Anthropic-derived, so
  applying them to an OpenRouter-reported cache read is an approximation.

* feat: surface model substitution and silent-fallback signals

- _platform_choice logs a warning when it falls through to the OpenRouter
  platform key, naming the fact that ANTHROPIC_API_KEY is unset and
  requests are therefore not running on the Claude Platform on AWS. A
  dedicated platform_provider setting was considered and rejected: it
  would reintroduce the configuration ambiguity this epic is removing, so
  inferring from key presence plus a loud warning is enough for now.
- classify_content_blocks logs a warning (deduped per call) for any
  content block type it does not recognize, instead of silently dropping
  it. A future block type that carries answer text would otherwise
  truncate answers with no error -- the same invisible-failure class the
  caching layer already guards against.
- anthropic_api_key_env_var and openrouter_api_key_env_var log a warning
  when coercing a present-but-blank value to None, so a broken template
  substitution is as visible as a wrong env var name already is.
- Add a `model: str` field to AskResponse and ChatResponse, and include
  the resolved model in the streaming `done` event, so callers can see
  which model actually answered instead of only server logs.

* refactor: delete dead pre-Phase-2 BYOK credential resolution

BYOKHeaders, get_byok_headers, GetBYOK, and get_llm_api_key have zero
callers in src/ now that chat.py is gone (verified with a repo-wide
grep). They implement the weaker pre-Phase-2 key resolution with no
origin check or community scoping (see resolve_byok/_resolve_provider in
src/api/routers/community.py for the current logic), so leaving them
around invites a future route to copy the weaker pattern. Remove them
and their tests.

* build: add respx as a dev dependency for HTTP-boundary tests

Needed for the new BYOK/CLI regression tests (items 16-17): the CLI
client and the FastAPI BYOK path both build their own httpx.Client
internally with no transport injection point, so the existing
httpx.MockTransport pattern (used elsewhere in this repo) cannot reach
them. respx patches httpx at the transport level app-wide instead.

* test: cover cache-write fixture shape, alias/pricing drift, and HTTP BYOK

- Real-shape cache regression (item 12, the important one): build
  usage_metadata through the real langchain_anthropic._create_usage_metadata
  against a real anthropic.types.usage.Usage/CacheCreation, for both
  extract_token_usage and _extract_token_usage. The hand-built
  {"cache_read": N, "cache_creation": M} shape the existing tests use is
  not what the real API produces once caching is active, which is why the
  mispricing bug went unnoticed.
- Provider dispatch: create_community_assistant with a ByokCredential for
  each provider, asserting the constructed model type (CachingChatAnthropic
  vs CachingLLMWrapper).
- Drift tests alongside test_every_offered_model_has_an_openrouter_slug:
  every OFFERED_MODELS key and every OPENROUTER_MODEL_IDS value must be in
  MODEL_PRICING.
- Alias mapping: every MODEL_ALIASES entry resolves to a valid OpenRouter
  slug through the canonicalize-then-map path, plus _select_model cases
  for a legacy alias on the OpenRouter path (both as a community default
  and as a requested model).
- HTTP-level BYOK (tests/test_api/test_byok_http.py): TestClient requests
  carrying X-Anthropic-API-Key to /ask and /chat from an unauthorized
  origin, asserting no 403, with a control test proving the same origin
  without BYOK really is rejected. respx mocks the Anthropic Messages API
  boundary so the full router/authorization/agent-loop path runs for real
  without leaving the process.
- CLI: a user with only ANTHROPIC_API_KEY configured does not take the
  "No API key" path, and the outgoing request carries X-Anthropic-API-Key
  (respx-mocked HTTP boundary).
- Pin CACHE_WRITE_MULTIPLIER == 1.25 and CACHE_READ_MULTIPLIER == 0.1 as
  external business facts.
- classify_content_blocks: unrecognized-type warning (once per call, and
  never for tool_use), plus a {"type": "text"} block with no "text" key.
- Rename test_authorization.py's TestIntegration (misleading name for
  unit-level, non-HTTP tests) and soften test_anthropic_router.py's module
  docstring, which claimed to prove reasoning never leaks: it greps for
  dict-repr artifacts, so it cannot catch a classification swap that
  streams reasoning as ordinary text; the unit tests in
  tests/test_agents/test_content.py cover that classification.
- Note on test_slugs_are_openrouter_shaped that it checks shape only; a
  wrong-but-well-formed slug would only surface as a live 400 from
  OpenRouter, since nothing here makes a real OpenRouter call.

* refactor: reduce the legacy LLM service to its observability role

src/core/services/llm.py carried a third model-construction path with its
own direct OpenAI, direct Anthropic, and OpenRouter factories. Nothing in
production called it: create_community_assistant uses only
get_config_with_tracing, for LangFuse. Its model tables had already drifted
out of step with the offered models, so CI failed once the platform default
became claude-haiku-4-5, an id those tables do not know.

Teaching a dead path the new ids would have kept a contradictory third
route alive, so remove the construction surface instead and keep the
tracing helper that production actually uses. Model construction stays in
anthropic_llm for platform traffic and litellm_llm for bring-your-own-key
OpenRouter traffic.

The tests for the removed surface go with it; the LangFuse and singleton
tests are unchanged.
…381)

* feat(api): expose offered models on the community config endpoint

Add OfferedModelResponse and an offered_models field to
CommunityConfigResponse, populated from OFFERED_MODELS in
anthropic_llm.py, so the widget can build its model menu from the
backend's real offer list instead of a hand-maintained copy. Drop the
"(default)" suffix from the Haiku label: which model is default is
already carried by default_model in the same response, and baking it
into the label creates a second source of truth.

Add a drift test asserting offered_models matches OFFERED_MODELS, each
id resolves through normalize_model, and default_model is one of the
offered ids; and a test guarding the labels against policy words
creeping back in.

* feat(widget): offer only the platform Claude models and accept either BYOK key

Model menu: DEFAULT_MODELS becomes a two-entry fallback (claude-haiku-4-5,
claude-sonnet-5) used only until fetchCommunityConfig's offered_models
response arrives; the live list now drives the settings dropdown and
getModelLabel. The saved-settings and custom-model regexes, which
rejected every first-party id the backend now returns, are replaced by
a shared isValidModelId() that accepts both a bare first-party id and
the legacy provider/model form. The custom-model field label now says
it needs a caller's own OpenRouter key, matching what the backend
enforces.

BYOK key: userSettings gains keyProvider, derived from the key's own
prefix (sk-ant- -> anthropic, sk-or-v1- -> openrouter) rather than
stored as a separate choice, so settings saved before this change keep
working without re-entering a key. Validation on load and save accepts
either key shape. The request now sends X-Anthropic-API-Key or
X-OpenRouter-Key depending on which key was entered.

* feat(widget): show a quiet thinking indicator while the model reasons

The backend already emits a thinking SSE event carrying no reasoning
text. The widget used to log it as an unknown event; it now sets an
isThinking flag while the model is reasoning, before the first content
chunk arrives, and reuses the existing loading label (no new UI) to
show "Thinking..." instead of the community title. The flag is cleared
on the first content chunk and at the end of every send, and scoped to
before the first content chunk on purpose so a thinking event arriving
between tool calls mid-answer cannot make the label flicker under
already-rendered text. Reasoning text itself is never rendered.

* feat(worker): allow and forward the Anthropic BYOK header

Add X-Anthropic-API-Key to the CORS allow-list, the forwarded BYOK
header set, and the Turnstile-bypass check, so an Anthropic BYOK key
can reach the backend from a browser: previously the preflight
rejected it, the header was never forwarded even if it passed, and a
caller providing only that key was still forced through Turnstile.

Drop X-OpenRouter-Model, X-OpenRouter-Provider, and
X-OpenRouter-Temperature from the allow-list and forwarding list.
Phase 2 deleted the backend extractor that read them, so the backend
has ignored them for a while now. Update the README's architecture
diagram and BYOK section to document both key types.

* chore(config): drop the unset per-community OpenRouter key vars

Remove openrouter_api_key_env_var from hed, bids, fieldtrip, and
openneuropet's config.yaml. None of the four named env vars is set on
the server, so every request for these communities logged an ERROR in
_resolve_provider and silently fell back to the platform key; if
anyone ever set one, that community would silently leave the Claude
Platform. The schema field stays supported for a community that
genuinely funds itself through OpenRouter.

Add a test asserting no shipped config.yaml sets the field (dynamic
over the registry, not hardcoded ids) alongside one confirming a
synthetic config that does set it still validates. Several existing
dynamic tests that looked for a community with the field configured
now skip gracefully, which is the intended behavior of their existing
pytest.skip fallback.

* chore(deploy): bring env example, compose, and docs in line with the Anthropic platform

.env.example was still documenting the pre-migration world (LLM_PROVIDER,
Ollama, an OpenRouter-format DEFAULT_MODEL, and a long tail of variables
no Settings field, deploy script, or workflow reads any more: ALLOW_BYOK,
DATABASE_URL, ENABLE_TELEMETRY, FEEDBACK_DIR, LOG_LEVEL, GITHUB_REPO,
SYNC_*_CRON, API_HOST/API_PORT/API_WORKERS, EXTRA_CORS_ORIGINS,
ALLOW_LOCALHOST_CORS, LANGFUSE_ENVIRONMENT). Rewrite it around the three
ANTHROPIC_* credentials plus the thinking/output/cache-ttl tuning
variables, DEFAULT_MODEL/TEST_MODEL on claude-haiku-4-5, and HOST/PORT
under the names Settings actually reads, with OpenRouter documented as
the BYOK-only path.

deploy/docker-compose.yml: add the ANTHROPIC_* variables to the
environment block and delete the DEFAULT_MODEL / DEFAULT_MODEL_PROVIDER
lines. Those two were a live bug: the block overrides env_file, and
compose interpolates ${DEFAULT_MODEL} from deploy/.env (which does not
exist), so the stale openai/gpt-oss-120b default always won over
whatever the real .env said. env_file already supplies both from ../.env.

Update deploy/DEPLOYMENT_ARCHITECTURE.md and README.md's docker run
examples and community-key section to lead with the Anthropic platform,
with OpenRouter kept as the BYOK alternative. Update the pyproject.toml
llm marker description, which still named OPENROUTER_API_KEY_FOR_TESTING
as the credential every llm-marked test needs; most of them exercise the
Anthropic path now.

Add tests/test_deploy/test_deploy_config.py: parses docker-compose.yml
to assert no DEFAULT_MODEL/DEFAULT_MODEL_PROVIDER leak into the
environment block, and parses .env.example to assert every anthropic_*
Settings field is documented and DEFAULT_MODEL/TEST_MODEL are real
offered model ids (dynamic over Settings.model_fields and OFFERED_MODELS,
not hardcoded).

* build(deploy): install from the lockfile so the image is reproducible

deploy/Dockerfile installed with `uv pip install --system ".[server]"`,
which ignores uv.lock: the image ships whatever PyPI resolves on build
day, which is how Phase 1 shipped a different langchain-anthropic than
it was developed against. Switch to a frozen `uv sync` against the
lockfile instead.

UV_PROJECT_ENVIRONMENT=/usr/local keeps packages where the existing
CMD already finds them, and --no-install-project is correct because
the container runs from /app/src on sys.path, never from the installed
distribution. uv.lock is already in the build context since there is
no .dockerignore.

CI keeps `uv pip install --system` for now (resolves forward, the safe
direction); that's a separate follow-up.

* ci: give the integration job the Anthropic credentials

.github/workflows/test.yml ran the whole "integration or llm" suite
with only OPENROUTER_API_KEY in the environment, then ran one
Anthropic-only file in a second step gated on ANTHROPIC_API_KEY. After
the platform migration most of the integration/llm suite targets
Anthropic, so the broad step would fail on main with only an
OpenRouter key. Fold the two steps into one: run the full suite gated
on the Anthropic key being present, with both the Anthropic
credentials and OPENROUTER_API_KEY available in the environment (some
tests still need the OpenRouter key for OpenRouter-specific coverage).

.github/workflows/docker-build.yml's smoke test passed
OPENROUTER_API_KEY=test-key-for-ci to a container that only answers
/health; use ANTHROPIC_API_KEY instead so the smoke test documents
what the image actually expects.

* fix(health): report a community Anthropic key as configured

compute_community_health read only config.openrouter_api_key_env_var,
but _resolve_provider (src/api/routers/community.py) checks the
Anthropic env var first. A community that correctly funds itself with
an Anthropic key was reporting api_key="using_platform",
status="degraded", and a public warning telling its maintainer to
configure a key they had already configured.

Mirror _resolve_provider's precedence exactly: the Anthropic env var
decides configured/missing when set, falling back to the OpenRouter
one, then the platform. Warning wording, status mapping, and the
public-endpoint redaction (env var names never leak into public
warnings) are unchanged; only which field is consulted.

Add regression coverage in tests/test_api/test_health.py: a community
configured with anthropic_api_key_env_var reports configured/healthy
when that env var is set, and missing/error naming that env var when
it is not. Confirmed both new tests fail against the pre-fix
compute_community_health (git stash of the health.py change) before
trusting them.

* test: cover the community key paths without relying on shipped configs

Five tests dynamically searched the registry for a community with
openrouter_api_key_env_var configured; since #363 removed that field
from every shipped config.yaml, they silently skipped instead of
exercising the code path. The field is still supported for a community
that funds its own OpenRouter usage, so the path still needs coverage.

Replace the search with monkeypatch.setattr on a real, registered
CommunityConfig object (the pattern already used for the equivalent
Anthropic-key tests in test_authorization.py), clearing
anthropic_api_key_env_var on the same config so the OpenRouter branch
under test is the one actually reached (both _resolve_provider and
compute_community_health check it first).

- test_authorization.py: _community_with_openrouter_env_var() now
  takes monkeypatch and configures "hed" directly instead of
  searching; both call sites updated.
- test_health.py: converts the two compute_community_health tests from
  bare os.environ manipulation to monkeypatch, alongside the
  anthropic-path tests added in the prior commit.
- test_community_router.py: the public-metrics test builds a fresh
  router via create_community_router("hed") bound to the just-patched
  config, rather than reusing the module-level app fixture. That app's
  community routes close over whatever registry snapshot existed the
  first time src.api.main was imported in the test session; other
  test modules' own discover_assistants() calls run later and replace
  the registry's CommunityConfig objects with new ones carrying the
  same values but a different identity, so a freshly-fetched object
  is not reliably the one an already-built route reads. Building an
  isolated router right after the monkeypatch sidesteps that.

Skip count drops from 18 to 13; none of the remaining skips mention
openrouter_api_key_env_var.

* fix(deploy): stop the compose environment block from blanking env_file values

deploy/docker-compose.yml's environment: block used the
`- FOO=${FOO:-default}` interpolation form for every entry. That form
resolves at compose time from the shell (or deploy/.env, which does
not exist), NOT from env_file, and silently overrides whatever
env_file provides -- verified with `docker compose config`: with
env_file providing REAL_SECRET=value-from-env-file, an environment:
entry of `- REAL_SECRET=${REAL_SECRET:-}` renders as REAL_SECRET: ""
regardless.

This is the same defect the prior commit removed for DEFAULT_MODEL,
just not limited to it: every entry in the block had it, including
API_KEYS, OPENROUTER_API_KEY, OPENAI_API_KEY, the ANTHROPIC_* set,
GITHUB_TOKEN, SEMANTIC_SCHOLAR_API_KEY, PUBMED_API_KEY, and both
LangFuse keys. Anyone following this file's own header instructions
(copy ../.env.example to ../.env, docker-compose up -d) got a
container with every secret blanked and every tuning default pinned,
which sends the platform straight down _platform_choice's OpenRouter
fallback -- the precise failure this epic exists to eliminate.
Production is unaffected because deploy/deploy.sh uses
`docker run --env-file` and never touches compose.

Every variable that was in the block has a genuine default on Settings
(src/api/config.py), so the fix is to delete the block entirely rather
than add more entries to it: env_file already supplies every one of
them, and letting Settings' own defaults apply when a variable is
absent is correct. Replaced with a comment explaining why the block is
empty and what to check before adding an entry back.

Extend tests/test_deploy/test_deploy_config.py with
test_environment_block_never_uses_var_default_interpolation, which
asserts no entry in the environment: block (if any exist at all) uses
the ${VAR:-...} form, checked dynamically over the block's actual
contents rather than a hardcoded list of names. Confirmed it fails
against the pre-fix file before trusting it.

* docs: correct env var names and document the platform credentials

Three documentation fixes in files this phase already touches:

- The widget's custom-model label used an em dash.
- deploy/DEPLOYMENT_ARCHITECTURE.md's docker run and .env examples named
  API_KEY, but the Settings field and env var are API_KEYS (plural,
  comma-separated), so following either example verbatim left the server
  with no configured key.
- deploy/Dockerfile's trailing reference block listed SYNC_GITHUB_CRON and
  SYNC_PAPERS_CRON, which nothing reads, and did not mention the three
  ANTHROPIC_ variables the image now needs to answer a request at all.

* fix(widget): surface init-time settings/history failures on open

loadUserSettings had four failure branches (corrupted JSON, localStorage
access error, invalid saved key, invalid saved model); each either tried
to call showError guarded by "container && isOpen" or only logged to
console. init() calls loadUserSettings/loadHistory before createWidget, so
the container query always returned null and isOpen was still false: none
of the four branches could ever reach the user. A saved BYOK key that
failed validation was dropped with no explanation, and every later request
silently billed the platform key instead.

Queue the failure reason in a module-level pending notice and flush it
through the existing showError presentation the first time the widget is
actually opened (toggleChat and the fullscreen init path), instead of
trying to render at init time. Routes loadHistory's corrupted-history case
through the same mechanism; its return value was already discarded at the
call site, so a load failure was previously invisible.

Also:
- offered_models: warn when a config response omits it (or ships it
  empty) and the widget falls back to DEFAULT_MODELS, matching the
  default_model check just above it, without disabling the widget.
- BYOK header selection: make the anthropic/openrouter branch explicit
  instead of treating "not anthropic" as "openrouter", so an unrecognized
  keyProvider can never send the wrong header; log and drop the key
  instead.

* test: add cross-language drift tests for widget/worker constants

Three constants are hand-duplicated across Python, the widget JS, and the
Cloudflare Worker JS with nothing keeping them in sync: DEFAULT_MODELS vs
OFFERED_MODELS, the widget's BYOK key regexes vs the backend's log
redaction pattern, and the worker's CORS/byokHeaders lists vs the BYOK
headers security.py actually resolves into a credential. Each is correct
today; each can drift silently, and the worker case would only surface as
a real browser's CORS preflight rejecting a request, with every Python
test staying green.

Parses the JS files as text (no JS test harness in this project) and
derives expected values from the real Python source at test time, the
same way tests/test_deploy/test_deploy_config.py parses deployment files.
Verified each test actually fails by perturbing the corresponding JS
constant before trusting it.

* test: fix a precedence test that did not prove its claim, cover two gaps

test_authorized_origin_uses_community_anthropic_key claimed Anthropic wins
over OpenRouter but only ever set the Anthropic field; since hed no longer
ships an openrouter_api_key_env_var, an implementation that checked
OpenRouter first would find it unset, fall through to Anthropic anyway,
and still pass. Set both fields, with OpenRouter pointing at a populated,
distinct env var, so a reversed-precedence implementation actually fails
the assertion (verified by temporarily reversing the precedence check and
confirming the test catches it, then reverting).

compute_community_health had the identical untested precedence gap. Added
a test that leaves the Anthropic env var unset and the OpenRouter one
populated: correct precedence still reports "missing" (it commits to
whichever env var name it selects, regardless of whether that one is
actually set), while a reversed implementation would find OpenRouter's
populated value and incorrectly report "configured". Also verified by
reversing the precedence check and confirming the test fails.

_community_without_configured_keys() searched the registry for a
community with neither key env var configured, and skipped (taking six
tests with it) once every shipped community had one -- an easier way to
lose coverage than the single-community helper beside it. Hardened it the
same way: monkeypatch a real, registered CommunityConfig directly instead
of searching for one that qualifies.

Added a test for get_community_config's platform-default branch
(default_model = settings.default_model when the community config has
none), previously exercised by no test since every shipped community sets
its own default_model.

* fix(deploy): fail hard on a missing .env instead of deploying unconfigured

deploy.sh only set --env-file when deploy/.env existed, with no else: a
missing .env meant the container started with no environment at all,
/health returned healthy regardless (it checks nothing), and the script
printed "Deployment complete!" and exited 0. This is the mechanism
CLAUDE.md documents as the real deploy path, and it now stands between a
deploy and the Anthropic credentials.

auto-update.sh and auto-update-dev.sh run unattended from cron and had the
same shape (a logged warning, then deploy anyway). Made all three fail
loudly and exit non-zero instead: deploy.sh via its existing error_exit,
naming the expected path; the two auto-update scripts to their own log
output, since a cron job's only visibility is its log file.

Verified by running each script with stubbed docker/curl against a
directory with and without .env: all three now exit 1 with a clear
message when it is missing, and behave as before when it is present.
* feat(tools): add the search result block builder

Adds src/tools/citations.py with build_search_result(), matching the
search_result content block schema verified live against the Claude
Platform on AWS (GA, no beta header), plus a shared truncate() helper to
replace the truncation logic the tools currently open-code in several
places.

* feat(tools): return citable search results from knowledge and doc tools

Threads a citations: bool flag through CommunityAssistant,
create_community_assistant, create_knowledge_tools, and the router's
provider resolution, so every citable tool (retrieve_docs,
fetch_current_page, search_papers, search_papers_live, search_code_docs,
get_full_docstring, search_faq, search_forum) returns search_result
blocks instead of formatted strings when the request is running on the
Anthropic path. Discussion search and recent-activity listing stay
string-only, matching their existing "discovery, not answering"
descriptions. Consolidates the open-coded truncation duplicates onto the
new truncate() helper.

* feat(agents): carry citations through content extraction

Extends classify_content_blocks() with a citations field per text block
(ContentBlock, a 3-field named tuple), adds extract_citations() to flatten
them, and adds CitationTracker to assign stable [n] markers per unique
source in first-appearance order, shared logic for both the streaming and
non-streaming response paths.

tests/fixtures/citation_response.json is a recorded real response payload:
one small claude-haiku-4-5 call (via this repo's create_anthropic_llm),
with a tool bound that returns a build_search_result() block, captured to
avoid the Phase 2 bug class where every test hand-built a citation shape
the API never actually produces.

* feat(api): return inline citation markers and citation data

Adds CitationInfo (marker, source, title, cited_text) and a citations
field to AskResponse and ChatResponse. _extract_agent_result now builds
the answer text with inline [n] markers via a new
_build_answer_with_citations, using CitationTracker so numbering matches
the streaming path. Both SSE streaming generators emit a citation event
the first time a source is cited (with its marker text folded into the
content stream at that point) and repeat the full citation list on the
done event. Threads citations=provider_choice.provider == "anthropic"
into registry.create_assistant so the flag follows the already-resolved
per-request provider choice.

* feat(widget): render inline citations

renderInlineMarkdown()/markdownToHtml() take an optional citationsByMarker
lookup and render a bare "[n]" (never a real markdown link) as a
superscript link to its source, with cited_text as the hover title. Each
cited assistant message also gets a compact numbered source list under
the answer. Handles the new "citation" SSE event and the "citations"
field on both the streaming "done" event and the non-streaming /chat
response; markers persist into session history unchanged. Behavior is
identical to today when a message carries no citations (OpenRouter path).

Verified with `node --check`; there is no JS test harness in this
project, so tests/test_frontend/test_widget_citations.py asserts the
invariants by parsing the file, matching test_widget_drift.py's approach.

* feat(prompt): require source links when native citations are unavailable

Adds a fallback prompt rule for the OpenRouter/BYOK path (citations=False,
the default), asking the model to end each claim drawn from a retrieved
source with a markdown link immediately, rather than a links dump at the
end. Folded into the additional_instructions substitution value rather
than a new placeholder, since every community config already includes
{additional_instructions} by convention (a new placeholder would only
reach the default template). Omitted entirely when native citations are
available (citations=True).

* test: cover the citation path end to end

Adds the llm-marked integration test that is the Definition of Done on
issue #364: a real request against the Claude Platform on AWS retrieves
an on-demand HED document via retrieve_hed_docs and returns an answer
whose [1] marker and citation both trace back to that document's own URL.

* fix(tools): cite only the sources the assistant may answer from

A tool is citable if and only if its description permits answering from
its content. search_{id}_papers, search_{id}_papers_live and
search_{id}_forum all carry "This is for DISCOVERY, not answering" / "Do
NOT use ... content to formulate answers" language, the same language
used to justify excluding search_{id}_discussions and list_{id}_recent,
so they were wrongly shipped citable. Reverts all three to their
pre-Phase-4 string-only behavior with no citations parameter at all, and
reverts search_{id}_forum's description to its original wording
unconditionally (no more citations-dependent description).

list_{id}_recent's description carried no discovery-only language at all,
even though it has always been meant as a non-answerable listing tool
(same category as search_{id}_discussions). Added the same "DISCOVERY,
not answering" / "Do NOT use" framing already used by its four siblings,
so the rule below can be checked mechanically rather than by a
hardcoded name list.

Replaces the gating test with one that encodes the rule itself:
TestCitabilityMatchesDescription seeds real rows across every backing
table, builds the full tool set once, and derives each tool's expected
return type from whether its own description contains discovery-only
language, so a new discovery tool added later is covered without a code
change here. TestProviderGating (real per-tool block content checks) and
TestDiscoveryToolsHaveNoCitationCapability (no factory accepts a
`citations` kwarg it can't honor) are kept alongside it; none of the
three overlap.

* fix(widget): escape quotes so a cited span cannot inject an attribute

escapeHtml serialized a text node, which escapes & < > but leaves both
quote characters alone. Its output is interpolated into href, title and
value attributes, so a value carrying a double quote closed the attribute
and everything after it parsed as further attributes. Confirmed in a real
DOM: a cited_text of 'prefix" onmouseover="...' produced an anchor with a
live onmouseover handler.

Citations made this reachable from the least trusted input the widget
renders, since cited_text is a verbatim span of a retrieved community
document, but the same gap applied to every pre-existing attribute site.
Fixed in the shared helper. Escaped quotes still render as quotes, and a
code block still copies real quotes because that path reads textContent.

Tests assert the invariant for every attribute interpolation, not just
this one site, and were confirmed to fail against the previous helper.
* feat(cli): resolve BYOK keys per provider from the key's own prefix

get_effective_anthropic_key() only ever read ANTHROPIC_API_KEY and the
saved Anthropic slot, while get_effective_config() resolved -k/--api-key
into the OpenRouter slot regardless of what the key was. An Anthropic key
typed at the flag therefore went out on X-OpenRouter-Key, where the server
cannot use it.

Replace it with get_effective_byok_keys(), which returns both slots, and
classify_api_key(), which reads the provider off the prefix the way the
widget's inferKeyProvider does. An explicit flag wins outright and clears
the other slot, because OSAClient prefers Anthropic when both are present:
otherwise an exported ANTHROPIC_API_KEY would silently override a typed
OpenRouter key and bill the wrong account. An unrecognized prefix stays
OpenRouter so pre-migration credentials keep working.

get_effective_config() is left alone; it still resolves the API URL and
its single-key return is pinned by existing tests.

Tested: 9 new tests in tests/test_cli/test_config.py, full unit suite.

* feat(cli): accept an Anthropic key in init, config set, ask, chat, mirror

The X-Anthropic-API-Key header was wired end to end in phase 2, but no CLI
entry point could put a key on it: `osa init` prompted for an OpenRouter
key and saved whatever it got into the OpenRouter slot, `config set` had no
--anthropic-key at all, and `osa mirror` refused to run for a user with
only an Anthropic key configured. The only working setup was to hand-edit
credentials.yaml or export ANTHROPIC_API_KEY in every shell.

- init names Anthropic first, prompts for "API key" rather than for one
  provider's key, and routes it by prefix. Its connection test is now gated
  on either slot and passes the Anthropic key through, so the test request
  goes out on the header the server reads.
- config set gains --anthropic-key; the two key flags do not clobber
  each other.
- ask, chat and mirror resolve both slots via get_effective_byok_keys().
- --api-key help text across all commands now names both providers.

Tested: 6 new tests, including one asserting init's own connection test
carries X-Anthropic-API-Key and not X-OpenRouter-Key. Verified against
reverted source: 2 of the 4 init tests fail, so they are load-bearing.
Full unit suite 2021 passed, 1 pre-existing Rich-ANSI failure in
test_version_shows_version that also fails on the epic branch.

* test: cover mirror and chat BYOK routing, name Anthropic in the README

Review findings on PR #385.

tests/test_cli/test_mirror.py did not exist, so mirror's _get_client fix had
no coverage at all. Five tests now assert on the outgoing request rather than
on the client object, because a client built with the right key and the wrong
header name would still pass the weaker check. Includes the OpenRouter path
and the no-key error path, so the two-provider resolution cannot make either
unreachable.

chat resolves its keys independently of ask, so it gets its own header test.
Its response body is serialized from the server's ChatResponse model instead
of hand-written: the first attempt hand-wrote message as a string, but it is
a nested ChatMessage and the CLI reads response["message"]["content"].

Verified all four new Anthropic-path tests fail when the fix is reverted.

README named openrouter.ai as the only place to get a key and showed only
--openrouter-key. Also documents anthropic_api_key_env_var alongside the
OpenRouter one for communities funding their own usage.

classify_api_key's docstring claimed to mirror the widget's inferKeyProvider.
It does not: the widget validates the full key shape by regex and returns
null for anything unrecognized, while the CLI falls back to OpenRouter so
pre-migration configs keep working. The docstring now states the difference
and why.
…tions live (#388)

Review findings on PR #383.

search_faq's citation path sent the stored answer uncapped while its string
path truncated to 500 chars. The other two citable tools pass search snippets
that src/knowledge/search.py has already truncated, but a FAQ answer comes
straight from the database, capped only at ingest (5000 chars). Reproduced:
at the default limit=5, one search carried 25,000 chars on the Anthropic path
against 3,476 on the OpenRouter path for the same query, a cost difference
visible only to whichever provider was paying. Capped at 2000 chars, more
generous than the display truncation because a citation points at an exact
span and a span cut mid-sentence is worse than no citation.

TestCitablePayloadsAreBounded covers per-block and whole-call size in both
modes, plus that an ordinary short answer is left alone. Verified both size
tests fail when the cap is reverted (5000 == 2000 + 3, and 25000 chars).

The streaming citation path had no live verification, unlike the
non-streaming one, so it rested on a hand-built chunk shape: the assumption
that a citation arrives as its own delta on an on_chat_model_stream chunk
rather than only on the final aggregated message. Added an llm-marked test
that drives the router's own SSE generator against the real endpoint and
asserts the accumulated content ends with the [n] marker at the moment each
citation event fires, which is what makes a citation inline rather than a
trailing bundle of links. Ran it: passes. It needs an Origin, taken from
HED's cors_origins rather than hardcoded, because the platform key is only
offered to an authorized origin and the citations flag follows the resolved
provider.

extract_text lost its last production caller when the API switched to
citation-aware assembly. Kept as the text-side counterpart of
extract_citations, with a docstring note saying it has no production caller
and why an answer must not be assembled through it.
…er (#391)

* refactor: move the first-party Anthropic endpoint into a shared module

The CLI's light paths cannot import anthropic_llm: it pulls in
langchain-anthropic from the server extra, and src/cli/main.py downgrades
osa validate to a stub when importing src/cli/validate.py fails. A
dependency-free module lets the validator use the same endpoint constant
the runtime does.

No behavior change.

* fix(cli): validate a community's own Anthropic key, not just OpenRouter

osa validate read only openrouter_api_key_env_var, so a community funding
its own Anthropic usage was told 'Not configured (using platform key)' and
never got the warning that exists to catch surprise platform billing.
Resolve the env var with the same precedence the runtime uses (Anthropic
first, matching _resolve_provider and health.py) and report which provider
owns it.

--test-api-key now tests the key against its own provider: a community
Anthropic key against the first-party /v1/models, because create_anthropic_llm
pins base_url there whenever an explicit key is passed, so that is where the
community's requests go. The flag's help text no longer says OpenRouter.

Tests cover both providers, the precedence between them, and that
src/cli/validate.py still imports with the server extra blocked, which is
what keeps file-mode validation working on a CLI-only install. Verified by
reverting each fix and watching the new tests fail.

Closes #390
…#387)

* feat: run FAQ generation on the Claude Platform instead of OpenRouter

FAQ generation was the last server-side route to OpenRouter. It ran from the
sync scheduler (src/api/scheduler.py:240) with no caller and no BYOK key, so
the platform needed its own OPENROUTER_API_KEY for the feature to work at
all, which contradicted .env.example's claim that OpenRouter is only reached
via a caller's key or a community's openrouter_api_key_env_var.

- faq_summarizer builds both agents with create_anthropic_llm, on the
  configured and the fallback path. Thinking is off for both: scoring needs
  the temperature determinism it would displace, and neither agent needs
  reasoning tokens across thousands of calls.
- eeglab's evaluation agent moves from qwen/qwen3-235b-a22b-2507 on
  DeepInfra/FP8 to claude-haiku-4-5, the cheapest offered model. Its summary
  agent stays on Haiku rather than moving up to Sonnet 5, because Sonnet
  rejects `temperature` and would silently discard the 0.0/0.1 split the two
  roles are built around.
- AgentConfig.provider is now inert. It still loads, so no config.yaml
  breaks, and _warn_if_provider_ignored logs when one is set rather than
  dropping a deliberate cost choice in silence.
- The same-model warning was inverted: with two offered models, Haiku for
  both agents is the cheapest valid setup, so warning on any repeat would
  fire on the recommended config. It now warns only when the evaluation
  agent, the one making thousands of calls, uses the expensive model.
- summary_model_name is normalized before it is stored, so a config still
  carrying a legacy id records the id that was billed and that
  src/metrics/cost.py prices.
- Fixes two stale docstrings that predate the migration: default_model
  ("OpenRouter format", anthropic/claude-3.5-sonnet example) and
  default_model_provider.

Cost note: the evaluation agent moves from a quantized open model to Haiku
at $1.00/$5.00 per 1M tokens, on the thread-scoring calls. Haiku is the
floor among offered models, so there is no cheaper option; the
quality_threshold of 0.7 still keeps ~85% of threads away from the summary
agent.

Tested: 8 new tests. The registry-wide model check fails against the
pre-migration eeglab config (ValueError on the Qwen id), and the repointed
e2e patch target fails if aimed back at create_openrouter_llm, so both are
load-bearing. Full unit suite 2090 passed, 1 pre-existing Rich-ANSI failure.

Closes #386.

* refactor(core): move the model tables to a langchain-free module

The offered models, their aliases, the sampling rule and normalize_model
now live in src/core/services/anthropic_models.py, which imports nothing
third-party. Config validation has to resolve a model id to judge a
community's choice, and it runs on CLI-only installs where langchain (and
therefore anthropic_llm) is not installed.

anthropic_llm re-exports the tables, so the server-side callers that have
always imported them from there keep working; the split is a packaging
detail, not something every router and agent should know about.

Also logs, at debug, when a configured temperature is dropped and which of
the two reasons applied: the model accepts only its default, or extended
thinking is on. It was silently discarded before. Debug rather than
warning because it is on the per-request path.

Tested: new tests for accepts_temperature over every alias and offered
model, that the re-exports are the same objects rather than copies, and
that the drop reason is reported. Full offline suite passes.

* fix(config): judge FAQ agent models by what they resolve to

validate_agent_roles compared agent.model against the literal string
"claude-sonnet-5", so a community that wrote a legacy id such as
anthropic/claude-sonnet-4.5 got no warning while still being billed for
Sonnet on every thread it scored. It now normalizes first, and names both
ids in the message so a maintainer recognizes the config line.

Two checks added alongside it:

- A model that resolves to nothing at all now warns, instead of being
  discovered when FAQ generation fails.
- An explicitly configured temperature on a model that only accepts its
  default now warns that the value is dropped rather than sent. Only an
  explicit temperature counts; the field's own default is not a choice the
  community made. The same is logged once per sync run, next to the
  existing provider-ignored warning, since that is where an operator looks.

All of these warn rather than raise: this schema backs the whole community,
and a questionable FAQ setting should not stop the assistant from serving.

Tested: new tests for the alias case, the unresolvable case, temperature on
and behind aliases of both models, and that the field default stays silent.
Also asserts CommunityConfig still imports with the server extra absent.

* fix(knowledge): price FAQ generation from the shared cost table

faq_summarizer carried its own four rate constants, left at pre-migration
OpenRouter prices (Haiku 0.25/1.25, Sonnet 3.00/15.00) while the platform
now bills 1.00/5.00 and 2.00/10.00. Both the estimate shown before a sync
and the total reported after it were wrong, and the per-thread total was
charged at Sonnet rates no matter which model actually ran.

Now sourced from src/metrics/cost.py, the same table the API and CLI report
from, so there is one place to update when a rate changes. Two accounting
fixes fall out of it:

- The scoring call is counted. It runs on every thread and is most of a
  run's cost, but only summarized threads were being charged for.
- Each call is priced at the model that ran it, tracked through both the
  configured-agent and fallback paths.

Estimates stay approximate in two stated directions: input tokens are
derived from the thread's character count rather than counted, and fixed
prompt overhead is not counted at all. The returned keys are unchanged, so
the sync CLI's cost display keeps working.

Tested: estimates derived from the pricing table rather than restated,
that the two strategies are the models the platform offers, and that a real
summarize_threads run charges for scoring alone and for both calls.
The `model` field on /ask and /chat still advertised "OpenRouter format:
creator/model-name. Requires BYOK." Both halves are now wrong: the ids the
platform accepts are bare first-party ones, and _select_model allows either
offered model from any caller, since the platform runs only those two and
neither can be used to run up an unbounded bill. A caller reading /docs was
being told to bring a key they do not need, in a format that gets a 400.

The description is built from OFFERED_MODELS and shared by both request
bodies, so a third offered model cannot leave it naming two.

Tested: drift tests that it names every offered model, names nothing the
platform does not offer, and is the description both bodies actually use.
X-OpenAI-API-Key bypassed the server API key requirement on every
RequireAuth endpoint, left over from when there was an OpenAI code path.
There is not one now: resolve_byok knows only Anthropic and OpenRouter,
so the header's value was read for the bypass and then dropped, and the
request ran on the community's key or the platform's. Sending the header
with any value at all bought answers on our bill. Confirmed against a
running server before the fix: no key gave 401 and a wrong admin key gave
403, but `X-OpenAI-API-Key: literally-anything` gave 200.

The bypass now accepts exactly the two headers resolve_byok understands,
which is the whole safety argument for having a bypass: the header you
send is the credential your request runs on, so junk fails upstream
against your own provider.

Tested: the OpenAI header alone now gets 401, both real BYOK headers
still bypass, and a signature check pins the set of headers
verify_api_key reads to the set of providers ByokCredential allows, so a
future header cannot bypass without something to resolve it. Both new
assertions were confirmed to fail with the old code in place.
Also drops the header from the BYOK table in deploy/DEPLOYMENT_ARCHITECTURE.md.

Closes #393
@github-actions

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-360-epic-anthr-demo.osc.earth
Branch feature/issue-360-epic-anthropic-platform
Commit 8d97fd2

This preview will be updated automatically when you push new commits.

… error prefix

fetch_page now returns PageFetchResult(success, content), and the citable
fetch_current_page path gates on the flag. It previously checked
content.startswith("Error:"), which the eight failure branches do not
all share, so a failure phrased differently was wrapped in a
search_result block and offered to the model as citable page content.

fetch_page_content stays as a thin string wrapper for the callers that
only ever wanted the content.

Tested: tests/test_agents/test_page_context.py, including respx-driven
coverage of every failure branch and a test that no branch is
recognizable by prefix alone.
RetrievedDoc.success only means no error was raised, so a page that is
all navigation chrome arrives as a success with empty content after
markdown cleaning. build_search_result rejects empty text, and that
ValueError escapes LangGraph's ToolNode into the router, which reads
ValueError as a malformed request and answers the user with a 400. The
citable path now returns the same plain string the OpenRouter path does,
and logs the gap.

Tested: tests/test_tools/test_tool_integration.py with a respx-served
chrome-only page; the pre-fix code raises the ValueError on both new
tests.
Two silent drops on the citable path. A search result with no text is
skipped, since build_search_result rejects empty content, and a citation
with no source is dropped by CitationTracker because no marker can point
anywhere. Either one shrinks the citable corpus for reasons that belong
to the synced data, not to the question, so both now log a warning.

_build_citation_blocks no longer skips a result that has text but no
source: the API accepts an empty source (verified against the live
endpoint), so the only loss is the marker, whereas skipping would hide a
real answer from the model.

Tested: tests/test_tools/test_citation_gating.py with real seeded FAQ
rows missing an answer and missing a thread URL, and
tests/test_agents/test_content.py for the dropped-citation warning.
renderInlineMarkdown took the first /\[(\d+)\]/ match in a text run, so
prose of the model's own ("see item [42]") hid a real marker later in
the same run: the marker rendered as dead text, and when nothing else in
the run matched either, the remainder was emitted unparsed. It now walks
every candidate with matchAll and picks the first one the citation map
knows.

Tested: frontend/test-citation-markers.js, which executes the shipped
widget's own renderInlineMarkdown (10 passed; 3 of them fail against the
pre-fix widget). Not wired into CI, which has no JS runtime, so
tests/test_frontend/test_widget_citations.py pins the exhaustive scan as
a source-level guard.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round on Phase 4, and the four fixes it produced

Phase 4's review had died on a 429 and this roll-up PR had none of its own, so two Sonnet reviewers were run over the Phase 4 diff before merging. Four real findings, fixed here in four commits, each disarm-verified by restoring the bug and confirming the new tests fail:

  • df1c487 Page-fetch failures could become citable content. fetch_page_content signalled failure only through the text it returned, and the citable fetch_current_page path tested startswith("Error:"). The eight failure branches do not share that prefix, so a differently phrased failure was wrapped in a search_result block. fetch_page now returns PageFetchResult(success, content) and the caller gates on the flag.
  • 4b44103 An empty page turned into a 400 for the user. RetrievedDoc.success is error is None, so a page that is all navigation chrome arrives as a success with empty content; build_search_result rejects it, and the ValueError escapes ToolNode into the router, which reads ValueError as a malformed request. The citable path now falls back to the plain string, as OpenRouter's already did.
  • 4d4f0f9 The widget dropped real citation markers. renderInlineMarkdown took the first [n] in a text run, so the model's own "see item [42]" hid a real marker later in the same run, and when nothing else in the run matched, the remainder was emitted unparsed. Now an exhaustive matchAll scan picking the first candidate the citation map knows. frontend/test-citation-markers.js executes the shipped widget: 10 passed, 3 of them failing against the pre-fix file.
  • 905c738 Uncitable results and sourceless citations were dropped silently. Both now log, since either one means the synced data is incomplete. One reviewer suggestion was reversed after checking it: a probe against the live endpoint showed the API accepts an empty source (the request succeeds and the citation returns with source: """"), so skipping such a result would hide a real answer from the model to save a marker it was never going to get. The content is kept and the code records why.

Two findings were filed rather than fixed, both pre-existing and outside the citation paths:

Verification: 2194 passed, 13 skipped, 1 failed locally (the known Rich-ANSI test_version_shows_version), with TestPapersSync deselected for the hang above. ruff clean. Lint, Test (3.11), Test (3.12) and the Docker build all pass here; claude-review fails on every PR (#357).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant