xonecas.io
79113
Ma

mini-coding-agent / commit ab1b6d6

feat: resume and other cli modes

xonecas2026-10-26 ab1b6d61dcbeb0f9ddca35ba8c36751083e93913 parent d9b8d01

6 files changed

README.md+13−5
@@ -15,9 +15,10 @@ builds for development. The binary lands at `zig-out/bin/mini`. `zig build run
1515
1616 ## Run
1717
18- mini # interactive TUI
19- mini -p '<prompt>' # one turn, print the reply, exit
20- mini -c <file> # overlay a config file for this run
18+ mini # interactive TUI
19+ mini -p '<prompt>' # one turn, print the reply, exit
20+ mini -c <file> # overlay a config file for this run
21+ mini --resume <id> # continue a past session
2122
2223 Arguments:
2324
@@ -25,9 +26,16 @@ Arguments:
2526 |---|---|
2627 | `-p <prompt>`, `--print <prompt>` | run one prompt non-interactively and print the assistant text |
2728 | `-c <file>`, `--config <file>` | read a config file after the global one; its keys win |
29+| `--resume <id>`, `--resume=<id>` | continue the session with that id, or the single session it prefixes |
30+| `--no-config` | ignore the config files and run on the built-in defaults |
31+| `--no-session` | record nothing; nothing to resume afterwards |
2832
29-`-p=<prompt>`, `--print=<prompt>`, `-c=<file>`, and `--config=<file>` work too.
30-Any other argument exits 1.
33+`-p=<prompt>`, `--print=<prompt>`, `-c=<file>`, `--config=<file>`, and
34+`--resume=<id>` work too. Any other argument exits 1.
35+
36+`--resume` replays the recorded conversation into the context and appends to the
37+same log. The TUI prints a dim `resume with: mini --resume <id>` line when it
38+exits, unless `--no-session` was given.
3139
3240 `-p` requires a model in the config. Without one it exits 1 and prints where
3341 the config lives. Interactive mode requires a TTY. In `-p` mode tool calls and
src/config.zig+3−2
@@ -147,10 +147,11 @@ fn sessionsDir(a: std.mem.Allocator) []const u8 {
147147 if (state.len == 0) return "sessions";
148148 return filesystem.join(a, &.{ state, "mini-coding-agent/sessions" }) catch "sessions";
149149 }
150-pub fn load(a: std.mem.Allocator, override: ?[]const u8) !Config {
150+pub fn load(a: std.mem.Allocator, override: ?[]const u8, no_config: bool) !Config {
151151 var cfg = try defaults(a);
152- try readInto(a, configPath(a), false, &cfg);
152+ if (no_config) return cfg;
153153
154+ try readInto(a, configPath(a), false, &cfg);
154155 if (override) |path| {
155156 cfg.path = path;
156157 try readInto(a, path, true, &cfg);
src/headless.zig+5−1
@@ -37,8 +37,12 @@ fn printEvent(ctx: *anyopaque, event: agent.Event) void {
3737 }
3838 }
3939
40-pub fn run(a: std.mem.Allocator, prompt_text: []const u8, opts: agent.Options) u8 {
40+pub fn run(a: std.mem.Allocator, prompt_text: []const u8, opts: agent.Options, resumed: []const message_mod.Message) u8 {
4141 var messages: std.ArrayList(message_mod.Message) = .empty;
42+ messages.appendSlice(a, resumed) catch {
43+ platform.printErr("[error] out of memory\n", .{});
44+ return 1;
45+ };
4246 const user = message_mod.Message{ .user = .{ .content = prompt_text, .timestamp = time.nowMs() } };
4347 messages.append(a, user) catch {
4448 platform.printErr("[error] out of memory\n", .{});
src/main.zig+34−4
@@ -9,6 +9,7 @@ const tools = @import("tools.zig");
99 const tui = @import("tui/tui.zig");
1010 const term = @import("tui/term.zig");
1111 const headless = @import("headless.zig");
12+const message_mod = @import("message.zig");
1213
1314 pub const panic = std.debug.FullPanic(panicRestore);
1415
@@ -26,7 +27,13 @@ pub const debug = struct {
2627
2728 var cancel = std.atomic.Value(bool).init(false);
2829
29-const ParsedArgs = struct { print: ?[]const u8 = null, config: ?[]const u8 = null };
30+const ParsedArgs = struct {
31+ print: ?[]const u8 = null,
32+ config: ?[]const u8 = null,
33+ resume_id: ?[]const u8 = null,
34+ no_config: bool = false,
35+ no_session: bool = false,
36+};
3037
3138 fn parseArgs(a: std.mem.Allocator) !ParsedArgs {
3239 var it = std.process.Args.Iterator.init(platform.args);
@@ -45,6 +52,15 @@ fn parseArgs(a: std.mem.Allocator) !ParsedArgs {
4552 } else if (std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--config")) {
4653 const value = it.next() orelse return error.MissingConfig;
4754 result.config = try a.dupe(u8, value);
55+ } else if (std.mem.startsWith(u8, arg, "--resume=")) {
56+ result.resume_id = try a.dupe(u8, arg["--resume=".len..]);
57+ } else if (std.mem.eql(u8, arg, "--resume")) {
58+ const value = it.next() orelse return error.MissingSession;
59+ result.resume_id = try a.dupe(u8, value);
60+ } else if (std.mem.eql(u8, arg, "--no-config")) {
61+ result.no_config = true;
62+ } else if (std.mem.eql(u8, arg, "--no-session")) {
63+ result.no_session = true;
4864 } else {
4965 platform.printErr("unknown argument: {s}\n", .{arg});
5066 return error.UnknownArg;
@@ -69,12 +85,13 @@ fn run() !u8 {
6985 switch (e) {
7086 error.MissingPrompt => platform.printErr("a prompt is required\n", .{}),
7187 error.MissingConfig => platform.printErr("a config path is required\n", .{}),
88+ error.MissingSession => platform.printErr("a session id is required\n", .{}),
7289 else => {},
7390 }
7491 return 1;
7592 };
7693
77- const cfg = config.load(a, args.config) catch return 1;
94+ const cfg = config.load(a, args.config, args.no_config) catch return 1;
7895
7996 var resolve_err: ?[]const u8 = null;
8097 const model = models.resolve(a, &cfg, &resolve_err);
@@ -85,6 +102,19 @@ fn run() !u8 {
85102
86103 const cwd = std.process.currentPathAlloc(platform.io, a) catch ".";
87104 var sess = session.Session.init(a, cfg.sessions_dir, cwd);
105+ var resumed: std.ArrayList(message_mod.Message) = .empty;
106+ if (args.resume_id) |id| {
107+ sess.reopen(id, &resumed) catch |e| {
108+ switch (e) {
109+ error.NoSuchSession => platform.printErr("no session matching '{s}'\n", .{id}),
110+ error.AmbiguousSession => platform.printErr("session id '{s}' is ambiguous\n", .{id}),
111+ else => platform.printErr("{s}\n", .{@errorName(e)}),
112+ }
113+ return 1;
114+ };
115+ } else {
116+ sess.disabled = args.no_session;
117+ }
88118
89119 const model_ptr: ?*const models.Model = if (model) |m| blk: {
90120 const ptr = try a.create(models.Model);
@@ -111,7 +141,7 @@ fn run() !u8 {
111141 platform.printErr("[error] no model configured; add \"provider\" and \"model\" to {s}\n", .{config.configPath(a)});
112142 return 1;
113143 }
114- return headless.run(a, print_text, opts);
144+ return headless.run(a, print_text, opts, resumed.items);
115145 }
116146
117147 const stdin_tty = std.Io.File.stdin().isTty(platform.io) catch false;
@@ -120,6 +150,6 @@ fn run() !u8 {
120150 platform.printErr("interactive mode requires a TTY; use -p for non-interactive mode\n", .{});
121151 return 1;
122152 }
123- try tui.run(opts, &cfg, cfg.tools);
153+ try tui.run(opts, &cfg, cfg.tools, resumed.items);
124154 return 0;
125155 }
src/session.zig+213−4
@@ -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+}
src/tui/tui.zig+12−1
@@ -998,6 +998,10 @@ const Tui = struct {
998998 self.term.write(self.live.erase(self.a, width));
999999 self.term.write(self.scrollback.buf.items);
10001000 self.term.stop();
1001+ if (self.opts.session.file != null) {
1002+ if (self.opts.session.id) |id|
1003+ platform.writeOut(styles.comment(self.a, std.fmt.allocPrint(self.a, "resume with: mini --resume {s}\n", .{id}) catch ""));
1004+ }
10011005 self.opts.session.close();
10021006 status.release();
10031007 }
@@ -1095,7 +1099,7 @@ fn eventTrampoline(ctx: *anyopaque, event: agent.Event) void {
10951099 self.event_mutex.unlock(platform.io);
10961100 }
10971101
1098-pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const config.ToolName) !void {
1102+pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const config.ToolName, resumed: []const message_mod.Message) !void {
10991103 const gpa = platform.gpa;
11001104 const opts_ptr = try gpa.create(agent.Options);
11011105 opts_ptr.* = opts;
@@ -1113,6 +1117,13 @@ pub fn run(opts: agent.Options, cfg: *const config.Config, tool_names: []const c
11131117
11141118 status.report("idle", null, null);
11151119 self.pushBanner();
1120+ if (resumed.len > 0) {
1121+ self.messages.appendSlice(gpa, resumed) catch {};
1122+ self.note(styles.comment(self.s, std.fmt.allocPrint(self.s, "resumed {s} · {d} messages", .{
1123+ opts_ptr.session.id orelse "",
1124+ resumed.len,
1125+ }) catch "resumed"));
1126+ }
11161127 self.draw();
11171128
11181129 const stdin_thread = std.Thread.spawn(.{}, inputThread, .{self}) catch return;