graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(agent): clock_sleep tool — interruptible, 12h-capped, feature-flagged (#225)
Rach Pradhan9d98e08ad263
diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 0a79a69f..8d5fdc3a 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -45,6 +45,8 @@ const ToolOutput = tools_mod.ToolOutput;const exec = @import("exec.zig");const execTool = exec.execTool;+const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement+// escWatchTask/drainStdin/rawNonblockStdin live in agent_interrupt.zig;// Agent.esc_watch_done is a struct-level pub var that STAYS declared inside the// Agent struct in main.zig (never alias a var — see esc_cancel/@@ -314,6 +316,38 @@ pub fn firstWord(cmd: []const u8) []const u8 {return cmd[0..end];}+/// #225: clock_sleep meta tool — root-only, feature-flagged (main.zig+/// g_clock_sleep / --clock-sleep / GRAFF_CLOCK_SLEEP=1). Mirrors codex's+/// clock.sleep: capped at 12h, cancelled by user input like any other+/// backoff (sleepInterruptible), and an interruption is reported as a+/// normal (non-error) outcome, not a tool failure.+pub const clock_sleep_max_ms: i64 = 43_200_000; // 12h, mirrors codex MAX_SLEEP_DURATION_MS++const ClockSleepMs = struct { ms: i64, clamped: bool };++/// Pure `ms`-field validation/clamping, split out of the handleMeta arm so+/// the reject/clamp paths are unit-testable without a live Agent/Io.+/// `input` must be `{"ms": <non-negative integer>}` — anything else+/// (missing, negative, non-integer, wrong shape) is a normal rejection,+/// never a crash. A value over the 12h cap clamps instead of rejecting.+fn parseClockSleepMs(input: Value) error{InvalidMs}!ClockSleepMs {+ if (input != .object) return error.InvalidMs;+ const raw = input.object.get("ms") orelse return error.InvalidMs;+ if (raw != .integer or raw.integer < 0) return error.InvalidMs;+ if (raw.integer > clock_sleep_max_ms) return .{ .ms = clock_sleep_max_ms, .clamped = true };+ return .{ .ms = raw.integer, .clamped = false };+}++fn clockSleepSuccessText(arena: std.mem.Allocator, ms: i64, clamped: bool) ![]const u8 {+ if (clamped) return std.fmt.allocPrint(arena, "clock_sleep: requested ms exceeded the 12h cap, clamped to {d} ms; slept {d} ms", .{ clock_sleep_max_ms, ms });+ return std.fmt.allocPrint(arena, "slept {d} ms", .{ms});+}++fn clockSleepInterruptedText(arena: std.mem.Allocator, elapsed_ms: i64) ![]const u8 {+ return std.fmt.allocPrint(arena, "sleep interrupted after {d} ms by user input", .{elapsed_ms});+}++/// Handle a meta tool inline on the agent's own thread.pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {if (std.mem.eql(u8, call.name, "attempt_completion")) {@@ -345,6 +379,26 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {if (!self.sub) try self.say("{s}\n", .{rendered});return .{ .text = rendered, .is_error = false };}+ if (std.mem.eql(u8, call.name, "clock_sleep")) {+ const parsed = parseClockSleepMs(call.input) catch return .{+ .text = "clock_sleep: ms must be a non-negative integer",+ .is_error = true,+ };+ if (parsed.ms == 0) {+ // Nothing to wait out — skip the sleep call (and the Io clock+ // reads below) entirely rather than round-tripping a zero-length+ // sleep through sleepInterruptible.+ return .{ .text = try clockSleepSuccessText(self.arena, 0, parsed.clamped), .is_error = false };+ }+ const start_ms = util.unixMs(self.io);+ self.sleepInterruptible(@intCast(parsed.ms)) catch |err| switch (err) {+ error.Interrupted => {+ const elapsed_ms = util.unixMs(self.io) - start_ms;+ return .{ .text = try clockSleepInterruptedText(self.arena, elapsed_ms), .is_error = false };+ },+ };+ return .{ .text = try clockSleepSuccessText(self.arena, parsed.ms, parsed.clamped), .is_error = false };+ }if (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);// todo_readreturn .{ .text = self.renderTodos(), .is_error = false };@@ -479,3 +533,121 @@ test "firstWord: splits the command on the first whitespace" {try std.testing.expectEqualStrings("", firstWord(""));try std.testing.expectEqualStrings("", firstWord(" leading"));}++test "parseClockSleepMs: valid ms passes through, missing/negative/non-integer reject, over-cap clamps (#225)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const valid = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":200}", .{}) catch unreachable;+ const parsed = try parseClockSleepMs(valid);+ try std.testing.expectEqual(@as(i64, 200), parsed.ms);+ try std.testing.expect(!parsed.clamped);++ const zero = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":0}", .{}) catch unreachable;+ try std.testing.expectEqual(@as(i64, 0), (try parseClockSleepMs(zero)).ms);++ const missing = std.json.parseFromSliceLeaky(Value, a, "{}", .{}) catch unreachable;+ try std.testing.expectError(error.InvalidMs, parseClockSleepMs(missing));++ const negative = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":-1}", .{}) catch unreachable;+ try std.testing.expectError(error.InvalidMs, parseClockSleepMs(negative));++ const string_ms = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":\"soon\"}", .{}) catch unreachable;+ try std.testing.expectError(error.InvalidMs, parseClockSleepMs(string_ms));++ const float_ms = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":200.5}", .{}) catch unreachable;+ try std.testing.expectError(error.InvalidMs, parseClockSleepMs(float_ms));++ const over_cap = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":99999999999}", .{}) catch unreachable;+ const clamped = try parseClockSleepMs(over_cap);+ try std.testing.expectEqual(clock_sleep_max_ms, clamped.ms);+ try std.testing.expect(clamped.clamped);+}++test "clockSleepSuccessText/clockSleepInterruptedText: exact result strings (#225 acceptance)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try std.testing.expectEqualStrings("slept 200 ms", try clockSleepSuccessText(a, 200, false));+ try std.testing.expectEqualStrings(+ "clock_sleep: requested ms exceeded the 12h cap, clamped to 43200000 ms; slept 43200000 ms",+ try clockSleepSuccessText(a, clock_sleep_max_ms, true),+ );+ try std.testing.expectEqualStrings("sleep interrupted after 150 ms by user input", try clockSleepInterruptedText(a, 150));+}++test "handleMeta clock_sleep: ms=0 completes for real end-to-end, bad ms rejects without touching Io" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent: Agent = .{+ .gpa = a,+ .arena = a,+ // ms=0 never reaches sleepInterruptible's self.io.sleep() call (its+ // while loop is skipped at left=0), and the ms-error paths below+ // return before sleepInterruptible is even called — undefined Io is+ // safe for exactly these cases (a real Io backend has no unit-test+ // seam in this codebase; see agent_argstream.zig's own `.io =+ // undefined` test for the established precedent).+ .io = undefined,+ .client = undefined,+ .provider = undefined,+ .messages = undefined,+ .sub = false,+ .label = "test",+ .out = null,+ };+ const zero_call: ToolCall = .{ .id = "1", .name = "clock_sleep", .input = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":0}", .{}) catch unreachable };+ const zero_result = try handleMeta(&agent, zero_call);+ try std.testing.expectEqualStrings("slept 0 ms", zero_result.text);+ try std.testing.expect(!zero_result.is_error);++ inline for (.{ "{}", "{\"ms\":-1}", "{\"ms\":\"soon\"}", "{\"ms\":200.5}" }) |bad_json| {+ const bad_call: ToolCall = .{ .id = "1", .name = "clock_sleep", .input = std.json.parseFromSliceLeaky(Value, a, bad_json, .{}) catch unreachable };+ const bad_result = try handleMeta(&agent, bad_call);+ try std.testing.expect(bad_result.is_error);+ try std.testing.expectEqualStrings("clock_sleep: ms must be a non-negative integer", bad_result.text);+ }+}++test "clock_sleep counts against --max-tool-calls and --dedupe-tool-calls like any other call (#225 rails, no bypass)" {+ const saved_max = main_mod.max_tool_calls;+ const saved_dedupe = main_mod.dedupe_tool_calls;+ defer {+ main_mod.max_tool_calls = saved_max;+ main_mod.dedupe_tool_calls = saved_dedupe;+ }+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent: Agent = .{+ .gpa = a,+ .arena = a,+ .io = undefined, // rejectToolCall never touches self.io+ .client = undefined,+ .provider = undefined,+ .messages = undefined,+ .sub = false,+ .label = "test",+ .out = null,+ };+ const call: ToolCall = .{ .id = "1", .name = "clock_sleep", .input = std.json.parseFromSliceLeaky(Value, a, "{\"ms\":0}", .{}) catch unreachable };++ main_mod.max_tool_calls = 1;+ main_mod.dedupe_tool_calls = false;+ try std.testing.expect((try rejectToolCall(&agent, call)) == null); // 1st call clears the budget gate+ const budget_denied = try rejectToolCall(&agent, call);+ try std.testing.expect(budget_denied != null);+ try std.testing.expect(budget_denied.?.is_error);+ try std.testing.expect(std.mem.indexOf(u8, budget_denied.?.text, "budget") != null);++ agent.tool_calls_this_turn = 0;+ main_mod.max_tool_calls = null;+ main_mod.dedupe_tool_calls = true;+ try std.testing.expect((try rejectToolCall(&agent, call)) == null); // 1st identical call clears the dedupe gate+ const dupe_denied = try rejectToolCall(&agent, call);+ try std.testing.expect(dupe_denied != null);+ try std.testing.expect(dupe_denied.?.is_error);+ try std.testing.expect(std.mem.indexOf(u8, dupe_denied.?.text, "duplicate") != null);+}diff --git a/src/args.zig b/src/args.zigindex 45800cdb..235d7e34 100644--- a/src/args.zig+++ b/src/args.zig@@ -108,6 +108,8 @@ pub fn parse(init: std.process.Init) !Flags {main_mod.max_tool_calls = std.fmt.parseInt(u64, mv, 10) catch std.process.fatal("--max-tool-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, "--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")) {main_mod.g_worktree_autocommit = false;} else if (std.mem.eql(u8, arg, "--schema")) {diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex e00bc161..6024efa8 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -40,6 +40,7 @@ const serde = @import("serde.zig");const schema = @import("schema.zig");const renderRootTools = schema.renderRootTools;const root_specs = schema.root_specs;+const effectiveRootSpecs = schema.effectiveRootSpecs; // #225: gate clock_sleep on the flag when re-rendering the tool listsconst mcp_cli = @import("mcp_cli.zig");const persistMcpServer = mcp_cli.persistMcpServer;@@ -205,9 +206,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;};// Re-render the tool lists so the new tools reach the model.- root.tools_anthropic = try renderRootTools(arena, .anthropic, &root_specs, reg.tools);- root.tools_openai = try renderRootTools(arena, .openai, &root_specs, reg.tools);- root.tools_responses = try renderRootTools(arena, .responses, &root_specs, reg.tools);+ const root_tool_specs = try effectiveRootSpecs(arena); // #225: gate clock_sleep on the flag+ root.tools_anthropic = try renderRootTools(arena, .anthropic, root_tool_specs, reg.tools);+ root.tools_openai = try renderRootTools(arena, .openai, root_tool_specs, reg.tools);+ root.tools_responses = try renderRootTools(arena, .responses, root_tool_specs, reg.tools);const persisted = persistMcpServer(root.io, arena, name, command, args.items);var has_note = false;for (mcp_notes) |mn| if (std.mem.eql(u8, mn.server, name)) {@@ -233,9 +235,10 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.writeAll("no untrusted workspace MCP server(s) to connect.\n");} else {// Re-render the tool lists so the new tools reach the model.- root.tools_anthropic = try renderRootTools(arena, .anthropic, &root_specs, reg.tools);- root.tools_openai = try renderRootTools(arena, .openai, &root_specs, reg.tools);- root.tools_responses = try renderRootTools(arena, .responses, &root_specs, reg.tools);+ const root_tool_specs = try effectiveRootSpecs(arena); // #225: gate clock_sleep on the flag+ root.tools_anthropic = try renderRootTools(arena, .anthropic, root_tool_specs, reg.tools);+ root.tools_openai = try renderRootTools(arena, .openai, root_tool_specs, reg.tools);+ root.tools_responses = try renderRootTools(arena, .responses, root_tool_specs, reg.tools);try out.print("{s}✓{s} trusted workspace — connected {d} MCP server(s); {d} tool(s) total\n", .{ style.green, style.reset, n, reg.tools.len });}try out.flush();diff --git a/src/main.zig b/src/main.zigindex 200810ce..d2c1f058 100644--- a/src/main.zig+++ b/src/main.zig@@ -58,6 +58,7 @@ pub var show_timing = false;pub var show_cost = false;pub var json_mode = false; // --json: structured JSONL events on stdout instead of human textpub var g_codex_ws = true; // root Codex turns use the WebSocket transport (Responses API over wss) with SSE fallback; GRAFF_CODEX_WS=off|0 forces SSE+pub var g_clock_sleep: bool = false; // #225: root-only clock_sleep meta tool, off by default; --clock-sleep / GRAFF_CLOCK_SLEEP=1 turns it on (gates advertising in renderRootTools, mirrors g_codex_ws)pub var g_force_stall_once: bool = false; // #134 test seam (GRAFF_FORCE_STALL_ONCE=1): the next live turn returns error.StreamStalled — proves the stall path is never labeled a user Escpub var g_force_drop_once: bool = false; // #132/#133 test seam (GRAFF_FORCE_DROP_ONCE=1): the next live turn returns error.StreamDroppedpub var max_tool_calls: ?u64 = null; // --max-tool-calls: hard per-turn root tool budgetdiff --git a/src/schema.zig b/src/schema.zigindex c234e6a0..b735faf9 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -189,6 +189,13 @@ const meta_specs = [_]ToolSpec{\\{"type": "object", "properties": {"result": {"type": "string", "description": "Final answer to present to the user"}}, "required": ["result"]},},+ .{+ .name = "clock_sleep",+ .desc = "Pause the current turn for up to 12 hours of wall-clock time; interruptible by user input, and reported as a normal (non-error) result either way. For autonomous /loop runs that need to wait before re-checking something (e.g. a long external job). Root-only; off unless --clock-sleep/GRAFF_CLOCK_SLEEP=1 is set.",+ .schema =+ \\{"type": "object", "properties": {"ms": {"type": "integer", "description": "Milliseconds to sleep (0 returns immediately; clamped to the 12h/43200000ms cap)"}, "reason": {"type": "string", "description": "Optional: why you're sleeping, for the trace/UX"}}, "required": ["ms"]}+ ,+ },};const subagent_spec = ToolSpec{@@ -214,7 +221,8 @@ pub fn isMetaName(name: []const u8) bool {std.mem.eql(u8, name, "todo_read") orstd.mem.eql(u8, name, "ask_user") orstd.mem.eql(u8, name, "eval") or- std.mem.eql(u8, name, "attempt_completion");+ std.mem.eql(u8, name, "attempt_completion") or+ std.mem.eql(u8, name, "clock_sleep");}// Comptime-rendered tool lists for subagents (base only, both formats).@@ -277,6 +285,21 @@ pub fn renderRootTools(return aw.toOwnedSlice();}+/// Root tool catalog for the current session: drops clock_sleep unless the+/// root-only feature flag is on (--clock-sleep / GRAFF_CLOCK_SLEEP=1, see+/// main.zig g_clock_sleep) so the model never even sees a tool it can't+/// call while the flag is off (#225). Subagents are unaffected — they+/// build their tool lists from base_specs only (tools_*_sub above), which+/// never included meta_specs/clock_sleep in the first place.+pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {+ if (root.g_clock_sleep) return &root_specs;+ var out: std.ArrayList(ToolSpec) = .empty;+ for (root_specs) |t| {+ if (!std.mem.eql(u8, t.name, "clock_sleep")) try out.append(arena, t);+ }+ return out.items;+}+const Schema = union(enum) { raw: []const u8, value: Value };fn writeSchema(s: *std.json.Stringify, schema: Schema) !void {@@ -459,15 +482,38 @@ test "providerDisplayName & providerLoginKind: id mapping with sane fallbacks" {try std.testing.expectEqualStrings("codex_device", providerLoginKind("codex"));try std.testing.expectEqualStrings("api_key", providerLoginKind("openai"));}-test "isMetaName: the four orchestrator-handled meta tools" {+test "isMetaName: the five orchestrator-handled meta tools" {try std.testing.expect(isMetaName("todo_write"));try std.testing.expect(isMetaName("todo_read"));try std.testing.expect(isMetaName("ask_user"));try std.testing.expect(isMetaName("attempt_completion"));+ try std.testing.expect(isMetaName("clock_sleep"));try std.testing.expect(!isMetaName("bash"));try std.testing.expect(!isMetaName("subagent"));try std.testing.expect(!isMetaName("codedb"));}++test "effectiveRootSpecs: drops clock_sleep from the root tool catalog unless the flag is on (#225)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const saved = root.g_clock_sleep;+ defer root.g_clock_sleep = saved;++ root.g_clock_sleep = false;+ const off_specs = try effectiveRootSpecs(a);+ try std.testing.expectEqual(root_specs.len - 1, off_specs.len);+ for (off_specs) |t| try std.testing.expect(!std.mem.eql(u8, t.name, "clock_sleep"));++ root.g_clock_sleep = true;+ const on_specs = try effectiveRootSpecs(a);+ try std.testing.expectEqual(root_specs.len, on_specs.len);+ var found = false;+ for (on_specs) |t| {+ if (std.mem.eql(u8, t.name, "clock_sleep")) found = true;+ }+ try std.testing.expect(found);+}test "providerTakesEffort: effort-honoring providers, but never for grok models" {try std.testing.expect(providerTakesEffort(.responses, "codex", "gpt-5.5"));try std.testing.expect(providerTakesEffort(.openai, "codegraff", "deepseek-v4-pro"));diff --git a/src/session_run.zig b/src/session_run.zigindex 5f8b63fe..ef32c30e 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -200,6 +200,9 @@ pub fn buildRootAgent(flags: args.Flags,telem_endpoint: []const u8,) !agent_mod.Agent {+ // #225: clock_sleep only appears in the model's tool catalog when the+ // root-only feature flag is on (--clock-sleep / GRAFF_CLOCK_SLEEP=1).+ const root_tool_specs = try schema.effectiveRootSpecs(arena);var root: agent_mod.Agent = .{.snapshots = snaps,.gpa = gpa,@@ -218,9 +221,9 @@ pub fn buildRootAgent(.tracer = tracer,.sys_normal = sys_normal,.sys_strict = sys_strict,- .tools_anthropic = try schema.renderRootTools(arena, .anthropic, &schema.root_specs, mcp_tools),- .tools_openai = try schema.renderRootTools(arena, .openai, &schema.root_specs, mcp_tools),- .tools_responses = try schema.renderRootTools(arena, .responses, &schema.root_specs, mcp_tools),+ .tools_anthropic = try schema.renderRootTools(arena, .anthropic, root_tool_specs, mcp_tools),+ .tools_openai = try schema.renderRootTools(arena, .openai, root_tool_specs, mcp_tools),+ .tools_responses = try schema.renderRootTools(arena, .responses, root_tool_specs, mcp_tools),};const fresh_session_name = try std.fmt.allocPrint(arena, "session-{d}", .{util.unixMs(io)});root.session_name = if (flags.resume_flag) |name| (if (!flags.new_session_flag and !flags.no_resume_flag) name else fresh_session_name) else fresh_session_name;@@ -359,6 +362,14 @@ 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.+ 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");+ }// (#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