const std = @import("std"); const agent = @import("agent.zig"); const Child = @import("child.zig").Child; const models = @import("models.zig"); const Provider = @import("provider.zig").Provider; const providers = @import("providers.zig"); const remote = @import("remote.zig"); const tui = @import("tui.zig"); const vaxis = @import("vaxis"); /// Restores the terminal before the default panic output when the program panics. pub const panic = std.debug.FullPanic(panicHandler); fn panicHandler(message: []const u8, ret_addr: ?usize) noreturn { vaxis.recover(); std.debug.defaultPanic(message, ret_addr); } pub const ConfigError = error{ MissingModel, UnknownModel, MissingLevel, UnknownLevel, MissingAccountId, MissingApiToken }; /// Parses the command line and the environment. Returns the model and how to /// reach it, or an error whose text names the problem. pub fn configure(args: []const [:0]const u8, env: std.process.Environ.Map) ConfigError!Config { var name: []const u8 = "deepseek-v4.1-flash"; var level = models.default_level; var embed = false; var index: usize = 1; while (index < args.len) : (index += 1) { if (std.mem.eql(u8, args[index], "--model")) { if (index + 1 >= args.len) { return error.MissingModel; } name = args[index + 1]; index += 1; } else if (std.mem.eql(u8, args[index], "--thinking")) { if (index + 1 >= args.len) { return error.MissingLevel; } level = std.meta.stringToEnum(models.Level, args[index + 1]) orelse return error.UnknownLevel; index += 1; } else if (std.mem.eql(u8, args[index], "--embed")) { embed = true; } } const model = models.find(name) orelse return error.UnknownModel; return .{ .model = model, .level = level, .embed = embed, .access = switch (model.provider) { .fake => .fake, .workers_ai => .{ .workers_ai = .{ .account_id = env.get("CLOUDFLARE_ACCOUNT_ID") orelse return error.MissingAccountId, .token = env.get("CLOUDFLARE_API_TOKEN") orelse env.get("CLOUDFLARE_AUTH_TOKEN") orelse return error.MissingApiToken, } }, } }; } pub const Config = struct { /// Be a core for the UI that started this process: requests arrive on /// the standard input and messages leave on the standard output. embed: bool, model: *const models.Entry, /// The reasoning level the user asked for. The model may not support it. level: models.Level, /// What the provider of the model needs. access: union(models.Provider) { workers_ai: struct { account_id: []const u8, token: []const u8 }, fake, }, }; pub const system_prompt = \\You are a coding assistant running in a terminal harness. Use the tools to \\read, write and edit files and to run commands. Read a file before you edit \\it. Paths are relative to the working directory. bash needs cwd and timeout. \\Be concise. \\ ; pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; var cwd_buffer: [std.fs.max_path_bytes]u8 = undefined; const cwd_length = try std.process.currentPath(io, &cwd_buffer); const cwd = cwd_buffer[0..cwd_length]; const argv = try init.minimal.args.toSlice(init.arena.allocator()); const config = configure(argv, init.environ_map.*) catch |err| { const text = switch (err) { error.MissingModel => "--model needs a NAME", error.UnknownModel => "unknown model; known models: " ++ models.names, error.MissingLevel => "--thinking needs a LEVEL", error.UnknownLevel => "unknown thinking level; known levels: off, low, medium, high, max", error.MissingAccountId => "CLOUDFLARE_ACCOUNT_ID is not set", error.MissingApiToken => "CLOUDFLARE_API_TOKEN (or CLOUDFLARE_AUTH_TOKEN) is not set", }; std.debug.print("{s}\n", .{text}); std.process.exit(1); }; if (!config.embed) { // The flags and the environment are good, so the core can start with them. if (try runUi(init, argv)) |failure| { std.debug.print("the core did not start{s}{s}\n", .{ if (failure.len == 0) "" else ": ", failure }); std.process.exit(1); } return; } const prompt = try std.fmt.allocPrint(gpa, "{s}Working directory: {s}", .{ system_prompt, cwd }); defer gpa.free(prompt); switch (config.access) { .workers_ai => |workers_ai| { const url = try std.fmt.allocPrint(gpa, "https://api.cloudflare.com/client/v4/accounts/{s}/ai/v1/chat/completions", .{workers_ai.account_id}); defer gpa.free(url); // Requests with the same id reach the instance that holds the prompt cache. var session_bytes: [16]u8 = undefined; io.random(&session_bytes); const session_id = std.fmt.bytesToHex(session_bytes, .lower); var client: providers.chat_completions.ChatCompletions = try .init(gpa, io, .{ .url = url, .token = workers_ai.token, .headers = &.{.{ .name = "x-session-affinity", .value = &session_id }}, }); defer client.deinit(); try runCore(init, config, .workers_ai, client.asProvider(), cwd, prompt); }, .fake => { var fake: providers.fake.Fake = .{ .io = io, .cwd = cwd }; try runCore(init, config, .fake, fake.asProvider(), cwd, prompt); }, } } /// Serves the UI on the other side of the standard streams until the input ends. fn runCore(init: std.process.Init, config: Config, name: models.Provider, provider: Provider, cwd: []const u8, system: []const u8) !void { const io = init.io; // Only the models of this provider can be selected. var table: agent.Agent.Providers = .initFill(null); table.set(name, provider); const core = try agent.Agent.init(init.gpa, io, .{ .environ = init.minimal.environ, .providers = table, .system_prompt = system, .model = models.indexOf(&models.entries, config.model.name).?, .level = config.level, .cwd = cwd, }); defer core.deinit(); var in_buffer: [4096]u8 = undefined; var out_buffer: [4096]u8 = undefined; var log_buffer: [256]u8 = undefined; var in = std.Io.File.stdin().readerStreaming(io, &in_buffer); var out = std.Io.File.stdout().writerStreaming(io, &out_buffer); var log = std.Io.File.stderr().writerStreaming(io, &log_buffer); var end: remote.CoreEnd = .{ .gpa = init.gpa, .out = &out.interface, .log = &log.interface }; try core.start(); defer core.stop(); try end.serve(&in.interface, core.sink()); } /// Runs the TUI with this executable as its core in a child process, and /// starts a new core when one ends. Returns null when the user quit, or what /// a core that could not start last wrote. The terminal is free again when /// it returns. fn runUi(init: std.process.Init, argv: []const [:0]const u8) !?[]const u8 { const gpa = init.gpa; const io = init.io; const arena = init.arena.allocator(); var exe_buffer: [std.fs.max_path_bytes]u8 = undefined; const exe = exe_buffer[0..try std.process.executablePath(io, &exe_buffer)]; var core_argv: std.ArrayList([]const u8) = .empty; try core_argv.appendSlice(arena, &.{ exe, "--embed" }); for (argv[1..]) |arg| try core_argv.append(arena, arg); const ui = try tui.Tui.init(gpa, io); defer ui.deinit(); try ui.open(init.environ_map); defer ui.close(); while (true) { const started = std.Io.Timestamp.now(io, .awake); const child = try Child.start(gpa, io, core_argv.items, ui.sink(), ui.endSink()); defer child.stop(); switch (try ui.run(child.sink())) { .quit => return null, // A core that ends this soon would end again, without end. .core_ended => if (started.untilNow(io, .awake).nanoseconds < 2 * std.time.ns_per_s) { return try arena.dupe(u8, child.lastOutput()); }, .core_failed => return try arena.dupe(u8, child.lastOutput()), } } } test { _ = @import("abort.zig"); _ = @import("agent.zig"); _ = @import("child.zig"); _ = @import("content.zig"); _ = @import("editor.zig"); _ = @import("models.zig"); _ = @import("protocol.zig"); _ = @import("provider.zig"); _ = @import("remote.zig"); _ = @import("providers.zig"); _ = @import("testing.zig"); _ = @import("tools.zig"); _ = @import("transcript.zig"); _ = @import("tui.zig"); _ = @import("view/block.zig"); _ = @import("view/chrome.zig"); _ = @import("view/footer.zig"); _ = @import("view/prompt.zig"); _ = @import("view/root.zig"); _ = @import("view/testing.zig"); _ = @import("view/tool.zig"); _ = @import("view/transcript.zig"); _ = @import("wire.zig"); } const testing = std.testing; const tools = @import("tools.zig"); const Watchdog = @import("testing.zig").Watchdog; const Fixture = @import("view/testing.zig").Fixture; fn environment(gpa: std.mem.Allocator, entries: []const [2][]const u8) !std.process.Environ.Map { var map: std.process.Environ.Map = .init(gpa); for (entries) |entry| try map.put(entry[0], entry[1]); return map; } test "a model flag without a name is reported" { var map = try environment(testing.allocator, &.{}); defer map.deinit(); try testing.expectError(error.MissingModel, configure(&.{ "jig", "--model" }, map)); } test "an unknown model is reported" { var map = try environment(testing.allocator, &.{}); defer map.deinit(); try testing.expectError(error.UnknownModel, configure(&.{ "jig", "--model", "gpt" }, map)); } test "the thinking flag sets the level, and medium is the default" { var map = try environment(testing.allocator, &.{}); defer map.deinit(); try testing.expectEqual(models.Level.medium, (try configure(&.{ "jig", "--model", "fake" }, map)).level); try testing.expectEqual(models.Level.max, (try configure(&.{ "jig", "--thinking", "max", "--model", "fake" }, map)).level); try testing.expectEqual(models.Level.off, (try configure(&.{ "jig", "--model", "fake", "--thinking", "off" }, map)).level); } test "a thinking flag without a level or with an unknown level is reported" { var map = try environment(testing.allocator, &.{}); defer map.deinit(); try testing.expectError(error.MissingLevel, configure(&.{ "jig", "--model", "fake", "--thinking" }, map)); try testing.expectError(error.UnknownLevel, configure(&.{ "jig", "--model", "fake", "--thinking", "extreme" }, map)); } test "the embed flag asks for a core, anywhere among the flags" { var map = try environment(testing.allocator, &.{}); defer map.deinit(); try testing.expect(!(try configure(&.{ "jig", "--model", "fake" }, map)).embed); try testing.expect((try configure(&.{ "jig", "--embed", "--model", "fake" }, map)).embed); try testing.expect((try configure(&.{ "jig", "--model", "fake", "--embed" }, map)).embed); } test "fake needs no credentials" { var map = try environment(testing.allocator, &.{}); defer map.deinit(); const config = try configure(&.{ "jig", "--model", "fake" }, map); try testing.expectEqualStrings("fake", config.model.name); try testing.expect(config.access == .fake); } test "a real model needs the account id and a token" { var map = try environment(testing.allocator, &.{}); defer map.deinit(); try testing.expectError(error.MissingAccountId, configure(&.{ "jig", "--model", "deepseek-v4.1-flash" }, map)); var with_id = try environment(testing.allocator, &.{.{ "CLOUDFLARE_ACCOUNT_ID", "1" }}); defer with_id.deinit(); try testing.expectError(error.MissingApiToken, configure(&.{ "jig", "--model", "deepseek-v4.1-flash" }, with_id)); var full = try environment(testing.allocator, &.{ .{ "CLOUDFLARE_ACCOUNT_ID", "1" }, .{ "CLOUDFLARE_AUTH_TOKEN", "t" }, }); defer full.deinit(); const config = try configure(&.{ "jig", "--model", "deepseek-v4.1-flash" }, full); try testing.expectEqualStrings("deepseek-v4.1-flash", config.model.name); try testing.expectEqualStrings("@cf/deepseek-ai/deepseek-v4.1-flash-1017", config.model.id); const workers_ai = config.access.workers_ai; try testing.expectEqualStrings("1", workers_ai.account_id); try testing.expectEqualStrings("t", workers_ai.token); } test "the API token wins over the auth token" { var map = try environment(testing.allocator, &.{ .{ "CLOUDFLARE_ACCOUNT_ID", "1" }, .{ "CLOUDFLARE_API_TOKEN", "api" }, .{ "CLOUDFLARE_AUTH_TOKEN", "auth" }, }); defer map.deinit(); try testing.expectEqualStrings("api", (try configure(&.{"jig"}, map)).access.workers_ai.token); } test "the tools prompt shows every tool call as done and then the answer" { var arena_state = std.heap.ArenaAllocator.init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); var dir = try tools.TestDir.init(); defer dir.deinit(); var fake: providers.fake.Fake = .{ .io = testing.io, .cwd = dir.root }; var table: agent.Agent.Providers = .initFill(null); table.set(.fake, fake.asProvider()); const core = try agent.Agent.init(testing.allocator, testing.io, .{ .environ = testing.environ, .providers = table, .system_prompt = "system", .model = models.indexOf(&models.entries, "fake").?, .cwd = dir.root, }); defer core.deinit(); const ui = try tui.Tui.init(testing.allocator, testing.io); defer ui.deinit(); try core.start(); defer core.stop(); try ui.attach(core.sink()); defer ui.detach(); try ui.editor.insert("tools"); try testing.expect(try ui.handle(.{ .key_press = .{ .codepoint = vaxis.Key.enter } })); { var watchdog: Watchdog(tui.Queue) = try .start(&ui.loop.queue); defer watchdog.stop(); while (true) { _ = try ui.handle(try ui.loop.queue.pop()); const items = ui.transcript.items.items; const last = if (items.len > 0) items[items.len - 1] else null; const answered = last != null and last.? == .assistant and std.mem.eql(u8, last.?.assistant.items, "done"); if (answered and !ui.view.working) { break; } } } try testing.expectEqualStrings("ho", try dir.read("fake.txt")); var screen: Fixture = undefined; try screen.init(40, 240); defer screen.deinit(); try ui.draw(screen.win); const user_bg = 8; const ok_bg = 2; const expected = [_]struct { prefix: []const u8, bg: ?u8 }{ .{ .prefix = " tools ", .bg = user_bg }, .{ .prefix = "running the tools ", .bg = null }, .{ .prefix = " write ", .bg = ok_bg }, .{ .prefix = " read ", .bg = ok_bg }, .{ .prefix = " 1 file(s), 1 lines ", .bg = ok_bg }, .{ .prefix = " edit ", .bg = ok_bg }, .{ .prefix = " bash cat fake.txt ", .bg = ok_bg }, .{ .prefix = " exit 0, ", .bg = ok_bg }, .{ .prefix = "done ", .bg = null }, }; var found: usize = 0; var line: u16 = 0; while (line < screen.win.height and found < expected.len) : (line += 1) { const want = expected[found]; if (!std.mem.startsWith(u8, try screen.row(line, arena), want.prefix)) { continue; } if (want.bg) |bg| { try testing.expectEqual(vaxis.Color{ .index = bg }, screen.style(0, line).bg); } found += 1; } try testing.expectEqual(expected.len, found); }