summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 688b61d89ec20fbedc69f74452dcab88085eb3ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
const std = @import("std");
const panto = @import("panto");

const Receiver = panto.provider.Receiver;
const ReceiverVTable = panto.provider.ReceiverVTable;
const ContentBlockType = panto.provider.ContentBlockType;
const BlockMeta = panto.provider.BlockMeta;
const MessageRole = panto.conversation.MessageRole;

/// Receiver that prints streaming deltas to stdout. Thinking blocks are
/// dimmed with ANSI escape codes; text blocks render plain.
const CLIReceiver = struct {
    stdout: *std.Io.Writer,
    file: *std.Io.File.Writer,

    pub fn receiver(self: *CLIReceiver) Receiver {
        return .{ .ptr = self, .vtable = &vtable };
    }

    const vtable: ReceiverVTable = .{
        .onMessageStart = onMessageStart,
        .onBlockStart = onBlockStart,
        .onContentDelta = onContentDelta,
        .onBlockComplete = onBlockComplete,
        .onMessageComplete = onMessageComplete,
        .onError = onError,
    };

    fn onMessageStart(ptr: *anyopaque, role: MessageRole) anyerror!void {
        _ = ptr;
        _ = role;
    }

    fn onBlockStart(
        ptr: *anyopaque,
        block_type: ContentBlockType,
        index: usize,
        meta: ?BlockMeta,
    ) anyerror!void {
        _ = index;
        _ = meta;
        const self: *CLIReceiver = @ptrCast(@alignCast(ptr));
        if (block_type == .Thinking) {
            try self.stdout.writeAll("\x1b[2m[thinking] ");
        }
        try self.file.flush();
    }

    fn onContentDelta(ptr: *anyopaque, index: usize, delta: []const u8) anyerror!void {
        _ = index;
        const self: *CLIReceiver = @ptrCast(@alignCast(ptr));
        try self.stdout.writeAll(delta);
        try self.file.flush();
    }

    fn onBlockComplete(
        ptr: *anyopaque,
        index: usize,
        block: panto.conversation.ContentBlock,
    ) anyerror!void {
        _ = index;
        const self: *CLIReceiver = @ptrCast(@alignCast(ptr));
        if (block == .Thinking) {
            try self.stdout.writeAll("\x1b[0m\n");
        }
        try self.file.flush();
    }

    fn onMessageComplete(ptr: *anyopaque, message: panto.conversation.Message) anyerror!void {
        _ = message;
        const self: *CLIReceiver = @ptrCast(@alignCast(ptr));
        try self.stdout.writeAll("\n");
        try self.file.flush();
    }

    /// Reset any in-progress display state after a failed turn. Errors here
    /// must be swallowed — we're already in the error path.
    fn onError(ptr: *anyopaque, err: anyerror) void {
        _ = &err;
        const self: *CLIReceiver = @ptrCast(@alignCast(ptr));
        // If we were rendering a Thinking block, clear the dim style so
        // subsequent output (including the "[error: ...]" line) is readable.
        self.stdout.writeAll("\x1b[0m") catch {};
        self.file.flush() catch {};
    }
};

fn loadConfig(environ_map: *const std.process.Environ.Map) !panto.config.Config {
    const style_str = environ_map.get("PANTO_API_STYLE") orelse "openai_chat";
    const style = std.meta.stringToEnum(panto.config.APIStyle, style_str) orelse {
        std.debug.print(
            "error: PANTO_API_STYLE must be one of: openai_chat, anthropic_messages (got: {s})\n",
            .{style_str},
        );
        return error.InvalidApiStyle;
    };

    switch (style) {
        .openai_chat => {
            const api_key = environ_map.get("OPENAI_API_KEY") orelse {
                std.debug.print("error: OPENAI_API_KEY is required\n", .{});
                return error.MissingApiKey;
            };
            const base_url = environ_map.get("OPENAI_BASE_URL") orelse "https://api.openai.com/v1";
            const model = environ_map.get("OPENAI_MODEL") orelse {
                std.debug.print("error: OPENAI_MODEL is required\n", .{});
                return error.MissingModel;
            };
            const reasoning: panto.config.ReasoningEffort =
                if (environ_map.get("OPENAI_REASONING")) |val|
                    std.meta.stringToEnum(panto.config.ReasoningEffort, val) orelse {
                        std.debug.print(
                            "error: OPENAI_REASONING must be one of: default, off, minimal, low, medium, high (got: {s})\n",
                            .{val},
                        );
                        return error.InvalidReasoning;
                    }
                else
                    .default;
            return .{ .openai_chat = .{
                .api_key = api_key,
                .base_url = base_url,
                .model = model,
                .reasoning = reasoning,
            } };
        },
        .anthropic_messages => {
            const api_key = environ_map.get("ANTHROPIC_API_KEY") orelse {
                std.debug.print("error: ANTHROPIC_API_KEY is required\n", .{});
                return error.MissingApiKey;
            };
            const base_url = environ_map.get("ANTHROPIC_BASE_URL") orelse "https://api.anthropic.com";
            const model = environ_map.get("ANTHROPIC_MODEL") orelse {
                std.debug.print("error: ANTHROPIC_MODEL is required\n", .{});
                return error.MissingModel;
            };
            const api_version = environ_map.get("ANTHROPIC_API_VERSION") orelse "2023-06-01";
            const max_tokens: u32 = if (environ_map.get("ANTHROPIC_MAX_TOKENS")) |val|
                std.fmt.parseInt(u32, val, 10) catch {
                    std.debug.print(
                        "error: ANTHROPIC_MAX_TOKENS must be a positive integer (got: {s})\n",
                        .{val},
                    );
                    return error.InvalidMaxTokens;
                }
            else
                4096;
            return .{ .anthropic_messages = .{
                .api_key = api_key,
                .base_url = base_url,
                .model = model,
                .api_version = api_version,
                .max_tokens = max_tokens,
            } };
        },
    }
}

pub fn main(init: std.process.Init) !void {
    const alloc = init.gpa;
    const io = init.io;

    const config = try loadConfig(init.environ_map);

    var stdout_buffer: [4096]u8 = undefined;
    var stdout_file = std.Io.File.stdout().writer(io, &stdout_buffer);
    const stdout = &stdout_file.interface;

    var stdin_buffer: [4096]u8 = undefined;
    var stdin_file = std.Io.File.stdin().reader(io, &stdin_buffer);
    const stdin = &stdin_file.interface;

    var conv = panto.conversation.Conversation.init(alloc);
    defer conv.deinit();
    try conv.addSystemMessage("You are a helpful assistant.");

    const prov = try panto.provider.Provider.init(alloc, io, config);
    const agent = panto.agent.Agent.init(alloc, prov);
    defer agent.deinit();

    const banner_model: []const u8 = switch (config) {
        inline else => |c| c.model,
    };
    const banner_base: []const u8 = switch (config) {
        inline else => |c| c.base_url,
    };
    try stdout.print("panto — {s}: {s} @ {s}\n", .{ @tagName(config), banner_model, banner_base });
    try stdout.print("> ", .{});
    try stdout_file.flush();

    var cli_recv = CLIReceiver{ .stdout = stdout, .file = &stdout_file };
    var recv = cli_recv.receiver();

    while (true) {
        const maybe_line = stdin.takeDelimiter('\n') catch |err| {
            std.debug.print("read error: {}\n", .{err});
            return;
        };
        const line = maybe_line orelse {
            try stdout.writeAll("\n");
            try stdout_file.flush();
            break;
        };

        if (line.len == 0) {
            try stdout.writeAll("\n> ");
            try stdout_file.flush();
            continue;
        }

        try conv.addUserMessage(line);

        agent.runStep(&conv, &recv) catch |err| {
            try stdout.print("\n[error: {s}]\n", .{@errorName(err)});
        };

        try stdout.writeAll("\n> ");
        try stdout_file.flush();
    }
}