xonecas.io
79113
Ma

mini-coding-agent / files

mini-coding-agent / src / session.zig

18.2 KB
1const std = @import("std");
2const platform = @import("platform.zig");
3const time = @import("time.zig");
4const filesystem = @import("filesystem.zig");
5const text = @import("text.zig");
6const message_mod = @import("message.zig");
7const json = @import("json.zig");
8
9const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
10
11const Raw = json.Raw;
12const StopReason = message_mod.StopReason;
13
14const ThinkingBlock = struct {
15    type: []const u8 = "thinking",
16    thinking: []const u8,
17    thinkingSignature: ?[]const u8 = null,
18};
19const CallBlock = struct {
20    type: []const u8 = "toolCall",
21    id: []const u8,
22    name: []const u8,
23    arguments: Raw,
24    thoughtSignature: ?[]const u8 = null,
25};
26const Block = union(enum) {
27    text: TextPart,
28    thinking: ThinkingBlock,
29    tool_call: CallBlock,
30
31    pub fn jsonStringify(self: Block, jws: anytype) !void {
32        switch (self) {
33            inline else => |v| try jws.write(v),
34        }
35    }
36};
37
38const UserRecord = struct {
39    role: []const u8 = "user",
40    content: []const u8,
41    timestamp: i64,
42};
43
44const TextPart = struct { type: []const u8 = "text", text: []const u8 };
45const ImagePart = struct { type: []const u8 = "image", data: []const u8, mimeType: []const u8 };
46const Part = union(enum) {
47    text: TextPart,
48    image: ImagePart,
49
50    pub fn jsonStringify(self: Part, jws: anytype) !void {
51        switch (self) {
52            inline else => |v| try jws.write(v),
53        }
54    }
55};
56
57const ToolResultRecord = struct {
58    role: []const u8 = "toolResult",
59    toolCallId: []const u8,
60    toolName: []const u8,
61    content: []const Part,
62    isError: bool,
63    timestamp: i64,
64};
65
66const Number = struct {
67    value: f64 = 0,
68    pub fn jsonStringify(self: Number, jws: anytype) !void {
69        if (!std.math.isFinite(self.value)) return jws.write(null);
70        try jws.write(self.value);
71    }
72};
73
74const UsageRecord = struct {
75    input: u64 = 0,
76    output: u64 = 0,
77    cacheRead: u64 = 0,
78    cacheWrite: u64 = 0,
79    reasoning: ?u64 = null,
80    totalTokens: u64 = 0,
81    cost: struct {
82        input: Number = .{},
83        output: Number = .{},
84        cacheRead: Number = .{},
85        total: Number = .{},
86    } = .{},
87};
88
89const AssistantRecord = struct {
90    role: []const u8 = "assistant",
91    content: []const Block,
92    api: []const u8,
93    provider: []const u8,
94    model: []const u8,
95    usage: UsageRecord,
96    stopReason: StopReason,
97    timestamp: i64,
98    responseId: ?[]const u8 = null,
99    responseModel: ?[]const u8 = null,
100    rawStopReason: ?[]const u8 = null,
101    errorMessage: ?[]const u8 = null,
102};
103
104const MessageRecord = union(enum) {
105    user: UserRecord,
106    tool_result: ToolResultRecord,
107    assistant: AssistantRecord,
108
109    pub fn jsonStringify(self: MessageRecord, jws: anytype) !void {
110        switch (self) {
111            inline else => |v| try jws.write(v),
112        }
113    }
114};
115
116const MessageLine = struct {
117    type: []const u8 = "message",
118    at: []const u8,
119    message: MessageRecord,
120};
121
122const RequestLine = struct {
123    type: []const u8 = "request",
124    at: []const u8,
125    provider: []const u8,
126    model: []const u8,
127    api: []const u8,
128    thinkingEffort: []const u8,
129    systemPrompt: []const u8,
130    tools: Raw,
131};
132
133const HeaderLine = struct {
134    type: []const u8 = "session",
135    version: u32 = 1,
136    id: []const u8,
137    cwd: []const u8,
138    createdAt: []const u8,
139    title: []const u8,
140};
141
142fn stringify(a: std.mem.Allocator, value: anytype) ![]u8 {
143    return std.json.Stringify.valueAlloc(a, value, .{ .emit_null_optional_fields = false });
144}
145
146pub const Request = struct {
147    provider: []const u8,
148    model: []const u8,
149    api: []const u8,
150    thinking_effort: []const u8,
151    system_prompt: []const u8,
152    tools_json: []const u8,
153};
154
155pub const Session = struct {
156    a: std.mem.Allocator,
157    sessions_dir: []const u8,
158    cwd: []const u8,
159    id: ?[]const u8 = null,
160    file: ?std.Io.File = null,
161    offset: u64 = 0,
162    disabled: bool = false,
163    closed: bool = false,
164
165    pub fn init(a: std.mem.Allocator, sessions_dir: []const u8, cwd: []const u8) Session {
166        var id: [6]u8 = undefined;
167        shortId(&id);
168        return .{ .a = a, .sessions_dir = sessions_dir, .cwd = cwd, .id = a.dupe(u8, &id) catch null };
169    }
170
171    pub fn appendMessage(self: *Session, scratch: std.mem.Allocator, message: message_mod.Message) !void {
172        try self.append(scratch, .{ .message = message });
173    }
174
175    pub fn appendRequest(self: *Session, scratch: std.mem.Allocator, req: Request) !void {
176        try self.append(scratch, .{ .request = req });
177    }
178
179    const Record = union(enum) { message: message_mod.Message, request: Request };
180
181    fn append(self: *Session, scratch: std.mem.Allocator, record: Record) !void {
182        if (self.closed or self.disabled) return;
183        const title = switch (record) {
184            .message => |m| if (m == .user) text.slugify(self.a, m.user.content) else "session",
185            .request => "session",
186        };
187        try self.ensure(title);
188        var arena = std.heap.ArenaAllocator.init(scratch);
189        defer arena.deinit();
190        const a = arena.allocator();
191        const at = time.isoAlloc(a);
192        const line = switch (record) {
193            .message => |m| try stringify(a, MessageLine{ .at = at, .message = try messageRecord(a, m) }),
194            .request => |r| try stringify(a, RequestLine{
195                .at = at,
196                .provider = r.provider,
197                .model = r.model,
198                .api = r.api,
199                .thinkingEffort = r.thinking_effort,
200                .systemPrompt = r.system_prompt,
201                .tools = .{ .bytes = if (r.tools_json.len > 0) r.tools_json else "[]" },
202            }),
203        };
204        try self.commitLine(scratch, line);
205    }
206
207    fn commitLine(self: *Session, scratch: std.mem.Allocator, line: []const u8) !void {
208        const f = self.file orelse return error.SessionNotOpen;
209        var out: std.Io.Writer.Allocating = .init(scratch);
210        defer out.deinit();
211        const w = &out.writer;
212        try w.writeAll(line);
213        try w.writeByte('\n');
214        try f.writePositionalAll(platform.io, out.written(), self.offset);
215        self.offset += out.written().len;
216        try f.sync(platform.io);
217    }
218
219    pub fn close(self: *Session) void {
220        self.closed = true;
221        if (self.file) |f| {
222            f.close(platform.io);
223            self.file = null;
224        }
225    }
226
227    pub fn reopen(self: *Session, id: []const u8, messages: *std.ArrayList(message_mod.Message)) !void {
228        var arena = std.heap.ArenaAllocator.init(self.a);
229        defer arena.deinit();
230        const scratch = arena.allocator();
231
232        const name = try self.matching(scratch, id);
233        const dir = try filesystem.join(scratch, &.{ self.sessions_dir, name });
234        const log_path = try filesystem.join(scratch, &.{ dir, "session.jsonl" });
235        const body = filesystem.readFileAlloc(scratch, log_path, 1 << 26) catch |e| switch (e) {
236            error.FileNotFound => return error.NoSuchSession,
237            else => return e,
238        };
239
240        var lines = std.mem.splitScalar(u8, body, '\n');
241        while (lines.next()) |line| {
242            if (parseMessage(self.a, scratch, line)) |message| try messages.append(self.a, message);
243        }
244
245        self.id = try self.a.dupe(u8, name);
246        const file = try std.Io.Dir.cwd().createFile(platform.io, log_path, .{ .truncate = false, .permissions = .fromMode(0o600) });
247        self.offset = try file.length(platform.io);
248        self.file = file;
249    }
250
251    fn matching(self: *Session, scratch: std.mem.Allocator, id: []const u8) ![]const u8 {
252        const names = filesystem.listDir(scratch, self.sessions_dir) catch return error.NoSuchSession;
253        for (names) |name| if (std.mem.eql(u8, name, id)) return name;
254        var found: ?[]const u8 = null;
255        for (names) |name| {
256            if (!std.mem.startsWith(u8, name, id)) continue;
257            if (found != null) return error.AmbiguousSession;
258            found = name;
259        }
260        return found orelse error.NoSuchSession;
261    }
262
263    fn ensure(self: *Session, title: []const u8) !void {
264        if (self.file != null) return;
265        _ = std.Io.Dir.cwd().createDirPathStatus(platform.io, self.sessions_dir, .fromMode(0o700)) catch {};
266        var stamp_buf: [15]u8 = undefined;
267        const stamp = time.stamp(&stamp_buf, time.nowMs());
268
269        var attempt: usize = 0;
270        while (attempt < 16) : (attempt += 1) {
271            var id_buf: [6]u8 = undefined;
272            shortId(&id_buf);
273            const name = try std.fmt.allocPrint(self.a, "{s}-{s}-{s}", .{ stamp, title, &id_buf });
274            const dir = try filesystem.join(self.a, &.{ self.sessions_dir, name });
275            std.Io.Dir.cwd().createDir(platform.io, dir, .fromMode(0o700)) catch |e| switch (e) {
276                error.PathAlreadyExists => continue,
277                else => return e,
278            };
279            const log_path = try filesystem.join(self.a, &.{ dir, "session.jsonl" });
280            const file = try std.Io.Dir.cwd().createFile(platform.io, log_path, .{ .truncate = false, .permissions = .fromMode(0o600) });
281            self.id = name;
282            self.file = file;
283            try self.commitLine(self.a, try stringify(self.a, HeaderLine{
284                .id = name,
285                .cwd = self.cwd,
286                .createdAt = time.isoAlloc(self.a),
287                .title = title,
288            }));
289            return;
290        }
291        return error.SessionDirectory;
292    }
293
294    fn shortId(buf: *[6]u8) void {
295        var bytes: [6]u8 = undefined;
296        std.Io.random(platform.io, &bytes);
297        for (bytes, 0..) |b, i| buf[i] = alphabet[b % 36];
298    }
299};
300
301fn messageRecord(a: std.mem.Allocator, message: message_mod.Message) !MessageRecord {
302    switch (message) {
303        .user => |u| return .{ .user = .{ .content = u.content, .timestamp = u.timestamp } },
304        .tool_result => |t| {
305            var parts: std.ArrayList(Part) = .empty;
306            try parts.append(a, .{ .text = .{ .text = t.text } });
307            for (t.images) |img| {
308                try parts.append(a, .{ .image = .{ .data = img.data, .mimeType = img.mime_type } });
309            }
310            return .{ .tool_result = .{
311                .toolCallId = t.tool_call_id,
312                .toolName = t.tool_name,
313                .content = try parts.toOwnedSlice(a),
314                .isError = t.is_error,
315                .timestamp = t.timestamp,
316            } };
317        },
318        .assistant => |m| {
319            var blocks: std.ArrayList(Block) = .empty;
320            for (m.content.items) |block| try blocks.append(a, switch (block) {
321                .text => |t| .{ .text = .{ .text = t } },
322                .thinking => |t| .{ .thinking = .{ .thinking = t.text, .thinkingSignature = t.signature } },
323                .tool_call => |c| .{ .tool_call = .{
324                    .id = c.id,
325                    .name = c.name,
326                    .arguments = .{ .bytes = c.arguments },
327                    .thoughtSignature = c.thought_signature,
328                } },
329            });
330            return .{ .assistant = .{
331                .content = try blocks.toOwnedSlice(a),
332                .api = m.api,
333                .provider = m.provider,
334                .model = m.model,
335                .usage = .{
336                    .input = m.usage.input,
337                    .output = m.usage.output,
338                    .cacheRead = m.usage.cache_read,
339                    .cacheWrite = m.usage.cache_write,
340                    .reasoning = m.usage.reasoning,
341                    .totalTokens = m.usage.total_tokens,
342                    .cost = .{
343                        .input = .{ .value = m.usage.cost_input },
344                        .output = .{ .value = m.usage.cost_output },
345                        .cacheRead = .{ .value = m.usage.cost_cache_read },
346                        .total = .{ .value = m.usage.cost_total },
347                    },
348                },
349                .stopReason = m.stop_reason,
350                .timestamp = m.timestamp,
351                .responseId = m.response_id,
352                .responseModel = m.response_model,
353                .rawStopReason = m.raw_stop_reason,
354                .errorMessage = m.error_message,
355            } };
356        },
357    }
358}
359
360fn dupStr(a: std.mem.Allocator, obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
361    const s = json.stringField(obj, key) orelse return null;
362    return a.dupe(u8, s) catch null;
363}
364
365fn int(obj: std.json.ObjectMap, key: []const u8) i64 {
366    const value = obj.get(key) orelse return 0;
367    return if (value == .integer) value.integer else 0;
368}
369
370fn count(obj: std.json.ObjectMap, key: []const u8) u64 {
371    return @intCast(@max(0, int(obj, key)));
372}
373
374fn num(obj: std.json.ObjectMap, key: []const u8) f64 {
375    const value = obj.get(key) orelse return 0;
376    return switch (value) {
377        .float => |f| f,
378        .integer => |i| @floatFromInt(i),
379        else => 0,
380    };
381}
382
383fn boolean(obj: std.json.ObjectMap, key: []const u8) bool {
384    const value = obj.get(key) orelse return false;
385    return value == .bool and value.bool;
386}
387
388fn items(obj: std.json.ObjectMap, key: []const u8) []std.json.Value {
389    const value = obj.get(key) orelse return &.{};
390    return if (value == .array) value.array.items else &.{};
391}
392
393fn object(obj: std.json.ObjectMap, key: []const u8) ?std.json.ObjectMap {
394    const value = obj.get(key) orelse return null;
395    return if (value == .object) value.object else null;
396}
397
398fn stopReason(name: ?[]const u8) StopReason {
399    const wire = name orelse return .stop;
400    for (std.meta.tags(StopReason)) |reason| {
401        if (std.mem.eql(u8, reason.wire(), wire)) return reason;
402    }
403    return .stop;
404}
405
406fn usageOf(record: ?std.json.ObjectMap) message_mod.Usage {
407    const u = record orelse return .{};
408    const cost = object(u, "cost") orelse std.json.ObjectMap.empty;
409    return .{
410        .input = count(u, "input"),
411        .output = count(u, "output"),
412        .cache_read = count(u, "cacheRead"),
413        .cache_write = count(u, "cacheWrite"),
414        .reasoning = if (u.get("reasoning") != null) count(u, "reasoning") else null,
415        .total_tokens = count(u, "totalTokens"),
416        .cost_input = num(cost, "input"),
417        .cost_output = num(cost, "output"),
418        .cost_cache_read = num(cost, "cacheRead"),
419        .cost_total = num(cost, "total"),
420    };
421}
422
423fn parseParts(a: std.mem.Allocator, parts: []std.json.Value) struct { text: []const u8, images: []const message_mod.ImageContent } {
424    var body: []const u8 = "";
425    var images: std.ArrayList(message_mod.ImageContent) = .empty;
426    for (parts) |part| {
427        if (part != .object) continue;
428        const p = part.object;
429        const kind = json.stringField(p, "type") orelse continue;
430        if (std.mem.eql(u8, kind, "text")) {
431            body = dupStr(a, p, "text") orelse body;
432        } else if (std.mem.eql(u8, kind, "image")) {
433            const data = dupStr(a, p, "data") orelse continue;
434            images.append(a, .{ .data = data, .mime_type = dupStr(a, p, "mimeType") orelse "" }) catch {};
435        }
436    }
437    return .{ .text = body, .images = images.toOwnedSlice(a) catch &.{} };
438}
439
440fn parseAssistant(a: std.mem.Allocator, record: std.json.ObjectMap) ?*message_mod.AssistantMessage {
441    const message = a.create(message_mod.AssistantMessage) catch return null;
442    message.* = .{
443        .content = .empty,
444        .api = dupStr(a, record, "api") orelse "",
445        .provider = dupStr(a, record, "provider") orelse "",
446        .model = dupStr(a, record, "model") orelse "",
447        .response_id = dupStr(a, record, "responseId"),
448        .response_model = dupStr(a, record, "responseModel"),
449        .raw_stop_reason = dupStr(a, record, "rawStopReason"),
450        .usage = usageOf(object(record, "usage")),
451        .stop_reason = stopReason(json.stringField(record, "stopReason")),
452        .error_message = dupStr(a, record, "errorMessage"),
453        .timestamp = int(record, "timestamp"),
454    };
455    for (items(record, "content")) |entry| {
456        if (entry != .object) continue;
457        const block = entry.object;
458        const kind = json.stringField(block, "type") orelse continue;
459        if (std.mem.eql(u8, kind, "text")) {
460            message.content.append(a, .{ .text = dupStr(a, block, "text") orelse "" }) catch {};
461        } else if (std.mem.eql(u8, kind, "thinking")) {
462            message.content.append(a, .{ .thinking = .{
463                .text = dupStr(a, block, "thinking") orelse "",
464                .signature = dupStr(a, block, "thinkingSignature"),
465            } }) catch {};
466        } else if (std.mem.eql(u8, kind, "toolCall")) {
467            const arguments = if (block.get("arguments")) |v|
468                std.json.Stringify.valueAlloc(a, v, .{}) catch ""
469            else
470                "";
471            message.content.append(a, .{ .tool_call = .{
472                .id = dupStr(a, block, "id") orelse "",
473                .name = dupStr(a, block, "name") orelse "",
474                .arguments = arguments,
475                .thought_signature = dupStr(a, block, "thoughtSignature"),
476            } }) catch {};
477        }
478    }
479    return message;
480}
481
482fn parseMessage(a: std.mem.Allocator, scratch: std.mem.Allocator, line: []const u8) ?message_mod.Message {
483    if (std.mem.trim(u8, line, " \t\r").len == 0) return null;
484    const root = std.json.parseFromSliceLeaky(std.json.Value, scratch, line, .{}) catch return null;
485    if (root != .object) return null;
486    const kind = json.stringField(root.object, "type") orelse return null;
487    if (!std.mem.eql(u8, kind, "message")) return null;
488    const record = object(root.object, "message") orelse return null;
489    const role = json.stringField(record, "role") orelse return null;
490
491    if (std.mem.eql(u8, role, "user")) {
492        return .{ .user = .{
493            .content = dupStr(a, record, "content") orelse "",
494            .timestamp = int(record, "timestamp"),
495        } };
496    }
497    if (std.mem.eql(u8, role, "toolResult")) {
498        const parsed = parseParts(a, items(record, "content"));
499        return .{ .tool_result = .{
500            .tool_call_id = dupStr(a, record, "toolCallId") orelse "",
501            .tool_name = dupStr(a, record, "toolName") orelse "",
502            .text = parsed.text,
503            .images = parsed.images,
504            .is_error = boolean(record, "isError"),
505            .timestamp = int(record, "timestamp"),
506        } };
507    }
508    if (std.mem.eql(u8, role, "assistant")) {
509        return .{ .assistant = parseAssistant(a, record) orelse return null };
510    }
511    return null;
512}