Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

refactor: break main.zig re-export hub so every file is <=600 lines (600-line goal complete)

justrach981c226727b5
diff --git a/src/agent.zig b/src/agent.zig
index a964e19f..efd48536 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -22,7 +22,8 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const Provider = main_mod.Provider;
+const provider_mod = @import("provider.zig");
+const Provider = provider_mod.Provider;
const ReasoningEffort = main_mod.ReasoningEffort;
const mcp = @import("mcp.zig");
diff --git a/src/agent_argstream.zig b/src/agent_argstream.zig
index d5caa3b7..60c72302 100644
--- a/src/agent_argstream.zig
+++ b/src/agent_argstream.zig
@@ -9,8 +9,10 @@ const std = @import("std");
const Io = std.Io;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const ToolCall = main_mod.ToolCall;
+const agent_mod = @import("agent.zig");
+const tools_mod = @import("tools.zig");
+const Agent = agent_mod.Agent;
+const ToolCall = tools_mod.ToolCall;
// sseIndex lives in agent_stream.zig; reached through the Agent struct's
// member alias.
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index a73a20ac..231bfa94 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -9,10 +9,12 @@ const Io = std.Io;
const Value = std.json.Value;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const ToolCall = main_mod.ToolCall;
+const agent_mod = @import("agent.zig");
+const repl_glue = @import("repl_glue.zig");
+const Agent = agent_mod.Agent;
+const ToolCall = tools_mod.ToolCall;
const ExecResult = tools_mod.ExecResult;
-const parseEvalScore = main_mod.parseEvalScore;
+const parseEvalScore = repl_glue.parseEvalScore;
const prompts = @import("prompts.zig");
const compact_instruction = prompts.compact_instruction;
diff --git a/src/agent_interrupt.zig b/src/agent_interrupt.zig
index 6a73981b..7096716c 100644
--- a/src/agent_interrupt.zig
+++ b/src/agent_interrupt.zig
@@ -17,7 +17,9 @@ const std = @import("std");
const Io = std.Io;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
+const agent_mod = @import("agent.zig");
+const repl_glue = @import("repl_glue.zig");
+const Agent = agent_mod.Agent;
const terminal = @import("term.zig");
const tty = terminal.tty;
@@ -121,7 +123,7 @@ pub fn escPressed(echo: bool) bool {
if (echo and main_mod.g_steer_echoed) {
var qbuf: [64]u8 = undefined;
const qmsg = std.fmt.bufPrint(&qbuf, " \x1b[2m[queued · {d} waiting]\x1b[0m\n", .{main_mod.g_steer_queue.items.len}) catch "\n";
- main_mod.steerEcho(qmsg);
+ repl_glue.steerEcho(qmsg);
}
} else if (main_mod.g_steer_queue.items.len > 0) {
// Double-enter (empty line + queue non-empty): force —
@@ -131,8 +133,8 @@ pub fn escPressed(echo: bool) bool {
esc_found = true;
main_mod.g_force_interrupt = true;
if (echo) {
- if (main_mod.g_steer_echoed) main_mod.steerEcho("\n");
- main_mod.steerEcho("\x1b[33m↳ force › interrupting…\x1b[0m\n");
+ if (main_mod.g_steer_echoed) repl_glue.steerEcho("\n");
+ repl_glue.steerEcho("\x1b[33m↳ force › interrupting…\x1b[0m\n");
}
}
main_mod.g_steer_echoed = false;
@@ -141,7 +143,7 @@ pub fn escPressed(echo: bool) bool {
} else if (c == 0x7f or c == 0x08) { // backspace / Ctrl-H
if (main_mod.g_steer_buf.items.len > 0) {
_ = main_mod.g_steer_buf.pop();
- if (echo) main_mod.steerEcho("\x08 \x08");
+ if (echo) repl_glue.steerEcho("\x08 \x08");
}
continue;
} else if (c == 0x14) { // Ctrl-T: fold/unfold the live Thinking block (#92)
@@ -154,10 +156,10 @@ pub fn escPressed(echo: bool) bool {
if (echo) {
if (!main_mod.g_steer_echoed) {
main_mod.g_steer_visible.store(true, .release);
- main_mod.steerEcho("\n\x1b[36m↳ steer ›\x1b[0m ");
+ repl_glue.steerEcho("\n\x1b[36m↳ steer ›\x1b[0m ");
main_mod.g_steer_echoed = true;
}
- main_mod.steerEcho(buf[i .. i + 1]);
+ repl_glue.steerEcho(buf[i .. i + 1]);
}
}
return esc_found;
diff --git a/src/agent_render.zig b/src/agent_render.zig
index b6c26c40..ad8f96fd 100644
--- a/src/agent_render.zig
+++ b/src/agent_render.zig
@@ -10,7 +10,8 @@ const std = @import("std");
const Io = std.Io;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
const ansi = @import("ansi.zig");
const style = &ansi.style;
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 789a4495..88a9f95a 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -13,7 +13,8 @@ const Io = std.Io;
const Value = std.json.Value;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
const max_tokens = main_mod.max_tokens;
const pricing = @import("pricing.zig");
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 973d2244..d0b794bc 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -12,8 +12,10 @@ const std = @import("std");
const Value = std.json.Value;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const ToolCall = main_mod.ToolCall;
+const agent_mod = @import("agent.zig");
+const tools_mod = @import("tools.zig");
+const Agent = agent_mod.Agent;
+const ToolCall = tools_mod.ToolCall;
const messages_mod = @import("messages.zig");
const toolResultMessage = messages_mod.toolResultMessage;
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index a895e5ad..82cc5ce7 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -17,7 +17,8 @@ const Io = std.Io;
const Value = std.json.Value;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
const ansi = @import("ansi.zig");
const style = &ansi.style;
diff --git a/src/agent_table.zig b/src/agent_table.zig
index 922f81a9..8721d2f3 100644
--- a/src/agent_table.zig
+++ b/src/agent_table.zig
@@ -8,7 +8,8 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
const ansi = @import("ansi.zig");
const style = &ansi.style;
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index f14336a3..1e9ae5a7 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -11,8 +11,9 @@ const Io = std.Io;
const Value = std.json.Value;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const ToolCall = main_mod.ToolCall;
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+const ToolCall = tools_mod.ToolCall;
const ExecResult = tools_mod.ExecResult;
const AnswerRequest = tools_mod.AnswerRequest;
diff --git a/src/anim.zig b/src/anim.zig
index dbbe4c49..65dc86bc 100644
--- a/src/anim.zig
+++ b/src/anim.zig
@@ -16,7 +16,8 @@ const ansi = @import("ansi.zig");
const style = &ansi.style;
const root = @import("main.zig");
-const Approvals = root.Approvals;
+const approvals_mod = @import("approvals.zig");
+const Approvals = approvals_mod.Approvals;
// Named single-line indicators for the model-wait spinner, ported in spirit
// from arpagon/pi-animations (MIT). Plain Unicode + ANSI 256-color only (no
diff --git a/src/cards.zig b/src/cards.zig
index 99177492..38d34695 100644
--- a/src/cards.zig
+++ b/src/cards.zig
@@ -17,7 +17,8 @@ const term = @import("term.zig");
const termCols = term.termCols;
const root = @import("main.zig");
-const utf8Prefix = root.utf8Prefix;
+const util = @import("util.zig");
+const utf8Prefix = util.utf8Prefix;
// ── Subagent cards (#51) ───────────────────────────────────────────────────
//
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index a251bbab..759ff382 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -9,14 +9,17 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const provider_specs = main_mod.provider_specs;
-const Agent = main_mod.Agent;
-const Keys = main_mod.Keys;
-const utf8Prefix = main_mod.utf8Prefix;
+const provider_mod = @import("provider.zig");
+const agent_mod = @import("agent.zig");
+const util = @import("util.zig");
+const provider_specs = provider_mod.provider_specs;
+const Agent = agent_mod.Agent;
+const Keys = provider_mod.Keys;
+const utf8Prefix = util.utf8Prefix;
const harness_version = main_mod.harness_version;
const mcp_config_path = main_mod.mcp_config_path;
-const session_ext = main_mod.session_ext;
-const saveSession = main_mod.saveSession;
+const session_ext = session.session_ext;
+const saveSession = session.saveSession;
const session = @import("session.zig");
const loadSession = session.loadSession;
const listSavedSessions = session.listSavedSessions;
diff --git a/src/commands_model.zig b/src/commands_model.zig
index 07033800..ef26cda5 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -12,10 +12,12 @@ const builtin = @import("builtin");
const ansi = @import("ansi.zig");
const style = &ansi.style;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Keys = main_mod.Keys;
-const provider_specs = main_mod.provider_specs;
-const storeKey = main_mod.storeKey;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const Agent = agent_mod.Agent;
+const Keys = provider_mod.Keys;
+const provider_specs = provider_mod.provider_specs;
+const storeKey = keys_cli.storeKey;
const repl_glue = @import("repl_glue.zig");
const saveThinkingSettings = repl_glue.saveThinkingSettings;
const keys_cli = @import("keys_cli.zig");
diff --git a/src/commands_session.zig b/src/commands_session.zig
index bf538651..3e9bfc30 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -8,13 +8,18 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Keys = main_mod.Keys;
-const ToolCall = main_mod.ToolCall;
-const saveSession = main_mod.saveSession;
-const unixMs = main_mod.unixMs;
-const utf8Prefix = main_mod.utf8Prefix;
-const session_ext = main_mod.session_ext;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const util = @import("util.zig");
+const tools_mod = @import("tools.zig");
+const session_mod = @import("session.zig");
+const Agent = agent_mod.Agent;
+const Keys = provider_mod.Keys;
+const ToolCall = tools_mod.ToolCall;
+const saveSession = session_mod.saveSession;
+const unixMs = util.unixMs;
+const utf8Prefix = util.utf8Prefix;
+const session_ext = session_mod.session_ext;
const ansi = @import("ansi.zig");
const style = &ansi.style;
diff --git a/src/exec.zig b/src/exec.zig
index 250da01b..bddd45b7 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -13,7 +13,8 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const ToolCall = main_mod.ToolCall;
+const util = @import("util.zig");
+const ToolCall = tools.ToolCall;
const tools = @import("tools.zig");
const ToolCtx = tools.ToolCtx;
@@ -238,7 +239,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// API calls. Cap what reaches the model and point it at targeted reads.
if (text.len > codedb_result_cap) {
defer gpa.free(text);
- const head = main_mod.utf8Prefix(text, codedb_result_cap);
+ const head = util.utf8Prefix(text, codedb_result_cap);
return .{ .text = try std.fmt.allocPrint(gpa, "{s}\n[codedb output truncated at {d} KB — prefer targeted queries: outline <path>, symbol <name> --body, or search, instead of whole-file reads]", .{ head, codedb_result_cap / 1024 }) };
}
return .{ .text = text };
diff --git a/src/fleet.zig b/src/fleet.zig
index 88e792f3..318badfb 100644
--- a/src/fleet.zig
+++ b/src/fleet.zig
@@ -17,8 +17,10 @@ const util = @import("util.zig");
const strFieldObj = util.strFieldObj;
const root = @import("main.zig");
-const Telemetry = root.Telemetry;
-const trajectory_path = root.trajectory_path;
+const trace = @import("trace.zig");
+const telemetry_mod = @import("telemetry.zig");
+const Telemetry = telemetry_mod.Telemetry;
+const trajectory_path = trace.trajectory_path;
// ── Agent types (the MAP-Elites niches) ─────────────────────────────────────
diff --git a/src/hooks.zig b/src/hooks.zig
index 15ff245f..1df4e454 100644
--- a/src/hooks.zig
+++ b/src/hooks.zig
@@ -15,8 +15,10 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const root = @import("main.zig");
-const Approvals = root.Approvals;
-const win = root.win;
+const approvals_mod = @import("approvals.zig");
+const terminal = @import("term.zig");
+const Approvals = approvals_mod.Approvals;
+const win = terminal.win;
/// Lifecycle hooks (codex/Claude-style), loaded once at startup from
/// .harness/settings.json's "hooks" object. Three events:
diff --git a/src/http.zig b/src/http.zig
index 94c66bcb..2b17bbf4 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -10,8 +10,10 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const root = @import("main.zig");
-const Provider = root.Provider;
-const Agent = root.Agent;
+const provider_mod = @import("provider.zig");
+const agent_mod = @import("agent.zig");
+const Provider = provider_mod.Provider;
+const Agent = agent_mod.Agent;
const anthropic_version = root.anthropic_version;
const kimi_user_agent = root.kimi_user_agent;
diff --git a/src/input_util.zig b/src/input_util.zig
index 929039e7..b95c91f8 100644
--- a/src/input_util.zig
+++ b/src/input_util.zig
@@ -25,9 +25,11 @@ const pricing = @import("pricing.zig");
const model_table = pricing.model_table;
const main_mod = @import("main.zig");
-const provider_specs = main_mod.provider_specs;
+const provider_mod = @import("provider.zig");
+const tools_mod = @import("tools.zig");
+const provider_specs = provider_mod.provider_specs;
const repl_commands = main_mod.repl_commands;
-const bash_stdout_cap = main_mod.bash_stdout_cap;
+const bash_stdout_cap = tools_mod.bash_stdout_cap;
pub var g_shine_phase: usize = 0; // ultracode input-wave animation frame
diff --git a/src/jobs.zig b/src/jobs.zig
index fd876ebf..8bdffb2f 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -11,8 +11,10 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const root = @import("main.zig");
-const ToolOutput = root.ToolOutput;
-const Agent = root.Agent;
+const agent_mod = @import("agent.zig");
+const tools_mod = @import("tools.zig");
+const ToolOutput = tools_mod.ToolOutput;
+const Agent = agent_mod.Agent;
const CappedRun = struct {
term: std.process.Child.Term,
diff --git a/src/keys_cli.zig b/src/keys_cli.zig
index 424547ff..4a32a73e 100644
--- a/src/keys_cli.zig
+++ b/src/keys_cli.zig
@@ -18,7 +18,8 @@ const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const main_mod = @import("main.zig");
-const provider_specs = main_mod.provider_specs;
+const provider_mod = @import("provider.zig");
+const provider_specs = provider_mod.provider_specs;
const util = @import("util.zig");
const strFieldObj = util.strFieldObj;
diff --git a/src/main.zig b/src/main.zig
index 88c0bcf1..2fe4c1a0 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -35,19 +35,19 @@ const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const mcp = @import("mcp.zig");
-// The interactive-REPL / --json-protocol turn loop that used to be the tail
-// of main() lives in mainloop.zig (600-line goal); main() just builds a
-// mainloop.Ctx of pointers into its own stack locals and calls run() once.
+// The interactive-REPL / --json-protocol turn loop lives in mainloop.zig;
+// main() just builds a mainloop.Ctx of pointers into its own stack locals
+// and calls run() once.
const mainloop = @import("mainloop.zig");
const builtin = @import("builtin");
// The Agent struct's method bodies are split across agent_*.zig sibling
-// files (#123, 600-line goal) as free `pub fn method(self: *Agent, ...)`
-// functions, member-aliased back inside `struct Agent` (`pub const method =
-// @import("agent_x.zig").method;`) so both `self.method(...)` and static
-// `Agent.method(...)` test calls resolve unchanged. Referenced here only to
-// keep their test blocks running (see the root test{} block below).
+// files as free `pub fn method(self: *Agent, ...)` functions, member-aliased
+// back inside `struct Agent` (`pub const method = @import("agent_x.zig").method;`)
+// so both `self.method(...)` and static `Agent.method(...)` calls resolve
+// unchanged. Imported here only to keep their test blocks running (see the
+// root test{} block below).
const agent_table = @import("agent_table.zig");
const agent_argstream = @import("agent_argstream.zig");
const agent_render = @import("agent_render.zig");
@@ -62,11 +62,10 @@ pub const anthropic_version = "2023-06-01";
pub const max_tokens = 16000;
pub const mcp_config_path = ".mcp.json";
-// The terminal color palette lives in ansi.zig (a std-only leaf) so the
-// spinner, streaming markdown renderer, and other UI code share one palette
-// (#123). `style` is a pointer alias into ansi.style, so the ~200 `style.field`
-// reads across this file auto-deref the live palette; main flips ansi.style to
-// Style.ansi at startup once it confirms stdout is a TTY with color enabled.
+// The terminal color palette lives in ansi.zig. `style` is a pointer alias
+// into ansi.style, so the ~200 `style.field` reads across this file
+// auto-deref the live palette; main flips ansi.style to Style.ansi at
+// startup once it confirms stdout is a TTY with color enabled.
const ansi = @import("ansi.zig");
pub var use_color = false; // stdout is a TTY and NO_COLOR unset → enables color + markdown
@@ -79,18 +78,12 @@ pub var dedupe_tool_calls = false; // --dedupe-tool-calls: reject duplicate root
pub var plan_mode = false; // /plan: read-only — mutating tools are denied, the model proposes
pub var unattended = false; // -p one-shot: no human to prompt; unapproved tool calls are denied
-// Model pricing/catalog + the session cost tally live in pricing.zig (#123).
-// Aliased here so the existing call sites read unchanged; later split slices
-// can migrate call sites to `pricing.` and drop these.
-const pricing = @import("pricing.zig");
-
-// Pure shared helpers (JSON ObjectMap getters) live in util.zig (#123). Aliased
-// so the ~50 existing strFieldObj/intFieldObj call sites stay unqualified.
-const util = @import("util.zig");
+const pricing = @import("pricing.zig"); // model pricing/catalog + session cost tally
+const util = @import("util.zig"); // shared JSON ObjectMap getters (strFieldObj/intFieldObj)
test {
- // build.zig's unit_tests root is main.zig only — reference split-out
- // modules here so their test blocks keep running (#123 watch-out).
+ // build.zig's unit_tests root is main.zig only — reference every
+ // split-out module here so their test blocks keep running.
_ = pricing;
_ = ansi;
_ = serve;
@@ -148,136 +141,91 @@ test {
_ = agent_mod;
}
-pub const provider_specs = provider_mod.provider_specs;
-
-// System-prompt text (main_system_prompt, strict_note,
-// main_system_prompt_strict, sub_system_prompt, compact_instruction) lives in
-// prompts.zig (600-line goal, #123). All aliased back — the Agent struct's
-// default field values and main()'s prompt-selection logic read unchanged.
-// compact_instruction is repointed to a direct prompts.zig import at its
-// one remaining consumer, agent_compact.zig.
+// System-prompt text (main_system_prompt, strict_note, main_system_prompt_strict,
+// sub_system_prompt, compact_instruction) lives in prompts.zig.
const prompts = @import("prompts.zig");
-// -------------------------------------------------------------------------
-// Tool-schema + provider-tool JSON emission (the ToolSpec catalog, per-provider
-// tool renderers, and emitSchema) lives in schema.zig (#123). Aliased back so
-// the existing call sites stay unqualified; emitSchema + schema_version are
-// re-exported (pub) for serve.zig's back-import.
+// Tool-schema + provider-tool JSON emission lives in schema.zig; serve.zig
+// and startup.zig import it directly. Kept here to pull in its test{} block.
const schema = @import("schema.zig");
-pub const emitSchema = schema.emitSchema;
-pub const schema_version = schema.schema_version;
-// -------------------------------------------------------------------------
// The provider/keys core (ProviderSpec/provider_specs, Provider, Keys) lives
-// in provider.zig (600-line goal). Re-exported so the ~everywhere
-// `main_mod.Provider`/`main_mod.Keys`/`main_mod.provider_specs` back-imports
-// across the other split files keep resolving unchanged regardless of
-// physical file.
+// in provider.zig. provider_specs/Keys stay local aliases — main()'s own
+// credential setup and tests still read them directly.
const provider_mod = @import("provider.zig");
-pub const Provider = provider_mod.Provider;
-pub const Keys = provider_mod.Keys;
+const provider_specs = provider_mod.provider_specs;
+const Keys = provider_mod.Keys;
-// Approvals (command/tool approval gate) + confinedPath/noSymlinkEscape live in
-// approvals.zig (#123). Re-exported here so `Approvals.*`, the two path-gate
-// helpers, and anim.zig's `root.Approvals` back-import resolve unchanged.
+// Approvals (command/tool approval gate) + confinedPath/noSymlinkEscape live
+// in approvals.zig. main() constructs one directly for the session.
const approvals_mod = @import("approvals.zig");
-pub const Approvals = approvals_mod.Approvals;
+const Approvals = approvals_mod.Approvals;
// Session tracing (harness.trace.jsonl Tracer) + the DGM trajectory archive
// (harness.trajectory.jsonl Trajectory) + the per-line JSON writer live in
-// trace.zig (600-line goal). Types aliased back; trajectory_path re-exported
-// (fleet.zig back-imports it); the session trajectory pointer is trace.-qualified.
+// trace.zig. main() constructs a Tracer/Trajectory directly; trajectory_path
+// locates the archive file.
const trace = @import("trace.zig");
-pub const Tracer = trace.Tracer;
-pub const Trajectory = trace.Trajectory;
-pub const trajectory_path = trace.trajectory_path;
-pub const ToolSink = trace.ToolSink;
+const Tracer = trace.Tracer;
+const Trajectory = trace.Trajectory;
+const trajectory_path = trace.trajectory_path;
const trace_path = trace.trace_path;
// ── Agent types / fleet (MAP-Elites niches) ───────────────────────────
-// The AgentType niche registry, the backgrounded elite pull, /agents promote,
-// and the niche/override resolvers live in fleet.zig (#123). The functions are
-// aliased back so call sites stay unqualified; the session agent-type globals
-// (the session agent-type state) moved with it and are
-// reached fleet.-qualified.
+// The AgentType niche registry, the backgrounded elite pull, /agents
+// promote, and the niche/override resolvers live in fleet.zig, aliased back
+// so call sites stay unqualified.
const fleet = @import("fleet.zig");
const joinElites = fleet.joinElites;
-// Prompt/provider-class fingerprinting + DGM score signing live in scoring.zig
-// (600-line goal). Pure fns aliased back; the signing globals are
-// scoring.-qualified at their call sites.
+// Prompt/provider-class fingerprinting + DGM score signing live in scoring.zig.
const scoring = @import("scoring.zig");
// ── Subagent cards (#51) ────────────────────────────────────────
// The parallel-subagent launch/done cards + box helpers + the inspect-report
-// writer live in cards.zig (600-line goal). Renderers aliased back; the
-// subagent-ordinal counter is reached cards.-qualified.
+// writer live in cards.zig.
const cards = @import("cards.zig");
-// Score-channel signing (DGM fitness integrity) + the session signing globals
-// live in scoring.zig (600-line goal); reached scoring.-qualified.
-
-// ToolSink (the per-agent tool-call log) lives in trace.zig (600-line goal).
-
-// utf8Prefix moved to util.zig (600-line goal); re-exported since
-// it's back-imported nearly everywhere as main_mod.utf8Prefix.
-pub const utf8Prefix = util.utf8Prefix;
-
// ── Telemetry (OTEL) ───────────────────────────────────────────
-// The Telemetry sink + its session-global pointer live in telemetry.zig
-// (600-line goal). Telemetry is re-exported (fleet.zig back-imports it); the
-// sink pointer is reached telemetry.-qualified at its call sites.
+// The Telemetry sink lives in telemetry.zig; the session-global pointer is
+// reached telemetry.-qualified at its call sites.
const telemetry = @import("telemetry.zig");
-pub const Telemetry = telemetry.Telemetry;
/// Federated-fleet contribution toggle (docs/hyperagents.md §9). On by default;
/// GRAFF_FLEET=off or /fleet off disables propose/submit/elite_pull. General
/// usage telemetry is separate (GRAFF_NO_TELEMETRY).
pub var g_fleet: bool = true;
-// unixMs moved to util.zig (600-line goal), re-exported since it's
-// back-imported nearly everywhere as main_mod.unixMs. loadOrCreateId moved
-// to keys_cli.zig instead; its only caller is the telemetry-init block
-// below, which calls keys_cli.loadOrCreateId directly.
-pub const unixMs = util.unixMs;
+const unixMs = util.unixMs;
/// Reasoning depth for codex/responses (OpenAI Responses `reasoning.effort`).
pub const ReasoningEffort = enum { low, medium, high };
pub const repl_commands = [_][]const u8{ "/model", "/models", "/clear", "/new", "/rename", "/goal", "/loop", "/bash", "/plan", "/key", "/keepcontext", "/effort", "/fast", "/ultracode", "/thinking", "/title", "/reasoning", "/strict", "/yolo", "/trace", "/fleet", "/trajectory", "/agents", "/skills", "/hooks", "/compact", "/rewind", "/image", "/paste", "/save", "/resume", "/sessions", "/todo", "/jobs", "/cost", "/animation", "/theme", "/mcp", "/help" };
-// isSlashCommandLine moved to repl_glue.zig (600-line goal); re-exported
-// since mainloop.zig back-imports it as main_mod.isSlashCommandLine.
-pub const isSlashCommandLine = repl_glue.isSlashCommandLine;
-
// Lifecycle hooks (Hook/Hooks config types + settings loader + per-hook
-// subprocess runner) live in hooks.zig (#123). g_hooks below, the
-// pre/post/turn-end dispatch, and the codedb-guard file-index cache stay here.
+// subprocess runner) live in hooks.zig. g_hooks below, the pre/post/turn-end
+// dispatch, and the codedb-guard file-index cache stay here.
const hooks = @import("hooks.zig");
pub var g_hooks: hooks.Hooks = .{};
-/// Built-in codedb guard (issue #626): when a repo is codedb-indexed, agents
-/// reflexively grep/sed/cat source files and never touch the structural tools,
-/// so codedb degrades to "ripgrep with smaller output." When on, a bash command
-/// that scans/reads a concrete source file is blocked with a redirect to the
-/// codedb tool. Off when GRAFF_NO_CODEDB_GUARD is set; the tri-state cache
-/// records whether `codedb` is actually on PATH (no redirect if it isn't).
+/// Built-in codedb guard (issue #626): blocks a bash command that scans/reads
+/// a concrete source file, redirecting to the codedb tool instead — without
+/// this, agents reflexively grep/cat and never touch the structural tools.
+/// Off when GRAFF_NO_CODEDB_GUARD is set; the tri-state cache records
+/// whether `codedb` is actually on PATH (no redirect if it isn't).
pub var g_codedb_guard = true;
pub var g_codedb_present: ?bool = null;
-// Codex-style optional skills / companion-server subsystem (skills_registry,
-// companion_servers, mcp_notes, install-status + opt-out helpers, the
-// companion tool-name classifiers, and the codedbpro license probe + note
-// picker) lives in skills.zig (600-line goal). companionRoute and
-// companionNativeFallback moved to tools.zig (they take ToolCtx/ToolCall —
-// the tools/exec region). g_path_env/g_skill_disabled/g_companion_disabled
-// stay `pub var` here (main's own /skills command handler + startup code
-// read/write them directly too); skills.zig reads/writes them live via
-// main_mod.g_x, never by-value.
+// Codex-style optional skills / companion-server subsystem lives in
+// skills.zig. companionRoute/companionNativeFallback stay in tools.zig
+// (they take ToolCtx/ToolCall). g_path_env/g_skill_disabled/
+// g_companion_disabled stay `pub var` here — skills.zig reads/writes them
+// live via main_mod.g_x, never by-value.
const skills = @import("skills.zig");
const skills_registry = skills.skills_registry;
-pub const companion_servers = skills.companion_servers;
+const companion_servers = skills.companion_servers;
const mcpServerConnected = skills.mcpServerConnected;
const probeCodedbproLicensed = skills.probeCodedbproLicensed;
@@ -291,32 +239,17 @@ pub var g_worktree_autocommit: bool = true; // --no-autocommit turns off the per
/// Short task label for terminal/TUI headers. Mirrors the GUI's first-prompt
/// fallback: use the user's first message as a compact tab/session title.
// Session-title + header rendering + provider-response text parsers live in
-// title.zig (600-line goal). All 9 helpers aliased back so call sites (incl.
-// the Agent-coupled titleTask below) stay unqualified.
+// title.zig.
const title_mod = @import("title.zig");
-// titleTask moved to title.zig (600-line goal); re-exported since main()'s
-// own `graff title` subcommand and mainloop.zig both call it unqualified /
-// as main_mod.titleTask.
-pub const titleTask = title_mod.titleTask;
-
/// Opaque context handed to repl.run so the REPL can run a real agent turn —
/// reuses the root agent's tool set, MCP registry, and system prompt (built in
/// main()). No harness internals leak into repl.zig; it only sees a callback.
-// The `graff repl` bridge (ReplCtx/ReplStreamSink + replTurnCb/ModelCb/
-// CancelCb), the goal/eval steering-note assembly, the Codex-style steering
-// queue drain (popSteer/resetSteerPartial/steerEcho), and the /effort /fast
-// /ultracode persistence (save/loadThinkingSettings) live in repl_glue.zig
-// (600-line goal, #123). parseEvalScore/steerEcho/saveThinkingSettings stay
-// pub — subagent.zig, agent_compact.zig, agent_interrupt.zig, and
-// commands_model.zig already back-import them as `main_mod.X`. The mutable
-// steer/thinking globals below (g_steer_buf, g_steer_queue, g_steer_echoed,
-// g_steer_visible, g_out) stay here and are read/written live via
-// `main_mod.g_x` from repl_glue.zig (never aliased — they're `var`s).
+// The `graff repl` bridge, steering-note assembly, steering queue drain, and
+// /effort /fast /ultracode persistence live in repl_glue.zig. SteerEntry
+// below is read from here; the mutable steer/thinking globals stay here and
+// are read/written live via `main_mod.g_x` (never aliased — they're `var`s).
const repl_glue = @import("repl_glue.zig");
-pub const parseEvalScore = repl_glue.parseEvalScore;
-pub const steerEcho = repl_glue.steerEcho;
-// saveThinkingSettings repointed to repl_glue.zig directly at commands_model.zig.
/// Per-skill user opt-out, persisted as {"skills": {"kuri": false}} in
/// .harness/settings.json. A disabled skill is treated as not installed
@@ -324,10 +257,8 @@ pub const steerEcho = repl_glue.steerEcho;
/// webfetch never shells out to it — even when its binaries are on PATH.
pub var g_skill_disabled = [_]bool{false} ** skills_registry.len;
-/// Same opt-out, for the metered companion MCP servers (codedb-pro). They live
-/// in companion_servers, NOT skills_registry, so they need their own flags —
-/// this is the bug fix: {"skills": {"codedbpro": false}} now actually disables
-/// the auto-connect (skillDisabled() never matched a companion server name).
+/// Same opt-out, for the metered companion MCP servers (codedb-pro) — they
+/// live in companion_servers, NOT skills_registry, so need their own flags.
pub var g_companion_disabled = [_]bool{false} ** companion_servers.len;
/// True when `codedb-pro probe` exits 0 (paid + usable). Set once at startup
@@ -336,20 +267,18 @@ var g_codedbpro_licensed: bool = false;
// ── thinking animations ──────────────────────────────────────────────────
// Spinner animations + color themes (and their settings persistence) live in
-// anim.zig (#123); it imports ansi and back-imports main for Approvals paths.
-// The spinner consumers (Agent.spinnerTask, /animation, /theme) stay here.
+// anim.zig; the spinner consumers (Agent.spinnerTask, /animation, /theme)
+// stay here.
const anim = @import("anim.zig");
// Steering (Codex-style): bytes typed while a turn streams are captured
-// instead of discarded, echoed live in dim cyan, and on Enter queued to
-// run as the next turn — so you can line up follow-ups one after the
-// other without waiting for the current turn to finish. TTY-only (the
-// raw-stdin esc-watch path is gated off in --json/GUI mode), so the queue
-// stays empty there. Watchdog/select arms may drain and echo stdin while the
-// stream reader is blocked; g_steer_visible pauses spinner redraws so the live
-// steering row is not cleared out from under the user.
+// instead of discarded, echoed live in dim cyan, and on Enter queued to run
+// next — so follow-ups queue up without waiting for the turn to finish.
+// TTY-only (raw-stdin esc-watch is gated off in --json/GUI mode). Watchdog/
+// select arms may drain/echo stdin while the stream reader is blocked;
+// g_steer_visible pauses spinner redraws so the live row survives it.
pub var g_steer_buf: std.ArrayList(u8) = .empty; // in-progress line (page-alloc)
-const SteerEntry = repl_glue.SteerEntry; // struct { text: []const u8, force: bool }; moved to repl_glue.zig
+const SteerEntry = repl_glue.SteerEntry; // struct { text: []const u8, force: bool }
pub var g_steer_queue: std.ArrayList(SteerEntry) = .empty; // completed lines
pub var g_steer_echoed = false; // "↳ steer ›" prefix shown for the current line
pub var g_steer_visible: std.atomic.Value(bool) = .init(false); // visible live steering row; pauses spinner redraws
@@ -360,31 +289,22 @@ pub var g_thinking_fold_request: bool = false; // Ctrl-T in escPressed → fold/
pub var g_thinking_open: bool = false; // a live Thinking block is on screen (gates the mouse-click fold, #92)
pub var g_5xx_body_buf: [600]u8 = undefined; // snippet of the last 5xx/429 error body
pub var g_5xx_body_len: usize = 0; // 0 = no body captured
-// fillCompletions/wrapAt/LineRender/parseDsrCol moved to input_util.zig
-// (see the breadcrumb below the term.zig import block for the aliases
-// this file still needs).
-
-// Terminal primitives (Windows console shim + cross-platform raw-mode tty layer
-// + size/poll/row-count helpers) live in term.zig (600-line goal). win is
-// re-exported (hooks.zig back-imports it); the rest are aliased back so call
-// sites stay unqualified.
+// fillCompletions/wrapAt/LineRender/parseDsrCol live in input_util.zig.
+
+// Terminal primitives (Windows console shim + cross-platform raw-mode tty
+// layer + size/poll/row-count helpers) live in term.zig; hooks.zig imports
+// it directly for win. tty is aliased back so call sites stay unqualified.
const terminal = @import("term.zig");
-pub const win = terminal.win;
const tty = terminal.tty;
-// The rest of the line editor's input helpers (ultracode wave palette, the
-// `@` picker's binary/dir filters + file collection, drag-and-drop path
-// cleanup, and the redraw/setLine/delRange/prevWord/nextWord/addMark buffer
-// helpers hoisted out of readLine) live in input_util.zig; readLine() itself
-// (+ HistoryNav, #101) lives in readline.zig — both split out of main.zig
-// (600-line goal). isImagePath is repointed to a direct input_util.zig
-// import at its one remaining consumer, vision.zig; binaryFileExt is
+// The rest of the line editor's input helpers live in input_util.zig;
+// readLine() itself (+ HistoryNav) lives in readline.zig. binaryFileExt is
// aliased back (a read_file guard below calls it).
const input_util = @import("input_util.zig");
const readline_mod = @import("readline.zig");
// Session persistence (last model, input history) + the wire-format message
-// serializers live in serde.zig (600-line goal, std-only leaf). Aliased back.
+// serializers live in serde.zig (std-only leaf).
const serde = @import("serde.zig");
const loadHistory = serde.loadHistory;
const saveHistory = serde.saveHistory;
@@ -396,30 +316,21 @@ pub const harness_version: []const u8 = @import("build_options").version;
/// lowest-precedence telemetry endpoint, below env overrides and opt-out.
const default_telemetry_endpoint: []const u8 = @import("build_options").telemetry_endpoint;
-/// A parsed `MAJOR.MINOR.PATCH` (no pre-release/build suffix). Used to compare
-/// the running version against a GitHub release tag without the exact-string
-/// mismatch that `git describe` suffixes ("-3-gabc", "-dirty", "-dev") cause.
-// `graff update` (latest-release check + SemVer compare + install.sh delegation)
-// + the changelog_text/usage_text (--version/--help) blocks live in cli.zig
-// (600-line goal, #123). All three aliased back.
+// `graff update` (release check + install.sh delegation) + --version/--help
+// text live in cli.zig.
const cli = @import("cli.zig");
-// CLI flag parsing (the Flags struct + main()'s former ~130-line flag loop)
-// lives in args.zig (600-line goal, #123 follow-up — the last file over the
-// line goal). Not aliased: main() calls `args.parse` once and reads
-// `flags.<name>` throughout, so there is no bare call-site to preserve.
+// CLI flag parsing (the Flags struct) lives in args.zig; main() calls
+// `args.parse` once and reads `flags.<name>` throughout.
const args = @import("args.zig");
-// Post-arg-parse setup helpers (resolveKeys, buildSystemPrompt, the early
-// subcommand dispatch) live in startup.zig (600-line goal, #123 follow-up).
-// Everything after credentials/the http.Client exist (title/-w/banner,
-// trace/traj/telemetry/MCP-connect, repl/one-shot early-exits) lives in its
-// sibling session_start.zig — startup.zig itself crossed the line goal once
-// that content grew, so it moved out into its own file.
+// Post-arg-parse setup (resolveKeys, buildSystemPrompt, early subcommand
+// dispatch) lives in startup.zig. Everything after credentials/the
+// http.Client exist (title/-w/banner, trace/traj/telemetry/MCP-connect,
+// repl/one-shot early-exits) lives in its sibling session_start.zig.
const startup = @import("startup.zig");
const session_start = @import("session_start.zig");
const session_run = @import("session_run.zig");
-
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const io = init.io;
@@ -429,8 +340,7 @@ pub fn main(init: std.process.Init) !void {
// color and cursor sequences render instead of printing as literal text.
if (builtin.os.tag == .windows) tty.enableVtOutput();
- // CLI flags: the Flags struct + parsing loop live in args.zig (600-line
- // goal, #123 follow-up — the last file over the line goal). Downstream
+ // CLI flags: the Flags struct + parsing loop live in args.zig. Downstream
// code reads flags.<name> in place of the ~27 locals + the positional
// args this block used to declare and populate directly.
const flags = try args.parse(init);
@@ -440,9 +350,8 @@ pub fn main(init: std.process.Init) !void {
if (try startup.runSubcommand(io, gpa, arena, init, flags)) return;
// Credential/model resolution (env vars → codegraff/codex/kimi on-disk
// logins → the `harness key set` store, env always wins; then --model or
- // the last-saved model) lives in startup.zig (600-line goal, #123
- // follow-up) as resolveKeys() — pure over env/disk/arena, safe to call
- // outside main()'s own stack frame (no address-of-local storage).
+ // the last-saved model) lives in startup.zig as resolveKeys() — pure over
+ // env/disk/arena, safe to call outside main()'s own stack frame.
const resolved_keys = try startup.resolveKeys(io, gpa, arena, init.environ_map, flags.model_flag);
var keys = resolved_keys.keys;
const default_provider = resolved_keys.default_provider;
@@ -518,10 +427,9 @@ pub fn main(init: std.process.Init) !void {
defer registry_storage.deinit();
const registry: ?*mcp.Registry = &registry_storage;
// Per-skill/companion opt-outs, animation/theme settings, and the
- // --selftest-spinner headless render live in session_start.zig
- // (600-line goal). The theme/limyuxi-glam reset `defer`s stay HERE
- // (registered in main()'s own frame, same order as before) so they fire
- // when main() returns, not when the helper does.
+ // --selftest-spinner headless render live in session_start.zig. The
+ // theme/limyuxi-glam reset `defer`s stay HERE (registered in main()'s
+ // own frame) so they fire when main() returns, not when the helper does.
const theme_setup = try session_run.setupSkillsAndTheme(io, arena, init.environ_map, out, flags, use_color, json_mode, g_cwd_display);
defer if (theme_setup.theme_on) {
out.writeAll(anim.theme_reset) catch {};
@@ -547,9 +455,8 @@ pub fn main(init: std.process.Init) !void {
// Root system-prompt layering (base + AGENTS.md/HARNESS.md/CLAUDE.md +
// --append-system-prompt + active-skill capability lines + connected-MCP
- // usage notes) lives in startup.zig (600-line goal, #123 follow-up) as
- // buildSystemPrompt() — pure over io/arena, returns both prompt strings
- // by value.
+ // usage notes) lives in startup.zig as buildSystemPrompt() — pure over
+ // io/arena, returns both prompt strings by value.
const sys_prompt = try startup.buildSystemPrompt(
io,
arena,
@@ -569,11 +476,10 @@ pub fn main(init: std.process.Init) !void {
defer jobsReap(gpa, io);
// Root Agent construction + post-construction config (session name,
// persisted thinking/goal/eval settings, the session-start trace note)
- // + the backgrounded fleet-champion pull live in session_start.zig
- // (600-line goal). `root`'s pointer fields (snapshots/client/tracer/
- // approvals/registry) all reference already-stable main()-owned storage
- // passed in by address, so returning the constructed Agent by value here
- // is safe (see session_start.zig's header).
+ // + the backgrounded fleet-champion pull live in session_start.zig.
+ // `root`'s pointer fields (snapshots/client/tracer/approvals/registry)
+ // all reference already-stable main()-owned storage passed in by
+ // address, so returning the constructed Agent by value here is safe.
var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, sys_strict, mcp_tools, &snaps, flags, telem.endpoint);
defer joinElites(io); // reap if the session quits before any turn joins it
@@ -609,12 +515,11 @@ pub fn main(init: std.process.Init) !void {
const interactive = use_color and !json_mode; // stdout is a TTY → enable line editing
try session_run.restoreResumedSession(io, arena, out, &root, keys, flags, json_mode, g_cwd_display);
- // The interactive-REPL / --json-protocol turn loop lives in mainloop.zig
- // (600-line goal). main() keeps owning every piece of storage the loop
- // touches (root, keys, tracer/traj/telem via root, history, linebuf, the
- // stdin/stdout writers) — Ctx below only holds POINTERS into this
- // stack frame, so nothing dangles once run() returns and the post-loop
- // cleanup below (unchanged) resumes.
+ // The interactive-REPL / --json-protocol turn loop lives in mainloop.zig.
+ // main() keeps owning every piece of storage the loop touches (root,
+ // keys, tracer/traj/telem via root, history, linebuf, the stdin/stdout
+ // writers) — Ctx below only holds POINTERS into this stack frame, so
+ // nothing dangles once run() returns and the post-loop cleanup resumes.
var loop_ctx: mainloop.Ctx = .{
.gpa = gpa,
.io = io,
@@ -633,35 +538,20 @@ pub fn main(init: std.process.Init) !void {
try session_run.finalizeSession(gpa, io, arena, out, &root, json_mode);
}
-/// Is this .mcp.json entry one the harness would auto-connect anyway? A
-/// companion entry running its own binary (codedb-pro/muonry) with no args
-/// (or just `--mcp`) carries the same trust as the PATH auto-activation — but
-/// ONLY exactly that shape: a repo putting `{"codedbpro": {"command": "evil"}}`
-/// (or extra args) in its config still hits the consent gate.
// The `graff mcp` CLI (list/add servers in .mcp.json) + the trusted-companion
-// check + startup untrusted-server count live in mcp_cli.zig (600-line goal).
-// The 3 externally-called entry points are aliased back.
+// check live in mcp_cli.zig.
const mcp_cli = @import("mcp_cli.zig");
-// extractText moved to providers.zig (600-line goal); repointed to a direct
-// providers.zig import at its one remaining consumer, title.zig.
-
-// Provider-switch core (translateHistory, applyProvider, resolveProvider*,
-// setModelRequestLabel, switchProvider) lives in providers.zig; the
-// interactive pickers, ultracode steering, and login/auth flow live in
-// pickers.zig — both split out of main.zig (600-line goal, #123).
+// Provider-switch core lives in providers.zig; the interactive pickers,
+// ultracode steering, and login/auth flow live in pickers.zig.
const providers = @import("providers.zig");
-
const pickers = @import("pickers.zig");
-// The ~1,200-line body of handleCommand (one if-block per slash command) is
-// split into 3 sibling tryHandle() modules by theme (600-line goal, #123):
-// commands_session.zig (session/env: /clear /new /rename /goal /loop /bash
-// /agents /animation /theme /hooks /skills /trajectory /plan), commands_model.zig
-// (model/provider/thinking: /model /compact /rewind /fast /thinking /title
-// /ultracode /effort /keepcontext /key /login /image /paste /strict), and
-// commands_misc.zig (/todo /jobs /cost /mcp /models /yolo /trace /fleet
-// /save /resume /sessions + the unknown-command/help terminal fallback).
+// handleCommand (one if-block per slash command) is split into 3 sibling
+// tryHandle() modules by theme: commands_session.zig (session/env),
+// commands_model.zig (model/provider/thinking), commands_misc.zig
+// (/todo /jobs /cost /mcp /models /yolo /trace /fleet /save /resume
+// /sessions + the unknown-command/help fallback).
const commands_session = @import("commands_session.zig");
const commands_model = @import("commands_model.zig");
const commands_misc = @import("commands_misc.zig");
@@ -673,138 +563,66 @@ pub fn handleCommand(root: *Agent, keys: *Keys, arena: Allocator, line: []const
try commands_misc.handleRest(line, out);
}
-// Session persistence (save/load/list/rename/age + the .graff/sessions path
-// helpers) lives in session.zig (600-line goal, #123). session_ext/
-// saveSession stay pub — commands_session.zig, commands_misc.zig, and
-// readline.zig already back-import them as `main_mod.saveSession` etc.
-// sessionAge/listSavedSessions/loadSession are repointed to a direct
-// session.zig import at their one remaining consumer, commands_misc.zig.
+// Session persistence lives in session.zig (kept here for its test{} block).
const session = @import("session.zig");
-pub const session_ext = session.session_ext;
-pub const saveSession = session.saveSession;
-
-// Provider login/credential flows (Codex PKCE, Kimi + Codegraff device-code)
-// live in oauth.zig (#123); it imports ansi + util and back-imports main for
-// unixMs/kimi_user_agent/the codegraff base.
+// Provider login/credential flows live in oauth.zig.
const oauth = @import("oauth.zig");
-
-// API-key storage + the `graff key` CLI + OpenAI-compatible model listing
-// live in keys_cli.zig (600-line goal, #123). storeKey stays pub
-// (commands_model.zig + pickers.zig back-import it as `main_mod.storeKey`);
-// isLocalUrl/openAiModelsUrl/fetchOpenAIModels are repointed to a direct
-// keys_cli.zig import at their one remaining consumer, commands_model.zig.
-// homeEnv/loadStoredKey/keyCommand are used only from within main() here,
-// so their aliases stay bare.
+// API-key storage + the `graff key` CLI live in keys_cli.zig.
const keys_cli = @import("keys_cli.zig");
const homeEnv = keys_cli.homeEnv;
-pub const storeKey = keys_cli.storeKey;
-
-// ---------------------------------------------------------------------------
-// `harness serve` — the same --json session protocol, served over HTTP so
-// clients that cannot spawn a local process (edge runtimes, browsers, other
-// machines) can still drive agents. The server is a thin bridge: each session
-// is a real `harness --json` child process (the tested stdio path), and one
-// HTTP request = one protocol request, streamed back as NDJSON until that
-// request's terminal event. Endpoints:
-//
-// GET /healthz → {"ok":true,...} (no auth)
-// GET /v1/schema → the `harness --schema` document
-// POST /v1/sessions → {"session_id":"<16 hex>"}; body may set
-// {"model","yolo","system_prompt","append_system_prompt"}
-// POST /v1/sessions/<id> → body is one protocol request object
-// ({"type":"user","text":...} etc); response
-// streams NDJSON events until turn/error/ack
-// DELETE /v1/sessions/<id> → close the session (graceful: stdin EOF)
-//
-// Auth: --token / HARNESS_SERVE_TOKEN as a Bearer token. Binding a
-// non-loopback host without a token is refused. CORS is fully open ONLY
-// when a token is set (the token is then the actual gate); on token-less
-// loopback no CORS headers are sent, so browsers stay same-origin.
-
-// The `graff serve` HTTP bridge (HTTP <-> NDJSON child-process pool) lives in
-// serve.zig (#123); it back-imports main for emitSchema + the version consts.
-const serve = @import("serve.zig");
-// ---------------------------------------------------------------------------
+// `harness serve` — the same --json session protocol over HTTP: each
+// session is a real `harness --json` child process, and one HTTP request =
+// one protocol request streamed back as NDJSON until its terminal event
+// (GET /healthz, GET /v1/schema, POST/DELETE /v1/sessions[/<id>]). Auth:
+// --token / HARNESS_SERVE_TOKEN as a Bearer token; a non-loopback bind
+// without a token is refused; CORS opens only when a token is set. The
+// HTTP <-> NDJSON child-process bridge lives in serve.zig.
+const serve = @import("serve.zig");
-// Codegraff device-code login — mirrors graff's CodegraffDeviceStrategy:
-// POST /v1/device/start → show verification_uri + user_code → poll
-// /v1/device/poll until status "ok" yields the cg_sk_ key. Base derived from
-// the codegraff provider URL (gateway.codegraff.com). The key is written to
-// ~/.simple-harness-codegraff.json, which loadCodegraffKey reads at startup.
+// Codegraff device-code login: POST /v1/device/start → show
+// verification_uri + user_code → poll /v1/device/poll until "ok" yields the
+// cg_sk_ key, written to ~/.simple-harness-codegraff.json. Also used by
+// cube.zig (`graff cube`/`graff sandboxes`) as its gateway base.
pub const codegraff_device_base = "https://gateway.codegraff.com";
-// `graff cube` / `graff sandboxes` + the gateway REST helpers live in cube.zig
-// (#123); it back-imports main for strFieldObj/intFieldObj + the gateway base.
-
-// ToolCall moved to tools.zig (600-line goal); re-exported since several
-// agent_*.zig files + commands_session.zig still back-import it as
-// main_mod.ToolCall. (ExecResult/AnswerRequest/answerParseError/
-// parseAnswerRequest also live there but are all repointed to a direct
-// tools.zig import at their remaining consumers.)
-pub const ToolCall = tools_mod.ToolCall;
-
-// The Agent struct itself (fields + smallest methods) + TodoItem live in
-// agent.zig (600-line goal). Re-exported so the ~everywhere
-// `main_mod.Agent`/`main_mod.TodoItem` back-imports across the other split
-// files keep resolving unchanged regardless of physical file. Named
-// agent_mod (not `agent`) — several functions in this file have a local
-// `var agent: Agent = ...`, which would shadow a bare `agent` import.
+// The Agent struct (fields + smallest methods) + TodoItem live in agent.zig.
+// Named agent_mod (not `agent`) — several functions in this file have a
+// local `var agent: Agent = ...`, which would shadow a bare `agent` import.
const agent_mod = @import("agent.zig");
-pub const Agent = agent_mod.Agent;
-pub const TodoItem = agent_mod.TodoItem;
+const Agent = agent_mod.Agent;
-// Wire-format message construction + UTF-8/history normalization live in
-// messages.zig (600-line goal). Aliased back so call sites stay unqualified;
-// imported as messages_mod to avoid shadowing the `messages` params/fields.
+// Wire-format message construction lives in messages.zig, imported as
+// messages_mod to avoid shadowing the `messages` params/fields.
const messages_mod = @import("messages.zig");
/// A base64-encoded image staged by `/image`, sent with the next user turn.
-// Image/vision support (staged-image type, per-provider vision check, image
-// message builder, /image·/paste stagers, macOS clipboard grab) lives in
-// vision.zig (600-line goal). Public surface aliased back.
-const vision = @import("vision.zig");
-/// Auth + provider-specific headers shared by post() and Agent.postStream().
-/// User-Agent for an outbound provider call. The Kimi for Coding plan gates
-/// access to recognized coding-agent clients by User-Agent (a graff/* or bare
-/// UA gets `access_terminated`), so graff identifies as one — a user's Kimi
-/// Code key then works here the same as in Kimi CLI or Claude Code. Every
-/// other provider keeps the http client default.
+const vision = @import("vision.zig"); // staged-image type, /image·/paste stagers, macOS clipboard grab
+/// User-Agent for outbound provider calls. The Kimi for Coding plan gates
+/// access by User-Agent (a graff/* or bare UA gets `access_terminated`), so
+/// graff identifies as one — a user's Kimi Code key then works here the same
+/// as in Kimi CLI or Claude Code. Every other provider keeps the default.
pub const kimi_user_agent = "claude-code/1.0.0";
-// HTTP transport (auth headers, raw POST, 5xx-body capture, request watchdogs)
-// lives in http.zig (600-line goal). Aliased back so Agent's model-call and
-// streaming select-arms stay unqualified.
+// HTTP transport (auth headers, raw POST, 5xx-body capture, watchdogs) lives
+// in http.zig.
const http = @import("http.zig");
-// Subprocess execution: the capped runner (runCapped), git-worktree management,
-// and the background bash-job pool live in jobs.zig (600-line goal). runCapped
-// is re-exported (hooks.zig back-imports it); the worktree + job entry points
-// are aliased back.
+// Subprocess execution (runCapped, git-worktree mgmt, background bash-job
+// pool) lives in jobs.zig; jobsReap is aliased back for main()'s cleanup defer.
const jobs = @import("jobs.zig");
-pub const runCapped = jobs.runCapped;
const jobsReap = jobs.jobsReap;
-// Tool execution: the tool-call context (ToolCtx), file-edit snapshots for
-// /rewind, pre/post-tool lifecycle-hook dispatch, the codedb-guard (#626)
-// and metered-companion router, and small per-tool helpers live in tools.zig
-// (600-line goal; imported as tools_mod — Agent.request/buildBody already
-// have a `tools` parameter, which a bare `tools` import would shadow).
-// Subagent/workflow-task spawning (execSubagent/runSub/workflowTask/
-// judgeTask + the ultracode/DGM variant judge) lives in subagent.zig —
-// judgeTask is aliased back (Agent.runJudge, above, spawns it directly via
-// io.async). Dynamic workflows-as-data (phases + pipeline mode) live in
-// workflow.zig. The tool dispatcher itself (execTool/execToolInner) lives in
-// exec.zig, importing the three as siblings; execTool is aliased back
-// (Agent.runTools' io.async spawn + the /bash slash-command handler above).
-const tools_mod = @import("tools.zig");
-pub const ToolOutput = tools_mod.ToolOutput;
-pub const ToolCtx = tools_mod.ToolCtx;
-pub const Snapshots = tools_mod.Snapshots;
-pub const bash_stdout_cap = tools_mod.bash_stdout_cap; // input_util.zig back-imports this for its file-collection caps
+// Tool execution (ToolCtx, /rewind snapshots, pre/post-tool hook dispatch,
+// codedb-guard #626, metered-companion router) lives in tools.zig, imported
+// as tools_mod — Agent.request/buildBody already have a `tools` parameter,
+// which a bare `tools` import would shadow. Snapshots stays a local alias —
+// main() constructs one directly for /rewind. Subagent/workflow-task
+// spawning (subagent.zig/workflow.zig) and the tool dispatcher (exec.zig)
+// are kept imported here only for their test{} blocks.
+const tools_mod = @import("tools.zig");
+const Snapshots = tools_mod.Snapshots;
const subagent = @import("subagent.zig");
-
const workflow = @import("workflow.zig");
-
const exec = @import("exec.zig");
// ── Unit tests (`zig build test`) ──────────────────────────────────────────
@@ -905,21 +723,10 @@ test "incremental markdown streaming renders like renderMdLine" {
try std.testing.expectEqualStrings("abc defghijklm\n", aw.writer.buffered());
}
-// table-cell-wrapping/isTableSeparator tests moved to agent_table.zig;
-// ArgLive test to agent_argstream.zig; assembleOpenAI test to
-// agent_steps.zig; utf8Prefix test to telemetry.zig; resolveModelName test
-// to pricing.zig; scoreSigMessage test to scoring.zig; parseAnswerRequest
-// tests to tools.zig — all moved alongside the functions they test.
-
test { // pull in tests from imported modules (mcp.zig)
_ = mcp;
}
-// Agent.firstWord/cleanUserTurn/emergencyCutIndex/codepointCount/
-// inlineVisibleLen/isTableSeparator tests moved with their functions to
-// agent_tools.zig/agent_compact.zig/agent_render.zig/agent_table.zig.
-// Provider.compactAt + Keys.providerFor/providerById/defaultProvider tests
-// moved to provider.zig. extractText's test moved to providers.zig.
test "/bash slash command runs the bash tool and frees its gpa-allocated result" {
// Regression guard for PR #38: the /bash slash handler routes through
// execTool, whose result.text is gpa-owned (NOT arena-owned — every other
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 52accb0b..3b4eb736 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -30,6 +30,9 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
+const util = @import("util.zig");
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
const ansi = @import("ansi.zig");
const style = &ansi.style;
@@ -62,8 +65,8 @@ pub const Ctx = struct {
gpa: Allocator,
io: Io,
arena: Allocator,
- root: *main_mod.Agent,
- keys: *main_mod.Keys,
+ root: *agent_mod.Agent,
+ keys: *provider_mod.Keys,
out: *Io.Writer,
in: *Io.Reader,
history: *std.ArrayList([]const u8),
@@ -114,7 +117,7 @@ pub fn run(ctx: *Ctx) !void {
if (std.mem.eql(u8, l, "exit") or std.mem.eql(u8, l, "quit") or std.mem.eql(u8, l, "q")) break;
}
- if (!main_mod.json_mode and main_mod.isSlashCommandLine(line) and loop_prompt == null) {
+ if (!main_mod.json_mode and repl_glue.isSlashCommandLine(line) and loop_prompt == null) {
// Bare "/" on a TTY: open the filterable command menu.
if (ctx.interactive and line.len == 1) {
if (pickers.listPicker(ctx.root, ctx.arena, ctx.out, "Command ›", &pickers.command_menu)) |idx| {
@@ -259,15 +262,15 @@ pub fn run(ctx: *Ctx) !void {
return if (o.get(k)) |v| (if (v == .string) v.string else "") else "";
}
};
- const judge_id = main_mod.utf8Prefix(reqStr.s(parsed.object, "judge_id"), 64);
- const artifact_sha = main_mod.utf8Prefix(reqStr.s(parsed.object, "artifact_sha"), 64);
+ const judge_id = util.utf8Prefix(reqStr.s(parsed.object, "judge_id"), 64);
+ const artifact_sha = util.utf8Prefix(reqStr.s(parsed.object, "artifact_sha"), 64);
// DGM lever: when the score omits eval_set_hash but an --eval suite is
// configured, stamp the suite's stable fingerprint so scores group into a
// promotable (niche × tier × suite) cell. Same --eval cmd → same hash
// across installs → the fleet can rank + promote a champion.
var esh_buf: [16]u8 = undefined;
const eval_set_hash = eshblk: {
- const provided = main_mod.utf8Prefix(reqStr.s(parsed.object, "eval_set_hash"), 64);
+ const provided = util.utf8Prefix(reqStr.s(parsed.object, "eval_set_hash"), 64);
if (provided.len > 0) break :eshblk provided;
if (ctx.root.eval_cmd) |c| {
esh_buf = scoring.promptFingerprint(c);
@@ -276,7 +279,7 @@ pub fn run(ctx: *Ctx) !void {
break :eshblk "";
};
const req_run = reqStr.s(parsed.object, "run_id");
- const run_id: []const u8 = if (req_run.len > 0) main_mod.utf8Prefix(req_run, 64) else &scoring.g_run_id;
+ const run_id: []const u8 = if (req_run.len > 0) util.utf8Prefix(req_run, 64) else &scoring.g_run_id;
const sig = scoring.signScore(sha, parent, sc, run_id, judge_id, artifact_sha, eval_set_hash);
const signed = scoring.g_score_key != null;
if (trace.g_traj) |tj| tj.node(.{
@@ -284,7 +287,7 @@ pub fn run(ctx: *Ctx) !void {
.prompt_sha = sha,
.parent_sha = parent,
.score = sc,
- .notes = main_mod.utf8Prefix(notes, 200),
+ .notes = util.utf8Prefix(notes, 200),
.run_id = run_id,
.judge_id = judge_id,
.artifact_sha = artifact_sha,
@@ -373,7 +376,7 @@ pub fn run(ctx: *Ctx) !void {
var title_fut: ?Io.Future(?[]const u8) = null;
if (!main_mod.json_mode and ctx.root.ai_title and !ctx.root.ai_title_done) {
ctx.root.ai_title_done = true;
- title_fut = ctx.io.async(main_mod.titleTask, .{ ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, base_msg });
+ title_fut = ctx.io.async(title_mod.titleTask, .{ ctx.gpa, ctx.io, ctx.root.client, ctx.root.provider, base_msg });
}
defer if (title_fut) |*f| {
_ = f.await(ctx.io);
@@ -456,7 +459,7 @@ pub fn run(ctx: *Ctx) !void {
.ms = turn_ms,
.prompt_sha = &fp,
.prompt_mutated = !std.mem.eql(u8, &fp, &prev_prompt_fp),
- .task = main_mod.utf8Prefix(base_msg, 160),
+ .task = util.utf8Prefix(base_msg, 160),
.tools = turn_tools,
.ok = turn_ok,
.context_tokens = ctx.root.last_context_tokens,
diff --git a/src/mcp_cli.zig b/src/mcp_cli.zig
index 37b9e8a2..0ce0d90d 100644
--- a/src/mcp_cli.zig
+++ b/src/mcp_cli.zig
@@ -10,8 +10,9 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const root = @import("main.zig");
+const skills = @import("skills.zig");
const mcp_config_path = root.mcp_config_path;
-const companion_servers = root.companion_servers;
+const companion_servers = skills.companion_servers;
fn trustedMcpEntry(name: []const u8, cfg: Value) bool {
if (cfg != .object) return false;
diff --git a/src/messages.zig b/src/messages.zig
index f1019480..16ff8215 100644
--- a/src/messages.zig
+++ b/src/messages.zig
@@ -11,8 +11,10 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const root = @import("main.zig");
-const Provider = root.Provider;
-const utf8Prefix = root.utf8Prefix;
+const provider_mod = @import("provider.zig");
+const util = @import("util.zig");
+const Provider = provider_mod.Provider;
+const utf8Prefix = util.utf8Prefix;
pub fn textMessage(arena: Allocator, role: []const u8, text: []const u8) !Value {
var msg: std.json.ObjectMap = .empty;
diff --git a/src/oauth.zig b/src/oauth.zig
index f58daf41..e06277c0 100644
--- a/src/oauth.zig
+++ b/src/oauth.zig
@@ -22,7 +22,7 @@ const strFieldObj = util.strFieldObj;
const intFieldObj = util.intFieldObj;
const root = @import("main.zig");
-const unixMs = root.unixMs;
+const unixMs = util.unixMs;
const kimi_user_agent = root.kimi_user_agent;
const codegraff_device_base = root.codegraff_device_base;
@@ -216,7 +216,6 @@ pub fn codexLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, re
try out.flush();
}
-
/// Extract a query-string parameter from an HTTP request line ("GET /p?k=v…").
fn queryParam(req_line: []const u8, key: []const u8) ?[]const u8 {
const q = std.mem.indexOfScalar(u8, req_line, '?') orelse return null;
@@ -430,7 +429,6 @@ fn httpJsonPost(io: Io, gpa: Allocator, arena: Allocator, url: []const u8, body:
return v.object;
}
-
pub fn codegraffLogin(io: Io, gpa: Allocator, arena: Allocator, home: []const u8) !void {
var obuf: [4096]u8 = undefined;
var ow = Io.File.stdout().writer(io, &obuf);
diff --git a/src/pickers.zig b/src/pickers.zig
index 35a7045a..90008e88 100644
--- a/src/pickers.zig
+++ b/src/pickers.zig
@@ -27,10 +27,13 @@ const providers = @import("providers.zig");
const switchProvider = providers.switchProvider;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Keys = main_mod.Keys;
-const provider_specs = main_mod.provider_specs;
-const storeKey = main_mod.storeKey;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const keys_cli = @import("keys_cli.zig");
+const Agent = agent_mod.Agent;
+const Keys = provider_mod.Keys;
+const provider_specs = provider_mod.provider_specs;
+const storeKey = keys_cli.storeKey;
/// Case-insensitive subsequence match (fzf-style): every char of `needle`
/// appears in `hay` in order, gaps allowed — so "gpt5.5" matches "gpt-5.5".
diff --git a/src/pricing.zig b/src/pricing.zig
index 51f3e510..e167ff73 100644
--- a/src/pricing.zig
+++ b/src/pricing.zig
@@ -327,9 +327,9 @@ test "priceFor: known model priced, unknown is null" {
}
test "resolveModelName exact aliases and miss" {
- const main_mod = @import("main.zig");
- const Keys = main_mod.Keys;
- const provider_specs = main_mod.provider_specs;
+ const provider_mod = @import("provider.zig");
+ const Keys = provider_mod.Keys;
+ const provider_specs = provider_mod.provider_specs;
const keys = Keys{ .values = [_]?[]const u8{null} ** provider_specs.len };
try std.testing.expect(resolveModelName(keys, "gpt-5.5") != null); // exact name
try std.testing.expectEqualStrings("glm-5.2", resolveModelName(keys, "glm5.2").?); // natural alias
diff --git a/src/providers.zig b/src/providers.zig
index a3155ef9..ecbb1685 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -22,10 +22,12 @@ const messages_mod = @import("messages.zig");
const textMessage = messages_mod.textMessage;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Keys = main_mod.Keys;
-const Provider = main_mod.Provider;
-const provider_specs = main_mod.provider_specs;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const Agent = agent_mod.Agent;
+const Keys = provider_mod.Keys;
+const Provider = provider_mod.Provider;
+const provider_specs = provider_mod.provider_specs;
/// Pull plain text out of a message's content (string, or the text blocks of a
/// content array — anthropic "text", openai "text", responses "input/output_text").
pub fn extractText(arena: Allocator, m: Value) []const u8 {
diff --git a/src/readline.zig b/src/readline.zig
index d7d77175..5d9f096f 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -45,8 +45,10 @@ const nextWord = input_util.nextWord;
const addMark = input_util.addMark;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const saveSession = main_mod.saveSession;
+const agent_mod = @import("agent.zig");
+const session = @import("session.zig");
+const Agent = agent_mod.Agent;
+const saveSession = session.saveSession;
/// History + unsent-draft navigation for the line editor (#101). Mirrors the
/// GUI's promptHistoryNavigation.ts: stepping UP out of the fresh slot snapshots
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 6726e3c2..fbfb42c9 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -22,8 +22,10 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Provider = main_mod.Provider;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const Agent = agent_mod.Agent;
+const Provider = provider_mod.Provider;
const ReasoningEffort = main_mod.ReasoningEffort;
const mcp = @import("mcp.zig");
diff --git a/src/schema.zig b/src/schema.zig
index fd7c382b..27dc5916 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -15,8 +15,9 @@ const pricing = @import("pricing.zig");
const model_table = pricing.model_table;
const root = @import("main.zig");
-const Provider = root.Provider;
-const provider_specs = root.provider_specs;
+const provider_mod = @import("provider.zig");
+const Provider = provider_mod.Provider;
+const provider_specs = provider_mod.provider_specs;
/// Documentation of the `--json` stdio protocol, embedded verbatim in
/// `--schema` output so SDK generators/users know the request/event contract.
diff --git a/src/serve.zig b/src/serve.zig
index 04aa0b4a..52b5a618 100644
--- a/src/serve.zig
+++ b/src/serve.zig
@@ -13,9 +13,10 @@ const Allocator = std.mem.Allocator;
// Back-import the root module for the few helpers that remain in main.zig. Zig
// resolves the main<->serve import cycle fine (all runtime, no comptime dep).
const root = @import("main.zig");
-const emitSchema = root.emitSchema;
+const schema = @import("schema.zig");
+const emitSchema = schema.emitSchema;
const harness_version = root.harness_version;
-const schema_version = root.schema_version;
+const schema_version = schema.schema_version;
const ServeConfig = struct {
host: []const u8,
diff --git a/src/session.zig b/src/session.zig
index 16641b18..2af33f17 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -3,22 +3,24 @@
//! plus the list/rename/age helpers behind `/sessions`, `/resume`, and the
//! AI-title auto-rename. Split out of main.zig (600-line goal, #123).
//!
-//! Every function here takes `*main_mod.Agent` (several params are named
-//! `root`, so the back-import is aliased `main_mod`, not `root`, to avoid
-//! shadowing). saveSession/loadSession/listSavedSessions/sessionAge/
-//! session_ext stay pub — commands_session.zig, commands_misc.zig, and
-//! readline.zig already back-import them as `main_mod.saveSession` etc.
+//! Every function here takes `*agent_mod.Agent` (several params are named
+//! `root`, matching the harness-wide root-agent convention). saveSession/
+//! loadSession/listSavedSessions/sessionAge/session_ext stay pub —
+//! commands_session.zig, commands_misc.zig, and readline.zig import them
+//! directly as `session.saveSession` etc.
const std = @import("std");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
-const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Keys = main_mod.Keys;
-const unixMs = main_mod.unixMs;
-const utf8Prefix = main_mod.utf8Prefix;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const util = @import("util.zig");
+const Agent = agent_mod.Agent;
+const Keys = provider_mod.Keys;
+const unixMs = util.unixMs;
+const utf8Prefix = util.utf8Prefix;
pub const session_ext = ".session.json";
const sessions_dir = ".graff/sessions"; // title-named session files live here (resume reads this)
diff --git a/src/session_run.zig b/src/session_run.zig
index f55ae5ce..df31af2a 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -6,11 +6,11 @@
//! setup.
//!
//! Same dangling-pointer discipline as session_start.zig: `buildRootAgent`
-//! returns `main_mod.Agent` by value — safe because its pointer fields
+//! returns `agent_mod.Agent` by value — safe because its pointer fields
//! (snapshots/client/tracer/approvals/registry) all reference storage the
//! CALLER already placed at a stable, final address (passed in by pointer),
//! not anything local to this function. `runReplCommand`/`runOneshotPrompt`/
-//! `restoreResumedSession`/`finalizeSession` take `root: *main_mod.Agent` —
+//! `restoreResumedSession`/`finalizeSession` take `root: *agent_mod.Agent` —
//! by the time any of these run, `root` is already stable main()-owned
//! storage, so passing its address around is ordinary pointer-passing.
//! `setupSkillsAndTheme` hands back which reset `defer`s main() needs to
@@ -25,6 +25,9 @@ const Allocator = std.mem.Allocator;
const args = @import("args.zig");
const main_mod = @import("main.zig");
+const agent_mod = @import("agent.zig");
+const approvals_mod = @import("approvals.zig");
+const tools_mod = @import("tools.zig");
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
@@ -54,7 +57,7 @@ const schema = @import("schema.zig");
/// `root` is already a stable, fully-constructed main()-owned Agent by the
/// time this is called, so taking its address here is safe (this helper
/// only reads through the pointer, it never owns or returns Agent storage).
-pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *main_mod.Agent, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {
+pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {
if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "repl"))) return false;
var repl_ctx = repl_glue.ReplCtx{
.io = io,
@@ -85,7 +88,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *main_
/// denies anything not pre-approved instead of prompting (there's no one to
/// ask). Moved out of main() verbatim (600-line goal); `root`/`tracer` are
/// already stable main()-owned storage by the time this runs.
-pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *main_mod.Agent, tracer: *trace.Tracer, out: *Io.Writer, prompt_text: []const u8) !void {
+pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mod.Agent, tracer: *trace.Tracer, out: *Io.Writer, prompt_text: []const u8) !void {
main_mod.unattended = true;
root.in = null; // gate: deny instead of prompt; ask_user: self-decide
root.out = null; // tool progress → stderr; stdout carries only the answer
@@ -139,7 +142,7 @@ pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *main_mo
/// its own `defer` for `approvals.prefixes` right after the call (a `defer`
/// registered inside this helper would fire at the WRONG time — when this
/// function returns, not when main() does).
-pub fn initApprovalsHooksFleet(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, approvals: *main_mod.Approvals, flags: args.Flags, out: *Io.Writer, json_mode: bool) !void {
+pub fn initApprovalsHooksFleet(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytype, approvals: *approvals_mod.Approvals, flags: args.Flags, out: *Io.Writer, json_mode: bool) !void {
approvals.* = .{ .yolo = flags.yolo_flag };
const persisted_approvals = approvals.loadPersisted(io, gpa, arena);
@@ -147,21 +150,21 @@ pub fn initApprovalsHooksFleet(io: Io, gpa: Allocator, arena: Allocator, environ
fleet.g_home = keys_cli.homeEnv(environ_map); // for /agents promote's personal tier
fleet.g_agent_types = fleet.loadAgentTypes(io, arena, fleet.g_home); // builtin < ~/.harness/agents (personal) < ./.harness/agents (private)
if (persisted_approvals > 0 and !json_mode and flags.oneshot_prompt == null) {
- try out.print("{s}loaded {d} saved approval(s) from {s}{s}\n", .{ ansi.style.dim, persisted_approvals, main_mod.Approvals.settings_path, ansi.style.reset });
+ try out.print("{s}loaded {d} saved approval(s) from {s}{s}\n", .{ ansi.style.dim, persisted_approvals, approvals_mod.Approvals.settings_path, ansi.style.reset });
try out.flush();
}
// Lifecycle hooks (pre_tool/post_tool/turn_end) from the same file.
// (Per-skill opt-outs were loaded earlier, before the muonry auto-connect.)
main_mod.g_hooks = hooks.loadHooks(io, arena);
if (main_mod.g_hooks.total() > 0 and !json_mode and flags.oneshot_prompt == null) {
- try out.print("{s}loaded {d} lifecycle hook(s) from {s} — /hooks lists them{s}\n", .{ ansi.style.dim, main_mod.g_hooks.total(), main_mod.Approvals.settings_path, ansi.style.reset });
+ try out.print("{s}loaded {d} lifecycle hook(s) from {s} — /hooks lists them{s}\n", .{ ansi.style.dim, main_mod.g_hooks.total(), approvals_mod.Approvals.settings_path, ansi.style.reset });
try out.flush();
}
}
/// Constructs the root Agent: snapshots/client/tracer/approvals/registry are
/// all ALREADY stable main()-owned storage by the time this is called (the
-/// caller passes their addresses in), so this returns `main_mod.Agent` by
+/// caller passes their addresses in), so this returns `agent_mod.Agent` by
/// value safely — its pointer fields reference external, already-placed
/// storage, not anything local to this function (see this file's header).
/// Also does the post-construction config (session name, persisted
@@ -178,16 +181,16 @@ pub fn buildRootAgent(
out: *Io.Writer,
in: *Io.Reader,
registry: ?*mcp.Registry,
- approvals: *main_mod.Approvals,
+ approvals: *approvals_mod.Approvals,
tracer: *trace.Tracer,
sys_normal: []const u8,
sys_strict: []const u8,
mcp_tools: []const mcp.Tool,
- snaps: *main_mod.Snapshots,
+ snaps: *tools_mod.Snapshots,
flags: args.Flags,
telem_endpoint: []const u8,
-) !main_mod.Agent {
- var root: main_mod.Agent = .{
+) !agent_mod.Agent {
+ var root: agent_mod.Agent = .{
.snapshots = snaps,
.gpa = gpa,
.arena = arena,
@@ -235,7 +238,7 @@ pub fn buildRootAgent(
/// resume-target reload for a resumed one-shot. Moved out of main() verbatim
/// (600-line goal). Both are best-effort (`catch {}`), matching main()'s
/// former inline behavior exactly.
-pub fn saveOrResumeSession(root: *main_mod.Agent, keys: provider_mod.Keys, arena: Allocator, flags: args.Flags) void {
+pub fn saveOrResumeSession(root: *agent_mod.Agent, keys: provider_mod.Keys, arena: Allocator, flags: args.Flags) void {
const will_resume = flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag;
if (!will_resume) session.saveSession(root, arena, root.session_name) catch {};
if (flags.oneshot_prompt != null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag) {
@@ -249,7 +252,7 @@ pub fn saveOrResumeSession(root: *main_mod.Agent, keys: provider_mod.Keys, arena
/// as what would trigger live compaction, summarizes up front instead of
/// re-billing the whole thing on the first turn. Moved out of main()
/// verbatim (600-line goal); `root` is already stable main()-owned storage.
-pub fn restoreResumedSession(io: Io, arena: Allocator, out: *Io.Writer, root: *main_mod.Agent, keys: provider_mod.Keys, flags: args.Flags, json_mode: bool, cwd_display: []const u8) !void {
+pub fn restoreResumedSession(io: Io, arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, keys: provider_mod.Keys, flags: args.Flags, json_mode: bool, cwd_display: []const u8) !void {
if (!(flags.oneshot_prompt == null and flags.resume_flag != null and !flags.new_session_flag and !flags.no_resume_flag)) return;
if (session.loadSession(root, keys, arena, root.session_name)) |_| {
if (root.messages.items.len > 0) {
@@ -282,7 +285,7 @@ pub fn restoreResumedSession(io: Io, arena: Allocator, out: *Io.Writer, root: *m
/// + the worktree checkpoint commit for any edits an interrupted/aborted
/// final turn left uncommitted. Moved out of main() verbatim (600-line
/// goal); `root` is already stable main()-owned storage.
-pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, root: *main_mod.Agent, json_mode: bool) !void {
+pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, root: *agent_mod.Agent, json_mode: bool) !void {
if (!json_mode and root.messages.items.len > 0) {
session.saveSession(root, arena, root.session_name) catch |err| {
out.print("{s}⚠ session save failed: {t}{s}\n", .{ ansi.style.yellow, err, ansi.style.reset }) catch {};
diff --git a/src/skills.zig b/src/skills.zig
index e2fb5655..d2147191 100644
--- a/src/skills.zig
+++ b/src/skills.zig
@@ -20,8 +20,10 @@ const Allocator = std.mem.Allocator;
const mcp = @import("mcp.zig");
const main_mod = @import("main.zig");
-const Approvals = main_mod.Approvals;
-const runCapped = main_mod.runCapped;
+const approvals_mod = @import("approvals.zig");
+const jobs = @import("jobs.zig");
+const Approvals = approvals_mod.Approvals;
+const runCapped = jobs.runCapped;
/// Codex-style optional skills: known companion tools the harness quietly
/// upgrades itself with when they're installed. Progressive disclosure, same
diff --git a/src/subagent.zig b/src/subagent.zig
index ca80252a..4415d345 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -15,7 +15,10 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
+const agent_mod = @import("agent.zig");
+const util = @import("util.zig");
+const repl_glue = @import("repl_glue.zig");
+const Agent = agent_mod.Agent;
const tools = @import("tools.zig");
const ToolCtx = tools.ToolCtx;
@@ -133,7 +136,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
.prompt_sha = &fp,
.prompt_mutated = sys_override != null,
.niche = niche, // MAP-Elites niche, so a local /agents promote can group scores by it
- .task = main_mod.utf8Prefix(prompt, 160),
+ .task = util.utf8Prefix(prompt, 160),
.tools = used_tools,
.ok = run_ok,
.context_tokens = agent.last_context_tokens,
@@ -173,7 +176,7 @@ pub fn judgeTask(ctx: ToolCtx, prompt: []const u8) ToolOutput {
/// task on a 0-100 scale (see scoreVariants). Bounded: the task spec and output
/// tail are truncated so a fat phase can't blow up the judge's context.
fn variantJudgePrompt(arena: Allocator, title: []const u8, task: []const u8, output: []const u8) ![]const u8 {
- const spec = main_mod.utf8Prefix(task, 1200);
+ const spec = util.utf8Prefix(task, 1200);
const work = if (output.len > 2000) output[output.len - 2000 ..] else output;
return std.fmt.allocPrint(arena,
\\An agent variant ran the task below as part of the "{s}" phase of a workflow.
@@ -246,7 +249,7 @@ pub fn scoreVariants(
const jout = jf.await(ctx.io);
defer ctx.gpa.free(jout.text);
if (jout.is_error) continue;
- const s = main_mod.parseEvalScore(jout.text) orelse continue;
+ const s = repl_glue.parseEvalScore(jout.text) orelse continue;
if (s <= 0) continue; // skip the total-failure 0 (don't pollute the cell mean), mirroring runEval
const genome_fp = promptFingerprint(overrides[i].?);
const esh_fp = promptFingerprint(raws[i]);
@@ -278,5 +281,5 @@ test "variantJudgePrompt: bounded, names the phase, keeps the score contract" {
// The `score:` contract parseEvalScore depends on is spelled out…
try std.testing.expect(std.mem.indexOf(u8, p, "score: <N>") != null);
// …and it round-trips: a judge tail like this parses back to the score.
- try std.testing.expectEqual(@as(?f64, 87), main_mod.parseEvalScore("ok\nscore: 87"));
+ try std.testing.expectEqual(@as(?f64, 87), repl_glue.parseEvalScore("ok\nscore: 87"));
}
diff --git a/src/title.zig b/src/title.zig
index c4bd0bb6..679a2e3b 100644
--- a/src/title.zig
+++ b/src/title.zig
@@ -15,8 +15,10 @@ const ansi = @import("ansi.zig");
const style = &ansi.style;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Provider = main_mod.Provider;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const Agent = agent_mod.Agent;
+const Provider = provider_mod.Provider;
const providers = @import("providers.zig");
const extractText = providers.extractText;
diff --git a/src/tools.zig b/src/tools.zig
index ec2d5090..991b1e8c 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -18,6 +18,7 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
+const provider_mod = @import("provider.zig");
/// A normalized tool invocation — same shape for both providers.
pub const ToolCall = struct {
id: []const u8,
@@ -58,7 +59,7 @@ pub fn parseAnswerRequest(parsed: Value, expected_call_id: []const u8) !AnswerRe
const text = if (parsed.object.get("text")) |v| (if (v == .string) v.string else "") else "";
return .{ .text = text, .cancelled = cancelled, .call_id = call_id };
}
-const Provider = main_mod.Provider;
+const Provider = provider_mod.Provider;
const harness_version = main_mod.harness_version;
const mcp = @import("mcp.zig");
diff --git a/src/vision.zig b/src/vision.zig
index e9303daf..27b792a9 100644
--- a/src/vision.zig
+++ b/src/vision.zig
@@ -12,8 +12,10 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
-const Agent = main_mod.Agent;
-const Provider = main_mod.Provider;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const Agent = agent_mod.Agent;
+const Provider = provider_mod.Provider;
const input_util = @import("input_util.zig");
const isImagePath = input_util.isImagePath;
diff --git a/src/workflow.zig b/src/workflow.zig
index bbfa8a79..7a4076d1 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -13,6 +13,7 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
+const util = @import("util.zig");
const tools = @import("tools.zig");
const ToolCtx = tools.ToolCtx;
@@ -44,7 +45,7 @@ const prev_tail_keep = 600;
/// outputs pass through untouched; over the cap, head + truncation marker + tail.
fn cappedPrevBody(arena: Allocator, text: []const u8) []const u8 {
if (text.len <= max_prev_per_task) return text;
- const head = main_mod.utf8Prefix(text, max_prev_per_task - prev_tail_keep);
+ const head = util.utf8Prefix(text, max_prev_per_task - prev_tail_keep);
const tail = text[text.len - prev_tail_keep ..];
return std.fmt.allocPrint(arena, "{s}\n\n…[{d} chars truncated — full result in the inspect file below]…\n\n{s}", .{ head, text.len - head.len - tail.len, tail }) catch text;
}