Lightpanda: the headless browser designed for AI and automation
tools: drop null arguments in normalizeArgs
Adrià Arrufat8662ba62ca5c
diff --git a/src/agent/Agent.zig b/src/agent/Agent.zigindex 1518d37f4..34e4a6973 100644--- a/src/agent/Agent.zig+++ b/src/agent/Agent.zig@@ -1874,7 +1874,7 @@ fn processUserMessage(self: *Agent, input: TurnInput) !?[]const u8 {if (tool == .extract and idx != i) continue;}const ca = self.conversation.arena.allocator();- const args = browser_tools.normalizeArgKeys(ca, tool, tc.arguments) catch tc.arguments;+ const args = browser_tools.normalizeArgs(ca, tool, tc.arguments) catch tc.arguments;// Fall back to the navigation a read tool performed, so a// markdown/tree-driven turn isn't lost from `/save`.const saved: SavedCall = if (i < self.save_calls.items.len) self.save_calls.items[i] else .{};diff --git a/src/browser/tools.zig b/src/browser/tools.zigindex f785e1f33..793889d43 100644--- a/src/browser/tools.zig+++ b/src/browser/tools.zig@@ -909,8 +909,7 @@ pub const ToolResult = struct {selector: ?[]const u8 = null,/// Set for the tools `Tool.reportsPageState` names.page_state: ?PageState = null,- /// An in-band argument diagnosis (also `is_error`): telemetry counts it- /// as `invalid_params`, like the bare `error.InvalidParams` it replaces.+ /// Implies `is_error`; telemetry counts it as `invalid_params`.invalid_params: bool = false,fn invalidParams(text: []const u8) ToolResult {@@ -1043,11 +1042,11 @@ fn callInner(return .invalidParams(msg);// Must run before substituteStringArgs so the `key=="value"` secret-// redaction check there still triggers on PascalCase keys.- const normalized = normalizeArgKeys(arena, tool, arguments) catch |err| switch (err) {+ const normalized = normalizeArgs(arena, tool, arguments) catch |err| switch (err) {error.OutOfMemory => return error.OutOfMemory,error.DuplicateField => return error.InvalidParams,};- // After normalizeArgKeys so a PascalCase `Script` isn't reported missing.+ // After normalizeArgs so a PascalCase `Script` or a `null` isn't missed.if (diagnoseMissingRequired(arena, tool, normalized)) |msg|return .invalidParams(msg);const substituted = try substituteStringArgs(arena, tool, normalized);@@ -2790,9 +2789,8 @@ const ParseArgsError = error{ OutOfMemory, InvalidParams };/// Names the first required argument absent from the call, so a bare/// `InvalidParams` from `parseValue` doesn't hide which field to add — a/// caller sending `{"expression": ...}` to evaluate learns about `script`.-/// An explicit `null` counts as missing: zero-filling models send it for-/// "unset". Default-true booleans (setChecked.checked) parse fine when-/// omitted, so they don't count. Runs on key-normalized arguments.+/// Default-true booleans (setChecked.checked) parse fine when omitted, so+/// they don't count as missing. Runs on normalized arguments.fn diagnoseMissingRequired(arena: std.mem.Allocator, tool: Tool, arguments: ?std.json.Value) ?[]const u8 {const schemas = lp.Schema.all();const tool_idx = @backingInt(tool);@@ -2806,7 +2804,7 @@ fn diagnoseMissingRequired(arena: std.mem.Allocator, tool: Tool, arguments: ?stdelse => return null,} else std.json.ObjectMap.empty;for (schema.required) |name| {- if (obj.get(name)) |v| if (v != .null) continue;+ if (obj.get(name) != null) continue;if (schema.findField(name)) |f| {if (f.default_true) continue;}@@ -2879,12 +2877,10 @@ pub fn parseArgs(comptime T: type, arena: std.mem.Allocator, arguments: ?std.jsoreturn parseValue(T, arena, arguments orelse return error.InvalidParams);}-/// Resolve `$LP_*` placeholders in every string arg before the tool runs.-/// `fill.value` is the one exception: `execFill` resolves it internally and-/// echoes the original placeholder so the credential never surfaces in the-/// result text. Co-located with `execFill` so both halves of the carve-out-/// live in one file.-pub fn normalizeArgKeys(arena: std.mem.Allocator, tool: Tool, args: ?std.json.Value) !?std.json.Value {+/// Renames keys to the schema's casing and drops `null` values, which+/// zero-filling models send for "unset" but `std.json` rejects for a+/// non-optional field.+pub fn normalizeArgs(arena: std.mem.Allocator, tool: Tool, args: ?std.json.Value) !?std.json.Value {const v = args orelse return null;if (v != .object) return v;@@ -2895,6 +2891,7 @@ pub fn normalizeArgKeys(arena: std.mem.Allocator, tool: Tool, args: ?std.json.Vavar it = v.object.iterator();while (it.next()) |entry| {+ if (entry.value_ptr.* == .null) break;const field = schema.findField(entry.key_ptr.*) orelse continue;if (!std.mem.eql(u8, field.name, entry.key_ptr.*)) break;} else return v;@@ -2903,6 +2900,7 @@ pub fn normalizeArgKeys(arena: std.mem.Allocator, tool: Tool, args: ?std.json.Vatry new_obj.ensureTotalCapacity(arena, v.object.count());it = v.object.iterator();while (it.next()) |entry| {+ if (entry.value_ptr.* == .null) continue;const canonical = if (schema.findField(entry.key_ptr.*)) |f| f.name else entry.key_ptr.*;const gop = try new_obj.getOrPut(arena, canonical);if (gop.found_existing) return error.DuplicateField;@@ -2911,6 +2909,11 @@ pub fn normalizeArgKeys(arena: std.mem.Allocator, tool: Tool, args: ?std.json.Vareturn .{ .object = new_obj };}+/// Resolve `$LP_*` placeholders in every string arg before the tool runs.+/// `fill.value` is the one exception: `execFill` resolves it internally and+/// echoes the original placeholder so the credential never surfaces in the+/// result text. Co-located with `execFill` so both halves of the carve-out+/// live in one file.fn substituteStringArgs(arena: std.mem.Allocator, tool: Tool, args: ?std.json.Value) error{OutOfMemory}!?std.json.Value {const v = args orelse return null;if (v != .object) return v;@@ -3035,9 +3038,8 @@ test "call: an argument diagnosis is in-band but counts as invalid_params" {try std.testing.expectEqualStrings("missing required argument 'script'", (try missing).text);try std.testing.expectEqual(.invalid_params, telemetryOutcome(missing));- var args: std.json.ObjectMap = .empty;- try args.put(arena.allocator(), "state", .{ .string = "idle" });- const bad_enum = call(arena.allocator(), testing.test_session, ®istry, "waitForState", .{ .object = args }, .{ .source = .user });+ const args = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), "{\"state\":\"idle\"}", .{});+ const bad_enum = call(arena.allocator(), testing.test_session, ®istry, "waitForState", args, .{ .source = .user });try std.testing.expect((try bad_enum).is_error);try std.testing.expectEqual(.invalid_params, telemetryOutcome(bad_enum));}@@ -3368,6 +3370,20 @@ test "parseValue: empty optional url treated as omitted" {try std.testing.expectEqualStrings("https://example.com", (try parseValue(Params, aa, real)).url.?);}+test "normalizeArgs: a null field takes its default" {+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);+ defer arena.deinit();+ const aa = arena.allocator();++ const Params = struct { selector: []const u8, checked: bool = true };+ const args = try std.json.parseFromSliceLeaky(std.json.Value, aa,+ \\{"Selector":"#x","checked":null}+ , .{});+ const parsed = try parseValue(Params, aa, (try normalizeArgs(aa, .setChecked, args)).?);+ try std.testing.expectEqualStrings("#x", parsed.selector);+ try std.testing.expect(parsed.checked);+}+test "substituteEnvVars resolves LP_* vars" {var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);defer arena.deinit();diff --git a/src/mcp/tools.zig b/src/mcp/tools.zigindex c5938aaad..75f1fdb9e 100644--- a/src/mcp/tools.zig+++ b/src/mcp/tools.zig@@ -535,7 +535,6 @@ test "MCP - missing required argument is named in the error" {try testing.expectJson(.{ .id = 5, .result = .{ .isError = false } }, out.written());out.clearRetainingCapacity();- // Zero-filling models send `null` for "unset"; it is as missing as absent.try router.handleMessage(server, testing.arena_allocator,\\{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"evaluate","arguments":{"script":null}}});