Skip to content

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

Python

feat(rlm): mid-stream spec-ptc and RLM llm_query

Cursor Agentfaa8f015ec08
diff --git a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md
index 0ceacf3b..5b293e44 100644
--- a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md
+++ b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md
@@ -6,10 +6,12 @@ Status: accepted 2026-08-25
[spec-ptc](https://github.com/alexzhang13/spec-ptc) overlaps tool work with
generation for harnesses whose tools are functions inside one code REPL (RLM,
-CodeAct). Graff's native loop is the opposite shape: the model emits structured
-`read_file` / `bash` / `subagent` calls, and `runTools` fans a *finished* batch
-across the pool. That is parallelism after the arguments close, not speculation
-from partial source.
+CodeAct). [Recursive Language Models](https://github.com/alexzhang13/rlm)
+(Zhang, Kraska, Khattab) treat long context as a REPL variable and peel
+questions off with `llm_query` / `rlm_query`. Graff's native loop is the
+opposite shape: the model emits structured `read_file` / `bash` / `subagent`
+calls, and `runTools` fans a *finished* batch across the pool. That is
+parallelism after the arguments close, not speculation from partial source.
Dropping spec-ptc's Python shadow REPL into the default catalog would change
every prefix and the 64-cell tool-catalog kernel. A first cut has to be
@@ -19,16 +21,22 @@ measurable against the native loop without that cost.
`rlm` is an opt-in native tool (`--rlm` / `GRAFF_RLM=1`). Off, the catalog is
unchanged. On, the model gets one REPL whose functions *are* graff tools
-(`read_file`, `codedb`) plus `sleep_ms` / `print`. The speculator is Zig
-(`src/spec_ptc.zig`): closed statements with literal args launch in parallel
-before the script walks them. Default structured tools stay the main harness.
+(`read_file`, `codedb`) plus `sleep_ms` / `llm_query` / `print`. The
+speculator is Zig (`src/spec_ptc.zig` + `rlm.feedLive`): closed statements
+with literal args launch as the `code` argument streams (including `-p`,
+where `Agent.out` is null), then `runScript` claims the futures. Default
+structured tools stay the main harness.
-A live comparison is `scripts/compare-ptc.py`: same prompt, native vs `--rlm`.
+A live comparison is `scripts/compare-ptc.py`. The eval A/B is
+`graff-evals/run.py --harness graff-dev,graff-dev-rlm`.
## Consequences
-- True mid-stream speculation (feed `code` while the `rlm` argument is still
- arriving) is the next increment; v1 speculates at exec start from the
- complete script, which already overlaps independent calls with each other.
-- `llm_query` as a host function (a real RLM sub-call) is not in this cut.
+- Mid-stream speculation is on the SSE path even when the one-shot frontend
+ is quiet (`printDelta` still feeds `ArgLive` for `rlm` when `--rlm` is set).
+ `rlm` is *not* visible-prose for the WS stall signal (SSE does not grow
+ `partial_text` for `code`).
+- `llm_query` is a bounded tools-off sub-call on the session provider
+ (`src/rlm_query.zig`). Nested spend is real; the host function exists so
+ sPTC can overlap an expensive sub-LM with the rest of the script.
- SDK / `--schema` do not list `rlm` until it graduates off the flag.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8f10f6b2..3ebfa3a6 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -32,7 +32,7 @@ record only when you need the evidence or the edge cases.
| [0019](0019-codedb-one-shot-over-hop-chains.md) | Advertise only `context` / `around` / `callpath` / `list_dir` / `status`; hop verbs stay callable, not on the menu. |
| [0020](0020-transcript-shows-decisions.md) | Transcript shows decisions: one interpreted tool line, collapsed infra failures, compact WORKING; raw output is `/debug` / TUI-fold. |
| [0021](0021-transcript-is-the-task-not-the-bus.md) | Transcript is the task, not the event bus: bookkeeping is silent, todos are WORKING, subagents are scouts. |
-| [0022](0022-rlm-is-opt-in-speculative-ptc.md) | `rlm` is opt-in speculative PTC (`--rlm` / `GRAFF_RLM=1`). Zig speculator; default structured-tool catalog unchanged. |
+| [0022](0022-rlm-is-opt-in-speculative-ptc.md) | `rlm` is opt-in RLM + mid-stream spec-ptc (`--rlm` / `GRAFF_RLM=1`). Default catalog unchanged. |
## When to write one
diff --git a/graff-evals/harnesses.json b/graff-evals/harnesses.json
index a18558df..323871a6 100644
--- a/graff-evals/harnesses.json
+++ b/graff-evals/harnesses.json
@@ -24,6 +24,16 @@
"schema_args": ["--output-schema", "{schema}"],
"default_model": "grok-4.6"
},
+ "graff-dev-rlm": {
+ "cmd": ["{repo}/zig-out/bin/graff", "-p", "{prompt}", "--model", "{model}", "--yolo", "--rlm"],
+ "answer": "stdout",
+ "usage": "graff-stderr",
+ "capabilities": ["output-schema"],
+ "schema_args": ["--output-schema", "{schema}"],
+ "env": {"GRAFF_POST_DEADLINE_SECS": "90"},
+ "default_model": "grok-4.6",
+ "note": "same as graff-dev plus --rlm (RLM REPL + mid-stream spec-ptc)"
+ },
"grok": {
"cmd": ["grok", "-p", "{prompt}", "-m", "{model}", "--always-approve", "--output-format", "streaming-messages-json"],
"answer": "grok-stream",
diff --git a/graff-evals/run.py b/graff-evals/run.py
index 1318319f..cc302837 100755
--- a/graff-evals/run.py
+++ b/graff-evals/run.py
@@ -21,7 +21,7 @@ RESULTS_DIR = os.path.join(ROOT, "results")
SANDBOX_DIR = os.path.join(ROOT, ".sandboxes")
GRAFF_USAGE_RE = re.compile(
- r"\[usage\] (\d+) api call\(s\) · (\d+) in \((\d+) cached\) \+ (\d+) out tokens")
+ r"\[usage\] (\d+) api call\(s\) · (\d+) in \((\d+) cached(?:, \d+ cache writes)?\) \+ (\d+) out tokens")
def load_tasks():
diff --git a/scripts/compare-ptc.py b/scripts/compare-ptc.py
index c95c0b7d..e2a399ec 100755
--- a/scripts/compare-ptc.py
+++ b/scripts/compare-ptc.py
@@ -94,10 +94,10 @@ def main() -> int:
print(f"graff={args.graff}", flush=True)
print("=== native (structured tools) ===", flush=True)
native = run(args.graff, [], PROMPT, td)
- print(json.dumps({k: native[k] for k in ("ok", "ms", "names", "finished_ms", "usage", "event_types")}, indent=2))
+ print(json.dumps({k: native[k] for k in ("ok", "ms", "names", "tools", "finished_ms", "usage")}, indent=2))
print("=== rlm (--rlm, speculated reads) ===", flush=True)
rlm = run(args.graff, ["--rlm"], PROMPT + RLM_HINT, td)
- print(json.dumps({k: rlm[k] for k in ("ok", "ms", "names", "finished_ms", "usage", "event_types")}, indent=2))
+ print(json.dumps({k: rlm[k] for k in ("ok", "ms", "names", "tools", "finished_ms", "usage")}, indent=2))
print("=== answers ===")
print("native:\n", native.get("answer") or native.get("stderr"))
print("rlm:\n", rlm.get("answer") or rlm.get("stderr"))
diff --git a/src/agent_argstream.zig b/src/agent_argstream.zig
index 100ea86f..7dbf9b57 100644
--- a/src/agent_argstream.zig
+++ b/src/agent_argstream.zig
@@ -14,16 +14,18 @@ const agent_mod = @import("agent.zig");
const tools_mod = @import("tools.zig");
const Agent = agent_mod.Agent;
const ToolCall = tools_mod.ToolCall;
+const rlm_spec = @import("rlm_spec.zig");
// sseIndex lives in agent_stream.zig; reached through the Agent struct's
// member alias.
const sseIndex = Agent.sseIndex;
-pub const ArgTool = enum { none, attempt_completion, ask_user };
+pub const ArgTool = enum { none, attempt_completion, ask_user, rlm };
pub fn argToolFor(name: []const u8) ArgTool {
if (std.mem.eql(u8, name, "attempt_completion")) return .attempt_completion;
if (std.mem.eql(u8, name, "ask_user")) return .ask_user;
+ if (std.mem.eql(u8, name, "rlm")) return .rlm;
return .none;
}
@@ -31,10 +33,33 @@ pub fn argField(tool: ArgTool) []const u8 {
return switch (tool) {
.attempt_completion => "result",
.ask_user => "question",
+ .rlm => "code",
.none => "",
};
}
+fn toolCtx(self: *Agent) tools_mod.ToolCtx {
+ return .{
+ .gpa = self.gpa,
+ .io = self.io,
+ .client = self.client,
+ .provider = self.provider,
+ .subagent_provider = self.subagent_provider,
+ .subagent_cross_provider = self.subagent_cross_provider,
+ .registry = if (self.sub) null else self.registry,
+ .from_sub = self.sub,
+ .has_eval = self.eval_cmd != null,
+ .approvals = self.approvals,
+ .tracer = self.tracer,
+ .run_budget = self.run_budget,
+ .depth = self.depth,
+ .snapshots = self.snapshots,
+ .tools_used = &self.tools_used,
+ .loop_deadline_ms = self.loop_deadline_ms,
+ .agent_cwd = self.agent_cwd,
+ };
+}
+
/// Live tool-argument text. attempt_completion and ask_user carry their
/// user-facing prose inside tool-call argument JSON, which the text-delta
/// matching in printDelta can't see — in strict mode that's the *whole*
@@ -240,7 +265,9 @@ pub fn outputIndex(obj: std.json.ObjectMap) ?i64 {
/// extractor for live printing. Root interactive streams only — SDK
/// (--json) clients get the assembled tool_call event instead.
pub fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {
- if (self.sub or main_mod.json_mode or self.stream_quiet) return;
+ if (self.sub) return;
+ const ui = !main_mod.json_mode and !self.stream_quiet;
+ if (!ui and !rlm_spec.available) return;
switch (self.provider.kind) {
.anthropic => {
const t = obj.get("type") orelse return;
@@ -252,7 +279,7 @@ pub fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {
const bt = cb.object.get("type") orelse return;
if (bt != .string or !std.mem.eql(u8, bt.string, "tool_use")) return;
const name = cb.object.get("name") orelse return;
- if (name == .string) self.arg_live.open(name.string, @intCast(ix));
+ if (name == .string) openLive(self, name.string, @intCast(ix));
} else if (std.mem.eql(u8, t.string, "content_block_delta")) {
const ix = sseIndex(obj) orelse return;
const d = obj.get("delta") orelse return;
@@ -284,7 +311,7 @@ pub fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {
const f = tc.object.get("function") orelse continue;
if (f != .object) continue;
if (f.object.get("name")) |n| if (n == .string and n.string.len > 0)
- self.arg_live.open(n.string, ix);
+ openLive(self, n.string, ix);
if (f.object.get("arguments")) |a| if (a == .string)
self.arg_live.feed(self, ix, a.string);
}
@@ -299,7 +326,7 @@ pub fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {
const it = item.object.get("type") orelse return;
if (it != .string or !std.mem.eql(u8, it.string, "function_call")) return;
const name = item.object.get("name") orelse return;
- if (name == .string) self.arg_live.open(name.string, ix);
+ if (name == .string) openLive(self, name.string, ix);
} else if (std.mem.eql(u8, t.string, "response.function_call_arguments.delta")) {
const ix = outputIndex(obj) orelse return;
const dl = obj.get("delta") orelse return;
@@ -319,7 +346,16 @@ pub fn argLiveDelta(self: *Agent, obj: std.json.ObjectMap) void {
/// exactly like a text delta (spinner handoff included); the --json wire
/// never carried these moments (argLiveDelta gates --json off), so JsonSink
/// stays silent.
+fn openLive(self: *Agent, name: []const u8, ix: i64) void {
+ if (argToolFor(name) == .rlm) rlm_spec.resetLive(self.gpa, self.io);
+ self.arg_live.open(name, ix);
+}
+
pub fn emitArgText(self: *Agent, tool: ArgTool, text: []const u8) void {
+ if (tool == .rlm) {
+ if (rlm_spec.available and text.len > 0) rlm_spec.feedLive(toolCtx(self), text);
+ return;
+ }
if (self.out == null) return; // frontendless agents skip capture too, as ever
if (text.len == 0) return;
self.streamed_text = true;
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index a4dc93e0..9a44fc54 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -18,6 +18,7 @@ const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
const engine_sink = @import("engine_sink.zig"); // #422: every emission goes through the sink
+const rlm_spec = @import("rlm_spec.zig");
const reasoningDelta = @import("title.zig").reasoningDelta;
const stream_tests = @import("agent_stream_tests.zig");
@@ -387,13 +388,15 @@ test "openaiComplete (#133): finish_reason marks completion, deltas do not" {
/// typed events through the sink. Best-effort: parse failures are ignored
/// (the buffered body is parsed afterwards).
pub fn printDelta(self: *Agent, raw_line: []const u8) void {
- if (self.out == null) return; // pool-thread subagents have no frontend writer: skip entirely (capture included), as ever
+ const no_ui = self.out == null;
+ if (no_ui and !rlm_spec.available) return; // -p still feeds rlm so sPTC can launch mid-stream
const payload = ssePayload(raw_line) orelse return;
const parsed = std.json.parseFromSlice(Value, self.gpa, payload, .{}) catch return;
defer parsed.deinit();
if (parsed.value != .object) return;
const obj = parsed.value.object;
self.argLiveDelta(obj);
+ if (no_ui) return;
const text: []const u8 = switch (self.provider.kind) {
.anthropic => blk: {
const t = obj.get("type") orelse break :blk "";
diff --git a/src/agent_ws_signal.zig b/src/agent_ws_signal.zig
index a77db338..8fc7f529 100644
--- a/src/agent_ws_signal.zig
+++ b/src/agent_ws_signal.zig
@@ -107,7 +107,11 @@ pub const TokenSignal = struct {
const name = item.object.get("name") orelse return false;
// Exactly ArgLive.open's gate: a non-whitelisted name opens nothing
// (and cannot clobber an open index — output indices are unique).
- if (name == .string and argToolFor(name.string) != .none) self.arg_ix = ix;
+ if (name == .string) {
+ const t = argToolFor(name.string);
+ // Visible prose only — rlm's `code` is speculated, not printed.
+ if (t == .attempt_completion or t == .ask_user) self.arg_ix = ix;
+ }
return false;
}
if (std.mem.eql(u8, ty.string, "response.output_item.done")) {
diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zig
index b0f62167..fbc00b64 100644
--- a/src/agent_ws_test.zig
+++ b/src/agent_ws_test.zig
@@ -520,6 +520,12 @@ test "#401: whitelisted tool-argument prose is a tokens-flowing signal too (SSE
try std.testing.expect(!ask.flowing(gpa, "{\"type\":\"response.output_item.added\",\"output_index\":7,\"item\":{\"type\":\"function_call\",\"name\":\"ask_user\"}}"));
try std.testing.expect(ask.flowing(gpa, "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":7,\"delta\":\"{\\\"question\\\":\\\"?\"}"));
+ // rlm's `code` is speculated, not printed — same as an ordinary tool:
+ // tightening here would drift from SSE (emitArgText does not grow partial_text).
+ var rlm_sig: agent_ws.TokenSignal = .{};
+ try std.testing.expect(!rlm_sig.flowing(gpa, "{\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"function_call\",\"name\":\"rlm\"}}"));
+ try std.testing.expect(!rlm_sig.flowing(gpa, arg_delta));
+
// An ORDINARY tool's arguments stream invisibly on SSE, so the identical
// delta must leave the pre-first-token budget standing.
var edit: agent_ws.TokenSignal = .{};
diff --git a/src/args.zig b/src/args.zig
index d4097462..f3809cd1 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -176,6 +176,7 @@ pub fn parse(init: std.process.Init) !Flags {
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, "--rlm")) {
@import("rlm.zig").available = true; // ADR 0022: opt-in programmatic tool calling (also GRAFF_RLM=1)
+ @import("rlm.zig").sync();
} else if (std.mem.eql(u8, arg, "--no-autocommit")) {
main_mod.g_worktree_autocommit = false;
} else if (std.mem.eql(u8, arg, "--schema")) {
diff --git a/src/cli.zig b/src/cli.zig
index 3e98dde5..0a529330 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -245,7 +245,7 @@ pub const usage_text =
\\ --context-limit name=N cap a named prefix: skill_catalog_bytes|mcp_schema_bytes|agents_md_bytes
\\ --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
- \\ --rlm advertise the rlm programmatic-tool-calling REPL (spec-ptc in Zig; GRAFF_RLM=1)
+ \\ --rlm advertise the rlm REPL (RLM llm_query + mid-stream spec-ptc; GRAFF_RLM=1)
\\ --lean slim tool surface (9 core tools) + MCP deferred behind load_tool_schemas — the DEFAULT for -p one-shots (GRAFF_LEAN=1)
\\ --no-lean opt a one-shot out of the implied --lean: full tool surface + eager MCP, the pre-default -p behavior
\\ --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)
diff --git a/src/exec.zig b/src/exec.zig
index 283ad7b7..45ebd282 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -539,5 +539,7 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,
_ = @import("codedb_health.zig");
_ = @import("list_dir.zig");
_ = @import("rlm.zig");
+ _ = @import("rlm_spec.zig");
+ _ = @import("rlm_query.zig");
_ = @import("spec_ptc.zig");
}
diff --git a/src/rlm.zig b/src/rlm.zig
index 99ec176b..75ca5828 100644
--- a/src/rlm.zig
+++ b/src/rlm.zig
@@ -2,9 +2,9 @@
//!
//! Off unless `--rlm` / `GRAFF_RLM=1`. The default catalog stays byte-stable
//! (ADR 0022). Host functions: `read_file`, `codedb` (real graff tools),
-//! `sleep_ms` (overlap proof), `print` (answer). Independent literal calls
-//! launch in parallel via spec_ptc before the script walks them — the Zig
-//! half of speculative PTC.
+//! `sleep_ms` (overlap proof), `llm_query` (RLM tools-off sub-LM), `print`
+//! (answer). Closed literal calls launch as the `code` argument streams
+//! (spec-ptc) and again at exec for anything the stream missed.
const std = @import("std");
const Io = std.Io;
@@ -17,19 +17,39 @@ const ToolCtx = tools.ToolCtx;
const ToolOutput = tools.ToolOutput;
const no_local_tools = @import("no_local_tools.zig");
const exec_mod = @import("exec.zig");
+const rlm_query = @import("rlm_query.zig");
+const rlm_spec = @import("rlm_spec.zig");
pub const tool_name = "rlm";
-pub const tool_desc = "Programmatic tool calling (sPTC). Run a short Python-like script whose functions ARE this session's tools. Independent read_file/codedb/sleep_ms calls with literal arguments start in parallel as the script is parsed (speculated), then print() is the answer. Example: a = read_file(\"src/main.zig\"); b = codedb(\"status\"); print(a); print(b). No imports, no control flow — assignments and calls only. Prefer this over N separate tool calls when the reads do not depend on each other.";
+pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Run a short Python-like script whose functions ARE this session's tools. Independent read_file/codedb/sleep_ms/llm_query calls with literal arguments start in parallel as the script streams (speculated), then print() is the answer. llm_query(prompt) is a tools-off sub-LM call. Example: a = read_file(\"src/main.zig\"); b = codedb(\"status\"); print(a); print(b). No imports, no control flow — assignments and calls only. Prefer this over N separate tool calls when the reads do not depend on each other.";
pub const tool_schema =
- \\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / sleep_ms(ms); print(...) is the result"}}, "required": ["code"]}
+ \\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / sleep_ms(ms) / llm_query(\"prompt\"); print(...) is the result"}}, "required": ["code"]}
;
/// Process-global: `--rlm` / GRAFF_RLM=1. Never flipped mid-session.
+/// Keep in sync with rlm_spec.available (`sync`) so the SSE path can see it
+/// without importing this file (exec.zig would cycle through Agent).
pub var available: bool = false;
+pub fn sync() void {
+ rlm_spec.available = available;
+ rlm_spec.run_host = runHost;
+}
+
+pub fn resetLive(gpa: Allocator, io: Io) void {
+ sync();
+ rlm_spec.resetLive(gpa, io);
+}
+
+pub fn feedLive(ctx: ToolCtx, delta: []const u8) void {
+ sync();
+ rlm_spec.feedLive(ctx, delta);
+}
+
/// Append `rlm` after the lean/no-local filters so `--rlm -p` still sees it.
/// No-op when the flag is off or embedder mode stripped host tools.
pub fn maybeAppend(comptime Spec: type, arena: Allocator, specs: []const Spec) ![]const Spec {
+ sync();
if (!available or no_local_tools.enabled) return specs;
for (specs) |s| if (std.mem.eql(u8, s.name, tool_name)) return specs;
const buf = try arena.alloc(Spec, specs.len + 1);
@@ -39,6 +59,7 @@ pub fn maybeAppend(comptime Spec: type, arena: Allocator, specs: []const Spec) !
}
pub fn exec(ctx: ToolCtx, input: Value) !ToolOutput {
+ sync();
if (!available) return .{ .text = try ctx.gpa.dupe(u8, "rlm is off — pass --rlm (or GRAFF_RLM=1)"), .is_error = true };
if (no_local_tools.enabled) return .{ .text = try ctx.gpa.dupe(u8, "rlm is a host tool and is disabled under --no-local-tools"), .is_error = true };
const code = tools.strField(input, "code") orelse return tools.missingArg(ctx.gpa, "code");
@@ -48,10 +69,19 @@ pub fn exec(ctx: ToolCtx, input: Value) !ToolOutput {
const Binding = struct { name: []const u8, text: []const u8 };
pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {
+ sync();
var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
+ var claimed = std.StringHashMap(ToolOutput).init(ctx.gpa);
+ defer {
+ var cit = claimed.iterator();
+ while (cit.next()) |e| ctx.gpa.free(e.value_ptr.text);
+ claimed.deinit();
+ }
+ rlm_spec.takeLive(ctx, &claimed, arena);
+
var stmts: std.ArrayList([]const u8) = .empty;
var it = std.mem.splitScalar(u8, code, '\n');
while (it.next()) |raw| {
@@ -60,12 +90,6 @@ pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {
}
const calls = try spec_ptc.extractCalls(arena, stmts.items);
- var claimed = std.StringHashMap(ToolOutput).init(ctx.gpa);
- defer {
- var cit = claimed.iterator();
- while (cit.next()) |e| ctx.gpa.free(e.value_ptr.text);
- claimed.deinit();
- }
try speculate(ctx, arena, calls, &claimed);
var binds: std.ArrayList(Binding) = .empty;
@@ -87,9 +111,11 @@ fn speculate(ctx: ToolCtx, arena: Allocator, calls: []const spec_ptc.Call, claim
var seen = std.StringHashMap(void).init(arena);
for (calls) |c| {
const key = try c.key(arena);
+ if (claimed.contains(key)) continue;
if (try seen.fetchPut(key, {})) |_| continue;
try uniq.append(arena, c);
}
+ if (uniq.items.len == 0) return;
const futs = try arena.alloc(Io.Future(ToolOutput), uniq.items.len);
const keys = try arena.alloc([]const u8, uniq.items.len);
for (uniq.items, futs, keys) |c, *fut, *key| {
@@ -104,6 +130,7 @@ fn speculate(ctx: ToolCtx, arena: Allocator, calls: []const spec_ptc.Call, claim
fn runHost(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {
if (std.mem.eql(u8, call.name, "sleep_ms")) return runSleep(ctx, call.args_json);
+ if (std.mem.eql(u8, call.name, "llm_query")) return rlm_query.run(ctx, call.args_json);
var parsed = std.json.parseFromSlice(Value, ctx.gpa, call.args_json, .{}) catch {
return .{ .text = ctx.gpa.dupe(u8, "rlm: bad args") catch &.{}, .is_error = true };
};
@@ -168,6 +195,19 @@ fn renderPrint(arena: Allocator, inner: []const u8, binds: []const Binding) ![]c
return try arena.dupe(u8, t);
}
+fn testCtx(gpa: Allocator, io: Io, client: *std.http.Client) ToolCtx {
+ return .{
+ .gpa = gpa,
+ .io = io,
+ .client = client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ };
+}
+
test "maybeAppend is a no-op until --rlm, and refuses to double-append" {
const gpa = std.testing.allocator;
var arena_state = std.heap.ArenaAllocator.init(gpa);
@@ -203,16 +243,7 @@ test "runScript speculates three sleeps so wall time is ~one sleep, not three" {
const saved = available;
defer available = saved;
available = true;
- const ctx: ToolCtx = .{
- .gpa = gpa,
- .io = io,
- .client = &dummy_client,
- .provider = undefined,
- .registry = null,
- .from_sub = false,
- .approvals = null,
- .tracer = null,
- };
+ const ctx = testCtx(gpa, io, &dummy_client);
const t0: Io.Timestamp = .now(io, .awake);
const out = try runScript(ctx, "a = sleep_ms(40)\nb = sleep_ms(41)\nc = sleep_ms(42)\nprint(a)");
defer gpa.free(out.text);
@@ -232,25 +263,39 @@ test "runScript reads a fixture via speculated read_file and prints it" {
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const n = try tmp.dir.realPath(io, &path_buf);
const dir = path_buf[0..n];
- // confinedPath requires a relative path; run from tmp via agent_cwd.
var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };
defer dummy_client.deinit();
const saved = available;
defer available = saved;
available = true;
- const ctx: ToolCtx = .{
- .gpa = gpa,
- .io = io,
- .client = &dummy_client,
- .provider = undefined,
- .registry = null,
- .from_sub = false,
- .approvals = null,
- .tracer = null,
- .agent_cwd = dir,
- };
+ var ctx = testCtx(gpa, io, &dummy_client);
+ ctx.agent_cwd = dir;
const out = try runScript(ctx, "x = read_file(\"note.txt\")\nprint(x)");
defer gpa.free(out.text);
try std.testing.expect(!out.is_error);
try std.testing.expect(std.mem.indexOf(u8, out.text, "hello-rlm") != null);
}
+
+test "feedLive launches sleeps before runScript, so claim is a hit not a re-run" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer dummy_client.deinit();
+ const saved = available;
+ defer {
+ available = saved;
+ resetLive(gpa, io);
+ }
+ available = true;
+ const ctx = testCtx(gpa, io, &dummy_client);
+ const t0: Io.Timestamp = .now(io, .awake);
+ feedLive(ctx, "a = sleep_ms(40)\n");
+ feedLive(ctx, "b = sleep_ms(41)\n");
+ feedLive(ctx, "c = sleep_ms(42)\n");
+ const out = try runScript(ctx, "a = sleep_ms(40)\nb = sleep_ms(41)\nc = sleep_ms(42)\nprint(a)");
+ defer gpa.free(out.text);
+ const dt = t0.untilNow(io, .awake).toMilliseconds();
+ try std.testing.expect(!out.is_error);
+ try std.testing.expectEqualStrings("slept 40ms", out.text);
+ try std.testing.expect(dt < 100);
+}
diff --git a/src/rlm_query.zig b/src/rlm_query.zig
new file mode 100644
index 00000000..0ecde4c8
--- /dev/null
+++ b/src/rlm_query.zig
@@ -0,0 +1,146 @@
+//! RLM `llm_query`: a tools-off sub-LM call on the session provider.
+//!
+//! [Recursive Language Models](https://github.com/alexzhang13/rlm) treat a
+//! long context as a REPL variable and peel questions off with `llm_query` /
+//! `rlm_query`. Here the host function is that sub-call: one bounded
+//! completion, no tools, so spec_ptc can launch it the moment the prompt
+//! literal closes — overlapping generation of the rest of the script.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const tools = @import("tools.zig");
+const ToolCtx = tools.ToolCtx;
+const ToolOutput = tools.ToolOutput;
+const provider_mod = @import("provider.zig");
+const Provider = provider_mod.Provider;
+const http = @import("http.zig");
+const title = @import("title.zig");
+
+pub const max_out_tokens: u32 = 256;
+
+pub fn run(ctx: ToolCtx, args_json: []const u8) ToolOutput {
+ var parsed = std.json.parseFromSlice(Value, ctx.gpa, args_json, .{}) catch {
+ return .{ .text = ctx.gpa.dupe(u8, "rlm: llm_query needs prompt") catch &.{}, .is_error = true };
+ };
+ defer parsed.deinit();
+ const prompt = tools.strField(parsed.value, "prompt") orelse {
+ return .{ .text = ctx.gpa.dupe(u8, "rlm: llm_query needs prompt") catch &.{}, .is_error = true };
+ };
+ if (prompt.len == 0) {
+ return .{ .text = ctx.gpa.dupe(u8, "rlm: llm_query prompt is empty") catch &.{}, .is_error = true };
+ }
+ const body = buildBody(ctx.gpa, ctx.provider, prompt) catch {
+ return .{ .text = ctx.gpa.dupe(u8, "rlm: llm_query could not build request") catch &.{}, .is_error = true };
+ };
+ defer ctx.gpa.free(body);
+ const raw = http.postWatched(ctx.gpa, ctx.io, ctx.client, ctx.provider, body, null) catch |err| {
+ return .{
+ .text = std.fmt.allocPrint(ctx.gpa, "rlm: llm_query failed: {s}", .{@errorName(err)}) catch &.{},
+ .is_error = true,
+ };
+ };
+ defer ctx.gpa.free(raw);
+ return extract(ctx.gpa, ctx.provider.kind, raw);
+}
+
+pub fn buildBody(gpa: Allocator, provider: Provider, prompt: []const u8) ![]u8 {
+ var aw: Io.Writer.Allocating = .init(gpa);
+ errdefer aw.deinit();
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.beginObject();
+ try s.objectField("model");
+ try s.write(provider.model);
+ switch (provider.kind) {
+ .openai => {
+ try s.objectField("max_tokens");
+ try s.write(max_out_tokens);
+ try s.objectField("messages");
+ try s.beginArray();
+ try s.beginObject();
+ try s.objectField("role");
+ try s.write("user");
+ try s.objectField("content");
+ try s.write(prompt);
+ try s.endObject();
+ try s.endArray();
+ },
+ .responses => {
+ try s.objectField("max_output_tokens");
+ try s.write(max_out_tokens);
+ try s.objectField("input");
+ try s.write(prompt);
+ },
+ .anthropic => {
+ try s.objectField("max_tokens");
+ try s.write(max_out_tokens);
+ try s.objectField("messages");
+ try s.beginArray();
+ try s.beginObject();
+ try s.objectField("role");
+ try s.write("user");
+ try s.objectField("content");
+ try s.write(prompt);
+ try s.endObject();
+ try s.endArray();
+ },
+ }
+ try s.endObject();
+ return aw.toOwnedSlice();
+}
+
+fn extract(gpa: Allocator, kind: Provider.Kind, raw: []const u8) ToolOutput {
+ var parsed = std.json.parseFromSlice(Value, gpa, raw, .{}) catch {
+ return .{ .text = gpa.dupe(u8, "rlm: llm_query returned non-JSON") catch &.{}, .is_error = true };
+ };
+ defer parsed.deinit();
+ if (parsed.value != .object) {
+ return .{ .text = gpa.dupe(u8, "rlm: llm_query returned a non-object") catch &.{}, .is_error = true };
+ }
+ const text = std.mem.trim(u8, title.assistantText(kind, parsed.value.object), " \t\r\n");
+ if (text.len == 0) {
+ return .{ .text = gpa.dupe(u8, "rlm: llm_query returned no text") catch &.{}, .is_error = true };
+ }
+ return .{ .text = gpa.dupe(u8, text) catch &.{} };
+}
+
+fn sampleProvider(kind: Provider.Kind) Provider {
+ return .{
+ .id = "xai",
+ .kind = kind,
+ .auth = .bearer,
+ .url = "http://127.0.0.1/v1",
+ .api_key = "test",
+ .model = "grok-4.6",
+ .context = 128_000,
+ };
+}
+
+test "llm_query body is tools-off and carries the prompt on every wire" {
+ const gpa = std.testing.allocator;
+ const prompt = "sum the first line of each chunk";
+ for ([_]Provider.Kind{ .openai, .responses, .anthropic }) |kind| {
+ const body = try buildBody(gpa, sampleProvider(kind), prompt);
+ defer gpa.free(body);
+ try std.testing.expect(std.mem.indexOf(u8, body, prompt) != null);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"tools\"") == null);
+ try std.testing.expect(std.mem.indexOf(u8, body, "grok-4.6") != null);
+ }
+}
+
+test "llm_query extract reads assistant text from each wire shape" {
+ const gpa = std.testing.allocator;
+ const openai = "{\"choices\":[{\"message\":{\"content\":\"42\"}}]}";
+ const out_oa = extract(gpa, .openai, openai);
+ defer gpa.free(out_oa.text);
+ try std.testing.expect(!out_oa.is_error);
+ try std.testing.expectEqualStrings("42", out_oa.text);
+
+ const resp = "{\"output\":[{\"type\":\"message\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok\"}]}]}";
+ const out_r = extract(gpa, .responses, resp);
+ defer gpa.free(out_r.text);
+ try std.testing.expect(!out_r.is_error);
+ try std.testing.expectEqualStrings("ok", out_r.text);
+}
diff --git a/src/rlm_spec.zig b/src/rlm_spec.zig
new file mode 100644
index 00000000..e5fe41fe
--- /dev/null
+++ b/src/rlm_spec.zig
@@ -0,0 +1,157 @@
+//! Mid-stream spec-ptc cache for `rlm`. Leaf on purpose: the SSE / ArgLive
+//! path must feed closed lines without importing exec.zig (that would cycle
+//! through Agent). `run_host` is installed by rlm.zig once `--rlm` is on.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const spec_ptc = @import("spec_ptc.zig");
+const tools = @import("tools.zig");
+const ToolCtx = tools.ToolCtx;
+const ToolOutput = tools.ToolOutput;
+
+pub var available: bool = false;
+pub var run_host: ?*const fn (ToolCtx, spec_ptc.Call) ToolOutput = null;
+
+const Inflight = struct {
+ fut: Io.Future(ToolOutput),
+ key: []u8,
+ name: []u8,
+ args: []u8,
+};
+
+const Live = struct {
+ mu: Io.Mutex = .init,
+ ready: bool = false,
+ seg: spec_ptc.Segmenter = .{},
+ launched: std.StringHashMap(void) = undefined,
+ inflight: std.ArrayList(Inflight) = .empty,
+ done: std.StringHashMap(ToolOutput) = undefined,
+};
+
+var live: Live = .{};
+
+pub fn resetLive(gpa: Allocator, io: Io) void {
+ live.mu.lockUncancelable(io);
+ defer live.mu.unlock(io);
+ resetUnlocked(gpa, io);
+}
+
+pub fn feedLive(ctx: ToolCtx, delta: []const u8) void {
+ if (!available or delta.len == 0) return;
+ live.mu.lockUncancelable(ctx.io);
+ defer live.mu.unlock(ctx.io);
+ liveInit(ctx.gpa);
+ const stmts = live.seg.feed(ctx.gpa, delta) catch return;
+ defer {
+ for (stmts) |s| ctx.gpa.free(s);
+ ctx.gpa.free(stmts);
+ }
+ launchStmts(ctx, stmts);
+}
+
+pub fn takeLive(ctx: ToolCtx, claimed: *std.StringHashMap(ToolOutput), arena: Allocator) void {
+ live.mu.lockUncancelable(ctx.io);
+ defer live.mu.unlock(ctx.io);
+ if (!live.ready) return;
+ const tail = live.seg.finish(ctx.gpa) catch &.{};
+ defer {
+ for (tail) |s| ctx.gpa.free(s);
+ if (tail.len > 0) ctx.gpa.free(tail);
+ }
+ launchStmts(ctx, tail);
+ absorbUnlocked(ctx.gpa, ctx.io);
+ var dit = live.done.iterator();
+ while (dit.next()) |e| {
+ const key = arena.dupe(u8, e.key_ptr.*) catch {
+ ctx.gpa.free(e.value_ptr.text);
+ ctx.gpa.free(e.key_ptr.*);
+ continue;
+ };
+ claimed.put(key, e.value_ptr.*) catch {
+ ctx.gpa.free(e.value_ptr.text);
+ ctx.gpa.free(e.key_ptr.*);
+ continue;
+ };
+ ctx.gpa.free(e.key_ptr.*);
+ }
+ live.done.clearRetainingCapacity();
+ live.launched.clearRetainingCapacity();
+ live.seg.deinit(ctx.gpa);
+ live.seg = .{};
+}
+
+fn liveInit(gpa: Allocator) void {
+ if (live.ready) return;
+ live.launched = .init(gpa);
+ live.done = .init(gpa);
+ live.ready = true;
+}
+
+fn resetUnlocked(gpa: Allocator, io: Io) void {
+ if (live.ready) {
+ absorbUnlocked(gpa, io);
+ var dit = live.done.iterator();
+ while (dit.next()) |e| {
+ gpa.free(e.value_ptr.text);
+ gpa.free(e.key_ptr.*);
+ }
+ live.done.deinit();
+ live.launched.deinit();
+ live.inflight.deinit(gpa);
+ live.inflight = .empty;
+ live.ready = false;
+ }
+ live.seg.deinit(gpa);
+ live.seg = .{};
+}
+
+fn runHostThunk(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {
+ if (run_host) |f| return f(ctx, call);
+ return .{ .text = ctx.gpa.dupe(u8, "rlm: host not installed") catch &.{}, .is_error = true };
+}
+
+fn launchStmts(ctx: ToolCtx, stmts: []const []const u8) void {
+ if (run_host == null) return;
+ var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ for (stmts) |stmt| {
+ const call = (spec_ptc.extractCall(arena, stmt) catch continue) orelse continue;
+ const key = call.key(arena) catch continue;
+ if (live.launched.contains(key) or live.done.contains(key)) continue;
+ const owned_key = ctx.gpa.dupe(u8, key) catch continue;
+ const owned_name = ctx.gpa.dupe(u8, call.name) catch {
+ ctx.gpa.free(owned_key);
+ continue;
+ };
+ const owned_args = ctx.gpa.dupe(u8, call.args_json) catch {
+ ctx.gpa.free(owned_key);
+ ctx.gpa.free(owned_name);
+ continue;
+ };
+ live.launched.put(owned_key, {}) catch {
+ ctx.gpa.free(owned_key);
+ ctx.gpa.free(owned_name);
+ ctx.gpa.free(owned_args);
+ continue;
+ };
+ const owned: spec_ptc.Call = .{ .name = owned_name, .args_json = owned_args };
+ const fut = ctx.io.async(runHostThunk, .{ ctx, owned });
+ live.inflight.append(ctx.gpa, .{ .fut = fut, .key = owned_key, .name = owned_name, .args = owned_args }) catch {};
+ }
+}
+
+fn absorbUnlocked(gpa: Allocator, io: Io) void {
+ for (live.inflight.items) |*item| {
+ const out = item.fut.await(io);
+ gpa.free(item.name);
+ gpa.free(item.args);
+ live.done.put(item.key, out) catch {
+ gpa.free(out.text);
+ gpa.free(item.key);
+ };
+ }
+ live.inflight.clearRetainingCapacity();
+}
diff --git a/src/session_settings.zig b/src/session_settings.zig
index c8c24ec2..6bd64d34 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -116,6 +116,7 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
if (environ_map.get("GRAFF_RLM")) |v| {
const rlm = @import("rlm.zig");
rlm.available = rlm.available 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");
+ rlm.sync();
}
if (environ_map.get("GRAFF_NO_LOCAL_TOOLS")) |v| no_local_tools.enabled = no_local_tools.enabled or no_local_tools.envEnables(v);
// GRAFF_LEAN: presence-based, exactly matching session_start.leanSkipsMcp
diff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zig
index a7055f85..e0228a55 100644
--- a/src/session_settings_tests.zig
+++ b/src/session_settings_tests.zig
@@ -129,6 +129,7 @@ const Saved = struct {
main_mod.g_codex_ws = s.codex_ws;
main_mod.g_clock_sleep = s.clock_sleep;
@import("rlm.zig").available = s.rlm;
+ @import("rlm.zig").sync();
http.stream_stall_ms = s.stream_stall_ms;
http.post_deadline_ms = s.post_deadline_ms;
agent_ws.codex_ws_idle_ms = s.codex_ws_idle_ms;
@@ -175,6 +176,7 @@ test "applyEnvKnobs actually applies the values it reads" {
main_mod.g_codex_ws = true;
main_mod.g_clock_sleep = false;
@import("rlm.zig").available = false;
+ @import("rlm.zig").sync();
no_local_tools.enabled = false;
ws.g_debug = false;
provider_mod.g_context_override = null;
diff --git a/src/spec_ptc.zig b/src/spec_ptc.zig
index 30ed5443..df9ee562 100644
--- a/src/spec_ptc.zig
+++ b/src/spec_ptc.zig
@@ -332,6 +332,9 @@ test "extractCall reads positional and keyword literals; print and names are ski
try std.testing.expectEqualStrings("{\"command\":\"status\"}", k.args_json);
const s = (try extractCall(a, "sleep_ms(40)")).?;
try std.testing.expectEqualStrings("{\"ms\":40}", s.args_json);
+ const q = (try extractCall(a, "n = llm_query(\"summarize this chunk\")")).?;
+ try std.testing.expectEqualStrings("llm_query", q.name);
+ try std.testing.expectEqualStrings("{\"prompt\":\"summarize this chunk\"}", q.args_json);
try std.testing.expect(try extractCall(a, "print(x)") == null);
try std.testing.expect(try extractCall(a, "read_file(path)") == null);
try std.testing.expect(try extractCall(a, "# just a comment") == null);