SPB Git

Repository Public License

AI_PROVIDERS.md 18.1 KB

# AI providers (ProviderKit)

ORIX Navigator works fully without AI. ProviderKit is the bring-your-own-key layer that is used only after the user configures a provider in Settings: until then no provider exists, no default is selected, and nothing in this module runs or contacts anyone.

Module: Packages/NavigatorKit/Sources/ProviderKit (imports Foundation, NavigatorCore, Diagnostics; no third-party dependency, never Persistence).

Not verified with a real key. No API key was available while this module was written. Every HTTP family is tested against scripted responses and an in-process URLProtocol stub; no request has been sent to Anthropic, OpenAI, OpenRouter or a real compatible server from this code. See What is not verified.

# Supported families

Family Wire protocol Authentication Model list Notes
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
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
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
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
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)

The model is always a free-form string. ProviderFamily.suggestedModels only pre-fills the picker before the live list is fetched (reviewed 2026-11-25; Anthropic ids from Anthropic's model table, OpenAI ids from the list ORIX Astra verified on 2026-11-21). Nothing in the code depends on a particular model id.

# Behaviour worth knowing

  • Anthropic and temperature. API version 2026-10-21 rejects temperature, top_p and top_k, so the Anthropic adapter never sends a sampling parameter; GenerationOptions.temperature is ignored for this family.
  • Reasoning effort. nil leaves the provider default. Otherwise: Anthropic gets thinking: {type: "adaptive", display: "summarized"} plus output_config.effort; OpenAI and compatible servers get reasoning_effort; OpenRouter gets reasoning: {effort}.
  • Parameter fallback. When a server answers 400 naming a parameter it does not accept (temperature, reasoning_effort, stream_options, stop, thinking, output_config, cache_control, eager_input_streaming, or max_tokens vs max_completion_tokens), that parameter is removed or renamed and the request is sent again, at most three times. This is not a backoff retry and happens before any output.
  • Anthropic prompt caching. A conversation with more than one message carries a top-level cache_control: {type: "ephemeral"} so the resent history is read at the cache price. A single opening message is not cached.
  • Thinking blocks. Anthropic thinking blocks (with their signatures) and OpenRouter reasoning_details travel as opaque ToolCall.providerState and are sent back unchanged with the tool results of the same cycle. Keep the assistant message from ChatResponse.assistantMessage intact; do not edit or display that state.
  • Refusals. Anthropic stop_reason: "refusal" is reported as FinishReason.contentFilter. Server-side model fallbacks are not requested.
  • Tool arguments are untrusted model output. ToolCall.hasValidArguments is false when the streamed text was not a JSON object (for example a call cut off by the token limit); such a call must not be executed. Validating arguments against the tool's schema is the caller's job.
  • Images (screenshots) are sent inline as base64. A screenshot returned by a tool is sent inside the tool_result on Anthropic and in a following user message on Chat Completions servers.

# How keys are stored

  • ProviderKit never stores a key. It reads and writes keys only through ProviderSecretSource (secret(for:), setSecret(_:for:), deleteSecret(for:)), which the app backs with the Keychain. SecretStoreSecretSource adapts NavigatorCore's SecretStore, so the app can pass SecretStoreSecretSource(KeychainSecretStore(...)).
  • The account name is provider.<configuration id>.api-key.
  • ProviderConfiguration has no key field. What ProviderConfigurationStore persists is non-secret JSON: configurations, the default provider id and user-edited prices. A test asserts the saved JSON does not contain the key.
  • The key is read at request time, so a changed key applies to the next request. Removing a configuration deletes its key.
  • Keys never appear in logs, errors or descriptions. Error text from a provider goes through Redactor and through an exact-match scrub of the key in use (a key for a self-hosted server can have any shape). A test feeds servers that echo the key back in JSON bodies, plain bodies, stream events and truncated messages, and asserts that no error rendering and no log line contains it.
  • Custom headers for compatible endpoints cannot be credentials (Authorization, x-api-key, Cookie… are refused), because they live in the non-secret configuration.
  • Redirects to another host, or from HTTPS to HTTP, are not followed, so custom headers cannot be forwarded to a third party.

# What is sent to a provider, and when

A request is sent only when the app calls stream, listModels or testConnection on a provider. ProviderKit never sends anything on its own: no telemetry, no background refresh, no model list fetch at launch.

Call Sent
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.
listModels() an authenticated GET with no body. For OpenRouter the list is public and the key is sent only if one is stored.
testConnection() the same GET as the model list (OpenRouter: GET /key). No text is generated and no tokens are billed.

Fixed headers: the family's authentication header, Content-Type, Accept, a User-Agent of ORIXNavigator, and for OpenRouter HTTP-Referer: https://www.orixlab.dev and X-Title: ORIX Navigator (its documented attribution headers). No cookies are stored or sent, and responses are not cached.

Cancelling the consuming task, or dropping the stream, cancels the HTTP request immediately.

# HTTP versus HTTPS for compatible endpoints

EndpointPolicy.validate(_:allowInsecureHTTP:):

  • https:// is always accepted.
  • http:// is accepted without further consent only when the host is this machine or a private network address: localhost, *.localhost, *.local, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16, 100.64.0.0/10, ::1, fc00::/7, fe80::/10. The decision is made from the spelling alone; no DNS lookup is done, so a public name that resolves to a private address is not local.
  • http:// to any other host requires the user's explicit opt-in (allowInsecureHTTP), because prompts, page content and the key would travel unencrypted.
  • URLs with credentials, a query or a fragment, and schemes other than http/https, are refused.
  • Hosted families (Anthropic, OpenAI, OpenRouter) accept a custom base URL only over HTTPS.

The rule is checked when a configuration is saved and again on every request.

App requirement (not handled here): App Transport Security blocks plain HTTP by default. The apps need NSAllowsLocalNetworking for local servers, and an opt-in to a public HTTP host additionally needs an ATS exception; without them the system refuses the connection and the user sees "Insecure endpoint".

# Reliability

  • Retries (RetryPolicy, default 3 tries, base 0.5 s doubling, cap 8 s, equal jitter): only for failures that can succeed on a second try — HTTP 429 that is a rate limit, 408, 5xx, 529, and connection failures before any response. Retry-After (seconds, HTTP date, or retry-after-ms) is a floor on the wait; a Retry-After longer than 30 s is not waited for and is reported to the user with the delay.
  • Never retried: 401, 403, 404, 400/422, quota or billing failures (including a 429 that says so), and anything after a 2xx response head. Once the response is accepted nothing is resent, so there is never a retry after the first streamed token, and a dropped connection mid-answer is reported instead of silently billed twice.
  • Timeouts: 30 s idle for JSON requests, 300 s idle for streams (reasoning models can be silent for a long time before the first token), one hour for a whole response.
  • Errors: ProviderError — missing key, invalid key, forbidden, rate limited, quota exceeded, model not found, context too long, content filtered, invalid request, overloaded, server, network, timeout, insecure endpoint, malformed response, unsupported, local, limit exceeded, configuration, cancelled. Each has a title and a user-presentable message. A body that is not JSON (an HTML gateway page) is never shown.

# Limits

Per configuration (ProviderLimits), enforced by the MeteredProvider returned from ProviderRegistry.provider(for:space:) before anything is sent:

Limit Effect
maxOutputTokens caps max_tokens of every request (a higher request is lowered, an unset one gets the cap)
maxRequestsPerMinute sliding 60-second window shared by every use of the configuration; the next request is refused with the wait, not queued
monthlyBudgetUSD when the estimated spend of the current calendar month reaches it, requests are refused

The monthly budget compares against estimated cost (see below). Requests whose cost is unknown do not count, a request already in flight is not interrupted, and the provider's own invoice may differ. It is a guard rail, not a guarantee; a hard cap must be set in the provider's console.

unmeteredProvider(for:) (settings screen: test connection, model list) applies no limits and records nothing.

The agent's own budget (AgentBudget in NavigatorCore: steps, duration, tokens, cost) is enforced by the agent runtime, using the usage and estimates this module reports.

# Usage and cost estimates

  • Token usage comes only from provider metadata. ProviderUsage fields are optional; a provider that reports nothing yields no usage event, ChatResponse.usage == nil, and a ledger record counted under requestsWithUnknownUsage. Tokens are never estimated from text length. inputTokens includes cached tokens; cacheReadTokens and cacheWriteTokens are the cached parts.
  • Costs are estimates and are labelled as such (CostEstimate.label always contains "estimate"). Sources, in order: the cost OpenRouter reports with the response; OpenRouter's live per-model prices (kept after refreshModels(for:) or MeteredProvider.listModels()); a user-edited price; the built-in table.
  • The built-in table is small and ages. It holds list prices for a handful of Anthropic models (read 2026-11-03) and four OpenAI models (read 2026-11-21 by ORIX Astra), standard tier, in USD per million tokens. It ignores batch discounts, priority or fast tiers, regional pricing, long-prompt tiers (Claude Haiku 5.5 above 100,000 prompt tokens), taxes and credits. Every entry can be replaced with setUserPrice.
  • No price, no estimate. A model without an entry, a compatible endpoint, and on-device models have no cost estimate; totals count them under requestsWithUnknownCost, and UsageTotals.estimatedCostUSD is then a lower bound.
  • Ledger. UsageLedger records one UsageRecord per request that reached a provider (failed and cancelled ones included, since tokens reported before the interruption were consumed) and returns totals per provider and per Orbit space. InMemoryUsageLedger lasts for the process; the app can implement the protocol over its database to keep history, which the monthly budget needs in order to survive a relaunch.

# Local models

DeviceCapability.current reads physical memory and platform. Local models are offered only on a real device with at least 8 GB of memory (threshold 7 GB, because "8 GB" devices report slightly less). A model may claim at most 60 % of physical memory on macOS and 40 % on iOS/iPadOS; a runtime's memoryRequirement(for:) above that is refused before loading.

LocalCapabilityReport.make(runtimes:device:) (also ProviderRegistry.localCapabilityReport()) is what the settings screen shows. It always contains an Apple row and an MLX row, built from facts: a runtime that was not handed to the registry is reported as not installed.

# Apple on-device model

The SDK used to build this package (Xcode 27.2) contains FoundationModels.framework for macOS and iOS (26.0+), so FoundationModelsRuntime is compiled behind #if canImport(FoundationModels) and created only behind if #available(macOS 26.0, iOS 26.0, visionOS 26.0, *); the package still deploys to macOS 15 / iOS 18, where AppleOnDeviceModel.makeRuntime() returns nil and unavailableReason says why. At run time the system's own SystemLanguageModel.default.availability is reported as it is: device not eligible, Apple Intelligence turned off, or model still downloading.

Stated limits of this runtime: text only; no tool calling (the framework runs tools itself from compile-time types and does not hand calls back, so a request with tools is refused with a clear error — it cannot drive the browser agent); no token usage (none is reported, so none is shown); earlier turns are passed as a labelled transcript in the prompt; a small system-managed context window.

# The MLX seam

This package has a no-third-party-dependency rule, and MLX is a third-party dependency, so MLX is not linked and no MLX model can run today. The capability report says exactly "MLX runtime not installed", and a configuration that names the MLX runtime fails with that message.

The seam is the LocalModelRuntime protocol. A separate optional package (for example NavigatorMLX, depending on mlx-swift, a tokenizer package and ProviderKit) would implement it with id == LocalRuntimeIdentifier.mlx:

Requirement What the MLX package implements
availability() Metal device present, not the Simulator, at least one model on disk
availableModels() models already downloaded (never a remote catalogue), with context length and whether the chat template supports tools
memoryRequirement(for:) weights on disk plus KV-cache and working memory at the configured context length
load(modelID:) / unload(modelID:) map weights, build the tokenizer; release them and clear the GPU cache (also on memory warnings)
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

It would also own model download, storage and licence display, which are outside this module. The app then passes the runtime in ProviderRegistry(localRuntimes:); no change to ProviderKit is needed. Owner reference for such an implementation: ORIXAstra/Packages/AstraLocal.

# Public API in brief

swift
// Configure (settings UI)
let registry = ProviderRegistry(store: appStore, secrets: SecretStoreSecretSource(keychain),
                                ledger: appLedger, localRuntimes: [AppleOnDeviceModel.makeRuntime()].compactMap { $0 })
try await registry.load()
try await registry.upsert(ProviderConfiguration(family: .anthropic, model: "claude-opus-5-5",
                                                limits: ProviderLimits(maxOutputTokens: 8_000, monthlyBudgetUSD: 20)))
try await registry.setAPIKey(typedKey, for: id)
let report = try await registry.unmeteredProvider(for: id).testConnection()
let models = try await registry.refreshModels(for: id)

// Generate (assistant, agent runtime)
let provider = try await registry.provider(for: id, space: spaceID)
for try await event in provider.stream(provider.request(system: prompt, messages: messages, tools: tools)) { … }

# What is not verified

  • Live calls. No request has been made to any real provider or local server; there was no key. Request shapes follow ORIX Astra's provider layer (which was exercised live on 2026-11-21) and the public API documentation, but for OpenAI this module uses Chat Completions where Astra uses the Responses API, so that adapter has no live precedent at all. The first run with a real key should check, per family: a plain answer, a tool call round trip, a screenshot, usage numbers, a wrong key, and a wrong model id.
  • Suggested model ids and built-in prices were not checked against live model lists or price pages on the day of writing; they come from the sources and dates named above.
  • Apple on-device generation. The runtime compiles for macOS and iOS and its availability check runs in the tests, but no text was generated with it (the test only asserts that availability and the model list agree).
  • MLX. Nothing exists beyond the protocol and the documentation above.
  • iOS. The target compiles for iOS (xcodebuild -scheme ProviderKit -destination 'generic/platform=iOS'); the tests ran on macOS only, and nothing ran on a device or simulator.
  • App Transport Security behaviour for plain-HTTP endpoints depends on the apps' Info.plist and was not tested.
  • Monthly budget across relaunches depends on a persistent UsageLedger, which the app has yet to provide.
  • Proxies, HTTP/3, very long streams and real network interruptions were only simulated.
Files main
Menu

Theme