graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Add structured ask_user event and answer protocol
Pranav P70e5676eab66
diff --git a/README.md b/README.mdindex a50c82cb..8db9ca47 100644--- a/README.md+++ b/README.md@@ -325,7 +325,8 @@ actionable: `/resume nope` says the session file wasn't found and points at## SDKs — TypeScript & Pythongraff is scriptable from your own code. `graff --json` is a structured stdio-protocol (JSON requests in, JSONL events out) and `graff --schema` prints the+protocol (JSON requests in, JSONL events out; `ask_user` is answered with a+structured `{"type":"answer","text":"...","cancelled":false}` line) and `graff --schema` prints themachine-readable interface — and the **TypeScript and Python SDKs in[`sdk/`](sdk/) are auto-generated from that schema**, so they never drift fromthe binary. On every release tag a GitHub Action rebuilds, regenerates, fails if@@ -656,8 +657,11 @@ together the foundation for the auto-generated TypeScript + Python SDKs in`graff serve` puts that same protocol on HTTP for clients that can't spawn alocal process (edge runtimes, browsers, other machines): each session is a real-`graff --json` child, one POST is one protocol request, and the response streams-NDJSON events until that request's terminal event. Bearer auth via+`graff --json` child, one non-answer POST is one protocol request, and the+response streams NDJSON events until that request's terminal event. `answer`+POSTs can be sent while the original stream is waiting on `ask_user`; they ack+immediately and the original stream continues to the `tool_result`/`turn`.+Bearer auth via`--token`/`HARNESS_SERVE_TOKEN` (required to bind beyond loopback); CORS opensonly when a token gates access. The SDKs ship matching remote clients —`@graff-new/sdk/remote` (fetch-only: Workers/Deno/Bun/browsers) and Python'sdiff --git a/examples/edge-worker/src/remote.ts b/examples/edge-worker/src/remote.tsindex 22acab7a..7f61c058 100644--- a/examples/edge-worker/src/remote.ts+++ b/examples/edge-worker/src/remote.ts@@ -11,7 +11,7 @@ export const HARNESS_VERSION = "0.4";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "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" | "glm-4.5" | "glm-4.7" | "glm-5" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.4" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.5-codex" | "grok-4.3" | "grok-build" | "kimi-k2-thinking" | "kimi-k2.5" | "kimi-k2.6" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3";export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "ask_user" | "attempt_completion" | "subagent" | "workflow";-export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "xai" | "zai" | "claude" | "codex";+export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "xai" | "zai" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).* Forward compatibility: a newer (edge) harness may stream event types not@@ -20,6 +20,7 @@ export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "miexport type Event =| { type: "text"; text: string }| { type: "tool_call"; name: string; input: Record<string, unknown> }+ | { type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }| { type: "tool_result"; name: string; is_error: boolean; text: string }| { type: "turn"; text: string; context_tokens: number; cost_usd: number }| { type: "system_prompt"; ok: boolean; append: boolean; chars: number }@@ -55,6 +56,12 @@ export interface ChatOptions {prompt: string;}+export interface AnswerOptions {+ text?: string;+ cancelled?: boolean;+ callId?: string;+}+export interface RunAgentRemoteOptions extends RemoteOptions {prompt: string;}@@ -160,6 +167,17 @@ export class RemoteHarness {return final;}+ /** Answer an in-flight ask_user event. The original chat() stream continues+ * and will later yield the ask_user tool_result plus the final turn. */+ async answer(input: string | AnswerOptions): Promise<void> {+ const payload = typeof input === "string"+ ? { type: "answer", text: input, cancelled: false }+ : { type: "answer", text: input.text ?? "", cancelled: input.cancelled ?? false, call_id: input.callId };+ const res = await this.req("POST", `/v1/sessions/${await this.sessionId}`, payload);+ await res.text();+ }++/** Replace (or with append=true, extend) the system prompt for later turns.* Same KV-cache warning as the stdio SDK: any mutation invalidates the* cached prefix for the whole conversation — prefer the creation-timediff --git a/sdk/README.md b/sdk/README.mdindex d7cc9b2f..e60413b2 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -1,20 +1,20 @@# simple-harness SDKs-TypeScript (`ts/`) and Python (`py/`) clients that drive the harness over its+TypeScript (`ts/`) and Python (`py/`) clients that drive graff over its`--json` stdio protocol. **Both are auto-generated** — never hand-edit thegenerated files.## How it works-The harness is the single source of truth. `harness --schema` emits its+The graff binary is the single source of truth. `graff --schema` emits itsinterface (providers, models, tools, and the `--json` event protocol) as JSON.`generate.py` turns that into typed clients:```sh# regenerate locally from the built binary-python3 sdk/generate.py --harness ./zig-out/bin/harness+python3 sdk/generate.py --harness ./zig-out/bin/graff# or from a saved schema-harness --schema | python3 sdk/generate.py+graff --schema | python3 sdk/generate.py```On every release tag the `sdk` GitHub Action rebuilds, regenerates, fails if the@@ -56,6 +56,9 @@ for await (const ev of runAgent({ prompt: "summarize README.md", model: "gpt-5.5const harness = Harness.init({ model: "claude-opus-4-8", yolo: true });const session = harness.session();console.log(await session.ask("what files are here?"));+for await (const ev of session.send("ask me a follow-up before continuing")) {+ if (ev.type === "ask_user") session.answer({ text: "continue", callId: ev.call_id });+}console.log(await session.ask("now read the largest one"));session.close();```@@ -66,7 +69,7 @@ Options: `binary`, `cwd`, `env`, `model` (model name *or* provider id, e.g. `"co## Remote (edge runtimes — no local binary)Both transports above spawn a local process, which edge runtimes can't do.-Run `harness serve` somewhere (default `127.0.0.1:8787`; pass+Run `graff serve` somewhere (default `127.0.0.1:8787`; pass`--token <secret>` — required for non-loopback binds) and drive it over HTTPinstead. Same method surface, same event stream:@@ -93,11 +96,12 @@ with RemoteHarness("http://127.0.0.1:8787", token="...", yolo=True) as h:One protocol request is in flight per session at a time; pass `yolo=True` inmost cases (the bridge has no terminal to show permission prompts on). The-HTTP contract lives under the `serve` key of `harness --schema`.+HTTP contract lives under the `serve` key of `graff --schema`.## Protocol-`harness --json` reads `{"type":"user","text":"..."}` lines on stdin and emits-JSONL events: `text` (assistant delta), `tool_call`, `tool_result`, `turn`-(final text + `context_tokens` + `cost_usd`), and `error`. See the `protocol`-key of `harness --schema`.+`graff --json` reads `{"type":"user","text":"..."}` lines on stdin and emits+JSONL events: `text` (assistant delta), `tool_call`, `ask_user`, `tool_result`,+`turn` (final text + `context_tokens` + `cost_usd`), and `error`. Answer an+`ask_user` event with `{"type":"answer","text":"...","cancelled":false,"call_id":"..."}`.+See the `protocol` key of `graff --schema`.diff --git a/sdk/generate.py b/sdk/generate.pyindex ee1eeab6..c737232d 100644--- a/sdk/generate.py+++ b/sdk/generate.py@@ -72,6 +72,7 @@ export type ProviderId = {provider_union};export type Event =| {{ type: "text"; text: string }}| {{ type: "tool_call"; name: string; input: Record<string, unknown> }}+ | {{ type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}| {{ type: "tool_result"; name: string; is_error: boolean; text: string }}| {{ type: "turn"; text: string; context_tokens: number; cost_usd: number }}| {{ type: "system_prompt"; ok: boolean; append: boolean; chars: number }}@@ -111,6 +112,12 @@ export interface ChatOptions {{prompt: string;}}+export interface AnswerOptions {{+ text?: string;+ cancelled?: boolean;+ callId?: string;+}}+export interface RunAgentOptions extends HarnessOptions {{/** User prompt to send to the agent. */prompt: string;@@ -308,6 +315,16 @@ export class Harness {{}}return final;}}++ /** Answer an in-flight ask_user event. Call this while consuming chat()+ * when you receive {{ type: "ask_user", call_id, ... }}. */+ answer(input: string | AnswerOptions): void {{+ const payload = typeof input === "string"+ ? {{ type: "answer", text: input, cancelled: false }}+ : {{ type: "answer", text: input.text ?? "", cancelled: input.cancelled ?? false, call_id: input.callId }};+ this.proc.stdin.write(JSON.stringify(payload) + "\\n");+ }}+/** Replace (or with append=true, extend) the system prompt for subsequent* turns. Call between turns; resolves on the harness's ack.*@@ -402,6 +419,7 @@ export class HarnessSession {{/** Send a user turn; async-iterate its events. */send(input: string | ChatOptions): AsyncGenerator<Event> {{ return this.agent.chat(input); }}ask(input: string | ChatOptions): Promise<string> {{ return this.agent.ask(input); }}+ answer(input: string | AnswerOptions): void {{ return this.agent.answer(input); }}setSystemPrompt(text: string, append = false): Promise<void> {{ return this.agent.setSystemPrompt(text, append); }}close(): void {{ this.agent.close(); }}}}@@ -458,6 +476,7 @@ export type ProviderId = {provider_union};export type Event =| {{ type: "text"; text: string }}| {{ type: "tool_call"; name: string; input: Record<string, unknown> }}+ | {{ type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}| {{ type: "tool_result"; name: string; is_error: boolean; text: string }}| {{ type: "turn"; text: string; context_tokens: number; cost_usd: number }}| {{ type: "system_prompt"; ok: boolean; append: boolean; chars: number }}@@ -493,6 +512,12 @@ export interface ChatOptions {{prompt: string;}}+export interface AnswerOptions {{+ text?: string;+ cancelled?: boolean;+ callId?: string;+}}+export interface RunAgentRemoteOptions extends RemoteOptions {{prompt: string;}}@@ -598,6 +623,17 @@ export class RemoteHarness {{return final;}}+ /** Answer an in-flight ask_user event. The original chat() stream continues+ * and will later yield the ask_user tool_result plus the final turn. */+ async answer(input: string | AnswerOptions): Promise<void> {{+ const payload = typeof input === "string"+ ? {{ type: "answer", text: input, cancelled: false }}+ : {{ type: "answer", text: input.text ?? "", cancelled: input.cancelled ?? false, call_id: input.callId }};+ const res = await this.req("POST", `/v1/sessions/${{await this.sessionId}}`, payload);+ await res.text();+ }}++/** Replace (or with append=true, extend) the system prompt for later turns.* Same KV-cache warning as the stdio SDK: any mutation invalidates the* cached prefix for the whole conversation — prefer the creation-time@@ -833,7 +869,8 @@ class Harness:"""Drives a `harness --json` subprocess. One turn = send text, stream events.Events are plain dicts with a "type" field: "text", "tool_call",- "tool_result", "turn", or "error" (see the harness --schema protocol).+ "ask_user", "tool_result", "turn", or "error" (see the harness+ --schema protocol)."""def __init__(self, binary: Optional[str] = None, args: Optional[list] = None,@@ -907,6 +944,16 @@ class Harness:raise RuntimeError(ev["message"])return final+ def answer(self, text: str = "", cancelled: bool = False,+ call_id: Optional[str] = None) -> None:+ """Answer an in-flight ask_user event while chat() is being consumed."""+ assert self.proc.stdin+ req = {{"type": "answer", "text": text, "cancelled": cancelled}}+ if call_id:+ req["call_id"] = call_id+ self.proc.stdin.write(json.dumps(req) + "\\n")+ self.proc.stdin.flush()+def set_system_prompt(self, text: str, append: bool = False) -> None:"""Replace (or with append=True, extend) the system prompt for laterturns. Call between turns; blocks until the harness acks.@@ -1113,6 +1160,15 @@ class RemoteHarness:raise RuntimeError(ev["message"])return final+ def answer(self, text: str = "", cancelled: bool = False,+ call_id: Optional[str] = None) -> None:+ """Answer an in-flight ask_user event. The original chat stream+ continues and later yields the ask_user tool_result plus final turn."""+ req = {{"type": "answer", "text": text, "cancelled": cancelled}}+ if call_id:+ req["call_id"] = call_id+ self._request("POST", f"/v1/sessions/{{self.session_id}}", req).read()+def set_system_prompt(self, text: str, append: bool = False) -> None:"""Replace (or with append=True, extend) the system prompt for laterturns. Same KV-cache warning as `Harness.set_system_prompt`: preferdiff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex b54a2542..aa6b703f 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -176,7 +176,8 @@ class Harness:"""Drives a `harness --json` subprocess. One turn = send text, stream events.Events are plain dicts with a "type" field: "text", "tool_call",- "tool_result", "turn", or "error" (see the harness --schema protocol).+ "ask_user", "tool_result", "turn", or "error" (see the harness+ --schema protocol)."""def __init__(self, binary: Optional[str] = None, args: Optional[list] = None,@@ -250,6 +251,16 @@ class Harness:raise RuntimeError(ev["message"])return final+ def answer(self, text: str = "", cancelled: bool = False,+ call_id: Optional[str] = None) -> None:+ """Answer an in-flight ask_user event while chat() is being consumed."""+ assert self.proc.stdin+ req = {"type": "answer", "text": text, "cancelled": cancelled}+ if call_id:+ req["call_id"] = call_id+ self.proc.stdin.write(json.dumps(req) + "\n")+ self.proc.stdin.flush()+def set_system_prompt(self, text: str, append: bool = False) -> None:"""Replace (or with append=True, extend) the system prompt for laterturns. Call between turns; blocks until the harness acks.@@ -456,6 +467,15 @@ class RemoteHarness:raise RuntimeError(ev["message"])return final+ def answer(self, text: str = "", cancelled: bool = False,+ call_id: Optional[str] = None) -> None:+ """Answer an in-flight ask_user event. The original chat stream+ continues and later yields the ask_user tool_result plus final turn."""+ req = {"type": "answer", "text": text, "cancelled": cancelled}+ if call_id:+ req["call_id"] = call_id+ self._request("POST", f"/v1/sessions/{self.session_id}", req).read()+def set_system_prompt(self, text: str, append: bool = False) -> None:"""Replace (or with append=True, extend) the system prompt for laterturns. Same KV-cache warning as `Harness.set_system_prompt`: preferdiff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex 53766143..fe6e211b 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -23,6 +23,7 @@ export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "miexport type Event =| { type: "text"; text: string }| { type: "tool_call"; name: string; input: Record<string, unknown> }+ | { type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }| { type: "tool_result"; name: string; is_error: boolean; text: string }| { type: "turn"; text: string; context_tokens: number; cost_usd: number }| { type: "system_prompt"; ok: boolean; append: boolean; chars: number }@@ -62,6 +63,12 @@ export interface ChatOptions {prompt: string;}+export interface AnswerOptions {+ text?: string;+ cancelled?: boolean;+ callId?: string;+}+export interface RunAgentOptions extends HarnessOptions {/** User prompt to send to the agent. */prompt: string;@@ -259,6 +266,16 @@ export class Harness {}return final;}++ /** Answer an in-flight ask_user event. Call this while consuming chat()+ * when you receive { type: "ask_user", call_id, ... }. */+ answer(input: string | AnswerOptions): void {+ const payload = typeof input === "string"+ ? { type: "answer", text: input, cancelled: false }+ : { type: "answer", text: input.text ?? "", cancelled: input.cancelled ?? false, call_id: input.callId };+ this.proc.stdin.write(JSON.stringify(payload) + "\n");+ }+/** Replace (or with append=true, extend) the system prompt for subsequent* turns. Call between turns; resolves on the harness's ack.*@@ -353,6 +370,7 @@ export class HarnessSession {/** Send a user turn; async-iterate its events. */send(input: string | ChatOptions): AsyncGenerator<Event> { return this.agent.chat(input); }ask(input: string | ChatOptions): Promise<string> { return this.agent.ask(input); }+ answer(input: string | AnswerOptions): void { return this.agent.answer(input); }setSystemPrompt(text: string, append = false): Promise<void> { return this.agent.setSystemPrompt(text, append); }close(): void { this.agent.close(); }}diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex e62dc560..7f61c058 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -20,6 +20,7 @@ export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "miexport type Event =| { type: "text"; text: string }| { type: "tool_call"; name: string; input: Record<string, unknown> }+ | { type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }| { type: "tool_result"; name: string; is_error: boolean; text: string }| { type: "turn"; text: string; context_tokens: number; cost_usd: number }| { type: "system_prompt"; ok: boolean; append: boolean; chars: number }@@ -55,6 +56,12 @@ export interface ChatOptions {prompt: string;}+export interface AnswerOptions {+ text?: string;+ cancelled?: boolean;+ callId?: string;+}+export interface RunAgentRemoteOptions extends RemoteOptions {prompt: string;}@@ -160,6 +167,17 @@ export class RemoteHarness {return final;}+ /** Answer an in-flight ask_user event. The original chat() stream continues+ * and will later yield the ask_user tool_result plus the final turn. */+ async answer(input: string | AnswerOptions): Promise<void> {+ const payload = typeof input === "string"+ ? { type: "answer", text: input, cancelled: false }+ : { type: "answer", text: input.text ?? "", cancelled: input.cancelled ?? false, call_id: input.callId };+ const res = await this.req("POST", `/v1/sessions/${await this.sessionId}`, payload);+ await res.text();+ }++/** Replace (or with append=true, extend) the system prompt for later turns.* Same KV-cache warning as the stdio SDK: any mutation invalidates the* cached prefix for the whole conversation — prefer the creation-timediff --git a/src/main.zig b/src/main.zigindex 3f206936..c98c63d7 100644--- a/src/main.zig+++ b/src/main.zig@@ -79,11 +79,12 @@ var unattended = false; // -p one-shot: no human to prompt; unapproved tool callconst schema_protocol_json =\\{\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",- \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"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\",\"name\":\"provider|provider/model|model\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"} are live control requests acked by model/compact/mode/agent events. 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",+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"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\",\"name\":\"provider|provider/model|model\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"} are live control requests acked by model/compact/mode/agent events. 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 harness.trajectory.jsonl (the 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",\\ "events": [\\ {"type": "text", "text": "assistant text delta"},\\ {"type": "tool_call", "name": "tool", "input": {}},+ \\ {"type": "ask_user", "call_id": "...", "question": "...", "input": {"question": "...", "options": ["..."]}},\\ {"type": "tool_result", "name": "tool", "is_error": false, "text": "..."},\\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0},\\ {"type": "system_prompt", "ok": true, "append": false, "chars": 0},@@ -108,7 +109,7 @@ const schema_serve_json =\\ {"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\",\"yolo\",\"system_prompt\",\"append_system_prompt\"} 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); response streams application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); one request in flight per session at a time"},+ \\ {"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"}\\ ]\\}@@ -4038,6 +4039,10 @@ pub fn main(init: std.process.Init) !void {root.emit(.{ .type = "score", .ok = true, .prompt_sha = sha, .signed = signed });continue;}+ if (std.mem.eql(u8, rtype, "answer")) {+ root.emit(.{ .type = "error", .message = "answer received with no active ask_user prompt" });+ continue;+ }const t = if (parsed == .object) parsed.object.get("text") else null;const text = if (t) |v| (if (v == .string) v.string else "") else "";if (text.len == 0) {@@ -5705,6 +5710,10 @@ const ServeSession = struct {rdr: Io.File.Reader, // persistent reader over child stdout — must not move (gpa.create)rbuf: []u8, // gpa-owned backing buffer for rdrbusy: Io.Mutex = .init, // one in-flight protocol request per session+ answer_mu: Io.Mutex = .init,+ awaiting_answer: bool = false,+ answer_call_id: [128]u8 = undefined,+ answer_call_id_len: usize = 0,};const ServeState = struct {@@ -5974,6 +5983,9 @@ 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 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);+s.busy.lockUncancelable(io); // serialize requests per sessiondefer s.busy.unlock(io);@@ -6013,14 +6025,77 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8)};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)) break;+ if (serveTerminalEvent(trimmed)) {+ serveClearAnswerState(io, s);+ break;+ }}bw.end() catch return;}+fn serveAnswer(st: *ServeState, req: *std.http.Server.Request, s: *ServeSession, line: []const u8, obj: std.json.ObjectMap) !void {+ const io = st.io;+ s.answer_mu.lockUncancelable(io);+ defer s.answer_mu.unlock(io);++ if (!s.awaiting_answer) {+ return respondJson(st, req, .conflict, "{\"error\":\"no active ask_user prompt\"}");+ }+ const req_call_id = if (obj.get("call_id")) |v| (if (v == .string) v.string else "") else "";+ const active_call_id = s.answer_call_id[0..s.answer_call_id_len];+ if (req_call_id.len > 0 and active_call_id.len > 0 and !std.mem.eql(u8, req_call_id, active_call_id)) {+ return respondJson(st, req, .conflict, "{\"error\":\"answer call_id does not match active ask_user prompt\"}");+ }++ var wb: [1024]u8 = undefined;+ var cw = s.child.stdin.?.writerStreaming(io, &wb);+ cw.interface.writeAll(line) catch return respondJson(st, req, .bad_gateway, "{\"error\":\"session process is gone\"}");+ cw.interface.writeByte('\n') catch return error.WriteFailed;+ cw.interface.flush() catch return respondJson(st, req, .bad_gateway, "{\"error\":\"session process is gone\"}");+ s.awaiting_answer = false;+ s.answer_call_id_len = 0;+ return respondJson(st, req, .ok, "{\"ok\":true,\"type\":\"answer\"}");+}++fn serveUpdateAnswerState(io: Io, s: *ServeSession, line: []const u8) void {+ const ty = serveStringField(line, "type") orelse return;+ if (!std.mem.eql(u8, ty, "ask_user")) return;+ const call_id = serveStringField(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);+ @memcpy(s.answer_call_id[0..n], call_id[0..n]);+ s.answer_call_id_len = n;+ 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);+ s.awaiting_answer = false;+ 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@@ -6399,6 +6474,33 @@ const ExecResult = struct {ms: i64 = 0, // wall-clock of the tool exec (external tools only; --timing)};+const AnswerRequest = struct {+ text: []const u8,+ cancelled: bool,+ call_id: []const u8,+};++fn answerParseError(err: anyerror) []const u8 {+ return switch (err) {+ error.AnswerNotObject => "answer must be a JSON object",+ error.AnswerWrongType => "expected answer request for ask_user",+ error.AnswerCallIdMismatch => "answer call_id did not match active ask_user prompt",+ else => "invalid answer JSON for ask_user",+ };+}++fn parseAnswerRequest(parsed: Value, expected_call_id: []const u8) !AnswerRequest {+ if (parsed != .object) return error.AnswerNotObject;+ const rtype = if (parsed.object.get("type")) |v| (if (v == .string) v.string else "") else "";+ if (!std.mem.eql(u8, rtype, "answer")) return error.AnswerWrongType;+ const call_id = if (parsed.object.get("call_id")) |v| (if (v == .string) v.string else "") else "";+ if (call_id.len > 0 and expected_call_id.len > 0 and !std.mem.eql(u8, call_id, expected_call_id))+ return error.AnswerCallIdMismatch;+ const cancelled = if (parsed.object.get("cancelled")) |v| v == .bool and v.bool else false;+ const text = if (parsed.object.get("text")) |v| (if (v == .string) v.string else "") else "";+ return .{ .text = text, .cancelled = cancelled, .call_id = call_id };+}+const TodoItem = struct {content: []const u8,status: []const u8,@@ -6460,6 +6562,7 @@ const Agent = struct {streamed_args: ArgTool = .none, // which meta tool's prose streamed live this requeststreamed_args_len: usize = 0, // raw bytes emitted for it (gates re-print suppression)cap_new: bool = false, // provider rejected max_tokens → use max_completion_tokens+ next_ask_id: u64 = 1,fn prompt(self: *Agent) !void {if (json_mode) return; // SDK drives turns; no human prompt@@ -7219,6 +7322,28 @@ const Agent = struct {};const w = self.out.?;const question = if (call.input.object.get("question")) |q| q.string else "(no question)";+ if (json_mode) {+ const call_id = if (call.id.len > 0) call.id else blk: {+ const id = try std.fmt.allocPrint(self.arena, "ask_user-{d}", .{self.next_ask_id});+ self.next_ask_id += 1;+ break :blk id;+ };+ try self.emitAskUser(call_id, question, call.input);+ const raw = (try in.takeDelimiter('\n')) orelse return .{+ .text = "user ended input without answering",+ .is_error = true,+ };+ const parsed = std.json.parseFromSliceLeaky(Value, self.arena, std.mem.trim(u8, raw, " \t\r"), .{ .allocate = .alloc_always }) catch return .{+ .text = "invalid answer JSON for ask_user",+ .is_error = true,+ };+ const answer = parseAnswerRequest(parsed, call_id) catch |err| return .{+ .text = answerParseError(err),+ .is_error = true,+ };+ if (answer.cancelled) return .{ .text = "user cancelled the follow-up", .is_error = true };+ return .{ .text = try self.arena.dupe(u8, answer.text), .is_error = false };+ }// Skip the re-print only when the question streamed live in full.if (!self.argStreamedFully(call)) try w.print("\n❓ {s}\n", .{question});if (call.input.object.get("options")) |opts| if (opts == .array) {@@ -7235,6 +7360,23 @@ const Agent = struct {return .{ .text = try self.arena.dupe(u8, answer), .is_error = false };}+ 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();+ try w.writeByte('\n');+ try w.flush();+ }+fn renderTodos(self: *Agent) []const u8 {if (self.todos.items.len == 0) return "(no todos)";var aw: Io.Writer.Allocating = .init(self.arena);@@ -7253,6 +7395,7 @@ const Agent = struct {fn sayToolUse(self: *Agent, call: ToolCall) !void {if (json_mode) {+ if (std.mem.eql(u8, call.name, "ask_user")) return;self.emit(.{ .type = "tool_call", .name = call.name, .input = call.input });return;}@@ -7277,11 +7420,12 @@ const Agent = struct {/// no writer); meta tools render their own UX, so skip them.fn sayToolResult(self: *Agent, name: []const u8, r: ExecResult) void {const w = self.out orelse return;- if (isMetaName(name)) return;if (json_mode) {+ if (isMetaName(name) and !std.mem.eql(u8, name, "ask_user")) return;self.emit(.{ .type = "tool_result", .name = name, .is_error = r.is_error, .text = r.text });return;}+ if (isMetaName(name)) return;const all = std.mem.trim(u8, r.text, " \t\r\n");var preview = all;if (std.mem.indexOfScalar(u8, preview, '\n')) |nl| preview = preview[0..nl];@@ -10754,6 +10898,36 @@ test "skillDisabled: registry lookup and toggle" {try std.testing.expect(!skillDisabled("not-a-skill"));}+test "parseAnswerRequest: preserves multiline text and optional call id" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const v = try std.json.parseFromSliceLeaky(Value, a,+ \\{"type":"answer","text":"line 1\nline 2","cancelled":false,"call_id":"call-1"}+ , .{});+ const answer = try parseAnswerRequest(v, "call-1");+ try std.testing.expectEqualStrings("line 1\nline 2", answer.text);+ try std.testing.expectEqualStrings("call-1", answer.call_id);+ try std.testing.expect(!answer.cancelled);+}++test "parseAnswerRequest: explicit cancel and mismatched call id" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const cancelled = try std.json.parseFromSliceLeaky(Value, a,+ \\{"type":"answer","cancelled":true,"call_id":"call-1"}+ , .{});+ const answer = try parseAnswerRequest(cancelled, "call-1");+ try std.testing.expect(answer.cancelled);+ try std.testing.expectEqualStrings("", answer.text);++ const mismatch = try std.json.parseFromSliceLeaky(Value, a,+ \\{"type":"answer","text":"nope","call_id":"call-2"}+ , .{});+ try std.testing.expectError(error.AnswerCallIdMismatch, parseAnswerRequest(mismatch, "call-1"));+}+test { // pull in tests from imported modules (mcp.zig)_ = mcp;}