Skip to content

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

Python

feat: graff login zai for GLM Coding Plan

justrach5aa44d519d25
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e98df70..42f57536 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ current is part of cutting a release.
## Unreleased
+- `graff login zai` (aliases `glm`, `z.ai`) signs in to a Z.AI Coding Plan and routes chat to `/api/coding/paas/v4` without `ZAI_CODING=1` (ADR 0151).
- Native: clickable browser/chat links, folder-picker repeat submissions, composer history recall layout, prompt-history session/attachment scoping, saved-snapshot reopen, worktree path wrapping. Shutdown-fixture stalls dump renderer/backend/worker state (#1080, #1103, #1105, #1108, #1109, #1112, #1113).
## v0.0.302.1
diff --git a/README.md b/README.md
index 45899090..0ed23c59 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,7 @@ graff -p "Explain this project" # ask a single question
```sh
graff login kimi
+graff login zai
graff login codex
graff key set deepseek sk-...
graff --model grok-4.6
@@ -206,7 +207,7 @@ for await (const ev of runAgent({ prompt: "summarize README.md", yolo: true }))
```
graff [flags] REPL
graff -p "prompt" one-shot (answer on stdout)
-graff login [codegraff|codex|kimi]
+graff login [codegraff|codex|kimi|xai|zai]
graff key set <provider> <key>
graff mcp add <name> -- <cmd>
graff learn <command>
diff --git a/docs/adr/0151-zai-coding-plan-login.md b/docs/adr/0151-zai-coding-plan-login.md
new file mode 100644
index 00000000..28e6e3a5
--- /dev/null
+++ b/docs/adr/0151-zai-coding-plan-login.md
@@ -0,0 +1,32 @@
+# 0151. Z.AI Coding Plan login is a Graff-named API key on the coding host
+
+Status: accepted 2026-09-21
+
+## Context
+
+Z.AI pay-go keys hit `https://api.z.ai/api/paas/v4`. A GLM Coding Plan key has
+to hit `/api/coding/paas/v4`, which until now required `ZAI_CODING=1` or
+`GRAFF_ZAI_URL` after pasting a key.
+
+[zai-org/ZCode](https://github.com/zai-org/ZCode) publishes a CLI OAuth broker
+at `https://zcode.z.ai/api/v1/oauth/cli/{init,poll}` that turns a browser login
+into a Z.AI OAuth access token, then provisions a business API key.
+
+## Decision
+
+- `graff login zai` (aliases `glm`, `z.ai`) is a `ProviderSpec.login = .zai_cli`
+ `sub_login`, same class as Kimi Code and SuperGrok.
+- The CLI broker is public, like the Codex and Kimi clients graff already uses.
+ User-Agent stays `graff/<version>`. The provisioned key is named
+ `graff-api-key`, not `zcode-api-key`, so a ZCode login and a Graff login do
+ not share or revoke each other.
+- Chat uses the provisioned `apiKey.secretKey` on `/api/coding/paas/v4`.
+ A successful login persists that routing; `ZAI_CODING=1` is no longer required.
+ `GRAFF_ZAI_URL` still wins.
+- Metered `ZAI_API_KEY` remains the pay-go seat and is parked when a plan login
+ exists (`credential_failover.preferPlan`).
+
+## Cost
+
+The broker can lock to the ZCode app. Fallback stays `ZAI_API_KEY` plus
+`ZAI_CODING=1`. China BigModel (`zcode login bigmodel`) is not this record.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index ff1e079d..125ca524 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -170,6 +170,7 @@ record only when you need the evidence or the edge cases.
| [0148](0148-read-file-miss-storm-stops.md) | After N same-prefix or incrementing `read_file` misses, refuse further guesses this turn and point at `codedb list_dir`. |
| [0149](0149-daddy-directives-are-explicit-control.md) | Ambient `[peer]` wakes are not a new task; `[daddy]` directives are explicit supervisor control. |
| [0150](0150-subagent-briefs-are-structured.md) | Child briefs are headed sections plus a harness environment header; the judge stays a bare prompt. |
+| [0151](0151-zai-coding-plan-login.md) | Z.AI Coding Plan is a `sub_login` like Kimi/xAI: `graff login zai` uses ZCode's public CLI OAuth broker, then provisions a Graff-named API key onto `/api/coding/paas/v4`. |
## When to write one
diff --git a/gui/src/components/providers-settings/utils/providerAuth.ts b/gui/src/components/providers-settings/utils/providerAuth.ts
index af742720..9364a908 100644
--- a/gui/src/components/providers-settings/utils/providerAuth.ts
+++ b/gui/src/components/providers-settings/utils/providerAuth.ts
@@ -12,6 +12,8 @@ function getAuthMethodPriority(method: ProviderAuthMethod) {
case "codex_device":
case "codegraff_device":
case "kimi_device":
+ case "xai_device":
+ case "zai_cli":
return 1;
case "google_adc":
return 2;
@@ -30,7 +32,7 @@ export function getSortedAuthMethods(provider: ProviderSummary) {
export function supportsOauth(provider: ProviderSummary) {
return provider.authMethods.some((method) =>
- ["o_auth_code", "o_auth_device", "codex_device", "codegraff_device", "kimi_device"].includes(method.kind),
+ ["o_auth_code", "o_auth_device", "codex_device", "codegraff_device", "kimi_device", "xai_device", "zai_cli"].includes(method.kind),
);
}
diff --git a/gui/src/services/desktop/types/contracts.generated.ts b/gui/src/services/desktop/types/contracts.generated.ts
index 70f1cf64..93b0cc2d 100644
--- a/gui/src/services/desktop/types/contracts.generated.ts
+++ b/gui/src/services/desktop/types/contracts.generated.ts
@@ -77,7 +77,7 @@ fastApplies: boolean, };
export type UpdatePromptSettingsInput = { workspacePath: string | null, providerId: string, modelId: string, reasoningEffort: string | null, };
-export type ProviderAuthMethodKind = "api_key" | "o_auth_device" | "o_auth_code" | "google_adc" | "aws_profile" | "codex_device" | "codegraff_device" | "kimi_device";
+export type ProviderAuthMethodKind = "api_key" | "o_auth_device" | "o_auth_code" | "google_adc" | "aws_profile" | "codex_device" | "codegraff_device" | "kimi_device" | "xai_device" | "zai_cli";
export type ProviderAuthMethod = { kind: ProviderAuthMethodKind, label: string, };
diff --git a/lean-proofs/Graff/Provider.lean b/lean-proofs/Graff/Provider.lean
index 2d28eae8..85939dff 100644
--- a/lean-proofs/Graff/Provider.lean
+++ b/lean-proofs/Graff/Provider.lean
@@ -23,6 +23,7 @@ inductive Login where
| codexDevice
| kimiDevice
| xaiDevice
+ | zaiCli
deriving DecidableEq, Repr, BEq
inductive Catalog where
@@ -58,7 +59,7 @@ def specs : List Row :=
, { id := "kimi", kind := .openai, auth := .bearer, login := .kimiDevice, catalog := .kimi, subLogin := true }
, { id := "moonshot", kind := .openai, auth := .bearer }
, { id := "xai", kind := .openai, auth := .bearer, login := .xaiDevice, catalog := .openai, subLogin := true }
- , { id := "zai", kind := .openai, auth := .bearer, catalog := .openai, takesEffort := true }
+ , { id := "zai", kind := .openai, auth := .bearer, login := .zaiCli, catalog := .openai, subLogin := true, takesEffort := true }
, { id := "meta", kind := .openai, auth := .bearer, catalog := .openai, takesEffort := true }
, { id := "vercel", kind := .openai, auth := .bearer, catalog := .openai, takesEffort := true }
, { id := "openrouter", kind := .openai, auth := .bearer, catalog := .openai, takesEffort := true }
diff --git a/spec/kernels/providers.json b/spec/kernels/providers.json
index 1a3282f2..32efb0c0 100644
--- a/spec/kernels/providers.json
+++ b/spec/kernels/providers.json
@@ -132,9 +132,9 @@
"id": "zai",
"kind": "openai",
"auth": "bearer",
- "login": "api_key",
+ "login": "zai_cli",
"catalog": "openai",
- "sub_login": false,
+ "sub_login": true,
"takes_effort": true
},
{
diff --git a/spec/ref/provider.py b/spec/ref/provider.py
index 07e75292..a73753a0 100644
--- a/spec/ref/provider.py
+++ b/spec/ref/provider.py
@@ -6,7 +6,7 @@ from typing import Literal
Kind = Literal["anthropic", "openai", "responses", "interactions"]
Auth = Literal["x_api_key", "bearer", "goog_api_key"]
-Login = Literal["api_key", "codegraff_device", "codex_device", "kimi_device", "xai_device"]
+Login = Literal["api_key", "codegraff_device", "codex_device", "kimi_device", "xai_device", "zai_cli"]
Catalog = Literal["baked", "codex", "kimi", "openai", "anthropic"]
@@ -45,7 +45,7 @@ SPECS: list[dict] = [
row("kimi", "openai", "bearer", login="kimi_device", catalog="kimi", sub_login=True),
row("moonshot", "openai", "bearer"),
row("xai", "openai", "bearer", login="xai_device", catalog="openai", sub_login=True),
- row("zai", "openai", "bearer", catalog="openai", takes_effort=True),
+ row("zai", "openai", "bearer", login="zai_cli", catalog="openai", sub_login=True, takes_effort=True),
row("meta", "openai", "bearer", catalog="openai", takes_effort=True),
row("vercel", "openai", "bearer", catalog="openai", takes_effort=True),
row("openrouter", "openai", "bearer", catalog="openai", takes_effort=True),
diff --git a/src/args.zig b/src/args.zig
index aee342a6..351e073c 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -43,6 +43,7 @@ pub const Flags = struct {
codex_login: bool = false,
kimi_login: bool = false,
xai_login: bool = false,
+ zai_login: bool = false,
help_flag: bool = false,
version_flag: bool = false,
print_flag: bool = false,
@@ -257,6 +258,7 @@ pub fn parse(init: std.process.Init) !Flags {
if (flags.positionals.items.len > 1 and std.mem.eql(u8, flags.positionals.items[1], "codex")) flags.codex_login = true;
if (flags.positionals.items.len > 1 and std.mem.eql(u8, flags.positionals.items[1], "kimi")) flags.kimi_login = true;
if (flags.positionals.items.len > 1 and std.mem.eql(u8, flags.positionals.items[1], "xai")) flags.xai_login = true;
+ if (flags.positionals.items.len > 1 and @import("oauth_zai.zig").isLoginName(flags.positionals.items[1])) flags.zai_login = true;
}
// One-shot print mode: `harness -p "prompt"` or a bare positional prompt
diff --git a/src/cli.zig b/src/cli.zig
index a54a2063..63bca8cc 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -320,6 +320,7 @@ pub const usage_text =
\\ graff login codex [--refresh] ChatGPT/Codex OAuth login (PKCE)
\\ graff login kimi Kimi Code OAuth login (device-code)
\\ 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)
\\ graff key list show which providers have keys
\\ graff models [refresh] list the live catalog; refresh Codex + models.dev metadata
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index a2631752..15435de4 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -52,7 +52,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|codex|kimi]", .desc = "OAuth sign-in (no key to paste); bare opens a picker (codex alias: oai)" },
+ .{ .name = "/login", .usage = "/login [codegraff|codex|kimi|xai|zai]", .desc = "OAuth sign-in (no key to paste); bare opens a picker (codex alias: oai; zai aliases: glm, z.ai)" },
.{ .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.zig
index c3383d88..23e511b4 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -354,6 +354,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
.{ .name = "codex", .desc = "ChatGPT / OpenAI sign-in (alias: oai)" },
.{ .name = "kimi", .desc = "Kimi Code sign-in (device-code OAuth)" },
.{ .name = "xai", .desc = "Grok / SuperGrok sign-in (device-code OAuth)" },
+ .{ .name = "zai", .desc = "Z.AI Coding Plan sign-in (CLI OAuth)" },
};
// Bare /login: pick a provider on a TTY, else just list the options.
if (target.len == 0) {
@@ -374,6 +375,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
target = "codex";
if (std.mem.eql(u8, target, "graff")) target = "codegraff";
if (std.mem.eql(u8, target, "grok")) target = "xai";
+ if (@import("oauth_zai.zig").isLoginName(target)) target = "zai";
const home = root.home;
try out.flush(); // hand stdout to the login flow's own writer
@@ -401,6 +403,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
};
+ } else if (std.mem.eql(u8, target, "zai")) {
+ oauth.zaiLogin(root.io, root.gpa, arena, home) catch |err| {
+ try out.print("\xe2\x9c\x97 zai login failed: {t}\n", .{err});
+ try out.flush();
+ return true;
+ };
} else {
// A pure API-key provider, or something unrecognized.
if (provider_mod.specFor(target) != null) {
@@ -408,7 +416,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
}
- try out.print("can't log into '{s}' \xe2\x80\x94 try /login codegraff | codex | kimi | xai (others: /key <provider> <key>)\n", .{target});
+ try out.print("can't log into '{s}' \xe2\x80\x94 try /login codegraff | codex | kimi | xai | zai (others: /key <provider> <key>)\n", .{target});
try out.flush();
return true;
}
diff --git a/src/credential_failover.zig b/src/credential_failover.zig
index 25d4a078..0a73d3d5 100644
--- a/src/credential_failover.zig
+++ b/src/credential_failover.zig
@@ -77,10 +77,10 @@ pub fn promote(provider_id: []const u8) ?Promotion {
/// startup.resolveKeys, which owns the "is this provider even in play"
/// gate (#274 — a login refresh is a synchronous network call).
///
-/// Only kimi and xai reach the load here: codegraff's device login is not a
-/// flat-rate plan (`sub_login = false`), and codex is resolved earlier because
-/// its `env_key` is the CODEX_DISABLED sentinel, so it has no metered key to
-/// outrank in the first place.
+/// Only kimi, xai, and zai reach the load here: codegraff's device login is
+/// not a flat-rate plan (`sub_login = false`), and codex is resolved earlier
+/// because its `env_key` is the CODEX_DISABLED sentinel, so it has no metered
+/// key to outrank in the first place.
pub fn preferPlan(
io: std.Io,
gpa: std.mem.Allocator,
@@ -95,6 +95,7 @@ pub fn preferPlan(
const token = switch (spec.login) {
.kimi_device => oauth.loadKimiOAuth(io, gpa, arena, home, false, null),
.xai_device => oauth.loadXaiOAuth(io, gpa, arena, home, false, null),
+ .zai_cli => oauth.loadZaiOAuth(io, gpa, arena, home, false, null),
else => null,
} orelse return;
if (value.*) |metered| park(spec.id, metered, source.*);
diff --git a/src/help.zig b/src/help.zig
index 46d539f7..9e9ac46a 100644
--- a/src/help.zig
+++ b/src/help.zig
@@ -62,7 +62,7 @@ pub fn render(out: *Io.Writer) !void {
\\esc during a response interrupts the turn; streamed output remains in history.
\\"always allow" answers persist to .harness/settings.json in the cwd.
\\launch flags: --model <name> · --yolo · -p "prompt" · --json · --help · --version
- \\subcommands: graff login [codex] · graff key set <provider> <key> · graff --schema
+ \\subcommands: graff login [codex|kimi|xai|zai] · graff key set <provider> <key> · graff --schema
\\
);
}
diff --git a/src/oauth.zig b/src/oauth.zig
index f9586ccd..70c81489 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -32,6 +32,7 @@ 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");
pub const CodexAuth = struct { token: []const u8, account: []const u8 };
@@ -495,6 +496,8 @@ pub fn loadXaiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8,
pub const codegraffLogin = codegraff.login;
pub const loadCodegraffKey = codegraff.loadKey;
+pub const zaiLogin = zai.login;
+pub const loadZaiOAuth = zai.loadZaiOAuth;
test "b64url: url-safe base64 without padding" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
diff --git a/src/oauth_zai.zig b/src/oauth_zai.zig
new file mode 100644
index 00000000..48756736
--- /dev/null
+++ b/src/oauth_zai.zig
@@ -0,0 +1,539 @@
+//! Z.AI Coding Plan login. Uses ZCode's public CLI OAuth broker, then
+//! provisions a Graff-named API key onto `/api/coding/paas/v4`.
+//!
+//! Identity stays `graff/<version>`. The provisioned key is named
+//! `graff-api-key`, not `zcode-api-key` (ADR 0151).
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+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 credential_store = @import("credential_store.zig");
+const provider_mod = @import("provider.zig");
+const credential_failover = @import("credential_failover.zig");
+const main_mod = @import("main.zig");
+
+const user_agent = "graff/" ++ @import("build_options").version;
+const cli_base = "https://zcode.z.ai/api/v1";
+const biz_host = "https://api.z.ai";
+const default_org_name = "默认机构";
+const default_project_name = "默认项目";
+
+pub const api_key_name = "graff-api-key";
+pub const oauth_dir = ".zai";
+
+pub const InitData = struct {
+ authorize_url: []const u8,
+ flow_id: []const u8,
+ expires_at: i64,
+ poll_interval_sec: i64,
+};
+
+pub const ReadyData = struct {
+ access_token: []const u8,
+ refresh_token: []const u8,
+ jwt: []const u8,
+};
+
+pub const PollStatus = union(enum) {
+ pending,
+ failed,
+ ready: ReadyData,
+};
+
+pub const OrgProject = struct {
+ organization_id: []const u8,
+ project_id: []const u8,
+};
+
+pub const KeySummary = struct {
+ name: []const u8,
+ api_key: []const u8,
+};
+
+pub fn isLoginName(name: []const u8) bool {
+ return std.mem.eql(u8, name, "zai") or std.mem.eql(u8, name, "glm") or std.mem.eql(u8, name, "z.ai");
+}
+
+/// Env `GRAFF_ZAI_URL` / `ZAI_CODING` win; a coding-plan login otherwise
+/// pins the coding host so the next process does not need `ZAI_CODING=1`.
+pub fn applyCodingOverride() void {
+ if (provider_mod.g_zai_url_override != null) return;
+ provider_mod.g_zai_url_override = provider_mod.zai_coding_url;
+}
+
+pub fn currentZaiUrl() []const u8 {
+ return provider_mod.g_zai_url_override orelse "https://api.z.ai/api/paas/v4/chat/completions";
+}
+
+fn authPath(arena: Allocator, home: []const u8) []const u8 {
+ return credential_store.oauthPath(arena, home, oauth_dir);
+}
+
+fn unwrapData(v: Value) !Value {
+ if (v != .object) return error.BadOAuthResponse;
+ if (!isSuccessfulRemoteCode(v.object.get("code"))) return error.BadOAuthResponse;
+ return v.object.get("data") orelse error.BadOAuthResponse;
+}
+
+fn asObject(v: Value) !std.json.ObjectMap {
+ if (v != .object) return error.BadOAuthResponse;
+ return v.object;
+}
+
+pub fn isSuccessfulRemoteCode(code: ?Value) bool {
+ const c = code orelse return true;
+ return switch (c) {
+ .integer => |i| i == 0 or i == 200,
+ .string => |s| std.mem.eql(u8, s, "0") or std.mem.eql(u8, s, "200"),
+ .null => true,
+ else => false,
+ };
+}
+
+pub fn parseInitData(data: std.json.ObjectMap) !InitData {
+ const url = strFieldObj(data, "authorize_url") orelse return error.BadOAuthResponse;
+ if (!std.mem.startsWith(u8, url, "https://")) return error.BadOAuthResponse;
+ const flow_id = strFieldObj(data, "flow_id") orelse return error.BadOAuthResponse;
+ if (flow_id.len == 0) return error.BadOAuthResponse;
+ const expires_at = intFieldObj(data, "expires_at", 0);
+ if (expires_at <= 0) return error.BadOAuthResponse;
+ const interval = intFieldObj(data, "poll_interval_sec", 0);
+ if (interval < 1) return error.BadOAuthResponse;
+ return .{ .authorize_url = url, .flow_id = flow_id, .expires_at = expires_at, .poll_interval_sec = interval };
+}
+
+pub fn parsePollData(data: std.json.ObjectMap) !PollStatus {
+ const status = strFieldObj(data, "status") orelse return error.BadOAuthResponse;
+ if (std.mem.eql(u8, status, "pending")) return .pending;
+ if (std.mem.eql(u8, status, "failed")) return .failed;
+ if (!std.mem.eql(u8, status, "ready")) return error.BadOAuthResponse;
+ const jwt = strFieldObj(data, "token") orelse return error.BadOAuthResponse;
+ const provider = data.get("zai") orelse return error.BadOAuthResponse;
+ if (provider != .object) return error.BadOAuthResponse;
+ const access = strFieldObj(provider.object, "access_token") orelse strFieldObj(provider.object, "accessToken") orelse return error.BadOAuthResponse;
+ if (access.len == 0 or jwt.len == 0) return error.BadOAuthResponse;
+ const refresh = strFieldObj(provider.object, "refresh_token") orelse strFieldObj(provider.object, "refreshToken") orelse "";
+ return .{ .ready = .{ .access_token = access, .refresh_token = refresh, .jwt = jwt } };
+}
+
+pub fn pickOrgAndProject(info: std.json.ObjectMap) ?OrgProject {
+ const orgs_v = info.get("organizations") orelse return null;
+ if (orgs_v != .array or orgs_v.array.items.len == 0) return null;
+ var chosen_org: ?std.json.ObjectMap = null;
+ for (orgs_v.array.items) |item| {
+ if (item != .object) continue;
+ const name = strFieldObj(item.object, "organizationName") orelse "";
+ if (std.mem.indexOf(u8, name, default_org_name) != null) {
+ chosen_org = item.object;
+ break;
+ }
+ if (chosen_org == null) chosen_org = item.object;
+ }
+ const org = chosen_org orelse return null;
+ const org_id = strFieldObj(org, "organizationId") orelse return null;
+ const projects_v = org.get("projects") orelse return null;
+ if (projects_v != .array or projects_v.array.items.len == 0) return null;
+ var chosen_project: ?std.json.ObjectMap = null;
+ for (projects_v.array.items) |item| {
+ if (item != .object) continue;
+ const name = strFieldObj(item.object, "projectName") orelse "";
+ if (std.mem.indexOf(u8, name, default_project_name) != null) {
+ chosen_project = item.object;
+ break;
+ }
+ if (chosen_project == null) chosen_project = item.object;
+ }
+ const project = chosen_project orelse return null;
+ const project_id = strFieldObj(project, "projectId") orelse return null;
+ if (org_id.len == 0 or project_id.len == 0) return null;
+ return .{ .organization_id = org_id, .project_id = project_id };
+}
+
+pub fn findGraffKey(keys: []const KeySummary) ?[]const u8 {
+ for (keys) |item| {
+ if (std.mem.eql(u8, item.name, api_key_name) and item.api_key.len > 0) return item.api_key;
+ }
+ return null;
+}
+
+pub fn composeApiKey(arena: Allocator, id: []const u8, secret: []const u8) ![]const u8 {
+ if (id.len == 0) return error.BadOAuthResponse;
+ if (secret.len == 0) return error.BadOAuthResponse;
+ return std.fmt.allocPrint(arena, "{s}.{s}", .{ id, secret });
+}
+
+fn parseJsonObject(arena: Allocator, raw: []const u8) !std.json.ObjectMap {
+ const v = try std.json.parseFromSliceLeaky(Value, arena, raw, .{ .allocate = .alloc_always });
+ if (v != .object) return error.BadOAuthResponse;
+ return v.object;
+}
+
+fn httpJson(
+ io: Io,
+ gpa: Allocator,
+ arena: Allocator,
+ method: std.http.Method,
+ url: []const u8,
+ body: ?[]const u8,
+ extra: []const std.http.Header,
+) !Value {
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var aw: Io.Writer.Allocating = .init(arena);
+ var extra_buf: [8]std.http.Header = undefined;
+ const n = @min(extra.len, extra_buf.len);
+ if (n > 0) @memcpy(extra_buf[0..n], extra[0..n]);
+ _ = try client.fetch(.{
+ .location = .{ .url = url },
+ .method = method,
+ .payload = body,
+ .response_writer = &aw.writer,
+ .headers = .{
+ .content_type = if (body != null) .{ .override = "application/json" } else .omit,
+ .user_agent = .{ .override = user_agent },
+ },
+ .extra_headers = extra_buf[0..n],
+ });
+ return std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });
+}
+
+fn writeAuth(
+ io: Io,
+ arena: Allocator,
+ home: []const u8,
+ api_key: []const u8,
+ access: []const u8,
+ refresh: []const u8,
+ expires_at: i64,
+) !void {
+ const base = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, oauth_dir });
+ const credentials = try std.fmt.allocPrint(arena, "{s}/credentials", .{base});
+ for ([_][]const u8{ base, credentials }) |path| {
+ Io.Dir.cwd().createDir(io, path, credential_store.private_dir) catch {};
+ const dir = Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch continue;
+ defer dir.close(io);
+ if (builtin.os.tag != .windows) dir.setPermissions(io, credential_store.private_dir) catch {};
+ }
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "api_key", .{ .string = api_key });
+ try obj.put(arena, "access_token", .{ .string = access });
+ try obj.put(arena, "refresh_token", .{ .string = refresh });
+ try obj.put(arena, "expires_at", .{ .integer = expires_at });
+ try obj.put(arena, "coding", .{ .bool = true });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ try stringify.write(Value{ .object = obj });
+ try credential_store.replaceFile(io, Io.Dir.cwd(), authPath(arena, home), aw.writer.buffered(), credential_store.private_file);
+}
+
+/// Reads the provisioned Coding Plan API key. Sets the coding host unless an
+/// env override already won. `gpa`/`force`/`stale` match the kimi/xai loader
+/// signature; the key is long-lived so there is no refresh in this module.
+pub fn loadZaiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, force: bool, stale: ?[]const u8) ?[]const u8 {
+ _ = gpa;
+ _ = force;
+ _ = stale;
+ 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;
+ if (v != .object) return null;
+ const key = strFieldObj(v.object, "api_key") orelse return null;
+ if (key.len == 0) return null;
+ applyCodingOverride();
+ return key;
+}
+
+fn bizGet(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, authorization: []const u8) !Value {
+ const extra = [_]std.http.Header{.{ .name = "Authorization", .value = authorization }};
+ return unwrapData(try httpJson(io, gpa, arena, .GET, url, null, &extra));
+}
+
+fn bizPost(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, authorization: []const u8, body: []const u8) !Value {
+ const extra = [_]std.http.Header{.{ .name = "Authorization", .value = authorization }};
+ return unwrapData(try httpJson(io, gpa, arena, .POST, url, body, &extra));
+}
+
+fn jsonObject(arena: Allocator, obj: std.json.ObjectMap) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ try stringify.write(Value{ .object = obj });
+ return aw.writer.buffered();
+}
+
+fn summariesFrom(arena: Allocator, v: Value) ![]KeySummary {
+ const items = switch (v) {
+ .array => |a| a.items,
+ .object => |o| blk: {
+ if (o.get("data")) |inner| if (inner == .array) break :blk inner.array.items;
+ return &.{};
+ },
+ else => return &.{},
+ };
+ var out: std.ArrayList(KeySummary) = .empty;
+ for (items) |item| {
+ if (item != .object) continue;
+ const name = strFieldObj(item.object, "name") orelse "";
+ const key = strFieldObj(item.object, "apiKey") orelse "";
+ if (key.len == 0) continue;
+ try out.append(arena, .{ .name = name, .api_key = key });
+ }
+ return out.items;
+}
+
+fn provisionApiKey(io: Io, gpa: Allocator, arena: Allocator, oauth_access: []const u8) ![]const u8 {
+ var login_obj: std.json.ObjectMap = .empty;
+ try login_obj.put(arena, "token", .{ .string = oauth_access });
+ const extra = [_]std.http.Header{};
+ const login_v = try httpJson(io, gpa, arena, .POST, biz_host ++ "/api/auth/z/login", try jsonObject(arena, login_obj), &extra);
+ const login_data = try asObject(try unwrapData(login_v));
+ const biz = strFieldObj(login_data, "access_token") orelse strFieldObj(login_data, "accessToken") orelse return error.BadOAuthResponse;
+ const authorization = try std.fmt.allocPrint(arena, "Bearer {s}", .{biz});
+
+ const customer = try asObject(try bizGet(io, gpa, arena, biz_host ++ "/api/biz/customer/getCustomerInfo", authorization));
+ const loc = pickOrgAndProject(customer) orelse return error.BadOAuthResponse;
+ const list_url = try std.fmt.allocPrint(
+ arena,
+ "{s}/api/biz/v1/organization/{s}/projects/{s}/api_keys",
+ .{ biz_host, loc.organization_id, loc.project_id },
+ );
+ const listed = try summariesFrom(arena, try bizGet(io, gpa, arena, list_url, authorization));
+ var api_id = findGraffKey(listed);
+ if (api_id == null) {
+ var create_obj: std.json.ObjectMap = .empty;
+ try create_obj.put(arena, "name", .{ .string = api_key_name });
+ const created = try asObject(try bizPost(io, gpa, arena, list_url, authorization, try jsonObject(arena, create_obj)));
+ api_id = strFieldObj(created, "apiKey");
+ }
+ const id = api_id orelse return error.BadOAuthResponse;
+ const copy_url = try std.fmt.allocPrint(arena, "{s}/copy/{s}", .{ list_url, id });
+ const secret_data = try asObject(try bizGet(io, gpa, arena, copy_url, authorization));
+ const secret = strFieldObj(secret_data, "secretKey") orelse return error.BadOAuthResponse;
+ return composeApiKey(arena, id, secret);
+}
+
+/// `graff login zai`: open the Z.AI Coding Plan authorize URL, poll the CLI
+/// broker, provision a Graff-named API key, and store it for `/api/coding/paas/v4`.
+pub fn login(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;
+
+ var raw: [32]u8 = undefined;
+ io.random(&raw);
+ const poll_token = std.fmt.bytesToHex(raw, .lower);
+ const bearer = try std.fmt.allocPrint(arena, "Bearer {s}", .{&poll_token});
+ const init_headers = [_]std.http.Header{.{ .name = "Authorization", .value = bearer }};
+ var init_obj: std.json.ObjectMap = .empty;
+ try init_obj.put(arena, "provider", .{ .string = "zai" });
+ const init_v = httpJson(io, gpa, arena, .POST, cli_base ++ "/oauth/cli/init", try jsonObject(arena, init_obj), &init_headers) catch |err| {
+ try out.print("\xe2\x9c\x97 Z.AI login failed: {t}\n", .{err});
+ try out.flush();
+ return;
+ };
+ const init_data = asObject(unwrapData(init_v) catch {
+ try out.writeAll("\xe2\x9c\x97 Z.AI login failed: bad init response\n");
+ try out.flush();
+ return;
+ }) catch {
+ try out.writeAll("\xe2\x9c\x97 Z.AI login failed: bad init response\n");
+ try out.flush();
+ return;
+ };
+ const init = parseInitData(init_data) catch {
+ try out.writeAll("\xe2\x9c\x97 Z.AI login failed: invalid authorize URL\n");
+ try out.flush();
+ 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.flush();
+ if (!main_mod.g_no_browser) openBrowser(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;
+ var attempts: usize = 0;
+ while (attempts < 360) : (attempts += 1) {
+ io.sleep(Io.Duration.fromSeconds(init.poll_interval_sec), .awake) catch {};
+ const now_s: i64 = @divTrunc(util.unixMs(io), 1000);
+ if (now_s >= init.expires_at) break;
+ const poll_v = httpJson(io, gpa, arena, .GET, poll_url, null, &init_headers) catch continue;
+ const poll_data = asObject(unwrapData(poll_v) catch continue) catch continue;
+ const status = parsePollData(poll_data) catch continue;
+ switch (status) {
+ .pending => continue,
+ .failed => {
+ try out.writeAll("\xe2\x9c\x97 authorization failed \xe2\x80\x94 run `graff login zai` again\n");
+ try out.flush();
+ return;
+ },
+ .ready => |r| {
+ ready = r;
+ break;
+ },
+ }
+ }
+ const tokens = ready orelse {
+ try out.writeAll("\xe2\x9c\x97 timed out waiting for authorization\n");
+ try out.flush();
+ return;
+ };
+
+ const api_key = provisionApiKey(io, gpa, arena, tokens.access_token) catch |err| {
+ try out.print("\xe2\x9c\x97 signed in but could not provision a Coding Plan key: {t}\n", .{err});
+ try out.flush();
+ return;
+ };
+ try writeAuth(io, arena, home, api_key, tokens.access_token, tokens.refresh_token, init.expires_at);
+ applyCodingOverride();
+ try out.print("{s}\xe2\x9c\x93{s} logged into Z.AI Coding Plan \xe2\x80\x94 wrote {s}. /model zai\n", .{ style.green, style.reset, authPath(arena, home) });
+ try out.flush();
+}
+
+test "isLoginName: zai aliases" {
+ try std.testing.expect(isLoginName("zai"));
+ try std.testing.expect(isLoginName("glm"));
+ try std.testing.expect(isLoginName("z.ai"));
+ try std.testing.expect(!isLoginName("xai"));
+ try std.testing.expect(!isLoginName("codegraff"));
+}
+
+test "parseInitData: requires https authorize URL and positive interval" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const good = try parseJsonObject(a, "{\"authorize_url\":\"https://chat.z.ai/a\",\"flow_id\":\"f1\",\"expires_at\":9999999999,\"poll_interval_sec\":2}");
+ const init = try parseInitData(good);
+ try std.testing.expectEqualStrings("https://chat.z.ai/a", init.authorize_url);
+ try std.testing.expectEqualStrings("f1", init.flow_id);
+ try std.testing.expectEqual(@as(i64, 2), init.poll_interval_sec);
+ const http = try parseJsonObject(a, "{\"authorize_url\":\"http://evil.example/a\",\"flow_id\":\"f1\",\"expires_at\":9,\"poll_interval_sec\":2}");
+ try std.testing.expectError(error.BadOAuthResponse, parseInitData(http));
+ const no_interval = try parseJsonObject(a, "{\"authorize_url\":\"https://chat.z.ai/a\",\"flow_id\":\"f1\",\"expires_at\":9,\"poll_interval_sec\":0}");
+ try std.testing.expectError(error.BadOAuthResponse, parseInitData(no_interval));
+}
+
+test "parsePollData: pending, failed, ready, missing token" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const pending = try parseJsonObject(a, "{\"status\":\"pending\"}");
+ try std.testing.expect(try parsePollData(pending) == .pending);
+ const failed = try parseJsonObject(a, "{\"status\":\"failed\"}");
+ try std.testing.expect(try parsePollData(failed) == .failed);
+ const ready = try parseJsonObject(a, "{\"status\":\"ready\",\"token\":\"jwt\",\"zai\":{\"access_token\":\"oa\",\"refresh_token\":\"rt\"}}");
+ const got = try parsePollData(ready);
+ try std.testing.expectEqualStrings("oa", got.ready.access_token);
+ try std.testing.expectEqualStrings("rt", got.ready.refresh_token);
+ try std.testing.expectEqualStrings("jwt", got.ready.jwt);
+ const missing = try parseJsonObject(a, "{\"status\":\"ready\",\"token\":\"jwt\"}");
+ try std.testing.expectError(error.BadOAuthResponse, parsePollData(missing));
+}
+
+test "pickOrgAndProject: default-name match, else first" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const named_json = try std.fmt.allocPrint(a, "{{\"organizations\":[{{\"organizationId\":\"o2\",\"organizationName\":\"other\",\"projects\":[{{\"projectId\":\"p2\",\"projectName\":\"x\"}}]}},{{\"organizationId\":\"o1\",\"organizationName\":\"pre {s}\",\"projects\":[{{\"projectId\":\"p0\",\"projectName\":\"skip\"}},{{\"projectId\":\"p1\",\"projectName\":\"{s}\"}}]}}]}}", .{ default_org_name, default_project_name });
+ const named = try parseJsonObject(a, named_json);
+ const loc = pickOrgAndProject(named).?;
+ try std.testing.expectEqualStrings("o1", loc.organization_id);
+ try std.testing.expectEqualStrings("p1", loc.project_id);
+ const first = try parseJsonObject(a, "{\"organizations\":[{\"organizationId\":\"ox\",\"organizationName\":\"acme\",\"projects\":[{\"projectId\":\"px\",\"projectName\":\"eng\"}]}]}");
+ const loc2 = pickOrgAndProject(first).?;
+ try std.testing.expectEqualStrings("ox", loc2.organization_id);
+ try std.testing.expectEqualStrings("px", loc2.project_id);
+ const empty = try parseJsonObject(a, "{\"organizations\":[]}");
+ try std.testing.expect(pickOrgAndProject(empty) == null);
+}
+
+test "findGraffKey + composeApiKey: graff-api-key and id.secret" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const keys = [_]KeySummary{
+ .{ .name = "other", .api_key = "aaa" },
+ .{ .name = api_key_name, .api_key = "kid" },
+ };
+ try std.testing.expectEqualStrings("kid", findGraffKey(&keys).?);
+ try std.testing.expect(findGraffKey(&.{.{ .name = "other", .api_key = "aaa" }}) == null);
+ try std.testing.expectEqualStrings("kid.sec", try composeApiKey(a, "kid", "sec"));
+ try std.testing.expectError(error.BadOAuthResponse, composeApiKey(a, "kid", ""));
+}
+
+test "isSuccessfulRemoteCode: 0/200 and string forms" {
+ try std.testing.expect(isSuccessfulRemoteCode(null));
+ try std.testing.expect(isSuccessfulRemoteCode(.{ .integer = 0 }));
+ try std.testing.expect(isSuccessfulRemoteCode(.{ .integer = 200 }));
+ try std.testing.expect(isSuccessfulRemoteCode(.{ .string = "0" }));
+ try std.testing.expect(isSuccessfulRemoteCode(.{ .string = "200" }));
+ try std.testing.expect(!isSuccessfulRemoteCode(.{ .integer = 401 }));
+ try std.testing.expect(!isSuccessfulRemoteCode(.{ .string = "no" }));
+}
+
+test "writeAuth/loadZaiOAuth: 0600 file, api_key round-trip, coding URL" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const home = try std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ const saved = provider_mod.g_zai_url_override;
+ provider_mod.g_zai_url_override = null;
+ defer provider_mod.g_zai_url_override = saved;
+
+ try writeAuth(io, arena, home, "id.secret", "oa", "rt", 42);
+ const credentials = try tmp.dir.openDir(io, ".zai/credentials", .{});
+ defer credentials.close(io);
+ const file = try credentials.openFile(io, "graff-oauth.json", .{});
+ defer file.close(io);
+ try std.testing.expectEqual(@as(u32, 0o600), (try file.stat(io)).permissions.toMode() & 0o777);
+
+ const key = loadZaiOAuth(io, std.testing.allocator, arena, home, false, null).?;
+ try std.testing.expectEqualStrings("id.secret", key);
+ try std.testing.expectEqualStrings(provider_mod.zai_coding_url, provider_mod.g_zai_url_override.?);
+}
+
+test "applyCodingOverride: env override wins" {
+ const saved = provider_mod.g_zai_url_override;
+ defer provider_mod.g_zai_url_override = saved;
+ provider_mod.g_zai_url_override = "https://example.test/v4";
+ applyCodingOverride();
+ try std.testing.expectEqualStrings("https://example.test/v4", provider_mod.g_zai_url_override.?);
+ provider_mod.g_zai_url_override = null;
+ applyCodingOverride();
+ try std.testing.expectEqualStrings(provider_mod.zai_coding_url, provider_mod.g_zai_url_override.?);
+}
+
+test "preferPlan parks a metered ZAI_API_KEY behind a coding-plan login" {
+ if (builtin.os.tag == .windows) return;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const home = try std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ const saved = provider_mod.g_zai_url_override;
+ provider_mod.g_zai_url_override = null;
+ defer provider_mod.g_zai_url_override = saved;
+ credential_failover.resetForTest();
+ defer credential_failover.resetForTest();
+
+ try writeAuth(io, arena, home, "id.secret", "oa", "rt", 42);
+ const spec = provider_mod.specFor("zai").?;
+ var value: ?[]const u8 = "sk-metered";
+ var source: provider_mod.Keys.CredentialSource = .environment;
+ credential_failover.preferPlan(io, std.testing.allocator, arena, home, spec, &value, &source);
+ try std.testing.expectEqualStrings("id.secret", value.?);
+ try std.testing.expectEqual(provider_mod.Keys.CredentialSource.login, source);
+ try std.testing.expect(credential_failover.standingBy("zai"));
+}
diff --git a/src/picker_auth.zig b/src/picker_auth.zig
index 3da07157..b9b03936 100644
--- a/src/picker_auth.zig
+++ b/src/picker_auth.zig
@@ -70,6 +70,12 @@ pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id:
keys.codex_account = auth.account;
reloaded = true;
}
+ } else if (std.mem.eql(u8, provider_id, "zai")) {
+ if (oauth.loadZaiOAuth(root.io, root.gpa, arena, home, false, null)) |k| {
+ value.* = k;
+ source.* = .login;
+ reloaded = true;
+ }
}
// #402: the live Agent holds its OWN Provider copy — providers.applyProviderInner
// is otherwise the only writer — so refreshing Keys alone left the active
@@ -86,6 +92,7 @@ pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id:
const is_codex = std.mem.eql(u8, provider_id, "codex");
policy.adoptFreshAuth(root, .{ .key = key, .account = if (is_codex) keys.codex_account else "" });
root.provider.source = .login;
+ if (std.mem.eql(u8, provider_id, "zai")) root.provider.url = provider_mod.g_zai_url_override orelse spec.url;
root.closeCodexWs(); // the held socket was dialed with the stale bearer
};
}
@@ -235,7 +242,7 @@ pub fn offerProviderAuth(
try out.flush();
return;
};
- const can_login = std.mem.eql(u8, pid, "codegraff") or std.mem.eql(u8, pid, "codex") or std.mem.eql(u8, pid, "kimi") or std.mem.eql(u8, pid, "xai");
+ const can_login = spec.login != .api_key;
// Non-interactive (one-shot / no TTY): no picker — print the hint and bail.
if (!use_color or root.in == null) {
@@ -300,6 +307,12 @@ pub fn offerProviderAuth(
try out.flush();
return;
};
+ } else if (std.mem.eql(u8, pid, "zai")) {
+ oauth.zaiLogin(root.io, root.gpa, arena, home) catch |err| {
+ try out.print("\xe2\x9c\x97 zai login failed: {t}\n", .{err});
+ try out.flush();
+ return;
+ };
}
reloadLoginKey(root, keys, arena, pid);
} else {
diff --git a/src/provider.zig b/src/provider.zig
index 545d3c04..695d4e7e 100644
--- a/src/provider.zig
+++ b/src/provider.zig
@@ -45,7 +45,7 @@ fn contextWindowFor(provider_id: []const u8, model: []const u8) u64 {
/// provider_specs; one additional OpenAI-compatible router may be loaded from
/// `.graff/.config.router` at startup.
pub const ProviderSpec = struct {
- pub const LoginKind = enum { api_key, codegraff_device, codex_device, kimi_device, xai_device };
+ pub const LoginKind = enum { api_key, codegraff_device, codex_device, kimi_device, xai_device, zai_cli };
pub const CatalogKind = enum { baked, codex, kimi, openai, anthropic };
id: []const u8,
@@ -103,7 +103,7 @@ pub const provider_specs = [_]ProviderSpec{
// `graff login xai` is a real device-code OAuth flow (oauth.zig), so xAI's
// login is a SuperGrok plan while XAI_API_KEY is metered api.x.ai access.
.{ .id = "xai", .display_name = "xAI", .kind = .openai, .auth = .bearer, .url = "https://api.x.ai/v1/chat/completions", .env_key = "XAI_API_KEY", .default_model = "grok-4.6", .login = .xai_device, .sub_login = true, .catalog = .openai, .models_url = "https://api.x.ai/v1/models" },
- .{ .id = "zai", .display_name = "Z.AI", .kind = .openai, .auth = .bearer, .url = "https://api.z.ai/api/paas/v4/chat/completions", .env_key = "ZAI_API_KEY", .default_model = "glm-5.3", .catalog = .openai, .models_url = "https://api.z.ai/api/paas/v4/models", .takes_effort = true },
+ .{ .id = "zai", .display_name = "Z.AI", .kind = .openai, .auth = .bearer, .url = "https://api.z.ai/api/paas/v4/chat/completions", .env_key = "ZAI_API_KEY", .default_model = "glm-5.3", .login = .zai_cli, .sub_login = true, .catalog = .openai, .models_url = "https://api.z.ai/api/paas/v4/models", .takes_effort = true },
// OpenAI-compatible Chat Completions with reasoning_effort support.
.{ .id = "meta", .display_name = "Meta", .kind = .openai, .auth = .bearer, .url = "https://api.meta.ai/v1/chat/completions", .env_key = "META_API_KEY", .default_model = "muse-spark-1.2-contributor", .catalog = .openai, .models_url = "https://api.meta.ai/v1/models", .takes_effort = true },
// Vercel AI Gateway: one key, live /models. Coding-agent surface marks
@@ -162,6 +162,7 @@ pub var g_xai_url_override: ?[]const u8 = null;
pub var g_zai_url_override: ?[]const u8 = null;
pub var g_vercel_url_override: ?[]const u8 = null;
pub const zai_coding_url = "https://api.z.ai/api/coding/paas/v4/chat/completions";
+pub const zai_coding_models_url = "https://api.z.ai/api/coding/paas/v4/models";
pub const vercel_v1_url = "https://ai-gateway.vercel.sh/v1/chat/completions";
fn resolvedUrl(spec: ProviderSpec, model: []const u8) []const u8 {
diff --git a/src/route_report.zig b/src/route_report.zig
index af551e80..2a03ce6b 100644
--- a/src/route_report.zig
+++ b/src/route_report.zig
@@ -51,6 +51,7 @@ pub fn loginOnDisk(io: Io, arena: Allocator, home: []const u8, spec: provider_mo
.api_key => return false,
.kimi_device => credential_store.oauthPath(arena, home, ".kimi"),
.xai_device => credential_store.oauthPath(arena, home, ".xai"),
+ .zai_cli => credential_store.oauthPath(arena, home, ".zai"),
.codex_device => blk: {
const dir = oauth_helpers.codexHomeDir(arena, home) orelse return false;
break :blk std.fmt.allocPrint(arena, "{s}/auth.json", .{dir}) catch return false;
diff --git a/src/schema.zig b/src/schema.zig
index 4499e4de..fad4622d 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -475,6 +475,7 @@ test "providerDisplayName & providerLoginKind: id mapping with sane fallbacks" {
try std.testing.expectEqualStrings("codegraff_device", providerLoginKind("codegraff"));
try std.testing.expectEqualStrings("codex_device", providerLoginKind("codex"));
try std.testing.expectEqualStrings("kimi_device", providerLoginKind("kimi"));
+ try std.testing.expectEqualStrings("zai_cli", providerLoginKind("zai"));
try std.testing.expectEqualStrings("api_key", providerLoginKind("openai"));
}
// isMetaName's own coverage, and #381's note_constraint catalog contract,
diff --git a/src/spec_provider_conformance.zig b/src/spec_provider_conformance.zig
index fa09a2fa..9dc9b8fe 100644
--- a/src/spec_provider_conformance.zig
+++ b/src/spec_provider_conformance.zig
@@ -32,6 +32,7 @@ fn loginName(l: ProviderSpec.LoginKind) []const u8 {
.codex_device => "codex_device",
.kimi_device => "kimi_device",
.xai_device => "xai_device",
+ .zai_cli => "zai_cli",
};
}
diff --git a/src/startup.zig b/src/startup.zig
index 458e263d..daabc2b0 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -302,7 +302,7 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
// `codex` (or --refresh) runs the ChatGPT PKCE/refresh flow → ~/.codex/auth.json.
if (flags.login_flag) {
const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});
- 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.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.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);
return true;
}
@@ -438,6 +438,12 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
source.* = .login;
continue;
}
+ } else if (spec.login == .zai_cli) {
+ if (oauth.loadZaiOAuth(io, gpa, arena, home, false, null)) |tok| {
+ value.* = tok;
+ source.* = .login;
+ continue;
+ }
} else if (spec.login == .codegraff_device) {
if (oauth.loadCodegraffKey(io, arena, home)) |tok| {
value.* = tok;
diff --git a/src/subagent_pin_tests.zig b/src/subagent_pin_tests.zig
index c549717b..270681ad 100644
--- a/src/subagent_pin_tests.zig
+++ b/src/subagent_pin_tests.zig
@@ -343,14 +343,16 @@ test "two logins split the tiers: k3 is mid, luna is the mechanical rung (#471)"
// anthropic rung — paying for work a logged-in plan already covers.
// The candidate list is derived from the specs' sub_login declaration.
var saw_kimi = false;
+ var saw_zai = false;
for (pin_mod.subscription_providers) |sid| {
- try std.testing.expect(!std.mem.eql(u8, sid, "zai"));
try std.testing.expect(!std.mem.eql(u8, sid, "vercel"));
try std.testing.expect(!std.mem.eql(u8, sid, "openrouter"));
try std.testing.expect(!std.mem.eql(u8, sid, "codegraff"));
if (std.mem.eql(u8, sid, "kimi")) saw_kimi = true;
+ if (std.mem.eql(u8, sid, "zai")) saw_zai = true;
}
try std.testing.expect(saw_kimi);
+ try std.testing.expect(saw_zai);
}
test "a kimi root borrows codex's cheap rung: small -> luna when it is logged in (#471)" {