Skip to content

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

Python

feat(embedder): hard --no-local-tools gate (#330)

Rach Pradhanbd1113e3e819
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dc29a309..f42641d8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -91,6 +91,9 @@ jobs:
- name: Smolify lazy public-only and secret-egress boundary
run: python3 scripts/test-smolify-boundary.py --graff zig-out/bin/graff
+ - name: Embedder mode --no-local-tools gate (#330)
+ run: python3 scripts/test-no-local-tools.py --graff zig-out/bin/graff
+
- name: Live JSON stream contains no raw stdout lines
run: python3 scripts/test-json-live.py zig-out/bin/graff
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 5c93c2ec..a4707d84 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -10,7 +10,7 @@
"src/main.zig",
"src/repl.zig"
],
- "test_count_baseline": 627,
+ "test_count_baseline": 633,
"required_invariants": [
{
"id": "goal-epochs",
diff --git a/scripts/test-no-local-tools.py b/scripts/test-no-local-tools.py
new file mode 100644
index 00000000..94b9bd61
--- /dev/null
+++ b/scripts/test-no-local-tools.py
@@ -0,0 +1,398 @@
+#!/usr/bin/env python3
+"""Offline end-to-end proof of the #330 `--no-local-tools` embedder gate.
+
+One scripted codex/Responses mock plus one Streamable HTTP MCP server stand in
+for the embedder's shape: the harness runs on the trusted host, the sandbox is
+reached only through MCP. Two scenarios run the same script.
+
+gated (`--no-local-tools`)
+ * the tools array the provider receives carries none of the seven local
+ execution tools, still carries webfetch/orchestration, and still carries the
+ MCP server's tool;
+ * a hallucinated `bash` call comes back as a tool error naming the flag, and
+ the command never runs (the marker it would print appears nowhere);
+ * a subagent inherits the gate - its own catalog is filtered too, and its
+ hallucinated `bash` call is refused the same way;
+ * the MCP tool still executes and its result reaches the model.
+
+control (same script, no flag)
+ * the identical `bash` call runs and its output comes back, so the diff
+ between the two runs is the gate and nothing else.
+"""
+
+from __future__ import annotations
+
+import argparse
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import threading
+from typing import Any
+
+from codex_ws_mock import CodexMock, RecordedRequest
+
+GATED_TOOLS = (
+ "bash",
+ "bash_output",
+ "bash_kill",
+ "read_file",
+ "edit_file",
+ "write_file",
+ "codedb",
+)
+# The marker is split by an empty shell quote, so the whole string only ever
+# exists because /bin/sh actually ran the command - it is not a substring of the
+# command text the model sent, which is echoed back in requests and events.
+ESCAPE_MARKER = "GATE_ESCAPED_a26362"
+BASH_COMMAND = "printf %s GATE_ESCAPED''_a26362"
+MCP_RESULT = "sandbox exec ok (via MCP)"
+FINAL_TEXT = "done"
+
+ROOT_BASH_CALL = "call_root_bash"
+SUBAGENT_CALL = "call_root_subagent"
+MCP_CALL = "call_root_mcp"
+CHILD_BASH_CALL = "call_child_bash"
+
+
+class SandboxMcp(BaseHTTPRequestHandler):
+ """A stand-in for the embedder's sandbox-proxy MCP server."""
+
+ protocol_version = "HTTP/1.1"
+ calls: list[dict[str, Any]] = []
+ lock = threading.Lock()
+
+ def log_message(self, _format: str, *_args: object) -> None:
+ pass
+
+ def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
+ length = int(self.headers.get("Content-Length", "0"))
+ message = json.loads(self.rfile.read(length))
+ method = message.get("method")
+ if method == "tools/list":
+ result = {
+ "tools": [
+ {
+ "name": "exec",
+ "description": "Run a command inside the sandbox VM.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"command": {"type": "string"}},
+ "required": ["command"],
+ },
+ }
+ ]
+ }
+ elif method == "tools/call":
+ with self.lock:
+ self.calls.append(message.get("params", {}))
+ result = {"content": [{"type": "text", "text": MCP_RESULT}]}
+ else:
+ result = {}
+ body = json.dumps(
+ {"jsonrpc": "2.0", "id": message.get("id"), "result": result},
+ separators=(",", ":"),
+ ).encode()
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Content-Type", "application/json")
+ self.end_headers()
+ self.wfile.write(body)
+
+
+def message_item(text: str, item_id: str) -> dict:
+ return {
+ "type": "message",
+ "id": item_id,
+ "status": "completed",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": text, "annotations": []}],
+ }
+
+
+def call_item(name: str, call_id: str, arguments: dict) -> dict:
+ return {
+ "type": "function_call",
+ "id": f"fc_{call_id}",
+ "call_id": call_id,
+ "name": name,
+ "arguments": json.dumps(arguments, separators=(",", ":")),
+ "status": "completed",
+ }
+
+
+def response_events(item: dict, response_id: str) -> list[dict]:
+ return [
+ {"type": "response.output_item.done", "item": item},
+ {
+ "type": "response.completed",
+ "response": {
+ "id": response_id,
+ "usage": {
+ "input_tokens": 900,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 100,
+ "total_tokens": 1000,
+ },
+ },
+ },
+ ]
+
+
+def tool_names(request: RecordedRequest) -> list[str]:
+ tools = request.body.get("tools")
+ return [t.get("name") for t in tools] if isinstance(tools, list) else []
+
+
+def mcp_tool_name(names: list[str]) -> str:
+ remote = [n for n in names if isinstance(n, str) and n.startswith("mcp__")]
+ if len(remote) != 1:
+ raise AssertionError(f"expected exactly one MCP tool, saw {remote!r}")
+ return remote[0]
+
+
+def script(request: RecordedRequest) -> list[dict]:
+ """Drive root and child through the same fixed sequence of tool calls.
+
+ Keyed on which call ids the request's own input already carries, so it does
+ not depend on how root and child requests interleave in wall-clock order.
+ """
+ names = tool_names(request)
+ seen = json.dumps(request.body.get("input"), separators=(",", ":"))
+ tag = f"resp_{request.ordinal}"
+ if "subagent" not in names: # a child: its catalog is base tools only
+ if CHILD_BASH_CALL not in seen:
+ return response_events(
+ call_item("bash", CHILD_BASH_CALL, {"command": BASH_COMMAND}), tag
+ )
+ return response_events(message_item("child done", f"msg_{tag}"), tag)
+ if ROOT_BASH_CALL not in seen:
+ return response_events(
+ call_item("bash", ROOT_BASH_CALL, {"command": BASH_COMMAND}), tag
+ )
+ if SUBAGENT_CALL not in seen:
+ return response_events(
+ call_item(
+ "subagent",
+ SUBAGENT_CALL,
+ {
+ "description": "probe the gate",
+ "prompt": "Try to run a shell command, then report what happened.",
+ },
+ ),
+ tag,
+ )
+ if MCP_CALL not in seen:
+ return response_events(
+ call_item(mcp_tool_name(names), MCP_CALL, {"command": "ls /"}), tag
+ )
+ return response_events(message_item(FINAL_TEXT, f"msg_{tag}"), tag)
+
+
+def run_graff(graff: Path, port: int, mcp_port: int, mode: str) -> list[dict]:
+ """One `--json` one-shot turn; returns the emitted JSONL events.
+
+ `mode` is "flag" (--no-local-tools), "env" (GRAFF_NO_LOCAL_TOOLS=1) or
+ "off" (the control run).
+ """
+ with tempfile.TemporaryDirectory(prefix="graff-no-local-tools-") as tmp:
+ workspace = Path(tmp)
+ codex_home = workspace / "codex-home"
+ codex_home.mkdir()
+ (codex_home / "auth.json").write_text(
+ json.dumps(
+ {
+ "tokens": {
+ "access_token": "no-local-tools-mock",
+ "account_id": "acct-no-local-tools",
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ (workspace / ".mcp.json").write_text(
+ json.dumps(
+ {"mcpServers": {"sandbox": {"url": f"http://127.0.0.1:{mcp_port}/mcp"}}},
+ separators=(",", ":"),
+ ),
+ encoding="utf-8",
+ )
+ settings = workspace / ".harness" / "settings.json"
+ settings.parent.mkdir()
+ settings.write_text(
+ json.dumps({"skills": {"codedbpro": False, "muonry": False}}),
+ encoding="utf-8",
+ )
+
+ env = os.environ.copy()
+ for name in tuple(env):
+ if name.startswith("GRAFF_") or name.startswith("CODEX_"):
+ env.pop(name)
+ env.update(
+ {
+ "HOME": tmp,
+ "CODEX_HOME": str(codex_home),
+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_SMOLIFY": "1",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_BEHAVIOR_TRACE": "0",
+ }
+ )
+ if mode == "env":
+ env["GRAFF_NO_LOCAL_TOOLS"] = "1"
+ argv = [str(graff), "--model", "codex", "--json", "--yolo", "--no-telemetry"]
+ if mode == "flag":
+ argv.append("--no-local-tools")
+ completed = subprocess.run(
+ argv,
+ cwd=tmp,
+ env=env,
+ input=json.dumps({"type": "user", "text": "run the probe"}) + "\n",
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=90,
+ check=False,
+ )
+ if completed.returncode != 0:
+ raise AssertionError(
+ f"graff exited {completed.returncode}\n"
+ f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
+ )
+ events = []
+ for line in completed.stdout.splitlines():
+ if line.strip():
+ events.append(json.loads(line))
+ return events
+
+
+def tool_results(events: list[dict], name: str) -> list[dict]:
+ return [
+ e for e in events if e.get("type") == "tool_result" and e.get("name") == name
+ ]
+
+
+def assert_gated(requests: list[RecordedRequest], events: list[dict]) -> None:
+ root = [r for r in requests if "subagent" in tool_names(r)]
+ child = [r for r in requests if "subagent" not in tool_names(r)]
+ if not root or not child:
+ raise AssertionError(
+ f"expected both root and child requests, saw {len(root)}/{len(child)}"
+ )
+
+ # Layer 1, root: nothing local advertised; webfetch, orchestration and the
+ # MCP-sourced sandbox tool all survive.
+ names = tool_names(root[0])
+ leaked = [n for n in names if n in GATED_TOOLS]
+ if leaked:
+ raise AssertionError(f"root catalog still advertises {leaked!r}")
+ for expected in ("webfetch", "subagent", "workflow", "todo_write"):
+ if expected not in names:
+ raise AssertionError(f"root catalog lost {expected}: {names!r}")
+ mcp_tool_name(names)
+
+ # Layer 1, child: subagents inherit the gate.
+ child_names = tool_names(child[0])
+ child_leaked = [n for n in child_names if n in GATED_TOOLS]
+ if child_leaked:
+ raise AssertionError(f"subagent catalog still advertises {child_leaked!r}")
+ if "webfetch" not in child_names:
+ raise AssertionError(f"subagent catalog lost webfetch: {child_names!r}")
+
+ # Layer 2, root: the hallucinated bash call is refused, not run.
+ results = tool_results(events, "bash")
+ if len(results) != 1 or not results[0].get("is_error"):
+ raise AssertionError(f"bash was not refused as a tool error: {results!r}")
+ if "--no-local-tools" not in results[0].get("text", ""):
+ raise AssertionError(f"refusal does not name the flag: {results[0]!r}")
+
+ # Layer 2, child: the refusal is what the child's next request carries back.
+ child_followups = [
+ r for r in child if CHILD_BASH_CALL in json.dumps(r.body, separators=(",", ":"))
+ ]
+ if not child_followups:
+ raise AssertionError("the child never reported its bash call back")
+ followup = json.dumps(child_followups[0].body, separators=(",", ":"))
+ if "--no-local-tools" not in followup:
+ raise AssertionError(f"child bash call was not refused: {followup[:800]}")
+
+ # Nothing executed: the marker never appears in any event or request body.
+ haystack = json.dumps(events, separators=(",", ":")) + json.dumps(
+ [r.body for r in requests], separators=(",", ":")
+ )
+ if ESCAPE_MARKER in haystack:
+ raise AssertionError("the gated bash command actually ran")
+
+ # MCP is unaffected: the sandbox tool ran and its output came back.
+ mcp_results = [
+ e
+ for e in events
+ if e.get("type") == "tool_result" and str(e.get("name", "")).startswith("mcp__")
+ ]
+ if len(mcp_results) != 1 or mcp_results[0].get("is_error"):
+ raise AssertionError(f"the MCP sandbox tool did not run: {mcp_results!r}")
+ if MCP_RESULT not in mcp_results[0].get("text", ""):
+ raise AssertionError(f"MCP result text missing: {mcp_results[0]!r}")
+ if not SandboxMcp.calls:
+ raise AssertionError("the MCP server never received a tools/call")
+
+
+def assert_control(requests: list[RecordedRequest], events: list[dict]) -> None:
+ names = tool_names(requests[0])
+ missing = [n for n in GATED_TOOLS if n not in names]
+ if missing:
+ raise AssertionError(f"ungated catalog is missing {missing!r}")
+ results = tool_results(events, "bash")
+ if len(results) != 1 or results[0].get("is_error"):
+ raise AssertionError(f"ungated bash did not run: {results!r}")
+ if ESCAPE_MARKER not in results[0].get("text", ""):
+ raise AssertionError(f"ungated bash produced no output: {results[0]!r}")
+
+
+def run(graff: Path) -> None:
+ mcp_server = ThreadingHTTPServer(("127.0.0.1", 0), SandboxMcp)
+ mcp_thread = threading.Thread(target=mcp_server.serve_forever, daemon=True)
+ mcp_thread.start()
+ try:
+ for mode, label in (
+ ("flag", "--no-local-tools: nothing local advertised, dispatch refused, MCP live"),
+ ("env", "GRAFF_NO_LOCAL_TOOLS=1 gates the run exactly like the flag"),
+ ("off", "control: the same scripted bash call runs without the gate"),
+ ):
+ SandboxMcp.calls = []
+ mock = CodexMock(events_for_request=script)
+ port = mock.start()
+ try:
+ events = run_graff(graff, port, mcp_server.server_port, mode)
+ requests = mock.recorded_requests()
+ finally:
+ mock.stop()
+ if mode == "off":
+ assert_control(requests, events)
+ else:
+ assert_gated(requests, events)
+ print(f"ok {label}")
+ finally:
+ mcp_server.shutdown()
+ mcp_server.server_close()
+ mcp_thread.join(timeout=5)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--graff", type=Path, default=Path("zig-out/bin/graff"))
+ args = parser.parse_args()
+ graff = args.graff.resolve()
+ if not graff.is_file():
+ parser.error(f"graff binary not found: {graff}")
+ run(graff)
+ print("--no-local-tools E2E passed")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/agent.zig b/src/agent.zig
index 5f6d27bd..4966e511 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -19,6 +19,7 @@ const tools_mod = @import("tools.zig");
const vision = @import("vision.zig");
const prompts = @import("prompts.zig");
const schema = @import("schema.zig");
+const no_local_tools = @import("no_local_tools.zig"); // #330: --no-local-tools picks the gated subagent catalogs
const models_cache = @import("models_cache.zig");
const keys_cli = @import("keys_cli.zig");
const run_budget_mod = @import("run_budget.zig");
@@ -240,11 +241,15 @@ pub const Agent = struct {
return schema.providerTakesEffort(self.provider.kind, self.provider.id, self.provider.model);
}
+ /// #330: a child's catalog is a comptime constant, so the gate picks the
+ /// pre-filtered twin rather than rebuilding one per subagent. Root catalogs
+ /// are filtered where they are assembled (schema.effectiveRootSpecs).
pub fn toolsJson(self: *const Agent) []const u8 {
+ const gated = no_local_tools.enabled;
return switch (self.provider.kind) {
- .anthropic => if (self.sub) schema.tools_anthropic_sub else self.tools_anthropic,
- .openai => if (self.sub) schema.tools_openai_sub else self.tools_openai,
- .responses => if (self.sub) schema.tools_responses_sub else self.tools_responses,
+ .anthropic => if (self.sub) (if (gated) schema.tools_anthropic_sub_remote else schema.tools_anthropic_sub) else self.tools_anthropic,
+ .openai => if (self.sub) (if (gated) schema.tools_openai_sub_remote else schema.tools_openai_sub) else self.tools_openai,
+ .responses => if (self.sub) (if (gated) schema.tools_responses_sub_remote else schema.tools_responses_sub) else self.tools_responses,
};
}
diff --git a/src/args.zig b/src/args.zig
index 9c368c3a..4b924600 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -24,6 +24,7 @@ const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
const learning_privacy = @import("learning_privacy.zig");
+const no_local_tools = @import("no_local_tools.zig"); // #330: `--no-local-tools` arms the process-global gate (same set-only pattern as the main_mod globals)
/// Every CLI-flag local main() used to declare, plus the resolved
/// positionals/subcommand-detection/one-shot-prompt outputs computed right
@@ -121,6 +122,8 @@ pub fn parse(init: std.process.Init) !Flags {
main_mod.max_model_calls = std.fmt.parseInt(u64, mv, 10) catch std.process.fatal("--max-model-calls needs a non-negative integer, got '{s}'", .{mv});
} else if (std.mem.eql(u8, arg, "--dedupe-tool-calls")) {
main_mod.dedupe_tool_calls = true;
+ } else if (std.mem.eql(u8, arg, "--no-local-tools")) {
+ no_local_tools.enabled = true; // #330: hard-disable the host-touching built-ins for the whole process (also GRAFF_NO_LOCAL_TOOLS=1)
} else if (std.mem.eql(u8, arg, "--clock-sleep")) {
main_mod.g_clock_sleep = true; // #225: opt in to the root-only clock_sleep meta tool (also GRAFF_CLOCK_SLEEP=1)
} else if (std.mem.eql(u8, arg, "--no-autocommit")) {
diff --git a/src/cli.zig b/src/cli.zig
index edeaacd5..d127b0ae 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -104,6 +104,7 @@ pub const usage_text =
\\ -w, --worktree <name> isolate this session in a git worktree (.graff/worktrees/<name>) so parallel agents don't collide on files
\\ --no-autocommit with -w, don't auto-commit each turn (default on; land work with `graff worktree merge`)
\\ --yolo skip all permission prompts for the session
+ \\ --no-local-tools embedder mode: hard-disable the built-in bash/bash_output/bash_kill/read_file/edit_file/write_file/codedb tools for the whole process (subagents included), so graff can run outside the sandbox and get its coding tools from an MCP server instead; webfetch, orchestration and MCP tools still work (GRAFF_NO_LOCAL_TOOLS=1)
\\ -p, --print one-shot print mode (answer on stdout, progress on stderr)
\\ --timing show per-tool wall-clock on result lines
\\ --cost show running session spend in the prompt
diff --git a/src/exec.zig b/src/exec.zig
index 2140d420..a6f1effc 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -1,11 +1,12 @@
-//! Tool dispatch: `execTool` (the timed/traced/hooked outer wrapper) and
+//! Tool dispatch: `execTool` (the timed/traced/hooked outer wrapper, whose
+//! guard chain starts with the #330 `--no-local-tools` refusal) and
//! `execToolInner` (the big per-tool-name switch — bash, bash_output,
//! bash_kill, webfetch, read_file, codedb, edit_file, write_file, subagent,
-//! workflow, learn_candidate). Split out of main.zig (600-line goal); LAST in the tool-exec
-//! region since it's the glue that imports tools.zig/subagent.zig/
-//! workflow.zig as siblings, plus approvals.zig/mcp.zig/jobs.zig/skills.zig/
-//! telemetry.zig. Back-imports main (as `main_mod`) for
-//! `ToolCall`/`plan_mode` (pub-flipped) and `utf8Prefix`.
+//! workflow, learn_candidate). Split out of main.zig (600-line goal); LAST in
+//! the tool-exec region since it's the glue that imports tools.zig/
+//! subagent.zig/workflow.zig as siblings, plus approvals.zig/mcp.zig/jobs.zig/
+//! skills.zig/telemetry.zig. Back-imports main (`main_mod`) for `ToolCall`/
+//! `plan_mode` (pub-flipped) and `utf8Prefix`.
const std = @import("std");
const Io = std.Io;
@@ -60,6 +61,7 @@ const read_file = @import("read_file.zig");
const hooks = @import("hooks.zig");
const telemetry = @import("telemetry.zig");
const learning_privacy = @import("learning_privacy.zig");
+const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate
/// Wall-clock ceiling for one *subagent* bash command. Subagents run on pool
/// threads with no TTY, so there is no Esc to kill a runaway command — without
@@ -94,7 +96,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 (codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call)) |blocked| {
+ if (noLocalToolsGate(ctx, call) orelse codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call)) |blocked| {
var out = blocked;
out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
if (ctx.tracer) |tr| {
@@ -123,6 +125,15 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
return out;
}
+/// #330 layer 2: refuse a host-touching built-in even if a provider hallucinates
+/// one that was never advertised (layer 1 is schema.zig). FIRST in the guard
+/// chain; an `mcp__*` name never matches, so the sandbox proxy keeps working.
+fn noLocalToolsGate(ctx: ToolCtx, call: ToolCall) ?ToolOutput {
+ if (!no_local_tools.blocks(call.name)) return null;
+ const text = ctx.gpa.dupe(u8, no_local_tools.refusal_text) catch return .{ .text = &.{}, .is_error = true };
+ return .{ .text = text, .is_error = true };
+}
+
fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
const gpa = ctx.gpa;
const io = ctx.io;
diff --git a/src/no_local_tools.zig b/src/no_local_tools.zig
new file mode 100644
index 00000000..39a4030c
--- /dev/null
+++ b/src/no_local_tools.zig
@@ -0,0 +1,232 @@
+//! #330 embedder mode: the hard `--no-local-tools` gate.
+//!
+//! An embedder runs graff as the reasoning loop on a TRUSTED host and reaches
+//! the sandbox only through tool calls, so the built-in tools that touch this
+//! machine have to be gone rather than merely un-approved. A permission rule is
+//! something a prompt-injected model can argue its way past; a tool that does
+//! not exist is not. The coding tools come back in over MCP - the embedder
+//! stands up a sandbox-proxy server and points graff at it - and this gate
+//! never touches MCP-sourced tools, which is the whole point.
+//!
+//! Two enforcement layers, both required, because either alone is a promise
+//! rather than a guarantee:
+//! 1. the gated tools are never advertised - schema.zig drops them from the
+//! root catalog (effectiveRootSpecs) and from the comptime subagent
+//! catalogs, so no provider is told they exist;
+//! 2. dispatch refuses - exec.zig's guard chain answers a hallucinated call
+//! with a tool error naming the flag, before anything runs.
+//!
+//! The switch is process-global on purpose. Subagents, workflow workers,
+//! retries and judges all run in-process through the same exec path, so one
+//! flag covers the whole agent tree and there is no per-agent state anyone can
+//! forget to inherit.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+/// Set once at startup by `--no-local-tools` (args.zig) or
+/// `GRAFF_NO_LOCAL_TOOLS=1` (session_run.zig). Never flipped mid-session.
+pub var enabled: bool = false;
+
+/// The built-in tools that reach this host: shell execution plus its two job
+/// controls, the three file tools, and codedb - which reads the host checkout
+/// through its own index. `webfetch` is deliberately absent: it is plain host
+/// HTTP with no sandbox to escape. So are the orchestration/meta tools, and
+/// everything MCP-sourced (an `mcp__*` name never matches here).
+pub const gated_tools = [_][]const u8{
+ "bash",
+ "bash_output",
+ "bash_kill",
+ "read_file",
+ "edit_file",
+ "write_file",
+ "codedb",
+};
+
+/// A name test only, independent of whether the gate is on, so the comptime
+/// catalog filter and the runtime refusal can share one list.
+pub fn isLocalTool(name: []const u8) bool {
+ for (gated_tools) |tool| {
+ if (std.mem.eql(u8, name, tool)) return true;
+ }
+ return false;
+}
+
+/// Layer 2's predicate: this call must be refused before anything runs.
+pub fn blocks(name: []const u8) bool {
+ return enabled and isLocalTool(name);
+}
+
+/// Refusal text. Names the flag so the model stops retrying the same call, and
+/// points it at what does work in this deployment.
+pub const refusal_text = "--no-local-tools is set for this process: the built-in bash, bash_output, bash_kill, read_file, edit_file, write_file and codedb tools are hard-disabled and cannot be re-enabled by asking. Run commands and touch files through the sandbox tools the connected MCP server provides instead; webfetch still works.";
+
+/// `GRAFF_NO_LOCAL_TOOLS` - affirmative-only, like GRAFF_CLOCK_SLEEP, and OR'd
+/// onto the CLI flag by the caller so a stray value can never turn
+/// `--no-local-tools` back off.
+pub fn envEnables(value: []const u8) bool {
+ return std.mem.eql(u8, value, "1") or
+ std.ascii.eqlIgnoreCase(value, "true") or
+ std.ascii.eqlIgnoreCase(value, "on") or
+ std.ascii.eqlIgnoreCase(value, "yes");
+}
+
+/// Layer 1, comptime half: the subagent catalogs are comptime constants, so
+/// their gated twin is computed once at compile time and merely selected at
+/// runtime.
+pub fn remoteSpecs(comptime Spec: type, comptime specs: []const Spec) []const Spec {
+ comptime {
+ var out: []const Spec = &.{};
+ for (specs) |spec| {
+ if (isLocalTool(spec.name)) continue;
+ out = out ++ [_]Spec{spec};
+ }
+ return out;
+ }
+}
+
+/// Layer 1, runtime half: the root catalog is picked at runtime (clock_sleep,
+/// learning), so the gated copy is built in the caller's arena. Returns the
+/// input untouched when the gate is off - no allocation on the normal path.
+pub fn filterRootSpecs(comptime Spec: type, arena: Allocator, specs: []const Spec) ![]const Spec {
+ if (!enabled) return specs;
+ const buf = try arena.alloc(Spec, specs.len);
+ var kept: usize = 0;
+ for (specs) |spec| {
+ if (isLocalTool(spec.name)) continue;
+ buf[kept] = spec;
+ kept += 1;
+ }
+ return buf[0..kept];
+}
+
+test "#330: the gated set is exactly the host-touching built-ins; webfetch, meta and MCP names are not gated" {
+ const saved = enabled;
+ defer enabled = saved;
+
+ for (gated_tools) |tool| try std.testing.expect(isLocalTool(tool));
+ try std.testing.expectEqual(@as(usize, 7), gated_tools.len);
+ for ([_][]const u8{ "webfetch", "skill", "subagent", "workflow", "todo_write", "eval", "mcp__sandbox__exec", "mcp__sandbox__bash" }) |tool|
+ try std.testing.expect(!isLocalTool(tool));
+
+ // blocks() is the gate, not the list: nothing is refused until it is on.
+ enabled = false;
+ for (gated_tools) |tool| try std.testing.expect(!blocks(tool));
+ enabled = true;
+ for (gated_tools) |tool| try std.testing.expect(blocks(tool));
+ try std.testing.expect(!blocks("webfetch"));
+ try std.testing.expect(!blocks("mcp__sandbox__bash"));
+}
+
+test "#330: GRAFF_NO_LOCAL_TOOLS is affirmative-only" {
+ for ([_][]const u8{ "1", "true", "TRUE", "on", "Yes" }) |value| try std.testing.expect(envEnables(value));
+ for ([_][]const u8{ "0", "off", "false", "no", "", "maybe" }) |value| try std.testing.expect(!envEnables(value));
+}
+
+test "#330: filterRootSpecs drops only the gated names, and does not allocate when the gate is off" {
+ const Spec = struct { name: []const u8 };
+ const specs = [_]Spec{
+ .{ .name = "bash" },
+ .{ .name = "webfetch" },
+ .{ .name = "read_file" },
+ .{ .name = "subagent" },
+ .{ .name = "codedb" },
+ };
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const saved = enabled;
+ defer enabled = saved;
+
+ enabled = false;
+ try std.testing.expectEqual(specs.len, (try filterRootSpecs(Spec, arena, &specs)).len);
+ try std.testing.expectEqual(@as(usize, 0), arena_state.queryCapacity());
+
+ enabled = true;
+ const gated = try filterRootSpecs(Spec, arena, &specs);
+ try std.testing.expectEqual(@as(usize, 2), gated.len);
+ try std.testing.expectEqualStrings("webfetch", gated[0].name);
+ try std.testing.expectEqualStrings("subagent", gated[1].name);
+}
+
+test "#330: neither catalog advertises a local tool under the gate, and webfetch survives in both" {
+ const schema = @import("schema.zig");
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const saved = enabled;
+ defer enabled = saved;
+
+ // Root catalog (runtime-assembled, and the one MCP tools are appended to).
+ enabled = false;
+ const open = try schema.effectiveRootSpecs(arena);
+ var open_local: usize = 0;
+ for (open) |spec| {
+ if (isLocalTool(spec.name)) open_local += 1;
+ }
+ try std.testing.expectEqual(gated_tools.len, open_local);
+
+ enabled = true;
+ const gated = try schema.effectiveRootSpecs(arena);
+ var kept_webfetch = false;
+ var kept_subagent = false;
+ for (gated) |spec| {
+ try std.testing.expect(!isLocalTool(spec.name));
+ if (std.mem.eql(u8, spec.name, "webfetch")) kept_webfetch = true;
+ if (std.mem.eql(u8, spec.name, "subagent")) kept_subagent = true;
+ }
+ try std.testing.expectEqual(open.len - gated_tools.len, gated.len);
+ try std.testing.expect(kept_webfetch); // pure host HTTP: no sandbox to escape
+ try std.testing.expect(kept_subagent); // orchestration stays; the child inherits the gate
+
+ // Subagent catalogs (comptime twins), in all three wire formats.
+ for ([_][]const u8{
+ schema.tools_anthropic_sub_remote,
+ schema.tools_openai_sub_remote,
+ schema.tools_responses_sub_remote,
+ }) |catalog| {
+ inline for (gated_tools) |tool|
+ try std.testing.expect(std.mem.indexOf(u8, catalog, "\"name\":\"" ++ tool ++ "\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, catalog, "\"name\":\"webfetch\"") != null);
+ }
+ // …and the ungated twins still carry them, so the filter is what changed.
+ try std.testing.expect(std.mem.indexOf(u8, schema.tools_anthropic_sub, "\"name\":\"bash\"") != null);
+}
+
+test "#330: dispatch refuses a hallucinated bash call for the root AND for a subagent" {
+ const exec = @import("exec.zig");
+ const tools = @import("tools.zig");
+ const gpa = std.testing.allocator;
+
+ const saved = enabled;
+ defer enabled = saved;
+
+ var parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"command\":\"echo gate-escaped\"}", .{});
+ defer parsed.deinit();
+
+ var client: std.http.Client = undefined;
+ var ctx: tools.ToolCtx = .{
+ .gpa = gpa,
+ .io = std.testing.io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ };
+
+ enabled = true;
+ // from_sub=true is the child path: a subagent's tool calls run through this
+ // very dispatch, so the process-global gate reaches them with no plumbing.
+ for ([_]bool{ false, true }) |from_sub| {
+ ctx.from_sub = from_sub;
+ const out = exec.execTool(ctx, .{ .id = "call_1", .name = "bash", .input = parsed.value });
+ defer gpa.free(out.text);
+ try std.testing.expect(out.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "--no-local-tools") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out.text, "gate-escaped") == null); // never ran
+ }
+}
diff --git a/src/schema.zig b/src/schema.zig
index a05822fb..c3deaf2d 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -14,6 +14,7 @@ const mcp = @import("mcp.zig");
const pricing = @import("pricing.zig");
const learn_store = @import("learn_store.zig");
const skill_docs = @import("skill_docs.zig"); // SKILL.md playbooks: the `skill` tool's name/desc/schema live there
+const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)
const root = @import("main.zig");
const provider_mod = @import("provider.zig");
@@ -38,28 +39,9 @@ const schema_serve_json =
\\ ]
\\}
;
-/// Launch flags relevant to SDK clients, embedded verbatim in `--schema`
-/// output so generated clients can surface them as first-class options.
-/// Pinned against learning_privacy.default_mode by a test there: the SDKs are
-/// generated from this text, so a stale default here is a promise the binary
-/// does not keep.
-pub const schema_flags_json =
- \\[
- \\ {"flag": "--model", "arg": "name", "description": "start on this model (same fuzzy resolution as /model)"},
- \\ {"flag": "--subagent-model", "arg": "name", "description": "pin direct subagents, workflow workers/retries, and judges to this model on the root provider; GRAFF_SUBAGENT_MODEL is the lower-precedence equivalent"},
- \\ {"flag": "--subagent-provider", "arg": "id", "description": "route pinned workers through this explicit provider; GRAFF_SUBAGENT_PROVIDER is the lower-precedence equivalent"},
- \\ {"flag": "--allow-cross-provider-subagents", "arg": null, "description": "explicitly consent to sending worker prompts, code, and tool results to a provider different from the root"},
- \\ {"flag": "--yolo", "arg": null, "description": "skip all permission prompts for the session"},
- \\ {"flag": "--system-prompt", "arg": "text", "description": "replace the built-in system prompt (cwd project-instructions file is still appended)"},
- \\ {"flag": "--append-system-prompt", "arg": "text", "description": "append extra text to the end of the system prompt"},
- \\ {"flag": "--json", "arg": null, "description": "structured stdio protocol (JSON in, JSONL events out)"},
- \\ {"flag": "--max-tool-calls", "arg": "N", "description": "hard per-turn root tool-call budget; rejected calls emit tool_rejected/tool_result"},
- \\ {"flag": "--max-model-calls", "arg": "N", "description": "opt-in invocation-wide provider-call ceiling shared by root, review, subagents, retries, title, compaction, and judges; default unlimited"},
- \\ {"flag": "--dedupe-tool-calls", "arg": null, "description": "reject duplicate root tool name+normalized-input calls per turn"},
- \\ {"flag": "--no-telemetry", "arg": null, "description": "disable anonymous OTEL usage telemetry for this run"},
- \\ {"flag": "--learning-privacy", "arg": "local|aggregate|templates|examples", "description": "set the prompt-learning egress ceiling; default aggregate (signed prompt-free grades), local sends nothing, and template text still requires exact interactive approval"}
- \\]
-;
+/// Launch flags for SDK clients (schema_protocol.zig, alongside the protocol
+/// doc it is emitted with), re-exported here as the `--schema` field name.
+pub const schema_flags_json = @import("schema_protocol.zig").flags;
const ToolSpec = struct {
name: []const u8,
desc: []const u8, // no characters needing JSON escapes
@@ -264,6 +246,14 @@ pub const tools_anthropic_sub = anthropicToolsJson(&base_specs);
pub const tools_openai_sub = openaiToolsJson(&base_specs);
pub const tools_responses_sub = responsesToolsJson(&base_specs);
+// #330 layer 1, subagent half: the same three catalogs with the host-touching
+// tools filtered out at compile time. agent.zig picks between the twins on
+// no_local_tools.enabled, so a child is never even told bash exists.
+const base_specs_remote = no_local_tools.remoteSpecs(ToolSpec, &base_specs);
+pub const tools_anthropic_sub_remote = anthropicToolsJson(base_specs_remote);
+pub const tools_openai_sub_remote = openaiToolsJson(base_specs_remote);
+pub const tools_responses_sub_remote = responsesToolsJson(base_specs_remote);
+
fn anthropicToolsJson(comptime specs: []const ToolSpec) []const u8 {
comptime {
var out: []const u8 = "[";
@@ -321,10 +311,15 @@ pub fn renderRootTools(
/// Root tool catalog for the current session: optional tools are absent unless
/// enabled and usable, avoiding schema tokens for calls that cannot succeed.
+/// #330 layer 1, root half: the gate then drops the host-touching tools from
+/// whichever catalog was chosen, so they are never advertised to a provider.
+/// MCP tools are appended afterwards by renderRootTools and stay untouched.
pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {
- _ = arena;
- if (root.g_clock_sleep) return if (learn_store.active_agent_loaded) &root_specs else &root_specs_without_learning;
- return if (learn_store.active_agent_loaded) &root_specs_without_clock else &root_specs_without_optional;
+ const chosen: []const ToolSpec = if (root.g_clock_sleep)
+ (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);
+ return no_local_tools.filterRootSpecs(ToolSpec, arena, chosen);
}
const Schema = union(enum) { raw: []const u8, value: Value };
@@ -497,6 +492,9 @@ pub fn emitSchema(w: *Io.Writer) !void {
try w.writeByte('\n');
try w.flush();
}
+test { // #330: the gate's own tests (advertising, dispatch, env) live with it
+ _ = no_local_tools;
+}
test "providerDisplayName & providerLoginKind: id mapping with sane fallbacks" {
try std.testing.expectEqualStrings("OpenAI", providerDisplayName("openai"));
try std.testing.expectEqualStrings("Codex (ChatGPT)", providerDisplayName("codex"));
diff --git a/src/schema_protocol.zig b/src/schema_protocol.zig
index 13d3e8a7..d98466b3 100644
--- a/src/schema_protocol.zig
+++ b/src/schema_protocol.zig
@@ -1,4 +1,30 @@
-//! Embedded documentation for Graff's newline-delimited JSON protocol.
+//! Embedded documentation for Graff's newline-delimited JSON protocol, plus
+//! the launch-flag list `--schema` publishes alongside it (schema.zig aliases
+//! both back; they live here to keep schema.zig under the 600-line ceiling).
+
+/// Launch flags relevant to SDK clients, embedded verbatim in `--schema`
+/// output so generated clients can surface them as first-class options.
+/// Pinned against learning_privacy.default_mode by a test there: the SDKs are
+/// generated from this text, so a stale default here is a promise the binary
+/// does not keep.
+pub const flags =
+ \\[
+ \\ {"flag": "--model", "arg": "name", "description": "start on this model (same fuzzy resolution as /model)"},
+ \\ {"flag": "--subagent-model", "arg": "name", "description": "pin direct subagents, workflow workers/retries, and judges to this model on the root provider; GRAFF_SUBAGENT_MODEL is the lower-precedence equivalent"},
+ \\ {"flag": "--subagent-provider", "arg": "id", "description": "route pinned workers through this explicit provider; GRAFF_SUBAGENT_PROVIDER is the lower-precedence equivalent"},
+ \\ {"flag": "--allow-cross-provider-subagents", "arg": null, "description": "explicitly consent to sending worker prompts, code, and tool results to a provider different from the root"},
+ \\ {"flag": "--yolo", "arg": null, "description": "skip all permission prompts for the session"},
+ \\ {"flag": "--no-local-tools", "arg": null, "description": "embedder mode: hard-disable the built-in bash/bash_output/bash_kill/read_file/edit_file/write_file/codedb tools for the whole process, so the harness can run outside the sandbox and source its coding tools from an MCP server instead; webfetch, orchestration and MCP tools are unaffected, and subagents inherit the gate. GRAFF_NO_LOCAL_TOOLS=1 is the equivalent"},
+ \\ {"flag": "--system-prompt", "arg": "text", "description": "replace the built-in system prompt (cwd project-instructions file is still appended)"},
+ \\ {"flag": "--append-system-prompt", "arg": "text", "description": "append extra text to the end of the system prompt"},
+ \\ {"flag": "--json", "arg": null, "description": "structured stdio protocol (JSON in, JSONL events out)"},
+ \\ {"flag": "--max-tool-calls", "arg": "N", "description": "hard per-turn root tool-call budget; rejected calls emit tool_rejected/tool_result"},
+ \\ {"flag": "--max-model-calls", "arg": "N", "description": "opt-in invocation-wide provider-call ceiling shared by root, review, subagents, retries, title, compaction, and judges; default unlimited"},
+ \\ {"flag": "--dedupe-tool-calls", "arg": null, "description": "reject duplicate root tool name+normalized-input calls per turn"},
+ \\ {"flag": "--no-telemetry", "arg": null, "description": "disable anonymous OTEL usage telemetry for this run"},
+ \\ {"flag": "--learning-privacy", "arg": "local|aggregate|templates|examples", "description": "set the prompt-learning egress ceiling; default aggregate (signed prompt-free grades), local sends nothing, and template text still requires exact interactive approval"}
+ \\]
+;
pub const json =
\\{
diff --git a/src/session_run.zig b/src/session_run.zig
index 2994d034..2b08dbfb 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -1,9 +1,8 @@
//! Agent-boot + run-loop entry helpers, split out of session_start.zig
-//! (600-line goal — session_start.zig itself crossed the line goal once
-//! this content grew). Covers everything from approvals/hooks/fleet-type
-//! loading through Agent construction, the `graff repl`/one-shot early-exit
-//! paths, session resume/finalize, and the skills/theme/PTY self-tests
-//! setup.
+//! (600-line goal — session_start.zig itself crossed the line goal once this
+//! content grew). Covers everything from approvals/hooks/fleet-type loading
+//! through Agent construction, the `graff repl`/one-shot early-exit paths,
+//! session resume/finalize, and the skills/theme/PTY self-tests setup.
//!
//! Same dangling-pointer discipline as session_start.zig: `buildRootAgent`
//! returns `agent_mod.Agent` by value — safe because its pointer fields
@@ -13,9 +12,8 @@
//! `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
-//! register itself (registering a `defer` in here would fire it when THIS
-//! function returns, not when main() does).
+//! `setupSkillsAndTheme` hands back which reset `defer`s main() must register
+//! itself (a `defer` here would fire when THIS function returns, not main()).
//!
//! Back-imports main (as main_mod) for Agent/the mutable globals it sets.
//! Sibling-imports everything else directly.
@@ -31,6 +29,7 @@ const tools_mod = @import("tools.zig");
const http = @import("http.zig");
const ws = @import("ws.zig");
const agent_ws = @import("agent_ws.zig"); // codex_ws_idle_ms override (#codex-ws)
+const no_local_tools = @import("no_local_tools.zig"); // #330: GRAFF_NO_LOCAL_TOOLS
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
@@ -415,14 +414,15 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
if (environ_map.get("GRAFF_CODEX_WS")) |v| {
main_mod.g_codex_ws = !(std.ascii.eqlIgnoreCase(v, "off") or std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no"));
}
- // #225: GRAFF_CLOCK_SLEEP=1|true|on|yes arms the root-only clock_sleep
- // meta tool (in addition to --clock-sleep). Affirmative-only, like
- // GRAFF_WS_FORCE_FAIL_ONCE below — OR'd onto the CLI flag so a
- // conflicting/absent env value never silently turns --clock-sleep back
- // off; default stays off.
+ // #225 GRAFF_CLOCK_SLEEP (root-only clock_sleep meta tool) and #330
+ // GRAFF_NO_LOCAL_TOOLS (the hard local-execution gate): both are
+ // affirmative-only (1|true|on|yes), like GRAFF_WS_FORCE_FAIL_ONCE below,
+ // and both are OR'd onto their CLI flag so a conflicting or absent env
+ // value can never silently turn --clock-sleep / --no-local-tools back off.
if (environ_map.get("GRAFF_CLOCK_SLEEP")) |v| {
main_mod.g_clock_sleep = main_mod.g_clock_sleep or std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");
}
+ if (environ_map.get("GRAFF_NO_LOCAL_TOOLS")) |v| no_local_tools.enabled = no_local_tools.enabled or no_local_tools.envEnables(v);
// (#codex-ws) GRAFF_CODEX_WS_IDLE_SECS raises/lowers the held-WS idle limit
// (default 4 min — the backend killed ours within 8.5 min idle; opencode
// pools at 5). Mirrors GRAFF_STREAM_STALL_SECS above: seconds, ignored if