diff --git a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts index 29f8a5606ac07..d95d037a7a590 100644 --- a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts @@ -4,8 +4,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import type * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; -import type * as FileSystem from "effect/FileSystem"; -import type * as Path from "effect/Path"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; import * as AcpErrors from "effect-acp/errors"; @@ -28,6 +28,15 @@ import { import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; +import * as ServerConfigModule from "../../config.ts"; +import { + openRouterUpstreamsFromSetting, + resolvePinnedUpstream, + ompOpenRouterRoutingPaths, + prepareOmpOpenRouterRouting, + writeOmpOpenRouterPin, + type OmpOpenRouterRoutingPaths, +} from "../../provider/acp/OmpOpenRouterRouting.ts"; import type * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; @@ -58,6 +67,13 @@ export interface OmpAdapterV2Options extends Omit< readonly environment: NodeJS.ProcessEnv; readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly makeRuntime?: AcpAdapterV2Flavor["makeRuntime"]; + readonly openRouterRouting?: OmpOpenRouterRoutingPaths | undefined; + /** Pin writer; the adapter must not depend on the filesystem service. */ + readonly writeRoutingPin?: (input: { + readonly sessionId: string; + readonly model: string; + readonly upstream: string | undefined; + }) => Effect.Effect; } /** Count root assistant output on the native transport, including frames before RPC settlement. */ @@ -114,6 +130,8 @@ function withOmpCompletionCheck(runtime: AcpSessionRuntime.AcpSessionRuntime["Se /** @public */ export function makeOmpAcpAdapterFlavor(options: OmpAdapterV2Options): AcpAdapterV2Flavor { + // A stored pin the settings no longer offer must not keep routing requests. + const configuredUpstreams = openRouterUpstreamsFromSetting(options.settings.openrouterUpstreams); return { driver: OMP_PROVIDER, runtimeHarness: "Oh My Pi", @@ -147,18 +165,32 @@ export function makeOmpAcpAdapterFlavor(options: OmpAdapterV2Options): AcpAdapte content: (answers) => buildOmpElicitationContent(questions, answers), }; }, - applyModelSelection: ({ runtime, modelSelection }) => + applyModelSelection: ({ runtime, startResult, modelSelection }) => applyOmpRequestedSessionConfiguration({ runtime, modelSelection, mapError: ({ cause }) => cause, - }).pipe(Effect.as(modelSelection.model === "default" ? undefined : modelSelection.model)), + }).pipe( + Effect.tap(() => + options.writeRoutingPin === undefined + ? Effect.void + : options.writeRoutingPin({ + sessionId: startResult.sessionId, + model: modelSelection.model, + upstream: resolvePinnedUpstream(modelSelection.options, configuredUpstreams), + }), + ), + Effect.as(modelSelection.model === "default" ? undefined : modelSelection.model), + ), makeRuntime: (input) => ( options.makeRuntime?.(input) ?? makeOmpAcpRuntime({ ...input, ompSettings: options.settings, + ...(options.openRouterRouting === undefined + ? {} + : { openRouterRouting: options.openRouterRouting }), environment: { ...options.environment, ...input.processEnvironment }, runtimeMode: input.runtimePolicy.approvalPolicy === undefined && @@ -188,6 +220,7 @@ export const makeOmpAdapterV2 = Effect.fn("makeOmpAdapterV2")(function* ( }); export type OmpAdapterV2DriverEnv = + | ServerConfigModule.ServerConfig | ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem @@ -197,6 +230,52 @@ export type OmpAdapterV2DriverEnv = | ProviderHost.ProviderHost | McpProviderSessions.McpProviderSessions; +/** + * OpenRouter routing is opt-in: with no upstreams configured nothing is spawned + * or loaded, so OMP keeps its stock behaviour. A state dir that cannot hold the + * artifacts disables the feature instead of failing the whole provider. + */ +const prepareOpenRouterRouting = Effect.fn("OmpAdapterV2.prepareOpenRouterRouting")(function* ( + setting: string | null | undefined, +): Effect.fn.Return< + Pick, + never, + ServerConfigModule.ServerConfig | FileSystem.FileSystem | Path.Path +> { + if (openRouterUpstreamsFromSetting(setting).length === 0) return {}; + const serverConfig = yield* ServerConfigModule.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const openRouterRouting = yield* ompOpenRouterRoutingPaths(serverConfig.stateDir); + const prepared = yield* Effect.result(prepareOmpOpenRouterRouting(openRouterRouting)); + if (prepared._tag === "Failure") { + yield* Effect.logWarning( + "Disabling Oh My Pi OpenRouter routing: routing artifacts unavailable", + { + cause: prepared.failure, + }, + ); + return {}; + } + return { + openRouterRouting, + // A failed pin write leaves the turn unpinned; failing the turn over a + // filesystem hiccup is worse, and the warning names the cause. + writeRoutingPin: (pin: { + readonly sessionId: string; + readonly model: string; + readonly upstream: string | undefined; + }) => + writeOmpOpenRouterPin({ paths: openRouterRouting, ...pin }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.catchCause((cause) => + Effect.logWarning("Failed to write Oh My Pi OpenRouter pin", { cause }), + ), + ), + }; +}); + export const OmpAdapterV2Driver: ProviderAdapterDriver = { driverKind: OMP_PROVIDER, configSchema: OmpSettings, @@ -206,7 +285,9 @@ export const OmpAdapterV2Driver: ProviderAdapterDriver { ]); }); + it("offers an upstream pin on OpenRouter models only", () => { + const models = buildOmpModelsFromJson( + { + models: [ + { + provider: "openrouter", + id: "z-ai/glm-5.3-flash", + selector: "openrouter/z-ai/glm-5.3-flash", + name: "GLM 5.3 Flash", + thinking: ["low", "max"], + }, + { + provider: "anthropic", + id: "claude-sonnet-5", + selector: "anthropic/claude-sonnet-5", + name: "Claude Sonnet 5", + thinking: null, + }, + ], + }, + { openRouterUpstreams: ["deepinfra", "cerebras"] }, + ); + + expect(models[0]?.capabilities?.optionDescriptors?.map((descriptor) => descriptor.id)).toEqual([ + "thinking", + "openrouterUpstream", + ]); + expect(models[0]?.capabilities?.optionDescriptors?.[1]).toEqual({ + id: "openrouterUpstream", + label: "Upstream", + type: "select", + description: "Pin the OpenRouter provider that serves this model.", + currentValue: "auto", + options: [ + { + id: "auto", + label: "Auto", + description: "Let OpenRouter route the request", + isDefault: true, + }, + { id: "deepinfra", label: "deepinfra" }, + { id: "cerebras", label: "cerebras" }, + ], + }); + expect(models[1]?.capabilities?.optionDescriptors).toEqual([]); + }); + it("rejects malformed JSON and only preserves configured model catalog arguments", () => { expect(parseOmpModelsJson("not json")).toBeUndefined(); expect(parseOmpModelsJson('{"unexpected":[]}')).toEqual([]); diff --git a/apps/server/src/provider/OmpProvider.ts b/apps/server/src/provider/OmpProvider.ts index 70cda754dcb98..255d1c91073b7 100644 --- a/apps/server/src/provider/OmpProvider.ts +++ b/apps/server/src/provider/OmpProvider.ts @@ -1,6 +1,7 @@ import { type ModelCapabilities, type OmpSettings, + type ProviderOptionDescriptor, type ServerProviderModel, type ServerProvider, } from "@t3tools/contracts"; @@ -29,6 +30,11 @@ import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/ser import { enrichProviderSnapshotWithVersionAdvisory } from "@t3tools/provider-core/server/maintenanceResolver"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import { ompProfileFromLaunchArgs } from "./acp/OmpAcpSupport.ts"; +import { + OMP_OPENROUTER_UPSTREAM_AUTO, + OMP_OPENROUTER_UPSTREAM_OPTION_ID, + openRouterUpstreamsFromSetting, +} from "./acp/OmpOpenRouterRouting.ts"; /** @public */ export const OMP_PRESENTATION = { @@ -100,10 +106,11 @@ function thinkingLabel(value: string): string { function ompModelCapabilities( thinking: ReadonlyArray, defaultThinking: string | undefined, + openRouterUpstreams: ReadonlyArray, ): ModelCapabilities { - if (thinking.length === 0) return EMPTY_CAPABILITIES; - return createModelCapabilities({ - optionDescriptors: [ + const optionDescriptors: Array = []; + if (thinking.length > 0) { + optionDescriptors.push( buildSelectOptionDescriptor({ id: "thinking", label: "Thinking", @@ -113,13 +120,35 @@ function ompModelCapabilities( ...(value === defaultThinking ? { isDefault: true } : {}), })), }), - ], - }); + ); + } + if (openRouterUpstreams.length > 0) { + optionDescriptors.push( + buildSelectOptionDescriptor({ + id: OMP_OPENROUTER_UPSTREAM_OPTION_ID, + label: "Upstream", + description: "Pin the OpenRouter provider that serves this model.", + options: [ + { + value: OMP_OPENROUTER_UPSTREAM_AUTO, + label: "Auto", + description: "Let OpenRouter route the request", + isDefault: true, + }, + ...openRouterUpstreams.map((value) => ({ value, label: value })), + ], + }), + ); + } + return optionDescriptors.length === 0 + ? EMPTY_CAPABILITIES + : createModelCapabilities({ optionDescriptors }); } export interface OmpModelCatalogDefaults { readonly defaultModelRole?: string | undefined; readonly defaultThinking?: string | undefined; + readonly openRouterUpstreams?: ReadonlyArray | undefined; } /** Parses the documented `omp models --json` catalog without trusting malformed entries. */ @@ -167,6 +196,7 @@ export function buildOmpModelsFromJson( selector === defaultSelector ? (roleThinking ?? defaults.defaultThinking) : defaults.defaultThinking, + provider === "openrouter" ? (defaults.openRouterUpstreams ?? []) : [], ), } satisfies ServerProviderModel, ]; @@ -433,6 +463,7 @@ export const checkOmpProviderStatus = Effect.fn("checkOmpProviderStatus")(functi const discoveredModels = parseOmpModelsJson(modelsResult.stdout, { defaultModelRole: trimmedString(asRecord(configDefaults.modelRoles)?.default), defaultThinking: trimmedString(configDefaults.defaultThinking), + openRouterUpstreams: openRouterUpstreamsFromSetting(settings.openrouterUpstreams), }); if (!discoveredModels) { return buildServerProvider({ diff --git a/apps/server/src/provider/acp/OmpAcpSupport.test.ts b/apps/server/src/provider/acp/OmpAcpSupport.test.ts index a52fe6779689f..07bca42190ce2 100644 --- a/apps/server/src/provider/acp/OmpAcpSupport.test.ts +++ b/apps/server/src/provider/acp/OmpAcpSupport.test.ts @@ -25,6 +25,47 @@ describe("buildOmpAcpSpawnInput", () => { }); }); + it("leaves the OMP command untouched when OpenRouter routing is not configured", () => { + const spawn = buildOmpAcpSpawnInput( + { binaryPath: "omp", launchArgs: "" }, + "/tmp/project", + { PATH: "/usr/bin" }, + "auto", + undefined, + ); + expect(spawn.args).not.toContain("-e"); + expect(spawn.env).not.toHaveProperty("T3_OMP_ROUTING_DIR"); + }); + + it("loads the OpenRouter routing extension and points it at the pin directory", () => { + expect( + buildOmpAcpSpawnInput( + { binaryPath: "omp", launchArgs: "--profile work" }, + "/tmp/project", + { PATH: "/usr/bin" }, + "auto", + { + dir: "/tmp/routing", + pinsDir: "/tmp/routing/pins", + extensionPath: "/tmp/routing/openrouter-routing.ts", + }, + ), + ).toEqual({ + command: "omp", + args: [ + "acp", + "--profile", + "work", + "--approval-mode", + "always-ask", + "-e", + "/tmp/routing/openrouter-routing.ts", + ], + cwd: "/tmp/project", + env: { PATH: "/usr/bin", T3_OMP_ROUTING_DIR: "/tmp/routing" }, + }); + }); + it.each([ ["approval-required", "always-ask"], ["auto", "always-ask"], diff --git a/apps/server/src/provider/acp/OmpAcpSupport.ts b/apps/server/src/provider/acp/OmpAcpSupport.ts index de44793976732..6f1fa20bb60ec 100644 --- a/apps/server/src/provider/acp/OmpAcpSupport.ts +++ b/apps/server/src/provider/acp/OmpAcpSupport.ts @@ -19,6 +19,10 @@ import * as Predicate from "effect/Predicate"; import { tokenizeCliArgs } from "@t3tools/shared/cliArgs"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import { + OMP_OPENROUTER_ROUTING_ENV, + type OmpOpenRouterRoutingPaths, +} from "./OmpOpenRouterRouting.ts"; import { type AcpSessionMode, type AcpSessionModeState, @@ -51,6 +55,7 @@ export interface OmpAcpRuntimeInput extends Omit< readonly ompSettings: Pick | null | undefined; readonly environment?: NodeJS.ProcessEnv; readonly runtimeMode?: RuntimeMode; + readonly openRouterRouting?: OmpOpenRouterRoutingPaths | undefined; } export interface OmpAcpModelSelectionErrorContext { @@ -110,7 +115,9 @@ function requestedOmpModeId(modeState: AcpSessionModeState | undefined): string ); } -export function applyOmpRequestedSessionConfiguration(input: { +export const applyOmpRequestedSessionConfiguration = Effect.fn( + "OmpAcp.applyRequestedSessionConfiguration", +)(function* (input: { readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"]; readonly modelSelection: | { @@ -122,28 +129,26 @@ export function applyOmpRequestedSessionConfiguration(input: { readonly cause: EffectAcpErrors.AcpError; readonly method: "session/set_config_option" | "session/set_mode" | "session/set_model"; }) => E; -}): Effect.Effect { - return Effect.gen(function* () { - if (input.modelSelection) { - yield* applyOmpAcpModelSelection({ - runtime: input.runtime, - model: input.modelSelection.model, - selections: input.modelSelection.options, - mapError: ({ cause, step }) => - input.mapError({ - cause, - method: step === "set-model" ? "session/set_model" : "session/set_config_option", - }), - }); - } +}): Effect.fn.Return { + if (input.modelSelection) { + yield* applyOmpAcpModelSelection({ + runtime: input.runtime, + model: input.modelSelection.model, + selections: input.modelSelection.options, + mapError: ({ cause, step }) => + input.mapError({ + cause, + method: step === "set-model" ? "session/set_model" : "session/set_config_option", + }), + }); + } - const modeId = requestedOmpModeId(yield* input.runtime.getModeState); - if (!modeId) return; - yield* input.runtime - .setMode(modeId) - .pipe(Effect.mapError((cause) => input.mapError({ cause, method: "session/set_mode" }))); - }); -} + const modeId = requestedOmpModeId(yield* input.runtime.getModeState); + if (!modeId) return; + yield* input.runtime + .setMode(modeId) + .pipe(Effect.mapError((cause) => input.mapError({ cause, method: "session/set_mode" }))); +}); export function selectAutoApprovedOmpPermissionOption( request: EffectAcpSchema.RequestPermissionRequest, @@ -354,6 +359,7 @@ export function buildOmpAcpSpawnInput( cwd: string, environment?: NodeJS.ProcessEnv, runtimeMode?: RuntimeMode, + openRouterRouting?: OmpOpenRouterRoutingPaths | undefined, ): AcpSessionRuntime.AcpSpawnInput { const configuredArgs = tokenizeCliArgs(ompSettings?.launchArgs); const launchArgs = runtimeMode @@ -361,9 +367,20 @@ export function buildOmpAcpSpawnInput( : configuredArgs; return { command: ompSettings?.binaryPath?.trim() || "omp", - args: ["acp", ...launchArgs], + args: [ + "acp", + ...launchArgs, + ...(openRouterRouting ? ["-e", openRouterRouting.extensionPath] : []), + ], cwd, - ...(environment ? { env: environment } : {}), + ...(environment || openRouterRouting + ? { + env: { + ...environment, + ...(openRouterRouting ? { [OMP_OPENROUTER_ROUTING_ENV]: openRouterRouting.dir } : {}), + }, + } + : {}), }; } @@ -471,6 +488,7 @@ export function buildOmpTextGenerationAcpSpawnInput( cwd: string, sessionDir: string, environment?: NodeJS.ProcessEnv, + openRouterRouting?: OmpOpenRouterRoutingPaths | undefined, ): AcpSessionRuntime.AcpSpawnInput { return { command: ompSettings?.binaryPath?.trim() || "omp", @@ -480,37 +498,44 @@ export function buildOmpTextGenerationAcpSpawnInput( "--session-dir", sessionDir, ...OMP_TEXT_GENERATION_ACP_ARGS, + ...(openRouterRouting ? ["-e", openRouterRouting.extensionPath] : []), ], cwd, - ...(environment ? { env: environment } : {}), + ...(environment || openRouterRouting + ? { + env: { + ...environment, + ...(openRouterRouting ? { [OMP_OPENROUTER_ROUTING_ENV]: openRouterRouting.dir } : {}), + }, + } + : {}), }; } -const makeOmpAcpRuntimeWithSpawn = ( +const makeOmpAcpRuntimeWithSpawn = Effect.fn("OmpAcp.makeRuntime")(function* ( input: OmpAcpRuntimeInput, spawn: AcpSessionRuntime.AcpSpawnInput, -): Effect.Effect< +): Effect.fn.Return< AcpSessionRuntime.AcpSessionRuntime["Service"], EffectAcpErrors.AcpError, Crypto.Crypto | Scope.Scope -> => - Effect.gen(function* () { - const acpContext = yield* Layer.build( - AcpSessionRuntime.layer({ - ...input, - spawn, - authMethodId: "agent", - clientCapabilities: { ...input.clientCapabilities, ...OMP_ACP_CLIENT_CAPABILITIES }, - }).pipe( - Layer.provide( - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner), - ), +> { + const acpContext = yield* Layer.build( + AcpSessionRuntime.layer({ + ...input, + spawn, + authMethodId: "agent", + clientCapabilities: { ...input.clientCapabilities, ...OMP_ACP_CLIENT_CAPABILITIES }, + }).pipe( + Layer.provide( + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner), ), - ); - return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(acpContext), - ); - }); + ), + ); + return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( + Effect.provide(acpContext), + ); +}); export const makeOmpAcpRuntime = ( input: OmpAcpRuntimeInput, @@ -521,7 +546,13 @@ export const makeOmpAcpRuntime = ( > => makeOmpAcpRuntimeWithSpawn( input, - buildOmpAcpSpawnInput(input.ompSettings, input.cwd, input.environment, input.runtimeMode), + buildOmpAcpSpawnInput( + input.ompSettings, + input.cwd, + input.environment, + input.runtimeMode, + input.openRouterRouting, + ), ); export const makeOmpTextGenerationAcpRuntime = ( @@ -538,6 +569,7 @@ export const makeOmpTextGenerationAcpRuntime = ( input.cwd, input.sessionDir, input.environment, + input.openRouterRouting, ), ); @@ -623,29 +655,29 @@ export function resolveOmpAcpConfigUpdates( return updates; } -export function applyOmpAcpModelSelection(input: { +export const applyOmpAcpModelSelection = Effect.fn("OmpAcp.applyModelSelection")(function* < + E, +>(input: { readonly runtime: OmpAcpModelSelectionRuntime; readonly model: string | null | undefined; readonly selections: ReadonlyArray | null | undefined; readonly mapError: (context: OmpAcpModelSelectionErrorContext) => E; -}): Effect.Effect { - return Effect.gen(function* () { - const model = input.model?.trim(); - if (model && model !== "default") { - yield* input.runtime - .setModel(model) - .pipe(Effect.mapError((cause) => input.mapError({ cause, step: "set-model" }))); - } +}): Effect.fn.Return { + const model = input.model?.trim(); + if (model && model !== "default") { + yield* input.runtime + .setModel(model) + .pipe(Effect.mapError((cause) => input.mapError({ cause, step: "set-model" }))); + } - const configOptions = yield* input.runtime.getConfigOptions; - for (const update of resolveOmpAcpConfigUpdates(configOptions, input.selections)) { - yield* input.runtime - .setConfigOption(update.configId, update.value) - .pipe( - Effect.mapError((cause) => - input.mapError({ cause, step: "set-config-option", configId: update.configId }), - ), - ); - } - }); -} + const configOptions = yield* input.runtime.getConfigOptions; + for (const update of resolveOmpAcpConfigUpdates(configOptions, input.selections)) { + yield* input.runtime + .setConfigOption(update.configId, update.value) + .pipe( + Effect.mapError((cause) => + input.mapError({ cause, step: "set-config-option", configId: update.configId }), + ), + ); + } +}); diff --git a/apps/server/src/provider/acp/OmpOpenRouterRouting.test.ts b/apps/server/src/provider/acp/OmpOpenRouterRouting.test.ts new file mode 100644 index 0000000000000..d49b8a838b79a --- /dev/null +++ b/apps/server/src/provider/acp/OmpOpenRouterRouting.test.ts @@ -0,0 +1,156 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { + OMP_OPENROUTER_ROUTING_EXTENSION_SOURCE, + OMP_OPENROUTER_ROUTING_ENV, + ompOpenRouterPinFileName, + ompOpenRouterRoutingPaths, + openRouterUpstreamFromSelection, + openRouterUpstreamsFromSetting, + prepareOmpOpenRouterRouting, + resolvePinnedUpstream, + writeOmpOpenRouterPin, +} from "./OmpOpenRouterRouting.ts"; + +const PINNED_MODEL = "openrouter/deepseek/deepseek-v4-flash"; + +describe("OpenRouter upstream setting", () => { + it("normalizes comma-separated slugs and drops blanks and duplicates", () => { + expect(openRouterUpstreamsFromSetting(" DeepInfra, cerebras ,, deepinfra, ")).toEqual([ + "deepinfra", + "cerebras", + ]); + expect(openRouterUpstreamsFromSetting("")).toEqual([]); + expect(openRouterUpstreamsFromSetting(null)).toEqual([]); + }); +}); + +describe("OpenRouter upstream selection", () => { + it("reads the pin from the provider option selection", () => { + expect( + openRouterUpstreamFromSelection([ + { id: "thinking", value: "high" }, + { id: "openrouterUpstream", value: " DeepInfra " }, + ]), + ).toBe("deepinfra"); + }); + + it("drops a stored pin the instance no longer offers", () => { + const selections = [{ id: "openrouterUpstream", value: "deepinfra" }]; + expect(resolvePinnedUpstream(selections, ["cerebras"])).toBeUndefined(); + expect(resolvePinnedUpstream(selections, ["deepinfra"])).toBe("deepinfra"); + expect(resolvePinnedUpstream([], ["deepinfra"])).toBeUndefined(); + }); + + it("treats auto and unrelated selections as unpinned", () => { + expect( + openRouterUpstreamFromSelection([{ id: "openrouterUpstream", value: "auto" }]), + ).toBeUndefined(); + expect(openRouterUpstreamFromSelection([{ id: "thinking", value: "high" }])).toBeUndefined(); + expect( + openRouterUpstreamFromSelection([{ id: "openrouterUpstream", value: true }]), + ).toBeUndefined(); + expect(openRouterUpstreamFromSelection(null)).toBeUndefined(); + }); +}); + +it.layer(NodeServices.layer)("OpenRouter routing artifacts", (it) => { + it.effect("writes the extension and round-trips a session pin", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-omp-routing-" }); + const paths = yield* ompOpenRouterRoutingPaths(stateDir); + + yield* prepareOmpOpenRouterRouting(paths); + + expect(yield* fs.readFileString(paths.extensionPath)).toBe( + OMP_OPENROUTER_ROUTING_EXTENSION_SOURCE, + ); + + const pinPath = path.join(paths.pinsDir, ompOpenRouterPinFileName("session with/slash")); + yield* writeOmpOpenRouterPin({ + paths, + sessionId: "session with/slash", + model: PINNED_MODEL, + upstream: "deepinfra", + }); + expect(pinPath).not.toContain("/slash"); + expect(yield* fs.readFileString(pinPath)).toBe(`deepinfra\n${PINNED_MODEL}\n`); + + yield* writeOmpOpenRouterPin({ + paths, + sessionId: "session with/slash", + model: PINNED_MODEL, + upstream: undefined, + }); + expect(yield* fs.exists(pinPath)).toBe(false); + }), + ); + + it.effect("the generated extension pins only the model the thread chose", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-omp-routing-ext-" }); + const paths = yield* ompOpenRouterRoutingPaths(stateDir); + yield* prepareOmpOpenRouterRouting(paths); + yield* writeOmpOpenRouterPin({ + paths, + sessionId: "pinned-session", + model: PINNED_MODEL, + upstream: "deepinfra", + }); + + const modulePath = path.join(stateDir, "extension-for-test.mjs"); + yield* fs.writeFileString(modulePath, OMP_OPENROUTER_ROUTING_EXTENSION_SOURCE); + const previousRoutingDir = process.env[OMP_OPENROUTER_ROUTING_ENV]; + process.env[OMP_OPENROUTER_ROUTING_ENV] = paths.dir; + const handlers: Array<(event: { payload: unknown }, ctx: unknown) => unknown> = []; + try { + const module: { default: (pi: unknown) => void } = yield* Effect.promise( + () => import(modulePath), + ); + module.default({ + on: (event: string, handler: (typeof handlers)[number]) => { + if (event === "before_provider_request") handlers.push(handler); + }, + }); + } finally { + if (previousRoutingDir === undefined) delete process.env[OMP_OPENROUTER_ROUTING_ENV]; + else process.env[OMP_OPENROUTER_ROUTING_ENV] = previousRoutingDir; + } + const handler = handlers[0]; + expect(handler).toBeDefined(); + const ctxFor = (provider: string, id: string, sessionId: string) => ({ + model: { provider, id }, + sessionManager: { getSessionId: () => sessionId }, + }); + + const payload = { model: "deepseek/deepseek-v4-flash", messages: [] }; + expect( + handler?.( + { payload }, + ctxFor("openrouter", "deepseek/deepseek-v4-flash", "pinned-session"), + ), + ).toEqual({ + ...payload, + provider: { only: ["deepinfra"] }, + }); + // Compaction and handoff send other models through the same hook. + expect( + handler?.({ payload }, ctxFor("openrouter", "openai/gpt-5-nano", "pinned-session")), + ).toBeUndefined(); + expect( + handler?.({ payload }, ctxFor("anthropic", "claude-sonnet-5", "pinned-session")), + ).toBeUndefined(); + expect( + handler?.({ payload }, ctxFor("openrouter", "deepseek/deepseek-v4-flash", "other-session")), + ).toBeUndefined(); + }), + ); +}); diff --git a/apps/server/src/provider/acp/OmpOpenRouterRouting.ts b/apps/server/src/provider/acp/OmpOpenRouterRouting.ts new file mode 100644 index 0000000000000..906180c962c44 --- /dev/null +++ b/apps/server/src/provider/acp/OmpOpenRouterRouting.ts @@ -0,0 +1,178 @@ +// Fork-local: Oh My Pi exposes no ACP surface for OpenRouter upstream routing +// (can1357/oh-my-pi#14876). A generated extension rewrites the request payload instead. +import type { ProviderOptionSelection } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; + +export const OMP_OPENROUTER_UPSTREAM_OPTION_ID = "openrouterUpstream"; +export const OMP_OPENROUTER_ROUTING_ENV = "T3_OMP_ROUTING_DIR"; +/** Selection value meaning "let OpenRouter route"; it never reaches the pin file. */ +export const OMP_OPENROUTER_UPSTREAM_AUTO = "auto"; + +const ROUTING_DIR_NAME = "omp-openrouter-routing"; +const PINS_DIR_NAME = "pins"; +const EXTENSION_FILE_NAME = "openrouter-routing.ts"; +const PIN_FILE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000; + +export interface OmpOpenRouterRoutingPaths { + /** Directory holding the generated extension; passed to OMP through the routing env var. */ + readonly dir: string; + readonly pinsDir: string; + readonly extensionPath: string; +} + +export const ompOpenRouterRoutingPaths = Effect.fn("ompOpenRouterRoutingPaths")(function* ( + stateDir: string, +) { + const path = yield* Path.Path; + const dir = path.join(stateDir, ROUTING_DIR_NAME); + return { + dir, + pinsDir: path.join(dir, PINS_DIR_NAME), + extensionPath: path.join(dir, EXTENSION_FILE_NAME), + } satisfies OmpOpenRouterRoutingPaths; +}); + +/** Comma-separated setting value to selectable OpenRouter provider slugs. */ +export function openRouterUpstreamsFromSetting( + raw: string | null | undefined, +): ReadonlyArray { + if (!raw) return []; + const seen = new Set(); + const upstreams: Array = []; + for (const entry of raw.split(",")) { + const normalized = entry.trim().toLowerCase(); + if (normalized.length === 0 || seen.has(normalized)) continue; + seen.add(normalized); + upstreams.push(normalized); + } + return upstreams; +} + +/** The pinned upstream, or undefined when the thread asks for OpenRouter's own routing. */ +export function openRouterUpstreamFromSelection( + selections: ReadonlyArray | null | undefined, +): string | undefined { + for (const selection of selections ?? []) { + if (selection.id !== OMP_OPENROUTER_UPSTREAM_OPTION_ID) continue; + if (typeof selection.value !== "string") return undefined; + const normalized = selection.value.trim().toLowerCase(); + if (normalized.length === 0 || normalized === OMP_OPENROUTER_UPSTREAM_AUTO) return undefined; + return normalized; + } + return undefined; +} + +/** A stored pin only counts while the instance still offers that upstream. */ +export function resolvePinnedUpstream( + selections: ReadonlyArray | null | undefined, + configuredUpstreams: ReadonlyArray, +): string | undefined { + const upstream = openRouterUpstreamFromSelection(selections); + return upstream !== undefined && configuredUpstreams.includes(upstream) ? upstream : undefined; +} + +export function ompOpenRouterPinFileName(sessionId: string): string { + return `${encodeURIComponent(sessionId)}.pin`; +} + +/** + * The extension OMP loads with `-e`: it rewrites OpenRouter requests whose model + * matches the session's pin. An in-session id rotation (ctx.newSession) drops + * the pin; T3 re-writes it on the next activation. + */ +export const OMP_OPENROUTER_ROUTING_EXTENSION_SOURCE = `// Generated by Tx Code. Regenerated on server start; edits are overwritten. +import * as fs from "node:fs"; +import * as path from "node:path"; + +export default function txCodeOpenRouterRouting(pi) { + const dir = process.env.${OMP_OPENROUTER_ROUTING_ENV}; + if (!dir) return; + const pinsDir = path.join(dir, "${PINS_DIR_NAME}"); + + const readPin = (ctx) => { + const model = ctx.model; + if (!model || model.provider !== "openrouter") return undefined; + const sessionId = ctx.sessionManager?.getSessionId?.(); + if (!sessionId) return undefined; + try { + const file = path.join(pinsDir, encodeURIComponent(sessionId) + ".pin"); + const [upstream, pinnedModel] = fs.readFileSync(file, "utf8").split("\\n").map((line) => line.trim()); + if (upstream.length === 0 || pinnedModel !== model.provider + "/" + model.id) return undefined; + return [upstream]; + } catch { + return undefined; + } + }; + + pi.on("before_provider_request", (event, ctx) => { + const only = readPin(ctx); + if (!only) return undefined; + const payload = event.payload; + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined; + const current = payload.provider && typeof payload.provider === "object" ? payload.provider : {}; + return { ...payload, provider: { ...current, only } }; + }); +} +`; + +/** Pins are keyed by ACP session id, so files for long-gone sessions are garbage. */ +const pruneOmpOpenRouterPins = Effect.fnUntraced(function* (paths: OmpOpenRouterRoutingPaths) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const now = yield* Clock.currentTimeMillis; + const entries = yield* fs.readDirectory(paths.pinsDir); + yield* Effect.forEach( + entries, + (entry) => + Effect.gen(function* () { + if (!entry.endsWith(".pin")) return; + const fullPath = path.join(paths.pinsDir, entry); + const modifiedAt = Option.getOrNull((yield* fs.stat(fullPath)).mtime); + if (modifiedAt !== null && now - modifiedAt.getTime() <= PIN_FILE_MAX_AGE_MS) return; + yield* fs.remove(fullPath).pipe(Effect.ignore); + }), + { discard: true }, + ); +}); + +export const prepareOmpOpenRouterRouting = Effect.fn("prepareOmpOpenRouterRouting")(function* ( + paths: OmpOpenRouterRoutingPaths, +) { + const fs = yield* FileSystem.FileSystem; + yield* fs.makeDirectory(paths.pinsDir, { recursive: true }); + yield* writeFileStringAtomically({ + filePath: paths.extensionPath, + contents: OMP_OPENROUTER_ROUTING_EXTENSION_SOURCE, + }); + yield* pruneOmpOpenRouterPins(paths).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to prune Oh My Pi OpenRouter pin files", { cause }), + ), + ); +}); + +export const writeOmpOpenRouterPin = Effect.fn("writeOmpOpenRouterPin")(function* (input: { + readonly paths: OmpOpenRouterRoutingPaths; + readonly sessionId: string; + /** OMP model selector (`provider/id`) the pin applies to. */ + readonly model: string; + readonly upstream: string | undefined; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.makeDirectory(input.paths.pinsDir, { recursive: true }); + const filePath = path.join(input.paths.pinsDir, ompOpenRouterPinFileName(input.sessionId)); + if (input.upstream === undefined) { + yield* fs.remove(filePath).pipe(Effect.ignore); + return; + } + yield* writeFileStringAtomically({ + filePath, + contents: `${input.upstream}\n${input.model}\n`, + }); +}); diff --git a/apps/server/src/textGeneration/OmpTextGeneration.ts b/apps/server/src/textGeneration/OmpTextGeneration.ts index 379f2c6d9c97c..880eadbda5464 100644 --- a/apps/server/src/textGeneration/OmpTextGeneration.ts +++ b/apps/server/src/textGeneration/OmpTextGeneration.ts @@ -17,6 +17,12 @@ import { applyOmpAcpModelSelection, makeOmpTextGenerationAcpRuntime, } from "../provider/acp/OmpAcpSupport.ts"; +import { + ompOpenRouterRoutingPaths, + openRouterUpstreamsFromSetting, + resolvePinnedUpstream, + writeOmpOpenRouterPin, +} from "../provider/acp/OmpOpenRouterRouting.ts"; const OMP_TIMEOUT_MS = 180_000; const isTextGenerationError = Schema.is(TextGenerationError); @@ -29,6 +35,11 @@ export const makeOmpTextGeneration = Effect.fn("makeOmpTextGeneration")(function const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; const serverConfig = yield* ServerConfig; + const configuredUpstreams = openRouterUpstreamsFromSetting(ompSettings.openrouterUpstreams); + const openRouterRouting = + configuredUpstreams.length > 0 + ? yield* ompOpenRouterRoutingPaths(serverConfig.stateDir) + : undefined; const imagePromptParts = Effect.fn("OmpTextGeneration.imagePromptParts")(function* ( attachments: ReadonlyArray | undefined, @@ -58,6 +69,10 @@ export const makeOmpTextGeneration = Effect.fn("makeOmpTextGeneration")(function const sessionDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-omp-text-session-", }); + const upstream = + openRouterRouting === undefined + ? undefined + : resolvePinnedUpstream(modelSelection.options, configuredUpstreams); const runtime = yield* makeOmpTextGenerationAcpRuntime({ ompSettings, environment, @@ -65,6 +80,7 @@ export const makeOmpTextGeneration = Effect.fn("makeOmpTextGeneration")(function cwd, sessionDir, clientInfo: { name: "t3-code-git-text", version: "0.0.0" }, + ...(upstream === undefined ? {} : { openRouterRouting }), }).pipe(Effect.provideService(Crypto.Crypto, crypto)); yield* runtime.handleSessionUpdate((notification) => { @@ -80,7 +96,27 @@ export const makeOmpTextGeneration = Effect.fn("makeOmpTextGeneration")(function ); const promptResult = yield* Effect.gen(function* () { - yield* runtime.start(); + const started = yield* runtime.start(); + if (upstream !== undefined && openRouterRouting !== undefined) { + const pin = { + paths: openRouterRouting, + sessionId: started.sessionId, + model: modelSelection.model, + }; + yield* Effect.acquireRelease( + writeOmpOpenRouterPin({ ...pin, upstream }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to write Oh My Pi OpenRouter pin", { cause }), + ), + ), + () => + writeOmpOpenRouterPin({ ...pin, upstream: undefined }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to clear Oh My Pi OpenRouter pin", { cause }), + ), + ), + ); + } yield* applyOmpAcpModelSelection({ runtime, model: modelSelection.model, diff --git a/docs/user/providers-omp.md b/docs/user/providers-omp.md index ee247ec194bc9..47d09acd3738f 100644 --- a/docs/user/providers-omp.md +++ b/docs/user/providers-omp.md @@ -55,3 +55,21 @@ currently applies its ACP client gate and its native approval gate to those call OMP does not yet expose the provider-history controls that Tx Code needs for checkpoint rollback or the Tx Code Plan mode lifecycle. Tx Code hides Plan mode for OMP and reports checkpoint rollback as unsupported. Follow-up messages wait for the active OMP turn to finish, then start a new turn. + +## OpenRouter upstreams + +OpenRouter can serve one model from several upstream providers, such as DeepInfra, Cerebras, or +Amazon Bedrock. Those endpoints differ in price, quantization, throughput, and context limit. To +choose one, list the upstreams you use under **Settings → Providers → Oh My Pi → OpenRouter +upstreams**, comma-separated, for example `deepinfra, cerebras`. + +OpenRouter models then show an **Upstream** control beside **Thinking** in the composer. **Auto** +keeps OpenRouter's own routing; picking a provider pins that thread's requests for that model to it, +including after the thread is resumed and for delegated work that runs the same model. A change +applies from the next message, and the selection is stored with the thread, so another device sees +the same pin. + +A pin is a hard restriction: if the chosen upstream does not serve the model, OpenRouter rejects the +request instead of falling back. Pick **Auto** to restore OpenRouter's routing. Tx Code applies the +pin through a small OMP extension it generates itself; your OMP configuration and `models.yml` are +not modified. diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 8c2b13980eaf7..f4b6862a9e057 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -918,13 +918,25 @@ export const OmpSettings = makeProviderSettingsSchema( }, }), ), + openrouterUpstreams: TrimmedString.pipe( + Schema.withDecodingDefault(Effect.succeed("")), + Schema.annotateKey({ + title: "OpenRouter upstreams", + description: + "Comma-separated OpenRouter provider slugs offered as an upstream pin on Oh My Pi OpenRouter models (for example deepinfra, cerebras). Leave empty to hide the pin.", + providerSettingsForm: { + placeholder: "deepinfra, cerebras", + clearWhenEmpty: "omit", + }, + }), + ), customModels: Schema.Array(Schema.String).pipe( Schema.withDecodingDefault(Effect.succeed([])), Schema.annotateKey({ providerSettingsForm: { hidden: true } }), ), }, { - order: ["binaryPath", "launchArgs"], + order: ["binaryPath", "launchArgs", "openrouterUpstreams"], }, ); export type OmpSettings = typeof OmpSettings.Type;