evOo-local/packages/adapters/src/pi-local-provider.ts
cynarAI b78eff1f7b
Run on the deployment's local models without any model choice, preselect Claude Opus 5.5 otherwise, explain why dictation is unavailable (#151)
* Recommend Claude Opus 5.5 by bumping the Pi model catalog

The pinned pi-ai 0.85.1 had no Claude Opus 5.5, so the connect flow fell
back to Opus 5. pi-ai and pi-agent-core 0.87.1 add it, and the keyless
recommendation now preselects it.

The new catalog names router aliases "Qwen Max Latest (Qwen3.8 Max)";
those now read "(auto-updates)" like the other alias labels, so no
picker entry claims to be "latest".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Name HTTPS as the cause when dictation is unavailable, and translate it

Over plain HTTP on a LAN address, Safari hides the microphone and speech
recognition, so voice mode said the browser had no dictation, in English
inside a German UI. Dictation now checks for a secure context first and
says to open the address with https://. Its other errors go through
Lingui too, and Safari's blocked recognizer gets a clear message instead
of "Dictation failed: not-allowed".

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Serve a fake Kokoro voice server in the E2E harness

Onboarding's voice step connects to the local Kokoro server on its
default port, so the shell E2E failed on any machine where nothing (or a
misbehaving server) listened there: the failed request shows up as a
browser console error. The harness now starts an offline stand-in and
points KOKORO_BASE_URL at it, so the suite no longer depends on the
runner host's own voice server.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Show only the recommended sign-in until a model is connected

With no model connected, "Connect model" opened the full model settings:
provider list, tiers and a model picker, even though the recommendation
was already preselected. Until something is connected, the Models panel
now shows just the preselected model with its sign-in and API key field;
"Other providers" reveals the full settings.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Give the second chart-links test the same cold-load allowance as the first

Each Playwright test runs in a fresh browser context, so the second test's
first navigation re-fetches the lazily imported Plot chunk just like the
first test's warm-up does. On a loaded CI runner that exceeded the default
20 s expect timeout.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Use the recommended model as the Anthropic deployment default

A deployment that sets only ANTHROPIC_API_KEY and PI_DEFAULT_PROVIDER=anthropic
now runs Claude Opus 5.5, the same model the connect flow preselects, instead
of an older default.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Run every space on the deployment's local models without a connect step

A deployment with PI_DEFAULT_PROVIDER=local and RAKAZO_LOCAL_MODELS set still
asked every user to connect a model, because only OpenRouter and Anthropic
counted as a deployment model. Configured local models now do, keylessly.

RAKAZO_LOCAL_TIERS assigns local models to the tiers the agent delegates to,
for spaces that have not mapped their own, and a RAKAZO_LOCAL_MODELS entry can
name its own server (id=url) when the models run behind different endpoints.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Hide model choices when the deployment routes models itself

When the server provides its own models, the system picks and routes
them per task, so Settings no longer offers Models and bot settings no
longer offer Model and Thinking, on web and mobile.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Wait for the workspace pane's width transition before measuring it

The pane animates its width over 300 ms, so a single boundingBox read
right after it opens can land mid-transition on a slow runner.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

* Allow chart re-renders inside the chart-links loops to take longer

Each navigation in the loops renders Observable Plot again. On a loaded
CI runner that exceeded the default expect timeout even after the
warm-up, so the per-iteration visibility checks get 30 s.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KWEAjTw26eRf3ZXTXfRjmD

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-05 23:18:40 +02:00

156 lines
5.6 KiB
TypeScript

import {
createProvider,
type Model,
type MutableModels,
type Provider,
} from "@earendil-works/pi-ai";
import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
import { type ModelTier, ModelTierSchema } from "@rakazo/contracts";
import { declaredVisionModelIds, inputModalities } from "./model-modalities.js";
/**
* Local OpenAI-compatible model server (Ollama, LM Studio, llama.cpp, MLX).
*
* Pi's built-in catalog only ships hosted providers, so a model running on the
* operator's own machine has no catalog entry to select. This registers one
* from environment configuration. The server is keyless: `resolve` returns a
* placeholder because OpenAI-compatible local servers ignore the header, but
* Models treats a provider with no resolvable auth as unconfigured and hides
* its models.
*/
export const LOCAL_PROVIDER_ID = "local";
/** Placeholder sent as the key: local servers ignore it, and it is distinct enough to redact safely. */
export const LOCAL_API_KEY = "rakazo-local-model-server";
/** Model ids the local server serves with vision, declared by the operator. */
export const LOCAL_VISION_MODELS_ENV = "RAKAZO_LOCAL_VISION_MODELS";
export function localVisionModelIds(): ReadonlySet<string> {
return declaredVisionModelIds(LOCAL_VISION_MODELS_ENV);
}
const DEFAULT_BASE_URL = "http://127.0.0.1:11434/v1";
const DEFAULT_CONTEXT_WINDOW = 32_768;
const DEFAULT_MAX_TOKENS = 4_096;
export function localBaseUrl(): string {
return checkedUrl(process.env.RAKAZO_LOCAL_MODELS_URL?.trim() || DEFAULT_BASE_URL);
}
function checkedUrl(value: string, name = "RAKAZO_LOCAL_MODELS_URL"): string {
let url: URL;
try {
url = new URL(value);
} catch {
throw new Error(`${name} must be an absolute HTTP(S) URL`);
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error(`${name} must be an absolute HTTP(S) URL`);
}
return value;
}
/**
* A token count from the environment, or the default when unset.
*
* Token limits are only meaningful as finite positive integers, so anything
* else is a configuration mistake. Throwing beats `Number(x) || default`, which
* would accept a negative window and silently swallow a typo as the default.
*/
function tokenLimit(name: string, fallback: number): number {
const raw = process.env[name]?.trim();
if (!raw) return fallback;
const value = Number(raw);
if (!Number.isSafeInteger(value) || value <= 0) {
throw new Error(`${name} must be a positive integer, received "${raw}"`);
}
return value;
}
/**
* Comma-separated model ids exactly as the local server names them. An entry may name its own
* server as `id=url` when the models run behind different endpoints.
*/
function localModelEntries(env: NodeJS.ProcessEnv): { id: string; baseUrl?: string }[] {
return (env.RAKAZO_LOCAL_MODELS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => {
const separator = entry.indexOf("=");
if (separator < 0) return { id: entry };
return { id: entry.slice(0, separator).trim(), baseUrl: entry.slice(separator + 1).trim() };
});
}
export function localModelIds(env: NodeJS.ProcessEnv = process.env): string[] {
return localModelEntries(env).map((entry) => entry.id);
}
/**
* The deployment's tiers served by local models, from `RAKAZO_LOCAL_TIERS` (`tier=id,…`).
* Entries naming an unknown tier or a model outside `RAKAZO_LOCAL_MODELS` are ignored.
*/
export function localTierModels(
env: NodeJS.ProcessEnv = process.env,
): Partial<Record<ModelTier, string>> {
const ids = new Set(localModelIds(env));
const tiers: Partial<Record<ModelTier, string>> = {};
for (const entry of (env.RAKAZO_LOCAL_TIERS ?? "").split(",")) {
const [tier, id] = entry.split("=").map((part) => part.trim());
const parsed = ModelTierSchema.safeParse(tier);
if (parsed.success && id && ids.has(id)) tiers[parsed.data] = id;
}
return tiers;
}
function localModel(entry: { id: string; baseUrl?: string }): Model<"openai-completions"> {
const { id } = entry;
return {
id,
name: id,
api: "openai-completions",
provider: LOCAL_PROVIDER_ID,
baseUrl: entry.baseUrl
? checkedUrl(entry.baseUrl, `The RAKAZO_LOCAL_MODELS URL for ${id}`)
: localBaseUrl(),
reasoning: false,
compat: { supportsDeveloperRole: false, supportsReasoningEffort: false },
input: inputModalities(localVisionModelIds().has(id)),
// Runs on the operator's own hardware, so there is nothing to bill.
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: tokenLimit("RAKAZO_LOCAL_CONTEXT_WINDOW", DEFAULT_CONTEXT_WINDOW),
maxTokens: tokenLimit("RAKAZO_LOCAL_MAX_TOKENS", DEFAULT_MAX_TOKENS),
};
}
/** The provider, or undefined when no local models are configured. */
export function localProvider(): Provider | undefined {
const entries = localModelEntries(process.env);
if (!entries.length) return undefined;
return createProvider({
id: LOCAL_PROVIDER_ID,
name: "Local (Ollama / LM Studio)",
baseUrl: localBaseUrl(),
auth: {
apiKey: {
name: "Local model server",
resolve: async () => ({
auth: { apiKey: LOCAL_API_KEY, baseUrl: localBaseUrl() },
source: "local model server",
}),
},
},
models: entries.map(localModel),
api: openAICompletionsApi(),
});
}
/** Register the local provider on a Models collection. No-op when unconfigured. */
export function registerLocalProvider(models: MutableModels): MutableModels {
const provider = localProvider();
if (provider) models.setProvider(provider);
return models;
}