graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(kimi): follow live catalog protocol
Rach Pradhana126b6cdd113
diff --git a/README.md b/README.mdindex 4ad8418d..e5ad996b 100644--- a/README.md+++ b/README.md@@ -131,6 +131,7 @@ Three ways, pick whichever is easiest:```shgraff login # free codegraff key (device-code OAuth, no signup forms)+graff login kimi # Kimi Code subscription OAuth (device-code)graff key set deepseek sk-... # store ANY provider's key (macOS Keychain, else 0600 file)export DEEPSEEK_API_KEY=sk-... # or just an env var (env always wins)```@@ -139,10 +140,10 @@ Already logged into the Codex CLI? Skip this step. Your ChatGPT subscription ispicked up automatically from `${CODEX_HOME:-~/.codex}/auth.json`. Or run`graff login codex`.-> **Note on `login`:** there is no per-provider `login` command. `graff login`-> is *specifically* the free codegraff key, and `graff login codex` is the-> ChatGPT-subscription OAuth. **Every other provider** (deepseek, openai,-> anthropic, kimi, xai, zai, minimax, xiaomi) is a key: set it with+> **Note on `login`:** `graff login` is the free codegraff key, `graff login+> codex` is the ChatGPT-subscription OAuth, and `graff login kimi` is Kimi+> Code's device-code OAuth. **Every other provider** (deepseek, openai,+> anthropic, xai, zai, minimax, xiaomi) is a key: set it with> `graff key set <provider> <key>` or its `<PROVIDER>_API_KEY` env var, then> select a model with `--model` / `/model`. See [Providers & models](#providers--models).@@ -267,7 +268,7 @@ the directory, so concurrent processes never share a truncate/append cursor:## Providers & models-Six API-key providers plus a subscription login, three wire formats. A+Direct API-key and OAuth providers across three wire formats. A`ProviderSpec` table (`provider_specs` in `src/main.zig`) holds each provider'sendpoint, auth style, env var, and default model; base URLs and key names comefrom [models.dev](https://models.dev)'s `api.json` (snapshot 2026-06-10).@@ -280,7 +281,8 @@ from [models.dev](https://models.dev)'s `api.json` (snapshot 2026-06-10).| `openai` | OpenAI chat, bearer | `OPENAI_API_KEY` || `minimax` | Anthropic Messages, bearer | `MINIMAX_API_KEY` || `xiaomi` (MiMo) | OpenAI chat, bearer | `XIAOMI_API_KEY` |-| `kimi` / `xai` (grok) / `zai` (GLM) | Kimi: Anthropic Messages; xAI/ZAI: OpenAI chat | `KIMI_API_KEY` / `XAI_API_KEY` / `ZAI_API_KEY` (via `graff key set`) |+| `kimi` | Live catalog-selected: native Kimi chat + bearer, or Anthropic beta Messages + x-api-key when declared | `graff login kimi` or `KIMI_API_KEY` |+| `xai` (grok) / `zai` (GLM) | OpenAI chat, bearer | `XAI_API_KEY` / `ZAI_API_KEY` (via `graff key set`) || `codex` | Responses API, ChatGPT login | `${CODEX_HOME:-~/.codex}/auth.json` (no API key) |**Using a specific provider directly** is always the same two steps: give it@@ -859,9 +861,13 @@ codegraff.com/cli/auth → poll → key, saved to `~/.simple-harness-codegraff.jthe codegraff key is also auto-picked-up from graff's own`~/forge/.credentials.json` if present, so no env var is needed. `graff logincodex` runs the Codex/ChatGPT OAuth browser flow (PKCE → localhost callback →-token) and `graff login codex --refresh` refreshes it. Those built-in login-flows write `~/.codex/auth.json`; set `CODEX_HOME` when reusing credentials from-a custom Codex CLI home.+token) and `graff login codex --refresh` refreshes it. `graff login kimi` runs+Kimi Code's device flow and stores its refreshable credential separately under+`~/.kimi/credentials/`. Kimi models, context sizes, thinking efforts, and+native-vs-Anthropic wire protocol are refreshed from the authenticated catalog+at startup; `--model kimi` follows the newest pure Kimi generation. Codex auth+lives in `~/.codex/auth.json`; set `CODEX_HOME` when reusing credentials from a+custom Codex CLI home.**SDKs.** `graff --json` exposes a structured stdio protocol (JSON requests in,JSONL events out) and `graff --schema` prints the machine-readable interface.diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex aec0a461..65a51d5c 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -8,7 +8,7 @@ import { homedir } from "node:os";import { join } from "node:path";import { createInterface } from "node:readline";-export const HARNESS_VERSION = "0.5";+export const HARNESS_VERSION = "0.6";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow";diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex e39dceb3..ad972922 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -7,7 +7,7 @@// `harness --json` child over there, and one POST = one protocol request,// streamed back as NDJSON until that request's terminal event.-export const HARNESS_VERSION = "0.5";+export const HARNESS_VERSION = "0.6";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow";diff --git a/src/agent_request_body.zig b/src/agent_request_body.zigindex a5cf38c3..0d4a2ec2 100644--- a/src/agent_request_body.zig+++ b/src/agent_request_body.zig@@ -8,7 +8,10 @@ const main_mod = @import("main.zig");const max_tokens = main_mod.max_tokens;const Agent = @import("agent.zig").Agent;const serde = @import("serde.zig");+const pricing = @import("pricing.zig");const writeAnthropicMessages = serde.writeAnthropicMessages;+const writeAnthropicTools = serde.writeAnthropicTools;+const writeKimiTools = serde.writeKimiTools;const writeOpenAIMessageNormalized = serde.writeOpenAIMessageNormalized;pub fn responsesOutputLimit(self: *const Agent) u32 {@@ -25,26 +28,43 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.write(self.provider.model);switch (self.provider.kind) {.anthropic => {+ const is_kimi = std.mem.eql(u8, self.provider.id, "kimi");try s.objectField("max_tokens");try s.write(max_tokens);if (stream) {try s.objectField("stream");try s.write(true);}- // Forced tool_choice conflicts with adaptive thinking; skip- // thinking only when forcing.+ // Kimi's catalog-declared Anthropic transport uses enabled+ // thinking plus output_config.effort; Claude uses adaptive.+ // Forced tool_choice conflicts with thinking, so skip it then.if (!force_tool) {- try s.objectField("thinking");- try s.print("{s}", .{"{\"type\":\"adaptive\"}"});+ if (is_kimi) {+ if (pricing.kimiSupportsThinking(self.provider.model)) {+ try s.objectField("thinking");+ try s.print("{s}", .{"{\"type\":\"enabled\"}"});+ if (pricing.kimiThinkingEffort(self.provider.model, @tagName(self.reasoning))) |effort| {+ try s.objectField("output_config");+ try s.beginObject();+ try s.objectField("effort");+ try s.write(effort);+ try s.endObject();+ }+ }+ } else {+ try s.objectField("thinking");+ try s.print("{s}", .{"{\"type\":\"adaptive\"}"});+ }}// Prompt caching (Anthropic): a cache_control breakpoint on the// system block caches the whole stable prefix (system + tools).// Must be block-level — a top-level cache_control is invalid.- // Other anthropic-format providers (minimax) get a plain- // string, since cache_control isn't part of their API.+ // Other anthropic-format providers (minimax) get a plain string,+ // since cache_control isn't part of their API. Kimi's official+ // Anthropic adapter uses the same cached text-block shape.try s.objectField("system");const cc = "{\"type\":\"ephemeral\"}";- if (std.mem.eql(u8, self.provider.id, "anthropic")) {+ if (std.mem.eql(u8, self.provider.id, "anthropic") or is_kimi) {try s.beginArray();try s.beginObject();try s.objectField("type");@@ -60,7 +80,7 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo}if (tools) |t| {try s.objectField("tools");- try s.print("{s}", .{t});+ try writeAnthropicTools(&s, self.scratchAlloc(), t, is_kimi);if (force_tool) {try s.objectField("tool_choice");try s.print("{s}", .{"{\"type\":\"any\"}"});@@ -68,17 +88,18 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo}try s.objectField("messages");// Cache the conversation prefix too (not just system) on the real- // Anthropic API: a rolling cache_control breakpoint on the last- // message. minimax (anthropic-format, no cache_control) is excluded.- const cache_msgs = std.mem.eql(u8, self.provider.id, "anthropic");- try writeAnthropicMessages(&s, self.messages, cache_msgs);+ // Anthropic API and Kimi's declared Anthropic transport. Kimi also+ // normalizes all string content into Anthropic text blocks.+ const cache_msgs = std.mem.eql(u8, self.provider.id, "anthropic") or is_kimi;+ try writeAnthropicMessages(&s, self.messages, cache_msgs, is_kimi);},.openai => {// graff's MakeOpenAiCompat: OpenAI deprecated max_tokens in// favor of max_completion_tokens — send the new name to the// direct OpenAI API, and to any provider that rejected the// old one (cap_new, learned via the retry in request()).- const cap_field = if (std.mem.eql(u8, self.provider.id, "openai") or self.cap_new)+ const is_kimi = std.mem.eql(u8, self.provider.id, "kimi");+ const cap_field = if (std.mem.eql(u8, self.provider.id, "openai") or is_kimi or self.cap_new)"max_completion_tokens"else"max_tokens";@@ -96,7 +117,10 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo}if (tools) |t| {try s.objectField("tools");- try s.print("{s}", .{t});+ if (is_kimi)+ try writeKimiTools(&s, self.scratchAlloc(), t)+ else+ try s.print("{s}", .{t});if (force_tool) {try s.objectField("tool_choice");try s.write("required");@@ -112,10 +136,24 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.endObject();for (self.messages.items) |m| try writeOpenAIMessageNormalized(&s, m);try s.endArray();+ // The live Kimi catalog declares thinking support and allowed+ // efforts per model. Native Kimi places this proprietary object at+ // the top level (not `reasoning_effort`).+ if (is_kimi and pricing.kimiSupportsThinking(self.provider.model)) {+ try s.objectField("thinking");+ try s.beginObject();+ try s.objectField("type");+ try s.write("enabled");+ if (pricing.kimiThinkingEffort(self.provider.model, @tagName(self.reasoning))) |effort| {+ try s.objectField("effort");+ try s.write(effort);+ }+ try s.endObject();+ }// Reasoning-effort hint for OpenAI-compatible providers that// honor it (codegraff gateway, deepseek). Mirrors the// Responses `reasoning.effort` set in the branch below.- if (self.effortApplies() and !self.effort_rejected) {+ if (!is_kimi and self.effortApplies() and !self.effort_rejected) {try s.objectField("reasoning_effort");try s.write(if (self.reasoning == .ultra) "max" else @tagName(self.reasoning));}@@ -183,3 +221,56 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: bootry s.endObject();return aw.toOwnedSlice();}++test "Kimi request body follows live native or Anthropic protocol metadata" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const saved = pricing.active_model_table;+ defer pricing.active_model_table = saved;+ const rows = [_]pricing.ModelInfo{+ .{ .provider = "kimi", .name = "native-k3", .context = 1_048_576, .protocol = .kimi, .supports_reasoning = true, .support_efforts = &.{"max"}, .default_effort = "max" },+ .{ .provider = "kimi", .name = "anthropic-k3", .context = 1_048_576, .protocol = .anthropic, .supports_reasoning = true, .support_efforts = &.{"max"}, .default_effort = "max" },+ };+ try std.testing.expect(pricing.activateKimiModels(arena, &rows));++ var messages = std.json.Array.init(arena);+ var user: std.json.ObjectMap = .empty;+ try user.put(arena, "role", .{ .string = "user" });+ try user.put(arena, "content", .{ .string = "hello" });+ try messages.append(.{ .object = user });+ var agent: Agent = .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = undefined,+ .client = undefined,+ .provider = .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = "", .api_key = "k", .model = "native-k3", .context = 1_048_576 },+ .messages = messages,+ .sub = false,+ .label = "",+ .out = null,+ .sys_normal = "system",+ };+ const openai_tools = "[{\"type\":\"function\",\"function\":{\"name\":\"ping\",\"description\":\"\",\"parameters\":{\"type\":\"object\",\"properties\":{\"target\":{\"type\":\"string\",\"anyOf\":[{\"const\":\"one\"},{\"const\":\"two\"}]},\"other\":{\"type\":\"string\"}},\"anyOf\":[{\"required\":[\"target\"]},{\"required\":[\"other\"]}]}}}]";+ const native = try agent.buildBody(openai_tools, false, true, true);+ defer std.testing.allocator.free(native);+ try std.testing.expect(std.mem.indexOf(u8, native, "\"max_completion_tokens\":16000") != null);+ try std.testing.expect(std.mem.indexOf(u8, native, "\"thinking\":{\"type\":\"enabled\",\"effort\":\"max\"}") != null);+ try std.testing.expect(std.mem.indexOf(u8, native, "\"role\":\"system\",\"content\":\"system\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, native, "\"reasoning_effort\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, native, "\"target\":{\"anyOf\":[{\"const\":\"one\",\"type\":\"string\"},{\"const\":\"two\",\"type\":\"string\"}]}") != null);+ try std.testing.expect(std.mem.indexOf(u8, native, "\"oneOf\":[{\"required\":[\"target\"],\"type\":\"object\"},{\"required\":[\"other\"],\"type\":\"object\"}]") != null);++ agent.provider.kind = .anthropic;+ agent.provider.auth = .x_api_key;+ agent.provider.model = "anthropic-k3";+ const anthropic_tools = "[{\"name\":\"ping\",\"description\":\"\",\"input_schema\":{\"type\":\"object\"}}]";+ const anthropic = try agent.buildBody(anthropic_tools, false, true, true);+ defer std.testing.allocator.free(anthropic);+ try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"thinking\":{\"type\":\"enabled\"}") != null);+ try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"output_config\":{\"effort\":\"max\"}") != null);+ try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"type\":\"adaptive\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"system\":[{\"type\":\"text\",\"text\":\"system\",\"cache_control\":{\"type\":\"ephemeral\"}}]") != null);+ try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"content\":[{\"type\":\"text\",\"text\":\"hello\",\"cache_control\":{\"type\":\"ephemeral\"}}]") != null);+ try std.testing.expect(std.mem.indexOf(u8, anthropic, "\"input_schema\":{\"type\":\"object\"},\"cache_control\":{\"type\":\"ephemeral\"}") != null);+}diff --git a/src/agent_stream.zig b/src/agent_stream.zigindex 6c31e296..a2a3522b 100644--- a/src/agent_stream.zig+++ b/src/agent_stream.zig@@ -194,7 +194,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons.bearer => try std.fmt.allocPrint(gpa, "Bearer {s}", .{provider.api_key}),};defer if (bearer.len > 0) gpa.free(bearer);- var headers_buf: [6]std.http.Header = undefined;+ var headers_buf: [12]std.http.Header = undefined;const extra = providerHeaders(provider, bearer, &headers_buf);self.md_buf.clearRetainingCapacity(); // fresh markdown state per streamdiff --git a/src/cli.zig b/src/cli.zigindex ae155d0b..1eb61247 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -21,8 +21,9 @@ const harness_version = root.harness_version;pub const changelog_text =\\What's new\\──────────- \\0.0.208- \\ • Kimi Code now uses its Anthropic Messages transport and authenticated live model catalog+ \\0.0.209+ \\ • Kimi Code now follows each live catalog model's native or Anthropic beta protocol, auth style, context, and thinking metadata+ \\ • Native Kimi tool schemas are normalized to Moonshot's stricter validator; OAuth requests carry the current Kimi Code identity headers\\ • `--model kimi` selects K3 today and automatically follows future pure Kimi generations\\\\0.0.206diff --git a/src/http.zig b/src/http.zigindex c6fc196c..d39fff55 100644--- a/src/http.zig+++ b/src/http.zig@@ -16,6 +16,7 @@ const Provider = provider_mod.Provider;const Agent = agent_mod.Agent;const anthropic_version = root.anthropic_version;const kimi_user_agent = root.kimi_user_agent;+const kimi_catalog = @import("kimi_catalog.zig");/// Launch-scoped gate installed while the shared client's CA bundle warms in/// the background. Null in unit tests and standalone pre-client subcommands.@@ -31,7 +32,7 @@ pub fn providerUserAgent(provider: Provider) std.http.Client.Request.Headers.Val}return .default;}-pub fn providerHeaders(provider: Provider, bearer: []const u8, buf: *[6]std.http.Header) []const std.http.Header {+pub fn providerHeaders(provider: Provider, bearer: []const u8, buf: *[12]std.http.Header) []const std.http.Header {var n: usize = 0;switch (provider.auth) {.x_api_key => {@@ -49,6 +50,10 @@ pub fn providerHeaders(provider: Provider, bearer: []const u8, buf: *[6]std.httpbuf[n] = .{ .name = "anthropic-version", .value = anthropic_version };n += 1;}+ if (std.mem.eql(u8, provider.id, "kimi")) {+ const identity = kimi_catalog.identityHeaders(buf[n..]);+ n += identity.len;+ }// Codex / ChatGPT backend: identify as the codex client and carry the// ChatGPT account id + Responses beta opt-in.if (provider.kind == .responses) {@@ -166,7 +171,7 @@ fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []co};defer if (bearer.len > 0) gpa.free(bearer);- var headers_buf: [6]std.http.Header = undefined;+ var headers_buf: [12]std.http.Header = undefined;const extra = providerHeaders(provider, bearer, &headers_buf);var req = try client.request(.POST, try std.Uri.parse(provider.url), .{diff --git a/src/kimi_catalog.zig b/src/kimi_catalog.zigindex e2569273..8e5b2c04 100644--- a/src/kimi_catalog.zig+++ b/src/kimi_catalog.zig@@ -3,6 +3,7 @@//! baking each K2/K3 rollout into the OAuth client.const std = @import("std");+const builtin = @import("builtin");const Io = std.Io;const Allocator = std.mem.Allocator;const Value = std.json.Value;@@ -11,9 +12,89 @@ const pricing = @import("pricing.zig");const util = @import("util.zig");pub const models_url = "https://api.kimi.com/coding/v1/models";-pub const user_agent = "claude-code/1.0.0";+pub const user_agent = "graff/" ++ @import("build_options").version;+pub const platform = "kimi_code_cli";+pub const version = @import("build_options").version;+pub const device_model = @tagName(builtin.os.tag) ++ " " ++ @tagName(builtin.cpu.arch);+pub const os_version = @tagName(builtin.os.tag);+pub var device_id: []const u8 = "unknown";pub var catalog_source: []const u8 = "baked offline fallback";+const private_file_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o600) else .default_file;+const private_dir_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o700) else .default_dir;++fn secureDir(io: Io, path: []const u8) void {+ const dir = Io.Dir.cwd().openDir(io, path, .{}) catch return;+ defer dir.close(io);+ dir.setPermissions(io, private_dir_permissions) catch {};+}++fn validDeviceId(value: []const u8) bool {+ if (value.len != 36) return false;+ for (value, 0..) |c, i| {+ if (i == 8 or i == 13 or i == 18 or i == 23) {+ if (c != '-') return false;+ } else if (!std.ascii.isHex(c)) return false;+ }+ return true;+}++/// Kimi Code sends a stable random device id with its X-Msh identity headers.+/// Graff owns a separate ~/.kimi/device_id so it never mutates another CLI's+/// credential store or impersonates that installation.+pub fn initIdentity(io: Io, arena: Allocator, home: []const u8) void {+ if (!std.mem.eql(u8, device_id, "unknown") or home.len == 0) return;+ const dir = std.fmt.allocPrint(arena, "{s}/.kimi", .{home}) catch return;+ const path = std.fmt.allocPrint(arena, "{s}/device_id", .{dir}) catch return;+ if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(128))) |raw| {+ const value = std.mem.trim(u8, raw, " \t\r\n");+ if (validDeviceId(value)) {+ device_id = arena.dupe(u8, value) catch "unknown";+ secureDir(io, dir);+ const file = Io.Dir.cwd().openFile(io, path, .{ .mode = .read_only }) catch return;+ defer file.close(io);+ file.setPermissions(io, private_file_permissions) catch {};+ return;+ }+ } else |_| {}+ var random: [16]u8 = undefined;+ io.random(&random);+ random[6] = (random[6] & 0x0f) | 0x40;+ random[8] = (random[8] & 0x3f) | 0x80;+ const hex = std.fmt.bytesToHex(random, .lower);+ const id = arena.alloc(u8, 36) catch return;+ @memcpy(id[0..8], hex[0..8]);+ id[8] = '-';+ @memcpy(id[9..13], hex[8..12]);+ id[13] = '-';+ @memcpy(id[14..18], hex[12..16]);+ id[18] = '-';+ @memcpy(id[19..23], hex[16..20]);+ id[23] = '-';+ @memcpy(id[24..36], hex[20..32]);+ device_id = id;+ Io.Dir.cwd().createDir(io, dir, private_dir_permissions) catch {};+ secureDir(io, dir);+ const file = Io.Dir.cwd().createFile(io, path, .{ .permissions = private_file_permissions }) catch return;+ defer file.close(io);+ file.setPermissions(io, private_file_permissions) catch {};+ var buf: [64]u8 = undefined;+ var writer = file.writer(io, &buf);+ writer.interface.print("{s}\n", .{id}) catch return;+ writer.interface.flush() catch {};+}++pub fn identityHeaders(buf: []std.http.Header) []std.http.Header {+ if (buf.len < 6) return buf[0..0];+ buf[0] = .{ .name = "X-Msh-Platform", .value = platform };+ buf[1] = .{ .name = "X-Msh-Version", .value = version };+ buf[2] = .{ .name = "X-Msh-Device-Name", .value = "graff" };+ buf[3] = .{ .name = "X-Msh-Device-Model", .value = device_model };+ buf[4] = .{ .name = "X-Msh-Os-Version", .value = os_version };+ buf[5] = .{ .name = "X-Msh-Device-Id", .value = device_id };+ return buf[0..6];+}+fn validModelId(id: []const u8) bool {if (id.len == 0 or id.len > 256) return false;for (id) |c| if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.' or c == '/')) return false;@@ -29,6 +110,35 @@ fn positiveInt(obj: std.json.ObjectMap, name: []const u8) u64 {};}+fn boolField(obj: std.json.ObjectMap, name: []const u8) bool {+ const value = obj.get(name) orelse return false;+ return value == .bool and value.bool;+}++fn thinkingSupport(obj: std.json.ObjectMap) pricing.ThinkingSupport {+ const raw = util.strFieldObj(obj, "supports_thinking_type") orelse return .unknown;+ if (std.mem.eql(u8, raw, "no")) return .no;+ if (std.mem.eql(u8, raw, "both")) return .both;+ if (std.mem.eql(u8, raw, "only")) return .only;+ return .unknown;+}++fn parseEfforts(arena: Allocator, obj: std.json.ObjectMap) struct { values: []const []const u8, default: ?[]const u8 } {+ const raw = obj.get("think_efforts") orelse return .{ .values = &.{}, .default = null };+ if (raw != .object or !boolField(raw.object, "support")) return .{ .values = &.{}, .default = null };+ var values: std.ArrayList([]const u8) = .empty;+ if (raw.object.get("valid_efforts")) |list| if (list == .array) {+ for (list.array.items) |value| {+ if (value != .string or value.string.len == 0 or value.string.len > 32) continue;+ values.append(arena, arena.dupe(u8, value.string) catch continue) catch continue;+ }+ };+ return .{+ .values = values.toOwnedSlice(arena) catch &.{},+ .default = if (util.strFieldObj(raw.object, "default_effort")) |value| arena.dupe(u8, value) catch null else null,+ };+}+/// Parse the OpenAI-style model list Kimi exposes. Preserve server ordering for/// the picker, while pricing.providerDefaultModel independently selects the/// newest pure `kN` generation rather than the first compatibility alias.@@ -50,10 +160,20 @@ pub fn parseModels(arena: Allocator, data: []const u8) ?[]const pricing.ModelInfvar context = positiveInt(item.object, "context_length");if (context == 0) context = positiveInt(item.object, "context_window");if (context == 0) context = pricing.default_context;+ const effort = parseEfforts(arena, item.object);+ const protocol: pricing.ModelProtocol = if (util.strFieldObj(item.object, "protocol")) |protocol_name|+ (if (std.mem.eql(u8, protocol_name, "anthropic")) .anthropic else .kimi)+ else+ .kimi;rows.append(arena, .{.provider = "kimi",.name = arena.dupe(u8, id) catch continue,.context = context,+ .protocol = protocol,+ .supports_reasoning = boolField(item.object, "supports_reasoning"),+ .thinking_support = thinkingSupport(item.object),+ .support_efforts = effort.values,+ .default_effort = effort.default,}) catch continue;}const owned = rows.toOwnedSlice(arena) catch return null;@@ -62,7 +182,8 @@ pub fn parseModels(arena: Allocator, data: []const u8) ?[]const pricing.ModelInf/// Fetch and activate the authenticated catalog. Any failure leaves the baked/// K3 rows intact, so offline runs and temporary Kimi outages still start.-pub fn load(io: Io, gpa: Allocator, arena: Allocator, access: []const u8) bool {+pub fn load(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access: []const u8) bool {+ initIdentity(io, arena, home);if (access.len == 0) {catalog_source = "baked fallback — no Kimi login";return false;@@ -71,10 +192,10 @@ pub fn load(io: Io, gpa: Allocator, arena: Allocator, access: []const u8) bool {defer client.deinit();var aw: Io.Writer.Allocating = .init(arena);const bearer = std.fmt.allocPrint(arena, "Bearer {s}", .{access}) catch return false;- const extra = [_]std.http.Header{- .{ .name = "Authorization", .value = bearer },- .{ .name = "Accept", .value = "application/json" },- };+ var extra: [8]std.http.Header = undefined;+ extra[0] = .{ .name = "Authorization", .value = bearer };+ extra[1] = .{ .name = "Accept", .value = "application/json" };+ _ = identityHeaders(extra[2..]);const response = client.fetch(.{.location = .{ .url = models_url },.method = .GET,@@ -103,8 +224,8 @@ test "parseModels accepts Kimi aliases and K3 context windows" {defer state.deinit();const rows = parseModels(state.allocator(),\\{"object":"list","data":[- \\ {"id":"kimi-for-coding","context_length":262144},- \\ {"id":"k3","context_length":1048576},+ \\ {"id":"kimi-for-coding","context_length":262144,"supports_reasoning":true},+ \\ {"id":"k3","context_length":1048576,"protocol":"anthropic","supports_reasoning":true,"supports_thinking_type":"only","think_efforts":{"support":true,"valid_efforts":["max"],"default_effort":"max"}},\\ {"id":"k3","context_length":1},\\ {"id":"bad id","context_length":42}]}).?;@@ -112,4 +233,8 @@ test "parseModels accepts Kimi aliases and K3 context windows" {try std.testing.expectEqualStrings("kimi-for-coding", rows[0].name);try std.testing.expectEqualStrings("k3", rows[1].name);try std.testing.expectEqual(@as(u64, 1_048_576), rows[1].context);+ try std.testing.expectEqual(pricing.ModelProtocol.anthropic, rows[1].protocol);+ try std.testing.expectEqual(pricing.ThinkingSupport.only, rows[1].thinking_support);+ try std.testing.expectEqualStrings("max", rows[1].support_efforts[0]);+ try std.testing.expectEqualStrings("max", rows[1].default_effort.?);}diff --git a/src/oauth.zig b/src/oauth.zigindex 8ba81a0a..da27ada3 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -208,16 +208,23 @@ const kimi_token_url = kimi_oauth_host ++ "/api/oauth/token";const kimi_client_id = "17e5f671-d194-4dfb-9706-5516cb48c098";/// POST a form body to a Kimi OAuth endpoint; return the parsed JSON object.-fn kimiOAuthPost(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, body: []const u8) !std.json.ObjectMap {+fn kimiOAuthPost(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, url: []const u8, body: []const u8) !std.json.ObjectMap {+ kimi_catalog.initIdentity(io, arena, home);var client: std.http.Client = .{ .allocator = gpa, .io = io };defer client.deinit();var aw: Io.Writer.Allocating = .init(arena);+ var identity: [6]std.http.Header = undefined;+ _ = kimi_catalog.identityHeaders(&identity);_ = try client.fetch(.{.location = .{ .url = url },.method = .POST,.payload = body,.response_writer = &aw.writer,- .headers = .{ .content_type = .{ .override = "application/x-www-form-urlencoded" } },+ .headers = .{+ .content_type = .{ .override = "application/x-www-form-urlencoded" },+ .user_agent = .{ .override = kimi_catalog.user_agent },+ },+ .extra_headers = &identity,});const v = try std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });if (v != .object) return error.BadOAuthResponse;@@ -229,9 +236,18 @@ fn kimiAuthPath(arena: Allocator, home: []const u8) []const u8 {}fn writeKimiAuth(io: Io, arena: Allocator, home: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {+ const private_file_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o600) else .default_file;+ const private_dir_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @enumFromInt(0o700) else .default_dir;// createDir is one level, so make ~/.kimi then ~/.kimi/credentials.- Io.Dir.cwd().createDir(io, try std.fmt.allocPrint(arena, "{s}/.kimi", .{home}), .default_dir) catch {};- Io.Dir.cwd().createDir(io, try std.fmt.allocPrint(arena, "{s}/.kimi/credentials", .{home}), .default_dir) catch {};+ const kimi_dir = try std.fmt.allocPrint(arena, "{s}/.kimi", .{home});+ const credentials_dir = try std.fmt.allocPrint(arena, "{s}/.kimi/credentials", .{home});+ Io.Dir.cwd().createDir(io, kimi_dir, private_dir_permissions) catch {};+ Io.Dir.cwd().createDir(io, credentials_dir, private_dir_permissions) catch {};+ for ([_][]const u8{ kimi_dir, credentials_dir }) |path| {+ const dir = Io.Dir.cwd().openDir(io, path, .{}) catch continue;+ defer dir.close(io);+ dir.setPermissions(io, private_dir_permissions) catch {};+ }var obj: std.json.ObjectMap = .empty;try obj.put(arena, "access_token", .{ .string = access });try obj.put(arena, "refresh_token", .{ .string = refresh });@@ -239,8 +255,9 @@ fn writeKimiAuth(io: Io, arena: Allocator, home: []const u8, access: []const u8,var aw: Io.Writer.Allocating = .init(arena);var s: std.json.Stringify = .{ .writer = &aw.writer };try s.write(Value{ .object = obj });- const f = try Io.Dir.cwd().createFile(io, kimiAuthPath(arena, home), .{});+ const f = try Io.Dir.cwd().createFile(io, kimiAuthPath(arena, home), .{ .permissions = private_file_permissions });defer f.close(io);+ f.setPermissions(io, private_file_permissions) catch {};var wbuf: [4096]u8 = undefined;var fw = f.writer(io, &wbuf);try fw.interface.writeAll(aw.writer.buffered());@@ -256,7 +273,7 @@ pub fn kimiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !voconst out = &ow.interface;const da_body = try std.fmt.allocPrint(arena, "client_id={s}", .{kimi_client_id});- const da = kimiOAuthPost(io, gpa, arena, kimi_device_auth_url, da_body) catch |err| {+ const da = kimiOAuthPost(io, gpa, arena, home, kimi_device_auth_url, da_body) catch |err| {try out.print("✗ Kimi device authorization failed: {t}\n", .{err});try out.flush();return;@@ -279,12 +296,12 @@ pub fn kimiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !vovar attempts: usize = 0;while (attempts < 360) : (attempts += 1) {io.sleep(Io.Duration.fromSeconds(interval), .awake) catch {};- const resp = kimiOAuthPost(io, gpa, arena, kimi_token_url, poll_body) catch continue;+ const resp = kimiOAuthPost(io, gpa, arena, home, kimi_token_url, poll_body) catch continue;if (resp.get("access_token")) |a| if (a == .string and a.string.len > 0) {const refresh = strFieldObj(resp, "refresh_token") orelse "";const expires_in: i64 = if (resp.get("expires_in")) |ei| (if (ei == .integer) ei.integer else 900) else 900;try writeKimiAuth(io, arena, home, a.string, refresh, @divTrunc(unixMs(io), 1000) + expires_in);- _ = kimi_catalog.load(io, gpa, arena, a.string);+ _ = kimi_catalog.load(io, gpa, arena, home, a.string);try out.print("✓ logged into Kimi — wrote {s}. /model kimi selects {s}\n", .{kimiAuthPath(arena, home), pricing.providerDefaultModel("kimi", "k3"),});@@ -319,7 +336,7 @@ pub fn loadKimiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8,if (force or (expires_at != 0 and @divTrunc(unixMs(io), 1000) >= expires_at - oauth_refresh_margin_s)) {if (strFieldObj(v.object, "refresh_token")) |refresh| {const body = std.fmt.allocPrint(arena, "client_id={s}&grant_type=refresh_token&refresh_token={s}", .{ kimi_client_id, refresh }) catch return access;- const resp = kimiOAuthPost(io, gpa, arena, kimi_token_url, body) catch return access;+ const resp = kimiOAuthPost(io, gpa, arena, home, kimi_token_url, body) catch return access;if (resp.get("access_token")) |a| if (a == .string and a.string.len > 0) {const new_refresh = strFieldObj(resp, "refresh_token") orelse refresh;const expires_in: i64 = if (resp.get("expires_in")) |ei| (if (ei == .integer) ei.integer else 900) else 900;diff --git a/src/pricing.zig b/src/pricing.zigindex c9dec66a..0c584ab1 100644--- a/src/pricing.zig+++ b/src/pricing.zig@@ -137,8 +137,19 @@ pub const ModelInfo = struct {provider: []const u8,name: []const u8,context: u64,+ // Kimi Code's authenticated /models catalog may choose the wire protocol+ // per model. Missing/`kimi` uses its native OpenAI-shaped transport;+ // `anthropic` switches only that model to beta Messages.+ protocol: ModelProtocol = .provider_default,+ supports_reasoning: bool = false,+ thinking_support: ThinkingSupport = .unknown,+ support_efforts: []const []const u8 = &.{},+ default_effort: ?[]const u8 = null,};+pub const ModelProtocol = enum { provider_default, kimi, anthropic };+pub const ThinkingSupport = enum { unknown, no, both, only };+// Hard cap on the usable input for ANY codex (ChatGPT-account) model. The// backend enforces ~272k input for every gpt-5.x regardless of what the /models// catalog advertises (e.g. 372k for sol/terra/luna, which is NOT honored for@@ -227,9 +238,9 @@ pub const model_table = [_]ModelInfo{// Kimi Code offline fallback. Authenticated startup replaces this slice// from /coding/v1/models; K3 is the current explicit generation while the// two compatibility aliases keep their smaller advertised window.- .{ .provider = "kimi", .name = "k3", .context = 1_048_576 },- .{ .provider = "kimi", .name = "kimi-for-coding", .context = 262_144 },- .{ .provider = "kimi", .name = "kimi-for-coding-highspeed", .context = 262_144 },+ .{ .provider = "kimi", .name = "k3", .context = 1_048_576, .protocol = .kimi, .supports_reasoning = true, .support_efforts = &.{"max"}, .default_effort = "max" },+ .{ .provider = "kimi", .name = "kimi-for-coding", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },+ .{ .provider = "kimi", .name = "kimi-for-coding-highspeed", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },.{ .provider = "moonshot", .name = "kimi-latest", .context = 131_072 },.{ .provider = "xai", .name = "grok-4.3", .context = 1_000_000 },.{ .provider = "xai", .name = "grok-build", .context = 256_000 },@@ -248,6 +259,43 @@ pub fn models() []const ModelInfo {return active_model_table;}+pub fn modelInfoFor(provider_id: []const u8, model: []const u8) ?ModelInfo {+ for (models()) |info| {+ if (std.mem.eql(u8, info.provider, provider_id) and std.mem.eql(u8, info.name, model)) return info;+ }+ return null;+}++/// The official Kimi Code client treats an absent protocol exactly like+/// `kimi`; only a server-declared `anthropic` row uses Messages beta.+pub fn kimiProtocol(model: []const u8) ModelProtocol {+ const info = modelInfoFor("kimi", model) orelse return .kimi;+ return if (info.protocol == .anthropic) .anthropic else .kimi;+}++pub fn kimiSupportsThinking(model: []const u8) bool {+ const info = modelInfoFor("kimi", model) orelse return false;+ return switch (info.thinking_support) {+ .no => false,+ .both, .only => true,+ .unknown => info.supports_reasoning,+ };+}++/// Normalize a requested Graff effort to the server's live allow-list. Kimi+/// Code uses the declared default (or the middle entry) when the requested+/// value is unavailable; an empty list means boolean thinking with no effort.+pub fn kimiThinkingEffort(model: []const u8, requested: []const u8) ?[]const u8 {+ const info = modelInfoFor("kimi", model) orelse return null;+ if (!kimiSupportsThinking(model) or info.support_efforts.len == 0) return null;+ const normalized = if (std.mem.eql(u8, requested, "ultra")) "max" else requested;+ for (info.support_efforts) |effort| if (std.mem.eql(u8, effort, normalized)) return effort;+ if (info.default_effort) |fallback| {+ for (info.support_efforts) |effort| if (std.mem.eql(u8, effort, fallback)) return effort;+ }+ return info.support_efforts[info.support_efforts.len / 2];+}+fn pureKimiGeneration(name: []const u8) ?u32 {if (name.len < 2 or name[0] != 'k') return null;for (name[1..]) |c| if (!std.ascii.isDigit(c)) return null;@@ -420,10 +468,13 @@ test "Kimi discovery preserves Codex and chooses the newest pure generation" {const discovered = [_]ModelInfo{.{ .provider = "kimi", .name = "kimi-for-coding", .context = 262_144 },.{ .provider = "kimi", .name = "k2p7", .context = 262_144 },- .{ .provider = "kimi", .name = "k3", .context = 1_048_576 },+ .{ .provider = "kimi", .name = "k3", .context = 1_048_576, .protocol = .anthropic, .supports_reasoning = true, .support_efforts = &.{"max"}, .default_effort = "max" },};try std.testing.expect(activateKimiModels(arena_state.allocator(), &discovered));try std.testing.expectEqualStrings("k3", providerDefaultModel("kimi", "fallback"));+ try std.testing.expectEqual(ModelProtocol.anthropic, kimiProtocol("k3"));+ try std.testing.expect(kimiSupportsThinking("k3"));+ try std.testing.expectEqualStrings("max", kimiThinkingEffort("k3", "medium").?);try std.testing.expect(providerModelInTable("codex", "gpt-5.6-sol"));try std.testing.expect(!providerModelInTable("kimi", "kimi-for-coding-highspeed"));const codex = [_]ModelInfo{.{ .provider = "codex", .name = "future-sol", .context = 270_000 }};diff --git a/src/provider.zig b/src/provider.zigindex 4989b1b7..9327180d 100644--- a/src/provider.zig+++ b/src/provider.zig@@ -56,10 +56,10 @@ pub const provider_specs = [_]ProviderSpec{.{ .id = "openai", .kind = .openai, .auth = .bearer, .url = "https://api.openai.com/v1/chat/completions", .env_key = "OPENAI_API_KEY", .default_model = "gpt-5.6" },.{ .id = "minimax", .kind = .anthropic, .auth = .bearer, .url = "https://api.minimax.io/anthropic/v1/messages", .env_key = "MINIMAX_API_KEY", .default_model = "MiniMax-M3" },.{ .id = "xiaomi", .kind = .openai, .auth = .bearer, .url = "https://api.xiaomimimo.com/v1/chat/completions", .env_key = "XIAOMI_API_KEY", .default_model = "mimo-v2.5-pro" },- // Kimi Code follows Anthropic Messages (including Anthropic tool schemas),- // despite exposing an OpenAI-shaped /models listing. OpenCode uses the same- // @ai-sdk/anthropic transport for its `kimi-for-coding` provider.- .{ .id = "kimi", .kind = .anthropic, .auth = .bearer, .url = "https://api.kimi.com/coding/v1/messages", .env_key = "KIMI_API_KEY", .default_model = "k3" },+ // Kimi Code publishes the protocol per model. Missing/`kimi` is the native+ // chat-completions wire; a live `protocol: anthropic` row is switched in+ // Keys.build to the beta Messages endpoint + x-api-key, matching kimi-code.+ .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = kimi_native_url, .env_key = "KIMI_API_KEY", .default_model = "k3" },// moonshot: the regular Kimi Open Platform (pay-as-you-go API key, not the// Coding plan). OpenAI-compatible; .cn host for China. kimi-latest tracks// the newest Kimi. Same /v1/models discovery applies if wired later.@@ -81,6 +81,9 @@ pub const provider_specs = [_]ProviderSpec{.{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "https://chatgpt.com/backend-api/codex/responses", .env_key = "CODEX_DISABLED", .default_model = "gpt-5.6-sol" },};+pub const kimi_native_url = "https://api.kimi.com/coding/v1/chat/completions";+pub const kimi_anthropic_url = "https://api.kimi.com/coding/v1/messages?beta=true";+/// Codex responses-endpoint override (GRAFF_CODEX_URL, parsed in main.zig at/// startup — localhost mocks / integration tests). Lives here because every/// provider (re)build path (startup, /model switches, session restore) goes@@ -183,11 +186,12 @@ pub const Keys = struct {pub fn build(keys: Keys, spec: ProviderSpec, key: []const u8, model: []const u8) Provider {const is_codex = std.mem.eql(u8, spec.id, "codex");+ const is_kimi_anthropic = std.mem.eql(u8, spec.id, "kimi") and pricing.kimiProtocol(model) == .anthropic;return .{.id = spec.id,- .kind = spec.kind,- .auth = spec.auth,- .url = if (is_codex) g_codex_url_override orelse spec.url else spec.url,+ .kind = if (is_kimi_anthropic) .anthropic else spec.kind,+ .auth = if (is_kimi_anthropic) .x_api_key else spec.auth,+ .url = if (is_kimi_anthropic) kimi_anthropic_url else if (is_codex) g_codex_url_override orelse spec.url else spec.url,.api_key = key,.model = model,.context = contextWindowFor(spec.id, model),@@ -301,6 +305,30 @@ test "Keys.build: g_codex_url_override rewires only the codex endpoint" {try std.testing.expectEqualStrings("https://api.anthropic.com/v1/messages", anthropic.url);}+test "Keys.build: Kimi follows the live model protocol and auth style" {+ const saved = pricing.active_model_table;+ defer pricing.active_model_table = saved;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const rows = [_]pricing.ModelInfo{+ .{ .provider = "kimi", .name = "native", .context = 1, .protocol = .kimi },+ .{ .provider = "kimi", .name = "messages", .context = 1, .protocol = .anthropic },+ };+ try std.testing.expect(pricing.activateKimiModels(arena_state.allocator(), &rows));+ var keys = Keys{ .values = [_]?[]const u8{null} ** provider_specs.len };+ for (provider_specs, 0..) |spec, i| {+ if (std.mem.eql(u8, spec.id, "kimi")) keys.values[i] = "token";+ }+ const native = try keys.providerById("kimi", "native");+ try std.testing.expectEqual(Provider.Kind.openai, native.kind);+ try std.testing.expectEqual(Provider.Auth.bearer, native.auth);+ try std.testing.expectEqualStrings(kimi_native_url, native.url);+ const messages = try keys.providerById("kimi", "messages");+ try std.testing.expectEqual(Provider.Kind.anthropic, messages.kind);+ try std.testing.expectEqual(Provider.Auth.x_api_key, messages.auth);+ try std.testing.expectEqualStrings(kimi_anthropic_url, messages.url);+}+test "perOutputCap (#201): window-proportional with an absolute ceiling, keep_recent-safe" {var p: Provider = undefined;// ~1/8 of the window in tokens (context/2 bytes at ~4 bytes/token)diff --git a/src/schema.zig b/src/schema.zigindex dd62460a..e8c5197b 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -372,7 +372,7 @@ fn writeToolEntry(s: *std.json.Stringify, kind: Provider.Kind, name: []const u8,/// a per-commit git describe) — bump this only when the schema or JSONL/// protocol changes shape, so SDK regeneration stays byte-stable across/// commits.-pub const schema_version = "0.5";+pub const schema_version = "0.6";/// Emit the machine-readable interface description for `harness --schema`:/// providers, models, built-in tools (name/description/parameters), and the@@ -405,9 +405,9 @@ fn providerLoginKind(id: []const u8) []const u8 {return "api_key";}-/// Whether a (kind,id,model) combo should carry a top-level reasoning_effort-/// hint. Effort-honoring providers: the Responses API (codex) and the-/// OpenAI-compatible gateways we know normalize it (codegraff, deepseek).+/// Whether a model exposes a user-selectable reasoning effort. Kimi maps the+/// setting through its live effort list into `thinking`; the other listed+/// providers use reasoning_effort / Responses reasoning.effort./// Grok models reject the hint even through the codegraff gateway, so they are/// excluded up front (mirrors how opencode gates effort per-model) — the/// reactive drop-and-retry in request() still covers any other model that@@ -415,6 +415,7 @@ fn providerLoginKind(id: []const u8) []const u8 {pub fn providerTakesEffort(kind: Provider.Kind, id: []const u8, model: []const u8) bool {if (std.mem.startsWith(u8, model, "grok")) return false;return kind == .responses or+ (std.mem.eql(u8, id, "kimi") and pricing.kimiSupportsThinking(model)) orstd.mem.eql(u8, id, "codegraff") orstd.mem.eql(u8, id, "deepseek");}@@ -444,6 +445,12 @@ pub fn emitSchema(w: *Io.Writer) !void {try s.write(providerLoginKind(p.id));try s.objectField("default_model");try s.write(p.default_model);+ if (std.mem.eql(u8, p.id, "kimi")) {+ try s.objectField("protocol_source");+ try s.write("live_model_catalog");+ try s.objectField("anthropic_auth");+ try s.write("x_api_key");+ }try s.endObject();}try s.endArray();@@ -534,7 +541,7 @@ test "providerTakesEffort: effort-honoring providers, but never for grok models"try std.testing.expect(providerTakesEffort(.responses, "codex", "gpt-5.5"));try std.testing.expect(providerTakesEffort(.openai, "codegraff", "deepseek-v4-pro"));try std.testing.expect(providerTakesEffort(.openai, "deepseek", "deepseek-v4-pro"));- try std.testing.expect(!providerTakesEffort(.anthropic, "kimi", "k3"));+ try std.testing.expect(providerTakesEffort(.openai, "kimi", "k3"));try std.testing.expect(!providerTakesEffort(.openai, "openai", "gpt-5.5")); // direct openai chattry std.testing.expect(!providerTakesEffort(.openai, "xai", "grok-4.3")); // xai not in the list// grok via the codegraff gateway must NOT get reasoning_effort (grok rejects it)diff --git a/src/serde.zig b/src/serde.zigindex 03c88076..3c972a9e 100644--- a/src/serde.zig+++ b/src/serde.zig@@ -81,19 +81,51 @@ pub fn saveHistory(io: Io, arena: Allocator, home: []const u8, history: []constfw.interface.flush() catch return;}-/// Serialize the Anthropic `messages` array. When `cache` is set and the final-/// message is a plain-string user turn (the common case at request time, and-/// the largest re-sent prefix), wrap it as a text block with a cache_control-/// ephemeral breakpoint — so the whole conversation prefix is cached, not just-/// the system block. Combined with the system breakpoint that's ≤2 of-/// Anthropic's 4 allowed. Other messages are written verbatim.-pub fn writeAnthropicMessages(s: *std.json.Stringify, messages: std.json.Array, cache: bool) !void {+fn anthropicCacheableBlock(value: Value) bool {+ if (value != .object) return false;+ const kind = value.object.get("type") orelse return false;+ if (kind != .string) return false;+ for ([_][]const u8{ "text", "image", "document", "search_result", "tool_use", "tool_result", "server_tool_use", "web_search_tool_result" }) |candidate| {+ if (std.mem.eql(u8, kind.string, candidate)) return true;+ }+ return false;+}++fn writeObjectWithCache(s: *std.json.Stringify, obj: std.json.ObjectMap) !void {+ try s.beginObject();+ var it = obj.iterator();+ while (it.next()) |kv| {+ try s.objectField(kv.key_ptr.*);+ try s.write(kv.value_ptr.*);+ }+ if (obj.get("cache_control") == null) {+ try s.objectField("cache_control");+ try s.print("{s}", .{"{\"type\":\"ephemeral\"}"});+ }+ try s.endObject();+}++/// Serialize Anthropic messages. `normalize_blocks` matches the official Kimi+/// adapter by turning every plain string into a `{type:text,text}` content+/// array. `cache` marks the final cacheable block (including tool_result), not+/// just the plain-string happy path.+pub fn writeAnthropicMessages(s: *std.json.Stringify, messages: std.json.Array, cache: bool, normalize_blocks: bool) !void {const items = messages.items;try s.beginArray();for (items, 0..) |m, i| {- const cache_this = cache and i + 1 == items.len and m == .object and- (if (m.object.get("content")) |c| c == .string else false);- if (!cache_this) {+ if (m != .object or m.object.get("content") == null) {+ try s.write(m);+ continue;+ }+ const content = m.object.get("content").?;+ const cache_this = cache and i + 1 == items.len;+ const string_content = content == .string;+ const array_cache = cache_this and content == .array and content.array.items.len > 0 and anthropicCacheableBlock(content.array.items[content.array.items.len - 1]);+ if (!normalize_blocks and !cache_this) {+ try s.write(m);+ continue;+ }+ if (!string_content and !array_cache) {try s.write(m);continue;}@@ -105,21 +137,161 @@ pub fn writeAnthropicMessages(s: *std.json.Stringify, messages: std.json.Array,try s.write(kv.value_ptr.*);}try s.objectField("content");- try s.beginArray();- try s.beginObject();- try s.objectField("type");- try s.write("text");- try s.objectField("text");- try s.write(m.object.get("content").?.string);- try s.objectField("cache_control");- try s.print("{s}", .{"{\"type\":\"ephemeral\"}"});- try s.endObject();- try s.endArray();+ if (string_content) {+ try s.beginArray();+ try s.beginObject();+ try s.objectField("type");+ try s.write("text");+ try s.objectField("text");+ try s.write(content.string);+ if (cache_this) {+ try s.objectField("cache_control");+ try s.print("{s}", .{"{\"type\":\"ephemeral\"}"});+ }+ try s.endObject();+ try s.endArray();+ } else {+ try s.beginArray();+ for (content.array.items, 0..) |block, block_i| {+ if (block_i + 1 == content.array.items.len and anthropicCacheableBlock(block))+ try writeObjectWithCache(s, block.object)+ else+ try s.write(block);+ }+ try s.endArray();+ }try s.endObject();}try s.endArray();}+/// Kimi's official Anthropic adapter places a cache breakpoint on the final+/// tool definition. The source catalog is already JSON, so rewrite only the+/// last object and fall back to the original bytes if a custom catalog is bad.+pub fn writeAnthropicTools(s: *std.json.Stringify, arena: Allocator, raw: []const u8, cache: bool) !void {+ if (!cache) return s.print("{s}", .{raw});+ const value = std.json.parseFromSliceLeaky(Value, arena, raw, .{ .allocate = .alloc_always }) catch return s.print("{s}", .{raw});+ if (value != .array or value.array.items.len == 0) return s.write(value);+ try s.beginArray();+ for (value.array.items, 0..) |tool, i| {+ if (i + 1 == value.array.items.len and tool == .object)+ try writeObjectWithCache(s, tool.object)+ else+ try s.write(tool);+ }+ try s.endArray();+}++fn jsonValueType(value: Value) ?[]const u8 {+ return switch (value) {+ .string => "string",+ .integer => "integer",+ .float => "number",+ .bool => "boolean",+ .object => "object",+ .array => "array",+ .null => "null",+ else => null,+ };+}++fn inferredKimiType(obj: std.json.ObjectMap) ?[]const u8 {+ if (obj.get("enum")) |values| if (values == .array and values.array.items.len > 0) {+ const first = jsonValueType(values.array.items[0]) orelse return null;+ for (values.array.items[1..]) |value| {+ const current = jsonValueType(value) orelse return null;+ if (!std.mem.eql(u8, first, current) and+ !(std.mem.eql(u8, first, "integer") and std.mem.eql(u8, current, "number")) and+ !(std.mem.eql(u8, first, "number") and std.mem.eql(u8, current, "integer"))) return null;+ }+ return first;+ };+ if (obj.get("const")) |value| return jsonValueType(value);+ for ([_][]const u8{ "properties", "required", "additionalProperties", "patternProperties" }) |key| if (obj.get(key) != null) return "object";+ for ([_][]const u8{ "items", "prefixItems", "minItems", "maxItems" }) |key| if (obj.get(key) != null) return "array";+ for ([_][]const u8{ "pattern", "format", "minLength", "maxLength" }) |key| if (obj.get(key) != null) return "string";+ for ([_][]const u8{ "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf" }) |key| if (obj.get(key) != null) return "number";+ return "string";+}++fn normalizeKimiSchemaMap(arena: Allocator, value: *Value) Allocator.Error!void {+ if (value.* != .object) return;+ var it = value.object.iterator();+ while (it.next()) |entry| try normalizeKimiSchema(arena, entry.value_ptr, false);+}++fn normalizeKimiSchemaArray(arena: Allocator, value: *Value) Allocator.Error!void {+ if (value.* != .array) return;+ for (value.array.items) |*item| try normalizeKimiSchema(arena, item, false);+}++fn normalizeKimiSchema(arena: Allocator, value: *Value, root: bool) Allocator.Error!void {+ if (value.* != .object) return;+ const obj = &value.object;++ // Moonshot requires a union's type on each anyOf branch, never on the+ // parent. MCP generators commonly emit the opposite shape.+ if (root) {+ // Native Kimi simultaneously requires parameters.type="object" and+ // rejects a root anyOf beside that type. Preserve the union as oneOf,+ // which its current schema walker accepts in this root position.+ if (obj.get("anyOf")) |branches| {+ if (obj.get("oneOf") == null) try obj.put(arena, "oneOf", branches);+ _ = obj.orderedRemove("anyOf");+ }+ } else if (obj.get("anyOf") != null) {+ if (obj.fetchOrderedRemove("type")) |removed| {+ const branches = obj.get("anyOf").?;+ if (branches == .array) {+ for (branches.array.items) |*branch| if (branch.* == .object and branch.object.get("type") == null) {+ try branch.object.put(arena, "type", removed.value);+ };+ }+ }+ }+ const has_composition = obj.get("$ref") != null or obj.get("allOf") != null or obj.get("anyOf") != null or obj.get("oneOf") != null or obj.get("not") != null or obj.get("if") != null;+ if (!root and obj.get("type") == null and !has_composition) {+ if (inferredKimiType(obj.*)) |kind| try obj.put(arena, "type", .{ .string = kind });+ }++ // These are the child-schema slots walked by Moonshot's adapter. Map+ // containers such as `properties` are not schemas themselves.+ for ([_][]const u8{ "$defs", "definitions", "dependencies", "dependentSchemas", "patternProperties", "properties" }) |key| {+ if (obj.getPtr(key)) |child| try normalizeKimiSchemaMap(arena, child);+ }+ for ([_][]const u8{ "additionalItems", "additionalProperties", "contains", "contentSchema", "else", "if", "not", "propertyNames", "then", "unevaluatedItems", "unevaluatedProperties" }) |key| {+ if (obj.getPtr(key)) |child| try normalizeKimiSchema(arena, child, false);+ }+ for ([_][]const u8{ "allOf", "anyOf", "oneOf", "prefixItems" }) |key| {+ if (obj.getPtr(key)) |child| try normalizeKimiSchemaArray(arena, child);+ }+ if (obj.getPtr("items")) |items| {+ if (items.* == .array)+ try normalizeKimiSchemaArray(arena, items)+ else+ try normalizeKimiSchema(arena, items, false);+ }+}++/// Kimi's native tool validator is stricter than JSON Schema. Apply the same+/// property-type completion as kimi-code plus its required anyOf rewrite.+pub fn writeKimiTools(s: *std.json.Stringify, arena: Allocator, raw: []const u8) !void {+ const value = std.json.parseFromSliceLeaky(Value, arena, raw, .{ .allocate = .alloc_always }) catch return s.print("{s}", .{raw});+ if (value != .array) return s.write(value);+ for (value.array.items) |*tool| {+ if (tool.* != .object) continue;+ var tool_it = tool.object.iterator();+ while (tool_it.next()) |entry| {+ if (!std.mem.eql(u8, entry.key_ptr.*, "function") or entry.value_ptr.* != .object) continue;+ var function_it = entry.value_ptr.object.iterator();+ while (function_it.next()) |field| {+ if (std.mem.eql(u8, field.key_ptr.*, "parameters")) try normalizeKimiSchema(arena, field.value_ptr, true);+ }+ }+ }+ try s.write(value);+}+pub fn writeOpenAIMessageNormalized(s: *std.json.Stringify, m: Value) !void {if (m != .object) return s.write(m);const role = if (m.object.get("role")) |v| (if (v == .string) v.string else "") else "";diff --git a/src/startup.zig b/src/startup.zigindex 21c2b6c3..354bc033 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -227,7 +227,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp// native-cache parse, and possible refresh until a model surface needs it.if (startupNeedsCodexCatalog(keys, model_flag, saved_model))model_catalog.ensure(io, gpa, arena, home, keys.get("codex") orelse "", keys.codex_account);- if (keys.get("kimi")) |token| _ = kimi_catalog.load(io, gpa, arena, token);+ if (keys.get("kimi")) |token| _ = kimi_catalog.load(io, gpa, arena, home, token);if (home.len != 0) {// Apply the independent models.dev price/context overlay after routing// discovery. Provider-specific Codex windows remain authoritative.@@ -477,7 +477,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.processstd.mem.eql(u8, flags.positionals.items[1], "update")),);const kimi_token = init.environ_map.get("KIMI_API_KEY") orelse oauth.loadKimiOAuth(io, gpa, arena, home, false) orelse "";- _ = kimi_catalog.load(io, gpa, arena, kimi_token);+ _ = kimi_catalog.load(io, gpa, arena, home, kimi_token);try models_cache.command(io, gpa, arena, home, flags.positionals.items[1..]);return true;}