Skip to content

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

Python

feat(tools): licensed one-read-surface, turn pulse, Smolify opt-in

Rach Pradhand422ee831f2a
diff --git a/src/agent.zig b/src/agent.zig
index 0900ebd4..ab228c8c 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -123,6 +123,7 @@ pub const Agent = struct {
agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their own
tools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)
tool_calls_this_turn: u64 = 0,
+ model_calls_this_turn: u64 = 0,
handle_note_shown: bool = false, // #541: the handle-protocol lesson rides this agent's FIRST handle, once
seen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keys
md_buf: std.ArrayList(u8) = .empty, // current incomplete streamed line (markdown rendering)
@@ -264,33 +265,12 @@ pub const Agent = struct {
return true;
}
- /// #330/#352: a child's catalog is a comptime constant, so both gates just
- /// pick the pre-built twin rather than rebuilding one per subagent —
- /// schema.subToolsJson owns that choice. Root catalogs are filtered where
- /// they are assembled (schema.effectiveRootSpecs).
pub fn toolsJson(self: *const Agent) []const u8 {
- if (self.sub) return schema.subToolsJson(self.provider.kind, no_local_tools.enabled);
- return switch (self.provider.kind) {
- .anthropic => self.tools_anthropic,
- .openai => self.tools_openai,
- .responses => self.tools_responses,
- };
+ return @import("agent_catalog.zig").toolsJson(self);
}
- /// Root catalogs include meta + MCP tools and are much larger than the
- /// subagent constants. Materialize only a wire format the session actually
- /// uses; provider switching calls this before updating the context meter.
pub fn ensureRootTools(self: *Agent, kind: Provider.Kind) !void {
- if (self.sub) return;
- const slot = switch (kind) {
- .anthropic => &self.tools_anthropic,
- .openai => &self.tools_openai,
- .responses => &self.tools_responses,
- };
- if (slot.*.len != 0) return;
- const specs = try schema.effectiveRootSpecs(self.arena);
- const connected: []const mcp.Tool = if (self.registry) |registry| registry.tools else &.{};
- slot.* = try schema.renderRootTools(self.arena, kind, specs, connected);
+ return @import("agent_catalog.zig").ensureRootTools(self, kind);
}
/// A live MCP registry change invalidates provider-specific catalogs. The
@@ -343,9 +323,8 @@ pub const Agent = struct {
self.completed = null;
if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) esc_cancel.store(false, .release);
while (true) {
- // Esc during a tool join (set by escWatchTask) lands here: the
- // root consumes the flag and aborts before the next request;
- // subagents see it too and bail without consuming.
+ if (try @import("turn_chrome.zig").beforeRequest(self)) |paused| return paused;
+ // Esc during a tool join lands here; root consumes, subagents bail.
if (esc_cancel.load(.acquire)) {
if (!self.sub) esc_cancel.store(false, .release);
return error.Interrupted;
diff --git a/src/agent_catalog.zig b/src/agent_catalog.zig
new file mode 100644
index 00000000..0504f3b7
--- /dev/null
+++ b/src/agent_catalog.zig
@@ -0,0 +1,44 @@
+//! Root/worker tool-catalog materialization. Split out of agent.zig (600-line ceiling).
+
+const main_mod = @import("main.zig");
+const schema = @import("schema.zig");
+const no_local_tools = @import("no_local_tools.zig");
+const surface = @import("tool_surface.zig");
+const mcp = @import("mcp.zig");
+const Provider = @import("provider.zig").Provider;
+const Agent = @import("agent.zig").Agent;
+
+pub fn toolsJson(self: *const Agent) []const u8 {
+ if (self.sub) {
+ if (main_mod.g_codedbpro_licensed) return slot(self);
+ return schema.subToolsJson(self.provider.kind, no_local_tools.enabled);
+ }
+ return slot(self);
+}
+
+fn slot(self: *const Agent) []const u8 {
+ return switch (self.provider.kind) {
+ .anthropic => self.tools_anthropic,
+ .openai => self.tools_openai,
+ .responses => self.tools_responses,
+ };
+}
+
+pub fn ensureRootTools(self: *Agent, kind: Provider.Kind) !void {
+ if (self.sub and !main_mod.g_codedbpro_licensed) return;
+ const dest = switch (kind) {
+ .anthropic => &self.tools_anthropic,
+ .openai => &self.tools_openai,
+ .responses => &self.tools_responses,
+ };
+ if (dest.*.len != 0) return;
+ const specs = if (self.sub)
+ try surface.filterSpecs(@TypeOf(schema.base_specs[0]), self.arena, schema.base_specs[0..])
+ else
+ try schema.effectiveRootSpecs(self.arena);
+ const connected: []const mcp.Tool = if (self.registry) |registry|
+ (if (self.sub) try surface.filterWorkerMcp(self.arena, registry.tools) else registry.tools)
+ else
+ &.{};
+ dest.* = try schema.renderRootTools(self.arena, kind, specs, connected);
+}
diff --git a/src/agent_request.zig b/src/agent_request.zig
index f43be88b..23cecb16 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -366,6 +366,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// just-closed keep-alive almost always re-fail
// (#86). 250ms·2ⁿ, capped at 4s over 6 tries; Esc cancels.
const delay_ms = RetryPlan.delayMs(throttled, attempt);
+ @import("turn_chrome.zig").emitRetryNotice(self.io, @errorName(err), attempt + 1, max_attempts);
if (showRecoveredTransportRetry(self.call_kind))
try self.say("[network error: {t} — retrying in {d}ms ({d}/{d})]\n", .{ err, delay_ms, attempt + 1, max_attempts });
// Same trace breadcrumb the 429/5xx branch leaves: a
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index e6314dfa..54cb97d5 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -120,7 +120,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
.provider = self.provider,
.subagent_provider = self.subagent_provider,
.subagent_cross_provider = self.subagent_cross_provider,
- .registry = if (self.sub) null else self.registry,
+ .registry = self.registry, // workers get licensed codedb-pro reads too (#627)
.from_sub = self.sub,
.has_eval = self.eval_cmd != null,
.approvals = self.approvals,
diff --git a/src/codedbpro_report.zig b/src/codedbpro_report.zig
index 1db67798..c40124e3 100644
--- a/src/codedbpro_report.zig
+++ b/src/codedbpro_report.zig
@@ -156,7 +156,7 @@ fn leadingSearchCommand(cmd: []const u8) bool {
const trimmed = std.mem.trimStart(u8, cmd, " \t");
const end = std.mem.indexOfAny(u8, trimmed, " \t") orelse trimmed.len;
const first = trimmed[0..end];
- return std.mem.eql(u8, first, "grep") or std.mem.eql(u8, first, "rg") or std.mem.eql(u8, first, "find");
+ return @import("tool_surface.zig").isSearchBash(first);
}
/// Whether the licensed-pro enforcement applies to this call right now.
@@ -465,9 +465,9 @@ test "nativeRefusal: licensed pro tools block the natives they replaced" {
try std.testing.expect(nativeRefusal(ctx, namedCall("codedb")) != null);
try std.testing.expect(nativeRefusal(ctx, bashCall(a, "find . -name '*.zig'")) != null);
try std.testing.expect(nativeRefusal(ctx, bashCall(a, "rg TODO src")) != null);
- // Untouched: edits stay native, non-search bash stays open, a piped grep
- // filters command output rather than searching the tree.
- try std.testing.expect(nativeRefusal(ctx, namedCall("edit_file")) == null);
+ try std.testing.expect(nativeRefusal(ctx, bashCall(a, "cat src/main.zig")) != null);
+ try std.testing.expect(nativeRefusal(ctx, bashCall(a, "head src/main.zig")) != null);
+ try std.testing.expect(nativeRefusal(ctx, namedCall("edit_file")) == null); // edits stay native
try std.testing.expect(nativeRefusal(ctx, bashCall(a, "git status")) == null);
try std.testing.expect(nativeRefusal(ctx, bashCall(a, "curl -s x | grep err")) == null);
}
diff --git a/src/exec.zig b/src/exec.zig
index 8e597920..778c944e 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -9,6 +9,7 @@ const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
const util = @import("util.zig");
const codedbpro_report = @import("codedbpro_report.zig"); // licensed-companion failure → redacted issue filer
+const tool_surface = @import("tool_surface.zig"); // companion-write gate + licensed hide
const codedbpro_paths = @import("codedbpro_paths.zig"); // session-cwd paths for the resident companion daemon
const tool_balance = @import("tool_balance.zig"); // session-wide tool-class tally (/tools)
const ToolCall = tools.ToolCall;
@@ -120,7 +121,7 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
// #255: reserved before any gate/dispatch runs so tool_started/
// tool_finished bracket the whole call, including a gate denial below.
const call_id: u64 = if (ctx.tracer) |tr| tr.toolStarted(call.name, call.input) else 0;
- if (noLocalToolsGate(ctx, call) orelse codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call) orelse codedbpro_report.licensedGate(ctx, call) orelse native_fold.gateExec(ctx.gpa, call.name, ctx.from_sub)) |blocked| {
+ if (noLocalToolsGate(ctx, call) orelse codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call) orelse codedbpro_report.licensedGate(ctx, call) orelse tool_surface.gate(ctx, call) orelse native_fold.gateExec(ctx.gpa, call.name, ctx.from_sub)) |blocked| {
var out = blocked;
out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
if (ctx.tracer) |tr| {
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 2cd72694..9bd0caec 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -401,6 +401,7 @@ pub fn run(ctx: *Ctx) !void {
} else 0;
ctx.root.tools_used.clear(ctx.io); // per-turn tool log for the turn's node
ctx.root.tool_calls_this_turn = 0;
+ ctx.root.model_calls_this_turn = 0;
goal_state.beginTurn(ctx.root, !is_loop_continuation); // per-turn gate flags (the ARMED double-check is NOT one, #318) + the new-ask retirement of a finished checklist (#394)
ctx.root.seen_tool_keys.clearRetainingCapacity();
if (main_mod.json_mode) ctx.root.emit(.{ .type = "started", .provider = ctx.root.provider.id, .model = ctx.root.provider.model });
diff --git a/src/mcp_boot.zig b/src/mcp_boot.zig
index 03c79d4a..02c9b67b 100644
--- a/src/mcp_boot.zig
+++ b/src/mcp_boot.zig
@@ -103,6 +103,7 @@ pub fn init(gpa: Allocator, io: Io, config_path: []const u8, global_path: ?[]con
var it = merged.servers.iterator();
while (it.next()) |entry| {
if (std.mem.eql(u8, entry.key_ptr.*, "smolify")) continue;
+ if (@import("tool_surface.zig").skipOptionalServer(entry.key_ptr.*, environ_map)) continue;
if (entry.value_ptr.* != .object) continue;
try entries.append(a, .{ .name = try a.dupe(u8, entry.key_ptr.*), .cfg = entry.value_ptr.*.object });
}
diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zig
index e4d89845..f5b16a03 100644
--- a/src/mcp_schema_gate.zig
+++ b/src/mcp_schema_gate.zig
@@ -45,6 +45,8 @@ const mcp = @import("mcp.zig");
const mcp_config = @import("mcp_config.zig");
const tools_mod = @import("tools.zig");
const util = @import("util.zig");
+const tool_surface = @import("tool_surface.zig");
+pub const omitMcp = tool_surface.omitMcp;
const ExecResult = tools_mod.ExecResult;
@@ -317,6 +319,7 @@ pub fn shortDesc(desc: []const u8) []const u8 {
/// direction — same rule as the native fold's markIfFolded). The catalog's
/// zero-stub listing is unchanged; the call itself was already provider-legal.
pub fn autoLoad(arena: Allocator, all: []const mcp.Tool, qualified: []const u8) void {
+ if (omitMcp(qualified)) return;
if (!blocked(all, qualified)) return;
for (all) |t| {
if (std.mem.eql(u8, t.qualified_name, qualified)) {
@@ -411,6 +414,7 @@ pub fn loadInto(arena: Allocator, all: []const mcp.Tool, input: Value) !Loaded {
// Named twice in one call (`server` plus its own name, say), or loaded
// by an earlier call: neither is an error, both are the cache working.
if (std.mem.indexOfScalar(usize, wanted.items[0..k], i) != null) continue;
+ if (omitMcp(all[i].qualified_name)) continue;
const first_time = !isLoaded(all[i].qualified_name);
try aw.writer.print("{s}\n", .{try enable(arena, all[i])});
emitted += 1;
@@ -505,6 +509,7 @@ pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {
for (native_fold.folded) |name| {
if (!native_fold.isFolded(name)) continue; // rlm stays off the default listing
if (!g_stable_catalog and native_fold.isLoaded(name)) continue;
+ if (tool_surface.hideBuiltin(name)) continue;
try natives.append(arena, name);
}
}
@@ -514,6 +519,7 @@ pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {
const deferredRule: *const fn ([]const mcp.Tool, mcp.Tool) bool = if (g_stable_catalog) &policyDeferred else &isDeferred;
var servers: std.ArrayList([]const u8) = .empty;
for (all) |t| {
+ if (omitMcp(t.qualified_name)) continue;
if (!deferredRule(all, t)) continue;
const sv = serverOf(t.qualified_name);
const seen = for (servers.items) |s| {
@@ -533,6 +539,7 @@ pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {
try aw.writer.print(" {s} (", .{sv});
var first = true;
for (all) |t| {
+ if (omitMcp(t.qualified_name)) continue;
if (!deferredRule(all, t)) continue;
if (!std.mem.eql(u8, serverOf(t.qualified_name), sv)) continue;
if (!first) try aw.writer.writeAll(", ");
diff --git a/src/prompts.zig b/src/prompts.zig
index 0ffae75e..548a1072 100644
--- a/src/prompts.zig
+++ b/src/prompts.zig
@@ -37,6 +37,7 @@ const playbook = @import("playbook.zig"); // #381: the user-constraint block com
const compact_note = @import("compact_note.zig"); // #391: the pre-compaction note-to-self, composed the same way and for the same reason
const no_local_tools = @import("no_local_tools.zig"); // #330's subtractive gate — one half of every capability answer below
const tool_gates = @import("tool_gates.zig"); // #352's additive gate — the other half
+const tool_surface = @import("tool_surface.zig");
const session_index = @import("session_index.zig"); // #410: where the durable transcript lives
/// The prompt text itself lives next door; this file owns when each part
@@ -130,7 +131,7 @@ pub const Caps = struct {
/// can remove a built-in, and nothing else — the same pair `exec.zig` refuses
/// a hallucinated call with, so the prompt can never disagree with dispatch.
pub fn toolAdvertised(name: []const u8) bool {
- return !no_local_tools.blocks(name) and !tool_gates.blocks(name);
+ return !no_local_tools.blocks(name) and !tool_gates.blocks(name) and !tool_surface.hideBuiltin(name);
}
/// The live gates. Every flag and env knob feeding them is settled before
@@ -139,7 +140,7 @@ pub fn detectCaps() Caps {
// The lean halves agree: a tool the catalog filtered out (no_local_tools)
// is also not a capability the prompt may instruct about.
return .{
- .local_tools = toolAdvertised("read_file") and toolAdvertised("bash"),
+ .local_tools = toolAdvertised("edit_file") and toolAdvertised("bash"),
.subagents = toolAdvertised("subagent") and !no_local_tools.lean, // lean: no fan-out essay
.todos = toolAdvertised("todo_write") and !no_local_tools.lean,
.constraints = toolAdvertised("note_constraint") and !no_local_tools.lean,
diff --git a/src/schema.zig b/src/schema.zig
index 6a5e0254..24e75608 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -50,7 +50,7 @@ const empty_schema =
\\{"type": "object", "properties": {}}
;
-const base_specs = [_]ToolSpec{
+pub const base_specs = [_]ToolSpec{
.{
.name = "bash",
.desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands that are still running after 120s (or timeout ms) are moved to the background and return a job id — the process keeps running. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. bash_output(wait_ms>0) blocks until exit (up to 10h); omit wait_ms for a snapshot. Stop it with bash_kill.",
@@ -307,7 +307,7 @@ pub fn renderRootTools(
}
// Deferred tools ship no entries (codex tool_search pattern); the meta
// tool's desc lists them, exec.zig layer 2 guards premature calls.
- for (mcp_tools) |m| if (!mcp_schema_gate.isDeferred(mcp_tools, m) and !(mcp_schema_gate.g_stable_catalog and mcp_schema_gate.policyDeferred(mcp_tools, m)))
+ for (mcp_tools) |m| if (!mcp_schema_gate.omitMcp(m.qualified_name) and !mcp_schema_gate.isDeferred(mcp_tools, m) and !(mcp_schema_gate.g_stable_catalog and mcp_schema_gate.policyDeferred(mcp_tools, m)))
try writeToolEntry(&s, kind, m.qualified_name, m.description, .{ .value = m.input_schema });
// GRAFF_STABLE_CATALOG (#476): loaded tools append in LOAD ORDER after the
// stable head — loads change only tail bytes, the prefix cache survives.
@@ -326,8 +326,8 @@ pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {
(if (learn_store.active_agent_loaded) &root_specs else &root_specs_without_learning)
else
(if (learn_store.active_agent_loaded) &root_specs_without_clock else &root_specs_without_optional);
- // Optionals are appended BEFORE the #330 filter, never after (optional ≠ exempt); the --lean token filter chains last.
- return rlm.maybeAppend(ToolSpec, arena, try no_local_tools.compactLeanSpecs(ToolSpec, arena, try no_local_tools.filterLeanSpecs(ToolSpec, arena, try no_local_tools.filterRootSpecs(ToolSpec, arena, try tool_gates.withAvailable(ToolSpec, arena, chosen, &optional_specs)))));
+ // Optionals before #330 (optional ≠ exempt); lean + licensed surface filter chain inside assembleRoot.
+ return rlm.maybeAppend(ToolSpec, arena, try tool_gates.assembleRoot(ToolSpec, arena, chosen, &optional_specs));
}
const Schema = union(enum) { raw: []const u8, value: Value };
diff --git a/src/session_connect_tests.zig b/src/session_connect_tests.zig
new file mode 100644
index 00000000..c84d812d
--- /dev/null
+++ b/src/session_connect_tests.zig
@@ -0,0 +1,47 @@
+//! Companion-connect opt-in: Smolify is not added unless GRAFF_SMOLIFY is set.
+
+const std = @import("std");
+const Io = std.Io;
+
+const args = @import("args.zig");
+const mcp = @import("mcp.zig");
+const session_start = @import("session_start.zig");
+const tool_surface = @import("tool_surface.zig");
+
+test "connectCompanion does not add Smolify tools unless the opt-in env is present" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var env = std.process.Environ.Map.init(std.testing.allocator);
+ defer env.deinit();
+ const flags: args.Flags = .{};
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+
+ var registry = mcp.Registry.empty(std.testing.allocator, std.testing.io);
+ defer registry.deinit();
+ try session_start.connectCompanion(std.testing.io, arena, &registry, flags, &aw.writer, true, env);
+ try std.testing.expectEqual(@as(usize, 0), registry.tools.len);
+ try std.testing.expectEqual(@as(usize, 0), registry.servers.len);
+
+ try env.put("GRAFF_SMOLIFY", "1");
+ var with_opt = mcp.Registry.empty(std.testing.allocator, std.testing.io);
+ defer with_opt.deinit();
+ try session_start.connectCompanion(std.testing.io, arena, &with_opt, flags, &aw.writer, true, env);
+ try std.testing.expect(with_opt.tools.len > 0);
+ try std.testing.expectEqualStrings("smolify", with_opt.servers[0].name);
+ for (with_opt.tools) |t| {
+ try std.testing.expect(std.mem.startsWith(u8, t.qualified_name, "mcp__smolify__"));
+ }
+}
+
+test "skipOptionalServer keeps deepwiki/mobbin out of the default catalog" {
+ var env = std.process.Environ.Map.init(std.testing.allocator);
+ defer env.deinit();
+ try std.testing.expect(tool_surface.skipOptionalServer("deepwiki", env));
+ try std.testing.expect(tool_surface.skipOptionalServer("mobbin", env));
+ try env.put("GRAFF_DEEPWIKI", "1");
+ try std.testing.expect(!tool_surface.skipOptionalServer("deepwiki", env));
+ try std.testing.expect(tool_surface.skipOptionalServer("mobbin", env));
+}
diff --git a/src/session_settings.zig b/src/session_settings.zig
index 9efa7fb7..c9ec58e6 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -231,6 +231,9 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
if (environ_map.get("GRAFF_WS_FORCE_FAIL_COUNT")) |v| {
ws.g_force_connect_failure_count = std.fmt.parseInt(u8, std.mem.trim(u8, v, " \t"), 10) catch 0;
}
+ if (environ_map.get("GRAFF_MAX_TURN_MODEL_CALLS")) |v| {
+ @import("turn_chrome.zig").max_turn_model_calls = @import("turn_chrome.zig").parseMaxTurnCalls(v);
+ }
}
pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out: *Io.Writer, flags: args.Flags, use_color: bool, json_mode: bool, cwd_display: []const u8) !ThemeSetup {
diff --git a/src/session_start.zig b/src/session_start.zig
index 4779e584..bc9adc01 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -527,9 +527,8 @@ pub fn connectCompanion(io: Io, arena: Allocator, registry: *mcp.Registry, flags
}
}
- // Smolify schemas are bundled and its hosted transport stays offline until
- // an approved call. Full/authenticated/write tools require explicit opt-in.
- if (environ_map.get("GRAFF_NO_SMOLIFY") != null) return;
+ // Smolify is opt-in: GRAFF_SMOLIFY=1 or GRAFF_SMOLIFY_ACCESS=public|full.
+ if (!@import("tool_surface.zig").smolifyWanted(environ_map)) return;
const access = environ_map.get("GRAFF_SMOLIFY_ACCESS") orelse "public";
const full_access = std.ascii.eqlIgnoreCase(access, "full") or std.ascii.eqlIgnoreCase(access, "authenticated");
const added = registry.connectSmolify(full_access) catch |err| {
diff --git a/src/skills.zig b/src/skills.zig
index ae0c1574..fd8bf2f3 100644
--- a/src/skills.zig
+++ b/src/skills.zig
@@ -67,7 +67,7 @@ pub const skills_registry = [_]SkillDef{
/// Edits inside the cwd stay native: edit_file/write_file are
/// /rewind-snapshotted and already splice via zigpatch, whereas codedb-pro
/// edit/patch/replace bypass /rewind. Explicit external targets use gated bash.
-const codedbpro_note_licensed = "The codedb-pro MCP server is connected and LICENSED — its mcp__codedbpro__* tools (load once per session via load_tool_schemas, e.g. by query) REPLACE the native read/search defaults, which are BLOCKED while the server is healthy: read/search calls are refused with a pointer to the pro equivalent, shell searches to `zigrep` via bash; any codedb-pro failure unblocks the natives for the rest of the session. Size reads to the file: mode=full in ONE call for small files — outline/symbol/lines modes are for files too big to read whole. KEEP EDITS on the native edit_file/write_file tools — codedb-pro edit/patch/replace bypass /rewind; the cwd and explicit-external-target rules above apply unchanged.";
+const codedbpro_note_licensed = "The codedb-pro MCP server is connected and LICENSED — its mcp__codedbpro__* tools (load once per session via load_tool_schemas, e.g. by query) REPLACE native read/search (read_file and the legacy codedb tool are hidden). Shell cat/grep/sed/head of source is redirected or refused. KEEP EDITS on native edit_file/write_file — codedb-pro write tools are hidden because they bypass /rewind. Size reads to the file: mode=full in ONE call for small files — outline/symbol/lines for files too big to read whole. Any codedb-pro failure unblocks the natives for the rest of the session.";
const McpNote = struct { server: []const u8, note: []const u8 };
pub const mcp_notes = [_]McpNote{
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index d2239c77..49e7b6c2 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -277,6 +277,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
.label = label,
.out = null,
.approvals = ctx.approvals,
+ .registry = ctx.registry,
.tracer = ctx.tracer,
.run_budget = ctx.run_budget,
.loop_deadline_ms = ctx.loop_deadline_ms, // a timed run's deadline reaches grandchildren too, not just depth 1
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index ca38ef6c..7e58fc69 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -148,6 +148,10 @@ const plugin_codex = @import("plugin_codex.zig"); // Codex config.toml → Plugi
// decls, but the hook makes the coverage explicit rather than contingent on
// that staying true.
const mcp_config = @import("mcp_config.zig");
+const turn_chrome = @import("turn_chrome.zig"); // #624 pulse + retry chrome
+const tool_surface = @import("tool_surface.zig");
+const agent_catalog = @import("agent_catalog.zig");
+const session_connect_tests = @import("session_connect_tests.zig");
const effort_route = @import("effort_route.zig");
// #416: two-phase MCP tool exposure. schema.zig/exec.zig reach the gate, but
@@ -320,4 +324,8 @@ test {
_ = commands_sandbox;
_ = sandbox_tests;
_ = provider_tests;
+ _ = turn_chrome;
+ _ = tool_surface;
+ _ = agent_catalog;
+ _ = session_connect_tests;
}
diff --git a/src/tool_gates.zig b/src/tool_gates.zig
index e381751b..b1700607 100644
--- a/src/tool_gates.zig
+++ b/src/tool_gates.zig
@@ -91,6 +91,18 @@ pub fn withAvailable(comptime Spec: type, arena: Allocator, base: []const Spec,
return buf[0..i];
}
+/// One catalog-assembly pass: optional tools, then #330/#lean, then the
+/// licensed surface filter (hide read_file/codedb when codedb-pro is in charge).
+pub fn assembleRoot(comptime Spec: type, arena: Allocator, base: []const Spec, optional: []const Spec) ![]const Spec {
+ const no_local_tools = @import("no_local_tools.zig");
+ const tool_surface = @import("tool_surface.zig");
+ const with_opt = try withAvailable(Spec, arena, base, optional);
+ const gated = try no_local_tools.filterRootSpecs(Spec, arena, with_opt);
+ const lean = try no_local_tools.filterLeanSpecs(Spec, arena, gated);
+ const compact = try no_local_tools.compactLeanSpecs(Spec, arena, lean);
+ return tool_surface.filterSpecs(Spec, arena, compact);
+}
+
test { // the served catalogs' wire-compatibility guard (an unreferenced module's tests never run)
_ = @import("tool_schema_tests.zig");
_ = @import("spec_catalog_conformance.zig");
diff --git a/src/tool_surface.zig b/src/tool_surface.zig
new file mode 100644
index 00000000..393ca5fc
--- /dev/null
+++ b/src/tool_surface.zig
@@ -0,0 +1,271 @@
+//! Licensed catalog/exec policy: one read/search surface, one edit surface.
+//!
+//! When codedb-pro is licensed, hide native `read_file` and legacy `codedb`.
+//! Companion write tools (edit/patch/create/replace) are omitted always — they
+//! bypass /rewind. Native `edit_file`/`write_file` stay. `subagent` stays.
+//! webfetch is not hidden here (optional extra, not this change).
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+const main_mod = @import("main.zig");
+const tools = @import("tools.zig");
+const mcp = @import("mcp.zig");
+
+const companion_write = [_][]const u8{
+ "edit", "patch", "create", "replace", "byte_delta",
+};
+
+const search_bash = [_][]const u8{
+ "grep", "rg", "find", "cat", "head", "tail", "sed", "awk", "egrep", "ripgrep",
+};
+
+pub fn isSearchBash(first: []const u8) bool {
+ for (search_bash) |w| if (std.mem.eql(u8, first, w)) return true;
+ return false;
+}
+
+pub fn isCompanionWrite(qualified: []const u8) bool {
+ const prefixes = [_][]const u8{ "mcp__codedbpro__", "mcp__muonry__" };
+ for (prefixes) |prefix| {
+ if (!std.mem.startsWith(u8, qualified, prefix)) continue;
+ const bare = qualified[prefix.len..];
+ for (companion_write) |w| if (std.mem.eql(u8, bare, w)) return true;
+ return false;
+ }
+ return false;
+}
+
+/// MCP names that must not appear in any catalog (companion writes + bundled
+/// smolify until opt-in connect actually adds it).
+pub fn omitMcp(qualified: []const u8) bool {
+ return isCompanionWrite(qualified);
+}
+
+/// Built-ins hidden from the advertised catalog. Never hides `subagent`.
+pub fn hideBuiltin(name: []const u8) bool {
+ if (!main_mod.g_codedbpro_licensed) return false;
+ return std.mem.eql(u8, name, "read_file") or std.mem.eql(u8, name, "codedb");
+}
+
+pub fn filterSpecs(comptime Spec: type, arena: Allocator, specs: []const Spec) ![]const Spec {
+ var drop: usize = 0;
+ for (specs) |spec| {
+ if (hideBuiltin(spec.name)) drop += 1;
+ }
+ if (drop == 0) return specs;
+ const buf = try arena.alloc(Spec, specs.len - drop);
+ var i: usize = 0;
+ for (specs) |spec| {
+ if (hideBuiltin(spec.name)) continue;
+ buf[i] = spec;
+ i += 1;
+ }
+ return buf[0..i];
+}
+
+/// Worker MCP: companion read/search only (no writes, no smolify).
+pub fn keepWorkerMcp(qualified: []const u8) bool {
+ if (omitMcp(qualified)) return false;
+ return std.mem.startsWith(u8, qualified, "mcp__codedbpro__") or
+ std.mem.startsWith(u8, qualified, "mcp__muonry__");
+}
+
+pub fn filterWorkerMcp(arena: Allocator, all: []const mcp.Tool) ![]const mcp.Tool {
+ var n: usize = 0;
+ for (all) |t| {
+ if (keepWorkerMcp(t.qualified_name)) n += 1;
+ }
+ if (n == all.len) return all;
+ const buf = try arena.alloc(mcp.Tool, n);
+ var i: usize = 0;
+ for (all) |t| {
+ if (!keepWorkerMcp(t.qualified_name)) continue;
+ buf[i] = t;
+ i += 1;
+ }
+ return buf[0..i];
+}
+
+pub const companion_write_refusal =
+ "codedb-pro write tools (edit/patch/create/replace) are hidden — they bypass /rewind. Use native edit_file for existing files and write_file for new files.";
+
+pub fn gate(ctx: tools.ToolCtx, call: tools.ToolCall) ?tools.ToolOutput {
+ if (!isCompanionWrite(call.name)) return null;
+ const text = ctx.gpa.dupe(u8, companion_write_refusal) catch return .{ .text = &.{}, .is_error = true };
+ return .{ .text = text, .is_error = true };
+}
+
+pub fn smolifyWanted(environ_map: anytype) bool {
+ if (environ_map.get("GRAFF_NO_SMOLIFY") != null) return false;
+ return environ_map.get("GRAFF_SMOLIFY") != null or environ_map.get("GRAFF_SMOLIFY_ACCESS") != null;
+}
+
+/// deepwiki / mobbin stay out of the default unauthenticated catalog unless
+/// an explicit opt-in env names them.
+pub fn skipOptionalServer(name: []const u8, environ_map: anytype) bool {
+ if (std.mem.eql(u8, name, "deepwiki")) return !optionalAllowed("deepwiki", environ_map);
+ if (std.mem.eql(u8, name, "mobbin")) return !optionalAllowed("mobbin", environ_map);
+ return false;
+}
+
+fn optionalAllowed(name: []const u8, environ_map: anytype) bool {
+ if (environ_map.get("GRAFF_MCP_OPTIONAL")) |v| {
+ var it = std.mem.tokenizeAny(u8, v, ", ");
+ while (it.next()) |tok| if (std.mem.eql(u8, tok, name)) return true;
+ }
+ if (std.mem.eql(u8, name, "deepwiki") and environ_map.get("GRAFF_DEEPWIKI") != null) return true;
+ if (std.mem.eql(u8, name, "mobbin") and environ_map.get("GRAFF_MOBBIN") != null) return true;
+ return false;
+}
+
+test "companion writes are omitted; reads are not" {
+ try std.testing.expect(isCompanionWrite("mcp__codedbpro__edit"));
+ try std.testing.expect(isCompanionWrite("mcp__codedbpro__patch"));
+ try std.testing.expect(isCompanionWrite("mcp__codedbpro__create"));
+ try std.testing.expect(isCompanionWrite("mcp__muonry__replace"));
+ try std.testing.expect(!isCompanionWrite("mcp__codedbpro__read"));
+ try std.testing.expect(!isCompanionWrite("mcp__codedbpro__faster_search"));
+ try std.testing.expect(!omitMcp("mcp__smolify__search_docs"));
+ try std.testing.expect(!omitMcp("mcp__codedbpro__read"));
+ try std.testing.expect(keepWorkerMcp("mcp__codedbpro__read"));
+ try std.testing.expect(!keepWorkerMcp("mcp__codedbpro__edit"));
+}
+
+test "hideBuiltin drops read_file/codedb only when licensed; never subagent" {
+ const saved = main_mod.g_codedbpro_licensed;
+ defer main_mod.g_codedbpro_licensed = saved;
+ main_mod.g_codedbpro_licensed = false;
+ try std.testing.expect(!hideBuiltin("read_file"));
+ try std.testing.expect(!hideBuiltin("codedb"));
+ try std.testing.expect(!hideBuiltin("subagent"));
+ try std.testing.expect(!hideBuiltin("edit_file"));
+ main_mod.g_codedbpro_licensed = true;
+ try std.testing.expect(hideBuiltin("read_file"));
+ try std.testing.expect(hideBuiltin("codedb"));
+ try std.testing.expect(!hideBuiltin("subagent"));
+ try std.testing.expect(!hideBuiltin("edit_file"));
+ try std.testing.expect(!hideBuiltin("write_file"));
+ try std.testing.expect(!hideBuiltin("webfetch"));
+}
+
+test "isSearchBash covers the licensed first-token list" {
+ try std.testing.expect(isSearchBash("grep"));
+ try std.testing.expect(isSearchBash("rg"));
+ try std.testing.expect(isSearchBash("find"));
+ try std.testing.expect(isSearchBash("cat"));
+ try std.testing.expect(isSearchBash("head"));
+ try std.testing.expect(isSearchBash("tail"));
+ try std.testing.expect(isSearchBash("sed"));
+ try std.testing.expect(isSearchBash("awk"));
+ try std.testing.expect(isSearchBash("egrep"));
+ try std.testing.expect(isSearchBash("ripgrep"));
+ try std.testing.expect(!isSearchBash("git"));
+ try std.testing.expect(!isSearchBash("zig"));
+}
+
+const FakeSpec = struct { name: []const u8 };
+test "filterSpecs drops hidden builtins and leaves the rest" {
+ const saved = main_mod.g_codedbpro_licensed;
+ defer main_mod.g_codedbpro_licensed = saved;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const specs = [_]FakeSpec{
+ .{ .name = "bash" },
+ .{ .name = "read_file" },
+ .{ .name = "edit_file" },
+ .{ .name = "codedb" },
+ .{ .name = "subagent" },
+ };
+ main_mod.g_codedbpro_licensed = false;
+ const all = try filterSpecs(FakeSpec, arena_state.allocator(), &specs);
+ try std.testing.expectEqual(@as(usize, 5), all.len);
+ main_mod.g_codedbpro_licensed = true;
+ const filtered = try filterSpecs(FakeSpec, arena_state.allocator(), &specs);
+ try std.testing.expectEqual(@as(usize, 3), filtered.len);
+ try std.testing.expectEqualStrings("bash", filtered[0].name);
+ try std.testing.expectEqualStrings("edit_file", filtered[1].name);
+ try std.testing.expectEqualStrings("subagent", filtered[2].name);
+}
+
+test "licensed root catalog drops read_file and codedb, keeps subagent and edit_file" {
+ const schema = @import("schema.zig");
+ const saved = main_mod.g_codedbpro_licensed;
+ defer main_mod.g_codedbpro_licensed = saved;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ main_mod.g_codedbpro_licensed = false;
+ const off = try schema.effectiveRootSpecs(a);
+ var saw_read = false;
+ var saw_sub = false;
+ for (off) |t| {
+ if (std.mem.eql(u8, t.name, "read_file")) saw_read = true;
+ if (std.mem.eql(u8, t.name, "subagent")) saw_sub = true;
+ }
+ try std.testing.expect(saw_read);
+ try std.testing.expect(saw_sub);
+
+ main_mod.g_codedbpro_licensed = true;
+ const on = try schema.effectiveRootSpecs(a);
+ var saw_edit = false;
+ var saw_sub2 = false;
+ for (on) |t| {
+ try std.testing.expect(!std.mem.eql(u8, t.name, "read_file"));
+ try std.testing.expect(!std.mem.eql(u8, t.name, "codedb"));
+ if (std.mem.eql(u8, t.name, "edit_file")) saw_edit = true;
+ if (std.mem.eql(u8, t.name, "subagent")) saw_sub2 = true;
+ if (std.mem.eql(u8, t.name, "write_file")) {}
+ }
+ try std.testing.expect(saw_edit);
+ try std.testing.expect(saw_sub2);
+}
+
+test "smolifyWanted and skipOptionalServer are opt-in" {
+ var env = std.process.Environ.Map.init(std.testing.allocator);
+ defer env.deinit();
+ try std.testing.expect(!smolifyWanted(env));
+ try std.testing.expect(skipOptionalServer("deepwiki", env));
+ try std.testing.expect(skipOptionalServer("mobbin", env));
+ try std.testing.expect(!skipOptionalServer("codedbpro", env));
+ try env.put("GRAFF_SMOLIFY", "1");
+ try std.testing.expect(smolifyWanted(env));
+ try env.put("GRAFF_MCP_OPTIONAL", "deepwiki,mobbin");
+ try std.testing.expect(!skipOptionalServer("deepwiki", env));
+ try std.testing.expect(!skipOptionalServer("mobbin", env));
+}
+
+test "worker specs drop read_file/codedb; worker MCP keeps reads not writes" {
+ const schema = @import("schema.zig");
+ const saved = main_mod.g_codedbpro_licensed;
+ defer main_mod.g_codedbpro_licensed = saved;
+ main_mod.g_codedbpro_licensed = true;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const specs = try filterSpecs(@TypeOf(schema.base_specs[0]), a, schema.base_specs[0..]);
+ var saw_edit = false;
+ for (specs) |t| {
+ try std.testing.expect(!std.mem.eql(u8, t.name, "read_file"));
+ try std.testing.expect(!std.mem.eql(u8, t.name, "codedb"));
+ try std.testing.expect(!std.mem.eql(u8, t.name, "subagent"));
+ if (std.mem.eql(u8, t.name, "edit_file")) saw_edit = true;
+ }
+ try std.testing.expect(saw_edit);
+ const fake = [_]mcp.Tool{
+ .{ .server_index = 0, .original_name = "read", .qualified_name = "mcp__codedbpro__read", .description = "d", .input_schema = .null },
+ .{ .server_index = 0, .original_name = "edit", .qualified_name = "mcp__codedbpro__edit", .description = "d", .input_schema = .null },
+ };
+ const kept = try filterWorkerMcp(a, &fake);
+ try std.testing.expectEqual(@as(usize, 1), kept.len);
+ try std.testing.expectEqualStrings("mcp__codedbpro__read", kept[0].qualified_name);
+ const mcp_gate = @import("mcp_schema_gate.zig");
+ const saved_policy = mcp_gate.g_policy;
+ defer mcp_gate.g_policy = saved_policy;
+ mcp_gate.g_policy = .{ .eager = &.{"codedbpro"} };
+ const json = try schema.renderRootTools(a, .openai, specs, kept);
+ try std.testing.expect(std.mem.indexOf(u8, json, "mcp__codedbpro__read") != null);
+ try std.testing.expect(std.mem.indexOf(u8, json, "read_file") == null);
+ try std.testing.expect(std.mem.indexOf(u8, json, "mcp__codedbpro__edit") == null);
+}
diff --git a/src/tools.zig b/src/tools.zig
index 113b3720..2a33d58d 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -195,6 +195,7 @@ pub fn runPostToolHooks(ctx: ToolCtx, call: ToolCall, out: ToolOutput) void {
/// model adapts — same contract as a pre_tool hook's exit 2.
pub fn codedbGuard(ctx: ToolCtx, call: ToolCall) ?ToolOutput {
if (!main_mod.g_codedb_guard) return null;
+ if (main_mod.g_codedbpro_licensed) return null; // licensedGate owns read/search
if (!std.mem.eql(u8, call.name, "bash")) return null;
const cmd = strField(call.input, "command") orelse return null;
diff --git a/src/turn_chrome.zig b/src/turn_chrome.zig
new file mode 100644
index 00000000..db90078d
--- /dev/null
+++ b/src/turn_chrome.zig
@@ -0,0 +1,80 @@
+//! Dim chrome for long inner-loop turns and API transport retries (retry n/N).
+//!
+//! Production default: unlimited inner-loop model calls (`max_turn_model_calls = 0`).
+//! `GRAFF_MAX_TURN_MODEL_CALLS` is the opt-in cap. JSON mode is dropped inside
+//! `tool_pulse.emitNotice` (ADR 0020: chrome, not output).
+
+const std = @import("std");
+const Io = std.Io;
+
+const main_mod = @import("main.zig");
+const Agent = @import("agent.zig").Agent;
+const tool_pulse = @import("tool_pulse.zig");
+
+/// Per-turn inner-loop cap. 0 = unlimited (the production default).
+pub var max_turn_model_calls: u64 = 0;
+
+pub fn parseMaxTurnCalls(raw: []const u8) u64 {
+ const trimmed = std.mem.trim(u8, raw, " \t");
+ if (trimmed.len == 0) return 0;
+ return std.fmt.parseInt(u64, trimmed, 10) catch 0;
+}
+
+pub fn formatRetryNotice(buf: []u8, class: []const u8, attempt: usize, max_attempts: usize) []const u8 {
+ return std.fmt.bufPrint(buf, "· retry {d}/{d} · {s}", .{ attempt, max_attempts, class }) catch buf[0..0];
+}
+
+pub fn formatTurnPulse(buf: []u8, call_n: u64, cap: u64, tools: u64) []const u8 {
+ if (cap == 0)
+ return std.fmt.bufPrint(buf, "· turn still going · model call {d} · {d} tools", .{ call_n, tools }) catch buf[0..0];
+ return std.fmt.bufPrint(buf, "· turn still going · model call {d}/{d} · {d} tools", .{ call_n, cap, tools }) catch buf[0..0];
+}
+
+pub fn emitRetryNotice(io: Io, class: []const u8, attempt: usize, max_attempts: usize) void {
+ var buf: [120]u8 = undefined;
+ const text = formatRetryNotice(&buf, class, attempt, max_attempts);
+ if (text.len == 0) return;
+ tool_pulse.emitNotice(io, "{s}", .{text});
+}
+
+/// Count this inner-loop request, pulse from call 2, optionally pause if a
+/// non-zero cap is set. Returns pause text or null to proceed. Never pauses
+/// when the cap is 0.
+pub fn beforeRequest(self: *Agent) !?[]const u8 {
+ self.model_calls_this_turn += 1;
+ const cap = max_turn_model_calls;
+ if (self.model_calls_this_turn >= 2 and !self.sub and !main_mod.json_mode) {
+ var buf: [120]u8 = undefined;
+ const text = formatTurnPulse(&buf, self.model_calls_this_turn, cap, self.tool_calls_this_turn);
+ if (text.len > 0) tool_pulse.emitNotice(self.io, "{s}", .{text});
+ }
+ if (cap != 0 and self.model_calls_this_turn > cap) {
+ return try std.fmt.allocPrint(
+ self.arena,
+ "paused after {d} model calls this turn ({d} tools). Reply to continue, or steer.",
+ .{ cap, self.tool_calls_this_turn },
+ );
+ }
+ return null;
+}
+
+test "default inner-loop cap is unlimited / 0 unless an explicit override parses" {
+ try std.testing.expectEqual(@as(u64, 0), max_turn_model_calls);
+ try std.testing.expectEqual(@as(u64, 0), parseMaxTurnCalls(""));
+ try std.testing.expectEqual(@as(u64, 0), parseMaxTurnCalls(" "));
+ try std.testing.expectEqual(@as(u64, 0), parseMaxTurnCalls("nope"));
+ try std.testing.expectEqual(@as(u64, 32), parseMaxTurnCalls("32"));
+ try std.testing.expectEqual(@as(u64, 16), parseMaxTurnCalls(" 16 "));
+}
+
+test "formatRetryNotice names HungRequest and UnknownHostName with attempt n/N" {
+ var buf: [80]u8 = undefined;
+ try std.testing.expectEqualStrings("· retry 3/6 · HungRequest", formatRetryNotice(&buf, "HungRequest", 3, 6));
+ try std.testing.expectEqualStrings("· retry 1/6 · UnknownHostName", formatRetryNotice(&buf, "UnknownHostName", 1, 6));
+}
+
+test "formatTurnPulse omits a denominator when the cap is unlimited" {
+ var buf: [80]u8 = undefined;
+ try std.testing.expectEqualStrings("· turn still going · model call 3 · 11 tools", formatTurnPulse(&buf, 3, 0, 11));
+ try std.testing.expectEqualStrings("· turn still going · model call 3/64 · 11 tools", formatTurnPulse(&buf, 3, 64, 11));
+}