feat(kimi): Kimi K3 provider on the official kimi-code CLI (#713)

* feat(kimi): Kimi K3 provider on the official kimi-code CLI (Wave 1)

ModelProvider.KIMI routes through KimiCliProvider driving Moonshot's kimi
CLI on a Kimi subscription (OAuth device-code, no metered key). One-shot
delivery roles only (V1), interactive ban wired in both guard lists.

Auth: one shared RW auth mount; containers symlink credentials/ and
oauth/ (the CLI's cross-process refresh-lock dir) into a container-local
KIMI_CODE_HOME so every container and the host redeem the SAME rotating
refresh chain - live-verified that per-copy chains cross-invalidate after
the reuse-grace window. No orchestrator refresh daemon; an expires_at
preflight exits 78.

Config renderer mirrors the login-managed provider/model blocks
field-for-field (live-captured; the model value is the CLI-side name,
never the raw API id), plus per-role deny rules and the bash-guard as a
PreToolUse hook via a wrapper script (an env key on a hooks entry makes
the CLI silently drop ALL hooks - live-verified). Usage capture sums
wire.jsonl usage.record 4-bucket events; sniff classifies rate-limit/auth
from structured error text only, mapped to the shared 75/78 park
contract. Image installs the CLI latest-at-build (no version pin, by
policy) with the resolved version stamped as provenance, binary split to
/usr/local away from mutable state.

Migrations 090 (enum) + 091 (provider seed); catalog, pricing, routing
mode, and orchestrator park/usage wiring mirror the codex integration.

* feat(kimi): surface sweep + fleet-wide pin drop (Wave 2)

Compose x3 gain the agent-kimi-image service and the orchestrator's
read-write ~/.kimi-code mount + kimi-usage dir; .env.example documents
the Kimi block. Panel mirrors ModelProvider.KIMI and adds the kimi
routing mode (catalog filter, mode button, mix-picker group, badge) with
tests; provider routes gain the kimi remediation entry. CLAUDE.md and
docs/map document the runtime. Per the no-pins policy, agent-grok/
gemini/codex Dockerfiles drop their version pins for latest-at-build
with resolved-version provenance stamps (grok resolves 0.2.112 vs the
old 0.2.56 pin - verified by real builds of all four images).

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
Renzo F
2026-07-29 01:48:55 +02:00
committed by GitHub
co-authored by Renn F
parent eb470dfb33
commit 6374bbbed0
43 changed files with 3907 additions and 110 deletions
+129 -3
View File
@@ -67,7 +67,15 @@ async def llm_setup(
type=ModelProvider.GEMINI,
enabled=True,
)
db_session.add_all([anthropic, grok, ollama, openai, gemini])
# Mirrors migration 091_seed_kimi_provider's contract: enabled=True at
# seed time (Codex's shape, not Gemini's disabled-then-flipped one) — no
# base_url, subscription auth only.
kimi = ProviderConfigTable(
name="kimi-test",
type=ModelProvider.KIMI,
enabled=True,
)
db_session.add_all([anthropic, grok, ollama, openai, gemini, kimi])
await db_session.flush()
yield {"svc": ModelRoutingService(db_session)}
@@ -235,6 +243,18 @@ async def test_derive_mode_gemini_when_only_gemini_global(llm_setup: dict) -> No
assert await svc.derive_mode() == "gemini"
@pytest.mark.asyncio
async def test_derive_mode_kimi_when_only_kimi_global(llm_setup: dict) -> None:
"""A pure-KIMI global assignment reports "kimi", not the catch-all
"mix" — mirrors the codex/gemini branches derive_mode already carries."""
svc = llm_setup["svc"]
kimi_model = _first_model_for_type(ModelProvider.KIMI)
await svc.upsert_assignment(
scope=AssignmentScope.GLOBAL, scope_value=None, model_name=kimi_model
)
assert await svc.derive_mode() == "kimi"
@pytest.mark.asyncio
async def test_derive_mode_mix_with_per_agent(llm_setup: dict) -> None:
svc = llm_setup["svc"]
@@ -419,6 +439,40 @@ async def test_apply_mode_gemini_enables_gemini_provider(llm_setup: dict) -> Non
assert refetched.enabled is True
@pytest.mark.asyncio
async def test_apply_mode_kimi_sets_global(llm_setup: dict) -> None:
svc = llm_setup["svc"]
await svc.apply_mode(mode="kimi")
assignments = await svc.list_assignments()
assert len(assignments) == 1
assert assignments[0].scope == AssignmentScope.GLOBAL
assert assignments[0].provider.type == ModelProvider.KIMI
assert assignments[0].model_name == "kimi-code/k3"
@pytest.mark.asyncio
async def test_apply_mode_kimi_enables_kimi_provider(llm_setup: dict) -> None:
"""apply_mode('kimi') force-enables the KIMI row — belt-and-suspenders
against a row disabled by some other path, mirroring the codex/gemini tests."""
svc = llm_setup["svc"]
provider_svc = ProviderService(svc.session)
kimi = next(
p
for p in await provider_svc.list_providers(include_disabled=True)
if p.type == ModelProvider.KIMI
)
await provider_svc.update_provider(
cast("UUID", kimi.id), ProviderUpdate(enabled=False)
)
await svc.session.flush()
await svc.apply_mode(mode="kimi")
refetched = await provider_svc.get_provider(cast("UUID", kimi.id))
assert refetched is not None
assert refetched.enabled is True
@pytest.mark.asyncio
async def test_apply_mode_mix_requires_per_agent(llm_setup: dict) -> None:
svc = llm_setup["svc"]
@@ -604,6 +658,78 @@ async def test_upsert_assignment_enables_disabled_gemini_provider(
assert route.provider_type == ModelProvider.GEMINI
@pytest.mark.asyncio
async def test_upsert_and_resolve_kimi_assignment_roundtrip(
llm_setup: dict,
) -> None:
"""kimi-code/k3 through upsert_assignment -> resolve_for_agent, against
the seeded KIMI row (migration 091). Proves resolve_for_agent actually
returns a KIMI spawn route — not a silent Anthropic fallback."""
svc = llm_setup["svc"]
kimi_model = _first_model_for_type(ModelProvider.KIMI)
row = await svc.upsert_assignment(
scope=AssignmentScope.AGENT_SLUG,
scope_value="be-dev-1",
model_name=kimi_model,
)
assert row.model_name == kimi_model
route = await svc.resolve_for_agent("be-dev-1")
assert route.provider_type == ModelProvider.KIMI
assert route.model_name == kimi_model
# The seeded row carries no stored token — Kimi authenticates via the
# shared, symlinked-in ~/.kimi-code subscription credential, not a
# decrypted token.
assert route.auth_token is None
@pytest.mark.asyncio
async def test_upsert_assignment_enables_disabled_kimi_provider(
llm_setup: dict,
) -> None:
"""Belt-and-suspenders: assigning a Kimi model via Mix (upsert_assignment)
force-enables the row even if it was disabled — not just apply_mode('kimi')."""
svc = llm_setup["svc"]
provider_svc = ProviderService(svc.session)
kimi = next(
p
for p in await provider_svc.list_providers(include_disabled=True)
if p.type == ModelProvider.KIMI
)
await provider_svc.update_provider(
cast("UUID", kimi.id), ProviderUpdate(enabled=False)
)
await svc.session.flush()
kimi_model = _first_model_for_type(ModelProvider.KIMI)
await svc.upsert_assignment(
scope=AssignmentScope.AGENT_SLUG,
scope_value="be-dev-1",
model_name=kimi_model,
)
refetched = await provider_svc.get_provider(cast("UUID", kimi.id))
assert refetched is not None
assert refetched.enabled is True
# And the route actually resolves to KIMI now that it's enabled.
route = await svc.resolve_for_agent("be-dev-1")
assert route.provider_type == ModelProvider.KIMI
@pytest.mark.asyncio
async def test_apply_mode_kimi_end_to_end_reachable(llm_setup: dict) -> None:
"""The full reachability chain: apply_mode -> derive_mode reflects it ->
resolve_for_agent actually spawns Kimi, mirroring the Codex/Gemini tests."""
svc = llm_setup["svc"]
await svc.apply_mode(mode="kimi")
assert await svc.derive_mode() == "kimi"
route = await svc.resolve_for_agent("be-dev-1")
assert route.provider_type == ModelProvider.KIMI
assert route.model_name == "kimi-code/k3"
@pytest.mark.asyncio
async def test_apply_mode_gemini_end_to_end_reachable(llm_setup: dict) -> None:
"""The full reachability chain the original drill missed: apply_mode
@@ -632,12 +758,12 @@ async def test_apply_mode_codex_end_to_end_reachable(llm_setup: dict) -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("mode", ["codex", "gemini"])
@pytest.mark.parametrize("mode", ["codex", "gemini", "kimi"])
@pytest.mark.parametrize("interactive_slug", ["intake-1", "secretary-1"])
async def test_interactive_agents_exempt_from_delivery_only_global_mode(
llm_setup: dict, mode: str, interactive_slug: str
) -> None:
"""A fleet-wide Codex/Gemini mode must not capture Intake/Secretary —
"""A fleet-wide Codex/Gemini/Kimi mode must not capture Intake/Secretary —
they have no V1 support on those providers, so the resolver keeps them
on the legacy Anthropic path (the completeness-drill gap: previously
they resolved to the unsupported provider and the spawn guard left both
@@ -0,0 +1,162 @@
"""Migration 091 tests — seed_kimi_provider.
Verifies the post-upgrade state and exercises the downgrade SQL ordering,
mirroring ``test_migration_083_seed_openai_provider.py``'s own shape (Kimi's
row is seeded ``enabled=true`` directly, the same posture as Codex's — there
is no ``apply_mode="kimi"``-only gate it needs to wait behind, unlike GROK's
disabled-until-key-set seed).
NOT a real alembic round-trip — the suite builds the test DB via
Base.metadata.create_all (see conftest). Migration 091's upgrade()/downgrade()
bodies are reviewed here; the tests guard the resulting DB-level contract —
in particular ``enabled=True`` at seed time and NULL base_url/auth_token
(subscription auth, no stored secret).
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from uuid import uuid4
import pytest
from roboco.db.tables import ModelAssignmentTable, ProviderConfigTable
from roboco.models.base import AssignmentScope, ModelProvider
from sqlalchemy import text
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
_INSERT_SQL = text(
"""
INSERT INTO provider_configs
(id, name, type, base_url, auth_token_encrypted, enabled, created_at)
VALUES
(
gen_random_uuid(),
'Kimi (Moonshot)',
'kimi',
NULL,
NULL,
true,
now()
)
ON CONFLICT (name) DO NOTHING
"""
)
@pytest.mark.asyncio
async def test_migration_091_upgrade_insert_contract(
db_session: AsyncSession,
) -> None:
"""The upgrade INSERT SQL seeds the Kimi row ENABLED with no stored
secret (subscription auth), and is idempotent."""
# --- First run: the row should be inserted.
await db_session.execute(_INSERT_SQL)
await db_session.flush()
result = await db_session.execute(
text(
"SELECT name, type, enabled, base_url, auth_token_encrypted "
"FROM provider_configs "
"WHERE name = 'Kimi (Moonshot)'"
)
)
rows = list(result)
assert len(rows) == 1
name, ptype, enabled, base_url, auth_token = rows[0]
assert name == "Kimi (Moonshot)"
assert ptype == "kimi"
# The load-bearing assertion: enabled=True at seed time (parity with
# Codex — there's no key-collection step gating this row).
assert enabled is True
assert base_url is None
assert auth_token is None
# --- Second run: ON CONFLICT DO NOTHING must not create a duplicate.
await db_session.execute(_INSERT_SQL)
await db_session.flush()
result = await db_session.execute(
text("SELECT id FROM provider_configs WHERE name = 'Kimi (Moonshot)'")
)
assert len(list(result)) == 1, (
"Expected exactly one 'Kimi (Moonshot)' row after two INSERT "
"executions; ON CONFLICT DO NOTHING must prevent duplicates."
)
@pytest.mark.asyncio
async def test_migration_091_downgrade_deletes_assignments_before_config(
db_session: AsyncSession,
) -> None:
"""Downgrade SQL deletes model_assignments before provider_configs.
A FK RESTRICT constraint on model_assignments.provider_config_id means
deleting provider_configs first would raise an IntegrityError.
"""
suffix = uuid4().hex[:8]
kimi = ProviderConfigTable(
name=f"Kimi (Moonshot)-test-{suffix}",
type=ModelProvider.KIMI,
enabled=True,
)
db_session.add(kimi)
await db_session.flush()
assignment = ModelAssignmentTable(
scope=AssignmentScope.AGENT_SLUG,
scope_value=f"test-agent-{suffix}",
provider_config_id=kimi.id,
model_name="kimi-code/k3",
)
db_session.add(assignment)
await db_session.flush()
result = await db_session.execute(
text("SELECT id FROM provider_configs WHERE name = :name").bindparams(
name=kimi.name
)
)
assert result.scalar_one_or_none() is not None
result = await db_session.execute(
text("SELECT id FROM model_assignments WHERE scope_value = :sv").bindparams(
sv=assignment.scope_value
)
)
assert result.scalar_one_or_none() is not None
# Step 1: delete referencing model_assignments first.
await db_session.execute(
text(
"DELETE FROM model_assignments "
"WHERE provider_config_id IN ("
" SELECT id FROM provider_configs WHERE name = :name"
")"
).bindparams(name=kimi.name)
)
# Step 2: now safe to delete the provider row.
await db_session.execute(
text("DELETE FROM provider_configs WHERE name = :name").bindparams(
name=kimi.name
)
)
result = await db_session.execute(
text("SELECT id FROM provider_configs WHERE name = :name").bindparams(
name=kimi.name
)
)
assert result.scalar_one_or_none() is None, (
"provider_configs row should be deleted by downgrade"
)
result = await db_session.execute(
text("SELECT id FROM model_assignments WHERE scope_value = :sv").bindparams(
sv=assignment.scope_value
)
)
assert result.scalar_one_or_none() is None, (
"model_assignments row should be deleted before provider_configs"
)