Repository Public License
1# AI providers (ProviderKit)23ORIX Navigator works fully without AI. `ProviderKit` is the bring-your-own-key layer that is used only after the4user configures a provider in Settings: until then no provider exists, no default is selected, and nothing in this5module runs or contacts anyone.67Module: `Packages/NavigatorKit/Sources/ProviderKit` (imports Foundation, `NavigatorCore`, `Diagnostics`; no8third-party dependency, never `Persistence`).910> **Not verified with a real key.** No API key was available while this module was written. Every HTTP family is11> tested against scripted responses and an in-process `URLProtocol` stub; **no request has been sent to Anthropic,12> OpenAI, OpenRouter or a real compatible server from this code.** See [What is not verified](#what-is-not-verified).1314## Supported families1516| Family | Wire protocol | Authentication | Model list | Notes |17|---|---|---|---|---|18| **Anthropic** | Messages API, `POST /v1/messages`, SSE | `x-api-key`, `anthropic-version: 2026-10-21` | `GET /v1/models` (paginated) | `tool_use` / `tool_result` blocks, thinking blocks replayed within a tool cycle, cache token usage |19| **OpenAI** | Chat Completions, `POST /v1/chat/completions`, SSE | `Authorization: Bearer` | `GET /v1/models` (chat families only) | `stream_options.include_usage`, `max_completion_tokens`, `reasoning_effort` |20| **OpenRouter** | Chat Completions | `Authorization: Bearer`, `HTTP-Referer`, `X-Title` | `GET /api/v1/models` with per-model prices | `reasoning: {effort}`, reported cost, `GET /key` for remaining credit |21| **Compatible endpoint** | Chat Completions at a base URL the user types | optional `Authorization: Bearer`, optional extra headers | `GET {base}/models` | Ollama, LM Studio, llama.cpp server, vLLM, a self-hosted gateway |22| **On this device** | `LocalModelRuntime` | none | the runtime's loaded/available models | Apple's on-device model where the OS has it; MLX through a separate package (not installed) |2324The model is always a free-form string. `ProviderFamily.suggestedModels` only pre-fills the picker before the live25list is fetched (reviewed 2026-11-25; Anthropic ids from Anthropic's model table, OpenAI ids from the list ORIX Astra26verified on 2026-11-21). Nothing in the code depends on a particular model id.2728### Behaviour worth knowing2930- **Anthropic and `temperature`.** API version `2026-10-21` rejects `temperature`, `top_p` and `top_k`, so the31 Anthropic adapter never sends a sampling parameter; `GenerationOptions.temperature` is ignored for this family.32- **Reasoning effort.** `nil` leaves the provider default. Otherwise: Anthropic gets33 `thinking: {type: "adaptive", display: "summarized"}` plus `output_config.effort`; OpenAI and compatible servers34 get `reasoning_effort`; OpenRouter gets `reasoning: {effort}`.35- **Parameter fallback.** When a server answers 400 naming a parameter it does not accept (`temperature`,36 `reasoning_effort`, `stream_options`, `stop`, `thinking`, `output_config`, `cache_control`,37 `eager_input_streaming`, or `max_tokens` vs `max_completion_tokens`), that parameter is removed or renamed and the38 request is sent again, at most three times. This is not a backoff retry and happens before any output.39- **Anthropic prompt caching.** A conversation with more than one message carries a top-level40 `cache_control: {type: "ephemeral"}` so the resent history is read at the cache price. A single opening message41 is not cached.42- **Thinking blocks.** Anthropic thinking blocks (with their signatures) and OpenRouter `reasoning_details` travel43 as opaque `ToolCall.providerState` and are sent back unchanged with the tool results of the same cycle. Keep the44 assistant message from `ChatResponse.assistantMessage` intact; do not edit or display that state.45- **Refusals.** Anthropic `stop_reason: "refusal"` is reported as `FinishReason.contentFilter`. Server-side model46 fallbacks are not requested.47- **Tool arguments** are untrusted model output. `ToolCall.hasValidArguments` is `false` when the streamed text was48 not a JSON object (for example a call cut off by the token limit); such a call must not be executed. Validating49 arguments against the tool's schema is the caller's job.50- **Images** (screenshots) are sent inline as base64. A screenshot returned by a tool is sent inside the51 `tool_result` on Anthropic and in a following user message on Chat Completions servers.5253## How keys are stored5455- ProviderKit never stores a key. It reads and writes keys only through `ProviderSecretSource`56 (`secret(for:)`, `setSecret(_:for:)`, `deleteSecret(for:)`), which the app backs with the Keychain.57 `SecretStoreSecretSource` adapts NavigatorCore's `SecretStore`, so the app can pass58 `SecretStoreSecretSource(KeychainSecretStore(...))`.59- The account name is `provider.<configuration id>.api-key`.60- `ProviderConfiguration` has no key field. What `ProviderConfigurationStore` persists is non-secret JSON:61 configurations, the default provider id and user-edited prices. A test asserts the saved JSON does not contain62 the key.63- The key is read at request time, so a changed key applies to the next request. Removing a configuration deletes64 its key.65- Keys never appear in logs, errors or `description`s. Error text from a provider goes through `Redactor` and66 through an exact-match scrub of the key in use (a key for a self-hosted server can have any shape). A test feeds67 servers that echo the key back in JSON bodies, plain bodies, stream events and truncated messages, and asserts68 that no error rendering and no log line contains it.69- Custom headers for compatible endpoints cannot be credentials (`Authorization`, `x-api-key`, `Cookie`… are70 refused), because they live in the non-secret configuration.71- Redirects to another host, or from HTTPS to HTTP, are not followed, so custom headers cannot be forwarded to a72 third party.7374## What is sent to a provider, and when7576A request is sent only when the app calls `stream`, `listModels` or `testConnection` on a provider. ProviderKit77never sends anything on its own: no telemetry, no background refresh, no model list fetch at launch.7879| Call | Sent |80|---|---|81| `stream(_:)` | the model id, the system prompt, the messages of the `ChatRequest` (text, inline images, earlier tool calls and tool results), the tool definitions, and the generation options. Nothing else from the browser: page content reaches a provider only if the caller put it in a message. |82| `listModels()` | an authenticated `GET` with no body. For OpenRouter the list is public and the key is sent only if one is stored. |83| `testConnection()` | the same `GET` as the model list (OpenRouter: `GET /key`). No text is generated and no tokens are billed. |8485Fixed headers: the family's authentication header, `Content-Type`, `Accept`, a `User-Agent` of `ORIXNavigator`, and86for OpenRouter `HTTP-Referer: https://www.orixlab.dev` and `X-Title: ORIX Navigator` (its documented attribution87headers). No cookies are stored or sent, and responses are not cached.8889Cancelling the consuming task, or dropping the stream, cancels the HTTP request immediately.9091### HTTP versus HTTPS for compatible endpoints9293`EndpointPolicy.validate(_:allowInsecureHTTP:)`:9495- `https://` is always accepted.96- `http://` is accepted without further consent only when the host is this machine or a private network address:97 `localhost`, `*.localhost`, `*.local`, `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`,98 `169.254.0.0/16`, `100.64.0.0/10`, `::1`, `fc00::/7`, `fe80::/10`. The decision is made from the spelling alone;99 no DNS lookup is done, so a public name that resolves to a private address is not local.100- `http://` to any other host requires the user's explicit opt-in (`allowInsecureHTTP`), because prompts, page101 content and the key would travel unencrypted.102- URLs with credentials, a query or a fragment, and schemes other than http/https, are refused.103- Hosted families (Anthropic, OpenAI, OpenRouter) accept a custom base URL only over HTTPS.104105The rule is checked when a configuration is saved and again on every request.106107**App requirement (not handled here):** App Transport Security blocks plain HTTP by default. The apps need108`NSAllowsLocalNetworking` for local servers, and an opt-in to a public HTTP host additionally needs an ATS109exception; without them the system refuses the connection and the user sees "Insecure endpoint".110111## Reliability112113- **Retries** (`RetryPolicy`, default 3 tries, base 0.5 s doubling, cap 8 s, equal jitter): only for failures that114 can succeed on a second try — HTTP 429 that is a rate limit, 408, 5xx, 529, and connection failures before any115 response. `Retry-After` (seconds, HTTP date, or `retry-after-ms`) is a floor on the wait; a `Retry-After` longer116 than 30 s is not waited for and is reported to the user with the delay.117- **Never retried:** 401, 403, 404, 400/422, quota or billing failures (including a 429 that says so), and anything118 after a 2xx response head. Once the response is accepted nothing is resent, so there is never a retry after the119 first streamed token, and a dropped connection mid-answer is reported instead of silently billed twice.120- **Timeouts:** 30 s idle for JSON requests, 300 s idle for streams (reasoning models can be silent for a long time121 before the first token), one hour for a whole response.122- **Errors:** `ProviderError` — missing key, invalid key, forbidden, rate limited, quota exceeded, model not found,123 context too long, content filtered, invalid request, overloaded, server, network, timeout, insecure endpoint,124 malformed response, unsupported, local, limit exceeded, configuration, cancelled. Each has a `title` and a125 user-presentable `message`. A body that is not JSON (an HTML gateway page) is never shown.126127## Limits128129Per configuration (`ProviderLimits`), enforced by the `MeteredProvider` returned from130`ProviderRegistry.provider(for:space:)` before anything is sent:131132| Limit | Effect |133|---|---|134| `maxOutputTokens` | caps `max_tokens` of every request (a higher request is lowered, an unset one gets the cap) |135| `maxRequestsPerMinute` | sliding 60-second window shared by every use of the configuration; the next request is refused with the wait, not queued |136| `monthlyBudgetUSD` | when the estimated spend of the current calendar month reaches it, requests are refused |137138The monthly budget compares against **estimated** cost (see below). Requests whose cost is unknown do not count,139a request already in flight is not interrupted, and the provider's own invoice may differ. It is a guard rail, not a140guarantee; a hard cap must be set in the provider's console.141142`unmeteredProvider(for:)` (settings screen: test connection, model list) applies no limits and records nothing.143144The agent's own budget (`AgentBudget` in NavigatorCore: steps, duration, tokens, cost) is enforced by the agent145runtime, using the usage and estimates this module reports.146147## Usage and cost estimates148149- **Token usage comes only from provider metadata.** `ProviderUsage` fields are optional; a provider that reports150 nothing yields no `usage` event, `ChatResponse.usage == nil`, and a ledger record counted under151 `requestsWithUnknownUsage`. Tokens are never estimated from text length. `inputTokens` includes cached tokens;152 `cacheReadTokens` and `cacheWriteTokens` are the cached parts.153- **Costs are estimates and are labelled as such** (`CostEstimate.label` always contains "estimate"). Sources, in154 order: the cost OpenRouter reports with the response; OpenRouter's live per-model prices (kept after155 `refreshModels(for:)` or `MeteredProvider.listModels()`); a user-edited price; the built-in table.156- **The built-in table is small and ages.** It holds list prices for a handful of Anthropic models (read157 2026-11-03) and four OpenAI models (read 2026-11-21 by ORIX Astra), standard tier, in USD per million tokens.158 It ignores batch discounts, priority or fast tiers, regional pricing, long-prompt tiers (Claude Haiku 5.5 above159 100,000 prompt tokens), taxes and credits. Every entry can be replaced with `setUserPrice`.160- **No price, no estimate.** A model without an entry, a compatible endpoint, and on-device models have no cost161 estimate; totals count them under `requestsWithUnknownCost`, and `UsageTotals.estimatedCostUSD` is then a lower162 bound.163- **Ledger.** `UsageLedger` records one `UsageRecord` per request that reached a provider (failed and cancelled164 ones included, since tokens reported before the interruption were consumed) and returns totals per provider and165 per Orbit space. `InMemoryUsageLedger` lasts for the process; the app can implement the protocol over its166 database to keep history, which the monthly budget needs in order to survive a relaunch.167168## Local models169170`DeviceCapability.current` reads physical memory and platform. Local models are offered only on a real device with171at least 8 GB of memory (threshold 7 GB, because "8 GB" devices report slightly less). A model may claim at most17260 % of physical memory on macOS and 40 % on iOS/iPadOS; a runtime's `memoryRequirement(for:)` above that is refused173before loading.174175`LocalCapabilityReport.make(runtimes:device:)` (also `ProviderRegistry.localCapabilityReport()`) is what the176settings screen shows. It always contains an Apple row and an MLX row, built from facts: a runtime that was not177handed to the registry is reported as not installed.178179### Apple on-device model180181The SDK used to build this package (Xcode 27.2) contains `FoundationModels.framework` for macOS and iOS (26.0+),182so `FoundationModelsRuntime` is compiled behind `#if canImport(FoundationModels)` and created only behind183`if #available(macOS 26.0, iOS 26.0, visionOS 26.0, *)`; the package still deploys to macOS 15 / iOS 18, where184`AppleOnDeviceModel.makeRuntime()` returns `nil` and `unavailableReason` says why. At run time the system's own185`SystemLanguageModel.default.availability` is reported as it is: device not eligible, Apple Intelligence turned186off, or model still downloading.187188Stated limits of this runtime: text only; **no tool calling** (the framework runs tools itself from compile-time189types and does not hand calls back, so a request with tools is refused with a clear error — it cannot drive the190browser agent); no token usage (none is reported, so none is shown); earlier turns are passed as a labelled191transcript in the prompt; a small system-managed context window.192193### The MLX seam194195This package has a no-third-party-dependency rule, and MLX is a third-party dependency, so **MLX is not linked and196no MLX model can run today.** The capability report says exactly "MLX runtime not installed", and a configuration197that names the MLX runtime fails with that message.198199The seam is the `LocalModelRuntime` protocol. A separate optional package (for example `NavigatorMLX`, depending200on `mlx-swift`, a tokenizer package and `ProviderKit`) would implement it with `id == LocalRuntimeIdentifier.mlx`:201202| Requirement | What the MLX package implements |203|---|---|204| `availability()` | Metal device present, not the Simulator, at least one model on disk |205| `availableModels()` | models already downloaded (never a remote catalogue), with context length and whether the chat template supports tools |206| `memoryRequirement(for:)` | weights on disk plus KV-cache and working memory at the configured context length |207| `load(modelID:)` / `unload(modelID:)` | map weights, build the tokenizer; release them and clear the GPU cache (also on memory warnings) |208| `generate(_:)` | apply the model's chat template to `ChatRequest` (system, messages, tools), sample with `GenerationOptions`, yield `textDelta` per decoded token, parse tool calls in the template's format into `toolCallCompleted`, emit `usage` from real token counts, then `finished`; stop when the stream is terminated |209210It would also own model download, storage and licence display, which are outside this module. The app then passes211the runtime in `ProviderRegistry(localRuntimes:)`; no change to ProviderKit is needed. Owner reference for such an212implementation: `ORIXAstra/Packages/AstraLocal`.213214## Public API in brief215216```swift217// Configure (settings UI)218let registry = ProviderRegistry(store: appStore, secrets: SecretStoreSecretSource(keychain),219 ledger: appLedger, localRuntimes: [AppleOnDeviceModel.makeRuntime()].compactMap { $0 })220try await registry.load()221try await registry.upsert(ProviderConfiguration(family: .anthropic, model: "claude-opus-5-5",222 limits: ProviderLimits(maxOutputTokens: 8_000, monthlyBudgetUSD: 20)))223try await registry.setAPIKey(typedKey, for: id)224let report = try await registry.unmeteredProvider(for: id).testConnection()225let models = try await registry.refreshModels(for: id)226227// Generate (assistant, agent runtime)228let provider = try await registry.provider(for: id, space: spaceID)229for try await event in provider.stream(provider.request(system: prompt, messages: messages, tools: tools)) { … }230```231232## What is not verified233234- **Live calls.** No request has been made to any real provider or local server; there was no key. Request shapes235 follow ORIX Astra's provider layer (which was exercised live on 2026-11-21) and the public API documentation, but236 for OpenAI this module uses Chat Completions where Astra uses the Responses API, so that adapter has no live237 precedent at all. The first run with a real key should check, per family: a plain answer, a tool call round trip,238 a screenshot, usage numbers, a wrong key, and a wrong model id.239- **Suggested model ids and built-in prices** were not checked against live model lists or price pages on the day240 of writing; they come from the sources and dates named above.241- **Apple on-device generation.** The runtime compiles for macOS and iOS and its availability check runs in the242 tests, but no text was generated with it (the test only asserts that availability and the model list agree).243- **MLX.** Nothing exists beyond the protocol and the documentation above.244- **iOS.** The target compiles for iOS (`xcodebuild -scheme ProviderKit -destination 'generic/platform=iOS'`); the245 tests ran on macOS only, and nothing ran on a device or simulator.246- **App Transport Security** behaviour for plain-HTTP endpoints depends on the apps' Info.plist and was not tested.247- **Monthly budget across relaunches** depends on a persistent `UsageLedger`, which the app has yet to provide.248- **Proxies, HTTP/3, very long streams and real network interruptions** were only simulated.249