Multiplayer agent harness for work.
feat: add admin-managed model definitions
Josh Franceb8e3c15083b6
diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.ymlindex 9c3575b6b..ee33caf05 100644--- a/.github/workflows/cicd.yml+++ b/.github/workflows/cicd.yml@@ -174,6 +174,10 @@ jobs:env:DATABASE_URL: postgres://postgres:postgres@localhost:5432/qmrun: npm run test:pg+ - name: Model registry cross-process tests+ env:+ MODEL_OVERLAY_TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/qm+ run: node --experimental-test-module-mocks --test test/model-overlay-postgres.test.ts- name: Memorable provider e2e (real CLI against Postgres)env:MEMORABLE_E2E_DB_URL: postgres://postgres:postgres@localhost:5432/qmdiff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex 2a1a7658f..4be72e354 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -4982,6 +4982,91 @@><span class="status" id="st-onboarding-model"></span></div></section>+ <section class="card">+ <div class="head">+ <h2>Models on existing providers</h2>+ <p>+ Add an API model using an existing provider and a compatible builtin template. Endpoint and+ credentials are inherited. Available through Pi; subscription support is not implied.+ </p>+ </div>+ <div class="body">+ <table class="table">+ <thead>+ <tr>+ <th>Model</th>+ <th>Provider</th>+ <th>Template</th>+ <th></th>+ </tr>+ </thead>+ <tbody id="model-registry-rows"></tbody>+ </table>+ <p class="muted" id="model-registry-empty">No additional models.</p>+ </div>+ <div class="body setup-form">+ <label>Model id <input type="text" id="model-registry-id" autocomplete="off" required /></label>+ <label>Display name <input type="text" id="model-registry-name" autocomplete="off" required /></label>+ <label+ >Provider+ <select id="model-registry-provider">+ <option value="openai">OpenAI</option>+ <option value="anthropic">Anthropic</option>+ </select></label+ >+ <label+ >Compatible builtin template+ <select id="model-registry-template"></select+ ></label>+ <p class="muted" id="model-registry-capabilities"></p>+ <label+ >Context window (tokens)+ <input id="model-registry-contextWindow" type="number" min="2" step="1" required+ /></label>+ <label+ >Maximum output (tokens) <input id="model-registry-maxTokens" type="number" min="1" step="1" required+ /></label>+ <label+ >Input ($ / million tokens)+ <input id="model-registry-input" type="number" min="0" step="any" required+ /></label>+ <label+ >Output ($ / million tokens)+ <input id="model-registry-output" type="number" min="0" step="any" required+ /></label>+ <label+ >Cache read ($ / million tokens)+ <input id="model-registry-cacheRead" type="number" min="0" step="any" required+ /></label>+ <label+ >Cache write ($ / million tokens)+ <input id="model-registry-cacheWrite" type="number" min="0" step="any" required+ /></label>+ <label class="check"+ ><input id="model-registry-base" type="checkbox" checked /> Offer in admin model choices</label+ >+ <label class="check"+ ><input id="model-registry-webui" type="checkbox" checked /> Offer in web picker by default</label+ >+ <label class="check"+ ><input id="model-registry-fastMode" type="checkbox" /> Model supports the Anthropic fast tier</label+ >+ <label class="check"+ ><input id="model-registry-auxiliary" type="checkbox" /> Eligible for auxiliary tasks</label+ >+ <details>+ <summary>Advanced pricing tiers</summary>+ <label+ >JSON array of inputTokensAbove, input, output, cacheRead and cacheWrite+ <textarea id="model-registry-tiers" rows="4" placeholder="[]"></textarea>+ </label>+ </details>+ </div>+ <div class="foot">+ <button class="primary" id="model-registry-save">Save model</button+ ><button id="model-registry-new">New model</button><span class="status" id="st-model-registry"></span>+ </div>+ </section><section class="card"><div class="head"><h2>Custom providers</h2>@@ -8764,6 +8849,7 @@: "Write-only API key";}async function loadOnboarding() {+ await loadModelRegistry();const [models, slack, catalog, config] = await Promise.all([api("GET", "/api/model-providers"),api("GET", "/api/slack-installation"),@@ -8869,6 +8955,127 @@await loadCustomProviders();setStatus("st-onboarding-model", "Provider disabled.", "ok");};+ let modelRegistryTemplates = [];+ function modelRegistryTemplateOptions() {+ const select = $("model-registry-template");+ const previous = select.value;+ select.replaceChildren();+ for (const template of modelRegistryTemplates.filter(+ (m) => m.provider === $("model-registry-provider").value,+ )) {+ const option = document.createElement("option");+ option.value = template.id;+ option.textContent = template.name;+ select.appendChild(option);+ }+ if ([...select.options].some((option) => option.value === previous)) select.value = previous;+ modelRegistryCapabilities();+ }+ function modelRegistryCapabilities() {+ const template = modelRegistryTemplates.find((m) => m.id === $("model-registry-template").value);+ $("model-registry-capabilities").textContent = template+ ? `Inherited: ${template.input.join(", ")} input; reasoning ${template.reasoning ? "yes" : "no"}.`+ : "";+ }+ function editRegistryModel(spec) {+ $("model-registry-id").disabled = Boolean(spec);+ $("model-registry-provider").disabled = Boolean(spec?.provider);+ $("model-registry-provider").value = spec?.provider || "openai";+ modelRegistryTemplateOptions();+ for (const field of ["id", "name", "contextWindow", "maxTokens", "template"])+ $("model-registry-" + field).value =+ spec?.[field] ?? (field === "template" ? $("model-registry-template").value : "");+ for (const field of ["input", "output", "cacheRead", "cacheWrite"])+ $("model-registry-" + field).value = spec?.cost?.[field] ?? "";+ for (const field of ["base", "webui", "auxiliary", "fastMode"])+ $("model-registry-" + field).checked = spec?.[field] ?? (field === "base" || field === "webui");+ $("model-registry-tiers").value = JSON.stringify(spec?.cost?.tiers || [], null, 2);+ modelRegistryCapabilities();+ }+ async function loadModelRegistry() {+ const response = await api("GET", "/api/model-registry");+ if (!response.ok) {+ setStatus("st-model-registry", "Could not load models.", "err");+ return;+ }+ modelRegistryTemplates = response.data.templates;+ modelRegistryTemplateOptions();+ const rows = $("model-registry-rows");+ rows.replaceChildren();+ const enabled = response.data.models.filter((m) => !m.disabled);+ $("model-registry-empty").hidden = enabled.length > 0;+ for (const { spec, unavailableReason } of enabled) {+ const row = document.createElement("tr");+ for (const value of [+ (spec.name || spec.id) + " (" + spec.id + ")" + (unavailableReason ? " — " + unavailableReason : ""),+ spec.provider || "Unknown",+ spec.template || "Missing",+ ]) {+ const cell = document.createElement("td");+ cell.textContent = value;+ row.appendChild(cell);+ }+ const actions = document.createElement("td");+ const edit = document.createElement("button");+ edit.textContent = "Edit";+ edit.onclick = () => editRegistryModel(spec);+ const remove = document.createElement("button");+ remove.className = "danger";+ remove.textContent = "Delete";+ remove.onclick = async () => {+ if (!confirm("Delete " + spec.name + "? New uses will be refused.")) return;+ const result = await api("DELETE", "/api/model-registry/" + encodeURIComponent(spec.id));+ if (!result.ok) {+ setStatus("st-model-registry", result.data?.message || "Could not delete model.", "err");+ return;+ }+ await loadOnboarding();+ editRegistryModel(null);+ setStatus("st-model-registry", "Model deleted.", "ok");+ };+ actions.append(edit, remove);+ row.appendChild(actions);+ rows.appendChild(row);+ }+ }+ $("model-registry-provider").onchange = modelRegistryTemplateOptions;+ $("model-registry-template").onchange = modelRegistryCapabilities;+ $("model-registry-new").onclick = () => editRegistryModel(null);+ $("model-registry-save").onclick = async () => {+ const button = $("model-registry-save");+ try {+ const value = (field) => $("model-registry-" + field).value.trim();+ const number = (field) => {+ if (!value(field)) throw new Error(field + " is required");+ return Number(value(field));+ };+ const spec = {+ id: value("id"),+ name: value("name"),+ provider: value("provider"),+ template: value("template"),+ contextWindow: number("contextWindow"),+ maxTokens: number("maxTokens"),+ cost: Object.fromEntries(+ ["input", "output", "cacheRead", "cacheWrite"].map((field) => [field, number(field)]),+ ),+ };+ spec.cost.tiers = JSON.parse(value("tiers") || "[]");+ for (const field of ["base", "webui", "auxiliary", "fastMode"])+ spec[field] = $("model-registry-" + field).checked;+ button.disabled = true;+ const result = await api("PUT", "/api/model-registry/" + encodeURIComponent(spec.id), spec);+ if (!result.ok) throw new Error(result.data?.message || "Could not save model.");+ await loadOnboarding();+ editRegistryModel(spec);+ setStatus("st-model-registry", "Model saved. New turns use this definition.", "ok");+ } catch (error) {+ setStatus("st-model-registry", error.message, "err");+ } finally {+ button.disabled = false;+ }+ };+let customProvidersLoaded = [];function parseCustomModels(text) {return textdiff --git a/plugins/admin/src/index.ts b/plugins/admin/src/index.tsindex 23ef0be94..66391c479 100644--- a/plugins/admin/src/index.ts+++ b/plugins/admin/src/index.ts@@ -288,6 +288,7 @@ const WRITES = new Map<string, string[]>([["users", ["PUT", "POST"]],["slack-installation", ["PUT", "DELETE"]],["model-providers", ["PUT", "DELETE"]],+ ["model-registry", ["PUT", "DELETE"]],["custom-providers", ["PUT", "DELETE"]],]);@@ -314,6 +315,7 @@ const READS = ["slack-installation","slack-emoji","model-providers",+ "model-registry","custom-providers",];diff --git a/plugins/admin/test/onboarding-view.test.ts b/plugins/admin/test/onboarding-view.test.tsindex 6630864b2..ae9bf23c6 100644--- a/plugins/admin/test/onboarding-view.test.ts+++ b/plugins/admin/test/onboarding-view.test.ts@@ -64,6 +64,7 @@ async function runLoadOnboarding(modelProviders: unknown): Promise<Record<string},}),api: async (_method: string, path: string) => ({ ok: true, data: fixtures[path] ?? {} }),+ loadModelRegistry: async () => {},orgScope: () => "org:default-org",encodeURIComponent,setStatus: () => {},diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 35e0c91a8..db70c1658 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -397,12 +397,12 @@ export function createChatSurface(chatState.host = document.createElement("div");chatState.host.className = "custom-chat";- const model = ctx.composer.currentModelOption().model;+ const model = ctx.composer.currentModelOption()?.model;const defaultThinkingLevel = defaultEffortForModel(model);const agent = new Agent({initialState: {systemPrompt: "",- model,+ ...(model ? { model } : {}),...(defaultThinkingLevel === "low" ? { thinkingLevel: "low" as const } : {}),messages,tools: [],@@ -517,7 +517,9 @@ export function createChatSurface(}function currentTurnOptions(): TurnOptions {- const { harnessId: harness } = ctx.composer.currentModelOption();+ const selected = ctx.composer.currentModelOption();+ if (!selected) throw new Error("No model is available");+ const harness = selected.harnessId;return {...(harnessSupportsEffort(harness) ? { effortLevel: ctx.composer.state.effortLevel } : {}),...(harnessSupportsFastMode(harness) ? { fastMode: ctx.composer.state.fastMode } : {}),diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex 0a25e316e..1fe33dad1 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -43,7 +43,7 @@ import {type RuntimeConfig,} from "./core-bridge";import { errMessage, swallow } from "../../chassis/src/errors";-import { icon } from "./ui";+import { fieldSelect, icon } from "./ui";import {EFFORT_LEVELS,applyRuntimeOptions,@@ -144,13 +144,8 @@ export function carryModelPick(fromThreadRef: string | null, toThreadRef: stringif (pick) rememberThreadPick(toThreadRef, pick);}-function modelOptionFor(value: ModelOptionValue, scopeKey?: string | null): ModelOption {- const options = getModelOptions(scopeKey);- return (- options.find((option) => option.value === value) ??- options.find((option) => option.value === defaultModelValue()) ??- options[0]- );+function modelOptionFor(value: ModelOptionValue, scopeKey?: string | null): ModelOption | undefined {+ return getModelOptions(scopeKey).find((option) => option.value === value);}function loadStoredFastMode(): boolean | undefined {@@ -258,7 +253,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {openMenu: null as ComposerMenu | null,menuQuery: "",slashDismissed: false,- effortLevel: loadStoredEffort(defaultEffortForModel(modelOptionFor(defaultModelValue()).model)),+ effortLevel: loadStoredEffort(defaultEffortForModel(modelOptionFor(defaultModelValue())?.model)),fastMode: loadStoredFastMode(),pasteView: null as { id: string; text: string; initial: string; dirty: boolean } | null,};@@ -309,7 +304,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {return runtimeScopeKey(ctx.chat.state.scopeId);}- function currentModelOption(): ModelOption {+ function currentModelOption(): ModelOption | undefined {const picked = ctx.chat.state.threadRef ? threadModelPicks.get(ctx.chat.state.threadRef) : undefined;return modelOptionFor(picked ?? defaultModelValue(scopeKey()), scopeKey());}@@ -319,6 +314,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {const scopeKey = runtimeScopeKey(scopeId);const seeded = scopeKey !== null && seededRuntime?.scopeId === scopeKey ? seededRuntime.config : null;if (seeded) {+ seededRuntime = null;applySelectedRuntime(seeded, agent);return;}@@ -328,6 +324,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {const config = await fetchRuntimeConfig(scopeId);if (request !== runtimeRequest) return;if (!config) {+ applyRuntimeOptions(scopeKey, [], {}, { harnessId: "", modelId: "" });composerState.error = "Could not load runtime settings.";ctx.chat.drawActiveChat(agent);return;@@ -348,11 +345,11 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {config.modelCatalog,);composerState.effortLevel =- (config.effective.effortLevel as EffortLevel | undefined) ?? defaultEffortForModel(currentModelOption().model);+ (config.effective.effortLevel as EffortLevel | undefined) ?? defaultEffortForModel(currentModelOption()?.model);composerState.fastMode =config.effective.fastMode === true && modelSupportsFastMode(scopeKey(), config.effective.modelId);if (agent && (!ctx.chat.state.threadRef || !threadModelPicks.has(ctx.chat.state.threadRef)))- agent.state.model = currentModelOption().model;+ if (currentModelOption()) agent.state.model = currentModelOption()!.model;ctx.chat.drawActiveChat(agent);if (pendingComposerFocus) focusComposerEnd();}@@ -384,12 +381,46 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {function composerForm(agent: Agent): TemplateResult {const selectedModel = currentModelOption();+ if (!selectedModel) {+ const selected =+ (ctx.chat.state.threadRef ? threadModelPicks.get(ctx.chat.state.threadRef) : undefined) ??+ defaultModelValue(scopeKey());+ return html`<div class="composer-wrap">+ ${composerApprovalPanel(ctx.chat.activePendingApprovals())}+ <p role="status">+ ${composerState.error || activeRuntimeConfig?.unavailableReason || "Selected model is unavailable. Choose a replacement to continue."}+ ${selected}+ </p>+ <label+ >Replacement model+ ${fieldSelect({+ ariaLabel: "Replacement model",+ value: "",+ options: html`<option value="" selected>Select a model…</option>+ ${getModelOptions(scopeKey()).map((option) => html`<option value=${option.value}>${option.harnessLabel} · ${option.label}</option>`)}`,+ onChange: async (value) => {+ const option = modelOptionFor(value, scopeKey());+ if (!option) return;+ await changeScopeRuntime({ harnessId: option.harnessId, modelId: option.model.id }, agent);+ if (+ activeRuntimeConfig?.effective.harnessId === option.harnessId &&+ activeRuntimeConfig.effective.modelId === option.model.id+ )+ selectModel(value, agent);+ },+ })}+ </label>+ <button type="button" @click=${() => void refreshRuntimeSelection(ctx.chat.state.scopeId, agent)}>+ Refresh models+ </button>+ </div>`;+ }const effortAvailable = harnessSupportsEffort(selectedModel.harnessId);const fastSupported = harnessSupportsFastMode(selectedModel.harnessId);const fastAvailable = fastSupported && modelSupportsFastMode(scopeKey(), selectedModel.model.id);const fastOn = fastAvailable && effectiveFastMode();const fastCharging = fastModeCharging && fastOn;- let fastTitle = "Fast mode is only available on Opus models";+ let fastTitle = "Fast mode is not enabled for this model";if (fastAvailable) fastTitle = fastOn ? "Fast mode active" : "Fast mode";const approvalPauses = ctx.chat.activePendingApprovals();const blockingPauses = approvalPauses.filter(approvalBlocksComposer);@@ -491,9 +522,9 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {? html`<div class="runtime-upgrade"><span>The org now recommends- ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`).harnessLabel}+ ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`)?.harnessLabel ?? activeRuntimeConfig.orgDefault.harnessId}·- ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`).buttonLabel}.</span+ ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`)?.buttonLabel ?? activeRuntimeConfig.orgDefault.modelId}.</span><buttontype="button"@@ -745,7 +776,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {const queued = queuedRunsFor(ctx.chat.state.threadRef);if (!queued.length) return nothing;const steerable =- agent.state.isStreaming && ctx.chat.hasLiveRun() && harnessSupportsSteer(currentModelOption().harnessId);+ agent.state.isStreaming && ctx.chat.hasLiveRun() && harnessSupportsSteer(currentModelOption()?.harnessId ?? "");const steerTip = (q: QueuedRun): string => {if (q.hasAttachments) return "This message carries files, which can't fold into a running task";if (steerable) return "Steer the running task with this instead of waiting";@@ -1210,6 +1241,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}function composerCanSend(): boolean {+ if (!currentModelOption()) return false;return (Boolean(composerState.draft.trim() || composerState.attachments.length) &&!composerState.processingFiles &&@@ -1475,8 +1507,9 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {}async function sendPrompt(agent: Agent): Promise<void> {+ if (!currentModelOption()) return;if (composerState.processingFiles) return;- if (!activeRuntimeConfig && !agent.state.isStreaming) return;+ if (!activeRuntimeConfig) return;if (composerState.pasteView) closePasteView(agent);if (ctx.chat.state.resolvingApprovals.size > 0) return;if (ctx.chat.hasUnresolvedApproval()) return;@@ -1771,7 +1804,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {function selectModel(value: string, agent: Agent): void {const option = getModelOptions(scopeKey()).find((candidate) => candidate.value === value);if (!option) return;- const previousDefaultEffort = defaultEffortForModel(currentModelOption().model);+ const previousDefaultEffort = defaultEffortForModel(currentModelOption()?.model);if (ctx.chat.state.threadRef) rememberThreadPick(ctx.chat.state.threadRef, option.value);agent.state.model = option.model;if (composerState.effortLevel === previousDefaultEffort) {@@ -1785,7 +1818,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {function selectHarness(harnessId: string, agent: Agent): void {const current = currentModelOption();const options = getModelOptionsForHarness(harnessId, scopeKey());- const option = options.find((candidate) => candidate.model.id === current.model.id) ?? options[0];+ const option = options.find((candidate) => candidate.model.id === current?.model.id) ?? options[0];if (option) selectModel(option.value, agent);}@@ -1798,7 +1831,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {function toggleFastMode(agent: Agent): void {if (ctx.chat.hasUnresolvedApproval() || ctx.chat.state.resolvingApprovals.size > 0) return;- if (!modelSupportsFastMode(scopeKey(), currentModelOption().model.id)) return;+ if (!modelSupportsFastMode(scopeKey(), currentModelOption()?.model.id)) return;composerState.fastMode = !effectiveFastMode();persistPreference(FAST_MODE_STORAGE_KEY, composerState.fastMode ? "1" : "0");if (fastModeChargeTimer) {diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.tsindex 0d6ec888e..ee9b57fae 100644--- a/plugins/web-ui/src/conv-types.ts+++ b/plugins/web-ui/src/conv-types.ts@@ -126,7 +126,7 @@ export interface ComposerSurface {resetComposer(): void;focusComposerEnd(): void;resizeComposer(): void;- currentModelOption(): ModelOption;+ currentModelOption(): ModelOption | undefined;carryModelPick(fromThreadRef: string | null, toThreadRef: string): void;refreshRuntimeSelection(scopeId: string | null, agent?: Agent): Promise<void>;onDragEnter(e: DragEvent): void;diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 89023b43c..76813752e 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -1,3 +1,4 @@+import type { ModelMetadata } from "./pi-models.ts";import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";import type { Attachment } from "@earendil-works/pi-web-ui";import type { Api, AssistantMessage, AssistantMessageEventStream, Context, Model, Usage } from "@earendil-works/pi-ai";@@ -639,10 +640,11 @@ export async function api<T = unknown>(path: string, init?: RequestInit): Promisexport interface RuntimeConfig {interactiveFastMode?: boolean;+ unavailableReason?: string;scopeId: string;approvedHarnesses: string[];modelsByHarness: Record<string, string[]>;- modelCatalog: Record<string, { name: string; provider: string }>;+ modelCatalog: Record<string, ModelMetadata>;orgDefault: { harnessId: string; modelId: string; effortLevel?: string; fastMode?: boolean; revision: number };scopeOverride: {harnessId: string;@@ -1652,7 +1654,7 @@ function userEntryText(payload: unknown): string | null {return display.trim() ? display : null;}-export function entriesToMessages(entries: SessionEntry[], model: Model<Api>): AgentMessage[] {+export function entriesToMessages(entries: SessionEntry[], model?: Model<Api>): AgentMessage[] {const out: AgentMessage[] = [];const userByTs = new Map<string, HistoryUserMessage>();let pending: ToolActivity[] = [];@@ -1716,9 +1718,9 @@ export function entriesToMessages(entries: SessionEntry[], model: Model<Api>): Aconst msg: AssistantWork = {role: "assistant",content: [{ type: "text", text }],- api: model.api,- provider: model.provider,- model: model.id,+ api: model?.api ?? "unknown",+ provider: model?.provider ?? "unknown",+ model: model?.id ?? "unknown",usage: zeroUsage(),stopReason: "stop",timestamp: at ?? pending[pending.length - 1]?.createdAt,@@ -1863,9 +1865,9 @@ export function entriesToMessages(entries: SessionEntry[], model: Model<Api>): Aconst msg: AssistantMessage = {role: "assistant",content: [{ type: "text", text: "" }],- api: model.api,- provider: model.provider,- model: model.id,+ api: model?.api ?? "unknown",+ provider: model?.provider ?? "unknown",+ model: model?.id ?? "unknown",usage: zeroUsage(),stopReason: "error",errorMessage: failure.message,@@ -1883,7 +1885,7 @@ export function entriesToMessages(entries: SessionEntry[], model: Model<Api>): Aexport function attachPendingApprovals(messages: AgentMessage[],approvals: PendingApproval[],- model: Model<Api>,+ model?: Model<Api>,): void {if (!approvals.length) return;@@ -1909,9 +1911,9 @@ export function attachPendingApprovals(trailing = {role: "assistant",content: [{ type: "text", text: "" }],- api: model.api,- provider: model.provider,- model: model.id,+ api: model?.api ?? "unknown",+ provider: model?.provider ?? "unknown",+ model: model?.id ?? "unknown",usage: zeroUsage(),stopReason: "stop",timestamp: Date.now(),diff --git a/plugins/web-ui/src/model-options.ts b/plugins/web-ui/src/model-options.tsindex 80bd67045..042dc097c 100644--- a/plugins/web-ui/src/model-options.ts+++ b/plugins/web-ui/src/model-options.ts@@ -1,5 +1,5 @@import type { Api, Model } from "@earendil-works/pi-ai";-import { getBaseModel } from "./pi-models.ts";+import { getBaseModel, type ModelMetadata } from "./pi-models.ts";export type ModelOptionValue = string;export interface ModelOption {@@ -12,67 +12,6 @@ export interface ModelOption {groupLabel: string;}-interface ModelMeta {- label: string;- buttonLabel: string;-}--const MODEL_CATALOG: Record<string, ModelMeta> = {- "claude-fable-5-1": { label: "Fable 5.1", buttonLabel: "Fable 5.1" },- "claude-opus-5": {- label: "Opus 5",- buttonLabel: "Opus 5",- },- "claude-opus-4-8": {- label: "Opus 4.8",- buttonLabel: "Opus 4.8",- },- "claude-sonnet-5": {- label: "Sonnet 5",- buttonLabel: "Sonnet 5",- },- "claude-haiku-4-5": {- label: "Haiku 4.5",- buttonLabel: "Haiku 4.5",- },- "claude-fable-5": {- label: "Fable 5",- buttonLabel: "Fable 5",- },- "gpt-6-astra": {- label: "GPT-6 Astra",- buttonLabel: "Astra",- },- "gpt-5.6-sol": {- label: "GPT-5.6 Sol",- buttonLabel: "5.6 Sol",- },- "gpt-5.6-terra": {- label: "GPT-5.6 Terra",- buttonLabel: "5.6 Terra",- },- "gpt-5.6-luna": {- label: "GPT-5.6 Luna",- buttonLabel: "5.6 Luna",- },-};--const DEFAULT_PICKER_MODEL_IDS: readonly string[] = [- "claude-fable-5-1",- "claude-fable-5",- "claude-opus-5",- "claude-opus-4-8",- "claude-sonnet-5",- "claude-haiku-4-5",-];-const DEFAULT_CODEX_MODEL_IDS: readonly string[] = ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"];--function defaultModelIdsForHarness(harnessId: string): readonly string[] {- if (harnessId === "codex") return DEFAULT_CODEX_MODEL_IDS;- if (harnessId === "claude") return DEFAULT_PICKER_MODEL_IDS;- return [...DEFAULT_PICKER_MODEL_IDS, ...DEFAULT_CODEX_MODEL_IDS];-}-const HARNESS_LABELS: Record<string, string> = {pi: "Pi",opencode: "OpenCode",@@ -111,11 +50,11 @@ function buildOption(id: string,harnessId = "pi",qualified = false,- catalog: Readonly<Record<string, { name: string; provider: string }>> = {},+ catalog: Readonly<Record<string, ModelMetadata>> = {},): ModelOption | null {try {const dynamic = catalog[id];- const meta = MODEL_CATALOG[id] ?? (dynamic ? { label: dynamic.name, buttonLabel: dynamic.name } : null);+ const meta = dynamic ? { label: dynamic.label, buttonLabel: dynamic.buttonLabel } : null;if (!meta) return null;const model = getBaseModel(id, dynamic);return {@@ -124,7 +63,7 @@ function buildOption(harnessLabel: HARNESS_LABELS[harnessId] ?? harnessId,model,...meta,- groupLabel: providerLabel(id, meta.label, dynamic?.provider ?? String(model.provider ?? model.api ?? "other")),+ groupLabel: providerLabel(id, meta.label, dynamic?.provider ?? String(model?.provider ?? model?.api ?? "other")),};} catch {return null;@@ -135,7 +74,7 @@ function buildOptions(ids: readonly string[],harnessId = "pi",qualified = false,- catalog: Readonly<Record<string, { name: string; provider: string }>> = {},+ catalog: Readonly<Record<string, ModelMetadata>> = {},): ModelOption[] {const seen = new Set<string>();const out: ModelOption[] = [];@@ -145,8 +84,7 @@ function buildOptions(const opt = buildOption(id, harnessId, qualified, catalog);if (opt) out.push(opt);}- if (out.length) return out;- return harnessId === "pi" ? buildOptions(DEFAULT_PICKER_MODEL_IDS, "pi", qualified, catalog) : [];+ return out;}interface RuntimeOptions {@@ -154,13 +92,13 @@ interface RuntimeOptions {defaultValue: string | null;}-const FALLBACK: RuntimeOptions = { options: buildOptions(DEFAULT_PICKER_MODEL_IDS), defaultValue: null };+const FALLBACK: RuntimeOptions = { options: [], defaultValue: null };const byScope = new Map<string, RuntimeOptions>();let lastApplied: RuntimeOptions = FALLBACK;function runtimeFor(scopeKey?: string | null): RuntimeOptions {if (scopeKey === undefined) return lastApplied;- return (scopeKey !== null ? byScope.get(scopeKey) : undefined) ?? lastApplied;+ return (scopeKey !== null ? byScope.get(scopeKey) : undefined) ?? FALLBACK;}export function getModelOptions(scopeKey?: string | null): ModelOption[] {@@ -178,25 +116,14 @@ export function getModelOptionsForHarness(harnessId: string, scopeKey?: string |return runtimeFor(scopeKey).options.filter((option) => option.harnessId === harnessId);}-export function applyPickerModelIds(ids: readonly string[] | null | undefined, baseModelId?: string | null): void {- lastApplied = {- options: buildOptions(ids && ids.length ? ids : DEFAULT_PICKER_MODEL_IDS),- defaultValue: baseModelId ?? null,- };-}-export function runtimeModelOptions(approvedHarnesses: readonly string[],modelsByHarness: Readonly<Record<string, readonly string[]>>,- catalog: Readonly<Record<string, { name: string; provider: string }>> = {},+ catalog: Readonly<Record<string, ModelMetadata>> = {},): ModelOption[] {- const options = approvedHarnesses.flatMap((harnessId) => {- const configured = buildOptions(modelsByHarness[harnessId] ?? [], harnessId, true, catalog);- return configured.length- ? configured- : buildOptions(defaultModelIdsForHarness(harnessId), harnessId, true, catalog);- });- return options.length ? options : buildOptions(DEFAULT_PICKER_MODEL_IDS);+ return approvedHarnesses.flatMap((harnessId) =>+ buildOptions(modelsByHarness[harnessId] ?? [], harnessId, true, catalog),+ );}export function applyRuntimeOptions(@@ -204,7 +131,7 @@ export function applyRuntimeOptions(approvedHarnesses: readonly string[],modelsByHarness: Readonly<Record<string, readonly string[]>>,effective: { harnessId: string; modelId: string },- catalog: Readonly<Record<string, { name: string; provider: string }>> = {},+ catalog: Readonly<Record<string, ModelMetadata>> = {},): void {const options = runtimeModelOptions(approvedHarnesses, modelsByHarness, catalog);const applied = { options, defaultValue: `${effective.harnessId}:${effective.modelId}` };@@ -213,13 +140,12 @@ export function applyRuntimeOptions(}export function defaultModelValue(scopeKey?: string | null): ModelOptionValue {- const { options, defaultValue } = runtimeFor(scopeKey);- return options.find((o) => o.value === defaultValue)?.value ?? options[0]!.value;+ return runtimeFor(scopeKey).defaultValue ?? "";}-export function transcriptModel(scopeKey?: string | null): Model<Api> {+export function transcriptModel(scopeKey?: string | null): Model<Api> | undefined {const { options, defaultValue } = runtimeFor(scopeKey);- return (options.find((o) => o.value === defaultValue) ?? options[0]!).model;+ return options.find((o) => o.value === defaultValue)?.model;}export type EffortLevel = "low" | "medium" | "high" | "xhigh" | "max" | "ultracode" | "auto";@@ -250,7 +176,7 @@ export function harnessSupportsSteer(harnessId: string): boolean {return harnessId === "pi" || harnessId === "claude" || harnessId === "codex" || harnessId === "opencode";}-export function defaultEffortForModel(model: Model<Api>): EffortLevel {- const provider = String(model.provider ?? model.api ?? "").toLowerCase();+export function defaultEffortForModel(model: Model<Api> | undefined): EffortLevel {+ const provider = String(model?.provider ?? model?.api ?? "").toLowerCase();return provider.includes("anthropic") ? "low" : "auto";}diff --git a/plugins/web-ui/src/pi-models.ts b/plugins/web-ui/src/pi-models.tsindex d900595b7..6f48dab22 100644--- a/plugins/web-ui/src/pi-models.ts+++ b/plugins/web-ui/src/pi-models.ts@@ -1,46 +1,17 @@-import { getModel } from "@earendil-works/pi-ai";import type { Api, Model } from "@earendil-works/pi-ai";-const KNOWN_PROVIDERS = ["anthropic", "openai", "openrouter"] as const;--const CLONE_TEMPLATES: Readonly<Record<string, { template: string; name: string }>> = {- "claude-fable-5-1": { template: "claude-opus-4-8", name: "Claude Fable 5.1" },- "claude-fable-5": { template: "claude-opus-4-8", name: "Claude Fable 5" },- "claude-opus-5": { template: "claude-opus-4-8", name: "Claude Opus 5" },- "claude-sonnet-5": { template: "claude-sonnet-4-6", name: "Claude Sonnet 5" },- "gpt-6-astra": { template: "gpt-5.5", name: "GPT-6 Astra" },- "gpt-5.6-sol": { template: "gpt-5.5", name: "GPT-5.6 Sol" },- "gpt-5.6-terra": { template: "gpt-5.5", name: "GPT-5.6 Terra" },- "gpt-5.6-luna": { template: "gpt-5.5", name: "GPT-5.6 Luna" },+export type ModelMetadata = Pick<+ Model<Api>,+ "id" | "name" | "provider" | "api" | "reasoning" | "input" | "cost" | "contextWindow" | "maxTokens"+> & {+ label: string;+ buttonLabel: string;+ fastMode: boolean;};-type PiModel = Model<Api>;--function builtinModel(id: string): PiModel | undefined {- for (const provider of KNOWN_PROVIDERS) {- const model = getModel(provider, id as Parameters<typeof getModel>[1]) as PiModel | undefined;- if (model) return model;- }- return undefined;-}--export function getBaseModel(id: string, fallback?: { name: string; provider: string }): PiModel {- const builtin = builtinModel(id);- if (builtin) return builtin;- const clone = CLONE_TEMPLATES[id];- if (clone) {- const template = builtinModel(clone.template);- if (template) return cloneModel(template, id, clone.name);- }- if (fallback) {- const template = getModel("openrouter", "openrouter/auto" as Parameters<typeof getModel>[1]) as PiModel | undefined;- if (template) return { ...cloneModel(template, id, fallback.name), provider: fallback.provider };- }- throw new Error(`Unsupported model: ${id}`);-}--function cloneModel(model: PiModel, id: string, name: string): PiModel {- return { ...structuredClone(model), id, name };+export function getBaseModel(id: string, metadata?: ModelMetadata): Model<Api> {+ if (!metadata || metadata.id !== id) throw new Error(`Model metadata unavailable: ${id}`);+ return { ...structuredClone(metadata), baseUrl: "" };}const fastModeByScope = new Map<string, Set<string>>();diff --git a/plugins/web-ui/test/approval-handoff.test.ts b/plugins/web-ui/test/approval-handoff.test.tsindex 6a4762a27..accc965d4 100644--- a/plugins/web-ui/test/approval-handoff.test.ts+++ b/plugins/web-ui/test/approval-handoff.test.ts@@ -1,3 +1,4 @@+import { metadata } from "./model-metadata.ts";import assert from "node:assert/strict";import { test } from "node:test";import { JSDOM } from "jsdom";@@ -50,6 +51,8 @@ test("approval handoff unlocks queue and steer without losing pending decisions"const approval: PendingApproval = { requestId: "a1", command: "echo test", reason: "requires approval" };const row = { id: "s1", threadRef: "web:owner:test", scopeId: "personal:owner", title: "Test" };const entries = [{ seq: 1, type: "user", createdAt: Date.now(), payload: { text: "run the command" } }];+ let selectedModelId = "gpt-5.6-sol";+ let modelDeleted = false;let pending = [approval];let decision = deferred<Response>();let continuation = deferred<Response>();@@ -61,21 +64,30 @@ test("approval handoff unlocks queue and steer without losing pending decisions"globalThis.fetch = async (input, init) => {const path = String(input);requests.push({ path, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });- if (path.includes("runtime-config"))+ if (path.includes("runtime-config")) {+ if (init?.method === "PUT") selectedModelId = JSON.parse(String(init.body)).modelId;return Response.json({scopeId: row.scopeId,approvedHarnesses: ["pi"],- modelsByHarness: { pi: ["gpt-5.6-sol"] },+ modelsByHarness: { pi: modelDeleted ? ["replacement-api"] : ["gpt-5.6-sol"] },+ modelCatalog: modelDeleted+ ? { "replacement-api": metadata("replacement-api", "Replacement API") }+ : { "gpt-5.6-sol": metadata("gpt-5.6-sol", "GPT-5.6 Sol") },orgDefault: { harnessId: "pi", modelId: "gpt-5.6-sol", revision: 0 },- effective: { harnessId: "pi", modelId: "gpt-5.6-sol" },- scopeOverride: null,+ effective: { harnessId: "pi", modelId: selectedModelId },+ scopeOverride: modelDeleted ? { harnessId: "pi", modelId: selectedModelId } : null,+ ...(modelDeleted && selectedModelId === "deleted-overlay"+ ? { unavailableReason: "Model has been deleted; select another model" }+ : {}),});+ }if (path.startsWith("/api/approvals/")) {submitted = true;return decision.promise;}if (path.includes("/api/runs/active")) return Response.json({ runId: null, queued: [] });if (path === "/api/runs/r1") return continuation.promise;+ if (path === "/api/runs/q1") return Response.json({ status: "done", result: { status: "ok", reply: "done" } });if (path === "/api/turn") return Response.json({ runId: "q1" });if (path === "/api/runs/q1/withdraw") return Response.json({ withdrawn: true });if (path === "/api/runs/r1/signal") return Response.json({ accepted: true });@@ -98,6 +110,8 @@ test("approval handoff unlocks queue and steer without losing pending decisions"const { createConversation } = await vite.ssrLoadModule("/src/conversations.ts");const { entriesToMessages, attachPendingApprovals } = await vite.ssrLoadModule("/src/core-bridge.ts");const { transcriptModel } = await vite.ssrLoadModule("/src/model-options.ts");+ const { seedRuntimeConfig } = await vite.ssrLoadModule("/src/composer.ts");+ seedRuntimeConfig(row.scopeId, await (await fetch("/api/runtime-config")).json());appState.me = { user: "owner", org: "test" };appState.currentView = "chats";sessionsState.list = [row];@@ -128,7 +142,7 @@ test("approval handoff unlocks queue and steer without losing pending decisions"button.click();}mount();- await until(() => !!host.querySelector(".approval-btn"));+ await until(() => !!chat.composer.currentModelOption() && !!host.querySelector(".approval-btn"));await t.test("submission and handoff suppress duplicate clicks and stale cards", async () => {click("Allow once");@@ -253,6 +267,36 @@ test("approval handoff unlocks queue and steer without losing pending decisions"decision.resolve(Response.json({ error: "new request failed" }, { status: 503 }));await until(() => chat.state.resolvingApprovals.size === 0);});+ await t.test("deleted selection blocks sends, renders transcript and offers explicit replacement", async () => {+ submitted = false;+ pending = [];+ selectedModelId = "deleted-overlay";+ modelDeleted = true;+ mount();+ await chat.composer.refreshRuntimeSelection(row.scopeId, chat.state.agent!);+ await until(() => !!host.querySelector('select[aria-label="Replacement model"]'));+ assert.equal(chat.composer.currentModelOption(), undefined);+ assert.match(host.textContent ?? "", /deleted-overlay/);+ assert.match(host.textContent ?? "", /run the command/);+ assert.equal(host.querySelector("textarea"), null);+ assert.equal(host.querySelector("button.send-btn"), null);+ const replacement = host.querySelector<HTMLSelectElement>('select[aria-label="Replacement model"]')!;+ assert.ok([...replacement.options].some((option) => option.value === "pi:replacement-api"));+ const writes = requests.filter((request) => request.path === "/api/turn").length;+ replacement.value = "pi:replacement-api";+ replacement.dispatchEvent(new Event("change", { bubbles: true }));+ await until(() => chat.composer.currentModelOption()?.model.id === "replacement-api");+ assert.equal(selectedModelId, "replacement-api");+ await until(() => !!host.querySelector("textarea"));+ assert.equal(requests.filter((request) => request.path === "/api/turn").length, writes);+ const input = host.querySelector<HTMLTextAreaElement>("textarea")!;+ input.value = "Continue with my chosen replacement";+ input.dispatchEvent(new InputEvent("input", { bubbles: true }));+ await until(() => host.querySelector<HTMLButtonElement>("button.send-btn")?.disabled === false);+ input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));+ await until(() => requests.filter((request) => request.path === "/api/turn").length === writes + 1);+ assert.equal(requests.filter((request) => request.path === "/api/turn").at(-1)?.body?.model, "replacement-api");+ });} finally {handoff.resolve();refreshGate?.resolve();diff --git a/plugins/web-ui/test/model-metadata.ts b/plugins/web-ui/test/model-metadata.tsnew file mode 100644index 000000000..bf5d03b50--- /dev/null+++ b/plugins/web-ui/test/model-metadata.ts@@ -0,0 +1,18 @@+import type { ModelMetadata } from "../src/pi-models.ts";++export function metadata(id: string, name = id, provider = "openai"): ModelMetadata {+ return {+ id,+ name,+ label: name,+ buttonLabel: name,+ provider,+ api: provider === "anthropic" ? "anthropic-messages" : "openai-completions",+ reasoning: false,+ input: ["text"],+ contextWindow: 98765,+ maxTokens: 4321,+ cost: { input: 7, output: 17, cacheRead: 0.2, cacheWrite: 9 },+ fastMode: false,+ };+}diff --git a/plugins/web-ui/test/model-options.test.ts b/plugins/web-ui/test/model-options.test.tsindex b056e1ac0..8a433471a 100644--- a/plugins/web-ui/test/model-options.test.ts+++ b/plugins/web-ui/test/model-options.test.ts@@ -1,212 +1,95 @@import { test } from "node:test";import assert from "node:assert/strict";+import { readFileSync } from "node:fs";import {- applyPickerModelIds,applyRuntimeOptions,defaultModelValue,- getHarnessOptions,getModelOptions,- getModelOptionsForHarness,+ getHarnessOptions,+ runtimeModelOptions,+ transcriptModel,harnessSupportsEffort,harnessSupportsFastMode,- runtimeModelOptions,} from "../src/model-options.ts";-import { modelSupportsFastMode, setFastModeModelIds } from "../src/pi-models.ts";+import { metadata } from "./model-metadata.ts";-test("the built-in picker includes Fable alongside Opus/Sonnet/Haiku", () => {- applyPickerModelIds(null);- const values = getModelOptions().map((o) => o.value);- assert.deepEqual(values, [- "claude-fable-5-1",- "claude-fable-5",- "claude-opus-5",- "claude-opus-4-8",- "claude-sonnet-5",- "claude-haiku-4-5",- ]);-});+const catalog = { future: metadata("future", "Future API Model"), custom: metadata("custom", "Custom", "gateway") };-test("the org base model is the default selection when it's an available option", () => {- applyPickerModelIds(null, "claude-fable-5");- assert.equal(defaultModelValue(), "claude-fable-5");- applyPickerModelIds(["claude-opus-4-8", "claude-sonnet-5"], "claude-sonnet-5");- assert.equal(defaultModelValue(), "claude-sonnet-5");+test("server metadata controls picker labels, geometry, price, order and effective selection", () => {+ applyRuntimeOptions(+ "scope:a",+ ["pi", "mock"],+ { pi: ["custom", "future", "custom"], mock: ["future"] },+ { harnessId: "mock", modelId: "future" },+ catalog,+ );+ assert.deepEqual(+ getModelOptions("scope:a").map((m) => m.value),+ ["pi:custom", "pi:future", "mock:future"],+ );+ assert.equal(defaultModelValue("scope:a"), "mock:future");+ const model = getModelOptions("scope:a")[1]!;+ assert.equal(model.label, "Future API Model");+ assert.equal(model.model.contextWindow, 98765);+ assert.deepEqual(model.model.cost, catalog.future.cost);+ assert.equal(model.model.baseUrl, "");});-test("without a base model (or one outside the picker) the first option is the default", () => {- applyPickerModelIds(null);- assert.equal(defaultModelValue(), "claude-fable-5-1");- applyPickerModelIds(["claude-sonnet-5", "claude-haiku-4-5"], "claude-fable-5");- assert.equal(defaultModelValue(), "claude-sonnet-5");- applyPickerModelIds(null, "not-a-real-model");- assert.equal(defaultModelValue(), "claude-fable-5-1");+test("empty, unknown, missing-metadata and unapproved lists stay empty", () => {+ for (const options of [+ runtimeModelOptions([], { pi: ["future"] }, catalog),+ runtimeModelOptions(["pi"], { pi: [] }, catalog),+ runtimeModelOptions(["pi"], { pi: ["future"] }),+ runtimeModelOptions(["pi"], { pi: ["unknown"] }, catalog),+ ])+ assert.deepEqual(options, []);+ applyRuntimeOptions("scope:empty", ["pi"], { pi: [] }, { harnessId: "pi", modelId: "future" }, catalog);+ assert.deepEqual(getModelOptions("scope:empty"), []);+ assert.equal(defaultModelValue("scope:empty"), "pi:future");+ assert.equal(transcriptModel("scope:empty"), undefined);+ assert.deepEqual(getHarnessOptions("scope:empty"), []);});-test("an admin-configured list filters and orders the picker", () => {- applyPickerModelIds(["claude-fable-5", "claude-sonnet-5"]);- const values = getModelOptions().map((o) => o.value);- assert.deepEqual(values, ["claude-fable-5", "claude-sonnet-5"]);+test("scopes retain independent choices and an unloaded scope does not borrow another policy", () => {+ applyRuntimeOptions("scope:a", ["pi"], { pi: ["future"] }, { harnessId: "pi", modelId: "future" }, catalog);+ applyRuntimeOptions("scope:b", ["mock"], { mock: ["custom"] }, { harnessId: "mock", modelId: "custom" }, catalog);+ assert.equal(defaultModelValue("scope:a"), "pi:future");+ assert.equal(defaultModelValue("scope:b"), "mock:custom");+ assert.deepEqual(getModelOptions("scope:new"), []);});-test("the Codex picker can render and select the OpenAI model", () => {- applyPickerModelIds(["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"], "gpt-5.6-terra");+test("OpenRouter and custom provider metadata retains provider grouping", () => {+ const models = { "vendor/new": metadata("vendor/new", "Vendor: New", "openrouter"), custom: catalog.custom };+ const options = runtimeModelOptions(["pi"], { pi: Object.keys(models) }, models);assert.deepEqual(- getModelOptions().map((o) => o.value),- ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"],+ options.map((m) => m.groupLabel),+ ["Vendor", "Gateway"],);- assert.equal(defaultModelValue(), "gpt-5.6-terra");});-test("runtime options qualify harness/model pairs and select the effective pair", () => {- applyRuntimeOptions(- null,- ["pi", "codex"],- { pi: ["claude-opus-4-8"], codex: ["gpt-5.6-sol"] },- { harnessId: "codex", modelId: "gpt-5.6-sol" },- );- assert.deepEqual(- getModelOptions().map((o) => [o.value, o.harnessId]),- [- ["pi:claude-opus-4-8", "pi"],- ["codex:gpt-5.6-sol", "codex"],- ],- );- assert.equal(defaultModelValue(), "codex:gpt-5.6-sol");- assert.deepEqual(getHarnessOptions(), [- { value: "pi", label: "Pi" },- { value: "codex", label: "Codex" },- ]);- assert.deepEqual(- getModelOptionsForHarness("codex").map((o) => o.label),- ["GPT-5.6 Sol"],- );+test("picker has no model IDs, clone templates or runtime SDK model registry imports", () => {+ const source = ["pi-models.ts", "model-options.ts"]+ .map((file) => readFileSync(new URL(`../src/${file}`, import.meta.url), "utf8"))+ .join("\n");+ assert.doesNotMatch(source, /MODEL_CATALOG|CLONE_TEMPLATES|gpt-5|claude-opus|openrouter\/auto|import \{ getModel/);});-test("runtime options preserve a fetched OpenRouter model as the selected web turn model", () => {- applyRuntimeOptions(- null,- ["pi"],- { pi: ["anthropic/claude-sonnet-4.5"] },- { harnessId: "pi", modelId: "anthropic/claude-sonnet-4.5" },- { "anthropic/claude-sonnet-4.5": { name: "Anthropic: Claude Sonnet 4.5", provider: "openrouter" } },- );- const option = getModelOptions()[0]!;- assert.equal(option.value, "pi:anthropic/claude-sonnet-4.5");- assert.equal(option.model.id, "anthropic/claude-sonnet-4.5");- assert.equal(option.model.provider, "openrouter");- assert.equal(defaultModelValue(), "pi:anthropic/claude-sonnet-4.5");-});--test("runtime options hide retired persisted model ids", () => {- applyRuntimeOptions(- null,- ["claude", "codex"],- {- claude: ["claude-fable-5", "claude-sonnet-4-6", "claude-sonnet-5"],- codex: ["gpt-5.5", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"],- },- { harnessId: "claude", modelId: "claude-fable-5" },- );- assert.deepEqual(- getModelOptionsForHarness("claude").map((o) => o.label),- ["Fable 5", "Sonnet 5"],- );- assert.deepEqual(- getModelOptionsForHarness("codex").map((o) => o.label),- ["GPT-5.6 Sol", "GPT-5.6 Terra", "GPT-5.6 Luna"],- );-});--test("harness-only turn controls are exposed only where the adapter supports them", () => {+test("harness controls retain their supported surfaces", () => {assert.equal(harnessSupportsEffort("pi"), true);- assert.equal(harnessSupportsEffort("codex"), true);- assert.equal(harnessSupportsEffort("claude"), true);assert.equal(harnessSupportsEffort("opencode"), false);- assert.equal(harnessSupportsFastMode("pi"), true);assert.equal(harnessSupportsFastMode("claude"), true);assert.equal(harnessSupportsFastMode("codex"), false);- assert.equal(harnessSupportsFastMode("opencode"), false);});-test("an all-retired list falls back within the approved harness", () => {- applyRuntimeOptions(null, ["codex"], { codex: ["gpt-5.5"] }, { harnessId: "codex", modelId: "gpt-5.5" });- assert.deepEqual(getHarnessOptions(), [{ value: "codex", label: "Codex" }]);+test("deleted selection retains identity and transcript rendering does not borrow a replacement", () => {+ applyRuntimeOptions("scope:deleted", ["pi"], { pi: ["custom"] }, { harnessId: "pi", modelId: "future" }, catalog);+ assert.equal(defaultModelValue("scope:deleted"), "pi:future");+ assert.equal(transcriptModel("scope:deleted"), undefined);assert.deepEqual(- getModelOptionsForHarness("codex").map((o) => o.label),- ["GPT-5.6 Sol", "GPT-5.6 Terra", "GPT-5.6 Luna"],- );- assert.equal(defaultModelValue(), "codex:gpt-5.6-sol");-});--test("unknown ids are dropped; an all-unknown list falls back to the built-in set", () => {- applyPickerModelIds(["claude-fable-5", "not-a-real-model"]);- assert.deepEqual(- getModelOptions().map((o) => o.value),- ["claude-fable-5"],- );- applyPickerModelIds(["nope-1", "nope-2"]);- assert.deepEqual(- getModelOptions().map((o) => o.value),- ["claude-fable-5-1", "claude-fable-5", "claude-opus-5", "claude-opus-4-8", "claude-sonnet-5", "claude-haiku-4-5"],- );-});--test("duplicate ids are de-duped, preserving first occurrence order", () => {- applyPickerModelIds(["claude-sonnet-5", "claude-sonnet-5", "claude-opus-4-8"]);- assert.deepEqual(- getModelOptions().map((o) => o.value),- ["claude-sonnet-5", "claude-opus-4-8"],- );- applyPickerModelIds(null);-});--test("two panes on different scopes keep their own picker, default, and fast-mode set", () => {- applyRuntimeOptions("personal:me", ["pi"], { pi: ["claude-opus-5"] }, { harnessId: "pi", modelId: "claude-opus-5" });- setFastModeModelIds("personal:me", ["claude-opus-5"]);- applyRuntimeOptions(- "group:team",- ["codex"],- { codex: ["gpt-5.6-sol"] },- { harnessId: "codex", modelId: "gpt-5.6-sol" },- );- setFastModeModelIds("group:team", []);-- assert.equal(- defaultModelValue("personal:me"),- "pi:claude-opus-5",- "the later scope must not capture the earlier one",- );- assert.equal(defaultModelValue("group:team"), "codex:gpt-5.6-sol");- assert.deepEqual(- getModelOptions("personal:me").map((o) => o.value),- ["pi:claude-opus-5"],- );- assert.equal(modelSupportsFastMode("personal:me", "claude-opus-5"), true);- assert.equal(modelSupportsFastMode("group:team", "claude-opus-5"), false);-});--test("a scope's own model list is derived without disturbing the active picker", () => {- applyPickerModelIds(["claude-opus-4-8"], "claude-opus-4-8");- const scoped = runtimeModelOptions(["pi", "codex"], { pi: ["claude-sonnet-5"], codex: ["gpt-5.6-sol"] });- assert.deepEqual(- scoped.map((o) => o.value),- ["pi:claude-sonnet-5", "codex:gpt-5.6-sol"],- );- assert.deepEqual(- getModelOptions().map((o) => o.value),- ["claude-opus-4-8"],- "reading a scope's options never re-points the composer's picker",- );-});--test("runtime options include custom-provider models from the catalog", () => {- const options = runtimeModelOptions(- ["pi"],- { pi: ["claude-opus-4-8", "acme-large"] },- { "acme-large": { name: "Acme Large", provider: "acme-gateway" } },+ getModelOptions("scope:deleted").map((model) => model.value),+ ["pi:custom"],);- const acme = options.find((option) => option.value === "pi:acme-large");- assert.ok(acme);- assert.equal(acme.label, "Acme Large");- assert.equal(acme.model.provider, "acme-gateway");+ applyRuntimeOptions("scope:deleted", ["pi"], { pi: ["custom"] }, { harnessId: "pi", modelId: "custom" }, catalog);+ assert.equal(defaultModelValue("scope:deleted"), "pi:custom");+ assert.equal(transcriptModel("scope:deleted")?.id, "custom");});diff --git a/plugins/web-ui/test/openrouter-turn.test.ts b/plugins/web-ui/test/openrouter-turn.test.tsindex 00e936ed0..ef888fef9 100644--- a/plugins/web-ui/test/openrouter-turn.test.ts+++ b/plugins/web-ui/test/openrouter-turn.test.ts@@ -1,3 +1,4 @@+import { metadata } from "./model-metadata.ts";import assert from "node:assert/strict";import { afterEach, test } from "node:test";import type { Agent } from "@earendil-works/pi-agent-core";@@ -17,7 +18,13 @@ test("a web turn submits the fetched OpenRouter model selected by runtime config["pi"],{ pi: ["anthropic/claude-sonnet-4.5"] },{ harnessId: "pi", modelId: "anthropic/claude-sonnet-4.5" },- { "anthropic/claude-sonnet-4.5": { name: "Anthropic: Claude Sonnet 4.5", provider: "openrouter" } },+ {+ "anthropic/claude-sonnet-4.5": metadata(+ "anthropic/claude-sonnet-4.5",+ "Anthropic: Claude Sonnet 4.5",+ "openrouter",+ ),+ },);const model = getModelOptions()[0]!.model;const submitted: Record<string, unknown>[] = [];diff --git a/plugins/web-ui/test/pi-models.test.ts b/plugins/web-ui/test/pi-models.test.tsindex 69edc12f0..905ba996a 100644--- a/plugins/web-ui/test/pi-models.test.ts+++ b/plugins/web-ui/test/pi-models.test.ts@@ -1,54 +1,26 @@import { test } from "node:test";import assert from "node:assert/strict";import { getBaseModel, modelSupportsFastMode, setFastModeModelIds } from "../src/pi-models.ts";+import { metadata } from "./model-metadata.ts";-test("web UI resolves models from the shared catalog without privileging a provider", () => {- const anthropic = getBaseModel("claude-opus-4-8");- assert.equal(anthropic.id, "claude-opus-4-8");- assert.equal(anthropic.provider, "anthropic");- assert.equal(anthropic.api, "anthropic-messages");-- const openai = getBaseModel("gpt-5.6-sol");- assert.equal(openai.id, "gpt-5.6-sol");- assert.equal(openai.provider, "openai");-- const openrouter = getBaseModel("openrouter/auto");- assert.equal(openrouter.provider, "openrouter");-- assert.throws(() => getBaseModel("claude-not-real"), /Unsupported/);-});--test("models this pi-ai build lacks are cloned from a template of their own provider", () => {- const fable51 = getBaseModel("claude-fable-5-1");- assert.equal(fable51.id, "claude-fable-5-1");- assert.equal(fable51.name, "Claude Fable 5.1");- assert.equal(fable51.provider, "anthropic");-- const fable = getBaseModel("claude-fable-5");- assert.equal(fable.id, "claude-fable-5");- assert.equal(fable.name, "Claude Fable 5");- assert.equal(fable.provider, "anthropic");-- const sol = getBaseModel("gpt-5.6-sol");- assert.equal(sol.id, "gpt-5.6-sol");- assert.equal(sol.name, "GPT-5.6 Sol");- assert.equal(sol.provider, "openai", "an OpenAI model never resolves through an Anthropic template");+test("models require server metadata even when the browser SDK knows their id", () => {+ assert.throws(() => getBaseModel("gpt-5.5"), /metadata unavailable/);+ assert.throws(() => getBaseModel("future", metadata("other")), /metadata unavailable/);});-test("fast-mode support is fed from core's runtime config, not a hardcoded client copy", () => {- setFastModeModelIds(null, []);- assert.equal(modelSupportsFastMode(null, "claude-opus-4-8"), false);-- setFastModeModelIds(null, ["claude-opus-4-8", "claude-opus-4-7"]);- assert.equal(modelSupportsFastMode(null, "claude-opus-4-8"), true);- assert.equal(modelSupportsFastMode(null, "claude-sonnet-4-6"), false);- assert.equal(modelSupportsFastMode(null, "claude-haiku-4-5"), false);- assert.equal(modelSupportsFastMode(null, undefined), false);+test("browser model preserves safe server geometry and does not share mutable metadata", () => {+ const spec = metadata("future", "Future", "anthropic");+ const model = getBaseModel("future", spec);+ assert.equal(model.api, "anthropic-messages");+ assert.equal(model.contextWindow, spec.contextWindow);+ model.cost.input = 999;+ assert.equal(spec.cost.input, 7);+ assert.equal(model.baseUrl, "");});-test("a custom-provider model builds from its dynamic catalog entry", () => {- const custom = getBaseModel("acme-large", { name: "Acme Large", provider: "acme-gateway" });- assert.equal(custom.id, "acme-large");- assert.equal(custom.name, "Acme Large");- assert.equal(custom.provider, "acme-gateway");+test("fast mode support follows server updates", () => {+ setFastModeModelIds("scope", ["future"]);+ assert.equal(modelSupportsFastMode("scope", "future"), true);+ setFastModeModelIds("scope", []);+ assert.equal(modelSupportsFastMode("scope", "future"), false);});diff --git a/plugins/web-ui/test/queue-by-default.test.ts b/plugins/web-ui/test/queue-by-default.test.tsindex 49946f4ad..b27cc22f6 100644--- a/plugins/web-ui/test/queue-by-default.test.ts+++ b/plugins/web-ui/test/queue-by-default.test.ts@@ -91,7 +91,7 @@ test("steering is reachable only as an explicit act on a queued row", () => {assert.match(strip, /class="chip-x"[\s\S]{0,240}removeQueued\(agent, q\)/);assert.match(composer,- /const steerable =\s*agent\.state\.isStreaming && ctx\.chat\.hasLiveRun\(\) && harnessSupportsSteer\(currentModelOption\(\)\.harnessId\);/,+ /const steerable =\s*agent\.state\.isStreaming && ctx\.chat\.hasLiveRun\(\) &&\s*harnessSupportsSteer\(currentModelOption\(\)\?\.harnessId \?\? ""\);/,"Steer acts only against a live run on a harness that can fold one in",);});diff --git a/plugins/web-ui/test/runtime-config-handoff.test.ts b/plugins/web-ui/test/runtime-config-handoff.test.tsindex 5b1d49b75..c209061c9 100644--- a/plugins/web-ui/test/runtime-config-handoff.test.ts+++ b/plugins/web-ui/test/runtime-config-handoff.test.ts@@ -26,15 +26,15 @@ test("the first mount in the seeded scope renders from it — no blanking, no seassert.ok(seedRead > 0, "the seeded config must be consulted");assert.ok(seedRead < blank, "consult the seed BEFORE blanking the composer");assert.ok(seedRead < fetchCall, "consult the seed BEFORE refetching");- assert.match(fn, /if \(seeded\) \{\s*applySelectedRuntime\(seeded, agent\);\s*return;\s*\}/);+ assert.match(fn, /if \(seeded\) \{\s*seededRuntime = null;\s*applySelectedRuntime\(seeded, agent\);\s*return;\s*\}/);assert.match(fn, /seededRuntime\?\.scopeId === scopeKey \? seededRuntime\.config : null/);assert.match(fn, /const scopeKey = runtimeScopeKey\(scopeId\);/);- assert.doesNotMatch(fn, /seededRuntime = null;/, "every pane booting on the seeded scope may read the seed");+ assert.match(fn, /seededRuntime = null;/, "later refreshes must read current server metadata");const change = composer.slice(composer.indexOf("async function changeScopeRuntime"));assert.match(change.slice(0, change.indexOf("\n }")),/seededRuntime = null;/,- "changing the scope default is what retires the boot seed",+ "scope updates also retire any remaining boot seed",);});diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex e129169ef..829fbf8d4 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -15,6 +15,8 @@ import {isHarnessId,modelProviderAvailabilityFor,modelServiceable,+ modelOfferedInWebui,+ modelUnavailableReason,resolveModel,} from "../model/pi-models.ts";import { selectableCatalogForHarness, selectableModelCatalog } from "../model/model-catalog.ts";@@ -74,6 +76,7 @@ export function createTurnMethods(const { shouldRouteToSpine, markTriggerHandled, addressedWakeText } = ambient;return {async turn(req: TurnRequest): Promise<TurnResult> {+ await deps.refreshModels?.();await deps.identity.refresh();const actor: Principal = deps.identity.resolve(req.actor);if (!deps.identity.isInternal(actor)) {@@ -165,21 +168,17 @@ export function createTurnMethods(deps.modelProviders ?? { anthropic: false, openai: false, openrouter: false };const managedKeys = deps.modelCredentials ? await deps.modelCredentials.availability() : configuredKeys;let orgRuntime;- let configuredRuntime;let runtime;try {- orgRuntime = await resolveRuntimeChoiceDurable(deps.config, org, org, runtimeFallback);- configuredRuntime =- targetScope === org- ? orgRuntime- : await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback);- runtime =- req.harness || req.model- ? await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback, {- ...(req.harness && isHarnessId(req.harness) ? { harnessId: req.harness } : {}),- ...(req.model ? { modelId: req.model } : {}),- })- : configuredRuntime;+ const orgModel =+ storedOrgRuntime?.modelId ?? (await deps.config.getBaseModelOwnDurable(org)) ?? runtimeFallback.modelId;+ orgRuntime = modelUnavailableReason(orgModel)+ ? { harnessId: storedOrgRuntime?.harnessId ?? runtimeFallback.harnessId, modelId: orgModel }+ : await resolveRuntimeChoiceDurable(deps.config, org, org, runtimeFallback);+ runtime = await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback, {+ ...(req.harness && isHarnessId(req.harness) ? { harnessId: req.harness } : {}),+ ...(req.model ? { modelId: req.model } : {}),+ });} catch (error) {swallow("turn: runtime resolution", error);return { status: "refused", reason: `I couldn't set up that runtime choice — ${GENERIC_FAILURE_CLAUSE}` };@@ -201,15 +200,19 @@ export function createTurnMethods(}const configuredWebuiModels = await deps.config.getWebuiModelsDurable(org);let enabledWebuiModels: string[] | null = null;- if (configuredWebuiModels?.length) {- enabledWebuiModels = [...new Set([...configuredWebuiModels, orgRuntime.modelId])];+ if (configuredWebuiModels != null) {+ enabledWebuiModels = configuredWebuiModels.length+ ? [...new Set([...configuredWebuiModels, orgRuntime.modelId])]+ : [];} else if (providers?.openrouter) {enabledWebuiModels = [...new Set([...selectableCatalogForHarness(await selectableModelCatalog(deps.modelCredentialFetch),runtime.harnessId,- ).map((model) => model.id),+ )+ .filter((model) => modelOfferedInWebui(model.id))+ .map((model) => model.id),...(orgRuntime.harnessId === runtime.harnessId ? [orgRuntime.modelId] : []),]),];diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 0ff360e46..557d25472 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -1,3 +1,4 @@+import type { ModelOverlayStore } from "../model/model-overlay-store.ts";import type {DeliveryProvenance,Grant,@@ -574,6 +575,8 @@ export interface AppDeps {mcpServers?: McpServerStore;mcpToolService?: McpToolService;modelCredentialFetch?: typeof fetch;+ modelRegistry?: ModelOverlayStore;+ refreshModels?: () => Promise<void>;customProviders?: CustomProviderStore;refreshCustomProviders?: () => Promise<void>;acl: AclStore;diff --git a/src/api/deps.ts b/src/api/deps.tsindex 451e5f1ee..a01ed044e 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -1,5 +1,6 @@import type { DurableByteStore } from "../files/durable-byte-store.ts";import type { SessionShareStore } from "../sessions/session-share.ts";+import type { ModelOverlayStore } from "../model/model-overlay-store.ts";import type { ModelProvider, ModelProviderAvailability } from "../model/pi-models.ts";import type { ModelCredentialStore } from "../model/model-credential-store.ts";import type { UserModelCredentialStore } from "../model/user-model-credential-store.ts";@@ -104,6 +105,8 @@ export interface ServerDeps {mcpServers?: McpServerStore;mcpToolService?: McpToolService;modelCredentialFetch?: typeof fetch;+ modelRegistry?: ModelOverlayStore;+ refreshModels?: () => Promise<void>;customProviders?: CustomProviderStore;refreshCustomProviders?: () => Promise<void>;brandingDefault?: OrgBranding;diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex 429de6f7e..3e542603a 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -6,7 +6,7 @@ import { parseCommandPolicy } from "../../policy/command-policy.ts";import { parseScopeId, scopeId, type CommandPolicy, type Grant, type ScopeId } from "../../types.ts";import {defaultModelForHarness,- FAST_MODE_MODEL_IDS,+ fastModeModelIds,harnessSupportsFastMode,HARNESS_IDS,isHarnessId,@@ -14,8 +14,8 @@ import {modelServiceable,modelProviderAvailabilityFor,resolveModel,- SELECTABLE_BASE_MODELS,thinkingLevelsForHarness,+ selectableBaseModels,ALL_PROVIDERS_AVAILABLE,type HarnessId,} from "../../model/pi-models.ts";@@ -535,7 +535,9 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [target: "any",clearable: true,readKey: "baseModel",- enumValues: SELECTABLE_BASE_MODELS,+ get enumValues() {+ return selectableBaseModels();+ },get: (deps, scope) => deps.config!.getBaseModel(scope),apply: async (ctx, _actor, scope) => {const raw = (ctx.body as { modelId?: unknown }).modelId;@@ -567,7 +569,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [fastMode:runtime.fastMode &&harnessSupportsFastMode(runtime.harnessId) &&- FAST_MODE_MODEL_IDS.includes(modelId),+ fastModeModelIds().includes(modelId),}: {}),});@@ -590,7 +592,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [fastMode:effective.fastMode &&harnessSupportsFastMode(effective.harnessId) &&- FAST_MODE_MODEL_IDS.includes(modelId),+ fastModeModelIds().includes(modelId),}: {}),});@@ -633,7 +635,7 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [harnessId,modelId,effortLevel,- fastMode: fastMode && harnessSupportsFastMode(harnessId) && FAST_MODE_MODEL_IDS.includes(modelId),+ fastMode: fastMode && harnessSupportsFastMode(harnessId) && fastModeModelIds().includes(modelId),});return { ok: true };},@@ -668,7 +670,9 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [label:"Web UI model picker (ordered list of model ids; the org base model is the default selection, else the first). Empty restores the built-in set.",readKey: "webuiModels",- enumValues: SELECTABLE_BASE_MODELS,+ get enumValues() {+ return selectableBaseModels();+ },get: (deps, scope) => deps.config!.getWebuiModels(scope),apply: generic<string[] | null>((body, { scope }) => {@@ -801,7 +805,9 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [label:"The model driving the browser agent in the browse skill, org-wide (empty follows the deployment's base model; fast mode applies only on Opus models).",readKey: "browseModel",- enumValues: SELECTABLE_BASE_MODELS,+ get enumValues() {+ return selectableBaseModels();+ },get: (deps, scope) => deps.config!.getBrowseModel(scope),apply: async (ctx, _actor, scope) => {const bad = orgOnly(scope, "the browse model is org-wide");diff --git a/src/api/routes/admin.ts b/src/api/routes/admin.tsindex a3fe1675c..74f0e88f8 100644--- a/src/api/routes/admin.ts+++ b/src/api/routes/admin.ts@@ -1,3 +1,4 @@+import { modelRegistry } from "./admin/model-registry.ts";import { type ApiCtx, type Route } from "./route.ts";import {getAdminResources,@@ -73,6 +74,9 @@ const routes: ReadonlyArray<Route<ApiCtx>> = [{ method: "PUT", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: putMcpServer },{ method: "DELETE", path: "/v1/admin/mcp-servers/:id", auth: "either", handle: deleteMcpServer },{ method: "DELETE", path: "/v1/admin/model-providers/:provider", auth: "either", handle: deleteModelProvider },+ { method: "GET", path: "/v1/admin/model-registry", auth: "either", handle: modelRegistry },+ { method: "PUT", path: "/v1/admin/model-registry/:model", auth: "either", handle: modelRegistry },+ { method: "DELETE", path: "/v1/admin/model-registry/:model", auth: "either", handle: modelRegistry },{ method: "GET", path: "/v1/admin/custom-providers", auth: "either", handle: getCustomProviders },{ method: "PUT", path: "/v1/admin/custom-providers/:provider", auth: "either", handle: putCustomProvider },{ method: "DELETE", path: "/v1/admin/custom-providers/:provider", auth: "either", handle: deleteCustomProvider },diff --git a/src/api/routes/admin/auto-flagger-test.ts b/src/api/routes/admin/auto-flagger-test.tsindex d2ae56c0f..6dbc003aa 100644--- a/src/api/routes/admin/auto-flagger-test.ts+++ b/src/api/routes/admin/auto-flagger-test.ts@@ -91,6 +91,7 @@ export async function testAutoFlagger(ctx: ApiCtx): Promise<void> {sendJson(ctx.res, 400, { error: "bad_request", message: "the Auto flagger is org-wide; request an org scope" });return;}+ await ctx.deps.refreshModels?.();const body = (ctx.body ?? {}) as {window?: unknown;harnessId?: unknown;diff --git a/src/api/routes/admin/model-providers.ts b/src/api/routes/admin/model-providers.tsindex 433f92d83..67a7725a7 100644--- a/src/api/routes/admin/model-providers.ts+++ b/src/api/routes/admin/model-providers.ts@@ -51,6 +51,7 @@ export async function validateProviderApiKey(ctx: ApiCtx, provider: ModelProvideexport async function getModelProviders(ctx: ApiCtx): Promise<void> {const authorized = await actor(ctx);if (!authorized) return;+ await ctx.deps.refreshModels?.();if (!ctx.deps.modelCredentials) return sendJson(ctx.res, 404, { error: "not_found" });audit(ctx.deps, {principalId: authorized.id,diff --git a/src/api/routes/admin/model-registry.ts b/src/api/routes/admin/model-registry.tsnew file mode 100644index 000000000..05f87a149--- /dev/null+++ b/src/api/routes/admin/model-registry.ts@@ -0,0 +1,42 @@+import { MODEL_REGISTRY, safeModelMetadata } from "../../../model/pi-models.ts";+import { errMessage } from "../../../util/errors.ts";+import { sendJson } from "../../http.ts";+import type { ApiCtx } from "../route.ts";+import { audit, authorizeAdmin, orgScope, isObj } from "../shared.ts";++export async function modelRegistry(ctx: ApiCtx): Promise<void> {+ const scope = orgScope(ctx.deps);+ const actor = await authorizeAdmin(ctx, scope);+ if (!actor) return;+ const store = ctx.deps.modelRegistry;+ if (!store) return sendJson(ctx.res, 404, { error: "not_found" });+ if (ctx.method === "GET") {+ await ctx.deps.refreshModels?.();+ const templates = MODEL_REGISTRY.flatMap(({ id }) => {+ const model = safeModelMetadata(id);+ return model && (model.provider === "openai" || model.provider === "anthropic") ? [model] : [];+ });+ return sendJson(ctx.res, 200, { models: await store.statuses(), templates });+ }+ const id = ctx.params.model;+ if (!id) return sendJson(ctx.res, 400, { error: "bad_request" });+ try {+ if (ctx.method === "DELETE") {+ if (!(await store.delete(id, actor.id))) return sendJson(ctx.res, 404, { error: "not_found" });+ } else {+ if (!isObj(ctx.body) || (ctx.body.id !== undefined && ctx.body.id !== id))+ return sendJson(ctx.res, 400, { error: "bad_request" });+ await store.upsert({ ...ctx.body, id }, actor.id);+ }+ } catch (error) {+ return sendJson(ctx.res, 400, { error: "bad_request", message: errMessage(error) });+ }+ audit(ctx.deps, {+ principalId: actor.id,+ action: ctx.method === "DELETE" ? "model-registry.delete" : "model-registry.update",+ resource: id,+ scopeLabel: scope,+ });+ await store.refresh();+ return sendJson(ctx.res, 200, { ok: true });+}diff --git a/src/api/routes/admin/scope-config.ts b/src/api/routes/admin/scope-config.tsindex 276666b3c..7ab0ae478 100644--- a/src/api/routes/admin/scope-config.ts+++ b/src/api/routes/admin/scope-config.ts@@ -5,7 +5,7 @@ import {FAST_MODE_MODEL_IDS,harnessSupportsFastMode,HARNESS_IDS,- SELECTABLE_BASE_MODELS,+ selectableBaseModels,defaultModelForHarness,modelProviderAvailabilityFor,modelServiceable,@@ -45,6 +45,8 @@ export async function putScopeConfig(ctx: ApiCtx): Promise<void> {const actor = await authorizeAdmin(ctx, targetScope);if (!actor) return;+ if (["base-model", "runtime", "webui-models", "browse-model", "auto-flagger", "import"].includes(resource))+ await deps.refreshModels?.();const withScopeMutationLock = async <T>(fn: () => Promise<T>): Promise<T> =>deps.advisoryLock ? deps.advisoryLock.withLock(`admin-governance:${targetScope}`, fn) : fn();@@ -110,6 +112,7 @@ export async function getAdminResources(ctx: ApiCtx): Promise<void> {const scope = orgScope(deps);const actor = await authorizeAdmin(ctx, scope);if (!actor) return;+ await deps.refreshModels?.();audit(deps, { principalId: actor.id, action: "resources.read", resource: "resources", scopeLabel: scope });return sendJson(res, 200, { resources: adminResourceManifest() });}@@ -242,6 +245,7 @@ export async function getScopeConfig(ctx: ApiCtx): Promise<void> {if (!targetScope || targetScope.includes("/")) return sendJson(res, 404, { error: "not_found" });const actor = await authorizeAdmin(ctx, targetScope);if (!actor) return;+ await deps.refreshModels?.();await deps.config.refreshScope(targetScope);audit(deps, { principalId: actor.id, action: "config.read", resource: "config", scopeLabel: targetScope });const environmentMetadata = await scopeEnvironmentMetadata(deps, targetScope);@@ -330,7 +334,7 @@ export async function getScopeConfig(ctx: ApiCtx): Promise<void> {fastModeModelIds: FAST_MODE_MODEL_IDS,fastModeHarnessIds: HARNESS_IDS.filter(harnessSupportsFastMode),autoFlaggerDefault: defaultAutoFlaggerConfig(deps),- browseModelOptions: SELECTABLE_BASE_MODELS.filter((m) =>+ browseModelOptions: selectableBaseModels().filter((m) =>modelServiceable(m.id, providersFor(deps.harnessId ?? "pi")),),egressEnforcement: {diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 3526501e4..dd4270bcf 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -8,10 +8,12 @@ import {isHarnessId,modelProviderAvailabilityFor,modelSupportedByHarness,- resolveModel,serviceableModelIds,ALL_PROVIDERS_AVAILABLE,- FAST_MODE_MODEL_IDS,+ fastModeModelIds,+ safeModelMetadata,+ modelOfferedInWebui,+ modelUnavailableReason,THINKING_LEVELS,type HarnessId,} from "../../model/pi-models.ts";@@ -1058,6 +1060,7 @@ export async function shareArtifact(ctx: ApiCtx): Promise<void> {}async function getSurfaceConfig(ctx: ApiCtx): Promise<void> {+ await ctx.deps.refreshModels?.();const { res, deps } = ctx;if (!deps.config) return sendJson(res, 404, { error: "not_found" });const [webuiModels, baseModel, externalSlackParticipants, branding] = await Promise.all([@@ -1073,7 +1076,9 @@ async function getSurfaceConfig(ctx: ApiCtx): Promise<void> {const catalog = managedKeys?.openrouter? await selectableModelCatalog(deps.modelCredentialFetch): builtInModelCatalog();- const allowed = selectableCatalogForHarness(catalog, harnessId).map((model) => model.id);+ const allowed = selectableCatalogForHarness(catalog, harnessId)+ .filter((model) => modelOfferedInWebui(model.id))+ .map((model) => model.id);const configuredPicker = webuiModels?.filter((id) => modelSupportedByHarness(id, harnessId)) ?? [];const resolvedBase = modelSupportedByHarness(baseModel ?? undefined, harnessId)? baseModel!@@ -1085,7 +1090,7 @@ async function getSurfaceConfig(ctx: ApiCtx): Promise<void> {...(branding.selfLabel ? { selfLabel: branding.selfLabel } : {}),};return sendJson(res, 200, {- webuiModels: configuredPicker.length ? configuredPicker : allowed,+ webuiModels: webuiModels != null ? configuredPicker : allowed,baseModel: resolvedBase,harnessId,...(providerStatus && {@@ -1104,7 +1109,7 @@ async function getSurfaceConfig(ctx: ApiCtx): Promise<void> {function runtimeFallback(ctx: ApiCtx): { harnessId: HarnessId; modelId: string } {const harnessId = isHarnessId(ctx.deps.harnessId) ? ctx.deps.harnessId : "pi";- return { harnessId, modelId: defaultModelForHarness(harnessId, ctx.deps.baseModelDefault) };+ return { harnessId, modelId: ctx.deps.baseModelDefault ?? defaultModelForHarness(harnessId) };}async function runtimeTarget(ctx: ApiCtx): Promise<{ actorId: string; scope: ScopeId } | null> {@@ -1130,11 +1135,6 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<stconst fallback = runtimeFallback(ctx);const org = orgScope(ctx.deps);const approvedHarnesses = ((await config.getApprovedHarnessesDurable()) ?? [fallback.harnessId]).filter(isHarnessId);- const firstApproved = approvedHarnesses[0] ?? fallback.harnessId;- const safeFallback =- approvedHarnesses.includes(fallback.harnessId) && modelSupportedByHarness(fallback.modelId, fallback.harnessId)- ? fallback- : { harnessId: firstApproved, modelId: defaultModelForHarness(firstApproved, fallback.modelId) };const configuredKeys = ctx.deps.providerKeys ?? ALL_PROVIDERS_AVAILABLE;const managedKeys = ctx.deps.modelCredentials ? await ctx.deps.modelCredentials.availability() : configuredKeys;const providersFor = (harnessId: string) => modelProviderAvailabilityFor(harnessId, configuredKeys, managedKeys);@@ -1150,13 +1150,8 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<steffortLevel?: string;fastMode?: boolean;revision: number;- } = { ...safeFallback, revision: orgStored?.revision ?? 0 };- if (- orgStored &&- isHarnessId(orgStored.harnessId) &&- approvedHarnesses.includes(orgStored.harnessId) &&- modelSupportedByHarness(orgStored.modelId, orgStored.harnessId)- ) {+ } = { ...fallback, revision: orgStored?.revision ?? 0 };+ if (orgStored && isHarnessId(orgStored.harnessId)) {orgDefault = {harnessId: orgStored.harnessId,modelId: orgStored.modelId,@@ -1164,11 +1159,7 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<st...(typeof orgStored.fastMode === "boolean" ? { fastMode: orgStored.fastMode } : {}),revision: orgStored.revision ?? 0,};- } else if (- orgLegacyModel &&- approvedHarnesses.includes(fallback.harnessId) &&- modelSupportedByHarness(orgLegacyModel, fallback.harnessId)- ) {+ } else if (orgLegacyModel) {orgDefault = { harnessId: fallback.harnessId, modelId: orgLegacyModel, revision: 0 };}const stored = scope === org ? orgStored : await config.getRuntimeSelectionDurable(scope);@@ -1180,12 +1171,7 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<stfastMode?: boolean;orgRevision?: number;} | null = null;- if (- stored &&- isHarnessId(stored.harnessId) &&- approvedHarnesses.includes(stored.harnessId) &&- modelSupportedByHarness(stored.modelId, stored.harnessId)- ) {+ if (stored && isHarnessId(stored.harnessId)) {scopeOverride = {harnessId: stored.harnessId,modelId: stored.modelId,@@ -1193,11 +1179,7 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<st...(typeof stored.fastMode === "boolean" ? { fastMode: stored.fastMode } : {}),orgRevision: stored.orgRevision,};- } else if (- legacyModel &&- approvedHarnesses.includes(fallback.harnessId) &&- modelSupportedByHarness(legacyModel, fallback.harnessId)- ) {+ } else if (legacyModel) {scopeOverride = { harnessId: fallback.harnessId, modelId: legacyModel, orgRevision: 0 };}const effective = scopeOverride ?? orgDefault;@@ -1205,11 +1187,15 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<stconst allowlist = await config.getWebuiModelsDurable(org);const modelsByHarness = Object.fromEntries(approvedHarnesses.map((harnessId) => {- const ids = allowlist?.length- ? allowlist.filter((id) => modelSupportedByHarness(id, harnessId))- : selectableCatalogForHarness(catalog, harnessId).map((model) => model.id);+ const ids =+ allowlist != null+ ? allowlist.filter((id) => modelSupportedByHarness(id, harnessId))+ : selectableCatalogForHarness(catalog, harnessId)+ .filter((model) => modelOfferedInWebui(model.id))+ .map((model) => model.id);for (const choice of selected) {if (+ allowlist?.length !== 0 &&choice.harnessId === harnessId &&modelSupportedByHarness(choice.modelId, harnessId) &&!ids.includes(choice.modelId)@@ -1222,10 +1208,8 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<stconst advertisedModelIds = new Set(Object.values(modelsByHarness).flat());const modelCatalog = Object.fromEntries([...advertisedModelIds].flatMap((id) => {- const model = catalog.find((candidate) => candidate.id === id);- if (model) return [[id, { name: model.name, provider: model.provider }]];- const resolved = resolveModel(id);- return resolved ? [[id, { name: resolved.name, provider: resolved.provider }]] : [];+ const metadata = safeModelMetadata(id);+ return metadata ? [[id, metadata]] : [];}),);return {@@ -1241,8 +1225,14 @@ async function runtimeConfigBody(ctx: ApiCtx, scope: ScopeId): Promise<Record<st...(effective.effortLevel ? { effortLevel: effective.effortLevel } : {}),...(typeof effective.fastMode === "boolean" ? { fastMode: effective.fastMode } : {}),},+ ...(!modelsByHarness[effective.harnessId]?.includes(effective.modelId)+ ? {+ unavailableReason:+ modelUnavailableReason(effective.modelId) ?? "Selected model is unavailable; choose another model",+ }+ : {}),upgradeAvailable: Boolean(scopeOverride && scopeOverride.orgRevision !== orgDefault.revision),- fastModeModelIds: FAST_MODE_MODEL_IDS,+ fastModeModelIds: fastModeModelIds(),interactiveFastMode: await config.getInteractiveFastModeDurable(),};}@@ -1251,13 +1241,15 @@ async function getRuntimeConfig(ctx: ApiCtx): Promise<void> {if (!ctx.deps.config) return sendJson(ctx.res, 404, { error: "not_found" });const target = await runtimeTarget(ctx);if (!target) return sendJson(ctx.res, 403, { error: "forbidden" });+ await ctx.deps.refreshModels?.();return sendJson(ctx.res, 200, await runtimeConfigBody(ctx, target.scope));}async function webuiModelEnabled(ctx: ApiCtx, modelId: string): Promise<boolean> {const config = ctx.deps.config!;const picker = await config.getWebuiModelsDurable(orgScope(ctx.deps));- if (!picker?.length || picker.includes(modelId)) return true;+ if (picker == null || picker.includes(modelId)) return true;+ if (picker.length === 0) return false;const org = orgScope(ctx.deps);const stored = await config.getRuntimeSelectionDurable(org);const orgModel = stored?.modelId ?? (await config.getBaseModelOwnDurable(org)) ?? runtimeFallback(ctx).modelId;@@ -1270,6 +1262,7 @@ async function putRuntimeConfig(ctx: ApiCtx): Promise<void> {return sendJson(ctx.res, 403, { error: "live_actor_required" });const target = await runtimeTarget(ctx);if (!target) return sendJson(ctx.res, 403, { error: "forbidden" });+ await ctx.deps.refreshModels?.();const config = ctx.deps.config;if (ctx.body.inherit === true) await config.setRuntimeSelectionLatest(target.scope, null);else if (ctx.body.keep === true) {@@ -1307,7 +1300,7 @@ async function putRuntimeConfig(ctx: ApiCtx): Promise<void> {harnessId,modelId,effortLevel,- fastMode: fastMode && FAST_MODE_MODEL_IDS.includes(modelId),+ fastMode: fastMode && fastModeModelIds().includes(modelId),});}audit(ctx.deps, {diff --git a/src/core/individual-auth-routing.ts b/src/core/individual-auth-routing.tsindex 60c958629..8c0280294 100644--- a/src/core/individual-auth-routing.ts+++ b/src/core/individual-auth-routing.ts@@ -5,6 +5,8 @@ import {defaultModelForHarness,defaultModelForProvider,resolveModel,+ isOverlayModel,+ modelUnavailableReason,type ModelProvider,} from "../model/pi-models.ts";import type { UserModelCredential } from "../model/user-model-credential-store.ts";@@ -22,6 +24,7 @@ export function resolveIndividualAuthRouting(requestedModel: string | undefined,preferredHarness?: string,): IndividualAuthRouting {+ if (requestedModel && modelUnavailableReason(requestedModel)) return null;const requestedProvider = requestedModel ? resolveModel(requestedModel)?.provider : undefined;const pick = ((): { provider: "anthropic" | "openai"; cred: UserModelCredential } | null => {if (requestedProvider === "anthropic" && anthCred) return { provider: "anthropic", cred: anthCred };@@ -31,6 +34,12 @@ export function resolveIndividualAuthRouting(return null;})();if (!pick) return null;+ if (+ requestedModel &&+ isOverlayModel(requestedModel) &&+ (pick.cred.kind !== "apikey" || requestedProvider !== pick.provider)+ )+ return null;if (pick.cred.kind === "apikey" && pick.cred.apiKey) {return {kind: "apikey",diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 1b381562e..fb3949f81 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -491,6 +491,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {},async handleTurn(input: OrchestratorInput): Promise<TurnResult> {+ await deps.refreshModels?.();const { actor, conversation } = input;const automatedTurn = input.origin.kind === "automation";const ambientTurn = input.origin.kind === "ambient";diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.tsindex 389bdddb7..4f55bce12 100644--- a/src/core/orchestrator/types.ts+++ b/src/core/orchestrator/types.ts@@ -98,6 +98,7 @@ export interface OrchestratorInput extends Omit<}export interface OrchestratorDeps {+ refreshModels?: () => Promise<void>;identity: IdentityService;resolution: ResolutionService;config?: ScopedConfigStore;diff --git a/src/core/turn-options.ts b/src/core/turn-options.tsindex 850688bf0..5f1736738 100644--- a/src/core/turn-options.ts+++ b/src/core/turn-options.ts@@ -1,5 +1,5 @@import {- DEFAULT_WEBUI_MODEL_IDS,+ defaultWebuiModelIds,THINKING_LEVELS,serviceableModelIds,modelServiceable,@@ -39,7 +39,7 @@ export function validateWebTurnModelOptions(enabledModels: readonly string[] | null,providers: ModelProviderAvailability = ALL_PROVIDERS_AVAILABLE,): string | null {- const enabled = enabledModels?.length ? enabledModels : DEFAULT_WEBUI_MODEL_IDS;+ const enabled = enabledModels ?? defaultWebuiModelIds();const allowedModels = serviceableModelIds(enabled, providers);if (input.model && !allowedModels.includes(input.model)) {return resolveModel(input.model) && !modelServiceable(input.model, providers)diff --git a/src/harness/harness-router.ts b/src/harness/harness-router.tsindex b6a32d6f3..0e3fd5352 100644--- a/src/harness/harness-router.ts+++ b/src/harness/harness-router.ts@@ -1,12 +1,13 @@import type { ScopedConfigStore } from "../resolution/config-store.ts";import {defaultModelForHarness,- FAST_MODE_MODEL_IDS,+ fastModeModelIds,harnessSupportsFastMode,isHarnessId,modelSupportedByHarness,resolveModel,thinkingLevelsForHarness,+ modelUnavailableReason,type HarnessId,} from "../model/pi-models.ts";import type { ScopeId } from "../types.ts";@@ -24,9 +25,7 @@ function normalizeRuntimeChoice(choice: RuntimeChoice): RuntimeChoice {...(typeof choice.fastMode === "boolean"? {fastMode:- choice.fastMode &&- harnessSupportsFastMode(choice.harnessId) &&- FAST_MODE_MODEL_IDS.includes(choice.modelId),+ choice.fastMode && harnessSupportsFastMode(choice.harnessId) && fastModeModelIds().includes(choice.modelId),}: {}),};@@ -40,6 +39,7 @@ export function resolveRuntimeChoice(requested?: Partial<RuntimeChoice>,): RuntimeChoice {const approved = config.getApprovedHarnesses() ?? [fallback.harnessId];+ if (approved.length === 0) throw new NonRetryableTurnError("No harnesses are approved");const orgStored = config.getRuntimeSelection(orgScopeId);const orgLegacy = config.getBaseModel(orgScopeId);const configuredOrg: RuntimeChoice =@@ -51,6 +51,12 @@ export function resolveRuntimeChoice(...(typeof orgStored.fastMode === "boolean" ? { fastMode: orgStored.fastMode } : {}),}: { harnessId: fallback.harnessId, modelId: orgLegacy ?? fallback.modelId };+ const configuredId =+ requested?.modelId ??+ (scope !== orgScopeId ? (config.getRuntimeSelection(scope)?.modelId ?? config.getBaseModel(scope)) : null) ??+ configuredOrg.modelId;+ const unavailableReason = modelUnavailableReason(configuredId);+ if (unavailableReason) throw new NonRetryableTurnError(`${configuredId}: ${unavailableReason}`);const firstApproved = approved.find(isHarnessId) ?? fallback.harnessId;const safeFallback =approved.includes(fallback.harnessId) && modelSupportedByHarness(fallback.modelId, fallback.harnessId)diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.tsindex 3dd34d866..194350fa2 100644--- a/src/harness/pi-harness.ts+++ b/src/harness/pi-harness.ts@@ -1430,6 +1430,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {const defaultTurnWallClockMs = opts?.turnWallClockMs ?? CONFIG_DEFAULTS.turnWallClockSec * 1000;const signals = opts?.signals;async function createTurnSession(+ model: Model<Api>,sessionId: string,systemPrompt: string,history: SessionEntry[],@@ -1484,7 +1485,6 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {const seedPlan = planColdStartSeed(seedSource, !!priorTurns?.length);const composedPrompt = systemPrompt + (seedPlan === "preamble" ? replayPreamble(history) : "");- const model = getRequiredModel(resolveModelId(turnScope), !turnProviderKeys);const modelRuntime = await buildModelRuntime(turnProviderKeys ?? (await resolveProviderKeys()),turnProviderKeys ? undefined : modelGateway,@@ -1659,7 +1659,13 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {},{async runTurn(turn: HarnessTurnInput): Promise<HarnessTurnResult> {+ const desiredModelId = turn.runtime?.modelId ?? resolveModelId(turn.scopeLabel);+ const baseModel = getRequiredModel(desiredModelId, !turn.providerKeys);+ const turnModelGateway = turn.providerKeys ? undefined : modelGateway;+ const wantFast = wantsFastMode(turn.runtime?.fastMode, desiredModelId);+ const wantFastHeader = wantFast && !turnModelGateway?.models[desiredModelId];const { entry, compileMs } = await createTurnSession(+ wantFastHeader ? withFastModeHeaders(baseModel) : baseModel,turn.session.id,turn.systemPrompt,turn.history,@@ -1678,7 +1684,6 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {turn.providerKeys,);try {- const turnModelGateway = turn.providerKeys ? undefined : modelGateway;const turnWallClockMs = turn.turnWallClockMs ?? defaultTurnWallClockMs;entry.ref.current = turn.tools;entry.ref.pendingApprovals = [];@@ -1692,19 +1697,6 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {entry.ref.screenExternalContent = turn.screenExternalContent;entry.ref.toolApprovalGate = turn.toolApprovalGate;- const desiredModelId = turn.runtime?.modelId ?? resolveModelId(turn.scopeLabel);- const wantFast = wantsFastMode(turn.runtime?.fastMode, desiredModelId);- const wantFastHeader = wantFast && !turnModelGateway?.models[desiredModelId];- const current = entry.agentSession.model as { id?: string; headers?: Record<string, string> } | undefined;- const currentFast = modelHasFastMode(current);- if (current?.id !== desiredModelId || currentFast !== wantFastHeader) {- try {- const base = resolveModel(desiredModelId, !turn.providerKeys);- if (base) await entry.agentSession.setModel(wantFastHeader ? withFastModeHeaders(base) : base);- } catch (e) {- swallow("pi: model switch", e);- }- }const activeModel = entry.agentSession.model as { id?: string; headers?: Record<string, string> } | undefined;entry.ref.fast = wantFast;const effectiveModel = activeModel?.id ?? desiredModelId;diff --git a/src/model/custom-provider-store.ts b/src/model/custom-provider-store.tsindex 285287271..6b0a151a9 100644--- a/src/model/custom-provider-store.ts+++ b/src/model/custom-provider-store.ts@@ -49,7 +49,9 @@ function strip(saved: StoredCustomProvider): CustomProviderSpec {export function createCustomProviderStore(input: {backing: DurableMap<StoredCustomProvider>;keyMaterial: string | Buffer;+ write?: <T>(fn: () => Promise<T>) => Promise<T>;}): CustomProviderStore {+ const write = input.write ?? (<T>(fn: () => Promise<T>) => fn());const key = deriveConnectorKey(input.keyMaterial, "custom-model-providers");return {@@ -78,31 +80,35 @@ export function createCustomProviderStore(input: {},async upsert(spec, apiKey, updatedBy) {- validateCustomProviderSpec(spec);- const actor = updatedBy.trim();- if (!actor) throw new Error("updatedBy is required");- const existing = await input.backing.get(spec.id);- const trimmedKey = apiKey?.trim();- const apiKeyEnc = trimmedKey ? encryptSecret(trimmedKey, key) : existing?.apiKeyEnc;- await input.backing.put(spec.id, {- ...spec,- ...(apiKeyEnc ? { apiKeyEnc } : {}),- disabled: false,- updatedAt: Date.now(),- updatedBy: actor,+ return write(async () => {+ validateCustomProviderSpec(spec);+ const actor = updatedBy.trim();+ if (!actor) throw new Error("updatedBy is required");+ const existing = await input.backing.get(spec.id);+ const trimmedKey = apiKey?.trim();+ const apiKeyEnc = trimmedKey ? encryptSecret(trimmedKey, key) : existing?.apiKeyEnc;+ await input.backing.put(spec.id, {+ ...spec,+ ...(apiKeyEnc ? { apiKeyEnc } : {}),+ disabled: false,+ updatedAt: Date.now(),+ updatedBy: actor,+ });});},async delete(id, updatedBy) {- const existing = await input.backing.get(id);- if (!existing || existing.disabled) return false;- await input.backing.put(id, {- ...existing,- disabled: true,- updatedAt: Date.now(),- updatedBy,+ return write(async () => {+ const existing = await input.backing.get(id);+ if (!existing || existing.disabled) return false;+ await input.backing.put(id, {+ ...existing,+ disabled: true,+ updatedAt: Date.now(),+ updatedBy,+ });+ return true;});- return true;},};}diff --git a/src/model/custom-providers.ts b/src/model/custom-providers.tsindex cb2a92c20..8a70008f8 100644--- a/src/model/custom-providers.ts+++ b/src/model/custom-providers.ts@@ -13,6 +13,7 @@* resolved per-call by wiring alongside the built-in provider keys.*/+import { modelIdReserved } from "./pi-models.ts";import { parseProviderBaseUrl, PROVIDER_IDS } from "./provider-endpoints.ts";export const CUSTOM_PROVIDER_PROTOCOLS = ["openai", "anthropic"] as const;@@ -61,6 +62,8 @@ export function validateCustomProviderSpec(spec: CustomProviderSpec): void {if (!m.id?.trim() || m.id.length > 200) throw new Error("every model needs an id (<=200 chars)");if (m.name !== undefined && (typeof m.name !== "string" || m.name.length > 200))throw new Error(`model "${m.id}": name must be a string of 200 chars or fewer`);+ if (modelIdReserved(m.id) || (registry.has(m.id) && registry.get(m.id)?.provider !== spec.id))+ throw new Error(`model id "${m.id}" is already registered`);if (seen.has(m.id)) throw new Error(`duplicate model id "${m.id}"`);seen.add(m.id);for (const [field, v] of [@@ -123,6 +126,8 @@ let version = 0;* built-in.*/export function setCustomProviders(specs: CustomProviderSpec[]): void {+ const snapshot = JSON.stringify(specs);+ if (snapshot === JSON.stringify(providers)) return;const next = new Map<string, CustomRuntimeModel>();for (const spec of specs) {for (const m of spec.models) {diff --git a/src/model/model-catalog.ts b/src/model/model-catalog.tsindex c487e663b..9d0c68132 100644--- a/src/model/model-catalog.ts+++ b/src/model/model-catalog.ts@@ -2,7 +2,9 @@ import {modelSupportedByHarness,registerOpenRouterCatalogModel,resolveModel,- SELECTABLE_BASE_MODELS,+ selectableBaseModels,+ modelOverlayVersion,+ overlayModelCatalog,} from "./pi-models.ts";import { customModelCatalog, customProvidersVersion } from "./custom-providers.ts";@@ -23,6 +25,8 @@ const FAILURE_TTL_MS = 30_000;interface CacheEntry {customVersion?: number;+ overlayVersion?: number;+ dynamic?: ModelCatalogEntry[];expiresAt: number;models: ModelCatalogEntry[];inFlight?: Promise<ModelCatalogEntry[]>;@@ -31,14 +35,14 @@ interface CacheEntry {const cache = new WeakMap<typeof fetch, CacheEntry>();export function builtInModelCatalog(): ModelCatalogEntry[] {- const builtIns = SELECTABLE_BASE_MODELS.flatMap((model) => {+ const builtIns = selectableBaseModels().flatMap((model) => {const provider = resolveModel(model.id)?.provider;return provider === "anthropic" || provider === "openai" || provider === "openrouter"? [{ ...model, provider: provider as string }]: [];});const known = new Set(builtIns.map((model) => model.id));- return [...builtIns, ...customModelCatalog().filter((model) => !known.has(model.id))];+ return [...builtIns, ...[...overlayModelCatalog(), ...customModelCatalog()].filter((model) => !known.has(model.id))];}async function boundedJson(response: Response): Promise<unknown> {@@ -152,25 +156,33 @@ async function fetchOpenRouterModels(fetcher: typeof fetch): Promise<ModelCataloexport async function selectableModelCatalog(fetcher: typeof fetch = fetch): Promise<ModelCatalogEntry[]> {const now = Date.now();const existing = cache.get(fetcher);- // A registry change (admin registered/removed a custom provider) must be- // visible in the next picker load, not after the TTL runs out.- if (existing && existing.expiresAt > now && existing.customVersion === customProvidersVersion())+ if (+ existing &&+ existing.expiresAt > now &&+ existing.customVersion === customProvidersVersion() &&+ existing.overlayVersion === modelOverlayVersion()+ )return existing.models;if (existing?.inFlight) return existing.inFlight;const entry = existing ?? { expiresAt: 0, models: [] };entry.inFlight = fetchOpenRouterModels(fetcher).then((dynamic) => {+ entry.dynamic = dynamic;const models = builtInModelCatalog();const known = new Set(models.map((model) => model.id));entry.models = [...models, ...dynamic.filter((model) => !known.has(model.id))];entry.expiresAt = Date.now() + CACHE_TTL_MS;entry.customVersion = customProvidersVersion();+ entry.overlayVersion = modelOverlayVersion();return entry.models;}).catch(() => {- entry.models = entry.models.length ? entry.models : builtInModelCatalog();+ const models = builtInModelCatalog();+ const known = new Set(models.map((model) => model.id));+ entry.models = [...models, ...(entry.dynamic ?? []).filter((model) => !known.has(model.id))];entry.expiresAt = Date.now() + FAILURE_TTL_MS;entry.customVersion = customProvidersVersion();+ entry.overlayVersion = modelOverlayVersion();return entry.models;}).finally(() => {diff --git a/src/model/model-overlay-store.ts b/src/model/model-overlay-store.tsnew file mode 100644index 000000000..e560d8dfd--- /dev/null+++ b/src/model/model-overlay-store.ts@@ -0,0 +1,63 @@+import type { DurableMap } from "../persistence/durable-map.ts";+import { parseModelOverlay, type ModelOverlay } from "./model-overlay.ts";+import { modelUnavailableReason, setModelOverlays, validateModelOverlay } from "./pi-models.ts";++export interface StoredModelOverlay {+ spec: ModelOverlay;+ disabled: boolean;+ updatedAt: number;+ updatedBy: string;+}++export function createModelOverlayStore(+ backing: DurableMap<StoredModelOverlay>,+ write: <T>(fn: () => Promise<T>) => Promise<T> = (fn) => fn(),+) {+ return {+ async statuses() {+ return (await backing.entries()).map(([id, row]) => {+ let spec: Partial<ModelOverlay> & { id: string };+ try {+ spec = parseModelOverlay({ ...row?.spec, id });+ } catch {+ spec = { id, name: id };+ }+ return {+ spec,+ disabled: row?.disabled === true,+ updatedAt: row?.updatedAt,+ updatedBy: row?.updatedBy,+ unavailableReason: modelUnavailableReason(id),+ };+ });+ },+ async refresh() {+ const rows = await backing.entries();+ setModelOverlays(+ rows.filter(([, row]) => row?.disabled !== true).map(([id, row]) => ({ ...row?.spec, id })),+ rows.filter(([, row]) => row?.disabled === true).map(([id]) => id),+ );+ },+ async upsert(value: unknown, updatedBy: string) {+ return write(async () => {+ const spec = validateModelOverlay(value);+ if (!updatedBy.trim()) throw new Error("updatedBy is required");+ const existing = await backing.get(spec.id);+ if (existing?.spec?.provider && existing.spec.provider !== spec.provider)+ throw new Error("provider cannot change for an existing model id");+ await backing.put(spec.id, { spec, disabled: false, updatedAt: Date.now(), updatedBy });+ });+ },+ async delete(id: string, updatedBy: string) {+ return write(async () => {+ if (!updatedBy.trim()) throw new Error("updatedBy is required");+ const existing = await backing.get(id);+ if (!existing || existing.disabled) return false;+ await backing.put(id, { ...existing, disabled: true, updatedAt: Date.now(), updatedBy });+ return true;+ });+ },+ };+}++export type ModelOverlayStore = ReturnType<typeof createModelOverlayStore>;diff --git a/src/model/model-overlay.ts b/src/model/model-overlay.tsnew file mode 100644index 000000000..952f228e3--- /dev/null+++ b/src/model/model-overlay.ts@@ -0,0 +1,40 @@+import { z } from "zod";++const price = z.number().finite().nonnegative();+const tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);+const rates = { input: price, output: price, cacheRead: price, cacheWrite: price };+const schema = z.strictObject({+ id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/),+ name: z.string().trim().min(1).max(200),+ provider: z.enum(["openai", "anthropic"]),+ template: z.string().min(1).max(200),+ contextWindow: tokens,+ maxTokens: tokens,+ cost: z.strictObject({+ ...rates,+ tiers: z+ .array(z.strictObject({ inputTokensAbove: tokens, ...rates }))+ .max(20)+ .optional(),+ }),+ fastMode: z.boolean().default(false),+ base: z.boolean().default(true),+ webui: z.boolean().default(true),+ auxiliary: z.boolean().default(false),+});++export type ModelOverlay = z.infer<typeof schema>;++export function parseModelOverlay(value: unknown): ModelOverlay {+ const model = schema.parse(value);+ if (model.maxTokens >= model.contextWindow) throw new Error("maxTokens must be less than contextWindow");+ if (model.fastMode && model.provider !== "anthropic")+ throw new Error("fast mode is supported only for Anthropic models");+ let previous = 0;+ for (const tier of model.cost.tiers ?? []) {+ if (tier.inputTokensAbove <= previous || tier.inputTokensAbove >= model.contextWindow)+ throw new Error("tier thresholds must increase and be below contextWindow");+ previous = tier.inputTokensAbove;+ }+ return model;+}diff --git a/src/model/pi-models.ts b/src/model/pi-models.tsindex bc765e2e6..c1a7b11da 100644--- a/src/model/pi-models.ts+++ b/src/model/pi-models.ts@@ -1,5 +1,6 @@import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";import type { Api, Model } from "@earendil-works/pi-ai";+import { parseModelOverlay, type ModelOverlay } from "./model-overlay.ts";import { providerBaseUrl } from "./provider-endpoints.ts";import { isCustomModelId, resolveCustomModel } from "./custom-providers.ts";@@ -50,6 +51,8 @@ interface ModelEntry {id: string;name: string;fastMode: boolean;+ label?: string;+ buttonLabel?: string;webui: boolean;base: boolean;auxiliary?: boolean;@@ -112,6 +115,7 @@ export const MODEL_REGISTRY: readonly ModelEntry[] = [{ id: "claude-haiku-4-5", name: "Claude Haiku 4.5", fastMode: false, webui: true, base: true, auxiliary: true },{id: "gpt-5.6-sol",+ buttonLabel: "5.6 Sol",name: "GPT-5.6 Sol",fastMode: true,webui: true,@@ -126,6 +130,7 @@ export const MODEL_REGISTRY: readonly ModelEntry[] = [},{id: "gpt-5.6-terra",+ buttonLabel: "5.6 Terra",name: "GPT-5.6 Terra",fastMode: true,webui: true,@@ -140,6 +145,7 @@ export const MODEL_REGISTRY: readonly ModelEntry[] = [},{id: "gpt-5.6-luna",+ buttonLabel: "5.6 Luna",name: "GPT-5.6 Luna",fastMode: true,webui: true,@@ -155,6 +161,7 @@ export const MODEL_REGISTRY: readonly ModelEntry[] = [},{id: "gpt-6-astra",+ buttonLabel: "Astra",name: "GPT-6 Astra",fastMode: true,webui: true,@@ -173,11 +180,118 @@ export const MODEL_REGISTRY: readonly ModelEntry[] = [{ id: "claude-opus-4-6", name: "Claude Opus 4.6", fastMode: false, webui: false, base: false },];+let overlays = new Map<string, ModelOverlay>();+let unavailableOverlays = new Map<string, string>();+let overlayVersion = 0;+let overlaySnapshot = JSON.stringify([[], [], []]);++export function modelOverlayVersion(): number {+ return overlayVersion;+}++export function isOverlayModel(id: string): boolean {+ return overlays.has(id);+}++export function modelOfferedInWebui(id: string): boolean {+ return overlays.get(id)?.webui ?? true;+}++export function modelUnavailableReason(id: string): string | undefined {+ return unavailableOverlays.get(id);+}++export function modelIdReserved(id: string): boolean {+ return (+ id.startsWith(CODEX_SUBSCRIPTION_PREFIX) ||+ REGISTRY_BY_ID.has(id) ||+ Boolean(builtinModel(id)) ||+ overlays.has(id) ||+ unavailableOverlays.has(id) ||+ OPENROUTER_CATALOG_MODELS.has(id)+ );+}++export function validateModelOverlay(value: unknown): ModelOverlay {+ const spec = parseModelOverlay(value);+ if (+ REGISTRY_BY_ID.has(spec.id) ||+ builtinModel(spec.id) ||+ isCustomModelId(spec.id) ||+ OPENROUTER_CATALOG_MODELS.has(spec.id)+ )+ throw new Error("model id is already registered");+ const template = resolveBuiltinModel(spec.template);+ if (!template || template.provider !== spec.provider)+ throw new Error("template must be a builtin model of the declared provider");+ return spec;+}++export function setModelOverlays(specs: readonly unknown[], deleted: string[] = []): void {+ const next = new Map<string, ModelOverlay>();+ const unavailable = new Map(deleted.map((id) => [id, "Model has been deleted; select another model"]));+ for (const value of specs) {+ const id =+ value && typeof value === "object" && "id" in value && typeof value.id === "string" ? value.id : undefined;+ if (!id) continue;+ try {+ const spec = parseModelOverlay(value);+ const builtin = resolveBuiltinModel(id);+ if (builtin) {+ if (builtin.provider !== spec.provider)+ unavailable.set(id, "Builtin provider differs from the stored model; choose another model");+ continue;+ }+ const template = resolveBuiltinModel(spec.template);+ if (!template || template.provider !== spec.provider) {+ unavailable.set(+ id,+ "Builtin template is unavailable or has a different provider; ask an administrator to repair this model",+ );+ } else if (isCustomModelId(id) || OPENROUTER_CATALOG_MODELS.has(id)) {+ unavailable.set(id, "Model id conflicts with another provider; ask an administrator to repair this model");+ } else next.set(id, spec);+ } catch {+ unavailable.set(id, "Stored model definition is invalid; ask an administrator to repair this model");+ }+ }+ const snapshot = JSON.stringify([[...next], [...unavailable], deleted]);+ if (snapshot === overlaySnapshot) return;+ overlays = next;+ unavailableOverlays = unavailable;+ overlaySnapshot = snapshot;+ overlayVersion += 1;+}++export function selectableBaseModels(): ReadonlyArray<{ id: string; name: string }> {+ return [+ ...SELECTABLE_BASE_MODELS.filter(({ id }) => resolveModel(id)),+ ...[...overlays.values()].filter((m) => m.base).map(({ id, name }) => ({ id, name })),+ ];+}++export function overlayModelCatalog(): Array<{ id: string; name: string; provider: string }> {+ return [...overlays.values()]+ .filter((m) => m.base || m.webui)+ .map(({ id, name, provider }) => ({ id, name, provider }));+}++export function defaultWebuiModelIds(): readonly string[] {+ return [...DEFAULT_WEBUI_MODEL_IDS, ...[...overlays.values()].filter((m) => m.webui).map((m) => m.id)];+}++export function fastModeModelIds(): readonly string[] {+ return [+ ...FAST_MODE_MODEL_IDS.filter(modelSupportsFastMode),+ ...[...overlays.values()].filter((m) => modelSupportsFastMode(m.id)).map((m) => m.id),+ ];+}+const REGISTRY_BY_ID = new Map(MODEL_REGISTRY.map((m) => [m.id, m]));const OPENROUTER_CATALOG_MODELS = new Map<string, PiModel>();export function modelDisplayName(id: string): string {- return REGISTRY_BY_ID.get(id)?.name ?? OPENROUTER_CATALOG_MODELS.get(id)?.name ?? id;+ return overlays.get(id)?.name ?? REGISTRY_BY_ID.get(id)?.name ?? OPENROUTER_CATALOG_MODELS.get(id)?.name ?? id;}export const DEFAULT_WEBUI_MODEL_IDS: readonly string[] = MODEL_REGISTRY.filter((m) => m.webui).map((m) => m.id);@@ -202,7 +316,7 @@ function cloneModel(model: PiModel, id: string, name: string, overrides: Partialid,name,input: [...model.input],- cost: { ...model.cost, ...overrides.cost },+ cost: structuredClone(overrides.cost ?? model.cost),...(model.headers ? { headers: { ...model.headers } } : {}),...(model.thinkingLevelMap ? { thinkingLevelMap: { ...model.thinkingLevelMap } } : {}),...(model.compat ? { compat: { ...(model.compat as Record<string, unknown>) } as PiModel["compat"] } : {}),@@ -220,6 +334,8 @@ export interface OpenRouterCatalogModel {}export function registerOpenRouterCatalogModel(definition: OpenRouterCatalogModel): PiModel | undefined {+ if (modelIdReserved(definition.id) && resolveModel(definition.id)?.provider !== "openrouter") return undefined;+ if (isCustomModelId(definition.id)) return undefined;const template = builtinModel("openrouter/auto");if (!template) return undefined;const model = cloneModel(template, definition.id, definition.name, {@@ -238,7 +354,7 @@ export function registerOpenRouterCatalogModel(definition: OpenRouterCatalogModereturn model;}-function resolveBaseModel(id: string): PiModel | undefined {+function resolveBuiltinModel(id: string): PiModel | undefined {if (id.startsWith(CODEX_SUBSCRIPTION_PREFIX)) {const m = getModel(CODEX_SUBSCRIPTION_PROVIDER, id.slice(CODEX_SUBSCRIPTION_PREFIX.length));// Keep the namespaced id: pi resolves the turn's model by this string,@@ -263,9 +379,25 @@ function resolveBaseModel(id: string): PiModel | undefined {}): undefined;}- return (- builtinModel(id) ?? (resolveCustomModel(id) as unknown as PiModel | undefined) ?? OPENROUTER_CATALOG_MODELS.get(id)- );+ return builtinModel(id);+}++function resolveBaseModel(id: string): PiModel | undefined {+ if (unavailableOverlays.has(id)) return undefined;+ const builtin = resolveBuiltinModel(id);+ if (builtin) return builtin;+ const overlay = overlays.get(id);+ if (overlay) {+ const template = resolveBuiltinModel(overlay.template);+ return template+ ? cloneModel(template, id, overlay.name, {+ contextWindow: overlay.contextWindow,+ maxTokens: overlay.maxTokens,+ cost: structuredClone(overlay.cost),+ })+ : undefined;+ }+ return (resolveCustomModel(id) as unknown as PiModel | undefined) ?? OPENROUTER_CATALOG_MODELS.get(id);}export function resolveModel(id: string, useOrgEndpoints = true): PiModel | undefined {@@ -276,7 +408,8 @@ export function resolveModel(id: string, useOrgEndpoints = true): PiModel | unde}export function auxiliaryModelForProvider(provider: string): string | undefined {- return MODEL_REGISTRY.find((m) => m.auxiliary && resolveModel(m.id)?.provider === provider)?.id;+ return [...MODEL_REGISTRY, ...overlays.values()].find((m) => m.auxiliary && resolveModel(m.id)?.provider === provider)+ ?.id;}export function auxiliaryModelFor(baseModelId: string): string {@@ -297,7 +430,8 @@ export function contextTokenBudgetForModel(id: string): number | undefined {}export function modelSupportedByHarness(id: string | undefined, harness: string): boolean {- if (!id) return false;+ if (!id || unavailableOverlays.has(id)) return false;+ if (overlays.has(id)) return harness === "pi" || harness === "mock";if (isCustomModelId(id) && !REGISTRY_BY_ID.has(id))return harness === "pi" || harness === "opencode" || harness === "mock";if (harness === "pi" || harness === "opencode" || harness === "mock") return Boolean(resolveModel(id));@@ -312,10 +446,11 @@ export function defaultModelForHarness(configured?: string,providers?: ModelProviderAvailability,): string {- if (configured && modelSupportedByHarness(configured, harness)) return configured;+ if (configured && (modelUnavailableReason(configured) || modelSupportedByHarness(configured, harness)))+ return configured;const preferred = harness === "codex" ? DEFAULT_CODEX_MODEL_ID : DEFAULT_AGENT_MODEL_ID;if (!providers || modelServiceable(preferred, providers)) return preferred;- const servable = SELECTABLE_BASE_MODELS.find(+ const servable = selectableBaseModels().find((model) => modelSupportedByHarness(model.id, harness) && modelServiceable(model.id, providers),);return servable?.id ?? preferred;@@ -380,7 +515,9 @@ export function getRequiredModel(id: string, useOrgEndpoints = true): PiModel {}export function modelSupportsFastMode(modelId: string | undefined): boolean {- return !!modelId && (REGISTRY_BY_ID.get(modelId)?.fastMode ?? false);+ if (!modelId) return false;+ if (unavailableOverlays.has(modelId)) return false;+ return overlays.get(modelId)?.fastMode ?? REGISTRY_BY_ID.get(modelId)?.fastMode ?? false;}export const FAST_MODE_MODEL_IDS: readonly string[] = MODEL_REGISTRY.filter((m) => m.fastMode).map((m) => m.id);@@ -391,3 +528,26 @@ export function defaultInteractiveThinkingLevel(model: Pick<PiModel, "api" | "pr}export const DEFAULT_AGENT_INPUT_USD_PER_MTOK = 5;++export function safeModelMetadata(id: string) {+ const model = resolveModel(id);+ if (!model) return undefined;+ const entry = REGISTRY_BY_ID.get(id);+ const name = modelDisplayName(id) === id ? model.name : modelDisplayName(id);+ const label = entry?.label ?? (entry ? name.replace(/^Claude /, "") : name);+ const buttonLabel = entry?.buttonLabel ?? label;+ return {+ id,+ name,+ label,+ buttonLabel,+ provider: String(model.provider),+ api: model.api,+ reasoning: model.reasoning,+ input: [...model.input],+ contextWindow: model.contextWindow,+ maxTokens: model.maxTokens,+ cost: structuredClone(model.cost),+ fastMode: modelSupportsFastMode(id),+ };+}diff --git a/src/wiring.ts b/src/wiring.tsindex 207942d42..9e623bbfc 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1,5 +1,6 @@import { createAwsRoleBroker, type AwsRoleBroker } from "./auth/aws-role-broker.ts";import type { SessionShare, SessionShareStore } from "./sessions/session-share.ts";+import { createModelOverlayStore, type ModelOverlayStore } from "./model/model-overlay-store.ts";import { mkdirSync } from "node:fs";import type { StagedEnvelope } from "./slack/envelope-staging.ts";import { randomBytes, randomUUID } from "node:crypto";@@ -318,6 +319,7 @@ import {modelProviderAvailabilityFor,resolveModel,type HarnessId,+ modelSupportedByHarness,} from "./model/pi-models.ts";import { createAdminService, bootAdminGrantSeed, type AdminService } from "./admin/admin-service.ts";import { createAdminGrantStore, createMapAdminGrantPersistence, type AdminGrant } from "./admin/admin-grant-store.ts";@@ -404,6 +406,8 @@ export interface BuiltApp {modelGateway: ModelGateway;modelCredentials: ModelCredentialStore;userModelCredentials: UserModelCredentialStore;+ modelRegistry: ModelOverlayStore;+ refreshModels: () => Promise<void>;customProviders: CustomProviderStore;refreshCustomProviders: () => Promise<void>;mcpServers: McpServerStore;@@ -978,17 +982,26 @@ export function buildApp(? createPostgresRunSignalStore(requireDbUrl("RUN_STORE")): createMemoryRunSignalStore();const tasks = config.databaseUrl ? createPostgresTaskStore(config.databaseUrl) : createMemoryTaskStore();+ const writeModelRegistry = <T>(fn: () => Promise<T>): Promise<T> =>+ advisoryLock.withLock("model-registry", async () => {+ await refreshModels();+ return fn();+ });const customProviders = createCustomProviderStore({+ write: writeModelRegistry,backing: artifactMap("custom_model_providers"),keyMaterial: config.connectorSecretKey ?? randomBytes(32),});+ const modelRegistry = createModelOverlayStore(artifactMap("model_registry"), writeModelRegistry);const refreshCustomProviders = async () => {setCustomProviders(await customProviders.enabled());};- void refreshCustomProviders().catch((e) =>- console.error("[wiring] custom provider hydration failed:", errMessage(e)),- );+ const refreshModels = async () => {+ await refreshCustomProviders();+ await modelRegistry.refresh();+ };const resolveModelProviderKeys = async () => {+ await refreshModels();const [anthropic, openai, openrouter, enabledCustom] = await Promise.all([modelCredentials.resolve("anthropic"),modelCredentials.resolve("openai"),@@ -1106,11 +1119,15 @@ export function buildApp(};const judgeModelId = (): string => config.judgeModelId ?? auxiliaryModelFor(orgBaseModelId() ?? fallback.modelId);const hydrateModelCatalog = async (): Promise<unknown> => {+ await refreshModels();if (!(await modelCredentials.availability()).openrouter) return undefined;return selectableModelCatalog(overrides.modelCredentialFetch);};- const harness = createHarnessRouter(adapters, adapters.get(fallbackHarness)!, (input) => {+ const harness = createHarnessRouter(adapters, adapters.get(fallbackHarness)!, async (input) => {+ await refreshModels();if (input.runtimePinned && input.runtime?.harnessId && input.runtime.modelId) {+ if (!modelSupportedByHarness(input.runtime.modelId, input.runtime.harnessId))+ throw new Error(`Unsupported model: ${input.runtime.modelId}`);return { ...input.runtime, harnessId: input.runtime.harnessId, modelId: input.runtime.modelId };}return resolveRuntimeChoiceDurable(@@ -1354,6 +1371,7 @@ export function buildApp(return broker;};const orchestratorDeps: OrchestratorDeps = {+ refreshModels,identity,resolution,config: configStore,@@ -1550,6 +1568,8 @@ export function buildApp(modelGateway,modelCredentials,userModelCredentials,+ modelRegistry,+ refreshModels,customProviders,refreshCustomProviders,mcpServers,@@ -1950,6 +1970,8 @@ export function buildApp(modelGateway,modelCredentials,userModelCredentials,+ modelRegistry,+ refreshModels,customProviders,refreshCustomProviders,mcpServers,@@ -2034,6 +2056,8 @@ export function serverDeps(providerKeys: providerKeysPresent(config),modelCredentials: built.modelCredentials,userModelCredentials: built.userModelCredentials,+ modelRegistry: built.modelRegistry,+ refreshModels: built.refreshModels,customProviders: built.customProviders,refreshCustomProviders: built.refreshCustomProviders,mcpServers: built.mcpServers,diff --git a/test/model-credential-route.test.ts b/test/model-credential-route.test.tsindex f479318f0..e49ec9f78 100644--- a/test/model-credential-route.test.ts+++ b/test/model-credential-route.test.ts@@ -305,10 +305,8 @@ test("OpenRouter catalog exposes runtime-supported tool models as selectable baseffective: { harnessId: string; modelId: string };};assert.ok(runtimeBody.modelsByHarness.pi!.includes("stealth/ox-alpha"));- assert.deepEqual(runtimeBody.modelCatalog["stealth/ox-alpha"], {- name: "Ox Alpha",- provider: "openrouter",- });+ assert.equal(runtimeBody.modelCatalog["stealth/ox-alpha"]?.name, "Ox Alpha");+ assert.equal(runtimeBody.modelCatalog["stealth/ox-alpha"]?.provider, "openrouter");assert.deepEqual(runtimeBody.effective, { harnessId: "pi", modelId: "stealth/ox-alpha" });const surface = await fetch(`${srv.base}/v1/surface-config`);diff --git a/test/model-overlay-postgres.test.ts b/test/model-overlay-postgres.test.tsnew file mode 100644index 000000000..5ab2050df--- /dev/null+++ b/test/model-overlay-postgres.test.ts@@ -0,0 +1,127 @@+import assert from "node:assert/strict";+import { fork, type ChildProcess } from "node:child_process";+import { once } from "node:events";+import { test } from "node:test";+import { createPostgresMapFactory } from "../src/persistence/durable-map.ts";+import { createModelOverlayStore } from "../src/model/model-overlay-store.ts";++const databaseUrl = process.env.MODEL_OVERLAY_TEST_DATABASE_URL;+const headers = { "content-type": "application/json", "x-admin-actor": "admin-alice@default-org" };+const runtimePath = "/v1/runtime-config?principalId=admin-alice@default-org&scopeId=personal:admin-alice@default-org";++async function start() {+ const child = fork(new URL("./support/model-overlay-server.ts", import.meta.url), {+ stdio: ["ignore", "ignore", "ignore", "ipc"],+ });+ const timeout = setTimeout(() => child.kill(), 30_000);+ const message = await Promise.race([+ once(child, "message"),+ once(child, "exit").then(() => {+ throw new Error("local API child exited before listening");+ }),+ ]);+ clearTimeout(timeout);+ return { child, base: (message[0] as { base: string }).base };+}++async function stop(child: ChildProcess) {+ const exited = once(child, "exit");+ child.kill();+ await exited;+}++test(+ "Postgres persistence: two serving processes refresh add/update/delete, including a cold start",+ { skip: !databaseUrl, timeout: 90_000 },+ async () => {+ assert.ok(databaseUrl);+ assert.ok(+ ["127.0.0.1", "localhost"].includes(new URL(databaseUrl).hostname),+ "use a dedicated local test database",+ );+ const factory = createPostgresMapFactory(databaseUrl);+ const backing = factory.map<import("../src/model/model-overlay-store.ts").StoredModelOverlay>("model_registry");+ await backing.delete("overlay-pg-model");+ await backing.delete("overlay-race-model");+ const customs = factory.map("custom_model_providers");+ await customs.delete("race-gateway");+ const processes: ChildProcess[] = [];+ try {+ const first = await start();+ processes.push(first.child);+ const second = await start();+ processes.push(second.child);+ const read = async (base: string) => {+ const response = await fetch(base + runtimePath, { headers });+ assert.equal(response.status, 200);+ return (await response.json()) as {+ effective: { modelId: string };+ unavailableReason?: string;+ modelCatalog: Record<string, { name: string; contextWindow: number }>;+ };+ };+ assert.equal((await read(second.base)).modelCatalog["overlay-pg-model"], undefined);+ const spec = {+ name: "Future PG model",+ provider: "openai",+ template: "gpt-5.5",+ contextWindow: 400_000,+ maxTokens: 20_000,+ cost: { input: 7, output: 21, cacheRead: 0.3, cacheWrite: 8 },+ };+ const path = first.base + "/v1/admin/model-registry/overlay-pg-model";+ assert.equal((await fetch(path, { method: "PUT", headers, body: JSON.stringify(spec) })).status, 200);+ assert.equal((await read(second.base)).modelCatalog["overlay-pg-model"]?.contextWindow, 400_000);+ assert.equal((await read(second.base)).effective.modelId, "overlay-pg-model");+ assert.equal(+ (await fetch(path, { method: "PUT", headers, body: JSON.stringify({ ...spec, contextWindow: 600_000 }) }))+ .status,+ 200,+ );+ assert.equal((await read(second.base)).modelCatalog["overlay-pg-model"]?.contextWindow, 600_000);+ const raced = await Promise.all([+ fetch(first.base + "/v1/admin/model-registry/overlay-race-model", {+ method: "PUT",+ headers,+ body: JSON.stringify(spec),+ }),+ fetch(second.base + "/v1/admin/custom-providers/race-gateway", {+ method: "PUT",+ headers,+ body: JSON.stringify({+ name: "Race gateway",+ protocol: "openai",+ baseUrl: "https://example.invalid/v1",+ models: [{ id: "overlay-race-model" }],+ }),+ }),+ ]);+ assert.deepEqual(raced.map((response) => response.status).sort(), [200, 400]);+ await read(first.base);+ await read(second.base);+ const cold = await start();+ processes.push(cold.child);+ const coldConfig = await read(cold.base);+ assert.equal(coldConfig.effective.modelId, "overlay-pg-model");+ assert.equal(coldConfig.modelCatalog["overlay-pg-model"]?.contextWindow, 600_000);+ const reloaded = createModelOverlayStore(factory.map("model_registry"));+ assert.equal(+ (await reloaded.statuses()).find((m) => m.spec.id === "overlay-pg-model")?.spec.contextWindow,+ 600_000,+ );+ assert.equal((await fetch(path, { method: "DELETE", headers })).status, 200);+ for (const instance of [second, cold]) {+ const deleted = await read(instance.base);+ assert.equal(deleted.modelCatalog["overlay-pg-model"], undefined);+ assert.equal(deleted.effective.modelId, "overlay-pg-model");+ assert.match(deleted.unavailableReason ?? "", /deleted/);+ }+ } finally {+ await Promise.all(processes.map(stop));+ await backing.delete("overlay-pg-model");+ await backing.delete("overlay-race-model");+ await customs.delete("race-gateway");+ await factory.pool.close();+ }+ },+);diff --git a/test/model-overlay.test.ts b/test/model-overlay.test.tsnew file mode 100644index 000000000..e9bbbddce--- /dev/null+++ b/test/model-overlay.test.ts@@ -0,0 +1,517 @@+import "./support/auto-fake-sprites.ts";+import assert from "node:assert/strict";+import { test } from "node:test";+import type { AddressInfo } from "node:net";+import { createInsecureTestServer } from "../src/api/server.ts";+import { buildApp, serverDeps } from "../src/wiring.ts";+import { testConfig } from "./support/test-config.ts";+import { getRequiredModel } from "../src/model/pi-models.ts";++const ADMIN = { "content-type": "application/json", "x-admin-actor": "admin-alice@default-org" };+const MODEL_ID = "overlay-future-model";++test("unknown builtin-provider model fails resolution and a live runtime selection request", async () => {+ assert.throws(() => getRequiredModel(MODEL_ID), /Unsupported model/);+ const config = testConfig({ harness: "pi" });+ const built = buildApp(config, { modelCredentialFetch: async () => Response.json({ data: [] }) });+ const server = createInsecureTestServer(built.app, serverDeps(config, built));+ server.listen(0, "127.0.0.1");+ await new Promise<void>((resolve) => server.once("listening", resolve));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ try {+ const response = await fetch(`${base}/v1/runtime-config`, {+ method: "PUT",+ headers: ADMIN,+ body: JSON.stringify({+ principalId: "admin-alice@default-org",+ scopeId: "personal:admin-alice@default-org",+ harnessId: "pi",+ modelId: MODEL_ID,+ }),+ });+ const body = await response.json();+ assert.equal(response.status, 400, JSON.stringify(body));+ assert.match(JSON.stringify(body), /model|supported/);+ console.log(`Baseline: unknown model resolution throws; live runtime selection HTTP ${response.status}`);+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++import { afterEach } from "node:test";+import { createMemoryMap } from "../src/persistence/durable-map.ts";+import { createModelOverlayStore, type StoredModelOverlay } from "../src/model/model-overlay-store.ts";+import {+ setModelOverlays,+ validateModelOverlay,+ resolveModel,+ contextTokenBudgetForModel,+ safeModelMetadata,+ modelSupportedByHarness,+ modelSupportsFastMode,+ fastModeModelIds,+ defaultWebuiModelIds,+} from "../src/model/pi-models.ts";+import { setCustomProviders, validateCustomProviderSpec } from "../src/model/custom-providers.ts";+import { selectableModelCatalog } from "../src/model/model-catalog.ts";+import { resolveIndividualAuthRouting } from "../src/core/individual-auth-routing.ts";+import { validateWebTurnModelOptions } from "../src/core/turn-options.ts";++const spec = {+ id: MODEL_ID,+ name: "Future API model",+ provider: "openai",+ template: "gpt-5.5",+ contextWindow: 400_000,+ maxTokens: 20_000,+ cost: {+ input: 7,+ output: 21,+ cacheRead: 0.3,+ cacheWrite: 8,+ tiers: [{ inputTokensAbove: 200_000, input: 14, output: 42, cacheRead: 0.6, cacheWrite: 16 }],+ },+};++afterEach(() => {+ setModelOverlays([]);+ setCustomProviders([]);+});++test("strict overlay validation rejects malformed fields, prices, bounds, reserved ids and incompatible templates", () => {+ for (const invalid of [+ null,+ [],+ { ...spec, provider: "openrouter" },+ { ...spec, provider: "anthropic" },+ { ...spec, template: MODEL_ID },+ { ...spec, name: 3 },+ { ...spec, id: "codex/gpt-new" },+ { ...spec, id: "vendor/new" },+ { ...spec, id: "gpt-5.5" },+ { ...spec, id: "gpt-6-astra" },+ { ...spec, baseUrl: "https://example.invalid" },+ { ...spec, headers: {} },+ { ...spec, apiKey: "invalid" },+ { ...spec, base: "true" },+ { ...spec, fastMode: "true" },+ { ...spec, fastMode: true },+ { ...spec, maxTokens: 400_000 },+ { ...spec, contextWindow: 1.2 },+ { ...spec, cost: { ...spec.cost, input: Infinity } },+ { ...spec, cost: { ...spec.cost, output: -1 } },+ { ...spec, cost: { input: 1, output: 2 } },+ { ...spec, cost: { ...spec.cost, tiers: [{ ...spec.cost.tiers[0], inputTokensAbove: 400_000 }] } },+ ]) {+ assert.throws(() => validateModelOverlay(invalid));+ }+ assert.equal(validateModelOverlay(spec).base, true);+ assert.equal(validateModelOverlay(spec).webui, true);+ assert.equal(validateModelOverlay(spec).auxiliary, false);+});++test("store reload and independent readers observe edits and soft deletion without mutating in-flight models", async () => {+ const backing = createMemoryMap<StoredModelOverlay>();+ const writer = createModelOverlayStore(backing);+ const reader = createModelOverlayStore(backing);+ await writer.upsert(spec, "admin");+ assert.equal(resolveModel(MODEL_ID), undefined);+ await reader.refresh();+ const inFlight = getRequiredModel(MODEL_ID);+ assert.equal(contextTokenBudgetForModel(MODEL_ID), 190_000);+ assert.deepEqual(inFlight.cost, spec.cost);+ assert.ok(defaultWebuiModelIds().includes(MODEL_ID));+ assert.equal(validateWebTurnModelOptions({ model: MODEL_ID }, null), null);+ for (const harness of ["pi", "mock"]) assert.equal(modelSupportedByHarness(MODEL_ID, harness), true);+ for (const harness of ["codex", "claude", "opencode"])+ assert.equal(modelSupportedByHarness(MODEL_ID, harness), false);+ assert.equal(resolveModel(`codex/${MODEL_ID}`), undefined);+ await writer.upsert(+ { ...spec, contextWindow: 600_000, cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 } },+ "editor",+ );+ await reader.refresh();+ assert.equal(contextTokenBudgetForModel(MODEL_ID), 290_000);+ assert.equal(getRequiredModel(MODEL_ID).cost.input, 1);+ assert.equal(getRequiredModel(MODEL_ID).cost.tiers, undefined);+ assert.equal(inFlight.contextWindow, 400_000);+ assert.deepEqual(inFlight.cost, spec.cost);+ setModelOverlays([]);+ await createModelOverlayStore(backing).refresh();+ assert.equal(getRequiredModel(MODEL_ID).contextWindow, 600_000);+ assert.equal(await writer.delete(MODEL_ID, "admin"), true);+ await reader.refresh();+ assert.equal(resolveModel(MODEL_ID), undefined);+ assert.equal(modelSupportedByHarness(MODEL_ID, "codex"), false);+ assert.equal(await writer.delete(MODEL_ID, "admin"), false);+ const row = (await reader.statuses())[0]!;+ assert.equal(row.disabled, true);+ assert.equal(row.updatedBy, "admin");+});++test("template capabilities are inherited and overlay API models cannot silently use subscription routing", () => {+ setModelOverlays([validateModelOverlay({ ...spec, provider: "anthropic", template: "claude-opus-4-8" })]);+ assert.equal(modelSupportsFastMode(MODEL_ID), false);+ assert.equal(wantsFastMode(true, MODEL_ID), false);+ assert.equal(safeModelMetadata(MODEL_ID)?.fastMode, false);+ assert.ok(!fastModeModelIds().includes(MODEL_ID));+ setModelOverlays([+ validateModelOverlay({ ...spec, provider: "anthropic", template: "claude-opus-4-8", fastMode: true }),+ ]);+ assert.equal(modelSupportsFastMode(MODEL_ID), true);+ assert.equal(wantsFastMode(true, MODEL_ID), true);+ assert.equal(safeModelMetadata(MODEL_ID)?.fastMode, true);+ assert.ok(fastModeModelIds().includes(MODEL_ID));+ assert.deepEqual(getRequiredModel(MODEL_ID).input, getRequiredModel("claude-opus-4-8").input);+ assert.equal(getRequiredModel(MODEL_ID).reasoning, getRequiredModel("claude-opus-4-8").reasoning);+ assert.equal(+ resolveIndividualAuthRouting(+ { provider: "anthropic", kind: "oauth", oauth: {}, updatedAt: 1 },+ null,+ MODEL_ID,+ "pi",+ ),+ null,+ );+});++test("collisions are rejected in both registration orders and OpenRouter failure rebuilds local choices", async () => {+ const custom = {+ id: "gateway",+ name: "Gateway",+ protocol: "openai" as const,+ baseUrl: "https://example.invalid/v1",+ models: [{ id: MODEL_ID }],+ };+ setCustomProviders([custom]);+ assert.throws(() => validateModelOverlay(spec), /already registered/);+ setCustomProviders([]);+ let fail = false;+ const fetcher: typeof fetch = async () => {+ if (fail) throw new Error("offline");+ return Response.json({ data: [] });+ };+ await selectableModelCatalog(fetcher);+ setModelOverlays([validateModelOverlay(spec)]);+ assert.throws(() => validateCustomProviderSpec(custom), /already registered/);+ fail = true;+ assert.ok((await selectableModelCatalog(fetcher)).some((m) => m.id === MODEL_ID));+ setModelOverlays([], [MODEL_ID]);+ assert.ok(!(await selectableModelCatalog(fetcher)).some((m) => m.id === MODEL_ID));+ assert.throws(() => validateCustomProviderSpec(custom), /already registered/);+});++test("live admin lifecycle is authorized, audited, immediately selectable and removed on delete", async () => {+ const config = testConfig({ harness: "pi", openaiApiKey: "local-test-key" });+ const built = buildApp(config, { modelCredentialFetch: async () => Response.json({ data: [] }) });+ const server = createInsecureTestServer(built.app, serverDeps(config, built));+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const api = (path: string, method = "GET", body?: unknown, headers = ADMIN) =>+ fetch(`${base}${path}`, { method, headers, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ const path = `/v1/admin/model-registry/${MODEL_ID}`;+ const runtime = {+ principalId: "admin-alice@default-org",+ scopeId: "personal:admin-alice@default-org",+ harnessId: "pi",+ modelId: MODEL_ID,+ };+ try {+ for (const method of ["PUT", "DELETE"])+ assert.equal(+ (await api(path, method, method === "PUT" ? spec : undefined, { ...ADMIN, "x-admin-actor": "bob@default-org" }))+ .status,+ 403,+ );+ assert.equal(+ (await api("/v1/admin/model-registry", "GET", undefined, { ...ADMIN, "x-admin-actor": "bob@default-org" }))+ .status,+ 403,+ );+ assert.equal((await api(path, "PUT", { ...spec, contextWindow: "400000" })).status, 400);+ assert.equal((await api(path, "PUT", spec)).status, 200);+ const response = await api("/v1/runtime-config", "PUT", runtime);+ assert.equal(response.status, 200);+ const body = (await response.json()) as {+ modelCatalog: Record<string, ReturnType<typeof safeModelMetadata>>;+ modelsByHarness: Record<string, string[]>;+ };+ assert.equal(body.modelCatalog[MODEL_ID]?.contextWindow, 400_000);+ assert.deepEqual(body.modelCatalog[MODEL_ID]?.cost, spec.cost);+ assert.ok(body.modelsByHarness.pi?.includes(MODEL_ID));+ const wire = JSON.stringify(body.modelCatalog);+ assert.doesNotMatch(wire, /baseUrl|headers|apiKey|local-test-key/);+ const turn = await built.app.turn({+ surface: "web",+ actor: { externalId: "alice" },+ conversation: { kind: "dm", threadRef: "overlay-live-test" },+ text: "hello",+ model: MODEL_ID,+ async: true,+ });+ assert.equal(turn.status, "queued");+ assert.equal((await api(path, "PUT", { ...spec, name: "Renamed", maxTokens: 30_000 })).status, 200);+ assert.equal(getRequiredModel(MODEL_ID).name, "Renamed");+ await built.config.setRuntimeSelectionLatest("org:default-org", { harnessId: "pi", modelId: MODEL_ID });+ assert.equal((await api(path, "DELETE")).status, 200);+ const afterDelete = await api(+ "/v1/runtime-config?principalId=admin-alice@default-org&scopeId=personal:admin-alice@default-org",+ );+ const unavailable = (await afterDelete.json()) as {+ effective: { modelId: string };+ scopeOverride: { modelId: string };+ unavailableReason: string;+ modelsByHarness: { pi: string[] };+ };+ assert.equal(unavailable.effective.modelId, MODEL_ID);+ assert.equal(unavailable.scopeOverride.modelId, MODEL_ID);+ assert.match(unavailable.unavailableReason, /deleted/);+ assert.ok(unavailable.modelsByHarness.pi.includes("gpt-5.6-sol"));+ assert.equal((await api("/v1/runtime-config", "PUT", runtime)).status, 400);+ const deletedTurn = await built.app.turn({+ surface: "web",+ actor: { externalId: "alice" },+ conversation: { kind: "dm", threadRef: "overlay-deleted-test" },+ text: "hello",+ model: MODEL_ID,+ async: true,+ });+ assert.equal(deletedTurn.status, "refused");+ assert.match(JSON.stringify(deletedTurn), /couldn.t set up that runtime choice/);+ const recovered = await api("/v1/runtime-config", "PUT", { ...runtime, modelId: "gpt-5.6-sol" });+ assert.equal(recovered.status, 200);+ assert.equal(((await recovered.json()) as { effective: { modelId: string } }).effective.modelId, "gpt-5.6-sol");+ for (const model of [undefined, "gpt-5.6-sol"]) {+ const recoveredTurn = await built.app.turn({+ surface: "web",+ actor: { externalId: runtime.principalId },+ conversation: { kind: "dm", threadRef: `overlay-recovered-${model ?? "saved-selection"}` },+ text: "Continue with the replacement I selected",+ ...(model ? { model } : {}),+ async: true,+ });+ assert.equal(recoveredTurn.status, "queued", JSON.stringify(recoveredTurn));+ }+ const events = await built.auditLog.events();+ assert.equal(events.filter((e) => e.action === "model-registry.update").length, 2);+ assert.equal(events.filter((e) => e.action === "model-registry.delete").length, 1);+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++import { createServer } from "node:http";+import { oneShot, createPiHarness, wantsFastMode } from "../src/harness/pi-harness.ts";+import { setProviderBaseUrls } from "../src/model/provider-endpoints.ts";+import { calculateCost } from "@earendil-works/pi-ai";++test("Pi serves an overlay via the inherited provider endpoint and metadata drives request limits and pricing", async () => {+ let received: { model?: string; max_tokens?: number } | undefined;+ let authorized = false;+ const upstream = createServer((req, res) => {+ let raw = "";+ req.on("data", (chunk) => {+ raw += chunk;+ });+ req.on("end", () => {+ received = JSON.parse(raw);+ authorized = req.headers["x-api-key"] === "local-test-key";+ assert.equal(req.url, "/v1/messages");+ res.writeHead(200, { "content-type": "text/event-stream" });+ const event = (type: string, data: object) =>+ res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`);+ event("message_start", {+ message: {+ id: "msg_overlay",+ type: "message",+ role: "assistant",+ content: [],+ model: MODEL_ID,+ stop_reason: null,+ usage: { input_tokens: 5, output_tokens: 0 },+ },+ });+ event("content_block_start", { index: 0, content_block: { type: "text", text: "" } });+ event("content_block_delta", { index: 0, delta: { type: "text_delta", text: "Overlay works" } });+ event("content_block_stop", { index: 0 });+ event("message_delta", { delta: { stop_reason: "end_turn" }, usage: { output_tokens: 3 } });+ event("message_stop", {});+ res.end();+ });+ });+ await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));+ setProviderBaseUrls({ anthropic: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}` });+ try {+ setModelOverlays([+ validateModelOverlay({ ...spec, provider: "anthropic", template: "claude-opus-4-8", maxTokens: 10_000 }),+ ]);+ const model = getRequiredModel(MODEL_ID);+ assert.equal(+ await oneShot("overlay-local", model, { anthropic: "local-test-key" }, "Be brief", "Hello"),+ "Overlay works",+ );+ assert.equal(received?.model, MODEL_ID);+ assert.equal(received?.max_tokens, 10_000);+ assert.equal(authorized, true);+ const harness = createPiHarness({ apiKey: "local-test-key", captureRequests: false });+ const turn = {+ session: { id: "overlay-runtime" } as import("../src/harness/harness.ts").HarnessTurnInput["session"],+ input: "Hello",+ systemPrompt: "Be brief",+ history: [],+ runtime: { harnessId: "pi" as const, modelId: MODEL_ID },+ recordModelCall: () => {},+ tools: {} as import("../src/harness/harness.ts").HarnessTurnInput["tools"],+ scopeLabel: "personal:alice" as const,+ orgScopeId: "org:default-org" as const,+ emit: async (entry: Parameters<import("../src/harness/harness.ts").HarnessTurnInput["emit"]>[0]) => ({+ ...entry,+ seq: 1,+ sessionId: "overlay-runtime",+ parentSeq: null,+ createdAt: Date.now(),+ }),+ };+ await harness.turns.runTurn(turn);+ assert.equal(received?.model, MODEL_ID);+ assert.equal(received?.max_tokens, 10_000);+ setModelOverlays([+ validateModelOverlay({ ...spec, provider: "anthropic", template: "claude-opus-4-8", maxTokens: 16_000 }),+ ]);+ await harness.turns.runTurn(turn);+ assert.equal(received?.max_tokens, 16_000);+ setModelOverlays([], [MODEL_ID]);+ await assert.rejects(harness.turns.runTurn(turn), /Unsupported model/);+ const usage = {+ input: 210_000,+ output: 100,+ cacheRead: 200,+ cacheWrite: 100,+ totalTokens: 210_400,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ };+ calculateCost(model, usage);+ assert.equal(usage.cost.input, 2.94);+ assert.equal(usage.cost.output, 0.0042);+ assert.ok(Math.abs(usage.cost.cacheRead - 0.00012) < 1e-12);+ assert.equal(usage.cost.cacheWrite, 0.0016);+ } finally {+ setProviderBaseUrls({});+ await new Promise<void>((resolve) => upstream.close(() => resolve()));+ }+});++test("hydration isolates promoted builtins, incompatible providers, missing templates and malformed rows", async () => {+ const backing = createMemoryMap<StoredModelOverlay>();+ const store = createModelOverlayStore(backing);+ const builtin = getRequiredModel("gpt-5.5");+ const row = (value: unknown) =>+ ({ spec: value, disabled: false, updatedAt: 1, updatedBy: "admin" }) as StoredModelOverlay;+ await backing.put("gpt-5.5", row({ ...spec, id: "gpt-5.5" }));+ await backing.put("missing-template", row({ ...spec, id: "missing-template", template: "removed-sdk-template" }));+ await backing.put("corrupt-model", row(null));+ await store.refresh();+ assert.equal(getRequiredModel("gpt-5.5").contextWindow, builtin.contextWindow);+ assert.deepEqual(getRequiredModel("gpt-5.5").cost, builtin.cost);+ assert.equal(resolveModel("missing-template"), undefined);+ assert.equal(resolveModel("corrupt-model"), undefined);+ assert.equal((await store.statuses()).length, 3);+ assert.throws(() => validateModelOverlay({ ...spec, id: "gpt-5.5" }), /already registered/);+ await backing.put("gpt-5.5", row({ ...spec, id: "gpt-5.5", provider: "anthropic" }));+ await store.refresh();+ assert.equal(resolveModel("gpt-5.5"), undefined);+ assert.ok(resolveModel("claude-opus-5"));+ await store.upsert({ ...spec, id: "missing-template" }, "admin");+ await store.refresh();+ assert.ok(resolveModel("missing-template"));+ assert.equal(await store.delete("corrupt-model", "admin"), true);+});++test("model refresh is limited to dependent routes and admin repair survives stale persisted definitions", async () => {+ const config = testConfig({ harness: "pi" });+ const built = buildApp(config, { modelCredentialFetch: async () => Response.json({ data: [] }) });+ const backing = createMemoryMap<StoredModelOverlay>();+ await backing.put("stale", {+ spec: { ...spec, id: "stale", template: "missing" },+ disabled: false,+ updatedAt: 1,+ updatedBy: "admin",+ } as StoredModelOverlay);+ const registry = createModelOverlayStore(backing);+ let refreshes = 0;+ const deps = {+ ...serverDeps(config, built),+ modelRegistry: registry,+ refreshModels: async () => {+ refreshes++;+ await registry.refresh();+ },+ };+ const server = createInsecureTestServer(built.app, deps);+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ try {+ assert.equal((await fetch(base + "/v1/admin/whoami", { headers: ADMIN })).status, 200);+ assert.equal(refreshes, 0);+ assert.equal(+ (await fetch(base + "/v1/admin/model-registry", { headers: { ...ADMIN, "x-admin-actor": "bob@default-org" } }))+ .status,+ 403,+ );+ assert.equal(refreshes, 0);+ const list = await fetch(base + "/v1/admin/model-registry", { headers: ADMIN });+ assert.equal(list.status, 200);+ assert.equal(refreshes, 1);+ assert.match(JSON.stringify(await list.json()), /template is unavailable/);+ assert.equal(+ (await fetch(base + "/v1/admin/model-registry/stale", { method: "DELETE", headers: ADMIN })).status,+ 200,+ );+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++test("overlay resolution preserves canonical personal endpoints and upstream builtin metadata", () => {+ setModelOverlays([validateModelOverlay(spec)]);+ const canonical = getRequiredModel(MODEL_ID, false).baseUrl;+ setProviderBaseUrls({ openai: "http://127.0.0.1:19999/v1" });+ try {+ assert.equal(getRequiredModel(MODEL_ID).baseUrl, "http://127.0.0.1:19999/v1");+ assert.equal(getRequiredModel(MODEL_ID, false).baseUrl, canonical);+ assert.equal(safeModelMetadata("claude-fable-5-1")?.label, "Fable 5.1");+ assert.equal(safeModelMetadata("gpt-5.6-sol")?.cost.input, 4);+ assert.equal(safeModelMetadata("gpt-5.6-sol")?.fastMode, true);+ } finally {+ setProviderBaseUrls({});+ }+});++import { createMemoryConfigStore } from "../src/resolution/config-store.ts";+import { resolveRuntimeChoice } from "../src/harness/harness-router.ts";++test("runtime normalization preserves native capabilities and reflects overlay capability edits", () => {+ const config = createMemoryConfigStore("default-org");+ config.setApprovedHarnesses(["pi", "codex", "claude"]);+ const org = "org:default-org" as const;+ const scope = "personal:alice" as const;+ const fallback = { harnessId: "pi" as const, modelId: "gpt-5.6-sol" };+ const overlay = validateModelOverlay({ ...spec, provider: "anthropic", template: "claude-opus-4-8", fastMode: true });+ setModelOverlays([overlay]);+ const requested = { harnessId: "pi" as const, modelId: MODEL_ID, effortLevel: "max", fastMode: true };+ assert.deepEqual(resolveRuntimeChoice(config, org, scope, fallback, requested), requested);+ setModelOverlays([{ ...overlay, fastMode: false }]);+ assert.equal(resolveRuntimeChoice(config, org, scope, fallback, requested).fastMode, false);+ assert.throws(+ () => resolveRuntimeChoice(config, org, scope, fallback, { ...requested, harnessId: "codex" }),+ /not approved/,+ );+ const native = resolveRuntimeChoice(config, org, scope, fallback, {+ harnessId: "codex",+ modelId: "gpt-5.6-sol",+ effortLevel: "xhigh",+ fastMode: true,+ });+ assert.equal(native.fastMode, true);+ assert.equal(native.effortLevel, "xhigh");+});diff --git a/test/support/model-overlay-server.ts b/test/support/model-overlay-server.tsnew file mode 100644index 000000000..b34a6a759--- /dev/null+++ b/test/support/model-overlay-server.ts@@ -0,0 +1,17 @@+import "./auto-fake-sprites.ts";+import type { AddressInfo } from "node:net";+import { buildApp, serverDeps } from "../../src/wiring.ts";+import { createInsecureTestServer } from "../../src/api/server.ts";+import { testConfig } from "./test-config.ts";++const config = testConfig({+ databaseUrl: process.env.MODEL_OVERLAY_TEST_DATABASE_URL,+ adminGrants: "admin-alice:org_admin",+ harness: "pi",+ modelId: "overlay-pg-model",+ openaiApiKey: "local-test-key",+});+const built = buildApp(config, { modelCredentialFetch: async () => Response.json({ data: [] }) });+const server = createInsecureTestServer(built.app, serverDeps(config, built));+await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+process.send?.({ base: `http://127.0.0.1:${(server.address() as AddressInfo).port}` });