Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 85 additions & 4 deletions apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand Down Expand Up @@ -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<void>;
}

/** Count root assistant output on the native transport, including frames before RPC settlement. */
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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 &&
Expand Down Expand Up @@ -188,6 +220,7 @@ export const makeOmpAdapterV2 = Effect.fn("makeOmpAdapterV2")(function* (
});

export type OmpAdapterV2DriverEnv =
| ServerConfigModule.ServerConfig
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
Expand All @@ -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<OmpAdapterV2Options, "openRouterRouting" | "writeRoutingPin">,
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<OmpSettings, OmpAdapterV2DriverEnv> = {
driverKind: OMP_PROVIDER,
configSchema: OmpSettings,
Expand All @@ -206,7 +285,9 @@ export const OmpAdapterV2Driver: ProviderAdapterDriver<OmpSettings, OmpAdapterV2
const hostEnvironment = yield* HostProcess.Environment;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
const routing = yield* prepareOpenRouterRouting(input.config.openrouterUpstreams);
return yield* makeOmpAdapterV2({
...routing,
instanceId: input.instanceId,
settings: { ...input.config, enabled: input.enabled },
environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
Expand Down
47 changes: 47 additions & 0 deletions apps/server/src/provider/OmpProvider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,53 @@ describe("OMP model catalog", () => {
]);
});

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([]);
Expand Down
41 changes: 36 additions & 5 deletions apps/server/src/provider/OmpProvider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
type ModelCapabilities,
type OmpSettings,
type ProviderOptionDescriptor,
type ServerProviderModel,
type ServerProvider,
} from "@t3tools/contracts";
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -100,10 +106,11 @@ function thinkingLabel(value: string): string {
function ompModelCapabilities(
thinking: ReadonlyArray<string>,
defaultThinking: string | undefined,
openRouterUpstreams: ReadonlyArray<string>,
): ModelCapabilities {
if (thinking.length === 0) return EMPTY_CAPABILITIES;
return createModelCapabilities({
optionDescriptors: [
const optionDescriptors: Array<ProviderOptionDescriptor> = [];
if (thinking.length > 0) {
optionDescriptors.push(
buildSelectOptionDescriptor({
id: "thinking",
label: "Thinking",
Expand All @@ -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<string> | undefined;
}

/** Parses the documented `omp models --json` catalog without trusting malformed entries. */
Expand Down Expand Up @@ -167,6 +196,7 @@ export function buildOmpModelsFromJson(
selector === defaultSelector
? (roleThinking ?? defaults.defaultThinking)
: defaults.defaultThinking,
provider === "openrouter" ? (defaults.openRouterUpstreams ?? []) : [],
),
} satisfies ServerProviderModel,
];
Expand Down Expand Up @@ -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({
Expand Down
41 changes: 41 additions & 0 deletions apps/server/src/provider/acp/OmpAcpSupport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
Loading
Loading