diff --git a/.changeset/3792-relay-jev-reranking.md b/.changeset/3792-relay-jev-reranking.md new file mode 100644 index 0000000000..bfdb4fed85 --- /dev/null +++ b/.changeset/3792-relay-jev-reranking.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-common": minor +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +Hosted search is reranked again. A governed or strict turn worker whose `TYPESAFE_API_KEY` the host withholds now sends the `jev` reranker's request through the host's provider relay, under the new `typesafe` family (`x-brain-provider: typesafe`, `POST /v1/systemone` only). The host adds its key for `https://api.typesafe.ai` and meters each request as operation `reranking`, with an unknown cost rather than zero. `brain search` and `brain_search` in such a worker no longer report `provider_unavailable` and fall back to lifecycle order. A host without the relay keeps that notice, and a credentialed maintenance worker keeps its JeV key as before. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index b39e78be9e..4a5be2478b 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -66,7 +66,7 @@ next to it. `packages/ui-server/src/brain/client.ts:180-248`, called at `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:478`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, - `packages/core/src/cli/commands/doctor.ts:505-509`) — the user's own Claude + `packages/core/src/cli/commands/doctor.ts:507-511`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's binary. - **Two moving parts.** The SDK is a runtime dependency of diff --git a/docs/decisions/cost-tracking.md b/docs/decisions/cost-tracking.md index 7a833d4d10..6bd625bbcd 100644 --- a/docs/decisions/cost-tracking.md +++ b/docs/decisions/cost-tracking.md @@ -228,10 +228,10 @@ feed the inference budgets, not Activity rollups: they never change a run's recorded or effective cost. Units are what the provider reported in the raw response, before an SDK converts it. Completion tokens are priced through the same `RollupPricing` as the agent's own inference, on the direct route -(`priceProviderAttempt`, `packages/ui-server/src/pricing/provider-pricing.ts:36-75`). +(`priceProviderAttempt`, `packages/ui-server/src/pricing/provider-pricing.ts:38-77`). Embeddings are in neither remote catalog, so the built-in model has one dated row per input modality, from Google's published list price, and it counts as -an estimate (`GEMINI_EMBEDDING_PRICES`, `packages/ui-server/src/pricing/provider-pricing.ts:23-25`). +an estimate (`GEMINI_EMBEDDING_PRICES`, `packages/ui-server/src/pricing/provider-pricing.ts:25-27`). A modality without a row, inline media without a modality split, and every image request stay unpriced. The CLI's own per-image estimate is not a provider receipt and is never booked. Unknown is never zero here either: an attempt diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 4c627403c0..74fbc83cac 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -543,10 +543,13 @@ maintenance worker no longer receives the keys the provider relay carries (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and keys the operator lists for it), and the brain's `.env*` files are masked as they are for a credential-free worker. Its `brain` CLI reaches those providers through its own -relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:432-439`). +relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:441-448`). What remains is narrower and stated in the status: keys the relay does not carry (the `jev` reranker's, a `brain sync` agent runner's login) and every -key on a host without managed native storage, where there is no relay. +key on a host without managed native storage, where there is no relay. Since +#3792 a turn worker's `jev` reranker is relayed; a maintenance worker keeps +that key, because its sync judge and propagation review call TypeSafe +directly. ### Module jobs: durable state and other repositories — 2026-11-02 (#3380) @@ -672,7 +675,7 @@ the key and forwards it as the turn's own egress (G5). A key goes only to its built-in first-party origin, or to an exact origin the operator lists for that key in `BRAIN_UI_CLI_PROVIDER_ORIGINS`, under the 2026-10-23 ruling on #1673; the backends' origin rulings grant the CLI nothing by analogy -(`startProviderRelay`, `packages/ui-sdk/src/server/provider-relay.ts:323-328`). +(`startProviderRelay`, `packages/ui-sdk/src/server/provider-relay.ts:329-334`). The inference relay's placeholder is not a key: the launcher names a key that holds it as withheld, so a relayed Claude API-key turn's `anthropic-haiku` reaches the host's key instead of failing authentication. The `jev` reranker @@ -4200,7 +4203,7 @@ only that line for a refused CONNECT. The provider relay passes the proxy's reason through as the refusal body's `error.message` and an additive `error.reason`, using the `egress_denial` reason words plus `outward_not_approved` (`const refuse`, -`packages/ui-sdk/src/server/provider-relay.ts:386-391`). The OpenAI image +`packages/ui-sdk/src/server/provider-relay.ts:392-397`). The OpenAI image provider no longer appends its account hint to a relay refusal (`const relayRefusal`, `packages/module-images/src/providers/openai.ts:258-259`). A cancelled connection keeps its bare 403. The system prompt's turn-lifecycle @@ -4352,7 +4355,7 @@ files, `.claude/`, `.agents/`, `.pi/`, `.mcp.json`, and - The core CLI loads `brain.config.ts` or `brain.config.json` at the canonical brain cwd (`loadUserConfig`, `packages/core/src/lib/config.ts:660-694`). Host commands bind that cwd to the selected brain (`function hostSpawn`, - `packages/ui-server/src/brain/host-boundary.ts:526-537`). + `packages/ui-server/src/brain/host-boundary.ts:535-546`). - Bun startup uses root `bunfig.toml` and `package.json`; retained literal preload/module inputs can identify a nested module's nearest package scope. The inventory walks parent directories only within the originating journal diff --git a/docs/decisions/interpreted-briefing.md b/docs/decisions/interpreted-briefing.md index 2b76387982..a60e3a5a7a 100644 --- a/docs/decisions/interpreted-briefing.md +++ b/docs/decisions/interpreted-briefing.md @@ -44,7 +44,7 @@ deadline, one bounded rate-limit retry and explicit failure outcomes (`createJevClient`, `packages/core/src/lib/jev.ts:248-333`). The search reranker also uses Choice, but asks which search candidate answers a query; its probabilities rank candidate IDs, not briefing action categories -(`jevReranker`, `packages/core/src/providers/rerankers/jev.ts:227-244`). +(`jevReranker`, `packages/core/src/providers/rerankers/jev.ts:231-248`). Reuse the transport, not the search question. TypeSafe's [API reference](https://docs.typesafe.ai/api) and [model limitations](https://docs.typesafe.ai/model-jaggedness/jev-1.13) diff --git a/docs/decisions/runtime-requirements.md b/docs/decisions/runtime-requirements.md index d0bdc751e0..f1352419a0 100644 --- a/docs/decisions/runtime-requirements.md +++ b/docs/decisions/runtime-requirements.md @@ -195,7 +195,7 @@ Paths may appear in local diagnostics; public fixtures use temporary paths. | --- | --- | --- | | Claude backend's SDK range | Retain `^0.3.241` | It is the published declaration (`"@anthropic-ai/claude-agent-sdk"`, `packages/ui-backend-claude/package.json:49`). Registry metadata on 2026-09-30 confirms 0.3.241 exists. This is a declared compatibility bound, not proof every allowed release passed current measurements. | | ui-server's content CLI floor | Retain `0.33.0` | `--` support is the reason documented immediately above `MIN_BRAIN_CLI_VERSION` (`MIN_BRAIN_CLI_VERSION`, `packages/ui-server/src/brain/client.ts:132`); the initial boot refusal test used 0.32.9. The current test exercises the corrected floor (`a 0.40.0 brain repo pin`, `packages/ui-server/tests/brain-client.test.ts:247-259`). | -| Bun engine floor | Retain existing `>=1.3.5` declarations | Existing engine metadata and the doctor's CVE-based warning (`const MIN_BUN`, `packages/core/src/cli/commands/doctor.ts:50`; `function checkRuntime`, `packages/core/src/cli/commands/doctor.ts:87-94`). This record introduces no new doctor verdict or blanket boot gate. | +| Bun engine floor | Retain existing `>=1.3.5` declarations | Existing engine metadata and the doctor's CVE-based warning (`const MIN_BUN`, `packages/core/src/cli/commands/doctor.ts:51`; `function checkRuntime`, `packages/core/src/cli/commands/doctor.ts:88-95`). This record introduces no new doctor verdict or blanket boot gate. | | Pi SDK requirements | Retain existing exact `0.87.1` declarations | `packages/ui-backend-pi/package.json`; a host floor composes with each actual imported Pi dependency's existing exact requirement. The Claude range ruling does not authorize changing Pi's pins. | | Additional default Claude runtime floor | None | There is no evidenced numerical incompatibility threshold in the existing record. The successful pairs are observations, not proof that the preceding release fails. A new library floor needs a feature requirement or reproducible incompatibility and its versioning review. | | Example host SDK/runtime floors | `0.3.283` / `2.1.283` | The installed SDK manifest and `MEASURED_RUNTIME` (`export const MEASURED_RUNTIME`, `packages/ui-backend-claude/src/measured-runtime.ts:18-25`) identify this measured pair, rechecked in commit `e1ce9600`. This is a host choosing the demonstrated baseline, not a new default package floor. | diff --git a/docs/extending/compute-providers.md b/docs/extending/compute-providers.md index 4b307c3278..a1440d3a3e 100644 --- a/docs/extending/compute-providers.md +++ b/docs/extending/compute-providers.md @@ -59,9 +59,9 @@ inside core. Core declares it as an optional peer; an instance naming `boat` without the package installed is `provider_unavailable` and names the install it needs. A built-in package is loaded only when an instance names it; it exports `computeProvider` and may export `defaultKeyEnv`, the variable an -instance without `apiKeyEnv` reads (`export async function loadComputePackage`, `packages/core/src/lib/registry.ts:437-461`). +instance without `apiKeyEnv` reads (`export async function loadComputePackage`, `packages/core/src/lib/registry.ts:439-463`). Resolution gives each instance its own options and secret -(`export async function resolveComputeInstance`, `packages/core/src/lib/registry.ts:515-561`). +(`export async function resolveComputeInstance`, `packages/core/src/lib/registry.ts:517-563`). ## The Boat built-in diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 16d0c20522..b56544da51 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -1341,7 +1341,7 @@ keep. | Claude through the host inference relay | Only placeholders under the Claude CLI's own variables | | pi through the relay | Nothing | | Restricted (autonomous) | Unchanged: its envelope's minimum environment | -| Maintenance workers | No relayed key (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and keys listed in `BRAIN_UI_CLI_PROVIDER_ORIGINS`) and no `.env*`; the CLI reaches those providers through the [metered relay](#metered-provider-relay-1673). Keys the relay does not carry (`TYPESAFE_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN` for a `brain sync` agent runner) stay | +| Maintenance workers | No relayed key (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, and keys listed in `BRAIN_UI_CLI_PROVIDER_ORIGINS`) and no `.env*`; the CLI reaches those providers through the [metered relay](#metered-provider-relay-1673). Keys the relay does not carry for them stay: `TYPESAFE_API_KEY`, which their sync judge and propagation review send to TypeSafe directly (only turn workers relay it, #3792), and `CLAUDE_CODE_OAUTH_TOKEN` for a `brain sync` agent runner | **Which commands need a key.** The audit of the first-party commands an agent runs in its worker: @@ -1349,7 +1349,7 @@ runs in its worker: | Command | Key it reads (default variable) | In a worker that lacks it | | --- | --- | --- | | `brain search` (hybrid or vector), and `brain_search` from the brain's own `brain mcp` server | The embeddings provider's `apiKeyEnv` (`GEMINI_API_KEY`) for the query embedding | Keyword results. The warning names the provider, with `degraded_to=keyword_search` (`none` for `--mode vector`) | -| `brain search` with an enabled `jev` reranker or `--rerank jev` | The reranker's `apiKeyEnv` (`TYPESAFE_API_KEY`) | Lifecycle order, `degraded_to=lifecycle_order` | +| `brain search` with an enabled `jev` reranker or `--rerank jev` | The reranker's `apiKeyEnv` (`TYPESAFE_API_KEY`) | Lifecycle order, `degraded_to=lifecycle_order`, on a host without the relay; reranked through it otherwise (#3792) | | `brain index --embeddings` | The embeddings key | A keyword index, `degraded_to=keyword_index` on stderr | | `brain process` | The completions provider's `apiKeyEnv` (`GEMINI_API_KEY` for `gemini-flash`, `ANTHROPIC_API_KEY` for `anthropic-haiku`) | Refused, naming the provider | | `brain image` | `OPENAI_API_KEY`, `GEMINI_API_KEY` | Refused, naming each withheld provider (the pinned one with `--provider` or `--model`) | @@ -1378,8 +1378,9 @@ worker keeps its ordinary messages. The token's grammar is part of the **What #1673 changes.** On a turn with a turn proxy, the commands above that use a Gemini, Anthropic or OpenAI image provider work again, through the [metered relay](#metered-provider-relay-1673), with no key in the worker. The -`jev` reranker still reports `provider_unavailable`; `brain video watch` is -relayed since #2738. +same holds for `brain video watch` since #2738, and for the `jev` reranker +since #3792: a relayed turn's `brain search` and `brain_search` are reranked +instead of reporting `provider_unavailable`. A relayed Claude API-key turn holds the inference placeholder under `ANTHROPIC_API_KEY`; the launcher names that key in `BRAIN_WITHHELD_KEYS`, and the CLI's `anthropic-haiku` reaches the host's key through the relay instead of @@ -1396,8 +1397,9 @@ own at `/run/brain-providers/relay.sock`. The launcher names it in its native request there (the routes are in the [CLI contract](../integration-contract/cli.md#provider-relay-additive-0440-1673)): Gemini embeddings and completions, the Gemini Files lifecycle a local video -needs (#2738), Anthropic completions, and OpenAI and Gemini images. The `jev` -reranker is not relayed. +needs (#2738), Anthropic completions, OpenAI and Gemini images, and the `jev` +reranker's one request (#3792). A maintenance run keeps its JeV key and does +not relay it. **Video files (#2738).** A relayed `brain video watch` uploads, polls, uses and deletes its file through the relay. The relay keeps the upload URL the provider @@ -1414,8 +1416,9 @@ deleted with the host's key when the turn's relay stops. **Who may receive a key.** The relay sends `GEMINI_API_KEY` only to `https://generativelanguage.googleapis.com`, `ANTHROPIC_API_KEY` only to -`https://api.anthropic.com` and `OPENAI_API_KEY` only to -`https://api.openai.com`, in the header that provider expects. A custom +`https://api.anthropic.com`, `OPENAI_API_KEY` only to +`https://api.openai.com` and `TYPESAFE_API_KEY` only to +`https://api.typesafe.ai`, in the header that provider expects. A custom endpoint (`GOOGLE_GEMINI_BASE_URL`, `GEMINI_BASE_URL`, `OPENAI_BASE_URL`) or a custom `apiKeyEnv` is refused, before any contact, unless the operator lists that key and exact origin in `BRAIN_UI_CLI_PROVIDER_ORIGINS`: @@ -1443,8 +1446,8 @@ read from the raw response before any SDK drops them. An attempt a crash interrupts therefore stays disclosed. When a turn ends, its relay waits for in-flight attempts to report before the turn's accounting closes. Gemini embeddings are priced at Google's published list price per modality; completions use -the same Activity price table as the agent's own inference; image units stay -unpriced. Reported tokens without a price count toward the unpriced-token +the same Activity price table as the agent's own inference; image units and +JeV reranking (operation `reranking`, #3792) stay unpriced. Reported tokens without a price count toward the unpriced-token stops; a request whose provider reported no usage is unknown spend and never blocks by itself. A turn's requests count toward its turn, conversation and UTC-day budgets and appear in its budget receipt, whose coverage now names @@ -1700,7 +1703,8 @@ qualifies existing first-party request shapes. The [metered provider relay](#metered-provider-relay-1673) built on it in [#1673](https://github.com/schlessera/brain-kit/issues/1673) relays the rows below except video and JeV; [#2738](https://github.com/schlessera/brain-kit/issues/2738) -added video. +added video and [#3792](https://github.com/schlessera/brain-kit/issues/3792) +JeV, for turn workers. | CLI consumer / provider | Credential selection | Native destination and request family | Accounting at the consumer | | --- | --- | --- | --- | @@ -1715,7 +1719,7 @@ The factories and concrete recipient provenance are implemented at (`geminiEmbeddings`, `packages/core/src/providers/embeddings/gemini.ts:59-221`), (`geminiCompletions`, `packages/core/src/providers/completions/gemini.ts:56-134`), (`anthropicCompletions`, `packages/core/src/providers/completions/anthropic.ts:63-147`) -and (`jevReranker`, `packages/core/src/providers/rerankers/jev.ts:227-347`). +and (`jevReranker`, `packages/core/src/providers/rerankers/jev.ts:231-272`). Configured model labels, endpoint overrides and key-variable names select native routing; none grants permission to release a host-held credential. diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index 37c0836727..90ba5593d6 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -9,7 +9,8 @@ the maintainer's 2026-10-23 rulings on that issue: first-party recipients by default plus `BRAIN_UI_CLI_PROVIDER_ORIGINS`, a socket the CLI finds through `BRAIN_PROVIDER_RELAY_SOCKET`, per-attempt rows with no reservation, maintenance charged to its turn or day, and no relay for video or JeV. #2738 later relayed -the video Files lifecycle (see below). The sections below +the video Files lifecycle (see below), and #3792 the JeV reranker's request for +turn workers (`typesafe` family, operation `reranking`, unpriced). The sections below keep the audit's evidence and requirements; where the relay settles one, it says so. diff --git a/docs/integration-contract.md b/docs/integration-contract.md index d741bf1aaa..5688b4db85 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,19 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## JeV reranking through the provider relay (additive, 0.45.0, #3792) + +The CLI provider relay gains the `typesafe` family, `x-brain-provider: +typesafe`, whose only route is `POST /v1/systemone`. A governed or strict turn +worker whose `TYPESAFE_API_KEY` the host withholds sends the `jev` reranker's +request there; the host adds its key for `https://api.typesafe.ai` and meters +the attempt as operation `reranking`, with an unknown cost rather than zero. +Such a worker's `brain search` and `brain_search` are reranked instead of +reporting `provider_unavailable` and falling back to lifecycle order; a host +without the relay keeps that notice. Credentialed maintenance workers keep the +key as before. See [the CLI component](integration-contract/cli.md#provider-relay-additive-0440-1673). +This ships in a minor; no breaking ruling is required. + ## The Start card's persona choice (additive, 0.45.0, #3698) In `@schlessera/brain-ui-react`, the conversation client's state adds diff --git a/docs/integration-contract/cli.md b/docs/integration-contract/cli.md index bf81105fc7..f53f6f1863 100644 --- a/docs/integration-contract/cli.md +++ b/docs/integration-contract/cli.md @@ -268,6 +268,7 @@ environment carries. A built-in provider whose key is withheld from the process | Anthropic completions | `anthropic` | `POST /v1/messages` | | OpenAI images | `openai` | `POST /v1/images/generations`, `/v1/images/edits` (multipart) | | Gemini images | `gemini` | `POST /v1beta/interactions` | +| `jev` reranker (additive, 0.45.0, #3792) | `typesafe` | `POST /v1/systemone` | The request keeps its method, path, body and content headers. The CLI drops every credential header and adds three headers that are names, never values: @@ -290,9 +291,22 @@ built-in providers retry as a transient error. A seam that is only available through the relay counts as configured: hybrid `brain search` embeds its query, `brain process` completes, `brain image` lists the provider's models, `brain video watch` uploads a local video (additive, -0.45.0, #2738). Without the variable, or for a key that is set or never -withheld, a provider behaves as before. The `jev` reranker is not relayed and -keeps the `provider_unavailable` notice. Existing JSON envelopes are unchanged. +0.45.0, #2738), and an enabled `jev` reranker reranks `brain search` and +`brain_search` (additive, 0.45.0, #3792). Without the variable, or for a key +that is set or never withheld, a provider behaves as before: on a host without +the relay, the `jev` reranker keeps the `provider_unavailable` notice and +lifecycle order. Existing JSON envelopes are unchanged. + +The `jev` reranker's family (additive, 0.45.0, #3792). `typesafe` relays only +`POST /v1/systemone` without a query string; any other method, path or query +under it is refused before contact. Its key, `TYPESAFE_API_KEY` by default, +goes only to `https://api.typesafe.ai`, as `Authorization: Bearer`, unless the +operator lists that key and an exact origin in `BRAIN_UI_CLI_PROVIDER_ORIGINS`; +a custom `apiKeyEnv` needs its own listing. Each request is one metered +attempt with operation `reranking`, carrying the usage the response reports. +No rate is held for it, so its cost is unknown, never zero. The relay carries +it for governed and strict turn workers; a credentialed maintenance worker +keeps `TYPESAFE_API_KEY` and calls the provider directly, as before. The video files lifecycle (additive, 0.45.0, #2738). The relay answers a resumable upload start with an `x-goog-upload-url` of its own, diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 260306317f..cb9cd49523 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -119,7 +119,8 @@ that has a turn proxy, and one per credentialed maintenance run where the host has managed native storage. A relay sends a key only to that key's built-in first-party origin (`GEMINI_API_KEY` to `https://generativelanguage.googleapis.com`, `ANTHROPIC_API_KEY` to `https://api.anthropic.com`, `OPENAI_API_KEY` to -`https://api.openai.com`) or to an exact origin the server's +`https://api.openai.com`, `TYPESAFE_API_KEY` to `https://api.typesafe.ai` +since #3792) or to an exact origin the server's `BRAIN_UI_CLI_PROVIDER_ORIGINS` (`KEY=origin[,origin];...`) lists for that key. A custom endpoint or a custom key variable is refused unless listed. The public protocol adds the `TurnBudgetCoverage` type ([wire](wire.md#completed-inference-usage-and-budgets-additive-1669)). diff --git a/packages/common/src/provider-relay.ts b/packages/common/src/provider-relay.ts index 090afb3af9..9db892fc63 100644 --- a/packages/common/src/provider-relay.ts +++ b/packages/common/src/provider-relay.ts @@ -19,7 +19,7 @@ import { INFERENCE_RELAY_PLACEHOLDER, isWithheldKey } from "./provider-unavailab /** Absolute path of the host's provider relay socket, set by the worker launcher. */ export const PROVIDER_RELAY_SOCKET_ENV = "BRAIN_PROVIDER_RELAY_SOCKET"; -/** Which first-party request family the CLI sent: `gemini`, `anthropic` or `openai`. */ +/** Which first-party request family the CLI sent: `gemini`, `anthropic`, `openai` or `typesafe` (the `jev` reranker, #3792). */ export const PROVIDER_RELAY_FAMILY_HEADER = "x-brain-provider"; /** The environment variable whose host value the request needs. A name, never a value. */ export const PROVIDER_RELAY_KEY_HEADER = "x-brain-provider-key"; @@ -28,7 +28,7 @@ export const PROVIDER_RELAY_ORIGIN_HEADER = "x-brain-provider-origin"; /** What a relayed provider holds where its key would be. Never a secret. */ export const PROVIDER_RELAY_PLACEHOLDER = "brain-provider-relay-placeholder"; -export type ProviderRelayFamily = "gemini" | "anthropic" | "openai"; +export type ProviderRelayFamily = "gemini" | "anthropic" | "openai" | "typesafe"; /** Credential headers the CLI never sends to the relay, whatever a provider SDK set. */ const CREDENTIAL_HEADERS = ["authorization", "x-api-key", "x-goog-api-key", "api-key", "cookie", "proxy-authorization"]; diff --git a/packages/core/src/cli/commands/doctor.ts b/packages/core/src/cli/commands/doctor.ts index b013dbbbee..cc00fefef9 100644 --- a/packages/core/src/cli/commands/doctor.ts +++ b/packages/core/src/cli/commands/doctor.ts @@ -25,6 +25,7 @@ import { foreignCoreSkill } from "../../lib/skills/core-installation.js"; import { packageVersion } from "../../package-version.js"; import { missingEmbeddingKey, rerankerKeyEnv, resolveReranker } from "../../lib/registry.js"; import { JEV_MODEL } from "../../lib/llm-defaults.js"; +import { relayedKey } from "@schlessera/brain-common/internal/provider-relay"; import type { CoreCommand, CliContext } from "../types.js"; import { emit, embeddingDims, parseArgs } from "../io.js"; import { resolveEmitters } from "../skills-util.js"; @@ -368,7 +369,8 @@ function checkReranker(cli: CliContext): Check { return { id: "reranker", status: "pass", detail: `reranking by ${cfg?.provider === "none" ? "retrieval order (none)" : "lifecycle factors (heuristic)"}, set in config` }; } const keyEnv = rerankerKeyEnv(cfg); - if (!readEnvVar(keyEnv)) { + // A key the host withholds and relays is available through the relay (#3792). + if (!readEnvVar(keyEnv) && !relayedKey(keyEnv)) { return { id: "reranker", status: "warn", diff --git a/packages/core/src/lib/registry.ts b/packages/core/src/lib/registry.ts index 2c08d21ab8..7472b51a8e 100644 --- a/packages/core/src/lib/registry.ts +++ b/packages/core/src/lib/registry.ts @@ -304,7 +304,8 @@ export interface RerankerSelection { * then the configured `reranker.provider` (default `jev`). * - Judgment ordering requires `config.enabled === true`. Credentials and * mode selection cannot enable it. Preview constructs a request only. - * - The built-in `jev` needs its key. Without it the configured default + * - The built-in `jev` needs its key, or the host's provider relay for a key + * the host withholds (#3792). Without either the configured default * quietly keeps the lifecycle ordering, the rule that keeps a keyless brain * working; an explicit request for `jev` gets the same ordering plus a * warning, never a silent pretence. @@ -350,8 +351,9 @@ export function selectReranker( }; } if (!explicit && typeof provider !== "string") return { rerank: "jev", reranker: provider, warning }; - // A dry run builds the request without sending it, so it needs no key. - if (!opts.preview && !readEnvVar(rerankerKeyEnv(config))) { + // A dry run builds the request without sending it, so it needs no key. A + // key the host withholds and relays is available through the relay (#3792). + if (!opts.preview && !readEnvVar(rerankerKeyEnv(config)) && !relayedKey(rerankerKeyEnv(config))) { const key = rerankerKeyEnv(config); return { rerank: "heuristic", diff --git a/packages/core/src/providers/rerankers/jev.ts b/packages/core/src/providers/rerankers/jev.ts index 40f796593f..082fd2a42a 100644 --- a/packages/core/src/providers/rerankers/jev.ts +++ b/packages/core/src/providers/rerankers/jev.ts @@ -24,9 +24,9 @@ * the span the retriever already matched, and unconditioned text dilutes it. */ -import { readEnvVar } from "../../config/env.js"; import { JEV_MODEL } from "../../lib/llm-defaults.js"; import type { Ranked, RerankCandidate, Reranker, RerankRequest } from "../../lib/seams.js"; +import { providerCredential, providerRelayFetch } from "@schlessera/brain-common/internal/provider-relay"; import { missingKeyMessage } from "@schlessera/brain-common/internal/provider-unavailable"; const API_URL = "https://api.typesafe.ai/v1/systemone"; @@ -223,6 +223,10 @@ export function orderFromAnswer( * Create a Jev-backed Reranker. Constructing it makes no network call; the * key is read on first rerank(). A single attempt per search: retrying inside * an interactive deadline only delays the fallback to retrieval order. + * + * In a worker whose key the host withholds and relays, the request goes to the + * host's provider relay instead, unchanged and without a credential; the host + * adds the key and meters the call (#3792). */ export function jevReranker(config: JevRerankerConfig = {}): Reranker { const model = config.model ?? JEV_MODEL; @@ -240,14 +244,15 @@ export function jevReranker(config: JevRerankerConfig = {}): Reranker { }, async rerank(req) { - const apiKey = readEnvVar(apiKeyEnv); - if (!apiKey) throw new Error(missingKeyMessage(apiKeyEnv, "jev", "reranking", `${apiKeyEnv} environment variable is required for the jev reranker`)); + const relay = providerRelayFetch("typesafe", apiKeyEnv); + const apiKey = relay ? undefined : providerCredential(apiKeyEnv); + if (!relay && !apiKey) throw new Error(missingKeyMessage(apiKeyEnv, "jev", "reranking", `${apiKeyEnv} environment variable is required for the jev reranker`)); if (req.candidates.length < 2) return req.candidates.map((item) => ({ item, score: 1 })); const { body, included } = buildJevRequest(model, req); - const res = await doFetch(url, { + const res = await (relay ?? doFetch)(url, { method: "POST", - headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` }, + headers: { "Content-Type": "application/json", ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}) }, body: JSON.stringify(body), signal: req.signal, }); diff --git a/packages/core/tests/provider-relay-jev.test.ts b/packages/core/tests/provider-relay-jev.test.ts new file mode 100644 index 0000000000..7e62ae956e --- /dev/null +++ b/packages/core/tests/provider-relay-jev.test.ts @@ -0,0 +1,89 @@ +/** + * The jev reranker through the host's provider relay (#3792). A governed or + * strict worker has no `TYPESAFE_API_KEY`; with a relay socket it reranks + * anyway, sending its native request to the socket with the `typesafe` family, + * the key's name and the first-party origin, and never a credential. Without + * the relay it keeps the `provider_unavailable` notice. (Until #3792 the relay + * had no Jev family, so every hosted search ran in lifecycle order.) + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { parseProviderUnavailable } from "@schlessera/brain-common/internal/provider-unavailable"; +import { rerankSetup } from "../src/lib/registry.js"; +import { JEV_MODEL } from "../src/lib/llm-defaults.js"; +import type { RerankCandidate } from "../src/lib/seams.js"; + +const NAMES = ["TYPESAFE_API_KEY", "BRAIN_WITHHELD_KEYS", "BRAIN_PROVIDER_RELAY_SOCKET", "BRAIN_RERANK_MODE"] as const; +const SOCKET = "/run/brain-egress/providers.sock"; +const saved = new Map(); +const savedFetch = Object.getOwnPropertyDescriptor(globalThis, "fetch")!; +interface Sent { method: string; url: string; unix: unknown; headers: Record; body: { model?: string } } +let sent: Sent[]; + +beforeEach(() => { + for (const name of NAMES) { saved.set(name, Object.getOwnPropertyDescriptor(process.env, name)); delete process.env[name]; } + process.env.BRAIN_WITHHELD_KEYS = "TYPESAFE_API_KEY"; + sent = []; + // The relay as the worker sees it, or the provider when the key is held: ranks the last candidate first. + Object.defineProperty(globalThis, "fetch", { ...savedFetch, value: async (input: string | URL | Request, init?: RequestInit) => { + const request = new Request(input, init); + const url = new URL(request.url); + sent.push({ method: request.method, url: `${url.origin}${url.pathname}${url.search}`, unix: (init as { unix?: unknown } | undefined)?.unix, + headers: Object.fromEntries(request.headers), body: await request.json() as { model?: string } }); + return Response.json({ model: JEV_MODEL, answers: { ranking: { type: "choice", choice: "C003", confidence: 0.8, + probabilities: { C001: 0.1, C002: 0.2, C003: 0.7 } } }, usage: { input_tokens: 700, output_tokens: 4 } }); + } }); +}); +afterEach(() => { + Object.defineProperty(globalThis, "fetch", savedFetch); + for (const [name, descriptor] of saved) { + if (descriptor) Object.defineProperty(process.env, name, descriptor); else delete process.env[name]; + } +}); + +const candidates: RerankCandidate[] = ["Ithaca harbour", "Ithaca palace", "Ithaca olive grove"].map((title, index) => ({ + id: `notes/${index}.md`, title, type: "note", tags: "ithaca", summary: `${title} at dawn`, excerpt: `Odysseus at ${title}`, score: 1 / (index + 1), +})); +const enabled = { enabled: true, provider: "jev" } as never; + +test("an enabled jev reranker whose key the host withholds reranks through the relay, with no notice", async () => { + process.env.BRAIN_PROVIDER_RELAY_SOCKET = SOCKET; + const setup = rerankSetup(enabled); + expect(setup.rerank, "RELAYED_JEV_SELECTED").toBe("jev"); + expect(setup.warning, "RELAYED_JEV_NO_NOTICE").toBeUndefined(); + const ranked = await setup.deps.reranker!.rerank({ query: "Ithaca", candidates }); + expect(ranked.map(entry => entry.item.title), "RELAYED_JEV_ORDERS_BY_ANSWER").toEqual(["Ithaca olive grove", "Ithaca palace", "Ithaca harbour"]); + expect(sent).toHaveLength(1); + const [request] = sent; + expect({ unix: request!.unix, method: request!.method, path: new URL(request!.url).pathname }, "RELAYED_JEV_GOES_TO_SOCKET") + .toEqual({ unix: SOCKET, method: "POST", path: "/v1/systemone" }); + expect(request!.headers, "RELAYED_JEV_NAMES_FAMILY_KEY_ORIGIN").toMatchObject({ "x-brain-provider": "typesafe", + "x-brain-provider-key": "TYPESAFE_API_KEY", "x-brain-provider-origin": "https://api.typesafe.ai" }); + expect(request!.headers.authorization, "RELAYED_JEV_SENDS_NO_CREDENTIAL").toBeUndefined(); + expect(request!.body.model).toBe(JEV_MODEL); +}); + +test("without the relay the withheld key keeps lifecycle order and the notice", () => { + const setup = rerankSetup(enabled); + expect(setup.rerank).toBe("heuristic"); + expect(parseProviderUnavailable(setup.warning ?? ""), "UNRELAYED_JEV_NOTICE").toEqual([ + { provider: "jev", capability: "reranking", key: "TYPESAFE_API_KEY", degradedTo: "lifecycle_order" }, + ]); +}); + +test("a key the worker holds is sent directly, never through the relay", async () => { + process.env.BRAIN_PROVIDER_RELAY_SOCKET = SOCKET; + process.env.TYPESAFE_API_KEY = "odysseus-worker-typesafe-key"; + const setup = rerankSetup(enabled); + expect(setup.warning).toBeUndefined(); + await setup.deps.reranker!.rerank({ query: "Ithaca", candidates }); + expect(sent.map(request => ({ url: request.url, unix: request.unix, authorization: request.headers.authorization })), "HELD_JEV_KEY_DIRECT") + .toEqual([{ url: "https://api.typesafe.ai/v1/systemone", unix: undefined, authorization: "Bearer odysseus-worker-typesafe-key" }]); +}); + +test("a relay socket without a withheld key is not a key: the reranker stays off", () => { + process.env.BRAIN_PROVIDER_RELAY_SOCKET = SOCKET; + delete process.env.BRAIN_WITHHELD_KEYS; + const setup = rerankSetup(enabled); + expect(setup.rerank, "NEVER_WITHHELD_NOT_RELAYED").toBe("heuristic"); + expect(sent).toEqual([]); +}); diff --git a/packages/ui-sdk/src/server/provider-relay.ts b/packages/ui-sdk/src/server/provider-relay.ts index 6d1e734249..fbf48fb485 100644 --- a/packages/ui-sdk/src/server/provider-relay.ts +++ b/packages/ui-sdk/src/server/provider-relay.ts @@ -2,8 +2,9 @@ * The metered host relay for the `brain` CLI's paid providers (#1673). * * A governed or strict turn worker, and a relayed maintenance worker, holds no - * provider key. A built-in Gemini, Anthropic or OpenAI image provider in it - * sends its native request to this Unix socket instead, naming its request + * provider key. A built-in Gemini, Anthropic or OpenAI image provider, or the + * `jev` reranker (#3792), in it sends its native request to this Unix socket + * instead, naming its request * family, the key variable and the origin it would have called * (`@schlessera/brain-common/internal/provider-relay`). The relay: * @@ -69,15 +70,18 @@ export const FIRST_PARTY_PROVIDER_RECIPIENTS: Readonly Record>> = { gemini: key => ({ "x-goog-api-key": key }), anthropic: key => ({ "x-api-key": key }), openai: key => ({ authorization: `Bearer ${key}` }), + typesafe: key => ({ authorization: `Bearer ${key}` }), }; /** `files`: a Gemini Files lifecycle request (upload, poll, delete), which the Files API does not charge for. */ -export type ProviderOperation = "embeddings" | "completions" | "image" | "files"; +export type ProviderOperation = "embeddings" | "completions" | "image" | "files" | "reranking"; /** The fixed routes of each family: the request the first-party CLI provider sends, and nothing else. */ const ROUTES: Readonly> = { gemini: [ @@ -87,6 +91,8 @@ const ROUTES: Readonly `**Secrets.** The brain's \`.env*\` files cannot be read here, and this worker holds no provider keys${kept.length ? ` except ${kept.map(name => `\`${name}\``).join(", ")}` : ""}. ${relayed ? RELAY_NOTE : `A \`brain\` command that needs ${kept.length ? "another" : "an"} embedding, completion, reranking or image provider key reports the provider as unavailable (\`provider_unavailable\`), and \`brain search\` then falls back to keyword results.`} Do not look for keys elsewhere; say which provider was unavailable.`; /** What the CLI provider relay meters (#1673). Fixed text: it names no live fact. */ -const RELAY_NOTE = "The `brain` CLI's Gemini embeddings and completions, Anthropic completions, and OpenAI and Gemini images go through the host's metered provider relay: the host adds their keys, records their usage on this turn and counts it toward its budgets, and refuses a request with `budget_exceeded` once a budget is blocked. Video and the JeV reranker are not relayed and report `provider_unavailable`, and `brain search` falls back to keyword results when its provider is unavailable."; +const RELAY_NOTE = "The `brain` CLI's Gemini embeddings and completions (video included), Anthropic completions, OpenAI and Gemini images, and the JeV reranker go through the host's metered provider relay: the host adds their keys, records their usage on this turn and counts it toward its budgets, and refuses a request with `budget_exceeded` once a budget is blocked. `brain search` falls back to keyword results when its embedding provider is unavailable, and to lifecycle order when its reranker is."; const SHARED_UID_NOTE = "The worker shares the server's uid; server state is protected by masks only. A read-only brain does not prevent access to other host paths available to that uid."; diff --git a/packages/ui-sdk/tests/provider-relay.test.ts b/packages/ui-sdk/tests/provider-relay.test.ts index 984526ab28..24d4089a84 100644 --- a/packages/ui-sdk/tests/provider-relay.test.ts +++ b/packages/ui-sdk/tests/provider-relay.test.ts @@ -23,7 +23,7 @@ beforeAll(() => { afterAll(() => upstream.stop(true)); const KEYS: Record = { ANTHROPIC_API_KEY: "odysseus-host-anthropic", GEMINI_API_KEY: "odysseus-host-gemini", - OPENAI_API_KEY: "odysseus-host-openai", ITHACA_GATEWAY_KEY: "odysseus-host-gateway" }; + OPENAI_API_KEY: "odysseus-host-openai", TYPESAFE_API_KEY: "odysseus-host-typesafe", ITHACA_GATEWAY_KEY: "odysseus-host-gateway" }; async function relayed(options: Partial, request: { path: string; family?: string; key?: string; origin?: string; method?: string; headers?: Record; body?: string | Uint8Array }) { @@ -88,6 +88,7 @@ describe("recipient authority", () => { gemini: { key: "GEMINI_API_KEY", origin: "https://generativelanguage.googleapis.com" }, anthropic: { key: "ANTHROPIC_API_KEY", origin: "https://api.anthropic.com" }, openai: { key: "OPENAI_API_KEY", origin: "https://api.openai.com" }, + typesafe: { key: "TYPESAFE_API_KEY", origin: "https://api.typesafe.ai" }, }); // Gemini's key toward Anthropic's first-party origin is not a default pair. const crossed = await relayed({ origins: new Map() }, { path: "/v1/messages", key: "GEMINI_API_KEY", origin: "https://api.anthropic.com" }); @@ -146,6 +147,55 @@ describe("routes", () => { }); }); +describe("jev reranking (#3792)", () => { + const jev = (request: { path?: string; key?: string; origin?: string; method?: string } = {}) => ({ path: "/v1/systemone", family: "typesafe", + key: "TYPESAFE_API_KEY", body: JSON.stringify({ model: "jev-1.13.0", state: { query: "Ithaca", candidates: [] }, questions: {} }), ...request }); + const answer = () => Response.json({ model: "jev-1.13.0", answers: { ranking: { type: "choice" } }, usage: { input_tokens: 700, output_tokens: 4 } }); + + test("the reranking request reaches its recipient with the host's key as a bearer token, metered", async () => { + reply = answer; + try { + const result = await relayed({ origins: new Map([["TYPESAFE_API_KEY", [upstream.url.origin]]]) }, + { ...jev(), headers: { authorization: "Bearer brain-provider-relay-placeholder", "x-api-key": "odysseus-worker-key" } }); + expect(result.status).toBe(200); + expect(result.upstream.map(request => request.path)).toEqual(["/v1/systemone"]); + const headers = result.upstream[0]!.headers; + expect(headers.authorization, "JEV_RELAY_PLACES_HOST_KEY").toBe(`Bearer ${KEYS.TYPESAFE_API_KEY}`); + expect(["x-api-key", "x-brain-provider", "x-brain-provider-key", "x-brain-provider-origin"].filter(name => headers[name] !== undefined), + "JEV_RELAY_STRIPS_WORKER_CREDENTIALS").toEqual([]); + expect(result.receipts, "JEV_RELAY_METERED").toMatchObject([{ family: "typesafe", operation: "reranking", model: "jev-1.13.0", + origin: upstream.url.origin, key: "TYPESAFE_API_KEY", outcome: "completed", status: 200, usage: { inputTokens: 700, outputTokens: 4 } }]); + } finally { reply = () => Response.json({ usage: { input_tokens: 7, output_tokens: 3 } }); } + }); + + test.each([ + ["another path", { path: "/v1/systemtwo" }, "route_not_allowed"], + ["a path below the route", { path: "/v1/systemone/batch" }, "route_not_allowed"], + ["a query string", { path: "/v1/systemone?debug=1" }, "route_not_allowed"], + ["another family's route", { path: "/v1/messages" }, "route_not_allowed"], + ["a GET", { method: "GET" }, "method_not_allowed"], + ["a DELETE", { method: "DELETE" }, "method_not_allowed"], + ["an unlisted origin", { origin: "https://sirens.example" }, "recipient_not_authorized"], + ["the key toward another provider's first-party origin", { origin: "https://api.anthropic.com" }, "recipient_not_authorized"], + ["another key toward the Jev origin", { key: "ANTHROPIC_API_KEY", origin: "https://api.typesafe.ai" }, "recipient_not_authorized"], + ] as const)("%s under the typesafe family is refused before contact", async (_, request, reason) => { + const result = await relayed({ origins: new Map([["TYPESAFE_API_KEY", [upstream.url.origin]]]) }, + jev({ origin: upstream.url.origin, ...request })); + expect(result.status).toBeGreaterThanOrEqual(400); + expect(result.refusals, "JEV_RELAY_REFUSES_OTHER_REQUESTS").toMatchObject([{ family: "typesafe", reason }]); + expect(result.upstream).toEqual([]); + expect(result.receipts).toEqual([]); + }); + + test("a blocked budget refuses the reranking request before contact", async () => { + const result = await relayed({ origins: new Map([["TYPESAFE_API_KEY", [upstream.url.origin]]]), + admit: () => ({ allowed: false, message: "Turn inference budget reached." }) }, jev({ origin: upstream.url.origin })); + expect(result.status).toBe(403); + expect(result.refusals, "JEV_RELAY_BUDGET_REFUSAL").toMatchObject([{ family: "typesafe", reason: "budget_exceeded" }]); + expect(result.upstream).toEqual([]); + }); +}); + describe("budget", () => { test("a blocked scope refuses the next request with budget_exceeded before contact", async () => { const result = await relayed({ admit: () => ({ allowed: false, message: "Turn inference budget reached." }) }, { path: "/v1/messages" }); diff --git a/packages/ui-sdk/tests/worker-provider-relay.test.ts b/packages/ui-sdk/tests/worker-provider-relay.test.ts index dd44fcc174..320bb25142 100644 --- a/packages/ui-sdk/tests/worker-provider-relay.test.ts +++ b/packages/ui-sdk/tests/worker-provider-relay.test.ts @@ -3,7 +3,9 @@ * bubblewrap. A governed or strict turn worker holds no provider key; the real * `brain search` embeds its query through the relay, which adds the host's key, * records the request's usage and refuses it once a budget is blocked. The - * upstream is a fictional loopback Gemini endpoint the operator lists. + * upstream is a fictional loopback Gemini endpoint the operator lists. Its + * `jev` reranking goes through the relay too (#3792), to the first-party + * origin, which the relay's own dispatch reaches on a loopback stand-in. */ import { launchFixtureAgentWorker } from "./helpers/worker-startup-view-fixture.js"; import { afterAll, beforeAll, describe, expect, test } from "bun:test"; @@ -28,7 +30,9 @@ const vector = (seed: number) => Array.from({ length: DIMENSIONS }, (_, index) = interface Seen { method?: string; path: string; headers: Record } let upstream: ReturnType; const seen: Seen[] = []; -let root: string, brain: string, videoBrain: string; +let root: string, brain: string, videoBrain: string, rerankBrain: string; +/** The candidate the fictional Jev answer ranks first: the last one it was asked about. */ +let jevChoice: string | undefined; /** Files the fictional provider still holds, by name. */ const stored = new Set(); @@ -51,6 +55,14 @@ beforeAll(async () => { if (request.method === "DELETE") stored.delete("files/troy-1"); return Response.json(request.method === "DELETE" ? {} : { name: "files/troy-1", uri: `${upstream.url.origin}/v1beta/files/troy-1`, state: "ACTIVE" }); } + if (url.pathname === "/v1/systemone") { + const asked = await request.json() as { questions: { ranking: { criteria: Record } } }; + const ids = Object.keys(asked.questions.ranking.criteria); + jevChoice = asked.questions.ranking.criteria[ids.at(-1)!]; + return Response.json({ model: "jev-1.13.0", answers: { ranking: { type: "choice", choice: ids.at(-1), confidence: 0.9, + probabilities: Object.fromEntries(ids.map((id, index) => [id, index === ids.length - 1 ? 0.9 : 0.1 / (ids.length - 1)])) } }, + usage: { input_tokens: 700, output_tokens: 4 } }); + } if (url.pathname.endsWith(":generateContent")) { const asked = await request.json() as { contents: Array<{ parts: Array<{ fileData?: { fileUri: string } }> }> }; const fileUri = asked.contents[0]!.parts.find(part => part.fileData)?.fileData?.fileUri; @@ -87,6 +99,18 @@ beforeAll(async () => { export default defineConfig({ modules: { "@schlessera/brain-module-video": {} } }); `); writeFileSync(join(videoBrain, "troy.mp4"), "fictional-video-bytes"); + // A third brain with model reranking enabled, searched by keyword so no embedding is involved. + rerankBrain = join(root, "rerank-brain"); + mkdirSync(join(rerankBrain, "notes"), { recursive: true }); + for (const [name, title] of [["harbour", "Ithaca harbour"], ["palace", "Ithaca palace"], ["grove", "Ithaca olive grove"]]) { + writeFileSync(join(rerankBrain, `notes/${name}.md`), `---\ntype: note\ntitle: ${title}\ncreated: 2026-07-12\nupdated: 2026-07-12\n---\n` + + `Odysseus walks to the ${title} on Ithaca.\n`); + } + writeFileSync(join(rerankBrain, "brain.config.json"), JSON.stringify({ reranker: { enabled: true } })); + const keywordIndex = Bun.spawn([process.execPath, BRAIN_CLI, "index", "--json"], { cwd: root, stdout: "pipe", stderr: "pipe", + env: { PATH: "/usr/bin:/bin", HOME: root, BRAIN_ROOT: rerankBrain, BUN_OPTIONS: "--no-env-file" } }); + const [keywordCode, keywordStderr] = await Promise.all([keywordIndex.exited, new Response(keywordIndex.stderr).text()]); + if (keywordCode !== 0) throw new Error(`brain index failed: ${keywordStderr}`); // Vectors built on the host against the fictional endpoint. Asynchronous: // the endpoint serves from this process while the CLI runs. const index = Bun.spawn([process.execPath, BRAIN_CLI, "index", "--embeddings", "--json"], { cwd: root, stdout: "pipe", stderr: "pipe", @@ -263,6 +287,56 @@ test("a relayed Claude API-key turn's anthropic-haiku completion uses the host k } }); +describe.each(["governed", "strict"] as const)("a %s turn worker's jev reranking (#3792)", (profile) => { + /** Run with the relay's own dispatch to the first-party Jev origin answered by the loopback stand-in. */ + async function reranked(options: Parameters[2] = {}) { + const realFetch = Object.getOwnPropertyDescriptor(globalThis, "fetch")!; + Object.defineProperty(globalThis, "fetch", { ...realFetch, value: (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : input); + if (url.origin !== "https://api.typesafe.ai") return realFetch.value(input, init); + return realFetch.value(`${upstream.url.origin}${url.pathname}`, init); + } }); + seen.length = 0; jevChoice = undefined; + try { + return await run(profile, [process.execPath, BRAIN_CLI, "search", "Ithaca", "--mode", "fts", "--rerank", "jev", "--json"], + // The worker's proxy still admits only loopback: a request that bypassed the relay could not reach the real origin. + { brainPath: rerankBrain, relayEgress: false, ...options }); + } finally { Object.defineProperty(globalThis, "fetch", realFetch); } + } + + test("brain search is reranked through the relay with the host's key, which the worker never held", async () => { + const { exit, stdout, stderr, receipts } = await reranked(); + expect(exit, stderr).toBe(0); + const found = JSON.parse(stdout) as { results: Array<{ path: string; title: string }>; warnings: string[] }; + expect(found.warnings.join("\n"), "RELAYED_JEV_NO_NOTICE").not.toMatch(/provider_unavailable|unavailable|lifecycle order/); + expect(seen.map(request => `${request.method} ${request.path}`), "RELAYED_JEV_REACHED_STAND_IN").toEqual(["POST /v1/systemone"]); + expect(seen[0]!.headers.authorization, "RELAYED_JEV_HOST_KEY_PLACED").toBe(`Bearer ${HOST_KEYS.TYPESAFE_API_KEY}`); + expect(Object.keys(seen[0]!.headers).filter(name => /^(x-api-key|x-brain-provider)/.test(name)), "RELAYED_JEV_NO_WORKER_HEADERS").toEqual([]); + expect(jevChoice).toBeDefined(); + expect(found.results[0]?.title, "RELAYED_JEV_ORDER_APPLIED").toBe(jevChoice!); + expect(receipts, "RELAYED_JEV_METERED").toMatchObject([{ family: "typesafe", operation: "reranking", model: "jev-1.13.0", + origin: "https://api.typesafe.ai", key: "TYPESAFE_API_KEY", outcome: "completed", status: 200, usage: { inputTokens: 700, outputTokens: 4 } }]); + expect(SECRETS.filter(secret => stdout.includes(secret) || stderr.includes(secret)), "RELAYED_JEV_WORKER_SEES_NO_KEY").toEqual([]); + }); + + test("the worker holds no Jev key and names it withheld", async () => { + const { exit, stdout, stderr } = await run(profile, INSPECT, { brainPath: rerankBrain }); + expect(exit, stderr).toBe(0); + const { env } = JSON.parse(stdout) as { env: Record }; + expect(env.TYPESAFE_API_KEY, "RELAYED_JEV_WORKER_HOLDS_NO_KEY").toBeUndefined(); + expect(env.BRAIN_WITHHELD_KEYS?.split(","), "RELAYED_JEV_KEY_NAMED_WITHHELD").toContain("TYPESAFE_API_KEY"); + }); + + test("a blocked budget refuses the reranking before contact and keeps lifecycle order", async () => { + const { exit, stdout, stderr, receipts } = await reranked({ blocked: true }); + expect(exit, stderr).toBe(0); + const found = JSON.parse(stdout) as { results: unknown[]; warnings: string[] }; + expect(found.results.length).toBeGreaterThan(0); + expect(seen, "BLOCKED_JEV_NEVER_CONTACTED").toEqual([]); + expect(receipts).toEqual([]); + }); +}); + test("an operator-listed custom key is named withheld, so the CLI relays it", async () => { const { exit, stdout, stderr } = await run("governed", INSPECT, { customKeys: ["ITHACA_GATEWAY_KEY"] }); expect(exit, stderr).toBe(0); diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index 170a49f0ff..3d955ea2be 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -365,7 +365,7 @@ under the [service terms](../geo/README.md#configuration). | `BRAIN_UI_CLAUDE_DEFAULT_THINKING_LEVEL` | Default Claude reasoning effort (off, minimal, low, medium, high, xhigh, max). Unsupported levels resolve to a supported choice. | medium | | `BRAIN_UI_CLAUDE_PROFILES` | JSON array of extra Anthropic-compatible inference profiles ({id,label,model?,baseUrl?,authTokenEnv?,apiKeyEnv?,modelAliases?}). | (none) | | `BRAIN_UI_CLAUDE_TOKEN_MINTED_AT` | The date CLAUDE_CODE_OAUTH_TOKEN was minted (ISO 8601, e.g. 2026-09-23), set next to the token in the same redeploy. The server counts the token's one-year lifetime from it and warns 30 days before expiry. An invalid date keeps serving with an explicit unknown-expiry warning in owner status and logs. Server-only. | no expiry warning (one WARN at boot says so) | -| `BRAIN_UI_CLI_PROVIDER_ORIGINS` | Extra recipients for the brain CLI's relayed provider keys: KEY=origin[,origin], separated by semicolons. Each origin is an exact https origin (http only for a loopback host). By default the relay sends GEMINI_API_KEY, ANTHROPIC_API_KEY and OPENAI_API_KEY only to their own first-party origins; a custom endpoint or a custom key variable is refused unless listed here. A malformed value stops the server. | (unset; first-party origins only) | +| `BRAIN_UI_CLI_PROVIDER_ORIGINS` | Extra recipients for the brain CLI's relayed provider keys: KEY=origin[,origin], separated by semicolons. Each origin is an exact https origin (http only for a loopback host). By default the relay sends GEMINI_API_KEY, ANTHROPIC_API_KEY, OPENAI_API_KEY and TYPESAFE_API_KEY only to their own first-party origins; a custom endpoint or a custom key variable is refused unless listed here. A malformed value stops the server. | (unset; first-party origins only) | | `BRAIN_UI_COASTLINE` | "0"/"off"/"false" stops the server fetching map geometry. Maps then draw their graticule, pins and scale bar with no coastline, which is still an accurate locator. | enabled | | `BRAIN_UI_COMPUTE_KEYS` | External compute credentials the host may use for hosted jobs (#3108), by built-in provider: semicolon-separated `provider=NAME[,NAME...]` entries, such as `boat=BOAT_CI_KEY,BOAT_HEAVY_KEY`. A listed provider's own default variable is bound too; list it alone (`boat`) to bind only that. A brain.config instance whose apiKeyEnv is not bound here is refused as provider_unavailable. Values are read on the host only and never reach a worker; a bound name that BRAIN_UI_SUBPROCESS_ENV_EXTRA or a profile would forward disables hosted compute. Unset: hosted compute has no credential, not even a provider's default variable. | (empty) | | `BRAIN_UI_COMPUTE_STATE_DIR` | Where hosted external compute keeps job records, leases, reservations and artifacts (#3108). Host operational state, masked from workers. Slots and budgets are shared per directory: point BRAIN_COMPUTE_STATE_DIR of a shell `brain compute` at the same directory to share one pool with it. | .compute | diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 58bb091904..874fe8af29 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -31,7 +31,7 @@ import { type MaintenanceTempKind, runMaintenanceWorkerSync, workerHostProven, hostMaintenanceTempLimits, resolveMaintenanceTempLimits, type WorkerStateLimits, type MaintenanceCommand, type WorkerHostProbe, prepareNativeWorkerStartupView, hasManagedNativeStorage, type WorkerStartupView, acquireHostCredentialExclusion, type HostCredentialDomain, - startProviderRelay, relayedProviderKeys, hostProviderCredential, type ProviderRelay, type ProviderRelayReceipt, + startProviderRelay, relayedProviderKeys, hostProviderCredential, FIRST_PARTY_PROVIDER_RECIPIENTS, type ProviderRelay, type ProviderRelayReceipt, } from "@schlessera/brain-ui-sdk/internal"; import { createKeyedLock, type KeyedLock, killWrapped, wrapCommand, type ExecWrapperConfig } from "@schlessera/brain-ui-sdk/server"; import { markUnpinnedHostWriter, refuseHostFallback, type GateHold, type GateMode, type WriterGate } from "./writer-gate.js"; @@ -181,8 +181,17 @@ export const hostExecution = { const TURN_EGRESS_ACTIVE = "Governed and strict Claude and pi turns run on their own turn egress proxy and the host inference relay. A pi turn whose credential runs a command, or whose provider and credential type the relay does not carry, is refused."; const TURN_EGRESS_INACTIVE = "This brain is not on managed native storage, which the server requires at boot, so the turn egress relay cannot run and every governed and strict turn is refused."; /** Whether the brain CLI's paid providers are relayed (#1673): where provider keys live on this host. */ -const PROVIDERS_RELAYED = "The brain CLI's Gemini, Anthropic and OpenAI image providers go through a metered host relay, in turn and maintenance workers alike: the host holds their keys, records each request's usage and counts it toward the budgets."; +const PROVIDERS_RELAYED = "The brain CLI's Gemini, Anthropic and OpenAI image providers go through a metered host relay, in turn and maintenance workers alike, and so does its JeV reranker in turn workers: the host holds their keys, records each request's usage and counts it toward the budgets."; const PROVIDERS_NOT_RELAYED = "The brain CLI's providers are not relayed here: governed and strict turn workers report them unavailable, and maintenance workers still receive the provider keys, so their spend is unmetered."; +/** + * The keys a credentialed maintenance run reaches only through its relay. The + * JeV key is not one of them unless the operator lists it: such a run's sync + * judge and propagation review call TypeSafe directly (`createJevClient`, + * `packages/core/src/lib/jev.ts`), outside the relay, so the run keeps the key + * as before. Only turn workers relay JeV reranking (#3792). + */ +const maintenanceRelayedKeys = (origins?: ReadonlyMap): string[] => + relayedProviderKeys(origins).filter(name => name !== FIRST_PARTY_PROVIDER_RECIPIENTS.typesafe.key || Boolean(origins?.has(name))); /** Deny direction (#3422): whether `path` is `dir` or below it; a `dir` of `/` holds every absolute path. */ export const within = (dir: string, path: string) => isWithin(dir, path, { trailingSeparator: "boundary" }); const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } }; @@ -455,8 +464,8 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { // A relayed run holds no relayed key: it learns their names and reaches // them through the relay. Keys the relay does not carry stay (#1673). if (relay) { - for (const name of relayedProviderKeys(options.providerRelay?.origins)) delete env[name]; - const held = relayedProviderKeys(options.providerRelay?.origins).filter(name => Boolean(runCredential(execution, name))); + for (const name of maintenanceRelayedKeys(options.providerRelay?.origins)) delete env[name]; + const held = maintenanceRelayedKeys(options.providerRelay?.origins).filter(name => Boolean(runCredential(execution, name))); if (held.length) env.BRAIN_WITHHELD_KEYS = held.join(","); else delete env.BRAIN_WITHHELD_KEYS; } diff --git a/packages/ui-server/src/config/env.ts b/packages/ui-server/src/config/env.ts index 3edd49d6b2..fee669346a 100644 --- a/packages/ui-server/src/config/env.ts +++ b/packages/ui-server/src/config/env.ts @@ -263,7 +263,7 @@ export const ENV_VARS: readonly EnvVarDescriptor[] = [ description: "Extra recipients for the brain CLI's relayed provider keys: KEY=origin[,origin], separated by semicolons. " + "Each origin is an exact https origin (http only for a loopback host). By default the relay sends GEMINI_API_KEY, " + - "ANTHROPIC_API_KEY and OPENAI_API_KEY only to their own first-party origins; a custom endpoint or a custom key " + + "ANTHROPIC_API_KEY, OPENAI_API_KEY and TYPESAFE_API_KEY only to their own first-party origins; a custom endpoint or a custom key " + "variable is refused unless listed here. A malformed value stops the server.", default: "(unset; first-party origins only)", required: false, diff --git a/packages/ui-server/src/pricing/provider-pricing.ts b/packages/ui-server/src/pricing/provider-pricing.ts index c6adea91c2..506c32f9c9 100644 --- a/packages/ui-server/src/pricing/provider-pricing.ts +++ b/packages/ui-server/src/pricing/provider-pricing.ts @@ -5,7 +5,9 @@ * inference. Embeddings are not in either remote catalog, so the built-in * embedding model carries one dated row here. Image usage stays unpriced: its * token classes have per-modality rates no table here holds, and the CLI's own - * per-image estimate is not a provider receipt. An unpriced attempt with + * per-image estimate is not a provider receipt. JeV reranking (#3792) stays + * unpriced too: this table holds no TypeSafe rate, so its reported tokens + * count toward the unpriced-token stops. An unpriced attempt with * reported tokens counts toward the unpriced-token stops; an attempt without * reported usage is unknown spend, never zero, and never blocks by itself. * The one exception is a Gemini Files lifecycle attempt, which the provider diff --git a/packages/ui-server/tests/maintenance-provider-relay.test.ts b/packages/ui-server/tests/maintenance-provider-relay.test.ts index e664382f61..d35a0b0fad 100644 --- a/packages/ui-server/tests/maintenance-provider-relay.test.ts +++ b/packages/ui-server/tests/maintenance-provider-relay.test.ts @@ -90,7 +90,8 @@ for (const method of ["run", "launch"] as const) { expect([DOTENV_KEY, HOST_KEYS.GEMINI_API_KEY, HOST_KEYS.OPENAI_API_KEY, HOST_KEYS.ANTHROPIC_API_KEY] .filter(secret => result.stdout.includes(secret)), "RELAYED_MAINTENANCE_LEAKS_NO_RELAYED_KEY").toEqual([]); expect(observed.dotenv, "RELAYED_MAINTENANCE_DOTENV_MASKED").toBe("EACCES"); - // JeV is not relayed: its key stays with credentialed maintenance (disclosed in status). + // JeV is relayed for turn workers only (#3792): its key stays with credentialed maintenance, whose + // sync judge and propagation review call TypeSafe directly (disclosed in status). expect(observed.env.TYPESAFE_API_KEY).toBe(HOST_KEYS.TYPESAFE_API_KEY); expect(observed.env.BRAIN_PROVIDER_RELAY_SOCKET).toBe("/run/brain-providers/relay.sock"); expect(observed.env.BRAIN_WITHHELD_KEYS, "RELAYED_MAINTENANCE_NAMES_HELD_KEYS").toBe("ANTHROPIC_API_KEY,GEMINI_API_KEY,OPENAI_API_KEY"); diff --git a/packages/ui-server/tests/provider-relay-budgets.test.ts b/packages/ui-server/tests/provider-relay-budgets.test.ts index d1ee05dafa..43f8ae93fe 100644 --- a/packages/ui-server/tests/provider-relay-budgets.test.ts +++ b/packages/ui-server/tests/provider-relay-budgets.test.ts @@ -133,6 +133,26 @@ test("a Gemini Files lifecycle attempt is known to cost nothing, so a relayed vi } finally { f.close(); } }); +test("a relayed jev reranking attempt is metered with its reported tokens, and its unknown price never reads as $0 (#3792)", async () => { + const reranking = (overrides: Partial = {}) => attempt({ family: "typesafe", operation: "reranking", + origin: "https://api.typesafe.ai", key: "TYPESAFE_API_KEY", model: "jev-1.13.0", usage: { inputTokens: 700, outputTokens: 4 }, ...overrides }); + expect(priceProviderAttempt(reranking(), pricing), "JEV_RERANKING_UNPRICED").toEqual({ costUsd: null, estimate: null, tokens: 704 }); + const f = fixture(); + try { + await f.budgets.begin("athena", "ithaca", policy()); + const before = f.budgets.receipt("athena").scopes; + const result = (await f.budgets.observeProvider("athena", reranking()))!; + expect(result.receipt.scopes.map(scope => (scope.tokens ?? 0) - (before.find(prior => prior.scope === scope.scope)!.tokens ?? 0)), + "JEV_RERANKING_TOKENS_IN_EVERY_SCOPE").toEqual([704, 704, 704]); + expect(result.receipt.scopes.map(scope => scope.unknownRuns - before.find(prior => prior.scope === scope.scope)!.unknownRuns), + "JEV_RERANKING_UNKNOWN_SPEND_DISCLOSED").toEqual([1, 1, 1]); + expect(result.receipt.scopes.map(scope => scope.costUsd), "JEV_RERANKING_NEVER_ZERO").toEqual([null, null, null]); + // Without reported usage it is still disclosed, never counted as free. + await f.budgets.observeProvider("athena", reranking({ usage: null, outcome: "failed", status: 502 })); + expect(f.budgets.receipt("athena").scopes[0]!.unknownRuns - before[0]!.unknownRuns).toBe(2); + } finally { f.close(); } +}); + test("a dispatched attempt is unknown spend until it settles, then counts once", async () => { const f = fixture(); try {