Design zur Kilo-Gateway-Provider-Integration

Überblick

Dieses Dokument beschreibt das Design zur Integration von „Kilo Gateway” als vollwertiger Provider in OpenClaw, angelehnt an die bestehende OpenRouter-Implementierung. Kilo Gateway nutzt eine OpenAI-kompatible Completions-API mit einer anderen Basis-URL.

Design-Entscheidungen

1. Provider-Benennung

Empfehlung: kilocode

Begründung:

  • Passt zum Beispiel in der Benutzerkonfiguration (Provider-Schlüssel kilocode)
  • Konsistent mit bestehenden Benennungsmustern (z. B. openrouter, opencode, moonshot)
  • Kurz und einprägsam
  • Vermeidet Verwechslungen mit den generischen Begriffen „kilo” oder „gateway”

Verworfene Alternative: kilo-gateway – abgelehnt, da Namen mit Bindestrich in der Codebasis seltener sind und kilocode kürzer ist.

2. Standard-Modellreferenz

Empfehlung: kilocode/anthropic/claude-opus-4.6

Begründung:

  • Basiert auf dem Konfigurationsbeispiel
  • Claude Opus 4.5 ist ein leistungsfähiges Standardmodell
  • Eine explizite Modellauswahl vermeidet die Abhängigkeit von Auto-Routing

3. Basis-URL-Konfiguration

Empfehlung: Fest kodierter Standard mit Konfigurations-Override

  • Standard-Basis-URL: https://api.kilo.ai/api/gateway/
  • Konfigurierbar: Ja, über models.providers.kilocode.baseUrl

Dies entspricht dem Muster anderer Provider wie Moonshot, Venice und Synthetic.

4. Modell-Scanning

Empfehlung: Zunächst kein dedizierter Modell-Scanning-Endpunkt

Begründung:

  • Kilo Gateway leitet an OpenRouter weiter, Modelle sind daher dynamisch
  • Benutzer können Modelle manuell in ihrer Konfiguration eintragen
  • Sollte Kilo Gateway künftig einen /models-Endpunkt bereitstellen, kann Scanning ergänzt werden

5. Spezialbehandlung

Empfehlung: OpenRouter-Verhalten für Anthropic-Modelle übernehmen

Da Kilo Gateway an OpenRouter weiterleitet, sollte dieselbe Spezialbehandlung gelten:

  • Cache-TTL-Berechtigung für anthropic/*-Modelle
  • Extra-Parameter (cacheControlTtl) für anthropic/*-Modelle
  • Transcript-Policy folgt den OpenRouter-Mustern

Zu ändernde Dateien

Zentrale Credential-Verwaltung

1. src/commands/onboard-auth.credentials.ts

Ergänzen:

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

In resolveEnvApiKey() zur envMap hinzufügen:

const envMap: Record<string, string> = {
  // ... bestehende Einträge
  kilocode: "KILOCODE_API_KEY",
};

3. src/config/io.ts

Zu SHELL_ENV_EXPECTED_KEYS hinzufügen:

const SHELL_ENV_EXPECTED_KEYS = [
  // ... bestehende Einträge
  "KILOCODE_API_KEY",
];

Konfigurations-Anwendung

4. src/commands/onboard-auth.config-core.ts

Neue Funktionen ergänzen:

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,
        },
      },
    },
  };
}

Auth-Choice-System

5. src/commands/onboard-types.ts

Zum AuthChoice-Typ hinzufügen:

export type AuthChoice =
  // ... bestehende Optionen
  "kilocode-api-key";
// ...

Zu OnboardOptions hinzufügen:

export type OnboardOptions = {
  // ... bestehende Optionen
  kilocodeApiKey?: string;
  // ...
};

6. src/commands/auth-choice-options.ts

Zu AuthChoiceGroupId hinzufügen:

export type AuthChoiceGroupId =
  // ... bestehende Gruppen
  "kilocode";
// ...

Zu AUTH_CHOICE_GROUP_DEFS hinzufügen:

{
  value: "kilocode",
  label: "Kilo Gateway",
  hint: "API key (OpenRouter-compatible)",
  choices: ["kilocode-api-key"],
},

Zu buildAuthChoiceOptions() hinzufügen:

options.push({
  value: "kilocode-api-key",
  label: "Kilo Gateway API key",
  hint: "OpenRouter-compatible gateway",
});

7. src/commands/auth-choice.preferred-provider.ts

Mapping ergänzen:

const PREFERRED_PROVIDER_BY_AUTH_CHOICE: Partial<Record<AuthChoice, string>> = {
  // ... bestehende Mappings
  "kilocode-api-key": "kilocode",
};

Auth-Choice-Anwendung

8. src/commands/auth-choice.apply.api-providers.ts

Import ergänzen:

import {
  // ... bestehende Imports
  applyKilocodeConfig,
  applyKilocodeProviderConfig,
  KILOCODE_DEFAULT_MODEL_REF,
  setKilocodeApiKey,
} from "./onboard-auth.js";

Behandlung für kilocode-api-key ergänzen:

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 };
}

Außerdem das tokenProvider-Mapping am Anfang der Funktion ergänzen:

if (params.opts.tokenProvider === "kilocode") {
  authChoice = "kilocode-api-key";
}

CLI-Registrierung

9. src/cli/program/register.onboard.ts

CLI-Option ergänzen:

.option("--kilocode-api-key <key>", "Kilo Gateway API key")

Im Action-Handler ergänzen:

kilocodeApiKey: opts.kilocodeApiKey as string | undefined,

Hilfetext für auth-choice aktualisieren:

.option(
  "--auth-choice <choice>",
  "Auth: setup-token|token|chutes|openai-codex|openai-api-key|openrouter-api-key|kilocode-api-key|ai-gateway-api-key|...",
)

Nicht-interaktives Onboarding

10. src/commands/onboard-non-interactive/local/auth-choice.ts

Behandlung für kilocode-api-key ergänzen:

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",
  });
  // ... Standard-Modell anwenden
}

Export-Updates

11. src/commands/onboard-auth.ts

Exports ergänzen:

export {
  // ... bestehende Exports
  applyKilocodeConfig,
  applyKilocodeProviderConfig,
  KILOCODE_BASE_URL,
} from "./onboard-auth.config-core.js";

export {
  // ... bestehende Exports
  KILOCODE_DEFAULT_MODEL_REF,
  setKilocodeApiKey,
} from "./onboard-auth.credentials.js";

Spezialbehandlung (optional)

12. src/agents/pi-embedded-runner/cache-ttl.ts

Kilo-Gateway-Unterstützung für Anthropic-Modelle ergänzen:

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-Behandlung ergänzen (analog zu OpenRouter):

const isKilocodeGemini = provider === "kilocode" && modelId.toLowerCase().includes("gemini");

// In die needsNonImageSanitize-Prüfung aufnehmen
const needsNonImageSanitize =
  isGoogle || isAnthropic || isMistral || isOpenRouterGemini || isKilocodeGemini;

Konfigurationsstruktur

Benutzerkonfigurations-Beispiel

{
  "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-Profil-Struktur

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

Überlegungen zum Testen

  1. Unit-Tests:

    • Testen, dass setKilocodeApiKey() das korrekte Profil schreibt
    • Testen, dass applyKilocodeConfig() die richtigen Standardwerte setzt
    • Testen, dass resolveEnvApiKey("kilocode") die korrekte Umgebungsvariable liefert
  2. Integrationstests:

    • Onboarding-Flow mit --auth-choice kilocode-api-key testen
    • Nicht-interaktives Onboarding mit --kilocode-api-key testen
    • Modellauswahl mit kilocode/-Präfix testen
  3. E2E-Tests:

    • Tatsächliche API-Aufrufe über Kilo Gateway testen (Live-Tests)

Hinweise zur Migration

  • Keine Migration für bestehende Benutzer erforderlich
  • Neue Benutzer können sofort die Auth-Choice kilocode-api-key verwenden
  • Bestehende manuelle Konfigurationen mit dem Provider kilocode funktionieren weiterhin

Zukünftige Überlegungen

  1. Modellkatalog: Sollte Kilo Gateway einen /models-Endpunkt bereitstellen, Scanning-Unterstützung analog zu scanOpenRouterModels() ergänzen

  2. OAuth-Unterstützung: Sollte Kilo Gateway OAuth ergänzen, das Auth-System entsprechend erweitern

  3. Rate-Limiting: Ggf. eine Kilo-Gateway-spezifische Rate-Limit-Behandlung hinzufügen

  4. Dokumentation: Docs unter docs/providers/kilocode.md mit Setup- und Nutzungsanleitung hinzufügen

Zusammenfassung der Änderungen

DateiÄnderungstypBeschreibung
src/commands/onboard-auth.credentials.tsHinzufügenKILOCODE_DEFAULT_MODEL_REF, setKilocodeApiKey()
src/agents/model-auth.tsÄndernkilocode zur envMap hinzufügen
src/config/io.tsÄndernKILOCODE_API_KEY zu Shell-Env-Keys hinzufügen
src/commands/onboard-auth.config-core.tsHinzufügenapplyKilocodeProviderConfig(), applyKilocodeConfig()
src/commands/onboard-types.tsÄndernkilocode-api-key zu AuthChoice, kilocodeApiKey zu Optionen
src/commands/auth-choice-options.tsÄndernkilocode-Gruppe und -Option hinzufügen
src/commands/auth-choice.preferred-provider.tsÄndernkilocode-api-key-Mapping hinzufügen
src/commands/auth-choice.apply.api-providers.tsÄndernkilocode-api-key-Behandlung hinzufügen
src/cli/program/register.onboard.tsÄndern--kilocode-api-key-Option hinzufügen
src/commands/onboard-non-interactive/local/auth-choice.tsÄndernNicht-interaktive Behandlung hinzufügen
src/commands/onboard-auth.tsÄndernNeue Funktionen exportieren
src/agents/pi-embedded-runner/cache-ttl.tsÄndernKilocode-Unterstützung hinzufügen
src/agents/transcript-policy.tsÄndernKilocode-Gemini-Behandlung hinzufügen