Repository navigation
Release: Anthropic Claude Platform migration and citation quality fixes - #403
Merged
Merged
Conversation
* 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.
…p-after-v0.8.9 chore: sync develop with main after v0.8.9
…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.
* fix: build release images and stop :latest racing * fix: keep pre-releases out of the latest tag
* 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
…epic-anthropic-platform
… 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.
…-epic-anthropic-platform feat: serve OSA from the Claude Platform on AWS and retire the OpenRouter platform route
Merge the citation placement, source-list numbering, and thinking placeholder fixes after local tests and PR review.
* fix: normalize citation sentence placement * fix: canonicalize citation sentence placement
* fix: normalize citation sentence placement * fix: canonicalize citation sentence placement * fix: preserve canonical streamed answer * fix: harden citation completion state
Contributor
Preview Deployment
This preview will be updated automatically when you push new commits. |
This was referenced Sep 19, 2026
This was referenced Sep 19, 2026
…usekeeping (#411) * fix: cap get_full_docstring citable text like the FAQ citation path Uncapped, a single call at the default limit=5 could put ~50K chars of citable text on the wire (25x the FAQ cap). Adds _MAX_CITABLE_DOCSTRING_CHARS and corrects the citable-payloads test docstring, which had wrongly assumed this tool's snippets were already truncated by search.py. * test: cover the docker-build.yml concurrency-group fix for the :latest race * docs: retitle Unreleased to 0.8.10 and add PR #399 to the changelog PR #400's own body says it is a follow-up to #399, and #399 also tightens conceptual code-document search relevance, which had no changelog entry anywhere. * test: convert TestFetchPageContentImpl from httpx.Client mocking to respx Matches the respx-boundary pattern already used by TestFetchPageReportsFailureStructurally in the same file and this project's no-mocks-of-business-logic policy. Found and fixed a respx route-shadowing gotcha along the way: a bare host URL with no path matches any path on that host, so a more specific route registered after it is silently shadowed. * fix: address review suggestions on PR #411 Name DOCSTRING_SNIPPET_MAX_LENGTH explicitly instead of the ambiguous 'above' (the adjacent constant is the unrelated FAQ cap). Anchor the remaining bare-host respx routes in TestFetchPageContentImpl with a trailing slash for defense against the route-shadowing gotcha this same PR found, even though each currently registers only one route.
neuromechanist
temporarily deployed
to
testpypi
September 19, 2026 19:44 — with
GitHub Actions
Inactive
* feat(deploy): add rollback capability to auto-update.sh Addresses the still-open part of issue #379 (the release-image tagging/rollback follow-up): auto-update.sh had no way to recover from a bad :latest short of manually finding a sha- tag. Records each successful deployment's registry digest, adds --rollback [N] to redeploy a prior one pinned by digest (not :latest), and a rollback lock so the next hourly check doesn't immediately re-pull the bad image and undo the rollback. --clear-rollback-lock resumes normal auto-updates once the registry is fixed. Not tested against a live registry/Docker daemon (this runs on the production host, not this dev machine); verified with bash -n, shellcheck, and a standalone check of the rollback line-arithmetic logic. * fix(deploy): address rollback-correctness findings from review - rollback_target_digest no longer relies on error_exit (log + exit) inside a $(...) command substitution: that exit only killed the subshell, and the error text got silently captured as the "digest" instead of stopping the script. It now returns 1 and callers use `|| error_exit`. - do_rollback no longer appends the rollback target back onto deploy-history.log. Doing so shifted "N deployments ago" on every rollback, so a second --rollback 1 during the same incident bounced back to the image just escaped instead of going further back in time. The cumulative offset for the current incident is now tracked in ROLLBACK_LOCK_FILE and reconciled into history by --clear-rollback-lock. - deploy_update now sets a DEPLOY_HEALTHY flag; do_rollback uses it so a rollback whose container never becomes healthy is reported as UNHEALTHY / needs manual investigation, not silently as "Rollback complete". - check_for_updates captures the pulled digest from `docker pull`'s own "Digest: sha256:..." output instead of `docker inspect --format='{{index .RepoDigests 0}}'`, which belongs to the local image object rather than the specific tag just pulled and has no guaranteed correspondence when this host pulls more than one tag of the same image. Also now checks docker pull's own exit status. - LOCK_FILE is now scoped per container (prod/dev), so a routine auto-update in one environment can no longer silently swallow (exit 0) an operator's --rollback in the other. - --rollback --check-only now resolves and prints the target without deploying, instead of silently performing a real rollback despite the flag name. --force's inability to override an active rollback lock is now documented and logged explicitly. - --rollback rejects a non-positive step count. Verified the offset fix against a simulated two-rollback incident (walks d3->d2->d1, not d3->d2->d3) and the subshell-exit fix (failure now propagates via `|| error_exit` instead of being swallowed). * fix(deploy): reflect DEPLOY_HEALTHY in rollback's exit code and banner do_rollback's internal messaging already distinguished a healthy rollback from one whose container never became healthy, but the caller in main execution didn't check DEPLOY_HEALTHY: it always logged "Rollback completed successfully!" and exited 0 regardless, contradicting do_rollback's own "did NOT resolve the incident" warning immediately above it and giving nothing external (monitoring, a wrapper script) a way to detect failure.
neuromechanist
temporarily deployed
to
testpypi
September 19, 2026 20:04 — with
GitHub Actions
Inactive
* fix: narrow the legacy citation-marker code exception to real code context The precedingIdentifier heuristic in migrateLegacyCitationMarkers fired for any word directly followed by [n], which is also the shape of a normal, unlinked citation marker (e.g. "documentation[1] explains"). Rely on the existing backtick-based inline-code check instead; array-index-style text now needs backticks to be preserved as code. * fix: don't treat common abbreviations as citation sentence boundaries _SENTENCE_END_PATTERN was punctuation-only, so a marker landed right after a title or 'et al.' (e.g. "Dr.[1] Smith") instead of the real sentence end. Add a fixed abbreviation-exception list (Dr., Mr., Mrs., Ms., Prof., vs., etc., i.e., e.g., et al.) applied everywhere the pattern is used to find a sentence boundary. * docs: fix stale 'not wired into CI' claims in citation test files PR #403 added a frontend-tests CI job (test.yml and tests.yml) that runs frontend/test-citation-markers.js and frontend/test-streaming.js with Bun. Update comments that still claimed no JS runtime is available in CI. * fix: let etc./e.g./et al. genuinely end a citation sentence The abbreviation exception treated every listed abbreviation as never sentence-final, forward-searching past it unconditionally. That's right for titles (Dr., Mr., ...), which are always followed by a name in the same sentence, but wrong for etc./e.g./et al., which frequently do end a sentence -- especially in enumerative technical prose (HED/BIDS/EEGLAB docs list features, tags, etc.). A marker after one of those was silently relocated into the next, unrelated sentence. Split the exception into two kinds: titles always skip forward; etc./al/ e.g./i.e. only skip forward when the text right after the period is lowercase, the signal that the same sentence continues. Otherwise their own boundary is accepted. * fix: stop guessing abbreviation sentence boundaries, never relocate across one Two rounds of heuristic each fixed the reported misplacement while causing the opposite one: a marker relocated into a different, unrelated sentence. Even the seemingly reliable 'title + capitalized word' signal fails ('she became a Dr. Her family...' has a capitalized word after the period too, and it is not a name). No cheap local signal reliably distinguishes an abbreviation's period from a real sentence end in both directions. Replace the heuristic with a conservative default: never relocate a marker across an abbreviation's period into a different sentence. A marker left right after 'Dr.' or 'et al.' is imprecisely placed but still within (or adjacent to) the sentence it supports -- an accepted, bounded degradation, not a misattribution to the wrong claim. 'vs.' is the sole exception, confirmed across two review passes to not occur as a genuine sentence end in natural prose, so it still skips forward. Test matrix covers both directions for each abbreviation family (title, et al., etc., e.g.) plus the title-as-standalone-noun edge case, using domain-flavored HED/BIDS/EEGLAB-style prose.
neuromechanist
temporarily deployed
to
testpypi
September 19, 2026 20:10 — with
GitHub Actions
Inactive
…#414) * fix: validate ANTHROPIC_WORKSPACE_ID at Settings construction, not first request * fix: correct stale Phase 2 docstring/comment, enforce cache_ttl on reassignment * fix: warn on unresolvable bare default_model ids * fix: warn when default_model_provider will be ignored * fix: type key_source as Literal at _check_model_cost and AssistantWithMetrics * fix: fail loud when no OpenRouter API key is available * fix: scope BYOK auth bypass to endpoints that actually spend the credential Mirror management (mirrors.py) and session list/get/delete endpoints used the same RequireAuth dependency as /ask and /chat, whose BYOK bypass is only safe because those endpoints actually spend the caller-supplied key against a real LLM. A syntactically-plausible header value on the mirror or session endpoints granted access with no real credential at all. Both now use RequireAdminAuth, which has no BYOK bypass. Also adds construction-time invariant enforcement to ByokCredential and ProviderChoice, closing a gap where a future caller passing an empty key would silently run on the platform's key with cost enforcement disabled. * fix: verify BYOK key reaches the real outbound Anthropic request test_byok_http.py's two HTTP-boundary tests used respx to mock api.anthropic.com, but the installed anthropic SDK (1.6.0) vendors its own isolated httpx fork (httpx2/httpcore2), which respx cannot intercept. Confirmed by direct testing: the respx route silently never matched and both tests were making a real network call to api.anthropic.com on every run, safely (a garbage test key just got a real 401, converted to a 500 by the endpoint's own exception handler, which happened to satisfy the old, weaker status_code != 403 assertion regardless of whether any mocking occurred at all). Rewrites the mock to patch langchain_anthropic's own client-construction function with an httpx2.MockTransport instead, and asserts the caller's key actually reaches the mocked request -- closing the gap on the bug class that already shipped twice (#393/#394): a silent fallback to the platform's key would have passed every existing assertion. Also strengthens the equivalent unit-level assertion in test_anthropic_llm.py's BYOK construction test. * chore: address remaining nice-to-have findings from the PR #403 review - Reuse anthropic_key_header/openrouter_key_header's header name in /ask and /chat instead of duplicating the literal string. - Add a two-call regression test for the cache-breakpoint mutation fix, more directly mirroring the original bug report. - Add a regression test proving an empty-string BYOK header does not bypass server auth. - Document the accepted 'mock one layer above the HTTP boundary' pattern in .rules/testing_guidelines.md. * fix(ci): make CI install locked dependencies instead of drifting latest test.yml and tests.yml both installed dependencies via `pip install`/ `uv pip install --system` with no lockfile, so every CI run re-resolved versions fresh from pyproject.toml's floor constraints instead of using uv.lock - unlike deploy/Dockerfile, which correctly uses `uv sync --frozen`. This silently drifted CI onto fastapi 0.141.1 / starlette 1.6.0 (a major Starlette version bump) against the locked fastapi 0.128.0 / starlette 0.50.0 that local dev and production actually run. That newer Starlette breaks route/dependant introspection in a way that made this PR's new TestEndpointsThatDoNotSpendByokRequireAdminAuth tests see zero registered routes for /mirrors and /sessions in CI, while passing locally and in a container with locked versions - reproduced and confirmed both ways. Switched every install step to `uv sync --frozen --extra dev` (`dev` already depends on `[server]`, so this pulls in FastAPI etc. too) and the corresponding run steps to `uv run pytest`/`uv run ruff`, so CI now tests against the exact versions the lockfile pins and production deploys, instead of whatever happens to be newest on a given day. * fix: scope BYOK auth bypass on GET /health/communities Same vulnerability class as mirrors.py and the session endpoints, missed in the first pass: this endpoint never spends a BYOK credential against an LLM (it returns a full per-community diagnostic dump -- API key status, CORS origin count, document counts, warnings), so RequireAuth's BYOK bypass let any syntactically-plausible header value read it with no real credential at all. Switched to RequireAdminAuth. Also adds a generalized structural test (in addition to a dedicated health.py case): enumerates every route depending on verify_api_key and asserts it's exactly /ask and /chat, so a future endpoint added with RequireAuth by copy-paste fails immediately regardless of its path, instead of needing a new dedicated test case added after the fact.
neuromechanist
temporarily deployed
to
testpypi
September 19, 2026 20:39 — with
GitHub Actions
Inactive
…Records (#409) * docs: migrate CLAUDE.md content to AGENTS.md CLAUDE.md is now a thin @AGENTS.md adapter, following the cross-tool AGENTS.md convention. Also drops the Code Exploration with Serena section (Serena MCP is no longer carried forward for this project). * docs: add code_review, self_improve, and ci_cd rule files Adds the missing pr-review-toolkit, rule-evolution, and CI/CD reference rules from the plugin template. ci_cd.md is adapted to describe this repo's actual workflows rather than generic examples. * docs: fix stale git.md/python.md, merge testing.md improvements git.md and python.md contradicted actual project conventions (branch from main, conda/pip/mypy) rather than the real workflow (branch from develop, UV/ruff/ty). Rewritten to match AGENTS.md and the global instructions. testing.md gains back a couple of generic template improvements (JS framework note, CI integration pointer) without losing the project-specific LLM/exemplar testing section. * docs: add Architecture Decision Records for existing decisions Introduces docs/adr/ (MADR format) and backfills nine ADRs for decisions already made but only documented informally: the develop/main branch and versioning strategy, the develop-sync and release-image-race incidents and their fixes, the Anthropic Claude Platform migration, today's PR-review enforcement, and the original architecture choices in .context/plan.md and .context/research.md (LangGraph, no external database, BYOK, Astral tooling). * fix: correct branch-protection docs to match live ruleset state ADR 0005 and AGENTS.md described the review requirement as having no admin bypass, but the user asked for the bypass to be restored after that version was written, then had a second ruleset added to close the deletion-protection gap that reintroduced. Rewrite ADR 0005 to document the full history and final live state (verified against gh api), add the exact re-verification commands, and update AGENTS.md and code_review.md to match rather than describe a stale intermediate state. * fix: correct python.md/ADR 0009 line-length and mypy/ty claims pyproject.toml sets ruff line-length to 100, not the Black-default 88 these files claimed. The ty-not-mypy rule was stated as settled practice, but pyproject.toml still depends on and configures mypy and ty appears nowhere in the repo; reworded both to be honest that this is the target direction, not the current state, and filed #412 to track the actual migration. * fix: stop self_improve.md citing a nonexistent scratch_history.md .context/scratch_history.md doesn't exist in this repo; point at files that do (.context/plan.md, .context/research.md) and note it should be created on first real use instead of treated as an existing source to mine. * fix: identify tests.yml, not test.yml, as the merge-gating workflow test.yml only triggers on push/PR to main and its job names (Unit Tests (Python X)) don't match the required status check names. tests.yml's Test job (matrix 3.11/3.12) is what actually produces the Test (3.11)/Test (3.12) checks both rulesets require, and it's the only one of the two that runs on a PR into develop. Also corrects the Python matrix claim: test.yml covers 3.13 too, but that isn't part of what branch protection checks. * fix: soften ADR 0004/0008 overstated claim about PR #394's bug PR #394's own description says the request ran on 'the community's key or the platform's', not definitively the platform's key. Match the ADRs' wording to the source instead of overstating certainty. * chore: remove orphaned .serena/ directory Serena MCP was dropped from AGENTS.md/.rules/ earlier in this branch; nothing points at .serena/ anymore, so remove it rather than leave a directory with no documentation telling anyone to use it.
neuromechanist
temporarily deployed
to
testpypi
September 19, 2026 20:51 — with
GitHub Actions
Inactive
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Release PR bringing
developup tomain. Merging strips the.devsuffix and ships0.8.10; tagging and the GitHub release happen automatically per the workflow in CLAUDE.md.See
CHANGELOG.md([Unreleased]) for the full list. Highlights::latesttag (fix: build release images and stop :latest racing #380)developnow syncs tomainthrough a pull request instead of a direct push (fix: sync develop through a pull request, not a direct push #373)Test plan
developvia their individual PRs