graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Sign Kimi accounts in on kimi.ai or kimi.com and copy sign-in links
Rach Pradhan148d56c96b1c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c69d128d..b4b24e8c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,9 @@ current is part of cutting a release.## v0.302.52+- `graff login kimi` signs international accounts in on kimi.ai and mainland China accounts on kimi.com. graff picks the site from your saved login or your clock and locale; `graff login kimi.ai` and `graff login kimi.com` choose it outright, and token refresh goes back to the site that issued the login. Earlier logins keep refreshing on kimi.com.+- Sign-in links are copied for you: in a terminal, `graff login` puts the link on the clipboard (over SSH, on your own terminal's clipboard) so it can be pasted into any browser or device. Over SSH and with `GRAFF_NO_BROWSER`, graff no longer opens a browser the user can't see.+- The Kimi sign-in waits as long as the code is valid, slows down when the server asks, says when the sign-in server is unreachable, and reports a declined sign-in plainly.- The terminal REPL has a clearer session strip, a subtle divider, and distinct styling for active and completed checklist items. The bare prompt, scrollback, and plain output remain intact; no native window or graphical toolkit is required.- Operational modes stay visible before workspace metadata when a terminal pane is narrow.- Includes independent conversation forks for subagents and workflow fan-out, optional retained workers, and bounded workflow synthesis that preserves earlier findings.diff --git a/src/args.zig b/src/args.zigindex 38e64891..14dfc1e7 100644--- a/src/args.zig+++ b/src/args.zig@@ -42,6 +42,7 @@ pub const Flags = struct {refresh_flag: bool = false,codex_login: bool = false,kimi_login: bool = false,+ kimi_region: ?@import("oauth_kimi.zig").Region = null, // `graff login kimi.ai` / `kimi.com`xai_login: bool = false,zai_login: bool = false,chatgpt_login: bool = false,@@ -273,6 +274,7 @@ pub fn parse(init: std.process.Init) !Flags {std.process.fatal("unknown login '{s}' — graff login [codegraff|chatgpt|anthropic|kimi|xai|zai]", .{name});flags.codex_login = std.mem.eql(u8, target, "codex");flags.kimi_login = std.mem.eql(u8, target, "kimi");+ flags.kimi_region = @import("oauth_kimi.zig").regionFromLoginName(name);flags.xai_login = std.mem.eql(u8, target, "xai");flags.zai_login = std.mem.eql(u8, target, "zai");flags.chatgpt_login = std.mem.eql(u8, target, "chatgpt-new");@@ -351,6 +353,7 @@ pub fn loginTarget(name: []const u8) ?[]const u8 {};for (aliases) |pair| if (std.ascii.eqlIgnoreCase(name, pair[0])) return pair[1];if (@import("oauth_zai.zig").isLoginName(name)) return "zai";+ if (@import("oauth_kimi.zig").isLoginName(name)) return "kimi";if (@import("oauth_chatgpt.zig").isLoginName(name)) return "chatgpt-new";return null;}@@ -361,6 +364,7 @@ test "loginTarget: every ChatGPT name, codex included, is the plan's sign-in; untry std.testing.expectEqualStrings("codegraff", loginTarget("graff").?);try std.testing.expectEqualStrings("xai", loginTarget("grok").?);try std.testing.expectEqualStrings("kimi", loginTarget("kimi").?);+ try std.testing.expectEqualStrings("kimi", loginTarget("kimi.ai").?);for ([_][]const u8{ "ant", "anthropic", "ANT", "Anthropic", "console", "Console" }) |name|try std.testing.expectEqualStrings("anthropic", loginTarget(name).?);try std.testing.expectEqualStrings("zai", loginTarget("zai").?);diff --git a/src/cli.zig b/src/cli.zigindex 454918ab..e9f400a6 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -24,6 +24,10 @@ const update_target = @import("update_target.zig");pub const changelog_text =\\What's new\\──────────+ \\0.302.52+ \\ • graff login kimi works for kimi.ai (international) and kimi.com accounts+ \\ • sign-in links are copied to your clipboard, over SSH too+ \\\\0.302.51\\ • Kimi API keys and logins work again (no more RstStream)\\ • a used-up Kimi plan window stops instead of retrying@@ -255,7 +259,7 @@ pub const usage_text =\\ graff login chatgpt ChatGPT sign-in (also: codex, openai)\\ graff login anthropic Claude subscription browser sign-in (also: ant)\\ graff login console metered Console sign-in through the `ant` CLI- \\ graff login kimi Kimi Code OAuth login (device-code)+ \\ graff login kimi Kimi Code OAuth login (kimi.ai; kimi.com for China)\\ graff login xai Grok/SuperGrok OAuth login (device-code)\\ graff login zai Z.AI Coding Plan OAuth login\\ graff key set <provider> <key> store a key (Keychain; POSIX 0600 file; Windows home ACL)diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex f5c106d7..d13ae7a1 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -79,7 +79,7 @@ pub const commands = [_]Item{.{ .name = "/ultracode", .desc = "toggle persistent workflow mode; bare opens an on/off picker, or /ultracode on|off" },.{ .name = "/fallback", .usage = "/fallback [allow|remove|off]", .desc = "opt-in cross-provider fallback for this workspace (same-provider rollout stays on)" },.{ .name = "/key", .usage = "/key [provider secret]", .desc = "show API-key status; /key <provider> <secret> adds one live (+ Keychain)" },- .{ .name = "/login", .usage = "/login [codegraff|chatgpt|kimi|xai|zai]", .desc = "OAuth sign-in (no key to paste); bare opens a picker (chatgpt aliases: codex, openai, oai; zai aliases: glm, z.ai)" },+ .{ .name = "/login", .usage = "/login [codegraff|chatgpt|kimi|xai|zai]", .desc = "OAuth sign-in (no key to paste); bare opens a picker (chatgpt aliases: codex, openai, oai; zai aliases: glm, z.ai; kimi sites: kimi.ai, kimi.com)" },.{ .name = "/keepcontext", .desc = "toggle keeping the conversation when /model switches wire format (default on)" },.{ .name = "/effort", .desc = "reasoning depth: low|medium|high|... (codex, deepseek, codegraff; persists)" },.{ .name = "/reasoning", .desc = "alias for /effort" },diff --git a/src/commands_model.zig b/src/commands_model.zigindex 1089a0e9..87ecbd5e 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -360,7 +360,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,.{ .name = "chatgpt", .desc = "ChatGPT sign-in (also: codex, openai)" },.{ .name = "anthropic", .desc = "Claude subscription sign-in (also: ant)" },.{ .name = "console", .desc = "metered Console sign-in through the ant CLI" },- .{ .name = "kimi", .desc = "Kimi Code sign-in (device-code OAuth)" },+ .{ .name = "kimi", .desc = "Kimi Code sign-in (kimi.ai; /login kimi.com for China)" },.{ .name = "xai", .desc = "Grok / SuperGrok sign-in (device-code OAuth)" },.{ .name = "zai", .desc = "Z.AI Coding Plan sign-in (CLI OAuth)" },};@@ -380,6 +380,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,// Same names as `graff login`: every ChatGPT name, codex included, is// the plan's sign-in, chatgpt-new (ADR 0229).const console_login = std.ascii.eqlIgnoreCase(target, "console");+ const kimi_region = @import("oauth_kimi.zig").regionFromLoginName(target);target = @import("args.zig").loginTarget(target) orelse target;const home = root.home;@@ -391,7 +392,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;};} else if (std.mem.eql(u8, target, "kimi")) {- oauth.kimiLogin(root.io, root.gpa, arena, home) catch |err| {+ oauth.kimiLogin(root.io, root.gpa, arena, home, kimi_region) catch |err| {try out.print("\xe2\x9c\x97 kimi login failed: {t}\n", .{err});try out.flush();return true;diff --git a/src/credential_store.zig b/src/credential_store.zigindex 0c2a02e9..10b67da8 100644--- a/src/credential_store.zig+++ b/src/credential_store.zig@@ -163,6 +163,12 @@ pub fn graffCredentialPath(arena: Allocator, home: []const u8, name: []const u8)/// Store an access/refresh/expiry triple at `oauthPath`, 0600 inside 0700 dirs.pub fn writeOAuth(io: Io, arena: Allocator, home: []const u8, provider_dir: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {+ return writeOAuthFrom(io, arena, home, provider_dir, access, refresh, expires_at, "");+}++/// writeOAuth that also records the sign-in server (`oauth_host`), for+/// providers whose refresh must return to the host that issued the token.+pub fn writeOAuthFrom(io: Io, arena: Allocator, home: []const u8, provider_dir: []const u8, access: []const u8, refresh: []const u8, expires_at: i64, oauth_host: []const u8) !void {// createDir is one level, so make <home>/<provider_dir> then its credentials/.const base = try std.fmt.allocPrint(arena, "{s}/{s}", .{ resolveHome(home), provider_dir });const credentials = try std.fmt.allocPrint(arena, "{s}/credentials", .{base});@@ -179,6 +185,7 @@ pub fn writeOAuth(io: Io, arena: Allocator, home: []const u8, provider_dir: []cotry obj.put(arena, "access_token", .{ .string = access });try obj.put(arena, "refresh_token", .{ .string = refresh });try obj.put(arena, "expires_at", .{ .integer = expires_at });+ if (oauth_host.len > 0) try obj.put(arena, "oauth_host", .{ .string = oauth_host });var aw: Io.Writer.Allocating = .init(arena);var stringify: std.json.Stringify = .{ .writer = &aw.writer };try stringify.write(Value{ .object = obj });diff --git a/src/main.zig b/src/main.zigindex 736edcda..d8eed873 100644--- a/src/main.zig+++ b/src/main.zig@@ -564,7 +564,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig"), @import("oauth_chatgpt.zig"), @import("chatgpt_reauth.zig"), @import("oauth_anthropic.zig"), @import("anthropic_oauth_wire.zig"), @import("anthropic_login_tests.zig") };_ = .{ @import("agent_empty_completion.zig"), @import("agent_length_cutoff.zig"), @import("agent_model_loop.zig"), @import("publication_policy_tests.zig"), @import("jobs_completion_tests.zig"), @import("headless_result.zig"), @import("oneshot.zig"), @import("agent_length.zig"), @import("agent_length_tests.zig") };_ = .{ @import("provider_routing_tests.zig"), @import("codegraff_messages_tests.zig"), @import("tool_result_empty_tests.zig"), @import("history_wire.zig"), @import("path_lookup.zig"), @import("agents_prepare.zig"), @import("catalog_price.zig"), @import("readline_paste_number_tests.zig"), @import("test_hooks.zig"), @import("peer_wake_loop.zig") };- _ = .{ @import("list_dir_nearmiss.zig"), @import("tool_preview_tests.zig"), @import("stream_reconnect.zig") };+ _ = .{ @import("list_dir_nearmiss.zig"), @import("tool_preview_tests.zig"), @import("stream_reconnect.zig"), @import("oauth_kimi.zig"), @import("signin_link.zig") };_ = @import("repo_map.zig");_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests_ = @import("agent_gateway_retry.zig"); // #1019: flake vs overflow classification must stay reachablediff --git a/src/oauth.zig b/src/oauth.zigindex 650acf06..b92a1674 100644--- a/src/oauth.zig+++ b/src/oauth.zig@@ -13,7 +13,7 @@ const accountFromIdToken = helpers.accountFromIdToken;const writeCodexAuth = helpers.writeCodexAuth;const codex_login_page_html = helpers.codex_login_page_html;const queryParam = helpers.queryParam;-const openBrowser = helpers.openBrowser;+const signin_link = @import("signin_link.zig");const callback = @import("oauth_callback.zig");const ansi = @import("ansi.zig");@@ -24,8 +24,6 @@ const util = @import("util.zig");const strFieldObj = util.strFieldObj;const unixMs = util.unixMs;-const kimi_catalog = @import("kimi_catalog.zig");-const pricing = @import("pricing.zig");const codegraff = @import("oauth_codegraff.zig");const zai = @import("oauth_zai.zig");const credential_store = @import("credential_store.zig");@@ -68,7 +66,7 @@ pub const takePersistError = helpers.takePersistError;// it — wider than the old 60s so a mid-session refresh has headroom before a// turn's request would otherwise cross the expiry and 401. kimi-code uses the// same "ensureFresh near expiry + force-refresh on 401" shape.-const oauth_refresh_margin_s: i64 = 300;+pub const oauth_refresh_margin_s: i64 = 300;// Serializes concurrent token refreshes (parallel subagents share the on-disk// token) so they don't race the single-use refresh_token.var oauth_refresh_mutex: Io.Mutex = .init;@@ -134,9 +132,11 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, revar server = try callback.listen(io, 1455);defer server.deinit(io);- try out.print("\nOpen this URL to authorize (browser should open automatically):\n\n{s}\n\nwaiting for the callback on {s} …\n", .{ url, codex_redirect });+ try out.print("\nOpen this URL to authorize (browser should open automatically):\n\n{s}\n", .{url});+ try signin_link.offer(io, out, url);+ try out.print("\nwaiting for the callback on {s} …\n", .{codex_redirect});try out.flush();- openBrowser(io, url);+ signin_link.open(io, url);// Only this attempt's redirect ends the wait (oauth_callback.zig).var rbuf: [16 * 1024]u8 = undefined;@@ -182,143 +182,16 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, retry out.flush();}-// Kimi Code OAuth — device-code flow on the shared kimi-code OAuth client and-// endpoints (auth.kimi.com). Moonshot's own hosts share this client and tell-// themselves apart by `X-Msh-Platform`; graff reports `graff` and-// `graff/<version>`, never the CLI's identity (#1297, ADR 0204).-// `graff login kimi` runs the flow and writes the token-// to ~/.kimi/credentials/graff-oauth.json; loadKimiOAuth reads it at startup-// and refreshes in place when near expiry.-const kimi_oauth_host = "https://auth.kimi.com";-const kimi_device_auth_url = kimi_oauth_host ++ "/api/oauth/device_authorization";-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 {- var client: std.http.Client = .{ .allocator = gpa, .io = io };- defer client.deinit();- var aw: Io.Writer.Allocating = .init(arena);- var identity_buf: [5]std.http.Header = undefined;- const identity = kimi_catalog.identityHeaders(&identity_buf);- _ = try client.fetch(.{- .location = .{ .url = url },- .method = .POST,- .payload = body,- .response_writer = &aw.writer,- .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;- return v.object;-}--fn kimiAuthPath(arena: Allocator, home: []const u8) []const u8 {- return credential_store.oauthPath(arena, home, ".kimi");-}--fn writeKimiAuth(io: Io, arena: Allocator, home: []const u8, access: []const u8, refresh: []const u8, expires_at: i64) !void {- return credential_store.writeOAuth(io, arena, home, ".kimi", access, refresh, expires_at);-}--/// `graff login kimi`: Kimi Code device-code OAuth. Prints a verification URL +-/// user code, opens the browser, polls until the user authorizes, then stores-/// the access/refresh token.-pub fn kimiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {- var obuf: [4096]u8 = undefined;- var ow = Io.File.stdout().writer(io, &obuf);- const 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| {- try out.print("✗ Kimi device authorization failed: {t}\n", .{err});- try out.flush();- return;- };- if (da.get("error")) |e| {- try out.print("✗ {s}\n", .{if (e == .string) e.string else "device authorization error"});- try out.flush();- return;- }- const device_code = strFieldObj(da, "device_code") orelse return error.BadOAuthResponse;- const user_code = strFieldObj(da, "user_code") orelse "";- const verify = strFieldObj(da, "verification_uri_complete") orelse strFieldObj(da, "verification_uri") orelse "";- const interval: i64 = if (da.get("interval")) |iv| (if (iv == .integer) @max(iv.integer, 1) else 5) else 5;-- try out.print("\nTo log in to Kimi, open this URL (browser should open automatically):\n\n {s}\n\nand confirm the code: {s}\n\nwaiting for authorization…\n", .{ verify, user_code });- try out.flush();- openBrowser(io, verify);-- const poll_body = try std.fmt.allocPrint(arena, "client_id={s}&device_code={s}&grant_type=urn:ietf:params:oauth:grant-type:device_code", .{ kimi_client_id, device_code });- var 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;- 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);- try out.print("✓ logged into Kimi — wrote {s}. /model kimi selects {s}\n", .{- kimiAuthPath(arena, home), pricing.providerDefaultModel("kimi", "k3"),- });- try out.flush();- return;- };- const msg = if (resp.get("error")) |e| (if (e == .string) e.string else "") else "";- if (std.mem.eql(u8, msg, "authorization_pending") or std.mem.eql(u8, msg, "slow_down")) continue;- if (std.mem.eql(u8, msg, "expired_token")) {- try out.writeAll("✗ the code expired — run `graff login kimi` again\n");- try out.flush();- return;- }- if (msg.len > 0) {- try out.print("✗ {s}\n", .{msg});- try out.flush();- return;- }- }- try out.writeAll("✗ timed out waiting for authorization\n");- try out.flush();-}+// Kimi Code OAuth lives in oauth_kimi.zig (two sign-in servers, kimi.ai and kimi.com).+const kimi = @import("oauth_kimi.zig");+pub const kimiLogin = kimi.login;+pub const loadKimiOAuth = kimi.load;/// #245 single-flight guard: has the token that just 401'd already been replaced/// on disk by another concurrent refresher? Defined in oauth_helpers.zig, where/// the silent codex refresh (#402) needs the same primitive.const supersededToken = helpers.supersededToken;-/// Reads the stored Kimi OAuth access token, refreshing it in place when within-/// 60s of expiry. Returns null if not logged in. Mirrors loadCodexAuth.-/// `stale` is the token that just 401'd (null when not recovering from one) —-/// see supersededToken.-pub fn loadKimiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {- const data = Io.Dir.cwd().readFileAlloc(io, kimiAuthPath(arena, home), arena, .limited(64 * 1024)) catch return null;- const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;- if (v != .object) return null;- const access = strFieldObj(v.object, "access_token") orelse return null;- const expires_at: i64 = if (v.object.get("expires_at")) |e| (if (e == .integer) e.integer else 0) else 0;- // #245: another concurrent refresher may already have replaced the token that- // 401'd; re-minting would rotate-kill theirs. Adopt what is on disk instead.- if (supersededToken(force, access, stale)) return access;- 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;- 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;- writeKimiAuth(io, arena, home, a.string, new_refresh, @divTrunc(unixMs(io), 1000) + expires_in) catch {};- return a.string;- };- }- }- return access;-}-/// #148: mid-session refresh for a login-sourced key. For the refreshable OAuth/// providers (kimi/xai/codex) returns the current access token, refreshed in/// place if near expiry or `force`d (e.g. after a 401). Returns null for@@ -439,9 +312,11 @@ pub fn xaiLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !voiconst verify = strFieldObj(da, "verification_uri_complete") orelse strFieldObj(da, "verification_uri") orelse "";const interval: i64 = if (da.get("interval")) |iv| (if (iv == .integer) @max(iv.integer, 1) else 5) else 5;- try out.print("\nTo log in to Grok (xAI), open this URL (browser should open automatically):\n\n {s}\n\nand confirm the code: {s}\n\nwaiting for authorization…\n", .{ verify, user_code });+ try out.print("\nTo log in to Grok (xAI), open this URL (browser should open automatically):\n\n {s}\n", .{verify});+ try signin_link.offer(io, out, verify);+ try out.print("\nand confirm the code: {s}\n\nwaiting for authorization…\n", .{user_code});try out.flush();- openBrowser(io, verify);+ signin_link.open(io, verify);const poll_body = try std.fmt.allocPrint(arena, "client_id={s}&device_code={s}&grant_type=urn:ietf:params:oauth:grant-type:device_code", .{ xai_client_id, device_code });var attempts: usize = 0;@@ -571,7 +446,7 @@ test "writeKimiAuth/writeXaiAuth: both real writers store 0600 in 0700 dirs, loa// Drive the two production writers, not a shared helper: xAI used to open its// token file with a bare createFile (0644, no 0700 dirs) while kimi hardened// its own, and only pinning both functions keeps that from coming back.- try writeKimiAuth(io, arena, home, "kimi-access", "kimi-refresh", far_future);+ try kimi.writeAuth(io, arena, home, "kimi-access", "kimi-refresh", far_future, "");try writeXaiAuth(io, arena, home, "xai-access", "xai-refresh", far_future);for ([_][]const u8{ ".kimi", ".xai" }) |provider_dir| {diff --git a/src/oauth_anthropic.zig b/src/oauth_anthropic.zigindex 3c1ea8e6..cb3ca6d5 100644--- a/src/oauth_anthropic.zig+++ b/src/oauth_anthropic.zig@@ -297,9 +297,11 @@ pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, refreshconst verifier = helpers.b64url(arena, &random);if (verifier.len == 0) return error.OutOfMemory;const url = try authorizeUrl(arena, redirect, verifier);- try out.print("\nSign in with Anthropic (your browser should open it):\n\n{s}\n\nWaiting for sign-in…\n", .{url});+ try out.print("\nSign in with Anthropic (your browser should open it):\n\n{s}\n", .{url});+ try @import("signin_link.zig").offer(io, out, url);+ try out.writeAll("\nWaiting for sign-in…\n");try out.flush();- helpers.openBrowser(io, url);+ @import("signin_link.zig").open(io, url);while (true) {const stream = try server.accept(io);defer stream.close(io);diff --git a/src/oauth_chatgpt.zig b/src/oauth_chatgpt.zigindex 76a5784a..06296776 100644--- a/src/oauth_chatgpt.zig+++ b/src/oauth_chatgpt.zig@@ -399,10 +399,11 @@ pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {.login_hint = if (returning) saved.?.email else "",};const url = try authorizeUrl(arena, attempt);- try out.print("\nSign in with ChatGPT (your browser should open it):\n\n{s}\n\n", .{url});- try out.print("waiting for the sign-in on {s} …\n", .{attempt.redirect});+ try out.print("\nSign in with ChatGPT (your browser should open it):\n\n{s}\n", .{url});+ try @import("signin_link.zig").offer(io, out, url);+ try out.print("\nwaiting for the sign-in on {s} …\n", .{attempt.redirect});try out.flush();- helpers.openBrowser(io, url);+ @import("signin_link.zig").open(io, url);// Only this attempt's redirect ends the wait; a tab left from an earlier// attempt gets a page saying so (oauth_callback.zig).var rbuf: [16 * 1024]u8 = undefined;diff --git a/src/oauth_codegraff.zig b/src/oauth_codegraff.zigindex 09e80a3d..85c015b0 100644--- a/src/oauth_codegraff.zig+++ b/src/oauth_codegraff.zig@@ -9,7 +9,7 @@ const style = &@import("ansi.zig").style;const util = @import("util.zig");const strFieldObj = util.strFieldObj;const intFieldObj = util.intFieldObj;-const openBrowser = @import("oauth_helpers.zig").openBrowser;+const signin_link = @import("signin_link.zig");const credential_store = @import("credential_store.zig");const codegraff_device_base = @import("main.zig").codegraff_device_base;@@ -56,9 +56,11 @@ pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {// Print the link that carries the code: a person who copies it (the// browser did not open, or opened elsewhere) lands on the approval itself,// not on a page with nowhere to type the code.- try out.print("\nTo authorize, open:\n\n {s}\n\nand check it shows the code {s}{s}{s}\n\nwaiting for approval …\n", .{ complete_uri, style.bold, user_code, style.reset });+ try out.print("\nTo authorize, open:\n\n {s}\n", .{complete_uri});+ try signin_link.offer(io, out, complete_uri);+ try out.print("\nand check it shows the code {s}{s}{s}\n\nwaiting for approval …\n", .{ style.bold, user_code, style.reset });try out.flush();- openBrowser(io, complete_uri);+ signin_link.open(io, complete_uri);const poll_body = try std.fmt.allocPrint(arena, "{{\"device_code\":\"{s}\"}}", .{device_code});var waited: i64 = 0;diff --git a/src/oauth_kimi.zig b/src/oauth_kimi.zignew file mode 100644index 00000000..5390c00a--- /dev/null+++ b/src/oauth_kimi.zig@@ -0,0 +1,320 @@+//! Kimi Code OAuth — device-code flow on the shared kimi-code OAuth client.+//! Moonshot runs two sign-in servers: auth.kimi.ai for international+//! accounts and auth.kimi.com for mainland China. Hosts tell themselves+//! apart by `X-Msh-Platform`; graff reports `graff` and `graff/<version>`,+//! never the CLI's identity (#1297, ADR 0204).+//! `graff login kimi` runs the flow and writes the token, plus the server+//! that issued it, to ~/.kimi/credentials/graff-oauth.json; `load` reads it at+//! startup and refreshes in place, on that same server, when near expiry.+//! Tokens from either server work on api.kimi.com, so the API host is shared.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const util = @import("util.zig");+const strFieldObj = util.strFieldObj;+const unixMs = util.unixMs;+const kimi_catalog = @import("kimi_catalog.zig");+const credential_store = @import("credential_store.zig");+const pricing = @import("pricing.zig");+const signin_link = @import("signin_link.zig");+const supersededToken = @import("oauth_helpers.zig").supersededToken;+const oauth_refresh_margin_s = @import("oauth.zig").oauth_refresh_margin_s;++const client_id = "17e5f671-d194-4dfb-9706-5516cb48c098";++pub const Region = enum {+ global,+ cn,++ pub fn host(r: Region) []const u8 {+ return switch (r) {+ .global => "https://auth.kimi.ai",+ .cn => "https://auth.kimi.com",+ };+ }++ pub fn site(r: Region) []const u8 {+ return switch (r) {+ .global => "kimi.ai",+ .cn => "kimi.com",+ };+ }++ fn other(r: Region) Region {+ return if (r == .global) .cn else .global;+ }+};++/// A login saved before graff recorded the server came from auth.kimi.com.+const legacy_host = Region.cn.host();++/// `graff login kimi.ai` / `kimi.com` pick the account's site; plain `kimi`+/// returns null and lets `chooseRegion` decide.+pub fn regionFromLoginName(name: []const u8) ?Region {+ for ([_][]const u8{ "kimi.ai", "kimi-global", "kimi-intl" }) |n| if (std.ascii.eqlIgnoreCase(name, n)) return .global;+ for ([_][]const u8{ "kimi.com", "kimi-cn" }) |n| if (std.ascii.eqlIgnoreCase(name, n)) return .cn;+ return null;+}++pub fn isLoginName(name: []const u8) bool {+ return std.ascii.eqlIgnoreCase(name, "kimi") or regionFromLoginName(name) != null;+}++fn regionOfHost(h: []const u8) ?Region {+ if (std.mem.eql(u8, h, Region.global.host())) return .global;+ if (std.mem.eql(u8, h, Region.cn.host())) return .cn;+ return null;+}++/// Same order as kimi-code: the env override, then the server the saved+/// login recorded, then a mainland-China clock or locale; everyone else is+/// global. A login from before graff recorded the server doesn't choose.+fn chooseRegion(io: Io, arena: Allocator, home: []const u8) Region {+ if (envHostRegion()) |r| return r;+ if (recordedRegion(io, arena, home)) |r| return r;+ var buf: [256]u8 = undefined;+ const n = Io.Dir.readLinkAbsolute(io, "/etc/localtime", &buf) catch 0;+ return if (inMainland(getenv("TZ"), getenv("LANG"), buf[0..n])) .cn else .global;+}++fn envHostRegion() ?Region {+ for ([_][*:0]const u8{ "KIMI_CODE_OAUTH_HOST", "KIMI_OAUTH_HOST" }) |name| {+ const v = getenv(name) orelse continue;+ if (std.mem.indexOf(u8, v, "kimi.ai") != null) return .global;+ if (std.mem.indexOf(u8, v, "kimi.com") != null) return .cn;+ }+ return null;+}++fn getenv(name: [*:0]const u8) ?[]const u8 {+ const v = std.c.getenv(name) orelse return null;+ return std.mem.span(v);+}++fn inMainland(tz: ?[]const u8, lang: ?[]const u8, localtime: []const u8) bool {+ const zones = [_][]const u8{ "Asia/Shanghai", "Asia/Urumqi", "Asia/Chongqing", "Asia/Chungking", "Asia/Harbin", "Asia/Kashgar", "PRC" };+ for (zones) |z| {+ if (tz) |t| if (std.mem.endsWith(u8, t, z)) return true;+ if (std.mem.endsWith(u8, localtime, z)) return true;+ }+ if (lang) |l| if (std.ascii.startsWithIgnoreCase(l, "zh_CN") or std.ascii.startsWithIgnoreCase(l, "zh-CN")) return true;+ return false;+}++/// POST a form body to a Kimi OAuth endpoint; return the parsed JSON object.+fn post(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_buf: [5]std.http.Header = undefined;+ const identity = kimi_catalog.identityHeaders(&identity_buf);+ _ = try client.fetch(.{+ .location = .{ .url = url },+ .method = .POST,+ .payload = body,+ .response_writer = &aw.writer,+ .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;+ return v.object;+}++fn endpoint(arena: Allocator, host: []const u8, path: []const u8) []const u8 {+ return std.fmt.allocPrint(arena, "{s}{s}", .{ host, path }) catch "";+}++pub fn authPath(arena: Allocator, home: []const u8) []const u8 {+ return credential_store.oauthPath(arena, home, ".kimi");+}++pub fn writeAuth(io: Io, arena: Allocator, home: []const u8, access: []const u8, refresh: []const u8, expires_at: i64, host: []const u8) !void {+ return credential_store.writeOAuthFrom(io, arena, home, ".kimi", access, refresh, expires_at, host);+}++fn readSaved(io: Io, arena: Allocator, home: []const u8) ?std.json.ObjectMap {+ const data = Io.Dir.cwd().readFileAlloc(io, authPath(arena, home), arena, .limited(64 * 1024)) catch return null;+ const v = std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always }) catch return null;+ return if (v == .object) v.object else null;+}++/// The server that issued the saved login. Only a known Kimi server counts:+/// the refresh token is sent there.+fn savedHost(io: Io, arena: Allocator, home: []const u8) ?[]const u8 {+ const saved = readSaved(io, arena, home) orelse return null;+ const h = strFieldObj(saved, "oauth_host") orelse return legacy_host;+ return if (regionOfHost(h) != null) h else legacy_host;+}++fn recordedRegion(io: Io, arena: Allocator, home: []const u8) ?Region {+ const saved = readSaved(io, arena, home) orelse return null;+ return regionOfHost(strFieldObj(saved, "oauth_host") orelse return null);+}++fn intField(obj: std.json.ObjectMap, name: []const u8, default: i64) i64 {+ const v = obj.get(name) orelse return default;+ return if (v == .integer) v.integer else default;+}++/// `graff login kimi`: prints a verification URL + user code, copies the URL,+/// opens the browser, polls until the user authorizes, then stores the+/// access/refresh token. `region` null = choose (see chooseRegion).+pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, region: ?Region) !void {+ var obuf: [4096]u8 = undefined;+ var ow = Io.File.stdout().writer(io, &obuf);+ const out = &ow.interface;+ const r = region orelse chooseRegion(io, arena, home);+ const host = r.host();++ const da_body = try std.fmt.allocPrint(arena, "client_id={s}", .{client_id});+ const da = post(io, gpa, arena, endpoint(arena, host, "/api/oauth/device_authorization"), da_body) catch |err| {+ try out.print("✗ Kimi device authorization failed: {t}\n", .{err});+ try out.flush();+ return;+ };+ if (da.get("error")) |e| {+ try out.print("✗ {s}\n", .{if (e == .string) e.string else "device authorization error"});+ try out.flush();+ return;+ }+ const device_code = strFieldObj(da, "device_code") orelse return error.BadOAuthResponse;+ const user_code = strFieldObj(da, "user_code") orelse "";+ const verify = strFieldObj(da, "verification_uri_complete") orelse strFieldObj(da, "verification_uri") orelse "";+ var interval: i64 = @max(intField(da, "interval", 5), 1);+ const lifetime: i64 = std.math.clamp(intField(da, "expires_in", 900), 60, 1800);++ const opens = signin_link.opensBrowser();+ try out.print("\nTo log in to Kimi on {s}, open this URL ({s}):\n\n {s}\n", .{+ r.site(), if (opens) "browser should open automatically" else "on any device", verify,+ });+ try signin_link.offer(io, out, verify);+ try out.print("\nand confirm the code: {s}\n\nwaiting for authorization… (the code expires in {d} min)\n", .{ user_code, @divTrunc(lifetime + 59, 60) });+ try out.print("Account on {s}? Run `graff login {s}` instead.\n", .{ r.other().site(), r.other().site() });+ try out.flush();+ signin_link.open(io, verify);++ const poll_body = try std.fmt.allocPrint(arena, "client_id={s}&device_code={s}&grant_type=urn:ietf:params:oauth:grant-type:device_code", .{ client_id, device_code });+ const token_url = endpoint(arena, host, "/api/oauth/token");+ const deadline = @divTrunc(unixMs(io), 1000) + lifetime;+ var failures: usize = 0;+ while (@divTrunc(unixMs(io), 1000) < deadline) {+ io.sleep(Io.Duration.fromSeconds(interval), .awake) catch {};+ const resp = post(io, gpa, arena, token_url, poll_body) catch |err| {+ failures += 1;+ if (failures >= 6) {+ try out.print("✗ can't reach {s}: {t}\n", .{ host, err });+ try out.flush();+ return;+ }+ if (failures == 1) {+ try out.print(" can't reach {s} ({t}), still trying…\n", .{ host, err });+ try out.flush();+ }+ continue;+ };+ failures = 0;+ if (resp.get("access_token")) |a| if (a == .string and a.string.len > 0) {+ const refresh = strFieldObj(resp, "refresh_token") orelse "";+ const expires_in = intField(resp, "expires_in", 900);+ try writeAuth(io, arena, home, a.string, refresh, @divTrunc(unixMs(io), 1000) + expires_in, host);+ _ = kimi_catalog.load(io, gpa, arena, a.string);+ try out.print("✓ logged into Kimi ({s}) — wrote {s}. /model kimi selects {s}\n", .{+ r.site(), authPath(arena, home), pricing.providerDefaultModel("kimi", "k3"),+ });+ try out.flush();+ return;+ };+ const msg = strFieldObj(resp, "error") orelse "";+ if (std.mem.eql(u8, msg, "authorization_pending")) continue;+ // RFC 8628 §3.5: every slow_down adds 5 seconds for the rest of the poll.+ if (std.mem.eql(u8, msg, "slow_down")) {+ interval += 5;+ continue;+ }+ if (std.mem.eql(u8, msg, "expired_token")) break;+ if (std.mem.eql(u8, msg, "access_denied")) {+ try out.print("✗ sign-in was declined on {s}\n", .{r.site()});+ try out.flush();+ return;+ }+ if (msg.len > 0) {+ try out.print("✗ {s}\n", .{strFieldObj(resp, "error_description") orelse msg});+ try out.flush();+ return;+ }+ }+ try out.writeAll("✗ the code expired — run `graff login kimi` again\n");+ try out.flush();+}++/// Reads the stored Kimi OAuth access token, refreshing it in place when within+/// the refresh margin of expiry. Returns null if not logged in. Mirrors+/// loadCodexAuth. `stale` is the token that just 401'd (null when not+/// recovering from one) — see supersededToken.+pub fn load(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {+ const saved = readSaved(io, arena, home) orelse return null;+ const access = strFieldObj(saved, "access_token") orelse return null;+ const expires_at = intField(saved, "expires_at", 0);+ // #245: another concurrent refresher may already have replaced the token that+ // 401'd; re-minting would rotate-kill theirs. Adopt what is on disk instead.+ if (supersededToken(force, access, stale)) return access;+ if (force or (expires_at != 0 and @divTrunc(unixMs(io), 1000) >= expires_at - oauth_refresh_margin_s)) {+ if (strFieldObj(saved, "refresh_token")) |refresh| {+ const host = savedHost(io, arena, home) orelse legacy_host;+ const body = std.fmt.allocPrint(arena, "client_id={s}&grant_type=refresh_token&refresh_token={s}", .{ client_id, refresh }) catch return access;+ const resp = post(io, gpa, arena, endpoint(arena, host, "/api/oauth/token"), 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 = intField(resp, "expires_in", 900);+ writeAuth(io, arena, home, a.string, new_refresh, @divTrunc(unixMs(io), 1000) + expires_in, host) catch {};+ return a.string;+ };+ }+ }+ return access;+}++test "login names pick the Kimi site" {+ try std.testing.expectEqual(Region.global, regionFromLoginName("kimi.ai").?);+ try std.testing.expectEqual(Region.cn, regionFromLoginName("Kimi.com").?);+ try std.testing.expect(regionFromLoginName("kimi") == null);+ try std.testing.expect(isLoginName("kimi") and isLoginName("kimi.ai") and !isLoginName("kimix"));+ try std.testing.expectEqualStrings("https://auth.kimi.ai", Region.global.host());+}++test "mainland clock or locale picks kimi.com; everyone else kimi.ai" {+ try std.testing.expect(inMainland(null, null, "/var/db/timezone/zoneinfo/Asia/Shanghai"));+ try std.testing.expect(inMainland("Asia/Urumqi", null, ""));+ try std.testing.expect(inMainland(null, "zh_CN.UTF-8", ""));+ try std.testing.expect(!inMainland(null, "zh_TW.UTF-8", "/usr/share/zoneinfo/Asia/Taipei"));+ try std.testing.expect(!inMainland("Asia/Singapore", "en_US.UTF-8", "/usr/share/zoneinfo/Asia/Singapore"));+}++test "a login keeps the server that issued it; old logins and unknown hosts mean kimi.com" {+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const home = try std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}", .{&tmp.sub_path});+ const far_future: i64 = 4102444800;++ try std.testing.expect(savedHost(io, arena, home) == null);+ try writeAuth(io, arena, home, "a", "r", far_future, Region.global.host());+ try std.testing.expectEqualStrings("https://auth.kimi.ai", savedHost(io, arena, home).?);+ try std.testing.expectEqual(Region.global, recordedRegion(io, arena, home).?);+ try writeAuth(io, arena, home, "a", "r", far_future, "");+ try std.testing.expectEqualStrings(legacy_host, savedHost(io, arena, home).?);+ try std.testing.expect(recordedRegion(io, arena, home) == null);+ try writeAuth(io, arena, home, "a", "r", far_future, "https://evil.example");+ try std.testing.expectEqualStrings(legacy_host, savedHost(io, arena, home).?);+ try std.testing.expectEqualStrings("a", load(io, std.testing.allocator, arena, home, false, null).?);+}diff --git a/src/oauth_zai.zig b/src/oauth_zai.zigindex 48756736..a0aae5b4 100644--- a/src/oauth_zai.zig+++ b/src/oauth_zai.zig@@ -14,7 +14,7 @@ const style = &@import("ansi.zig").style;const util = @import("util.zig");const strFieldObj = util.strFieldObj;const intFieldObj = util.intFieldObj;-const openBrowser = @import("oauth_helpers.zig").openBrowser;+const signin_link = @import("signin_link.zig");const credential_store = @import("credential_store.zig");const provider_mod = @import("provider.zig");const credential_failover = @import("credential_failover.zig");@@ -352,9 +352,11 @@ pub fn login(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {return;};- try out.print("\nTo log in to Z.AI Coding Plan, open this URL (browser should open automatically):\n\n {s}\n\nwaiting for authorization\xe2\x80\xa6\n", .{init.authorize_url});+ try out.print("\nTo log in to Z.AI Coding Plan, open this URL (browser should open automatically):\n\n {s}\n", .{init.authorize_url});+ try signin_link.offer(io, out, init.authorize_url);+ try out.writeAll("\nwaiting for authorization\xe2\x80\xa6\n");try out.flush();- if (!main_mod.g_no_browser) openBrowser(io, init.authorize_url);+ signin_link.open(io, init.authorize_url);const poll_url = try std.fmt.allocPrint(arena, "{s}/oauth/cli/poll/{s}", .{ cli_base, init.flow_id });var ready: ?ReadyData = null;diff --git a/src/picker_auth.zig b/src/picker_auth.zigindex 3e8d0e88..9b0a19f8 100644--- a/src/picker_auth.zig+++ b/src/picker_auth.zig@@ -325,7 +325,7 @@ pub fn offerProviderAuth(return;};} else if (std.mem.eql(u8, pid, "kimi")) {- oauth.kimiLogin(root.io, root.gpa, arena, home) catch |err| {+ oauth.kimiLogin(root.io, root.gpa, arena, home, null) catch |err| {try out.print("\xe2\x9c\x97 kimi login failed: {t}\n", .{err});try out.flush();return;diff --git a/src/signin_link.zig b/src/signin_link.zignew file mode 100644index 00000000..f4ab494a--- /dev/null+++ b/src/signin_link.zig@@ -0,0 +1,114 @@+//! A sign-in link the user can paste anywhere. Device logins print the+//! link and open a browser; on a terminal graff also puts the link on the+//! clipboard, so signing in from another browser or machine is one paste.+//! Over SSH the clipboard that matters is the user's own, so the link goes+//! to the terminal (OSC 52) rather than the remote machine's pasteboard.+//! Piped output (Harness, scripts) is left alone: the caller shows the link.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;++pub const Copied = enum { clipboard, terminal, none };++/// Copy `url` when stdout is a terminal. Never fails the login.+pub fn copy(io: Io, url: []const u8) Copied {+ if (url.len == 0 or url.len > 4096) return .none;+ if (!(Io.File.stdout().isTty(io) catch false)) return .none;+ if (overSsh()) return if (osc52(io, url)) .terminal else .none;+ var buf: [3][]const u8 = undefined;+ const argv = copierArgv(builtin.os.tag, hasEnv("WAYLAND_DISPLAY"), hasEnv("DISPLAY"), &buf) orelse return .none;+ return if (pipeTo(io, argv, url)) .clipboard else .none;+}++/// The line that follows the link, or "" when nothing was copied. No `✓`:+/// Harness reads a `✓` line as the finished login.+pub fn note(copied: Copied) []const u8 {+ return switch (copied) {+ .clipboard => " (copied to your clipboard)\n",+ .terminal => " (sent to your terminal's clipboard)\n",+ .none => "",+ };+}++/// After the link line: copy it and say so.+pub fn offer(io: Io, out: *Io.Writer, url: []const u8) !void {+ try out.flush();+ try out.writeAll(note(copy(io, url)));+ try out.flush();+}++/// Open the browser unless the user can't see it (GRAFF_NO_BROWSER, SSH).+pub fn open(io: Io, url: []const u8) void {+ if (opensBrowser()) @import("oauth_helpers.zig").openBrowser(io, url);+}++pub fn opensBrowser() bool {+ return !@import("main.zig").g_no_browser and !overSsh();+}++/// Is graff running on a machine the user reached over SSH? A browser+/// opened there is one the user can't see.+pub fn overSsh() bool {+ return hasEnv("SSH_TTY") or hasEnv("SSH_CONNECTION");+}++fn hasEnv(name: [*:0]const u8) bool {+ const v = std.c.getenv(name) orelse return false;+ return std.mem.span(v).len > 0;+}++fn copierArgv(os: std.Target.Os.Tag, wayland: bool, x11: bool, buf: *[3][]const u8) ?[]const []const u8 {+ const parts: []const []const u8 = switch (os) {+ .macos => &.{"pbcopy"},+ .windows => &.{"clip.exe"},+ else => if (wayland) &.{"wl-copy"} else if (x11) &.{ "xclip", "-selection", "clipboard" } else return null,+ };+ @memcpy(buf[0..parts.len], parts);+ return buf[0..parts.len];+}++fn pipeTo(io: Io, argv: []const []const u8, text: []const u8) bool {+ var child = std.process.spawn(io, .{ .argv = argv, .stdin = .pipe, .stdout = .ignore, .stderr = .ignore }) catch return false;+ {+ var wbuf: [512]u8 = undefined;+ var w = child.stdin.?.writerStreaming(io, &wbuf);+ w.interface.writeAll(text) catch {};+ w.interface.flush() catch {};+ child.stdin.?.close(io);+ child.stdin = null;+ }+ const term = child.wait(io) catch return false;+ return switch (term) {+ .exited => |code| code == 0,+ else => false,+ };+}++fn osc52(io: Io, url: []const u8) bool {+ var enc: [std.base64.standard.Encoder.calcSize(4096)]u8 = undefined;+ var obuf: [64]u8 = undefined;+ var ow = Io.File.stdout().writer(io, &obuf);+ const w = &ow.interface;+ w.writeAll("\x1b]52;c;") catch return false;+ w.writeAll(std.base64.standard.Encoder.encode(&enc, url)) catch return false;+ w.writeAll("\x07") catch return false;+ w.flush() catch return false;+ return true;+}++test "copierArgv picks the platform's clipboard tool" {+ var buf: [3][]const u8 = undefined;+ try std.testing.expectEqualDeep(@as([]const []const u8, &.{"pbcopy"}), copierArgv(.macos, false, false, &buf).?);+ try std.testing.expectEqualDeep(@as([]const []const u8, &.{"clip.exe"}), copierArgv(.windows, false, false, &buf).?);+ try std.testing.expectEqualDeep(@as([]const []const u8, &.{"wl-copy"}), copierArgv(.linux, true, true, &buf).?);+ try std.testing.expectEqualDeep(@as([]const []const u8, &.{ "xclip", "-selection", "clipboard" }), copierArgv(.linux, false, true, &buf).?);+ try std.testing.expect(copierArgv(.linux, false, false, &buf) == null);+}++test "note never claims a finished login" {+ for ([_]Copied{ .clipboard, .terminal, .none }) |c| {+ try std.testing.expect(std.mem.indexOf(u8, note(c), "\xe2\x9c\x93") == null);+ }+ try std.testing.expectEqualStrings("", note(.none));+}diff --git a/src/startup.zig b/src/startup.zigindex 8e63ce82..670d25de 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -335,7 +335,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process// args.loginTarget owns the names.if (flags.login_flag) {const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});- if (flags.anthropic_console_login) try @import("anthropic_profile.zig").login(io, arena, init.environ_map, home) else if (flags.anthropic_login) try @import("oauth_anthropic.zig").login(io, gpa, arena, home, flags.refresh_flag) else if (flags.chatgpt_login) try @import("oauth_chatgpt.zig").login(io, gpa, arena, home) else if (flags.xai_login) try oauth.xaiLogin(io, gpa, arena, home) else if (flags.kimi_login) try oauth.kimiLogin(io, gpa, arena, home) else if (flags.zai_login) try oauth.zaiLogin(io, gpa, arena, home) else if (flags.codex_login or flags.refresh_flag) try oauth.codexLogin(io, gpa, arena, home, flags.refresh_flag) else try oauth.codegraffLogin(io, gpa, arena, home);+ if (flags.anthropic_console_login) try @import("anthropic_profile.zig").login(io, arena, init.environ_map, home) else if (flags.anthropic_login) try @import("oauth_anthropic.zig").login(io, gpa, arena, home, flags.refresh_flag) else if (flags.chatgpt_login) try @import("oauth_chatgpt.zig").login(io, gpa, arena, home) else if (flags.xai_login) try oauth.xaiLogin(io, gpa, arena, home) else if (flags.kimi_login) try oauth.kimiLogin(io, gpa, arena, home, flags.kimi_region) else if (flags.zai_login) try oauth.zaiLogin(io, gpa, arena, home) else if (flags.codex_login or flags.refresh_flag) try oauth.codexLogin(io, gpa, arena, home, flags.refresh_flag) else try oauth.codegraffLogin(io, gpa, arena, home);return true;}