Repository navigation
Expand file tree
/
Copy pathmain.zig
More file actions
956 lines (888 loc) · 43.9 KB
/
Copy pathmain.zig
File metadata and controls
956 lines (888 loc) · 43.9 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
const std = @import("std");
const Config = @import("model/config.zig").Config;
const Agent = @import("agent/mod.zig").Agent;
const debug = @import("debug/trace.zig");
const provider = @import("model/provider.zig");
const history = @import("cli/history.zig");
const commands = @import("cli/commands.zig");
const mcp = @import("mcp/mod.zig");
const banner = @import("ui/banner.zig");
const term = @import("ui/term.zig");
const sanitize = @import("util/terminal/sanitize.zig");
const Screen = @import("ui/screen.zig").Screen;
const layout = @import("ui/layout.zig");
const Linenoise = @import("editor/linenoise.zig").Linenoise;
const sgr = @import("ui/style.zig");
const RESET = sgr.RESET;
const BOLD = sgr.BOLD;
const DIM = sgr.DIM;
const RED = sgr.RED;
const GREEN = sgr.GREEN;
const YELLOW = sgr.YELLOW;
/// What a build that keeps no trace answers when it is asked to keep one. It
/// is the whole of the tracing feature in such a binary: a flag, a command and
/// a sentence, no recorder and no report renderer.
const NO_TRACING = DIM ++ "Debug: this build records no traces; build it with -Dtrace to record one.\n" ++ RESET;
const HELP_HEAD =
\\Commands:
\\ /help Show this help message
\\ /clear Clear conversation history
\\ /new New session: new id, cleared screen, empty scratch
\\ /session Show the current session ID and resume command
\\ /plan Show the plan; /plan clear drops it
\\ /memory List saved memories
\\ /remember <text> Save a note to memory
\\ /forget <n|all> Remove a saved note
\\ /model Show current model
\\ /status Show token usage and account quota
\\ /mcp List the MCP servers and their tools
;
/// Only a build that can record offers the command, and only that build lists
/// the flags that ask for a trace.
const HELP_TRACE = " /debug Record every step and write an HTML report\n";
const DEBUG_FLAGS =
" --debug Record every step and write an HTML report\n" ++
" --debug-report <trace.jsonl>\n" ++
" Rebuild the HTML report of a trace\n";
const DEBUG_ENV = "AI_DEBUG=1 Same as --debug\n";
const HELP_TAIL =
\\ /quit, /exit Exit zagent
\\ /, @, $ Command / project file / reserved candidates
\\ ↑/↓ Select candidate; Tab/Enter inserts; Esc closes
\\ Wheel/PageUp/Down Scroll output history
\\ While running: commands remain available; typed text adjusts the task
\\ Questions The menu owns the keyboard; Esc or Ctrl+D dismisses it
\\ Own answer Esc in the free-text row goes back to the options
\\ Esc Stop current task and discard input typed while it ran
\\ Ctrl+Z Suspend; resume with fg
\\ Ctrl+D Exit zagent
\\
;
const HELP = HELP_HEAD ++ (if (debug.enabled) HELP_TRACE else "") ++ HELP_TAIL;
// Prompt passed to linenoise. Colour codes are fine here because
// the editor's width() implementation correctly ignores ANSI SGR sequences.
// The arrow is the whole prompt: the word it used to carry said nothing that
// the colour and the position do not.
const PROMPT = BOLD ++ GREEN ++ "\xe2\x9d\xaf" ++ RESET ++ " ";
/// Process arguments are borrowed from the OS (or from an iterator's internal
/// buffer), so copy the ones we keep around for the lifetime of `main`.
fn collectArgs(allocator: std.mem.Allocator, args: std.process.Args) !std.ArrayList([]const u8) {
var list: std.ArrayList([]const u8) = .empty;
errdefer {
for (list.items) |arg| allocator.free(arg);
list.deinit(allocator);
}
var iter = try std.process.Args.Iterator.initAllocator(args, allocator);
defer iter.deinit();
while (iter.next()) |arg| {
try list.append(allocator, try allocator.dupe(u8, arg));
}
return list;
}
fn freeArgs(allocator: std.mem.Allocator, args: []const []const u8) void {
for (args) |arg| allocator.free(arg);
}
/// Recall the prompts typed in earlier runs and hand back the file to save
/// them to, or null when they cannot be kept: no home directory to put them
/// in, or no terminal whose history would be worth keeping. Lines read from a
/// pipe are not the user's own history, so a non-interactive stdin is left
/// alone.
fn openHistory(
allocator: std.mem.Allocator,
io: std.Io,
env: *const std.process.Environ.Map,
ln: *Linenoise,
) !?[]u8 {
if (!ln.is_tty) return null;
const path = (try history.statePath(allocator, env)) orelse return null;
errdefer allocator.free(path);
if (!history.load(io, ln, path)) {
allocator.free(path);
return null;
}
return path;
}
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
const io = init.io;
const env = init.environ_map;
var args = try collectArgs(allocator, init.minimal.args);
defer {
freeArgs(allocator, args.items);
args.deinit(allocator);
}
if (args.items.len == 2 and (std.mem.eql(u8, args.items[1], "--help") or std.mem.eql(u8, args.items[1], "-h"))) {
try std.Io.File.stdout().writeStreamingAll(io, "Usage: zagent [query ...]\n" ++
"With no query, start an interactive conversation.\n\n" ++
" --help, -h Show this help\n" ++
" --version Show version\n" ++
" --resume <id> Resume a saved session in this workspace\n" ++
(if (debug.enabled) DEBUG_FLAGS else "") ++
" login / logout Sign in with ChatGPT / remove local credentials\n" ++
" models List models for the selected provider\n\n" ++
"AI_PROVIDER=deepseek Use DEEPSEEK_API_KEY\n" ++
"AI_PROVIDER=openai-compatible Any Responses-compatible vendor; set AI_URL and AI_MODEL.\n" ++
"AI_URL / AI_MODEL / AI_KEY override provider settings.\n" ++
(if (debug.enabled) DEBUG_ENV else "") ++
"AI_MEMORY_FILE Store memory in another file\n" ++
"Tools and local MCP servers run on the host with inherited environment and network access.\n" ++
"Build with Zig 0.17.0.\n");
return;
}
if (args.items.len == 2 and std.mem.eql(u8, args.items[1], "--version")) {
try std.Io.File.stdout().writeStreamingAll(io, "zagent 0.1.0 (Zig 0.17)\n");
return;
}
// Turning a trace kept earlier into a report touches no workspace, no
// credentials and no trust decision: the file is read, the page is written
// beside it, and the run is over.
if (args.items.len == 3 and std.mem.eql(u8, args.items[1], "--debug-report")) {
if (comptime debug.enabled) {
try writeDebugReport(allocator, io, args.items[2]);
} else {
try printToStderr(allocator, io, NO_TRACING, .{});
std.process.exit(1);
}
return;
}
if (args.items.len == 2 and (std.mem.eql(u8, args.items[1], "login") or std.mem.eql(u8, args.items[1], "logout"))) {
const auth = @import("model/codex_auth.zig");
const auth_path = try auth.path(allocator, env);
defer allocator.free(auth_path);
if (std.mem.eql(u8, args.items[1], "login")) {
try auth.login(allocator, io, auth_path);
} else {
try auth.logout(io, auth_path);
}
return;
}
// Trust must precede state loading, API requests and local MCP startup.
// Administrative commands do not operate in the current workspace.
if (!(args.items.len == 2 and std.mem.eql(u8, args.items[1], "models"))) {
const workspace = @import("state/workspace.zig");
if (!try workspace.isTrusted(allocator, io, env)) {
const canonical = try std.Io.Dir.cwd().realPathFileAlloc(io, ".", allocator);
defer allocator.free(canonical);
const stderr = std.Io.File.stderr();
if (!(std.Io.File.stdin().isTty(io) catch false) or !(stderr.isTty(io) catch false)) {
try stderr.writeStreamingAll(io, "Not trusted. Run interactively to approve this directory first.\n");
std.process.exit(1);
}
try printToStderr(allocator, io, "\nTrust this directory?\n {s}\nTrusted directories allow tool execution and local MCP servers.\n", .{canonical});
const menu = @import("ui/menu.zig");
const options = [_]menu.Option{
.{ .label = "Don't trust and exit", .description = "", .recommended = false },
.{ .label = "Trust and continue", .description = "", .recommended = false },
};
const answer = try menu.selectOnly(allocator, io, "Choose an action", &options);
const trusted = switch (answer) {
.option => |index| index == 1,
.custom, .cancel => false,
};
if (!trusted) {
try std.Io.File.stderr().writeStreamingAll(io, "Not trusted. Exiting.\n");
std.process.exit(1);
}
try workspace.trust(allocator, io, env);
}
}
const config = Config.load(allocator, io, env) catch |err| switch (err) {
error.UnknownProvider => {
const valid = try std.mem.join(allocator, ", ", provider.Provider.names());
defer allocator.free(valid);
const msg = try std.fmt.allocPrint(
allocator,
RED ++ "Error: unknown AI_PROVIDER." ++ RESET ++
"\n Valid values: {s}\n" ++
" To use another Responses-compatible vendor, set AI_PROVIDER=openai-compatible\n" ++
" together with AI_URL, AI_MODEL and AI_KEY; for a vendor speaking the\n" ++
" Anthropic Messages API, use anthropic-compatible instead.\n",
.{valid},
);
defer allocator.free(msg);
std.Io.File.stderr().writeStreamingAll(io, msg) catch {};
// Exiting directly rather than returning keeps Zig from printing a
// stack trace underneath an error that is already fully explained.
std.process.exit(1);
},
error.MissingProviderUrl, error.MissingProviderModel => {
// Both "-compatible" presets have no host of their own, so point at
// the exact setting that is missing rather than at an empty request.
const missing = if (err == error.MissingProviderUrl) "AI_URL" else "AI_MODEL";
const msg = try std.fmt.allocPrint(
allocator,
RED ++ "Error: the selected AI_PROVIDER needs {s}." ++ RESET ++
"\n AI_URL is the base URL without /responses or /messages," ++
" AI_MODEL is sent unchanged.\n" ++
"\n Alibaba Cloud Model Studio (百炼), Responses API:\n" ++
" export AI_PROVIDER=openai-compatible\n" ++
" export AI_URL=https://dashscope.aliyuncs.com/compatible-mode/v1\n" ++
" export AI_MODEL=qwen-plus\n" ++
" export AI_KEY=sk-your-dashscope-key\n" ++
"\n A gateway speaking the Anthropic Messages API:\n" ++
" export AI_PROVIDER=anthropic-compatible\n" ++
" export AI_URL=https://api.moonshot.cn/anthropic\n" ++
" export AI_MODEL=kimi-k2-turbo-preview\n" ++
" export AI_KEY=sk-your-key\n" ++
"\n Anthropic's own API needs neither: AI_PROVIDER=anthropic and" ++
" ANTHROPIC_API_KEY.\n",
.{missing},
);
defer allocator.free(msg);
std.Io.File.stderr().writeStreamingAll(io, msg) catch {};
std.process.exit(1);
},
error.InvalidThinking => {
std.Io.File.stderr().writeStreamingAll(io, RED ++ "Error: unknown AI_THINKING value." ++ RESET ++
"\n Accepted: enabled, disabled, or omit (on/off also work)." ++
"\n DeepSeek and openai-compatible ask for thinking by default; the OpenAI" ++
"\n and Codex backends send nothing unless AI_THINKING says otherwise.\n") catch {};
std.process.exit(1);
},
else => return err,
};
defer config.deinit();
if (args.items.len == 2 and std.mem.eql(u8, args.items[1], "models")) {
var client = @import("model/openai.zig").Client.init(allocator, io, config);
defer client.deinit();
const models = try client.listModels();
defer allocator.free(models);
try std.Io.File.stdout().writeStreamingAll(io, models);
try std.Io.File.stdout().writeStreamingAll(io, "\n");
return;
}
// Flags come before the query: the first word that is not one starts it.
var query_start: usize = 1;
var resume_id: ?[]const u8 = null;
// Asked for by the flag, the environment or the config file. A build
// without tracing says so once and runs untouched, rather than quitting on
// a switch it never had.
var tracing_requested = config.debug;
while (query_start < args.items.len) {
const arg = args.items[query_start];
if (std.mem.eql(u8, arg, "--resume")) {
if (query_start + 1 >= args.items.len) {
try std.Io.File.stderr().writeStreamingAll(io, "Usage: zagent --resume <session-id> [query ...]\n");
std.process.exit(1);
}
resume_id = args.items[query_start + 1];
query_start += 2;
} else if (std.mem.eql(u8, arg, "--debug")) {
tracing_requested = true;
query_start += 1;
} else break;
}
// The terminal is created here rather than inside the REPL so that the
// ask_user menu also works in single-query mode.
var ln = Linenoise.init(allocator, io, env);
defer ln.deinit();
// Show command, file, and reserved-extension candidates as the user types.
ln.completions_callback = commands.complete;
ln.popup_callback = @import("cli/completion.zig").candidates;
const history_path = try openHistory(allocator, io, env, &ln);
defer if (history_path) |path| allocator.free(path);
// The MCP servers are started before the first question, because the tools
// they bring are part of what the question is asked with.
var problems: std.ArrayList([]u8) = .empty;
defer {
for (problems.items) |problem| allocator.free(problem);
problems.deinit(allocator);
}
const stderr = std.Io.File.stderr();
// What came of the servers is collected rather than printed: the
// interactive session takes the terminal over and starts on a blank
// screen, so a line written now would be erased before it could be read.
// It is drawn under the wordmark instead. Only the per-server "starting"
// progress stays live, because that is what the wait looks like.
var report: std.Io.Writer.Allocating = .init(allocator);
defer report.deinit();
var watcher = McpProgress{ .io = io, .allocator = allocator };
var registry = mcp.Registry.connect(allocator, io, env, &problems, .{
.context = &watcher,
.started = McpProgress.started,
}) catch |err| failed: {
try report.writer.print(YELLOW ++ " ⚠ mcp: no servers were read: {s}\n" ++ RESET, .{@errorName(err)});
break :failed mcp.Registry.empty(allocator, io);
};
// Declared before the agent, because the agent borrows it and the defers
// run in reverse: the agent has to be gone before this one is freed.
defer registry.deinit();
for (problems.items) |problem| {
try report.writer.print(YELLOW ++ " ⚠ {s}\n" ++ RESET, .{problem});
}
try registry.writeStartup(&report.writer);
// Registered before the agent, so it runs after it: a sub-agent closed in
// `agent.deinit` still has its last steps recorded, and the report is
// written once nothing else can write to the trace.
var trace: ?*debug.Recorder = null;
defer if (trace) |opened| publishTrace(allocator, io, opened);
var agent = try Agent.init(allocator, io, &config, &ln, env, ®istry);
defer agent.deinit();
agent.startSession(resume_id) catch |err| {
try printToStderr(allocator, io, "Cannot open session: {s}\n", .{@errorName(err)});
std.process.exit(1);
};
// The trace is named after the session, so it opens once the session does.
if (comptime debug.enabled) {
if (tracing_requested) {
trace = openTrace(allocator, io, env, agent.session_id);
if (trace) |opened| agent.attachTrace(opened);
}
} else if (tracing_requested) {
try printToStderr(allocator, io, NO_TRACING, .{});
}
if (args.items.len > query_start) {
// No wordmark and no screen in this mode, so the report goes out here,
// to stderr: stdout belongs to the answer, and `zagent "..." > notes.md`
// stays clean.
if (trace) |opened| {
try printToStderr(allocator, io, DIM ++ "Debug: recording this run; report {s}\n" ++ RESET, .{opened.report_path});
}
if (report.written().len > 0) {
try stderr.writeStreamingAll(io, report.written());
try stderr.writeStreamingAll(io, "\n");
}
if (agent.session_id) |id| {
try printToStderr(allocator, io, "Session: {s} (resume: zagent --resume {s})\n", .{ id, id });
}
// Single-query mode: join remaining args as the query
const query = try std.mem.join(allocator, " ", args.items[query_start..]);
defer allocator.free(query);
// Esc at a question ends the run as a cancellation, and the notice for
// it was written where the run stopped: that is not a failed query.
agent.processQuery(query) catch |err| {
if (err != error.Canceled or !agent.interrupted.load(.acquire)) return err;
};
} else {
// Interactive REPL mode
try runRepl(allocator, io, env, &agent, config, &ln, history_path, ®istry, report.written(), &trace);
if (agent.session_id) |id| {
try printToStderr(allocator, io, "Resume session: zagent --resume {s}\n", .{id});
}
}
}
fn runRepl(
allocator: std.mem.Allocator,
io: std.Io,
env: *const std.process.Environ.Map,
agent: *Agent,
config: Config,
ln: *Linenoise,
history_path: ?[]const u8,
registry: *const mcp.Registry,
mcp_report: []const u8,
/// The run's trace, or the slot `/debug` opens one into. The pointer is
/// what makes a trace turned on mid-session outlive this function.
trace: *?*debug.Recorder,
) !void {
const stdout = std.Io.File.stdout();
const stderr = std.Io.File.stderr();
// The interactive session owns the whole terminal: the conversation fills
// it and the prompt sits at the bottom. A piped or `TERM=dumb` run keeps
// the old inline layout, where the output is what the consumer reads.
var screen = Screen.init(allocator, io, ln.is_tty and ln.term_supported and
(stdout.isTty(io) catch false));
if (env.get("TMUX")) |value| {
if (value.len > 0) screen.tmux_env = env;
}
agent.attachScreen(if (screen.isActive()) &screen else null);
defer agent.attachScreen(null);
try screen.enter();
defer screen.deinit();
var runtime = @import("cli/runtime.zig").Runtime{ .agent = agent, .screen = &screen };
if (screen.isActive()) {
screen.buffered = true;
agent.form_context = &runtime;
agent.form_callback = @import("cli/runtime.zig").Runtime.presentForm;
ln.tick_callback = tickRuntime;
ln.scroll_callback = scrollRuntime;
ln.mouse_callback = mouseRuntime;
ln.interrupt_callback = interruptRuntime;
ln.handoff_callback = questionRuntime;
}
ln.multiline_mode = true;
ln.bottom_anchor = screen.isActive();
ln.layout_callback = layoutScreen;
ln.layout_context = &runtime;
// The editor must not keep pointing at a screen that is about to go away.
defer {
runtime.deinit();
ln.bottom_anchor = false;
ln.layout_callback = null;
ln.layout_context = null;
ln.tick_callback = null;
ln.scroll_callback = null;
ln.mouse_callback = null;
ln.interrupt_callback = null;
ln.handoff_callback = null;
agent.form_callback = null;
agent.form_context = null;
}
// Fullscreen keeps its own blank prompt row at the bottom, so the
// animation must not draw a second prompt above it.
agent.progress_prompt = if (ln.is_tty and !screen.isActive()) PROMPT else null;
// The opening report is drawn again by `/new`, so it is one function: a
// session this process opens later has to look like the one it opened on.
const colour = ln.term_supported and (stdout.isTty(io) catch false);
try writeHeader(allocator, io, env, &screen, config, agent, mcp_report, trace, colour);
// The API history was loaded before the terminal existed. Seed the screen's
// conversation log now so scrolling and redraws retain the restored turns.
try agent.replayHistory();
while (true) {
// linenoise handles raw-mode input, Unicode width, and multi-byte
// character deletion correctly (including Chinese/CJK characters).
// Returns null on EOF (Ctrl+D); error.CtrlC on Ctrl+C, error.Suspend on
// Ctrl+Z. The rows the prompt needs are reserved before every read: the
// conversation is drawn above them, never under them.
try screen.prepareInput();
const maybe_line = ln.linenoise(PROMPT) catch |err| switch (err) {
error.CtrlC => null,
error.Handoff => {
// A question is waiting. The editor has parked the line it was
// editing, so the menu can have the keyboard and the prompt
// rows: the question is asked where the input box was.
try screen.endInput();
try runtime.serveQuestions();
continue;
},
error.Suspend => {
// Hand the terminal back, stop, and come back to the same
// line: the editor hands the typed text over in
// `pending_input`, so the retry opens on it.
try screen.suspendProcess();
continue;
},
else => return err,
};
try screen.endInput();
const raw_line = maybe_line orelse {
try writeOut(&screen, stdout, io, "\n");
break;
};
defer allocator.free(raw_line);
const line = std.mem.trim(u8, raw_line, " \t\r\n");
if (line.len == 0) continue;
screen.followLatest();
// The editor's rows are cleared once the line is read; the question
// still belongs in the record, with the prompt it was typed after. An
// inline run keeps the prompt line on screen already.
if (screen.isActive()) {
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
try aw.writer.writeAll(PROMPT);
try sanitize.writeSanitized(&aw.writer, line);
try aw.writer.writeByte('\n');
try screen.writeLog(aw.written());
}
// Add non-empty lines to history so the user can navigate with ↑/↓.
// The file, when there is one, makes that outlive the process; it is
// written before the query runs, so an interrupt part-way through an
// answer cannot lose the question that asked for it.
try ln.history.add(line);
if (history_path) |path| history.save(io, ln, path);
// Only the bare `/plan` reads while a task runs: `/plan clear` changes
// state the worker is still using, so it waits like the other commands
// that do.
const plan_read_only = std.mem.eql(u8, line, "/plan");
if (runtime.busy() and line[0] == '/' and !plan_read_only and
!std.mem.eql(u8, line, "/status") and !std.mem.eql(u8, line, "/help") and
!std.mem.eql(u8, line, "/model") and !std.mem.eql(u8, line, "/mcp") and !std.mem.eql(u8, line, "/session") and
!std.mem.eql(u8, line, "/debug") and
!std.mem.eql(u8, line, "/quit") and !std.mem.eql(u8, line, "/exit"))
{
try writeBlock(allocator, &screen, stdout, io, "This command changes session state; retry after the current task finishes.\n");
continue;
}
if (std.mem.eql(u8, line, "/quit") or std.mem.eql(u8, line, "/exit")) {
try writeBlock(allocator, &screen, stdout, io, DIM ++ "Goodbye!\n" ++ RESET);
break;
} else if (std.mem.eql(u8, line, "/help")) {
try writeBlock(allocator, &screen, stdout, io, HELP);
} else if (std.mem.eql(u8, line, "/session")) {
const message = try std.fmt.allocPrint(allocator, "Session: {s}\nResume: zagent --resume {s}\n", .{ agent.session_id.?, agent.session_id.? });
defer allocator.free(message);
try writeBlock(allocator, &screen, stdout, io, message);
} else if (std.mem.eql(u8, line, "/new")) {
// The id of the session being left outlives it: the line that
// announces the new session names the old one, so the conversation
// that just left the screen can be found again.
const previous = if (agent.session_id) |id| try allocator.dupe(u8, id) else null;
defer if (previous) |id| allocator.free(id);
agent.startSession(null) catch |err| {
const message = try std.fmt.allocPrint(allocator, "Cannot create session: {s}\n", .{@errorName(err)});
defer allocator.free(message);
try writeBlock(allocator, &screen, stderr, io, message);
continue;
};
// The scratch directory belongs to the conversation being left
// behind, not to the new one, so a new session starts from an empty
// directory. The path itself stays: the system prompt names it.
agent.scratch.reset() catch |err| {
const message = try std.fmt.allocPrint(allocator, "Cannot clear scratch directory: {s}\n", .{@errorName(err)});
defer allocator.free(message);
try writeBlock(allocator, &screen, stderr, io, message);
};
// Nothing of the old session may stay visible: an answer above the
// prompt would be read as this session's own context. The screen is
// emptied and the opening report drawn again, so a new session
// begins on the screen a new process begins on.
screen.clearLog();
try writeHeader(allocator, io, env, &screen, config, agent, mcp_report, trace, colour);
const message = if (previous) |id|
try std.fmt.allocPrint(allocator, DIM ++ " ── new session ── the previous conversation is off the screen; zagent --resume {s} brings it back\n" ++ RESET, .{id})
else
try std.fmt.allocPrint(allocator, DIM ++ " ── new session ── the previous conversation is off the screen\n" ++ RESET, .{});
defer allocator.free(message);
try writeOut(&screen, stdout, io, message);
// The header ends with the blank line the next prompt needs, so the
// loop's trailing newline would leave one row more than a fresh
// start does.
continue;
} else if (std.mem.eql(u8, line, "/clear")) {
agent.clearHistory();
try writeBlock(allocator, &screen, stdout, io, DIM ++ "Conversation history cleared.\n" ++ RESET);
} else if (std.mem.eql(u8, line, "/plan") or std.mem.startsWith(u8, line, "/plan ")) {
const argument = std.mem.trim(u8, line["/plan".len..], " \t");
agent.planCommand(argument) catch |err| try reportCommandError(allocator, &screen, io, "plan", err);
} else if (std.mem.eql(u8, line, "/memory")) {
agent.listMemory() catch |err| try reportCommandError(allocator, &screen, io, "memory", err);
} else if (std.mem.eql(u8, line, "/remember") or std.mem.startsWith(u8, line, "/remember ")) {
const note = std.mem.trim(u8, line["/remember".len..], " \t");
agent.rememberCommand(note) catch |err| try reportCommandError(allocator, &screen, io, "remember", err);
} else if (std.mem.eql(u8, line, "/forget") or std.mem.startsWith(u8, line, "/forget ")) {
const argument = std.mem.trim(u8, line["/forget".len..], " \t");
agent.forgetCommand(argument) catch |err| try reportCommandError(allocator, &screen, io, "forget", err);
} else if (std.mem.eql(u8, line, "/status")) {
const counts = agent.client.tokenCounts();
const msg = try std.fmt.allocPrint(allocator, "Model: {s}\nWorkspace: {s}\nScratch: {s}\nLast turn tokens (server usage only): input {d} (cached {d}), output {d} (reasoning {d}), total {d}\nUsage reported: {d}/{d} calls; missing usage is unknown, not estimated.\nCached/reasoning tokens are included in input/output, not added again.\n", .{ config.model, agent.workspace, agent.scratch.path, counts.input, counts.cached, counts.output, counts.reasoning, counts.total, counts.usage_reports, counts.requests });
defer allocator.free(msg);
try writeBlock(allocator, &screen, stdout, io, msg);
if (config.provider == .codex) {
const settings = try @import("model/status.zig").formatCodexSettings(allocator, config.service_tier, config.reasoning_effort);
defer allocator.free(settings);
try writeBlock(allocator, &screen, stdout, io, settings);
}
var status_client = @import("model/openai.zig").Client.init(allocator, io, config);
defer status_client.deinit();
const quota = status_client.quotaStatus() catch |err| {
try reportCommandError(allocator, &screen, io, "status: quota unavailable", err);
continue;
};
defer allocator.free(quota);
try writeBlock(allocator, &screen, stdout, io, quota);
} else if (std.mem.eql(u8, line, "/model")) {
const msg = try std.fmt.allocPrint(allocator, "Model: {s}\n", .{config.model});
defer allocator.free(msg);
try writeBlock(allocator, &screen, stdout, io, msg);
} else if (std.mem.eql(u8, line, "/mcp")) {
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
try registry.writeStatus(&aw.writer);
try writeBlock(allocator, &screen, stdout, io, aw.written());
} else if (std.mem.eql(u8, line, "/debug")) {
try debugCommand(allocator, io, &screen, stdout, stderr, env, agent, trace);
} else if (screen.isActive()) {
try runtime.submit(line);
} else {
// A stop ends one run, not the session: the next line starts with
// a clean flag, the way the screen runtime's tick does.
agent.interrupted.store(false, .release);
agent.processQuery(line) catch |err| {
if (err == error.Canceled and agent.interrupted.load(.acquire)) {
try writeOut(&screen, stdout, io, "\n");
continue;
}
const errmsg = try std.fmt.allocPrint(allocator, RED ++ "Error: {s}" ++ RESET ++ "\n", .{@errorName(err)});
defer allocator.free(errmsg);
try writeBlock(allocator, &screen, stderr, io, errmsg);
};
}
try writeOut(&screen, stdout, io, "\n");
}
}
/// Send finished bytes to the conversation, or straight to `file` when the
/// session does not own the screen.
fn writeOut(screen: *Screen, file: std.Io.File, io: std.Io, bytes: []const u8) !void {
if (screen.isActive()) return screen.writeLog(bytes);
try file.writeStreamingAll(io, bytes);
}
/// Send a finished block — help, a listing, a notice — to the conversation at
/// its left margin, so a command's output starts where the answer and the tool
/// calls above it start. Anything else is handed over as it is: a pipe or a
/// file is read by another program, which cannot see a margin and did not ask
/// for one.
fn writeBlock(
allocator: std.mem.Allocator,
screen: *Screen,
file: std.Io.File,
io: std.Io,
bytes: []const u8,
) !void {
if (!onTerminal(screen, io)) return writeOut(screen, file, io, bytes);
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
try layout.write(&aw.writer, bytes);
return writeOut(screen, file, io, aw.written());
}
/// Whether what is written is read by a person on a terminal rather than by
/// another program. It is the one condition under which the conversation takes
/// a left margin.
fn onTerminal(screen: *Screen, io: std.Io) bool {
if (screen.isActive()) return true;
return std.Io.File.stdout().isTty(io) catch false;
}
/// Report a slash-command failure without taking the REPL down with it.
fn reportCommandError(
allocator: std.mem.Allocator,
screen: *Screen,
io: std.Io,
command: []const u8,
err: anyerror,
) !void {
const message = try std.fmt.allocPrint(allocator, RED ++ "Error: {s}: {s}" ++ RESET ++ "\n", .{ command, @errorName(err) });
defer allocator.free(message);
try writeBlock(allocator, screen, std.Io.File.stderr(), io, message);
}
/// The opening report: wordmark, model, session, hints.
///
/// It is drawn once when the process starts and again by `/new`, which is why
/// it is a function rather than a block at the top of the REPL: the session the
/// process opens with and one started later have to look the same, so that a
/// cleared screen reads as a fresh start.
fn writeHeader(
allocator: std.mem.Allocator,
io: std.Io,
env: *const std.process.Environ.Map,
screen: *Screen,
config: Config,
agent: *Agent,
mcp_report: []const u8,
trace: *?*debug.Recorder,
/// Whether the terminal can take colour and the wordmark's letterforms.
colour: bool,
) !void {
const stdout = std.Io.File.stdout();
{
// The wordmark is drawn through an allocating writer because a
// truecolour one costs a few kilobytes of escape sequences. Colour is
// for a terminal only: piped to a file it would be noise.
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
try banner.write(&aw.writer, .{
.mode = banner.detect(env, colour),
.columns = if (screen.isActive()) screen.cols else term.columns(stdout),
});
// The startup report belongs to the header, and the terminal was taken
// over after the servers were started: this is where it can be read.
if (mcp_report.len > 0) try aw.writer.writeAll(mcp_report);
try aw.writer.writeByte('\n');
try writeOut(screen, stdout, io, aw.written());
}
{
// The label is dim and the model name is not, so the eye lands on the
// value rather than on the word "Model".
const model_line = if (config.provider) |selected|
try std.fmt.allocPrint(allocator, DIM ++ " Model " ++ RESET ++ "{s}" ++ DIM ++ " · {s}\n" ++ RESET, .{ config.model, selected.name() })
else
try std.fmt.allocPrint(allocator, DIM ++ " Model " ++ RESET ++ "{s}\n" ++ RESET, .{config.model});
defer allocator.free(model_line);
try writeOut(screen, stdout, io, model_line);
}
if (agent.session_id) |id| {
const message = try std.fmt.allocPrint(allocator, " Session {s}\n Resume zagent --resume {s}\n", .{ id, id });
defer allocator.free(message);
try writeOut(screen, stdout, io, message);
}
if (trace.*) |opened| {
const message = try std.fmt.allocPrint(allocator, DIM ++ " Debug recording; report {s}\n" ++ RESET, .{opened.report_path});
defer allocator.free(message);
try writeOut(screen, stdout, io, message);
}
try writeOut(screen, stdout, io, DIM ++ " Enter to send, Shift+Enter for newline, Ctrl+Z to suspend, Ctrl+D to exit. /help for commands.\n\n" ++ RESET);
if (config.api_key.len == 0 and config.provider != .codex) {
// Name the variable that actually applies, so a provider user is not
// told to export a key for some other service.
const key_var = if (config.provider) |selected| selected.spec().api_key_env else "OPENAI_API_KEY";
const msg = try std.fmt.allocPrint(
allocator,
YELLOW ++ "Warning: {s} is not set.\n export {s}=your-key\n\n" ++ RESET,
.{ key_var, key_var },
);
defer allocator.free(msg);
try writeBlock(allocator, screen, std.Io.File.stderr(), io, msg);
}
}
/// The editor reports how many rows it needs at the bottom. Reserving them is
/// what repaints the conversation when the prompt grows.
fn layoutScreen(context: ?*anyopaque, rows: usize, repaint: bool) anyerror!void {
const runtime: *@import("cli/runtime.zig").Runtime = @ptrCast(@alignCast(context));
runtime.screen.editor_frame = true;
defer runtime.screen.editor_frame = false;
try runtime.screen.reserveInput(rows, repaint);
}
fn tickRuntime(context: ?*anyopaque) anyerror!bool {
const runtime: *@import("cli/runtime.zig").Runtime = @ptrCast(@alignCast(context));
return runtime.tick();
}
fn interruptRuntime(context: ?*anyopaque) anyerror!void {
const runtime: *@import("cli/runtime.zig").Runtime = @ptrCast(@alignCast(context));
try runtime.interrupt();
}
fn questionRuntime(context: ?*anyopaque) anyerror!bool {
return @import("cli/runtime.zig").Runtime.questionPending(context);
}
fn mouseRuntime(context: ?*anyopaque, report: []const u8) anyerror!void {
const rt: *@import("cli/runtime.zig").Runtime = @ptrCast(@alignCast(context orelse return));
try rt.screen.mouse(report);
}
fn scrollRuntime(context: ?*anyopaque, up: bool, page: bool) anyerror!void {
const runtime: *@import("cli/runtime.zig").Runtime = @ptrCast(@alignCast(context));
try runtime.screen.scroll(up, page);
}
/// Says what is being waited for before each server is started. Written to
/// stderr, where the rest of the progress already goes.
const McpProgress = struct {
io: std.Io,
allocator: std.mem.Allocator,
fn started(context: *anyopaque, name: []const u8) void {
const self: *McpProgress = @ptrCast(@alignCast(context));
const line = std.fmt.allocPrint(
self.allocator,
DIM ++ " ⚙ mcp: starting \"{s}\"…\n" ++ RESET,
.{name},
) catch return;
defer self.allocator.free(line);
std.Io.File.stderr().writeStreamingAll(self.io, line) catch {};
}
};
/// `/debug`: report where the record is going, or start one, because a problem
/// has usually already happened twice before anyone thinks to look. A build
/// without tracing answers with the one sentence it has on the subject.
fn debugCommand(
allocator: std.mem.Allocator,
io: std.Io,
screen: *Screen,
stdout: std.Io.File,
stderr: std.Io.File,
env: *const std.process.Environ.Map,
agent: *Agent,
trace: *?*debug.Recorder,
) !void {
if (comptime !debug.enabled) {
try writeBlock(allocator, screen, stderr, io, NO_TRACING);
} else {
if (trace.*) |opened| {
const message = try std.fmt.allocPrint(allocator, "Debug: report {s}\nDebug: trace {s}\n", .{ opened.report_path, opened.jsonl_path });
defer allocator.free(message);
try writeBlock(allocator, screen, stdout, io, message);
} else if (openTrace(allocator, io, env, agent.session_id)) |opened| {
trace.* = opened;
agent.attachTrace(opened);
const message = try std.fmt.allocPrint(allocator, DIM ++ "Debug: recording from here; report {s}\n" ++ RESET, .{opened.report_path});
defer allocator.free(message);
try writeBlock(allocator, screen, stdout, io, message);
} else {
try writeBlock(allocator, screen, stderr, io, "Debug: this run cannot be recorded.\n");
}
}
}
fn printToStderr(
allocator: std.mem.Allocator,
io: std.Io,
comptime fmt: []const u8,
args: anytype,
) !void {
const message = try std.fmt.allocPrint(allocator, fmt, args);
defer allocator.free(message);
try std.Io.File.stderr().writeStreamingAll(io, message);
}
/// Open a trace for this run, saying where it went. Failure to record is never
/// failure of the run: it is reported and the answer goes on without it.
fn openTrace(
allocator: std.mem.Allocator,
io: std.Io,
env: *const std.process.Environ.Map,
session: ?[]const u8,
) ?*debug.Recorder {
const opened = allocator.create(debug.Recorder) catch return null;
opened.* = debug.Recorder.open(allocator, io, env, session) catch |err| {
allocator.destroy(opened);
printToStderr(allocator, io, "Debug: cannot record this run: {s}\n", .{@errorName(err)}) catch {};
return null;
};
return opened;
}
/// Close the record and say where the report and the trace are. The report is
/// rendered from the trace file, so a failure to render it loses the page but
/// not the record.
fn publishTrace(allocator: std.mem.Allocator, io: std.Io, opened: *debug.Recorder) void {
const failed = if (opened.finish()) |_| false else |err| reported: {
printToStderr(allocator, io, "Debug: the report could not be written: {s}\n", .{@errorName(err)}) catch {};
break :reported true;
};
if (!failed) {
printToStderr(allocator, io, DIM ++ "Debug: report " ++ RESET ++ "{s}\n", .{opened.report_path}) catch {};
}
printToStderr(allocator, io, DIM ++ "Debug: trace " ++ RESET ++ "{s}\n", .{opened.jsonl_path}) catch {};
opened.deinit();
allocator.destroy(opened);
}
/// Turn a trace kept earlier into its report, beside it.
fn writeDebugReport(allocator: std.mem.Allocator, io: std.Io, jsonl_path: []const u8) !void {
const html_path = try @import("debug/report.zig").htmlPathFor(allocator, jsonl_path);
defer allocator.free(html_path);
@import("debug/report.zig").writeFile(allocator, io, jsonl_path, html_path) catch |err| {
try printToStderr(allocator, io, "Cannot read the trace: {s}\n", .{@errorName(err)});
std.process.exit(1);
};
const stdout = std.Io.File.stdout();
try stdout.writeStreamingAll(io, html_path);
try stdout.writeStreamingAll(io, "\n");
}
// The other modules are only reachable from `main`, which a test build never
// analyzes, so their tests would otherwise be dropped from `zig build test`.
test {
_ = @import("editor/linenoise.zig");
_ = @import("unicode_width/wcwidth.zig");
_ = @import("agent/mod.zig");
_ = @import("model/status.zig");
_ = @import("host/exec.zig");
_ = @import("host/sysinfo.zig");
_ = @import("state/session.zig");
_ = @import("tools/dispatch.zig");
_ = @import("cli/history.zig");
_ = @import("tools/mod.zig");
_ = @import("diff/mod.zig");
_ = @import("model/openai.zig");
_ = @import("model/config.zig");
_ = @import("model/provider.zig");
_ = @import("ui/menu.zig");
_ = @import("cli/completion.zig");
_ = @import("cli/commands.zig");
_ = @import("state/memory.zig");
_ = @import("ui/style.zig");
_ = @import("ui/term.zig");
_ = @import("ui/screen.zig");
_ = @import("ui/banner.zig");
_ = @import("util/text.zig");
_ = @import("util/terminal/ansi.zig");
_ = @import("util/terminal/sanitize.zig");
_ = @import("util/terminal/normalize.zig");
_ = @import("ui/render.zig");
_ = @import("ui/layout.zig");
_ = @import("ui/spinner.zig");
_ = @import("mcp/mod.zig");
_ = @import("mcp/transport.zig");
_ = @import("debug/trace.zig");
_ = @import("debug/report.zig");
}
test "config loads" {
const allocator = std.testing.allocator;
// An empty map has no HOME, so no config file is read and the developer's
// own environment cannot leak into the test.
var env = std.process.Environ.Map.init(allocator);
defer env.deinit();
const config = try Config.load(allocator, std.testing.io, &env);
defer config.deinit();
try std.testing.expect(config.max_tokens > 0);
}