Skip to content

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

Python

feat(serve): resumable embedder streams — seq ids, ?from=N replay, durable sessions

Rach Pradhan4e7a253f2605
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 5c93c2ec..fd818684 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -10,7 +10,7 @@
"src/main.zig",
"src/repl.zig"
],
- "test_count_baseline": 627,
+ "test_count_baseline": 640,
"required_invariants": [
{
"id": "goal-epochs",
diff --git a/scripts/test-serve-resume.py b/scripts/test-serve-resume.py
new file mode 100644
index 00000000..a21e01a2
--- /dev/null
+++ b/scripts/test-serve-resume.py
@@ -0,0 +1,319 @@
+#!/usr/bin/env python3
+"""#330 part 2: `graff serve` streams are sequenced, replayable, and resumable.
+
+Five things are proven end-to-end against a scripted codex/Responses mock (no
+network, no real provider):
+
+1. every event of a turn carries a monotonic `seq`, contiguous from 1;
+2. `GET /v1/sessions/<id>/events?from=N` after completion replays byte-identical
+ events with no gaps and no duplicates;
+3. a supervisor that drops the socket MID-TURN loses nothing: the bridge keeps
+ draining the child into the persisted log, and `?from=N` delivers the tail;
+4. killing the whole bridge and starting a REPLACEMENT process, then posting the
+ same session name, continues the conversation - the mock sees turn one's
+ history in turn three's request;
+5. the sequence continues across that process boundary instead of restarting,
+ so `?from=N` keeps meaning the same thing to the client.
+
+Usage: python3 scripts/test-serve-resume.py [path/to/graff]
+"""
+
+from __future__ import annotations
+
+import http.client
+import json
+import os
+import shutil
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from codex_ws_mock import CodexMock, RecordedRequest # noqa: E402
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+SESSION = "e2e-resume"
+SENTINEL = "TURN_ONE_SENTINEL"
+
+
+# ── the mock ──────────────────────────────────────────────────────────────────
+
+
+def reply(text: str, ordinal: int) -> list[dict]:
+ return [
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "message",
+ "id": f"msg_{ordinal}",
+ "status": "completed",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": text, "annotations": []}],
+ },
+ },
+ {
+ "type": "response.completed",
+ "response": {
+ "id": f"resp_{ordinal}",
+ "usage": {
+ "input_tokens": 100,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 10,
+ "total_tokens": 110,
+ },
+ },
+ },
+ ]
+
+
+slow_turn = threading.Event() # armed while the mid-stream-disconnect turn runs
+
+
+def events_for_request(request: RecordedRequest) -> list[dict]:
+ """Echo back exactly what history the model was handed, so the transcript
+ itself proves whether context survived the process boundary."""
+ body = json.dumps(request.body.get("input", []))
+ if slow_turn.is_set():
+ time.sleep(1.5) # long enough for the client to walk away mid-turn
+ return reply(
+ f"call#{request.ordinal} items={len(request.body.get('input', []) or [])} "
+ f"saw_sentinel={SENTINEL in body}",
+ request.ordinal,
+ )
+
+
+# ── process + HTTP plumbing ───────────────────────────────────────────────────
+
+
+def free_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+def environment(tmp: str, mock_port: int) -> dict[str, str]:
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home, exist_ok=True)
+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:
+ json.dump({"tokens": {"access_token": "resume-mock", "account_id": "acct"}}, fh)
+ harness_dir = os.path.join(tmp, ".harness")
+ os.makedirs(harness_dir, exist_ok=True)
+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:
+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)
+ env = {
+ k: v
+ for k, v in os.environ.items()
+ if not k.startswith("GRAFF_") and not k.startswith("CODEX_")
+ }
+ env.update(
+ {
+ "HOME": tmp,
+ "CODEX_HOME": codex_home,
+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{mock_port}/backend-api/codex/responses",
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_LEARN_AUTO": "off",
+ }
+ )
+ return env
+
+
+def start_serve(tmp: str, mock_port: int, port: int) -> subprocess.Popen:
+ proc = subprocess.Popen(
+ [GRAFF, "serve", "--host", "127.0.0.1", "--port", str(port),
+ "--model", "codex", "--yolo", "--no-telemetry"],
+ cwd=tmp,
+ env=environment(tmp, mock_port),
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.PIPE,
+ )
+ threading.Thread(target=lambda: [None for _ in proc.stderr], daemon=True).start()
+ for _ in range(200):
+ try:
+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
+ conn.request("GET", "/healthz")
+ if conn.getresponse().status == 200:
+ conn.close()
+ return proc
+ except OSError:
+ time.sleep(0.05)
+ raise AssertionError("graff serve never became healthy")
+
+
+def post_json(port: int, path: str, body: dict) -> dict:
+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
+ conn.request("POST", path, json.dumps(body), {"content-type": "application/json"})
+ resp = conn.getresponse()
+ payload = json.loads(resp.read())
+ conn.close()
+ return payload
+
+
+def stream(port: int, method: str, path: str, body: dict | None = None,
+ stop_after: int | None = None) -> list[dict]:
+ """Read an NDJSON stream. stop_after=N closes the socket after N events -
+ that is a supervisor crashing mid-turn, not a graceful end."""
+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=60)
+ payload = None if body is None else json.dumps(body)
+ conn.request(method, path, payload, {"content-type": "application/json"})
+ resp = conn.getresponse()
+ if resp.status != 200:
+ raise AssertionError(f"{method} {path} -> {resp.status}: {resp.read()[:200]!r}")
+ out: list[dict] = []
+ try:
+ while True:
+ line = resp.readline()
+ if not line:
+ break
+ line = line.strip()
+ if not line:
+ continue
+ out.append(json.loads(line))
+ if stop_after is not None and len(out) >= stop_after:
+ break
+ finally:
+ conn.close() # mid-stream: this is the disconnect under test
+ return out
+
+
+# ── assertions ────────────────────────────────────────────────────────────────
+
+
+def seqs(events: list[dict]) -> list[int]:
+ for ev in events:
+ if "seq" not in ev:
+ raise AssertionError(f"event without a seq: {ev!r}")
+ return [ev["seq"] for ev in events]
+
+
+def expect_contiguous(events: list[dict], start: int, label: str) -> int:
+ got = seqs(events)
+ want = list(range(start, start + len(got)))
+ if got != want:
+ raise AssertionError(f"{label}: seq not contiguous from {start}: {got}")
+ if len(set(got)) != len(got):
+ raise AssertionError(f"{label}: duplicate seq: {got}")
+ return got[-1] if got else start - 1
+
+
+def final_text(events: list[dict]) -> str:
+ if events[-1].get("type") != "turn":
+ raise AssertionError(f"turn did not terminate cleanly: {events[-1]!r}")
+ return events[-1]["text"]
+
+
+def main() -> None:
+ tmp = tempfile.mkdtemp(prefix="graff-serve-resume-")
+ mock = CodexMock(events_for_request=events_for_request)
+ mock_port = mock.start()
+ serve_port = free_port()
+ serve = start_serve(tmp, mock_port, serve_port)
+ try:
+ # 1 ── create a durable session and run a turn ────────────────────────
+ created = post_json(serve_port, "/v1/sessions", {"session": SESSION})
+ assert created == {"session_id": SESSION, "resumed": False, "last_seq": 0}, created
+
+ first = stream(serve_port, "POST", f"/v1/sessions/{SESSION}",
+ {"type": "user", "text": SENTINEL})
+ last = expect_contiguous(first, 1, "turn one")
+ text_one = final_text(first)
+ print(f" turn 1: {len(first)} events, seq 1..{last} -> {text_one!r}")
+
+ # 2 ── replay after completion is byte-identical, no gaps, no dupes ───
+ replay_all = stream(serve_port, "GET", f"/v1/sessions/{SESSION}/events?from=1")
+ if replay_all != first:
+ raise AssertionError("full replay did not match the live stream")
+ mid = last // 2 + 1
+ replay_tail = stream(serve_port, "GET", f"/v1/sessions/{SESSION}/events?from={mid}")
+ if replay_tail != [e for e in first if e["seq"] >= mid]:
+ raise AssertionError("?from=N replayed the wrong slice")
+ expect_contiguous(replay_tail, mid, "replay tail")
+ past_end = stream(serve_port, "GET", f"/v1/sessions/{SESSION}/events?from={last + 1}")
+ if past_end:
+ raise AssertionError(f"replay past the tape invented events: {past_end!r}")
+ print(f" replay: from=1 identical ({len(replay_all)}), from={mid} exact tail "
+ f"({len(replay_tail)}), from={last + 1} empty")
+
+ # 3 ── drop the socket mid-turn; the run continues, ?from=N catches up ─
+ slow_turn.set()
+ partial: list[dict] = []
+ runner = threading.Thread(
+ target=lambda: partial.extend(
+ stream(serve_port, "POST", f"/v1/sessions/{SESSION}",
+ {"type": "user", "text": "TURN_TWO"}, stop_after=2)))
+ runner.start()
+ runner.join(timeout=30)
+ expect_contiguous(partial, last + 1, "turn two (before the crash)")
+ seen = partial[-1]["seq"]
+ rest = stream(serve_port, "GET", f"/v1/sessions/{SESSION}/events?from={seen + 1}")
+ slow_turn.clear()
+ last = expect_contiguous(rest, seen + 1, "turn two (after reconnect)")
+ text_two = final_text(rest)
+ if any(e["seq"] <= seen for e in rest):
+ raise AssertionError("reconnect re-delivered events the client already had")
+ print(f" mid-stream: client died after seq {seen}; reconnect delivered "
+ f"seq {seen + 1}..{last} -> {text_two!r}")
+
+ # 4+5 ── kill the bridge, resume on a REPLACEMENT process ─────────────
+ serve.kill()
+ serve.wait(timeout=30)
+ serve_port_2 = free_port()
+ serve = start_serve(tmp, mock_port, serve_port_2)
+ resumed = post_json(serve_port_2, "/v1/sessions", {"session": SESSION})
+ if not resumed["resumed"] or resumed["session_id"] != SESSION:
+ raise AssertionError(f"replacement bridge did not resume: {resumed!r}")
+ if resumed["last_seq"] != last:
+ raise AssertionError(
+ f"replacement bridge lost the tape end: {resumed['last_seq']} != {last}")
+
+ third = stream(serve_port_2, "POST", f"/v1/sessions/{SESSION}",
+ {"type": "user", "text": "TURN_THREE"})
+ last_3 = expect_contiguous(third, last + 1, "turn three (replacement process)")
+ text_three = final_text(third)
+ if "saw_sentinel=True" not in text_three:
+ raise AssertionError(
+ f"model context did NOT carry over into the replacement process: {text_three!r}")
+ items = int(text_three.split("items=")[1].split()[0])
+ if items < 5:
+ raise AssertionError(f"resumed history is too short to be turns 1-2: {text_three!r}")
+ print(f" replacement bridge: resumed={resumed['resumed']} last_seq={resumed['last_seq']}, "
+ f"turn 3 seq {last + 1}..{last_3} -> {text_three!r}")
+
+ # the whole tape, across both processes, is one gap-free sequence
+ log = os.path.join(tmp, ".graff", "serve", f"{SESSION}.events.jsonl")
+ with open(log, encoding="utf-8") as fh:
+ tape = [json.loads(l) for l in fh if l.strip()]
+ expect_contiguous(tape, 1, "persisted tape")
+ print(f" persisted tape: {len(tape)} events, seq 1..{tape[-1]['seq']}, no gaps")
+
+ # The autosave lands just after the terminal event the HTTP response
+ # ended on, so poll rather than race the child's own write.
+ session_file = os.path.join(tmp, ".graff", "sessions", f"{SESSION}.session.json")
+ saved: dict = {}
+ for _ in range(100):
+ with open(session_file, encoding="utf-8") as fh:
+ saved = json.load(fh)
+ if saved.get("event_seq", 0) >= last_3:
+ break
+ time.sleep(0.1)
+ if saved.get("event_seq", 0) < last_3:
+ raise AssertionError(f"session file did not persist the sequence: {saved.get('event_seq')}")
+ print(f" session file: event_seq={saved['event_seq']}, {len(saved['messages'])} messages")
+ print("ok serve streams are sequenced, replayable, and resumable across processes")
+ finally:
+ try:
+ serve.kill()
+ serve.wait(timeout=10)
+ except Exception:
+ pass
+ mock.stop()
+ shutil.rmtree(tmp, ignore_errors=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/sdk/generate.py b/sdk/generate.py
index ed4e93dd..4abdab3c 100644
--- a/sdk/generate.py
+++ b/sdk/generate.py
@@ -67,28 +67,31 @@ export type ProviderId = {provider_union};
/** Events streamed by `harness --json` (one JSON object per stdout line), each
* discriminated by `type` — the analogue of codegraff's AgentEvent stream.
+ * `seq` is a monotonic, gap-free, 1-based per-session id: it is what lets a
+ * supervisor say exactly where it stopped reading, and it CONTINUES across a
+ * `--resume` rather than restarting (#330).
* Forward compatibility: a newer (edge) harness binary may stream event
* types not in this union; the runtime yields them as-is and every loop in
* this client only terminates on `turn`/`error`, so unknown events are safe
* to ignore in consumer code too. */
export type Event =
- | {{ type: "text"; text: string }}
- | {{ type: "reasoning"; text: string }}
- | {{ type: "started"; provider: string; model: string }}
- | {{ type: "model_call_started"; provider: string; model: string }}
- | {{ type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }}
- | {{ type: "tool_call"; name: string; input: Record<string, unknown> }}
- | {{ type: "tool_call_started"; name: string; input: Record<string, unknown> }}
- | {{ type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }}
- | {{ type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}
- | {{ type: "tool_result"; name: string; is_error: boolean; text: string }}
- | {{ type: "tool_call_finished"; name: string; is_error: boolean; ms: number }}
- | {{ type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }}
- | {{ type: "finalizing" }}
- | {{ type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }}
- | {{ type: "system_prompt"; ok: boolean; append: boolean; chars: number }}
- | {{ type: "score"; ok: boolean; prompt_sha: string }}
- | {{ type: "error"; message: string }};
+ | {{ seq: number; type: "text"; text: string }}
+ | {{ seq: number; type: "reasoning"; text: string }}
+ | {{ seq: number; type: "started"; provider: string; model: string }}
+ | {{ seq: number; type: "model_call_started"; provider: string; model: string }}
+ | {{ seq: number; type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }}
+ | {{ seq: number; type: "tool_call"; name: string; input: Record<string, unknown> }}
+ | {{ seq: number; type: "tool_call_started"; name: string; input: Record<string, unknown> }}
+ | {{ seq: number; type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }}
+ | {{ seq: number; type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}
+ | {{ seq: number; type: "tool_result"; name: string; is_error: boolean; text: string }}
+ | {{ seq: number; type: "tool_call_finished"; name: string; is_error: boolean; ms: number }}
+ | {{ seq: number; type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }}
+ | {{ seq: number; type: "finalizing" }}
+ | {{ seq: number; type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }}
+ | {{ seq: number; type: "system_prompt"; ok: boolean; append: boolean; chars: number }}
+ | {{ seq: number; type: "score"; ok: boolean; prompt_sha: string }}
+ | {{ seq: number; type: "error"; message: string }};
/** Fingerprint of a system prompt as used in `.graff/trajectories` —
* the aggregate DGM-style archive — and by `Harness.score()`:
@@ -515,27 +518,30 @@ export type ToolName = {tool_union};
export type ProviderId = {provider_union};
/** Events streamed by the bridge (same `--json` contract as the stdio SDK).
+ * `seq` is a monotonic, gap-free, 1-based per-session id the bridge forwards
+ * unchanged from the child and persists; reconnect with `?from=seq+1` to pick
+ * the stream back up exactly where you stopped (#330).
* Forward compatibility: a newer (edge) harness may stream event types not
* in this union; every loop here only terminates on its request's terminal
* event, so unknown events pass through and are safe to ignore. */
export type Event =
- | {{ type: "text"; text: string }}
- | {{ type: "reasoning"; text: string }}
- | {{ type: "started"; provider: string; model: string }}
- | {{ type: "model_call_started"; provider: string; model: string }}
- | {{ type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }}
- | {{ type: "tool_call"; name: string; input: Record<string, unknown> }}
- | {{ type: "tool_call_started"; name: string; input: Record<string, unknown> }}
- | {{ type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }}
- | {{ type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}
- | {{ type: "tool_result"; name: string; is_error: boolean; text: string }}
- | {{ type: "tool_call_finished"; name: string; is_error: boolean; ms: number }}
- | {{ type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }}
- | {{ type: "finalizing" }}
- | {{ type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }}
- | {{ type: "system_prompt"; ok: boolean; append: boolean; chars: number }}
- | {{ type: "score"; ok: boolean; prompt_sha: string }}
- | {{ type: "error"; message: string }};
+ | {{ seq: number; type: "text"; text: string }}
+ | {{ seq: number; type: "reasoning"; text: string }}
+ | {{ seq: number; type: "started"; provider: string; model: string }}
+ | {{ seq: number; type: "model_call_started"; provider: string; model: string }}
+ | {{ seq: number; type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }}
+ | {{ seq: number; type: "tool_call"; name: string; input: Record<string, unknown> }}
+ | {{ seq: number; type: "tool_call_started"; name: string; input: Record<string, unknown> }}
+ | {{ seq: number; type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }}
+ | {{ seq: number; type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}
+ | {{ seq: number; type: "tool_result"; name: string; is_error: boolean; text: string }}
+ | {{ seq: number; type: "tool_call_finished"; name: string; is_error: boolean; ms: number }}
+ | {{ seq: number; type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }}
+ | {{ seq: number; type: "finalizing" }}
+ | {{ seq: number; type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }}
+ | {{ seq: number; type: "system_prompt"; ok: boolean; append: boolean; chars: number }}
+ | {{ seq: number; type: "score"; ok: boolean; prompt_sha: string }}
+ | {{ seq: number; type: "error"; message: string }};
/** Async (WebCrypto) variant of the trajectory-archive prompt fingerprint:
* first 8 bytes of SHA-256, hex (16 chars). */
@@ -564,13 +570,33 @@ export interface RemoteOptions {{
maxModelCalls?: number;
/** Reject duplicate root tool name+normalized-input calls per turn. */
dedupeToolCalls?: boolean;
- /** Attach to an existing session instead of creating one. */
+ /** Attach to an existing LIVE session on this bridge without creating one.
+ * Skips the create call entirely — use `session` to create-or-resume. */
sessionId?: string;
+ /** Name a DURABLE session (1-64 chars of [A-Za-z0-9._-]). The bridge runs
+ * the child as `graff --json --resume <session>` in its workspace, so the
+ * conversation is autosaved after every turn. Passing the same name to a
+ * REPLACEMENT bridge picks the run up from the last persisted turn, with
+ * the event sequence continuing rather than restarting (#330). Omitted:
+ * the bridge mints a fresh 16-hex name, which is still durable. */
+ session?: string;
+}}
+
+/** What the bridge reports when a session is created or resumed. */
+export interface SessionInfo {{
+ /** The durable session id — also the graff session name on the server. */
+ session_id: string;
+ /** A session file already existed: this run continues an earlier one. */
+ resumed: boolean;
+ /** Highest seq on the persisted event tape. Reconnect from `last_seq + 1`. */
+ last_seq: number;
}}
export interface ChatOptions {{
prompt: string;
review?: boolean;
+ /** Replay persisted events with seq >= from before this turn's live ones. */
+ from?: number;
}}
export interface AnswerOptions {{
@@ -608,19 +634,37 @@ async function* ndjson(res: Response): AsyncGenerator<Event> {{
const HEX16 = /^[0-9a-f]{{16}}$/;
/** A session on a remote `harness serve` bridge — the fetch-transport
- * analogue of the stdio `Harness` class, same method surface. */
+ * analogue of the stdio `Harness` class, same method surface.
+ *
+ * Resumability (#330): every event carries a monotonic `seq`, tracked here as
+ * `lastSeq`. If a stream dies mid-turn, call `reconnect(h.lastSeq + 1)` — the
+ * bridge kept draining the child into a persisted log the whole time, so you
+ * get the events you missed and then the live tail. If the whole BRIDGE died,
+ * point a new `RemoteHarness` at the replacement with the same `session` name
+ * and the run continues from the last persisted turn. */
export class RemoteHarness {{
private base: string;
private token?: string;
/** Resolves to the session id (creation is lazy-started in the constructor). */
readonly sessionId: Promise<string>;
+ /** Resolves to the bridge's create/resume report; null when attaching by
+ * `sessionId` (no create call was made). */
+ readonly info: Promise<SessionInfo | null>;
+ /** Highest `seq` this client has seen. `reconnect(lastSeq + 1)` resumes
+ * exactly where it stopped; 0 before the first event. */
+ lastSeq = 0;
constructor(opts: RemoteOptions) {{
this.base = opts.url.replace(/\\/+$/, "");
this.token = opts.token;
- this.sessionId = opts.sessionId
- ? Promise.resolve(opts.sessionId)
- : this.create(opts);
+ if (opts.sessionId) {{
+ this.sessionId = Promise.resolve(opts.sessionId);
+ this.info = Promise.resolve(null);
+ }} else {{
+ const created = this.create(opts);
+ this.info = created;
+ this.sessionId = created.then((d) => d.session_id);
+ }}
}}
/** Create a session (codegraff parity for `Graff.init`, remote edition). */
@@ -645,8 +689,9 @@ export class RemoteHarness {{
return res;
}}
- private async create(opts: RemoteOptions): Promise<string> {{
+ private async create(opts: RemoteOptions): Promise<SessionInfo> {{
const body: Record<string, unknown> = {{}};
+ if (opts.session) body.session = opts.session;
if (opts.model) body.model = opts.model;
if (opts.yolo !== undefined) body.yolo = opts.yolo;
if (opts.systemPrompt) body.system_prompt = opts.systemPrompt;
@@ -655,29 +700,51 @@ export class RemoteHarness {{
if (opts.maxModelCalls !== undefined) body.maxModelCalls = opts.maxModelCalls;
if (opts.dedupeToolCalls !== undefined) body.dedupeToolCalls = opts.dedupeToolCalls;
const res = await this.req("POST", "/v1/sessions", body);
- const data = (await res.json()) as {{ session_id: string }};
- return data.session_id;
+ const data = (await res.json()) as SessionInfo;
+ this.lastSeq = data.last_seq ?? 0;
+ return data;
+ }}
+
+ /** Track the sequence as events go by, so a reconnect needs no bookkeeping
+ * from the caller. */
+ private note(ev: Event): Event {{
+ if (typeof ev.seq === "number" && ev.seq > this.lastSeq) this.lastSeq = ev.seq;
+ return ev;
}}
/** Send one protocol request; stream its events. */
- private async *send(payload: Record<string, unknown>): AsyncGenerator<Event> {{
+ private async *send(payload: Record<string, unknown>, from?: number): AsyncGenerator<Event> {{
const id = await this.sessionId;
- const res = await this.req("POST", `/v1/sessions/${{id}}`, payload);
- yield* ndjson(res);
+ const q = from === undefined ? "" : `?from=${{from}}`;
+ const res = await this.req("POST", `/v1/sessions/${{id}}${{q}}`, payload);
+ for await (const ev of ndjson(res)) yield this.note(ev);
}}
/** Run one turn; async-iterate events up to and including `turn`/`error`. */
async *chat(input: string | ChatOptions): AsyncGenerator<Event> {{
const prompt = typeof input === "string" ? input : input.prompt;
const type = typeof input === "string" || !input.review ? "user" : "review";
+ const from = typeof input === "string" ? undefined : input.from;
let terminal = false;
- for await (const ev of this.send({{ type, text: prompt }})) {{
+ for await (const ev of this.send({{ type, text: prompt }}, from)) {{
yield ev;
if (ev.type === "turn" || ev.type === "error") {{ terminal = true; break; }}
}}
if (!terminal) throw new Error("bridge stream ended mid-turn (session process died?)");
}}
+ /** Re-attach to a session after losing the stream: replay persisted events
+ * with `seq >= from` (default: everything after what this client already
+ * saw), then follow live until the in-flight request's terminal event.
+ * Sends nothing to the model, so it is safe to call while a turn is
+ * running — including from a different process than the one that started
+ * it. Also the way to read a completed turn you never received. */
+ async *reconnect(from = this.lastSeq + 1): AsyncGenerator<Event> {{
+ const id = await this.sessionId;
+ const res = await this.req("GET", `/v1/sessions/${{id}}/events?from=${{from}}`);
+ for await (const ev of ndjson(res)) yield this.note(ev);
+ }}
+
/** Run a turn and return just the final assistant text. */
async ask(input: string | ChatOptions): Promise<string> {{
let final = "";
@@ -1227,7 +1294,12 @@ class RemoteHarness:
Stdlib-only (urllib): usable anywhere Python runs, no local binary
needed. Pass yolo=True in most cases — the bridge has no terminal to
- show permission prompts on."""
+ show permission prompts on.
+
+ #330: sessions are durable. Pass `session="<name>"` and the bridge runs
+ `graff --json --resume <name>`, so a REPLACEMENT bridge given the same
+ name continues the run. Every event carries a monotonic `seq`; after a
+ dropped stream, `reconnect()` replays exactly what was missed."""
def __init__(self, url: str, token: Optional[str] = None,
model: Optional[str] = None, yolo: bool = False,
@@ -1236,13 +1308,22 @@ class RemoteHarness:
max_tool_calls: Optional[int] = None,
dedupe_tool_calls: bool = False,
session_id: Optional[str] = None,
- max_model_calls: Optional[int] = None):
+ max_model_calls: Optional[int] = None,
+ session: Optional[str] = None):
self.base = url.rstrip("/")
self.token = token
+ # #330: highest event seq seen. reconnect() picks up from last_seq + 1.
+ self.last_seq = 0
+ self.info = None
if session_id is not None:
self.session_id = session_id
return
opts = {{}}
+ # A durable session name: the bridge runs the child as
+ # `graff --json --resume <session>`, so a REPLACEMENT bridge given the
+ # same name continues the run from its last persisted turn.
+ if session:
+ opts["session"] = session
if model:
opts["model"] = model
if yolo:
@@ -1258,7 +1339,9 @@ class RemoteHarness:
if dedupe_tool_calls:
opts["dedupeToolCalls"] = True
resp = self._request("POST", "/v1/sessions", opts)
- self.session_id = json.loads(resp.read())["session_id"]
+ self.info = json.loads(resp.read())
+ self.session_id = self.info["session_id"]
+ self.last_seq = int(self.info.get("last_seq") or 0)
def _request(self, method: str, path: str, body=None):
headers = {{"Content-Type": "application/json",
@@ -1274,24 +1357,45 @@ class RemoteHarness:
detail = e.read().decode(errors="replace")[:256]
raise RuntimeError(f"bridge {{method}} {{path}} → {{e.code}}: {{detail}}") from None
- def _send(self, payload: dict) -> Iterator[dict]:
- """POST one protocol request; yield its streamed NDJSON events."""
- resp = self._request("POST", f"/v1/sessions/{{self.session_id}}", payload)
+ def _stream(self, resp) -> Iterator[dict]:
for line in resp:
line = line.strip()
if not line:
continue
try:
- yield json.loads(line)
+ ev = json.loads(line)
except json.JSONDecodeError:
continue
+ seq = ev.get("seq")
+ if isinstance(seq, int) and seq > self.last_seq:
+ self.last_seq = seq
+ yield ev
- def chat(self, text: str, review: bool = False) -> Iterator[dict]:
+ def _send(self, payload: dict, from_seq: Optional[int] = None) -> Iterator[dict]:
+ """POST one protocol request; yield its streamed NDJSON events.
+ from_seq replays persisted events with seq >= from_seq first."""
+ query = "" if from_seq is None else f"?from={{from_seq}}"
+ resp = self._request("POST", f"/v1/sessions/{{self.session_id}}{{query}}", payload)
+ return self._stream(resp)
+
+ def reconnect(self, from_seq: Optional[int] = None) -> Iterator[dict]:
+ """Re-attach after losing the stream: replay persisted events with
+ seq >= from_seq (default: everything after what this client saw), then
+ follow live until the in-flight request's terminal event. Sends nothing
+ to the model, so it is safe while a turn is running — including from a
+ different process than the one that started it."""
+ start = self.last_seq + 1 if from_seq is None else from_seq
+ resp = self._request("GET", f"/v1/sessions/{{self.session_id}}/events?from={{start}}")
+ return self._stream(resp)
+
+ def chat(self, text: str, review: bool = False,
+ from_seq: Optional[int] = None) -> Iterator[dict]:
"""Send a user turn; yield events until (and including) the 'turn'
event. Raises RuntimeError if the stream ends without one (the
session process died server-side)."""
terminal = False
- for ev in self._send({{"type": "review" if review else "user", "text": text}}):
+ payload = {{"type": "review" if review else "user", "text": text}}
+ for ev in self._send(payload, from_seq):
yield ev
if ev.get("type") in ("turn", "error"):
terminal = True
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.py
index d39986b5..30bbc7ed 100644
--- a/sdk/py/harness_sdk.py
+++ b/sdk/py/harness_sdk.py
@@ -457,7 +457,12 @@ class RemoteHarness:
Stdlib-only (urllib): usable anywhere Python runs, no local binary
needed. Pass yolo=True in most cases — the bridge has no terminal to
- show permission prompts on."""
+ show permission prompts on.
+
+ #330: sessions are durable. Pass `session="<name>"` and the bridge runs
+ `graff --json --resume <name>`, so a REPLACEMENT bridge given the same
+ name continues the run. Every event carries a monotonic `seq`; after a
+ dropped stream, `reconnect()` replays exactly what was missed."""
def __init__(self, url: str, token: Optional[str] = None,
model: Optional[str] = None, yolo: bool = False,
@@ -466,13 +471,22 @@ class RemoteHarness:
max_tool_calls: Optional[int] = None,
dedupe_tool_calls: bool = False,
session_id: Optional[str] = None,
- max_model_calls: Optional[int] = None):
+ max_model_calls: Optional[int] = None,
+ session: Optional[str] = None):
self.base = url.rstrip("/")
self.token = token
+ # #330: highest event seq seen. reconnect() picks up from last_seq + 1.
+ self.last_seq = 0
+ self.info = None
if session_id is not None:
self.session_id = session_id
return
opts = {}
+ # A durable session name: the bridge runs the child as
+ # `graff --json --resume <session>`, so a REPLACEMENT bridge given the
+ # same name continues the run from its last persisted turn.
+ if session:
+ opts["session"] = session
if model:
opts["model"] = model
if yolo:
@@ -488,7 +502,9 @@ class RemoteHarness:
if dedupe_tool_calls:
opts["dedupeToolCalls"] = True
resp = self._request("POST", "/v1/sessions", opts)
- self.session_id = json.loads(resp.read())["session_id"]
+ self.info = json.loads(resp.read())
+ self.session_id = self.info["session_id"]
+ self.last_seq = int(self.info.get("last_seq") or 0)
def _request(self, method: str, path: str, body=None):
headers = {"Content-Type": "application/json",
@@ -504,24 +520,45 @@ class RemoteHarness:
detail = e.read().decode(errors="replace")[:256]
raise RuntimeError(f"bridge {method} {path} → {e.code}: {detail}") from None
- def _send(self, payload: dict) -> Iterator[dict]:
- """POST one protocol request; yield its streamed NDJSON events."""
- resp = self._request("POST", f"/v1/sessions/{self.session_id}", payload)
+ def _stream(self, resp) -> Iterator[dict]:
for line in resp:
line = line.strip()
if not line:
continue
try:
- yield json.loads(line)
+ ev = json.loads(line)
except json.JSONDecodeError:
continue
+ seq = ev.get("seq")
+ if isinstance(seq, int) and seq > self.last_seq:
+ self.last_seq = seq
+ yield ev
- def chat(self, text: str, review: bool = False) -> Iterator[dict]:
+ def _send(self, payload: dict, from_seq: Optional[int] = None) -> Iterator[dict]:
+ """POST one protocol request; yield its streamed NDJSON events.
+ from_seq replays persisted events with seq >= from_seq first."""
+ query = "" if from_seq is None else f"?from={from_seq}"
+ resp = self._request("POST", f"/v1/sessions/{self.session_id}{query}", payload)
+ return self._stream(resp)
+
+ def reconnect(self, from_seq: Optional[int] = None) -> Iterator[dict]:
+ """Re-attach after losing the stream: replay persisted events with
+ seq >= from_seq (default: everything after what this client saw), then
+ follow live until the in-flight request's terminal event. Sends nothing
+ to the model, so it is safe while a turn is running — including from a
+ different process than the one that started it."""
+ start = self.last_seq + 1 if from_seq is None else from_seq
+ resp = self._request("GET", f"/v1/sessions/{self.session_id}/events?from={start}")
+ return self._stream(resp)
+
+ def chat(self, text: str, review: bool = False,
+ from_seq: Optional[int] = None) -> Iterator[dict]:
"""Send a user turn; yield events until (and including) the 'turn'
event. Raises RuntimeError if the stream ends without one (the
session process died server-side)."""
terminal = False
- for ev in self._send({"type": "review" if review else "user", "text": text}):
+ payload = {"type": "review" if review else "user", "text": text}
+ for ev in self._send(payload, from_seq):
yield ev
if ev.get("type") in ("turn", "error"):
terminal = True
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index c62829ce..9d700048 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -8,7 +8,7 @@ import { homedir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
-export const HARNESS_VERSION = "0.9";
+export const HARNESS_VERSION = "0.10";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});
export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate";
@@ -16,28 +16,31 @@ export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "mi
/** Events streamed by `harness --json` (one JSON object per stdout line), each
* discriminated by `type` — the analogue of codegraff's AgentEvent stream.
+ * `seq` is a monotonic, gap-free, 1-based per-session id: it is what lets a
+ * supervisor say exactly where it stopped reading, and it CONTINUES across a
+ * `--resume` rather than restarting (#330).
* Forward compatibility: a newer (edge) harness binary may stream event
* types not in this union; the runtime yields them as-is and every loop in
* this client only terminates on `turn`/`error`, so unknown events are safe
* to ignore in consumer code too. */
export type Event =
- | { type: "text"; text: string }
- | { type: "reasoning"; text: string }
- | { type: "started"; provider: string; model: string }
- | { type: "model_call_started"; provider: string; model: string }
- | { type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }
- | { type: "tool_call"; name: string; input: Record<string, unknown> }
- | { type: "tool_call_started"; name: string; input: Record<string, unknown> }
- | { type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }
- | { type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }
- | { type: "tool_result"; name: string; is_error: boolean; text: string }
- | { type: "tool_call_finished"; name: string; is_error: boolean; ms: number }
- | { type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }
- | { type: "finalizing" }
- | { type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }
- | { type: "system_prompt"; ok: boolean; append: boolean; chars: number }
- | { type: "score"; ok: boolean; prompt_sha: string }
- | { type: "error"; message: string };
+ | { seq: number; type: "text"; text: string }
+ | { seq: number; type: "reasoning"; text: string }
+ | { seq: number; type: "started"; provider: string; model: string }
+ | { seq: number; type: "model_call_started"; provider: string; model: string }
+ | { seq: number; type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }
+ | { seq: number; type: "tool_call"; name: string; input: Record<string, unknown> }
+ | { seq: number; type: "tool_call_started"; name: string; input: Record<string, unknown> }
+ | { seq: number; type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }
+ | { seq: number; type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }
+ | { seq: number; type: "tool_result"; name: string; is_error: boolean; text: string }
+ | { seq: number; type: "tool_call_finished"; name: string; is_error: boolean; ms: number }
+ | { seq: number; type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }
+ | { seq: number; type: "finalizing" }
+ | { seq: number; type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }
+ | { seq: number; type: "system_prompt"; ok: boolean; append: boolean; chars: number }
+ | { seq: number; type: "score"; ok: boolean; prompt_sha: string }
+ | { seq: number; type: "error"; message: string };
/** Fingerprint of a system prompt as used in `.graff/trajectories` —
* the aggregate DGM-style archive — and by `Harness.score()`:
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index 301afffe..86bce1b9 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -7,34 +7,37 @@
// `harness --json` child over there, and one POST = one protocol request,
// streamed back as NDJSON until that request's terminal event.
-export const HARNESS_VERSION = "0.9";
+export const HARNESS_VERSION = "0.10";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});
export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by the bridge (same `--json` contract as the stdio SDK).
+ * `seq` is a monotonic, gap-free, 1-based per-session id the bridge forwards
+ * unchanged from the child and persists; reconnect with `?from=seq+1` to pick
+ * the stream back up exactly where you stopped (#330).
* Forward compatibility: a newer (edge) harness may stream event types not
* in this union; every loop here only terminates on its request's terminal
* event, so unknown events pass through and are safe to ignore. */
export type Event =
- | { type: "text"; text: string }
- | { type: "reasoning"; text: string }
- | { type: "started"; provider: string; model: string }
- | { type: "model_call_started"; provider: string; model: string }
- | { type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }
- | { type: "tool_call"; name: string; input: Record<string, unknown> }
- | { type: "tool_call_started"; name: string; input: Record<string, unknown> }
- | { type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }
- | { type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }
- | { type: "tool_result"; name: string; is_error: boolean; text: string }
- | { type: "tool_call_finished"; name: string; is_error: boolean; ms: number }
- | { type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }
- | { type: "finalizing" }
- | { type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }
- | { type: "system_prompt"; ok: boolean; append: boolean; chars: number }
- | { type: "score"; ok: boolean; prompt_sha: string }
- | { type: "error"; message: string };
+ | { seq: number; type: "text"; text: string }
+ | { seq: number; type: "reasoning"; text: string }
+ | { seq: number; type: "started"; provider: string; model: string }
+ | { seq: number; type: "model_call_started"; provider: string; model: string }
+ | { seq: number; type: "model_call_finished"; provider: string; model: string; ok: boolean; ms: number }
+ | { seq: number; type: "tool_call"; name: string; input: Record<string, unknown> }
+ | { seq: number; type: "tool_call_started"; name: string; input: Record<string, unknown> }
+ | { seq: number; type: "tool_rejected"; name: string; reason: "budget" | "duplicate" | string; input: Record<string, unknown>; message: string }
+ | { seq: number; type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }
+ | { seq: number; type: "tool_result"; name: string; is_error: boolean; text: string }
+ | { seq: number; type: "tool_call_finished"; name: string; is_error: boolean; ms: number }
+ | { seq: number; type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }
+ | { seq: number; type: "finalizing" }
+ | { seq: number; type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }
+ | { seq: number; type: "system_prompt"; ok: boolean; append: boolean; chars: number }
+ | { seq: number; type: "score"; ok: boolean; prompt_sha: string }
+ | { seq: number; type: "error"; message: string };
/** Async (WebCrypto) variant of the trajectory-archive prompt fingerprint:
* first 8 bytes of SHA-256, hex (16 chars). */
@@ -63,13 +66,33 @@ export interface RemoteOptions {
maxModelCalls?: number;
/** Reject duplicate root tool name+normalized-input calls per turn. */
dedupeToolCalls?: boolean;
- /** Attach to an existing session instead of creating one. */
+ /** Attach to an existing LIVE session on this bridge without creating one.
+ * Skips the create call entirely — use `session` to create-or-resume. */
sessionId?: string;
+ /** Name a DURABLE session (1-64 chars of [A-Za-z0-9._-]). The bridge runs
+ * the child as `graff --json --resume <session>` in its workspace, so the
+ * conversation is autosaved after every turn. Passing the same name to a
+ * REPLACEMENT bridge picks the run up from the last persisted turn, with
+ * the event sequence continuing rather than restarting (#330). Omitted:
+ * the bridge mints a fresh 16-hex name, which is still durable. */
+ session?: string;
+}
+
+/** What the bridge reports when a session is created or resumed. */
+export interface SessionInfo {
+ /** The durable session id — also the graff session name on the server. */
+ session_id: string;
+ /** A session file already existed: this run continues an earlier one. */
+ resumed: boolean;
+ /** Highest seq on the persisted event tape. Reconnect from `last_seq + 1`. */
+ last_seq: number;
}
export interface ChatOptions {
prompt: string;
review?: boolean;
+ /** Replay persisted events with seq >= from before this turn's live ones. */
+ from?: number;
}
export interface AnswerOptions {
@@ -107,19 +130,37 @@ async function* ndjson(res: Response): AsyncGenerator<Event> {
const HEX16 = /^[0-9a-f]{16}$/;
/** A session on a remote `harness serve` bridge — the fetch-transport
- * analogue of the stdio `Harness` class, same method surface. */
+ * analogue of the stdio `Harness` class, same method surface.
+ *
+ * Resumability (#330): every event carries a monotonic `seq`, tracked here as
+ * `lastSeq`. If a stream dies mid-turn, call `reconnect(h.lastSeq + 1)` — the
+ * bridge kept draining the child into a persisted log the whole time, so you
+ * get the events you missed and then the live tail. If the whole BRIDGE died,
+ * point a new `RemoteHarness` at the replacement with the same `session` name
+ * and the run continues from the last persisted turn. */
export class RemoteHarness {
private base: string;
private token?: string;
/** Resolves to the session id (creation is lazy-started in the constructor). */
readonly sessionId: Promise<string>;
+ /** Resolves to the bridge's create/resume report; null when attaching by
+ * `sessionId` (no create call was made). */
+ readonly info: Promise<SessionInfo | null>;
+ /** Highest `seq` this client has seen. `reconnect(lastSeq + 1)` resumes
+ * exactly where it stopped; 0 before the first event. */
+ lastSeq = 0;
constructor(opts: RemoteOptions) {
this.base = opts.url.replace(/\/+$/, "");
this.token = opts.token;
- this.sessionId = opts.sessionId
- ? Promise.resolve(opts.sessionId)
- : this.create(opts);
+ if (opts.sessionId) {
+ this.sessionId = Promise.resolve(opts.sessionId);
+ this.info = Promise.resolve(null);
+ } else {
+ const created = this.create(opts);
+ this.info = created;
+ this.sessionId = created.then((d) => d.session_id);
+ }
}
/** Create a session (codegraff parity for `Graff.init`, remote edition). */
@@ -144,8 +185,9 @@ export class RemoteHarness {
return res;
}
- private async create(opts: RemoteOptions): Promise<string> {
+ private async create(opts: RemoteOptions): Promise<SessionInfo> {
const body: Record<string, unknown> = {};
+ if (opts.session) body.session = opts.session;
if (opts.model) body.model = opts.model;
if (opts.yolo !== undefined) body.yolo = opts.yolo;
if (opts.systemPrompt) body.system_prompt = opts.systemPrompt;
@@ -154,29 +196,51 @@ export class RemoteHarness {
if (opts.maxModelCalls !== undefined) body.maxModelCalls = opts.maxModelCalls;
if (opts.dedupeToolCalls !== undefined) body.dedupeToolCalls = opts.dedupeToolCalls;
const res = await this.req("POST", "/v1/sessions", body);
- const data = (await res.json()) as { session_id: string };
- return data.session_id;
+ const data = (await res.json()) as SessionInfo;
+ this.lastSeq = data.last_seq ?? 0;
+ return data;
+ }
+
+ /** Track the sequence as events go by, so a reconnect needs no bookkeeping
+ * from the caller. */
+ private note(ev: Event): Event {
+ if (typeof ev.seq === "number" && ev.seq > this.lastSeq) this.lastSeq = ev.seq;
+ return ev;
}
/** Send one protocol request; stream its events. */
- private async *send(payload: Record<string, unknown>): AsyncGenerator<Event> {
+ private async *send(payload: Record<string, unknown>, from?: number): AsyncGenerator<Event> {
const id = await this.sessionId;
- const res = await this.req("POST", `/v1/sessions/${id}`, payload);
- yield* ndjson(res);
+ const q = from === undefined ? "" : `?from=${from}`;
+ const res = await this.req("POST", `/v1/sessions/${id}${q}`, payload);
+ for await (const ev of ndjson(res)) yield this.note(ev);
}
/** Run one turn; async-iterate events up to and including `turn`/`error`. */
async *chat(input: string | ChatOptions): AsyncGenerator<Event> {
const prompt = typeof input === "string" ? input : input.prompt;
const type = typeof input === "string" || !input.review ? "user" : "review";
+ const from = typeof input === "string" ? undefined : input.from;
let terminal = false;
- for await (const ev of this.send({ type, text: prompt })) {
+ for await (const ev of this.send({ type, text: prompt }, from)) {
yield ev;
if (ev.type === "turn" || ev.type === "error") { terminal = true; break; }
}
if (!terminal) throw new Error("bridge stream ended mid-turn (session process died?)");
}
+ /** Re-attach to a session after losing the stream: replay persisted events
+ * with `seq >= from` (default: everything after what this client already
+ * saw), then follow live until the in-flight request's terminal event.
+ * Sends nothing to the model, so it is safe to call while a turn is
+ * running — including from a different process than the one that started
+ * it. Also the way to read a completed turn you never received. */
+ async *reconnect(from = this.lastSeq + 1): AsyncGenerator<Event> {
+ const id = await this.sessionId;
+ const res = await this.req("GET", `/v1/sessions/${id}/events?from=${from}`);
+ for await (const ev of ndjson(res)) yield this.note(ev);
+ }
+
/** Run a turn and return just the final assistant text. */
async ask(input: string | ChatOptions): Promise<string> {
let final = "";
diff --git a/src/agent.zig b/src/agent.zig
index 5f6d27bd..65b8f92a 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -22,6 +22,7 @@ const schema = @import("schema.zig");
const models_cache = @import("models_cache.zig");
const keys_cli = @import("keys_cli.zig");
const run_budget_mod = @import("run_budget.zig");
+const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event
// prompt_ui (agent_prompt.zig) owns the width-budgeted status line (#209,
// 600-line goal); prompt() is member-aliased back onto Agent below.
@@ -213,6 +214,11 @@ pub const Agent = struct {
/// Emit one structured JSONL event to stdout (--json mode). `ev` is any
/// struct/anonymous struct; field names become JSON keys (a std.json.Value
/// field, e.g. tool input, serializes correctly). Best-effort.
+ ///
+ /// #330: in --json mode the event is stamped with a monotonic `seq` so a
+ /// supervisor that loses the stream can say exactly where it stopped. The
+ /// counter is bumped inside the same lock that serializes stdout, which is
+ /// what makes the sequence gap-free rather than merely increasing.
pub fn emit(self: *Agent, ev: anytype) void {
const w = self.out orelse return;
// --json: the GUI stream is shared with pool-thread subagent emits
@@ -220,8 +226,12 @@ pub const Agent = struct {
// land mid-buffer and two writers must never interleave on stdout.
if (main_mod.json_mode) main_mod.g_gui_mu.lockUncancelable(self.io);
defer if (main_mod.json_mode) main_mod.g_gui_mu.unlock(self.io);
- var s: std.json.Stringify = .{ .writer = w };
- s.write(ev) catch return;
+ if (main_mod.json_mode) {
+ protocol_seq.writeEvent(w, ev) catch return;
+ } else {
+ var s: std.json.Stringify = .{ .writer = w };
+ s.write(ev) catch return;
+ }
w.writeByte('\n') catch return;
w.flush() catch return;
}
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 5f90a4f3..40131ac1 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -44,6 +44,7 @@ const exec = @import("exec.zig");
const execTool = exec.execTool;
const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement
+const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event
const tool_results_dir = ".graff/tool-results";
pub const tool_preview_chars: usize = 2_000;
@@ -397,17 +398,16 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
pub fn emitAskUser(self: *Agent, call_id: []const u8, question: []const u8, input: Value) !void {
const w = self.out orelse return;
- var s: std.json.Stringify = .{ .writer = w };
- try s.beginObject();
- try s.objectField("type");
- try s.write("ask_user");
- try s.objectField("call_id");
- try s.write(call_id);
- try s.objectField("question");
- try s.write(question);
- try s.objectField("input");
- try s.write(input);
- try s.endObject();
+ // Same envelope as Agent.emit — hand-rolled only because `input` is a
+ // std.json.Value; #330's `seq` must ride this line too or a supervisor
+ // would see a hole exactly where it is asked to answer.
+ const ev = .{ .type = "ask_user", .call_id = call_id, .question = question, .input = input };
+ if (main_mod.json_mode) {
+ try protocol_seq.writeEvent(w, ev);
+ } else {
+ var s: std.json.Stringify = .{ .writer = w };
+ try s.write(ev);
+ }
try w.writeByte('\n');
try w.flush();
}
diff --git a/src/protocol_seq.zig b/src/protocol_seq.zig
new file mode 100644
index 00000000..acdf04af
--- /dev/null
+++ b/src/protocol_seq.zig
@@ -0,0 +1,139 @@
+//! Monotonic sequence ids for the `--json` / `graff serve` protocol (#330).
+//!
+//! Every structured event a `graff --json` process emits carries a `seq`: a
+//! per-session counter that starts at 1 and is stamped as the FIRST field of
+//! the event object, so a bridge can read it off a short prefix even when the
+//! rest of the line is a multi-MiB tool_result. Gaps are impossible in normal
+//! operation — the counter is bumped exactly once per emitted line, inside the
+//! same lock that already serializes the shared `--json` stdout.
+//!
+//! The counter outlives the process: session.zig persists `event_seq` next to
+//! the conversation and loadSession restores it, so a REPLACEMENT graff picking
+//! a run up on a fresh host continues the numbering instead of reissuing ids a
+//! supervisor has already seen.
+
+const std = @import("std");
+const Io = std.Io;
+
+var g_seq: std.atomic.Value(u64) = .init(0);
+
+/// Reserve the next id. Monotonic and gap-free within a process.
+pub fn next() u64 {
+ return g_seq.fetchAdd(1, .monotonic) + 1;
+}
+
+/// Highest id handed out so far; 0 before the first event.
+pub fn current() u64 {
+ return g_seq.load(.monotonic);
+}
+
+/// Continue a restored session's numbering. Only ever RAISES the counter: a
+/// stale or rolled-back session file must never make this process reissue ids
+/// that are already on the wire.
+pub fn restore(n: u64) void {
+ var seen = g_seq.load(.monotonic);
+ while (n > seen) {
+ seen = g_seq.cmpxchgWeak(seen, n, .monotonic, .monotonic) orelse return;
+ }
+}
+
+/// Tests only: back to a fresh session.
+pub fn resetForTest() void {
+ g_seq.store(0, .monotonic);
+}
+
+/// Serialize one protocol event as a single JSON object with `seq` first.
+/// `ev` must be a struct; its own fields follow in declaration order, so the
+/// `"type":"…"` prefix scans elsewhere still hit inside their window.
+/// Does NOT write the trailing newline — the caller owns line framing (and,
+/// for stdout, the lock that keeps two writers from interleaving).
+pub fn writeEvent(w: *Io.Writer, ev: anytype) !void {
+ var s: std.json.Stringify = .{ .writer = w };
+ try s.beginObject();
+ try s.objectField("seq");
+ try s.write(next());
+ inline for (comptime std.meta.fieldNames(@TypeOf(ev))) |name| {
+ comptime {
+ if (std.mem.eql(u8, name, "seq"))
+ @compileError("protocol event field collides with the envelope: seq");
+ }
+ try s.objectField(name);
+ try s.write(@field(ev, name));
+ }
+ try s.endObject();
+}
+
+/// The envelope prefix every stamped line opens with. Matching the POSITION,
+/// not merely the field name, is what makes this both O(1) on a megabyte-long
+/// tool_result and impossible to fool with a payload field that happens to be
+/// called "seq".
+const envelope_prefix = "{\"seq\":";
+
+/// Read the `seq` a producer stamped on an event line, or null when the line
+/// carries none (an older child, or an unstamped bridge line).
+pub fn seqOf(line: []const u8) ?u64 {
+ if (!std.mem.startsWith(u8, line, envelope_prefix)) return null;
+ var i = envelope_prefix.len;
+ const start = i;
+ while (i < line.len and line[i] >= '0' and line[i] <= '9') i += 1;
+ if (i == start) return null;
+ return std.fmt.parseInt(u64, line[start..i], 10) catch null;
+}
+
+test "seq counter is monotonic and gap-free" {
+ resetForTest();
+ defer resetForTest();
+ try std.testing.expectEqual(@as(u64, 0), current());
+ var prev: u64 = 0;
+ for (0..64) |_| {
+ const n = next();
+ try std.testing.expectEqual(prev + 1, n); // no gaps, ever
+ prev = n;
+ }
+ try std.testing.expectEqual(prev, current());
+}
+
+test "restore only raises the counter, so a stale session cannot reissue ids" {
+ resetForTest();
+ defer resetForTest();
+ restore(100);
+ try std.testing.expectEqual(@as(u64, 100), current());
+ try std.testing.expectEqual(@as(u64, 101), next());
+ restore(7); // a stale/rolled-back session file
+ try std.testing.expectEqual(@as(u64, 101), current());
+ try std.testing.expectEqual(@as(u64, 102), next());
+ restore(0);
+ try std.testing.expectEqual(@as(u64, 102), current());
+}
+
+test "writeEvent stamps seq first and keeps every field of the event" {
+ resetForTest();
+ defer resetForTest();
+ var buf: [512]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ try writeEvent(&w, .{ .type = "turn", .text = "hi", .context_tokens = @as(u64, 42) });
+ const line = w.buffered();
+ try std.testing.expect(std.mem.startsWith(u8, line, "{\"seq\":1,\"type\":\"turn\""));
+ try std.testing.expect(std.mem.indexOf(u8, line, "\"text\":\"hi\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, line, "\"context_tokens\":42") != null);
+ try std.testing.expectEqual(@as(u64, 1), seqOf(line).?);
+
+ // The next event takes the next id; the counter is shared, not per-writer.
+ var buf2: [256]u8 = undefined;
+ var w2: Io.Writer = .fixed(&buf2);
+ try writeEvent(&w2, .{ .type = "finalizing" });
+ try std.testing.expectEqual(@as(u64, 2), seqOf(w2.buffered()).?);
+}
+
+test "seqOf reads the envelope off a prefix and refuses to guess" {
+ try std.testing.expectEqual(@as(u64, 9), seqOf("{\"seq\":9,\"type\":\"text\"}").?);
+ try std.testing.expectEqual(@as(u64, 1234567), seqOf("{\"seq\":1234567,\"type\":\"text\",\"text\":\"x\"}").?);
+ // Unstamped lines (an older child, a bridge-generated error) report null
+ // rather than a fabricated position.
+ try std.testing.expect(seqOf("{\"type\":\"error\",\"message\":\"gone\"}") == null);
+ try std.testing.expect(seqOf("") == null);
+ try std.testing.expect(seqOf("{\"seq\":}") == null);
+ // A payload field named "seq" is NOT the envelope, however close it sits.
+ try std.testing.expect(seqOf("{\"type\":\"tool_result\",\"seq\":5}") == null);
+ try std.testing.expect(seqOf(" {\"seq\":5}") == null); // callers trim first
+}
diff --git a/src/schema.zig b/src/schema.zig
index a05822fb..ac8d69a9 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -25,19 +25,9 @@ const schema_protocol_json = @import("schema_protocol.zig").json;
/// Documentation of the `harness serve` HTTP bridge, embedded verbatim in
/// `--schema` output. Same request/event contract as the stdio protocol —
/// one POST = one protocol request, streamed back as NDJSON until that
-/// request's terminal event (turn/error for user turns; the ack for others).
-const schema_serve_json =
- \\{
- \\ "transport": "HTTP/1.1 (graff serve, default 127.0.0.1:8787); auth via Authorization: Bearer <token> when --token/HARNESS_SERVE_TOKEN is set (required on non-loopback binds)",
- \\ "endpoints": [
- \\ {"method": "GET", "path": "/healthz", "description": "liveness + version, no auth"},
- \\ {"method": "GET", "path": "/v1/schema", "description": "this schema document"},
- \\ {"method": "POST", "path": "/v1/sessions", "description": "create a session (a graff --json child); optional JSON body {\"model\",\"subagentProvider\",\"subagentModel\",\"allowCrossProviderSubagents\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"maxModelCalls\",\"dedupeToolCalls\"} overrides serve-level defaults; responds {\"session_id\":\"<16 hex>\"}"},
- \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / set_system_prompt / set_model / compact / set_mode / set_agent / score / answer); non-answer requests stream application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); answer requests return JSON ack while the original user stream continues; one non-answer request in flight per session at a time"},
- \\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin"}
- \\ ]
- \\}
-;
+/// request's terminal event (turn/error for user turns; the ack for others) —
+/// plus the #330 resumability surface (seq, ?from=N, durable session names).
+const schema_serve_json = @import("schema_serve.zig").json;
/// Launch flags relevant to SDK clients, embedded verbatim in `--schema`
/// output so generated clients can surface them as first-class options.
/// Pinned against learning_privacy.default_mode by a test there: the SDKs are
@@ -386,7 +376,7 @@ fn writeToolEntry(s: *std.json.Stringify, kind: Provider.Kind, name: []const u8,
/// a per-commit git describe) — bump this only when the schema or JSONL
/// protocol changes shape, so SDK regeneration stays byte-stable across
/// commits.
-pub const schema_version = "0.9"; // new `skill` tool (SKILL.md playbooks, skill_docs.zig)
+pub const schema_version = "0.10"; // #330: every --json/serve event carries a monotonic `seq`
/// Emit the machine-readable interface description for `harness --schema`:
/// providers, models, built-in tools (name/description/parameters), and the
diff --git a/src/schema_protocol.zig b/src/schema_protocol.zig
index 13d3e8a7..8c0653e3 100644
--- a/src/schema_protocol.zig
+++ b/src/schema_protocol.zig
@@ -5,6 +5,7 @@ pub const json =
\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",
\\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"review\",\"text\":\"target or instructions\"} runs one isolated read-only review turn with fresh model-visible history and no edits, delegation, workflows, or web access; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",
\\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to this run's file under .graff/trajectories (the aggregate append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",
+ \\ "sequencing": "every event object below carries a monotonic per-session \"seq\" as its FIRST field: 1-based, gap-free, one id per emitted line. It survives a resume - the counter is persisted with the conversation as event_seq and restored by --resume, so a REPLACEMENT process continues the numbering instead of reissuing ids a consumer already saw. `graff serve` forwards the child's seq unchanged and uses it for ?from=N replay",
\\ "events": [
\\ {"type": "text", "text": "assistant text delta"},
\\ {"type": "reasoning", "text": "reasoning/thinking delta (GUI shows a collapsible Thinking block)"},
diff --git a/src/schema_serve.zig b/src/schema_serve.zig
new file mode 100644
index 00000000..94ee3821
--- /dev/null
+++ b/src/schema_serve.zig
@@ -0,0 +1,19 @@
+//! Embedded documentation for the `graff serve` HTTP bridge, emitted verbatim
+//! under the "serve" key of `graff --schema` (the SDK generators read it).
+//! Split out of schema.zig, which is at the 600-line cap.
+
+pub const json =
+ \\{
+ \\ "transport": "HTTP/1.1 (graff serve, default 127.0.0.1:8787); auth via Authorization: Bearer <token> when --token/HARNESS_SERVE_TOKEN is set (required on non-loopback binds)",
+ \\ "sequencing": "every streamed event carries a monotonic per-session \"seq\" (1-based, gap-free) as its FIRST field. The bridge persists each forwarded line to .graff/serve/<session_id>.events.jsonl and keeps draining the child into that log even after a client disconnects, so a supervisor that dies mid-turn loses nothing. Reconnect with ?from=N (or {\"resume_from\":N}) to receive persisted events with seq >= N before the live stream continues",
+ \\ "resume": "the session id IS the graff session name: the child runs as `graff --json --resume <id>`, autosaving .graff/sessions/<id>.session.json after every turn. A REPLACEMENT serve process on a fresh host POSTs /v1/sessions with {\"session\":\"<id>\"} in the same workspace and the run continues from the last persisted turn, with the event sequence continuing (never restarting) because the counter is persisted alongside the conversation as event_seq",
+ \\ "endpoints": [
+ \\ {"method": "GET", "path": "/healthz", "description": "liveness + version, no auth"},
+ \\ {"method": "GET", "path": "/v1/schema", "description": "this schema document"},
+ \\ {"method": "POST", "path": "/v1/sessions", "description": "create OR resume a session (a graff --json child); optional JSON body {\"session\",\"model\",\"subagentProvider\",\"subagentModel\",\"allowCrossProviderSubagents\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"maxModelCalls\",\"dedupeToolCalls\"} overrides serve-level defaults. \"session\" (aliases \"session_id\"/\"resume\") names a durable session: 1-64 chars of [A-Za-z0-9._-], not starting with . or -; omitted means a fresh 16-hex name. Responds {\"session_id\":\"<name>\",\"resumed\":<bool>,\"last_seq\":<N>} - resumed says a session file already existed, last_seq is where the persisted event tape ends (reconnect with ?from=last_seq+1)"},
+ \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / review / set_system_prompt / set_model / compact / set_mode / set_agent / set_effort / set_fast / score / answer); non-answer requests stream application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); answer requests return a JSON ack while the original user stream continues; one non-answer request in flight per session at a time. ?from=N or {\"resume_from\":N} replays persisted events with seq >= N before the live stream. {\"type\":\"reattach\"} sends nothing to the child and only replays+follows, so it is safe while another connection is mid-turn"},
+ \\ {"method": "GET", "path": "/v1/sessions/{id}/events?from=N", "description": "reconnect: replay persisted events with seq >= N (default 1), then keep following the log live while a request is in flight, ending at that request's terminal event. Takes no protocol lock and never writes to the child, and works for a session this process never spawned as long as its event log is in the workspace"},
+ \\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin. The session file and the event log stay on disk, so the id remains resumable"}
+ \\ ]
+ \\}
+;
diff --git a/src/serve.zig b/src/serve.zig
index 3a63e084..407f1810 100644
--- a/src/serve.zig
+++ b/src/serve.zig
@@ -2,6 +2,15 @@
//! streamed back as NDJSON. Manages a pool of `<exe> --json` child processes
//! and bridges HTTP <-> the stdio protocol. Split out of main.zig (#123).
//!
+//! #330 (embedder mode): a session is DURABLE. Its id doubles as the graff
+//! session name, the child is spawned with `--resume <id>` so the conversation
+//! autosaves after every turn, and every forwarded event line is appended to
+//! `.graff/serve/<id>.events.jsonl` with the monotonic `seq` the child stamped.
+//! A supervisor that drops the socket reconnects with `?from=N`; a supervisor
+//! whose whole bridge died starts a REPLACEMENT process, POSTs the same session
+//! id, and picks the run up from the last persisted turn. The log plumbing and
+//! replay filter live in serve_events.zig.
+//!
//! std-only except for three things that stay in main and are back-imported:
//! emitSchema (GET /v1/schema) and harness_version + schema_version (/healthz).
@@ -14,6 +23,8 @@ const Allocator = std.mem.Allocator;
// resolves the main<->serve import cycle fine (all runtime, no comptime dep).
const root = @import("main.zig");
const schema = @import("schema.zig");
+const events = @import("serve_events.zig");
+const serve_create = @import("serve_create.zig"); // POST /v1/sessions (durable naming + spawn)
const emitSchema = schema.emitSchema;
const harness_version = root.harness_version;
const schema_version = schema.schema_version;
@@ -36,23 +47,31 @@ const ServeConfig = struct {
/// Cap on one child event line (a tool_result event carrying a big tool
/// output is the realistic worst case). Also the per-session reader buffer.
-const serve_line_cap = 1024 * 1024;
+pub const serve_line_cap = 1024 * 1024;
/// Cap on one request body (a user prompt; pasted files can be large).
const serve_body_cap = 8 * 1024 * 1024;
-
-const ServeSession = struct {
- id: [16]u8, // hex
+/// Follow poll cadence and ceiling: a reattached client waits for live events
+/// at 25ms, and gives up after ~10 minutes rather than pinning a connection.
+const follow_poll_ms = 25;
+const follow_max_polls = 10 * 60 * 1000 / follow_poll_ms;
+
+pub const ServeSession = struct {
+ name: []const u8, // gpa-owned; the HTTP id AND the graff --resume session name
+ log_path: []const u8, // gpa-owned; .graff/serve/<name>.events.jsonl
+ log: events.EventLog,
+ last_seq: u64 = 0, // highest seq forwarded/persisted; bridge-generated errors continue it
child: std.process.Child,
rdr: Io.File.Reader, // persistent reader over child stdout — must not move (gpa.create)
rbuf: []u8, // gpa-owned backing buffer for rdr
busy: Io.Mutex = .init, // one in-flight protocol request per session
+ in_flight: std.atomic.Value(bool) = .init(false), // a request is streaming: followers keep tailing
answer_mu: Io.Mutex = .init,
awaiting_answer: bool = false,
answer_call_id: [128]u8 = undefined,
answer_call_id_len: usize = 0,
};
-const ServeState = struct {
+pub const ServeState = struct {
gpa: Allocator,
io: Io,
exe: []const u8, // this binary, re-spawned as `<exe> --json …` per session
@@ -61,8 +80,8 @@ const ServeState = struct {
sessions: std.ArrayList(*ServeSession) = .empty,
group: *Io.Group, // detached reapers for closed sessions
- fn find(self: *ServeState, id: []const u8) ?*ServeSession {
- for (self.sessions.items) |s| if (std.mem.eql(u8, &s.id, id)) return s;
+ pub fn find(self: *ServeState, id: []const u8) ?*ServeSession {
+ for (self.sessions.items) |s| if (std.mem.eql(u8, s.name, id)) return s;
return null;
}
};
@@ -75,7 +94,7 @@ fn ctEql(a: []const u8, b: []const u8) bool {
return diff == 0;
}
-fn serveLog(io: Io, comptime fmt: []const u8, args: anytype) void {
+pub fn serveLog(io: Io, comptime fmt: []const u8, args: anytype) void {
var buf: [512]u8 = undefined;
var w = Io.File.stderr().writer(io, &buf);
w.interface.print(fmt ++ "\n", args) catch {};
@@ -150,7 +169,11 @@ fn serveJsonHeaders(st: *ServeState) []const std.http.Header {
return if (st.cfg.token != null) &serve_cors_headers else &serve_json_headers;
}
-fn respondJson(st: *ServeState, req: *std.http.Server.Request, status: std.http.Status, body: []const u8) !void {
+fn serveNdjsonHeaders(st: *ServeState) []const std.http.Header {
+ return if (st.cfg.token != null) &serve_ndjson_cors_headers else &serve_ndjson_headers;
+}
+
+pub fn respondJson(st: *ServeState, req: *std.http.Server.Request, status: std.http.Status, body: []const u8) !void {
// A body-less POST/DELETE (neither content-length nor transfer-encoding)
// trips an assert in std's keep-alive discardBody path — just close the
// connection for those instead.
@@ -168,12 +191,17 @@ fn serveRequest(st: *ServeState, req: *std.http.Server.Request) !void {
const target = target_buf[0..req.head.target.len];
@memcpy(target, req.head.target);
const method = req.head.method;
+ const split = events.splitTarget(target);
+ const path = split.path;
+ // #330: `?from=N` asks for persisted events with seq >= N before the live
+ // stream. Same meaning on the reattach GET and on a request POST.
+ const from_query = events.queryU64(split.query, "from");
if (method == .OPTIONS) // CORS preflight
return req.respond("", .{ .status = .no_content, .extra_headers = serveJsonHeaders(st) });
if (st.cfg.token) |tok| {
- if (!std.mem.eql(u8, target, "/healthz")) {
+ if (!std.mem.eql(u8, path, "/healthz")) {
var authed = false;
var it = req.iterateHeaders();
while (it.next()) |h| {
@@ -186,7 +214,7 @@ fn serveRequest(st: *ServeState, req: *std.http.Server.Request) !void {
}
}
- if (method == .GET and std.mem.eql(u8, target, "/healthz")) {
+ if (method == .GET and std.mem.eql(u8, path, "/healthz")) {
st.mutex.lockUncancelable(io);
const n = st.sessions.items.len;
st.mutex.unlock(io);
@@ -194,140 +222,42 @@ fn serveRequest(st: *ServeState, req: *std.http.Server.Request) !void {
const body = std.fmt.bufPrint(&buf, "{{\"ok\":true,\"harness\":\"{s}\",\"schema\":\"{s}\",\"sessions\":{d}}}", .{ harness_version, schema_version, n }) catch unreachable;
return respondJson(st, req, .ok, body);
}
- if (method == .GET and std.mem.eql(u8, target, "/v1/schema")) {
+ if (method == .GET and std.mem.eql(u8, path, "/v1/schema")) {
var aw: Io.Writer.Allocating = .init(gpa);
defer aw.deinit();
emitSchema(&aw.writer) catch return respondJson(st, req, .internal_server_error, "{\"error\":\"schema emit failed\"}");
return respondJson(st, req, .ok, aw.writer.buffered());
}
- if (method == .POST and std.mem.eql(u8, target, "/v1/sessions"))
- return serveCreate(st, req);
+ if (method == .POST and std.mem.eql(u8, path, "/v1/sessions"))
+ return serve_create.create(st, req);
const sess_prefix = "/v1/sessions/";
- if (std.mem.startsWith(u8, target, sess_prefix)) {
- const id = target[sess_prefix.len..];
- if (method == .POST) return serveMessage(st, req, id);
+ if (std.mem.startsWith(u8, path, sess_prefix)) {
+ var id = path[sess_prefix.len..];
+ const events_suffix = "/events";
+ if (method == .GET and std.mem.endsWith(u8, id, events_suffix)) {
+ id = id[0 .. id.len - events_suffix.len];
+ return serveFollow(st, req, id, from_query orelse 1);
+ }
+ if (method == .POST) return serveMessage(st, req, id, from_query);
if (method == .DELETE) return serveDelete(st, req, id);
}
return respondJson(st, req, .not_found, "{\"error\":\"not found — see /v1/schema\"}");
}
-/// POST /v1/sessions: spawn a `harness --json` child. Per-session options in
-/// the (optional) JSON body override the serve-level defaults.
-fn serveCreate(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();
- const arena = arena_state.allocator();
-
- var bbuf: [4096]u8 = undefined;
- const br = req.readerExpectContinue(&bbuf) catch return error.WriteFailed;
- const body = br.allocRemaining(arena, .limited(64 * 1024)) catch
- return respondJson(st, req, .payload_too_large, "{\"error\":\"body too large\"}");
-
- var model = st.cfg.model;
- var subagent_provider = st.cfg.subagent_provider;
- var subagent_model = st.cfg.subagent_model;
- var allow_cross_provider_subagents = st.cfg.allow_cross_provider_subagents;
- var yolo = st.cfg.yolo;
- var sys = st.cfg.system_prompt;
- var append_sys = st.cfg.append_system_prompt;
- var max_tools = st.cfg.max_tool_calls;
- var max_models: ?u64 = st.cfg.max_model_calls;
- var dedupe_tools = st.cfg.dedupe_tool_calls;
- if (std.mem.trim(u8, body, " \t\r\n").len > 0) {
- const v = std.json.parseFromSliceLeaky(Value, arena, body, .{ .allocate = .alloc_always }) catch
- return respondJson(st, req, .bad_request, "{\"error\":\"body must be a JSON object\"}");
- if (v != .object) return respondJson(st, req, .bad_request, "{\"error\":\"body must be a JSON object\"}");
- if (v.object.get("model")) |m| if (m == .string) {
- model = m.string;
- };
- if (v.object.get("subagentModel") orelse v.object.get("subagent_model")) |m| if (m == .string) {
- subagent_model = m.string;
- };
- if (v.object.get("subagentProvider") orelse v.object.get("subagent_provider")) |p| if (p == .string) {
- subagent_provider = p.string;
- };
- if (v.object.get("allowCrossProviderSubagents") orelse v.object.get("allow_cross_provider_subagents")) |a| if (a == .bool) {
- allow_cross_provider_subagents = a.bool;
- };
- if (v.object.get("yolo")) |y| if (y == .bool) {
- yolo = y.bool;
- };
- if (v.object.get("system_prompt")) |s| if (s == .string) {
- sys = s.string;
- };
- if (v.object.get("append_system_prompt")) |s| if (s == .string) {
- append_sys = s.string;
- };
- if (v.object.get("maxToolCalls") orelse v.object.get("max_tool_calls")) |m| if (m == .integer and m.integer >= 0) {
- max_tools = @intCast(m.integer);
- };
- if (v.object.get("maxModelCalls") orelse v.object.get("max_model_calls")) |m| if (m == .integer and m.integer >= 0) {
- max_models = @intCast(m.integer);
- };
- if (v.object.get("dedupeToolCalls") orelse v.object.get("dedupe_tool_calls")) |d| if (d == .bool) {
- dedupe_tools = d.bool;
- };
- }
-
- var argv: std.ArrayList([]const u8) = .empty;
- try argv.appendSlice(arena, &.{ st.exe, "--json" });
- if (yolo) try argv.append(arena, "--yolo");
- if (model) |m| try argv.appendSlice(arena, &.{ "--model", m });
- if (subagent_provider) |p| try argv.appendSlice(arena, &.{ "--subagent-provider", p });
- if (subagent_model) |m| try argv.appendSlice(arena, &.{ "--subagent-model", m });
- if (allow_cross_provider_subagents) try argv.append(arena, "--allow-cross-provider-subagents");
- if (max_tools) |n| try argv.appendSlice(arena, &.{ "--max-tool-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });
- if (max_models) |n| try argv.appendSlice(arena, &.{ "--max-model-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });
- if (dedupe_tools) try argv.append(arena, "--dedupe-tool-calls");
- if (sys) |s| try argv.appendSlice(arena, &.{ "--system-prompt", s });
- if (append_sys) |s| try argv.appendSlice(arena, &.{ "--append-system-prompt", s });
-
- var child = std.process.spawn(io, .{
- .argv = argv.items,
- .stdin = .pipe,
- .stdout = .pipe,
- .stderr = .inherit, // tool progress → the server's terminal
- }) catch return respondJson(st, req, .internal_server_error, "{\"error\":\"failed to spawn harness child\"}");
-
- const rbuf = gpa.alloc(u8, serve_line_cap) catch {
- child.kill(io);
- return error.WriteFailed;
- };
- const sess = gpa.create(ServeSession) catch {
- gpa.free(rbuf);
- child.kill(io);
- return error.WriteFailed;
- };
- var raw: [8]u8 = undefined;
- io.random(&raw);
- sess.* = .{ .id = undefined, .child = child, .rdr = undefined, .rbuf = rbuf };
- _ = std.fmt.bufPrint(&sess.id, "{x:0>16}", .{std.mem.readInt(u64, &raw, .big)}) catch unreachable;
- sess.rdr = sess.child.stdout.?.readerStreaming(io, sess.rbuf);
-
- st.mutex.lockUncancelable(io);
- const appended = blk: {
- st.sessions.append(gpa, sess) catch break :blk false;
- break :blk true;
- };
- st.mutex.unlock(io);
- if (!appended) {
- sess.child.kill(io);
- gpa.free(sess.rbuf);
- gpa.destroy(sess);
- return error.WriteFailed;
- }
- serveLog(io, "serve: session {s} created (model={s} yolo={})", .{ &sess.id, model orelse "default", yolo });
- var obuf: [64]u8 = undefined;
- const out = std.fmt.bufPrint(&obuf, "{{\"session_id\":\"{s}\"}}", .{&sess.id}) catch unreachable;
- return respondJson(st, req, .created, out);
+pub fn freeSession(st: *ServeState, sess: *ServeSession) void {
+ sess.log.close();
+ st.gpa.free(sess.rbuf);
+ st.gpa.free(sess.name);
+ st.gpa.free(sess.log_path);
+ st.gpa.destroy(sess);
}
/// POST /v1/sessions/<id>: forward one protocol request line to the child and
/// stream its stdout events back as chunked NDJSON until the terminal event
/// for that request (turn/error for user turns; system_prompt/score acks).
-fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8) !void {
+/// `?from=N` (or `"resume_from": N` in the body) replays persisted events with
+/// seq >= N first, so a reconnecting supervisor never has a hole.
+fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8, from_query: ?u64) !void {
const io = st.io;
const gpa = st.gpa;
var arena_state = std.heap.ArenaAllocator.init(gpa);
@@ -349,8 +279,14 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8)
if (parsed != .object or std.mem.indexOfScalar(u8, line, '\n') != null)
return respondJson(st, req, .bad_request, "{\"error\":\"body must be a single-line JSON object\"}");
+ const from = from_query orelse blk: {
+ const v = parsed.object.get("resume_from") orelse break :blk null;
+ break :blk if (v == .integer and v.integer > 0) @as(u64, @intCast(v.integer)) else null;
+ };
const rtype = if (parsed.object.get("type")) |v| (if (v == .string) v.string else "") else "";
if (std.mem.eql(u8, rtype, "answer")) return serveAnswer(st, req, s, line, parsed.object);
+ // A pure reconnect: replay + tail, send nothing new to the child.
+ if (std.mem.eql(u8, rtype, "reattach")) return serveFollow(st, req, id, from orelse 1);
s.busy.lockUncancelable(io); // serialize requests per session
defer s.busy.unlock(io);
@@ -365,41 +301,127 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8)
var stream_buf: [16 * 1024]u8 = undefined;
var bw = req.respondStreaming(&stream_buf, .{
- .respond_options = .{
- .extra_headers = if (st.cfg.token != null) &serve_ndjson_cors_headers else &serve_ndjson_headers,
- },
+ .respond_options = .{ .extra_headers = serveNdjsonHeaders(st) },
}) catch return error.WriteFailed;
+ // Replayed events all predate the request we just sent, so the client sees
+ // one ordered, gap-free sequence: the tail it missed, then the live turn.
+ var client_alive = true;
+ if (from) |n| {
+ if (Io.Dir.cwd().readFileAlloc(io, s.log_path, arena, .limited(events.max_log_bytes))) |data| {
+ _ = events.replay(&bw.writer, data, n) catch {
+ client_alive = false;
+ };
+ bw.flush() catch {
+ client_alive = false;
+ };
+ } else |_| {}
+ }
+
+ s.in_flight.store(true, .release);
+ defer s.in_flight.store(false, .release);
while (true) {
const ev_line = s.rdr.interface.takeDelimiter('\n') catch |err| switch (err) {
- error.StreamTooLong => {
- bw.writer.writeAll("{\"type\":\"error\",\"message\":\"event line exceeded the 1 MiB serve cap — session closed\"}\n") catch {};
- bw.end() catch {};
- serveDrop(st, s);
- return;
- },
- error.ReadFailed => {
- bw.writer.writeAll("{\"type\":\"error\",\"message\":\"session process exited mid-request\"}\n") catch {};
- bw.end() catch {};
- serveDrop(st, s);
- return;
- },
- } orelse {
- bw.writer.writeAll("{\"type\":\"error\",\"message\":\"session process exited mid-request\"}\n") catch {};
- bw.end() catch {};
- serveDrop(st, s);
- return;
- };
+ error.StreamTooLong => return serveAbort(st, s, &bw, client_alive, "event line exceeded the 1 MiB serve cap — session closed"),
+ error.ReadFailed => return serveAbort(st, s, &bw, client_alive, "session process exited mid-request"),
+ } orelse return serveAbort(st, s, &bw, client_alive, "session process exited mid-request");
const trimmed = std.mem.trim(u8, ev_line, " \t\r");
if (trimmed.len == 0) continue;
serveUpdateAnswerState(io, s, trimmed);
- bw.writer.writeAll(trimmed) catch return;
- bw.writer.writeByte('\n') catch return;
- bw.flush() catch return; // deliver each event as it happens
- if (serveTerminalEvent(trimmed)) {
+ // Persist BEFORE the socket: the tape has to survive a client that is
+ // already gone, or a reconnect would find the run stalled at the
+ // moment the supervisor died.
+ s.log.append(trimmed);
+ if (events.seqOf(trimmed)) |q| s.last_seq = @max(s.last_seq, q);
+ if (client_alive) {
+ bw.writer.writeAll(trimmed) catch {
+ client_alive = false;
+ };
+ if (client_alive) bw.writer.writeByte('\n') catch {
+ client_alive = false;
+ };
+ if (client_alive) bw.flush() catch {
+ client_alive = false;
+ }; // deliver each event as it happens
+ }
+ if (events.terminalEvent(trimmed)) {
serveClearAnswerState(io, s);
break;
}
}
+ if (client_alive) bw.end() catch return;
+}
+
+/// The child died (or overran the line cap) mid-request: record a terminal
+/// error on the tape with the next sequence id — a reconnecting client must
+/// see the failure, not a hole — then drop the session.
+fn serveAbort(st: *ServeState, s: *ServeSession, bw: anytype, client_alive: bool, message: []const u8) 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);
+ if (client_alive) {
+ bw.writer.writeAll(line) catch {};
+ bw.writer.writeByte('\n') catch {};
+ bw.end() catch {};
+ }
+ serveDrop(st, s);
+}
+
+/// GET /v1/sessions/<id>/events?from=N (and the `{"type":"reattach"}` POST):
+/// replay the persisted tape from seq N, then keep tailing it live while a
+/// request is in flight. Takes no protocol lock and never writes to the child,
+/// so it works while another connection is mid-turn — that connection keeps
+/// draining the child into the log even after ITS socket dies.
+fn serveFollow(st: *ServeState, req: *std.http.Server.Request, id: []const u8, from: u64) !void {
+ const io = st.io;
+ const gpa = st.gpa;
+ if (!events.validName(id)) return respondJson(st, req, .bad_request, "{\"error\":\"bad session id\"}");
+ st.mutex.lockUncancelable(io);
+ const sess = st.find(id);
+ st.mutex.unlock(io);
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const log_path = if (sess) |s| s.log_path else try events.logPath(arena, id);
+ // A session this bridge never spawned is still replayable from its tape:
+ // that is exactly the supervisor-crash case.
+ if (sess == null) {
+ if (Io.Dir.cwd().statFile(io, log_path, .{})) |_| {} else |_| {
+ return respondJson(st, req, .not_found, "{\"error\":\"no such session\"}");
+ }
+ }
+
+ const buf = gpa.alloc(u8, serve_line_cap + 4096) catch return error.WriteFailed;
+ defer gpa.free(buf);
+ var follower = events.Follower.open(io, .cwd(), log_path, buf, 0);
+ defer follower.close();
+
+ var stream_buf: [16 * 1024]u8 = undefined;
+ var bw = req.respondStreaming(&stream_buf, .{
+ .respond_options = .{ .extra_headers = serveNdjsonHeaders(st) },
+ }) catch return error.WriteFailed;
+ var next_from = from;
+ var idle: usize = 0;
+ while (true) {
+ const chunk = follower.poll();
+ if (chunk.len > 0) {
+ const replayed = events.replay(&bw.writer, chunk, next_from) catch break;
+ if (replayed.emitted > 0) {
+ next_from = replayed.last_seq + 1;
+ bw.flush() catch break;
+ if (replayed.terminal) break; // the request this client was watching ended
+ }
+ idle = 0;
+ continue;
+ }
+ const s = sess orelse break; // cold replay of a dead session: tape only
+ if (!s.in_flight.load(.acquire)) break; // idle session: the tape is complete
+ idle += 1;
+ if (idle > follow_max_polls) break;
+ io.sleep(.fromMilliseconds(follow_poll_ms), .awake) catch break;
+ }
bw.end() catch return;
}
@@ -428,9 +450,9 @@ fn serveAnswer(st: *ServeState, req: *std.http.Server.Request, s: *ServeSession,
}
fn serveUpdateAnswerState(io: Io, s: *ServeSession, line: []const u8) void {
- const ty = serveStringField(line, "type") orelse return;
+ const ty = events.stringField(line, "type") orelse return;
if (!std.mem.eql(u8, ty, "ask_user")) return;
- const call_id = serveStringField(line, "call_id") orelse "";
+ const call_id = events.stringField(line, "call_id") orelse "";
s.answer_mu.lockUncancelable(io);
defer s.answer_mu.unlock(io);
const n = @min(call_id.len, s.answer_call_id.len);
@@ -439,22 +461,6 @@ fn serveUpdateAnswerState(io: Io, s: *ServeSession, line: []const u8) void {
s.awaiting_answer = true;
}
-fn serveStringField(line: []const u8, field: []const u8) ?[]const u8 {
- var needle_buf: [64]u8 = undefined;
- if (field.len + 4 > needle_buf.len) return null;
- const needle = std.fmt.bufPrint(&needle_buf, "\"{s}\":\"", .{field}) catch return null;
- const start = std.mem.indexOf(u8, line, needle) orelse return null;
- var i = start + needle.len;
- while (i < line.len) : (i += 1) {
- if (line[i] == '\\') {
- i += 1;
- continue;
- }
- if (line[i] == '"') return line[start + needle.len .. i];
- }
- return null;
-}
-
fn serveClearAnswerState(io: Io, s: *ServeSession) void {
s.answer_mu.lockUncancelable(io);
defer s.answer_mu.unlock(io);
@@ -462,36 +468,6 @@ fn serveClearAnswerState(io: Io, s: *ServeSession) void {
s.answer_call_id_len = 0;
}
-/// Is this child event line the terminal event of a protocol request?
-/// turn/error end user turns; system_prompt and score are between-turn acks.
-/// Unknown event types stream through (edge-version durability) — a newer
-/// child must still terminate every request with one of these four.
-fn serveTerminalEvent(line: []const u8) bool {
- var scratch: [4096]u8 = undefined;
- var fba = std.heap.FixedBufferAllocator.init(&scratch);
- // Only the leading "type" field matters; events put it first, so parsing
- // a truncated prefix is enough even for MiB-sized tool_result lines.
- const head = line[0..@min(line.len, 256)];
- var t: []const u8 = "";
- if (std.json.parseFromSliceLeaky(Value, fba.allocator(), line, .{})) |v| {
- if (v == .object) if (v.object.get("type")) |ty| if (ty == .string) {
- t = ty.string;
- };
- } else |_| {
- // Huge line: fall back to a prefix scan for {"type":"..."}.
- const needle = "\"type\":\"";
- if (std.mem.indexOf(u8, head, needle)) |i| {
- const rest = head[i + needle.len ..];
- if (std.mem.indexOfScalar(u8, rest, '"')) |j| t = rest[0..j];
- }
- }
- return std.mem.eql(u8, t, "turn") or std.mem.eql(u8, t, "error") or
- std.mem.eql(u8, t, "system_prompt") or std.mem.eql(u8, t, "score") or
- std.mem.eql(u8, t, "model") or std.mem.eql(u8, t, "compact") or
- std.mem.eql(u8, t, "mode") or std.mem.eql(u8, t, "agent") or
- std.mem.eql(u8, t, "effort") or std.mem.eql(u8, t, "fast");
-}
-
/// Remove a dead session and free it (child already gone or being killed).
fn serveDrop(st: *ServeState, sess: *ServeSession) void {
const io = st.io;
@@ -504,23 +480,21 @@ fn serveDrop(st: *ServeState, sess: *ServeSession) void {
}
st.mutex.unlock(io);
sess.child.kill(io); // reaps; harmless if already exited
- st.gpa.free(sess.rbuf);
- st.gpa.destroy(sess);
+ freeSession(st, sess);
}
/// 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 {
- const io = st.io;
- _ = sess.child.wait(io) catch {};
- st.gpa.free(sess.rbuf);
- st.gpa.destroy(sess);
+ _ = sess.child.wait(st.io) catch {};
+ freeSession(st, sess);
}
/// DELETE /v1/sessions/<id>: graceful close. Waits for an in-flight request
/// to finish streaming (the busy lock), then EOFs the child's stdin and
-/// reaps it in the background.
+/// reaps it in the background. The event log and the session file stay on
+/// disk: closing a session ends the process, not the run's resumability.
fn serveDelete(st: *ServeState, req: *std.http.Server.Request, id: []const u8) !void {
const io = st.io;
st.mutex.lockUncancelable(io);
@@ -552,13 +526,3 @@ test "ctEql: constant-time compare matches std.mem.eql semantics" {
try std.testing.expect(!ctEql("short", "longer-string"));
try std.testing.expect(ctEql("", ""));
}
-
-test "serveStringField: extracts a JSON string field, handles escapes and misses" {
- const line = "{\"type\":\"user\",\"text\":\"hello\"}";
- try std.testing.expectEqualStrings("user", serveStringField(line, "type").?);
- try std.testing.expectEqualStrings("hello", serveStringField(line, "text").?);
- try std.testing.expect(serveStringField(line, "missing") == null);
- // escaped quote inside the value is skipped, not treated as the terminator
- const esc = "{\"text\":\"a\\\"b\"}";
- try std.testing.expectEqualStrings("a\\\"b", serveStringField(esc, "text").?);
-}
diff --git a/src/serve_create.zig b/src/serve_create.zig
new file mode 100644
index 00000000..4c49b396
--- /dev/null
+++ b/src/serve_create.zig
@@ -0,0 +1,202 @@
+//! `POST /v1/sessions`: option parsing, the durable-session naming rules, and
+//! the child spawn. Split out of serve.zig, which is at the 600-line cap.
+//!
+//! #330: the session id IS the graff session name. The child is always spawned
+//! with `--resume <name>`, so the conversation autosaves under that name from
+//! the first turn and a REPLACEMENT bridge that posts the same name restores it
+//! instead of starting an empty one. The reply tells the client where the
+//! persisted event tape currently ends (`last_seq`) so it can reconnect with
+//! `?from=last_seq+1` without guessing.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const serve = @import("serve.zig"); // back-import: shared state + HTTP helpers
+const events = @import("serve_events.zig");
+
+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();
+ const arena = arena_state.allocator();
+
+ var bbuf: [4096]u8 = undefined;
+ 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\"}");
+
+ var model = st.cfg.model;
+ var subagent_provider = st.cfg.subagent_provider;
+ var subagent_model = st.cfg.subagent_model;
+ var allow_cross_provider_subagents = st.cfg.allow_cross_provider_subagents;
+ var yolo = st.cfg.yolo;
+ var sys = st.cfg.system_prompt;
+ var append_sys = st.cfg.append_system_prompt;
+ var max_tools = st.cfg.max_tool_calls;
+ var max_models: ?u64 = st.cfg.max_model_calls;
+ var dedupe_tools = st.cfg.dedupe_tool_calls;
+ 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\"}");
+ 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 -\"}");
+ name = n.string;
+ };
+ if (v.object.get("model")) |m| if (m == .string) {
+ model = m.string;
+ };
+ if (v.object.get("subagentModel") orelse v.object.get("subagent_model")) |m| if (m == .string) {
+ subagent_model = m.string;
+ };
+ if (v.object.get("subagentProvider") orelse v.object.get("subagent_provider")) |p| if (p == .string) {
+ subagent_provider = p.string;
+ };
+ if (v.object.get("allowCrossProviderSubagents") orelse v.object.get("allow_cross_provider_subagents")) |a| if (a == .bool) {
+ allow_cross_provider_subagents = a.bool;
+ };
+ if (v.object.get("yolo")) |y| if (y == .bool) {
+ yolo = y.bool;
+ };
+ if (v.object.get("system_prompt")) |s| if (s == .string) {
+ sys = s.string;
+ };
+ if (v.object.get("append_system_prompt")) |s| if (s == .string) {
+ append_sys = s.string;
+ };
+ if (v.object.get("maxToolCalls") orelse v.object.get("max_tool_calls")) |m| if (m == .integer and m.integer >= 0) {
+ max_tools = @intCast(m.integer);
+ };
+ if (v.object.get("maxModelCalls") orelse v.object.get("max_model_calls")) |m| if (m == .integer and m.integer >= 0) {
+ max_models = @intCast(m.integer);
+ };
+ if (v.object.get("dedupeToolCalls") orelse v.object.get("dedupe_tool_calls")) |d| if (d == .bool) {
+ dedupe_tools = d.bool;
+ };
+ }
+
+ // Attaching to a session this bridge already runs is idempotent: report it
+ // (and where its tape ends) rather than spawning a second child onto the
+ // same session file.
+ st.mutex.lockUncancelable(io);
+ 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));
+
+ const log_path = try events.logPath(arena, name);
+ const resumed = sessionOnDisk(io, arena, name);
+ const last_seq = events.lastSeqOnDisk(io, .cwd(), arena, log_path);
+
+ var argv: std.ArrayList([]const u8) = .empty;
+ // `--resume <name>` on a name with no file yet is how a session becomes
+ // durable from its very first turn: the child autosaves under that name.
+ try argv.appendSlice(arena, &.{ st.exe, "--json", "--resume", name });
+ if (yolo) try argv.append(arena, "--yolo");
+ if (model) |m| try argv.appendSlice(arena, &.{ "--model", m });
+ if (subagent_provider) |p| try argv.appendSlice(arena, &.{ "--subagent-provider", p });
+ if (subagent_model) |m| try argv.appendSlice(arena, &.{ "--subagent-model", m });
+ if (allow_cross_provider_subagents) try argv.append(arena, "--allow-cross-provider-subagents");
+ if (max_tools) |n| try argv.appendSlice(arena, &.{ "--max-tool-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });
+ if (max_models) |n| try argv.appendSlice(arena, &.{ "--max-model-calls", try std.fmt.allocPrint(arena, "{d}", .{n}) });
+ if (dedupe_tools) try argv.append(arena, "--dedupe-tool-calls");
+ if (sys) |s| try argv.appendSlice(arena, &.{ "--system-prompt", s });
+ if (append_sys) |s| try argv.appendSlice(arena, &.{ "--append-system-prompt", s });
+
+ var child = std.process.spawn(io, .{
+ .argv = argv.items,
+ .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\"}");
+
+ const sess = newSession(st, &child, name, log_path, last_seq) catch {
+ child.kill(io);
+ return error.WriteFailed;
+ };
+
+ st.mutex.lockUncancelable(io);
+ const appended = blk: {
+ st.sessions.append(gpa, sess) catch break :blk false;
+ break :blk true;
+ };
+ st.mutex.unlock(io);
+ if (!appended) {
+ sess.child.kill(io);
+ serve.freeSession(st, sess);
+ return error.WriteFailed;
+ }
+ 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));
+}
+
+fn createdBody(arena: Allocator, name: []const u8, resumed: bool, last_seq: u64) ![]const u8 {
+ return std.fmt.allocPrint(arena, "{{\"session_id\":\"{s}\",\"resumed\":{},\"last_seq\":{d}}}", .{ name, resumed, last_seq });
+}
+
+fn newSessionName(io: Io, arena: Allocator) ![]const u8 {
+ var raw: [8]u8 = undefined;
+ io.random(&raw);
+ return std.fmt.allocPrint(arena, "{x:0>16}", .{std.mem.readInt(u64, &raw, .big)});
+}
+
+fn sessionOnDisk(io: Io, arena: Allocator, name: []const u8) bool {
+ const path = std.fmt.allocPrint(arena, ".graff/sessions/{s}.session.json", .{name}) catch return false;
+ if (Io.Dir.cwd().statFile(io, path, .{})) |_| return true else |_| return false;
+}
+
+/// Allocate the per-session state (all gpa-owned so it outlives the request
+/// arena) and open its durable event log.
+fn newSession(st: *ServeState, child: *std.process.Child, name: []const u8, log_path: []const u8, last_seq: u64) !*ServeSession {
+ const gpa = st.gpa;
+ const rbuf = try gpa.alloc(u8, serve.serve_line_cap);
+ errdefer gpa.free(rbuf);
+ const owned_name = try gpa.dupe(u8, name);
+ errdefer gpa.free(owned_name);
+ const owned_path = try gpa.dupe(u8, log_path);
+ errdefer gpa.free(owned_path);
+ const sess = try gpa.create(ServeSession);
+ sess.* = .{
+ .name = owned_name,
+ .log_path = owned_path,
+ .log = events.EventLog.open(st.io, .cwd(), owned_path),
+ .last_seq = last_seq,
+ .child = child.*,
+ .rdr = undefined,
+ .rbuf = rbuf,
+ };
+ sess.rdr = sess.child.stdout.?.readerStreaming(st.io, sess.rbuf);
+ return sess;
+}
+
+test "createdBody reports the durable id, whether it resumed, and the tape end (#330)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ try std.testing.expectEqualStrings(
+ "{\"session_id\":\"nightly\",\"resumed\":true,\"last_seq\":42}",
+ try createdBody(arena, "nightly", true, 42),
+ );
+ try std.testing.expectEqualStrings(
+ "{\"session_id\":\"00ff\",\"resumed\":false,\"last_seq\":0}",
+ try createdBody(arena, "00ff", false, 0),
+ );
+}
+
+test "a generated session name is a valid durable id" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const name = try newSessionName(std.testing.io, arena_state.allocator());
+ try std.testing.expectEqual(@as(usize, 16), name.len);
+ try std.testing.expect(events.validName(name)); // usable as a path AND a URL segment
+}
diff --git a/src/serve_events.zig b/src/serve_events.zig
new file mode 100644
index 00000000..9abc3c47
--- /dev/null
+++ b/src/serve_events.zig
@@ -0,0 +1,347 @@
+//! The durable side of `graff serve` (#330 part 2): a per-session append-only
+//! log of the exact protocol event lines the bridge forwarded, plus the replay
+//! filter and the line helpers serve.zig reads events with.
+//!
+//! Why a second file rather than the existing `.graff/traces/<run>.jsonl`: the
+//! trace stream is per-PROCESS performance telemetry keyed by run id, and it
+//! does not contain protocol events at all — nothing in it can reconstruct the
+//! `--json` stream a supervisor lost. The conversation itself is NOT duplicated
+//! here; that stays in `.graff/sessions/<name>.session.json`, which the child
+//! already autosaves after every turn and `--resume <name>` already restores.
+//! This log is only the event tape, keyed by the same session name, so a
+//! REPLACEMENT serve process appends to the very file the dead one was writing
+//! and `?from=N` keeps meaning the same thing across the process boundary.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const protocol_seq = @import("protocol_seq.zig");
+
+pub const serve_dir = ".graff/serve";
+/// The producer stamps `seq`; the bridge only reads it back off the line.
+pub const seqOf = protocol_seq.seqOf;
+/// Cap on a whole event log we are willing to slurp for a cold replay. Well
+/// past a realistic session; a bigger file replays nothing rather than trying
+/// to buy the memory.
+pub const max_log_bytes = 64 * 1024 * 1024;
+
+pub fn logPath(allocator: Allocator, name: []const u8) Allocator.Error![]const u8 {
+ return std.fmt.allocPrint(allocator, "{s}/{s}.events.jsonl", .{ serve_dir, name });
+}
+
+/// A session name is both a URL path segment and a file name, so it is
+/// restricted to characters that are unambiguous in both and can never walk
+/// out of `.graff/`.
+pub fn validName(name: []const u8) bool {
+ if (name.len == 0 or name.len > 64) return false;
+ if (name[0] == '.' or name[0] == '-') return false;
+ for (name) |c| {
+ const ok = (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or
+ (c >= '0' and c <= '9') or c == '-' or c == '_' or c == '.';
+ if (!ok) return false;
+ }
+ return true;
+}
+
+/// Append-only writer for one live session. Best-effort throughout: losing the
+/// log degrades resumability, it must never fail a turn. On any write error the
+/// file is dropped rather than kept at a drifted offset (#242's lesson: a
+/// swallowed short write silently corrupts every later record).
+pub const EventLog = struct {
+ io: Io,
+ file: ?Io.File = null,
+ offset: u64 = 0,
+
+ pub fn open(io: Io, dir: Io.Dir, path: []const u8) EventLog {
+ if (std.fs.path.dirname(path)) |parent| dir.createDirPath(io, parent) catch {};
+ const file = dir.createFile(io, path, .{ .truncate = false }) catch return .{ .io = io };
+ const size: u64 = if (file.stat(io)) |st| st.size else |_| 0;
+ return .{ .io = io, .file = file, .offset = size };
+ }
+
+ pub fn close(self: *EventLog) void {
+ if (self.file) |f| f.close(self.io);
+ self.file = null;
+ }
+
+ /// Persist one event line (without its newline; this adds it).
+ pub fn append(self: *EventLog, line: []const u8) void {
+ const file = self.file orelse return;
+ file.writePositionalAll(self.io, line, self.offset) catch return self.close();
+ self.offset += line.len;
+ file.writePositionalAll(self.io, "\n", self.offset) catch return self.close();
+ self.offset += 1;
+ }
+};
+
+/// Highest `seq` persisted in `data`. 0 when the log is empty or unstamped.
+/// Only COMPLETE (newline-terminated) lines count: a half-written tail is a
+/// mid-append artifact, and reporting its id as the end of the tape would tell
+/// a reconnecting client to skip past an event it never received.
+pub fn lastSeqOf(data: []const u8) u64 {
+ var high: u64 = 0;
+ 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;
+ if (protocol_seq.seqOf(line)) |s| high = @max(high, s);
+ }
+ return high;
+}
+
+/// Highest `seq` already on disk for `name`, so a fresh bridge can tell a
+/// client where the tape ends before it reconnects.
+pub fn lastSeqOnDisk(io: Io, dir: Io.Dir, gpa: Allocator, path: []const u8) u64 {
+ const data = dir.readFileAlloc(io, path, gpa, .limited(max_log_bytes)) catch return 0;
+ defer gpa.free(data);
+ return lastSeqOf(data);
+}
+
+pub const Replayed = struct {
+ /// Lines written to the sink.
+ emitted: usize = 0,
+ /// Highest seq written; 0 when nothing matched.
+ last_seq: u64 = 0,
+ /// The last line written terminates a protocol request.
+ terminal: bool = false,
+};
+
+/// Write every COMPLETE line of `data` whose stamped seq is >= `from`.
+///
+/// A trailing partial line (the producer is mid-append) is deliberately not
+/// written — the caller polls again once its newline lands, which is what makes
+/// duplicate-free tailing possible. Unstamped lines are skipped rather than
+/// guessed at, so replay can never invent a position. CRLF tolerant.
+pub fn replay(w: *Io.Writer, data: []const u8, from: u64) !Replayed {
+ var out: Replayed = .{};
+ var rest = data;
+ while (std.mem.indexOfScalar(u8, rest, '\n')) |nl| {
+ const raw = rest[0..nl];
+ rest = rest[nl + 1 ..];
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0) continue;
+ const seq = protocol_seq.seqOf(line) orelse continue;
+ if (seq < from) continue;
+ try w.writeAll(line);
+ try w.writeByte('\n');
+ out.emitted += 1;
+ out.last_seq = seq;
+ out.terminal = terminalEvent(line);
+ }
+ return out;
+}
+
+/// Streams complete lines appended to a log by ANOTHER writer (the in-flight
+/// request, possibly in this process, possibly not). Stateless about partial
+/// lines: the file offset only ever advances past a newline, so a line that is
+/// still being written is simply re-read on the next poll.
+pub const Follower = struct {
+ io: Io,
+ file: ?Io.File = null,
+ offset: u64 = 0,
+ buf: []u8,
+
+ pub fn open(io: Io, dir: Io.Dir, path: []const u8, buf: []u8, from_offset: u64) Follower {
+ const file = dir.openFile(io, path, .{}) catch return .{ .io = io, .buf = buf };
+ return .{ .io = io, .file = file, .buf = buf, .offset = from_offset };
+ }
+
+ pub fn close(self: *Follower) void {
+ if (self.file) |f| f.close(self.io);
+ self.file = null;
+ }
+
+ /// Bytes ending at the last complete line, or "" when nothing new landed.
+ pub fn poll(self: *Follower) []const u8 {
+ const file = self.file orelse return "";
+ const size = (file.stat(self.io) catch return "").size;
+ if (size <= self.offset) return "";
+ const want: usize = @intCast(@min(@as(u64, self.buf.len), size - self.offset));
+ const got = file.readPositionalAll(self.io, self.buf[0..want], self.offset) catch return "";
+ const chunk = self.buf[0..got];
+ const last_nl = std.mem.lastIndexOfScalar(u8, chunk, '\n') orelse return "";
+ self.offset += last_nl + 1;
+ return chunk[0 .. last_nl + 1];
+ }
+};
+
+/// Is this child event line the terminal event of a protocol request?
+/// turn/error end user turns; the rest are between-turn acks. Unknown event
+/// types stream through (edge-version durability) — a newer child must still
+/// terminate every request with one of these.
+pub fn terminalEvent(line: []const u8) bool {
+ const t = stringField(line, "type") orelse "";
+ return std.mem.eql(u8, t, "turn") or std.mem.eql(u8, t, "error") or
+ std.mem.eql(u8, t, "system_prompt") or std.mem.eql(u8, t, "score") or
+ std.mem.eql(u8, t, "model") or std.mem.eql(u8, t, "compact") or
+ std.mem.eql(u8, t, "mode") or std.mem.eql(u8, t, "agent") or
+ std.mem.eql(u8, t, "effort") or std.mem.eql(u8, t, "fast");
+}
+
+/// Pull a JSON string field out of an event line by scanning, not parsing:
+/// `type` sits in the envelope, so this stays O(1) on a MiB-sized tool_result.
+pub fn stringField(line: []const u8, field: []const u8) ?[]const u8 {
+ var needle_buf: [64]u8 = undefined;
+ if (field.len + 4 > needle_buf.len) return null;
+ const needle = std.fmt.bufPrint(&needle_buf, "\"{s}\":\"", .{field}) catch return null;
+ const start = std.mem.indexOf(u8, line, needle) orelse return null;
+ var i = start + needle.len;
+ while (i < line.len) : (i += 1) {
+ if (line[i] == '\\') {
+ i += 1;
+ continue;
+ }
+ if (line[i] == '"') return line[start + needle.len .. i];
+ }
+ return null;
+}
+
+/// `from` out of a request target's query string (`/v1/…?from=12&x=y`).
+pub fn queryU64(query: []const u8, key: []const u8) ?u64 {
+ var it = std.mem.splitAny(u8, query, "&;");
+ while (it.next()) |pair| {
+ const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
+ if (!std.mem.eql(u8, pair[0..eq], key)) continue;
+ return std.fmt.parseInt(u64, pair[eq + 1 ..], 10) catch null;
+ }
+ return null;
+}
+
+/// Split a request target into path and query. No query -> "".
+pub fn splitTarget(target: []const u8) struct { path: []const u8, query: []const u8 } {
+ const q = std.mem.indexOfScalar(u8, target, '?') orelse return .{ .path = target, .query = "" };
+ return .{ .path = target[0..q], .query = target[q + 1 ..] };
+}
+
+const testing = std.testing;
+
+test "replay: from=N is inclusive, gap-free, and never duplicates" {
+ const log =
+ "{\"seq\":1,\"type\":\"started\"}\n" ++
+ "{\"seq\":2,\"type\":\"text\",\"text\":\"a\"}\n" ++
+ "{\"seq\":3,\"type\":\"text\",\"text\":\"b\"}\n" ++
+ "{\"seq\":4,\"type\":\"turn\",\"text\":\"done\"}\n";
+ var buf: [1024]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ const all = try replay(&w, log, 1);
+ try testing.expectEqual(@as(usize, 4), all.emitted);
+ try testing.expectEqual(@as(u64, 4), all.last_seq);
+ try testing.expect(all.terminal); // the turn event closes the request
+ try testing.expectEqualStrings(log, w.buffered());
+
+ var buf2: [1024]u8 = undefined;
+ var w2: Io.Writer = .fixed(&buf2);
+ const tail = try replay(&w2, log, 3);
+ try testing.expectEqual(@as(usize, 2), tail.emitted);
+ try testing.expect(std.mem.startsWith(u8, w2.buffered(), "{\"seq\":3,"));
+ try testing.expect(std.mem.indexOf(u8, w2.buffered(), "\"seq\":2") == null);
+
+ // Past the end: nothing replayed, and nothing invented.
+ var buf3: [64]u8 = undefined;
+ var w3: Io.Writer = .fixed(&buf3);
+ const none = try replay(&w3, log, 99);
+ try testing.expectEqual(@as(usize, 0), none.emitted);
+ try testing.expectEqual(@as(u64, 0), none.last_seq);
+ try testing.expect(!none.terminal);
+ try testing.expectEqual(@as(usize, 0), w3.buffered().len);
+}
+
+test "replay: holds back a partial line, tolerates CRLF and unstamped noise" {
+ // The producer is mid-append: the last line has no newline yet.
+ const log = "{\"seq\":1,\"type\":\"text\"}\r\n\r\n{\"type\":\"error\"}\n{\"seq\":2,\"type\":\"tur";
+ var buf: [512]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ const got = try replay(&w, log, 1);
+ try testing.expectEqual(@as(usize, 1), got.emitted); // seq 2 is still partial
+ try testing.expectEqual(@as(u64, 1), got.last_seq);
+ // CR stripped, blank line skipped, unstamped line skipped rather than guessed.
+ try testing.expectEqualStrings("{\"seq\":1,\"type\":\"text\"}\n", w.buffered());
+ try testing.expectEqual(@as(u64, 1), lastSeqOf(log));
+}
+
+test "lastSeqOf reads the high-water mark of a log" {
+ try testing.expectEqual(@as(u64, 0), lastSeqOf(""));
+ try testing.expectEqual(@as(u64, 0), lastSeqOf("{\"type\":\"text\"}\n"));
+ try testing.expectEqual(@as(u64, 7), lastSeqOf("{\"seq\":5,\"type\":\"a\"}\n{\"seq\":7,\"type\":\"b\"}\n"));
+}
+
+test "validName keeps a session name inside .graff and inside one URL segment" {
+ try testing.expect(validName("a1b2c3d4e5f60718"));
+ try testing.expect(validName("nightly_run-2"));
+ try testing.expect(!validName(""));
+ try testing.expect(!validName("../../etc/passwd"));
+ try testing.expect(!validName(".hidden"));
+ try testing.expect(!validName("has space"));
+ try testing.expect(!validName("slash/inside"));
+ var long: [65]u8 = undefined;
+ @memset(&long, 'a');
+ try testing.expect(!validName(&long));
+}
+
+test "queryU64 + splitTarget: ?from=N off a request target" {
+ const split = splitTarget("/v1/sessions/abc/events?from=12&x=y");
+ try testing.expectEqualStrings("/v1/sessions/abc/events", split.path);
+ try testing.expectEqual(@as(u64, 12), queryU64(split.query, "from").?);
+ try testing.expect(queryU64(split.query, "missing") == null);
+ const bare = splitTarget("/healthz");
+ try testing.expectEqualStrings("/healthz", bare.path);
+ try testing.expectEqualStrings("", bare.query);
+ try testing.expect(queryU64(bare.query, "from") == null);
+ try testing.expect(queryU64("from=notanumber", "from") == null);
+}
+
+test "terminalEvent + stringField: envelope reads survive a seq prefix" {
+ try testing.expect(terminalEvent("{\"seq\":9,\"type\":\"turn\",\"text\":\"x\"}"));
+ try testing.expect(terminalEvent("{\"seq\":9,\"type\":\"error\",\"message\":\"x\"}"));
+ try testing.expect(!terminalEvent("{\"seq\":9,\"type\":\"text\",\"text\":\"x\"}"));
+ try testing.expect(!terminalEvent("{\"seq\":9,\"type\":\"tool_call\",\"name\":\"bash\"}"));
+ try testing.expectEqualStrings("turn", stringField("{\"seq\":1,\"type\":\"turn\"}", "type").?);
+ try testing.expect(stringField("{\"seq\":1,\"type\":\"turn\"}", "missing") == null);
+ // escaped quote inside the value is skipped, not treated as the terminator
+ try testing.expectEqualStrings("a\\\"b", stringField("{\"text\":\"a\\\"b\"}", "text").?);
+}
+
+test "EventLog + Follower: appended lines tail without gaps or duplicates" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ // Exactly the path serve builds, including the .graff/serve/ chain the
+ // writer has to create for itself on a cold workspace.
+ const path = try logPath(testing.allocator, "run-1");
+ defer testing.allocator.free(path);
+
+ var log = EventLog.open(io, tmp.dir, path);
+ defer log.close();
+ log.append("{\"seq\":1,\"type\":\"started\"}");
+ log.append("{\"seq\":2,\"type\":\"text\",\"text\":\"a\"}");
+
+ var buf: [4096]u8 = undefined;
+ var follower = Follower.open(io, tmp.dir, path, &buf, 0);
+ defer follower.close();
+ var out: [4096]u8 = undefined;
+ var w: Io.Writer = .fixed(&out);
+ const first = try replay(&w, follower.poll(), 1);
+ try testing.expectEqual(@as(usize, 2), first.emitted);
+ try testing.expect(!first.terminal);
+
+ // Nothing new: the follower yields nothing rather than replaying itself.
+ try testing.expectEqualStrings("", follower.poll());
+
+ log.append("{\"seq\":3,\"type\":\"turn\",\"text\":\"done\"}");
+ var out2: [4096]u8 = undefined;
+ var w2: Io.Writer = .fixed(&out2);
+ const second = try replay(&w2, follower.poll(), 1);
+ try testing.expectEqual(@as(usize, 1), second.emitted);
+ try testing.expectEqual(@as(u64, 3), second.last_seq);
+ try testing.expect(second.terminal);
+
+ // A second process re-opening the same log appends past the tape, and the
+ // on-disk high-water mark is what a fresh bridge reports to its client.
+ var reopened = EventLog.open(io, tmp.dir, path);
+ defer reopened.close();
+ try testing.expectEqual(@as(u64, 3), lastSeqOnDisk(io, tmp.dir, testing.allocator, path));
+ reopened.append("{\"seq\":4,\"type\":\"started\"}");
+ try testing.expectEqual(@as(u64, 4), lastSeqOnDisk(io, tmp.dir, testing.allocator, path));
+}
diff --git a/src/session.zig b/src/session.zig
index f23e3134..c62ec41e 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -19,108 +19,24 @@ const provider_mod = @import("provider.zig");
const util = @import("util.zig");
const goal_state = @import("goal_state.zig");
const session_lock = @import("session_lock.zig"); // the locked write path (#289)
+const protocol_seq = @import("protocol_seq.zig"); // #330: the --json event sequence survives a resume
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
const unixMs = util.unixMs;
const utf8Prefix = util.utf8Prefix;
-pub const session_ext = ".session.json";
-const sessions_dir = ".graff/sessions"; // title-named session files live here (resume reads this)
-
-/// Path to a session file: .graff/sessions/<name>.session.json.
-pub fn sessionPath(arena: Allocator, name: []const u8) ![]const u8 {
- return std.fmt.allocPrint(arena, "{s}/{s}{s}", .{ sessions_dir, name, session_ext });
-}
-
-/// Session-list metadata peeked from a session file WITHOUT parsing the
-/// (potentially multi-MB) messages array: saveSession writes "title" and
-/// "updated_ms" before "messages", so parsing the header slice alone is
-/// enough. Zero-value fields when the file predates them or the header
-/// can't be read — callers fall back to the raw session name (#109).
-pub const SessionMeta = struct { title: ?[]const u8 = null, updated_ms: i64 = 0 };
-
-pub fn sessionMetaFromBytes(arena: Allocator, data: []const u8) SessionMeta {
- // Embedded quotes inside string values are escaped in the file, so the
- // raw needle can only match the real top-level "messages" key.
- const idx = std.mem.indexOf(u8, data, "\"messages\":") orelse return .{};
- const header = std.mem.trimEnd(u8, data[0..idx], " \t\r\n");
- if (header.len < 2 or header[header.len - 1] != ',') return .{};
- const hjson = std.fmt.allocPrint(arena, "{s}}}", .{header[0 .. header.len - 1]}) catch return .{};
- const parsed = std.json.parseFromSliceLeaky(Value, arena, hjson, .{ .allocate = .alloc_always }) catch return .{};
- if (parsed != .object) return .{};
- return .{
- .title = if (parsed.object.get("title")) |v| (if (v == .string and v.string.len > 0) v.string else null) else null,
- .updated_ms = if (parsed.object.get("updated_ms")) |v| (if (v == .integer) v.integer else 0) else 0,
- };
-}
-
-pub fn sessionMeta(root: *Agent, arena: Allocator, base: []const u8) SessionMeta {
- const path = sessionPath(arena, base) catch return .{};
- const data = Io.Dir.cwd().readFileAlloc(root.io, path, arena, .limited(8 * 1024 * 1024)) catch return .{};
- return sessionMetaFromBytes(arena, data);
-}
-
-/// "3m ago"-style age for the session lists; "" when the timestamp is missing.
-pub fn sessionAge(arena: Allocator, io: Io, then_ms: i64) []const u8 {
- if (then_ms <= 0) return "";
- const s = @divTrunc(unixMs(io) - then_ms, 1000);
- if (s < 60) return "just now";
- if (s < 3600) return std.fmt.allocPrint(arena, "{d}m ago", .{@divTrunc(s, 60)}) catch "";
- if (s < 86_400) return std.fmt.allocPrint(arena, "{d}h ago", .{@divTrunc(s, 3600)}) catch "";
- return std.fmt.allocPrint(arena, "{d}d ago", .{@divTrunc(s, 86_400)}) catch "";
-}
-
-/// One row per saved session for the /resume picker and /sessions list:
-/// newest first, keyed (and resumed) by the file base name.
-pub const SessionEntry = struct { base: []const u8, title: ?[]const u8 = null, updated_ms: i64 = 0 };
-
-pub fn listSavedSessions(root: *Agent, arena: Allocator) std.ArrayList(SessionEntry) {
- var entries: std.ArrayList(SessionEntry) = .empty;
- var dir = Io.Dir.cwd().openDir(root.io, sessions_dir, .{ .iterate = true }) catch return entries;
- defer dir.close(root.io);
- var it = dir.iterate();
- while (it.next(root.io) catch null) |entry| {
- if (entry.kind != .file) continue;
- if (!std.mem.endsWith(u8, entry.name, session_ext)) continue;
- const base = arena.dupe(u8, entry.name[0 .. entry.name.len - session_ext.len]) catch continue;
- const meta = sessionMeta(root, arena, base);
- entries.append(arena, .{ .base = base, .title = meta.title, .updated_ms = meta.updated_ms }) catch {};
- }
- std.mem.sort(SessionEntry, entries.items, {}, struct {
- fn newerFirst(_: void, a: SessionEntry, b: SessionEntry) bool {
- return a.updated_ms > b.updated_ms;
- }
- }.newerFirst);
- return entries;
-}
-
-test "sessionMetaFromBytes reads title + updated_ms from the header only" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const arena = arena_state.allocator();
- const meta = sessionMetaFromBytes(arena,
- \\{"provider":"codegraff","model":"glm-5.2","strict":false,"ultracode_mode":false,"goal":null,"title":"Fix \"login\" bug","updated_ms":1782294417239,"messages":[{"role":"user","content":"hi"}]}
- );
- try std.testing.expectEqualStrings("Fix \"login\" bug", meta.title.?);
- try std.testing.expectEqual(@as(i64, 1782294417239), meta.updated_ms);
-}
-
-test "sessionMetaFromBytes falls back cleanly on legacy/invalid headers" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const arena = arena_state.allocator();
- const legacy = sessionMetaFromBytes(arena,
- \\{"provider":"kimi","model":"k3","strict":false,"messages":[]}
- );
- try std.testing.expect(legacy.title == null);
- try std.testing.expectEqual(@as(i64, 0), legacy.updated_ms);
- const tricky = sessionMetaFromBytes(arena,
- \\{"provider":"x","model":"y","goal":"say \"messages\": then stop","title":"T","updated_ms":5,"messages":[]}
- );
- try std.testing.expectEqualStrings("T", tricky.title.?);
- try std.testing.expectEqual(@as(i64, 5), tricky.updated_ms);
- try std.testing.expect(sessionMetaFromBytes(arena, "not json").title == null);
-}
+// The session INDEX (paths + the /sessions listing) lives in session_index.zig
+// so this file stays under the 600-line cap. Re-exported: callers keep using
+// `session.sessionPath`, `session.listSavedSessions`, and friends.
+const session_index = @import("session_index.zig");
+pub const session_ext = session_index.session_ext;
+pub const sessionPath = session_index.sessionPath;
+pub const SessionMeta = session_index.SessionMeta;
+pub const sessionMetaFromBytes = session_index.sessionMetaFromBytes;
+pub const sessionMeta = session_index.sessionMeta;
+pub const sessionAge = session_index.sessionAge;
+pub const SessionEntry = session_index.SessionEntry;
+pub const listSavedSessions = session_index.listSavedSessions;
/// Filesystem-safe slug of an AI title: lowercase alnum, any other run collapses
/// to one '-', trimmed, capped at 60. "Fixing the login bug" -> "fixing-the-login-bug".
@@ -285,6 +201,11 @@ pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {
// this component with today's prompt/tool-schema estimate.
try s.objectField("context_local_tokens");
try s.write(@min(context_estimate.local, @as(u64, std.math.maxInt(i64))));
+ // #330: the --json protocol sequence high-water mark. A REPLACEMENT graff
+ // resuming this session continues the numbering from here instead of
+ // reissuing ids the supervisor has already read off the event log.
+ try s.objectField("event_seq");
+ try s.write(@min(protocol_seq.current(), @as(u64, std.math.maxInt(i64))));
try s.endObject();
// #289: two graffs in one workspace share this file — writeSession makes the
@@ -384,6 +305,14 @@ fn contextTokensFromSession(obj: std.json.ObjectMap) u64 {
return @intCast(v.integer);
}
+/// The persisted --json sequence high-water mark (#330); 0 for sessions saved
+/// before it existed, so a resume of one starts the numbering fresh.
+fn eventSeqFromSession(obj: std.json.ObjectMap) u64 {
+ const v = obj.get("event_seq") orelse return 0;
+ if (v != .integer or v.integer <= 0) return 0;
+ return @intCast(v.integer);
+}
+
fn contextLocalTokensFromSession(obj: std.json.ObjectMap) ?u64 {
const v = obj.get("context_local_tokens") orelse return null;
if (v != .integer or v.integer < 0) return null;
@@ -431,6 +360,10 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
// values instead of turning a corrupt session into an enormous unsigned count.
const saved_context_tokens = contextTokensFromSession(obj);
const saved_local_tokens = contextLocalTokensFromSession(obj);
+ // #330: continue the protocol sequence rather than restarting at 1. restore()
+ // only ever raises the counter, so a legacy session (no field) or a corrupt
+ // negative value simply leaves this process's numbering alone.
+ protocol_seq.restore(eventSeqFromSession(obj));
root.ensureStoredKeys(keys);
if (std.mem.eql(u8, pid, "codex")) root.ensureModelCatalog(keys.*);
@@ -561,6 +494,27 @@ test "session context meter restores hidden delta and legacy sessions re-estimat
try std.testing.expectEqual(local_estimate, root.last_context_tokens);
}
+test "event_seq round-trips so a replacement graff continues the sequence (#330)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const saved = try std.json.parseFromSliceLeaky(Value, a, "{\"event_seq\":41}", .{});
+ try std.testing.expectEqual(@as(u64, 41), eventSeqFromSession(saved.object));
+ // Legacy sessions and corrupt values leave the live counter alone.
+ const legacy = try std.json.parseFromSliceLeaky(Value, a, "{}", .{});
+ try std.testing.expectEqual(@as(u64, 0), eventSeqFromSession(legacy.object));
+ const bad = try std.json.parseFromSliceLeaky(Value, a, "{\"event_seq\":-3}", .{});
+ try std.testing.expectEqual(@as(u64, 0), eventSeqFromSession(bad.object));
+
+ protocol_seq.resetForTest();
+ defer protocol_seq.resetForTest();
+ protocol_seq.restore(eventSeqFromSession(saved.object));
+ try std.testing.expectEqual(@as(u64, 42), protocol_seq.next()); // no id is ever reissued
+ protocol_seq.restore(eventSeqFromSession(legacy.object));
+ try std.testing.expectEqual(@as(u64, 43), protocol_seq.next());
+}
+
test "slugifyTitle makes a filesystem-safe slug from an AI title" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/session_index.zig b/src/session_index.zig
new file mode 100644
index 00000000..a8f48ad2
--- /dev/null
+++ b/src/session_index.zig
@@ -0,0 +1,114 @@
+//! The session INDEX: everything `/sessions` and the `/resume` picker need to
+//! list saved conversations without parsing them. Split out of session.zig,
+//! which sits at the 600-line cap (#330 needed room there for the protocol
+//! sequence high-water mark). session.zig re-exports every name here, so
+//! callers keep importing `session.listSavedSessions` and friends.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const agent_mod = @import("agent.zig");
+const util = @import("util.zig");
+const Agent = agent_mod.Agent;
+const unixMs = util.unixMs;
+
+pub const session_ext = ".session.json";
+/// Title-named session files live here (resume reads this).
+pub const sessions_dir = ".graff/sessions";
+
+/// Path to a session file: .graff/sessions/<name>.session.json.
+pub fn sessionPath(arena: Allocator, name: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(arena, "{s}/{s}{s}", .{ sessions_dir, name, session_ext });
+}
+
+/// Session-list metadata peeked from a session file WITHOUT parsing the
+/// (potentially multi-MB) messages array: saveSession writes "title" and
+/// "updated_ms" before "messages", so parsing the header slice alone is
+/// enough. Zero-value fields when the file predates them or the header
+/// can't be read — callers fall back to the raw session name (#109).
+pub const SessionMeta = struct { title: ?[]const u8 = null, updated_ms: i64 = 0 };
+
+pub fn sessionMetaFromBytes(arena: Allocator, data: []const u8) SessionMeta {
+ // Embedded quotes inside string values are escaped in the file, so the
+ // raw needle can only match the real top-level "messages" key.
+ const idx = std.mem.indexOf(u8, data, "\"messages\":") orelse return .{};
+ const header = std.mem.trimEnd(u8, data[0..idx], " \t\r\n");
+ if (header.len < 2 or header[header.len - 1] != ',') return .{};
+ const hjson = std.fmt.allocPrint(arena, "{s}}}", .{header[0 .. header.len - 1]}) catch return .{};
+ const parsed = std.json.parseFromSliceLeaky(Value, arena, hjson, .{ .allocate = .alloc_always }) catch return .{};
+ if (parsed != .object) return .{};
+ return .{
+ .title = if (parsed.object.get("title")) |v| (if (v == .string and v.string.len > 0) v.string else null) else null,
+ .updated_ms = if (parsed.object.get("updated_ms")) |v| (if (v == .integer) v.integer else 0) else 0,
+ };
+}
+
+pub fn sessionMeta(root: *Agent, arena: Allocator, base: []const u8) SessionMeta {
+ const path = sessionPath(arena, base) catch return .{};
+ const data = Io.Dir.cwd().readFileAlloc(root.io, path, arena, .limited(8 * 1024 * 1024)) catch return .{};
+ return sessionMetaFromBytes(arena, data);
+}
+
+/// "3m ago"-style age for the session lists; "" when the timestamp is missing.
+pub fn sessionAge(arena: Allocator, io: Io, then_ms: i64) []const u8 {
+ if (then_ms <= 0) return "";
+ const s = @divTrunc(unixMs(io) - then_ms, 1000);
+ if (s < 60) return "just now";
+ if (s < 3600) return std.fmt.allocPrint(arena, "{d}m ago", .{@divTrunc(s, 60)}) catch "";
+ if (s < 86_400) return std.fmt.allocPrint(arena, "{d}h ago", .{@divTrunc(s, 3600)}) catch "";
+ return std.fmt.allocPrint(arena, "{d}d ago", .{@divTrunc(s, 86_400)}) catch "";
+}
+
+/// One row per saved session for the /resume picker and /sessions list:
+/// newest first, keyed (and resumed) by the file base name.
+pub const SessionEntry = struct { base: []const u8, title: ?[]const u8 = null, updated_ms: i64 = 0 };
+
+pub fn listSavedSessions(root: *Agent, arena: Allocator) std.ArrayList(SessionEntry) {
+ var entries: std.ArrayList(SessionEntry) = .empty;
+ var dir = Io.Dir.cwd().openDir(root.io, sessions_dir, .{ .iterate = true }) catch return entries;
+ defer dir.close(root.io);
+ var it = dir.iterate();
+ while (it.next(root.io) catch null) |entry| {
+ if (entry.kind != .file) continue;
+ if (!std.mem.endsWith(u8, entry.name, session_ext)) continue;
+ const base = arena.dupe(u8, entry.name[0 .. entry.name.len - session_ext.len]) catch continue;
+ const meta = sessionMeta(root, arena, base);
+ entries.append(arena, .{ .base = base, .title = meta.title, .updated_ms = meta.updated_ms }) catch {};
+ }
+ std.mem.sort(SessionEntry, entries.items, {}, struct {
+ fn newerFirst(_: void, a: SessionEntry, b: SessionEntry) bool {
+ return a.updated_ms > b.updated_ms;
+ }
+ }.newerFirst);
+ return entries;
+}
+
+test "sessionMetaFromBytes reads title + updated_ms from the header only" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const meta = sessionMetaFromBytes(arena,
+ \\{"provider":"codegraff","model":"glm-5.2","strict":false,"ultracode_mode":false,"goal":null,"title":"Fix \"login\" bug","updated_ms":1782294417239,"messages":[{"role":"user","content":"hi"}]}
+ );
+ try std.testing.expectEqualStrings("Fix \"login\" bug", meta.title.?);
+ try std.testing.expectEqual(@as(i64, 1782294417239), meta.updated_ms);
+}
+
+test "sessionMetaFromBytes falls back cleanly on legacy/invalid headers" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const legacy = sessionMetaFromBytes(arena,
+ \\{"provider":"kimi","model":"k3","strict":false,"messages":[]}
+ );
+ try std.testing.expect(legacy.title == null);
+ try std.testing.expectEqual(@as(i64, 0), legacy.updated_ms);
+ const tricky = sessionMetaFromBytes(arena,
+ \\{"provider":"x","model":"y","goal":"say \"messages\": then stop","title":"T","updated_ms":5,"messages":[]}
+ );
+ try std.testing.expectEqualStrings("T", tricky.title.?);
+ try std.testing.expectEqual(@as(i64, 5), tricky.updated_ms);
+ try std.testing.expect(sessionMetaFromBytes(arena, "not json").title == null);
+}
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 513db41d..44e21f56 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -24,14 +24,16 @@ const jobs = @import("jobs.zig");
const cards = @import("cards.zig");
const trace = @import("trace.zig");
const textMessage = @import("messages.zig").textMessage;
+const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event
fn guiEmit(io: Io, ev: anytype) void {
if (!main_mod.json_mode) return;
const w = main_mod.g_out orelse return;
main_mod.g_gui_mu.lockUncancelable(io);
defer main_mod.g_gui_mu.unlock(io);
- var s: std.json.Stringify = .{ .writer = w };
- s.write(ev) catch return;
+ // #330: one shared --json stream, one shared sequence — a pool-thread
+ // subagent emit takes its id under the same lock as the root agent's.
+ protocol_seq.writeEvent(w, ev) catch return;
w.writeByte('\n') catch return;
w.flush() catch return;
}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 2e1a7a03..7fb19acc 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -39,6 +39,11 @@ const repl_parser = @import("repl_parser.zig");
const router_config = @import("router_config.zig");
const subagent_selection = @import("subagent_selection.zig");
+// `graff serve` resumability (#330): serve.zig imports these, but nothing in
+// the production graph references their decls, so Zig never analyses them.
+const serve_events = @import("serve_events.zig");
+const serve_create = @import("serve_create.zig");
+
// Moved off main.zig, which is at the 600-line cap.
const scoring_slot_test = @import("scoring_slot_test.zig");
@@ -55,5 +60,7 @@ test {
_ = repl_parser;
_ = router_config;
_ = subagent_selection;
+ _ = serve_events;
+ _ = serve_create;
_ = scoring_slot_test;
}
diff --git a/src/workflow_progress.zig b/src/workflow_progress.zig
index 37e93847..0eaf7c04 100644
--- a/src/workflow_progress.zig
+++ b/src/workflow_progress.zig
@@ -19,6 +19,7 @@ const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
const shapes = @import("shapes.zig");
const util = @import("util.zig");
+const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event
/// Titles and task labels are free text from the model. Cap them so one absurd
/// title can never turn a progress line into a megabyte of JSONL.
@@ -65,9 +66,15 @@ pub const TaskEvent = struct {
status: []const u8,
};
-fn writeLine(w: *Io.Writer, ev: anytype) void {
- var s: std.json.Stringify = .{ .writer = w };
- s.write(ev) catch return;
+fn writeLine(w: *Io.Writer, ev: anytype, stamp: bool) void {
+ if (stamp) {
+ // #330: the shared --json stream is one sequence; a workflow event
+ // emitted from a pool thread takes its id from the same counter.
+ protocol_seq.writeEvent(w, ev) catch return;
+ } else {
+ var s: std.json.Stringify = .{ .writer = w };
+ s.write(ev) catch return;
+ }
w.writeByte('\n') catch return;
}
@@ -75,14 +82,14 @@ fn writeLine(w: *Io.Writer, ev: anytype) void {
/// throughout: a progress event must never be able to fail a workflow, so every
/// error path is a silent return.
fn emit(io: Io, ev: anytype) void {
- if (g_test_sink) |sink| return writeLine(&sink.writer, ev);
+ if (g_test_sink) |sink| return writeLine(&sink.writer, ev, false);
if (!main_mod.json_mode) return;
const w = main_mod.g_out orelse return;
// The same lock guiEmit/printDelta take: workflow tasks emit from pool
// threads, and a half-written line would corrupt the SDK's JSONL parse.
main_mod.g_gui_mu.lockUncancelable(io);
defer main_mod.g_gui_mu.unlock(io);
- writeLine(w, ev);
+ writeLine(w, ev, true);
w.flush() catch return;
}