graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: ACP terminal auth, local tools, schedule, and channel workers
Cursor Agent1fc394575f11
diff --git a/TUI/catalog.zig b/TUI/catalog.zigindex 3ed02ab6..0a016c8c 100644--- a/TUI/catalog.zig+++ b/TUI/catalog.zig@@ -31,6 +31,8 @@ pub const items = [_]Item{.{ .name = "/plan", .desc = "Toggle plan mode" },.{ .name = "/theme", .desc = "Switch color theme", .aliases = &.{"/t"} },.{ .name = "/goal", .desc = "Set a standing objective" },+ .{ .name = "/schedule", .desc = "Fire a prompt later (30s/5m/2h)" },+ .{ .name = "/adapter", .desc = "Channel-worker send / inbox" },.{ .name = "/thinking", .desc = "Show live reasoning" },.{ .name = "/fast", .desc = "Priority service tier" },.{ .name = "/ultracode", .desc = "Persistent workflow mode", .aliases = &.{"/ult"} },diff --git a/docs/acp-registry.md b/docs/acp-registry.mdindex 76c1a2b8..0c43c5f5 100644--- a/docs/acp-registry.md+++ b/docs/acp-registry.md@@ -18,7 +18,7 @@ and the host recipe stays [embedding.md](embedding.md). Replace those with| `graff acp` stdio agent | Shipped. Protocol version 1. || Mid-turn `session/update` (thought / tool / text) | Shipped (ADR [0032](adr/0032-acp-streams-mid-turn.md), #612). || Provider login | `graff login` / keychain / env keys. Not ACP `authenticate`. |-| `initialize.authMethods` | **Missing.** Registry CI requires at least one method with `type: "agent"` or `type: "terminal"`. |+| `initialize.authMethods` | **Shipped.** `graff-login` / `type: "terminal"` / `args: ["login"]`. `authenticate` stays unused — the client re-spawns `graff login`. || `session/load`, `session/request_permission` | Not implemented. Unattended + `--yolo` is the host path. |A stale comment on #613 said #612 was still open. It is not: streaming is on@@ -33,8 +33,8 @@ accepts only:- **Terminal Auth** — the client re-spawns the binary with setup args (a TUIlogin), then runs the normal ACP command.-`graff login` is already Terminal Auth in product terms. Listing still fails-until `initialize` advertises it, for example:+`graff login` is already Terminal Auth in product terms. `initialize` now+advertises it:```json{@@ -121,11 +121,11 @@ Pin `sha256` from that release's `SHA256SUMS` before the PR. Archive layoutis sometimes flat (`graff` at the tarball root) and sometimes nested(`graff-<target>/graff`); `cmd` must match what the installer extracts.-Until `authMethods` is on the wire, this draft is documentation, not a-submission.+`authMethods` is on the wire. Pin `sha256` from a real release, then open the+registry PR in the other repo. This repo still does not fetch the catalog.## Not this repo- No `graff registry` command.- No fetch of `cdn.agentclientprotocol.com`.-- No change to `src/acp.zig` on this continuation cut for listing.+- No `authenticate` implementation (Terminal Auth is out of band).diff --git a/docs/adr/0039-local-tools-are-project-scripts.md b/docs/adr/0039-local-tools-are-project-scripts.mdnew file mode 100644index 00000000..d5c35eb2--- /dev/null+++ b/docs/adr/0039-local-tools-are-project-scripts.md@@ -0,0 +1,34 @@+# 0039. Agent-authored local tools are project scripts, not skills++Status: accepted 2026-08-27++## Context++#555 asked for exo's `install_agent_tool` loop: the agent writes a tool at+runtime, the harness validates it, and later sessions see it as a first-class+tool. Graff already has skills (instruction playbooks) and MCP (out-of-process+servers). A third thing that is "just a skill with a shebang" would blur both.++`schema.zig` is at the 600-line cap and feeds the 64-cell+`spec/kernels/tool_catalog.json` cube. Putting every installed name into+`effectiveRootSpecs` would force an SDK regen on every project script.++## Decision++- A local tool lives at `.graff/tools/<name>/` with `manifest.json` plus a+ script. Runners are `python3`, `bun`, or `sh`.+- `install_agent_tool` validates the manifest, dry-runs `argv --dry-run`+ (exit 0 required), then registers `local__<name>`. Live calls pass the+ JSON args as argv[2] — `process_runner.runCapped` has no stdin.+- Skills stay instructions. MCP stays consent-gated servers. This is the+ executable, project-local half.+- Catalog extras are concatenated in `agent_catalog.ensureRootTools`, not+ added to `schema.effectiveRootSpecs`. `--no-local-tools` / `--lean` hide+ them. Subagents do not see them. Plan mode refuses install and live calls.++## Consequences++- A script that ignores `--dry-run` fails install. A script that reads stdin+ for args will see nothing.+- Do not grow `schema.meta_names` or the SDK cube for these names.+- Revisit if a project needs MCP-shaped stdin JSON or a fourth runner.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex fcc12358..048fe2d2 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -49,6 +49,7 @@ record only when you need the evidence or the edge cases.| [0036](0036-computer-use-keeps-the-signed-codex-bridge.md) | Codex Computer Use keeps its authenticated node_repl process chain: Graff launches it through the signed Codex sandbox wrapper, never embeds V8 or spoofs the service. || [0037](0037-experiment-pool-is-opt-in.md) | `--experiment N` / `/experiment N` pre-mints a child worktree pool; default isolation stays `shared_cwd`. 279 continuation — not on main until a later cut. || [0038](0038-in-process-acp-core.md) | Same-process embed is `libgraff` + `graff-core.wasm` + `createGraffAgent()` (ACP core, echo turn). Live coding stays `graff acp`. 279 continuation — not on main until a later cut. |+| [0039](0039-local-tools-are-project-scripts.md) | Agent-authored local tools are project scripts under `.graff/tools/`; skills stay instructions. Runtime catalog extras, not `schema.effectiveRootSpecs`. |## When to write onediff --git a/src/acp.zig b/src/acp.zigindex 97fa02fc..5458b6b2 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -279,6 +279,8 @@ test "handleLine: initialize, session/new, then a prompt turn" {try testing.expect(std.mem.indexOf(u8, init_line, "\"embeddedContext\":true") != null);try testing.expect(std.mem.indexOf(u8, init_line, "\"name\":\"graff\"") != null);try testing.expect(std.mem.indexOf(u8, init_line, "\"loadSession\":false") != null);+ try testing.expect(std.mem.indexOf(u8, init_line, "graff-login") != null);+ try testing.expect(std.mem.indexOf(u8, init_line, "\"type\":\"terminal\"") != null);w = .fixed(&buf);try handleLine(&d, a, &w, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\",\"params\":{\"cwd\":\"/tmp\"}}");diff --git a/src/acp_auth.zig b/src/acp_auth.zignew file mode 100644index 00000000..d5841177--- /dev/null+++ b/src/acp_auth.zig@@ -0,0 +1,66 @@+//! ACP v1 Terminal Auth descriptor (#613). `graff login` is already that+//! flow; this module is the wire shape `initialize` advertises so registry+//! CI (and Zed) can see it.+//!+//! Do not invent Agent Auth. Do not accept a terminal method on+//! `authenticate` — the client re-spawns the binary (ACP RFD).++const std = @import("std");+const Value = std.json.Value;++pub const AuthMethod = struct {+ id: []const u8,+ name: []const u8,+ description: []const u8,+ type: []const u8,+ args: []const []const u8,+};++pub const terminal_login = AuthMethod{+ .id = "graff-login",+ .name = "graff login",+ .description = "Interactive terminal login (codegraff / Codex / Kimi)",+ .type = "terminal",+ .args = &.{"login"},+};++pub const advertised = [_]AuthMethod{terminal_login};++/// v1 clients that can open an interactive terminal set+/// `clientCapabilities.auth.terminal = true`. Missing keys default false;+/// we still advertise (registry CI must see a method) because `graff login`+/// exists whether the client sent the capability or not.+pub fn clientAllowsTerminal(params: ?Value) bool {+ const p = params orelse return false;+ if (p != .object) return false;+ const caps = p.object.get("clientCapabilities") orelse return false;+ if (caps != .object) return false;+ const auth = caps.object.get("auth") orelse return false;+ if (auth != .object) return false;+ const terminal = auth.object.get("terminal") orelse return false;+ return switch (terminal) {+ .bool => |b| b,+ else => false,+ };+}++test "terminal_login is the registry Terminal Auth shape" {+ try std.testing.expectEqualStrings("graff-login", terminal_login.id);+ try std.testing.expectEqualStrings("terminal", terminal_login.type);+ try std.testing.expectEqualStrings("login", terminal_login.args[0]);+}++test "clientAllowsTerminal reads the v1 capability" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const yes = try std.json.parseFromSliceLeaky(Value, a,+ \\{"clientCapabilities":{"auth":{"terminal":true}}}+ , .{});+ const no = try std.json.parseFromSliceLeaky(Value, a,+ \\{"clientCapabilities":{"fs":{}}}+ , .{});+ try std.testing.expect(clientAllowsTerminal(yes));+ try std.testing.expect(!clientAllowsTerminal(no));+ try std.testing.expect(!clientAllowsTerminal(null));+}diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex e656c638..ede34dda 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -8,6 +8,7 @@ const Allocator = std.mem.Allocator;const proto = @import("acp_protocol.zig");const util = @import("util.zig");+const acp_auth = @import("acp_auth.zig");pub const parseRequest = proto.parseRequest;pub const negotiateVersion = proto.negotiateVersion;@@ -103,7 +104,10 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u.promptCapabilities = proto.PromptCapabilities{},},.agentImplementation = proto.AgentImplementation{ .version = implementation_version },+ .authMethods = acp_auth.advertised,});+ if (std.mem.eql(u8, req.method, "authenticate"))+ return respondError(w, req, err_method_not_found, "terminal auth is out of band: re-spawn graff login");if (std.mem.eql(u8, req.method, "session/new")) {d.created += 1;d.session_id = try std.fmt.allocPrint(arena, "acp-{x}-{d}", .{ d.seed, d.created });@@ -140,6 +144,9 @@ test "in-process handleLine speaks the same initialize / new / prompt envelopes"try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"protocolVersion\":1") != null);try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"name\":\"graff\"") != null);try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "embed-test") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"authMethods\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "graff-login") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"type\":\"terminal\"") != null);w = .fixed(&buf);try handleLine(&d, a, &w, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}");@@ -152,6 +159,17 @@ test "in-process handleLine speaks the same initialize / new / prompt envelopes"try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"stopReason\":\"end_turn\"") != null);}+test "authenticate names the out-of-band terminal login" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ var buf: [512]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined };+ try handleLine(&d, state.allocator(), &w, "{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"authenticate\",\"params\":{\"methodId\":\"graff-login\"}}");+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"code\":-32601") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "graff login") != null);+}+test "stripSgr drops CSI sequences" {var state = std.heap.ArenaAllocator.init(std.testing.allocator);defer state.deinit();diff --git a/src/agent.zig b/src/agent.zigindex 031b8eca..550cbdb2 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -36,6 +36,8 @@ const empty_completion = @import("agent_empty_completion.zig");const goal_state = @import("goal_state.zig");const peer_channel = @import("peer_channel.zig"); // #469: turn-boundary peer message deliveryconst job_notify = @import("job_notify.zig");+const schedule = @import("schedule.zig");+const channel_worker = @import("channel_worker.zig");pub const TodoItem = struct {content: []const u8,@@ -339,6 +341,8 @@ pub const Agent = struct {// an empty channel costs one small stat per step.peer_channel.deliverInbound(self);job_notify.deliver(self);+ schedule.deliver(self);+ channel_worker.deliver(self);// #193: pre-send overflow gate. A single turn's tool-output burst can// push the input past the model's wall before the between-turns 80%// meter (last_context_tokens, server-reported) catches up. Estimate thediff --git a/src/agent_catalog.zig b/src/agent_catalog.zigindex 0504f3b7..fe7343ca 100644--- a/src/agent_catalog.zig+++ b/src/agent_catalog.zig@@ -1,5 +1,7 @@//! Root/worker tool-catalog materialization. Split out of agent.zig (600-line ceiling).+const std = @import("std");+const Allocator = std.mem.Allocator;const main_mod = @import("main.zig");const schema = @import("schema.zig");const no_local_tools = @import("no_local_tools.zig");@@ -7,6 +9,19 @@ const surface = @import("tool_surface.zig");const mcp = @import("mcp.zig");const Provider = @import("provider.zig").Provider;const Agent = @import("agent.zig").Agent;+const local_tools = @import("local_tools.zig");+const schedule = @import("schedule.zig");++fn withExtras(arena: Allocator, base: []const schema.ToolSpec) ![]const schema.ToolSpec {+ const a = local_tools.catalogExtras(arena);+ const b = schedule.catalogExtras(arena);+ if (a.len == 0 and b.len == 0) return base;+ const out = try arena.alloc(schema.ToolSpec, base.len + a.len + b.len);+ @memcpy(out[0..base.len], base);+ @memcpy(out[base.len..][0..a.len], a);+ @memcpy(out[base.len + a.len ..], b);+ return out;+}pub fn toolsJson(self: *const Agent) []const u8 {if (self.sub) {@@ -35,7 +50,7 @@ pub fn ensureRootTools(self: *Agent, kind: Provider.Kind) !void {const specs = if (self.sub)try surface.filterSpecs(@TypeOf(schema.base_specs[0]), self.arena, schema.base_specs[0..])else- try schema.effectiveRootSpecs(self.arena);+ try withExtras(self.arena, try schema.effectiveRootSpecs(self.arena));const connected: []const mcp.Tool = if (self.registry) |registry|(if (self.sub) try surface.filterWorkerMcp(self.arena, registry.tools) else registry.tools)elsediff --git a/src/agent_tools.zig b/src/agent_tools.zigindex a91bb4ff..dcb1a8c1 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -49,6 +49,8 @@ const brief_diversity = @import("brief_diversity.zig"); // #382: N sibling spawnconst playbook_glue = @import("playbook_glue.zig"); // #381: the note_constraint meta armconst mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the load_tool_schemas meta armconst native_fold = @import("native_fold.zig"); // folded native power tools: load_tool_schemas's native half+const local_tools = @import("local_tools.zig");+const schedule = @import("schedule.zig");const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement// #440: the ONE size contract for a tool result — preview + durable handle +@@ -102,7 +104,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {try self.sayToolUse(call);if (self.output_schema != null and std.mem.eql(u8, call.name, "structured_output")) {results[i] = @import("agent_request_body_responses.zig").handleStructuredOutput(self, call.input); // #543 tool-mode capture- } else if (isMetaName(call.name)) {+ } else if (isMetaName(call.name) or local_tools.isInstall(call.name) or schedule.isName(call.name)) {results[i] = try self.handleMeta(call);} else if (try self.gateTool(call)) |denied| {results[i] = denied;@@ -312,6 +314,14 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {// #469: sideways coordination between co-resident root sessions.if (std.mem.eql(u8, call.name, peer_channel.tool_name)) return peer_channel.handleMessage(self, call);if (std.mem.eql(u8, call.name, workspace_switch.tool_name)) return workspace_switch.handle(self, call);+ if (local_tools.isInstall(call.name)) {+ if (main_mod.plan_mode) return .{ .text = "plan mode is on — install_agent_tool writes .graff/tools; switch to act first.", .is_error = true };+ return local_tools.handleInstall(self, call);+ }+ if (schedule.isName(call.name)) {+ if (main_mod.plan_mode) return .{ .text = "plan mode is on — schedule_task writes .graff/schedule; switch to act first.", .is_error = true };+ return schedule.handleTool(self, call);+ }if (std.mem.eql(u8, call.name, "attempt_completion")) {if (!self.review_mode and self.eval_cmd != null and (!self.eval_verified or self.eval_repair_pending)) {const message = if (self.eval_repair_pending)diff --git a/src/channel_worker.zig b/src/channel_worker.zignew file mode 100644index 00000000..a9c09585--- /dev/null+++ b/src/channel_worker.zig@@ -0,0 +1,170 @@+//! Host-managed channel workers (#558). JSONL over stdin/stdout: inbound+//! `{"type":"message","text":"..."}` wakes the session; outbound+//! `{"type":"send","text":"..."}` is the outbox. Discord/Slack fronts come+//! later; this is the protocol + wake seam.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const session_wake = @import("session_wake.zig");+const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;++pub const inbound_type = "message";+pub const outbound_type = "send";++const cap: usize = 16;+var mu: Io.Mutex = .init;+var ring: [cap][]u8 = undefined;+var count: usize = 0;+var gpa_hold: ?Allocator = null;++pub fn parseInbound(arena: Allocator, line: []const u8) ?[]const u8 {+ const v = std.json.parseFromSliceLeaky(Value, arena, std.mem.trim(u8, line, " \t\r\n"), .{}) catch return null;+ if (v != .object) return null;+ const ty = if (v.object.get("type")) |x| (if (x == .string) x.string else "") else "";+ if (!std.mem.eql(u8, ty, inbound_type)) return null;+ const text = if (v.object.get("text")) |x| (if (x == .string) x.string else "") else "";+ return if (text.len == 0) null else text;+}++pub fn formatOutbound(arena: Allocator, text: []const u8) ![]const u8 {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(.{ .type = outbound_type, .text = text });+ try aw.writer.writeByte('\n');+ return aw.writer.buffered();+}++/// Queue an inbound worker line (host thread). `gpa` owns the copy.+pub fn record(io: Io, gpa: Allocator, text: []const u8) void {+ const owned = gpa.dupe(u8, text) catch return;+ mu.lockUncancelable(io);+ defer mu.unlock(io);+ gpa_hold = gpa;+ if (count == cap) {+ gpa.free(ring[0]);+ std.mem.copyForwards([]u8, ring[0 .. cap - 1], ring[1..cap]);+ count = cap - 1;+ }+ ring[count] = owned;+ count += 1;+}++pub fn takeAll(io: Io, arena: Allocator) []const []const u8 {+ mu.lockUncancelable(io);+ defer mu.unlock(io);+ if (count == 0) return &.{};+ const out = arena.alloc([]const u8, count) catch return &.{};+ var i: usize = 0;+ while (i < count) : (i += 1) {+ out[i] = arena.dupe(u8, ring[i]) catch "";+ if (gpa_hold) |g| g.free(ring[i]);+ }+ count = 0;+ return out;+}++pub fn deliver(root: *Agent) void {+ if (root.sub) return;+ const lines = takeAll(root.io, root.arena);+ for (lines) |text| {+ const wake = std.fmt.allocPrint(root.arena, "[adapter] {s}", .{text}) catch continue;+ session_wake.inject(root, wake);+ }+}++/// `/adapter send <text>` posts to the outbox (tests + a later live worker).+pub fn slashCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ const rest = std.mem.trim(u8, line["/adapter".len..], " \t");+ if (std.mem.startsWith(u8, rest, "send ") or std.mem.startsWith(u8, rest, "send\t")) {+ const text = std.mem.trim(u8, rest["send".len..], " \t");+ if (text.len == 0) {+ try out.writeAll("usage: /adapter send <text>\n");+ try out.flush();+ return true;+ }+ const wire = try formatOutbound(arena, text);+ try out.writeAll(wire);+ try out.flush();+ return true;+ }+ if (std.mem.eql(u8, rest, "inbox")) {+ const lines = takeAll(root.io, arena);+ if (lines.len == 0) try out.writeAll("(adapter inbox empty)\n") else {+ for (lines) |t| try out.print("{s}\n", .{t});+ }+ try out.flush();+ return true;+ }+ try out.writeAll("usage: /adapter send <text> | /adapter inbox\n");+ try out.flush();+ return true;+}++test "parseInbound accepts message lines and drops the rest" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ try std.testing.expectEqualStrings("hi", parseInbound(a, "{\"type\":\"message\",\"text\":\"hi\"}").?);+ try std.testing.expect(parseInbound(a, "{\"type\":\"send\",\"text\":\"hi\"}") == null);+ try std.testing.expect(parseInbound(a, "not-json") == null);+}++test "formatOutbound is a send line" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const wire = try formatOutbound(arena.allocator(), "pong");+ try std.testing.expect(std.mem.indexOf(u8, wire, "\"type\":\"send\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, wire, "pong") != null);+ try std.testing.expect(std.mem.endsWith(u8, wire, "\n"));+}++/// Idle TUI auto-turn: drain the inbox into a buffer without an Agent.+pub fn takeWake(io: Io, buf: []u8) ?[]const u8 {+ var scratch: [16 * 1024]u8 = undefined;+ var fba = std.heap.FixedBufferAllocator.init(&scratch);+ const lines = takeAll(io, fba.allocator());+ if (lines.len == 0) return null;+ var used: usize = 0;+ for (lines) |text| {+ const piece = std.fmt.bufPrint(buf[used..], if (used == 0) "[adapter] {s}" else "\n[adapter] {s}", .{text}) catch break;+ used += piece.len;+ }+ return if (used == 0) null else buf[0..used];+}++test "slashCommand send is a send line; inbox drains takeWake" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var arena = std.heap.ArenaAllocator.init(gpa);+ defer arena.deinit();+ _ = takeAll(io, arena.allocator());+ var root: Agent = undefined;+ root.io = io;+ var aw: std.Io.Writer.Allocating = .init(gpa);+ defer aw.deinit();+ try std.testing.expect(try slashCommand(&root, arena.allocator(), "/adapter send pong", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "\"type\":\"send\"") != null);+ record(io, gpa, "hello");+ var buf: [128]u8 = undefined;+ const wake = takeWake(io, &buf) orelse return error.Empty;+ try std.testing.expectEqualStrings("[adapter] hello", wake);+ try std.testing.expect(takeWake(io, &buf) == null);+}++test "record then takeAll drains once" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var arena = std.heap.ArenaAllocator.init(gpa);+ defer arena.deinit();+ _ = takeAll(io, arena.allocator());+ record(io, gpa, "one");+ record(io, gpa, "two");+ const got = takeAll(io, arena.allocator());+ try std.testing.expectEqual(@as(usize, 2), got.len);+ try std.testing.expectEqualStrings("one", got[0]);+ try std.testing.expectEqual(@as(usize, 0), takeAll(io, arena.allocator()).len);+}diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 2d894fc4..fcdac633 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -28,6 +28,8 @@ pub const commands = [_]Item{.{ .name = "/rename", .usage = "/rename <title>", .desc = "set the current session title" },.{ .name = "/goal", .usage = "/goal [30m] [text|pause|resume|status|clear]", .desc = "set a standing objective and work it autonomously; an optional 30s/30m/2h budget paces the run; pause/resume steering, status shows state, clear removes it" },.{ .name = "/loop", .usage = "/loop [30m] <prompt>", .desc = "the same autonomous run as /goal, without adopting a standing objective" },+ .{ .name = "/schedule", .usage = "/schedule <30s|5m|2h> <prompt>", .desc = "fire a prompt later; delay tokens match /loop (not a standing goal)" },+ .{ .name = "/adapter", .usage = "/adapter send <text>|inbox", .desc = "channel-worker outbox / inbox (JSONL protocol; Discord/Slack fronts later)" },.{ .name = "/review", .usage = "/review <target or instructions>", .desc = "run one isolated read-only review pass; no edits, delegation, or workflows" },.{ .name = "/never", .usage = "/never [<text>|rm <id-or-text>]", .desc = "standing constraints that ride every brief; bare opens a searchable picker (TTY) or lists them, rm <id-or-text> retires one (alias /constraint)" },.{ .name = "/tell", .usage = "/tell <session|all> <text>", .desc = "message a running graff: <session> is a DM (only it hears, any folder); all broadcasts to every graff on this device; /sessions lists who's around" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex ebae797f..aad656ec 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -163,6 +163,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (try @import("adopt.zig").trySlash(root.io, arena, root.home, line, out)) return true;if (try commands_privacy.tryHandle(root, line, out)) return true;if (try playbook_glue.command(root, arena, line, out)) return true; // #381 /never | /constraint+ if (std.mem.startsWith(u8, line, "/schedule") and (line.len == 9 or line[9] == ' ' or line[9] == '\t')) return @import("schedule.zig").slashCommand(root, arena, line, out);+ if (std.mem.startsWith(u8, line, "/adapter") and (line.len == 8 or line[8] == ' ' or line[8] == '\t')) return @import("channel_worker.zig").slashCommand(root, arena, line, out);if (try side_question.command(root, arena, line, out)) return true; // #415 /btw// #321: doctor.zig shipped with a catalog entry but no dispatch, so /doctor// was advertised in /help and the `/` menu while answering "unknown command".diff --git a/src/exec.zig b/src/exec.zigindex 308fee86..4c9c69ad 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -67,6 +67,7 @@ const native_fold = @import("native_fold.zig"); // folded native power tools: laconst vision = @import("vision.zig"); // read_file stages images like MCP image results (#249)const input_util = @import("input_util.zig");const imagegen = @import("imagegen.zig"); // #352: the codex-gated image tool (advertising lives in schema.zig/tool_gates.zig)+const local_tools = @import("local_tools.zig");fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {var argc: usize = 0;@@ -163,6 +164,10 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {/// one that was never advertised (layer 1 is schema.zig). FIRST in the guard/// chain; an `mcp__*` name never matches, so the sandbox proxy keeps working.fn noLocalToolsGate(ctx: ToolCtx, call: ToolCall) ?ToolOutput {+ if (no_local_tools.enabled and local_tools.isLocal(call.name)) {+ const text = ctx.gpa.dupe(u8, no_local_tools.refusal_text) catch return .{ .text = &.{}, .is_error = true };+ return .{ .text = text, .is_error = true };+ }if (!no_local_tools.blocks(call.name)) return null;const text = ctx.gpa.dupe(u8, no_local_tools.refusal_text) catch return .{ .text = &.{}, .is_error = true };return .{ .text = text, .is_error = true };@@ -175,7 +180,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {// Plan mode backstop: the root gate already denies these with a nicer// message; this catches subagents (which skip the gate entirely).if (main_mod.plan_mode) {- if (std.mem.eql(u8, call.name, "learn_candidate") or std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or std.mem.eql(u8, call.name, imagegen.tool_name) or mcp.Registry.isMcp(call.name)) return .{+ if (local_tools.isLocal(call.name) or std.mem.eql(u8, call.name, "learn_candidate") or std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file") or std.mem.eql(u8, call.name, imagegen.tool_name) or mcp.Registry.isMcp(call.name)) return .{.text = try gpa.dupe(u8, "plan mode is on — read-only; describe the change instead of making it"),.is_error = true,};@@ -408,6 +413,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {if (std.mem.eql(u8, call.name, "subagent")) return execSubagent(ctx, input);if (std.mem.eql(u8, call.name, "workflow")) return execWorkflow(ctx, input);if (std.mem.eql(u8, call.name, @import("rlm.zig").tool_name)) return @import("rlm.zig").exec(ctx, input);+ if (local_tools.isLocal(call.name)) return local_tools.call(gpa, io, call.name, input);if (std.mem.eql(u8, call.name, "agent_output")) {const id = intField(input, "id") orelse return missingArg(gpa, "id");const wait_ms = intField(input, "wait_ms") orelse 0;diff --git a/src/help.zig b/src/help.zigindex af61f8f7..75dd6d0f 100644--- a/src/help.zig+++ b/src/help.zig@@ -30,8 +30,8 @@ const peers_blurb =pub const sections = [_]Section{.{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/snapshot" } },.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },- .{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },- .{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek" }, .blurb = peers_blurb },+ .{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/schedule", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },+ .{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek", "/adapter" }, .blurb = peers_blurb },.{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/privacy", "/mcp", "/import-claude", "/skills", "/plugins", "/agents", "/hooks", "/tools", "/fleet" } },.{ .title = "context & history", .names = &.{ "/compact", "/btw", "/doctor", "/debug", "/cache", "/trace", "/trajectory" } },.{ .title = "shell & images", .names = &.{ "/bash", "/image", "/images", "/paste" } },diff --git a/src/local_tools.zig b/src/local_tools.zignew file mode 100644index 00000000..d9861535--- /dev/null+++ b/src/local_tools.zig@@ -0,0 +1,269 @@+//! Agent-authored project-local tools (#555). Skills stay instructions;+//! this is the executable half: `.graff/tools/<name>/` with a manifest ++//! script, validated at install, registered on every later session.+//!+//! Runner is a subprocess speaking a one-shot JSON contract (stdin args,+//! stdout text or `{"text","is_error"}`). Not MCP, not a skill.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const schema = @import("schema.zig");+const no_local_tools = @import("no_local_tools.zig");+const process_runner = @import("process_runner.zig");+const agent_mod = @import("agent.zig");+const tools_mod = @import("tools.zig");++const Agent = agent_mod.Agent;+const ToolCall = tools_mod.ToolCall;+const ExecResult = tools_mod.ExecResult;+const ToolSpec = schema.ToolSpec;++pub const install_name = "install_agent_tool";+pub const install_desc = "Install a project-local tool under .graff/tools/<name>/. Validates the manifest, dry-runs the script, and registers it as local__<name> for later turns. Skills stay instructions; this is the executable half.";+pub const install_schema =+ \\{"type": "object", "properties": {"name": {"type": "string", "description": "tool name (letters, digits, _-)"}, "description": {"type": "string"}, "schema": {"type": "string", "description": "JSON Schema object for the tool input"}, "runner": {"type": "string", "enum": ["python3", "bun", "sh"]}, "entry": {"type": "string", "description": "script filename inside the tool dir (no path separators)"}, "source": {"type": "string", "description": "script body"}}, "required": ["name", "description", "schema", "runner", "entry", "source"]}+;++pub const prefix = "local__";+pub const store_rel = ".graff/tools";++const install_spec = ToolSpec{ .name = install_name, .desc = install_desc, .schema = install_schema };++pub const Installed = struct {+ spec: ToolSpec,+ runner: []const u8,+ entry_path: []const u8,+};++var g_loaded: []Installed = &.{};++pub fn isInstall(name: []const u8) bool {+ return std.mem.eql(u8, name, install_name);+}++pub fn isLocal(name: []const u8) bool {+ return std.mem.startsWith(u8, name, prefix);+}++pub fn nameOk(name: []const u8) bool {+ if (name.len == 0 or name.len > 40) return false;+ for (name) |c| {+ const ok = std.ascii.isAlphanumeric(c) or c == '_' or c == '-';+ if (!ok) return false;+ }+ return true;+}++pub fn runnerOk(runner: []const u8) bool {+ return std.mem.eql(u8, runner, "python3") or std.mem.eql(u8, runner, "bun") or std.mem.eql(u8, runner, "sh");+}++pub fn entryOk(entry: []const u8) bool {+ if (entry.len == 0 or std.mem.indexOfAny(u8, entry, "/\\") != null) return false;+ if (std.mem.eql(u8, entry, "..") or std.mem.indexOf(u8, entry, "..") != null) return false;+ return true;+}++pub fn schemaOk(raw: []const u8) bool {+ var parsed = std.json.parseFromSlice(Value, std.heap.page_allocator, raw, .{}) catch return false;+ defer parsed.deinit();+ if (parsed.value != .object) return false;+ const ty = parsed.value.object.get("type") orelse return false;+ return ty == .string and std.mem.eql(u8, ty.string, "object");+}++pub fn qualified(arena: Allocator, name: []const u8) []const u8 {+ return std.fmt.allocPrint(arena, "{s}{s}", .{ prefix, name }) catch name;+}++/// Scan `.graff/tools/` into the process-local table (session arena).+pub fn load(io: Io, arena: Allocator) void {+ g_loaded = &.{};+ if (no_local_tools.enabled or no_local_tools.lean) return;+ var dir = Io.Dir.cwd().openDir(io, store_rel, .{ .iterate = true }) catch return;+ defer dir.close(io);+ var it = dir.iterate(io);+ var list: std.ArrayList(Installed) = .empty;+ while (it.next(io) catch null) |ent| {+ if (ent.kind != .directory) continue;+ if (!nameOk(ent.name)) continue;+ const one = readOne(io, arena, ent.name) orelse continue;+ list.append(arena, one) catch break;+ }+ g_loaded = list.items;+}++fn readOne(io: Io, arena: Allocator, name: []const u8) ?Installed {+ const man_path = std.fmt.allocPrint(arena, "{s}/{s}/manifest.json", .{ store_rel, name }) catch return null;+ const raw = Io.Dir.cwd().readFileAlloc(io, man_path, arena, .limited(64 * 1024)) catch return null;+ const obj = std.json.parseFromSliceLeaky(Value, arena, raw, .{}) catch return null;+ if (obj != .object) return null;+ const desc = if (obj.object.get("description")) |v| (if (v == .string) v.string else "") else "";+ const schema_s = if (obj.object.get("schema")) |v| (if (v == .string) v.string else "") else "";+ const runner = if (obj.object.get("runner")) |v| (if (v == .string) v.string else "") else "";+ const entry = if (obj.object.get("entry")) |v| (if (v == .string) v.string else "") else "";+ if (desc.len == 0 or !schemaOk(schema_s) or !runnerOk(runner) or !entryOk(entry)) return null;+ const entry_path = std.fmt.allocPrint(arena, "{s}/{s}/{s}", .{ store_rel, name, entry }) catch return null;+ Io.Dir.cwd().access(io, entry_path, .{}) catch return null;+ return .{+ .spec = .{ .name = qualified(arena, name), .desc = desc, .schema = schema_s },+ .runner = runner,+ .entry_path = entry_path,+ };+}++/// Catalog extras for this session: the install meta-tool plus every loaded local.+pub fn catalogExtras(arena: Allocator) []const ToolSpec {+ if (no_local_tools.enabled or no_local_tools.lean) return &.{};+ const n = 1 + g_loaded.len;+ const out = arena.alloc(ToolSpec, n) catch return &.{};+ out[0] = install_spec;+ for (g_loaded, 0..) |it, i| out[i + 1] = it.spec;+ return out;+}++pub fn handleInstall(self: *Agent, call: ToolCall) !ExecResult {+ if (self.sub) return .{ .text = "install_agent_tool is root-only", .is_error = true };+ if (no_local_tools.enabled or no_local_tools.lean) return .{ .text = "local tools are disabled under --no-local-tools / --lean", .is_error = true };+ const obj = tools_mod.json_args.object(call.input) orelse return .{ .text = "install_agent_tool needs an object", .is_error = true };+ const name = tools_mod.json_args.str(obj, "name") orelse "";+ const description = tools_mod.json_args.str(obj, "description") orelse "";+ const schema_s = tools_mod.json_args.str(obj, "schema") orelse "";+ const runner = tools_mod.json_args.str(obj, "runner") orelse "";+ const entry = tools_mod.json_args.str(obj, "entry") orelse "";+ const source = tools_mod.json_args.str(obj, "source") orelse "";+ if (!nameOk(name)) return .{ .text = "name must be 1-40 letters, digits, _ or -", .is_error = true };+ if (description.len == 0) return .{ .text = "description is required", .is_error = true };+ if (!schemaOk(schema_s)) return .{ .text = "schema must be a JSON object schema", .is_error = true };+ if (!runnerOk(runner)) return .{ .text = "runner must be python3, bun, or sh", .is_error = true };+ if (!entryOk(entry)) return .{ .text = "entry must be a filename in the tool dir", .is_error = true };+ if (source.len == 0) return .{ .text = "source is required", .is_error = true };++ const dir_rel = try std.fmt.allocPrint(self.arena, "{s}/{s}", .{ store_rel, name });+ Io.Dir.cwd().makePath(self.io, dir_rel) catch return .{ .text = "could not create .graff/tools dir", .is_error = true };+ const entry_rel = try std.fmt.allocPrint(self.arena, "{s}/{s}", .{ dir_rel, entry });+ Io.Dir.cwd().writeFile(self.io, .{ .sub_path = entry_rel, .data = source }) catch return .{ .text = "could not write the script", .is_error = true };+ const man = try std.fmt.allocPrint(self.arena,+ \\{{"name":{s},"description":{s},"schema":{s},"runner":{s},"entry":{s}}}+ , .{+ try jsonString(self.arena, name),+ try jsonString(self.arena, description),+ try jsonString(self.arena, schema_s),+ try jsonString(self.arena, runner),+ try jsonString(self.arena, entry),+ });+ const man_rel = try std.fmt.allocPrint(self.arena, "{s}/manifest.json", .{dir_rel});+ Io.Dir.cwd().writeFile(self.io, .{ .sub_path = man_rel, .data = man }) catch return .{ .text = "could not write the manifest", .is_error = true };++ if (!dryRun(self.io, self.gpa, runner, entry_rel)) {+ return .{ .text = "dry-run failed — the script must exit 0 on --dry-run", .is_error = true };+ }+ load(self.io, self.arena);+ self.invalidateRootTools();+ return .{ .text = try std.fmt.allocPrint(self.arena, "installed {s}{s} — registered for the next model call", .{ prefix, name }), .is_error = false };+}++fn jsonString(arena: Allocator, s: []const u8) ![]const u8 {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var st: std.json.Stringify = .{ .writer = &aw.writer };+ try st.write(s);+ return aw.writer.buffered();+}++fn dryRun(io: Io, gpa: Allocator, runner: []const u8, entry_rel: []const u8) bool {+ const argv = [_][]const u8{ runner, entry_rel, "--dry-run" };+ const run_res = process_runner.runCapped(gpa, io, &argv, 32 * 1024, 4 * 1024, 8_000) catch return false;+ defer gpa.free(run_res.stdout);+ defer gpa.free(run_res.stderr);+ return run_res.term == .exited and run_res.term.exited == 0;+}++pub fn call(gpa: Allocator, io: Io, name: []const u8, input: Value) !tools_mod.ToolOutput {+ if (!isLocal(name)) return .{ .text = try gpa.dupe(u8, "not a local tool"), .is_error = true };+ const inst = find(name) orelse return .{ .text = try gpa.dupe(u8, "local tool is not installed in this session"), .is_error = true };+ var aw: std.Io.Writer.Allocating = .init(gpa);+ defer aw.deinit();+ var st: std.json.Stringify = .{ .writer = &aw.writer };+ st.write(input) catch return .{ .text = try gpa.dupe(u8, "could not encode args"), .is_error = true };+ const argv = [_][]const u8{ inst.runner, inst.entry_path, aw.writer.buffered() };+ const run_res = process_runner.runCapped(gpa, io, &argv, 256 * 1024, 16 * 1024, 30_000) catch |err| {+ return .{ .text = try std.fmt.allocPrint(gpa, "local tool failed: {s}", .{@errorName(err)}), .is_error = true };+ };+ defer gpa.free(run_res.stdout);+ defer gpa.free(run_res.stderr);+ const raw_out = std.mem.trim(u8, run_res.stdout, " \t\r\n");+ if (std.json.parseFromSlice(Value, gpa, raw_out, .{})) |parsed| {+ defer parsed.deinit();+ if (parsed.value == .object) {+ const text = if (parsed.value.object.get("text")) |v| (if (v == .string) v.string else raw_out) else raw_out;+ const err = if (parsed.value.object.get("is_error")) |v| (v == .bool and v.bool) else false;+ return .{ .text = try gpa.dupe(u8, text), .is_error = err };+ }+ } else |_| {}+ const failed = run_res.term != .exited or run_res.term.exited != 0;+ return .{ .text = try gpa.dupe(u8, if (raw_out.len > 0) raw_out else run_res.stderr), .is_error = failed };+}++fn find(name: []const u8) ?Installed {+ for (g_loaded) |it| if (std.mem.eql(u8, it.spec.name, name)) return it;+ return null;+}++test "nameOk / runnerOk / entryOk / schemaOk" {+ try std.testing.expect(nameOk("digest"));+ try std.testing.expect(!nameOk("../x"));+ try std.testing.expect(!nameOk(""));+ try std.testing.expect(runnerOk("python3") and runnerOk("sh") and !runnerOk("node"));+ try std.testing.expect(entryOk("run.py") and !entryOk("../run.py") and !entryOk("a/b"));+ try std.testing.expect(schemaOk("{\"type\":\"object\",\"properties\":{}}"));+ try std.testing.expect(!schemaOk("[]"));+ try std.testing.expect(!schemaOk("{"));+}++test "install then load registers local__name" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var orig = try Io.Dir.cwd().openDir(io, ".", .{});+ defer orig.close(io);+ defer _ = std.posix.system.fchdir(orig.handle);+ try tmp.dir.setAsCwd();++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ defer {+ g_loaded = &.{};+ }+ const arena = arena_state.allocator();+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ var root: Agent = undefined;+ root.io = io;+ root.arena = arena;+ root.gpa = gpa;+ root.sub = false;+ root.client = &dummy_client;+ root.tools_anthropic = "keep";+ root.tools_openai = "keep";+ root.tools_responses = "keep";++ const input = try std.json.parseFromSliceLeaky(Value, arena,+ \\{"name":"echo","description":"echo args","schema":"{\"type\":\"object\",\"properties\":{}}","runner":"python3","entry":"run.py","source":"import sys\nraise SystemExit(0) if '--dry-run' in sys.argv else print(sys.argv[2])\n"}+ , .{});+ const call: ToolCall = .{ .id = "t1", .name = install_name, .input = input };+ const r = try handleInstall(&root, call);+ try std.testing.expect(!r.is_error);+ try std.testing.expect(std.mem.indexOf(u8, r.text, "local__echo") != null);+ try std.testing.expectEqualStrings("", root.tools_anthropic);+ try std.testing.expect(g_loaded.len == 1);+ try std.testing.expectEqualStrings("local__echo", g_loaded[0].spec.name);+ const extras = catalogExtras(arena);+ try std.testing.expectEqualStrings(install_name, extras[0].name);+ const called = try call(gpa, io, "local__echo", input);+ defer gpa.free(called.text);+ try std.testing.expect(!called.is_error);+ g_loaded = &.{};+}diff --git a/src/schedule.zig b/src/schedule.zignew file mode 100644index 00000000..081ba278--- /dev/null+++ b/src/schedule.zig@@ -0,0 +1,221 @@+//! Time-triggered tasks that wake a session (#556). Store is+//! `.graff/schedule/<id>.json`. Due-claim runs at the same step boundary as+//! job_notify. `/loop` stays the standing-goal controller; this is cron.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const schema = @import("schema.zig");+const no_local_tools = @import("no_local_tools.zig");+const goal_pacing = @import("goal_pacing.zig");+const session_wake = @import("session_wake.zig");+const agent_mod = @import("agent.zig");+const tools_mod = @import("tools.zig");+const util = @import("util.zig");++const Agent = agent_mod.Agent;+const ToolCall = tools_mod.ToolCall;+const ExecResult = tools_mod.ExecResult;+const ToolSpec = schema.ToolSpec;++pub const tool_name = "schedule_task";+pub const tool_desc = "Schedule a prompt to wake this session later. delay is 30s/5m/2h (same tokens as /loop). At the due time the prompt is injected as a user turn.";+pub const tool_schema =+ \\{"type": "object", "properties": {"delay": {"type": "string", "description": "30s, 5m, or 2h"}, "prompt": {"type": "string", "description": "what to do when it fires"}}, "required": ["delay", "prompt"]}+;++pub const store_rel = ".graff/schedule";++const tool_spec = ToolSpec{ .name = tool_name, .desc = tool_desc, .schema = tool_schema };++pub const Record = struct {+ id: []const u8,+ at_ms: i64,+ prompt: []const u8,+ claimed_ms: i64 = 0,+};++pub fn isName(name: []const u8) bool {+ return std.mem.eql(u8, name, tool_name);+}++pub fn catalogExtras(arena: Allocator) []const ToolSpec {+ _ = arena;+ if (no_local_tools.enabled or no_local_tools.lean) return &.{};+ return &.{tool_spec};+}++pub fn add(io: Io, arena: Allocator, at_ms: i64, prompt: []const u8) !Record {+ Io.Dir.cwd().makePath(io, store_rel) catch return error.StoreUnavailable;+ const id = try std.fmt.allocPrint(arena, "{d}", .{at_ms});+ const rec = Record{ .id = id, .at_ms = at_ms, .prompt = prompt };+ const text = try encode(arena, rec);+ const path = try std.fmt.allocPrint(arena, "{s}/{s}.json", .{ store_rel, id });+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text }) catch return error.StoreUnavailable;+ return rec;+}++fn encode(arena: Allocator, rec: Record) ![]const u8 {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(.{ .id = rec.id, .at_ms = rec.at_ms, .prompt = rec.prompt, .claimed_ms = rec.claimed_ms });+ return aw.writer.buffered();+}++pub fn claimDue(io: Io, arena: Allocator, now_ms: i64) []const Record {+ var dir = Io.Dir.cwd().openDir(io, store_rel, .{ .iterate = true }) catch return &.{};+ defer dir.close(io);+ var it = dir.iterate(io);+ var out: std.ArrayList(Record) = .empty;+ while (it.next(io) catch null) |ent| {+ if (ent.kind != .file) continue;+ if (!std.mem.endsWith(u8, ent.name, ".json")) continue;+ const raw = dir.readFileAlloc(io, ent.name, arena, .limited(16 * 1024)) catch continue;+ const rec = parse(arena, raw) orelse continue;+ if (rec.claimed_ms != 0 or rec.at_ms > now_ms) continue;+ var claimed = rec;+ claimed.claimed_ms = now_ms;+ const text = encode(arena, claimed) catch continue;+ dir.writeFile(io, .{ .sub_path = ent.name, .data = text }) catch continue;+ out.append(arena, claimed) catch break;+ }+ return out.items;+}++fn parse(arena: Allocator, raw: []const u8) ?Record {+ const v = std.json.parseFromSliceLeaky(Value, arena, raw, .{}) catch return null;+ if (v != .object) return null;+ const id = if (v.object.get("id")) |x| (if (x == .string) x.string else "") else "";+ const prompt = if (v.object.get("prompt")) |x| (if (x == .string) x.string else "") else "";+ const at = if (v.object.get("at_ms")) |x| switch (x) {+ .integer => |n| n,+ else => return null,+ } else return null;+ const claimed = if (v.object.get("claimed_ms")) |x| switch (x) {+ .integer => |n| n,+ else => 0,+ } else 0;+ if (id.len == 0 or prompt.len == 0) return null;+ return .{ .id = id, .at_ms = at, .prompt = prompt, .claimed_ms = claimed };+}++pub fn deliver(root: *Agent) void {+ if (root.sub) return;+ const due = claimDue(root.io, root.arena, util.unixMs(root.io));+ for (due) |rec| {+ const line = std.fmt.allocPrint(root.arena, "[schedule {s}] {s}", .{ rec.id, rec.prompt }) catch continue;+ session_wake.inject(root, line);+ }+}++pub fn handleTool(self: *Agent, call: ToolCall) !ExecResult {+ if (self.sub) return .{ .text = "schedule_task is root-only", .is_error = true };+ if (no_local_tools.enabled or no_local_tools.lean) return .{ .text = "schedule_task is disabled under --no-local-tools / --lean", .is_error = true };+ const obj = tools_mod.json_args.object(call.input) orelse return .{ .text = "schedule_task needs an object", .is_error = true };+ const delay = tools_mod.json_args.str(obj, "delay") orelse "";+ const prompt = tools_mod.json_args.str(obj, "prompt") orelse "";+ if (delay.len == 0 or prompt.len == 0) return .{ .text = "usage: delay (30s|5m|2h) and prompt", .is_error = true };+ const padded = try std.fmt.allocPrint(self.arena, "{s} {s}", .{ delay, prompt });+ const budget = goal_pacing.parseLoopBudget(padded);+ const delta = budget.deadline_ms_delta orelse return .{ .text = "delay must be 30s, 5m, or 2h", .is_error = true };+ const at = util.unixMs(self.io) + delta;+ const rec = add(self.io, self.arena, at, prompt) catch return .{ .text = "could not write .graff/schedule", .is_error = true };+ return .{ .text = try std.fmt.allocPrint(self.arena, "scheduled {s} at {d}", .{ rec.id, rec.at_ms }), .is_error = false };+}++/// `/schedule 5m check the deploy`+pub fn slashCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ const rest = std.mem.trim(u8, line["/schedule".len..], " \t");+ if (rest.len == 0) {+ try out.writeAll("usage: /schedule <30s|5m|2h> <prompt>\n");+ try out.flush();+ return true;+ }+ const budget = goal_pacing.parseLoopBudget(rest);+ const delta = budget.deadline_ms_delta orelse {+ try out.writeAll("usage: /schedule <30s|5m|2h> <prompt>\n");+ try out.flush();+ return true;+ };+ if (budget.prompt.len == 0) {+ try out.writeAll("usage: /schedule <30s|5m|2h> <prompt>\n");+ try out.flush();+ return true;+ }+ const at = util.unixMs(root.io) + delta;+ const rec = add(root.io, arena, at, budget.prompt) catch {+ try out.writeAll("could not write .graff/schedule\n");+ try out.flush();+ return true;+ };+ try out.print("scheduled {s} — fires in {s}\n", .{ rec.id, rest[0 .. rest.len - budget.prompt.len] });+ try out.flush();+ return true;+}++test "add then claimDue only yields past-due unclaimed records" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var orig = try Io.Dir.cwd().openDir(io, ".", .{});+ defer orig.close(io);+ defer _ = std.posix.system.fchdir(orig.handle);+ try tmp.dir.setAsCwd();++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const rec = try add(io, arena, 10, "check the deploy");+ try std.testing.expectEqualStrings("10", rec.id);+ try std.testing.expectEqual(@as(usize, 0), claimDue(io, arena, 9).len);+ const due = claimDue(io, arena, 11);+ try std.testing.expectEqual(@as(usize, 1), due.len);+ try std.testing.expectEqualStrings("check the deploy", due[0].prompt);+ try std.testing.expect(due[0].claimed_ms == 11);+ try std.testing.expectEqual(@as(usize, 0), claimDue(io, arena, 12).len);+}++/// Idle TUI auto-turn: claim due tasks into a buffer without an Agent.+pub fn takeWake(io: Io, buf: []u8) ?[]const u8 {+ var scratch: [32 * 1024]u8 = undefined;+ var fba = std.heap.FixedBufferAllocator.init(&scratch);+ const due = claimDue(io, fba.allocator(), util.unixMs(io));+ if (due.len == 0) return null;+ var used: usize = 0;+ for (due) |rec| {+ const piece = std.fmt.bufPrint(buf[used..], if (used == 0) "[schedule {s}] {s}" else "\n[schedule {s}] {s}", .{ rec.id, rec.prompt }) catch break;+ used += piece.len;+ }+ return if (used == 0) null else buf[0..used];+}++test "slashCommand and takeWake share the due-claim store" {+ const io = std.testing.io;+ const gpa = std.testing.allocator;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var orig = try Io.Dir.cwd().openDir(io, ".", .{});+ defer orig.close(io);+ defer _ = std.posix.system.fchdir(orig.handle);+ try tmp.dir.setAsCwd();++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var root: Agent = undefined;+ root.io = io;+ var aw: std.Io.Writer.Allocating = .init(gpa);+ defer aw.deinit();+ try std.testing.expect(try slashCommand(&root, arena, "/schedule 30s check the deploy", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "scheduled") != null);+ const rec = try add(io, arena, 1, "already due");+ try std.testing.expectEqualStrings("1", rec.id);+ var buf: [256]u8 = undefined;+ const wake = takeWake(io, &buf) orelse return error.Empty;+ try std.testing.expect(std.mem.indexOf(u8, wake, "[schedule 1]") != null);+ try std.testing.expect(std.mem.indexOf(u8, wake, "already due") != null);+ try std.testing.expect(takeWake(io, &buf) == null);+}diff --git a/src/session_run.zig b/src/session_run.zigindex 32635c38..bb7bbf17 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -64,6 +64,7 @@ const run_budget_mod = @import("run_budget.zig");const learning_privacy = @import("learning_privacy.zig");const commands_privacy = @import("commands_privacy.zig");const prompts = @import("prompts.zig");+const local_tools = @import("local_tools.zig");/// `graff repl`: interactive chat on the Grok-style TUI (same as `graff tui`)./// Piped/non-TTY stdin still drives the old scripted zigzag Model so CI@@ -309,6 +310,7 @@ pub fn buildRootAgent(const fresh_session_name = try std.fmt.allocPrint(arena, "session-{d}-{d}", .{ util.unixMs(io), proc_identity.selfPid() });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;try prompts.setRootSystemPrompts(&root, sys_normal, arena); // #381: same funnel + the live .graff/playbook.jsonl constraint block+ local_tools.load(io, arena);// Startup pays for one provider format, not all three. Other formats are// rendered on first switch with the same built-in + live MCP inputs.try root.ensureRootTools(default_provider.kind);diff --git a/src/session_wake.zig b/src/session_wake.zignew file mode 100644index 00000000..025826a8--- /dev/null+++ b/src/session_wake.zig@@ -0,0 +1,44 @@+//! One-line user-role inject used by job_notify, schedule, and channel+//! workers. Same shape as a finished-job wake: history + session_notice.++const std = @import("std");++const agent_mod = @import("agent.zig");+const engine_sink = @import("engine_sink.zig");+const Agent = agent_mod.Agent;++pub fn inject(root: *Agent, text: []const u8) void {+ if (root.sub or text.len == 0) return;+ const owned = root.arena.dupe(u8, text) catch return;+ var obj: std.json.ObjectMap = .empty;+ obj.put(root.arena, "role", .{ .string = "user" }) catch return;+ obj.put(root.arena, "content", .{ .string = owned }) catch return;+ root.messages.append(.{ .object = obj }) catch {};+ engine_sink.forAgent(root).emit(root.io, .{ .session_notice = .{ .text = owned, .tone = .dim } });+}++test "inject is a no-op on subagents" {+ var root: Agent = undefined;+ root.sub = true;+ root.messages = .empty;+ inject(&root, "hi");+ try std.testing.expectEqual(@as(usize, 0), root.messages.items.len);+}++test "inject appends a user-role line on the root" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const drop = struct {+ fn emit(_: *anyopaque, _: engine_sink.Stamped) void {}+ };+ const vt = engine_sink.VTable{ .emit = drop.emit, .durable = false };+ var root: Agent = undefined;+ root.sub = false;+ root.arena = arena_state.allocator();+ root.messages = std.json.Array.init(arena_state.allocator());+ root.sink = .{ .ctx = undefined, .vt = &vt };+ inject(&root, "wake up");+ try std.testing.expectEqual(@as(usize, 1), root.messages.items.len);+ try std.testing.expectEqualStrings("user", root.messages.items[0].object.get("role").?.string);+ try std.testing.expectEqualStrings("wake up", root.messages.items[0].object.get("content").?.string);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex a112a9e1..ccca8f2f 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -334,4 +334,9 @@ test {_ = @import("commands_experiment.zig");_ = @import("acp_engine.zig");_ = @import("libgraff.zig");+ _ = @import("acp_auth.zig");+ _ = @import("local_tools.zig");+ _ = @import("schedule.zig");+ _ = @import("channel_worker.zig");+ _ = @import("session_wake.zig");}diff --git a/src/tui_launch.zig b/src/tui_launch.zigindex 321d38e8..48a7a489 100644--- a/src/tui_launch.zig+++ b/src/tui_launch.zig@@ -19,6 +19,8 @@ const tui = @import("tui");const engine_sink = @import("engine_sink.zig");const tui_sink = @import("tui_sink.zig");const job_notify = @import("job_notify.zig");+const schedule = @import("schedule.zig");+const channel_worker = @import("channel_worker.zig");const obs = @import("obs.zig");const telemetry = @import("telemetry.zig");const vision = @import("vision.zig");@@ -139,7 +141,9 @@ fn historyCb(ctx: ?*anyopaque, op: tui.HistoryOp) void {fn idleWakeCb(ctx: ?*anyopaque, buf: []u8) ?[]const u8 {const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- return job_notify.takeWake(c.io, buf);+ if (job_notify.takeWake(c.io, buf)) |t| return t;+ if (schedule.takeWake(c.io, buf)) |t| return t;+ return channel_worker.takeWake(c.io, buf);}/// Overlay the TUI preview buffer as a repl.StreamBuf so replTurnCb's