graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(#615): carry native images through RemoteHarness
Rach Pradhan77fad36c9518
diff --git a/docs/adr/0034-remote-images-stay-native.md b/docs/adr/0034-remote-images-stay-native.mdnew file mode 100644index 00000000..9f32c393--- /dev/null+++ b/docs/adr/0034-remote-images-stay-native.md@@ -0,0 +1,42 @@+# 0034. Remote images stay native++Status: accepted 2026-08-26++## Context++The edge-safe SDK could send only `{type:"user",text}` through `graff serve`.+Putting base64 bytes in `text` did not make them model-visible pixels: the+synthetic witness in #615 returned the wrong random code. Edge callers cannot+fall back to a local clipboard or path because the harness runs elsewhere.++Graff already had one provider-specific image-message builder for normal and+`ask_user` turns (ADR 0015). The missing boundary was typed transport into that+queue, not a second vision implementation.++## Decision++- JSON `user` and `review` requests accept at most 16 `image_url` or+ `image_base64` parts. URLs must be HTTP(S). Base64 parts must name an+ `image/*` media type, decode successfully, and stay within the existing+ 3.7 MB staged-image limit.+- Validate the whole request before staging any part. A rejected or cancelled+ request releases JSON inbox ownership and cannot leak images into the next+ turn.+- Preserve URLs as URLs. Convert URL/base64 parts to Anthropic, Chat+ Completions, or Responses shapes only in `vision.imageMessages`. Never paste+ encoded pixels into prompt text.+- Generate matching TypeScript and Python SDK types from `sdk/generate.py`.+ Remote callers send file bytes as base64; local filesystem paths are not a+ remote wire type.++## Consequences++Cloudflare, browser, and remote Python callers can use the supported SDK+boundary for vision. Text-only models reject image-bearing requests before a+provider call. Provider-side URL fetching retains each provider's URL-access+rules; callers that need deterministic bytes should send base64.++`scripts/test-remote-vision.py` is the opt-in end-to-end witness. On+2026-08-26, `RemoteHarness → graff serve → xai/grok-4.6` read the unpredictable+six-digit PNG code `853765`; unit tests separately lock all three provider wire+shapes and invalid-request atomicity.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 2ce0b253..402d02b6 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -44,6 +44,7 @@ record only when you need the evidence or the edge cases.| [0031](0031-xai-hosted-x-search.md) | xAI Responses splices hosted `x_search` onto tools turns. It is not a catalog function; `GRAFF_XAI_X_SEARCH=0` opts out. || [0032](0032-acp-streams-mid-turn.md) | `graff acp` streams thought / tool / text `session/update`s mid-turn. The native app is an ACP client; it does not need `graff serve`. || [0033](0033-user-can-retire-a-standing-constraint.md) | Only the user retires a standing constraint: TTY `/never` picker (two confirms), ACP/`rm`, or an explicit override. The model cannot. |+| [0034](0034-remote-images-stay-native.md) | JSON/serve image inputs are a typed URL/base64 union, validated atomically and preserved as native provider vision blocks; never flatten pixels into prompt text. |## When to write onediff --git a/docs/embedding.md b/docs/embedding.mdindex 9e71f765..fe4e5fea 100644--- a/docs/embedding.md+++ b/docs/embedding.md@@ -103,9 +103,17 @@ import { Harness } from "@codegraff/sdk";const session = Harness.init({ yolo: true, model: "gpt-5.5" }).session();console.log(await session.ask("what files are here?"));+console.log(await session.ask({+ prompt: "read the code in this image",+ images: [{ type: "image_url", url: "https://example.com/code.png" }],+}));await session.close();```+The same `images` option works through edge-safe `RemoteHarness`: HTTP(S)+URLs and base64 payloads stay native vision parts across `graff serve` rather+than being flattened into prompt text.+## Embedder modeA hosted product that must not exec on the host machine already has a gate:diff --git a/examples/edge-worker/src/remote.ts b/examples/edge-worker/src/remote.tsindex 7f61c058..4867205e 100644--- a/examples/edge-worker/src/remote.ts+++ b/examples/edge-worker/src/remote.ts@@ -7,25 +7,41 @@// `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.4";+export const HARNESS_VERSION = "0.12";-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" | "codex";+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" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "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-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemma-4-31b" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5v-turbo" | "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" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "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" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "openai/gpt-oss-120b" | (string & {});+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";+export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "vercel" | "openrouter" | "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: "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 }- | { 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: "session_recap"; text: string; status: "needs_input" | "completed" | "failed"; source: "heuristic" | "model" }+ | { seq: number; type: "turn"; text: string; context_tokens: number; cost_usd: number; input_tokens: number; uncached_input_tokens: number; cache_read_tokens: number; output_tokens: number; api_calls: number; subscription_calls: number; unpriced_calls: number; complete?: boolean; metadata_complete?: boolean }+ | { seq: number; type: "system_prompt"; ok: boolean; append: boolean; chars: number }+ | { seq: number; type: "model"; ok: boolean; provider: string; model: string; context: number; note: string }+ | { seq: number; type: "compact"; ok: boolean; chars: number }+ | { seq: number; type: "effort"; ok: boolean; level: string; applies: boolean }+ | { 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). */@@ -48,12 +64,52 @@ export interface RemoteOptions {systemPrompt?: string;/** Append extra text to the system prompt. */appendSystemPrompt?: string;- /** Attach to an existing session instead of creating one. */+ /** Hard per-turn root tool-call budget for the child session. */+ maxToolCalls?: number;+ /** Invocation-wide provider-call ceiling shared by all agent work. */+ maxModelCalls?: number;+ /** Reject duplicate root tool name+normalized-input calls per turn. */+ dedupeToolCalls?: boolean;+ /** 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;+}++/** Native image input for a user turn. URLs stay URLs on every provider;+ * base64 is converted to that provider's image-content shape by Graff. */+export type ImageInput =+ | { type: "image_url"; url: string }+ | { type: "image_base64"; mediaType: string; data: string };+export interface ChatOptions {prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];+ review?: boolean;+ /** Replay persisted events with seq >= from before this turn's live ones. */+ from?: number;+ /** Abort the turn mid-flight: on abort the SDK POSTs {"type":"cancel"}+ * (the bridge answers it ahead of the session's busy lock); the stream+ * still runs to the cancelled turn's terminal event — an `error` event+ * ("turn cancelled"). */+ signal?: AbortSignal;}export interface AnswerOptions {@@ -62,8 +118,37 @@ export interface AnswerOptions {callId?: string;}+/** Reasoning effort levels accepted by setEffort (protocol set_effort). */+export type EffortLevel = "low" | "medium" | "high" | "xhigh" | "max" | "ultra";++/** Structured result of one turn: the final assistant text plus the usage+ * the harness reported on the terminal `turn` event. */+export interface AskResult {+ /** Final assistant text. */+ text: string;+ /** Server-reported context size at turn end. */+ contextTokens: number;+ /** Turn cost in USD. */+ costUsd: number;+ inputTokens: number;+ uncachedInputTokens: number;+ cacheReadTokens: number;+ outputTokens: number;+ /** Provider API calls made this turn. */+ apiCalls: number;+ /** Calls served under a subscription (unmetered) login. */+ subscriptionCalls: number;+ /** Calls with no pricing data. */+ unpricedCalls: number;+ /** False when the turn finished incomplete (interrupted/stalled). */+ complete?: boolean;+ metadataComplete?: boolean;+}+export interface RunAgentRemoteOptions extends RemoteOptions {prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];}/** Parse a streaming NDJSON response body into events. */@@ -73,37 +158,72 @@ async function* ndjson(res: Response): AsyncGenerator<Event> {const reader = body.getReader();const dec = new TextDecoder();let buf = "";- while (true) {- const { done, value } = await reader.read();- if (done) break;- buf += dec.decode(value, { stream: true });- let i: number;- while ((i = buf.indexOf("\n")) >= 0) {- const line = buf.slice(0, i).trim();- buf = buf.slice(i + 1);- if (line) { try { yield JSON.parse(line) as Event; } catch { /* skip noise */ } }+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ buf += dec.decode(value, { stream: true });+ let i: number;+ while ((i = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, i).trim();+ buf = buf.slice(i + 1);+ if (line) { try { yield JSON.parse(line) as Event; } catch { /* skip noise */ } }+ }}+ const tail = buf.trim();+ if (tail) { try { yield JSON.parse(tail) as Event; } catch { /* skip noise */ } }+ } finally {+ // Release the body however the consumer left — terminal event, break,+ // or throw — so the connection drains back to keep-alive and the+ // server-side stream never dangles.+ await reader.cancel().catch(() => {});}- const tail = buf.trim();- if (tail) { try { yield JSON.parse(tail) as Event; } catch { /* skip noise */ } }}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;+ /** Tail of the operation chain (see acquireOp). Always resolves. */+ private opTail: Promise<void> = Promise.resolve();+ private closed = false;/** 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);+ // Observe BOTH derived promises up front: a caller that only ever+ // awaits one of info/sessionId must not trip an unhandled rejection on+ // the other when creation fails — awaiting either still rejects with+ // the original cause.+ created.catch(() => {});+ this.info = created;+ const sid = created.then((d) => d.session_id);+ sid.catch(() => {});+ this.sessionId = sid;+ }}/** Create a session (codegraff parity for `Graff.init`, remote edition). */@@ -128,43 +248,150 @@ 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;if (opts.appendSystemPrompt) body.append_system_prompt = opts.appendSystemPrompt;+ if (opts.maxToolCalls !== undefined) body.maxToolCalls = opts.maxToolCalls;+ 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;+ }++ /** Operation chain, the client-side mirror of the bridge's+ * one-non-answer-request-in-flight rule: turns and acked controls run one+ * at a time. The tail always RESOLVES, so one operation's failure cannot+ * poison the queue behind it. answer(), cancel(), and reconnect() bypass+ * it — the bridge handles all three without taking the protocol lock. */+ private acquireOp(): Promise<() => void> {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const acquired = this.opTail.then(() => release);+ this.opTail = this.opTail.then(() => gate);+ return acquired;+ }++ /** Run `op` holding the operation lock (see acquireOp). */+ private async runOp<T>(op: () => Promise<T>): Promise<T> {+ const release = await this.acquireOp();+ try {+ return await op();+ } finally {+ release();+ }}/** 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`. */+ /** Run one turn; async-iterate events up to and including `turn`/`error`.+ * Holds the operation slot until the terminal event (the bridge itself+ * allows one non-answer request in flight per session). Pass `signal` to+ * cancel the turn (see ChatOptions.signal / cancel()). */async *chat(input: string | ChatOptions): AsyncGenerator<Event> {const prompt = typeof input === "string" ? input : input.prompt;- let terminal = false;- for await (const ev of this.send({ type: "user", text: prompt })) {- yield ev;- if (ev.type === "turn" || ev.type === "error") { terminal = true; break; }+ const type = typeof input === "string" || !input.review ? "user" : "review";+ const images = typeof input === "string" ? undefined : input.images?.map((image) =>+ image.type === "image_base64"+ ? { type: image.type, media_type: image.mediaType, data: image.data }+ : image);+ const from = typeof input === "string" ? undefined : input.from;+ const signal = typeof input === "string" ? undefined : input.signal;+ signal?.throwIfAborted();+ const release = await this.acquireOp();+ let aborted = false;+ const onAbort = () => { if (aborted) return; aborted = true; void this.cancel(); };+ try {+ // Wait until the bridge has accepted the turn and returned stream headers+ // before arming cancel. Otherwise an immediately-aborted signal can POST+ // cancel first, receive 409, and leave the following turn running.+ const id = await this.sessionId;+ const q = from === undefined ? "" : `?from=${from}`;+ const res = await this.req("POST", `/v1/sessions/${id}${q}`, { type, text: prompt, ...(images?.length ? { images } : {}) });+ if (signal) {+ signal.addEventListener("abort", onAbort, { once: true });+ if (signal.aborted) onAbort();+ }+ let terminal = false;+ for await (const raw of ndjson(res)) {+ const ev = this.note(raw);+ 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?)");+ } finally {+ if (signal) signal.removeEventListener("abort", onAbort);+ release();}- if (!terminal) throw new Error("bridge stream ended mid-turn (session process died?)");}- /** Run a turn and return just the final assistant text. */- async ask(input: string | ChatOptions): Promise<string> {- let final = "";+ /** 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 its final text plus the usage the harness+ * reported on the terminal `turn` event (tokens, cost, call breakdown).+ * Rejects on an `error` event — including a cancelled turn. */+ async askResult(input: string | ChatOptions): Promise<AskResult> {+ let result: AskResult | null = null;for await (const ev of this.chat(input)) {- if (ev.type === "turn") final = ev.text;+ if (ev.type === "turn") {+ result = {+ text: ev.text,+ contextTokens: ev.context_tokens,+ costUsd: ev.cost_usd,+ inputTokens: ev.input_tokens,+ uncachedInputTokens: ev.uncached_input_tokens,+ cacheReadTokens: ev.cache_read_tokens,+ outputTokens: ev.output_tokens,+ apiCalls: ev.api_calls,+ subscriptionCalls: ev.subscription_calls,+ unpricedCalls: ev.unpriced_calls,+ complete: ev.complete,+ metadataComplete: ev.metadata_complete,+ };+ }if (ev.type === "error") throw new Error(ev.message);}- return final;+ if (!result) throw new Error("turn ended without a terminal event");+ return result;+ }++ /** Run a turn and return just the final assistant text. */+ async ask(input: string | ChatOptions): Promise<string> {+ return (await this.askResult(input)).text;+ }++ /** Run one isolated, read-only review turn and return its final report. */+ review(input: string | ChatOptions): Promise<string> {+ const options = typeof input === "string" ? { prompt: input } : input;+ return this.ask({ ...options, review: true });}/** Answer an in-flight ask_user event. The original chat() stream continues@@ -177,54 +404,122 @@ export class RemoteHarness {await res.text();}+ /** Cancel the in-flight turn (REPL Esc equivalent): POSTs+ * {"type":"cancel"} to the bridge, which answers it AHEAD of the+ * session's busy lock and forwards it down the child's out-of-band cancel+ * path — so it bypasses the client operation queue too. Best-effort: the+ * bridge 409s when no request is in flight, which is not an error here. */+ async cancel(): Promise<void> {+ const id = await this.sessionId.catch(() => null);+ if (id === null) return; // no live session: nothing to cancel+ const res = await this.req("POST", `/v1/sessions/${id}`, { type: "cancel" }).catch(() => null);+ if (res) await res.text().catch(() => {});+ }++ /** Switch provider/model mid-session — the provider-qualified form of the+ * protocol's set_model control. Resolves on the `model` ack, rejects on+ * the `error` event; serialized with chat() and the other controls. */+ setModel(provider: ProviderId | string, model: ModelName | string): Promise<void> {+ return this.runOp(async () => {+ for await (const ev of this.send({ type: "set_model", provider, model })) {+ if (ev.type === "error") throw new Error(ev.message);+ if (ev.type === "model") return;+ }+ throw new Error("bridge stream ended before acking set_model");+ });+ }++ /** Set the reasoning effort for later turns (protocol set_effort).+ * Resolves on the `effort` ack; serialized like the other controls. */+ setEffort(level: EffortLevel): Promise<void> {+ return this.runOp(async () => {+ for await (const ev of this.send({ type: "set_effort", level })) {+ if (ev.type === "error") throw new Error(ev.message);+ if (ev.type === "effort") return;+ }+ throw new Error("bridge stream ended before acking set_effort");+ });+ }++ /** Compact the conversation history now (protocol compact). Resolves on+ * the `compact` ack; rejects when compaction fails (history is left+ * unchanged in that case). Serialized like the other controls. */+ compact(): Promise<void> {+ return this.runOp(async () => {+ for await (const ev of this.send({ type: "compact" })) {+ if (ev.type === "error") throw new Error(ev.message);+ if (ev.type === "compact") return;+ }+ throw new Error("bridge stream ended before acking compact");+ });+ }+/** 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* options; mutate only at task boundaries. */async setSystemPrompt(text: string, append = false): Promise<void> {- for await (const ev of this.send({ type: "set_system_prompt", text, append })) {- if (ev.type === "error") throw new Error(ev.message);- if (ev.type === "system_prompt") return;- }- throw new Error("bridge stream ended before acking set_system_prompt");+ return this.runOp(async () => {+ for await (const ev of this.send({ type: "set_system_prompt", text, append })) {+ if (ev.type === "error") throw new Error(ev.message);+ if (ev.type === "system_prompt") return;+ }+ throw new Error("bridge stream ended before acking set_system_prompt");+ });}appendSystemPrompt(text: string): Promise<void> { return this.setSystemPrompt(text, true); }/** Record an evaluation score in the server-side trajectory archive —- * same semantics as the stdio SDK's `score()`. */- async score(promptOrSha: string, value: number, notes = "", parent?: string): Promise<void> {+ * same semantics as the stdio SDK's `score()`, including the optional+ * `scale` ("unit" | "percent") override of the harness's+ * value-normalization heuristic. */+ async score(promptOrSha: string, value: number, notes = "", parent?: string, niche?: string, scale?: "unit" | "percent"): Promise<void> {const sha = HEX16.test(promptOrSha) ? promptOrSha : await promptFingerprint(promptOrSha);const parent_sha = parent === undefined ? undefined: HEX16.test(parent) ? parent : await promptFingerprint(parent);- for await (const ev of this.send({ type: "score", prompt_sha: sha, score: value, notes, parent_sha })) {- if (ev.type === "error") throw new Error(ev.message);- if (ev.type === "score") return;- }- throw new Error("bridge stream ended before acking score");+ // `niche` files the score into a MAP-Elites cell so the fleet can promote a+ // champion for the role; the remote harness reads it from the request and+ // tags its own score/submit. (Genome capture rides the harness process,+ // which holds the persona text the remote bridge only references by sha.)+ return this.runOp(async () => {+ for await (const ev of this.send({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale })) {+ if (ev.type === "error") throw new Error(ev.message);+ if (ev.type === "score") return;+ }+ throw new Error("bridge stream ended before acking score");+ });}/** The harness schema version this client was generated from. */version(): string { return HARNESS_VERSION; }/** Close the remote session (graceful: the bridge EOFs the child's stdin- * so it flushes telemetry/trajectory on the way out). */+ * so it flushes telemetry/trajectory on the way out). Idempotent and+ * never throws — safe even when session creation failed. */async close(): Promise<void> {- const id = await this.sessionId;- await this.req("DELETE", `/v1/sessions/${id}`).catch(() => {});+ if (this.closed) return;+ this.closed = true;+ const id = await this.sessionId.catch(() => null);+ if (id === null) return; // creation failed or no session: nothing to close+ const res = await this.req("DELETE", `/v1/sessions/${id}`).catch(() => null);+ if (res) await res.text().catch(() => {});}++ /** Alias for close(). */+ dispose(): Promise<void> { return this.close(); }}/** Create a remote session, run a single turn, stream its events, close. */export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerator<Event> {const h = new RemoteHarness(opts);try {- yield* h.chat({ prompt: opts.prompt });+ yield* h.chat({ prompt: opts.prompt, images: opts.images });} finally {await h.close();}}-export const MODELS: 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 const TOOLS: 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 const MODELS: 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", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "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-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemma-4-31b", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5v-turbo", "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", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "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", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];diff --git a/scripts/test-remote-vision.py b/scripts/test-remote-vision.pynew file mode 100644index 00000000..7844ba3e--- /dev/null+++ b/scripts/test-remote-vision.py@@ -0,0 +1,158 @@+#!/usr/bin/env python3+"""Opt-in #615 witness: a random PNG crosses RemoteHarness + graff serve.++This intentionally makes one real provider call. Example:++ python3 scripts/test-remote-vision.py --model gpt-5.5++Set --bridge-url to exercise an already-running bridge; otherwise the script+starts zig-out/bin/graff serve on an ephemeral loopback port.+"""++from __future__ import annotations++import argparse+import base64+import binascii+import os+from pathlib import Path+import secrets+import socket+import struct+import subprocess+import sys+import time+import urllib.request+import zlib+++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "sdk" / "py"))+from harness_sdk import RemoteHarness # noqa: E402+++SEGMENTS = {+ "0": "ab cdef".replace(" ", ""),+ "1": "bc",+ "2": "abdeg",+ "3": "abcdg",+ "4": "bcfg",+ "5": "acdfg",+ "6": "acdefg",+ "7": "abc",+ "8": "abcdefg",+ "9": "abcdfg",+}+++def chunk(tag: bytes, data: bytes) -> bytes:+ body = tag + data+ return struct.pack(">I", len(data)) + body + struct.pack(">I", binascii.crc32(body) & 0xFFFFFFFF)+++def code_png(code: str, scale: int = 5) -> bytes:+ digit_w, height, gap, thick = 14, 24, 4, 3+ width = len(code) * (digit_w + gap) + gap+ pixels = [[255] * width for _ in range(height)]++ def rect(x: int, y: int, w: int, h: int) -> None:+ for row in range(max(0, y), min(height, y + h)):+ for col in range(max(0, x), min(width, x + w)):+ pixels[row][col] = 0++ for index, digit in enumerate(code):+ x = gap + index * (digit_w + gap)+ for segment in SEGMENTS[digit]:+ if segment == "a":+ rect(x + thick, 1, digit_w - 2 * thick, thick)+ elif segment == "b":+ rect(x + digit_w - thick - 1, 3, thick, 8)+ elif segment == "c":+ rect(x + digit_w - thick - 1, 13, thick, 8)+ elif segment == "d":+ rect(x + thick, height - thick - 1, digit_w - 2 * thick, thick)+ elif segment == "e":+ rect(x + 1, 13, thick, 8)+ elif segment == "f":+ rect(x + 1, 3, thick, 8)+ elif segment == "g":+ rect(x + thick, 11, digit_w - 2 * thick, thick)++ scaled_w, scaled_h = width * scale, height * scale+ rows = bytearray()+ for row in pixels:+ expanded = bytes(value for value in row for _ in range(scale))+ for _ in range(scale):+ rows.append(0) # PNG filter: none+ rows.extend(expanded)+ header = struct.pack(">IIBBBBB", scaled_w, scaled_h, 8, 0, 0, 0, 0)+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(bytes(rows), 9)) + chunk(b"IEND", b"")+++def free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def wait_for_bridge(url: str, process: subprocess.Popen[bytes] | None) -> None:+ deadline = time.monotonic() + 15+ while time.monotonic() < deadline:+ if process is not None and process.poll() is not None:+ raise RuntimeError(f"graff serve exited early with status {process.returncode}")+ try:+ with urllib.request.urlopen(url + "/healthz", timeout=0.5) as response:+ if response.status == 200:+ return+ except OSError:+ time.sleep(0.1)+ raise RuntimeError("graff serve did not become healthy within 15 seconds")+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--model", default=os.environ.get("GRAFF_VISION_MODEL"), help="vision-capable model (or GRAFF_VISION_MODEL)")+ parser.add_argument("--bridge-url", default=os.environ.get("GRAFF_SERVE_URL"), help="reuse a running bridge")+ parser.add_argument("--binary", default=str(ROOT / "zig-out" / "bin" / "graff"))+ args = parser.parse_args()+ if not args.model:+ parser.error("--model is required so this opt-in witness never spends against an accidental default")++ process: subprocess.Popen[bytes] | None = None+ url = args.bridge_url+ if not url:+ port = free_port()+ url = f"http://127.0.0.1:{port}"+ process = subprocess.Popen(+ [args.binary, "serve", "--host", "127.0.0.1", "--port", str(port)],+ cwd=ROOT,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )++ try:+ wait_for_bridge(url.rstrip("/"), process)+ code = "".join(secrets.choice("23456789") for _ in range(6))+ png = base64.b64encode(code_png(code)).decode("ascii")+ with RemoteHarness(url, model=args.model, yolo=True) as harness:+ answer = harness.ask(+ "Read the six digits shown in this image. Reply with the digits only.",+ images=[{"type": "image_base64", "media_type": "image/png", "data": png}],+ )+ digits = "".join(char for char in answer if char.isdigit())+ if code not in digits:+ raise AssertionError(f"expected image code {code}, model returned {answer!r}")+ print(f"ok: RemoteHarness → graff serve → {args.model} read unpredictable image code {code}")+ return 0+ finally:+ if process is not None:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sdk/README.md b/sdk/README.mdindex 4cfac6d0..d618493e 100644--- a/sdk/README.md+++ b/sdk/README.md@@ -86,16 +86,31 @@ for await (const ev of runAgentRemote({ url: "https://my-bridge.example", token,const h = RemoteHarness.init({ url: "http://127.0.0.1:8787", yolo: true });console.log(await h.ask("what files are here?"));+console.log(await h.ask({+ prompt: "read the code in this image",+ images: [{ type: "image_url", url: "https://example.com/code.png" }],+}));await h.close(); // graceful: the bridge EOFs the child's stdin``````python+import base64+from pathlib import Pathfrom harness_sdk import RemoteHarness # stdlib urllib only+png_base64 = base64.b64encode(Path("code.png").read_bytes()).decode()with RemoteHarness("http://127.0.0.1:8787", token="...", yolo=True) as h:- print(h.ask("what is 2+2?"))+ print(h.ask("read this image", images=[+ {"type": "image_base64", "media_type": "image/png", "data": png_base64},+ ]))```+Both clients preserve URL/base64 inputs as native provider vision parts.+`images` is capped at 16 entries and each decoded base64 image at 3.7 MB.+The opt-in real-provider witness generates a random-code PNG and verifies that+it survives the complete bridge: `python3 scripts/test-remote-vision.py+--model <vision-model>` (one provider call).+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). TheHTTP contract lives under the `serve` key of `graff --schema`.diff --git a/sdk/generate.py b/sdk/generate.pyindex b42911da..03e266bf 100644--- a/sdk/generate.py+++ b/sdk/generate.py@@ -138,9 +138,17 @@ export interface HarnessOptions {{args?: string[];}}+/** Native image input for a user turn. URLs stay URLs on every provider;+ * base64 is converted to that provider's image-content shape by Graff. */+export type ImageInput =+ | {{ type: "image_url"; url: string }}+ | {{ type: "image_base64"; mediaType: string; data: string }};+export interface ChatOptions {{/** User prompt for this turn. */prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];/** Run this turn in isolated, read-only review mode. */review?: boolean;/** Abort the turn mid-flight: on abort the SDK writes {{"type":"cancel"}}@@ -185,6 +193,8 @@ export interface AskResult {{export interface RunAgentOptions extends HarnessOptions {{/** User prompt to send to the agent. */prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];}}function spawnArgs(o: HarnessOptions): string[] {{@@ -439,6 +449,10 @@ export class Harness {{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 images = typeof input === "string" ? undefined : input.images?.map((image) =>+ image.type === "image_base64"+ ? {{ type: image.type, media_type: image.mediaType, data: image.data }}+ : image);const signal = typeof input === "string" ? undefined : input.signal;// Already aborted: send nothing — a cancel written before the turn's// first line would be cleared again when the turn starts.@@ -447,7 +461,7 @@ export class Harness {{let aborted = false;const onAbort = () => {{ if (aborted) return; aborted = true; this.cancel(); }};try {{- this.proc.stdin.write(JSON.stringify({{ type, text: prompt }}) + "\\n");+ this.proc.stdin.write(JSON.stringify({{ type, text: prompt, ...(images?.length ? {{ images }} : {{}}) }}) + "\\n");if (signal) {{signal.addEventListener("abort", onAbort, {{ once: true }});if (signal.aborted) onAbort(); // aborted between the entry check and here@@ -711,7 +725,7 @@ export class HarnessSession {{export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {{const h = new Harness(opts);try {{- yield* h.chat({{ prompt: opts.prompt }});+ yield* h.chat({{ prompt: opts.prompt, images: opts.images }});}} finally {{await h.close();}}@@ -831,8 +845,16 @@ export interface SessionInfo {{last_seq: number;}}+/** Native image input for a user turn. URLs stay URLs on every provider;+ * base64 is converted to that provider's image-content shape by Graff. */+export type ImageInput =+ | {{ type: "image_url"; url: string }}+ | {{ type: "image_base64"; mediaType: string; data: string }};+export interface ChatOptions {{prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];review?: boolean;/** Replay persisted events with seq >= from before this turn's live ones. */from?: number;@@ -878,6 +900,8 @@ export interface AskResult {{export interface RunAgentRemoteOptions extends RemoteOptions {{prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];}}/** Parse a streaming NDJSON response body into events. */@@ -1038,6 +1062,10 @@ export class RemoteHarness {{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 images = typeof input === "string" ? undefined : input.images?.map((image) =>+ image.type === "image_base64"+ ? {{ type: image.type, media_type: image.mediaType, data: image.data }}+ : image);const from = typeof input === "string" ? undefined : input.from;const signal = typeof input === "string" ? undefined : input.signal;signal?.throwIfAborted();@@ -1050,7 +1078,7 @@ export class RemoteHarness {{// cancel first, receive 409, and leave the following turn running.const id = await this.sessionId;const q = from === undefined ? "" : `?from=${{from}}`;- const res = await this.req("POST", `/v1/sessions/${{id}}${{q}}`, {{ type, text: prompt }});+ const res = await this.req("POST", `/v1/sessions/${{id}}${{q}}`, {{ type, text: prompt, ...(images?.length ? {{ images }} : {{}}) }});if (signal) {{signal.addEventListener("abort", onAbort, {{ once: true }});if (signal.aborted) onAbort();@@ -1240,7 +1268,7 @@ export class RemoteHarness {{export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerator<Event> {{const h = new RemoteHarness(opts);try {{- yield* h.chat({{ prompt: opts.prompt }});+ yield* h.chat({{ prompt: opts.prompt, images: opts.images }});}} finally {{await h.close();}}@@ -1268,13 +1296,27 @@ import threadingimport timeimport urllib.errorimport urllib.request-from typing import Iterator, Optional+from typing import Iterator, List, Literal, Optional, TypedDict, UnionMODELS = {json.dumps(models)}TOOLS = {json.dumps(tools)}PROVIDERS = {json.dumps(providers)}+class ImageUrlInput(TypedDict):+ type: Literal["image_url"]+ url: str+++class ImageBase64Input(TypedDict):+ type: Literal["image_base64"]+ media_type: str+ data: str+++ImageInput = Union[ImageUrlInput, ImageBase64Input]++def _sdk_install_id() -> str:"""Anonymous per-install id for SDK telemetry — its own id file, distinctfrom the harness CLI's install id, so SDK users are counted separately.@@ -1503,13 +1545,17 @@ class Harness:_report_error("spawn", f"{{binary}}: {{e}}")raise- def chat(self, text: str, review: bool = False) -> Iterator[dict]:+ def chat(self, text: str, review: bool = False,+ images: Optional[List[ImageInput]] = None) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError (after reporting to telemetry) if theharness process dies mid-turn instead of silently yielding nothing."""assert self.proc.stdin and self.proc.stdouttry:- self.proc.stdin.write(json.dumps({{"type": "review" if review else "user", "text": text}}) + "\\n")+ payload = {{"type": "review" if review else "user", "text": text}}+ if images:+ payload["images"] = images+ self.proc.stdin.write(json.dumps(payload) + "\\n")self.proc.stdin.flush()except OSError as e:_report_error("died", f"harness pipe closed on send: {{e}}")@@ -1530,20 +1576,20 @@ class Harness:_report_error("died", f"harness exited mid-turn (rc={{rc}})")raise RuntimeError(f"harness exited mid-turn (rc={{rc}})")- def ask(self, text: str) -> str:+ def ask(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run a turn and return just the final assistant text."""final = ""- for ev in self.chat(text):+ for ev in self.chat(text, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":raise RuntimeError(ev["message"])return final- def review(self, text: str) -> str:+ def review(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run one isolated, read-only review turn and return its report."""final = ""- for ev in self.chat(text, review=True):+ for ev in self.chat(text, review=True, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":@@ -1809,12 +1855,15 @@ class RemoteHarness:return self._stream(resp)def chat(self, text: str, review: bool = False,- from_seq: Optional[int] = None) -> Iterator[dict]:+ from_seq: Optional[int] = None,+ images: Optional[List[ImageInput]] = None) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError if the stream ends without one (thesession process died server-side)."""terminal = Falsepayload = {{"type": "review" if review else "user", "text": text}}+ if images:+ payload["images"] = imagesfor ev in self._send(payload, from_seq):yield evif ev.get("type") in ("turn", "error"):@@ -1823,20 +1872,20 @@ class RemoteHarness:if not terminal:raise RuntimeError("bridge stream ended mid-turn (session process died?)")- def ask(self, text: str) -> str:+ def ask(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run a turn and return just the final assistant text."""final = ""- for ev in self.chat(text):+ for ev in self.chat(text, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":raise RuntimeError(ev["message"])return final- def review(self, text: str) -> str:+ def review(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run one isolated, read-only review turn and return its report."""final = ""- for ev in self.chat(text, review=True):+ for ev in self.chat(text, review=True, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":@@ -1927,6 +1976,7 @@ def main():write(os.path.join(HERE, "ts", "harness.ts"), gen_ts(schema))write(os.path.join(HERE, "ts", "remote.ts"), gen_ts_remote(schema))write(os.path.join(HERE, "py", "harness_sdk.py"), gen_py(schema))+ write(os.path.join(HERE, "..", "examples", "edge-worker", "src", "remote.ts"), gen_ts_remote(schema))print("done.")diff --git a/sdk/py/README.md b/sdk/py/README.mdindex 204f6fc5..eccda94b 100644--- a/sdk/py/README.md+++ b/sdk/py/README.md@@ -70,12 +70,22 @@ Edge / serverless runtimes can't spawn a subprocess. Run `graff serve` somewhereand drive it over HTTP (stdlib `urllib` only):```python+import base64+from pathlib import Pathfrom harness_sdk import RemoteHarnesswith RemoteHarness("http://127.0.0.1:8787", token="...", yolo=True) as h:print(h.ask("what is 2+2?"))+ png = base64.b64encode(Path("code.png").read_bytes()).decode()+ print(h.ask("read the code in this image", images=[+ {"type": "image_base64", "media_type": "image/png", "data": png},+ ]))```+Remote images ride native provider vision blocks. Use `image_url` with an+HTTP(S) `url`, or `image_base64` with `media_type` and `data`; they are never+flattened into prompt text.+## Links- Repository: <https://github.com/justrach/codegraff>diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex d2742561..623dd78d 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -11,13 +11,27 @@ import threadingimport timeimport urllib.errorimport urllib.request-from typing import Iterator, Optional+from typing import Iterator, List, Literal, Optional, TypedDict, UnionMODELS = ["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", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "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-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemma-4-31b", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5v-turbo", "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", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "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", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"]TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"]PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kilo", "groq", "cerebras", "mistral", "kimi", "moonshot", "xai", "zai", "vercel", "openrouter", "fugu", "fireworks", "mlx", "lmstudio", "codex"]+class ImageUrlInput(TypedDict):+ type: Literal["image_url"]+ url: str+++class ImageBase64Input(TypedDict):+ type: Literal["image_base64"]+ media_type: str+ data: str+++ImageInput = Union[ImageUrlInput, ImageBase64Input]++def _sdk_install_id() -> str:"""Anonymous per-install id for SDK telemetry — its own id file, distinctfrom the harness CLI's install id, so SDK users are counted separately.@@ -246,13 +260,17 @@ class Harness:_report_error("spawn", f"{binary}: {e}")raise- def chat(self, text: str, review: bool = False) -> Iterator[dict]:+ def chat(self, text: str, review: bool = False,+ images: Optional[List[ImageInput]] = None) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError (after reporting to telemetry) if theharness process dies mid-turn instead of silently yielding nothing."""assert self.proc.stdin and self.proc.stdouttry:- self.proc.stdin.write(json.dumps({"type": "review" if review else "user", "text": text}) + "\n")+ payload = {"type": "review" if review else "user", "text": text}+ if images:+ payload["images"] = images+ self.proc.stdin.write(json.dumps(payload) + "\n")self.proc.stdin.flush()except OSError as e:_report_error("died", f"harness pipe closed on send: {e}")@@ -273,20 +291,20 @@ class Harness:_report_error("died", f"harness exited mid-turn (rc={rc})")raise RuntimeError(f"harness exited mid-turn (rc={rc})")- def ask(self, text: str) -> str:+ def ask(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run a turn and return just the final assistant text."""final = ""- for ev in self.chat(text):+ for ev in self.chat(text, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":raise RuntimeError(ev["message"])return final- def review(self, text: str) -> str:+ def review(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run one isolated, read-only review turn and return its report."""final = ""- for ev in self.chat(text, review=True):+ for ev in self.chat(text, review=True, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":@@ -552,12 +570,15 @@ class RemoteHarness:return self._stream(resp)def chat(self, text: str, review: bool = False,- from_seq: Optional[int] = None) -> Iterator[dict]:+ from_seq: Optional[int] = None,+ images: Optional[List[ImageInput]] = None) -> Iterator[dict]:"""Send a user turn; yield events until (and including) the 'turn'event. Raises RuntimeError if the stream ends without one (thesession process died server-side)."""terminal = Falsepayload = {"type": "review" if review else "user", "text": text}+ if images:+ payload["images"] = imagesfor ev in self._send(payload, from_seq):yield evif ev.get("type") in ("turn", "error"):@@ -566,20 +587,20 @@ class RemoteHarness:if not terminal:raise RuntimeError("bridge stream ended mid-turn (session process died?)")- def ask(self, text: str) -> str:+ def ask(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run a turn and return just the final assistant text."""final = ""- for ev in self.chat(text):+ for ev in self.chat(text, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":raise RuntimeError(ev["message"])return final- def review(self, text: str) -> str:+ def review(self, text: str, images: Optional[List[ImageInput]] = None) -> str:"""Run one isolated, read-only review turn and return its report."""final = ""- for ev in self.chat(text, review=True):+ for ev in self.chat(text, review=True, images=images):if ev.get("type") == "turn":final = ev["text"]elif ev.get("type") == "error":diff --git a/sdk/ts/README.md b/sdk/ts/README.mdindex 6d06d353..af741100 100644--- a/sdk/ts/README.md+++ b/sdk/ts/README.md@@ -102,9 +102,20 @@ for await (const ev of runAgentRemote({ url: "https://my-bridge.example", token,const h = RemoteHarness.init({ url: "http://127.0.0.1:8787", token, yolo: true });console.log(await h.ask("what files are here?"));+console.log(await h.ask({+ prompt: "read the code in this image",+ images: [+ { type: "image_url", url: "https://example.com/code.png" },+ { type: "image_base64", mediaType: "image/png", data: pngBase64 },+ ],+}));await h.close();```+`images` are native provider vision parts, not text pasted into the prompt.+They work on local `Harness` and edge-safe `RemoteHarness` turns and are+validated against the selected model and the 16-image/3.7 MB-per-image limits.+## Orchestration (#276): agent()/parallel()/pipeline(), budgets, resumable runs`@codegraff/sdk/orchestrate` is a deterministic scripting layer on top of thediff --git a/sdk/ts/harness.test.ts b/sdk/ts/harness.test.tsindex d5102bfe..88aa3476 100644--- a/sdk/ts/harness.test.ts+++ b/sdk/ts/harness.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, test } from "bun:test";import { join } from "node:path";-import { Harness } from "./harness.ts";+import { Harness, runAgent } from "./harness.ts";const binary = join(import.meta.dir, "test-fixtures", "fake-graff.mjs");const live: Harness[] = [];@@ -59,6 +59,36 @@ describe("Harness transport", () => {expect(await h.ask("plain")).toBe("user:plain");});+ test("serializes native URL and base64 image parts", async () => {+ const h = harness();+ const result = await h.ask({+ prompt: "images",+ images: [+ { type: "image_url", url: "https://images.test/code.png" },+ { type: "image_base64", mediaType: "image/png", data: "aGVsbG8=" },+ ],+ });+ expect(JSON.parse(result)).toEqual([+ { type: "image_url", url: "https://images.test/code.png" },+ { type: "image_base64", media_type: "image/png", data: "aGVsbG8=" },+ ]);+ });++ test("one-shot runAgent preserves native image parts", async () => {+ let result = "";+ for await (const event of runAgent({+ binary,+ env: { ...process.env, GRAFF_NO_TELEMETRY: "1" },+ prompt: "images",+ images: [{ type: "image_url", url: "https://images.test/one-shot.png" }],+ })) {+ if (event.type === "turn") result = event.text;+ }+ expect(JSON.parse(result)).toEqual([+ { type: "image_url", url: "https://images.test/one-shot.png" },+ ]);+ });+test("answer bypasses the operation lock during ask_user", async () => {const h = harness();let final = "";diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex ce664d22..82d9aeaa 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -81,9 +81,17 @@ export interface HarnessOptions {args?: string[];}+/** Native image input for a user turn. URLs stay URLs on every provider;+ * base64 is converted to that provider's image-content shape by Graff. */+export type ImageInput =+ | { type: "image_url"; url: string }+ | { type: "image_base64"; mediaType: string; data: string };+export interface ChatOptions {/** User prompt for this turn. */prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];/** Run this turn in isolated, read-only review mode. */review?: boolean;/** Abort the turn mid-flight: on abort the SDK writes {"type":"cancel"}@@ -128,6 +136,8 @@ export interface AskResult {export interface RunAgentOptions extends HarnessOptions {/** User prompt to send to the agent. */prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];}function spawnArgs(o: HarnessOptions): string[] {@@ -382,6 +392,10 @@ export class Harness {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 images = typeof input === "string" ? undefined : input.images?.map((image) =>+ image.type === "image_base64"+ ? { type: image.type, media_type: image.mediaType, data: image.data }+ : image);const signal = typeof input === "string" ? undefined : input.signal;// Already aborted: send nothing — a cancel written before the turn's// first line would be cleared again when the turn starts.@@ -390,7 +404,7 @@ export class Harness {let aborted = false;const onAbort = () => { if (aborted) return; aborted = true; this.cancel(); };try {- this.proc.stdin.write(JSON.stringify({ type, text: prompt }) + "\n");+ this.proc.stdin.write(JSON.stringify({ type, text: prompt, ...(images?.length ? { images } : {}) }) + "\n");if (signal) {signal.addEventListener("abort", onAbort, { once: true });if (signal.aborted) onAbort(); // aborted between the entry check and here@@ -654,7 +668,7 @@ export class HarnessSession {export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {const h = new Harness(opts);try {- yield* h.chat({ prompt: opts.prompt });+ yield* h.chat({ prompt: opts.prompt, images: opts.images });} finally {await h.close();}diff --git a/sdk/ts/remote.test.ts b/sdk/ts/remote.test.tsindex c8e73ee7..b46a0174 100644--- a/sdk/ts/remote.test.ts+++ b/sdk/ts/remote.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, test } from "bun:test";-import { RemoteHarness, type Event } from "./remote.ts";+import { RemoteHarness, runAgentRemote, type Event } from "./remote.ts";const originalFetch = globalThis.fetch;const live: RemoteHarness[] = [];@@ -9,6 +9,7 @@ const line = (event: Event) => enc.encode(`${JSON.stringify(event)}\n`);class FakeBridge {requests: string[] = [];+ bodies: Record<string, unknown>[] = [];readerCancels = 0;active?: ReadableStreamDefaultController<Uint8Array>;seq = 0;@@ -37,6 +38,7 @@ class FakeBridge {if (init?.method === "DELETE") return Response.json({ ok: true });const type = String(body.type ?? "reattach");this.requests.push(type);+ this.bodies.push(body);if (type === "cancel") {this.active?.enqueue(line(this.event({ type: "error", message: "turn cancelled" })));this.active = undefined;@@ -135,6 +137,35 @@ describe("RemoteHarness transport", () => {expect(await h.ask("after-error")).toBe("user:after-error");});+ test("serializes URL and base64 images as native protocol parts", async () => {+ const bridge = new FakeBridge();+ const h = use(bridge);+ expect(await h.ask({+ prompt: "read the code",+ images: [+ { type: "image_url", url: "https://images.test/code.png" },+ { type: "image_base64", mediaType: "image/png", data: "aGVsbG8=" },+ ],+ })).toBe("user:read the code");+ expect(bridge.bodies.find((body) => body.type === "user")?.images).toEqual([+ { type: "image_url", url: "https://images.test/code.png" },+ { type: "image_base64", media_type: "image/png", data: "aGVsbG8=" },+ ]);+ });++ test("one-shot runAgentRemote preserves native image parts", async () => {+ const bridge = new FakeBridge();+ globalThis.fetch = bridge.fetch as typeof fetch;+ for await (const _event of runAgentRemote({+ url: "http://bridge.test",+ prompt: "read the code",+ images: [{ type: "image_url", url: "https://images.test/one-shot.png" }],+ })) {}+ expect(bridge.bodies.find((body) => body.type === "user")?.images).toEqual([+ { type: "image_url", url: "https://images.test/one-shot.png" },+ ]);+ });+test("AbortSignal sends an out-of-band cancel and later turns still work", async () => {const bridge = new FakeBridge();const h = use(bridge);diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex b3bd2239..4867205e 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -92,8 +92,16 @@ export interface SessionInfo {last_seq: number;}+/** Native image input for a user turn. URLs stay URLs on every provider;+ * base64 is converted to that provider's image-content shape by Graff. */+export type ImageInput =+ | { type: "image_url"; url: string }+ | { type: "image_base64"; mediaType: string; data: string };+export interface ChatOptions {prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];review?: boolean;/** Replay persisted events with seq >= from before this turn's live ones. */from?: number;@@ -139,6 +147,8 @@ export interface AskResult {export interface RunAgentRemoteOptions extends RemoteOptions {prompt: string;+ /** Native vision parts (max 16); never flattened into prompt text. */+ images?: ImageInput[];}/** Parse a streaming NDJSON response body into events. */@@ -299,6 +309,10 @@ export class RemoteHarness {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 images = typeof input === "string" ? undefined : input.images?.map((image) =>+ image.type === "image_base64"+ ? { type: image.type, media_type: image.mediaType, data: image.data }+ : image);const from = typeof input === "string" ? undefined : input.from;const signal = typeof input === "string" ? undefined : input.signal;signal?.throwIfAborted();@@ -311,7 +325,7 @@ export class RemoteHarness {// cancel first, receive 409, and leave the following turn running.const id = await this.sessionId;const q = from === undefined ? "" : `?from=${from}`;- const res = await this.req("POST", `/v1/sessions/${id}${q}`, { type, text: prompt });+ const res = await this.req("POST", `/v1/sessions/${id}${q}`, { type, text: prompt, ...(images?.length ? { images } : {}) });if (signal) {signal.addEventListener("abort", onAbort, { once: true });if (signal.aborted) onAbort();@@ -501,7 +515,7 @@ export class RemoteHarness {export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerator<Event> {const h = new RemoteHarness(opts);try {- yield* h.chat({ prompt: opts.prompt });+ yield* h.chat({ prompt: opts.prompt, images: opts.images });} finally {await h.close();}diff --git a/sdk/ts/test-fixtures/fake-graff.mjs b/sdk/ts/test-fixtures/fake-graff.mjsindex 4ff22d58..91566848 100755--- a/sdk/ts/test-fixtures/fake-graff.mjs+++ b/sdk/ts/test-fixtures/fake-graff.mjs@@ -24,6 +24,11 @@ createInterface({ input: process.stdin }).on("line", (line) => {emit({ type: "ask_user", call_id: "ask-1", question: "continue?", options: ["yes"] });return;}+ if (request.text === "images") {+ turn(JSON.stringify(request.images));+ active = null;+ return;+ }setTimeout(() => {turn(`${request.type}:${request.text}`);active = null;diff --git a/src/json_controls.zig b/src/json_controls.zigindex c46abe54..3e13205c 100644--- a/src/json_controls.zig+++ b/src/json_controls.zig@@ -10,8 +10,10 @@ const std = @import("std");const Allocator = std.mem.Allocator;const Agent = @import("agent.zig").Agent;+const json_inbox = @import("json_inbox.zig");const main_mod = @import("main.zig");const side_question = @import("side_question.zig");+const remote_images = @import("remote_images.zig");/// `{"type":"btw","text":"…"}` — #415's side question, the GUI's half of the/// feature. True when the request WAS a side question and is now fully@@ -45,6 +47,28 @@ pub fn applyToolKnobs(obj: std.json.ObjectMap) void {}}+/// Turn-scoped JSON options: tool ceilings plus native image parts. False+/// means image validation already emitted the request error.+pub fn applyTurnOptions(root: *Agent, obj: std.json.ObjectMap) bool {+ if (!remote_images.stage(root, obj)) return false;+ applyToolKnobs(obj);+ return true;+}++/// Claim the dequeued JSON turn, then validate and stage all of its options.+/// A rejected request releases inbox ownership before the next request.+pub fn beginTurn(root: *Agent, obj: std.json.ObjectMap) bool {+ if (!json_inbox.beginTurn(root)) return false;+ if (applyTurnOptions(root, obj)) return true;+ json_inbox.endTurn();+ return false;+}++pub fn rejectTurn(root: *Agent, message: []const u8) void {+ root.emit(.{ .type = "error", .message = message });+ json_inbox.endTurn();+}+test "applyToolKnobs reads both spellings and ignores junk" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/mainloop.zig b/src/mainloop.zigindex 5e0b9cb1..7e820384 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -288,7 +288,7 @@ pub fn run(ctx: *Ctx) !void {// #415: a side question is ANSWERED here and never becomes a turn —// billed, parent-prefix cached, nothing added to the session.if (json_controls.sideQuestion(ctx.root, ctx.arena, rtype, text)) continue;- json_controls.applyToolKnobs(parsed.object);+ if (!json_controls.beginTurn(ctx.root, parsed.object)) continue;break :blk text;} else line;ctx.root.review_mode = review_prompt != null;@@ -302,13 +302,12 @@ pub fn run(ctx: *Ctx) !void {if (ctx.root.fallback_blocked) {const message = try std.fmt.allocPrint(ctx.arena, "saved model unavailable; sending to {s} requires explicit consent — run /fallback allow {s} or choose /model", .{ ctx.root.provider.id, ctx.root.provider.id });- if (main_mod.json_mode) ctx.root.emit(.{ .type = "error", .message = message }) else {+ if (main_mod.json_mode) json_controls.rejectTurn(ctx.root, message) else {try ctx.out.print("{s}⚠ {s}{s}\n", .{ style.yellow, message, style.reset });try ctx.out.flush();}continue;}- if (main_mod.json_mode and !json_inbox.beginTurn(ctx.root)) continue;if (!main_mod.json_mode) agent_mod.Agent.prepareRootTurn();// Persistent goal steering (#318): diff-gated standing-goal plus one-shotdiff --git a/src/readline_history.zig b/src/readline_history.zigindex f8d3b81a..da830e80 100644--- a/src/readline_history.zig+++ b/src/readline_history.zig@@ -115,7 +115,7 @@ pub fn repeatsLast(fn sameImage(a: ?PendingImage, b: ?PendingImage) bool {const x = a orelse return b == null;const y = b orelse return false;- return std.mem.eql(u8, x.media_type, y.media_type) and std.mem.eql(u8, x.b64, y.b64);+ return std.mem.eql(u8, x.media_type, y.media_type) and std.mem.eql(u8, x.b64, y.b64) and std.mem.eql(u8, x.url, y.url);}const no_images: []const ?PendingImage = &.{};diff --git a/src/remote_images.zig b/src/remote_images.zignew file mode 100644index 00000000..0d1d67dd--- /dev/null+++ b/src/remote_images.zig@@ -0,0 +1,113 @@+//! Native image parts on the JSON/serve user-turn boundary (#615).+//!+//! The request owns its parsed strings only until mainloop advances, so this+//! module validates every part first, then copies it into the Agent's existing+//! staged-image queue. `vision.imageMessages` performs the provider-specific+//! Anthropic/OpenAI/Responses conversion at the ordinary prompt boundary.++const std = @import("std");+const Value = std.json.Value;++const Agent = @import("agent.zig").Agent;+const vision = @import("vision.zig");+const vision_queue = @import("vision_queue.zig");++const Spec = union(enum) {+ url: []const u8,+ base64: struct { media_type: []const u8, data: []const u8 },+};++fn stringField(obj: std.json.ObjectMap, name: []const u8) []const u8 {+ const value = obj.get(name) orelse return "";+ return if (value == .string) value.string else "";+}++fn fail(root: *Agent, message: []const u8) bool {+ root.emit(.{ .type = "error", .message = message });+ return false;+}++fn validUrl(url: []const u8) bool {+ return url.len <= 8192 and+ (std.mem.startsWith(u8, url, "https://") or std.mem.startsWith(u8, url, "http://"));+}++/// Validate and stage `images` from one `{type:"user",text,images}` request.+/// Canonical wire fields are snake_case; `mediaType` is accepted for the+/// generated TypeScript SDK's idiomatic public shape.+pub fn stage(root: *Agent, request: std.json.ObjectMap) bool {+ const value = request.get("images") orelse return true;+ if (value != .array) return fail(root, "request images must be an array");+ const parts = value.array.items;+ if (parts.len == 0) return true;+ if (parts.len + root.pending_image_len > vision_queue.cap)+ return fail(root, "request exceeds the 16-image limit");+ if (!vision.visionCapable(root.provider))+ return fail(root, "the selected model does not advertise native image input");++ var specs: [vision_queue.cap]Spec = undefined;+ for (parts, 0..) |part, i| {+ if (part != .object) return fail(root, "each request image must be an object");+ const kind = stringField(part.object, "type");+ if (std.mem.eql(u8, kind, "image_url")) {+ const url = stringField(part.object, "url");+ if (!validUrl(url)) return fail(root, "image_url needs an http(s) URL of at most 8192 bytes");+ specs[i] = .{ .url = url };+ continue;+ }+ if (std.mem.eql(u8, kind, "image_base64")) {+ const data = stringField(part.object, "data");+ const snake = stringField(part.object, "media_type");+ const camel = stringField(part.object, "mediaType");+ const media_type = if (snake.len > 0) snake else camel;+ if (!std.mem.startsWith(u8, media_type, "image/"))+ return fail(root, "image_base64 needs an image/* media_type");+ const bytes = std.base64.standard.Decoder.calcSizeForSlice(data) catch+ return fail(root, "image_base64 data is not valid base64");+ if (bytes == 0 or bytes > vision.max_staged_image_bytes)+ return fail(root, "image_base64 is empty or exceeds the staged-image limit");+ {+ const scratch = root.gpa.alloc(u8, bytes) catch+ return fail(root, "could not validate remote image data");+ defer root.gpa.free(scratch);+ std.base64.standard.Decoder.decode(scratch, data) catch+ return fail(root, "image_base64 data is not valid base64");+ }+ specs[i] = .{ .base64 = .{ .media_type = media_type, .data = data } };+ continue;+ }+ return fail(root, "request image type must be image_url or image_base64");+ }++ const prior_len = root.pending_image_len;+ const prior_latest = root.pending_image;+ for (specs[0..parts.len]) |spec| {+ const image: vision.PendingImage = switch (spec) {+ .url => |url| .{+ .media_type = "",+ .b64 = "",+ .url = root.arena.dupe(u8, url) catch {+ root.pending_image_len = prior_len;+ root.pending_image = prior_latest;+ return fail(root, "could not retain remote image URL");+ },+ .label = "remote URL",+ },+ .base64 => |b| .{+ .media_type = root.arena.dupe(u8, b.media_type) catch {+ root.pending_image_len = prior_len;+ root.pending_image = prior_latest;+ return fail(root, "could not retain remote image media type");+ },+ .b64 = root.arena.dupe(u8, b.data) catch {+ root.pending_image_len = prior_len;+ root.pending_image = prior_latest;+ return fail(root, "could not retain remote image data");+ },+ .label = "remote image",+ },+ };+ vision_queue.stage(root, image);+ }+ return true;+}diff --git a/src/schema_protocol.zig b/src/schema_protocol.zigindex f350156c..1eab7017 100644--- a/src/schema_protocol.zig+++ b/src/schema_protocol.zig@@ -36,7 +36,7 @@ pub const flags =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\":\"cancel\"} interrupts an active 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\",\"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\"}, {\"type\":\"set_fast\",\"on\":true}, and {\"type\":\"set_ultracode\",\"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",+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\",\"images\":[{\"type\":\"image_url\",\"url\":\"https://...\"},{\"type\":\"image_base64\",\"media_type\":\"image/png\",\"data\":\"...\"}]} sends a native multimodal user turn (images optional, max 16); {\"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\":\"cancel\"} interrupts an active 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\",\"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\"}, {\"type\":\"set_fast\",\"on\":true}, and {\"type\":\"set_ultracode\",\"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": [diff --git a/src/schema_serve.zig b/src/schema_serve.zigindex 4839786a..83f82daf 100644--- a/src/schema_serve.zig+++ b/src/schema_serve.zig@@ -11,7 +11,7 @@ pub const 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 OR resume a session (a graff --json child); optional JSON body {\"session\",\"model\",\"subagentProvider\",\"subagentModel\",\"allowCrossProviderSubagents\",\"noSubagentTier\",\"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 / set_ultracode / score / answer / cancel); ordinary requests stream application/x-ndjson events until their terminal event (turn/error, or the request-specific ack); answer and cancel return a JSON ack while the original user stream continues; one ordinary 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": "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 / set_ultracode / score / answer / cancel). user/review may include images: [{\"type\":\"image_url\",\"url\":\"https://...\"}|{\"type\":\"image_base64\",\"media_type\":\"image/png\",\"data\":\"...\"}] (max 16), preserved as native provider vision parts; ordinary requests stream application/x-ndjson events until their terminal event (turn/error, or the request-specific ack); answer and cancel return a JSON ack while the original user stream continues; one ordinary 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/vision.zig b/src/vision.zigindex bd8383f4..fa5e63f4 100644--- a/src/vision.zig+++ b/src/vision.zig@@ -34,6 +34,7 @@ pub const fmtBytes = clip.fmtMb;pub const PendingImage = struct {media_type: []const u8,b64: []const u8,+ url: []const u8 = "",label: []const u8,/// Ctrl-V / drop inserted a composer chip. Submit keeps the payload only/// while that chip (or an `@[path]`) is still in the prompt (#634).@@ -100,20 +101,27 @@ pub fn imageMessages(arena: Allocator, kind: Provider.Kind, text: []const u8, im.anthropic => {try ib.put(arena, "type", .{ .string = "image" });var src: std.json.ObjectMap = .empty;- try src.put(arena, "type", .{ .string = "base64" });- try src.put(arena, "media_type", .{ .string = img.media_type });- try src.put(arena, "data", .{ .string = img.b64 });+ if (img.url.len > 0) {+ try src.put(arena, "type", .{ .string = "url" });+ try src.put(arena, "url", .{ .string = img.url });+ } else {+ try src.put(arena, "type", .{ .string = "base64" });+ try src.put(arena, "media_type", .{ .string = img.media_type });+ try src.put(arena, "data", .{ .string = img.b64 });+ }try ib.put(arena, "source", .{ .object = src });},.openai => {try ib.put(arena, "type", .{ .string = "image_url" });var iu: std.json.ObjectMap = .empty;- try iu.put(arena, "url", .{ .string = try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 }) });+ const url = if (img.url.len > 0) img.url else try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 });+ try iu.put(arena, "url", .{ .string = url });try ib.put(arena, "image_url", .{ .object = iu });},.responses => {try ib.put(arena, "type", .{ .string = "input_image" });- try ib.put(arena, "image_url", .{ .string = try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 }) });+ const url = if (img.url.len > 0) img.url else try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 });+ try ib.put(arena, "image_url", .{ .string = url });},}try content.append(.{ .object = ib });diff --git a/src/vision_queue.zig b/src/vision_queue.zigindex 7ac4e992..7b748b07 100644--- a/src/vision_queue.zig+++ b/src/vision_queue.zig@@ -119,7 +119,7 @@ fn selectForPrompt(imgs: []const PendingImage, text: []const u8, keep: *[cap]Penif (!want) continue;var dup = false;for (keep[0..n]) |k| {- if (std.mem.eql(u8, k.b64, img.b64)) {+ if (std.mem.eql(u8, k.b64, img.b64) and std.mem.eql(u8, k.url, img.url)) {dup = true;break;}@@ -230,6 +230,60 @@ test "ask_user images become follow-up vision blocks (#580)" {try std.testing.expect(std.mem.indexOf(u8, content[2].object.get("image_url").?.string, "BBB") != null);}+test "remote URL and base64 parts become native provider image blocks (#615)" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const request = try std.json.parseFromSliceLeaky(Value, arena,+ \\{"type":"user","text":"read it","images":[+ \\ {"type":"image_url","url":"https://images.test/code.png"},+ \\ {"type":"image_base64","mediaType":"image/png","data":"aGVsbG8="}]}+ , .{});+ const remote = @import("remote_images.zig");++ for ([_]@import("provider.zig").Provider.Kind{ .responses, .openai, .anthropic }) |kind| {+ var root = testAgent(arena);+ root.provider.kind = kind;+ try std.testing.expect(remote.stage(&root, request.object));+ const msg = try consumePromptImages(arena, &root, "read it");+ const content = msg.object.get("content").?.array.items;+ try std.testing.expectEqual(@as(usize, 3), content.len);+ switch (kind) {+ .responses => {+ try std.testing.expectEqualStrings("https://images.test/code.png", content[1].object.get("image_url").?.string);+ try std.testing.expectEqualStrings("data:image/png;base64,aGVsbG8=", content[2].object.get("image_url").?.string);+ },+ .openai => {+ try std.testing.expectEqualStrings("https://images.test/code.png", content[1].object.get("image_url").?.object.get("url").?.string);+ try std.testing.expectEqualStrings("data:image/png;base64,aGVsbG8=", content[2].object.get("image_url").?.object.get("url").?.string);+ },+ .anthropic => {+ const url_source = content[1].object.get("source").?.object;+ const b64_source = content[2].object.get("source").?.object;+ try std.testing.expectEqualStrings("url", url_source.get("type").?.string);+ try std.testing.expectEqualStrings("https://images.test/code.png", url_source.get("url").?.string);+ try std.testing.expectEqualStrings("base64", b64_source.get("type").?.string);+ try std.testing.expectEqualStrings("aGVsbG8=", b64_source.get("data").?.string);+ },+ }+ }+}++test "remote image validation rejects malformed data before staging (#615)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var root = testAgent(arena);+ const bad = try std.json.parseFromSliceLeaky(Value, arena,+ \\{"type":"user","text":"read it","images":[+ \\ {"type":"image_url","url":"https://images.test/valid.png"},+ \\ {"type":"image_base64","media_type":"image/png","data":"!!!!"}]}+ , .{});+ try std.testing.expect(!@import("remote_images.zig").stage(&root, bad.object));+ try std.testing.expectEqual(@as(u8, 0), root.pending_image_len);+}+test "placeholder-only ask_user reply gets an explicit fallback" {const note = try withUnsupportedNote(std.testing.allocator, "[Image] [Image]");defer std.testing.allocator.free(note);