Vendor OpenClaw source as Adolf fork baseline
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

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
This commit is contained in:
2026-07-05 09:36:54 +00:00
parent 3216769225
commit bedb527145
21108 changed files with 6010766 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
# OpenClaw Kilo Gateway Provider
Official OpenClaw provider plugin for Kilo Gateway.
Install from OpenClaw:
```bash
openclaw plugins install @openclaw/kilocode-provider
openclaw gateway restart
```
See <https://docs.openclaw.ai/providers/kilocode> for setup and configuration.

View File

@@ -0,0 +1,15 @@
// Kilocode API module exposes the plugin public contract.
export { buildKilocodeProvider, buildKilocodeProviderWithDiscovery } from "./provider-catalog.js";
export {
buildKilocodeModelDefinition,
KILOCODE_BASE_URL,
KILOCODE_DEFAULT_CONTEXT_WINDOW,
KILOCODE_DEFAULT_COST,
KILOCODE_DEFAULT_MAX_TOKENS,
KILOCODE_DEFAULT_MODEL_ID,
KILOCODE_DEFAULT_MODEL_NAME,
KILOCODE_DEFAULT_MODEL_REF,
KILOCODE_MODELS_URL,
KILOCODE_MODEL_CATALOG,
discoverKilocodeModels,
} from "./provider-models.js";

View File

@@ -0,0 +1,23 @@
// Kilocode tests cover implicit provider plugin behavior.
import { describe, expect, it } from "vitest";
import { buildKilocodeProvider } from "./provider-catalog.js";
describe("Kilo Gateway implicit provider", () => {
it("publishes the Kilo static provider catalog used by implicit provider setup", () => {
const provider = buildKilocodeProvider();
expect(provider.baseUrl).toBe("https://api.kilo.ai/api/gateway/");
expect(provider.api).toBe("openai-completions");
expect(provider.models).toStrictEqual([
{
id: "kilo/auto",
name: "Kilo Auto",
reasoning: true,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 128000,
},
]);
});
});

View File

@@ -0,0 +1,236 @@
// Kilocode tests cover index plugin behavior.
import type { StreamFn } from "openclaw/plugin-sdk/agent-core";
import type { Context, Model } from "openclaw/plugin-sdk/llm";
import { registerSingleProviderPlugin } from "openclaw/plugin-sdk/plugin-test-runtime";
import { expectPassthroughReplayPolicy } from "openclaw/plugin-sdk/provider-test-contracts";
import { describe, expect, it } from "vitest";
import plugin from "./index.js";
describe("kilocode provider plugin", () => {
it("owns passthrough-gemini replay policy for Gemini-backed models", async () => {
await expectPassthroughReplayPolicy({
plugin,
providerId: "kilocode",
modelId: "gemini-2.5-pro",
sanitizeThoughtSignatures: true,
});
});
it("wires kilocode-thinking stream hooks", async () => {
const provider = await registerSingleProviderPlugin(plugin);
let capturedPayload: Record<string, unknown> | undefined;
const baseStreamFn: StreamFn = (model, _context, options) => {
const payload = { config: { thinkingConfig: { thinkingBudget: -1 } } } as Record<
string,
unknown
>;
options?.onPayload?.(payload as never, model as never);
capturedPayload = payload;
return {} as never;
};
const wrappedReasoning = provider.wrapStreamFn?.({
provider: "kilocode",
modelId: "openai/gpt-5.4",
thinkingLevel: "high",
streamFn: baseStreamFn,
} as never);
void wrappedReasoning?.(
{
api: "openai-completions",
provider: "kilocode",
id: "openai/gpt-5.4",
} as Model<"openai-completions">,
{ messages: [] } as Context,
{},
);
expect(capturedPayload).toEqual({
config: { thinkingConfig: { thinkingBudget: -1 } },
reasoning: { effort: "high" },
});
const wrappedAuto = provider.wrapStreamFn?.({
provider: "kilocode",
modelId: "kilo/auto",
thinkingLevel: "high",
streamFn: baseStreamFn,
} as never);
void wrappedAuto?.(
{
api: "openai-completions",
provider: "kilocode",
id: "kilo/auto",
} as Model<"openai-completions">,
{ messages: [] } as Context,
{},
);
expect(capturedPayload).not.toHaveProperty("reasoning");
});
it("normalizes string stop to array in plugin-owned stream hook", async () => {
const provider = await registerSingleProviderPlugin(plugin);
const payloads: Array<Record<string, unknown>> = [];
const baseStreamFn: StreamFn = (model, _context, options) => {
const payload: Record<string, unknown> = { stop: "\n" };
options?.onPayload?.(payload as never, model as never);
payloads.push(payload);
return {} as never;
};
const wrapped = provider.wrapStreamFn?.({
provider: "kilocode",
modelId: "deepseek/deepseek-v4-flash",
streamFn: baseStreamFn,
} as never);
void wrapped?.(
{
api: "openai-completions",
provider: "kilocode",
id: "deepseek/deepseek-v4-flash",
} as Model<"openai-completions">,
{ messages: [] } as Context,
{},
);
expect(payloads[0]?.stop).toEqual(["\n"]);
});
it("normalizes string stop after caller payload hooks", async () => {
const provider = await registerSingleProviderPlugin(plugin);
const payloads: Array<Record<string, unknown>> = [];
const baseStreamFn: StreamFn = (model, _context, options) => {
const payload: Record<string, unknown> = {};
options?.onPayload?.(payload as never, model as never);
payloads.push(payload);
return {} as never;
};
const wrapped = provider.wrapStreamFn?.({
provider: "kilocode",
modelId: "deepseek/deepseek-v4-flash",
streamFn: baseStreamFn,
} as never);
void wrapped?.(
{
api: "openai-completions",
provider: "kilocode",
id: "deepseek/deepseek-v4-flash",
} as Model<"openai-completions">,
{ messages: [] } as Context,
{
onPayload: (payload) => {
(payload as Record<string, unknown>).stop = "\n";
},
},
);
expect(payloads[0]?.stop).toEqual(["\n"]);
});
it("leaves array stop unchanged in plugin-owned stream hook", async () => {
const provider = await registerSingleProviderPlugin(plugin);
const payloads: Array<Record<string, unknown>> = [];
const baseStreamFn: StreamFn = (model, _context, options) => {
const payload: Record<string, unknown> = { stop: ["\n", "END"] };
options?.onPayload?.(payload as never, model as never);
payloads.push(payload);
return {} as never;
};
const wrapped = provider.wrapStreamFn?.({
provider: "kilocode",
modelId: "deepseek/deepseek-v4-flash",
streamFn: baseStreamFn,
} as never);
void wrapped?.(
{
api: "openai-completions",
provider: "kilocode",
id: "deepseek/deepseek-v4-flash",
} as Model<"openai-completions">,
{ messages: [] } as Context,
{},
);
expect(payloads[0]?.stop).toEqual(["\n", "END"]);
});
it("keeps Kilo feature headers case-insensitively provider-owned", async () => {
const provider = await registerSingleProviderPlugin(plugin);
let capturedHeaders: Record<string, string> | undefined;
const baseStreamFn: StreamFn = (_model, _context, options) => {
capturedHeaders = options?.headers;
return {} as never;
};
const wrapped = provider.wrapStreamFn?.({
provider: "kilocode",
modelId: "deepseek/deepseek-v4-flash",
streamFn: baseStreamFn,
} as never);
void wrapped?.(
{
api: "openai-completions",
provider: "kilocode",
id: "deepseek/deepseek-v4-flash",
} as Model<"openai-completions">,
{ messages: [] } as Context,
{
headers: {
"x-kilocode-feature": "spoofed",
"X-Custom": "1",
},
},
);
const featureHeaderKeys = Object.keys(capturedHeaders ?? {}).filter(
(key) => key.toLowerCase() === "x-kilocode-feature",
);
expect(featureHeaderKeys).toEqual(["X-KILOCODE-FEATURE"]);
expect(capturedHeaders?.["X-KILOCODE-FEATURE"]).toBe("openclaw");
expect(capturedHeaders?.["X-Custom"]).toBe("1");
});
it("publishes configured Kilo models through plugin-owned catalog augmentation", async () => {
const provider = await registerSingleProviderPlugin(plugin);
expect(
provider.augmentModelCatalog?.({
config: {
models: {
providers: {
kilocode: {
models: [
{
id: "google/gemini-3-pro-preview",
name: "Gemini 3 Pro Preview",
input: ["text", "image"],
reasoning: true,
contextWindow: 1048576,
},
],
},
},
},
},
} as never),
).toEqual([
{
provider: "kilocode",
id: "google/gemini-3.1-pro-preview",
name: "Gemini 3 Pro Preview",
input: ["text", "image"],
reasoning: true,
contextWindow: 1048576,
},
]);
});
});

View File

@@ -0,0 +1,44 @@
// Kilocode plugin entrypoint registers its OpenClaw integration.
import { readConfiguredProviderCatalogEntries } from "openclaw/plugin-sdk/provider-catalog-shared";
import { defineSingleProviderPluginEntry } from "openclaw/plugin-sdk/provider-entry";
import { PASSTHROUGH_GEMINI_REPLAY_HOOKS } from "openclaw/plugin-sdk/provider-model-shared";
import { applyKilocodeConfig, KILOCODE_DEFAULT_MODEL_REF } from "./onboard.js";
import { buildKilocodeProvider, buildKilocodeProviderWithDiscovery } from "./provider-catalog.js";
import { wrapKilocodeProviderStream } from "./stream.js";
const PROVIDER_ID = "kilocode";
export default defineSingleProviderPluginEntry({
id: PROVIDER_ID,
name: "Kilo Gateway Provider",
description: "Bundled Kilo Gateway provider plugin",
provider: {
label: "Kilo Gateway",
docsPath: "/providers/kilocode",
auth: [
{
methodId: "api-key",
label: "Kilo Gateway API key",
hint: "API key (OpenRouter-compatible)",
optionKey: "kilocodeApiKey",
flagName: "--kilocode-api-key",
envVar: "KILOCODE_API_KEY",
promptMessage: "Enter Kilo Gateway API key",
defaultModel: KILOCODE_DEFAULT_MODEL_REF,
applyConfig: (cfg) => applyKilocodeConfig(cfg),
},
],
catalog: {
buildProvider: buildKilocodeProviderWithDiscovery,
buildStaticProvider: buildKilocodeProvider,
},
augmentModelCatalog: ({ config }) =>
readConfiguredProviderCatalogEntries({
config,
providerId: PROVIDER_ID,
}),
...PASSTHROUGH_GEMINI_REPLAY_HOOKS,
wrapStreamFn: wrapKilocodeProviderStream,
isCacheTtlEligible: (ctx) => ctx.modelId.startsWith("anthropic/"),
},
});

12
extensions/kilocode/npm-shrinkwrap.json generated Normal file
View File

@@ -0,0 +1,12 @@
{
"name": "@openclaw/kilocode-provider",
"version": "2026.6.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openclaw/kilocode-provider",
"version": "2026.6.11"
}
}
}

View File

@@ -0,0 +1,171 @@
// Kilocode tests cover onboard plugin behavior.
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
import { resolveEnvApiKey } from "openclaw/plugin-sdk/provider-auth-runtime";
import { resolveAgentModelPrimaryValue } from "openclaw/plugin-sdk/provider-onboard";
import { describe, expect, it, vi } from "vitest";
import {
buildKilocodeModelDefinition,
KILOCODE_DEFAULT_CONTEXT_WINDOW,
KILOCODE_DEFAULT_MAX_TOKENS,
KILOCODE_DEFAULT_COST,
KILOCODE_DEFAULT_MODEL_ID,
} from "./api.js";
import {
applyKilocodeConfig,
KILOCODE_BASE_URL,
KILOCODE_DEFAULT_MODEL_REF,
} from "./onboard.js";
const emptyCfg: OpenClawConfig = {};
const KILOCODE_MODEL_IDS = ["kilo/auto"];
function requireKilocodeProvider(cfg: OpenClawConfig) {
const provider = cfg.models?.providers?.kilocode;
if (!provider) {
throw new Error("expected Kilocode provider config");
}
return provider;
}
describe("Kilo Gateway provider config", () => {
describe("constants", () => {
it("KILOCODE_BASE_URL points to kilo openrouter endpoint", () => {
expect(KILOCODE_BASE_URL).toBe("https://api.kilo.ai/api/gateway/");
});
it("KILOCODE_DEFAULT_MODEL_REF includes provider prefix", () => {
expect(KILOCODE_DEFAULT_MODEL_REF).toBe("kilocode/kilo/auto");
});
it("KILOCODE_DEFAULT_MODEL_ID is kilo/auto", () => {
expect(KILOCODE_DEFAULT_MODEL_ID).toBe("kilo/auto");
});
});
describe("buildKilocodeModelDefinition", () => {
it("returns correct model shape", () => {
const model = buildKilocodeModelDefinition();
expect(model.id).toBe(KILOCODE_DEFAULT_MODEL_ID);
expect(model.name).toBe("Kilo Auto");
expect(model.reasoning).toBe(true);
expect(model.input).toEqual(["text", "image"]);
expect(model.contextWindow).toBe(KILOCODE_DEFAULT_CONTEXT_WINDOW);
expect(model.maxTokens).toBe(KILOCODE_DEFAULT_MAX_TOKENS);
expect(model.cost).toEqual(KILOCODE_DEFAULT_COST);
});
});
describe("applyKilocodeConfig", () => {
it("registers kilocode provider with correct baseUrl and api", () => {
const result = applyKilocodeConfig(emptyCfg);
const provider = requireKilocodeProvider(result);
expect(provider.baseUrl).toBe(KILOCODE_BASE_URL);
expect(provider.api).toBe("openai-completions");
});
it("includes the default model in the provider model list", () => {
const result = applyKilocodeConfig(emptyCfg);
const provider = result.models?.providers?.kilocode;
const models = provider?.models;
expect(Array.isArray(models)).toBe(true);
const modelIds = models?.map((m) => m.id) ?? [];
expect(modelIds).toContain(KILOCODE_DEFAULT_MODEL_ID);
});
it("surfaces the full Kilo model catalog", () => {
const result = applyKilocodeConfig(emptyCfg);
const provider = result.models?.providers?.kilocode;
const modelIds = provider?.models?.map((m) => m.id) ?? [];
for (const modelId of KILOCODE_MODEL_IDS) {
expect(modelIds).toContain(modelId);
}
});
it("appends missing catalog models to existing Kilo provider config", () => {
const result = applyKilocodeConfig({
models: {
providers: {
kilocode: {
baseUrl: KILOCODE_BASE_URL,
api: "openai-completions",
models: [buildKilocodeModelDefinition()],
},
},
},
});
const modelIds = result.models?.providers?.kilocode?.models?.map((m) => m.id) ?? [];
for (const modelId of KILOCODE_MODEL_IDS) {
expect(modelIds).toContain(modelId);
}
});
it("sets Kilo Gateway alias in agent default models", () => {
const result = applyKilocodeConfig(emptyCfg);
const agentModel = result.agents?.defaults?.models?.[KILOCODE_DEFAULT_MODEL_REF];
expect(agentModel).toEqual({ alias: "Kilo Gateway" });
});
it("preserves existing alias if already set", () => {
const cfg: OpenClawConfig = {
agents: {
defaults: {
models: {
[KILOCODE_DEFAULT_MODEL_REF]: { alias: "My Custom Alias" },
},
},
},
};
const result = applyKilocodeConfig(cfg);
const agentModel = result.agents?.defaults?.models?.[KILOCODE_DEFAULT_MODEL_REF];
expect(agentModel?.alias).toBe("My Custom Alias");
});
it("does not change the default model selection", () => {
const cfg: OpenClawConfig = {
agents: {
defaults: {
model: { primary: "openai/gpt-5" },
},
},
};
const result = applyKilocodeConfig(cfg);
expect(resolveAgentModelPrimaryValue(result.agents?.defaults?.model)).toBe("openai/gpt-5");
});
});
it("sets kilocode as the default model", () => {
const result = applyKilocodeConfig(emptyCfg);
expect(resolveAgentModelPrimaryValue(result.agents?.defaults?.model)).toBe(
KILOCODE_DEFAULT_MODEL_REF,
);
const provider = requireKilocodeProvider(result);
expect(provider.baseUrl).toBe(KILOCODE_BASE_URL);
});
describe("env var resolution", () => {
it("resolves KILOCODE_API_KEY from env", () => {
vi.stubEnv("KILOCODE_API_KEY", "test-kilo-key");
try {
const result = resolveEnvApiKey("kilocode");
expect(result).toEqual({
apiKey: "test-kilo-key",
source: "env: KILOCODE_API_KEY",
});
} finally {
vi.unstubAllEnvs();
}
});
it("returns null when KILOCODE_API_KEY is not set", () => {
vi.stubEnv("KILOCODE_API_KEY", "");
try {
const result = resolveEnvApiKey("kilocode");
expect(result).toBeNull();
} finally {
vi.unstubAllEnvs();
}
});
});
});

View File

@@ -0,0 +1,24 @@
// Kilocode setup module handles plugin onboarding behavior.
import {
createModelCatalogPresetAppliers,
type OpenClawConfig,
} from "openclaw/plugin-sdk/provider-onboard";
import { buildKilocodeProvider } from "./provider-catalog.js";
import { KILOCODE_BASE_URL, KILOCODE_DEFAULT_MODEL_REF } from "./provider-models.js";
export { KILOCODE_BASE_URL, KILOCODE_DEFAULT_MODEL_REF };
const kilocodePresetAppliers = createModelCatalogPresetAppliers({
primaryModelRef: KILOCODE_DEFAULT_MODEL_REF,
resolveParams: (_cfg: OpenClawConfig) => ({
providerId: "kilocode",
api: "openai-completions",
baseUrl: KILOCODE_BASE_URL,
catalogModels: buildKilocodeProvider().models ?? [],
aliases: [{ modelRef: KILOCODE_DEFAULT_MODEL_REF, alias: "Kilo Gateway" }],
}),
});
export function applyKilocodeConfig(cfg: OpenClawConfig): OpenClawConfig {
return kilocodePresetAppliers.applyConfig(cfg);
}

View File

@@ -0,0 +1,76 @@
{
"id": "kilocode",
"activation": {
"onStartup": false
},
"enabledByDefault": true,
"providers": ["kilocode"],
"modelPricing": {
"providers": {
"kilocode": {
"openRouter": {
"passthroughProviderModel": true
},
"liteLLM": {
"passthroughProviderModel": true
}
}
}
},
"setup": {
"providers": [
{
"id": "kilocode",
"envVars": ["KILOCODE_API_KEY"]
}
]
},
"providerAuthChoices": [
{
"provider": "kilocode",
"method": "api-key",
"choiceId": "kilocode-api-key",
"choiceLabel": "Kilo Gateway API key",
"choiceHint": "API key (OpenRouter-compatible)",
"groupId": "kilocode",
"groupLabel": "Kilo Gateway",
"groupHint": "API key (OpenRouter-compatible)",
"optionKey": "kilocodeApiKey",
"cliFlag": "--kilocode-api-key",
"cliOption": "--kilocode-api-key <key>",
"cliDescription": "Kilo Gateway API key"
}
],
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {}
},
"modelCatalog": {
"providers": {
"kilocode": {
"baseUrl": "https://api.kilo.ai/api/gateway/",
"api": "openai-completions",
"models": [
{
"id": "kilo/auto",
"name": "Kilo Auto",
"reasoning": true,
"input": ["text", "image"],
"cost": {
"input": 0,
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
},
"contextWindow": 1000000,
"maxTokens": 128000
}
]
}
},
"discovery": {
"kilocode": "refreshable"
}
}
}

View File

@@ -0,0 +1,35 @@
{
"name": "@openclaw/kilocode-provider",
"version": "2026.6.11",
"description": "OpenClaw Kilo Gateway provider plugin.",
"repository": {
"type": "git",
"url": "https://github.com/openclaw/openclaw"
},
"type": "module",
"devDependencies": {
"@openclaw/plugin-sdk": "workspace:*"
},
"openclaw": {
"extensions": [
"./index.ts"
],
"install": {
"clawhubSpec": "clawhub:@openclaw/kilocode-provider",
"npmSpec": "@openclaw/kilocode-provider",
"defaultChoice": "npm",
"minHostVersion": ">=2026.6.8"
},
"compat": {
"pluginApi": ">=2026.6.11"
},
"build": {
"openclawVersion": "2026.6.11",
"bundledDist": false
},
"release": {
"publishToClawHub": true,
"publishToNpm": true
}
}
}

View File

@@ -0,0 +1,35 @@
// Kilocode provider module implements model/runtime integration.
import type { ModelProviderConfig } from "openclaw/plugin-sdk/provider-model-shared";
import {
discoverKilocodeModels,
KILOCODE_BASE_URL as LOCAL_KILOCODE_BASE_URL,
KILOCODE_DEFAULT_CONTEXT_WINDOW as LOCAL_KILOCODE_DEFAULT_CONTEXT_WINDOW,
KILOCODE_DEFAULT_COST as LOCAL_KILOCODE_DEFAULT_COST,
KILOCODE_DEFAULT_MAX_TOKENS as LOCAL_KILOCODE_DEFAULT_MAX_TOKENS,
KILOCODE_MODEL_CATALOG as LOCAL_KILOCODE_MODEL_CATALOG,
} from "./provider-models.js";
export function buildKilocodeProvider(): ModelProviderConfig {
return {
baseUrl: LOCAL_KILOCODE_BASE_URL,
api: "openai-completions",
models: LOCAL_KILOCODE_MODEL_CATALOG.map((model) => ({
id: model.id,
name: model.name,
reasoning: model.reasoning,
input: model.input,
cost: LOCAL_KILOCODE_DEFAULT_COST,
contextWindow: model.contextWindow ?? LOCAL_KILOCODE_DEFAULT_CONTEXT_WINDOW,
maxTokens: model.maxTokens ?? LOCAL_KILOCODE_DEFAULT_MAX_TOKENS,
})),
};
}
export async function buildKilocodeProviderWithDiscovery(): Promise<ModelProviderConfig> {
const models = await discoverKilocodeModels();
return {
baseUrl: LOCAL_KILOCODE_BASE_URL,
api: "openai-completions",
models,
};
}

View File

@@ -0,0 +1,321 @@
// Kilocode tests cover provider models plugin behavior.
import { afterAll, describe, expect, it, vi } from "vitest";
const { fetchWithSsrFGuardMock } = vi.hoisted(() => ({
fetchWithSsrFGuardMock: vi.fn(),
}));
vi.mock("openclaw/plugin-sdk/ssrf-runtime", () => ({
fetchWithSsrFGuard: fetchWithSsrFGuardMock,
ssrfPolicyFromHttpBaseUrlAllowedHostname: (baseUrl: string) => ({
allowedHostnames: [new URL(baseUrl).hostname],
}),
}));
import { discoverKilocodeModels, KILOCODE_MODELS_URL } from "./provider-models.js";
type MockKilocodeFetch = ((url: string, init?: RequestInit) => Promise<Response>) & {
mock: { calls: unknown[][] };
};
const EXPECTED_STATIC_KILOCODE_MODELS = [
{
id: "kilo/auto",
name: "Kilo Auto",
reasoning: true,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 128000,
},
];
function requireModelById(
models: Awaited<ReturnType<typeof discoverKilocodeModels>>,
id: string,
): Awaited<ReturnType<typeof discoverKilocodeModels>>[number] {
const model = models.find((candidate) => candidate.id === id);
if (!model) {
throw new Error(`expected Kilocode model ${id}`);
}
return model;
}
function requireRecord(value: unknown, label: string): Record<string, unknown> {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`expected ${label} to be a record`);
}
return value as Record<string, unknown>;
}
function requireFirstMockCall(mock: { mock: { calls: unknown[][] } }, label: string): unknown[] {
const [call] = mock.mock.calls;
if (!call) {
throw new Error(`expected ${label}`);
}
return call;
}
function makeGatewayModel(overrides: Record<string, unknown> = {}) {
return {
id: "anthropic/claude-sonnet-4",
name: "Anthropic: Claude Sonnet 4",
created: 1700000000,
description: "A model",
context_length: 200000,
architecture: {
input_modalities: ["text", "image"],
output_modalities: ["text"],
tokenizer: "Claude",
},
top_provider: {
is_moderated: false,
max_completion_tokens: 8192,
},
pricing: {
prompt: "0.000003",
completion: "0.000015",
input_cache_read: "0.0000003",
input_cache_write: "0.00000375",
},
supported_parameters: ["max_tokens", "temperature", "tools", "reasoning"],
...overrides,
};
}
function makeAutoModel(overrides: Record<string, unknown> = {}) {
return makeGatewayModel({
id: "kilo/auto",
name: "Kilo: Auto",
context_length: 1000000,
architecture: {
input_modalities: ["text", "image"],
output_modalities: ["text"],
tokenizer: "Other",
},
top_provider: {
is_moderated: false,
max_completion_tokens: 128000,
},
pricing: {
prompt: "0.000005",
completion: "0.000025",
},
supported_parameters: ["max_tokens", "temperature", "tools", "reasoning", "include_reasoning"],
...overrides,
});
}
function jsonResponse(payload: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "Content-Type": "application/json" },
...init,
});
}
async function withFetchPathTest(mockFetch: MockKilocodeFetch, runAssertions: () => Promise<void>) {
const release = vi.fn(async () => {});
vi.stubEnv("NODE_ENV", "");
vi.stubEnv("VITEST", "");
fetchWithSsrFGuardMock.mockReset();
const callMockFetch = mockFetch as unknown as (
url: string,
init?: RequestInit,
) => Promise<unknown>;
fetchWithSsrFGuardMock.mockImplementation(
async (params: { url: string; init?: RequestInit }) => ({
response: await callMockFetch(params.url, params.init),
release,
}),
);
try {
await runAssertions();
} finally {
vi.unstubAllEnvs();
fetchWithSsrFGuardMock.mockReset();
}
}
afterAll(() => {
vi.doUnmock("openclaw/plugin-sdk/ssrf-runtime");
vi.resetModules();
});
describe("discoverKilocodeModels", () => {
it("returns static catalog in test environment", async () => {
const models = await discoverKilocodeModels();
expect(models).toStrictEqual(EXPECTED_STATIC_KILOCODE_MODELS);
});
it("static catalog has correct defaults for kilo/auto", async () => {
const models = await discoverKilocodeModels();
const auto = requireModelById(models, "kilo/auto");
expect(auto.name).toBe("Kilo Auto");
expect(auto.reasoning).toBe(true);
expect(auto.input).toEqual(["text", "image"]);
expect(auto.contextWindow).toBe(1000000);
expect(auto.maxTokens).toBe(128000);
expect(auto.cost).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
});
});
describe("discoverKilocodeModels (fetch path)", () => {
it("parses gateway models with correct pricing conversion", async () => {
const mockFetch = vi.fn().mockResolvedValue(
jsonResponse({
data: [makeAutoModel(), makeGatewayModel()],
}),
);
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
expect(fetchWithSsrFGuardMock).toHaveBeenCalledOnce();
const [guardedFetchParams] = requireFirstMockCall(
fetchWithSsrFGuardMock,
"guarded fetch call",
);
const guardedFetch = requireRecord(guardedFetchParams, "guarded fetch params");
expect(guardedFetch.url).toBe(KILOCODE_MODELS_URL);
const guardedInit = requireRecord(guardedFetch.init, "guarded fetch init");
expect(guardedInit.headers).toEqual({ Accept: "application/json" });
expect(guardedFetch.policy).toEqual({ allowedHostnames: ["api.kilo.ai"] });
expect(guardedFetch.timeoutMs).toBe(5000);
expect(guardedFetch.auditContext).toBe("kilocode.model_discovery");
expect(mockFetch).toHaveBeenCalledOnce();
const [fetchUrl, fetchOptions] = requireFirstMockCall(mockFetch, "mock fetch call");
expect(fetchUrl).toBe(KILOCODE_MODELS_URL);
const fetchInit = requireRecord(fetchOptions, "mock fetch init");
expect(fetchInit.headers).toEqual({ Accept: "application/json" });
expect(models.length).toBe(2);
const sonnet = requireModelById(models, "anthropic/claude-sonnet-4");
expect(sonnet.cost.input).toBeCloseTo(3);
expect(sonnet.cost.output).toBeCloseTo(15);
expect(sonnet.cost.cacheRead).toBeCloseTo(0.3);
expect(sonnet.cost.cacheWrite).toBeCloseTo(3.75);
expect(sonnet.input).toEqual(["text", "image"]);
expect(sonnet.reasoning).toBe(true);
expect(sonnet.contextWindow).toBe(200000);
expect(sonnet.maxTokens).toBe(8192);
});
});
it("falls back to static catalog on network error", async () => {
const mockFetch = vi.fn().mockRejectedValue(new Error("network error"));
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
expect(models).toStrictEqual(EXPECTED_STATIC_KILOCODE_MODELS);
});
});
it("falls back to static catalog on HTTP error", async () => {
const mockFetch = vi.fn().mockResolvedValue(new Response("", { status: 500 }));
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
expect(models).toStrictEqual(EXPECTED_STATIC_KILOCODE_MODELS);
});
});
it("falls back to static catalog for malformed successful model list payloads", async () => {
for (const payload of [[], { data: {} }, { data: [null] }]) {
const mockFetch = vi.fn().mockResolvedValue(jsonResponse(payload));
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
expect(models).toStrictEqual(EXPECTED_STATIC_KILOCODE_MODELS);
});
}
});
it("falls back from malformed live token metadata", async () => {
const mockFetch = vi.fn().mockResolvedValue(
jsonResponse({
data: [
makeGatewayModel({
id: "some/bad-window",
context_length: -1,
top_provider: { max_completion_tokens: 8192.5 },
}),
makeGatewayModel({
id: "some/bad-output",
context_length: Number.POSITIVE_INFINITY,
top_provider: { max_completion_tokens: 0 },
}),
],
}),
);
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
expect(requireModelById(models, "some/bad-window")).toMatchObject({
contextWindow: 1000000,
maxTokens: 128000,
});
expect(requireModelById(models, "some/bad-output")).toMatchObject({
contextWindow: 1000000,
maxTokens: 128000,
});
});
});
it("ensures kilo/auto is present even when API doesn't return it", async () => {
const mockFetch = vi.fn().mockResolvedValue(
jsonResponse({
data: [makeGatewayModel()],
}),
);
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
expect(requireModelById(models, "kilo/auto").id).toBe("kilo/auto");
expect(requireModelById(models, "anthropic/claude-sonnet-4").id).toBe(
"anthropic/claude-sonnet-4",
);
});
});
it("detects text-only models without image modality", async () => {
const textOnlyModel = makeGatewayModel({
id: "some/text-model",
architecture: {
input_modalities: ["text"],
output_modalities: ["text"],
},
supported_parameters: ["max_tokens", "temperature"],
});
const mockFetch = vi.fn().mockResolvedValue(jsonResponse({ data: [textOnlyModel] }));
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
const textModel = requireModelById(models, "some/text-model");
expect(textModel.input).toEqual(["text"]);
expect(textModel.reasoning).toBe(false);
});
});
it("keeps a later valid duplicate when an earlier entry is malformed", async () => {
const malformedAutoModel = makeAutoModel({
name: "Broken Kilo Auto",
pricing: undefined,
});
const mockFetch = vi.fn().mockResolvedValue(
jsonResponse({
data: [malformedAutoModel, makeAutoModel(), makeGatewayModel()],
}),
);
await withFetchPathTest(mockFetch, async () => {
const models = await discoverKilocodeModels();
const auto = requireModelById(models, "kilo/auto");
expect(auto.name).toBe("Kilo: Auto");
expect(auto.cost.input).toBeCloseTo(5);
expect(requireModelById(models, "anthropic/claude-sonnet-4").id).toBe(
"anthropic/claude-sonnet-4",
);
});
});
});

View File

@@ -0,0 +1,238 @@
// 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,
};
}

View File

@@ -0,0 +1,108 @@
// Kilocode plugin module implements stream behavior.
import type { ProviderWrapStreamFnContext } from "openclaw/plugin-sdk/plugin-entry";
import { resolveProviderRequestHeaders } from "openclaw/plugin-sdk/provider-http";
import { normalizeOpenAICompatibleReasoningPayload } from "openclaw/plugin-sdk/provider-stream-shared";
import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/string-coerce-runtime";
const KILOCODE_FEATURE_HEADER = "X-KILOCODE-FEATURE";
const KILOCODE_FEATURE_DEFAULT = "openclaw";
const KILOCODE_FEATURE_ENV_VAR = "KILOCODE_FEATURE";
type ThinkLevel = NonNullable<ProviderWrapStreamFnContext["thinkingLevel"]>;
type ProviderStreamFn = NonNullable<ProviderWrapStreamFnContext["streamFn"]>;
function resolveKilocodeAppHeaders(): Record<string, string> {
const feature = process.env[KILOCODE_FEATURE_ENV_VAR]?.trim() || KILOCODE_FEATURE_DEFAULT;
return { [KILOCODE_FEATURE_HEADER]: feature };
}
function normalizeKilocodeStopPayload(payloadObj: Record<string, unknown>): void {
if (typeof payloadObj.stop === "string") {
payloadObj.stop = [payloadObj.stop];
}
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function normalizeKilocodeStopAfterCaller(
value: unknown,
fallbackPayload: Record<string, unknown> | undefined,
): unknown {
const replacementPayload = asRecord(value);
if (replacementPayload) {
normalizeKilocodeStopPayload(replacementPayload);
return value;
}
if (fallbackPayload) {
normalizeKilocodeStopPayload(fallbackPayload);
}
return value;
}
function isProxyReasoningUnsupported(modelId: string): boolean {
const trimmed = normalizeOptionalLowercaseString(modelId);
const slashIndex = trimmed?.indexOf("/") ?? -1;
return slashIndex > 0 && trimmed?.slice(0, slashIndex) === "x-ai";
}
function resolveKilocodeThinkingLevel(ctx: ProviderWrapStreamFnContext): ThinkLevel | undefined {
if (ctx.modelId === "kilo/auto" || isProxyReasoningUnsupported(ctx.modelId)) {
return undefined;
}
return ctx.thinkingLevel;
}
export function createKilocodeStreamWrapper(
baseStreamFn: ProviderWrapStreamFnContext["streamFn"],
thinkingLevel?: ThinkLevel,
): ProviderWrapStreamFnContext["streamFn"] {
if (!baseStreamFn) {
return undefined;
}
const underlying = baseStreamFn;
return (model, context, options) => {
const originalOnPayload = options?.onPayload;
const headers = resolveProviderRequestHeaders({
provider: typeof model.provider === "string" ? model.provider : "kilocode",
api: model.api,
baseUrl: typeof model.baseUrl === "string" ? model.baseUrl : undefined,
capability: "llm",
transport: "stream",
callerHeaders: options?.headers,
defaultHeaders: resolveKilocodeAppHeaders(),
precedence: "defaults-win",
});
return underlying(model, context, {
...options,
headers,
onPayload(payload, payloadModel) {
const payloadObj = asRecord(payload);
if (payloadObj) {
// Keep Kilo thinking defaults overrideable by later caller/config payload hooks.
normalizeOpenAICompatibleReasoningPayload(payloadObj, thinkingLevel);
}
const result = originalOnPayload?.(payload, payloadModel);
if (result && typeof (result as Promise<unknown>).then === "function") {
return Promise.resolve(result).then((resolved) =>
normalizeKilocodeStopAfterCaller(resolved, payloadObj),
);
}
return normalizeKilocodeStopAfterCaller(result, payloadObj);
},
});
};
}
export function wrapKilocodeProviderStream(
ctx: ProviderWrapStreamFnContext,
): ProviderStreamFn | undefined {
if (normalizeOptionalLowercaseString(ctx.provider) !== "kilocode") {
return undefined;
}
return createKilocodeStreamWrapper(ctx.streamFn, resolveKilocodeThinkingLevel(ctx));
}

View File

@@ -0,0 +1,16 @@
{
"extends": "../tsconfig.package-boundary.base.json",
"compilerOptions": {
"rootDir": "."
},
"include": ["./*.ts", "./src/**/*.ts"],
"exclude": [
"./**/*.test.ts",
"./dist/**",
"./node_modules/**",
"./src/test-support/**",
"./src/**/*test-helpers.ts",
"./src/**/*test-harness.ts",
"./src/**/*test-support.ts"
]
}