Multiplayer agent harness for work.
Support dynamic OpenRouter models (#656)
Joshua Francecd1e9dd3f578
diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex 9d5dc70b7..889a7a1f2 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -12,6 +12,7 @@ import {isHarnessId,modelProviderAvailabilityFor,modelServiceable,+ resolveModel,} from "../model/pi-models.ts";import { selectableCatalogForHarness, selectableModelCatalog } from "../model/model-catalog.ts";import { resolveRuntimeChoiceDurable } from "../harness/harness-router.ts";@@ -100,6 +101,22 @@ export function createTurnMethods(}}+ const orgRuntimeScope = scopeId("org", orgIdOf());+ const turnRuntimeScope =+ req.conversation.kind === "dm"+ ? scopeId("personal", actor.id)+ : scopeId(req.conversation.kind, req.conversation.channelRef ?? req.conversation.threadRef);+ const [storedOrgRuntime, storedTurnRuntime] = await Promise.all([+ deps.config.getRuntimeSelectionDurable(orgRuntimeScope),+ turnRuntimeScope === orgRuntimeScope ? null : deps.config.getRuntimeSelectionDurable(turnRuntimeScope),+ ]);+ const needsOpenRouterCatalog = [storedOrgRuntime?.modelId, storedTurnRuntime?.modelId].some(+ (modelId) => modelId && !resolveModel(modelId),+ );+ if (needsOpenRouterCatalog && deps.modelCredentials && (await deps.modelCredentials.availability()).openrouter) {+ await selectableModelCatalog(deps.modelCredentialFetch);+ }+async function withCurrentProjectRoster<T>(fn: () => Promise<T>): Promise<T | null> {if (!projectId || !deps.projects) return fn();if (!conversationRef || !projectVersion) return null;@@ -130,6 +147,9 @@ export function createTurnMethods(harnessId: fallbackHarness,modelId: defaultModelForHarness(fallbackHarness),};+ const configuredKeys = deps.providerKeys ??+ deps.modelProviders ?? { anthropic: false, openai: false, openrouter: false };+ const managedKeys = deps.modelCredentials ? await deps.modelCredentials.availability() : configuredKeys;let orgRuntime;let configuredRuntime;let runtime;@@ -152,15 +172,9 @@ export function createTurnMethods(if (req.harness && !isHarnessId(req.harness)) {return { status: "refused", reason: `runtime ${req.harness} is not approved` };}- const configuredKeys = deps.providerKeys ??- deps.modelProviders ?? { anthropic: false, openai: false, openrouter: false };let providers = deps.modelProviders;if (deps.modelCredentials) {- providers = modelProviderAvailabilityFor(- runtime.harnessId,- configuredKeys,- await deps.modelCredentials.availability(),- );+ providers = modelProviderAvailabilityFor(runtime.harnessId, configuredKeys, managedKeys);} else if (deps.providerKeys) {providers = modelProviderAvailabilityFor(runtime.harnessId, configuredKeys);}diff --git a/src/model/model-catalog.ts b/src/model/model-catalog.tsindex 77a264407..c487e663b 100644--- a/src/model/model-catalog.ts+++ b/src/model/model-catalog.ts@@ -1,4 +1,9 @@-import { modelSupportedByHarness, resolveModel, SELECTABLE_BASE_MODELS } from "./pi-models.ts";+import {+ modelSupportedByHarness,+ registerOpenRouterCatalogModel,+ resolveModel,+ SELECTABLE_BASE_MODELS,+} from "./pi-models.ts";import { customModelCatalog, customProvidersVersion } from "./custom-providers.ts";export interface ModelCatalogEntry {@@ -9,6 +14,7 @@ export interface ModelCatalogEntry {}const OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models?supported_parameters=tools&sort=most-popular";+const OPENROUTER_MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:+-]*$/;const MAX_CATALOG_BYTES = 2 * 1024 * 1024;const MAX_CATALOG_MODELS = 1_000;@@ -58,24 +64,88 @@ async function boundedJson(response: Response): Promise<unknown> {return JSON.parse(text) as unknown;}+function finiteNumber(value: unknown): number | undefined {+ let parsed = Number.NaN;+ if (typeof value === "number") parsed = value;+ else if (typeof value === "string") parsed = Number(value);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;+}++function parseOpenRouterModel(candidate: unknown): ModelCatalogEntry | undefined {+ if (!candidate || typeof candidate !== "object") return undefined;+ const raw = candidate as Record<string, unknown>;+ const id = raw.id;+ const name = raw.name;+ const supportedParameters = raw.supported_parameters;+ const contextWindow = finiteNumber(raw.context_length);+ const topProvider = raw.top_provider;+ const maxTokens =+ topProvider && typeof topProvider === "object"+ ? finiteNumber((topProvider as Record<string, unknown>).max_completion_tokens)+ : undefined;+ const pricing = raw.pricing;+ const promptPrice =+ pricing && typeof pricing === "object" ? finiteNumber((pricing as Record<string, unknown>).prompt) : undefined;+ const completionPrice =+ pricing && typeof pricing === "object" ? finiteNumber((pricing as Record<string, unknown>).completion) : undefined;+ const architecture = raw.architecture;+ const inputModalities =+ architecture && typeof architecture === "object"+ ? (architecture as Record<string, unknown>).input_modalities+ : undefined;+ if (+ typeof id !== "string" ||+ id.length > 200 ||+ !OPENROUTER_MODEL_ID_RE.test(id) ||+ typeof name !== "string" ||+ name.length === 0 ||+ name.length > 200 ||+ !Array.isArray(supportedParameters) ||+ !supportedParameters.includes("tools")+ )+ return undefined;+ const knownOpenRouter = resolveModel(id)?.provider === "openrouter";+ const inputPrice = promptPrice === undefined ? undefined : promptPrice * 1_000_000;+ const outputPrice = completionPrice === undefined ? undefined : completionPrice * 1_000_000;+ if (+ contextWindow === undefined ||+ !Number.isSafeInteger(contextWindow) ||+ contextWindow <= 0 ||+ maxTokens === undefined ||+ !Number.isSafeInteger(maxTokens) ||+ maxTokens <= 0 ||+ maxTokens > contextWindow ||+ inputPrice === undefined ||+ !Number.isFinite(inputPrice) ||+ outputPrice === undefined ||+ !Number.isFinite(outputPrice) ||+ !Array.isArray(inputModalities) ||+ !inputModalities.includes("text")+ )+ return knownOpenRouter ? { id, name, provider: "openrouter" } : undefined;+ const registered = registerOpenRouterCatalogModel({+ id,+ name,+ contextWindow,+ maxTokens,+ input: inputModalities.includes("image") ? ["text", "image"] : ["text"],+ reasoning:+ supportedParameters.includes("reasoning") ||+ supportedParameters.includes("include_reasoning") ||+ supportedParameters.includes("reasoning_effort"),+ cost: { input: inputPrice, output: outputPrice },+ });+ return registered ? { id, name, provider: "openrouter" } : undefined;+}+async function fetchOpenRouterModels(fetcher: typeof fetch): Promise<ModelCatalogEntry[]> {const response = await fetcher(OPENROUTER_MODELS_URL, { signal: AbortSignal.timeout(5_000) });if (!response.ok) throw new Error(`OpenRouter catalog returned ${response.status}`);const body = (await boundedJson(response)) as { data?: unknown };if (!Array.isArray(body.data)) throw new Error("OpenRouter catalog is invalid");return body.data.slice(0, MAX_CATALOG_MODELS).flatMap((candidate) => {- if (!candidate || typeof candidate !== "object") return [];- const { id, name, supported_parameters: supportedParameters } = candidate as Record<string, unknown>;- if (- typeof id !== "string" ||- id.length > 200 ||- typeof name !== "string" ||- name.length > 200 ||- !Array.isArray(supportedParameters) ||- !supportedParameters.includes("tools")- )- return [];- return resolveModel(id)?.provider === "openrouter" ? [{ id, name, provider: "openrouter" as const }] : [];+ const model = parseOpenRouterModel(candidate);+ return model ? [model] : [];});}diff --git a/src/model/pi-models.ts b/src/model/pi-models.tsindex 7d193eec4..b23d86c01 100644--- a/src/model/pi-models.ts+++ b/src/model/pi-models.ts@@ -94,9 +94,10 @@ export const MODEL_REGISTRY: readonly ModelEntry[] = [];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 ?? id;+ return 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);@@ -132,6 +133,35 @@ function cloneModel(model: PiModel, id: string, name: string, overrides: Partial};}+export interface OpenRouterCatalogModel {+ id: string;+ name: string;+ contextWindow: number;+ maxTokens: number;+ input: ("text" | "image")[];+ reasoning: boolean;+ cost: { input: number; output: number };+}++export function registerOpenRouterCatalogModel(definition: OpenRouterCatalogModel): PiModel | undefined {+ const template = builtinModel("openrouter/auto");+ if (!template) return undefined;+ const model = cloneModel(template, definition.id, definition.name, {+ contextWindow: definition.contextWindow,+ maxTokens: definition.maxTokens,+ reasoning: definition.reasoning,+ cost: {+ input: definition.cost.input,+ output: definition.cost.output,+ cacheRead: 0,+ cacheWrite: 0,+ },+ });+ model.input = [...definition.input];+ OPENROUTER_CATALOG_MODELS.set(model.id, model);+ return model;+}+export function resolveModel(id: string): PiModel | undefined {const entry = REGISTRY_BY_ID.get(id);if (entry?.clone) {@@ -149,7 +179,9 @@ export function resolveModel(id: string): PiModel | undefined {}): undefined;}- return builtinModel(id) ?? (resolveCustomModel(id) as unknown as PiModel | undefined);+ return (+ builtinModel(id) ?? (resolveCustomModel(id) as unknown as PiModel | undefined) ?? OPENROUTER_CATALOG_MODELS.get(id)+ );}export function auxiliaryModelForProvider(provider: string): string | undefined {diff --git a/test/dynamic-openrouter-model.test.ts b/test/dynamic-openrouter-model.test.tsnew file mode 100644index 000000000..428b294f9--- /dev/null+++ b/test/dynamic-openrouter-model.test.ts@@ -0,0 +1,48 @@+import "./support/auto-fake-sprites.ts";++import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { test } from "node:test";+import { buildApp } from "../src/wiring.ts";+import { testConfig } from "./support/test-config.ts";++const oxAlphaCatalog: typeof fetch = async () =>+ Response.json({+ data: [+ {+ id: "stealth/ox-alpha",+ name: "Ox Alpha",+ context_length: 1_048_576,+ pricing: { prompt: "0", completion: "0" },+ top_provider: { max_completion_tokens: 131_072 },+ architecture: { input_modalities: ["text", "image", "video"] },+ supported_parameters: ["tools", "reasoning", "reasoning_effort"],+ },+ ],+ });++test("web turns hydrate persisted OpenRouter catalog models before runtime resolution", async () => {+ const built = buildApp(+ testConfig({+ dataDir: mkdtempSync(join(tmpdir(), "dynamic-openrouter-model-")),+ openrouterApiKey: "deployment-openrouter-key",+ }),+ { modelCredentialFetch: oxAlphaCatalog },+ );+ await built.config.setRuntimeSelectionLatest("org:default-org", {+ harnessId: "pi",+ modelId: "stealth/ox-alpha",+ });++ const turn = await built.app.turn({+ surface: "web",+ actor: { externalId: "alice" },+ conversation: { kind: "dm", threadRef: "web:alice:dynamic-openrouter-model" },+ text: "hello",+ model: "stealth/ox-alpha",+ async: true,+ });+ assert.equal(turn.status, "queued");+});diff --git a/test/model-credential-route.test.ts b/test/model-credential-route.test.tsindex e127025ab..a23343525 100644--- a/test/model-credential-route.test.ts+++ b/test/model-credential-route.test.ts@@ -11,6 +11,7 @@ import { buildApp, type BuiltApp } from "../src/wiring.ts";import { testConfig } from "./support/test-config.ts";import { createModelCredentialStore, type StoredModelCredential } from "../src/model/model-credential-store.ts";import { createMemoryMap } from "../src/persistence/durable-map.ts";+import { getRequiredModel } from "../src/model/pi-models.ts";const ADMIN = { "content-type": "application/json", "x-admin-actor": "admin-alice@default-org" };@@ -149,8 +150,20 @@ test("OpenRouter catalog exposes runtime-supported tool models as selectable bassupported_parameters: ["tools"],},{- id: "vendor/not-in-the-pinned-runtime",- name: "Future Model",+ id: "stealth/ox-alpha",+ name: "Ox Alpha",+ context_length: 1_048_576,+ pricing: { prompt: "0", completion: "0" },+ top_provider: { max_completion_tokens: 131_072 },+ architecture: { input_modalities: ["text", "image", "video"] },+ supported_parameters: ["tools", "reasoning", "reasoning_effort"],+ },+ {+ id: "future/incomplete-model",+ name: "Incomplete Future Model",+ context_length: 128_000,+ pricing: { prompt: "0", completion: "0" },+ architecture: { input_modalities: ["text"] },supported_parameters: ["tools"],},{@@ -172,16 +185,23 @@ test("OpenRouter catalog exposes runtime-supported tool models as selectable basassert.deepEqual(models, [{ id: "openrouter/auto", name: "OpenRouter Auto", provider: "openrouter" },{ id: "anthropic/claude-sonnet-4.5", name: "Anthropic: Claude Sonnet 4.5", provider: "openrouter" },+ { id: "stealth/ox-alpha", name: "Ox Alpha", provider: "openrouter" },]);+ const dynamic = getRequiredModel("stealth/ox-alpha");+ assert.equal(dynamic.provider, "openrouter");+ assert.equal(dynamic.contextWindow, 1_048_576);+ assert.equal(dynamic.maxTokens, 131_072);+ assert.deepEqual(dynamic.input, ["text", "image"]);+ assert.deepEqual(dynamic.cost, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });assert.equal(requested, "https://openrouter.ai/api/v1/models?supported_parameters=tools&sort=most-popular");const selected = await fetch(`${srv.base}/v1/admin/scopes/org%3Adefault-org/base-model`, {method: "PUT",headers: ADMIN,- body: JSON.stringify({ modelId: "anthropic/claude-sonnet-4.5" }),+ body: JSON.stringify({ modelId: "stealth/ox-alpha" }),});assert.equal(selected.status, 200);- assert.equal(srv.built.config.getBaseModel("org:default-org"), "anthropic/claude-sonnet-4.5");+ assert.equal(srv.built.config.getBaseModel("org:default-org"), "stealth/ox-alpha");const governance = await fetch(`${srv.base}/v1/admin/scopes/org%3Adefault-org`, { headers: ADMIN });assert.equal(governance.status, 200);@@ -190,9 +210,9 @@ test("OpenRouter catalog exposes runtime-supported tool models as selectable basmodelsByHarness: Record<string, Array<{ id: string; name: string }>>;runtime: { harnessId: string; modelId: string };};- assert.ok(governanceBody.baseModelOptions.some((model) => model.id === "anthropic/claude-sonnet-4.5"));- assert.ok(governanceBody.modelsByHarness.pi!.some((model) => model.id === "anthropic/claude-sonnet-4.5"));- assert.equal(governanceBody.runtime.modelId, "anthropic/claude-sonnet-4.5");+ assert.ok(governanceBody.baseModelOptions.some((model) => model.id === "stealth/ox-alpha"));+ assert.ok(governanceBody.modelsByHarness.pi!.some((model) => model.id === "stealth/ox-alpha"));+ assert.equal(governanceBody.runtime.modelId, "stealth/ox-alpha");const runtime = await fetch(`${srv.base}/v1/runtime-config?principalId=alice&scopeId=personal%3Aalice`);assert.equal(runtime.status, 200);@@ -201,25 +221,25 @@ test("OpenRouter catalog exposes runtime-supported tool models as selectable basmodelCatalog: Record<string, { name: string; provider: string }>;effective: { harnessId: string; modelId: string };};- assert.ok(runtimeBody.modelsByHarness.pi!.includes("anthropic/claude-sonnet-4.5"));- assert.deepEqual(runtimeBody.modelCatalog["anthropic/claude-sonnet-4.5"], {- name: "Anthropic: Claude Sonnet 4.5",+ assert.ok(runtimeBody.modelsByHarness.pi!.includes("stealth/ox-alpha"));+ assert.deepEqual(runtimeBody.modelCatalog["stealth/ox-alpha"], {+ name: "Ox Alpha",provider: "openrouter",});- assert.deepEqual(runtimeBody.effective, { harnessId: "pi", modelId: "anthropic/claude-sonnet-4.5" });+ assert.deepEqual(runtimeBody.effective, { harnessId: "pi", modelId: "stealth/ox-alpha" });const surface = await fetch(`${srv.base}/v1/surface-config`);assert.equal(surface.status, 200);const surfaceBody = (await surface.json()) as { webuiModels: string[]; baseModel: string };- assert.ok(surfaceBody.webuiModels.includes("anthropic/claude-sonnet-4.5"));- assert.equal(surfaceBody.baseModel, "anthropic/claude-sonnet-4.5");+ assert.ok(surfaceBody.webuiModels.includes("stealth/ox-alpha"));+ assert.equal(surfaceBody.baseModel, "stealth/ox-alpha");const turn = await srv.built.app.turn({surface: "web",actor: { externalId: "alice" },conversation: { kind: "dm", threadRef: "web:alice:openrouter-catalog" },text: "hello",- model: "anthropic/claude-sonnet-4.5",+ model: "stealth/ox-alpha",async: true,});assert.equal(turn.status, "queued");