Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Stop sending a Kimi device id

Rach Pradhanc6ce73c19273
diff --git a/src/commands_model.zig b/src/commands_model.zig
index 833377bb..1089a0e9 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -340,7 +340,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
const home = root.home;
const saved = storeKey(root.io, root.gpa, arena, home, pid, key); // persist
_ = keys.set(pid, live_key, if (saved) .stored else .session);
- if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, home, live_key);
+ if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, live_key);
try out.print("✓ {s} key set (live{s}) — now: /model {s}\n", .{ pid, if (saved) " + Keychain" else "", pid });
try out.flush();
return true;
diff --git a/src/kimi_catalog.zig b/src/kimi_catalog.zig
index 3810321c..dde0245a 100644
--- a/src/kimi_catalog.zig
+++ b/src/kimi_catalog.zig
@@ -15,7 +15,6 @@ pub const models_url = "https://api.kimi.com/coding/v1/models";
pub const user_agent = identity.user_agent;
pub const platform = identity.platform;
pub const version = identity.version;
-pub const initIdentity = identity.initIdentity;
pub const identityHeaders = identity.identityHeaders;
pub var catalog_source: []const u8 = "baked offline fallback";
var catalog_attempted = false;
@@ -113,8 +112,7 @@ pub const Fetch = struct {
source: []const u8 = "baked fallback — live refresh unavailable",
};
-pub fn fetch(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access: []const u8) Fetch {
- initIdentity(io, arena, home);
+pub fn fetch(io: Io, gpa: Allocator, arena: Allocator, access: []const u8) Fetch {
if (access.len == 0) return .{ .source = "baked fallback — no Kimi login" };
var client: std.http.Client = .{ .allocator = gpa, .io = io };
defer client.deinit();
@@ -123,13 +121,13 @@ pub fn fetch(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access:
var extra: [8]std.http.Header = undefined;
extra[0] = .{ .name = "Authorization", .value = bearer };
extra[1] = .{ .name = "Accept", .value = "application/json" };
- _ = identityHeaders(extra[2..]);
+ const sent = 2 + identityHeaders(extra[2..]).len;
const response = client.fetch(.{
.location = .{ .url = models_url },
.method = .GET,
.response_writer = &aw.writer,
.headers = .{ .user_agent = .{ .override = user_agent } },
- .extra_headers = &extra,
+ .extra_headers = extra[0..sent],
}) catch return .{};
if (@backingInt(response.status) != 200) return .{};
const rows = parseModels(arena, aw.writer.buffered()) orelse
@@ -178,14 +176,13 @@ pub fn claimAttempt() bool {
/// 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, home: []const u8, access: []const u8) bool {
- initIdentity(io, arena, home);
+pub fn load(io: Io, gpa: Allocator, arena: Allocator, access: []const u8) bool {
if (access.len == 0) {
catalog_source = "baked fallback — no Kimi login";
return false;
}
catalog_attempted = true;
- const got = fetch(io, gpa, arena, home, access);
+ const got = fetch(io, gpa, arena, access);
if (got.rows.len == 0) {
catalog_source = got.source;
return false;
@@ -198,9 +195,9 @@ pub fn load(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access:
/// Demand-load the account catalog at most once per process. Startup fans
/// the GET out via `claimAttempt` + `fetch`; `/model` and `/models` call
/// this when their catalog surfaces become visible.
-pub fn ensure(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, access: []const u8) void {
+pub fn ensure(io: Io, gpa: Allocator, arena: Allocator, access: []const u8) void {
if (catalog_attempted) return;
- _ = load(io, gpa, arena, home, access);
+ _ = load(io, gpa, arena, access);
}
test "parseModels accepts Kimi aliases and K3 context windows" {
diff --git a/src/kimi_identity.zig b/src/kimi_identity.zig
index 5c9b6b37..99bc646e 100644
--- a/src/kimi_identity.zig
+++ b/src/kimi_identity.zig
@@ -7,28 +7,20 @@
const std = @import("std");
const builtin = @import("builtin");
const Io = std.Io;
-const Allocator = std.mem.Allocator;
pub const user_agent = "graff/" ++ @import("build_options").version;
pub const platform = "graff";
pub const version = @import("build_options").version;
-pub var device_id: []const u8 = "unknown";
pub var device_name: []const u8 = "unknown";
pub var device_model: []const u8 = "unknown";
pub var os_version: []const u8 = "unknown";
-/// `device_id` outlives every caller's arena (it rides on each request's
-/// headers), so it is copied here rather than allocated.
-var device_id_buf: [36]u8 = undefined;
var device_name_buf: [256]u8 = undefined;
var device_model_buf: [128]u8 = undefined;
var os_version_buf: [128]u8 = undefined;
var host_fields_ready = false;
-const private_file_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @fromBackingInt(@intCast(0o600)) else .default_file;
-const private_dir_permissions: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) @fromBackingInt(@intCast(0o700)) else .default_dir;
-
/// Node `os.arch()` names. kimi-code puts these in `X-Msh-Device-Model`.
pub fn nodeArch(tag: std.Target.Cpu.Arch) []const u8 {
return switch (tag) {
@@ -74,22 +66,6 @@ pub fn persistAscii(buf: []u8, value: []const u8) []const u8 {
return if (trimmed.len == 0) "unknown" else trimmed;
}
-fn secureDir(io: Io, path: []const u8) void {
- const dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return;
- defer dir.close(io);
- if (builtin.os.tag != .windows) 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;
-}
-
fn readHostname(buf: []u8) []const u8 {
if (comptime builtin.os.tag == .windows) return windowsHostname(buf);
if (comptime builtin.os.tag == .wasi) return "unknown";
@@ -159,63 +135,15 @@ pub fn fillHostFields() void {
device_model = formatDeviceModel(&device_model_buf, builtin.os.tag, os_version, product, arch);
}
-/// 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 {
- fillHostFields();
- 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)) {
- @memcpy(&device_id_buf, value);
- device_id = &device_id_buf;
- 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 = &device_id_buf;
- @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 {
fillHostFields();
- if (buf.len < 6) return buf[0..0];
+ if (buf.len < 5) 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 = device_name };
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];
+ return buf[0..5];
}
test "user_agent is graff/<version>, not a spoofed kimi-code-cli token" {
@@ -259,9 +187,11 @@ test "persistAscii strips non-ASCII and falls back like kimi-code asciiHeader" {
}
test "identityHeaders use hostname and Node-shaped model, not zig os tags" {
- var headers: [6]std.http.Header = undefined;
+ var headers: [5]std.http.Header = undefined;
const got = identityHeaders(&headers);
- try std.testing.expectEqual(@as(usize, 6), got.len);
+ try std.testing.expectEqual(@as(usize, 5), got.len);
+ // No device id: graff keeps no persistent install identifier for Kimi.
+ for (got) |h| try std.testing.expect(!std.ascii.eqlIgnoreCase(h.name, "X-Msh-Device-Id"));
try std.testing.expectEqualStrings("X-Msh-Platform", got[0].name);
// graff states its own platform; it never reports the Kimi CLI's (#1297).
try std.testing.expectEqualStrings("graff", got[0].value);
@@ -280,23 +210,3 @@ test "identityHeaders use hostname and Node-shaped model, not zig os tags" {
try std.testing.expect(std.mem.endsWith(u8, got[3].value, nodeArch(builtin.cpu.arch)));
try std.testing.expect(!std.mem.eql(u8, got[4].value, @tagName(builtin.os.tag)));
}
-
-test "device_id survives the arena initIdentity was called with" {
- const io = std.testing.io;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- try tmp.dir.createDir(io, ".kimi", private_dir_permissions);
- const stored = "0b8f2c4e-1d3a-4f5b-9c6d-7e8f9a0b1c2d";
- try tmp.dir.writeFile(io, .{ .sub_path = ".kimi/device_id", .data = stored ++ "\n" });
- const saved = device_id;
- defer device_id = saved;
-
- // Startup and the catalog fetch hand in short-lived arenas; the id rides
- // on every later request header, so it must not point into them.
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- const home = try std.fmt.allocPrint(arena_state.allocator(), ".zig-cache/tmp/{s}", .{&tmp.sub_path});
- device_id = "unknown";
- initIdentity(io, arena_state.allocator(), home);
- arena_state.deinit();
- try std.testing.expectEqualStrings(stored, device_id);
-}
diff --git a/src/oauth.zig b/src/oauth.zig
index 0270de84..650acf06 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -195,13 +195,12 @@ 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, home: []const u8, url: []const u8, body: []const u8) !std.json.ObjectMap {
- kimi_catalog.initIdentity(io, arena, home);
+fn kimiOAuthPost(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, body: []const u8) !std.json.ObjectMap {
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);
+ var identity_buf: [5]std.http.Header = undefined;
+ const identity = kimi_catalog.identityHeaders(&identity_buf);
_ = try client.fetch(.{
.location = .{ .url = url },
.method = .POST,
@@ -211,7 +210,7 @@ fn kimiOAuthPost(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, url
.content_type = .{ .override = "application/x-www-form-urlencoded" },
.user_agent = .{ .override = kimi_catalog.user_agent },
},
- .extra_headers = &identity,
+ .extra_headers = identity,
});
const v = try std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });
if (v != .object) return error.BadOAuthResponse;
@@ -235,7 +234,7 @@ pub fn kimiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !vo
const out = &ow.interface;
const da_body = try std.fmt.allocPrint(arena, "client_id={s}", .{kimi_client_id});
- const da = kimiOAuthPost(io, gpa, arena, home, kimi_device_auth_url, da_body) catch |err| {
+ const da = kimiOAuthPost(io, gpa, arena, kimi_device_auth_url, da_body) catch |err| {
try out.print("✗ Kimi device authorization failed: {t}\n", .{err});
try out.flush();
return;
@@ -258,12 +257,12 @@ pub fn kimiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !vo
var attempts: usize = 0;
while (attempts < 360) : (attempts += 1) {
io.sleep(Io.Duration.fromSeconds(interval), .awake) catch {};
- const resp = kimiOAuthPost(io, gpa, arena, home, kimi_token_url, poll_body) catch continue;
+ const resp = kimiOAuthPost(io, gpa, arena, 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, home, a.string);
+ _ = kimi_catalog.load(io, gpa, arena, a.string);
try out.print("✓ logged into Kimi — wrote {s}. /model kimi selects {s}\n", .{
kimiAuthPath(arena, home), pricing.providerDefaultModel("kimi", "k3"),
});
@@ -308,7 +307,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, home, kimi_token_url, body) catch return access;
+ const resp = kimiOAuthPost(io, gpa, arena, 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/picker_auth.zig b/src/picker_auth.zig
index 47162d5c..3e8d0e88 100644
--- a/src/picker_auth.zig
+++ b/src/picker_auth.zig
@@ -368,7 +368,7 @@ pub fn offerProviderAuth(
const dup = arena.dupe(u8, key) catch key;
const saved = storeKey(root.io, root.gpa, arena, root.home, pid, dup);
_ = keys.set(pid, dup, if (saved) .stored else .session);
- if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, root.home, dup);
+ if (std.mem.eql(u8, pid, "kimi")) _ = kimi_catalog.load(root.io, root.gpa, arena, dup);
try out.print("\xe2\x9c\x93 {s} key set (live{s})\n", .{ pid, if (saved) " + Keychain" else "" });
}
diff --git a/src/providers.zig b/src/providers.zig
index a975be97..699a3204 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -311,7 +311,7 @@ fn modelQueryMayUseKimi(query: []const u8) bool {
pub fn ensureModelQueryCatalogs(root: *Agent, keys: Keys, query: []const u8) void {
if (modelQueryMayUseCodex(query)) root.ensureModelCatalog(keys);
if (modelQueryMayUseKimi(query))
- kimi_catalog.ensure(root.io, root.gpa, root.arena, root.home, keys.get("kimi") orelse "");
+ kimi_catalog.ensure(root.io, root.gpa, root.arena, keys.get("kimi") orelse "");
router_catalog.ensureForQuery(root.io, root.gpa, root.arena, root.home, keys, query);
}
@@ -334,7 +334,7 @@ pub fn ensureControlRequestCatalogs(root: *Agent, keys: Keys, provider_query: []
if (controlRequestMayUseCodex(provider_query, model_query, legacy_name)) root.ensureModelCatalog(keys);
const query = catalog_selection.controlQuery(provider_query, model_query, legacy_name);
if (modelQueryMayUseKimi(query))
- kimi_catalog.ensure(root.io, root.gpa, root.arena, root.home, keys.get("kimi") orelse "");
+ kimi_catalog.ensure(root.io, root.gpa, root.arena, keys.get("kimi") orelse "");
router_catalog.ensureForQuery(root.io, root.gpa, root.arena, root.home, keys, query);
}
diff --git a/src/router_catalog.zig b/src/router_catalog.zig
index bf4e5cb2..db0d5abd 100644
--- a/src/router_catalog.zig
+++ b/src/router_catalog.zig
@@ -456,15 +456,15 @@ const KimiOutcome = struct {
arena_state: ?std.heap.ArenaAllocator = null,
};
-fn kimiFetchTask(io: Io, gpa: Allocator, home: []const u8, access: []const u8) KimiOutcome {
+fn kimiFetchTask(io: Io, gpa: Allocator, access: []const u8) KimiOutcome {
var arena_state = std.heap.ArenaAllocator.init(gpa);
return .{
- .fetch = kimi_catalog.fetch(io, gpa, arena_state.allocator(), home, access),
+ .fetch = kimi_catalog.fetch(io, gpa, arena_state.allocator(), access),
.arena_state = arena_state,
};
}
-fn spawnKimi(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) ?Io.Future(KimiOutcome) {
+fn spawnKimi(io: Io, gpa: Allocator, arena: Allocator, keys: provider.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) ?Io.Future(KimiOutcome) {
if (!catalog_selection.startupMayUse(keys, "kimi", model_flag, saved)) return null;
if (!kimi_catalog.claimAttempt()) return null;
const access = keys.get("kimi") orelse "";
@@ -472,7 +472,7 @@ fn spawnKimi(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: p
kimi_catalog.commit(arena, &.{}, "baked fallback — no Kimi login");
return null;
}
- const args = .{ io, gpa, home, access };
+ const args = .{ io, gpa, access };
return io.concurrent(kimiFetchTask, args) catch io.async(kimiFetchTask, args);
}
@@ -481,7 +481,7 @@ fn spawnKimi(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: p
/// cache immediately, waits `live_budget_ms` only when there is none, and
/// otherwise refreshes the cache file in the background.
pub fn ensureForStartup(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, keys: provider.Keys, model_flag: ?[]const u8, saved: ?serde.SavedModel) void {
- var kimi_task = spawnKimi(io, gpa, arena, home, keys, model_flag, saved);
+ var kimi_task = spawnKimi(io, gpa, arena, keys, model_flag, saved);
defer if (kimi_task) |*fut| {
var outcome = fut.await(io);
defer if (outcome.arena_state) |*ta| ta.deinit();
diff --git a/src/startup.zig b/src/startup.zig
index 2343c0a0..8e63ce82 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -481,7 +481,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
true,
);
const kimi_token = init.environ_map.get("KIMI_API_KEY") orelse oauth.loadKimiOAuth(io, gpa, arena, home, false, null) orelse "";
- _ = kimi_catalog.load(io, gpa, arena, home, kimi_token);
+ _ = kimi_catalog.load(io, gpa, arena, kimi_token);
var router_keys: provider_mod.Keys = .{ .values = @splat(null) };
for (provider_mod.provider_specs, &router_keys.values, &router_keys.sources) |spec, *value, *source| {
if (!router_catalog.dynamic(spec)) continue;