Kilo Gateway 供應商整合設計
概覽
本文件說明如何將「Kilo Gateway」作為 OpenClaw 的一級供應商進行整合,參考現有 OpenRouter 實作方式。Kilo Gateway 採用 OpenAI 相容的 Completions API,僅使用不同的 Base URL。
設計決策
1. 供應商命名
建議:kilocode
理由:
- 符合使用者設定範例(
kilocode供應商 key) - 與現有命名慣例一致(如
openrouter、opencode、moonshot) - 簡短好記
- 避免與泛用的「kilo」或「gateway」混淆
曾考慮的替代方案:kilo-gateway —— 因程式碼庫中較少使用連字號名稱,且 kilocode 更簡潔而捨棄。
2. 預設模型參照
建議:kilocode/anthropic/claude-opus-4.6
理由:
- 依據使用者設定範例
- Claude Opus 4.5 是能力出色的預設模型
- 明確選擇模型,避免依賴自動路由
3. Base URL 設定
建議:內建預設值搭配可覆寫設定
- 預設 Base URL:
https://api.kilo.ai/api/gateway/ - 可設定: 是,透過
models.providers.kilocode.baseUrl
此做法與 Moonshot、Venice、Synthetic 等供應商的模式一致。
4. 模型掃描
建議:初期不設專屬的模型掃描端點
理由:
- Kilo Gateway 透過 OpenRouter 代理,因此模型是動態的
- 使用者可在設定檔中手動配置模型
- 若 Kilo Gateway 未來提供
/models端點,屆時可加入掃描功能
5. 特殊處理
建議:繼承 OpenRouter 對 Anthropic 模型的行為
由於 Kilo Gateway 透過 OpenRouter 代理,應套用相同的特殊處理:
anthropic/*模型的快取 TTL 資格判定anthropic/*模型的額外參數(cacheControlTtl)- 對話紀錄策略沿用 OpenRouter 模式
需修改的檔案
核心憑證管理
1. src/commands/onboard-auth.credentials.ts
新增:
export const KILOCODE_DEFAULT_MODEL_REF = "kilocode/anthropic/claude-opus-4.6";
export async function setKilocodeApiKey(key: string, agentDir?: string) {
upsertAuthProfile({
profileId: "kilocode:default",
credential: {
type: "api_key",
provider: "kilocode",
key,
},
agentDir: resolveAuthAgentDir(agentDir),
});
}
2. src/agents/model-auth.ts
在 resolveEnvApiKey() 的 envMap 中新增:
const envMap: Record<string, string> = {
// ... 既有項目
kilocode: "KILOCODE_API_KEY",
};
3. src/config/io.ts
在 SHELL_ENV_EXPECTED_KEYS 中新增:
const SHELL_ENV_EXPECTED_KEYS = [
// ... 既有項目
"KILOCODE_API_KEY",
];
設定套用
4. src/commands/onboard-auth.config-core.ts
新增函式:
export const KILOCODE_BASE_URL = "https://api.kilo.ai/api/gateway/";
export function applyKilocodeProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
const models = { ...cfg.agents?.defaults?.models };
models[KILOCODE_DEFAULT_MODEL_REF] = {
...models[KILOCODE_DEFAULT_MODEL_REF],
alias: models[KILOCODE_DEFAULT_MODEL_REF]?.alias ?? "Kilo Gateway",
};
const providers = { ...cfg.models?.providers };
const existingProvider = providers.kilocode;
const { apiKey: existingApiKey, ...existingProviderRest } = (existingProvider ?? {}) as Record<
string,
unknown
> as { apiKey?: string };
const resolvedApiKey = typeof existingApiKey === "string" ? existingApiKey : undefined;
const normalizedApiKey = resolvedApiKey?.trim();
providers.kilocode = {
...existingProviderRest,
baseUrl: KILOCODE_BASE_URL,
api: "openai-completions",
...(normalizedApiKey ? { apiKey: normalizedApiKey } : {}),
};
return {
...cfg,
agents: {
...cfg.agents,
defaults: {
...cfg.agents?.defaults,
models,
},
},
models: {
mode: cfg.models?.mode ?? "merge",
providers,
},
};
}
export function applyKilocodeConfig(cfg: OpenClawConfig): OpenClawConfig {
const next = applyKilocodeProviderConfig(cfg);
const existingModel = next.agents?.defaults?.model;
return {
...next,
agents: {
...next.agents,
defaults: {
...next.agents?.defaults,
model: {
...(existingModel && "fallbacks" in (existingModel as Record<string, unknown>)
? {
fallbacks: (existingModel as { fallbacks?: string[] }).fallbacks,
}
: undefined),
primary: KILOCODE_DEFAULT_MODEL_REF,
},
},
},
};
}
驗證選項系統
5. src/commands/onboard-types.ts
在 AuthChoice 型別中新增:
export type AuthChoice =
// ... 既有選項
"kilocode-api-key";
// ...
在 OnboardOptions 中新增:
export type OnboardOptions = {
// ... 既有選項
kilocodeApiKey?: string;
// ...
};
6. src/commands/auth-choice-options.ts
在 AuthChoiceGroupId 中新增:
export type AuthChoiceGroupId =
// ... 既有群組
"kilocode";
// ...
在 AUTH_CHOICE_GROUP_DEFS 中新增:
{
value: "kilocode",
label: "Kilo Gateway",
hint: "API key (OpenRouter-compatible)",
choices: ["kilocode-api-key"],
},
在 buildAuthChoiceOptions() 中新增:
options.push({
value: "kilocode-api-key",
label: "Kilo Gateway API key",
hint: "OpenRouter-compatible gateway",
});
7. src/commands/auth-choice.preferred-provider.ts
新增對應:
const PREFERRED_PROVIDER_BY_AUTH_CHOICE: Partial<Record<AuthChoice, string>> = {
// ... 既有對應
"kilocode-api-key": "kilocode",
};
驗證選項套用
8. src/commands/auth-choice.apply.api-providers.ts
新增匯入:
import {
// ... 既有匯入
applyKilocodeConfig,
applyKilocodeProviderConfig,
KILOCODE_DEFAULT_MODEL_REF,
setKilocodeApiKey,
} from "./onboard-auth.js";
新增 kilocode-api-key 處理:
if (authChoice === "kilocode-api-key") {
const store = ensureAuthProfileStore(params.agentDir, {
allowKeychainPrompt: false,
});
const profileOrder = resolveAuthProfileOrder({
cfg: nextConfig,
store,
provider: "kilocode",
});
const existingProfileId = profileOrder.find((profileId) => Boolean(store.profiles[profileId]));
const existingCred = existingProfileId ? store.profiles[existingProfileId] : undefined;
let profileId = "kilocode:default";
let mode: "api_key" | "oauth" | "token" = "api_key";
let hasCredential = false;
if (existingProfileId && existingCred?.type) {
profileId = existingProfileId;
mode =
existingCred.type === "oauth" ? "oauth" : existingCred.type === "token" ? "token" : "api_key";
hasCredential = true;
}
if (!hasCredential && params.opts?.token && params.opts?.tokenProvider === "kilocode") {
await setKilocodeApiKey(normalizeApiKeyInput(params.opts.token), params.agentDir);
hasCredential = true;
}
if (!hasCredential) {
const envKey = resolveEnvApiKey("kilocode");
if (envKey) {
const useExisting = await params.prompter.confirm({
message: `Use existing KILOCODE_API_KEY (${envKey.source}, ${formatApiKeyPreview(envKey.apiKey)})?`,
initialValue: true,
});
if (useExisting) {
await setKilocodeApiKey(envKey.apiKey, params.agentDir);
hasCredential = true;
}
}
}
if (!hasCredential) {
const key = await params.prompter.text({
message: "Enter Kilo Gateway API key",
validate: validateApiKeyInput,
});
await setKilocodeApiKey(normalizeApiKeyInput(String(key)), params.agentDir);
hasCredential = true;
}
if (hasCredential) {
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId,
provider: "kilocode",
mode,
});
}
{
const applied = await applyDefaultModelChoice({
config: nextConfig,
setDefaultModel: params.setDefaultModel,
defaultModel: KILOCODE_DEFAULT_MODEL_REF,
applyDefaultConfig: applyKilocodeConfig,
applyProviderConfig: applyKilocodeProviderConfig,
noteDefault: KILOCODE_DEFAULT_MODEL_REF,
noteAgentModel,
prompter: params.prompter,
});
nextConfig = applied.config;
agentModelOverride = applied.agentModelOverride ?? agentModelOverride;
}
return { config: nextConfig, agentModelOverride };
}
在函式頂部加入 tokenProvider 對應:
if (params.opts.tokenProvider === "kilocode") {
authChoice = "kilocode-api-key";
}
CLI 註冊
9. src/cli/program/register.onboard.ts
新增 CLI 選項:
.option("--kilocode-api-key <key>", "Kilo Gateway API key")
在 action handler 中新增:
kilocodeApiKey: opts.kilocodeApiKey as string | undefined,
更新 auth-choice 說明文字:
.option(
"--auth-choice <choice>",
"Auth: setup-token|token|chutes|openai-codex|openai-api-key|openrouter-api-key|kilocode-api-key|ai-gateway-api-key|...",
)
非互動式安裝
10. src/commands/onboard-non-interactive/local/auth-choice.ts
新增 kilocode-api-key 處理:
if (authChoice === "kilocode-api-key") {
const resolved = await resolveNonInteractiveApiKey({
provider: "kilocode",
cfg: baseConfig,
flagValue: opts.kilocodeApiKey,
flagName: "--kilocode-api-key",
envVar: "KILOCODE_API_KEY",
});
await setKilocodeApiKey(resolved.apiKey, agentDir);
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: "kilocode:default",
provider: "kilocode",
mode: "api_key",
});
// ... 套用預設模型
}
匯出更新
11. src/commands/onboard-auth.ts
新增匯出:
export {
// ... 既有匯出
applyKilocodeConfig,
applyKilocodeProviderConfig,
KILOCODE_BASE_URL,
} from "./onboard-auth.config-core.js";
export {
// ... 既有匯出
KILOCODE_DEFAULT_MODEL_REF,
setKilocodeApiKey,
} from "./onboard-auth.credentials.js";
特殊處理(選用)
12. src/agents/pi-embedded-runner/cache-ttl.ts
新增 Kilo Gateway 對 Anthropic 模型的支援:
export function isCacheTtlEligibleProvider(provider: string, modelId: string): boolean {
const normalizedProvider = provider.toLowerCase();
const normalizedModelId = modelId.toLowerCase();
if (normalizedProvider === "anthropic") return true;
if (normalizedProvider === "openrouter" && normalizedModelId.startsWith("anthropic/"))
return true;
if (normalizedProvider === "kilocode" && normalizedModelId.startsWith("anthropic/")) return true;
return false;
}
13. src/agents/transcript-policy.ts
新增 Kilo Gateway 處理(與 OpenRouter 類似):
const isKilocodeGemini = provider === "kilocode" && modelId.toLowerCase().includes("gemini");
// 加入 needsNonImageSanitize 判斷
const needsNonImageSanitize =
isGoogle || isAnthropic || isMistral || isOpenRouterGemini || isKilocodeGemini;
設定結構
使用者設定範例
{
"models": {
"mode": "merge",
"providers": {
"kilocode": {
"baseUrl": "https://api.kilo.ai/api/gateway/",
"apiKey": "xxxxx",
"api": "openai-completions",
"models": [
{
"id": "anthropic/claude-opus-4.6",
"name": "Anthropic: Claude Opus 4.6"
},
{ "id": "minimax/minimax-m2.5:free", "name": "Minimax: Minimax M2.5" }
]
}
}
}
}
Auth Profile 結構
{
"profiles": {
"kilocode:default": {
"type": "api_key",
"provider": "kilocode",
"key": "xxxxx"
}
}
}
測試考量
-
單元測試:
- 測試
setKilocodeApiKey()是否正確寫入 profile - 測試
applyKilocodeConfig()是否設定正確預設值 - 測試
resolveEnvApiKey("kilocode")是否回傳正確的環境變數
- 測試
-
整合測試:
- 測試使用
--auth-choice kilocode-api-key的安裝流程 - 測試使用
--kilocode-api-key的非互動式安裝 - 測試
kilocode/前綴的模型選擇
- 測試使用
-
端對端測試:
- 測試透過 Kilo Gateway 的實際 API 呼叫(即時測試)
遷移注意事項
- 現有使用者無需任何遷移
- 新使用者可立即使用
kilocode-api-key驗證選項 - 現有手動設定的
kilocode供應商將繼續正常運作
後續發展
-
模型目錄: 若 Kilo Gateway 提供
/models端點,可新增類似scanOpenRouterModels()的掃描支援 -
OAuth 支援: 若 Kilo Gateway 加入 OAuth,對應擴展驗證系統
-
速率限制: 必要時為 Kilo Gateway 添加專屬的速率限制處理
-
文件: 在
docs/providers/kilocode.md新增設定與使用說明
變更摘要
| 檔案 | 變更類型 | 說明 |
|---|---|---|
src/commands/onboard-auth.credentials.ts | 新增 | KILOCODE_DEFAULT_MODEL_REF、setKilocodeApiKey() |
src/agents/model-auth.ts | 修改 | 在 envMap 中新增 kilocode |
src/config/io.ts | 修改 | 在 shell env keys 中新增 KILOCODE_API_KEY |
src/commands/onboard-auth.config-core.ts | 新增 | applyKilocodeProviderConfig()、applyKilocodeConfig() |
src/commands/onboard-types.ts | 修改 | 在 AuthChoice 中新增 kilocode-api-key,在 options 中新增 kilocodeApiKey |
src/commands/auth-choice-options.ts | 修改 | 新增 kilocode 群組與選項 |
src/commands/auth-choice.preferred-provider.ts | 修改 | 新增 kilocode-api-key 對應 |
src/commands/auth-choice.apply.api-providers.ts | 修改 | 新增 kilocode-api-key 處理 |
src/cli/program/register.onboard.ts | 修改 | 新增 --kilocode-api-key 選項 |
src/commands/onboard-non-interactive/local/auth-choice.ts | 修改 | 新增非互動式處理 |
src/commands/onboard-auth.ts | 修改 | 匯出新函式 |
src/agents/pi-embedded-runner/cache-ttl.ts | 修改 | 新增 kilocode 支援 |
src/agents/transcript-policy.ts | 修改 | 新增 kilocode Gemini 處理 |