@@ -163,14 +163,20 @@ pub const Session = struct {
163163 cwd: []const u8,
164164 id: ?[]const u8 = null,
165165 file: ?std.Io.File = null,
166+ offset: u64 = 0,
167+ disabled: bool = false,
166168 closed: bool = false,
167169
170+ /// `id` names the provider's session header until a log is opened; a recording
171+ /// session then takes the name of its directory.
168172 pub fn init(a: std.mem.Allocator, sessions_dir: []const u8, cwd: []const u8) Session {
169- return .{ .a = a, .sessions_dir = sessions_dir, .cwd = cwd };
173+ var id: [6]u8 = undefined;
174+ shortId(&id);
175+ return .{ .a = a, .sessions_dir = sessions_dir, .cwd = cwd, .id = a.dupe(u8, &id) catch null };
170176 }
171177
172178 pub fn appendMessage(self: *Session, scratch: std.mem.Allocator, message: message_mod.Message) !void {
173- if (self.closed) return;
179+ if (self.closed or self.disabled) return;
174180 try self.ensure(if (message == .user) text.slugify(self.a, message.user.content) else "session");
175181
176182 var arena = std.heap.ArenaAllocator.init(scratch);
@@ -184,7 +190,7 @@ pub const Session = struct {
184190 }
185191
186192 pub fn appendRequest(self: *Session, scratch: std.mem.Allocator, req: Request) !void {
187- if (self.closed) return;
193+ if (self.closed or self.disabled) return;
188194 try self.ensure("session");
189195
190196 var arena = std.heap.ArenaAllocator.init(scratch);
@@ -209,7 +215,8 @@ pub const Session = struct {
209215 const w = &out.writer;
210216 try w.writeAll(line);
211217 try w.writeByte('\n');
212- try f.writeStreamingAll(platform.io, out.written());
218+ try f.writePositionalAll(platform.io, out.written(), self.offset);
219+ self.offset += out.written().len;
213220 try f.sync(platform.io);
214221 }
215222
@@ -221,6 +228,45 @@ pub const Session = struct {
221228 }
222229 }
223230
231+ /// Reopens the session matching `id` for appending and replays its messages into
232+ /// `messages`. Strings land in `self.a`, so the caller may release its own arena.
233+ pub fn reopen(self: *Session, id: []const u8, messages: *std.ArrayList(message_mod.Message)) !void {
234+ var arena = std.heap.ArenaAllocator.init(self.a);
235+ defer arena.deinit();
236+ const scratch = arena.allocator();
237+
238+ const name = try self.matching(scratch, id);
239+ const dir = try filesystem.join(scratch, &.{ self.sessions_dir, name });
240+ const log_path = try filesystem.join(scratch, &.{ dir, "session.jsonl" });
241+ const body = filesystem.readFileAlloc(scratch, log_path, 1 << 26) catch |e| switch (e) {
242+ error.FileNotFound => return error.NoSuchSession,
243+ else => return e,
244+ };
245+
246+ var lines = std.mem.splitScalar(u8, body, '\n');
247+ while (lines.next()) |line| {
248+ if (parseMessage(self.a, scratch, line)) |message| try messages.append(self.a, message);
249+ }
250+
251+ self.id = try self.a.dupe(u8, name);
252+ const file = try std.Io.Dir.cwd().createFile(platform.io, log_path, .{ .truncate = false, .permissions = .fromMode(0o600) });
253+ self.offset = try file.length(platform.io);
254+ self.file = file;
255+ }
256+
257+ /// An exact session name, or the single one it prefixes.
258+ fn matching(self: *Session, scratch: std.mem.Allocator, id: []const u8) ![]const u8 {
259+ const names = filesystem.listDir(scratch, self.sessions_dir) catch return error.NoSuchSession;
260+ for (names) |name| if (std.mem.eql(u8, name, id)) return name;
261+ var found: ?[]const u8 = null;
262+ for (names) |name| {
263+ if (!std.mem.startsWith(u8, name, id)) continue;
264+ if (found != null) return error.AmbiguousSession;
265+ found = name;
266+ }
267+ return found orelse error.NoSuchSession;
268+ }
269+
224270 fn ensure(self: *Session, title: []const u8) !void {
225271 if (self.file != null) return;
226272 _ = std.Io.Dir.cwd().createDirPathStatus(platform.io, self.sessions_dir, .fromMode(0o700)) catch {};
@@ -317,3 +363,166 @@ fn messageRecord(a: std.mem.Allocator, message: message_mod.Message) !MessageRec
317363 },
318364 }
319365 }
366+
367+fn str(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
368+ const value = obj.get(key) orelse return null;
369+ return if (value == .string) value.string else null;
370+}
371+
372+fn dupStr(a: std.mem.Allocator, obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {
373+ const s = str(obj, key) orelse return null;
374+ return a.dupe(u8, s) catch null;
375+}
376+
377+fn int(obj: std.json.ObjectMap, key: []const u8) i64 {
378+ const value = obj.get(key) orelse return 0;
379+ return if (value == .integer) value.integer else 0;
380+}
381+
382+fn count(obj: std.json.ObjectMap, key: []const u8) u64 {
383+ return @intCast(@max(0, int(obj, key)));
384+}
385+
386+fn num(obj: std.json.ObjectMap, key: []const u8) f64 {
387+ const value = obj.get(key) orelse return 0;
388+ return switch (value) {
389+ .float => |f| f,
390+ .integer => |i| @floatFromInt(i),
391+ else => 0,
392+ };
393+}
394+
395+fn boolean(obj: std.json.ObjectMap, key: []const u8) bool {
396+ const value = obj.get(key) orelse return false;
397+ return value == .bool and value.bool;
398+}
399+
400+fn items(obj: std.json.ObjectMap, key: []const u8) []std.json.Value {
401+ const value = obj.get(key) orelse return &.{};
402+ return if (value == .array) value.array.items else &.{};
403+}
404+
405+fn object(obj: std.json.ObjectMap, key: []const u8) ?std.json.ObjectMap {
406+ const value = obj.get(key) orelse return null;
407+ return if (value == .object) value.object else null;
408+}
409+
410+fn stopReason(name: ?[]const u8) StopReason {
411+ const wire = name orelse return .stop;
412+ if (std.mem.eql(u8, wire, "pending")) return .pending;
413+ if (std.mem.eql(u8, wire, "length")) return .length;
414+ if (std.mem.eql(u8, wire, "toolUse")) return .tool_use;
415+ if (std.mem.eql(u8, wire, "error")) return .err;
416+ if (std.mem.eql(u8, wire, "aborted")) return .aborted;
417+ return .stop;
418+}
419+
420+fn usageOf(record: ?std.json.ObjectMap) message_mod.Usage {
421+ const u = record orelse return .{};
422+ const cost = object(u, "cost") orelse std.json.ObjectMap.empty;
423+ return .{
424+ .input = count(u, "input"),
425+ .output = count(u, "output"),
426+ .cache_read = count(u, "cacheRead"),
427+ .cache_write = count(u, "cacheWrite"),
428+ .reasoning = if (u.get("reasoning") != null) count(u, "reasoning") else null,
429+ .total_tokens = count(u, "totalTokens"),
430+ .cost_input = num(cost, "input"),
431+ .cost_output = num(cost, "output"),
432+ .cost_cache_read = num(cost, "cacheRead"),
433+ .cost_total = num(cost, "total"),
434+ };
435+}
436+
437+fn parseParts(a: std.mem.Allocator, parts: []std.json.Value) struct { text: []const u8, images: []const message_mod.ImageContent } {
438+ var body: []const u8 = "";
439+ var images: std.ArrayList(message_mod.ImageContent) = .empty;
440+ for (parts) |part| {
441+ if (part != .object) continue;
442+ const p = part.object;
443+ const kind = str(p, "type") orelse continue;
444+ if (std.mem.eql(u8, kind, "text")) {
445+ body = dupStr(a, p, "text") orelse body;
446+ } else if (std.mem.eql(u8, kind, "image")) {
447+ const data = dupStr(a, p, "data") orelse continue;
448+ images.append(a, .{ .data = data, .mime_type = dupStr(a, p, "mimeType") orelse "" }) catch {};
449+ }
450+ }
451+ return .{ .text = body, .images = images.toOwnedSlice(a) catch &.{} };
452+}
453+
454+fn parseAssistant(a: std.mem.Allocator, record: std.json.ObjectMap) ?*message_mod.AssistantMessage {
455+ const message = a.create(message_mod.AssistantMessage) catch return null;
456+ message.* = .{
457+ .content = .empty,
458+ .api = dupStr(a, record, "api") orelse "",
459+ .provider = dupStr(a, record, "provider") orelse "",
460+ .model = dupStr(a, record, "model") orelse "",
461+ .response_id = dupStr(a, record, "responseId"),
462+ .response_model = dupStr(a, record, "responseModel"),
463+ .raw_stop_reason = dupStr(a, record, "rawStopReason"),
464+ .usage = usageOf(object(record, "usage")),
465+ .stop_reason = stopReason(str(record, "stopReason")),
466+ .error_message = dupStr(a, record, "errorMessage"),
467+ .timestamp = int(record, "timestamp"),
468+ };
469+ for (items(record, "content")) |entry| {
470+ if (entry != .object) continue;
471+ const block = entry.object;
472+ const kind = str(block, "type") orelse continue;
473+ if (std.mem.eql(u8, kind, "text")) {
474+ message.content.append(a, .{ .text = dupStr(a, block, "text") orelse "" }) catch {};
475+ } else if (std.mem.eql(u8, kind, "thinking")) {
476+ message.content.append(a, .{ .thinking = .{
477+ .text = dupStr(a, block, "thinking") orelse "",
478+ .signature = dupStr(a, block, "thinkingSignature"),
479+ } }) catch {};
480+ } else if (std.mem.eql(u8, kind, "toolCall")) {
481+ const arguments = if (block.get("arguments")) |v|
482+ std.json.Stringify.valueAlloc(a, v, .{}) catch ""
483+ else
484+ "";
485+ message.content.append(a, .{ .tool_call = .{
486+ .id = dupStr(a, block, "id") orelse "",
487+ .name = dupStr(a, block, "name") orelse "",
488+ .arguments = arguments,
489+ .thought_signature = dupStr(a, block, "thoughtSignature"),
490+ } }) catch {};
491+ }
492+ }
493+ return message;
494+}
495+
496+/// One JSONL record, if it carries a conversation message. Everything else in the
497+/// log (the header, requests) is history of the run, not context for the model.
498+fn parseMessage(a: std.mem.Allocator, scratch: std.mem.Allocator, line: []const u8) ?message_mod.Message {
499+ if (std.mem.trim(u8, line, " \t\r").len == 0) return null;
500+ const root = std.json.parseFromSliceLeaky(std.json.Value, scratch, line, .{}) catch return null;
501+ if (root != .object) return null;
502+ const kind = str(root.object, "type") orelse return null;
503+ if (!std.mem.eql(u8, kind, "message")) return null;
504+ const record = object(root.object, "message") orelse return null;
505+ const role = str(record, "role") orelse return null;
506+
507+ if (std.mem.eql(u8, role, "user")) {
508+ return .{ .user = .{
509+ .content = dupStr(a, record, "content") orelse "",
510+ .timestamp = int(record, "timestamp"),
511+ } };
512+ }
513+ if (std.mem.eql(u8, role, "toolResult")) {
514+ const parsed = parseParts(a, items(record, "content"));
515+ return .{ .tool_result = .{
516+ .tool_call_id = dupStr(a, record, "toolCallId") orelse "",
517+ .tool_name = dupStr(a, record, "toolName") orelse "",
518+ .text = parsed.text,
519+ .images = parsed.images,
520+ .is_error = boolean(record, "isError"),
521+ .timestamp = int(record, "timestamp"),
522+ } };
523+ }
524+ if (std.mem.eql(u8, role, "assistant")) {
525+ return .{ .assistant = parseAssistant(a, record) orelse return null };
526+ }
527+ return null;
528+}