Skip to content

Lightpanda: the headless browser designed for AI and automation

agent: streamline and shorten comments

Adrià Arrufat3baa2726e934
diff --git a/src/agent/Agent.zig b/src/agent/Agent.zig
index ea2e834bb..0f2ba0869 100644
--- a/src/agent/Agent.zig
+++ b/src/agent/Agent.zig
@@ -42,9 +42,8 @@ const string = @import("../string.zig");
const Agent = @This();
-/// Errors raised by Agent.init / listModels where the function has already
-/// printed a human-readable message to stderr. Callers should exit non-zero
-/// without further logging.
+/// Raised by init/listModels after they've printed a user-facing message to
+/// stderr; callers should exit non-zero without logging more.
pub const UserError = error{
MissingApiKey,
MissingProvider,
@@ -94,14 +93,14 @@ const synthesis_prompt =
allocator: std.mem.Allocator,
ai_client: ?zenai.provider.Client,
model_credentials: ?Credentials,
-/// True when the no-LLM state is a persisted preference (a remembered null
-/// provider or a runtime `/provider null`), so `reportSaved` writes
-/// `provider = null`. A transient `--no-llm` run leaves this false so saving
+/// True when the no-LLM state is a persisted preference (remembered null
+/// provider or runtime `/provider null`), so `reportSaved` writes
+/// `provider = null`. A transient `--no-llm` run leaves it false so saving
/// other settings doesn't clobber the remembered provider.
no_llm_persisted: bool,
model_base_url: ?[:0]const u8,
/// Cached chat-model ids for the current provider, backed by
-/// `model_completion_arena` and invalidated on `/provider` switch.
+/// `model_completion_arena`; invalidated on `/provider` switch.
model_completions: ?ModelCompletions,
model_completion_arena: std.heap.ArenaAllocator,
notification: *lp.Notification,
@@ -125,10 +124,9 @@ cancel_requested: std.atomic.Value(bool) = .init(false),
/// mid-request instead of blocking until the model's full response arrives.
http_interrupt: zenai.http.Interrupt = .{},
synthetic_tool_call_id: u32 = 0,
-/// Aggregate Anthropic/OpenAI/Gemini token usage across every model call
-/// this Agent has made. Printed as a structured `$usage ...` line on stderr
-/// at the end of `--task` (one-shot) mode so wrappers can capture
-/// per-task cost.
+/// Aggregate Anthropic/OpenAI/Gemini token usage across every model call.
+/// Printed as a structured `$usage ...` line on stderr at the end of `--task`
+/// (one-shot) mode so wrappers can capture per-task cost.
total_usage: zenai.provider.Usage = .{},
/// Set when the last turn ended in a model refusal (safety stop).
last_turn_refused: bool = false,
@@ -164,31 +162,30 @@ pub fn init(allocator: std.mem.Allocator, app: *App, opts: Config.Agent) !*Agent
const is_one_shot = opts.task != null;
const will_repl = !is_one_shot and opts.script_file == null;
- // Load the remembered selection up front so a saved null provider can flip
- // the REPL into basic mode before resolution. Pure script runs need nothing.
+ // Load remembered selection up front so a saved null provider can flip the
+ // REPL into basic mode before resolution. Pure script runs need nothing.
const remembered: ?settings.Remembered = if (will_repl or is_one_shot) settings.loadRemembered(allocator) else null;
defer if (remembered) |r| std.zon.parse.free(allocator, r);
// A remembered null provider means the user disabled the LLM via
- // `/provider null`; honor it for the interactive REPL only (one-shot --task
- // and script runs always need a model). An explicit --provider overrides it.
+ // `/provider null`; honor it for the REPL only (one-shot --task and script
+ // runs always need a model). An explicit --provider overrides it.
const remembered_no_llm = will_repl and opts.provider == null and
remembered != null and remembered.?.provider == null;
// Basic-mode REPL (no LLM) must be opted into via --no-llm or a remembered
- // null provider. Without it, the REPL accepts natural language and an absent
- // API key would only surface at the first non-slash-command line — too late
- // to be useful. Pure JavaScript script runs stay allowed: no REPL, no LLM.
+ // null provider. Without it the REPL accepts natural language, so an absent
+ // API key would only surface at the first non-slash-command line — too late.
+ // Pure JavaScript script runs stay allowed: no REPL, no LLM.
const requires_llm = is_one_shot or (will_repl and !opts.no_llm and !remembered_no_llm);
- // Skip resolve when no client is wanted — otherwise resolveCredentials
- // prints "No API key detected" for a run that does not need one.
+ // Skip resolve when no client is wanted — else resolveCredentials prints
+ // "No API key detected" for a run that does not need one.
const resolve = !opts.no_llm and requires_llm;
- // Print the banner before provider resolution so it appears before any
- // interactive "Select a provider" prompt. On error paths (missing key /
- // no key detected) resolveCredentials prints its own message and the
- // banner is skipped.
+ // Print the banner before provider resolution so it precedes any
+ // interactive "Select a provider" prompt. On error paths (missing key / no
+ // key detected) resolveCredentials prints its own message; banner skipped.
if (will_repl and (!resolve or settings.wouldResolve(allocator, opts, remembered))) {
welcome.print(resolve);
}
@@ -206,7 +203,7 @@ pub fn init(allocator: std.mem.Allocator, app: *App, opts: Config.Agent) !*Agent
var model = try allocator.dupe(u8, settings.resolveModelName(opts, resolved, remembered));
errdefer allocator.free(model);
- // The REPL skips this network round trip to keep startup snappy; an invalid
+ // The REPL skips this network round trip for snappy startup; an invalid
// model surfaces on the first turn instead.
if (llm) |l| if (!will_repl) {
const remembered_matches = remembered != null and remembered.?.provider == l.provider;
@@ -287,8 +284,8 @@ pub fn init(allocator: std.mem.Allocator, app: *App, opts: Config.Agent) !*Agent
.providers = completionProviders,
.models = completionModels,
};
- // The model-list cache fills lazily on the first `/model` completion so
- // startup never blocks on the network.
+ // The model-list cache fills lazily on the first `/model` completion,
+ // so startup never blocks on the network.
}
return self;
@@ -312,13 +309,13 @@ pub fn deinit(self: *Agent) void {
}
/// Create a fresh browser session and wire its cancel hook back to this agent
-/// so Ctrl-C aborts in-flight page work. Used at startup and by `/reset`.
+/// so Ctrl-C aborts in-flight page work. Startup and `/reset`.
fn startSession(self: *Agent) !void {
self.session = try self.browser.newSession(self.notification);
self.session.cancel_hook = .{ .context = @ptrCast(self), .check = checkCancel };
}
-// Compile-time constant; project them once per process to avoid rebuilding per call.
+// Compile-time constant; projected once per process to avoid rebuilding per call.
var global_tools_storage: [browser_tools.tool_defs.len]ProviderTool = undefined;
var global_tools_once = std.once(initGlobalTools);
@@ -333,11 +330,10 @@ fn globalTools() []const ProviderTool {
return global_tools_storage[0..browser_tools.tool_defs.len];
}
-/// Called from the sighandler thread. Flips `cancel_requested` for the
-/// LLM streaming/HTTP probe and any code polling `Session.isCancelled`,
-/// then asks V8 to bail out of whatever JS is currently running. Both
-/// hooks are thread-safe (`Env.terminate` takes a mutex); no terminal
-/// touches from this context.
+/// Called from the sighandler thread. Flips `cancel_requested` for the LLM
+/// streaming/HTTP probe and any code polling `Session.isCancelled`, then asks
+/// V8 to bail out of whatever JS is running. Both hooks are thread-safe
+/// (`Env.terminate` takes a mutex); no terminal touches from this context.
pub fn requestCancel(self: *Agent) void {
self.cancel_requested.store(true, .release);
self.http_interrupt.fire();
@@ -351,10 +347,10 @@ pub fn requestCancel(self: *Agent) void {
self.browser.env.terminate();
}
-/// Lives in main's stack so it can be registered with the sighandler
-/// before the agent thread exists. The agent attaches itself once it's
-/// constructed and detaches before deinit, so the sighandler-thread
-/// listener can fire safely whether or not an agent is currently up.
+/// Lives in main's stack so it can be registered with the sighandler before the
+/// agent thread exists. The agent attaches once constructed and detaches before
+/// deinit, so the sighandler-thread listener can fire safely whether or not an
+/// agent is currently up.
pub const SigBridge = struct {
agent: std.atomic.Value(?*Agent) = .init(null),
@@ -377,10 +373,9 @@ fn checkCancel(ctx: *anyopaque) bool {
return self.cancel_requested.load(.acquire);
}
-/// Roll the agent back to `baseline` messages, clear the V8 termination
-/// flag, drop the cancel signal, and surface `error.UserCancelled` to the
-/// caller. Caller is responsible for any spinner cleanup that hasn't
-/// already happened on its path.
+/// Roll the agent back to `baseline` messages, clear the V8 termination flag,
+/// drop the cancel signal, and surface `error.UserCancelled`. Caller handles
+/// any spinner cleanup not already done on its path.
fn drainCancellation(self: *Agent, baseline: usize) error{UserCancelled} {
self.resetAfterCancel(baseline);
return error.UserCancelled;
@@ -394,9 +389,9 @@ fn resetAfterCancel(self: *Agent, baseline: usize) void {
self.cancel_requested.store(false, .release);
}
-/// One agent turn: the prompt sent to the model, plus optional context
-/// (a recorder comment to write before the turn, file attachments to bundle
-/// into the first user message, and a display label used in error output).
+/// One agent turn: the prompt sent to the model, plus optional context — a
+/// recorder comment to write before the turn, file attachments to bundle into
+/// the first user message, and a display label used in error output.
pub const TurnInput = struct {
prompt: []const u8,
record_comment: ?[]const u8 = null,
@@ -422,11 +417,11 @@ pub fn run(self: *Agent) bool {
return true;
}
-/// Print a single-line summary of cumulative token usage to stderr, so
-/// wrappers driving `lightpanda agent --task ...` can capture per-task cost
-/// by `grep`-ing for the `$usage` prefix. Format is stable and key=value:
+/// Print single-line cumulative token usage to stderr, so wrappers driving
+/// `lightpanda agent --task ...` can capture per-task cost by `grep`-ing the
+/// `$usage` prefix. Stable key=value format:
/// $usage prompt=N completion=N total=N cached=N cache_creation=N
-/// Fields are emitted with value 0 when the provider didn't report them.
+/// Fields emit 0 when the provider didn't report them.
fn printUsageSummary(self: *Agent) void {
const u = self.total_usage;
std.debug.print(
@@ -477,8 +472,8 @@ fn runRepl(self: *Agent) void {
const line = Terminal.readLine("") orelse break;
defer Terminal.freeLine(line);
- // Slash commands and idle Ctrl-C set the cancel flag without
- // clearing V8's terminate state; drain both before the next turn.
+ // Slash commands and idle Ctrl-C set the cancel flag without clearing
+ // V8's terminate state; drain both before the next turn.
if (self.cancel_requested.swap(false, .acq_rel)) {
self.browser.env.cancelTerminate();
}
@@ -506,8 +501,8 @@ fn runRepl(self: *Agent) void {
}});
continue :repl;
};
- // Surface console output: slash commands (and thus /consoleLogs) are
- // unreachable in JS mode, so a console must echo logs itself.
+ // Surface console output: slash commands (and thus /consoleLogs)
+ // are unreachable in JS mode, so a console must echo logs itself.
const logs = std.mem.trimRight(u8, self.session.drainConsoleMessages(), "\n");
if (logs.len > 0) self.printData(logs);
if (result.is_error) {
@@ -573,9 +568,8 @@ fn runRepl(self: *Agent) void {
}
}
-/// Handle a REPL-only meta slash command. These aren't tool slash commands
-/// and never reach the browser tool dispatcher. Returns `true` if the user
-/// asked to quit.
+/// Handle a REPL-only meta slash command — not a tool slash command, never
+/// reaches the browser tool dispatcher. Returns `true` if the user asked to quit.
fn handleMeta(self: *Agent, arena: std.mem.Allocator, meta: *const SlashCommand.MetaCommand, rest: []const u8) bool {
switch (meta.tag) {
.quit => return true,
@@ -595,7 +589,7 @@ fn handleMeta(self: *Agent, arena: std.mem.Allocator, meta: *const SlashCommand.
/// Shared body of `/verbosity` and `/effort`: bare prints the current level; an
/// argument is parsed against the enum, stored in `target`, and persisted.
-/// `name` drives the slash name, the usage hint, and the report label together.
+/// `name` drives the slash name, usage hint, and report label.
fn setEnumOption(self: *Agent, comptime name: []const u8, target: anytype, rest: []const u8) void {
const T = @typeInfo(@TypeOf(target)).pointer.child;
if (rest.len == 0) {
@@ -610,10 +604,10 @@ fn setEnumOption(self: *Agent, comptime name: []const u8, target: anytype, rest:
self.reportSaved(name, @tagName(level));
}
-/// Print cumulative token usage for the session, broken down so the cache's
-/// effect is visible — the REPL otherwise never surfaces the `$usage` line that
-/// `--task` prints. Reads `total_usage`, accumulated across every turn by
-/// `processUserMessage`; the fresh/cache split semantics live on `Usage`.
+/// Print cumulative session token usage, broken down so the cache's effect is
+/// visible — the REPL otherwise never surfaces the `$usage` line `--task`
+/// prints. Reads `total_usage` (accumulated per turn by `processUserMessage`);
+/// fresh/cache split semantics live on `Usage`.
fn handleUsage(self: *Agent) void {
const u = self.total_usage;
const input = u.inputTokens();
@@ -631,9 +625,9 @@ fn handleUsage(self: *Agent) void {
}
}
-/// Drop everything tied to the conversation: history (the system prompt
-/// re-seeds lazily on the next turn), cumulative usage, the recorded action
-/// buffer, and DOM node IDs. Shared by `/clear` and `/reset`.
+/// Drop everything tied to the conversation: history (system prompt re-seeds
+/// lazily next turn), cumulative usage, the recorded action buffer, and DOM
+/// node IDs. Shared by `/clear` and `/reset`.
fn clearConversation(self: *Agent) void {
self.conversation.rollback(0);
self.save_buffer.reset();
@@ -641,8 +635,8 @@ fn clearConversation(self: *Agent) void {
self.node_registry.reset();
}
-/// Forget the conversation while leaving the browser session live — the loaded
-/// page stays put and cookies/logins are preserved.
+/// Forget the conversation while leaving the browser session live — loaded page
+/// stays put, cookies/logins preserved.
fn handleClear(self: *Agent) void {
self.clearConversation();
self.terminal.printInfo("Cleared conversation, usage, and node IDs. Page and cookies kept.", .{});
@@ -671,8 +665,8 @@ fn handleLoad(self: *Agent, rest: []const u8) void {
const api_keys_hint = settings.api_keys_hint;
const llm_setup_hint = "set an API key (" ++ api_keys_hint ++ ") and run /provider <name>";
-/// `/provider <keyword>` disables the LLM and persists it; shared by the command
-/// parser, autocomplete, and the save report so they can't drift apart.
+/// `/provider <keyword>` disables the LLM and persists it; shared by command
+/// parser, autocomplete, and save report so they can't drift apart.
const provider_off_keyword = "null";
fn requireLlm(self: *Agent, name: []const u8) bool {
@@ -692,7 +686,7 @@ fn handleModel(self: *Agent, _: std.mem.Allocator, rest: []const u8) void {
return;
}
const ids = completionModels(self, self.allocator);
- // Empty list = fetch failed or unlisted local models; can't confirm, so allow.
+ // Empty list = fetch failed or unlisted local models; can't confirm, allow.
if (ids.len != 0 and !string.isOneOf(trimmed, ids)) {
self.terminal.printError("unknown model: {s} (Tab to list)", .{trimmed});
return;
@@ -702,9 +696,9 @@ fn handleModel(self: *Agent, _: std.mem.Allocator, rest: []const u8) void {
};
}
-/// Persist the current provider/model/effort/verbosity to `.lp-agent.zon` and report it
-/// as "<label>: <value>", appending "(saved to …)" when the write succeeds. With no
-/// model credentials it persists `provider = null` only when that's an intentional
+/// Persist provider/model/effort/verbosity to `.lp-agent.zon` and report it as
+/// "<label>: <value>", appending "(saved to …)" on write success. With no model
+/// credentials it persists `provider = null` only when that's an intentional
/// preference (`no_llm_persisted`); a transient --no-llm run reports without saving.
fn reportSaved(self: *Agent, label: []const u8, value: []const u8) void {
const provider: ?Config.AiProvider = if (self.model_credentials) |c| c.provider else null;
@@ -847,8 +841,8 @@ fn handleSave(self: *Agent, arena: std.mem.Allocator, rest: []const u8) void {
const mode = resolved.mode;
// `path` aliases either an arena-owned string (first save) or
- // `self.save_path` (subsequent saves to the same destination); only
- // the former needs to be persisted into agent-owned memory.
+ // `self.save_path` (subsequent saves to the same destination); only the
+ // former needs persisting into agent-owned memory.
var new_save_path: ?[]u8 = if (self.save_path == null)
self.allocator.dupe(u8, path) catch |err| {
self.terminal.printError("failed to remember save destination {s}: {s}", .{ path, @errorName(err) });
@@ -876,8 +870,8 @@ const SaveCommand = struct { filename: ?[]const u8, prompt: ?[]const u8 };
/// Split `/save` arguments into an optional filename and an optional trailing
/// natural-language prompt. A quoted leading token is always a filename; an
-/// unquoted one is a filename only if it ends in `.js` (otherwise the whole
-/// argument is the prompt, and a name is chosen automatically).
+/// unquoted one is a filename only if it ends in `.js` (else the whole argument
+/// is the prompt, and a name is chosen automatically).
fn parseSaveCommand(rest: []const u8) !SaveCommand {
const trimmed = std.mem.trim(u8, rest, &std.ascii.whitespace);
if (trimmed.len == 0) return .{ .filename = null, .prompt = null };
@@ -1016,8 +1010,8 @@ fn synthesizeSave(self: *Agent, arena: std.mem.Allocator, filename: ?[]const u8,
const raw = result.text orelse return self.abortSave(baseline, "the model returned no script");
- // `result.text` lives in the conversation arena, which the rollback below
- // frees; copy into the command arena first (scrubbing may return its input
+ // `result.text` lives in the conversation arena, freed by the rollback
+ // below; copy into the command arena first (scrubbing may return its input
// as-is).
const owned = arena.dupe(u8, stripCodeFence(raw)) catch return self.abortSave(baseline, "out of memory");
const script = browser_tools.reverseSubstituteEnvVars(arena, owned) catch return self.abortSave(baseline, "out of memory");
@@ -1064,9 +1058,9 @@ fn buildSaveSynthesisMessage(self: *Agent, arena: std.mem.Allocator, prompt: ?[]
}
/// Document the recorded browser tools — the subset callable from a saved
-/// script — with their full descriptions, so the model gets each function's
-/// argument dialect (e.g. `extract`'s schema format) without being handed the
-/// tool schemas a no-tools synthesis turn omits.
+/// script — with full descriptions, so the model gets each function's argument
+/// dialect (e.g. `extract`'s schema format) without the tool schemas a no-tools
+/// synthesis turn omits.
fn renderBuiltinCatalog(w: *std.Io.Writer) !void {
for (Schema.all()) |s| {
if (!s.tool.isRecorded()) continue;
@@ -1187,7 +1181,7 @@ fn printSlashHelp(self: *Agent, arena: std.mem.Allocator, target: []const u8) vo
}
/// Caller contract: `cmd` must be `.tool_call` — `.comment` and `.llm` are
-/// filtered upstream because they have no tool mapping.
+/// filtered upstream, having no tool mapping.
fn runCommand(self: *Agent, arena: std.mem.Allocator, cmd: Command) browser_tools.ToolResult {
const tc = switch (cmd) {
.tool_call => |t| t,
@@ -1205,9 +1199,9 @@ fn runCommand(self: *Agent, arena: std.mem.Allocator, cmd: Command) browser_tool
/// Data output (/extract, /evaluate, /markdown, /tree, …) → plain stdout on
/// success so a caller can pipe it. Everything else routes through
-/// `printToolOutcome`, which lays down the green ● / red ● dot shared
-/// with the LLM tool-call path. Callers only invoke this for `.tool_call`
-/// commands (the comment/login/acceptCookies branches take other paths).
+/// `printToolOutcome`, which lays down the green ● / red ● dot shared with the
+/// LLM tool-call path. Callers only invoke this for `.tool_call` commands (the
+/// comment/login/acceptCookies branches take other paths).
fn printCommandResult(self: *Agent, cmd: Command, result: browser_tools.ToolResult) void {
const tc = switch (cmd) {
.tool_call => |t| t,
@@ -1227,10 +1221,9 @@ fn printData(self: *Agent, text: []const u8) void {
self.terminal.printAssistant(Terminal.reindentJson(arena.allocator(), text) orelse text);
}
-/// Tracks whether a `/load`-run script has emitted any `console.*` output,
-/// which decides how `runScript` ends: a script that printed nothing freezes
-/// the spinner into a `/goto`-style bullet; one that printed leaves its
-/// output as the result.
+/// Tracks whether a `/load`-run script emitted any `console.*` output, deciding
+/// how `runScript` ends: one that printed nothing freezes the spinner into a
+/// `/goto`-style bullet; one that printed leaves its output as the result.
const ScriptOutput = struct {
terminal: *Terminal,
emitted: bool = false,
@@ -1285,16 +1278,15 @@ fn runScript(self: *Agent, path: []const u8) bool {
return false;
}
- // A script that printed nothing leaves no trace, so freeze the spinner
- // into a green bullet (like /goto); one that printed already showed its
- // result.
+ // A script that printed nothing leaves no trace, so freeze the spinner into
+ // a green bullet (like /goto); one that printed already showed its result.
if (!output.emitted) self.terminal.printScriptDone("script", path);
return true;
}
-/// Mirror a user-typed slash command into `self.conversation.messages` as if the LLM
-/// had called the tool itself, so the next natural-language turn sees
-/// the same conversation shape either way.
+/// Mirror a user-typed slash command into `self.conversation.messages` as if the
+/// LLM had called the tool itself, so the next natural-language turn sees the
+/// same conversation shape either way.
fn recordSlashToolCall(
self: *Agent,
user_input: []const u8,
@@ -1317,8 +1309,8 @@ fn recordSlashToolCall(
.arguments = if (args) |v| try zenai.json.dupeValue(ma, v) else null,
};
- // capToolOutput returns its input unchanged under the cap; dupe so
- // content doesn't alias the caller's per-iteration arena.
+ // capToolOutput returns its input unchanged under the cap; dupe so content
+ // doesn't alias the caller's per-iteration arena.
const capped = capToolOutput(ma, result.text);
const content = if (capped.ptr == result.text.ptr) try ma.dupe(u8, capped) else capped;
@@ -1348,18 +1340,16 @@ fn recordSlashToolCall(
});
}
-/// Returned text lives in `conversation.arena`, so it's only valid until the
-/// next prune. The caller is responsible for calling `conversation.prune()`
-/// after consuming the returned text — pruning earlier would free the
-/// arena the slice points into. `null` means the model emitted nothing
+/// Returned text lives in `conversation.arena`, valid only until the next prune.
+/// Caller must call `conversation.prune()` after consuming it — pruning earlier
+/// frees the arena the slice points into. `null` means the model emitted nothing
/// even after the synthesis turn.
fn processUserMessage(self: *Agent, input: TurnInput) !?[]const u8 {
const ma = self.conversation.arena.allocator();
try self.conversation.ensureSystemPrompt();
- // Attachments only ride on the very first user turn (just after the
- // system prompt).
+ // Attachments only ride on the first user turn (just after the system prompt).
const turn_attachments: ?[]const []const u8 =
if (self.conversation.messages.items.len == 1) input.attachments else null;
@@ -1396,16 +1386,15 @@ fn processUserMessage(self: *Agent, input: TurnInput) !?[]const u8 {
.max_tokens = 4096,
.tool_choice = .auto,
// Per-turn reasoning budget; resolved from --effort / .lp-agent.zon
- // / mode default and adjustable at runtime via /effort. Ignored by
+ // / mode default, adjustable at runtime via /effort. Ignored by
// non-thinking models.
.effort = self.effort,
.cancel = .{ .context = @ptrCast(self), .checkFn = checkCancel },
},
) catch |err| {
self.terminal.spinner.cancel();
- // Ctrl-C can land while runTools is unwinding an HTTP error —
- // surface UserCancelled, not ApiError, so the user sees the
- // outcome they asked for.
+ // Ctrl-C can land while runTools unwinds an HTTP error — surface
+ // UserCancelled, not ApiError, so the user sees the outcome they asked for.
if (self.cancel_requested.load(.acquire)) return self.drainCancellation(msg_baseline);
log.err(.app, "AI API error", .{ .err = err });
self.conversation.rollback(msg_baseline);
@@ -1419,7 +1408,7 @@ fn processUserMessage(self: *Agent, input: TurnInput) !?[]const u8 {
if (input.capture_for_save) {
// When the LLM tries multiple `extract` schemas in one turn, only the
- // last successful one is the answer — earlier probes are noise.
+ // last successful one is the answer; earlier probes are noise.
var last_extract_idx: ?usize = null;
for (result.tool_calls_made, 0..) |tc, i| {
const t = std.meta.stringToEnum(BrowserTool, tc.name) orelse continue;
@@ -1444,7 +1433,7 @@ fn processUserMessage(self: *Agent, input: TurnInput) !?[]const u8 {
}
}
- // Dupe into the conversation arena — RunToolsResult arenas are deinited below.
+ // Dupe into the conversation arena — RunToolsResult arenas deinit below.
self.last_turn_refused = result.finish_reason == .safety;
const final_text: ?[]const u8 = blk: {
if (result.text) |text| {
@@ -1493,17 +1482,17 @@ fn processUserMessage(self: *Agent, input: TurnInput) !?[]const u8 {
break :blk if (synth.text) |text| try ma.dupe(u8, text) else null;
};
- // NB: pruning is deferred to the caller. `final_text` is allocated in the
- // conversation arena, and `conversation.prune()` may rebuild that arena —
- // running it here would hand the caller a dangling slice.
+ // NB: pruning is deferred to the caller. `final_text` is in the conversation
+ // arena, and `conversation.prune()` may rebuild that arena — running it here
+ // would hand the caller a dangling slice.
return final_text;
}
-/// Build a `parts`-based user message when `--attach` was given.
-/// Text-ish files are inlined into the text prefix (surrounded by clear
-/// markers); binary files (image/audio/pdf) are base64-encoded and sent as
-/// provider inline-data parts. Unknown extensions error out so the caller
-/// fails loudly instead of silently dropping the attachment.
+/// Build a `parts`-based user message when `--attach` was given. Text-ish files
+/// are inlined into the text prefix (surrounded by clear markers); binary files
+/// (image/audio/pdf) are base64-encoded as provider inline-data parts. Unknown
+/// extensions error out so the caller fails loudly instead of silently dropping
+/// the attachment.
fn buildUserMessageParts(
self: *Agent,
ma: std.mem.Allocator,
@@ -1553,8 +1542,8 @@ fn buildUserMessageParts(
return parts.toOwnedSlice(ma);
}
-// Cap per-call tool output so heavy pages don't balloon the message arena
-// (and the next request body) without bound.
+// Cap per-call tool output so heavy pages don't balloon the message arena (and
+// the next request body) without bound.
const tool_output_max_bytes: usize = 1 * 1024 * 1024;
fn capToolOutput(allocator: std.mem.Allocator, output: []const u8) []const u8 {
@@ -1567,8 +1556,8 @@ fn capToolOutput(allocator: std.mem.Allocator, output: []const u8) []const u8 {
fn handleToolCall(ctx: *anyopaque, allocator: std.mem.Allocator, tool_name: []const u8, arguments: ?std.json.Value) zenai.provider.Client.ToolHandler.Result {
const self: *Agent = @ptrCast(@alignCast(ctx));
- // The spinner doesn't render args, and `agentToolDone` skips the body
- // line at low verbosity — don't pay for the stringify when nobody reads it.
+ // The spinner doesn't render args, and `agentToolDone` skips the body line
+ // at low verbosity — don't pay for the stringify when nobody reads it.
const needs_args = self.terminal.spinner.isEnabled() or self.terminal.verbosity != .low;
// Stringify the pre-substitution args so $LP_* placeholders the model
// emitted stay redacted in the UI.
@@ -1589,8 +1578,8 @@ fn handleToolCall(ctx: *anyopaque, allocator: std.mem.Allocator, tool_name: []co
return outcome;
}
-/// One-shot for `--list-models`: resolve provider+key, fetch chat-capable
-/// model IDs, print to stdout (one per line).
+/// One-shot for `--list-models`: resolve provider+key, fetch chat-capable model
+/// IDs, print to stdout one per line.
pub fn listModels(allocator: std.mem.Allocator, opts: Config.Agent) !void {
if (opts.no_llm) {
log.fatal(.app, "list-models needs LLM", .{
@@ -1620,12 +1609,12 @@ pub fn listModels(allocator: std.mem.Allocator, opts: Config.Agent) !void {
const ModelCompletions = struct {
provider: Config.AiProvider,
/// Empty when the fetch failed — cached so the per-keystroke hinter doesn't
- /// re-hit the network on every press.
+ /// re-hit the network each press.
ids: []const []const u8,
};
-/// `CompletionSource.providers`. Reuses pre-detected available providers to avoid
-/// reading environment variables on every autocomplete keypress.
+/// `CompletionSource.providers`. Reuses pre-detected available providers to
+/// avoid reading environment variables on each autocomplete keypress.
fn completionProviders(context: *anyopaque, arena: std.mem.Allocator) []const []const u8 {
const self: *Agent = @ptrCast(@alignCast(context));
const names = arena.alloc([]const u8, self.available_providers.len + 1) catch return &.{};
@@ -1637,7 +1626,7 @@ fn completionProviders(context: *anyopaque, arena: std.mem.Allocator) []const []
}
/// `CompletionSource.models`. Blocks on a one-time fetch per provider, caching
-/// success or empty so the per-keystroke hinter pays the round-trip only once.
+/// success or empty so the per-keystroke hinter pays the round-trip once.
fn completionModels(context: *anyopaque, _: std.mem.Allocator) []const []const u8 {
const self: *Agent = @ptrCast(@alignCast(context));
const llm = self.model_credentials orelse return &.{};
diff --git a/src/agent/Conversation.zig b/src/agent/Conversation.zig
index 3b5110e48..e1e9acdc6 100644
--- a/src/agent/Conversation.zig
+++ b/src/agent/Conversation.zig
@@ -16,12 +16,12 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-//! The agent's chat history and the arena backing every message's bytes. The
-//! pairing is the point: pruning and rollback re-home the surviving messages
-//! into a fresh arena so dropped turns' bytes are freed in one shot, and the
-//! system prompt at index 0 is the one message kept outside the arena so those
-//! rebuilds never disturb it. `Agent` appends turns and reads `messages` /
-//! `arena` directly; it leaves the lifecycle (seed, prune, rollback) here.
+//! The agent's chat history paired with the arena backing every message's
+//! bytes: prune and rollback re-home the surviving messages into a fresh arena,
+//! freeing dropped turns' bytes in one shot. The system prompt at index 0 lives
+//! outside the arena so those rebuilds never disturb it. `Agent` appends turns
+//! and reads `messages` / `arena` directly; lifecycle (seed, prune, rollback)
+//! lives here.
const std = @import("std");
const zenai = @import("zenai");
diff --git a/src/agent/SlashCommand.zig b/src/agent/SlashCommand.zig
index 2749d347a..80cadf709 100644
--- a/src/agent/SlashCommand.zig
+++ b/src/agent/SlashCommand.zig
@@ -17,10 +17,9 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! REPL-only meta slash commands (`/help`, `/quit`, `/verbosity`, `/effort`,
-//! `/usage`, `/model`, `/provider`). Meta commands aren't tool slash commands — they're handled
-//! by `Agent.handleMeta` and never reach the recorder. Tool slash-command
-//! schema primitives live in `lp.Schema`; consumers should import that
-//! directly.
+//! `/usage`, `/model`, `/provider`). Not tool slash commands — handled by
+//! `Agent.handleMeta`, never reaching the recorder. Tool slash-command schema
+//! primitives live in `lp.Schema`; import that directly.
const std = @import("std");
const lp = @import("lightpanda");
@@ -36,17 +35,17 @@ pub const Help = struct {
pub const MetaCommand = struct {
tag: Tag,
name: [:0]const u8,
- /// Ghost-text fragment shown after the name + space. Empty when the
- /// command takes no args (`/help`, `/quit`).
+ /// Ghost-text fragment shown after the name + space. Empty when the command
+ /// takes no args (`/help`, `/quit`).
hint: []const u8,
/// Tab-completion candidates for the first positional arg.
values: []const []const u8,
- /// Terse one-liner for the `/help` listing; longer detail is rendered
- /// by `Agent.printSlashHelp` for the per-command lookup.
+ /// Terse one-liner for the `/help` listing; longer per-command detail is
+ /// rendered by `Agent.printSlashHelp`.
description: []const u8,
- /// Dispatched by `Agent.handleMeta` via an exhaustive switch so adding
- /// a new meta command is a compile error until it's wired up there too.
+ /// Dispatched by `Agent.handleMeta` via an exhaustive switch, so a new meta
+ /// command is a compile error until it's wired up there too.
const Tag = enum { help, quit, verbosity, effort, usage, clear, reset, save, load, model, provider };
};
@@ -67,8 +66,8 @@ pub const meta_commands = [_]MetaCommand{
.{ .tag = .provider, .name = "provider", .hint = "[name|null]", .values = &.{}, .description = "Change the provider, or 'null' to disable the LLM" },
};
-/// Derived from `Command.LlmCommand` — name and description both come from
-/// the enum, so a new trigger there surfaces here automatically.
+/// Derived from `Command.LlmCommand` — name and description both come from the
+/// enum, so a new trigger there surfaces here automatically.
pub const llm_commands = blk: {
const values = std.enums.values(Command.LlmCommand);
var rows: [values.len]Help = undefined;
diff --git a/src/agent/Spinner.zig b/src/agent/Spinner.zig
index 65ab62e39..36d91381f 100644
--- a/src/agent/Spinner.zig
+++ b/src/agent/Spinner.zig
@@ -28,14 +28,14 @@ const Spinner = @This();
const braille = [_][]const u8{ "⡇", "⣆", "⣤", "⣰", "⢸", "⠹", "⠛", "⠏" };
const interval_ns: u64 = 100 * std.time.ns_per_ms;
/// Minimum dwell on a tool label so the user can read it. Slow tools exceed
-/// this naturally; fast ones (getUrl, getCookies) get padded.
+/// it naturally; fast ones (getUrl, getCookies) get padded.
const min_tool_display_ns: u64 = 1500 * std.time.ns_per_ms;
const clear_eol = ansi.clear_eol;
const max_args_bytes: usize = 256;
const frame_buf_bytes: usize = 512;
-/// Visual ceiling on the args slice. Combined with the terminal-width cap so
-/// the spinner line stays single-row even when the script body is huge.
+/// Visual ceiling on the args slice. With the terminal-width cap, keeps the
+/// spinner line single-row even when the script body is huge.
const max_args_cells: usize = 70;
/// UTF-8 horizontal ellipsis ("…") — 3 bytes, 1 visual cell.
const ellipsis = "\xe2\x80\xa6";
@@ -48,11 +48,11 @@ const ToolState = struct {
args_len: usize = 0,
/// Wall-clock at which `setTool` last fired; gates dwell-honoring.
set_ns: i128 = 0,
- /// Worker should flip back to thinking once dwell elapses. Cleared by a
- /// fresh `setTool` (which overrides the dwell with a new label).
+ /// Worker should flip back to thinking once dwell elapses. A fresh
+ /// `setTool` clears it, overriding the dwell with a new label.
dwell_pending: bool = false,
- /// User-typed REPL commands drop the `agent:` framing since no agent
- /// is involved — it's lightpanda running the command directly.
+ /// User-typed REPL commands drop the `agent:` framing: no agent is
+ /// involved, it's lightpanda running the command directly.
manual: bool = false,
};
@@ -125,7 +125,7 @@ fn ensureWorkerLocked(self: *Spinner) void {
}
/// End an agent turn cleanly: clear the indicator, commit a one-line summary,
-/// reset state. Called from a `defer` in the agent code so it always runs.
+/// reset state. Called from a `defer` in agent code so it always runs.
pub fn stop(self: *Spinner) void {
if (!self.isEnabled()) return;
self.mu.lock();
@@ -160,8 +160,8 @@ pub fn cancel(self: *Spinner) void {
/// Switch the indicator to "running tool <name> <args>". Counts toward the
/// turn's tool-call total. Args are truncated to `max_args_bytes`. Called
-/// without a preceding `start()` (state `.idle`) the label drops the `agent:`
-/// prefix — that path is for user-typed REPL commands, not LLM tool calls.
+/// without a preceding `start()` (state `.idle`), the label drops the `agent:`
+/// prefix — that path is user-typed REPL commands, not LLM tool calls.
pub fn setTool(self: *Spinner, name: []const u8, args: []const u8) void {
if (!self.isEnabled()) return;
self.mu.lock();
@@ -173,24 +173,24 @@ pub fn setTool(self: *Spinner, name: []const u8, args: []const u8) void {
tool.name_len = name_prefix.len;
@memcpy(tool.name_buf[0..name_prefix.len], name_prefix);
// Strip control chars: a literal `\n` in args (e.g. /evaluate """…""" bodies)
- // breaks the spinner's `\r`-based redraw — the cursor only rewinds to the
- // start of the last line, leaving prior frames stuck on screen.
+ // breaks the `\r`-based redraw — `\r` only rewinds to the start of the last
+ // line, leaving prior frames stuck on screen.
const args_prefix = truncateUtf8(args, tool.args_buf.len);
tool.args_len = args_prefix.len;
for (args_prefix, 0..) |ch, i| {
tool.args_buf[i] = if (ch < 0x20 or ch == 0x7f) ' ' else ch;
}
self.state = .{ .tool = tool };
- // Manual paths skip `start()`, so spawn the worker on demand to drive
- // the braille animation.
+ // Manual paths skip `start()`, so spawn the worker on demand to drive the
+ // braille animation.
if (manual) self.ensureWorkerLocked();
self.renderLocked();
self.cv.signal();
}
/// Request a transition back to the cycling "thinking" state. The worker
-/// honors `min_tool_display_ns` — if the current tool label has not been
-/// up long enough, the flip is deferred until it has.
+/// honors `min_tool_display_ns`: if the current tool label has not been up
+/// long enough, the flip is deferred until it has.
pub fn setThinking(self: *Spinner) void {
if (!self.isEnabled()) return;
self.mu.lock();
@@ -230,7 +230,7 @@ fn workerLoop(self: *Spinner) void {
switch (self.state) {
.tool => {
if (self.state.tool.dwell_pending) {
- // Compare signed: a backward clock jump (NTP slew, suspend/resume)
+ // Signed compare: a backward clock jump (NTP slew, suspend/resume)
// can make the delta negative; `@intCast` to u64 would panic.
const delta: i128 = std.time.nanoTimestamp() - self.state.tool.set_ns;
if (delta >= @as(i128, min_tool_display_ns)) {
@@ -262,15 +262,14 @@ fn renderLocked(self: *Spinner) void {
const prefix: []const u8 = if (tool.manual) "" else "agent: ";
const name = tool.name_buf[0..tool.name_len];
const all_args = tool.args_buf[0..tool.args_len];
- // "<glyph> [<prefix><name> <args>]" — 5 visible cells of fixed
- // decoration (glyph, two spaces, `[`, `]`) around prefix+name+args.
- // `\r` and ANSI escapes are zero-width, so they don't count toward
- // terminal wrap.
+ // "<glyph> [<prefix><name> <args>]" — 5 fixed decoration cells
+ // (glyph, two spaces, `[`, `]`) around prefix+name+args. `\r` and
+ // ANSI escapes are zero-width, so they don't count toward wrap.
const decoration_cells: usize = 5 + prefix.len + name.len;
const cols: usize = Terminal.columns() orelse 80;
- // Reserve one extra cell so the line is strictly less than `cols` —
- // terminals with auto-wrap (DECAWM) advance past a row that exactly
- // fills the width.
+ // Reserve one extra cell so the line is strictly less than `cols`:
+ // auto-wrap (DECAWM) terminals advance past a row that exactly fills
+ // the width.
const reserved = decoration_cells + ellipsis_cells + 1;
const room: usize = if (cols > reserved) cols - reserved else 0;
const cap = @min(max_args_cells, room);
@@ -289,10 +288,9 @@ fn renderLocked(self: *Spinner) void {
_ = std.posix.write(std.posix.STDERR_FILENO, written) catch {};
}
-/// Returns the byte length of `bytes` that fits in `max_cells` cells,
-/// rounded down to a whole UTF-8 codepoint. Multi-cell glyphs (CJK,
-/// wide emoji) are counted as 1 — args are typically ASCII so the
-/// approximation is good enough.
+/// Returns the byte length of `bytes` that fits in `max_cells` cells, rounded
+/// down to a whole UTF-8 codepoint. Multi-cell glyphs (CJK, wide emoji) count
+/// as 1 — args are typically ASCII, so the approximation is good enough.
fn truncToCells(bytes: []const u8, max_cells: usize) usize {
var cells: usize = 0;
var i: usize = 0;
diff --git a/src/agent/Terminal.zig b/src/agent/Terminal.zig
index 65171a354..69ec9835b 100644
--- a/src/agent/Terminal.zig
+++ b/src/agent/Terminal.zig
@@ -63,10 +63,10 @@ const Verbosity = Config.AgentVerbosity;
allocator: std.mem.Allocator,
verbosity: Verbosity,
-/// Non-null in REPL mode. Doubles as scratch arena for the pretty-printer
-/// (reset per `printToolOutcome`, so memory is bounded by the largest
-/// single tool output). REPL forces tool calls/results visible regardless
-/// of verbosity — the dial only gates non-interactive runs.
+/// Non-null in REPL mode. Doubles as pretty-printer scratch arena (reset per
+/// `printToolOutcome`, so memory is bounded by the largest single tool output).
+/// REPL forces tool calls/results visible regardless of verbosity — the dial
+/// only gates non-interactive runs.
repl_arena: ?std.heap.ArenaAllocator,
stderr_is_tty: bool,
spinner: Spinner,
@@ -140,8 +140,8 @@ pub const HistoryPaths = struct {
pub fn init(allocator: std.mem.Allocator, history_paths: ?HistoryPaths, verbosity: Verbosity, is_repl: bool) Terminal {
// Isocline probes the terminal on init (writes ESC[6n cursor-report on
- // stdout), so skip the whole setup in script-only mode — `ic_readline` is
- // never reached there anyway.
+ // stdout), so skip setup in script-only mode — `ic_readline` is never
+ // reached there anyway.
if (is_repl) {
_ = c.ic_enable_multiline(true);
_ = c.ic_enable_hint(true);
@@ -168,8 +168,8 @@ pub fn init(allocator: std.mem.Allocator, history_paths: ?HistoryPaths, verbosit
c.ic_set_prompt_marker("❯ ", "");
_ = c.ic_enable_highlight(true);
if (history_paths) |hp| {
- // Mode is inactive at launch, so load the normal file; modeCallback
- // swaps to the JS file when JS mode is entered.
+ // Mode inactive at launch, so load the normal file; modeCallback
+ // swaps to JS on mode entry.
c.ic_set_history(hp.normal.ptr, -1); // -1 → 200-entry default cap
}
}
@@ -200,16 +200,16 @@ pub fn beginTool(self: *Terminal, name: []const u8, args: []const u8) void {
self.spinner.setTool(name, args);
}
-/// Mark the end of a manual REPL tool call. Clears the running spinner; the
-/// caller's `printToolOutcome` lays down the colored status dot.
+/// Mark the end of a manual REPL tool call. Clears the spinner; the caller's
+/// `printToolOutcome` lays down the colored status dot.
pub fn endTool(self: *Terminal) void {
self.spinner.cancel();
}
/// Called after the tool returns. At `medium`+, commits a `● [tool: …]` line
/// above the spinner (green/red bullet for ok/fail) so the run leaves a trace.
-/// In non-TTY contexts ANSI is still emitted — pipes that strip color see
-/// plain text via the bullet character.
+/// ANSI is emitted even in non-TTY contexts — pipes that strip color see plain
+/// text via the bullet character.
pub fn agentToolDone(self: *Terminal, name: []const u8, args: []const u8, ok: bool) void {
if (!self.verbosity.atLeast(.medium)) return;
const spinner_on = self.spinner.isEnabled();
@@ -256,8 +256,8 @@ fn addPrefixedCompletion(
_ = c.ic_add_completion_prim(cenv, text.ptr, null, null, @intCast(input.len), 0);
}
-// Cap on tokens we read out of the body. Real schemas and CLI inputs have far
-// fewer fields than this; extra tokens are ignored.
+// Cap on tokens read out of the body; extra tokens are ignored. Real schemas
+// and CLI inputs have far fewer fields.
const max_tokens = 32;
const BodyAnalysis = struct {
@@ -301,9 +301,8 @@ fn analyzeBody(schema: *const Schema, body: []const u8, ends_ws: bool) BodyAnaly
a.markUsed(tok[0..eq]);
continue;
}
- // Single-required schemas accept the first arg positionally
- // (`/goto https://example.com`); the schema's only required field
- // is implicitly bound.
+ // Single-required schemas bind the first arg positionally to their
+ // lone required field (`/goto https://example.com`).
if (i == 0 and schema.required.len == 1) {
a.markUsed(schema.required[0]);
continue;
@@ -502,7 +501,7 @@ fn completionCallback(cenv: ?*c.ic_completion_env_t, prefix: [*c]const u8) callc
const partial = input[1..];
// Trailing space on commands with params hands off to the hinter,
// which renders the full ` <url> [timeout=…]` template uniformly
- // whether the user typed the name or Tab-completed it.
+ // whether the name was typed or Tab-completed.
for (all_slash_names) |name| {
const suffix: []const u8 = if (slashHasParams(name)) " " else "";
addPrefixedCompletion(cenv, &buf, input, "/", name, suffix, partial);
@@ -527,8 +526,8 @@ fn completionCallback(cenv: ?*c.ic_completion_env_t, prefix: [*c]const u8) callc
}
// File-scope so the buffer outlives the callback's stack frame. Isocline's
-// `sbuf_replace` copies the returned string into its own stringbuf, so it's
-// safe to overwrite this on the next invocation. Single-threaded — isocline's
+// `sbuf_replace` copies the returned string into its own stringbuf, so
+// overwriting this on the next invocation is safe. Single-threaded: isocline's
// edit loop runs on the main thread, and we have one Terminal instance.
var hint_buf: [completion_buf_len:0]u8 = undefined;
@@ -567,8 +566,7 @@ fn hintsCallback(input_c: [*c]const u8, arg: ?*anyopaque) callconv(.c) [*c]const
/// Join `fragments` into `hint_buf` with single-space separators, prefixed by
/// `lead` (typically `""` or `" "`). Null-terminates and returns the isocline
-/// C pointer, or null when there's nothing to render or the buffer would
-/// overflow.
+/// C pointer, or null when nothing to render or the buffer would overflow.
fn writeHints(lead: []const u8, fragments: []const []const u8) [*c]const u8 {
if (fragments.len == 0) return null;
const cap = hint_buf.len - 1;
@@ -653,8 +651,8 @@ fn ghostFirstMatch(names: []const []const u8, body: []const u8, lead: []const u8
/// `<keyname>=…` when the user is typing a key prefix.
fn renderSchemaHint(schema: *const Schema, body: []const u8, ends_ws: bool) [*c]const u8 {
// Ghost a matching enum value once the user is typing one. A bare leading
- // positional with nothing typed yet keeps the `<state> …` template below,
- // which is more informative than ghosting one arbitrary value.
+ // positional with nothing typed keeps the `<state> …` template below — more
+ // informative than ghosting one arbitrary value.
if (valueAt(schema, body, ends_ws)) |v| {
if (v.field.enum_values.len > 0 and (v.kv or v.partial.len > 0)) {
return ghostFirstMatch(v.field.enum_values, v.partial, "");
@@ -705,7 +703,7 @@ fn highlighterCallback(henv: ?*c.ic_highlight_env_t, input: [*c]const u8, arg: ?
var i = cmd_start;
while (i < text.len and !std.ascii.isWhitespace(text[i])) i += 1;
const cmd = text[cmd_start..i];
- // Commit to red once the user has moved past the token, OR as soon as the
+ // Commit to red once the cursor moves past the token, OR as soon as the
// prefix cannot complete to any known name.
const closed = i < text.len;
if (cmd.len > 0 and cmd[0] == '/') {
@@ -723,8 +721,7 @@ fn highlighterCallback(henv: ?*c.ic_highlight_env_t, input: [*c]const u8, arg: ?
highlightSlashArgs(henv, text, i);
} else {
// No leading `/`: a natural-language prompt, so no command validation.
- // Start at `cmd_start`, not `i` — a `$LP_*` as the first token must
- // highlight too.
+ // Start at `cmd_start`, not `i`, so a `$LP_*` first token highlights too.
highlightDollarVars(henv, text, cmd_start);
}
}
@@ -831,9 +828,8 @@ fn highlightDollarVarsIn(henv: ?*c.ic_highlight_env_t, text: []const u8, start:
if (i > tok_start + 1) {
c.ic_highlight(henv, @intCast(tok_start), @intCast(i - tok_start), style_var.ptr);
}
- // Don't post-step — the inner loop already landed on the char
- // after the identifier (or end-of-text). Auto-advancing would
- // skip an adjacent `$LP_*`.
+ // Don't post-step: the inner loop already landed on the char after the
+ // identifier (or end-of-text); auto-advancing would skip an adjacent `$LP_*`.
}
}
@@ -942,8 +938,8 @@ fn highlightSlashArgs(henv: ?*c.ic_highlight_env_t, text: []const u8, start: usi
pub fn readLine(prompt: [*:0]const u8) ?[]const u8 {
// Kitty-keyboard "disambiguate" (Ctrl+Enter as a distinct CSI-u, not bare
// \r) only while isocline reads: while active, Ctrl-C arrives as a CSI-u
- // escape, not a raw \x03, so the tty driver raises no SIGINT — leaving it on
- // during thinking/tool runs would make Ctrl-C unable to interrupt them.
+ // escape rather than raw \x03, so the tty driver raises no SIGINT. Leaving
+ // it on during thinking/tool runs would make Ctrl-C unable to interrupt them.
_ = std.posix.write(std.posix.STDOUT_FILENO, "\x1b[>1u") catch {};
defer _ = std.posix.write(std.posix.STDOUT_FILENO, "\x1b[<u") catch {};
// Isocline auto-appends the line to its (optionally-persisted) history.
@@ -983,13 +979,13 @@ fn logSink(bytes: []const u8) void {
/// Current terminal width in columns, queried via TIOCGWINSZ on stderr.
/// Null when stderr isn't a tty, the ioctl fails, or the kernel reports 0
-/// (some pseudo-ttys leave the field unset). Cheap enough to call per
-/// render frame — picks up resizes without SIGWINCH plumbing.
+/// (some pseudo-ttys leave the field unset). Cheap enough to call per render
+/// frame; picks up resizes without SIGWINCH plumbing.
pub fn columns() ?u16 {
var ws: std.posix.winsize = undefined;
// bitcast via c_uint: on archs where `_IOR` sets the direction bit
- // (MIPS/PPC/SPARC), `IOCGWINSZ` exceeds i32 range — a plain @intCast
- // panics there. The bitcast preserves the bit pattern.
+ // (MIPS/PPC/SPARC), `IOCGWINSZ` exceeds i32 range, so a plain @intCast
+ // panics; the bitcast preserves the bit pattern.
const req: c_int = @bitCast(@as(c_uint, std.posix.T.IOCGWINSZ));
const rc = std.c.ioctl(std.posix.STDERR_FILENO, req, &ws);
if (rc != 0 or ws.col == 0) return null;
@@ -997,7 +993,7 @@ pub fn columns() ?u16 {
}
/// Erase the frame after an empty submit. The bars collapse on submit, leaving
-/// the spacing and prompt lines with the cursor one line below; move up two and
+/// the spacing and prompt lines with the cursor one line below; move up two,
/// clear to end of screen.
pub fn clearPromptFrame(self: *Terminal) void {
if (!self.isRepl()) return;
@@ -1279,16 +1275,16 @@ pub fn printAssistant(_: *Terminal, text: []const u8) void {
_ = std.posix.write(fd, "\n") catch {};
}
-// Must exceed the downstream LLM-judge's snapshot window so it has full
-// grounding evidence. Does not cap the agent's own LLM, which gets up to
-// tool_output_max_bytes (1 MiB) via Agent.zig:capToolOutput. Bypassed in
-// REPL where the human can scroll.
+// Must exceed the downstream LLM-judge's snapshot window for full grounding
+// evidence. Does not cap the agent's own LLM, which gets up to
+// tool_output_max_bytes (1 MiB) via Agent.zig:capToolOutput. Bypassed in REPL
+// where the human can scroll.
const max_result_display_len = 2000;
/// Tool-outcome line shared by REPL slash commands and LLM tool calls.
/// REPL: green ● on success, red ● on error. Non-REPL prefixes `[result:
-/// name]`; success gates on `medium+`, errors bypass the gate so a
-/// failing script still surfaces *why* at the default verbosity.
+/// name]`; success gates on `medium+`, errors bypass the gate so a failing
+/// script still surfaces *why* at default verbosity.
pub fn printToolOutcome(self: *Terminal, name: []const u8, text: []const u8, is_error: bool) void {
if (self.repl_arena) |*a| {
defer _ = a.reset(.retain_capacity);
@@ -1331,9 +1327,9 @@ pub fn reindentJson(arena: std.mem.Allocator, text: []const u8) ?[]const u8 {
return aw.written();
}
-/// REPL outcome line: colored ● marker followed by the body, pretty-printed
-/// if JSON. Builds the entire payload in the arena so callers can route it
-/// past the spinner (`emitAbove`) without interleaving with frame writes.
+/// REPL outcome line: colored ● marker followed by the body, pretty-printed if
+/// JSON. Builds the whole payload in the arena so callers can route it past the
+/// spinner (`emitAbove`) without interleaving with frame writes.
fn formatReplOutcome(arena: std.mem.Allocator, text: []const u8, is_error: bool) ![]const u8 {
var aw: std.Io.Writer.Allocating = .init(arena);
const w = &aw.writer;
diff --git a/src/agent/settings.zig b/src/agent/settings.zig
index 25335c8c5..5041f9001 100644
--- a/src/agent/settings.zig
+++ b/src/agent/settings.zig
@@ -110,11 +110,11 @@ pub fn resolveCredentials(allocator: std.mem.Allocator, opts: Config.Agent, reme
pub const remembered_path = ".lp-agent.zon";
/// Last user-selected provider/model/effort/verbosity, persisted per-directory
-/// in `.lp-agent.zon`. `model` is owned by the caller. A null `provider` means
-/// the user disabled the LLM (`/provider null`), so the REPL starts in basic
-/// mode without re-prompting. `effort` and `verbosity` are optional so files
-/// written before they existed still parse; null means "use the mode default"
-/// (see `Agent.resolveEffort` / `Agent.resolveVerbosity`).
+/// in `.lp-agent.zon`. `model` is caller-owned. A null `provider` means the user
+/// disabled the LLM (`/provider null`), so the REPL starts in basic mode without
+/// re-prompting. `effort`/`verbosity` are optional so files predating them still
+/// parse; null means "use the mode default" (see `Agent.resolveEffort` /
+/// `Agent.resolveVerbosity`).
pub const Remembered = struct {
provider: ?Config.AiProvider = null,
model: []const u8,
@@ -185,10 +185,10 @@ pub const ReconciledModel = union(enum) {
};
/// Validate `desired` against the provider's catalog, mirroring the interactive
-/// `/model` command. An unreachable server (empty list) leaves it unchecked.
-/// An explicit model that isn't listed is fatal. Ollama's local catalog is
-/// authoritative, so its default is substituted when not pulled; cloud defaults
-/// are hardcoded real models and trusted as-is.
+/// `/model` command. Empty list (unreachable server) leaves it unchecked; an
+/// explicit unlisted model is fatal. Ollama's local catalog is authoritative, so
+/// its default is substituted when not pulled; cloud defaults are hardcoded real
+/// models, trusted as-is.
pub fn reconcileModel(
allocator: std.mem.Allocator,
llm: Credentials,
diff --git a/src/agent/welcome.zig b/src/agent/welcome.zig
index 388b937d8..c6169fba1 100644
--- a/src/agent/welcome.zig
+++ b/src/agent/welcome.zig
@@ -54,9 +54,9 @@ const logo_rows = blk: {
};
const welcome_gap = " ";
-/// Banner text. Kept narrow enough that the logo + gap + the widest line fits in
-/// 80 columns (asserted at comptime below), so the banner always shows in full
-/// and never needs to measure the terminal or shed the logo.
+/// Banner text. Kept narrow enough that logo + gap + widest line fits in 80
+/// columns (asserted at comptime below), so the banner always shows in full
+/// without measuring the terminal or shedding the logo.
const banner_tagline_llm = "Control the browser with natural language";
const banner_tagline_basic = "Basic REPL (--no-llm) — commands only";
const banner_setup = "Set an API key, then run /provider <name>";