Skip to content

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

Python

refactor: enforce 600-line Zig modules

Rach Pradhanf461baa3d3a2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ae62751c..9de6fef0 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -15,6 +15,9 @@ jobs:
- name: Pinned Zig installer integrity tests
run: python3 scripts/test-install-zig-ci.py
+ - name: Zig source-size guard integrity tests
+ run: python3 scripts/test-zig-lines.py
+
- name: Python SDK import smoke
run: python3 -c "import sys; sys.path.insert(0, 'sdk/py'); import harness_sdk; assert harness_sdk.MODELS and harness_sdk.TOOLS; print('py sdk ok:', len(harness_sdk.MODELS), 'models')"
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
index 838183d7..0516abb6 100644
--- a/docs/releases/v0.0.215.md
+++ b/docs/releases/v0.0.215.md
@@ -60,6 +60,10 @@ and connects Streamable HTTP tools without a Node bridge.
- The default catalog excludes identity, private-project, rating, proposal, and
publishing tools. `GRAFF_SMOLIFY_ACCESS=full` explicitly opts into the full
OAuth-aware catalog; `GRAFF_NO_SMOLIFY=1` removes the surface entirely.
+- First-party Zig modules now obey the repository's 600-line source ceiling.
+ Cohesive prompt, stream-test, HTTP-header, title-job, model-cache-test, and
+ Codegraff OAuth responsibilities were split into sibling modules. CI checks
+ both tracked and newly created sources so the ceiling cannot silently drift.
## Validation
diff --git a/scripts/check-zig-lines.sh b/scripts/check-zig-lines.sh
index fd7a0568..51405be9 100755
--- a/scripts/check-zig-lines.sh
+++ b/scripts/check-zig-lines.sh
@@ -8,7 +8,7 @@ cd "$repo_root"
# non-ignored files locally so a newly split module is checked before it is
# staged; CI sees the same files once committed. Vendored sources are exempt per
# AGENTS.md and are maintained by their upstream project.
-max_lines=699
+max_lines=600
failed=0
while IFS= read -r -d '' file; do
diff --git a/scripts/test-zig-lines.py b/scripts/test-zig-lines.py
new file mode 100644
index 00000000..6eea1fcb
--- /dev/null
+++ b/scripts/test-zig-lines.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""Integrity tests for the first-party Zig source-size guard."""
+
+from __future__ import annotations
+
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+
+SCRIPT = Path(__file__).with_name("check-zig-lines.sh")
+
+
+class ZigLineGuardTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.scratch = tempfile.TemporaryDirectory(prefix="codegraff-line-guard-")
+ self.root = Path(self.scratch.name)
+ (self.root / "scripts").mkdir()
+ shutil.copy2(SCRIPT, self.root / "scripts" / SCRIPT.name)
+ subprocess.run(["git", "init", "-q"], cwd=self.root, check=True)
+ subprocess.run(
+ ["git", "config", "user.email", "[email protected]"],
+ cwd=self.root,
+ check=True,
+ )
+ subprocess.run(
+ ["git", "config", "user.name", "Line Guard"],
+ cwd=self.root,
+ check=True,
+ )
+
+ def tearDown(self) -> None:
+ self.scratch.cleanup()
+
+ def write_zig(self, relative: str, lines: int) -> Path:
+ path = self.root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("const line_guard_probe = 1;\n" * lines, encoding="utf-8")
+ return path
+
+ def run_guard(self) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["bash", "scripts/check-zig-lines.sh"],
+ cwd=self.root,
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ check=False,
+ )
+
+ def test_exactly_600_lines_passes(self) -> None:
+ self.write_zig("src/exact.zig", 600)
+ completed = self.run_guard()
+ self.assertEqual(completed.returncode, 0, completed.stderr)
+ self.assertIn("at most 600 lines", completed.stdout)
+
+ def test_tracked_601_line_file_fails_with_path_and_count(self) -> None:
+ path = self.write_zig("src/tracked.zig", 601)
+ subprocess.run(["git", "add", str(path.relative_to(self.root))], cwd=self.root, check=True)
+ completed = self.run_guard()
+ self.assertNotEqual(completed.returncode, 0)
+ self.assertIn("src/tracked.zig (601)", completed.stderr)
+
+ def test_untracked_601_line_file_also_fails(self) -> None:
+ self.write_zig("src/new-module.zig", 601)
+ completed = self.run_guard()
+ self.assertNotEqual(completed.returncode, 0)
+ self.assertIn("src/new-module.zig (601)", completed.stderr)
+
+ def test_vendored_sources_are_exempt(self) -> None:
+ self.write_zig("vendor/upstream/large.zig", 900)
+ completed = self.run_guard()
+ self.assertEqual(completed.returncode, 0, completed.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/agent.zig b/src/agent.zig
index 6de5d8d8..de1bad32 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -28,44 +28,14 @@ const learning_privacy = @import("learning_privacy.zig");
const ansi = @import("ansi.zig");
const style = &ansi.style;
+const prompt_ui = @import("agent_prompt.zig");
+const agent_tests = @import("agent_tests.zig");
-fn reasoningPromptLabel(effort: ReasoningEffort) []const u8 {
- return switch (effort) {
- .low => "Low",
- .medium => "Medium",
- .high => "High",
- .xhigh => "Extra high",
- .max => "Max",
- .ultra => "Ultra",
- };
-}
-
-fn reasoningPromptColor(effort: ReasoningEffort) []const u8 {
- return switch (effort) {
- .low => style.green,
- .medium => style.accent,
- .high => style.yellow,
- .xhigh => style.accent,
- .max => style.red,
- .ultra => style.accent,
- };
-}
-
-fn writePromptBadge(w: *Io.Writer, color: []const u8, label: []const u8) !void {
- try w.print("{s} · {s}{s}{s}{s}", .{ style.dim, style.reset, color, label, style.reset });
-}
-
-fn compactTokenCount(buf: []u8, tokens: u64) []const u8 {
- return if (tokens >= 1000)
- std.fmt.bufPrint(buf, "{d}k", .{tokens / 1000}) catch "?"
- else
- std.fmt.bufPrint(buf, "{d}", .{tokens}) catch "?";
-}
-
-fn contextPercent(tokens: u64, window: u64) u64 {
- if (window == 0) return 0;
- return @min((tokens *| 100) / window, 100);
-}
+const reasoningPromptLabel = prompt_ui.reasoningLabel;
+const reasoningPromptColor = prompt_ui.reasoningColor;
+const writePromptBadge = prompt_ui.writeBadge;
+const compactTokenCount = prompt_ui.compactTokenCount;
+const contextPercent = prompt_ui.contextPercent;
pub const TodoItem = struct {
content: []const u8,
@@ -619,58 +589,10 @@ pub const Agent = struct {
pub const isTableSeparator = @import("agent_table.zig").isTableSeparator;
};
-test "reasoning prompt label uses picker wording" {
- try std.testing.expectEqualStrings("Low", reasoningPromptLabel(.low));
- try std.testing.expectEqualStrings("Medium", reasoningPromptLabel(.medium));
- try std.testing.expectEqualStrings("High", reasoningPromptLabel(.high));
- try std.testing.expectEqualStrings("Extra high", reasoningPromptLabel(.xhigh));
- try std.testing.expectEqualStrings("Max", reasoningPromptLabel(.max));
- try std.testing.expectEqualStrings("Ultra", reasoningPromptLabel(.ultra));
-}
-
-test "compact token counts keep prompt usage readable" {
- var buf: [24]u8 = undefined;
- try std.testing.expectEqualStrings("999", compactTokenCount(&buf, 999));
- try std.testing.expectEqualStrings("138k", compactTokenCount(&buf, 138_082));
-}
-
-test "context percent saturates malformed or over-window server meters" {
- try std.testing.expectEqual(@as(u64, 0), contextPercent(100, 0));
- try std.testing.expectEqual(@as(u64, 50), contextPercent(50_000, 100_000));
- try std.testing.expectEqual(@as(u64, 100), contextPercent(150_000, 100_000));
- try std.testing.expectEqual(@as(u64, 100), contextPercent(std.math.maxInt(u64), 100_000));
+test "agent prompt helper suite" {
+ _ = @import("agent_prompt.zig");
}
test "lazy root tool catalogs preserve MCP tools across provider formats" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const arena = arena_state.allocator();
- var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io);
- defer registry.deinit();
- var connected = [_]mcp.Tool{.{
- .server_index = 0,
- .original_name = "search",
- .qualified_name = "mcp__bench__search",
- .description = "search the benchmark index",
- .input_schema = .{ .object = .empty },
- }};
- registry.tools = &connected;
-
- var agent: Agent = undefined;
- agent.arena = arena;
- agent.sub = false;
- agent.registry = &registry;
- agent.tools_anthropic = "";
- agent.tools_openai = "";
- agent.tools_responses = "";
-
- try agent.ensureRootTools(.responses);
- try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "mcp__bench__search") != null);
- try std.testing.expectEqual(@as(usize, 0), agent.tools_openai.len);
- try std.testing.expectEqual(@as(usize, 0), agent.tools_anthropic.len);
-
- agent.invalidateRootTools();
- try agent.ensureRootTools(.anthropic);
- try std.testing.expect(std.mem.indexOf(u8, agent.tools_anthropic, "mcp__bench__search") != null);
- try std.testing.expectEqual(@as(usize, 0), agent.tools_responses.len);
+ try agent_tests.lazyRootTools(Agent);
}
diff --git a/src/agent_prompt.zig b/src/agent_prompt.zig
new file mode 100644
index 00000000..d6ad29d6
--- /dev/null
+++ b/src/agent_prompt.zig
@@ -0,0 +1,66 @@
+//! Compact prompt badges and context-meter formatting.
+
+const std = @import("std");
+const Io = std.Io;
+const style = &@import("ansi.zig").style;
+
+pub fn reasoningLabel(effort: anytype) []const u8 {
+ return switch (effort) {
+ .low => "Low",
+ .medium => "Medium",
+ .high => "High",
+ .xhigh => "Extra high",
+ .max => "Max",
+ .ultra => "Ultra",
+ };
+}
+
+pub fn reasoningColor(effort: anytype) []const u8 {
+ return switch (effort) {
+ .low => style.green,
+ .medium => style.accent,
+ .high => style.yellow,
+ .xhigh => style.accent,
+ .max => style.red,
+ .ultra => style.accent,
+ };
+}
+
+pub fn writeBadge(writer: *Io.Writer, color: []const u8, label: []const u8) !void {
+ try writer.print("{s} · {s}{s}{s}{s}", .{ style.dim, style.reset, color, label, style.reset });
+}
+
+pub fn compactTokenCount(buf: []u8, tokens: u64) []const u8 {
+ return if (tokens >= 1000)
+ std.fmt.bufPrint(buf, "{d}k", .{tokens / 1000}) catch "?"
+ else
+ std.fmt.bufPrint(buf, "{d}", .{tokens}) catch "?";
+}
+
+pub fn contextPercent(tokens: u64, window: u64) u64 {
+ if (window == 0) return 0;
+ return @min((tokens *| 100) / window, 100);
+}
+
+test "reasoning prompt label uses picker wording" {
+ const Effort = enum { low, medium, high, xhigh, max, ultra };
+ try std.testing.expectEqualStrings("Low", reasoningLabel(Effort.low));
+ try std.testing.expectEqualStrings("Medium", reasoningLabel(Effort.medium));
+ try std.testing.expectEqualStrings("High", reasoningLabel(Effort.high));
+ try std.testing.expectEqualStrings("Extra high", reasoningLabel(Effort.xhigh));
+ try std.testing.expectEqualStrings("Max", reasoningLabel(Effort.max));
+ try std.testing.expectEqualStrings("Ultra", reasoningLabel(Effort.ultra));
+}
+
+test "compact token counts keep prompt usage readable" {
+ var buf: [24]u8 = undefined;
+ try std.testing.expectEqualStrings("999", compactTokenCount(&buf, 999));
+ try std.testing.expectEqualStrings("138k", compactTokenCount(&buf, 138_082));
+}
+
+test "context percent saturates malformed or over-window server meters" {
+ try std.testing.expectEqual(@as(u64, 0), contextPercent(100, 0));
+ try std.testing.expectEqual(@as(u64, 50), contextPercent(50_000, 100_000));
+ try std.testing.expectEqual(@as(u64, 100), contextPercent(150_000, 100_000));
+ try std.testing.expectEqual(@as(u64, 100), contextPercent(std.math.maxInt(u64), 100_000));
+}
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index a9f1e185..d2b5ee1f 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -20,8 +20,7 @@ const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
-const ansi = @import("ansi.zig");
-const style = &ansi.style;
+const style = &@import("ansi.zig").style;
const anim = @import("anim.zig");
@@ -31,8 +30,8 @@ const termCols = terminal.termCols;
const termRows = terminal.termRows;
const advanceThinkingRows = terminal.advanceThinkingRows;
-const title_mod = @import("title.zig");
-const reasoningDelta = title_mod.reasoningDelta;
+const reasoningDelta = @import("title.zig").reasoningDelta;
+const stream_tests = @import("agent_stream_tests.zig");
const http = @import("http.zig");
const providerUserAgent = http.providerUserAgent;
@@ -528,40 +527,11 @@ pub fn isStreamEnd(arena: std.mem.Allocator, kind: anytype, raw_line: []const u8
}
test "isStreamEnd (#134): terminal events detected, content deltas never false-match" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- const Kind = @import("provider.zig").Provider.Kind;
- // OpenAI/Responses [DONE] sentinel; a content delta merely CONTAINING it must not end the stream.
- try std.testing.expect(isStreamEnd(a, Kind.openai, "data: [DONE]"));
- try std.testing.expect(!isStreamEnd(a, Kind.openai, "data: {\"choices\":[{\"delta\":{\"content\":\"[DONE]\"}}]}"));
- // Anthropic: event: line and data payload both terminate; a delta with the word does not.
- try std.testing.expect(isStreamEnd(a, Kind.anthropic, "event: message_stop"));
- try std.testing.expect(isStreamEnd(a, Kind.anthropic, "data: {\"type\":\"message_stop\"}"));
- try std.testing.expect(!isStreamEnd(a, Kind.anthropic, "data: {\"type\":\"content_block_delta\",\"delta\":{\"text\":\"message_stop\"}}"));
- // Responses (codex/gpt-5.5): completed/incomplete terminate; an output-text delta does not.
- try std.testing.expect(isStreamEnd(a, Kind.responses, "event: response.completed"));
- try std.testing.expect(isStreamEnd(a, Kind.responses, "data: {\"type\":\"response.completed\"}"));
- try std.testing.expect(isStreamEnd(a, Kind.responses, "data: {\"type\":\"response.incomplete\"}"));
- try std.testing.expect(!isStreamEnd(a, Kind.responses, "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}"));
- // #133 (openai/kimi): a non-null string finish_reason chunk is terminal (some
- // gateways omit [DONE]); a null finish_reason or a bare reasoning/content
- // delta is NOT — a connection drop after one of those is a StreamDropped, not
- // a clean end.
- try std.testing.expect(!isStreamEnd(a, Kind.openai, "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"},\"finish_reason\":null}]}"));
- try std.testing.expect(!isStreamEnd(a, Kind.openai, "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}"));
+ try stream_tests.streamEnd(isStreamEnd);
}
test "openaiComplete (#133): finish_reason marks completion, deltas do not" {
- // non-null finish_reason => complete (even without [DONE]).
- try std.testing.expect(openaiComplete("data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}"));
- try std.testing.expect(openaiComplete("data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"length\"}]}"));
- // mid-stream: null finish_reason or a bare reasoning delta is NOT complete —
- // a connection drop after one of these is the #133 StreamDropped case.
- try std.testing.expect(!openaiComplete("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"},\"finish_reason\":null}]}"));
- try std.testing.expect(!openaiComplete("data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}"));
- // the substring must not false-match a finish_reason that appears in escaped content.
- try std.testing.expect(!openaiComplete("data: {\"choices\":[{\"delta\":{\"content\":\"\\\"finish_reason\\\":\\\"x\"}}]}"));
+ try stream_tests.openaiCompletion(openaiComplete);
}
/// Print the user-visible text from one SSE line, if any. Best-effort:
diff --git a/src/agent_stream_tests.zig b/src/agent_stream_tests.zig
new file mode 100644
index 00000000..772e7596
--- /dev/null
+++ b/src/agent_stream_tests.zig
@@ -0,0 +1,34 @@
+//! Stream-termination fixtures kept out of the transport implementation.
+
+const std = @import("std");
+const Kind = @import("provider.zig").Provider.Kind;
+
+pub fn streamEnd(is_stream_end: anytype) !void {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ // OpenAI/Responses [DONE] sentinel; content merely containing it must not end the stream.
+ try std.testing.expect(is_stream_end(arena, Kind.openai, "data: [DONE]"));
+ try std.testing.expect(!is_stream_end(arena, Kind.openai, "data: {\"choices\":[{\"delta\":{\"content\":\"[DONE]\"}}]}"));
+ // Anthropic event and data payload terminate; a delta with the word does not.
+ try std.testing.expect(is_stream_end(arena, Kind.anthropic, "event: message_stop"));
+ try std.testing.expect(is_stream_end(arena, Kind.anthropic, "data: {\"type\":\"message_stop\"}"));
+ try std.testing.expect(!is_stream_end(arena, Kind.anthropic, "data: {\"type\":\"content_block_delta\",\"delta\":{\"text\":\"message_stop\"}}"));
+ // Responses completion/incompletion terminate; output deltas do not.
+ try std.testing.expect(is_stream_end(arena, Kind.responses, "event: response.completed"));
+ try std.testing.expect(is_stream_end(arena, Kind.responses, "data: {\"type\":\"response.completed\"}"));
+ try std.testing.expect(is_stream_end(arena, Kind.responses, "data: {\"type\":\"response.incomplete\"}"));
+ try std.testing.expect(!is_stream_end(arena, Kind.responses, "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}"));
+ // OpenAI null finish reasons and reasoning deltas remain mid-stream.
+ try std.testing.expect(!is_stream_end(arena, Kind.openai, "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"},\"finish_reason\":null}]}"));
+ try std.testing.expect(!is_stream_end(arena, Kind.openai, "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}"));
+}
+
+pub fn openaiCompletion(openai_complete: anytype) !void {
+ try std.testing.expect(openai_complete("data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}"));
+ try std.testing.expect(openai_complete("data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"length\"}]}"));
+ try std.testing.expect(!openai_complete("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"},\"finish_reason\":null}]}"));
+ try std.testing.expect(!openai_complete("data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"thinking\"}}]}"));
+ // Escaped content must not false-match a finish_reason field.
+ try std.testing.expect(!openai_complete("data: {\"choices\":[{\"delta\":{\"content\":\"\\\"finish_reason\\\":\\\"x\"}}]}"));
+}
diff --git a/src/agent_tests.zig b/src/agent_tests.zig
new file mode 100644
index 00000000..687669bd
--- /dev/null
+++ b/src/agent_tests.zig
@@ -0,0 +1,38 @@
+//! Larger Agent fixtures kept separate from the state/method definition.
+
+const std = @import("std");
+const mcp = @import("mcp.zig");
+
+pub fn lazyRootTools(comptime Agent: type) !void {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io);
+ defer registry.deinit();
+ var connected = [_]mcp.Tool{.{
+ .server_index = 0,
+ .original_name = "search",
+ .qualified_name = "mcp__bench__search",
+ .description = "search the benchmark index",
+ .input_schema = .{ .object = .empty },
+ }};
+ registry.tools = &connected;
+
+ var agent: Agent = undefined;
+ agent.arena = arena;
+ agent.sub = false;
+ agent.registry = &registry;
+ agent.tools_anthropic = "";
+ agent.tools_openai = "";
+ agent.tools_responses = "";
+
+ try agent.ensureRootTools(.responses);
+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_responses, "mcp__bench__search") != null);
+ try std.testing.expectEqual(@as(usize, 0), agent.tools_openai.len);
+ try std.testing.expectEqual(@as(usize, 0), agent.tools_anthropic.len);
+
+ agent.invalidateRootTools();
+ try agent.ensureRootTools(.anthropic);
+ try std.testing.expect(std.mem.indexOf(u8, agent.tools_anthropic, "mcp__bench__search") != null);
+ try std.testing.expectEqual(@as(usize, 0), agent.tools_responses.len);
+}
diff --git a/src/http.zig b/src/http.zig
index d39fff55..b9c5d6d7 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -14,9 +14,7 @@ const provider_mod = @import("provider.zig");
const agent_mod = @import("agent.zig");
const Provider = provider_mod.Provider;
const Agent = agent_mod.Agent;
-const anthropic_version = root.anthropic_version;
-const kimi_user_agent = root.kimi_user_agent;
-const kimi_catalog = @import("kimi_catalog.zig");
+const headers = @import("http_headers.zig");
/// Launch-scoped gate installed while the shared client's CA bundle warms in
/// the background. Null in unit tests and standalone pre-client subcommands.
@@ -26,48 +24,8 @@ pub fn waitForClientReady(io: Io) void {
if (g_client_ready) |ready| ready.waitUncancelable(io);
}
-pub fn providerUserAgent(provider: Provider) std.http.Client.Request.Headers.Value {
- if (std.mem.eql(u8, provider.id, "kimi")) {
- return .{ .override = kimi_user_agent };
- }
- return .default;
-}
-pub fn providerHeaders(provider: Provider, bearer: []const u8, buf: *[12]std.http.Header) []const std.http.Header {
- var n: usize = 0;
- switch (provider.auth) {
- .x_api_key => {
- buf[n] = .{ .name = "x-api-key", .value = provider.api_key };
- n += 1;
- },
- .bearer => {
- buf[n] = .{ .name = "authorization", .value = bearer };
- n += 1;
- },
- }
- // Anthropic-format endpoints also get the anthropic-version header
- // (harmless extra for compatible providers).
- if (provider.kind == .anthropic) {
- buf[n] = .{ .name = "anthropic-version", .value = anthropic_version };
- n += 1;
- }
- if (std.mem.eql(u8, provider.id, "kimi")) {
- const identity = kimi_catalog.identityHeaders(buf[n..]);
- n += identity.len;
- }
- // Codex / ChatGPT backend: identify as the codex client and carry the
- // ChatGPT account id + Responses beta opt-in.
- if (provider.kind == .responses) {
- buf[n] = .{ .name = "chatgpt-account-id", .value = provider.account };
- n += 1;
- buf[n] = .{ .name = "OpenAI-Beta", .value = "responses=experimental" };
- n += 1;
- buf[n] = .{ .name = "originator", .value = "codex_cli_rs" };
- n += 1;
- buf[n] = .{ .name = "session_id", .value = "00000000-0000-0000-0000-000000000001" };
- n += 1;
- }
- return buf[0..n];
-}
+pub const providerUserAgent = headers.userAgent;
+pub const providerHeaders = headers.providerHeaders;
/// Copy up to root.g_5xx_body_buf.len bytes of an error response body into the
/// global buffer so request()'s retry message can surface the gateway's
diff --git a/src/http_headers.zig b/src/http_headers.zig
new file mode 100644
index 00000000..04dfc18a
--- /dev/null
+++ b/src/http_headers.zig
@@ -0,0 +1,46 @@
+//! Provider-specific HTTP identity and authorization headers.
+
+const std = @import("std");
+const Provider = @import("provider.zig").Provider;
+const root = @import("main.zig");
+const kimi_catalog = @import("kimi_catalog.zig");
+
+pub fn userAgent(provider: Provider) std.http.Client.Request.Headers.Value {
+ if (std.mem.eql(u8, provider.id, "kimi")) {
+ return .{ .override = root.kimi_user_agent };
+ }
+ return .default;
+}
+
+pub fn providerHeaders(provider: Provider, bearer: []const u8, buf: *[12]std.http.Header) []const std.http.Header {
+ var count: usize = 0;
+ switch (provider.auth) {
+ .x_api_key => {
+ buf[count] = .{ .name = "x-api-key", .value = provider.api_key };
+ count += 1;
+ },
+ .bearer => {
+ buf[count] = .{ .name = "authorization", .value = bearer };
+ count += 1;
+ },
+ }
+ if (provider.kind == .anthropic) {
+ buf[count] = .{ .name = "anthropic-version", .value = root.anthropic_version };
+ count += 1;
+ }
+ if (std.mem.eql(u8, provider.id, "kimi")) {
+ const identity = kimi_catalog.identityHeaders(buf[count..]);
+ count += identity.len;
+ }
+ if (provider.kind == .responses) {
+ buf[count] = .{ .name = "chatgpt-account-id", .value = provider.account };
+ count += 1;
+ buf[count] = .{ .name = "OpenAI-Beta", .value = "responses=experimental" };
+ count += 1;
+ buf[count] = .{ .name = "originator", .value = "codex_cli_rs" };
+ count += 1;
+ buf[count] = .{ .name = "session_id", .value = "00000000-0000-0000-0000-000000000001" };
+ count += 1;
+ }
+ return buf[0..count];
+}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 75c2b6a5..779cc9c3 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -34,6 +34,7 @@ const anim = @import("anim.zig");
const hooks = @import("hooks.zig");
const readline = @import("readline.zig");
const title_mod = @import("title.zig");
+const mainloop_title = @import("mainloop_title.zig");
/// Borrowed pointers into main()'s stack plus immutable arena-owned prompt slices.
pub const Ctx = struct {
@@ -51,88 +52,6 @@ pub const Ctx = struct {
sys_strict: []const u8,
};
-fn applyAiTitle(ctx: *Ctx, title: []const u8) void {
- ctx.root.session_title = ctx.arena.dupe(u8, title) catch null;
- if (ctx.root.session_title) |st| {
- title_mod.setTerminalTitle(ctx.out, st, main_mod.g_cwd_display);
- session.renameSession(ctx.root, ctx.arena, session.slugifyTitle(ctx.arena, st));
- }
-}
-
-const TitleJob = struct {
- future: ?Io.Future(void) = null,
- prompt: []const u8, // gpa-owned: readline storage may be reused next turn
- result: ?[]const u8 = null, // gpa-owned, published before done.release
- done: std.atomic.Value(bool) = .init(false),
- generation: u64,
-};
-
-fn detachedTitleTask(job: *TitleJob, gpa: Allocator, io: Io, client: *std.http.Client, provider: provider_mod.Provider, budget: ?*@import("run_budget.zig").RunBudget, tracer: ?*@import("trace.zig").Tracer) void {
- job.result = title_mod.titleTask(gpa, io, client, provider, job.prompt, budget, tracer);
- job.done.store(true, .release);
-}
-
-/// Session title tasks are polled without waiting and canceled only at close.
-const TitleJobs = struct {
- items: std.ArrayList(*TitleJob) = .empty,
-
- fn start(self: *TitleJobs, ctx: *Ctx, prompt: []const u8) void {
- // An explicitly tiny budget still owes the user a real answer. Do not
- // let cosmetic title work consume the final provider-call slot before
- // the root request has a chance to acquire it.
- if (ctx.root.run_budget) |budget| if (budget.remaining() <= 1) {
- if (ctx.root.tracer) |tr| tr.note("budget", "AI title skipped to reserve the final model call for the root turn");
- return;
- };
- const job = ctx.gpa.create(TitleJob) catch return;
- const owned_prompt = ctx.gpa.dupe(u8, prompt) catch {
- ctx.gpa.destroy(job);
- return;
- };
- job.* = .{ .prompt = owned_prompt, .generation = ctx.root.title_generation };
- const args = .{ job, ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, ctx.root.run_budget, ctx.root.tracer };
- job.future = ctx.io.concurrent(detachedTitleTask, args) catch ctx.io.async(detachedTitleTask, args);
- self.items.append(ctx.gpa, job) catch {
- if (job.future) |*future| future.cancel(ctx.io);
- if (job.result) |title| ctx.gpa.free(title);
- ctx.gpa.free(job.prompt);
- ctx.gpa.destroy(job);
- };
- }
-
- fn poll(self: *TitleJobs, ctx: *Ctx) void {
- var i: usize = 0;
- while (i < self.items.items.len) {
- const job = self.items.items[i];
- if (!job.done.load(.acquire)) {
- i += 1;
- continue;
- }
- if (job.future) |*future| future.await(ctx.io); // done=true: never blocks
- job.future = null;
- if (job.result) |title| {
- // Manual rename/session reset wins over an older detached result.
- if (job.generation == ctx.root.title_generation and ctx.root.session_title == null)
- applyAiTitle(ctx, title);
- ctx.gpa.free(title);
- }
- ctx.gpa.free(job.prompt);
- _ = self.items.orderedRemove(i);
- ctx.gpa.destroy(job);
- }
- }
-
- fn deinit(self: *TitleJobs, ctx: *Ctx) void {
- for (self.items.items) |job| {
- if (job.future) |*future| future.cancel(ctx.io);
- if (job.result) |title| ctx.gpa.free(title);
- ctx.gpa.free(job.prompt);
- ctx.gpa.destroy(job);
- }
- self.items.deinit(ctx.gpa);
- }
-};
-
/// True only when a nonempty live checklist is entirely completed (#226).
fn allTodosDone(root: *agent_mod.Agent) bool {
if (root.todos.items.len == 0) return false;
@@ -142,7 +61,7 @@ fn allTodosDone(root: *agent_mod.Agent) bool {
/// Run turns until EOF/quit; main then performs final save/worktree cleanup.
pub fn run(ctx: *Ctx) !void {
- var title_jobs: TitleJobs = .{};
+ var title_jobs: mainloop_title.Jobs = .{};
defer title_jobs.deinit(ctx);
// Trajectory spine state: each turn's parent is the previous turn, and a
// changed prompt fingerprint marks a set_system_prompt mutation edge.
diff --git a/src/mainloop_title.zig b/src/mainloop_title.zig
new file mode 100644
index 00000000..abbd6ef3
--- /dev/null
+++ b/src/mainloop_title.zig
@@ -0,0 +1,93 @@
+//! Detached AI-title jobs for the root loop. The caller context is generic so
+//! this module stays independent of `mainloop.zig`'s orchestration type.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const main_mod = @import("main.zig");
+const provider_mod = @import("provider.zig");
+const session = @import("session.zig");
+const title_mod = @import("title.zig");
+
+const Job = struct {
+ future: ?Io.Future(void) = null,
+ prompt: []const u8, // gpa-owned: readline storage may be reused next turn
+ result: ?[]const u8 = null, // gpa-owned, published before done.release
+ done: std.atomic.Value(bool) = .init(false),
+ generation: u64,
+};
+
+fn apply(ctx: anytype, title: []const u8) void {
+ ctx.root.session_title = ctx.arena.dupe(u8, title) catch null;
+ if (ctx.root.session_title) |stored| {
+ title_mod.setTerminalTitle(ctx.out, stored, main_mod.g_cwd_display);
+ session.renameSession(ctx.root, ctx.arena, session.slugifyTitle(ctx.arena, stored));
+ }
+}
+
+fn detachedTask(job: *Job, gpa: Allocator, io: Io, client: *std.http.Client, provider: provider_mod.Provider, budget: ?*@import("run_budget.zig").RunBudget, tracer: ?*@import("trace.zig").Tracer) void {
+ job.result = title_mod.titleTask(gpa, io, client, provider, job.prompt, budget, tracer);
+ job.done.store(true, .release);
+}
+
+/// Session title tasks are polled without waiting and canceled only at close.
+pub const Jobs = struct {
+ items: std.ArrayList(*Job) = .empty,
+
+ pub fn start(self: *Jobs, ctx: anytype, prompt: []const u8) void {
+ // An explicitly tiny budget still owes the user a real answer. Do not
+ // let cosmetic title work consume the final provider-call slot before
+ // the root request has a chance to acquire it.
+ if (ctx.root.run_budget) |budget| if (budget.remaining() <= 1) {
+ if (ctx.root.tracer) |tr| tr.note("budget", "AI title skipped to reserve the final model call for the root turn");
+ return;
+ };
+ const job = ctx.gpa.create(Job) catch return;
+ const owned_prompt = ctx.gpa.dupe(u8, prompt) catch {
+ ctx.gpa.destroy(job);
+ return;
+ };
+ job.* = .{ .prompt = owned_prompt, .generation = ctx.root.title_generation };
+ const args = .{ job, ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, ctx.root.run_budget, ctx.root.tracer };
+ job.future = ctx.io.concurrent(detachedTask, args) catch ctx.io.async(detachedTask, args);
+ self.items.append(ctx.gpa, job) catch {
+ if (job.future) |*future| future.cancel(ctx.io);
+ if (job.result) |title| ctx.gpa.free(title);
+ ctx.gpa.free(job.prompt);
+ ctx.gpa.destroy(job);
+ };
+ }
+
+ pub fn poll(self: *Jobs, ctx: anytype) void {
+ var i: usize = 0;
+ while (i < self.items.items.len) {
+ const job = self.items.items[i];
+ if (!job.done.load(.acquire)) {
+ i += 1;
+ continue;
+ }
+ if (job.future) |*future| future.await(ctx.io); // done=true: never blocks
+ job.future = null;
+ if (job.result) |title| {
+ // Manual rename/session reset wins over an older detached result.
+ if (job.generation == ctx.root.title_generation and ctx.root.session_title == null)
+ apply(ctx, title);
+ ctx.gpa.free(title);
+ }
+ ctx.gpa.free(job.prompt);
+ _ = self.items.orderedRemove(i);
+ ctx.gpa.destroy(job);
+ }
+ }
+
+ pub fn deinit(self: *Jobs, ctx: anytype) void {
+ for (self.items.items) |job| {
+ if (job.future) |*future| future.cancel(ctx.io);
+ if (job.result) |title| ctx.gpa.free(title);
+ ctx.gpa.free(job.prompt);
+ ctx.gpa.destroy(job);
+ }
+ self.items.deinit(ctx.gpa);
+ }
+};
diff --git a/src/models_cache.zig b/src/models_cache.zig
index eae0569c..04f38e47 100644
--- a/src/models_cache.zig
+++ b/src/models_cache.zig
@@ -19,9 +19,8 @@
//! sole source, so nothing here can break a run. The models.dev overlay only
//! refreshes numbers for names the active table already routes.
//!
-//! Cache path: ~/.codegraff/models.json, falling back to the flat dotfile
-//! ~/.codegraff-models.json when that directory doesn't exist; the flat form
-//! also matches the existing ~/.simple-harness-*.json state layout.
+//! Cache path: ~/.codegraff/models.json, falling back to ~/.codegraff-models.json;
+//! the flat form also matches the existing ~/.simple-harness-*.json layout.
const std = @import("std");
const Io = std.Io;
@@ -33,14 +32,14 @@ const util = @import("util.zig");
const strFieldObj = util.strFieldObj;
const provider = @import("provider.zig"); // g_codex_url_override: keep /models discovery on the same origin as the overridden responses endpoint
const kimi_catalog = @import("kimi_catalog.zig");
+const cache_tests = @import("models_cache_tests.zig");
const models_dev_url = "https://models.dev/api.json";
const codex_models_url = "https://chatgpt.com/backend-api/codex/models";
const codex_cache_ttl_ms: i64 = 5 * 60 * 1000;
// The Codex backend filters /models by client_version. Official openai/codex
-// sends its own compiled package version (client_version_to_whole), not the
-// version of some other Codex installation on PATH. This is the newest Codex
-// protocol Graff has been verified against; a newer installed/native version
+// sends its compiled package version, not another Codex installation on PATH.
+// This is the newest protocol Graff has verified; a newer installed/native version
// may raise it, but an older one must never hide models Graff supports.
// Reference: openai/codex rust-v0.144.1, codex-rs/models-manager.
const codex_client_version_floor = "0.144.1";
@@ -581,70 +580,21 @@ pub fn command(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, sub_a
}
test "numField reads int and float JSON numbers; u64Field clamps" {
- var a = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer a.deinit();
- const v = try std.json.parseFromSliceLeaky(Value, a.allocator(),
- \\{"i": 42, "f": 2.5, "neg": -3, "s": "x"}
- , .{ .allocate = .alloc_always });
- try std.testing.expectEqual(@as(f64, 42), numField(v.object, "i").?);
- try std.testing.expectEqual(@as(f64, 2.5), numField(v.object, "f").?);
- try std.testing.expect(numField(v.object, "s") == null);
- try std.testing.expect(numField(v.object, "missing") == null);
- try std.testing.expectEqual(@as(u64, 42), u64Field(v.object, "i"));
- try std.testing.expectEqual(@as(u64, 0), u64Field(v.object, "neg")); // clamped
- try std.testing.expectEqual(@as(u64, 0), u64Field(v.object, "missing"));
+ try cache_tests.numberFields(numField, u64Field);
}
test "lazy Codex catalog can be invalidated after account changes" {
- const previous_source = codex_catalog_source;
- defer codex_catalog_source = previous_source;
- var catalog: LazyCodexCatalog = .{ .codex_home = "" };
- catalog.ensure(std.testing.io, std.testing.allocator, std.testing.allocator, "", "", "");
- try std.testing.expect(catalog.loaded);
- catalog.invalidate();
- try std.testing.expect(!catalog.loaded);
+ try cache_tests.lazyCatalog(LazyCodexCatalog, &codex_catalog_source);
}
test "findModel prefers the canonical vendor over a reseller markup" {
- var a = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer a.deinit();
- // gpt-5.6 listed under a reseller (higher price) AND canonical openai.
- const v = try std.json.parseFromSliceLeaky(Value, a.allocator(),
- \\{"reseller":{"models":{"gpt-5.6":{"limit":{"context":100},"cost":{"input":99,"output":99,"cache_read":9}}}},
- \\ "openai":{"models":{"gpt-5.6":{"limit":{"context":1050000},"cost":{"input":5,"output":30,"cache_read":0.5}}}}}
- , .{ .allocate = .alloc_always });
- const m = findModel(v.object, "gpt-5.6").?;
- try std.testing.expectEqual(@as(f64, 5), m.in); // openai, not the reseller's 99
- try std.testing.expectEqual(@as(u64, 1_050_000), m.context);
- // Alias match: "gpt5.6" normalizes to "gpt-5.6".
- try std.testing.expect(findModel(v.object, "gpt5.6") != null);
- try std.testing.expect(findModel(v.object, "no-such-model") == null);
+ try cache_tests.canonicalVendor(findModel);
}
test "Codex snapshot uses visible remote slugs and their advertised contexts" {
- var a = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer a.deinit();
- const snapshot = parseCodexSnapshot(a.allocator(),
- \\{"client_version":"9.9.9","models":[
- \\ {"slug":"future-sol","visibility":"list","context_window":372000},
- \\ {"slug":"future-hidden","visibility":"hide","context_window":999000},
- \\ {"slug":"future-luna","visibility":"list","context_window":128000},
- \\ {"slug":"future-luna","visibility":"list","context_window":1}]}
- ).?;
- try std.testing.expectEqualStrings("9.9.9", snapshot.client_version);
- try std.testing.expectEqual(@as(usize, 2), snapshot.models.len);
- try std.testing.expectEqualStrings("future-sol", snapshot.models[0].name);
- try std.testing.expectEqual(@as(u64, 372_000), snapshot.models[0].context);
- try std.testing.expectEqualStrings("future-luna", snapshot.models[1].name);
- try std.testing.expectEqual(@as(u64, 128_000), snapshot.models[1].context);
+ try cache_tests.visibleSnapshots(parseCodexSnapshot);
}
test "Codex discovery never regresses below Graff's supported client version" {
- try std.testing.expectEqualStrings(codex_client_version_floor, effectiveCodexVersion("0.130.0", null));
- try std.testing.expectEqualStrings("0.145.0", effectiveCodexVersion("0.145.0", null));
- try std.testing.expectEqualStrings(codex_client_version_floor, effectiveCodexVersion("invalid", null));
- try std.testing.expect(!snapshotMatchesVersion(.{
- .models = &.{},
- .client_version = "0.130.0",
- }, codex_client_version_floor));
+ try cache_tests.versionFloor(codex_client_version_floor, effectiveCodexVersion, snapshotMatchesVersion);
}
diff --git a/src/models_cache_tests.zig b/src/models_cache_tests.zig
new file mode 100644
index 00000000..7a0eec3c
--- /dev/null
+++ b/src/models_cache_tests.zig
@@ -0,0 +1,71 @@
+//! Catalog parsing and precedence fixtures.
+
+const std = @import("std");
+const Value = std.json.Value;
+
+pub fn numberFields(num_field: anytype, u64_field: anytype) !void {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const value = try std.json.parseFromSliceLeaky(Value, arena.allocator(),
+ \\{"i": 42, "f": 2.5, "neg": -3, "s": "x"}
+ , .{ .allocate = .alloc_always });
+ try std.testing.expectEqual(@as(f64, 42), num_field(value.object, "i").?);
+ try std.testing.expectEqual(@as(f64, 2.5), num_field(value.object, "f").?);
+ try std.testing.expect(num_field(value.object, "s") == null);
+ try std.testing.expect(num_field(value.object, "missing") == null);
+ try std.testing.expectEqual(@as(u64, 42), u64_field(value.object, "i"));
+ try std.testing.expectEqual(@as(u64, 0), u64_field(value.object, "neg"));
+ try std.testing.expectEqual(@as(u64, 0), u64_field(value.object, "missing"));
+}
+
+pub fn lazyCatalog(comptime Catalog: type, source: *[]const u8) !void {
+ const previous_source = source.*;
+ defer source.* = previous_source;
+ var catalog: Catalog = .{ .codex_home = "" };
+ catalog.ensure(std.testing.io, std.testing.allocator, std.testing.allocator, "", "", "");
+ try std.testing.expect(catalog.loaded);
+ catalog.invalidate();
+ try std.testing.expect(!catalog.loaded);
+}
+
+pub fn canonicalVendor(find_model: anytype) !void {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const value = try std.json.parseFromSliceLeaky(Value, arena.allocator(),
+ \\{"reseller":{"models":{"gpt-5.6":{"limit":{"context":100},"cost":{"input":99,"output":99,"cache_read":9}}}},
+ \\ "openai":{"models":{"gpt-5.6":{"limit":{"context":1050000},"cost":{"input":5,"output":30,"cache_read":0.5}}}}}
+ , .{ .allocate = .alloc_always });
+ const model = find_model(value.object, "gpt-5.6").?;
+ try std.testing.expectEqual(@as(f64, 5), model.in);
+ try std.testing.expectEqual(@as(u64, 1_050_000), model.context);
+ try std.testing.expect(find_model(value.object, "gpt5.6") != null);
+ try std.testing.expect(find_model(value.object, "no-such-model") == null);
+}
+
+pub fn visibleSnapshots(parse_snapshot: anytype) !void {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const snapshot = parse_snapshot(arena.allocator(),
+ \\{"client_version":"9.9.9","models":[
+ \\ {"slug":"future-sol","visibility":"list","context_window":372000},
+ \\ {"slug":"future-hidden","visibility":"hide","context_window":999000},
+ \\ {"slug":"future-luna","visibility":"list","context_window":128000},
+ \\ {"slug":"future-luna","visibility":"list","context_window":1}]}
+ ).?;
+ try std.testing.expectEqualStrings("9.9.9", snapshot.client_version);
+ try std.testing.expectEqual(@as(usize, 2), snapshot.models.len);
+ try std.testing.expectEqualStrings("future-sol", snapshot.models[0].name);
+ try std.testing.expectEqual(@as(u64, 372_000), snapshot.models[0].context);
+ try std.testing.expectEqualStrings("future-luna", snapshot.models[1].name);
+ try std.testing.expectEqual(@as(u64, 128_000), snapshot.models[1].context);
+}
+
+pub fn versionFloor(floor: []const u8, effective_version: anytype, snapshot_matches: anytype) !void {
+ try std.testing.expectEqualStrings(floor, effective_version("0.130.0", null));
+ try std.testing.expectEqualStrings("0.145.0", effective_version("0.145.0", null));
+ try std.testing.expectEqualStrings(floor, effective_version("invalid", null));
+ try std.testing.expect(!snapshot_matches(.{
+ .models = &.{},
+ .client_version = "0.130.0",
+ }, floor));
+}
diff --git a/src/oauth.zig b/src/oauth.zig
index fce59728..1cafab5c 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -26,13 +26,11 @@ const Style = ansi.Style;
const util = @import("util.zig");
const strFieldObj = util.strFieldObj;
-const intFieldObj = util.intFieldObj;
-const root = @import("main.zig");
const unixMs = util.unixMs;
-const codegraff_device_base = root.codegraff_device_base;
const kimi_catalog = @import("kimi_catalog.zig");
const pricing = @import("pricing.zig");
+const codegraff = @import("oauth_codegraff.zig");
pub const CodexAuth = struct { token: []const u8, account: []const u8 };
@@ -509,123 +507,8 @@ pub fn loadXaiOAuth(io: Io, gpa: Allocator, arena: Allocator, home: []const u8,
return access;
}
-// Codegraff device-code login — mirrors graff's CodegraffDeviceStrategy: POST
-// /v1/device/start → show verification_uri + user_code → poll /v1/device/poll
-// until status "ok" yields the cg_sk_ key, written to ~/<codegraff_key_file>.
-const codegraff_key_file = ".simple-harness-codegraff.json";
-
-fn httpJsonPost(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);
- _ = try client.fetch(.{
- .location = .{ .url = url },
- .method = .POST,
- .payload = body,
- .response_writer = &aw.writer,
- .headers = .{ .content_type = .{ .override = "application/json" } },
- });
- const v = try std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });
- if (v != .object) return error.BadOAuthResponse;
- return v.object;
-}
-
-pub fn codegraffLogin(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 start_resp = httpJsonPost(io, gpa, arena, codegraff_device_base ++ "/v1/device/start", "{\"device_label\":\"simple-harness\"}") catch |err| {
- try out.print("✗ device/start failed: {t}\n", .{err});
- try out.flush();
- return;
- };
- const device_code = strFieldObj(start_resp, "device_code") orelse {
- try out.writeAll("✗ no device_code in start response\n");
- try out.flush();
- return;
- };
- const user_code = strFieldObj(start_resp, "user_code") orelse "";
- const vuri = strFieldObj(start_resp, "verification_uri") orelse "https://codegraff.com/cli/auth";
- const vuri_complete = strFieldObj(start_resp, "verification_uri_complete") orelse vuri;
- const interval: i64 = @max(1, intFieldObj(start_resp, "interval", 2));
- const expires: i64 = intFieldObj(start_resp, "expires_in", 600);
-
- try out.print("\nTo authorize, open:\n\n {s}\n\nand enter code: {s}{s}{s}\n\nwaiting for approval …\n", .{ vuri, style.bold, user_code, style.reset });
- try out.flush();
- openBrowser(io, vuri_complete);
-
- const poll_body = try std.fmt.allocPrint(arena, "{{\"device_code\":\"{s}\"}}", .{device_code});
- var waited: i64 = 0;
- while (waited < expires) : (waited += interval) {
- io.sleep(Io.Duration.fromSeconds(interval), .awake) catch {};
- const poll = httpJsonPost(io, gpa, arena, codegraff_device_base ++ "/v1/device/poll", poll_body) catch continue;
- const status = strFieldObj(poll, "status") orelse "pending";
- if (std.mem.eql(u8, status, "ok")) {
- const key = strFieldObj(poll, "api_key") orelse {
- try out.writeAll("✗ approved but no api_key returned\n");
- try out.flush();
- return;
- };
- try writeCodegraffKey(io, arena, home, key);
- try out.print("{s}✓{s} logged into codegraff — key saved to ~/{s}. /model deepseek-v4-pro\n", .{ style.green, style.reset, codegraff_key_file });
- try out.flush();
- return;
- } else if (std.mem.eql(u8, status, "denied")) {
- try out.writeAll("✗ authorization denied\n");
- try out.flush();
- return;
- } else if (std.mem.eql(u8, status, "expired")) {
- try out.writeAll("✗ code expired — run `graff login codegraff` again\n");
- try out.flush();
- return;
- }
- }
- try out.writeAll("✗ timed out waiting for approval\n");
- try out.flush();
-}
-
-fn writeCodegraffKey(io: Io, arena: Allocator, home: []const u8, key: []const u8) !void {
- const path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, codegraff_key_file });
- var obj: std.json.ObjectMap = .empty;
- try obj.put(arena, "api_key", .{ .string = key });
- var aw: Io.Writer.Allocating = .init(arena);
- var s: std.json.Stringify = .{ .writer = &aw.writer };
- try s.write(Value{ .object = obj });
- const f = try Io.Dir.cwd().createFile(io, path, .{});
- defer f.close(io);
- var wbuf: [4096]u8 = undefined;
- var fw = f.writer(io, &wbuf);
- try fw.interface.writeAll(aw.writer.buffered());
- try fw.interface.flush();
-}
-
-/// Load a codegraff key without an env var: the harness's own login file
-/// (~/.simple-harness-codegraff.json) first, then graff's store
-/// (~/forge/.credentials.json: array, entry id=="codegraff", .auth_details.api_key).
-pub fn loadCodegraffKey(io: Io, arena: Allocator, home: []const u8) ?[]const u8 {
- if (std.fmt.allocPrint(arena, "{s}/{s}", .{ home, codegraff_key_file })) |path| {
- if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024))) |data| {
- if (std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always })) |v| {
- if (v == .object) if (v.object.get("api_key")) |k| if (k == .string and k.string.len > 0) return k.string;
- } else |_| {}
- } else |_| {}
- } else |_| {}
- if (std.fmt.allocPrint(arena, "{s}/forge/.credentials.json", .{home})) |path| {
- if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256 * 1024))) |data| {
- if (std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always })) |v| {
- if (v == .array) for (v.array.items) |e| {
- if (e != .object) continue;
- const id = if (e.object.get("id")) |i| (if (i == .string) i.string else "") else "";
- if (!std.mem.eql(u8, id, "codegraff")) continue;
- if (e.object.get("auth_details")) |ad| if (ad == .object)
- if (ad.object.get("api_key")) |k| if (k == .string and k.string.len > 0) return k.string;
- };
- } else |_| {}
- } else |_| {}
- } else |_| {}
- return null;
-}
+pub const codegraffLogin = codegraff.login;
+pub const loadCodegraffKey = codegraff.loadKey;
test "b64url: url-safe base64 without padding" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
diff --git a/src/oauth_codegraff.zig b/src/oauth_codegraff.zig
new file mode 100644
index 00000000..e7ad5713
--- /dev/null
+++ b/src/oauth_codegraff.zig
@@ -0,0 +1,127 @@
+//! Codegraff device-code login and local credential discovery.
+
+const std = @import("std");
+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 codegraff_device_base = @import("main.zig").codegraff_device_base;
+
+const key_file = ".simple-harness-codegraff.json";
+
+fn httpJsonPost(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);
+ _ = try client.fetch(.{
+ .location = .{ .url = url },
+ .method = .POST,
+ .payload = body,
+ .response_writer = &aw.writer,
+ .headers = .{ .content_type = .{ .override = "application/json" } },
+ });
+ const value = try std.json.parseFromSliceLeaky(Value, arena, aw.writer.buffered(), .{ .allocate = .alloc_always });
+ if (value != .object) return error.BadOAuthResponse;
+ return value.object;
+}
+
+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;
+
+ const start_resp = httpJsonPost(io, gpa, arena, codegraff_device_base ++ "/v1/device/start", "{\"device_label\":\"simple-harness\"}") catch |err| {
+ try out.print("✗ device/start failed: {t}\n", .{err});
+ try out.flush();
+ return;
+ };
+ const device_code = strFieldObj(start_resp, "device_code") orelse {
+ try out.writeAll("✗ no device_code in start response\n");
+ try out.flush();
+ return;
+ };
+ const user_code = strFieldObj(start_resp, "user_code") orelse "";
+ const verification_uri = strFieldObj(start_resp, "verification_uri") orelse "https://codegraff.com/cli/auth";
+ const complete_uri = strFieldObj(start_resp, "verification_uri_complete") orelse verification_uri;
+ const interval: i64 = @max(1, intFieldObj(start_resp, "interval", 2));
+ const expires: i64 = intFieldObj(start_resp, "expires_in", 600);
+
+ try out.print("\nTo authorize, open:\n\n {s}\n\nand enter code: {s}{s}{s}\n\nwaiting for approval …\n", .{ verification_uri, style.bold, user_code, style.reset });
+ try out.flush();
+ openBrowser(io, complete_uri);
+
+ const poll_body = try std.fmt.allocPrint(arena, "{{\"device_code\":\"{s}\"}}", .{device_code});
+ var waited: i64 = 0;
+ while (waited < expires) : (waited += interval) {
+ io.sleep(Io.Duration.fromSeconds(interval), .awake) catch {};
+ const poll = httpJsonPost(io, gpa, arena, codegraff_device_base ++ "/v1/device/poll", poll_body) catch continue;
+ const status = strFieldObj(poll, "status") orelse "pending";
+ if (std.mem.eql(u8, status, "ok")) {
+ const key = strFieldObj(poll, "api_key") orelse {
+ try out.writeAll("✗ approved but no api_key returned\n");
+ try out.flush();
+ return;
+ };
+ try writeKey(io, arena, home, key);
+ try out.print("{s}✓{s} logged into codegraff — key saved to ~/{s}. /model deepseek-v4-pro\n", .{ style.green, style.reset, key_file });
+ try out.flush();
+ return;
+ } else if (std.mem.eql(u8, status, "denied")) {
+ try out.writeAll("✗ authorization denied\n");
+ try out.flush();
+ return;
+ } else if (std.mem.eql(u8, status, "expired")) {
+ try out.writeAll("✗ code expired — run `graff login codegraff` again\n");
+ try out.flush();
+ return;
+ }
+ }
+ try out.writeAll("✗ timed out waiting for approval\n");
+ try out.flush();
+}
+
+fn writeKey(io: Io, arena: Allocator, home: []const u8, key: []const u8) !void {
+ const path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, key_file });
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "api_key", .{ .string = key });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var stringify: std.json.Stringify = .{ .writer = &aw.writer };
+ try stringify.write(Value{ .object = obj });
+ const file = try Io.Dir.cwd().createFile(io, path, .{});
+ defer file.close(io);
+ var wbuf: [4096]u8 = undefined;
+ var writer = file.writer(io, &wbuf);
+ try writer.interface.writeAll(aw.writer.buffered());
+ try writer.interface.flush();
+}
+
+/// Load the harness login file first, then graff's credential store.
+pub fn loadKey(io: Io, arena: Allocator, home: []const u8) ?[]const u8 {
+ if (std.fmt.allocPrint(arena, "{s}/{s}", .{ home, key_file })) |path| {
+ if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024))) |data| {
+ if (std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always })) |value| {
+ if (value == .object) if (value.object.get("api_key")) |key|
+ if (key == .string and key.string.len > 0) return key.string;
+ } else |_| {}
+ } else |_| {}
+ } else |_| {}
+ if (std.fmt.allocPrint(arena, "{s}/forge/.credentials.json", .{home})) |path| {
+ if (Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(256 * 1024))) |data| {
+ if (std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always })) |value| {
+ if (value == .array) for (value.array.items) |entry| {
+ if (entry != .object) continue;
+ const id = if (entry.object.get("id")) |item| (if (item == .string) item.string else "") else "";
+ if (!std.mem.eql(u8, id, "codegraff")) continue;
+ if (entry.object.get("auth_details")) |details| if (details == .object)
+ if (details.object.get("api_key")) |key| if (key == .string and key.string.len > 0) return key.string;
+ };
+ } else |_| {}
+ } else |_| {}
+ } else |_| {}
+ return null;
+}