refactor(providers): share template model cloning

This commit is contained in:
Peter Steinberger
2026-03-17 04:20:13 +00:00
parent dd85ff4da7
commit ed06d21013
4 changed files with 90 additions and 72 deletions

View File

@@ -0,0 +1,56 @@
import type { ModelRegistry } from "@mariozechner/pi-coding-agent";
import { describe, expect, it } from "vitest";
import { cloneFirstTemplateModel } from "./provider-model-helpers.js";
import type { ProviderResolveDynamicModelContext, ProviderRuntimeModel } from "./types.js";
function createContext(models: ProviderRuntimeModel[]): ProviderResolveDynamicModelContext {
return {
provider: "test-provider",
modelId: "next-model",
modelRegistry: {
find(providerId: string, modelId: string) {
return (
models.find((model) => model.provider === providerId && model.id === modelId) ?? null
);
},
} as ModelRegistry,
};
}
describe("cloneFirstTemplateModel", () => {
it("clones the first matching template and applies patches", () => {
const model = cloneFirstTemplateModel({
providerId: "test-provider",
modelId: " next-model ",
templateIds: ["missing", "template-a", "template-b"],
ctx: createContext([
{
id: "template-a",
name: "Template A",
provider: "test-provider",
api: "openai-completions",
} as ProviderRuntimeModel,
]),
patch: { reasoning: true },
});
expect(model).toMatchObject({
id: "next-model",
name: "next-model",
provider: "test-provider",
api: "openai-completions",
reasoning: true,
});
});
it("returns undefined when no template exists", () => {
const model = cloneFirstTemplateModel({
providerId: "test-provider",
modelId: "next-model",
templateIds: ["missing"],
ctx: createContext([]),
});
expect(model).toBeUndefined();
});
});

View File

@@ -0,0 +1,28 @@
import { normalizeModelCompat } from "../agents/model-compat.js";
import type { ProviderResolveDynamicModelContext, ProviderRuntimeModel } from "./types.js";
export function cloneFirstTemplateModel(params: {
providerId: string;
modelId: string;
templateIds: readonly string[];
ctx: ProviderResolveDynamicModelContext;
patch?: Partial<ProviderRuntimeModel>;
}): ProviderRuntimeModel | undefined {
const trimmedModelId = params.modelId.trim();
for (const templateId of [...new Set(params.templateIds)].filter(Boolean)) {
const template = params.ctx.modelRegistry.find(
params.providerId,
templateId,
) as ProviderRuntimeModel | null;
if (!template) {
continue;
}
return normalizeModelCompat({
...template,
id: trimmedModelId,
name: trimmedModelId,
...params.patch,
} as ProviderRuntimeModel);
}
return undefined;
}