Files
adolf/extensions/kilocode/provider-models.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

239 lines
7.0 KiB
TypeScript

// Kilocode provider module implements model/runtime integration.
import { readProviderJsonArrayFieldResponse } from "openclaw/plugin-sdk/provider-http";
import type { ModelDefinitionConfig } from "openclaw/plugin-sdk/provider-model-shared";
import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
import {
fetchWithSsrFGuard,
ssrfPolicyFromHttpBaseUrlAllowedHostname,
} from "openclaw/plugin-sdk/ssrf-runtime";
import {
asPositiveSafeInteger,
normalizeLowercaseStringOrEmpty,
} from "openclaw/plugin-sdk/string-coerce-runtime";
const log = createSubsystemLogger("kilocode-models");
export const KILOCODE_BASE_URL = "https://api.kilo.ai/api/gateway/";
export const KILOCODE_DEFAULT_MODEL_ID = "kilo/auto";
export const KILOCODE_DEFAULT_MODEL_REF = `kilocode/${KILOCODE_DEFAULT_MODEL_ID}`;
export const KILOCODE_DEFAULT_MODEL_NAME = "Kilo Auto";
type KilocodeModelCatalogEntry = {
id: string;
name: string;
reasoning: boolean;
input: Array<"text" | "image">;
contextWindow?: number;
maxTokens?: number;
};
export const KILOCODE_MODEL_CATALOG: KilocodeModelCatalogEntry[] = [
{
id: KILOCODE_DEFAULT_MODEL_ID,
name: KILOCODE_DEFAULT_MODEL_NAME,
input: ["text", "image"],
reasoning: true,
},
];
export const KILOCODE_DEFAULT_CONTEXT_WINDOW = 1000000;
export const KILOCODE_DEFAULT_MAX_TOKENS = 128000;
export const KILOCODE_DEFAULT_COST = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
};
export const KILOCODE_MODELS_URL = `${KILOCODE_BASE_URL}models`;
const DISCOVERY_TIMEOUT_MS = 5000;
interface GatewayModelPricing {
prompt: string;
completion: string;
image?: string;
request?: string;
input_cache_read?: string;
input_cache_write?: string;
web_search?: string;
internal_reasoning?: string;
}
interface GatewayModelEntry {
id: string;
name: string;
context_length: number;
architecture?: {
input_modalities?: string[];
output_modalities?: string[];
};
top_provider?: {
max_completion_tokens?: number | null;
};
pricing: GatewayModelPricing;
supported_parameters?: string[];
}
function toPricePerMillion(perToken: string | undefined): number {
if (!perToken) {
return 0;
}
const num = Number(perToken);
if (!Number.isFinite(num) || num < 0) {
return 0;
}
return num * 1_000_000;
}
function parseModality(entry: GatewayModelEntry): Array<"text" | "image"> {
const modalities = entry.architecture?.input_modalities;
if (!Array.isArray(modalities)) {
return ["text"];
}
const hasImage = modalities.some(
(m) => typeof m === "string" && normalizeLowercaseStringOrEmpty(m) === "image",
);
return hasImage ? ["text", "image"] : ["text"];
}
function parseReasoning(entry: GatewayModelEntry): boolean {
const params = entry.supported_parameters;
if (!Array.isArray(params)) {
return false;
}
return params.includes("reasoning") || params.includes("include_reasoning");
}
function toModelDefinition(entry: GatewayModelEntry): ModelDefinitionConfig {
return {
id: entry.id,
name: entry.name || entry.id,
reasoning: parseReasoning(entry),
input: parseModality(entry),
cost: {
input: toPricePerMillion(entry.pricing.prompt),
output: toPricePerMillion(entry.pricing.completion),
cacheRead: toPricePerMillion(entry.pricing.input_cache_read),
cacheWrite: toPricePerMillion(entry.pricing.input_cache_write),
},
contextWindow: asPositiveSafeInteger(entry.context_length) ?? KILOCODE_DEFAULT_CONTEXT_WINDOW,
maxTokens:
asPositiveSafeInteger(entry.top_provider?.max_completion_tokens) ??
KILOCODE_DEFAULT_MAX_TOKENS,
};
}
function buildStaticCatalog(): ModelDefinitionConfig[] {
return KILOCODE_MODEL_CATALOG.map((model) => ({
id: model.id,
name: model.name,
reasoning: model.reasoning,
input: model.input,
cost: KILOCODE_DEFAULT_COST,
contextWindow: model.contextWindow ?? KILOCODE_DEFAULT_CONTEXT_WINDOW,
maxTokens: model.maxTokens ?? KILOCODE_DEFAULT_MAX_TOKENS,
}));
}
function asGatewayModelEntry(value: unknown): GatewayModelEntry {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new Error("Kilocode model list: malformed JSON response");
}
const entry = value as Partial<GatewayModelEntry>;
if (
typeof entry.id !== "string" ||
typeof entry.pricing !== "object" ||
entry.pricing === null ||
Array.isArray(entry.pricing)
) {
throw new Error("Kilocode model list: malformed JSON response");
}
return value as GatewayModelEntry;
}
function readGatewayModelId(value: unknown): string {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return "";
}
const id = (value as Partial<GatewayModelEntry>).id;
return typeof id === "string" ? id.trim() : "";
}
export async function discoverKilocodeModels(): Promise<ModelDefinitionConfig[]> {
if (process.env.NODE_ENV === "test" || process.env.VITEST) {
return buildStaticCatalog();
}
try {
const { response, release } = await fetchWithSsrFGuard({
url: KILOCODE_MODELS_URL,
init: {
headers: { Accept: "application/json" },
},
timeoutMs: DISCOVERY_TIMEOUT_MS,
policy: ssrfPolicyFromHttpBaseUrlAllowedHostname(KILOCODE_BASE_URL),
auditContext: "kilocode.model_discovery",
});
try {
if (!response.ok) {
log.warn(`Failed to discover models: HTTP ${response.status}, using static catalog`);
return buildStaticCatalog();
}
const data = await readProviderJsonArrayFieldResponse(
response,
"Kilocode model list",
"data",
);
if (data.length === 0) {
log.warn("No models found from gateway API, using static catalog");
return buildStaticCatalog();
}
const models: ModelDefinitionConfig[] = [];
const discoveredIds = new Set<string>();
for (const rawEntry of data) {
const id = readGatewayModelId(rawEntry);
try {
const entry = asGatewayModelEntry(rawEntry);
if (!id || discoveredIds.has(id)) {
continue;
}
models.push(toModelDefinition(entry));
discoveredIds.add(id);
} catch (e) {
log.warn(`Skipping malformed model entry "${id}": ${String(e)}`);
}
}
const staticModels = buildStaticCatalog();
for (const staticModel of staticModels) {
if (!discoveredIds.has(staticModel.id)) {
models.unshift(staticModel);
}
}
return models.length > 0 ? models : buildStaticCatalog();
} finally {
await release();
}
} catch (error) {
log.warn(`Discovery failed: ${String(error)}, using static catalog`);
return buildStaticCatalog();
}
}
export function buildKilocodeModelDefinition(): ModelDefinitionConfig {
return {
id: KILOCODE_DEFAULT_MODEL_ID,
name: KILOCODE_DEFAULT_MODEL_NAME,
reasoning: true,
input: ["text", "image"],
cost: KILOCODE_DEFAULT_COST,
contextWindow: KILOCODE_DEFAULT_CONTEXT_WINDOW,
maxTokens: KILOCODE_DEFAULT_MAX_TOKENS,
};
}