Skip to content

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

Python

feat(sdk): add production embedding parity

Rach Pradhan8ec8195fcc9f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b21ee987..5ebe3f2d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -28,10 +28,18 @@ jobs:
with:
node-version: 22
- - name: TypeScript SDK validation
+ - uses: oven-sh/setup-bun@v2
+
+ - name: TypeScript SDK test, typecheck, build, and package smoke
+ working-directory: sdk/ts
run: |
- node -e "JSON.parse(require('fs').readFileSync('sdk/ts/package.json','utf8')); console.log('package.json ok')"
- node --experimental-strip-types -e "import('./sdk/ts/harness.ts').then(m => { if (!m.Harness || !m.runAgent || !m.MODELS) throw new Error('missing exports'); console.log('ts sdk ok:', m.MODELS.length, 'models'); })"
+ npm install --ignore-scripts --workspaces=false
+ bun test
+ npm run typecheck
+ npm run build
+ npm pack --dry-run
+ npm run test:packed
+ node -e "import('./dist/harness.js').then(m => { if (!m.Harness || !m.runAgent || !m.MODELS) throw new Error('missing exports'); console.log('ts sdk ok:', m.MODELS.length, 'models'); })"
# Zig build / fmt / test + SDK drift, pinned to the exact 0.17 dev build the
# codebase targets.
diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml
index f56f0dd8..b3cc0ab2 100644
--- a/.github/workflows/sdk.yml
+++ b/.github/workflows/sdk.yml
@@ -12,7 +12,87 @@ permissions:
contents: read
jobs:
+ native:
+ name: native ${{ matrix.target }}
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - target: aarch64-macos
+ asset: graff-aarch64-macos.tar.gz
+ package_dir: graff-darwin-arm64
+ - target: x86_64-macos
+ asset: graff-x86_64-macos.tar.gz
+ package_dir: graff-darwin-x64
+ - target: aarch64-linux
+ asset: graff-aarch64-linux.tar.gz
+ package_dir: graff-linux-arm64
+ - target: x86_64-linux
+ asset: graff-x86_64-linux.tar.gz
+ package_dir: graff-linux-x64
+ - target: aarch64-windows
+ asset: graff-aarch64-windows.tar.gz
+ package_dir: graff-win32-arm64
+ - target: x86_64-windows
+ asset: graff-x86_64-windows.tar.gz
+ package_dir: graff-win32-x64
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: "24"
+ registry-url: "https://registry.npmjs.org"
+ - name: Package and publish release binary
+ env:
+ GH_TOKEN: ${{ github.token }}
+ GRAFF_NATIVE_RELEASE: ${{ vars.GRAFF_NATIVE_RELEASE }}
+ run: |
+ set -euo pipefail
+ [ -n "$GRAFF_NATIVE_RELEASE" ] || {
+ echo "set the GRAFF_NATIVE_RELEASE repository variable to the compatible v* release" >&2
+ exit 1
+ }
+ npm install -g npm@latest
+ git fetch --no-tags origin "refs/tags/$GRAFF_NATIVE_RELEASE:refs/tags/$GRAFF_NATIVE_RELEASE"
+ sdk_protocol="$(sed -n 's/^export const HARNESS_VERSION = "\([^"]*\)";.*/\1/p' sdk/ts/harness.ts)"
+ release_protocol="$(git show "$GRAFF_NATIVE_RELEASE:sdk/ts/harness.ts" | sed -n 's/^export const HARNESS_VERSION = "\([^"]*\)";.*/\1/p')"
+ [ -n "$sdk_protocol" ] && [ "$release_protocol" = "$sdk_protocol" ] || {
+ echo "$GRAFF_NATIVE_RELEASE uses protocol ${release_protocol:-unknown}; SDK requires $sdk_protocol" >&2
+ exit 1
+ }
+ is_draft="$(gh release view "$GRAFF_NATIVE_RELEASE" --json isDraft --jq .isDraft)"
+ [ "$is_draft" = false ] || {
+ echo "$GRAFF_NATIVE_RELEASE is still a draft; publish and sign its final assets before the SDK" >&2
+ exit 1
+ }
+ gh release download "$GRAFF_NATIVE_RELEASE" --pattern "${{ matrix.asset }}" --pattern SHA256SUMS
+ grep -F "${{ matrix.asset }}" SHA256SUMS | sha256sum -c -
+ mkdir native-unpack native-packages
+ tar -xzf "${{ matrix.asset }}" -C native-unpack
+ binary_name=graff
+ case "${{ matrix.target }}" in *-windows) binary_name=graff.exe ;; esac
+ binary="$(find native-unpack -type f -name "$binary_name" -print -quit)"
+ [ -n "$binary" ] || { echo "archive contains no $binary_name" >&2; exit 1; }
+ version="${GITHUB_REF_NAME#sdk-v}"
+ node sdk/ts/scripts/package-platform.mjs \
+ --target "${{ matrix.target }}" --binary "$binary" \
+ --version "$version" --out native-packages
+ package="$(node -p "require('./native-packages/${{ matrix.package_dir }}/package.json').name")"
+ published_version="$(npm view "$package@$version" version 2>/dev/null || true)"
+ if [ -n "$published_version" ]; then
+ published_protocol="$(npm view "$package@$version" graffProtocol 2>/dev/null || true)"
+ [ "$published_protocol" = "$sdk_protocol" ] || {
+ echo "$package@$version already exists with protocol ${published_protocol:-unknown}" >&2
+ exit 1
+ }
+ echo "$package@$version already published; keeping immutable package"
+ else
+ npm publish "native-packages/${{ matrix.package_dir }}" --access public
+ fi
+
publish:
+ needs: native
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
@@ -36,9 +116,15 @@ jobs:
with:
node-version: "24"
registry-url: "https://registry.npmjs.org"
- - name: Publish @codegraff/sdk (npm, OIDC + provenance)
+ - uses: oven-sh/setup-bun@v2
+ - name: Test and publish @codegraff/sdk (npm, OIDC + provenance)
working-directory: sdk/ts
run: |
npm install -g npm@latest
- npm version "${GITHUB_REF_NAME#sdk-v}" --no-git-tag-version --allow-same-version
+ npm run version:sync -- "${GITHUB_REF_NAME#sdk-v}"
+ npm install --ignore-scripts --workspaces=false
+ bun test
+ npm run typecheck
+ npm run build
+ npm run test:packed
npm publish --access public
diff --git a/scripts/test-json-cancel.py b/scripts/test-json-cancel.py
new file mode 100644
index 00000000..54180160
--- /dev/null
+++ b/scripts/test-json-cancel.py
@@ -0,0 +1,261 @@
+#!/usr/bin/env python3
+"""Offline end-to-end regression for mid-turn JSON cancellation."""
+
+import http.client
+import http.server
+import json
+import os
+import queue
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+
+GRAFF = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")
+
+
+class Mock(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+ calls = 0
+ lock = threading.Lock()
+
+ def log_message(self, *_args):
+ pass
+
+ def do_GET(self):
+ body = json.dumps({"data": [{"id": "mock"}]}).encode()
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ length = int(self.headers.get("content-length", "0"))
+ self.rfile.read(length)
+ with self.lock:
+ type(self).calls += 1
+ call = type(self).calls
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.send_header("connection", "close")
+ self.end_headers()
+ if call == 1:
+ chunks = [
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "cancel-probe",
+ "type": "function", "function": {"name": "bash", "arguments": json.dumps({"command": "sleep 20"})}}]},
+ "finish_reason": None}]},
+ {"choices": [{"delta": {}, "finish_reason": "tool_calls"}]},
+ ]
+ else:
+ chunks = [
+ {"choices": [{"delta": {"content": "after-cancel-ok"}, "finish_reason": None}]},
+ {"choices": [{"delta": {}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 2, "completion_tokens": 1, "total_tokens": 3}},
+ ]
+ for chunk in chunks:
+ self.wfile.write(b"data: " + json.dumps(chunk).encode() + b"\n\n")
+ self.wfile.write(b"data: [DONE]\n\n")
+ self.wfile.flush()
+ self.close_connection = True
+
+
+def read_events(proc, events):
+ for line in proc.stdout:
+ try:
+ events.put(json.loads(line))
+ except json.JSONDecodeError:
+ pass
+
+
+def event_until(events, predicate, timeout=8):
+ deadline = time.monotonic() + timeout
+ seen = []
+ while time.monotonic() < deadline:
+ try:
+ event = events.get(timeout=min(0.1, deadline - time.monotonic()))
+ except queue.Empty:
+ continue
+ seen.append(event)
+ if predicate(event):
+ return event
+ raise AssertionError(f"timed out waiting for event; saw {seen!r}")
+
+
+def send(proc, request):
+ proc.stdin.write(json.dumps(request) + "\n")
+ proc.stdin.flush()
+
+
+def free_port():
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+def http_json(port, method, path, body=None, timeout=10):
+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout)
+ payload = None if body is None else json.dumps(body)
+ conn.request(method, path, payload, {"content-type": "application/json"})
+ response = conn.getresponse()
+ raw = response.read()
+ conn.close()
+ return response.status, json.loads(raw) if raw else None
+
+
+def stream_http(port, path, body, events):
+ conn = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
+ try:
+ conn.request("POST", path, json.dumps(body), {"content-type": "application/json"})
+ response = conn.getresponse()
+ events.put({"type": "headers", "status": response.status})
+ if response.status != 200:
+ raise AssertionError(f"turn POST returned {response.status}: {response.read()[:200]!r}")
+ while line := response.readline():
+ if line.strip():
+ events.put(json.loads(line))
+ except Exception as exc:
+ events.put({"type": "stream_error", "message": repr(exc)})
+ finally:
+ conn.close()
+
+
+def main():
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 1234), Mock)
+ server.daemon_threads = True
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-json-cancel-") as tmp:
+ env = {**os.environ, "HOME": tmp, "CODEGRAFF_API_KEY": "offline-test-key", "LMSTUDIO_API_KEY": "offline-test-key",
+ "GRAFF_NO_TELEMETRY": "1", "GRAFF_NO_SMOLIFY": "1"}
+ proc = subprocess.Popen(
+ [GRAFF, "--json", "--model", "lmstudio", "--yolo", "--no-telemetry"],
+ cwd=tmp, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True, bufsize=1,
+ )
+ events = queue.Queue()
+ threading.Thread(target=read_events, args=(proc, events), daemon=True).start()
+ try:
+ send(proc, {"type": "user", "text": "block until cancelled"})
+ event_until(events, lambda e: e.get("type") == "tool_call" and e.get("name") == "bash")
+ started = time.monotonic()
+ send(proc, {"type": "cancel"})
+ event_until(events, lambda e: e.get("type") == "error" and e.get("message") == "turn cancelled")
+ assert time.monotonic() - started < 5, "cancel queued behind the active turn"
+
+ send(proc, {"type": "user", "text": "prove the inbox still owns stdin"})
+ turn = event_until(events, lambda e: e.get("type") == "turn", timeout=10)
+ assert turn.get("text") == "after-cancel-ok", turn
+
+ # AbortSignal can fire immediately after the SDK writes the user
+ # line, before mainloop has dequeued it. The inbox must retain
+ # that cancellation for the queued turn rather than lose it.
+ send(proc, {"type": "user", "text": "cancel before started"})
+ send(proc, {"type": "cancel"})
+ event_until(events, lambda e: e.get("type") == "error" and e.get("message") == "turn cancelled")
+ send(proc, {"type": "user", "text": "still usable after queued cancel"})
+ turn = event_until(events, lambda e: e.get("type") == "turn", timeout=10)
+ assert turn.get("text") == "after-cancel-ok", turn
+ print("ok: active and queued JSON turns cancel cleanly; later turns still complete")
+ finally:
+ proc.stdin.close()
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ if proc.returncode != 0:
+ raise AssertionError(proc.stderr.read())
+
+ with Mock.lock:
+ Mock.calls = 0
+ port = free_port()
+ serve = subprocess.Popen(
+ [GRAFF, "serve", "--host", "127.0.0.1", "--port", str(port),
+ "--model", "lmstudio", "--yolo", "--no-telemetry"],
+ cwd=tmp, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ stderr=subprocess.PIPE, text=True,
+ )
+ serve_stderr = []
+ threading.Thread(target=lambda: serve_stderr.extend(serve.stderr), daemon=True).start()
+ session_id = None
+ try:
+ for _ in range(200):
+ if serve.poll() is not None:
+ raise AssertionError(f"graff serve exited early ({serve.returncode})")
+ try:
+ status, _ = http_json(port, "GET", "/healthz", timeout=2)
+ if status == 200:
+ break
+ except OSError:
+ time.sleep(0.05)
+ else:
+ raise AssertionError("graff serve never became healthy")
+
+ status, created = http_json(port, "POST", "/v1/sessions",
+ {"session": "cancel-e2e", "model": "lmstudio", "yolo": True})
+ assert status == 201, (status, created)
+ session_id = created["session_id"]
+ path = f"/v1/sessions/{session_id}"
+ events = queue.Queue()
+ turn_thread = threading.Thread(
+ target=stream_http,
+ args=(port, path, {"type": "user", "text": "block in serve until cancelled"}, events),
+ daemon=True,
+ )
+ turn_thread.start()
+ try:
+ event_until(events, lambda e: e.get("type") == "tool_call" and e.get("name") == "bash")
+ except AssertionError as exc:
+ event_log = os.path.join(tmp, ".graff", "serve", f"{session_id}.events.jsonl")
+ log_tail = "<missing>"
+ if os.path.exists(event_log):
+ with open(event_log) as log_file:
+ log_tail = log_file.read()[-2000:]
+ raise AssertionError(
+ f"{exc}; mock calls={Mock.calls}; event log={log_tail!r}; "
+ f"serve stderr={''.join(serve_stderr)[-2000:]!r}"
+ ) from exc
+ started = time.monotonic()
+ status, cancelled = http_json(port, "POST", path, {"type": "cancel"})
+ assert status == 200 and cancelled.get("type") == "cancel", (status, cancelled)
+ event_until(events, lambda e: e.get("type") == "error" and e.get("message") == "turn cancelled")
+ assert time.monotonic() - started < 5, "serve cancel waited behind the active turn"
+ turn_thread.join(timeout=2)
+ assert not turn_thread.is_alive(), "cancelled serve stream did not close"
+
+ events = queue.Queue()
+ turn_thread = threading.Thread(
+ target=stream_http,
+ args=(port, path, {"type": "user", "text": "prove serve session reuse"}, events),
+ daemon=True,
+ )
+ turn_thread.start()
+ turn = event_until(events, lambda e: e.get("type") == "turn", timeout=10)
+ assert turn.get("text") == "after-cancel-ok", turn
+ turn_thread.join(timeout=2)
+ assert not turn_thread.is_alive(), "completed serve stream did not close"
+ print("ok: serve cancellation bypasses busy and leaves the session reusable")
+ finally:
+ if session_id is not None and serve.poll() is None:
+ try:
+ http_json(port, "DELETE", f"/v1/sessions/{session_id}")
+ except OSError:
+ pass
+ if serve.poll() is None:
+ serve.terminate()
+ try:
+ serve.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ serve.kill()
+ serve.wait()
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test-json-live.py b/scripts/test-json-live.py
index 9f2f464f..707a8829 100644
--- a/scripts/test-json-live.py
+++ b/scripts/test-json-live.py
@@ -7,7 +7,7 @@ import subprocess
import sys
import tempfile
-from codex_ws_mock import CodexMock, REPLY_TEXT
+from codex_ws_mock import CodexMock, REPLY_TEXT, USAGE
_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
@@ -27,6 +27,7 @@ def decode(line: str) -> dict | None:
def main() -> None:
+ USAGE["input_tokens_details"]["cached_tokens"] = 400
mock = CodexMock()
port = mock.start()
try:
@@ -127,6 +128,21 @@ def main() -> None:
for event in turns
):
raise AssertionError(f"bad terminal turn events: {turns!r}")
+ for call_count, event in enumerate(turns, 1):
+ expected_usage = {
+ "input_tokens": 1200 * call_count,
+ "uncached_input_tokens": 800 * call_count,
+ "cache_read_tokens": 400 * call_count,
+ "output_tokens": 300 * call_count,
+ "api_calls": call_count,
+ "subscription_calls": call_count,
+ "unpriced_calls": 0,
+ }
+ actual_usage = {key: event.get(key) for key in expected_usage}
+ if actual_usage != expected_usage:
+ raise AssertionError(
+ f"bad cumulative usage for turn {call_count}: {actual_usage!r}"
+ )
if mock.ws_turns != 2:
raise AssertionError(f"expected two WS turns, got {mock.ws_turns}")
finally:
diff --git a/sdk/generate.py b/sdk/generate.py
index c21ab6e2..b42911da 100644
--- a/sdk/generate.py
+++ b/sdk/generate.py
@@ -59,11 +59,12 @@ def gen_ts(schema):
return header + f'''
import {{ spawn, type ChildProcessByStdio }} from "node:child_process";
import {{ createHash, randomBytes }} from "node:crypto";
-import type {{ Readable, Writable }} from "node:stream";
-import {{ existsSync, readFileSync, writeFileSync }} from "node:fs";
+import {{ accessSync, constants, existsSync, readFileSync, writeFileSync }} from "node:fs";
+import {{ createRequire }} from "node:module";
import {{ homedir }} from "node:os";
-import {{ join }} from "node:path";
+import {{ delimiter, dirname, join }} from "node:path";
import {{ createInterface }} from "node:readline";
+import type {{ Readable, Writable }} from "node:stream";
export const HARNESS_VERSION = "{version}";
@@ -95,8 +96,11 @@ export type Event =
| {{ 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; complete?: boolean; metadata_complete?: boolean }}
+ | {{ 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 }};
@@ -110,8 +114,8 @@ export function promptFingerprint(text: string): string {{
// ── Options ──────────────────────────────────────────────────────────────
export interface HarnessOptions {{
- /** Path to the CLI binary (default: "graff" on PATH, falling back to its
- * old name "harness"). */
+ /** Path to the CLI binary. Defaults to the matching optional
+ * `@codegraff/graff-*` package, then `graff` on PATH. */
binary?: string;
/** Working directory for the agent. Defaults to the parent process cwd. */
cwd?: string;
@@ -139,6 +143,10 @@ export interface ChatOptions {{
prompt: string;
/** Run this turn in isolated, read-only review mode. */
review?: boolean;
+ /** Abort the turn mid-flight: on abort the SDK writes {{"type":"cancel"}}
+ * out-of-band (the REPL's Esc path); the stream still runs to the
+ * cancelled turn's terminal event — an `error` event ("turn cancelled"). */
+ signal?: AbortSignal;
}}
export interface AnswerOptions {{
@@ -147,6 +155,33 @@ 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 RunAgentOptions extends HarnessOptions {{
/** User prompt to send to the agent. */
prompt: string;
@@ -181,13 +216,53 @@ function sdkInstallId(): string {{
return id;
}}
-/** The CLI is `graff` (renamed from `harness`); prefer it when on PATH,
- * fall back to the old name so pre-rename installs keep working. */
-function defaultBinary(): string {{
- for (const dir of (process.env.PATH ?? "").split(":")) {{
- if (dir && existsSync(join(dir, "graff"))) return "graff";
+const PLATFORM_PACKAGES: Readonly<Record<string, string>> = {{
+ "darwin-arm64": "@codegraff/graff-darwin-arm64",
+ "darwin-x64": "@codegraff/graff-darwin-x64",
+ "linux-arm64": "@codegraff/graff-linux-arm64",
+ "linux-x64": "@codegraff/graff-linux-x64",
+ "win32-arm64": "@codegraff/graff-win32-arm64",
+ "win32-x64": "@codegraff/graff-win32-x64",
+}};
+
+/** Resolve the binary bundled by npm. `createRequire` anchors lookup beside
+ * this installed SDK, so hoisted and nested optional dependencies both work. */
+function packagedBinary(): {{ path?: string; packageName?: string }} {{
+ const packageName = PLATFORM_PACKAGES[`${{process.platform}}-${{process.arch}}`];
+ if (!packageName) return {{}};
+ const require = createRequire(import.meta.url);
+ let manifest: string;
+ try {{ manifest = require.resolve(`${{packageName}}/package.json`); }} catch {{
+ return {{ packageName }};
}}
- return "harness";
+ let protocol: unknown;
+ try {{ protocol = JSON.parse(readFileSync(manifest, "utf8")).graffProtocol; }} catch {{}}
+ if (protocol !== HARNESS_VERSION) {{
+ throw new Error(`${{packageName}} uses graff protocol ${{String(protocol ?? "unknown")}}, but @codegraff/sdk requires ${{HARNESS_VERSION}}. Reinstall @codegraff/sdk without disabling optional dependencies.`);
+ }}
+ const binary = process.platform === "win32" ? "graff.exe" : "graff";
+ const path = join(dirname(manifest), "bin", binary);
+ return existsSync(path) ? {{ path, packageName }} : {{ packageName }};
+}}
+
+/** Prefer the version-pinned npm binary, then a caller-supplied PATH. Return
+ * an absolute path so probing and spawning cannot disagree. */
+function defaultBinary(env: NodeJS.ProcessEnv): string {{
+ const packaged = packagedBinary();
+ if (packaged.path) return packaged.path;
+ const binary = process.platform === "win32" ? "graff.exe" : "graff";
+ for (const dir of (env.PATH ?? env.Path ?? env.path ?? "").split(delimiter)) {{
+ if (!dir) continue;
+ const path = join(dir, binary);
+ try {{
+ accessSync(path, process.platform === "win32" ? constants.F_OK : constants.X_OK);
+ return path;
+ }} catch {{}}
+ }}
+ const install = packaged.packageName
+ ? `Reinstall @codegraff/sdk so npm can install ${{packaged.packageName}}, or install graff on PATH.`
+ : "Install graff on PATH or pass Harness.init({{ binary: ... }}).";
+ throw new Error(`No graff binary is available for ${{process.platform}}-${{process.arch}}. ${{install}}`);
}}
const TELEMETRY_DEFAULT = "https://harness-telemetry.rachpradhan.workers.dev";
@@ -290,11 +365,16 @@ export class Harness {{
private proc: ChildProcessByStdio<Writable, Readable, null>;
private queue: ((e: Event | null) => void)[] = [];
private buffer: Event[] = [];
+ /** Tail of the operation chain (see acquireOp). Always resolves. */
+ private opTail: Promise<void> = Promise.resolve();
+ private closed = false;
+ private closePromise?: Promise<void>;
constructor(opts: HarnessOptions = {{}}) {{
- this.proc = spawn(opts.binary ?? defaultBinary(), spawnArgs(opts), {{
+ const env = sdkEnv(opts.env);
+ this.proc = spawn(opts.binary ?? defaultBinary(env), spawnArgs(opts), {{
cwd: opts.cwd,
- env: sdkEnv(opts.env),
+ env,
stdio: ["pipe", "pipe", "inherit"],
}});
const rl = createInterface({{ input: this.proc.stdout }});
@@ -313,6 +393,9 @@ export class Harness {{
for (const w of this.queue) w(null);
this.queue = [];
}});
+ // cancel()/answer() are lock-free, so their writes can race process
+ // death: swallow stdin stream errors instead of crashing the host.
+ this.proc.stdin.on("error", () => {{}});
}}
/** Start a long-lived agent (codegraff parity for `Graff.init`). */
@@ -323,38 +406,106 @@ export class Harness {{
return new Promise((resolve) => this.queue.push(resolve));
}}
- /** Run one turn; async-iterate events up to and including `turn`/`error`. */
+ /** Operation chain: turns (chat) and acked controls (setSystemPrompt,
+ * setModel, setEffort, compact, score) run one at a time, so a control
+ * can never steal a chat's terminal event off the shared event queue.
+ * The tail always RESOLVES — an operation's error goes only to its own
+ * caller and can never poison the queue behind it. answer() and cancel()
+ * bypass the chain on purpose: the harness reads both out-of-band. */
+ private acquireOp(): Promise<() => void> {{
+ if (this.closed) return Promise.reject(new Error("harness is closed"));
+ 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();
+ }}
+ }}
+
+ /** Run one turn; async-iterate events up to and including `turn`/`error`.
+ * Holds the operation lock until the terminal event, so a control issued
+ * mid-turn (setSystemPrompt, setModel, …) queues BEHIND the turn instead
+ * of stealing its events off the shared queue. 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;
const type = typeof input === "string" || !input.review ? "user" : "review";
- this.proc.stdin.write(JSON.stringify({{ type, text: prompt }}) + "\\n");
- while (true) {{
- const ev = await this.next();
- if (ev === null) {{
- // Process closed without a terminal event: died mid-turn. Reported
- // to telemetry and thrown instead of silently ending the stream.
- reportError("died", `harness exited mid-turn (code=${{this.proc.exitCode}})`);
- throw new Error(`harness exited mid-turn (code=${{this.proc.exitCode}})`);
+ 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.
+ signal?.throwIfAborted();
+ const release = await this.acquireOp();
+ let aborted = false;
+ const onAbort = () => {{ if (aborted) return; aborted = true; this.cancel(); }};
+ try {{
+ this.proc.stdin.write(JSON.stringify({{ type, text: prompt }}) + "\\n");
+ if (signal) {{
+ signal.addEventListener("abort", onAbort, {{ once: true }});
+ if (signal.aborted) onAbort(); // aborted between the entry check and here
+ }}
+ while (true) {{
+ const ev = await this.next();
+ if (ev === null) {{
+ // Process closed without a terminal event: died mid-turn. Reported
+ // to telemetry and thrown instead of silently ending the stream.
+ reportError("died", `harness exited mid-turn (code=${{this.proc.exitCode}})`);
+ throw new Error(`harness exited mid-turn (code=${{this.proc.exitCode}})`);
+ }}
+ yield ev;
+ if (ev.type === "turn" || ev.type === "error") return;
}}
- yield ev;
- if (ev.type === "turn" || ev.type === "error") return;
+ }} finally {{
+ if (signal) signal.removeEventListener("abort", onAbort);
+ release();
}}
}}
- /** Run a turn and return just the final assistant text. */
- async ask(input: string | ChatOptions): Promise<string> {{
- let final = "";
+ /** 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 prompt = typeof input === "string" ? input : input.prompt;
- return this.ask({{ prompt, review: true }});
+ const options = typeof input === "string" ? {{ prompt: input }} : input;
+ return this.ask({{ ...options, review: true }});
}}
/** Answer an in-flight ask_user event. Call this while consuming chat()
@@ -376,21 +527,78 @@ export class Harness {{
* `appendSystemPrompt` options; mutate only at task boundaries, never
* back-and-forth inside a loop. */
async setSystemPrompt(text: string, append = false): Promise<void> {{
- this.proc.stdin.write(JSON.stringify({{ type: "set_system_prompt", text, append }}) + "\\n");
- // Edge-version durability: a newer harness may emit event types this
- // client predates — skip them while waiting for the ack (the chat loop
- // already tolerates unknowns the same way) instead of throwing.
- while (true) {{
- const ev = await this.next();
- if (ev === null) {{ reportError("died", "harness closed before acking set_system_prompt"); throw new Error("harness closed"); }}
- if (ev.type === "error") throw new Error(ev.message);
- if (ev.type === "system_prompt") return;
- }}
+ return this.runOp(async () => {{
+ this.proc.stdin.write(JSON.stringify({{ type: "set_system_prompt", text, append }}) + "\\n");
+ // Edge-version durability: a newer harness may emit event types this
+ // client predates — skip them while waiting for the ack (the chat loop
+ // already tolerates unknowns the same way) instead of throwing.
+ while (true) {{
+ const ev = await this.next();
+ if (ev === null) {{ reportError("died", "harness closed before acking set_system_prompt"); throw new Error("harness closed"); }}
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "system_prompt") return;
+ }}
+ }});
}}
/** Tack extra instructions onto the current system prompt. */
appendSystemPrompt(text: string): Promise<void> {{ return this.setSystemPrompt(text, true); }}
+ /** Cancel the in-flight turn — the SDK analogue of the REPL's Esc. Writes
+ * {{"type":"cancel"}} straight to stdin, which the harness inbox reads
+ * OUT-OF-BAND (ahead of any queued request), so this deliberately does
+ * NOT join the operation queue: a cancel queued behind the turn it means
+ * to stop would fire too late. Lock-free like answer(). The active
+ * chat() stream still runs to the cancelled turn's terminal event. */
+ cancel(): void {{
+ this.proc.stdin.write(JSON.stringify({{ type: "cancel" }}) + "\\n");
+ }}
+
+ /** Switch provider/model mid-session — the provider-qualified form of the
+ * protocol's set_model control. Call between turns; resolves on the
+ * `model` ack, rejects on the harness's `error` event (unknown model,
+ * missing key/login, …). Serialized with chat() and the other controls. */
+ setModel(provider: ProviderId | string, model: ModelName | string): Promise<void> {{
+ return this.runOp(async () => {{
+ this.proc.stdin.write(JSON.stringify({{ type: "set_model", provider, model }}) + "\\n");
+ while (true) {{
+ const ev = await this.next();
+ if (ev === null) {{ reportError("died", "harness closed before acking set_model"); throw new Error("harness closed"); }}
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "model") return;
+ }}
+ }});
+ }}
+
+ /** 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 () => {{
+ this.proc.stdin.write(JSON.stringify({{ type: "set_effort", level }}) + "\\n");
+ while (true) {{
+ const ev = await this.next();
+ if (ev === null) {{ reportError("died", "harness closed before acking set_effort"); throw new Error("harness closed"); }}
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "effort") return;
+ }}
+ }});
+ }}
+
+ /** Compact the conversation history now (protocol compact). Resolves on
+ * the `compact` ack; rejects when compaction fails — the harness leaves
+ * history unchanged in that case. Serialized like the other controls. */
+ compact(): Promise<void> {{
+ return this.runOp(async () => {{
+ this.proc.stdin.write(JSON.stringify({{ type: "compact" }}) + "\\n");
+ while (true) {{
+ const ev = await this.next();
+ if (ev === null) {{ reportError("died", "harness closed before acking compact"); throw new Error("harness closed"); }}
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "compact") return;
+ }}
+ }});
+ }}
+
/** Record an evaluation score for an agent/prompt variant in the
* aggregate `.graff/trajectories` archive — the DGM evaluation
* phase writing back. `promptOrSha` is either the full system-prompt
@@ -414,15 +622,17 @@ export class Harness {{
: /^[0-9a-f]{{16}}$/.test(parent) ? parent : promptFingerprint(parent);
// The SDK emitter strips prompt_text until it has an interactive review UI.
if (niche && !/^[0-9a-f]{{16}}$/.test(promptOrSha)) fleetSignal("propose", {{ niche, prompt_sha: sha, parent_sha: parent_sha ?? "", prompt_text: promptOrSha }});
- this.proc.stdin.write(JSON.stringify({{ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }}) + "\\n");
- // Same edge-version tolerance as setSystemPrompt: skip unknown events
- // while waiting for the ack.
- while (true) {{
- const ev = await this.next();
- if (ev === null) {{ reportError("died", "harness closed before acking score"); throw new Error("harness closed"); }}
- if (ev.type === "error") throw new Error(ev.message);
- if (ev.type === "score") {{ fleetSignal("submit", {{ prompt_sha: sha, parent_sha: parent_sha ?? "", niche: niche ?? "" }}); return; }}
- }}
+ return this.runOp(async () => {{
+ this.proc.stdin.write(JSON.stringify({{ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }}) + "\\n");
+ // Same edge-version tolerance as setSystemPrompt: skip unknown events
+ // while waiting for the ack.
+ while (true) {{
+ const ev = await this.next();
+ if (ev === null) {{ reportError("died", "harness closed before acking score"); throw new Error("harness closed"); }}
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "score") {{ fleetSignal("submit", {{ prompt_sha: sha, parent_sha: parent_sha ?? "", niche: niche ?? "" }}); return; }}
+ }}
+ }});
}}
/** Pull the fleet's live champion personas (GET /v1/elites). Local mode
@@ -451,15 +661,27 @@ export class Harness {{
/** The harness schema version this client was generated from. */
version(): string {{ return HARNESS_VERSION; }}
- /** Close stdin and give the harness a moment to exit cleanly — it flushes
- * telemetry and trajectory records on the way out; killing immediately
- * would race (and lose) that flush. */
- close(): void {{
+ /** Cancel active work, close stdin, and await the child's clean exit so its
+ * telemetry and trajectory flushes are durable. Idempotent; force-kills
+ * only after the graceful deadline. */
+ close(): Promise<void> {{
+ if (this.closePromise) return this.closePromise;
+ this.cancel();
+ this.closed = true;
this.proc.stdin.end();
- const t = setTimeout(() => this.proc.kill(), 15000);
- t.unref?.();
- this.proc.on("close", () => clearTimeout(t));
+ this.closePromise = new Promise((resolve) => {{
+ if (this.proc.exitCode !== null) return resolve();
+ const timer = setTimeout(() => this.proc.kill(), 15000);
+ timer.unref?.();
+ const finish = () => {{ clearTimeout(timer); resolve(); }};
+ this.proc.once("close", finish);
+ this.proc.once("error", finish);
+ }});
+ return this.closePromise;
}}
+
+ /** Alias for close(). */
+ dispose(): Promise<void> {{ return this.close(); }}
}}
// ── HarnessSession (parallel to codegraff's `GraffSession`) ────────────────
@@ -471,10 +693,16 @@ 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); }}
+ askResult(input: string | ChatOptions): Promise<AskResult> {{ return this.agent.askResult(input); }}
review(input: string | ChatOptions): Promise<string> {{ return this.agent.review(input); }}
answer(input: string | AnswerOptions): void {{ return this.agent.answer(input); }}
+ cancel(): void {{ this.agent.cancel(); }}
setSystemPrompt(text: string, append = false): Promise<void> {{ return this.agent.setSystemPrompt(text, append); }}
- close(): void {{ this.agent.close(); }}
+ setModel(provider: ProviderId | string, model: ModelName | string): Promise<void> {{ return this.agent.setModel(provider, model); }}
+ setEffort(level: EffortLevel): Promise<void> {{ return this.agent.setEffort(level); }}
+ compact(): Promise<void> {{ return this.agent.compact(); }}
+ close(): Promise<void> {{ return this.agent.close(); }}
+ dispose(): Promise<void> {{ return this.agent.dispose(); }}
}}
// ── Top-level one-shot (parallel to codegraff's `runAgent`) ────────────────
@@ -485,7 +713,7 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {{
try {{
yield* h.chat({{ prompt: opts.prompt }});
}} finally {{
- h.close();
+ await h.close();
}}
}}
@@ -546,8 +774,11 @@ export type Event =
| {{ 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; complete?: boolean; metadata_complete?: boolean }}
+ | {{ 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 }};
@@ -605,6 +836,11 @@ export interface ChatOptions {{
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 {{
@@ -613,6 +849,33 @@ 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;
}}
@@ -624,19 +887,26 @@ 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}}$/;
@@ -653,6 +923,9 @@ const HEX16 = /^[0-9a-f]{{16}}$/;
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
@@ -670,8 +943,15 @@ export class RemoteHarness {{
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;
- this.sessionId = created.then((d) => d.session_id);
+ const sid = created.then((d) => d.session_id);
+ sid.catch(() => {{}});
+ this.sessionId = sid;
}}
}}
@@ -720,6 +1000,29 @@ export class RemoteHarness {{
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>, from?: number): AsyncGenerator<Event> {{
const id = await this.sessionId;
@@ -728,17 +1031,41 @@ export class RemoteHarness {{
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;
const type = typeof input === "string" || !input.review ? "user" : "review";
const from = typeof input === "string" ? undefined : input.from;
- let terminal = false;
- for await (const ev of this.send({{ type, text: prompt }}, from)) {{
- yield ev;
- if (ev.type === "turn" || ev.type === "error") {{ terminal = true; break; }}
+ 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 }});
+ 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?)");
}}
/** Re-attach to a session after losing the stream: replay persisted events
@@ -753,20 +1080,43 @@ export class RemoteHarness {{
for await (const ev of ndjson(res)) yield this.note(ev);
}}
- /** Run a turn and return just the final assistant text. */
- async ask(input: string | ChatOptions): Promise<string> {{
- let final = "";
+ /** 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 prompt = typeof input === "string" ? input : input.prompt;
- return this.ask({{ prompt, review: true }});
+ 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
@@ -779,17 +1129,69 @@ 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); }}
@@ -806,22 +1208,32 @@ export class RemoteHarness {{
// 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.)
- 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");
+ 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. */
diff --git a/sdk/ts/README.md b/sdk/ts/README.md
index e46f97df..d986326b 100644
--- a/sdk/ts/README.md
+++ b/sdk/ts/README.md
@@ -10,16 +10,19 @@ types are auto-generated from `graff --schema`.
npm install @codegraff/sdk
```
-### Prerequisite: the `graff` binary
+### Native binary included
-The SDK spawns the `graff` binary as a subprocess, so it must be installed:
+npm installs the matching native `graff` executable through an optional platform
+package, so a separate CLI install or `PATH` setup is not required on supported
+macOS, Linux, and Windows arm64/x64 systems. Provider authentication is still
+required through the normal environment variables or `graff login` credentials.
-```sh
-curl -fsSL https://github.com/justrach/codegraff/releases/latest/download/install.sh | sh
-```
+If optional dependencies are disabled, the SDK falls back to `graff` on `PATH`.
+Development and custom builds can always set an explicit binary:
-If `graff` isn't on your `PATH`, point at it explicitly with the `binary` option
-(`Harness.init({ binary: "./zig-out/bin/graff" })`).
+```ts
+const graff = Harness.init({ binary: "./zig-out/bin/graff" });
+```
## Quick start
@@ -37,11 +40,13 @@ for await (const ev of runAgent({ prompt: "summarize README.md", model: "gpt-5.5
const harness = Harness.init({ model: "claude-opus-4-8", yolo: true });
const session = harness.session();
console.log(await session.ask("what files are here?")); // returns final text
+const result = await session.askResult("summarize the changes");
+console.log(result.text, result.inputTokens, result.costUsd);
console.log(await session.review("review HEAD against main")); // isolated + read-only
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 });
}
-session.close();
+await session.close();
```
`Harness.init` accepts `{ model, yolo, cwd, env, binary, systemPrompt,
@@ -49,6 +54,28 @@ maxToolCalls, maxModelCalls, dedupeToolCalls, args }`.
`model` may be a model name **or** a provider id (e.g. `"codex"`, `"moonshot"`).
Also exported: `MODELS` and `PROVIDERS`.
+## Runtime controls and cancellation
+
+Turns and acknowledged controls are serialized per session, so overlapping calls
+cannot steal each other's events. `answer()` remains out-of-band so it can answer
+an active `ask_user` prompt.
+
+```ts
+await session.setModel("codex", "gpt-5.6-luna");
+await session.setEffort("high");
+await session.compact();
+
+const controller = new AbortController();
+const pending = session.ask({ prompt: "long task", signal: controller.signal });
+controller.abort(); // interrupts the active model/tool turn
+await pending; // rejects with the terminal cancellation error
+```
+
+`askResult()` returns final text plus context, token, cache, cost, and provider-call
+usage. `ask()` remains the compatibility shorthand that returns only final text.
+The same controls, abort behavior, structured results, and out-of-band answers are
+available on `RemoteHarness`.
+
## Events
Both `runAgent` and `session.send` yield an `AsyncGenerator<Event>`:
diff --git a/sdk/ts/harness.test.ts b/sdk/ts/harness.test.ts
new file mode 100644
index 00000000..d5102bfe
--- /dev/null
+++ b/sdk/ts/harness.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import { Harness } from "./harness.ts";
+
+const binary = join(import.meta.dir, "test-fixtures", "fake-graff.mjs");
+const live: Harness[] = [];
+const harness = () => {
+ const value = new Harness({ binary, env: { ...process.env, GRAFF_NO_TELEMETRY: "1" } });
+ live.push(value);
+ return value;
+};
+
+const deadline = <T>(promise: Promise<T>, ms = 2_000): Promise<T> => Promise.race([
+ promise,
+ new Promise<T>((_, reject) => setTimeout(() => reject(new Error("test timed out")), ms)),
+]);
+
+afterEach(async () => {
+ await Promise.all(live.splice(0).map((value) => value.close()));
+});
+
+describe("Harness transport", () => {
+ test("serializes overlapping turns and controls without event theft", async () => {
+ const h = harness();
+ const first = h.ask("one");
+ const model = h.setModel("codex", "gpt-test");
+ const effort = h.setEffort("high");
+ const compact = h.compact();
+ const second = h.ask("two");
+
+ expect(await deadline(first)).toBe("user:one");
+ await deadline(Promise.all([model, effort, compact]));
+ expect(await deadline(second)).toBe("user:two");
+ });
+
+ test("a failed control does not poison the operation queue", async () => {
+ const h = harness();
+ await expect(h.setModel("codex", "bad")).rejects.toThrow("bad model");
+ expect(await deadline(h.ask("after-error"))).toBe("user:after-error");
+ });
+
+ test("returns structured turn usage while ask remains string-compatible", async () => {
+ const h = harness();
+ const result = await h.askResult("usage");
+ expect(result).toEqual({
+ text: "user:usage",
+ contextTokens: 42,
+ costUsd: 0.012,
+ inputTokens: 10,
+ uncachedInputTokens: 4,
+ cacheReadTokens: 6,
+ outputTokens: 3,
+ apiCalls: 2,
+ subscriptionCalls: 1,
+ unpricedCalls: 0,
+ complete: true,
+ metadataComplete: true,
+ });
+ expect(await h.ask("plain")).toBe("user:plain");
+ });
+
+ test("answer bypasses the operation lock during ask_user", async () => {
+ const h = harness();
+ let final = "";
+ for await (const event of h.chat("ask")) {
+ if (event.type === "ask_user") h.answer({ text: "yes", callId: event.call_id });
+ if (event.type === "turn") final = event.text;
+ }
+ expect(final).toBe("answered:yes");
+ });
+
+ test("AbortSignal cancels an active turn and leaves the session usable", async () => {
+ const h = harness();
+ const controller = new AbortController();
+ const pending = h.ask({ prompt: "slow", signal: controller.signal });
+ setTimeout(() => controller.abort(), 20);
+ await expect(deadline(pending)).rejects.toThrow("turn cancelled");
+ expect(await deadline(h.ask("after"))).toBe("user:after");
+ });
+
+ test("child death rejects instead of hanging and does not poison other instances", async () => {
+ const dead = harness();
+ await expect(deadline(dead.ask("die"))).rejects.toThrow("exited mid-turn");
+ const healthy = harness();
+ expect(await deadline(healthy.ask("healthy"))).toBe("user:healthy");
+ });
+});
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index c630bc9f..cb6ee6ca 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -2,13 +2,14 @@
import { spawn, type ChildProcessByStdio } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
-import type { Readable, Writable } from "node:stream";
-import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { accessSync, constants, existsSync, readFileSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { delimiter, dirname, join } from "node:path";
import { createInterface } from "node:readline";
+import type { Readable, Writable } from "node:stream";
-export const HARNESS_VERSION = "0.11";
+export const HARNESS_VERSION = "0.12";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-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" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "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" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "imagegen";
@@ -38,8 +39,11 @@ export type Event =
| { 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; complete?: boolean; metadata_complete?: boolean }
+ | { 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 };
@@ -53,8 +57,8 @@ export function promptFingerprint(text: string): string {
// ── Options ──────────────────────────────────────────────────────────────
export interface HarnessOptions {
- /** Path to the CLI binary (default: "graff" on PATH, falling back to its
- * old name "harness"). */
+ /** Path to the CLI binary. Defaults to the matching optional
+ * `@codegraff/graff-*` package, then `graff` on PATH. */
binary?: string;
/** Working directory for the agent. Defaults to the parent process cwd. */
cwd?: string;
@@ -82,6 +86,10 @@ export interface ChatOptions {
prompt: string;
/** Run this turn in isolated, read-only review mode. */
review?: boolean;
+ /** Abort the turn mid-flight: on abort the SDK writes {"type":"cancel"}
+ * out-of-band (the REPL's Esc path); the stream still runs to the
+ * cancelled turn's terminal event — an `error` event ("turn cancelled"). */
+ signal?: AbortSignal;
}
export interface AnswerOptions {
@@ -90,6 +98,33 @@ 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 RunAgentOptions extends HarnessOptions {
/** User prompt to send to the agent. */
prompt: string;
@@ -124,13 +159,53 @@ function sdkInstallId(): string {
return id;
}
-/** The CLI is `graff` (renamed from `harness`); prefer it when on PATH,
- * fall back to the old name so pre-rename installs keep working. */
-function defaultBinary(): string {
- for (const dir of (process.env.PATH ?? "").split(":")) {
- if (dir && existsSync(join(dir, "graff"))) return "graff";
+const PLATFORM_PACKAGES: Readonly<Record<string, string>> = {
+ "darwin-arm64": "@codegraff/graff-darwin-arm64",
+ "darwin-x64": "@codegraff/graff-darwin-x64",
+ "linux-arm64": "@codegraff/graff-linux-arm64",
+ "linux-x64": "@codegraff/graff-linux-x64",
+ "win32-arm64": "@codegraff/graff-win32-arm64",
+ "win32-x64": "@codegraff/graff-win32-x64",
+};
+
+/** Resolve the binary bundled by npm. `createRequire` anchors lookup beside
+ * this installed SDK, so hoisted and nested optional dependencies both work. */
+function packagedBinary(): { path?: string; packageName?: string } {
+ const packageName = PLATFORM_PACKAGES[`${process.platform}-${process.arch}`];
+ if (!packageName) return {};
+ const require = createRequire(import.meta.url);
+ let manifest: string;
+ try { manifest = require.resolve(`${packageName}/package.json`); } catch {
+ return { packageName };
}
- return "harness";
+ let protocol: unknown;
+ try { protocol = JSON.parse(readFileSync(manifest, "utf8")).graffProtocol; } catch {}
+ if (protocol !== HARNESS_VERSION) {
+ throw new Error(`${packageName} uses graff protocol ${String(protocol ?? "unknown")}, but @codegraff/sdk requires ${HARNESS_VERSION}. Reinstall @codegraff/sdk without disabling optional dependencies.`);
+ }
+ const binary = process.platform === "win32" ? "graff.exe" : "graff";
+ const path = join(dirname(manifest), "bin", binary);
+ return existsSync(path) ? { path, packageName } : { packageName };
+}
+
+/** Prefer the version-pinned npm binary, then a caller-supplied PATH. Return
+ * an absolute path so probing and spawning cannot disagree. */
+function defaultBinary(env: NodeJS.ProcessEnv): string {
+ const packaged = packagedBinary();
+ if (packaged.path) return packaged.path;
+ const binary = process.platform === "win32" ? "graff.exe" : "graff";
+ for (const dir of (env.PATH ?? env.Path ?? env.path ?? "").split(delimiter)) {
+ if (!dir) continue;
+ const path = join(dir, binary);
+ try {
+ accessSync(path, process.platform === "win32" ? constants.F_OK : constants.X_OK);
+ return path;
+ } catch {}
+ }
+ const install = packaged.packageName
+ ? `Reinstall @codegraff/sdk so npm can install ${packaged.packageName}, or install graff on PATH.`
+ : "Install graff on PATH or pass Harness.init({ binary: ... }).";
+ throw new Error(`No graff binary is available for ${process.platform}-${process.arch}. ${install}`);
}
const TELEMETRY_DEFAULT = "https://harness-telemetry.rachpradhan.workers.dev";
@@ -233,11 +308,16 @@ export class Harness {
private proc: ChildProcessByStdio<Writable, Readable, null>;
private queue: ((e: Event | null) => void)[] = [];
private buffer: Event[] = [];
+ /** Tail of the operation chain (see acquireOp). Always resolves. */
+ private opTail: Promise<void> = Promise.resolve();
+ private closed = false;
+ private closePromise?: Promise<void>;
constructor(opts: HarnessOptions = {}) {
- this.proc = spawn(opts.binary ?? defaultBinary(), spawnArgs(opts), {
+ const env = sdkEnv(opts.env);
+ this.proc = spawn(opts.binary ?? defaultBinary(env), spawnArgs(opts), {
cwd: opts.cwd,
- env: sdkEnv(opts.env),
+ env,
stdio: ["pipe", "pipe", "inherit"],
});
const rl = createInterface({ input: this.proc.stdout });
@@ -256,6 +336,9 @@ export class Harness {
for (const w of this.queue) w(null);
this.queue = [];
});
+ // cancel()/answer() are lock-free, so their writes can race process
+ // death: swallow stdin stream errors instead of crashing the host.
+ this.proc.stdin.on("error", () => {});
}
/** Start a long-lived agent (codegraff parity for `Graff.init`). */
@@ -266,38 +349,106 @@ export class Harness {
return new Promise((resolve) => this.queue.push(resolve));
}
- /** Run one turn; async-iterate events up to and including `turn`/`error`. */
+ /** Operation chain: turns (chat) and acked controls (setSystemPrompt,
+ * setModel, setEffort, compact, score) run one at a time, so a control
+ * can never steal a chat's terminal event off the shared event queue.
+ * The tail always RESOLVES — an operation's error goes only to its own
+ * caller and can never poison the queue behind it. answer() and cancel()
+ * bypass the chain on purpose: the harness reads both out-of-band. */
+ private acquireOp(): Promise<() => void> {
+ if (this.closed) return Promise.reject(new Error("harness is closed"));
+ 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();
+ }
+ }
+
+ /** Run one turn; async-iterate events up to and including `turn`/`error`.
+ * Holds the operation lock until the terminal event, so a control issued
+ * mid-turn (setSystemPrompt, setModel, …) queues BEHIND the turn instead
+ * of stealing its events off the shared queue. 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;
const type = typeof input === "string" || !input.review ? "user" : "review";
- this.proc.stdin.write(JSON.stringify({ type, text: prompt }) + "\n");
- while (true) {
- const ev = await this.next();
- if (ev === null) {
- // Process closed without a terminal event: died mid-turn. Reported
- // to telemetry and thrown instead of silently ending the stream.
- reportError("died", `harness exited mid-turn (code=${this.proc.exitCode})`);
- throw new Error(`harness exited mid-turn (code=${this.proc.exitCode})`);
+ 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.
+ signal?.throwIfAborted();
+ const release = await this.acquireOp();
+ let aborted = false;
+ const onAbort = () => { if (aborted) return; aborted = true; this.cancel(); };
+ try {
+ this.proc.stdin.write(JSON.stringify({ type, text: prompt }) + "\n");
+ if (signal) {
+ signal.addEventListener("abort", onAbort, { once: true });
+ if (signal.aborted) onAbort(); // aborted between the entry check and here
}
- yield ev;
- if (ev.type === "turn" || ev.type === "error") return;
+ while (true) {
+ const ev = await this.next();
+ if (ev === null) {
+ // Process closed without a terminal event: died mid-turn. Reported
+ // to telemetry and thrown instead of silently ending the stream.
+ reportError("died", `harness exited mid-turn (code=${this.proc.exitCode})`);
+ throw new Error(`harness exited mid-turn (code=${this.proc.exitCode})`);
+ }
+ yield ev;
+ if (ev.type === "turn" || ev.type === "error") return;
+ }
+ } finally {
+ if (signal) signal.removeEventListener("abort", onAbort);
+ release();
}
}
- /** Run a turn and return just the final assistant text. */
- async ask(input: string | ChatOptions): Promise<string> {
- let final = "";
+ /** 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 prompt = typeof input === "string" ? input : input.prompt;
- return this.ask({ prompt, review: true });
+ const options = typeof input === "string" ? { prompt: input } : input;
+ return this.ask({ ...options, review: true });
}
/** Answer an in-flight ask_user event. Call this while consuming chat()
@@ -319,21 +470,78 @@ export class Harness {
* `appendSystemPrompt` options; mutate only at task boundaries, never
* back-and-forth inside a loop. */
async setSystemPrompt(text: string, append = false): Promise<void> {
- this.proc.stdin.write(JSON.stringify({ type: "set_system_prompt", text, append }) + "\n");
- // Edge-version durability: a newer harness may emit event types this
- // client predates — skip them while waiting for the ack (the chat loop
- // already tolerates unknowns the same way) instead of throwing.
- while (true) {
- const ev = await this.next();
- if (ev === null) { reportError("died", "harness closed before acking set_system_prompt"); throw new Error("harness closed"); }
- if (ev.type === "error") throw new Error(ev.message);
- if (ev.type === "system_prompt") return;
- }
+ return this.runOp(async () => {
+ this.proc.stdin.write(JSON.stringify({ type: "set_system_prompt", text, append }) + "\n");
+ // Edge-version durability: a newer harness may emit event types this
+ // client predates — skip them while waiting for the ack (the chat loop
+ // already tolerates unknowns the same way) instead of throwing.
+ while (true) {
+ const ev = await this.next();
+ if (ev === null) { reportError("died", "harness closed before acking set_system_prompt"); throw new Error("harness closed"); }
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "system_prompt") return;
+ }
+ });
}
/** Tack extra instructions onto the current system prompt. */
appendSystemPrompt(text: string): Promise<void> { return this.setSystemPrompt(text, true); }
+ /** Cancel the in-flight turn — the SDK analogue of the REPL's Esc. Writes
+ * {"type":"cancel"} straight to stdin, which the harness inbox reads
+ * OUT-OF-BAND (ahead of any queued request), so this deliberately does
+ * NOT join the operation queue: a cancel queued behind the turn it means
+ * to stop would fire too late. Lock-free like answer(). The active
+ * chat() stream still runs to the cancelled turn's terminal event. */
+ cancel(): void {
+ this.proc.stdin.write(JSON.stringify({ type: "cancel" }) + "\n");
+ }
+
+ /** Switch provider/model mid-session — the provider-qualified form of the
+ * protocol's set_model control. Call between turns; resolves on the
+ * `model` ack, rejects on the harness's `error` event (unknown model,
+ * missing key/login, …). Serialized with chat() and the other controls. */
+ setModel(provider: ProviderId | string, model: ModelName | string): Promise<void> {
+ return this.runOp(async () => {
+ this.proc.stdin.write(JSON.stringify({ type: "set_model", provider, model }) + "\n");
+ while (true) {
+ const ev = await this.next();
+ if (ev === null) { reportError("died", "harness closed before acking set_model"); throw new Error("harness closed"); }
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "model") return;
+ }
+ });
+ }
+
+ /** 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 () => {
+ this.proc.stdin.write(JSON.stringify({ type: "set_effort", level }) + "\n");
+ while (true) {
+ const ev = await this.next();
+ if (ev === null) { reportError("died", "harness closed before acking set_effort"); throw new Error("harness closed"); }
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "effort") return;
+ }
+ });
+ }
+
+ /** Compact the conversation history now (protocol compact). Resolves on
+ * the `compact` ack; rejects when compaction fails — the harness leaves
+ * history unchanged in that case. Serialized like the other controls. */
+ compact(): Promise<void> {
+ return this.runOp(async () => {
+ this.proc.stdin.write(JSON.stringify({ type: "compact" }) + "\n");
+ while (true) {
+ const ev = await this.next();
+ if (ev === null) { reportError("died", "harness closed before acking compact"); throw new Error("harness closed"); }
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "compact") return;
+ }
+ });
+ }
+
/** Record an evaluation score for an agent/prompt variant in the
* aggregate `.graff/trajectories` archive — the DGM evaluation
* phase writing back. `promptOrSha` is either the full system-prompt
@@ -357,15 +565,17 @@ export class Harness {
: /^[0-9a-f]{16}$/.test(parent) ? parent : promptFingerprint(parent);
// The SDK emitter strips prompt_text until it has an interactive review UI.
if (niche && !/^[0-9a-f]{16}$/.test(promptOrSha)) fleetSignal("propose", { niche, prompt_sha: sha, parent_sha: parent_sha ?? "", prompt_text: promptOrSha });
- this.proc.stdin.write(JSON.stringify({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }) + "\n");
- // Same edge-version tolerance as setSystemPrompt: skip unknown events
- // while waiting for the ack.
- while (true) {
- const ev = await this.next();
- if (ev === null) { reportError("died", "harness closed before acking score"); throw new Error("harness closed"); }
- if (ev.type === "error") throw new Error(ev.message);
- if (ev.type === "score") { fleetSignal("submit", { prompt_sha: sha, parent_sha: parent_sha ?? "", niche: niche ?? "" }); return; }
- }
+ return this.runOp(async () => {
+ this.proc.stdin.write(JSON.stringify({ type: "score", prompt_sha: sha, score: value, notes, parent_sha, niche, scale }) + "\n");
+ // Same edge-version tolerance as setSystemPrompt: skip unknown events
+ // while waiting for the ack.
+ while (true) {
+ const ev = await this.next();
+ if (ev === null) { reportError("died", "harness closed before acking score"); throw new Error("harness closed"); }
+ if (ev.type === "error") throw new Error(ev.message);
+ if (ev.type === "score") { fleetSignal("submit", { prompt_sha: sha, parent_sha: parent_sha ?? "", niche: niche ?? "" }); return; }
+ }
+ });
}
/** Pull the fleet's live champion personas (GET /v1/elites). Local mode
@@ -394,15 +604,27 @@ export class Harness {
/** The harness schema version this client was generated from. */
version(): string { return HARNESS_VERSION; }
- /** Close stdin and give the harness a moment to exit cleanly — it flushes
- * telemetry and trajectory records on the way out; killing immediately
- * would race (and lose) that flush. */
- close(): void {
+ /** Cancel active work, close stdin, and await the child's clean exit so its
+ * telemetry and trajectory flushes are durable. Idempotent; force-kills
+ * only after the graceful deadline. */
+ close(): Promise<void> {
+ if (this.closePromise) return this.closePromise;
+ this.cancel();
+ this.closed = true;
this.proc.stdin.end();
- const t = setTimeout(() => this.proc.kill(), 15000);
- t.unref?.();
- this.proc.on("close", () => clearTimeout(t));
+ this.closePromise = new Promise((resolve) => {
+ if (this.proc.exitCode !== null) return resolve();
+ const timer = setTimeout(() => this.proc.kill(), 15000);
+ timer.unref?.();
+ const finish = () => { clearTimeout(timer); resolve(); };
+ this.proc.once("close", finish);
+ this.proc.once("error", finish);
+ });
+ return this.closePromise;
}
+
+ /** Alias for close(). */
+ dispose(): Promise<void> { return this.close(); }
}
// ── HarnessSession (parallel to codegraff's `GraffSession`) ────────────────
@@ -414,10 +636,16 @@ 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); }
+ askResult(input: string | ChatOptions): Promise<AskResult> { return this.agent.askResult(input); }
review(input: string | ChatOptions): Promise<string> { return this.agent.review(input); }
answer(input: string | AnswerOptions): void { return this.agent.answer(input); }
+ cancel(): void { this.agent.cancel(); }
setSystemPrompt(text: string, append = false): Promise<void> { return this.agent.setSystemPrompt(text, append); }
- close(): void { this.agent.close(); }
+ setModel(provider: ProviderId | string, model: ModelName | string): Promise<void> { return this.agent.setModel(provider, model); }
+ setEffort(level: EffortLevel): Promise<void> { return this.agent.setEffort(level); }
+ compact(): Promise<void> { return this.agent.compact(); }
+ close(): Promise<void> { return this.agent.close(); }
+ dispose(): Promise<void> { return this.agent.dispose(); }
}
// ── Top-level one-shot (parallel to codegraff's `runAgent`) ────────────────
@@ -428,7 +656,7 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {
try {
yield* h.chat({ prompt: opts.prompt });
} finally {
- h.close();
+ await h.close();
}
}
diff --git a/sdk/ts/orchestrate.test.ts b/sdk/ts/orchestrate.test.ts
index f51c71e4..e63f198e 100644
--- a/sdk/ts/orchestrate.test.ts
+++ b/sdk/ts/orchestrate.test.ts
@@ -5,7 +5,7 @@
// binary and is exercised structurally by the pure-helper tests instead).
import { describe, expect, test } from "bun:test";
-import { mkdtempSync, rmSync } from "node:fs";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -229,6 +229,54 @@ describe("Run budget admission", () => {
rmSync(dir, { recursive: true, force: true });
}
});
+
+ test("a runner that throws releases its reservation instead of draining the calls budget", async () => {
+ const dir = tmpJournalDir();
+ try {
+ let fail = true;
+ const runner = new FakeRunner(() => {
+ if (fail) throw new Error("transport down");
+ return ok("recovered", 10);
+ });
+ const run = new Run({ dir, budget: { maxCalls: 1 }, runner });
+
+ await expect(run.agent("attempt")).rejects.toThrow("transport down");
+ // The failed call never ran: nothing spent, and the slot is back — a
+ // healthy retry with the same maxCalls:1 ceiling is still admitted.
+ expect(run.budget.spent()).toEqual({ calls: 0, tokens: 0 });
+
+ fail = false;
+ const retry = await run.agent("attempt");
+ expect(retry.ok).toBe(true);
+ expect(retry.text).toBe("recovered");
+ expect(run.budget.spent()).toEqual({ calls: 1, tokens: 10 });
+
+ // A thrown call is NOT journaled (one record per LIVE call — file
+ // header), so a later resume re-runs from the failed key. The single
+ // record is the retry at key a1; a0 was consumed by the failed attempt.
+ const lines = readFileSync(run.journalPath, "utf8").trim().split("\n");
+ expect(lines.length).toBe(1);
+ expect(JSON.parse(lines[0]).key).toBe("a1");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("budget-exhaustion results do not share one mutable usage object", async () => {
+ const dir = tmpJournalDir();
+ try {
+ const run = new Run({ dir, budget: { maxCalls: 0 }, runner: new FakeRunner(() => ok("never runs")) });
+ const r1 = await run.agent("x");
+ const r2 = await run.agent("y");
+ expect(r1.ok).toBe(false);
+ expect(r2.ok).toBe(false);
+ expect(r1.usage).not.toBe(r2.usage);
+ r1.usage.contextTokens = 999;
+ expect(r2.usage.contextTokens).toBe(0);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
});
// ── Run: journal write/replay + prefix resume ────────────────────────────
diff --git a/sdk/ts/orchestrate.ts b/sdk/ts/orchestrate.ts
index 6673ab20..f221075c 100644
--- a/sdk/ts/orchestrate.ts
+++ b/sdk/ts/orchestrate.ts
@@ -217,7 +217,7 @@ export class HarnessRunner implements AgentRunner {
* tool_result — and whatever agent_usage event preceded it — have been
* seen. Never waits for the dispatcher's own turn/attempt_completion. */
private async drive(h: Harness, prompt: string, toolName: string): Promise<{ result: AgentResult | null; usage: AgentUsage }> {
- let usage = zeroUsage;
+ let usage = { ...zeroUsage };
let result: AgentResult | null = null;
for await (const ev of h.chat(prompt)) {
if (ev.type === "agent_usage") usage = usageFromEvent(ev);
@@ -282,7 +282,8 @@ export class Budget {
}
/** Record one live agent() call. Internal bookkeeping — agent()/Run.agent
- * call this; nothing else should. */
+ * call reserveCall()/chargeReserved() instead; nothing outside a Run
+ * should call any of the three. */
charge(usage: AgentUsage): void {
this._calls += 1;
this._tokens += usage.contextTokens;
@@ -301,6 +302,13 @@ export class Budget {
chargeReserved(usage: AgentUsage): void {
this._tokens += usage.contextTokens;
}
+
+ /** Undo a reservation whose runner never produced a result (transport
+ * error): the call never happened, so it must not count in spent() or
+ * drain the calls ceiling. Tokens are untouched — none were charged. */
+ releaseCall(): void {
+ this._calls -= 1;
+ }
}
// ── Concurrency ──────────────────────────────────────────────────────────
@@ -520,11 +528,22 @@ export class Run {
}
if (!this.budget.reserveCall()) {
- return { ok: false, text: "agent(): budget exhausted, call not admitted", usage: zeroUsage, cached: false };
+ return { ok: false, text: "agent(): budget exhausted, call not admitted", usage: { ...zeroUsage }, cached: false };
}
const runner = opts.runner ?? this.runner;
- const result = await runner.run(spec, { model: opts.model, harness: opts.harness });
+ let result: AgentResult;
+ try {
+ result = await runner.run(spec, { model: opts.model, harness: opts.harness });
+ } catch (err) {
+ // Transport failure: the call never ran. Release its reservation so a
+ // flaky runner can't drain the calls budget (making later calls fail
+ // with a misleading "budget exhausted"), and leave the journal
+ // untouched — resume re-runs from this key. Rethrow so callers and
+ // parallel()/pipeline() keep their reject/null-on-failure contract.
+ this.budget.releaseCall();
+ throw err;
+ }
this.budget.chargeReserved(result.usage);
this.appendJournal({ key, promptHash, optsHash, ok: result.ok, text: result.text, usage: result.usage, ts: Date.now() });
return result;
diff --git a/sdk/ts/package.json b/sdk/ts/package.json
index 62ca189d..480e0458 100644
--- a/sdk/ts/package.json
+++ b/sdk/ts/package.json
@@ -1,25 +1,25 @@
{
"name": "@codegraff/sdk",
- "version": "0.3.1",
+ "version": "0.4.0",
"description": "TypeScript / Node SDK for the codegraff agent — drives `graff --json` over stdio. Types auto-generated from `graff --schema`.",
"type": "module",
- "main": "harness.ts",
- "types": "harness.ts",
+ "main": "dist/harness.js",
+ "types": "dist/harness.d.ts",
"exports": {
".": {
- "types": "./harness.ts",
- "import": "./harness.ts",
- "default": "./harness.ts"
+ "types": "./dist/harness.d.ts",
+ "import": "./dist/harness.js",
+ "default": "./dist/harness.js"
},
"./remote": {
- "types": "./remote.ts",
- "import": "./remote.ts",
- "default": "./remote.ts"
+ "types": "./dist/remote.d.ts",
+ "import": "./dist/remote.js",
+ "default": "./dist/remote.js"
},
"./orchestrate": {
- "types": "./orchestrate.ts",
- "import": "./orchestrate.ts",
- "default": "./orchestrate.ts"
+ "types": "./dist/orchestrate.d.ts",
+ "import": "./dist/orchestrate.js",
+ "default": "./dist/orchestrate.js"
},
"./package.json": "./package.json"
},
@@ -30,12 +30,24 @@
},
"homepage": "https://codegraff.com",
"keywords": ["codegraff", "graff", "agent", "llm", "harness", "sdk"],
- "files": ["harness.ts", "remote.ts", "orchestrate.ts", "README.md"],
+ "files": ["dist", "README.md"],
"engines": { "node": ">=18" },
"license": "Apache-2.0",
+ "optionalDependencies": {
+ "@codegraff/graff-darwin-arm64": "0.4.0",
+ "@codegraff/graff-darwin-x64": "0.4.0",
+ "@codegraff/graff-linux-arm64": "0.4.0",
+ "@codegraff/graff-linux-x64": "0.4.0",
+ "@codegraff/graff-win32-arm64": "0.4.0",
+ "@codegraff/graff-win32-x64": "0.4.0"
+ },
"scripts": {
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
+ "version:sync": "node scripts/set-version.mjs",
"typecheck": "tsc --noEmit -p tsconfig.json",
- "test": "bun test"
+ "test": "bun test",
+ "test:packed": "node scripts/test-packed-install.mjs",
+ "prepack": "npm run build"
},
"devDependencies": {
"@types/node": "^22.10.2",
diff --git a/sdk/ts/remote.test.ts b/sdk/ts/remote.test.ts
new file mode 100644
index 00000000..1f2a0485
--- /dev/null
+++ b/sdk/ts/remote.test.ts
@@ -0,0 +1,183 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { RemoteHarness, type Event } from "./remote.ts";
+
+const originalFetch = globalThis.fetch;
+const live: RemoteHarness[] = [];
+const enc = new TextEncoder();
+type InputEvent = Event extends infer T ? T extends { seq: number } ? Omit<T, "seq"> : never : never;
+const line = (event: Event) => enc.encode(`${JSON.stringify(event)}\n`);
+
+class FakeBridge {
+ requests: string[] = [];
+ readerCancels = 0;
+ active?: ReadableStreamDefaultController<Uint8Array>;
+ seq = 0;
+
+ event(event: InputEvent): Event {
+ return { seq: ++this.seq, ...event } as Event;
+ }
+
+ stream(events: InputEvent[], keepOpen = true): Response {
+ const bridge = this;
+ return new Response(new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const event of events) controller.enqueue(line(bridge.event(event)));
+ if (!keepOpen) controller.close();
+ },
+ cancel() { bridge.readerCancels += 1; },
+ }), { status: 200, headers: { "content-type": "application/x-ndjson" } });
+ }
+
+ fetch = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
+ const url = new URL(String(input));
+ const body = init?.body ? JSON.parse(String(init.body)) as Record<string, unknown> : {};
+ if (url.pathname === "/v1/sessions") {
+ return Response.json({ session_id: "s1", resumed: false, last_seq: 0 });
+ }
+ if (init?.method === "DELETE") return Response.json({ ok: true });
+ const type = String(body.type ?? "reattach");
+ this.requests.push(type);
+ if (type === "cancel") {
+ this.active?.enqueue(line(this.event({ type: "error", message: "turn cancelled" })));
+ this.active = undefined;
+ return Response.json({ ok: true, type: "cancel" });
+ }
+ if (type === "answer") {
+ this.active?.enqueue(line(this.event({
+ type: "turn", text: `answered:${String(body.text)}`, context_tokens: 1,
+ cost_usd: 0, input_tokens: 1, uncached_input_tokens: 1,
+ cache_read_tokens: 0, output_tokens: 1, api_calls: 1,
+ subscription_calls: 0, unpriced_calls: 0, complete: true,
+ metadata_complete: true,
+ })));
+ this.active = undefined;
+ return Response.json({ ok: true, type: "answer" });
+ }
+ if (type === "user" || type === "review") {
+ const text = String(body.text);
+ if (text === "slow" || text === "ask") {
+ const bridge = this;
+ return new Response(new ReadableStream<Uint8Array>({
+ start(controller) {
+ bridge.active = controller;
+ controller.enqueue(line(bridge.event(text === "ask"
+ ? { type: "ask_user", call_id: "r-ask", question: "continue?", input: {} }
+ : { type: "started", provider: "fake", model: "fake" })));
+ },
+ cancel() { bridge.readerCancels += 1; },
+ }), { status: 200 });
+ }
+ return this.stream([{
+ type: "turn", text: `${type}:${text}`, context_tokens: 9,
+ cost_usd: 0.1, input_tokens: 5, uncached_input_tokens: 2,
+ cache_read_tokens: 3, output_tokens: 4, api_calls: 1,
+ subscription_calls: 1, unpriced_calls: 0, complete: true,
+ metadata_complete: true,
+ }]);
+ }
+ if (type === "set_model") return String(body.model) === "bad"
+ ? this.stream([{ type: "error", message: "bad model" }])
+ : this.stream([{
+ type: "model", ok: true, provider: String(body.provider), model: String(body.model), context: 100, note: "",
+ }]);
+ if (type === "set_effort") return this.stream([{
+ type: "effort", ok: true, level: String(body.level), applies: true,
+ }]);
+ if (type === "compact") return this.stream([{ type: "compact", ok: true, chars: 3 }]);
+ if (type === "reattach") return this.stream([{
+ type: "turn", text: "replayed", context_tokens: 1, cost_usd: 0,
+ input_tokens: 1, uncached_input_tokens: 1, cache_read_tokens: 0,
+ output_tokens: 1, api_calls: 1, subscription_calls: 0,
+ unpriced_calls: 0, complete: true, metadata_complete: true,
+ }], false);
+ throw new Error(`unexpected request ${type}`);
+ };
+}
+
+const use = (bridge: FakeBridge) => {
+ globalThis.fetch = bridge.fetch as typeof fetch;
+ const h = new RemoteHarness({ url: "http://bridge.test" });
+ live.push(h);
+ return h;
+};
+
+const waitFor = async (predicate: () => boolean) => {
+ for (let i = 0; i < 100 && !predicate(); i += 1) await Bun.sleep(5);
+ if (!predicate()) throw new Error("condition timed out");
+};
+
+afterEach(async () => {
+ for (const value of live.splice(0)) await value.close();
+ globalThis.fetch = originalFetch;
+});
+
+describe("RemoteHarness transport", () => {
+ test("serializes turns and controls and releases terminal response readers", async () => {
+ const bridge = new FakeBridge();
+ const h = use(bridge);
+ const turn = h.askResult("one");
+ const model = h.setModel("codex", "gpt-test");
+ const effort = h.setEffort("xhigh");
+ const compact = h.compact();
+ const result = await turn;
+ await Promise.all([model, effort, compact]);
+
+ expect(result.text).toBe("user:one");
+ expect(result.cacheReadTokens).toBe(3);
+ expect(bridge.requests.slice(0, 4)).toEqual(["user", "set_model", "set_effort", "compact"]);
+ expect(bridge.readerCancels).toBeGreaterThanOrEqual(4);
+ });
+
+ test("a failed control does not poison the operation queue", async () => {
+ const bridge = new FakeBridge();
+ const h = use(bridge);
+ await expect(h.setModel("codex", "bad")).rejects.toThrow("bad model");
+ expect(await h.ask("after-error")).toBe("user:after-error");
+ });
+
+ test("AbortSignal sends an out-of-band cancel and later turns still work", async () => {
+ const bridge = new FakeBridge();
+ const h = use(bridge);
+ const controller = new AbortController();
+ const pending = h.ask({ prompt: "slow", signal: controller.signal });
+ await waitFor(() => bridge.requests.includes("user"));
+ controller.abort();
+ await expect(pending).rejects.toThrow("turn cancelled");
+ expect(bridge.requests).toContain("cancel");
+ expect(await h.ask("after")).toBe("user:after");
+ });
+
+ test("answer bypasses the active ask_user stream", async () => {
+ const bridge = new FakeBridge();
+ const h = use(bridge);
+ let final = "";
+ for await (const event of h.chat("ask")) {
+ if (event.type === "ask_user") await h.answer({ text: "yes", callId: event.call_id });
+ if (event.type === "turn") final = event.text;
+ }
+ expect(final).toBe("answered:yes");
+ });
+
+ test("reconnect replays from the requested sequence and updates lastSeq", async () => {
+ const bridge = new FakeBridge();
+ const h = use(bridge);
+ const events = [];
+ for await (const event of h.reconnect(7)) events.push(event);
+ expect(events.at(-1)?.type).toBe("turn");
+ expect(h.lastSeq).toBeGreaterThan(0);
+ expect(bridge.requests).toContain("reattach");
+ });
+
+ test("constructor observes create rejection even when the caller never awaits it", async () => {
+ let unhandled = 0;
+ const listener = () => { unhandled += 1; };
+ process.on("unhandledRejection", listener);
+ globalThis.fetch = (async () => { throw new Error("create failed"); }) as unknown as typeof fetch;
+ const h = new RemoteHarness({ url: "http://bridge.test" });
+ live.push(h);
+ await Bun.sleep(30);
+ process.off("unhandledRejection", listener);
+ expect(unhandled).toBe(0);
+ await expect(h.sessionId).rejects.toThrow("create failed");
+ });
+});
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index 1b0657ab..d7026999 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -7,7 +7,7 @@
// `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.11";
+export const HARNESS_VERSION = "0.12";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-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" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "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" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "imagegen";
@@ -35,8 +35,11 @@ export type Event =
| { 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; complete?: boolean; metadata_complete?: boolean }
+ | { 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 };
@@ -94,6 +97,11 @@ export interface ChatOptions {
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 {
@@ -102,6 +110,33 @@ 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;
}
@@ -113,19 +148,26 @@ 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}$/;
@@ -142,6 +184,9 @@ const HEX16 = /^[0-9a-f]{16}$/;
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
@@ -159,8 +204,15 @@ export class RemoteHarness {
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;
- this.sessionId = created.then((d) => d.session_id);
+ const sid = created.then((d) => d.session_id);
+ sid.catch(() => {});
+ this.sessionId = sid;
}
}
@@ -209,6 +261,29 @@ export class RemoteHarness {
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>, from?: number): AsyncGenerator<Event> {
const id = await this.sessionId;
@@ -217,17 +292,41 @@ export class RemoteHarness {
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;
const type = typeof input === "string" || !input.review ? "user" : "review";
const from = typeof input === "string" ? undefined : input.from;
- let terminal = false;
- for await (const ev of this.send({ type, text: prompt }, from)) {
- yield ev;
- if (ev.type === "turn" || ev.type === "error") { terminal = true; break; }
+ 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 });
+ 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?)");
}
/** Re-attach to a session after losing the stream: replay persisted events
@@ -242,20 +341,43 @@ export class RemoteHarness {
for await (const ev of ndjson(res)) yield this.note(ev);
}
- /** Run a turn and return just the final assistant text. */
- async ask(input: string | ChatOptions): Promise<string> {
- let final = "";
+ /** 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 prompt = typeof input === "string" ? input : input.prompt;
- return this.ask({ prompt, review: true });
+ 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
@@ -268,17 +390,69 @@ 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); }
@@ -295,22 +469,32 @@ export class RemoteHarness {
// 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.)
- 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");
+ 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. */
diff --git a/sdk/ts/scripts/package-platform.mjs b/sdk/ts/scripts/package-platform.mjs
new file mode 100644
index 00000000..aa327268
--- /dev/null
+++ b/sdk/ts/scripts/package-platform.mjs
@@ -0,0 +1,84 @@
+#!/usr/bin/env node
+import { chmod, copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { basename, dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const SDK_ROOT = resolve(HERE, "..");
+const REPO_ROOT = resolve(SDK_ROOT, "../..");
+
+const TARGETS = {
+ "aarch64-macos": { suffix: "darwin-arm64", os: "darwin", cpu: "arm64", binary: "graff" },
+ "x86_64-macos": { suffix: "darwin-x64", os: "darwin", cpu: "x64", binary: "graff" },
+ "aarch64-linux": { suffix: "linux-arm64", os: "linux", cpu: "arm64", binary: "graff" },
+ "x86_64-linux": { suffix: "linux-x64", os: "linux", cpu: "x64", binary: "graff" },
+ "aarch64-windows": { suffix: "win32-arm64", os: "win32", cpu: "arm64", binary: "graff.exe" },
+ "x86_64-windows": { suffix: "win32-x64", os: "win32", cpu: "x64", binary: "graff.exe" },
+};
+
+function usage(message) {
+ if (message) console.error(`error: ${message}`);
+ console.error("usage: package-platform.mjs --target <zig-target> --binary <path> --out <dir> [--version <semver>]");
+ process.exit(2);
+}
+
+function argumentsMap(argv) {
+ const values = {};
+ for (let i = 0; i < argv.length; i += 2) {
+ const key = argv[i];
+ const value = argv[i + 1];
+ if (!key?.startsWith("--") || value === undefined) usage("options require values");
+ values[key.slice(2)] = value;
+ }
+ return values;
+}
+
+const args = argumentsMap(process.argv.slice(2));
+const target = TARGETS[args.target];
+if (!target) usage(`unsupported target ${args.target ?? "(missing)"}`);
+if (!args.binary) usage("--binary is required");
+if (!args.out) usage("--out is required");
+
+const sdkManifest = JSON.parse(await readFile(join(SDK_ROOT, "package.json"), "utf8"));
+const generated = await readFile(join(SDK_ROOT, "harness.ts"), "utf8");
+const protocol = generated.match(/export const HARNESS_VERSION = "([^"]+)";/)?.[1];
+if (!protocol) throw new Error("could not read HARNESS_VERSION from generated harness.ts");
+const version = args.version ?? sdkManifest.version;
+const packageName = `@codegraff/graff-${target.suffix}`;
+const packageDir = resolve(args.out, `graff-${target.suffix}`);
+const binaryDir = join(packageDir, "bin");
+const binaryDest = join(binaryDir, target.binary);
+
+await rm(packageDir, { recursive: true, force: true });
+await mkdir(binaryDir, { recursive: true });
+await copyFile(resolve(args.binary), binaryDest);
+await chmod(binaryDest, 0o755);
+await copyFile(join(REPO_ROOT, "LICENSE"), join(packageDir, "LICENSE"));
+
+const manifest = {
+ name: packageName,
+ version,
+ description: `Native graff executable for ${target.os}-${target.cpu}`,
+ graffProtocol: protocol,
+ license: "Apache-2.0",
+ repository: {
+ type: "git",
+ url: "git+https://github.com/justrach/codegraff.git",
+ },
+ os: [target.os],
+ cpu: [target.cpu],
+ preferUnplugged: true,
+ files: ["bin", "README.md", "LICENSE"],
+ bin: { graff: `bin/${target.binary}` },
+ exports: {
+ "./package.json": "./package.json",
+ [`./bin/${target.binary}`]: `./bin/${target.binary}`,
+ },
+};
+
+await writeFile(join(packageDir, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+await writeFile(join(packageDir, "README.md"), `# ${packageName}\n\n` +
+ `Platform-specific native executable used by \`@codegraff/sdk\`. ` +
+ `Install the SDK instead of depending on this package directly.\n`);
+
+process.stdout.write(`${JSON.stringify({ packageDir, packageName, version, target: args.target, binary: basename(binaryDest) })}\n`);
diff --git a/sdk/ts/scripts/set-version.mjs b/sdk/ts/scripts/set-version.mjs
new file mode 100644
index 00000000..e61640cb
--- /dev/null
+++ b/sdk/ts/scripts/set-version.mjs
@@ -0,0 +1,19 @@
+#!/usr/bin/env node
+import { readFile, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
+const version = process.argv[2];
+if (!version || !/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
+ console.error("usage: set-version.mjs <semver>");
+ process.exit(2);
+}
+
+const path = join(ROOT, "package.json");
+const manifest = JSON.parse(await readFile(path, "utf8"));
+manifest.version = version;
+for (const name of Object.keys(manifest.optionalDependencies ?? {})) {
+ if (name.startsWith("@codegraff/graff-")) manifest.optionalDependencies[name] = version;
+}
+await writeFile(path, `${JSON.stringify(manifest, null, 2)}\n`);
diff --git a/sdk/ts/scripts/test-packed-install.mjs b/sdk/ts/scripts/test-packed-install.mjs
new file mode 100644
index 00000000..0492458a
--- /dev/null
+++ b/sdk/ts/scripts/test-packed-install.mjs
@@ -0,0 +1,133 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const SDK_ROOT = resolve(HERE, "..");
+const npmCli = process.env.npm_execpath;
+if (!npmCli) throw new Error("run this smoke through `npm run test:packed`");
+const PLATFORM_PACKAGES = {
+ "darwin-arm64": "@codegraff/graff-darwin-arm64",
+ "darwin-x64": "@codegraff/graff-darwin-x64",
+ "linux-arm64": "@codegraff/graff-linux-arm64",
+ "linux-x64": "@codegraff/graff-linux-x64",
+ "win32-arm64": "@codegraff/graff-win32-arm64",
+ "win32-x64": "@codegraff/graff-win32-x64",
+};
+const ALL_TARGETS = [
+ ["aarch64-macos", "@codegraff/graff-darwin-arm64"],
+ ["x86_64-macos", "@codegraff/graff-darwin-x64"],
+ ["aarch64-linux", "@codegraff/graff-linux-arm64"],
+ ["x86_64-linux", "@codegraff/graff-linux-x64"],
+ ["aarch64-windows", "@codegraff/graff-win32-arm64"],
+ ["x86_64-windows", "@codegraff/graff-win32-x64"],
+];
+
+function option(name) {
+ const index = process.argv.indexOf(name);
+ return index === -1 ? undefined : process.argv[index + 1];
+}
+
+function run(file, args, cwd, env = process.env) {
+ return execFileSync(file, args, { cwd, env, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
+}
+
+function npmRun(args, cwd) {
+ return run(process.execPath, [npmCli, ...args], cwd);
+}
+
+function pack(directory, destination) {
+ const output = npmRun(["pack", directory, "--pack-destination", destination, "--json", "--silent"], SDK_ROOT);
+ const result = JSON.parse(output);
+ if (result.length !== 1 || !result[0].filename) throw new Error(`unexpected npm pack output: ${output}`);
+ return join(destination, result[0].filename);
+}
+
+const temp = await mkdtemp(join(tmpdir(), "codegraff-sdk-packed-"));
+try {
+ const packages = join(temp, "packages");
+ const tarballs = join(temp, "tarballs");
+ const consumer = join(temp, "consumer");
+ const emptyPath = join(temp, "empty-path");
+ await Promise.all([packages, tarballs, consumer, emptyPath].map((path) => mkdir(path, { recursive: true })));
+
+ const suppliedBinary = option("--binary");
+ if (process.platform === "win32" && !suppliedBinary) {
+ throw new Error("Windows packed smoke requires --binary pointing to a real graff.exe");
+ }
+ const sourceBinary = suppliedBinary ? resolve(suppliedBinary) : join(temp, "fake-graff");
+ if (!suppliedBinary) {
+ const fixture = await readFile(join(SDK_ROOT, "test-fixtures", "fake-graff.mjs"), "utf8");
+ await writeFile(sourceBinary, fixture.replace(/^#!.*$/m, `#!${process.execPath}`));
+ await chmod(sourceBinary, 0o755);
+ }
+
+ const nativeTarballs = {};
+ for (const [target, packageName] of ALL_TARGETS) {
+ const output = run(process.execPath, [
+ join(HERE, "package-platform.mjs"),
+ "--target", target,
+ "--binary", sourceBinary,
+ "--out", packages,
+ ], SDK_ROOT);
+ const { packageDir } = JSON.parse(output);
+ nativeTarballs[packageName] = pack(packageDir, tarballs);
+ }
+ const sdkTarball = pack(SDK_ROOT, tarballs);
+
+ const manifest = {
+ private: true,
+ type: "module",
+ dependencies: { "@codegraff/sdk": `file:${sdkTarball}` },
+ optionalDependencies: Object.fromEntries(
+ Object.entries(nativeTarballs).map(([name, path]) => [name, `file:${path}`]),
+ ),
+ };
+ await writeFile(join(consumer, "package.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+ npmRun(["install", "--ignore-scripts", "--no-audit", "--no-fund"], consumer);
+
+ const smoke = `
+import { Harness } from "@codegraff/sdk";
+const harness = Harness.init({ env: { ...process.env, PATH: process.env.CLEAN_PATH, Path: process.env.CLEAN_PATH, GRAFF_NO_TELEMETRY: "1" } });
+try {
+ ${suppliedBinary ? "await harness.setEffort(\"low\");" : "const text = await harness.ask(\"out-of-box\"); if (text !== \"user:out-of-box\") throw new Error(`unexpected reply: \${text}`);"}
+} finally {
+ await harness.close();
+}
+console.log("packed SDK resolved and ran its optional native package with no graff on PATH");
+`;
+ await writeFile(join(consumer, "smoke.mjs"), smoke);
+ const output = run(process.execPath, [join(consumer, "smoke.mjs")], consumer, {
+ ...process.env,
+ CLEAN_PATH: emptyPath,
+ });
+ process.stdout.write(output);
+
+ const packageName = PLATFORM_PACKAGES[`${process.platform}-${process.arch}`];
+ if (!packageName) throw new Error(`test does not support ${process.platform}-${process.arch}`);
+ const require = createRequire(join(consumer, "package.json"));
+ const nativeManifestPath = require.resolve(`${packageName}/package.json`);
+ const nativeManifest = JSON.parse(await readFile(nativeManifestPath, "utf8"));
+ nativeManifest.graffProtocol = "incompatible-test-version";
+ await writeFile(nativeManifestPath, `${JSON.stringify(nativeManifest, null, 2)}\n`);
+ await writeFile(join(consumer, "mismatch.mjs"), `
+import { Harness } from "@codegraff/sdk";
+try {
+ Harness.init({ env: { ...process.env, PATH: process.env.CLEAN_PATH, Path: process.env.CLEAN_PATH } });
+ throw new Error("expected protocol mismatch");
+} catch (error) {
+ if (!String(error).includes("uses graff protocol incompatible-test-version")) throw error;
+}
+console.log("packed SDK rejects an incompatible optional native package");
+`);
+ process.stdout.write(run(process.execPath, [join(consumer, "mismatch.mjs")], consumer, {
+ ...process.env,
+ CLEAN_PATH: emptyPath,
+ }));
+} finally {
+ await rm(temp, { recursive: true, force: true });
+}
diff --git a/sdk/ts/test-fixtures/fake-graff.mjs b/sdk/ts/test-fixtures/fake-graff.mjs
new file mode 100755
index 00000000..4ff22d58
--- /dev/null
+++ b/sdk/ts/test-fixtures/fake-graff.mjs
@@ -0,0 +1,62 @@
+#!/usr/bin/env node
+import { createInterface } from "node:readline";
+
+let seq = 0;
+let active = null;
+const emit = (event) => process.stdout.write(JSON.stringify({ seq: ++seq, ...event }) + "\n");
+const turn = (text) => emit({
+ type: "turn", text, context_tokens: 42, cost_usd: 0.012,
+ input_tokens: 10, uncached_input_tokens: 4, cache_read_tokens: 6,
+ output_tokens: 3, api_calls: 2, subscription_calls: 1,
+ unpriced_calls: 0, complete: true, metadata_complete: true,
+});
+
+createInterface({ input: process.stdin }).on("line", (line) => {
+ const request = JSON.parse(line);
+ switch (request.type) {
+ case "user":
+ case "review":
+ if (request.text === "die") process.exit(7);
+ active = request.text;
+ emit({ type: "started", provider: "fake", model: "fake" });
+ if (request.text === "slow") return;
+ if (request.text === "ask") {
+ emit({ type: "ask_user", call_id: "ask-1", question: "continue?", options: ["yes"] });
+ return;
+ }
+ setTimeout(() => {
+ turn(`${request.type}:${request.text}`);
+ active = null;
+ }, 15);
+ return;
+ case "answer":
+ if (active !== "ask") return;
+ emit({ type: "tool_result", name: "ask_user", is_error: false, text: request.text });
+ turn(`answered:${request.text}`);
+ active = null;
+ return;
+ case "cancel":
+ if (active === null) return;
+ emit({ type: "error", message: "turn cancelled" });
+ active = null;
+ return;
+ case "set_model":
+ if (request.model === "bad") emit({ type: "error", message: "bad model" });
+ else emit({ type: "model", ok: true, provider: request.provider, model: request.model, context: 1000, note: "" });
+ return;
+ case "set_effort":
+ emit({ type: "effort", ok: true, level: request.level, applies: true });
+ return;
+ case "compact":
+ emit({ type: "compact", ok: true, chars: 12 });
+ return;
+ case "set_system_prompt":
+ emit({ type: "system_prompt", ok: true, append: !!request.append, chars: request.text.length });
+ return;
+ case "score":
+ emit({ type: "score", ok: true, prompt_sha: request.prompt_sha });
+ return;
+ default:
+ emit({ type: "error", message: `unexpected request ${request.type}` });
+ }
+});
diff --git a/sdk/ts/tsconfig.build.json b/sdk/ts/tsconfig.build.json
new file mode 100644
index 00000000..c859eb75
--- /dev/null
+++ b/sdk/ts/tsconfig.build.json
@@ -0,0 +1,14 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "dist",
+ "rootDir": ".",
+ "rewriteRelativeImportExtensions": true
+ },
+ "include": ["harness.ts", "remote.ts", "orchestrate.ts"],
+ "exclude": ["*.test.ts"]
+}
diff --git a/src/agent.zig b/src/agent.zig
index acf33f87..03da64ce 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -321,7 +321,7 @@ pub const Agent = struct {
try self.ensureRootTools(self.provider.kind);
// No per-turn teardown: the socket and the chain span user turns, guarded by codex_chain.usable instead.
self.completed = null;
- if (!self.sub) esc_cancel.store(false, .release); // fresh turn, no stale cancel
+ if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) esc_cancel.store(false, .release);
while (true) {
// Esc during a tool join (set by escWatchTask) lands here: the
// root consumes the flag and aborts before the next request;
@@ -474,8 +474,16 @@ pub const Agent = struct {
/// turn iterations, and the root consumes at its next loop head as
/// error.Interrupted.
pub var esc_cancel: std.atomic.Value(bool) = .init(false);
+ var root_turn_prepared: std.atomic.Value(bool) = .init(false);
pub var esc_watch_done: std.atomic.Value(bool) = .init(true);
+ /// Clear stale cancellation before the root becomes externally cancellable;
+ /// runTurn consumes the marker without erasing a cancellation arriving later.
+ pub fn prepareRootTurn() void {
+ esc_cancel.store(false, .release);
+ root_turn_prepared.store(true, .release);
+ }
+
// Esc-cancel handling (the stdin scanner + steering-buffer capture +
// interruptible sleep) lives in agent_interrupt.zig (#123, 600-line
// goal). Member-aliased so self.sleepInterruptible(...)/etc. resolve
diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zig
index 8f285125..06f8f5f0 100644
--- a/src/agent_tool_gate.zig
+++ b/src/agent_tool_gate.zig
@@ -3,6 +3,7 @@
const std = @import("std");
const main_mod = @import("main.zig");
+const json_inbox = @import("json_inbox.zig");
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
const tools_mod = @import("tools.zig");
@@ -92,7 +93,7 @@ fn gatePrivateTemplateSharing(self: *Agent, call: ToolCall) !?ExecResult {
try w.writeAll(" Sends: exact reusable system/persona text. Excludes: task prompt, bindings, code, paths, reports, and tool results.\n");
try w.writeAll(" [y] share exact template version(s) this session · [l] run locally · [n] cancel child › ");
try w.flush();
- const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";
+ const raw: []const u8 = (try json_inbox.reply(self.arena, in)) orelse "";
const answer = std.mem.trim(u8, raw, " \t\r");
if (answer.len > 0 and (answer[0] == 'y' or answer[0] == 'Y')) {
for (candidates.items[0..candidates.len]) |prompt| {
@@ -187,7 +188,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
if (self.in) |in| if (self.out) |w| {
try w.print(" ⚠ plan mode — read outside the project: {s}\n [a]llow read-only access to these paths this session · [n]o › ", .{cmd});
try w.flush();
- const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";
+ const raw: []const u8 = (try json_inbox.reply(self.arena, in)) orelse "";
const answer = std.mem.trim(u8, raw, " \t\r");
if (answer.len > 0 and (answer[0] == 'a' or answer[0] == 'A' or answer[0] == 'y' or answer[0] == 'Y')) {
try approvals.approvePlanRead(self.io, self.gpa, cmd);
@@ -265,7 +266,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
" [y] run + send once · [n] cancel › ",
);
try w.flush();
- const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";
+ const raw: []const u8 = (try json_inbox.reply(self.arena, in)) orelse "";
const answer = std.mem.trim(u8, raw, " \t\r");
if (answer.len > 0 and (answer[0] == 'y' or answer[0] == 'Y')) {
learning_privacy.authorizeAggregateOnce(self.io);
@@ -303,7 +304,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
};
try w.print(" ⚠ {s}\n [y]es once · [a]lways allow \"{s}\" (saved to {s}) · [n]o › ", .{ prompt_line, key, Approvals.settings_path });
try w.flush();
- const raw: []const u8 = (try in.takeDelimiter('\n')) orelse "";
+ const raw: []const u8 = (try json_inbox.reply(self.arena, in)) orelse "";
const answer = std.mem.trim(u8, raw, " \t\r");
if (answer.len > 0) switch (answer[0]) {
'y', 'Y' => return null,
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 7d47e251..69912726 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -11,6 +11,7 @@ const Io = std.Io;
const Value = std.json.Value;
const main_mod = @import("main.zig");
+const json_inbox = @import("json_inbox.zig");
const review = @import("review.zig");
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
@@ -367,9 +368,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
return .{ .text = self.renderTodos(goal_state.currentEpoch(self.goal)), .is_error = false };
}
-/// The "user message as a tool" half of the loop: the agent calls
-/// ask_user, we block for a typed reply, and hand it back as the tool
-/// result. Only the root agent has stdin; subagents must self-decide.
+/// Block the root agent for an ask_user reply; subagents have no stdin.
pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
const in = self.in orelse return .{
.text = "no human is attached — make a reasonable assumption and continue",
@@ -384,7 +383,7 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
break :blk id;
};
try self.emitAskUser(call_id, question, call.input);
- const raw = (try in.takeDelimiter('\n')) orelse return .{
+ const raw = (try json_inbox.reply(self.arena, in)) orelse return .{
.text = "user ended input without answering",
.is_error = true,
};
diff --git a/src/json_inbox.zig b/src/json_inbox.zig
new file mode 100644
index 00000000..f175b455
--- /dev/null
+++ b/src/json_inbox.zig
@@ -0,0 +1,180 @@
+//! Single owner for `--json` stdin. The reader runs while a model turn is
+//! blocked so `cancel` can trip Agent.esc_cancel without racing ask/gate replies.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const Agent = @import("agent.zig").Agent;
+
+const cancelled_answer = "{\"type\":\"answer\",\"cancelled\":true}";
+
+var inbox_io: ?Io = null;
+var inbox_gpa: ?Allocator = null;
+var inbox_reader: ?*Io.Reader = null;
+var mutex: Io.Mutex = .init;
+var ready: Io.Condition = .init;
+var lines: std.ArrayList([]u8) = .empty;
+var eof = false;
+var cancel_epoch: u64 = 0;
+var turn_active: std.atomic.Value(bool) = .init(false);
+var turn_pending: std.atomic.Value(bool) = .init(false);
+var pending_cancelled = false;
+var queued_cancel = false;
+var reply_cancel_epoch: u64 = 0;
+var future: ?Io.Future(void) = null;
+
+pub fn start(gpa: Allocator, io: Io, reader: *Io.Reader) void {
+ std.debug.assert(inbox_io == null);
+ inbox_io = io;
+ inbox_gpa = gpa;
+ inbox_reader = reader;
+ eof = false;
+ cancel_epoch = 0;
+ reply_cancel_epoch = 0;
+ pending_cancelled = false;
+ queued_cancel = false;
+ turn_active.store(false, .release);
+ turn_pending.store(false, .release);
+ future = io.async(readerTask, .{});
+}
+
+pub fn stop() void {
+ const io = inbox_io orelse return;
+ if (future) |*f| f.cancel(io);
+ future = null;
+ mutex.lockUncancelable(io);
+ const gpa = inbox_gpa.?;
+ for (lines.items) |line| gpa.free(line);
+ lines.deinit(gpa);
+ lines = .empty;
+ inbox_reader = null;
+ inbox_gpa = null;
+ inbox_io = null;
+ mutex.unlock(io);
+}
+
+/// Promote the dequeued request to active without a gap where cancel can be
+/// cleared by fresh-turn setup. Returns false when the pending turn was cancelled.
+pub fn beginTurn(root: *Agent) bool {
+ const io = inbox_io orelse {
+ Agent.prepareRootTurn();
+ return true;
+ };
+ mutex.lockUncancelable(io);
+ defer mutex.unlock(io);
+ turn_pending.store(false, .release);
+ if (pending_cancelled) {
+ pending_cancelled = false;
+ Agent.esc_cancel.store(false, .release);
+ root.emit(.{ .type = "error", .message = "turn cancelled" });
+ return false;
+ }
+ Agent.prepareRootTurn();
+ turn_active.store(true, .release);
+ return true;
+}
+
+pub fn endTurn() void {
+ turn_active.store(false, .release);
+}
+
+/// Mainloop request read. In non-JSON modes the original reader remains owner.
+pub fn request(arena: Allocator, fallback: *Io.Reader) !?[]const u8 {
+ return read(arena, fallback, false);
+}
+
+/// Mid-turn ask/gate read. A cancel wakes it with a synthetic cancelled answer,
+/// allowing the tool future to join before runTurn observes esc_cancel.
+pub fn reply(arena: Allocator, fallback: *Io.Reader) !?[]const u8 {
+ return read(arena, fallback, true);
+}
+
+fn read(arena: Allocator, fallback: *Io.Reader, is_reply: bool) !?[]const u8 {
+ const io = inbox_io orelse return fallback.takeDelimiter('\n');
+ mutex.lockUncancelable(io);
+ defer mutex.unlock(io);
+ while (lines.items.len == 0 and !eof and !(is_reply and cancel_epoch > reply_cancel_epoch))
+ ready.waitUncancelable(io, &mutex);
+ if (is_reply and cancel_epoch > reply_cancel_epoch) {
+ reply_cancel_epoch = cancel_epoch;
+ return try arena.dupe(u8, cancelled_answer);
+ }
+ if (lines.items.len == 0) return null;
+ const owned = lines.orderedRemove(0);
+ defer inbox_gpa.?.free(owned);
+ if (!is_reply and isTurn(inbox_gpa.?, owned)) {
+ turn_pending.store(true, .release);
+ if (queued_cancel) {
+ queued_cancel = false;
+ pending_cancelled = true;
+ }
+ }
+ return try arena.dupe(u8, owned);
+}
+
+fn readerTask() void {
+ const io = inbox_io.?;
+ const gpa = inbox_gpa.?;
+ const reader = inbox_reader.?;
+ while (true) {
+ const raw = reader.takeDelimiter('\n') catch break;
+ const line = raw orelse break;
+ if (isCancel(gpa, line)) {
+ mutex.lockUncancelable(io);
+ const active = turn_active.load(.acquire);
+ const pending = turn_pending.load(.acquire);
+ var queued_turn = false;
+ for (lines.items) |queued| queued_turn = queued_turn or isTurn(gpa, queued);
+ if (active) {
+ Agent.esc_cancel.store(true, .release);
+ cancel_epoch +%= 1;
+ } else if (pending) {
+ pending_cancelled = true;
+ } else if (queued_turn) {
+ queued_cancel = true;
+ }
+ if (active or pending or queued_turn) ready.broadcast(io);
+ mutex.unlock(io);
+ continue;
+ }
+ const copy = gpa.dupe(u8, line) catch break;
+ mutex.lockUncancelable(io);
+ lines.append(gpa, copy) catch {
+ mutex.unlock(io);
+ gpa.free(copy);
+ break;
+ };
+ ready.broadcast(io);
+ mutex.unlock(io);
+ }
+ mutex.lockUncancelable(io);
+ eof = true;
+ ready.broadcast(io);
+ mutex.unlock(io);
+}
+
+fn isCancel(gpa: Allocator, line: []const u8) bool {
+ return isRequestType(gpa, line, "cancel", false);
+}
+
+fn isTurn(gpa: Allocator, line: []const u8) bool {
+ return isRequestType(gpa, line, "user", true) or isRequestType(gpa, line, "review", true);
+}
+
+fn isRequestType(gpa: Allocator, line: []const u8, expected: []const u8, require_text: bool) bool {
+ const parsed = std.json.parseFromSlice(Value, gpa, std.mem.trim(u8, line, " \t\r"), .{}) catch return false;
+ defer parsed.deinit();
+ if (parsed.value != .object) return false;
+ const ty = parsed.value.object.get("type") orelse return false;
+ if (ty != .string or !std.mem.eql(u8, ty.string, expected)) return false;
+ if (!require_text) return true;
+ const text = parsed.value.object.get("text") orelse return false;
+ return text == .string and std.mem.trim(u8, text.string, " \t\r").len > 0;
+}
+
+test "cancel classification is exact" {
+ try std.testing.expect(isCancel(std.testing.allocator, "{\"type\":\"cancel\"}"));
+ try std.testing.expect(!isCancel(std.testing.allocator, "{\"type\":\"user\",\"text\":\"cancel\"}"));
+ try std.testing.expect(!isCancel(std.testing.allocator, "not json"));
+}
diff --git a/src/main.zig b/src/main.zig
index 180501ee..96393771 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -58,7 +58,7 @@ test { // unit_tests' root is main.zig only, so reference every split-out module
_ = pricing;
_ = models_cache;
_ = ansi;
- _ = serve;
+ _ = .{ serve, @import("json_inbox.zig") };
_ = util;
_ = learn_store;
_ = learn_eval;
diff --git a/src/mainloop.zig b/src/mainloop.zig
index feff54ba..f3dfd68f 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -10,11 +10,11 @@ const main_mod = @import("main.zig");
const util = @import("util.zig");
const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
-
const ansi = @import("ansi.zig");
const style = &ansi.style;
const pricing = @import("pricing.zig");
+const turn_event = @import("turn_event.zig");
const prompts = @import("prompts.zig");
const providers = @import("providers.zig");
const pickers = @import("pickers.zig");
@@ -27,6 +27,7 @@ const goal_flow = @import("goal_flow.zig");
const goal_pacing = @import("goal_pacing.zig");
const eval_memory = @import("eval_memory.zig");
const json_controls = @import("json_controls.zig"); // #415: the --json controls that never become a turn
+const json_inbox = @import("json_inbox.zig");
const mainloop_score = @import("mainloop_score.zig");
const mainloop_trace = @import("mainloop_trace.zig");
const scoring = @import("scoring.zig");
@@ -60,6 +61,8 @@ pub const Ctx = struct {
/// Run turns until EOF/quit; main then performs final save/worktree cleanup.
pub fn run(ctx: *Ctx) !void {
+ if (main_mod.json_mode) json_inbox.start(ctx.gpa, ctx.io, ctx.in);
+ defer if (main_mod.json_mode) json_inbox.stop();
var title_jobs: mainloop_title.Jobs = .{};
defer title_jobs.deinit(ctx);
var recap_jobs: mainloop_recap.Jobs = .{};
@@ -114,9 +117,7 @@ pub fn run(ctx: *Ctx) !void {
} else if (ctx.interactive) blk: {
try ctx.root.prompt();
break :blk (try readline.readLine(ctx.root, ctx.in, ctx.out, ctx.gpa, ctx.history, ctx.linebuf)) orelse break;
- } else (try ctx.in.takeDelimiter('\n')) orelse break;
- // The title may have completed while readline was waiting. Apply it
- // before starting the newly-entered turn, still without ever waiting.
+ } else (try json_inbox.request(ctx.arena, ctx.in)) orelse break;
title_jobs.poll(ctx);
recap_jobs.poll(ctx);
const line = std.mem.trim(u8, raw_line, " \t\r");
@@ -305,10 +306,10 @@ pub fn run(ctx: *Ctx) !void {
}
continue;
}
-
- // Persistent goal steering (#318): the diff-gated standing-goal note
- // plus one-shot notes (/goal replace|clear, and the standing state an
- // emergency trim re-queues). Compaction restates the checklist itself.
+ 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 and one-shot notes;
+ // compaction restates the list.
var goal_msg: []const u8 = try goal_state.applyGoalSteering(ctx.arena, ctx.root, base_msg);
const eval_note = if (ctx.root.review_mode) "" else try repl_glue.evalSteeringNote(
ctx.arena,
@@ -410,10 +411,8 @@ pub fn run(ctx: *Ctx) !void {
}
const turn_before = mainloop_trace.begin(ctx.root, ctx.io);
const turn_started = Io.Timestamp.now(ctx.io, .awake);
- // A failed turn must never kill the session: ApiError is already
- // reported inside request(); anything else is surfaced here. Either
- // way we drop back to the prompt (or emit a JSON error/turn event).
const turn_result = providers.runTurnWithFallback(ctx.root, ctx.keys, ctx.arena, ctx.out);
+ if (main_mod.json_mode) json_inbox.endTurn();
// Reuse one full-history scan for trace, terminal event, and compaction.
const post_turn_context_tokens = ctx.root.effectiveContextTokens();
mainloop_trace.record(ctx.root, ctx.io, ctx.arena, base_msg, turn_id, turn_started, turn_result, post_turn_context_tokens, turn_before, &prev_turn_id, &prev_prompt_fp);
@@ -426,9 +425,7 @@ pub fn run(ctx: *Ctx) !void {
}
const final_text = turn_result catch |err| switch (err) {
error.Interrupted => {
- // Esc: keep what streamed so far in history (as an assistant
- // turn with an explicit marker) so the conversation stays
- // coherent, then drop back to the prompt.
+ // Preserve streamed text and mark the saved assistant turn incomplete.
const partial = std.mem.trim(u8, ctx.root.partial_text.items, " \t\r\n");
const marker: []const u8 = if (partial.len > 0)
try std.fmt.allocPrint(ctx.arena, "{s}\n\n[response interrupted by user]", .{partial})
@@ -437,8 +434,12 @@ pub fn run(ctx: *Ctx) !void {
try ctx.root.messages.append(try messages.textMessage(ctx.arena, "assistant", marker));
const int_msg: []const u8 = if (main_mod.g_force_interrupt) "✗ interrupted (force)" else "✗ interrupted (esc)";
main_mod.g_force_interrupt = false;
- try ctx.out.print("{s}{s}{s}\n", .{ style.yellow, int_msg, style.reset });
- try ctx.out.flush();
+ if (main_mod.json_mode) {
+ ctx.root.emit(.{ .type = "error", .message = "turn cancelled" });
+ } else {
+ try ctx.out.print("{s}{s}{s}\n", .{ style.yellow, int_msg, style.reset });
+ try ctx.out.flush();
+ }
session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
continue;
},
@@ -457,7 +458,7 @@ pub fn run(ctx: *Ctx) !void {
if (partial.len > 0) {
ctx.root.emit(.{ .type = "finalizing" });
const context_tokens = ctx.root.effectiveContextTokens();
- ctx.root.emit(.{ .type = "turn", .text = partial, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = false, .metadata_complete = context_tokens > 0 });
+ ctx.root.emit(turn_event.fromTally(&pricing.g_cost, ctx.io, partial, context_tokens, false));
}
}
session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
@@ -479,7 +480,7 @@ pub fn run(ctx: *Ctx) !void {
if (partial.len > 0) {
ctx.root.emit(.{ .type = "finalizing" });
const context_tokens = ctx.root.effectiveContextTokens();
- ctx.root.emit(.{ .type = "turn", .text = partial, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = false, .metadata_complete = context_tokens > 0 });
+ ctx.root.emit(turn_event.fromTally(&pricing.g_cost, ctx.io, partial, context_tokens, false));
}
}
session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
@@ -493,7 +494,7 @@ pub fn run(ctx: *Ctx) !void {
if (partial.len > 0) {
ctx.root.emit(.{ .type = "finalizing" });
const context_tokens = ctx.root.effectiveContextTokens();
- ctx.root.emit(.{ .type = "turn", .text = partial, .context_tokens = context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = false, .metadata_complete = context_tokens > 0 });
+ ctx.root.emit(turn_event.fromTally(&pricing.g_cost, ctx.io, partial, context_tokens, false));
}
}
// A turn can fail because the context window overflowed; if we're
@@ -540,7 +541,7 @@ pub fn run(ctx: *Ctx) !void {
.session_arena_kb = if (main_mod.g_session_arena) |a| a.queryCapacity() / 1024 else 0,
.scratch_arena_kb = if (ctx.root.scratch_arena) |a| a.queryCapacity() / 1024 else 0,
});
- ctx.root.emit(.{ .type = "turn", .text = emitted_text, .context_tokens = session_context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = isolated_review or !ctx.root.eval_repair_pending, .metadata_complete = session_context_tokens > 0 });
+ ctx.root.emit(turn_event.fromTally(&pricing.g_cost, ctx.io, emitted_text, session_context_tokens, isolated_review or !ctx.root.eval_repair_pending));
}
// Apply only if already complete; poll never waits for title generation.
title_jobs.poll(ctx);
diff --git a/src/schema.zig b/src/schema.zig
index 72e5d202..c7272c10 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -390,7 +390,7 @@ pub fn writeToolEntry(s: *std.json.Stringify, kind: Provider.Kind, name: []const
/// a per-commit git describe) — bump this only when the schema or JSONL
/// protocol changes shape, so SDK regeneration stays byte-stable across
/// commits.
-pub const schema_version = "0.11"; // #419: session_recap event (one-line session summary + status, heuristic/model)
+pub const schema_version = "0.12"; // cancel request interrupts active stdio/serve turns
/// Emit the machine-readable interface description for `harness --schema`:
/// providers, models, built-in tools (name/description/parameters), and the
diff --git a/src/schema_protocol.zig b/src/schema_protocol.zig
index 5cc1457e..0cd642d7 100644
--- a/src/schema_protocol.zig
+++ b/src/schema_protocol.zig
@@ -32,7 +32,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\":\"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\":\"...\"} 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",
\\ "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": [
@@ -50,7 +50,7 @@ pub const json =
\\ {"type": "agent_usage", "id": "sa-...", "ok": true, "duration_ms": 0, "tool_calls": 0, "context_tokens": 0, "cache_read_tokens": 0},
\\ {"type": "finalizing"},
\\ {"type": "session_recap", "text": "one-line session summary", "status": "needs_input|completed|failed", "source": "heuristic|model (heuristic precedes every completed turn's terminal event; a model recap may follow later)"},
- \\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0, "complete": true, "metadata_complete": true},
+ \\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0, "input_tokens": 0, "uncached_input_tokens": 0, "cache_read_tokens": 0, "output_tokens": 0, "api_calls": 0, "subscription_calls": 0, "unpriced_calls": 0, "complete": true, "metadata_complete": true},
\\ {"type": "system_prompt", "ok": true, "append": false, "chars": 0},
\\ {"type": "model", "ok": true, "provider": "provider", "model": "model", "context": 0, "note": "context kept"},
\\ {"type": "compact", "ok": true, "chars": 0},
diff --git a/src/schema_serve.zig b/src/schema_serve.zig
index 2125aaad..4839786a 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); non-answer requests stream application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); answer requests return a JSON ack while the original user stream continues; one non-answer request in flight per session at a time. ?from=N or {\"resume_from\":N} replays persisted events with seq >= N before the live stream. {\"type\":\"reattach\"} sends nothing to the child and only replays+follows, so it is safe while another connection is mid-turn"},
+ \\ {"method": "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": "GET", "path": "/v1/sessions/{id}/events?from=N", "description": "reconnect: replay persisted events with seq >= N (default 1), then keep following the log live while a request is in flight, ending at that request's terminal event. Takes no protocol lock and never writes to the child, and works for a session this process never spawned as long as its event log is in the workspace"},
\\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin. The session file and the event log stay on disk, so the id remains resumable"}
\\ ]
diff --git a/src/serve.zig b/src/serve.zig
index cba832e2..a6efdc82 100644
--- a/src/serve.zig
+++ b/src/serve.zig
@@ -66,6 +66,7 @@ pub const ServeSession = struct {
rbuf: []u8, // gpa-owned backing buffer for rdr
busy: Io.Mutex = .init, // one in-flight protocol request per session
in_flight: std.atomic.Value(bool) = .init(false), // a request is streaming: followers keep tailing
+ stdin_mu: Io.Mutex = .init, // answer/cancel bypass busy but never interleave child writes
answer_mu: Io.Mutex = .init,
awaiting_answer: bool = false,
answer_call_id: [128]u8 = undefined,
@@ -140,7 +141,7 @@ fn serveConn(st: *ServeState, stream: std.Io.net.Stream) void {
var http_server = std.http.Server.init(&sr.interface, &sw.interface);
while (true) {
var req = http_server.receiveHead() catch return;
- serveRequest(st, &req) catch return;
+ serveRequest(st, &req, &sw.interface) catch return;
}
}
@@ -183,7 +184,7 @@ pub fn respondJson(st: *ServeState, req: *std.http.Server.Request, status: std.h
try req.respond(body, .{ .status = status, .keep_alive = keep, .extra_headers = serveJsonHeaders(st) });
}
-fn serveRequest(st: *ServeState, req: *std.http.Server.Request) !void {
+fn serveRequest(st: *ServeState, req: *std.http.Server.Request, transport: *Io.Writer) !void {
const io = st.io;
const gpa = st.gpa;
// head strings are invalidated once the body reader starts — copy now.
@@ -237,9 +238,9 @@ fn serveRequest(st: *ServeState, req: *std.http.Server.Request) !void {
const events_suffix = "/events";
if (method == .GET and std.mem.endsWith(u8, id, events_suffix)) {
id = id[0 .. id.len - events_suffix.len];
- return serveFollow(st, req, id, from_query orelse 1);
+ return serveFollow(st, req, transport, id, from_query orelse 1);
}
- if (method == .POST) return serveMessage(st, req, id, from_query);
+ if (method == .POST) return serveMessage(st, req, transport, id, from_query);
if (method == .DELETE) return serveDelete(st, req, id);
}
return respondJson(st, req, .not_found, "{\"error\":\"not found — see /v1/schema\"}");
@@ -258,7 +259,7 @@ pub fn freeSession(st: *ServeState, sess: *ServeSession) void {
/// for that request (every type in serve_events.terminal_events).
/// `?from=N` (or `"resume_from": N` in the body) replays persisted events with
/// seq >= N first, so a reconnecting supervisor never has a hole.
-fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8, from_query: ?u64) !void {
+fn serveMessage(st: *ServeState, req: *std.http.Server.Request, transport: *Io.Writer, id: []const u8, from_query: ?u64) !void {
const io = st.io;
const gpa = st.gpa;
var arena_state = std.heap.ArenaAllocator.init(gpa);
@@ -283,13 +284,14 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8,
// A pure reconnect: replay + tail, send nothing new to the child. Answered
// before the live-session lookup, because the session this client is
// catching up on may belong to a bridge that is already dead.
- if (std.mem.eql(u8, rtype, "reattach")) return serveFollow(st, req, id, from orelse 1);
+ if (std.mem.eql(u8, rtype, "reattach")) return serveFollow(st, req, transport, id, from orelse 1);
st.mutex.lockUncancelable(io);
const sess = st.find(id);
st.mutex.unlock(io);
const s = sess orelse return respondJson(st, req, .not_found, "{\"error\":\"no such session\"}");
if (std.mem.eql(u8, rtype, "answer")) return serveAnswer(st, req, s, line, parsed.object);
+ if (std.mem.eql(u8, rtype, "cancel")) return serveCancel(st, req, s, line);
// `dead` rather than dropping inline: serveDrop FREES the session, and the
// busy/in_flight defers below would then run through a dangling pointer.
@@ -297,19 +299,16 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8,
{
s.busy.lockUncancelable(io); // serialize requests per session
defer s.busy.unlock(io);
+ s.in_flight.store(true, .release);
+ defer s.in_flight.store(false, .release);
- {
- 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\"}");
- }
+ writeChildLine(io, s, line) catch return respondJson(st, req, .bad_gateway, "{\"error\":\"session process is gone\"}");
var stream_buf: [16 * 1024]u8 = undefined;
var bw = req.respondStreaming(&stream_buf, .{
.respond_options = .{ .extra_headers = serveNdjsonHeaders(st) },
}) catch return error.WriteFailed;
+ transport.flush() catch return error.WriteFailed;
// Replayed events all predate the request we just sent, so the client
// sees one ordered, gap-free sequence: the tail it missed, then the
// live turn.
@@ -319,14 +318,18 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8,
_ = events.replay(&bw.writer, data, n) catch {
client_alive = false;
};
- bw.flush() catch {
+ bw.writer.flush() catch {
+ client_alive = false;
+ };
+ if (client_alive) bw.flush() catch {
+ client_alive = false;
+ };
+ if (client_alive) transport.flush() catch {
client_alive = false;
};
} else |_| {}
}
- s.in_flight.store(true, .release);
- defer s.in_flight.store(false, .release);
while (true) {
const ev_line = s.rdr.interface.takeDelimiter('\n') catch |err| switch (err) {
error.StreamTooLong => break serveAbort(s, &bw, client_alive, "event line exceeded the 1 MiB serve cap — session closed", &dead),
@@ -347,8 +350,14 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8,
if (client_alive) bw.writer.writeByte('\n') catch {
client_alive = false;
};
+ if (client_alive) bw.writer.flush() catch {
+ client_alive = false;
+ };
if (client_alive) bw.flush() catch {
client_alive = false;
+ };
+ if (client_alive) transport.flush() catch {
+ client_alive = false;
}; // deliver each event as it happens
}
if (events.terminalEvent(trimmed)) {
@@ -356,7 +365,10 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, id: []const u8,
break;
}
}
- if (client_alive and !dead) bw.end() catch {};
+ if (client_alive and !dead) {
+ bw.end() catch {};
+ transport.flush() catch {};
+ }
}
if (dead) serveDrop(st, s); // after the defers above are done with `s`
}
@@ -384,7 +396,7 @@ fn serveAbort(s: *ServeSession, bw: anytype, client_alive: bool, message: []cons
/// request is in flight. Takes no protocol lock and never writes to the child,
/// so it works while another connection is mid-turn — that connection keeps
/// draining the child into the log even after ITS socket dies.
-fn serveFollow(st: *ServeState, req: *std.http.Server.Request, id: []const u8, from: u64) !void {
+fn serveFollow(st: *ServeState, req: *std.http.Server.Request, transport: *Io.Writer, id: []const u8, from: u64) !void {
const io = st.io;
const gpa = st.gpa;
if (!events.validName(id)) return respondJson(st, req, .bad_request, "{\"error\":\"bad session id\"}");
@@ -412,6 +424,7 @@ fn serveFollow(st: *ServeState, req: *std.http.Server.Request, id: []const u8, f
var bw = req.respondStreaming(&stream_buf, .{
.respond_options = .{ .extra_headers = serveNdjsonHeaders(st) },
}) catch return error.WriteFailed;
+ transport.flush() catch return error.WriteFailed;
var next_from = from;
var idle: usize = 0;
// A terminal event ends this client's watch, but only once the tape is
@@ -425,7 +438,9 @@ fn serveFollow(st: *ServeState, req: *std.http.Server.Request, id: []const u8, f
const replayed = events.replay(&bw.writer, chunk, next_from) catch break;
if (replayed.emitted > 0) {
next_from = replayed.last_seq + 1;
+ bw.writer.flush() catch break;
bw.flush() catch break;
+ transport.flush() catch break;
ended = replayed.terminal;
}
idle = 0;
@@ -439,6 +454,7 @@ fn serveFollow(st: *ServeState, req: *std.http.Server.Request, id: []const u8, f
io.sleep(.fromMilliseconds(follow_poll_ms), .awake) catch break;
}
bw.end() catch return;
+ transport.flush() catch return;
}
/// Is a request streaming on this session right now? Read under the session
@@ -465,16 +481,30 @@ fn serveAnswer(st: *ServeState, req: *std.http.Server.Request, s: *ServeSession,
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\"}");
+ writeChildLine(io, s, line) 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 serveCancel(st: *ServeState, req: *std.http.Server.Request, s: *ServeSession, line: []const u8) !void {
+ if (!s.in_flight.load(.acquire))
+ return respondJson(st, req, .conflict, "{\"error\":\"no request is in flight\"}");
+ writeChildLine(st.io, s, line) catch
+ return respondJson(st, req, .bad_gateway, "{\"error\":\"session process is gone\"}");
+ return respondJson(st, req, .ok, "{\"ok\":true,\"type\":\"cancel\"}");
+}
+
+fn writeChildLine(io: Io, s: *ServeSession, line: []const u8) !void {
+ s.stdin_mu.lockUncancelable(io);
+ defer s.stdin_mu.unlock(io);
+ var buf: [1024]u8 = undefined;
+ var writer = s.child.stdin.?.writerStreaming(io, &buf);
+ try writer.interface.writeAll(line);
+ try writer.interface.writeByte('\n');
+ try writer.interface.flush();
+}
+
fn serveUpdateAnswerState(io: Io, s: *ServeSession, line: []const u8) void {
const ty = events.stringField(line, "type") orelse return;
if (!std.mem.eql(u8, ty, "ask_user")) return;
diff --git a/src/turn_event.zig b/src/turn_event.zig
new file mode 100644
index 00000000..a77fffd8
--- /dev/null
+++ b/src/turn_event.zig
@@ -0,0 +1,40 @@
+//! Terminal JSON turn-event projection for the session-wide usage tally.
+
+const std = @import("std");
+const Io = std.Io;
+const pricing = @import("pricing.zig");
+
+pub const Event = struct {
+ type: []const u8 = "turn",
+ text: []const u8,
+ context_tokens: u64,
+ cost_usd: f64,
+ input_tokens: u64,
+ uncached_input_tokens: u64,
+ cache_read_tokens: u64,
+ output_tokens: u64,
+ api_calls: u64,
+ subscription_calls: u64,
+ unpriced_calls: u64,
+ complete: bool,
+ metadata_complete: bool,
+};
+
+/// Build one terminal event from an internally consistent cumulative snapshot.
+pub fn fromTally(tally: *pricing.CostTally, io: Io, text: []const u8, context_tokens: u64, complete: bool) Event {
+ const c = tally.snap(io);
+ return .{
+ .text = text,
+ .context_tokens = context_tokens,
+ .cost_usd = c.usd,
+ .input_tokens = c.in_tokens +| c.cache_tokens,
+ .uncached_input_tokens = c.in_tokens,
+ .cache_read_tokens = c.cache_tokens,
+ .output_tokens = c.out_tokens,
+ .api_calls = c.api_calls,
+ .subscription_calls = c.sub_calls,
+ .unpriced_calls = c.unpriced_calls,
+ .complete = complete,
+ .metadata_complete = context_tokens > 0,
+ };
+}