Skip to content

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

Python

fix(tools): tag-check every model-supplied JSON deref before reading it

Rach Pradhanf1cce8600374
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 68ff9964..a16501eb 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -170,17 +170,21 @@ pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {
try self.say("[api error: choice had no message]\n", .{});
return error.ApiError;
};
+ const msg_obj = tools_mod.json_args.object(message) orelse {
+ try self.say("[api error: choice message was not an object]\n", .{});
+ return error.ApiError;
+ };
try self.messages.append(message); // echo verbatim (content may be null)
var final_text: []const u8 = "";
- if (message.object.get("content")) |c| if (c == .string and c.string.len > 0) {
+ if (msg_obj.get("content")) |c| if (c == .string and c.string.len > 0) {
final_text = c.string;
try surfaceUnstreamedText(self, c.string);
};
var calls: std.ArrayList(ToolCall) = .empty;
defer calls.deinit(self.gpa);
- if (message.object.get("tool_calls")) |tcs| if (tcs == .array) {
+ if (msg_obj.get("tool_calls")) |tcs| if (tcs == .array) {
for (tcs.array.items) |tc| {
if (tc != .object) continue;
const function = tc.object.get("function") orelse continue;
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 2fcf6f10..5f90a4f3 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -297,7 +297,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
if (!self.sub) try self.say("\xe2\x8f\xb8 completion deferred \xe2\x80\x94 the standing goal's checklist isn't settled\n", .{});
return .{ .text = refusal, .is_error = true };
}
- const result = if (call.input.object.get("result")) |r| r.string else "";
+ const result = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "result") orelse "") else "";
self.completed = try self.arena.dupe(u8, result);
// .complete retires the epoch (goal_state.currentEpoch) and the checklist parks - readable, no longer current, never deleted (#318).
// A --goal standing objective is exempt: the completion is recorded above, the steering stays, and only /goal clear|pause|<new> retires it.
@@ -312,13 +312,13 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
return .{ .text = "completion recorded", .is_error = false };
}
if (std.mem.eql(u8, call.name, "eval")) {
- const note = if (call.input.object.get("note")) |n| (if (n == .string) n.string else "") else "";
+ const note = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "note") orelse "") else "";
return self.runEval(note);
}
if (std.mem.eql(u8, call.name, "todo_write")) {
// Epoch-scoped replace, keeping omitted completed items; a write with
// no usable items is rejected untouched (#318). goal_todo owns the rule.
- const r = try goal_todo.applyTodoWrite(self, call.input.object.get("todos"));
+ const r = try goal_todo.applyTodoWrite(self, if (tools_mod.json_args.object(call.input)) |o| o.get("todos") else null);
if (!self.sub and !r.rejected) try self.say("{s}\n", .{r.text});
return .{ .text = r.text, .is_error = r.rejected };
}
@@ -356,7 +356,7 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
.is_error = true,
};
const w = self.out.?;
- const question = if (call.input.object.get("question")) |q| q.string else "(no question)";
+ const question = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "question") orelse "(no question)") else "(no question)";
if (main_mod.json_mode) {
const call_id = if (call.id.len > 0) call.id else blk: {
const id = try std.fmt.allocPrint(self.arena, "ask_user-{d}", .{self.next_ask_id});
@@ -381,8 +381,8 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
}
// Skip the re-print only when the question streamed live in full.
if (!self.argStreamedFully(call)) try w.print("\n❓ {s}\n", .{question});
- if (call.input.object.get("options")) |opts| if (opts == .array) {
- for (opts.array.items, 1..) |opt, n| try w.print(" {d}) {s}\n", .{ n, opt.string });
+ if (tools_mod.json_args.object(call.input)) |o| if (tools_mod.json_args.arrayOf(o, "options")) |opts| {
+ for (opts, 1..) |opt, n| try w.print(" {d}) {s}\n", .{ n, tools_mod.json_args.text(opt) orelse "(non-text option)" });
};
try w.writeAll(" your answer › ");
try w.flush();
diff --git a/src/exec.zig b/src/exec.zig
index 5698cd73..4553c8b9 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -195,7 +195,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
.text = try gpa.dupe(u8, "command not pre-approved — subagents may only run user-approved or read-only commands, with no chaining/pipes/redirection. Use read_file/edit_file/write_file, or report back what you need run."),
.is_error = true,
};
- const bg = if (input == .object) (if (input.object.get("run_in_background")) |v| v == .bool and v.bool else false) else false;
+ const bg = tools.json_args.flag(input, "run_in_background");
if (bg) {
const job = spawnJob(gpa, io, cmd) catch |err| return .{
// #122: backgrounding costs MORE fds (pipes + pump task), so the
@@ -282,7 +282,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);
const start_line = intField(input, "start_line");
const end_line = intField(input, "end_line");
- const want_compact = if (input == .object) (if (input.object.get("compact")) |v| v == .bool and v.bool else false) else false;
+ const want_compact = tools.json_args.flag(input, "compact");
// #66: opt-in compact view routes to `codedb read <path> [-L a-b] --compact`
// when codedb is present and this file is indexed. Lossy (strips comments/
// blanks, shows line numbers) so it is NEVER the default and is labeled
@@ -368,7 +368,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
const old = strField(input, "old_string") orelse return missingArg(gpa, "old_string");
const new = strField(input, "new_string") orelse return missingArg(gpa, "new_string");
if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);
- const all = if (input.object.get("replace_all")) |v| v == .bool and v.bool else false;
+ const all = tools.json_args.flag(input, "replace_all");
if (old.len == 0) return .{ .text = try gpa.dupe(u8, "old_string must not be empty"), .is_error = true };
// #276 P0-1: resolve under the agent's isolated worktree when set.
diff --git a/src/json_args.zig b/src/json_args.zig
new file mode 100644
index 00000000..baa9e7f7
--- /dev/null
+++ b/src/json_args.zig
@@ -0,0 +1,139 @@
+//! Tag-checked accessors for model-supplied JSON tool arguments.
+//!
+//! A model can emit any JSON shape as tool arguments — nothing constrains it
+//! to what a tool's schema promises. Reading `v.object`/`v.string`/`v.array`
+//! off a `std.json.Value` without first checking its active tag panics in a
+//! Debug build but is UNDEFINED BEHAVIOR in ReleaseFast (the shipped build):
+//! the union access is unchecked there, so a wrong-tag read silently
+//! reinterprets whatever bytes happen to be in the payload as an object/
+//! string/array header. Every accessor below returns null (or false, for
+//! `flag`) on a tag mismatch instead, so a caller can turn a malformed
+//! argument tree into an ordinary `is_error` tool result the model can see
+//! and react to, rather than a memory-safety incident.
+
+const std = @import("std");
+const Value = std.json.Value;
+const ObjectMap = std.json.ObjectMap;
+
+pub fn object(v: Value) ?ObjectMap {
+ return if (v == .object) v.object else null;
+}
+
+pub fn text(v: Value) ?[]const u8 {
+ return if (v == .string) v.string else null;
+}
+
+pub fn list(v: Value) ?[]const Value {
+ return if (v == .array) v.array.items else null;
+}
+
+pub fn str(o: ObjectMap, name: []const u8) ?[]const u8 {
+ return text(o.get(name) orelse return null);
+}
+
+pub fn arrayOf(o: ObjectMap, name: []const u8) ?[]const Value {
+ return list(o.get(name) orelse return null);
+}
+
+/// Takes the RAW argument tree: a flag on a non-object argument tree is
+/// simply false.
+pub fn flag(v: Value, name: []const u8) bool {
+ const o = object(v) orelse return false;
+ const f = o.get(name) orelse return false;
+ return f == .bool and f.bool;
+}
+
+test "accessors return null on a tag mismatch instead of dereferencing (ReleaseFast UB)" {
+ const string_v: Value = .{ .string = "x" };
+ const int_v: Value = .{ .integer = 5 };
+ const bool_v: Value = .{ .bool = true };
+ const null_v: Value = .null;
+ var arr = std.json.Array.init(std.testing.allocator);
+ defer arr.deinit();
+ try arr.append(.{ .integer = 1 });
+ const arr_v: Value = .{ .array = arr };
+ const obj_v: Value = .{ .object = ObjectMap.empty };
+
+ for ([_]Value{ string_v, int_v, bool_v, null_v, arr_v }) |v| {
+ try std.testing.expect(object(v) == null);
+ }
+ try std.testing.expect(object(obj_v) != null);
+
+ for ([_]Value{ int_v, bool_v, null_v, arr_v, obj_v }) |v| {
+ try std.testing.expect(text(v) == null);
+ }
+ try std.testing.expect(text(string_v) != null);
+
+ for ([_]Value{ string_v, int_v, bool_v, null_v, obj_v }) |v| {
+ try std.testing.expect(list(v) == null);
+ }
+ try std.testing.expect(list(arr_v) != null);
+}
+
+test "str/arrayOf survive every malformed tool-argument shape a model actually emits" {
+ const gpa = std.testing.allocator;
+ const shapes = [_][]const u8{
+ "{\"result\":5}",
+ "{\"question\":[]}",
+ "{\"options\":[1,2]}",
+ "{\"note\":null}",
+ "{\"prompt\":{}}",
+ };
+ for (shapes) |shape| {
+ const parsed = try std.json.parseFromSlice(Value, gpa, shape, .{});
+ defer parsed.deinit();
+ const o = object(parsed.value).?;
+ var it = o.iterator();
+ while (it.next()) |entry| {
+ try std.testing.expect(str(o, entry.key_ptr.*) == null);
+ }
+ }
+
+ const opts_parsed = try std.json.parseFromSlice(Value, gpa, "{\"options\":[1,2]}", .{});
+ defer opts_parsed.deinit();
+ const opts_obj = object(opts_parsed.value).?;
+ const opts = arrayOf(opts_obj, "options").?;
+ try std.testing.expectEqual(@as(usize, 2), opts.len);
+ for (opts) |item| try std.testing.expect(text(item) == null);
+
+ const top_level = [_][]const u8{ "[1,2]", "\"hi\"", "5", "null" };
+ for (top_level) |shape| {
+ const parsed = try std.json.parseFromSlice(Value, gpa, shape, .{});
+ defer parsed.deinit();
+ try std.testing.expect(object(parsed.value) == null);
+ }
+}
+
+test "flag is true only for an explicit boolean true" {
+ const gpa = std.testing.allocator;
+ {
+ const parsed = try std.json.parseFromSlice(Value, gpa, "{\"b\":true}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(flag(parsed.value, "b"));
+ }
+ {
+ const parsed = try std.json.parseFromSlice(Value, gpa, "{\"b\":false}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(!flag(parsed.value, "b"));
+ }
+ {
+ const parsed = try std.json.parseFromSlice(Value, gpa, "{\"b\":\"true\"}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(!flag(parsed.value, "b"));
+ }
+ {
+ const parsed = try std.json.parseFromSlice(Value, gpa, "{\"b\":1}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(!flag(parsed.value, "b"));
+ }
+ {
+ const parsed = try std.json.parseFromSlice(Value, gpa, "{}", .{});
+ defer parsed.deinit();
+ try std.testing.expect(!flag(parsed.value, "b"));
+ }
+ {
+ const parsed = try std.json.parseFromSlice(Value, gpa, "[1]", .{});
+ defer parsed.deinit();
+ try std.testing.expect(!flag(parsed.value, "b"));
+ }
+}
diff --git a/src/subagent.zig b/src/subagent.zig
index 38d68a64..1afd9ab8 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -52,15 +52,15 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {
.text = try ctx.gpa.dupe(u8, "subagents cannot spawn subagents — do this work yourself"),
.is_error = true,
};
- const label = if (input.object.get("description")) |d| (if (d == .string) d.string else "subagent") else "subagent";
- const prompt = if (input.object.get("prompt")) |p| (if (p == .string) p.string else "") else "";
+ const obj = tools.json_args.object(input) orelse return .{ .text = try ctx.gpa.dupe(u8, "subagent: arguments must be a JSON object with a \"prompt\" string"), .is_error = true };
+ const label = tools.json_args.str(obj, "description") orelse "subagent";
+ const prompt = tools.json_args.str(obj, "prompt") orelse "";
if (prompt.len == 0) return .{ .text = try ctx.gpa.dupe(u8, "subagent: missing required \"prompt\" (a self-contained task)"), .is_error = true };
- const sys_override = fleet.resolveOverride(input.object);
- const niche = fleet.resolveNiche(input.object);
- const isolation = fleet.resolveIsolation(input.object);
- const isolation_fallback = fleet.resolveIsolationFallback(input.object);
- const background = if (input.object.get("run_in_background")) |v| v == .bool and v.bool else false;
- if (background) return spawnSubBackground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback);
+ const sys_override = fleet.resolveOverride(obj);
+ const niche = fleet.resolveNiche(obj);
+ const isolation = fleet.resolveIsolation(obj);
+ const isolation_fallback = fleet.resolveIsolationFallback(obj);
+ if (tools.json_args.flag(input, "run_in_background")) return spawnSubBackground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback);
const run = try runSub(ctx, "subagent", label, prompt, sys_override, niche, isolation, isolation_fallback);
return run.output;
}
diff --git a/src/tools.zig b/src/tools.zig
index 7cd6648b..031faf17 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -71,6 +71,7 @@ const approvals_mod = @import("approvals.zig");
const Approvals = approvals_mod.Approvals;
const skills = @import("skills.zig");
const run_budget_mod = @import("run_budget.zig");
+pub const json_args = @import("json_args.zig");
pub const ToolOutput = struct {
text: []u8 = &.{}, // gpa-owned
diff --git a/src/workflow.zig b/src/workflow.zig
index e24056a9..95c8a2a9 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -217,12 +217,19 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
};
// Pipeline mode (#3): {pipeline:{items,stages}} maps each item through the
// stages with no barrier — distinct from phases (fan-out + synthesis).
- if (input.object.get("pipeline")) |pv| return runPipeline(ctx, pv);
- const phases_val = input.object.get("phases") orelse return .{
+ const obj = tools.json_args.object(input) orelse return .{
+ .text = try gpa.dupe(u8, "workflow: arguments must be a JSON object with a \"phases\" array (or a \"pipeline\" object)"),
+ .is_error = true,
+ };
+ if (obj.get("pipeline")) |pv| return runPipeline(ctx, pv);
+ const phases_val = obj.get("phases") orelse return .{
.text = try gpa.dupe(u8, "workflow needs a \"phases\" array (or a \"pipeline\" object)"),
.is_error = true,
};
- const phases = phases_val.array.items;
+ const phases = tools.json_args.list(phases_val) orelse return .{
+ .text = try gpa.dupe(u8, "workflow: \"phases\" must be an array of phase objects"),
+ .is_error = true,
+ };
if (phases.len == 0 or phases.len > max_workflow_phases) return .{
.text = try std.fmt.allocPrint(gpa, "workflow needs 1-{d} phases", .{max_workflow_phases}),
.is_error = true,
@@ -418,3 +425,33 @@ test "pipelinePrompt substitutes {{item}}/{{prev}} and appends when omitted (#3)
try std.testing.expect(std.mem.indexOf(u8, s3, "Result from the previous stage:") != null);
try std.testing.expect(std.mem.indexOf(u8, s3, "DONE") != null);
}
+
+test "execWorkflow rejects a non-object argument tree instead of dereferencing it" {
+ var ctx: ToolCtx = undefined;
+ ctx.gpa = std.testing.allocator;
+ ctx.from_sub = false;
+
+ const out1 = try execWorkflow(ctx, .{ .string = "do it" });
+ try std.testing.expect(out1.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out1.text, "object") != null);
+ std.testing.allocator.free(out1.text);
+
+ const parsed = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"phases\":\"nope\"}", .{});
+ defer parsed.deinit();
+ const out2 = try execWorkflow(ctx, parsed.value);
+ try std.testing.expect(out2.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, out2.text, "array") != null);
+ std.testing.allocator.free(out2.text);
+}
+
+test "execSubagent rejects a non-object argument tree instead of dereferencing it" {
+ var ctx: ToolCtx = undefined;
+ ctx.gpa = std.testing.allocator;
+ ctx.from_sub = false;
+
+ const parsed = try std.json.parseFromSlice(Value, std.testing.allocator, "[1,2]", .{});
+ defer parsed.deinit();
+ const out = try subagent.execSubagent(ctx, parsed.value);
+ try std.testing.expect(out.is_error);
+ std.testing.allocator.free(out.text);
+}