Kilo Gatewayプロバイダー統合設計

概要

OpenClawに「Kilo Gateway」をファーストクラスのプロバイダーとして統合するための設計ドキュメント。既存のOpenRouter実装をモデルとし、Kilo GatewayはOpenAI互換のCompletions APIを異なるベースURLで提供する。

設計上の決定事項

1. プロバイダー名

推奨: kilocode

理由:

  • ユーザー設定例で使用されているプロバイダーキー(kilocode)と一致
  • 既存のプロバイダー命名パターン(openrouteropencodemoonshotなど)と整合
  • 短くて覚えやすい
  • 一般的な「kilo」や「gateway」との混同を回避

検討した代替案: kilo-gateway — ハイフン付きの名前はコードベースでは一般的でなく、kilocodeのほうが簡潔なため不採用。

2. デフォルトモデルリファレンス

推奨: kilocode/anthropic/claude-opus-4.6

理由:

  • ユーザー設定例に基づく
  • Claude Opus 4.5は優れたデフォルトモデル
  • 明示的なモデル選択によりオートルーティングへの依存を回避

3. ベースURL設定

推奨: ハードコードされたデフォルト値と設定オーバーライド

  • デフォルトベースURL: https://api.kilo.ai/api/gateway/
  • 設定変更可能: models.providers.kilocode.baseUrl で変更可能

Moonshot、Venice、Syntheticなど他のプロバイダーと同じパターン。

4. モデルスキャン

推奨: 初期段階では専用のモデルスキャンエンドポイントなし

理由:

  • Kilo GatewayはOpenRouterへのプロキシのため、モデルは動的
  • ユーザーは設定でモデルを手動設定可能
  • 将来Kilo Gatewayが/modelsエンドポイントを公開すれば、スキャン機能を追加可能

5. 特別な処理

推奨: Anthropicモデルに対してOpenRouterの動作を継承

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")

アクションハンドラーに追加:

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

Anthropicモデル向けのKilo Gatewayサポートを追加:

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" }
        ]
      }
    }
  }
}

認証プロファイル構造

{
  "profiles": {
    "kilocode:default": {
      "type": "api_key",
      "provider": "kilocode",
      "key": "xxxxx"
    }
  }
}

テストに関する考慮事項

  1. ユニットテスト:

    • setKilocodeApiKey()が正しいプロファイルを書き込むことを検証
    • applyKilocodeConfig()が正しいデフォルトを設定することを検証
    • resolveEnvApiKey("kilocode")が正しい環境変数を返すことを検証
  2. インテグレーションテスト:

    • --auth-choice kilocode-api-keyでのオンボーディングフローをテスト
    • --kilocode-api-keyでの非対話型オンボーディングをテスト
    • kilocode/プレフィックスでのモデル選択をテスト
  3. E2Eテスト:

    • Kilo Gateway経由の実際のAPI呼び出しをテスト(ライブテスト)

移行に関する注意点

  • 既存ユーザーへの移行作業は不要
  • 新規ユーザーは即座にkilocode-api-key認証を使用可能
  • 既存のkilocodeプロバイダー手動設定は引き続き動作

今後の検討事項

  1. モデルカタログ: Kilo Gatewayが/modelsエンドポイントを公開した場合、scanOpenRouterModels()と同様のスキャン機能を追加
  2. OAuth対応: Kilo GatewayがOAuthを追加した場合、認証システムを拡張
  3. レート制限: 必要に応じてKilo Gateway固有のレート制限処理を追加
  4. ドキュメント: docs/providers/kilocode.mdにセットアップと使用方法のドキュメントを追加

変更一覧

ファイル変更種別説明
src/commands/onboard-auth.credentials.ts追加KILOCODE_DEFAULT_MODEL_REFsetKilocodeApiKey()
src/agents/model-auth.ts変更envMapkilocodeを追加
src/config/io.ts変更シェル環境キーにKILOCODE_API_KEYを追加
src/commands/onboard-auth.config-core.ts追加applyKilocodeProviderConfig()applyKilocodeConfig()
src/commands/onboard-types.ts変更AuthChoicekilocode-api-key、オプションに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処理を追加