graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(acp): advertise auth before provider startup
yxlyx8e1787a55fc5
diff --git a/build.zig b/build.zigindex 72ea869f..091729a5 100644--- a/build.zig+++ b/build.zig@@ -116,8 +116,11 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addAnonymousImport("spec_prompt_prefix", .{ .root_source_file = b.path("spec/kernels/prompt_prefix.json") });unit_tests.root_module.addAnonymousImport("spec_prompt_stable", .{ .root_source_file = b.path("spec/kernels/prompt_stable.json") });const run_tests = b.addRunArtifact(unit_tests);- const test_step = b.step("test", "Run unit tests");+ const test_step = b.step("test", "Run unit and subprocess integration tests");test_step.dependOn(&run_tests.step);+ const acp_preauth_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-preauth.py" });+ acp_preauth_test.addArtifactArg(exe);+ test_step.dependOn(&acp_preauth_test.step);// Learning kit: the adapter/suite files `graff learn init` materializes// into a workspace so zero-configuration learning needs no repo checkout.diff --git a/docs/acp-registry.md b/docs/acp-registry.mdindex dfc33b81..ceb182d2 100644--- a/docs/acp-registry.md+++ b/docs/acp-registry.md@@ -19,12 +19,14 @@ and the host recipe stays [embedding.md](embedding.md). Replace those with| Mid-turn `session/update` (thought / tool / text) | Shipped (ADR [0032](adr/0032-acp-streams-mid-turn.md), #612). || Provider login | `graff login` / keychain / env keys. Not ACP `authenticate`. || `initialize.authMethods` | **Shipped.** `graff-login` / `type: "terminal"` / `args: ["login"]`. `authenticate` stays unused — the client re-spawns `graff login`. |+| Credential-free startup | **Shipped.** A clean `graff acp` initializes, then returns ACP `auth_required` until login and respawn. || `session/load`, `session/request_permission` | Not implemented. Unattended + `--yolo` is the host path. |A stale comment on #613 said #612 was still open. It is not: streaming is on-the tagged v0.0.279 cut. The remaining blocker for a listing is protocol auth.+the tagged v0.0.279 cut. The final in-repo registry prerequisite was startup+ordering: key resolution used to exit before a clean process could initialize.-## Registry auth (the actual blocker)+## Registry authThe registry's [AUTHENTICATION.md](https://github.com/agentclientprotocol/registry/blob/main/AUTHENTICATION.md)accepts only:@@ -53,6 +55,14 @@ advertises it:Do not invent Agent Auth that duplicates `graff login`. Do not add env-varauth to satisfy the registry — it is not one of the two accepted types.+When startup finds no provider credential, the lightweight ACP loop uses the+same `acp_engine` initialize response as the full runtime. Requests that need+a live Agent are rejected without exiting the loop:++```json+{"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"Authentication required: run `graff login`, then restart the ACP agent."}}+```+CI on the registry repo runs`python3 .github/workflows/verify_agents.py --auth-check` and rejects anagent whose `initialize` omits `authMethods`.@@ -121,8 +131,9 @@ Pin `sha256` from that release's `SHA256SUMS` before the PR. Archive layoutis sometimes flat (`graff` at the tarball root) and sometimes nested(`graff-<target>/graff`); `cmd` must match what the installer extracts.-`authMethods` is on the wire. Pin `sha256` from a real release, then open the-registry PR in the other repo. This repo still does not fetch the catalog.+`authMethods` and the credential-free handshake are on the wire. Pin `sha256`+from a real release, then open the registry PR in the other repo. This repo+still does not fetch the catalog.## Not this repodiff --git a/scripts/test-acp-preauth.py b/scripts/test-acp-preauth.pynew file mode 100644index 00000000..4ea0fa68--- /dev/null+++ b/scripts/test-acp-preauth.py@@ -0,0 +1,145 @@+#!/usr/bin/env python3+"""Registry-shaped subprocess regression for credential-free `graff acp`."""++import json+import os+import platform+import subprocess+import sys+import tempfile+from pathlib import Path++PASSTHROUGH = {+ "CI",+ "COMSPEC",+ "NPM_CONFIG_CACHE",+ "NODE_EXTRA_CA_CERTS",+ "PATH",+ "PATHEXT",+ "PYTHON_KEYRING_BACKEND",+ "PYTHON_KEYRING_DISABLED",+ "REQUESTS_CA_BUNDLE",+ "SSL_CERT_DIR",+ "SSL_CERT_FILE",+ "SystemRoot",+ "TMP",+ "TMPDIR",+ "TEMP",+ "UV_CACHE_DIR",+ "WINDIR",+ "XDG_CACHE_HOME",+ "XDG_CONFIG_HOME",+}+++def fail(message: str, proc: subprocess.CompletedProcess[str]) -> None:+ raise AssertionError(+ f"{message}\nexit={proc.returncode}\nstdout={proc.stdout!r}\nstderr={proc.stderr!r}"+ )+++def main() -> None:+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve()+ initialize = {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": 1,+ "clientInfo": {"name": "ACP Registry Validator", "version": "1.0.0"},+ "clientCapabilities": {+ "terminal": True,+ "fs": {"readTextFile": True, "writeTextFile": True},+ "_meta": {"terminal_output": True, "terminal-auth": True},+ },+ },+ }+ def padded(record: dict, length: int) -> str:+ line = json.dumps(record, separators=(",", ":"))+ if len(line) > length:+ raise AssertionError(f"fixture is longer than {length} bytes")+ return line + " " * (length - len(line))++ requests = [+ padded(initialize, 65535),+ "{not json",+ {"jsonrpc": "2.0", "method": "initialize"}, # notification+ padded({"jsonrpc": "2.0", "id": 20, "method": "session/new", "params": {}}, 65536),+ padded({"jsonrpc": "2.0", "id": 21, "method": "session/new", "params": {}}, 70000),+ {**initialize, "id": 4},+ {"jsonrpc": "2.0", "id": 2, "method": "session/new", "params": {"cwd": "/tmp"}},+ {"jsonrpc": "2.0", "id": 3, "method": "graff/models", "params": {}},+ ]+ eof_oversize = padded({"jsonrpc": "2.0", "id": 30, "method": "session/new", "params": {}}, 70000)++ with tempfile.TemporaryDirectory(prefix="graff-acp-preauth-") as temp:+ home = Path(temp) / "home"+ home.mkdir()+ env = {name: value for name in PASSTHROUGH if (value := os.environ.get(name))}+ env.update({"HOME": str(home), "TERM": "dumb"})+ # HOME does not isolate the macOS login Keychain. Shadow `security` so+ # this regression remains credential-free on a signed-in developer Mac.+ if platform.system() == "Darwin":+ shim_dir = Path(temp) / "bin"+ shim_dir.mkdir()+ shim = shim_dir / "security"+ shim.write_text("#!/bin/sh\nexit 44\n")+ shim.chmod(0o755)+ env["PATH"] = str(shim_dir) + os.pathsep + env.get("PATH", "")++ proc = subprocess.run(+ [str(binary), "acp"],+ input="".join((request if isinstance(request, str) else json.dumps(request, separators=(",", ":"))) + "\n" for request in requests) + eof_oversize,+ text=True,+ capture_output=True,+ env=env,+ timeout=15,+ check=False,+ )++ if proc.returncode != 0:+ fail("credential-free ACP process did not exit cleanly on EOF", proc)+ if proc.stderr:+ fail("credential-free ACP wrote diagnostics instead of staying protocol-clean", proc)+ try:+ responses = [json.loads(line) for line in proc.stdout.splitlines()]+ except json.JSONDecodeError as error:+ fail(f"stdout contained a non-JSON ACP line: {error}", proc)+ if len(responses) != 4:+ fail("expected two initializes plus two auth-required responses", proc)++ if [response.get("id") for response in responses] != [1, 4, 2, 3]:+ fail("oversized/notification records disturbed ACP response order", proc)++ result = responses[0].get("result", {})+ expected_auth = [+ {+ "id": "graff-login",+ "name": "graff login",+ "description": "Interactive terminal login (codegraff / Codex / Kimi)",+ "type": "terminal",+ "args": ["login"],+ }+ ]+ if responses[0].get("id") != 1 or result.get("protocolVersion") != 1:+ fail("initialize response did not correlate or negotiate ACP v1", proc)+ if result.get("authMethods") != expected_auth:+ fail("initialize did not advertise the registry Terminal Auth descriptor", proc)+ implementation = result.get("agentImplementation", {})+ if implementation.get("name") != "graff" or not implementation.get("version"):+ fail("initialize omitted the graff implementation identity", proc)++ expected_error = {+ "code": -32000,+ "message": "Authentication required: run `graff login`, then restart the ACP agent.",+ }+ if responses[2] != {"jsonrpc": "2.0", "id": 2, "error": expected_error}:+ fail("session/new was not rejected with ACP auth_required", proc)+ if responses[3] != {"jsonrpc": "2.0", "id": 3, "error": expected_error}:+ fail("graff/models was not rejected with ACP auth_required", proc)++ print("acp pre-auth integration: ok")+++if __name__ == "__main__":+ main()diff --git a/scripts/tui-pty-guard.py b/scripts/tui-pty-guard.pyindex d75bda65..0316058b 100644--- a/scripts/tui-pty-guard.py+++ b/scripts/tui-pty-guard.py@@ -54,13 +54,16 @@ def boot(fd):return out-def spawn(cwd, env_extra):+def spawn(cwd, env_extra, entry="tui"):import ptypid, fd = pty.fork()if pid == 0:os.chdir(cwd)os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])+ if env_extra.get("GRAFF_TEST_NO_CREDENTIALS"):+ for name in PROVIDER_ENV:+ os.environ.pop(name, None)+ os.execv(BIN, [BIN, entry, "--yolo"])return pid, fd@@ -121,6 +124,16 @@ def mode_imbalance(stream):return sorted(wrong), max(depth, 0)+PROVIDER_ENV = {+ "ANTHROPIC_API_KEY", "CODEGRAFF_API_KEY", "DEEPSEEK_API_KEY",+ "OPENAI_API_KEY", "MINIMAX_API_KEY", "XIAOMI_API_KEY", "KILO_API_KEY",+ "GROQ_API_KEY", "CEREBRAS_API_KEY", "MISTRAL_API_KEY", "KIMI_API_KEY",+ "MOONSHOT_API_KEY", "XAI_API_KEY", "ZAI_API_KEY", "AI_GATEWAY_API_KEY",+ "OPENROUTER_API_KEY", "FUGU_API_KEY", "FIREWORKS_API_KEY", "MLX_API_KEY",+ "LMSTUDIO_API_KEY", "CODEX_DISABLED", "MYROUTER_API_KEY",+}++def fresh_ws():ws = tempfile.mkdtemp(prefix="tui-guard-")empty = os.path.join(ws, "empty-mcp.json")@@ -129,6 +142,23 @@ def fresh_ws():return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}+def fresh_no_credentials():+ ws, env = fresh_ws()+ home = os.path.join(ws, "home")+ os.makedirs(os.path.join(home, ".codex"))+ env.update({"HOME": home, "CODEX_HOME": os.path.join(home, ".codex"),+ "TERM": "xterm", "GRAFF_TEST_NO_CREDENTIALS": "1"})+ if sys.platform == "darwin":+ shim_dir = os.path.join(ws, "bin")+ os.makedirs(shim_dir)+ shim = os.path.join(shim_dir, "security")+ with open(shim, "w") as f:+ f.write("#!/bin/sh\nexit 44\n")+ os.chmod(shim, 0o755)+ env["PATH"] = shim_dir + os.pathsep + os.environ.get("PATH", "")+ return ws, env++def quit_seq(fd):os.write(fd, b"\x11") # Ctrl+Q — single byte, parser-independent@@ -226,6 +256,27 @@ def check_c():return None+def check_d():+ """Credential failure after the early pager claim restores the shell."""+ for entry in ("tui", "repl"):+ ws, env = fresh_no_credentials()+ pid, fd = spawn(ws, env, entry)+ out = drain(fd, 5.0)+ status = reap(pid)+ if status is None:+ return f"D/{entry}: fatal credential path did not exit"+ if b"no API key found" not in out:+ return f"D/{entry}: fatal login diagnostic was not visible on the tty"+ latched, depth = mode_imbalance(out)+ if latched:+ return f"D/{entry}: terminal modes remained latched: {latched}"+ if depth != 0:+ return f"D/{entry}: kitty depth was {depth}"+ if b"\x1b[?1049h" in out and b"\x1b[?1049l" not in out:+ return f"D/{entry}: alt-screen was not released"+ return None++def main():if not os.path.exists(BIN):print(f"tui-pty-guard: {BIN} not built — skipping")@@ -236,7 +287,7 @@ def main():print("tui-pty-guard: no pty support here — skipping")return 0failures = []- for name, fn in (("mode-balance", check_a), ("hostile-input", check_b), ("kill-restore", check_c)):+ for name, fn in (("mode-balance", check_a), ("hostile-input", check_b), ("kill-restore", check_c), ("missing-credentials", check_d)):try:err = fn()except OSError as e:diff --git a/src/acp_auth.zig b/src/acp_auth.zigindex d5841177..5f03a0e8 100644--- a/src/acp_auth.zig+++ b/src/acp_auth.zig@@ -26,6 +26,8 @@ pub const terminal_login = AuthMethod{pub const advertised = [_]AuthMethod{terminal_login};+pub const required_message = "Authentication required: run `graff login`, then restart the ACP agent.";+/// v1 clients that can open an interactive terminal set/// `clientCapabilities.auth.terminal = true`. Missing keys default false;/// we still advertise (registry CI must see a method) because `graff login`diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 83eaf62c..6c6b129c 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -18,6 +18,7 @@ pub const writeError = proto.writeError;pub const writeSessionUpdate = proto.writeSessionUpdate;pub const err_method_not_found = proto.err_method_not_found;pub const err_internal = proto.err_internal;+pub const err_auth_required = proto.err_auth_required;/// Stamped by the CLI (`harness_version`) or the embed create() call.pub var implementation_version: []const u8 = "0.0.0-embed";@@ -99,9 +100,8 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)try respond(w, req, .{ .stopReason = stop });}-pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u8) !void {- const req = parseRequest(arena, line) orelse return;- if (std.mem.eql(u8, req.method, "initialize")) return respond(w, req, .{+fn respondInitialize(w: *Io.Writer, req: proto.Request) !void {+ return respond(w, req, .{.protocolVersion = negotiateVersion(req.params),.agentCapabilities = .{.loadSession = false,@@ -110,6 +110,19 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u.agentImplementation = proto.AgentImplementation{ .version = implementation_version },.authMethods = acp_auth.advertised,});+}++/// Credential-free ACP bootstrap. Initialize is byte-for-byte the full+/// engine response; every request that needs a live Agent is auth-gated.+pub fn handlePreAuthLine(arena: Allocator, w: *Io.Writer, line: []const u8) !void {+ const req = parseRequest(arena, line) orelse return;+ if (std.mem.eql(u8, req.method, "initialize")) return respondInitialize(w, req);+ return respondError(w, req, err_auth_required, acp_auth.required_message);+}++pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u8) !void {+ const req = parseRequest(arena, line) orelse return;+ if (std.mem.eql(u8, req.method, "initialize")) return respondInitialize(w, req);if (std.mem.eql(u8, req.method, "authenticate"))return respondError(w, req, err_method_not_found, "terminal auth is out of band: re-spawn graff login");if (std.mem.eql(u8, req.method, "session/new")) {diff --git a/src/acp_preauth.zig b/src/acp_preauth.zignew file mode 100644index 00000000..75cba96f--- /dev/null+++ b/src/acp_preauth.zig@@ -0,0 +1,173 @@+//! Credential-free `graff acp` bootstrap. This loop exists only when startup+//! found no usable provider credential; authenticated launches continue into+//! the unchanged live Agent runtime in acp.zig.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const engine = @import("acp_engine.zig");++pub fn serve(gpa: Allocator, in: *Io.Reader, out: *Io.Writer) !void {+ var scratch_state = std.heap.ArenaAllocator.init(gpa);+ defer scratch_state.deinit();+ const scratch = scratch_state.allocator();+ while (true) {+ const line = in.takeDelimiter('\n') catch |err| switch (err) {+ // Reader.takeDelimiter leaves an overlong record untouched. Drop+ // it through its newline with constant memory, then keep serving.+ error.StreamTooLong => {+ _ = in.discardDelimiterInclusive('\n') catch |discard_err| switch (discard_err) {+ error.EndOfStream => return,+ else => |e| return e,+ };+ continue;+ },+ else => |e| return e,+ };+ const record = line orelse break;+ try engine.handlePreAuthLine(scratch, out, record);+ // The writer may still refer to request data until it drains. Do this+ // before resetting the scratch arena for the next record.+ try out.flush();+ _ = scratch_state.reset(.retain_capacity);+ }+}++pub fn run(io: Io, gpa: Allocator, implementation_version: []const u8) !void {+ engine.implementation_version = implementation_version;+ var stdin_buf: [64 * 1024]u8 = undefined;+ var stdin_reader = Io.File.stdin().reader(io, &stdin_buf);+ var stdout_buf: [4096]u8 = undefined;+ var stdout_writer = Io.File.stdout().writer(io, &stdout_buf);+ try serve(gpa, &stdin_reader.interface, &stdout_writer.interface);+}++fn serveFixed(gpa: Allocator, input: []const u8, storage: []u8) ![]const u8 {+ var read_buf: [64 * 1024]u8 = undefined;+ const calls = [_]std.testing.Reader.Call{.{ .buffer = input }};+ var source = std.testing.Reader.init(&read_buf, &calls);+ var writer: Io.Writer = .fixed(storage);+ try serve(gpa, &source.interface, &writer);+ return writer.buffered();+}++fn appendPaddedLine(input: *std.array_list.Managed(u8), line_len: usize, prefix: []const u8) !void {+ const start = input.items.len;+ try input.appendSlice(prefix);+ try input.resize(start + line_len);+ @memset(input.items[start + prefix.len ..], ' ');+ try input.append('\n');+}++test "pre-auth returns ACP auth_required with terminal-login instructions" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ var buf: [2048]u8 = undefined;+ const output = try serveFixed(state.allocator(),+ \\{"jsonrpc":"2.0","id":2,"method":"session/new","params":{"cwd":"/tmp"}}+ \\{"jsonrpc":"2.0","id":"prompt-1","method":"session/prompt","params":{}}+ \\+ , &buf);+ try std.testing.expectEqualStrings(+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"error\":{\"code\":-32000,\"message\":\"Authentication required: run `graff login`, then restart the ACP agent.\"}}\n" +++ "{\"jsonrpc\":\"2.0\",\"id\":\"prompt-1\",\"error\":{\"code\":-32000,\"message\":\"Authentication required: run `graff login`, then restart the ACP agent.\"}}\n",+ output,+ );+}++test "pre-auth answers multiple initialize requests from the shared engine" {+ engine.implementation_version = "preauth-test";+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ var buf: [4096]u8 = undefined;+ const output = try serveFixed(state.allocator(),+ \\{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}+ \\{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":9}}+ \\+ , &buf);+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, output, "\"authMethods\""));+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, output, "graff-login"));+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, output, "preauth-test"));+}++test "pre-auth ignores invalid input and continues serving requests" {+ engine.implementation_version = "preauth-test";+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ var buf: [2048]u8 = undefined;+ const output = try serveFixed(state.allocator(),+ \\{not json+ \\[1,2]+ \\{"jsonrpc":"2.0","method":"initialize"}+ \\{"jsonrpc":"2.0","id":7,"method":"initialize","params":{"protocolVersion":1}}+ \\+ , &buf);+ try std.testing.expect(std.mem.startsWith(u8, output, "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":"));+ try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, output, "\n"));+}++test "pre-auth accepts 65535 bytes and discards 65536 and 70000 byte records" {+ engine.implementation_version = "preauth-boundaries";+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var input = std.array_list.Managed(u8).init(a);+ try appendPaddedLine(&input, 65535, "{\"jsonrpc\":\"2.0\",\"id\":10,\"method\":\"initialize\",\"params\":{}}");+ try appendPaddedLine(&input, 65536, "{\"jsonrpc\":\"2.0\",\"id\":20,\"method\":\"session/new\",\"params\":{}}");+ try appendPaddedLine(&input, 70000, "{\"jsonrpc\":\"2.0\",\"id\":21,\"method\":\"session/new\",\"params\":{}}");+ try input.appendSlice("{\"jsonrpc\":\"2.0\",\"id\":11,\"method\":\"initialize\",\"params\":{}}\n");+ var buf: [4096]u8 = undefined;+ const output = try serveFixed(a, input.items, &buf);+ try std.testing.expect(std.mem.indexOf(u8, output, "\"id\":10") != null);+ try std.testing.expect(std.mem.indexOf(u8, output, "\"id\":11") != null);+ try std.testing.expect(std.mem.indexOf(u8, output, "\"id\":20") == null);+ try std.testing.expect(std.mem.indexOf(u8, output, "\"id\":21") == null);+ try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, output, "\"authMethods\""));+}++test "pre-auth reclaims scratch allocations across near-limit records" {+ engine.implementation_version = "preauth-reclaim";+ var backing: [256 * 1024]u8 = undefined;+ var fixed = std.heap.FixedBufferAllocator.init(&backing);++ var record: [64 * 1024]u8 = undefined;+ const prefix = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"session/new\",\"params\":{\"blob\":\"";+ const suffix = "\"}}";+ const record_len = record.len - 1;+ @memcpy(record[0..prefix.len], prefix);+ @memset(record[prefix.len .. record_len - suffix.len], 'x');+ @memcpy(record[record_len - suffix.len .. record_len], suffix);+ record[record_len] = '\n';++ var calls: [2048]std.testing.Reader.Call = undefined;+ for (&calls) |*call| call.* = .{ .buffer = &record };+ var read_buf: [64 * 1024]u8 = undefined;+ var source = std.testing.Reader.init(&read_buf, &calls);+ var sink_buf: [256]u8 = undefined;+ var sink = Io.Writer.Discarding.init(&sink_buf);+ try serve(fixed.allocator(), &source.interface, &sink.writer);+ try std.testing.expectEqual(calls.len, source.next_call_index);+}++test "pre-auth discards an oversized record that reaches EOF without newline" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var input = std.array_list.Managed(u8).init(a);+ const prefix = "{\"jsonrpc\":\"2.0\",\"id\":30,\"method\":\"session/new\",\"params\":{}}";+ try input.appendSlice(prefix);+ try input.resize(70000);+ @memset(input.items[prefix.len..], ' ');+ var buf: [256]u8 = undefined;+ const output = try serveFixed(a, input.items, &buf);+ try std.testing.expectEqual(@as(usize, 0), output.len);+}++test "pre-auth exits cleanly on EOF" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ var buf: [64]u8 = undefined;+ const output = try serveFixed(state.allocator(), "", &buf);+ try std.testing.expectEqual(@as(usize, 0), output.len);+}diff --git a/src/acp_protocol.zig b/src/acp_protocol.zigindex 11beacb6..38a5f160 100644--- a/src/acp_protocol.zig+++ b/src/acp_protocol.zig@@ -13,6 +13,7 @@ pub const protocol_version: i64 = 1;pub const err_method_not_found: i32 = -32601;pub const err_internal: i32 = -32603;+pub const err_auth_required: i32 = -32000;/// ACP v1 `promptCapabilities` (https://agentclientprotocol.com/protocol/v1/schema)./// Missing keys default to false; we send the three named fields so a clientdiff --git a/src/main.zig b/src/main.zigindex a37727d5..fcc0321d 100644--- a/src/main.zig+++ b/src/main.zig@@ -284,7 +284,7 @@ pub fn main(init: std.process.Init) !void {if (try startup.runSubcommand(io, gpa, arena, init, flags)) return;// Credential/model resolution (env vars → on-disk logins → `harness key set` store, env always wins; then --model or the last-saved model) lives// in startup.zig as resolveKeys() — pure over env/disk/arena, safe to call outside main()'s own stack frame.- const resolved_keys = try startup.resolveKeys(io, gpa, arena, init.environ_map, flags.model_flag, flags.subagent_provider_flag orelse init.environ_map.get("GRAFF_SUBAGENT_PROVIDER"));+ const resolved_keys = (try startup.resolveKeysOrRunAcpPreAuth(io, gpa, arena, init, flags)) orelse return;boot.mark(io, "credentials/model");var keys = resolved_keys.keys;const default_provider = resolved_keys.default_provider;@@ -586,6 +586,7 @@ test { // pull in tests from imported modules (mcp.zig)_ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests_ = @import("agent_server_compact.zig"); // server-side autocompact (codex Responses)+ _ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root_ = @import("task_outcome.zig"); // goal-outcome telemetry events_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here_ = @import("additional_tests.zig");diff --git a/src/startup.zig b/src/startup.zigindex a305aa7e..f2adc02e 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -181,6 +181,7 @@ pub fn buildSystemPrompt(}const args = @import("args.zig");+const acp_preauth = @import("acp_preauth.zig");const mcp_cli = @import("mcp_cli.zig");const learn_cli = @import("learn_cli.zig");const cli = @import("cli.zig");@@ -190,6 +191,18 @@ const schema = @import("schema.zig");const serve = @import("serve.zig");const main_mod = @import("main.zig");+/// A credentialed ACP launch returns the exact ResolvedKeys value used before+/// #613. Only a launch with no usable provider enters the lightweight loop;+/// every other terminal trajectory keeps resolveKeys' existing fatal behavior.+pub fn resolveKeysOrRunAcpPreAuth(io: Io, gpa: Allocator, arena: Allocator, init: std.process.Init, flags: args.Flags) !?ResolvedKeys {+ const worker_hint = flags.subagent_provider_flag orelse init.environ_map.get("GRAFF_SUBAGENT_PROVIDER");+ const is_acp = flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "acp");+ if (!is_acp) return try resolveKeys(io, gpa, arena, init.environ_map, flags.model_flag, worker_hint);+ if (try startup_keys.resolveKeysOptional(io, gpa, arena, init.environ_map, flags.model_flag, worker_hint)) |resolved| return resolved;+ try acp_preauth.run(io, gpa, main_mod.harness_version);+ return null;+}+/// The early subcommand/flag branches that exit before any credential/// resolution or Agent construction happens — `--help`/`--version`, `key`,/// `mcp add`, `login`, `serve`, `update`, `worktree` (list/merge), `sandboxes`,diff --git a/src/startup_keys.zig b/src/startup_keys.zigindex 3ab9805b..a6866b59 100644--- a/src/startup_keys.zig+++ b/src/startup_keys.zig@@ -118,6 +118,26 @@ test "Kimi catalog loads at startup only when selection can observe it" {/// std.process.fatal exactly as that block did (no key found, or a bad/// --model value).pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, model_flag: ?[]const u8, worker_provider_hint: ?[]const u8) !ResolvedKeys {+ return (try resolveKeysOptional(io, gpa, arena, environ_map, model_flag, worker_provider_hint)) orelse missingCredentials();+}++fn missingCredentials() noreturn {+ // `tui`/TTY `repl` claim the pager before credential resolution. Fatal+ // exits do not unwind defers, so release that claim before stderr prints.+ @import("tui").restore.releaseIfOwned();+ std.process.fatal(+ \\no API key found. quickest fixes:+ \\ graff login free codegraff key (device-code OAuth)+ \\ graff key set <provider> <key> store a key (macOS Keychain, else 0600 file)+ \\ export ANTHROPIC_API_KEY=sk-ant-… or CODEGRAFF/DEEPSEEK/OPENAI/MINIMAX/XIAOMI/KIMI/MOONSHOT/XAI/ZAI _API_KEY+ \\a Codex CLI login (~/.codex/auth.json) is also picked up automatically.+ , .{});+}++/// The ACP bootstrap needs to distinguish "no credential yet" from startup+/// failures without manufacturing a provider. All successful resolution and+/// model-selection behavior is shared with resolveKeys above.+pub fn resolveKeysOptional(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, model_flag: ?[]const u8, worker_provider_hint: ?[]const u8) !?ResolvedKeys {var keys: provider_mod.Keys = .{ .values = undefined };for (provider_mod.provider_specs, &keys.values, &keys.sources) |spec, *value, *source| {value.* = environ_map.get(spec.env_key);@@ -201,15 +221,7 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp// discovery. Provider-specific Codex windows remain authoritative.models_cache.loadOverlay(io, arena, home);}- var default_provider = keys.defaultProvider() catch {- std.process.fatal(- \\no API key found. quickest fixes:- \\ graff login free codegraff key (device-code OAuth)- \\ graff key set <provider> <key> store a key (Keychain; POSIX 0600 file; Windows home ACL)- \\ export ANTHROPIC_API_KEY=sk-ant-… or CODEGRAFF/DEEPSEEK/OPENAI/MINIMAX/XIAOMI/KIMI/MOONSHOT/XAI/ZAI _API_KEY- \\a Codex CLI login (~/.codex/auth.json) is also picked up automatically.- , .{});- };+ var default_provider = keys.defaultProvider() catch return null;var stale_saved_model: ?[]const u8 = null;var preferred_provider: ?[]const u8 = null;// `--model <name|provider>` pins the startup model (same resolution as /model).