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
//! Terminal rendering of agent events.
//!
//! Streams the answer as it arrives and narrates tool use around it. Colour is
//! used only when stdout is a terminal, so piped output stays clean.
use mecha_core::agent::AgentEvent;
use mecha_core::message::Usage;
use std::io::{IsTerminal, Write};
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::task::JoinHandle;
#[derive(Clone, Copy, Default)]
pub struct RenderOpts {
/// Show thinking, tool arguments, tool output, and per-turn usage.
pub verbose: bool,
/// Suppress everything except the final answer text.
pub quiet: bool,
}
struct Style {
on: bool,
}
impl Style {
fn new() -> Self {
// NO_COLOR is the de-facto standard opt-out.
Style {
on: std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(),
}
}
fn dim(&self, s: &str) -> String {
if self.on {
format!("\x1b[2m{s}\x1b[0m")
} else {
s.to_string()
}
}
fn cyan(&self, s: &str) -> String {
if self.on {
format!("\x1b[36m{s}\x1b[0m")
} else {
s.to_string()
}
}
fn red(&self, s: &str) -> String {
if self.on {
format!("\x1b[31m{s}\x1b[0m")
} else {
s.to_string()
}
}
}
/// Drain `rx` on a background task, printing as events arrive.
pub fn spawn(mut rx: UnboundedReceiver<AgentEvent>, opts: RenderOpts) -> JoinHandle<()> {
tokio::spawn(async move {
let style = Style::new();
let mut out = std::io::stdout();
// Tool narration has to start on its own line, but only if the model
// was mid-sentence when it called the tool.
let mut mid_line = false;
while let Some(event) = rx.recv().await {
match event {
AgentEvent::TextDelta(t) => {
print!("{t}");
mid_line = !t.ends_with('\n');
let _ = out.flush();
}
AgentEvent::ThinkingDelta(t) if opts.verbose => {
print!("{}", style.dim(&t));
mid_line = !t.ends_with('\n');
let _ = out.flush();
}
AgentEvent::ToolCall { name, input, .. } if !opts.quiet => {
if mid_line {
println!();
mid_line = false;
}
let detail = if opts.verbose {
serde_json::to_string(&input).unwrap_or_default()
} else {
one_line(&input)
};
println!(
"{} {} {}",
style.cyan("→"),
style.cyan(&name),
style.dim(&detail)
);
let _ = out.flush();
}
AgentEvent::ToolResult {
name,
is_error,
content,
..
} if !opts.quiet => {
if is_error {
println!("{} {}", style.red("✗"), style.red(&first_line(&content)));
} else if opts.verbose {
println!("{}", style.dim(&indent(&truncate(&content, 2_000))));
} else {
println!(
"{} {}",
style.dim("✓"),
style.dim(&format!("{name} — {}", size_hint(&content)))
);
}
let _ = out.flush();
}
AgentEvent::ToolDenied { name, reason } if !opts.quiet => {
println!("{} {}", style.red(&format!("✗ {name}")), style.dim(&reason));
}
AgentEvent::Compacted {
messages_before,
messages_after,
..
} if !opts.quiet => {
if mid_line {
println!();
mid_line = false;
}
// Worth saying out loud even when not verbose: the agent's
// memory of the session just changed, and a later answer
// that forgets something has an explanation here.
eprintln!(
"{}",
style.dim(&format!(
"compacted {messages_before} messages into {messages_after} to fit the context"
))
);
}
AgentEvent::TurnUsage(usage) if opts.verbose => {
println!("{}", style.dim(&format!(" {}", format_usage(&usage))));
}
AgentEvent::MessageDelivered { id, from } if !opts.quiet => {
if mid_line {
println!();
mid_line = false;
}
// Out loud even when not verbose, like a compaction: what
// the conversation contains just changed, and a turn that
// suddenly discusses something nobody typed has its
// explanation here.
eprintln!(
"{}",
style.dim(&format!("✉ message {id} from `{from}` delivered"))
);
}
AgentEvent::Done(outcome) => {
if mid_line {
println!();
mid_line = false;
}
if let Some(refusal) = &outcome.refusal {
eprintln!(
"{}",
style.red(&format!(
"refused ({}): {}",
refusal.category.as_deref().unwrap_or("unspecified"),
refusal
.explanation
.as_deref()
.unwrap_or("no explanation given")
))
);
}
if outcome.exhausted {
use mecha_core::agent::StopCause;
// An interruption is the user getting what they asked
// for, so it is reported plainly and without a
// suggested fix. Every other early stop is the harness
// cutting the run short against the user's wishes, and
// is worth telling them how to prevent.
let line = match outcome.stop_cause {
StopCause::Interrupted => {
format!(
"interrupted after {}",
mecha_core::agent::turns_phrase(outcome.turns)
)
}
other => {
let fix = match other {
StopCause::MaxTurns => "raise --max-turns",
StopCause::OutputTokenBudget => "raise --max-output-tokens",
StopCause::CostBudget => "raise --max-cost",
// Not a budget: raising a ceiling won't
// unstick it. Starting over will.
StopCause::Loop => "the task did not survive compaction; retry, or raise the compaction threshold",
// Also not a budget. The per-turn budget
// went to reasoning before the answer
// started, so raising it buys a longer
// runaway; bounding the thinking is what
// helps. See scripts/start-moe-mtp.sh.
StopCause::NoOutput => "the model reasoned past its per-turn budget without answering; cap its thinking (llama-server: --reasoning-budget) or retry",
StopCause::Completed | StopCause::Interrupted => "",
};
format!(
"{} after {} — the answer may be incomplete ({fix})",
other.describe(),
mecha_core::agent::turns_phrase(outcome.turns)
)
}
};
eprintln!("{}", style.red(&line));
}
if opts.verbose {
let cost = outcome
.cost_usd
.map(|c| format!(" · ${c:.4}"))
.unwrap_or_default();
// An interrupted run knows what the prompt cost but not
// what the cut turn produced, so the figure is a floor.
// Printing it bare would read as a measurement.
let at_least = if outcome.usage_complete {
""
} else {
"at least "
};
println!(
"{}",
style.dim(&format!(
" {} turns · {at_least}{}{cost}",
outcome.turns,
format_usage(&outcome.usage)
))
);
}
}
// A subagent's turn, wrapped once per nesting level. Only its
// tool activity is narrated — indented, so it reads as the
// delegation's work and not the parent's — and its prose is
// skipped: the child's conclusions come back through the
// parent's tool result.
AgentEvent::Nested { event, .. } if !opts.quiet => {
let (depth, inner) = unwrap_nested(AgentEvent::Nested {
tool: String::new(),
id: None,
event,
});
let pad = " ".repeat(depth);
match inner {
AgentEvent::ToolCall { name, input, .. } => {
if mid_line {
println!();
mid_line = false;
}
println!(
"{pad}{} {} {}",
style.dim("→"),
style.dim(&name),
style.dim(&one_line(&input))
);
}
AgentEvent::ToolResult {
name,
is_error,
content,
..
} => {
if is_error {
println!(
"{pad}{} {}",
style.red("✗"),
style.red(&first_line(&content))
);
} else {
println!(
"{pad}{} {}",
style.dim("✓"),
style.dim(&format!("{name} — {}", size_hint(&content)))
);
}
}
AgentEvent::ToolDenied { name, reason } => {
println!(
"{pad}{} {}",
style.red(&format!("✗ {name}")),
style.dim(&reason)
);
}
_ => {}
}
let _ = out.flush();
}
// Everything else is only interesting in verbose mode, and is
// already handled by the arms above.
_ => {}
}
}
})
}
pub fn format_usage(u: &Usage) -> String {
let mut s = format!("{} in / {} out", u.total_input(), u.output_tokens);
if u.cache_read_input_tokens > 0 || u.cache_creation_input_tokens > 0 {
s.push_str(&format!(
" (cache {} read / {} write)",
u.cache_read_input_tokens, u.cache_creation_input_tokens
));
}
s
}
/// Peel `Nested` wrappers, counting them. The count is the nesting depth: a
/// child's event is wrapped once, a grandchild's twice.
fn unwrap_nested(mut event: AgentEvent) -> (usize, AgentEvent) {
let mut depth = 0;
while let AgentEvent::Nested { event: inner, .. } = event {
event = *inner;
depth += 1;
}
(depth, event)
}
/// The most informative single argument, for the non-verbose tool line.
fn one_line(input: &serde_json::Value) -> String {
let pick = ["command", "path", "url", "query"]
.iter()
.find_map(|k| input.get(*k).and_then(serde_json::Value::as_str))
.map(str::to_string)
.unwrap_or_else(|| serde_json::to_string(input).unwrap_or_default());
truncate(&pick.replace('\n', " "), 90)
}
fn first_line(s: &str) -> String {
truncate(s.lines().next().unwrap_or(""), 200)
}
fn truncate(s: &str, max: usize) -> String {
if s.chars().count() <= max {
s.to_string()
} else {
format!("{}…", s.chars().take(max).collect::<String>())
}
}
fn indent(s: &str) -> String {
s.lines()
.map(|l| format!(" {l}"))
.collect::<Vec<_>>()
.join("\n")
}
fn size_hint(content: &str) -> String {
let lines = content.lines().count();
if lines <= 1 {
format!("{} bytes", content.len())
} else {
format!("{lines} lines")
}
}