Repository navigation
Expand file tree
/
Copy pathmod.zig
More file actions
3263 lines (3031 loc) · 162 KB
/
Copy pathmod.zig
File metadata and controls
3263 lines (3031 loc) · 162 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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const openai = @import("../model/openai.zig");
const trace_mod = @import("../debug/trace.zig");
const tools = @import("../tools/mod.zig");
const sanitize = @import("../util/terminal/sanitize.zig");
const menu = @import("../ui/menu.zig");
const memory_mod = @import("../state/memory.zig");
const plan_mod = @import("../state/plan.zig");
const mcp = @import("../mcp/mod.zig");
const scratch_mod = @import("../state/scratch.zig");
const sysinfo = @import("../host/sysinfo.zig");
const render = @import("../ui/render.zig");
const layout = @import("../ui/layout.zig");
const term = @import("../ui/term.zig");
const spinner = @import("../ui/spinner.zig");
const Screen = @import("../ui/screen.zig").Screen;
const ScreenLogWriter = @import("../ui/screen.zig").LogWriter;
const Config = @import("../model/config.zig").Config;
const Linenoise = @import("../editor/linenoise.zig").Linenoise;
const Message = openai.Message;
const ToolCallData = openai.ToolCallData;
// ANSI colour codes
const sgr = @import("../ui/style.zig");
const RESET = sgr.RESET;
const BOLD = sgr.BOLD;
const DIM = sgr.DIM;
const CYAN = sgr.CYAN;
const GREEN = sgr.GREEN;
const YELLOW = sgr.YELLOW;
const RED = sgr.RED;
// The instructions a run starts with, and the limits around them, live in
// prompt.zig; the loop below uses them by their own names.
const agent_prompt = @import("prompt.zig");
const subagent = @import("subagent.zig");
const max_continuations = agent_prompt.max_continuations;
const max_empty_continuations = agent_prompt.max_empty_continuations;
const continue_prompt = agent_prompt.continue_prompt;
const restart_prompt = agent_prompt.restart_prompt;
const steering_note = agent_prompt.steering_note;
const CHOICE_PROMPT = agent_prompt.CHOICE_PROMPT;
const error_preview_max = agent_prompt.error_preview_max;
const self_check_prompt = agent_prompt.self_check_prompt;
const deadline_prompt = agent_prompt.deadline_prompt;
const subagent_deadline_grace_seconds = agent_prompt.subagent_deadline_grace_seconds;
/// How long the waiting caller sleeps between looks at its own clocks. The
/// same order as the supervisor's own poll: these are status checks, not work.
const subagent_poll_ms: i64 = 100;
const main_omitted = agent_prompt.main_omitted;
const buildSystemPrompt = agent_prompt.buildSystemPrompt;
const buildSubagentPrompt = agent_prompt.buildSubagentPrompt;
const subagent_omitted = agent_prompt.subagent_omitted;
/// The lines a terminal sees of one tool result: the status on the first line
/// under the call — `✓`, `✗`, and how the call ended where the result says
/// so — then the result on the line after it, at the column where that status
/// line's own text would have started. A result that printed nothing is its
/// status line, not a status and a blank line beneath it.
fn writeResultPreview(w: *std.Io.Writer, body: []const u8, status: tools.ToolResult) std.Io.Writer.Error!void {
try w.writeAll(if (status.is_error) RED ++ layout.indent ++ "✗" else DIM ++ layout.indent ++ "✓");
// The way the call ended belongs on the status line, next to the glyph that
// already says whether it succeeded: a timeout, a killed program and a
// failed one all read as `✗`, and how it ended is the part nobody can guess.
if (status.timed_out) {
try w.writeAll(" timed out");
} else if (status.exit_code) |code| {
try w.print(" exit {d}", .{code});
} else if (status.termination) |termination| {
try w.print(" {s}", .{termination});
}
if (body.len > 0) {
try w.writeByte('\n');
try layout.writeBlock(w, body, layout.after_glyph, layout.after_glyph);
}
try w.writeAll("\n" ++ RESET);
}
pub const Agent = struct {
interrupted: std.atomic.Value(bool) = .init(false),
allocator: std.mem.Allocator,
io: std.Io,
client: openai.Client,
history: std.ArrayList(Message),
/// The terminal ask_user and the choice menus read from.
linenoise: *Linenoise,
form_context: ?*anyopaque = null,
/// Who puts a form of questions to the user. The full-screen runtime owns
/// the keyboard, so it presents the form instead of the terminal below.
form_callback: ?*const fn (?*anyopaque, []menu.Slot) anyerror!menu.Replies = null,
/// Which search programs the machine has. Decided once, in `init`, for the
/// same reason as `render_markdown`: a search should not have to ask the
/// filesystem a question whose answer cannot change while the agent runs.
search: tools.SearchBackends,
tool_env: *const std.process.Environ.Map,
session_path: ?[]u8,
session_id: ?[]u8 = null,
child_record: ?@import("../state/session.zig").Child = null,
/// The working directory commands run in, named in the system prompt.
workspace: [:0]u8,
/// What machine this run is on: the OS and its version, the kernel, the
/// architecture, the CPUs and the memory, read once in `init` and named in
/// the system prompt. A sub-agent inherits it from the agent that called
/// it, which works on the same machine.
host: sysinfo.Info,
/// The private scratch directory this run owns, named in the system prompt.
/// Created once, at startup, so concurrent agents never share one path and
/// the model never has to ask for a place to work. Not a sandbox, and not
/// durable: a new session empties it and the process removes it on exit.
scratch: scratch_mod.Scratch,
/// Durable notes loaded at startup and updated by the memory_save tool.
memory: memory_mod.Memory,
/// The checklist of the work in progress. It lives in memory, is changed by
/// the plan tool and `/plan`, and is saved with the session rather than in
/// a file of its own. Named in the system prompt, which is rebuilt whenever
/// it changes rather than fixed at startup.
plan: plan_mod.Plan,
/// Whether to render the model's markdown for a terminal. Decided once, in
/// `init`, so the answer path never has to ask the operating system.
render_markdown: bool,
/// Whether the progress line for a wait may be animated. Decided once, in
/// `init`, next to `render_markdown` and by the same test — a terminal that
/// cannot do line editing is no place for a carriage return and an erase,
/// and neither is one where stdout is a file or a pager: the animation
/// takes a line of the terminal, and it must be the only writer to it.
animate_progress: bool,
terminal_title: term.Title,
/// The settings this agent was built from, borrowed: the agent that owns
/// them outlives every agent started from it. A sub-agent starts from the
/// same provider, model and key as the one that called it.
config: *const Config,
/// Whether this agent is the one on the terminal, or one a tool call
/// started. A sub-agent has no terminal or plan; durable parents give it a child session.
role: Role = .main,
/// The agent that started this one. Its interrupt flag is checked too, so
/// Esc stops the whole tree rather than the outer turn alone.
parent: ?*Agent = null,
/// Where a sub-agent's answer is collected instead of printed. Null for the
/// agent on the terminal, which has a user to answer.
capture: ?*std.ArrayList(u8) = null,
/// Where the report of this turn starts in `capture`. The commentary that
/// precedes a round of tool calls is not part of it: only the reply that
/// stands on the finished work is.
capture_mark: usize = 0,
/// What this sub-agent shares with its caller: the self-check it is asked
/// for, the deadline it must meet. Null for the agent on the terminal, which
/// has nobody to check in with.
supervisor: ?*subagent.Supervisor = null,
/// The sub-agents this agent started and has not closed. A run that has
/// reported back is paused, not finished: it stays here until the model
/// resumes or stops it, and `deinit` closes whatever is left over.
runs: std.ArrayList(*Run) = .empty,
run_counter: usize = 0,
/// The task the model last announced, named in the terminal title. It is
/// kept across turns on purpose: a follow-up that announces no task of its
/// own still belongs to the work the title names, and dropping it at the
/// next prompt would leave the title with nothing to show.
current_task: []const u8 = "",
query_started: ?std.Io.Timestamp = null,
progress_prompt: ?[]const u8 = null,
/// The terminal's part in the tool call being answered. It is filled in by
/// the dispatch hooks below, which is where the host UI's work for a call
/// happens, and read back by whoever previews the result.
tool_ui: ToolUi,
/// Lines the user typed while this task was running. They are not a new
/// task: the worker drains them at its next request boundary and sends
/// them to the model inside the work in progress. The terminal thread
/// appends and the worker swaps the whole list out, so the mutex only
/// ever guards that hand-over.
inbox: std.ArrayList([]u8) = .empty,
inbox_mutex: std.Io.Mutex = .init,
/// Where the conversation is drawn when the interactive session owns the
/// screen. Null for a single query: answers then go straight to stdout, so
/// `zagent "q" > notes.md` stays clean.
screen: ?*Screen = null,
/// What the model is thinking while it thinks it. The reasoning is shown in
/// a panel above the prompt; only its duration stays in the status bar.
thinking: Thinking = .{},
/// The MCP servers and the tools they brought. Borrowed rather than owned:
/// whoever started the agent outlives it, and the agent only reads this and
/// calls through it.
mcp_registry: *mcp.Registry,
/// Where a `--debug` run records what this agent did. Null otherwise, and
/// borrowed when set: the run that opened the trace outlives the agent and
/// renders the report from it.
trace: ?*trace_mod.Recorder = null,
/// Who this agent is in the record. The agent on the terminal is "main";
/// each sub-agent is named after the run that started it.
trace_agent: []const u8 = "main",
/// The name above when this agent had to make one, freed with it.
trace_agent_owned: ?[]u8 = null,
/// Which request of the turn is in flight, numbered from one.
trace_iteration: usize = 0,
pub const Role = enum {
/// The agent a person talks to: it owns the terminal, the session and
/// the plan.
main,
/// An agent a tool call started for one task. It reports back through
/// its caller instead of printing, with a child session when the parent is durable.
subagent,
};
const InitOptions = struct {
role: Role = .main,
/// The agent that starts this one, for a sub-agent. It lends the
/// working directory, the search programs and the interrupt flag, and
/// it must outlive the agent it starts.
parent: ?*Agent = null,
/// Where a sub-agent's answer goes.
capture: ?*std.ArrayList(u8) = null,
/// What this child shares with its caller. The run that starts the
/// child owns it and outlives the child.
supervisor: ?*subagent.Supervisor = null,
};
pub fn init(
allocator: std.mem.Allocator,
io: std.Io,
config: *const Config,
linenoise: *Linenoise,
env: *const std.process.Environ.Map,
mcp_registry: *mcp.Registry,
) !Agent {
return initWith(allocator, io, config, linenoise, env, mcp_registry, .{});
}
fn initWith(
allocator: std.mem.Allocator,
io: std.Io,
config: *const Config,
linenoise: *Linenoise,
env: *const std.process.Environ.Map,
mcp_registry: *mcp.Registry,
options: InitOptions,
) !Agent {
var history: std.ArrayList(Message) = .empty;
errdefer history.deinit(allocator);
var memory = try memory_mod.Memory.init(allocator, io, env);
errdefer memory.deinit();
// An empty plan: this process has no session yet, and whichever one
// `startSession` opens brings its own checklist with it.
var plan = plan_mod.Plan.init(allocator);
errdefer plan.deinit();
// A sub-agent works on the same machine as the agent that called it, so
// it is told about the same search programs rather than looking again.
const parent = options.parent;
const search = if (parent) |p| p.search else tools.detectSearchBackends(io, env);
var client = openai.Client.init(allocator, io, config.*);
client.search = search;
// Each role is described by the few tools it does not get: the caller
// has no report to hand in, and a sub-agent has neither the call that
// started it nor the one that stops it.
client.builtin_omit = switch (options.role) {
.main => &main_omitted,
.subagent => &subagent_omitted,
};
// A test transport is the one thing a sub-agent inherits that is not
// settings: the loop is driven without a socket, so the requests the
// sub-agent makes are scripted by the same test.
if (parent) |p| client.transport = p.client.transport;
// A debug run writes the whole tree into one file: a sub-agent records
// into the trace its caller holds, under its own name.
if (parent) |p| client.trace = p.client.trace;
const workspace: [:0]u8 = if (parent) |p|
try allocator.dupeSentinel(u8, p.workspace, 0)
else
try std.Io.Dir.cwd().realPathFileAlloc(io, ".", allocator);
errdefer allocator.free(workspace);
// The machine, read once: like the search programs above, its answer
// cannot change while the process runs, and a sub-agent works on the
// same one, so it inherits the parent's facts instead of asking again.
var host = if (parent) |p| try p.host.clone(allocator) else try sysinfo.Info.read(allocator, io);
errdefer host.deinit(allocator);
var scratch = try scratch_mod.Scratch.init(io, allocator, env);
errdefer scratch.deinit(allocator);
const system_content = switch (options.role) {
.main => try buildSystemPrompt(allocator, mcp_registry, memory.enabled, search, &host, workspace, scratch.path),
.subagent => try buildSubagentPrompt(allocator, mcp_registry, memory.enabled, search, &host, workspace, scratch.path),
};
errdefer allocator.free(system_content);
try history.append(allocator, .{
.role = "system",
.content = system_content,
.reasoning_content = null,
.tool_calls = null,
.tool_call_id = null,
});
// Only the agent a person talks to has a terminal to write on, a
// session to record, and a plan of its own. A sub-agent reports back
// through the tool result and leaves all three to its caller.
const interactive = options.role == .main;
return .{
.allocator = allocator,
.io = io,
.client = client,
.history = history,
.linenoise = linenoise,
.search = search,
.tool_env = env,
.host = host,
.tool_ui = .{ .spinner = spinner.Spinner.disabled(io), .label = .init(allocator) },
.session_path = null,
.workspace = workspace,
.scratch = scratch,
.memory = memory,
.plan = plan,
.config = config,
.role = options.role,
.parent = options.parent,
.capture = options.capture,
.supervisor = options.supervisor,
// The check is on stdout rather than on `linenoise.is_tty`, which
// describes stdin: `zagent "q" < file` with a terminal on stdout
// should still render, and `zagent "q" | less` must not.
.render_markdown = interactive and linenoise.term_supported and
(std.Io.File.stdout().isTty(io) catch false),
// stderr as well as stdout, unlike the renderer: the animation is
// written to stderr, and a run whose stdout is a file or a pager is
// one where the terminal belongs to something else.
.animate_progress = interactive and linenoise.term_supported and
(std.Io.File.stdout().isTty(io) catch false) and
(std.Io.File.stderr().isTty(io) catch false),
.mcp_registry = mcp_registry,
.trace = if (parent) |p| p.trace else null,
.terminal_title = term.Title.init(io, interactive and linenoise.term_supported),
};
}
pub fn deinit(self: *Agent) void {
// A sub-agent still running would keep its task alive for the life of
// the process: the caller that was watching it is gone.
// Whatever is still open is closed here, before anything it borrows.
self.closeRuns();
self.stopCallProgress();
self.tool_ui.label.deinit();
self.runs.deinit(self.allocator);
if (self.current_task.len > 0) self.allocator.free(self.current_task);
if (self.trace_agent_owned) |label| self.allocator.free(label);
for (self.inbox.items) |line| self.allocator.free(line);
self.inbox.deinit(self.allocator);
self.host.deinit(self.allocator);
self.scratch.deinit(self.allocator);
self.allocator.free(self.workspace);
self.terminal_title.deinit();
for (self.history.items) |msg| msg.deinit(self.allocator);
self.history.deinit(self.allocator);
self.client.deinit();
self.memory.deinit();
self.plan.deinit();
if (self.session_path) |path| self.allocator.free(path);
if (self.session_id) |id| self.allocator.free(id);
}
/// Draw the conversation on `screen` instead of on the files the progress
/// lines normally use.
pub fn attachScreen(self: *Agent, screen: ?*Screen) void {
self.screen = screen;
}
/// Record this agent's steps from here on. Called once the session exists,
/// because the trace is named after it, and by `/debug` when a run that
/// started without one turns tracing on mid-session.
pub fn attachTrace(self: *Agent, trace: ?*trace_mod.Recorder) void {
self.trace = trace;
self.client.trace = trace;
self.client.trace_ctx = self.traceCtx();
const opened = trace orelse return;
// Only the agent on the terminal describes the run: a sub-agent's
// events are steps inside it, not another run.
if (self.role != .main) return;
opened.run(.{
.session = self.session_id orelse "",
.workspace = self.workspace,
.scratch = self.scratch.path,
.model = self.config.model,
.provider = if (self.config.provider) |selected| selected.name() else "",
.base_url = self.config.base_url,
.max_tokens = self.config.max_tokens,
});
}
/// Which agent and which request a step belongs to, as the trace records it.
fn traceCtx(self: *Agent) trace_mod.Ctx {
return .{ .agent = self.trace_agent, .iteration = self.trace_iteration };
}
/// One status or answer line: into the conversation when a screen owns it,
/// and to `file` otherwise. The file still matters for a redirected run,
/// where stdout belongs to another program and stderr carries progress.
fn emit(self: *Agent, file: std.Io.File, comptime fmt: []const u8, args: anytype) !void {
if (self.capture) |_| {
// A sub-agent has no terminal. Text meant for the conversation is
// kept for its report; its progress is nobody's business but its
// own, and the caller prints a line for the call already.
if (file.handle != std.Io.File.stdout().handle) return;
const message = try std.fmt.allocPrint(self.allocator, fmt, args);
defer self.allocator.free(message);
return self.writeLogOrStdout(message);
}
if (self.screen) |screen| {
if (screen.isActive()) {
const message = try std.fmt.allocPrint(self.allocator, fmt, args);
defer self.allocator.free(message);
return screen.writeLog(message);
}
}
try printFmt(file, self.io, self.allocator, fmt, args);
}
/// Clear conversation history (keeps the system prompt).
pub fn clearHistory(self: *Agent) void {
// The ids of the runs this conversation started do not survive it. A
// paused child would sit there until the process ended, unreachable
// from a conversation that no longer names it.
self.closeRuns();
for (self.history.items[1..]) |msg| msg.deinit(self.allocator);
self.history.shrinkRetainingCapacity(1);
self.checkpoint() catch {};
}
/// Switch only after the new snapshot has been created or fully validated.
pub fn startSession(self: *Agent, resume_id: ?[]const u8) !void {
const session = @import("../state/session.zig");
const id = if (resume_id) |value| try self.allocator.dupe(u8, value) else try session.newId(self.io, self.allocator);
errdefer self.allocator.free(id);
try session.validateId(id);
const relative = try std.fmt.allocPrint(self.allocator, "sessions/{s}.json", .{id});
defer self.allocator.free(relative);
const path = try @import("../state/workspace.zig").filePath(self.allocator, self.io, self.tool_env, relative);
errdefer self.allocator.free(path);
var loaded: session.Loaded = undefined;
if (resume_id != null) {
try std.Io.Dir.cwd().access(self.io, path, .{});
loaded = try session.load(self.io, self.allocator, path);
} else {
// A new session starts without a plan: the checklist belongs to
// the session the work was done in, not to this process.
loaded = .{ .messages = .empty, .plan = plan_mod.Plan.init(self.allocator) };
session.save(self.io, self.allocator, path, &.{}, &loaded.plan) catch |err| {
loaded.deinit(self.allocator);
return err;
};
}
defer loaded.deinit(self.allocator);
try self.history.ensureTotalCapacity(self.allocator, loaded.messages.items.len + 1);
self.closeRuns();
// The system prompt names this process's working and scratch
// directories, so switching sessions replaces the messages only.
for (self.history.items[1..]) |message| message.deinit(self.allocator);
self.history.shrinkRetainingCapacity(1);
self.history.appendSliceAssumeCapacity(loaded.messages.items);
loaded.messages.clearRetainingCapacity();
// The plan of the session just opened replaces this process's; the old
// one goes into `loaded` and is freed with it.
std.mem.swap(plan_mod.Plan, &self.plan, &loaded.plan);
if (self.session_path) |old| self.allocator.free(old);
if (self.session_id) |old| self.allocator.free(old);
self.session_path = path;
self.session_id = id;
self.client.resetTokenCounters();
// Another session is another piece of work: the task the old one
// announced says nothing about this one.
self.forgetTask();
}
/// Drop the title's task label, leaving the activity to speak for itself.
fn forgetTask(self: *Agent) void {
if (self.current_task.len > 0) self.allocator.free(self.current_task);
self.current_task = "";
self.terminal_title.update("ready", "");
}
/// Restore the visible conversation from the saved messages, without
/// dispatching tools or changing the model history/checkpoint.
pub fn replayHistory(self: *Agent) !void {
if (self.history.items.len <= 1) return;
try self.emit(std.Io.File.stdout(), DIM ++ " ── Restored session history ──\n" ++ RESET, .{});
for (self.history.items[1..]) |message| {
if (std.mem.eql(u8, message.role, "user")) {
if (message.content) |content| {
var aw: std.Io.Writer.Allocating = .init(self.allocator);
defer aw.deinit();
try aw.writer.writeAll("\n" ++ BOLD ++ GREEN ++ "❯" ++ RESET ++ " ");
try sanitize.writeSanitized(&aw.writer, content);
try aw.writer.writeByte('\n');
try self.writeLogOrStdout(aw.written());
}
} else if (std.mem.eql(u8, message.role, "assistant")) {
if (message.content) |content| {
if (content.len > 0) {
try self.answerHeader();
try self.writeAnswer(content);
try self.answerTrailer();
}
}
if (message.tool_calls) |calls| {
for (calls) |call| try self.announceToolCall(call.name, call.arguments);
}
} else if (std.mem.eql(u8, message.role, "tool")) {
if (message.tool_result) |result| {
try self.previewToolResult(result.output, result, false);
}
}
}
try self.emit(std.Io.File.stdout(), DIM ++ " ── End of restored history ──\n\n" ++ RESET, .{});
}
fn checkpoint(self: *Agent) !void {
if (self.session_path) |path| try @import("../state/session.zig").saveChild(self.io, self.allocator, path, self.history.items[1..], &self.plan, self.child_record);
}
/// `/memory`: list what is saved, newest last.
pub fn listMemory(self: *Agent) !void {
var aw: std.Io.Writer.Allocating = .init(self.allocator);
defer aw.deinit();
try self.memory.writeList(&aw.writer);
try self.writeBlock(aw.written());
}
/// `/remember <text>`: save a note by hand, as the model's memory_save tool
/// does, and make it part of this session's system prompt.
pub fn rememberCommand(self: *Agent, note: []const u8) !void {
if (!self.memory.enabled) {
try self.emit(std.Io.File.stderr(), DIM ++ " memory is disabled\n" ++ RESET, .{});
return;
}
if (note.len == 0) {
try self.emit(std.Io.File.stderr(), DIM ++ " usage: /remember <text>\n" ++ RESET, .{});
return;
}
const added = self.memory.add(note) catch |err| {
try self.emit(std.Io.File.stderr(), RED ++ " ✗ could not remember: {s}\n" ++ RESET, .{@errorName(err)});
return;
};
if (!added) {
try self.emit(std.Io.File.stderr(), DIM ++ " already remembered\n" ++ RESET, .{});
return;
}
self.memory.save() catch |err| {
try self.emit(std.Io.File.stderr(), DIM ++ " ⚠ memory could not be saved: {s}\n" ++ RESET, .{@errorName(err)});
return;
};
try self.emit(std.Io.File.stderr(), DIM ++ " ✓ remembered: {s}\n" ++ RESET, .{note});
}
/// `/forget <n|all>`: drop one numbered note, or every note.
pub fn forgetCommand(self: *Agent, argument: []const u8) !void {
if (!self.memory.enabled) {
try self.emit(std.Io.File.stderr(), DIM ++ " memory is disabled\n" ++ RESET, .{});
return;
}
const arg = std.mem.trim(u8, argument, " \t");
if (arg.len == 0) {
try self.emit(std.Io.File.stderr(), DIM ++ " usage: /forget <number> | /forget all\n" ++ RESET, .{});
return;
}
if (std.ascii.eqlIgnoreCase(arg, "all")) {
self.memory.clear();
self.memory.save() catch |err| {
try self.emit(std.Io.File.stderr(), DIM ++ " ⚠ memory could not be saved: {s}\n" ++ RESET, .{@errorName(err)});
return;
};
try self.emit(std.Io.File.stderr(), DIM ++ " all memories forgotten\n" ++ RESET, .{});
return;
}
const number = std.fmt.parseInt(usize, arg, 10) catch {
try self.emit(std.Io.File.stderr(), DIM ++ " usage: /forget <number> | /forget all\n" ++ RESET, .{});
return;
};
if (number == 0 or !self.memory.remove(number - 1)) {
try self.emit(std.Io.File.stderr(), DIM ++ " no memory number {d} (see /memory)\n" ++ RESET, .{number});
return;
}
self.memory.save() catch |err| {
try self.emit(std.Io.File.stderr(), DIM ++ " ⚠ memory could not be saved: {s}\n" ++ RESET, .{@errorName(err)});
return;
};
try self.emit(std.Io.File.stderr(), DIM ++ " ✓ forgot memory {d}\n" ++ RESET, .{number});
}
/// `/plan`: show the checklist, or `/plan clear` to drop it.
pub fn planCommand(self: *Agent, argument: []const u8) !void {
const arg = std.mem.trim(u8, argument, " \t");
if (arg.len == 0) {
var aw: std.Io.Writer.Allocating = .init(self.allocator);
defer aw.deinit();
try self.plan.writeChecklist(&aw.writer);
return self.writeBlock(aw.written());
}
if (!std.ascii.eqlIgnoreCase(arg, "clear")) {
try self.emit(std.Io.File.stderr(), DIM ++ " usage: /plan [clear]\n" ++ RESET, .{});
return;
}
if (self.plan.steps.items.len == 0) {
try self.emit(std.Io.File.stderr(), DIM ++ " no plan to clear\n" ++ RESET, .{});
return;
}
self.plan.clear();
// The session snapshot is where the plan lives once this process is
// gone, so a cleared plan is saved before the command reports success.
self.checkpoint() catch |err| {
try self.emit(std.Io.File.stderr(), RED ++ " ✗ plan cleared, but the session was not saved: {s}\n" ++ RESET, .{@errorName(err)});
return;
};
try self.emit(std.Io.File.stderr(), DIM ++ " ✓ plan cleared\n" ++ RESET, .{});
}
/// Settle unanswered calls after an interrupted query.
/// Called only after the worker has joined. Preserve completed tool results
/// and explicitly settle any calls that cancellation left unanswered.
pub fn finishInterruption(self: *Agent) !void {
var index = self.history.items.len;
while (index > 0) {
index -= 1;
const calls = self.history.items[index].tool_calls orelse continue;
for (calls) |call| {
var answered = false;
for (self.history.items[index + 1 ..]) |message| {
if (message.tool_call_id) |id| {
if (std.mem.eql(u8, id, call.id)) answered = true;
}
}
if (answered) continue;
const content = try self.allocator.dupe(u8, "Task interrupted by user. Execution may have partially completed; inspect actual state before retrying.");
errdefer self.allocator.free(content);
const id = try self.allocator.dupe(u8, call.id);
errdefer self.allocator.free(id);
try self.history.append(self.allocator, .{
.role = "tool",
.content = null,
.tool_result = .{ .output = content, .is_error = true },
.tool_call_id = id,
.reasoning_content = null,
.tool_calls = null,
});
}
break;
}
// The work was stopped, so nothing of it stays on the screen waiting
// out the panel's delay.
self.thinking.close(self);
self.terminal_title.update("ready", self.current_task);
try self.checkpoint();
}
fn checkInterrupted(self: *Agent) !void {
if (self.interrupted.load(.acquire)) return error.Canceled;
// Esc belongs to the whole tree: the user stopped the work, not the
// outer turn alone, and a sub-agent that kept going would edit files
// after a task was called off.
if (self.parent) |parent| {
if (parent.interrupted.load(.acquire)) return error.Canceled;
}
}
/// Hand a line the user typed during a running task to that task. The
/// worker sends it with its next request, so the instruction reaches the
/// model now instead of queueing behind the answer it belongs to.
pub fn steer(self: *Agent, line: []const u8) !void {
const owned = try self.allocator.dupe(u8, line);
errdefer self.allocator.free(owned);
// Appended under the lock so a drain cannot miss the allocation.
self.inbox_mutex.lockUncancelable(self.io);
defer self.inbox_mutex.unlock(self.io);
try self.inbox.append(self.allocator, owned);
}
/// Move the lines typed during the task into `into`, for a caller with no
/// request left to send them with. Ownership of the lines passes over.
pub fn takeSteering(self: *Agent, into: *std.ArrayList([]u8)) !void {
var lines = self.claimInbox();
defer lines.deinit(self.allocator);
var moved: usize = 0;
errdefer for (lines.items[moved..]) |line| self.allocator.free(line);
for (lines.items) |line| {
try into.append(self.allocator, line);
moved += 1;
}
}
/// Throw away guidance no request will carry: Esc drops it with the task.
pub fn clearSteering(self: *Agent) void {
var lines = self.claimInbox();
defer lines.deinit(self.allocator);
for (lines.items) |line| self.allocator.free(line);
}
/// Take the whole inbox, leaving an empty one behind. The list that comes
/// back is the caller's to free.
fn claimInbox(self: *Agent) std.ArrayList([]u8) {
self.inbox_mutex.lockUncancelable(self.io);
defer self.inbox_mutex.unlock(self.io);
const lines = self.inbox;
self.inbox = .empty;
return lines;
}
/// Put what the user typed during the task into the conversation, so the
/// next request carries it. Returns false when nothing arrived.
///
/// Holding it back until a request boundary is the point: a request in
/// flight cannot take new input, and a line that cut it short would throw
/// away work the user asked for. The answer that is already streaming
/// finishes, and the guidance redirects the request after it.
fn injectSteering(self: *Agent) !bool {
var lines = self.claimInbox();
defer {
for (lines.items) |line| self.allocator.free(line);
lines.deinit(self.allocator);
}
if (lines.items.len == 0) return false;
var aw: std.Io.Writer.Allocating = .init(self.allocator);
defer aw.deinit();
try aw.writer.writeAll(steering_note);
try aw.writer.writeAll("\n\n");
for (lines.items, 0..) |line, index| {
if (index > 0) try aw.writer.writeByte('\n');
try sanitize.writeSanitized(&aw.writer, line);
}
try self.appendUserMessage(aw.written());
try self.emit(std.Io.File.stderr(), DIM ++ " ↳ guidance from the terminal added to this task\n" ++ RESET, .{});
if (self.trace) |trace| trace.note(self.traceCtx(), "info", "guidance typed while the task ran was added to this request");
try self.checkpoint();
return true;
}
pub fn processQuery(self: *Agent, query: []const u8) !void {
self.query_started = std.Io.Timestamp.now(self.io, .awake);
defer self.query_started = null;
self.client.resetTokenCounters();
if (self.screen) |screen| screen.clearThinkingSummary();
// Raw user input is never a terminal title, and the task last
// announced stays until the model announces a new one: the title
// describes the work in progress, not the line that started it.
self.terminal_title.update("thinking…", self.current_task);
self.processQueryInner(query) catch |err| {
self.terminal_title.update("error", self.current_task);
return err;
};
self.terminal_title.update("ready", self.current_task);
const elapsed_ms = self.query_started.?.untilNow(self.io, .awake).toMilliseconds();
const counts = self.client.tokenCounts();
try self.emit(std.Io.File.stderr(), DIM ++ " Worked for {d}.{d}s · in {d} (cached {d}, {s}; cache reports {d}/{d}) · out {d} (reasoning {d}) · total {d} tokens · usage {d}/{d} calls\n" ++ RESET, .{
@divTrunc(elapsed_ms, 1000),
@divTrunc(@mod(elapsed_ms, 1000), 100),
counts.input,
counts.cached,
if (counts.cache_usage_reports == 0) "unknown" else if (counts.cache_usage_reports < counts.requests) "partial" else "reported",
counts.cache_usage_reports,
counts.requests,
counts.output,
counts.reasoning,
counts.total,
counts.usage_reports,
counts.requests,
});
try self.checkInterrupted();
// The final answer settles the turn; its text is not a status protocol.
try self.emit(std.Io.File.stderr(), BOLD ++ GREEN ++ " ✓ Turn finished" ++ RESET ++ "\n", .{});
}
fn progressOptions(self: *Agent) spinner.Options {
return .{
.enabled = self.animate_progress,
.screen = if (self.form_callback != null) self.screen else null,
.started = self.query_started,
.prompt = self.progress_prompt,
.first_frame_delay_ms = 0,
.in_tokens = &self.client.input_tokens,
.out_tokens = &self.client.output_tokens,
};
}
/// Start one sub-agent and the task that runs it. The run owns the child,
/// what the two sides share, and the buffer the child answers into; the
/// caller of `subagent` only ever holds it by its id.
///
/// `title` is the summary the terminal names the run with, and may be
/// empty: a run without one is named by its task on the lines that would
/// have shown it.
pub fn startRun(self: *Agent, task: []const u8, context: []const u8, title: []const u8, self_check_seconds: u32) !*Run {
return self.createRun(task, context, title, self_check_seconds, null);
}
pub fn restoreRun(self: *Agent, id: []const u8, self_check_seconds: u32) !*Run {
if (id.len < 2 or id[0] != 's') return error.InvalidSessionId;
_ = try std.fmt.parseInt(usize, id[1..], 10);
return self.createRun("", "", "", self_check_seconds, id);
}
fn createRun(self: *Agent, task: []const u8, context: []const u8, title: []const u8, self_check_seconds: u32, restore_id: ?[]const u8) !*Run {
const session = @import("../state/session.zig");
const run = try self.allocator.create(Run);
errdefer self.allocator.destroy(run);
// Reserve ids against durable children, including completed ones.
while (true) {
self.run_counter += 1;
const parent_path = self.session_path orelse break;
const candidate = try std.fmt.allocPrint(self.allocator, "{s}.s{d}.json", .{ parent_path, self.run_counter });
defer self.allocator.free(candidate);
std.Io.Dir.cwd().access(self.io, candidate, .{}) catch |err| switch (err) {
error.FileNotFound => break,
else => return err,
};
}
const id = if (restore_id) |value| try self.allocator.dupe(u8, value) else try std.fmt.allocPrint(self.allocator, "s{d}", .{self.run_counter});
errdefer self.allocator.free(id);
const owned_title = try self.allocator.dupe(u8, title);
errdefer self.allocator.free(run.title);
run.* = .{
.id = id,
.title = owned_title,
.child = undefined,
.supervisor = subagent.Supervisor.init(self.io, self.allocator),
.started = std.Io.Timestamp.now(self.io, .awake),
};
errdefer run.supervisor.deinit();
const child = try self.allocator.create(Agent);
errdefer self.allocator.destroy(child);
child.* = try Agent.initWith(self.allocator, self.io, self.config, self.linenoise, self.tool_env, self.mcp_registry, .{
.role = .subagent,
.parent = self,
.capture = &run.capture,
.supervisor = &run.supervisor,
});
errdefer child.deinit();
// Named in the record after the run the caller watches: two sub-agents
// interleave their steps in one trace, and the name is how a reader
// tells which one a request belongs to. Only a debug run pays for it.
if (child.trace != null) {
child.trace_agent_owned = try std.fmt.allocPrint(self.allocator, "subagent {s}", .{run.id});
child.trace_agent = child.trace_agent_owned.?;
}
run.child = child;
if (self.session_path) |parent_path| {
child.session_path = try std.fmt.allocPrint(self.allocator, "{s}.{s}.json", .{ parent_path, id });
child.child_record = .{ .parent = self.session_id orelse "", .id = id, .title = run.title };
}
var continuation: []const u8 = task;
if (restore_id != null) {
const path = child.session_path orelse return error.NoSession;
try std.Io.Dir.cwd().access(self.io, path, .{});
var loaded = try session.load(self.io, self.allocator, path);
defer loaded.deinit(self.allocator);
const record = loaded.child orelse return error.InvalidSessionId;
continuation = switch (record.status) {
.completed => "The caller explicitly requested continuation of this completed task. Continue from saved history; do not repeat already completed work unless needed for the follow-up.",
.failed => "The caller requested continuation of this failed task. Review the saved failure and history before proceeding. Unconfirmed tool outcomes are unknown; inspect before retrying side effects.",
.running, .interrupted => "The process restarted: this task was interrupted. Continue from saved history. Unconfirmed tool outcomes are unknown; inspect before retrying any side effects.",
};
if (!std.mem.eql(u8, record.parent, self.session_id orelse "") or !std.mem.eql(u8, record.id, id)) return error.InvalidSessionId;
const restored_title = try self.allocator.dupe(u8, record.title);
self.allocator.free(run.title);
run.title = restored_title;
child.child_record.?.title = run.title;
try child.history.appendSlice(self.allocator, loaded.messages.items);
loaded.messages.clearRetainingCapacity();
}
// The two ways a run stops for a reason other than its caller's
// deadline: this process asking for the task to stop, and the child
// itself being told to.
run.supervisor.canceled = &child.interrupted;
run.supervisor.caller_canceled = &self.interrupted;
var prompt: std.ArrayList(u8) = .empty;
errdefer prompt.deinit(self.allocator);
try prompt.appendSlice(self.allocator, continuation);
if (context.len > 0) {
try prompt.appendSlice(self.allocator, "\n\nWhat the agent that asked you already knows:\n");
try prompt.appendSlice(self.allocator, context);
}
const owned_prompt = try prompt.toOwnedSlice(self.allocator);
// Taken out of the list above, so it owns itself until the task does.
errdefer self.allocator.free(owned_prompt);
// A self-check of zero means the child's first boundary: asking before
// the task starts is what makes that the first request rather than
// whichever one the child happens to reach next.
if (self_check_seconds == 0) run.supervisor.requestProgress();
// In the list before the task starts: once the child is running, only
// `closeRun` may free what it is using, and a failure below must not
// leave a live task pointing at freed memory.
try self.runs.append(self.allocator, run);
run.future = self.io.concurrent(childTurn, .{ child, &run.supervisor, owned_prompt }) catch |err| {
_ = self.runs.pop();
return err;
};
return run;
}
/// Watch the run until it ends, on the two clocks its caller set, and make
/// its final report the tool result.
///
/// Every `self_check_seconds` the child is asked for a self-check, and what
/// it answers is printed on the terminal: the model that started the run
/// reads none of it, which is what makes the whole call one wait. At
/// `deadline_seconds` the child is told to stop working and write its final
/// report; the grace after that is for that report, not for more work, and
/// a child that misses it is stopped where it stands.
///
/// A command that is already running is never cut short, because a report
/// that claims a check it did not finish is worse than a report that
/// arrives late.
pub fn waitRun(self: *Agent, run: *Run, self_check_seconds: u32, deadline_seconds: u32) anyerror!tools.ToolResult {
const interval_ms: i64 = @as(i64, @intCast(self_check_seconds)) * std.time.ms_per_s;
const deadline_at = inMs(run.started, @as(i64, @intCast(deadline_seconds)) * std.time.ms_per_s);
var check_at = inMs(run.started, interval_ms);
// Set once the deadline has been passed on to the child: the run is over
// from there, and `cut_at` is when the report it was asked for is given
// up on.
var deadline_sent = false;
var cut_at: ?std.Io.Timestamp = null;
while (true) {
const wake = run.supervisor.wait(nextWake(check_at, deadline_at, cut_at)) catch |err| {
// Esc while the caller was waiting: nobody owns the child any
// more, and a child that kept going would edit files after a
// task was called off.
self.abortRun(run);
return err;
};
switch (wake) {
.progress => |report| {
defer self.allocator.free(report);
try self.showSelfCheck(run, report);
// A self-check the caller asked to be due at once is asked
// for at once: with an interval of zero the child is
// checked at its next boundary, and waiting for the next
// look at the clock would make that the one after it.
if (interval_ms == 0) run.supervisor.requestProgress();
check_at = inMsNow(self.io, @max(interval_ms, subagent_poll_ms));
},
.done => return self.finishRun(run, if (deadline_sent)
"Sub-agent reached its deadline and stopped. Its final report — what is done and what is left undone. Verify it before marking a plan step done:"
else
"Sub-agent report — verify it before marking a plan step done:"),
.failed => |failure| return self.failRun(run, failure),
.timeout => {
const now = std.Io.Timestamp.now(self.io, .awake);
if (cut_at) |cut| {
// The deadline stands until the run ends: a child that
// answered it with more work instead of its report is
// told again at the boundary after that.
run.supervisor.setDeadline();
if (cut.untilNow(self.io, .awake).nanoseconds >= 0) return self.cutRun(run);
continue;
}
if (deadline_at.untilNow(self.io, .awake).nanoseconds >= 0) {
deadline_sent = true;
run.supervisor.setDeadline();
cut_at = inMs(now, @as(i64, subagent_deadline_grace_seconds) * std.time.ms_per_s);
continue;
}
if (check_at.untilNow(self.io, .awake).nanoseconds >= 0) {
// Asked for once: a request the child has not reached a
// boundary for yet is the one it will see, and asking
// again on every poll would only set the same flag.
if (!run.supervisor.progressPending()) run.supervisor.requestProgress();
check_at = inMsNow(self.io, @max(interval_ms, subagent_poll_ms));
}
},
}
}
}
/// Show a sub-agent's self-check on the terminal.
///
/// It is the caller's line and the caller's terminal: the child's own
/// output is captured, so this is the only place its progress is read. The
/// animation the call owns is given the line back for it and taken again
/// afterwards, because a frame drawn over the report would erase it.
fn showSelfCheck(self: *Agent, run: *Run, report: []const u8) !void {
self.takeLine();
defer self.giveLine();
const elapsed_s = @divTrunc(run.started.untilNow(self.io, .awake).toMilliseconds(), std.time.ms_per_s);
var line: std.Io.Writer.Allocating = .init(self.allocator);
defer line.deinit();
try line.writer.print(" ⇢ self-check, {d}m {d}s in · ", .{
@divTrunc(elapsed_s, std.time.s_per_min),
@mod(elapsed_s, std.time.s_per_min),
});
try writeRunTag(&line.writer, run);
// The run carries on by itself: the report is the user's to read, and
// stopping it is theirs too, so the line says how.
try line.writer.writeAll(" · carrying on, Esc stops it\n");
try sanitize.writeSanitized(&line.writer, report);
try line.writer.writeAll("\n");
try self.emit(std.Io.File.stderr(), CYAN ++ "{s}" ++ RESET, .{line.written()});
}
/// Read the answer a run ended on and close it. `heading` says how the run