Skip to content

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

Python

rlm: say what a script accepts, and let a bound name reach write_file

justrachdd1141c92e0d
diff --git a/src/rlm.zig b/src/rlm.zig
index 102cbfaa..21fd28ef 100644
--- a/src/rlm.zig
+++ b/src/rlm.zig
@@ -25,12 +25,12 @@ const mcp_shapes = @import("mcp_shapes.zig");
const read_miss = @import("read_miss.zig");
pub const tool_name = "rlm";
-pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Functions ARE this session's tools. Leading read_file/codedb/sleep_ms/llm_query calls overlap as it streams; other calls run in order, stopping on error/cancel/pending. Binds persist. subagent(\"task\") is sidecar-only (keep the critical-path next step local). Loaded MCP names are host functions after load_tool_schemas; tools.server.tool(...) is that name; each(arr, tool, field) maps a JSON array; len(x)/project(x, field) slim it. print() is the answer. Prefer one rlm over N tool calls.";
+pub const tool_desc = "Tools as a call-only script, not Python: name = tool(args), args being literals or bound names (a bound name passes its text); no expressions, indexing or comprehensions. To compute over a result, write_file(\"r.json\", name), then shell. Leading read_file/codedb/sleep_ms/llm_query calls overlap; others run in order, stopping on error/cancel/pending. Binds persist. subagent(\"task\") is sidecar-only (critical-path steps stay local). Loaded MCP names are host functions after load_tool_schemas; each(arr, tool, field) maps a JSON array; len(x)/project(x, field) slim it. print() is the answer.";
/// --lean catalog desc: same contract, no REPL essay. maybeAppend is after
/// compactLeanSpecs, so this is the one-shot wire text.
pub const lean_tool_desc = "Batch independent read_file/codedb here. print(read_file(\"p\")) returns the file — do not catalog-read it again. Then edit_file/write_file/shell as catalog tools. Leading reads overlap; other calls run in order, stopping on error/cancel/pending. Binds persist. Loaded MCP names are host functions after load_tool_schemas.";
pub const tool_schema =
- \\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / bash(\"cmd\") / sleep_ms(ms) / llm_query(\"prompt\") / subagent(\"task\") / loaded mcp__server__tool() or tools.server.tool(); each(arr, tool, field) maps a JSON array; len(x) and project(x, field) slim it; print(...) is the result. Assignments persist across rlm calls."}}, "required": ["code"]}
+ \\{"type": "object", "properties": {"code": {"type": "string", "description": "Call-only script, not Python. One statement per line: name = read_file(\"path\") / codedb(\"command\") / bash(\"cmd\") / sleep_ms(ms) / llm_query(\"prompt\") / subagent(\"task\") / loaded mcp__server__tool() or tools.server.tool(); write_file(\"path\", name) saves a bound result; each(arr, tool, field) maps a JSON array; len(x) and project(x, field) slim it; print(name, ...) is the result. Arguments are string, number or boolean literals or bound names. Assignments persist across rlm calls."}}, "required": ["code"]}
;
/// Process-global: on by default. `--old` / `--no-rlm` turn it off; `--rlm`
@@ -304,7 +304,7 @@ fn evalStmt(
.ok => return null,
.fail => |e| return .{ .text = e, .is_error = true },
}
- const call = try spec_ptc.extractCall(arena, stmt);
+ const call = try spec_ptc.extractCallBound(arena, stmt, binds);
if (call) |c| {
const key = try c.key(arena);
const cached = claimed.get(key);
@@ -362,7 +362,7 @@ fn renderPrintPart(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []c
if (std.mem.startsWith(u8, t, name) and t.len > name.len and
(t[name.len] == '[' or t[name.len] == '.')) return unsupportedPrint(ctx, status);
}
- if (try spec_ptc.extractCall(arena, t)) |c| {
+ if (try spec_ptc.extractCallBound(arena, t, binds)) |c| {
const key = try c.key(arena);
const cached = claimed.get(key);
const out = cached orelse runHost(ctx, c);
diff --git a/src/rlm_spec.zig b/src/rlm_spec.zig
index 41af19d4..23be5408 100644
--- a/src/rlm_spec.zig
+++ b/src/rlm_spec.zig
@@ -23,12 +23,12 @@ pub var run_host: ?*const fn (ToolCtx, spec_ptc.Call) ToolOutput = null;
/// `subagent("task")` is Prime-style recursion via graff's existing subagent
/// tool. v1 is synchronous; speculate() still overlaps independent calls.
/// Keyword `run_in_background=true` returns an agent id (a handle).
-pub const system_note = "\n\nrlm(code): tools as script. Leading reads overlap; other calls run in order, stopping on error/cancel/pending. Binds persist until /new or /clear. subagent() is sidecar-only; keep critical-path local. Loaded MCP names are functions (tools.server.tool too). each maps arrays; len/project slim them. print() returns the answer.";
+pub const system_note = "\n\nrlm(code): call-only script, not Python: literal or bound-name args, no expressions; write_file(\"f\", name) then shell to compute. Leading reads overlap; other calls run in order, stopping on error. Binds persist until /new or /clear. subagent() is sidecar-only; keep critical-path local. each maps arrays; len/project slim them. print() returns the answer.";
/// One REPL assignment. `runScript` seeds these from the process-local store
/// so a later `rlm` call can `print(prev)` without re-reading. Owned by the
/// caller's arena when seeded; the store holds gpa copies.
-pub const Binding = struct { name: []const u8, text: []const u8 };
+pub const Binding = @import("spec_ptc.zig").Bound;
const BindStore = struct {
mu: Io.Mutex = .init,
diff --git a/src/rlm_tests.zig b/src/rlm_tests.zig
index b9a931fc..89b1c846 100644
--- a/src/rlm_tests.zig
+++ b/src/rlm_tests.zig
@@ -100,6 +100,32 @@ test "runScript reads a fixture via speculated read_file and prints it" {
try std.testing.expect(std.mem.indexOf(u8, nested.text, "hello-rlm") != null);
}
+test "runScript saves a bound result with write_file(path, name) for the shell" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "note.txt", .data = "hello-rlm\n" });
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &path_buf);
+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer dummy_client.deinit();
+ const saved = rlm.available;
+ defer {
+ rlm.available = saved;
+ rlm.resetLive(gpa, io);
+ }
+ rlm.available = true;
+ var ctx = testCtx(gpa, io, &dummy_client);
+ ctx.agent_cwd = path_buf[0..n];
+ const out = try rlm.runScript(ctx, "x = read_file(\"note.txt\")\nwrite_file(\"copy.txt\", x)");
+ defer gpa.free(out.text);
+ try std.testing.expect(!out.is_error);
+ var buf: [64]u8 = undefined;
+ const copied = try tmp.dir.readFile(io, "copy.txt", &buf);
+ try std.testing.expect(std.mem.indexOf(u8, copied, "hello-rlm") != null);
+}
+
test "runScript splits a semicolon one-liner and prints both binds" {
const gpa = std.testing.allocator;
const io = std.testing.io;
diff --git a/src/spec_ptc.zig b/src/spec_ptc.zig
index 3227b090..1bd89a1c 100644
--- a/src/spec_ptc.zig
+++ b/src/spec_ptc.zig
@@ -73,7 +73,17 @@ pub const Segmenter = struct {
/// Pull a speculatable `name(...)` / `var = name(...)` from one statement.
/// Only literal args (string / int / bool). Returns null for print, comments,
/// or anything that still depends on a runtime value.
+/// A value an rlm script bound earlier (rlm_spec.Binding is this type).
+pub const Bound = struct { name: []const u8, text: []const u8 };
+
pub fn extractCall(arena: Allocator, stmt: []const u8) !?Call {
+ return extractCallBound(arena, stmt, &.{});
+}
+
+/// extractCall where a bare name in the arguments passes that bind's text
+/// (the latest binding wins). Speculation has no binds, so it never
+/// pre-runs a call that needs one.
+pub fn extractCallBound(arena: Allocator, stmt: []const u8, binds: []const Bound) !?Call {
const line = stripComment(stmt);
const trimmed = std.mem.trim(u8, line, " \t");
if (trimmed.len == 0) return null;
@@ -84,7 +94,7 @@ pub fn extractCall(arena: Allocator, stmt: []const u8) !?Call {
if (std.mem.eql(u8, name, "print")) return null;
const close = lastParen(call_src) orelse return null;
const inner = call_src[open + 1 .. close];
- const args_json = parseArgs(arena, name, inner) catch |err| switch (err) {
+ const args_json = parseArgs(arena, name, inner, binds) catch |err| switch (err) {
error.NeedKeywords => return null,
else => return err,
} orelse return null;
@@ -195,7 +205,7 @@ const Value = union(enum) {
bool: bool,
};
-fn parseArgs(arena: Allocator, tool: []const u8, inner: []const u8) !?[]const u8 {
+fn parseArgs(arena: Allocator, tool: []const u8, inner: []const u8, binds: []const Bound) !?[]const u8 {
var args: std.ArrayList(Arg) = .empty;
var i: usize = 0;
const src = inner;
@@ -219,7 +229,7 @@ fn parseArgs(arena: Allocator, tool: []const u8, inner: []const u8) !?[]const u8
i = start;
}
}
- const val = (try parseValue(arena, src, &i)) orelse return null;
+ const val = (try parseValue(arena, src, &i, binds)) orelse return null;
try args.append(arena, .{ .key = key, .value = val });
skipWs(src, &i);
if (i >= src.len) break;
@@ -229,13 +239,25 @@ fn parseArgs(arena: Allocator, tool: []const u8, inner: []const u8) !?[]const u8
return try canonicalize(arena, tool, args.items);
}
-fn parseValue(arena: Allocator, src: []const u8, i: *usize) !?Value {
+fn parseValue(arena: Allocator, src: []const u8, i: *usize, binds: []const Bound) !?Value {
if (i.* >= src.len) return null;
const c = src[i.*];
if (c == '"' or c == '\'') return .{ .string = (try parseString(arena, src, i)) orelse return null };
if (c == '-' or (c >= '0' and c <= '9')) return parseInt(src, i);
if (takeWord(src, i, "true")) return .{ .bool = true };
if (takeWord(src, i, "false")) return .{ .bool = false };
+ if (!identStart(c)) return null;
+ var end = i.* + 1;
+ while (end < src.len and identCont(src[end])) end += 1;
+ const name = src[i.*..end];
+ var n = binds.len;
+ while (n > 0) {
+ n -= 1;
+ if (std.mem.eql(u8, binds[n].name, name)) {
+ i.* = end;
+ return .{ .string = binds[n].text };
+ }
+ }
return null;
}
@@ -302,7 +324,15 @@ fn skipWs(src: []const u8, i: *usize) void {
fn canonicalize(arena: Allocator, tool: []const u8, args: []const Arg) ![]const u8 {
var obj: std.json.ObjectMap = .empty;
const field = hostField(tool);
- if (args.len == 1 and args[0].key == null) {
+ const positional = for (args) |a| {
+ if (a.key != null) break false;
+ } else true;
+ // write_file(path, content) is the one two-argument positional call:
+ // how a script saves a bound result for the shell to compute over.
+ if (positional and args.len == 2 and std.mem.eql(u8, tool, "write_file")) {
+ try putValue(arena, &obj, field, args[0].value);
+ try putValue(arena, &obj, "content", args[1].value);
+ } else if (args.len == 1 and args[0].key == null) {
try putValue(arena, &obj, field, args[0].value);
} else {
for (args) |a| {
@@ -520,3 +550,22 @@ test "extractCall maps subagent(\"task\") onto prompt; two calls stay independen
try std.testing.expectEqualStrings("{\"prompt\":\"read a.txt\"}", calls[0].args_json);
try std.testing.expectEqualStrings("{\"prompt\":\"read b.txt\"}", calls[1].args_json);
}
+
+test "extractCallBound: a bare bound name passes its text; write_file takes path then content" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const binds = [_]Bound{ .{ .name = "notes", .text = "old" }, .{ .name = "notes", .text = "a \"quoted\" line" } };
+ const w = (try extractCallBound(a, "write_file(\"out.json\", notes)", &binds)).?;
+ try std.testing.expectEqualStrings("write_file", w.name);
+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, w.args_json, .{});
+ try std.testing.expectEqualStrings("out.json", parsed.object.get("path").?.string);
+ try std.testing.expectEqualStrings("a \"quoted\" line", parsed.object.get("content").?.string); // latest bind
+ const kw = (try extractCallBound(a, "w = write_file(path=\"o.txt\", content=notes)", &binds)).?;
+ try std.testing.expect(std.mem.indexOf(u8, kw.args_json, "quoted") != null);
+ // Without binds (speculation) the call is not pre-run; an unknown name is not a call.
+ try std.testing.expect((try extractCall(a, "write_file(\"out.json\", notes)")) == null);
+ try std.testing.expect((try extractCallBound(a, "write_file(\"out.json\", missing)", &binds)) == null);
+ // Other tools keep one positional argument.
+ try std.testing.expect((try extractCallBound(a, "read_file(\"a\", notes)", &binds)) == null);
+}