Skip to content

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

Python

feat: remote control over the account relay (#722)

Rach Pradhanefc15c5fbc0d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1b17a1ef..5cfa3644 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,15 +12,28 @@ current is part of cutting a release.
## Unreleased
-
- Live 12-PR board on grok-4.6 SuperGrok (n=3, no SPEC.md): graff / Pi /
OpenCode 12/12, grok 11/12 (`#727`), exo 9/12 (gemini + two turbos —
no-token check-greens do not count). Honest list$ $21.48 / $18.47 /
$25.71 / $33.69 / $16.01. Receipt and site-palette card in
`artifacts/graff-evals-live/`.
+- `#722`: remote control. `graff remote-control` is `graff serve` with no
+ listener: it dials out to your Codegraff account and takes commands from
+ the account's relay, so nothing on the machine is ever bound. From anywhere
+ the same `graff login` is valid, `graff remote` lists the machines and
+ their sessions; `graff remote new` / `send` / `answer` / `tail` / `cancel`
+ / `close` drive them, with the same NDJSON events a serve client gets. The
+ machine keeps the complete tape; the relay keeps a recent window and a
+ viewer that falls behind gets a replay from the machine. Gated on the
+ `sessions` key scope, so a plain `api` key can never reach a machine.
+ `docs/remote-control.md`.
## v0.0.295
+- `#812`: a mid-turn native image follow-up no longer sends empty `text` with
+ the image, which some Chat Completions providers reject (Z.AI 1210). The
+ caption is `Attached image.`
+- Muse Spark models accept image inputs on the Meta/Muse vision path.
- Bare `codedb context <task>` defaults to on-device retrieval. Remote
reranking remains an explicit opt-in and is refused under local-only
policy (ADR 0084, ADR 0092).
diff --git a/docs/remote-control.md b/docs/remote-control.md
new file mode 100644
index 00000000..ce5f6494
--- /dev/null
+++ b/docs/remote-control.md
@@ -0,0 +1,97 @@
+# Remote control
+
+Drive the graff sessions on one machine from anywhere your Codegraff login
+is valid: a laptop at home from the office, a build box from your phone, a
+cloud sandbox from the CLI. The machine never opens a port. It dials out.
+
+```
+# on the machine that runs the agent
+graff login # once
+graff remote-control # stays in the foreground; Ctrl-C disconnects
+
+# anywhere else, same login
+graff remote # sessions on every machine running remote-control
+graff remote new nightly # a durable session on that machine
+graff remote send nightly "run the tests and fix what fails"
+graff remote tail nightly # watch it work
+graff remote close nightly # end the process; its history stays on the machine
+```
+
+## How it works
+
+`graff remote-control` is [`graff serve`](embedding.md) with no listener. It
+runs the same pool of `graff --json` children, keeps the same durable named
+sessions (`--resume <id>`, autosaved after every turn) and the same
+seq-stamped event tape under `.graff/serve/`. Instead of accepting
+connections it:
+
+1. registers with the gateway using the `graff login` key, as a device with
+ a stable id (`~/.graff/remote-device.json`), a name (`--name`, default
+ hostname) and its working directory;
+2. long-polls the account's relay for commands, sending its live sessions
+ (id, idle/busy, last seq) with every poll;
+3. runs each command exactly as serve would (create a session, one protocol
+ request, close) and streams the resulting event lines back as they land
+ on the local tape.
+
+The relay keeps one object per account: the registered machines, their
+sessions, queued commands and a bounded recent window of each session's
+events. The machine keeps the complete tape. A viewer whose cursor falls
+behind the window sends `reattach` and gets a replay from the machine.
+
+Nothing is ever pushed *to* the machine. It only executes what arrives on
+the connection it opened, and revoking the key ends the pipe.
+
+## Commands
+
+| command | what it does |
+|---|---|
+| `graff remote-control [--name n]` | run the supervisor on this machine; `--model`, `--yolo`, `--system-prompt` and the other serve flags set the defaults for its sessions |
+| `graff remote` / `graff remote sessions` | sessions on every machine, with state and machine name |
+| `graff remote agents` | the machines themselves, online or not |
+| `graff remote new [session] [agent]` | create (or resume) a session; with one machine online the agent is implied; `--model` / `--yolo` apply |
+| `graff remote send <session> <text>` | one turn; events stream back until it ends |
+| `graff remote answer <session> <text>` | answer the session's `ask_user` prompt |
+| `graff remote tail <session> [from]` | watch a session's events from a cursor (default: the recent window) |
+| `graff remote cancel <session>` | cancel the in-flight turn |
+| `graff remote close <session>` | end the session process; `graff remote new <session>` resumes it later |
+
+## Auth
+
+- Machine → gateway: the `graff login` device key. Remote control requires
+ the `sessions` scope (device keys have it; dashboard keys opt in), so a
+ plain `api` key embedded in a product can never drive anyone's machine.
+- Viewer → gateway: the same account login.
+- Gateway → machine: nothing inbound.
+
+`CODEGRAFF_API_KEY` overrides the login file on either side.
+`GRAFF_REMOTE_BASE` points both at a different gateway (a local one while
+developing the relay).
+
+## Wire
+
+The viewer API is the gateway's `/v1/remote/*`, bearer-authenticated:
+
+```
+GET /v1/remote/agents machines + their sessions
+GET /v1/remote/sessions sessions across machines
+POST /v1/remote/agents/:agent/sessions create; body = serve's create options
+POST /v1/remote/sessions/:id one protocol request; 202 {command_id, from}
+GET /v1/remote/sessions/:id/events?from=N&wait=MS long-poll: {events, next_from, in_flight, gap}
+DELETE /v1/remote/sessions/:id close
+```
+
+Events are the NDJSON lines serve streams (`text`, `reasoning`, `tool_call`,
+`ask_user`, `turn`, `error`, …), each with its `seq`, so a client written
+against `graff serve` needs only a base URL change plus the cursor loop.
+`gap: true` means the window no longer starts at your cursor: send
+`{"type":"reattach","resume_from":N}` and tail again. Event lines above
+256 KiB reach the relay as an envelope-only stub (`truncated: true`); the
+full line is on the machine's tape and a `reattach` replays it.
+
+## Not yet
+
+- Sessions this supervisor did not start (a TUI you left open) are not
+ listed; only its own children are. See #469 for the device-local bridge.
+- Per-session short-lived viewer tokens (shareable links).
+- ACP `session/list` / `session/load` over relayed sessions.
diff --git a/src/args.zig b/src/args.zig
index 3f28ca1d..aee342a6 100644
--- a/src/args.zig
+++ b/src/args.zig
@@ -60,6 +60,7 @@ pub const Flags = struct {
host_flag: []const u8 = "127.0.0.1", // harness serve
port_flag: u16 = 8787, // harness serve
token_flag: ?[]const u8 = null, // harness serve
+ name_flag: ?[]const u8 = null, // graff remote-control --name: how this machine is listed
resume_flag: ?[]const u8 = null, // restore this named session
branch_flag: ?[]const u8 = null, // clone --resume into this independent autosave target
goal_flag: ?[]const u8 = null, // --goal: standing objective (todos) every turn gets, incl. --json/-p
@@ -242,6 +243,9 @@ pub fn parse(init: std.process.Init) !Flags {
} else if (std.mem.eql(u8, arg, "--token")) {
const tv = it.next() orelse std.process.fatal("--token needs a value — harness --help", .{});
flags.token_flag = try arena.dupe(u8, tv);
+ } else if (std.mem.eql(u8, arg, "--name")) {
+ const nv = it.next() orelse std.process.fatal("--name needs a value — harness --help", .{});
+ flags.name_flag = try arena.dupe(u8, nv);
} else {
std.process.fatal("unknown flag '{s}' — harness --help lists them", .{arg});
}
@@ -260,7 +264,8 @@ pub fn parse(init: std.process.Init) !Flags {
flags.is_subcommand = flags.positionals.items.len > 0 and
(std.mem.eql(u8, flags.positionals.items[0], "login") or std.mem.eql(u8, flags.positionals.items[0], "key") or std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn") or
std.mem.eql(u8, flags.positionals.items[0], "serve") or std.mem.eql(u8, flags.positionals.items[0], "update") or std.mem.eql(u8, flags.positionals.items[0], "title") or std.mem.eql(u8, flags.positionals.items[0], "repl") or std.mem.eql(u8, flags.positionals.items[0], "tui") or
- std.mem.eql(u8, flags.positionals.items[0], "worktree") or std.mem.eql(u8, flags.positionals.items[0], "sandboxes") or std.mem.eql(u8, flags.positionals.items[0], "cube") or std.mem.eql(u8, flags.positionals.items[0], "models") or @import("acp.zig").isAcpSubcommand(flags.positionals.items[0])); // `acp` also arms ACP's stdout discipline (json_mode) — see acp.isAcpSubcommand
+ std.mem.eql(u8, flags.positionals.items[0], "worktree") or std.mem.eql(u8, flags.positionals.items[0], "sandboxes") or std.mem.eql(u8, flags.positionals.items[0], "cube") or std.mem.eql(u8, flags.positionals.items[0], "models") or
+ std.mem.eql(u8, flags.positionals.items[0], "remote-control") or std.mem.eql(u8, flags.positionals.items[0], "remote") or @import("acp.zig").isAcpSubcommand(flags.positionals.items[0])); // `acp` also arms ACP's stdout discipline (json_mode) — see acp.isAcpSubcommand
if (!flags.is_subcommand and flags.positionals.items.len > 0) {
flags.oneshot_prompt = try std.mem.join(arena, " ", flags.positionals.items);
}
diff --git a/src/cli.zig b/src/cli.zig
index 1b52473b..ae90ffd1 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -336,6 +336,9 @@ pub const usage_text =
\\ graff --schema print the machine-readable interface (SDK codegen)
\\ graff serve HTTP/NDJSON bridge over the --json protocol
\\ (--host/--port/--token; sessions are --json children)
+ \\ graff remote-control [--name n] serve with no listener: dial out to your Codegraff account so
+ \\ `graff remote` anywhere can drive sessions on this machine
+ \\ graff remote [new|send|tail|…] list and drive the sessions of machines running remote-control
\\ graff acp Agent Client Protocol agent on stdio (Zed and other ACP editors)
\\ graff update [--force|--check] update graff to the latest GitHub release
\\ graff title <prompt> print the AI tab-title for a prompt (test title styles)
diff --git a/src/remote_client.zig b/src/remote_client.zig
new file mode 100644
index 00000000..39984628
--- /dev/null
+++ b/src/remote_client.zig
@@ -0,0 +1,344 @@
+//! `graff remote`: the viewer half of remote control (#722). From any machine
+//! where the same `graff login` is valid: list the machines running
+//! `graff remote-control` and their sessions, create one, send it a turn and
+//! watch the events stream back, tail a live one, answer a prompt, cancel,
+//! close. The wire is the gateway's `/v1/remote/*` API; events are the same
+//! NDJSON lines serve streams, fetched from a cursor in long-poll batches.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const ansi = @import("ansi.zig");
+const style = &ansi.style;
+const root = @import("main.zig");
+const util = @import("util.zig");
+const events = @import("serve_events.zig");
+const strFieldObj = util.strFieldObj;
+const intFieldObj = util.intFieldObj;
+const harness_version = root.harness_version;
+
+pub const Options = struct { model: ?[]const u8 = null, yolo: bool = false };
+
+/// How long one events long-poll is held before an empty answer.
+const tail_wait_ms: u64 = 25_000;
+
+const Client = struct {
+ io: Io,
+ gpa: Allocator,
+ base: []const u8,
+ key: []const u8,
+ http: std.http.Client,
+
+ const Reply = struct { code: u16, body: []const u8 };
+
+ fn fetch(c: *Client, arena: Allocator, method: std.http.Method, path: []const u8, payload: ?[]const u8) !Reply {
+ const url = try std.fmt.allocPrint(arena, "{s}{s}", .{ c.base, path });
+ var aw: Io.Writer.Allocating = .init(arena);
+ const default_payload: ?[]const u8 = if (method == .POST) "{}" else null;
+ const res = try c.http.fetch(.{
+ .location = .{ .url = url },
+ .method = method,
+ .payload = payload orelse default_payload,
+ .response_writer = &aw.writer,
+ .headers = .{
+ .content_type = .{ .override = "application/json" },
+ .authorization = .{ .override = try std.fmt.allocPrint(arena, "Bearer {s}", .{c.key}) },
+ .user_agent = .{ .override = "simple-harness/" ++ harness_version },
+ },
+ });
+ return .{ .code = @intFromEnum(res.status), .body = aw.writer.buffered() };
+ }
+
+ /// Non-2xx is fatal with the gateway's message: every subcommand here is
+ /// one user action, and a half-answer is worse than none.
+ fn json(c: *Client, arena: Allocator, method: std.http.Method, path: []const u8, payload: ?[]const u8) !Value {
+ const r = try c.fetch(arena, method, path, payload);
+ if (r.code < 200 or r.code >= 300) std.process.fatal("remote: HTTP {d}: {s}", .{ r.code, errorMessage(arena, r.body) });
+ return std.json.parseFromSliceLeaky(Value, arena, r.body, .{ .allocate = .alloc_always }) catch
+ std.process.fatal("remote: gateway sent something that is not JSON", .{});
+ }
+};
+
+pub fn errorMessage(arena: Allocator, body: []const u8) []const u8 {
+ if (std.json.parseFromSliceLeaky(Value, arena, body, .{ .allocate = .alloc_always })) |v| {
+ if (v == .object) {
+ if (v.object.get("error")) |e| {
+ if (e == .object) if (strFieldObj(e.object, "message")) |m| return m;
+ if (e == .string) return e.string;
+ }
+ }
+ } else |_| {}
+ return body[0..@min(body.len, 200)];
+}
+
+const usage =
+ \\usage: graff remote sessions on every machine running `graff remote-control`
+ \\ graff remote agents the machines themselves
+ \\ graff remote new [session] [agent] create (or resume) a session on a machine; --model/--yolo apply
+ \\ graff remote send <session> <text…> one turn, events streamed back until it ends
+ \\ graff remote answer <session> <text…> answer the session's ask_user prompt
+ \\ graff remote tail <session> [from] watch a session's events from a cursor (default: the recent window)
+ \\ graff remote cancel <session> cancel the in-flight turn
+ \\ graff remote close <session> end the session process (its history stays on that machine)
+;
+
+pub fn command(io: Io, gpa: Allocator, arena: Allocator, base: []const u8, key: []const u8, args: []const []const u8, opts: Options) !void {
+ var obuf: [4096]u8 = undefined;
+ var ow = Io.File.stdout().writer(io, &obuf);
+ const out = &ow.interface;
+ var c: Client = .{ .io = io, .gpa = gpa, .base = base, .key = key, .http = .{ .allocator = gpa, .io = io } };
+ defer c.http.deinit();
+
+ const sub = if (args.len == 0) "sessions" else args[0];
+ const rest = if (args.len == 0) args else args[1..];
+ if (std.mem.eql(u8, sub, "sessions")) {
+ try listSessions(&c, arena, out);
+ } else if (std.mem.eql(u8, sub, "agents")) {
+ try listAgents(&c, arena, out);
+ } else if (std.mem.eql(u8, sub, "new")) {
+ try createSession(&c, arena, out, rest, opts);
+ } else if (std.mem.eql(u8, sub, "send") or std.mem.eql(u8, sub, "answer")) {
+ if (rest.len < 2) std.process.fatal("{s}", .{usage});
+ const sid = sessionArg(rest[0]);
+ const text = try std.mem.join(arena, " ", rest[1..]);
+ const from = try request(&c, arena, sid, if (std.mem.eql(u8, sub, "send")) "user" else "answer", text);
+ try tail(&c, arena, out, sid, from, true);
+ } else if (std.mem.eql(u8, sub, "tail")) {
+ if (rest.len < 1) std.process.fatal("{s}", .{usage});
+ const sid = sessionArg(rest[0]);
+ const from: u64 = if (rest.len > 1) std.fmt.parseInt(u64, rest[1], 10) catch std.process.fatal("remote tail: from must be a number", .{}) else 1;
+ try tail(&c, arena, out, sid, from, false);
+ } else if (std.mem.eql(u8, sub, "cancel")) {
+ if (rest.len < 1) std.process.fatal("{s}", .{usage});
+ _ = try request(&c, arena, sessionArg(rest[0]), "cancel", null);
+ try out.print("{s}✓{s} cancel queued\n", .{ style.green, style.reset });
+ } else if (std.mem.eql(u8, sub, "close")) {
+ if (rest.len < 1) std.process.fatal("{s}", .{usage});
+ const sid = sessionArg(rest[0]);
+ const path = try std.fmt.allocPrint(arena, "/v1/remote/sessions/{s}", .{sid});
+ _ = try c.json(arena, .DELETE, path, null);
+ try out.print("{s}✓{s} {s} closed (history stays on its machine; `graff remote new {s}` resumes it)\n", .{ style.green, style.reset, sid, sid });
+ } else {
+ std.process.fatal("{s}", .{usage});
+ }
+ try out.flush();
+}
+
+/// `reply[key]` as a slice of values; missing or not an array reads empty.
+fn items(v: Value, key: []const u8) []const Value {
+ if (v != .object) return &.{};
+ const l = v.object.get(key) orelse return &.{};
+ return if (l == .array) l.array.items else &.{};
+}
+
+fn sessionArg(s: []const u8) []const u8 {
+ if (!events.validName(s)) std.process.fatal("remote: '{s}' is not a session id", .{s});
+ return s;
+}
+
+fn listAgents(c: *Client, arena: Allocator, out: *Io.Writer) !void {
+ const list = items(try c.json(arena, .GET, "/v1/remote/agents", null), "agents");
+ if (list.len == 0) {
+ try out.writeAll("no machines — run `graff remote-control` on one (same `graff login`)\n");
+ return;
+ }
+ try out.print("{s}{s:<18} {s:<8} {s:<20} {s:<8} {s}{s}\n", .{ style.dim, "agent", "online", "name", "sessions", "cwd", style.reset });
+ for (list) |item| {
+ if (item != .object) continue;
+ const o = item.object;
+ const online = if (o.get("online")) |b| (b == .bool and b.bool) else false;
+ const n = if (o.get("sessions")) |s| (if (s == .array) s.array.items.len else 0) else 0;
+ try out.print("{s:<18} {s}{s:<8}{s} {s:<20} {d:<8} {s}\n", .{
+ strFieldObj(o, "agent_id") orelse "?",
+ if (online) style.green else style.dim,
+ if (online) "yes" else "no",
+ style.reset,
+ strFieldObj(o, "name") orelse strFieldObj(o, "hostname") orelse "?",
+ n,
+ strFieldObj(o, "cwd") orelse "",
+ });
+ }
+}
+
+fn listSessions(c: *Client, arena: Allocator, out: *Io.Writer) !void {
+ const list = items(try c.json(arena, .GET, "/v1/remote/sessions", null), "sessions");
+ if (list.len == 0) {
+ try out.writeAll("no remote sessions — `graff remote new` starts one on a machine running `graff remote-control`\n");
+ return;
+ }
+ try out.print("{s}{s:<18} {s:<6} {s:<18} {s:<8} {s}{s}\n", .{ style.dim, "session", "state", "machine", "last_seq", "cwd", style.reset });
+ for (list) |item| {
+ if (item != .object) continue;
+ const o = item.object;
+ const online = if (o.get("online")) |b| (b == .bool and b.bool) else false;
+ const state = if (!online) "offline" else strFieldObj(o, "state") orelse "?";
+ try out.print("{s:<18} {s}{s:<6}{s} {s:<18} {d:<8} {s}\n", .{
+ strFieldObj(o, "session_id") orelse "?",
+ if (std.mem.eql(u8, state, "busy")) style.green else style.dim,
+ state,
+ style.reset,
+ strFieldObj(o, "name") orelse strFieldObj(o, "hostname") orelse "?",
+ @as(u64, @intCast(@max(intFieldObj(o, "last_seq", 0), 0))),
+ strFieldObj(o, "cwd") orelse "",
+ });
+ }
+}
+
+/// `new [session] [agent]`: with one machine online the agent is implied.
+fn createSession(c: *Client, arena: Allocator, out: *Io.Writer, rest: []const []const u8, opts: Options) !void {
+ const agent = if (rest.len > 1) rest[1] else try onlyOnlineAgent(c, arena);
+ var obj: std.json.ObjectMap = .empty;
+ if (rest.len > 0) try obj.put(arena, "session", .{ .string = sessionArg(rest[0]) });
+ if (opts.model) |m| try obj.put(arena, "model", .{ .string = m });
+ if (opts.yolo) try obj.put(arena, "yolo", .{ .bool = true });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(Value{ .object = obj });
+ const path = try std.fmt.allocPrint(arena, "/v1/remote/agents/{s}/sessions", .{agent});
+ const v = try c.json(arena, .POST, path, aw.writer.buffered());
+ if (v != .object) std.process.fatal("remote new: unexpected reply", .{});
+ const sid = strFieldObj(v.object, "session_id") orelse "?";
+ const resumed = if (v.object.get("resumed")) |b| (b == .bool and b.bool) else false;
+ try out.print("{s}✓{s} session {s} {s} on {s} (last_seq {d})\n graff remote send {s} <text>\n", .{
+ style.green, style.reset, sid, if (resumed) "resumed" else "created", agent, @as(u64, @intCast(@max(intFieldObj(v.object, "last_seq", 0), 0))), sid,
+ });
+}
+
+fn onlyOnlineAgent(c: *Client, arena: Allocator) ![]const u8 {
+ var found: ?[]const u8 = null;
+ var n: usize = 0;
+ for (items(try c.json(arena, .GET, "/v1/remote/agents", null), "agents")) |item| {
+ if (item != .object) continue;
+ const online = if (item.object.get("online")) |b| (b == .bool and b.bool) else false;
+ if (!online) continue;
+ n += 1;
+ found = strFieldObj(item.object, "agent_id");
+ }
+ if (n == 0) std.process.fatal("remote new: no machine is online — run `graff remote-control` there first (`graff remote agents` lists them)", .{});
+ if (n > 1) std.process.fatal("remote new: {d} machines are online — name one: graff remote new [session] <agent> (see `graff remote agents`)", .{n});
+ return found.?;
+}
+
+/// Queue one protocol request; returns the cursor its events start at.
+fn request(c: *Client, arena: Allocator, sid: []const u8, rtype: []const u8, text: ?[]const u8) !u64 {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "type", .{ .string = rtype });
+ if (text) |t| try obj.put(arena, "text", .{ .string = t });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(Value{ .object = obj });
+ const path = try std.fmt.allocPrint(arena, "/v1/remote/sessions/{s}", .{sid});
+ const v = try c.json(arena, .POST, path, aw.writer.buffered());
+ return if (v == .object) @intCast(@max(intFieldObj(v.object, "from", 1), 1)) else 1;
+}
+
+/// Long-poll the session's events from `from`, painting each as it lands.
+/// `until_terminal`: stop at the request's terminal event (send/answer);
+/// otherwise stop once the tape is drained and nothing is in flight.
+fn tail(c: *Client, arena: Allocator, out: *Io.Writer, sid: []const u8, from: u64, until_terminal: bool) !void {
+ var cursor = from;
+ var reattached = false;
+ var idle_rounds: usize = 0;
+ while (true) {
+ const path = try std.fmt.allocPrint(arena, "/v1/remote/sessions/{s}/events?from={d}&wait={d}", .{ sid, cursor, tail_wait_ms });
+ const v = try c.json(arena, .GET, path, null);
+ if (v != .object) std.process.fatal("remote tail: unexpected reply", .{});
+ const o = v.object;
+ const list = items(v, "events");
+ var terminal = false;
+ for (list) |ev| {
+ if (ev != .string) continue;
+ try paint(arena, out, ev.string);
+ if (events.terminalEvent(ev.string)) terminal = true;
+ }
+ try out.flush();
+ cursor = @intCast(@max(intFieldObj(o, "next_from", @intCast(cursor)), @as(i64, @intCast(cursor))));
+ const in_flight = if (o.get("in_flight")) |b| (b == .bool and b.bool) else false;
+ const gap = if (o.get("gap")) |b| (b == .bool and b.bool) else false;
+ // The relay's window no longer starts at our cursor: ask the machine
+ // to replay its tape from there, once.
+ if (gap and !reattached) {
+ reattached = true;
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "type", .{ .string = "reattach" });
+ try obj.put(arena, "resume_from", .{ .integer = @intCast(cursor) });
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(Value{ .object = obj });
+ const rpath = try std.fmt.allocPrint(arena, "/v1/remote/sessions/{s}", .{sid});
+ _ = try c.json(arena, .POST, rpath, aw.writer.buffered());
+ continue;
+ }
+ if (until_terminal and terminal) return;
+ const got = list.len > 0;
+ // A plain tail stops as soon as the tape is quiet: a batch that ended a
+ // request with nothing else running, or an empty poll on an idle session.
+ if (!until_terminal and got and terminal and !in_flight) return;
+ if (!until_terminal and !got and !in_flight) {
+ idle_rounds += 1;
+ if (idle_rounds >= 1) return; // drained and quiet: the tape is complete for now
+ } else idle_rounds = 0;
+ }
+}
+
+/// One event line to the terminal: text streams inline, the rest one-liners.
+pub fn paint(arena: Allocator, out: *Io.Writer, line: []const u8) !void {
+ const v = std.json.parseFromSliceLeaky(Value, arena, line, .{ .allocate = .alloc_always }) catch return;
+ if (v != .object) return;
+ const o = v.object;
+ const t = strFieldObj(o, "type") orelse return;
+ if (std.mem.eql(u8, t, "text")) {
+ try out.writeAll(strFieldObj(o, "text") orelse "");
+ } else if (std.mem.eql(u8, t, "reasoning")) {
+ try out.print("{s}{s}{s}", .{ style.dim, strFieldObj(o, "text") orelse "", style.reset });
+ } else if (std.mem.eql(u8, t, "tool_call")) {
+ try out.print("\n{s}[tool_call {s}]{s}\n", .{ style.dim, strFieldObj(o, "name") orelse "tool", style.reset });
+ } else if (std.mem.eql(u8, t, "ask_user")) {
+ try out.print("\n{s}[ask_user]{s} {s}\n answer with: graff remote answer <session> <text>\n", .{ style.yellow, style.reset, strFieldObj(o, "question") orelse strFieldObj(o, "text") orelse "" });
+ } else if (std.mem.eql(u8, t, "turn")) {
+ try out.print("\n{s}— turn done · context {d} tokens · ${d:.4}{s}\n", .{ style.dim, intFieldObj(o, "context_tokens", 0), floatField(o, "cost_usd"), style.reset });
+ } else if (std.mem.eql(u8, t, "error")) {
+ try out.print("\n{s}error:{s} {s}\n", .{ style.red, style.reset, strFieldObj(o, "message") orelse "" });
+ } else if (o.get("truncated") != null) {
+ try out.print("\n{s}[{s} · {d} bytes, kept on the machine]{s}\n", .{ style.dim, t, intFieldObj(o, "bytes", 0), style.reset });
+ }
+}
+
+fn floatField(o: std.json.ObjectMap, name: []const u8) f64 {
+ const v = o.get(name) orelse return 0;
+ return switch (v) {
+ .float => |f| f,
+ .integer => |i| @floatFromInt(i),
+ else => 0,
+ };
+}
+
+test "paint: text streams inline, control events become one-liners, noise is silent" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var aw: Io.Writer.Allocating = .init(arena);
+ try paint(arena, &aw.writer, "{\"seq\":1,\"type\":\"text\",\"text\":\"hel\"}");
+ try paint(arena, &aw.writer, "{\"seq\":2,\"type\":\"text\",\"text\":\"lo\"}");
+ try paint(arena, &aw.writer, "{\"seq\":3,\"type\":\"tool_result\",\"output\":\"ignored\"}");
+ try paint(arena, &aw.writer, "{\"seq\":4,\"type\":\"tool_call\",\"name\":\"bash\"}");
+ try paint(arena, &aw.writer, "{\"seq\":5,\"type\":\"turn\",\"context_tokens\":1200,\"cost_usd\":0.0021}");
+ try paint(arena, &aw.writer, "not json");
+ const got = aw.writer.buffered();
+ try std.testing.expect(std.mem.startsWith(u8, got, "hello"));
+ try std.testing.expect(std.mem.indexOf(u8, got, "[tool_call bash]") != null);
+ try std.testing.expect(std.mem.indexOf(u8, got, "ignored") == null);
+ try std.testing.expect(std.mem.indexOf(u8, got, "context 1200 tokens") != null);
+ try std.testing.expect(std.mem.indexOf(u8, got, "$0.0021") != null);
+}
+
+test "errorMessage prefers the gateway's structured message" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ try std.testing.expectEqualStrings("device is offline", errorMessage(arena, "{\"error\":{\"message\":\"device is offline\",\"type\":\"device_offline\"}}"));
+ try std.testing.expectEqualStrings("unauthorized", errorMessage(arena, "{\"error\":\"unauthorized\"}"));
+ try std.testing.expectEqualStrings("<html>", errorMessage(arena, "<html>"));
+}
diff --git a/src/remote_control.zig b/src/remote_control.zig
new file mode 100644
index 00000000..916344e4
--- /dev/null
+++ b/src/remote_control.zig
@@ -0,0 +1,522 @@
+//! `graff remote-control`: the serve supervisor with no listener (#722).
+//!
+//! The machine that runs the agent only ever dials OUT. It registers with the
+//! gateway using the `graff login` key, long-polls the account's relay for
+//! commands, and streams each session's event tape back as it lands. The
+//! commands are exactly serve's request set — create a durable session, one
+//! protocol request (user / answer / cancel / reattach), close — so a viewer
+//! anywhere sees the same NDJSON a serve client would. Nothing is bound: the
+//! only channel is the one this process opened, and revoking the key ends it.
+//!
+//! Sessions are serve's ServeSession (durable `--resume <id>` children with
+//! the seq-stamped tape under .graff/serve/); serve_create spawns them and the
+//! drain here mirrors serveMessage with the socket replaced by coalesced
+//! uploads. The relay keeps a bounded recent window; the tape here is complete,
+//! so a viewer whose cursor fell behind asks for `reattach` and gets a replay.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const root = @import("main.zig");
+const serve = @import("serve.zig");
+const serve_create = @import("serve_create.zig");
+const events = @import("serve_events.zig");
+const util = @import("util.zig");
+
+const ServeState = serve.ServeState;
+const ServeSession = serve.ServeSession;
+const harness_version = root.harness_version;
+
+pub const Config = struct {
+ base: []const u8, // gateway base URL (GRAFF_REMOTE_BASE overrides for a local relay)
+ key: []const u8, // the account's cg_sk_ key
+ home: []const u8,
+ name: ?[]const u8, // display name for this machine; default hostname
+ serve: serve.ServeConfig,
+};
+
+/// Where this machine's stable relay identity lives (16 hex chars).
+pub const device_file = ".graff/remote-device.json";
+/// Longest one poll is held server-side before an empty answer.
+const poll_wait_ms: u64 = 25_000;
+/// Event lines above this go upstream as a stub; the local tape stays complete.
+pub const upload_line_cap: usize = 256 * 1024;
+/// Coalesce uploads: a burst of text deltas becomes one POST per window.
+const flush_window_ms: i64 = 60;
+const flush_bytes: usize = 32 * 1024;
+const backoff_min_ms: i64 = 1_000;
+const backoff_max_ms: i64 = 30_000;
+
+const State = struct {
+ st: ServeState,
+ cfg: Config,
+ client: std.http.Client,
+ agent_id: [16]u8 = undefined,
+ hostname_buf: [std.posix.HOST_NAME_MAX]u8 = undefined,
+ hostname: []const u8 = "",
+};
+
+const Reply = struct { code: u16, body: []const u8 };
+
+fn post(self: *State, arena: Allocator, path: []const u8, payload: []const u8) !Reply {
+ const url = try std.fmt.allocPrint(arena, "{s}{s}", .{ self.cfg.base, path });
+ var aw: Io.Writer.Allocating = .init(arena);
+ const res = try self.client.fetch(.{
+ .location = .{ .url = url },
+ .method = .POST,
+ .payload = payload,
+ .response_writer = &aw.writer,
+ .headers = .{
+ .content_type = .{ .override = "application/json" },
+ .authorization = .{ .override = try std.fmt.allocPrint(arena, "Bearer {s}", .{self.cfg.key}) },
+ .user_agent = .{ .override = "simple-harness/" ++ harness_version },
+ },
+ });
+ return .{ .code = @intFromEnum(res.status), .body = aw.writer.buffered() };
+}
+
+/// The gateway's error message out of a non-2xx body, or the raw body.
+fn errorMessage(arena: Allocator, body: []const u8) []const u8 {
+ if (std.json.parseFromSliceLeaky(Value, arena, body, .{ .allocate = .alloc_always })) |v| {
+ if (v == .object) if (v.object.get("error")) |e| if (e == .object)
+ if (util.strFieldObj(e.object, "message")) |m| return m;
+ } else |_| {}
+ return body[0..@min(body.len, 200)];
+}
+
+pub fn remoteControlMain(gpa: Allocator, io: Io, cfg: Config, exe: []const u8) !void {
+ var group: Io.Group = .init;
+ defer group.cancel(io);
+ var self: State = .{
+ .st = .{ .gpa = gpa, .io = io, .exe = exe, .cfg = cfg.serve, .group = &group },
+ .cfg = cfg,
+ .client = .{ .allocator = gpa, .io = io },
+ };
+ defer self.client.deinit();
+ self.hostname = std.posix.gethostname(&self.hostname_buf) catch "unknown";
+ self.agent_id = try deviceId(io, gpa, cfg.home);
+ const label = cfg.name orelse self.hostname;
+
+ var backoff: i64 = backoff_min_ms;
+ var registered = false;
+ while (true) {
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ if (!registered) {
+ register(&self, arena, label) catch |err| {
+ serve.serveLog(io, "remote-control: register failed ({t}) — retrying in {d}s", .{ err, @divTrunc(backoff, 1000) });
+ io.sleep(.fromMilliseconds(backoff), .awake) catch return;
+ backoff = @min(backoff * 2, backoff_max_ms);
+ continue;
+ };
+ registered = true;
+ serve.serveLog(io, "graff remote-control · {s} ({s}) · device {s} · relay {s} · sessions are `{s} --json` children · Ctrl-C disconnects", .{
+ label, self.hostname, &self.agent_id, cfg.base, exe,
+ });
+ }
+ const cmds = poll(&self, arena) catch |err| {
+ if (err == error.UnknownDevice) registered = false;
+ serve.serveLog(io, "remote-control: poll failed ({t}) — retrying in {d}s", .{ err, @divTrunc(backoff, 1000) });
+ io.sleep(.fromMilliseconds(backoff), .awake) catch return;
+ backoff = @min(backoff * 2, backoff_max_ms);
+ continue;
+ };
+ backoff = backoff_min_ms;
+ for (cmds) |cmd| runCommand(&self, arena, cmd);
+ }
+}
+
+/// Read (or mint and persist) the 16-hex device id under $HOME.
+fn deviceId(io: Io, gpa: Allocator, home: []const u8) ![16]u8 {
+ var out: [16]u8 = undefined;
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}", .{ home, device_file });
+ defer gpa.free(path);
+ if (Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(4096))) |data| {
+ defer gpa.free(data);
+ if (parseDeviceId(data)) |id| return id;
+ } else |_| {}
+ var raw: [8]u8 = undefined;
+ io.random(&raw);
+ _ = std.fmt.bufPrint(&out, "{x:0>16}", .{std.mem.readInt(u64, &raw, .big)}) catch unreachable;
+ if (std.fs.path.dirname(path)) |parent| Io.Dir.cwd().createDirPath(io, parent) catch {};
+ var text_buf: [64]u8 = undefined;
+ const text = std.fmt.bufPrint(&text_buf, "{{\"device_id\":\"{s}\"}}\n", .{&out}) catch unreachable;
+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text }) catch |err|
+ serve.serveLog(io, "remote-control: cannot persist device id at {s} ({t}) — this run gets a fresh one", .{ path, err });
+ return out;
+}
+
+/// The stored id, only if it is exactly 16 lowercase hex characters.
+pub fn parseDeviceId(data: []const u8) ?[16]u8 {
+ const id = events.stringField(data, "device_id") orelse return null;
+ if (id.len != 16) return null;
+ for (id) |c| if (!std.ascii.isHex(c) or std.ascii.isUpper(c)) return null;
+ var out: [16]u8 = undefined;
+ @memcpy(&out, id);
+ return out;
+}
+
+fn register(self: *State, arena: Allocator, label: []const u8) !void {
+ // AT_FDCWD has no path of its own; resolve "." through it instead.
+ const cwd: []const u8 = Io.Dir.cwd().realPathFileAlloc(self.st.io, ".", arena) catch "";
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(.{ .hostname = self.hostname, .name = label, .cwd = cwd, .version = harness_version });
+ const path = try std.fmt.allocPrint(arena, "/v1/remote/agents/{s}/register", .{&self.agent_id});
+ const r = try post(self, arena, path, aw.writer.buffered());
+ if (r.code == 401 or r.code == 403) std.process.fatal("remote-control: gateway refused the key (HTTP {d}: {s}) — run `graff login`", .{ r.code, errorMessage(arena, r.body) });
+ if (r.code < 200 or r.code >= 300) {
+ serve.serveLog(self.st.io, "remote-control: HTTP {d}: {s}", .{ r.code, errorMessage(arena, r.body) });
+ return error.RegisterFailed;
+ }
+}
+
+/// One command the relay handed us. `body` is the object re-serialized to a
+/// single line: serve's request set is line-oriented on the child's stdin.
+pub const Command = struct {
+ id: []const u8,
+ kind: []const u8,
+ session_id: ?[]const u8,
+ body: []const u8,
+};
+
+fn poll(self: *State, arena: Allocator) ![]const Command {
+ const payload = try pollPayload(self, arena);
+ const path = try std.fmt.allocPrint(arena, "/v1/remote/agents/{s}/poll", .{&self.agent_id});
+ const r = try post(self, arena, path, payload);
+ if (r.code == 404) return error.UnknownDevice;
+ if (r.code < 200 or r.code >= 300) {
+ serve.serveLog(self.st.io, "remote-control: HTTP {d}: {s}", .{ r.code, errorMessage(arena, r.body) });
+ return error.PollFailed;
+ }
+ return parseCommands(arena, r.body);
+}
+
+/// `{"wait_ms":N,"sessions":[{"id","state","last_seq"}…]}` — presence rides
+/// on the poll. Names are validName-safe, so they print raw.
+fn pollPayload(self: *State, arena: Allocator) ![]const u8 {
+ const io = self.st.io;
+ var aw: Io.Writer.Allocating = .init(arena);
+ const w = &aw.writer;
+ try w.print("{{\"wait_ms\":{d},\"sessions\":[", .{poll_wait_ms});
+ self.st.mutex.lockUncancelable(io);
+ defer self.st.mutex.unlock(io);
+ for (self.st.sessions.items, 0..) |s, i| {
+ if (i > 0) try w.writeByte(',');
+ try w.print("{{\"id\":\"{s}\",\"state\":\"{s}\",\"last_seq\":{d}}}", .{
+ s.name, if (s.in_flight.load(.acquire)) "busy" else "idle", s.last_seq,
+ });
+ }
+ try w.writeAll("]}");
+ return aw.writer.buffered();
+}
+
+/// Command ids are relay-minted; anything outside [A-Za-z0-9_-] is dropped
+/// rather than printed back into a JSON body.
+pub fn validCommandId(id: []const u8) bool {
+ if (id.len == 0 or id.len > 64) return false;
+ for (id) |c| if (!std.ascii.isAlphanumeric(c) and c != '-' and c != '_') return false;
+ return true;
+}
+
+pub fn parseCommands(arena: Allocator, text: []const u8) ![]const Command {
+ const v = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch return error.BadReply;
+ if (v != .object) return error.BadReply;
+ const list = v.object.get("commands") orelse return &.{};
+ if (list != .array) return error.BadReply;
+ var out: std.ArrayList(Command) = .empty;
+ for (list.array.items) |item| {
+ if (item != .object) continue;
+ const o = item.object;
+ const id = util.strFieldObj(o, "id") orelse continue;
+ const kind = util.strFieldObj(o, "kind") orelse continue;
+ if (!validCommandId(id)) continue;
+ const session_id = util.strFieldObj(o, "session_id");
+ if (session_id) |sid| if (!events.validName(sid)) continue;
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.write(o.get("body") orelse Value{ .object = .empty });
+ try out.append(arena, .{ .id = id, .kind = kind, .session_id = session_id, .body = aw.writer.buffered() });
+ }
+ return out.items;
+}
+
+fn runCommand(self: *State, arena: Allocator, cmd: Command) void {
+ const io = self.st.io;
+ if (std.mem.eql(u8, cmd.kind, "create")) {
+ const made = serve_create.createFromBody(&self.st, arena, cmd.body) catch |err| {
+ serve.serveLog(io, "remote-control: create failed ({t})", .{err});
+ return sendResult(self, arena, cmd.id, null, 500, "{\"error\":\"failed to create session\"}");
+ };
+ return sendResult(self, arena, cmd.id, null, @intFromEnum(made.status), made.body);
+ }
+ const sid = cmd.session_id orelse return sendResult(self, arena, cmd.id, null, 400, "{\"error\":\"session_id required\"}");
+ if (std.mem.eql(u8, cmd.kind, "close")) return closeSession(self, arena, cmd.id, sid);
+ if (!std.mem.eql(u8, cmd.kind, "request")) return sendResult(self, arena, cmd.id, sid, 400, "{\"error\":\"unknown command kind\"}");
+
+ const rtype = events.stringField(cmd.body, "type") orelse "";
+ const from: ?u64 = blk: {
+ const v = std.json.parseFromSliceLeaky(Value, arena, cmd.body, .{ .allocate = .alloc_always }) catch break :blk null;
+ if (v != .object) break :blk null;
+ const f = v.object.get("resume_from") orelse v.object.get("from") orelse break :blk null;
+ break :blk if (f == .integer and f.integer > 0) @as(u64, @intCast(f.integer)) else null;
+ };
+ // A pure reconnect replays the tape and sends nothing to the child — and
+ // works for a session this supervisor never ran, straight off the disk.
+ if (std.mem.eql(u8, rtype, "reattach")) {
+ var up = Uploader.init(self, arena, cmd.id, sid);
+ replayTape(self, arena, &up, sid, from orelse 1);
+ return up.finish(200, "{\"ok\":true,\"type\":\"reattach\"}");
+ }
+ self.st.mutex.lockUncancelable(io);
+ const found = self.st.find(sid);
+ self.st.mutex.unlock(io);
+ const s = found orelse return sendResult(self, arena, cmd.id, sid, 404, "{\"error\":\"no such session\"}");
+ if (std.mem.eql(u8, rtype, "answer")) {
+ s.answer_mu.lockUncancelable(io);
+ defer s.answer_mu.unlock(io);
+ if (!s.awaiting_answer) return sendResult(self, arena, cmd.id, sid, 409, "{\"error\":\"no active ask_user prompt\"}");
+ serve.writeChildLine(io, s, cmd.body) catch return sendResult(self, arena, cmd.id, sid, 502, "{\"error\":\"session process is gone\"}");
+ s.awaiting_answer = false;
+ s.answer_call_id_len = 0;
+ return sendResult(self, arena, cmd.id, sid, 200, "{\"ok\":true,\"type\":\"answer\"}");
+ }
+ if (std.mem.eql(u8, rtype, "cancel")) {
+ if (!s.in_flight.load(.acquire)) return sendResult(self, arena, cmd.id, sid, 409, "{\"error\":\"no request is in flight\"}");
+ serve.writeChildLine(io, s, cmd.body) catch return sendResult(self, arena, cmd.id, sid, 502, "{\"error\":\"session process is gone\"}");
+ return sendResult(self, arena, cmd.id, sid, 200, "{\"ok\":true,\"type\":\"cancel\"}");
+ }
+ drain(self, arena, s, cmd.id, cmd.body, from);
+}
+
+/// Mirror of serveMessage: one request in, its events out until the terminal
+/// one — persisted to the tape BEFORE they go upstream, so a relay hiccup
+/// never costs the run its history.
+fn drain(self: *State, arena: Allocator, s: *ServeSession, cmd_id: []const u8, line: []const u8, from: ?u64) void {
+ const io = self.st.io;
+ var dead = false;
+ var up = Uploader.init(self, arena, cmd_id, s.name);
+ {
+ s.busy.lockUncancelable(io); // serialize requests per session
+ defer s.busy.unlock(io);
+ s.in_flight.store(true, .release);
+ defer s.in_flight.store(false, .release);
+
+ serve.writeChildLine(io, s, line) catch return up.finish(502, "{\"error\":\"session process is gone\"}");
+ if (from) |n| replayTape(self, arena, &up, s.name, n);
+ while (true) {
+ const ev_line = s.rdr.interface.takeDelimiter('\n') catch |err| switch (err) {
+ error.StreamTooLong => break abort(s, &up, "event line exceeded the 1 MiB serve cap — session closed", &dead),
+ error.ReadFailed => break abort(s, &up, "session process exited mid-request", &dead),
+ } orelse break abort(s, &up, "session process exited mid-request", &dead);
+ const trimmed = std.mem.trim(u8, ev_line, " \t\r");
+ if (trimmed.len == 0) continue;
+ serve.serveUpdateAnswerState(io, s, trimmed);
+ s.log.append(trimmed);
+ if (events.seqOf(trimmed)) |q| s.last_seq = @max(s.last_seq, q);
+ up.push(trimmed);
+ if (events.terminalEvent(trimmed)) {
+ serve.serveClearAnswerState(io, s);
+ break;
+ }
+ }
+ }
+ up.finish(200, "{\"ok\":true}");
+ if (dead) serve.serveDrop(&self.st, s); // after the defers above are done with `s`
+}
+
+/// The child died mid-request: a terminal error with the next seq goes on the
+/// tape and upstream, so a viewer sees the failure, not a hole.
+fn abort(s: *ServeSession, up: *Uploader, message: []const u8, dead: *bool) void {
+ s.last_seq += 1;
+ var buf: [256]u8 = undefined;
+ const line = std.fmt.bufPrint(&buf, "{{\"seq\":{d},\"type\":\"error\",\"message\":\"{s}\"}}", .{ s.last_seq, message }) catch
+ "{\"type\":\"error\",\"message\":\"session process exited mid-request\"}";
+ s.log.append(line);
+ up.push(line);
+ dead.* = true;
+}
+
+/// Every complete tape line with seq >= from, in order.
+fn replayTape(self: *State, arena: Allocator, up: *Uploader, sid: []const u8, from: u64) void {
+ const path = events.logPath(arena, sid) catch return;
+ const data = Io.Dir.cwd().readFileAlloc(self.st.io, path, arena, .limited(events.max_log_bytes)) catch return;
+ var rest = data;
+ while (std.mem.indexOfScalar(u8, rest, '\n')) |nl| {
+ const line = std.mem.trim(u8, rest[0..nl], " \t\r");
+ rest = rest[nl + 1 ..];
+ if (line.len == 0) continue;
+ const seq = events.seqOf(line) orelse continue;
+ if (seq >= from) up.push(line);
+ }
+}
+
+/// Graceful close, as serveDelete: wait out an in-flight request, EOF the
+/// child's stdin, reap in the background. Tape and session file stay.
+fn closeSession(self: *State, arena: Allocator, cmd_id: []const u8, sid: []const u8) void {
+ const io = self.st.io;
+ self.st.mutex.lockUncancelable(io);
+ const found = self.st.find(sid);
+ if (found) |sess| {
+ for (self.st.sessions.items, 0..) |p, i| {
+ if (p == sess) {
+ _ = self.st.sessions.swapRemove(i);
+ break;
+ }
+ }
+ }
+ self.st.mutex.unlock(io);
+ const sess = found orelse return sendResult(self, arena, cmd_id, sid, 404, "{\"error\":\"no such session\"}");
+ sess.busy.lockUncancelable(io);
+ sess.busy.unlock(io);
+ if (sess.child.stdin) |f| {
+ f.close(io);
+ sess.child.stdin = null;
+ }
+ self.st.group.concurrent(io, serve.serveReap, .{ &self.st, sess }) catch serve.serveReap(&self.st, sess);
+ serve.serveLog(io, "remote-control: session {s} closed", .{sid});
+ sendResult(self, arena, cmd_id, sid, 200, "{\"ok\":true}");
+}
+
+fn sendResult(self: *State, arena: Allocator, cmd_id: []const u8, sid: ?[]const u8, status: u16, body: []const u8) void {
+ var up = Uploader.init(self, arena, cmd_id, sid orelse "");
+ up.finish(status, body);
+}
+
+/// Event types a viewer must see NOW rather than at the end of a window.
+pub fn urgent(line: []const u8) bool {
+ const t = events.stringField(line, "type") orelse return false;
+ return std.mem.eql(u8, t, "tool_call") or std.mem.eql(u8, t, "ask_user") or events.terminalEvent(line);
+}
+
+/// A line too big for the relay window becomes an envelope-only stub. Only the
+/// upload shrinks: the tape and a later `reattach` still carry the full line.
+pub fn uploadLine(buf: []u8, line: []const u8) []const u8 {
+ if (line.len <= upload_line_cap) return line;
+ const seq = events.seqOf(line) orelse 0;
+ const t = events.stringField(line, "type") orelse "event";
+ return std.fmt.bufPrint(buf, "{{\"seq\":{d},\"type\":\"{s}\",\"truncated\":true,\"bytes\":{d}}}", .{ seq, t[0..@min(t.len, 64)], line.len }) catch line[0..0];
+}
+
+/// Batches event lines for one command into `POST …/events` bodies:
+/// `{"command_id","session_id","events":[<line>,…][,"result":{status,body}]}`.
+/// Lines are JSON objects already, so they ride as values, never re-escaped.
+const Uploader = struct {
+ self: *State,
+ arena: Allocator,
+ cmd_id: []const u8,
+ sid: []const u8,
+ aw: Io.Writer.Allocating,
+ count: usize = 0,
+ last_flush_ms: i64,
+
+ fn init(self: *State, arena: Allocator, cmd_id: []const u8, sid: []const u8) Uploader {
+ return .{ .self = self, .arena = arena, .cmd_id = cmd_id, .sid = sid, .aw = .init(arena), .last_flush_ms = util.unixMs(self.st.io) };
+ }
+
+ fn open(u: *Uploader) void {
+ u.aw.writer.print("{{\"command_id\":\"{s}\",\"session_id\":\"{s}\",\"events\":[", .{ u.cmd_id, u.sid }) catch {};
+ }
+
+ fn push(u: *Uploader, line: []const u8) void {
+ if (u.count == 0) u.open();
+ if (u.count > 0) u.aw.writer.writeByte(',') catch {};
+ var stub: [256]u8 = undefined;
+ u.aw.writer.writeAll(uploadLine(&stub, line)) catch {};
+ u.count += 1;
+ const now = util.unixMs(u.self.st.io);
+ if (u.aw.writer.buffered().len >= flush_bytes or now - u.last_flush_ms >= flush_window_ms or urgent(line)) u.flush(null);
+ }
+
+ /// One POST. A failed upload is logged and dropped: the tape is complete
+ /// and the viewer's next `reattach` fills the hole from it.
+ fn flush(u: *Uploader, result: ?struct { status: u16, body: []const u8 }) void {
+ if (u.count == 0 and result == null) return;
+ if (u.count == 0) u.open();
+ u.aw.writer.writeByte(']') catch {};
+ if (result) |r| u.aw.writer.print(",\"result\":{{\"status\":{d},\"body\":{s}}}", .{ r.status, r.body }) catch {};
+ u.aw.writer.writeByte('}') catch {};
+ const path = std.fmt.allocPrint(u.arena, "/v1/remote/agents/{s}/events", .{&u.self.agent_id}) catch return;
+ var attempt: usize = 0;
+ while (attempt < 3) : (attempt += 1) {
+ if (post(u.self, u.arena, path, u.aw.writer.buffered())) |r| {
+ if (r.code >= 200 and r.code < 300) break;
+ serve.serveLog(u.self.st.io, "remote-control: upload HTTP {d}: {s}", .{ r.code, errorMessage(u.arena, r.body) });
+ if (r.code < 500) break;
+ } else |err| serve.serveLog(u.self.st.io, "remote-control: upload failed ({t})", .{err});
+ u.self.st.io.sleep(.fromMilliseconds(250 * @as(i64, @intCast(attempt + 1))), .awake) catch break;
+ }
+ u.aw = .init(u.arena);
+ u.count = 0;
+ u.last_flush_ms = util.unixMs(u.self.st.io);
+ }
+
+ fn finish(u: *Uploader, status: u16, body: []const u8) void {
+ u.flush(.{ .status = status, .body = body });
+ }
+};
+
+test "parseDeviceId accepts exactly 16 lowercase hex, nothing else" {
+ try std.testing.expectEqualStrings("00ff00ff00ff00ff", &(parseDeviceId("{\"device_id\":\"00ff00ff00ff00ff\"}\n").?));
+ try std.testing.expect(parseDeviceId("{\"device_id\":\"00FF00FF00FF00FF\"}") == null);
+ try std.testing.expect(parseDeviceId("{\"device_id\":\"short\"}") == null);
+ try std.testing.expect(parseDeviceId("{}") == null);
+}
+
+test "parseCommands: ids validated, session names validated, bodies re-lined" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const cmds = try parseCommands(arena,
+ \\{"commands":[
+ \\ {"id":"c1","kind":"create","body":{"model":"m","yolo":true}},
+ \\ {"id":"c2","kind":"request","session_id":"nightly","body":{"type":"user","text":"hi"}},
+ \\ {"id":"bad id","kind":"close","session_id":"x","body":{}},
+ \\ {"id":"c3","kind":"close","session_id":"../etc","body":{}},
+ \\ {"id":"c4","kind":"close","session_id":"ok"}
+ \\]}
+ );
+ try std.testing.expectEqual(@as(usize, 3), cmds.len);
+ try std.testing.expectEqualStrings("c1", cmds[0].id);
+ try std.testing.expect(cmds[0].session_id == null);
+ try std.testing.expectEqualStrings("{\"model\":\"m\",\"yolo\":true}", cmds[0].body);
+ try std.testing.expectEqualStrings("nightly", cmds[1].session_id.?);
+ try std.testing.expectEqualStrings("{\"type\":\"user\",\"text\":\"hi\"}", cmds[1].body);
+ try std.testing.expectEqualStrings("{}", cmds[2].body); // a body-less command still carries one line
+ try std.testing.expectEqual(@as(usize, 0), (try parseCommands(arena, "{\"commands\":[]}")).len);
+ try std.testing.expectError(error.BadReply, parseCommands(arena, "[]"));
+}
+
+test "urgent: tool calls, prompts and terminals flush immediately; deltas batch" {
+ try std.testing.expect(urgent("{\"seq\":1,\"type\":\"tool_call\",\"name\":\"bash\"}"));
+ try std.testing.expect(urgent("{\"seq\":2,\"type\":\"ask_user\",\"call_id\":\"q\"}"));
+ try std.testing.expect(urgent("{\"seq\":3,\"type\":\"turn\"}"));
+ try std.testing.expect(!urgent("{\"seq\":4,\"type\":\"text\",\"text\":\"turn\"}"));
+ try std.testing.expect(!urgent("{\"seq\":5,\"type\":\"reasoning\",\"text\":\"…\"}"));
+}
+
+test "uploadLine: small lines pass through, oversized ones become an envelope stub" {
+ var buf: [256]u8 = undefined;
+ const small = "{\"seq\":7,\"type\":\"text\",\"text\":\"hi\"}";
+ try std.testing.expectEqualStrings(small, uploadLine(&buf, small));
+ const big = try std.testing.allocator.alloc(u8, upload_line_cap + 100);
+ defer std.testing.allocator.free(big);
+ const head = "{\"seq\":9,\"type\":\"tool_result\",\"output\":\"";
+ @memset(big, 'x');
+ @memcpy(big[0..head.len], head);
+ big[big.len - 2] = '"';
+ big[big.len - 1] = '}';
+ const stub = uploadLine(&buf, big);
+ try std.testing.expect(std.mem.startsWith(u8, stub, "{\"seq\":9,\"type\":\"tool_result\",\"truncated\":true,\"bytes\":"));
+ try std.testing.expect(events.seqOf(stub).? == 9);
+}
+
+test "validCommandId keeps relay ids inside a JSON string" {
+ try std.testing.expect(validCommandId("3f2a9c1e-7b4d-4e6f-9a0b-1c2d3e4f5a6b"));
+ try std.testing.expect(!validCommandId(""));
+ try std.testing.expect(!validCommandId("has\"quote"));
+ try std.testing.expect(!validCommandId("has space"));
+}
diff --git a/src/serve.zig b/src/serve.zig
index a6efdc82..4a1ac6cb 100644
--- a/src/serve.zig
+++ b/src/serve.zig
@@ -29,7 +29,7 @@ const emitSchema = schema.emitSchema;
const harness_version = root.harness_version;
const schema_version = schema.schema_version;
-const ServeConfig = struct {
+pub const ServeConfig = struct {
host: []const u8,
port: u16,
token: ?[]const u8,
@@ -495,7 +495,7 @@ fn serveCancel(st: *ServeState, req: *std.http.Server.Request, s: *ServeSession,
return respondJson(st, req, .ok, "{\"ok\":true,\"type\":\"cancel\"}");
}
-fn writeChildLine(io: Io, s: *ServeSession, line: []const u8) !void {
+pub fn writeChildLine(io: Io, s: *ServeSession, line: []const u8) !void {
s.stdin_mu.lockUncancelable(io);
defer s.stdin_mu.unlock(io);
var buf: [1024]u8 = undefined;
@@ -505,7 +505,7 @@ fn writeChildLine(io: Io, s: *ServeSession, line: []const u8) !void {
try writer.interface.flush();
}
-fn serveUpdateAnswerState(io: Io, s: *ServeSession, line: []const u8) void {
+pub fn serveUpdateAnswerState(io: Io, s: *ServeSession, line: []const u8) void {
const ty = events.stringField(line, "type") orelse return;
if (!std.mem.eql(u8, ty, "ask_user")) return;
const call_id = events.stringField(line, "call_id") orelse "";
@@ -517,7 +517,7 @@ fn serveUpdateAnswerState(io: Io, s: *ServeSession, line: []const u8) void {
s.awaiting_answer = true;
}
-fn serveClearAnswerState(io: Io, s: *ServeSession) void {
+pub fn serveClearAnswerState(io: Io, s: *ServeSession) void {
s.answer_mu.lockUncancelable(io);
defer s.answer_mu.unlock(io);
s.awaiting_answer = false;
@@ -525,7 +525,7 @@ fn serveClearAnswerState(io: Io, s: *ServeSession) void {
}
/// Remove a dead session and free it (child already gone or being killed).
-fn serveDrop(st: *ServeState, sess: *ServeSession) void {
+pub fn serveDrop(st: *ServeState, sess: *ServeSession) void {
const io = st.io;
st.mutex.lockUncancelable(io);
for (st.sessions.items, 0..) |p, i| {
@@ -542,7 +542,7 @@ fn serveDrop(st: *ServeState, sess: *ServeSession) void {
/// Background reaper for a gracefully-closed session: the child exits on
/// stdin EOF (after finishing any in-flight turn) and flushes telemetry and
/// trajectory records on the way out — kill would race (and lose) that flush.
-fn serveReap(st: *ServeState, sess: *ServeSession) void {
+pub fn serveReap(st: *ServeState, sess: *ServeSession) void {
_ = sess.child.wait(st.io) catch {};
freeSession(st, sess);
}
diff --git a/src/serve_create.zig b/src/serve_create.zig
index a47ac090..769f1737 100644
--- a/src/serve_create.zig
+++ b/src/serve_create.zig
@@ -21,7 +21,6 @@ const ServeState = serve.ServeState;
const ServeSession = serve.ServeSession;
pub fn create(st: *ServeState, req: *std.http.Server.Request) !void {
- const io = st.io;
const gpa = st.gpa;
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
@@ -31,6 +30,20 @@ pub fn create(st: *ServeState, req: *std.http.Server.Request) !void {
const br = req.readerExpectContinue(&bbuf) catch return error.WriteFailed;
const body = br.allocRemaining(arena, .limited(64 * 1024)) catch
return serve.respondJson(st, req, .payload_too_large, "{\"error\":\"body too large\"}");
+ const made = try createFromBody(st, arena, body);
+ return serve.respondJson(st, req, made.status, made.body);
+}
+
+/// What creating a session came to, as the HTTP bridge reports it.
+pub const Created = struct { status: std.http.Status, body: []const u8 };
+
+/// The transport-free half of `POST /v1/sessions`: parse the options object,
+/// spawn (or attach to) the durable session, and describe the outcome as an
+/// HTTP status + JSON body. Shared by the HTTP bridge and remote control,
+/// which delivers the same object from the relay instead of a socket.
+pub fn createFromBody(st: *ServeState, arena: Allocator, body: []const u8) !Created {
+ const io = st.io;
+ const gpa = st.gpa;
var model = st.cfg.model;
var subagent_provider = st.cfg.subagent_provider;
@@ -46,11 +59,11 @@ pub fn create(st: *ServeState, req: *std.http.Server.Request) !void {
var name = try newSessionName(io, arena);
if (std.mem.trim(u8, body, " \t\r\n").len > 0) {
const v = std.json.parseFromSliceLeaky(Value, arena, body, .{ .allocate = .alloc_always }) catch
- return serve.respondJson(st, req, .bad_request, "{\"error\":\"body must be a JSON object\"}");
- if (v != .object) return serve.respondJson(st, req, .bad_request, "{\"error\":\"body must be a JSON object\"}");
+ return .{ .status = .bad_request, .body = "{\"error\":\"body must be a JSON object\"}" };
+ if (v != .object) return .{ .status = .bad_request, .body = "{\"error\":\"body must be a JSON object\"}" };
if (v.object.get("session") orelse v.object.get("session_id") orelse v.object.get("resume")) |n| if (n == .string) {
if (!events.validName(n.string))
- return serve.respondJson(st, req, .bad_request, "{\"error\":\"session must be 1-64 chars of [A-Za-z0-9._-] and must not start with . or -\"}");
+ return .{ .status = .bad_request, .body = "{\"error\":\"session must be 1-64 chars of [A-Za-z0-9._-] and must not start with . or -\"}" };
name = n.string;
};
if (v.object.get("model")) |m| if (m == .string) {
@@ -95,7 +108,7 @@ pub fn create(st: *ServeState, req: *std.http.Server.Request) !void {
const live = st.find(name);
const live_seq = if (live) |s| s.last_seq else 0;
st.mutex.unlock(io);
- if (live != null) return serve.respondJson(st, req, .ok, try createdBody(arena, name, true, live_seq));
+ if (live != null) return .{ .status = .ok, .body = try createdBody(arena, name, true, live_seq) };
const log_path = try events.logPath(arena, name);
const resumed = sessionOnDisk(io, arena, name);
@@ -122,7 +135,7 @@ pub fn create(st: *ServeState, req: *std.http.Server.Request) !void {
.stdin = .pipe,
.stdout = .pipe,
.stderr = .inherit, // tool progress → the server's terminal
- }) catch return serve.respondJson(st, req, .internal_server_error, "{\"error\":\"failed to spawn harness child\"}");
+ }) catch return .{ .status = .internal_server_error, .body = "{\"error\":\"failed to spawn harness child\"}" };
const sess = newSession(st, &child, name, log_path, last_seq) catch {
child.kill(io);
@@ -143,7 +156,7 @@ pub fn create(st: *ServeState, req: *std.http.Server.Request) !void {
serve.serveLog(io, "serve: session {s} {s} (model={s} yolo={} last_seq={d})", .{
sess.name, if (resumed) "resumed" else "created", model orelse "default", yolo, last_seq,
});
- return serve.respondJson(st, req, .created, try createdBody(arena, sess.name, resumed, last_seq));
+ return .{ .status = .created, .body = try createdBody(arena, sess.name, resumed, last_seq) };
}
fn createdBody(arena: Allocator, name: []const u8, resumed: bool, last_seq: u64) ![]const u8 {
diff --git a/src/startup.zig b/src/startup.zig
index 5a5630aa..c38f365a 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -190,8 +190,31 @@ const job_registry = @import("job_registry.zig"); // #199
const cube = @import("cube.zig");
const schema = @import("schema.zig");
const serve = @import("serve.zig");
+const remote_control = @import("remote_control.zig"); // #722: serve without a listener
+const remote_client = @import("remote_client.zig"); // #722: `graff remote …`
const main_mod = @import("main.zig");
+/// The session-child settings `graff serve` and `graff remote-control` share:
+/// both spawn the same `<exe> --json` children from the same flags.
+fn serveConfig(flags: args.Flags, environ: anytype) serve.ServeConfig {
+ return .{
+ .host = flags.host_flag,
+ .port = flags.port_flag,
+ .token = flags.token_flag orelse environ.get("HARNESS_SERVE_TOKEN") orelse environ.get("GRAFF_SERVE_TOKEN"),
+ .yolo = flags.yolo_flag,
+ .model = flags.model_flag,
+ .subagent_provider = flags.subagent_provider_flag,
+ .subagent_model = flags.subagent_model_flag,
+ .allow_cross_provider_subagents = flags.allow_cross_provider_subagents_flag,
+ .no_subagent_tier = flags.no_subagent_tier_flag,
+ .system_prompt = flags.system_prompt_flag,
+ .append_system_prompt = flags.append_system_flag,
+ .max_tool_calls = main_mod.max_tool_calls,
+ .max_model_calls = main_mod.max_model_calls,
+ .dedupe_tool_calls = main_mod.dedupe_tool_calls,
+ };
+}
+
/// A credentialed ACP launch returns the exact ResolvedKeys value used before
/// #613. Only a launch with no usable provider enters the lightweight loop;
/// every other terminal trajectory keeps resolveKeys' existing fatal behavior.
@@ -287,28 +310,42 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.process
// session is a `harness --json` child of this same binary. Keys are
// loaded by the children, not here.
if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "serve")) {
- const token = flags.token_flag orelse init.environ_map.get("HARNESS_SERVE_TOKEN") orelse init.environ_map.get("GRAFF_SERVE_TOKEN");
const exe = std.process.executablePathAlloc(io, arena) catch
std.process.fatal("serve: cannot resolve own executable path", .{});
- try serve.serveMain(gpa, io, .{
- .host = flags.host_flag,
- .port = flags.port_flag,
- .token = token,
- .yolo = flags.yolo_flag,
- .model = flags.model_flag,
- .subagent_provider = flags.subagent_provider_flag,
- .subagent_model = flags.subagent_model_flag,
- .allow_cross_provider_subagents = flags.allow_cross_provider_subagents_flag,
- .no_subagent_tier = flags.no_subagent_tier_flag,
- .system_prompt = flags.system_prompt_flag,
- .append_system_prompt = flags.append_system_flag,
- .max_tool_calls = main_mod.max_tool_calls,
- .max_model_calls = main_mod.max_model_calls,
- .dedupe_tool_calls = main_mod.dedupe_tool_calls,
+ try serve.serveMain(gpa, io, serveConfig(flags, init.environ_map), exe);
+ return true;
+ }
+
+ // `graff remote-control [--name <n>]`: the serve supervisor with no
+ // listener — dials OUT to the gateway with the `graff login` key and takes
+ // commands from the account's relay (#722). Same session children as serve.
+ if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "remote-control")) {
+ const home = keys_cli.homeEnv(init.environ_map) orelse std.process.fatal("no HOME/USERPROFILE", .{});
+ const cg_key = init.environ_map.get("CODEGRAFF_API_KEY") orelse oauth.loadCodegraffKey(io, arena, home) orelse
+ std.process.fatal("remote-control: no codegraff key — run `graff login` first", .{});
+ const exe = std.process.executablePathAlloc(io, arena) catch
+ std.process.fatal("remote-control: cannot resolve own executable path", .{});
+ try remote_control.remoteControlMain(gpa, io, .{
+ .base = init.environ_map.get("GRAFF_REMOTE_BASE") orelse main_mod.codegraff_device_base,
+ .key = cg_key,
+ .home = home,
+ .name = flags.name_flag,
+ .serve = serveConfig(flags, init.environ_map),
}, exe);
return true;
}
+ // `graff remote [sessions|agents|new|send|answer|tail|cancel|close]`: drive
+ // the sessions of any machine running `graff remote-control` on this login.
+ if (flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "remote")) {
+ const cg_key = init.environ_map.get("CODEGRAFF_API_KEY") orelse
+ (if (keys_cli.homeEnv(init.environ_map)) |home| oauth.loadCodegraffKey(io, arena, home) else null) orelse
+ std.process.fatal("remote: no codegraff key — run `graff login` first", .{});
+ const base = init.environ_map.get("GRAFF_REMOTE_BASE") orelse main_mod.codegraff_device_base;
+ try remote_client.command(io, gpa, arena, base, cg_key, flags.positionals.items[1..], .{ .model = flags.model_flag, .yolo = flags.yolo_flag });
+ return true;
+ }
+
// `harness update [--force|--check]`: self-update to the latest GitHub
// release. Version-checked (skips if already current), reuses install.sh
// for the actual download/codesign/atomic swap. Exits after.
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 2744f23c..e522735f 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -360,6 +360,8 @@ test {
_ = @import("codex_tool_search.zig"); // hosted tool_search on gpt-5.4+ Codex
_ = @import("tool_call_args.zig"); // #752: truncated tool-call arguments must not poison history
_ = @import("cache_affinity.zig"); // ADR 0069: git-root / scratch cache seed
+ _ = @import("remote_control.zig"); // #722: relay command parsing, upload stubs, device id
+ _ = @import("remote_client.zig"); // #722: event painting, gateway error shapes
_ = @import("meta_wire.zig"); // #751 / ADR 0083: Meta tool_choice is auto-only
_ = @import("codedb_local.zig"); // #765: local-only codedb context (no remote rerank)
_ = @import("version_status.zig");